Buffering an array in C

Status
Not open for further replies.

svdsinner

Ars Legatus Legionis
15,152
Subscriptor
In my embedded project, I have one process that creates values that should be transmitted, and another that processes them. I made the below code to allow the creation process to write up to 2 packets ahead or the processor, so the processor (which operates in real-time based on the data) doesn't ever run out of data.

Here is the relevant buffering code:
Code:
//Header file (relevant parts)
#define NumChannels (uint8_t)9

static uint8_t ChannelValues[NumChannels];
static uint8_t TransmitBuffer[3][NumChannels];
volatile uint8_t CurrentReadBuffer;
volatile uint8_t CurrentWriteBuffer;

//Source file (relevant parts)
uint8_t NextValue(uint8_t currentValue) {
	uint8_t next = currentValue+1;
	if (next > 2)
		next = 0;
	return next;
}

int CanRead() {
	return CurrentReadBuffer != CurrentWriteBuffer;
}

int ValuesAllZero(uint8_t * values)
{
	int ret = 1;
	int i;
	for (i=0;ret && i<NumChannels;i++)
		ret &= (*(values+i)== 0);
	return ret;
}

void WriteValuesToTransmitBuffer(uint8_t * values) {
	if (ValuesAllZero(values))
		_NOP();
	//Wait until the values are copied before incrementing the write buffer
	//	to prevent concurrency issues.
	uint8_t writingBuffer = NextValue(CurrentWriteBuffer);
	if (writingBuffer == CurrentReadBuffer)
		//If buffer is full, overwrite previously buffered data, as it is now stale.
		writingBuffer = CurrentWriteBuffer;
		
//		TransmitBuffer[writingBuffer] = values;
	memcpy(TransmitBuffer[writingBuffer], values,
			NumChannels * sizeof(uint8_t));
	if (ValuesAllZero(TransmitBuffer[writingBuffer]))
		_NOP();

	CurrentWriteBuffer = writingBuffer;
}

uint8_t * ReadValuesFromTransmitBuffer() {
	if (CanRead()) {
		uint8_t * ret = malloc(NumChannels);
		if (NULL == ret) return NULL;
		
//		ret = TransmitBuffer[CurrentReadBuffer];
		memcpy(ret, TransmitBuffer[CurrentReadBuffer], NumChannels * sizeof(uint8_t));
		if (ValuesAllZero(ret))
			_NOP();//A breakpoint here gets hit, showing I've lost my data.

		CurrentReadBuffer = NextValue(CurrentReadBuffer);
		return ret;
	}
	return NULL;
}
The writing process is called with:
Code:
			//Add readings to Buffer
			ChannelValues[0] = controlsReport.X + 128;
			ChannelValues[1] = controlsReport.Y + 128;
			ChannelValues[2] = controlsReport.Collective + 128;
			ChannelValues[3] = controlsReport.Throttle + 128;
			ChannelValues[4] = controlsReport.AntiTorque + 128;
			ChannelValues[5] = controlsReport.Collective + 128;
			ChannelValues[6] = 129; //Future use
			ChannelValues[7] = 129; //Future use
			ChannelValues[8] = 129; //Future use
			if (ValuesAllZero(ChannelValues))
				_NOP();

			WriteValuesToTransmitBuffer(ChannelValues);

Problem: ReadValuesFromTransmitBuffer() always returns an array of zeros, rather than the data I wrote to the buffer.

I added the ValuesAllZero function as a debug to see where the values get lost. The seem to be intact when passed in, and intact when written, but zero when they are read from the buffer.

C isn't my native turf, and this is my first time I've attempted to use malloc or memcpy in more than a decade, so my mistake is probably basic.
 

andrewme

Senator
7,120
Subscriptor
Is all of the reader/writer code in the same source file (specifically, the "//Source file (relevant parts)" block and the "the writing process is called by part)? It's a little suspicious that you're defining global variables with "static" in a header file and never saying "extern". If you have separate source files both including that header, you'll have two separate copies of the arrays.

Volatile is almost useless. You may need actual synchronization primitives.

Have you used a debugger / stepped through the code to verify which buffer slots the writes are going into, and which slots the reader is reading from?
 

topham

Ars Legatus Legionis
13,756
Subscriptor
Not the specific error, but:

Your malloc is wrong, you should be multiplying by the size, but we know that's one so it isn't the problem, it'll just bite you in the ass if you start using a multiple byte type later.

Why not use assert, instead if you if/NOP code?

Magic values - I realize it's a work in progress, but you're using 2 & 3 when you should be using something to represent your buffer pool size.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
You aren't initializing the currentReadBuffer or currentWriteBuffer in the code you've posted.
There's some interesting possibilities if the value for one is 255, and the other is 0.
If currentWrite = 255 and currentRead = 0

CurrentWrite = Next value = 255 + 1 = 0.

If currentWrite == currentRead, use original value of currentWrite; which was 255. Oops.
 

andrewme

Senator
7,120
Subscriptor
[url=http:/civis/viewtopic.php?p=26928993#p26928993:38pvlot3 said:
topham[/url]":38pvlot3]You aren't initializing the currentReadBuffer or currentWriteBuffer in the code you've posted.

Globals in C are automatically initialized to 0. I do prefer to explicitly initialize them, but it shouldn't matter here. Pretty sure LF found the actual issue.
 
Globals in C are initialized to zero, but not always in embedded. ! I had a bug where I needed to modify a pre-init function to clear some pins that had to happen fast, before memory init would complete. I modified it wrong, so that instead of returning a 1/0 indicator of whether or not to clear memory, it just returned whatever had been in R12, the return register; it returned void, basically. So it worked after a *long* power-off cycle, because the RAM had time to settle out, but not on a fast reset.
 
[url=http:/civis/viewtopic.php?p=26931689#p26931689:2ln4u2wr said:
SurfaceTension[/url]":2ln4u2wr]Globals in C are initialized to zero, but not always in embedded. ! I had a bug where I needed to modify a pre-init function to clear some pins that had to happen fast, before memory init would complete. I modified it wrong, so that instead of returning a 1/0 indicator of whether or not to clear memory, it just returned whatever had been in R12, the return register; it returned void, basically. So it worked after a *long* power-off cycle, because the RAM had time to settle out, but not on a fast reset.
Eww, thats a bit nasty. Is there anyone you can complain to that their toolchain doesn't actually implement the C specification properly in that regard? :)

In my experience, even if there's not an OS to ensure you get loaded into nice clean zero-pages, the toolchain/crt provider should compensate, typically by having a routine before main, (in _start is what I've seen) that clears from _bss_start to _bss_end. Sometimes some linkerscript magic is needed to get the symbols in the right place but if you're that deeply embedded you may already have custom lds files anyway.

IME - it's worth the initial investment doing this once, to never have to worry about that kind of stuff in your code ever again.
 
Status
Not open for further replies.