Use double buffer
This commit is contained in:
parent
8c0f98b7a7
commit
1974376134
@ -1,29 +1,39 @@
|
||||
#include <Arduino.h>
|
||||
|
||||
#include <Wire.h>
|
||||
|
||||
#define I2C_SLAVE_ADDRESS 0x08
|
||||
|
||||
uint16_t values[6] = {0};
|
||||
volatile uint16_t bufferA[6];
|
||||
volatile uint16_t bufferB[6];
|
||||
|
||||
// Pointer to the buffer currently exposed to ISR
|
||||
volatile uint16_t* activeBuffer = bufferA;
|
||||
|
||||
void onI2CRequest() {
|
||||
Wire.write((uint8_t*)values, sizeof(values));
|
||||
// Safe: ISR only reads active buffer
|
||||
Wire.write((uint8_t*)activeBuffer, 6 * sizeof(uint16_t));
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Wire.begin(I2C_SLAVE_ADDRESS);
|
||||
Wire.onRequest(onI2CRequest);
|
||||
|
||||
analogReference(DEFAULT);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
values[0] = analogRead(A0);
|
||||
values[1] = analogRead(A1);
|
||||
values[2] = analogRead(A2);
|
||||
// Choose the inactive buffer
|
||||
volatile uint16_t* writeBuffer =
|
||||
(activeBuffer == bufferA) ? bufferB : bufferA;
|
||||
|
||||
values[3] = analogRead(A3);
|
||||
values[4] = analogRead(A6);
|
||||
values[5] = analogRead(A7);
|
||||
delay(50);
|
||||
writeBuffer[0] = analogRead(A0);
|
||||
writeBuffer[1] = analogRead(A1);
|
||||
writeBuffer[2] = analogRead(A2);
|
||||
writeBuffer[3] = analogRead(A3);
|
||||
writeBuffer[4] = analogRead(A6);
|
||||
writeBuffer[5] = analogRead(A7);
|
||||
|
||||
// Atomic pointer swap
|
||||
noInterrupts();
|
||||
activeBuffer = writeBuffer;
|
||||
interrupts();
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user