I'm having a double buffer to write data from sensors to SD card. inBuf
points to the buffer that are written into (from sensors). The other buffer write data to SD card.
char buffer[2][BUFLEN];
volatile int inBuf = 0;
inBuf = 1 - inBuf;
However, the update of inBuf
does not work. Firstly inBuf
is 0, and after that inBuf
becomes 32!!! I tried different data types: boolean
, uint8_t
, int
and the results are the same.
How could I fix this problem? Also, what datatype should I use for inBuf
, as it's really just one bit?
I ended up using the following:
inBuf = inBuf? 0:1;
but seems really complicated and unnecessary.
EDITS: Sorry for was not being clear previously. It turns out that I had an overflow in the code:
char buffer[2][BUFLEN];
volatile uint16_t bufferCounter;
volatile int inBuf = 0;
volatile bool outBufHasData = false;
Inside the interrupt handler:
if (bufferCounter < BUFLEN - SAMPLESIZEINCHAR + 1) {
epoch = now();
proximity = vcnl.readProximity();
ambientLight = vcnl.readAmbient();
// format to be fixed length as opposed to variable length
// sacrifice overhead in written data with simpler and more robust code
// since we know exactly how much to increment after each write
int written = snprintf(&buffer[inBuf][bufferCounter], SAMPLESIZEINCHAR,
"%10lu,%5d,%5d\n",
epoch, proximity, ambientLight);
if (written > 0) {
bufferCounter += written;
}
} else {
// only switch buffer if out buffer is written to SD card
if (!outBufHasData) {
inBuf = inBuf? 0:1;
bufferCounter = 0;
outBufHasData = true;
}
}
Then in the for
loop, where the buffer is written to SD card when the buffer is full:
if (outBufHasData) {
myFile.print(buffer[1 - inBuf]);
myFile.close();
outBufHasData = false;
}
Previously, I had bufferCounter < BUFLEN
!! Thus I was writing over the memory of the buffer, and spill into bufferCounter
and inBuf
. That's why I got the value 32 of inBuf
, which is the ASCII code of space. Mystery resolved!!
inBuf
immediately followsbuffer
in the definitions you are overflowingbuffer
and clobbering the contents ofinBuf
- but that's just a guess since we cannot see your code!