Use double buffer

This commit is contained in:
C0d3v 2026-01-20 10:41:27 +01:00
parent 8c0f98b7a7
commit 1974376134

View File

@ -1,29 +1,39 @@
#include <Arduino.h> #include <Arduino.h>
#include <Wire.h> #include <Wire.h>
#define I2C_SLAVE_ADDRESS 0x08 #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() { 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() { void setup() {
Wire.begin(I2C_SLAVE_ADDRESS); Wire.begin(I2C_SLAVE_ADDRESS);
Wire.onRequest(onI2CRequest); Wire.onRequest(onI2CRequest);
analogReference(DEFAULT); analogReference(DEFAULT);
} }
void loop() { void loop() {
values[0] = analogRead(A0); // Choose the inactive buffer
values[1] = analogRead(A1); volatile uint16_t* writeBuffer =
values[2] = analogRead(A2); (activeBuffer == bufferA) ? bufferB : bufferA;
values[3] = analogRead(A3); writeBuffer[0] = analogRead(A0);
values[4] = analogRead(A6); writeBuffer[1] = analogRead(A1);
values[5] = analogRead(A7); writeBuffer[2] = analogRead(A2);
delay(50); writeBuffer[3] = analogRead(A3);
writeBuffer[4] = analogRead(A6);
writeBuffer[5] = analogRead(A7);
// Atomic pointer swap
noInterrupts();
activeBuffer = writeBuffer;
interrupts();
} }