Hey guys I'm writing a C code in Atmel Studio 6.0 with GCC C compiler. Essentially I'm doing USART communication on a microcontroller, and I found a sample code(a header file) that handles sending/receiving (Tx/Rx) using a circular receiving buffer from an Atmel employee's blog
http://www.fourwalledcubicle.com/files/LightweightRingBuff.h[
^]
Code excerpt that works:
Besides initializing the Buffer and other functions, it insert the char type data it receives into the Buffer as such:
static inline void RingBuffer_Insert(RingBuff_t* const Buffer,
const RingBuff_Data_t Data) {
*Buffer->In = Data;
if (++Buffer->In == &Buffer->Buffer[BUFFER_SIZE])
Buffer->In = Buffer->Buffer;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
Buffer->Count++;
}
}
and here's the function in the header file to get'em out
static inline RingBuff_Data_t RingBuffer_Remove(RingBuff_t* const Buffer)
{
RingBuff_Data_t Data = *Buffer->Out;
if (++Buffer->Out == &Buffer->Buffer[BUFFER_SIZE])
Buffer->Out = Buffer->Buffer;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
Buffer->Count--;
}
return Data;
}
And then in main.c we can use this to read out chars in the Buffer
while (BufferCount--)
putc(RingBuffer_Remove(&Buffer));
My goal: I'm trying to wait until an entire string of chars is stored in the Buffer (terminated with a '\0' or '\n'? ), read out the string, and maybe parse it.
Code excerpt that doesn't work:
Now as an absolute C newbie,
here's what I have attempted to do (buggy code with blatantly wrong pointer usage coming thru) Just to illustrate what I hope to achieve:
int main( void ) {
RingBuffer_InitBuffer(&Buffer);
unsigned char holder;
while(true) {
if(usart_kbhit()) { holder = usart_getchar(); RingBuffer_Insert(&Buffer, holder);
if (holder == '\n') {
uint16_t BufferCount = RingBuffer_GetCount(&Buffer);
char Command_String[BufferCount];
while (BufferCount--)
strcat(Command_String,RingBuffer_Remove(&Buffer));
if strncmp(Command_String,"ABC\n",4) tell_the_microcontroller_to_do_stuff (); }
}
}
}
Sorry about the long post but all I need are some comments about the way I read out the string from Buffer, store it in Command_String, and compare Command_String with "ABC"
Here's my code without the wordy comments
while(true) {
if(usart_kbhit()) {
holder = usart_getchar();
RingBuffer_Insert(&Buffer, holder);
if (holder == '\n') {
uint16_t BufferCount = RingBuffer_GetCount(&Buffer);
char Command_String[BufferCount] ;
while (BufferCount--)
strcat(Command_String,RingBuffer_Remove(&Buffer));
if strncmp(Command_String,"ABC\n",4)
tell_the_microcontroller_to_do_stuff ();
}
}
}
}
Thank you