Hi, I’ve been trying to understand Serial and tried to follow this code for creating a buffer for data coming in through Serial: Gammon Forum : Electronics : Microprocessors : How to process incoming serial data without blocking
I understand it’s kind of old but it seems the sketch doesn’t use anything that’s deprecated so I still tried to follow it.
My question is, within the sketch itself it does a while loop when data is available:
void loop()
{
// if serial data available, process it
while (Serial.available () > 0)
processIncomingByte (Serial.read ());
// do other stuff here like testing digital input (button presses) ...
} // end of loop
and calls the processIncomingByte() function taking the data from the Serial using Serial.read() as an argument. The function takes each character from the data as a byte and stores it in a character array using switch statements to determine when it stops storing (when ‘\n’ is detected). What I don’t understand is this:
void processIncomingByte (const byte inByte)
{
static char input_line [MAX_INPUT];
static unsigned int input_pos = 0;
switch (inByte)
{
case '\n': // end of text
input_line [input_pos] = 0; // terminating null byte
// terminator reached! process input_line here ...
process_data (input_line);
// reset buffer for next time
input_pos = 0;
break;
case '\r': // discard carriage return
break;
default:
// keep adding if not full ... allow for terminating null byte
if (input_pos < (MAX_INPUT - 1))
input_line [input_pos++] = inByte;
break;
} // end of switch
} // end of processIncomingByte
Inside the processIncomingByte() function, it initializes the static unsigned integer variable “input_pos” to 0.
-
Why does it not reset after every while loop instance that “Serial.read()” is made if it is initialized over and over again per character of the input data?
-
why does the while loop not have “{ }” in the sketch as well?
-
how does a Byte of data can directly be stored in a char array? Shouldn’t it be converted first?
-
I tried to get the raw data of any incoming input data I put in through the Serial monitor by Serial.print() but it always comes out as the ASCII representation. Is there a way to print the RAW bits of the characters I send?
-
I tried to understand it by placing a Serial.write() to provide data but it seems Serial.read() does not recognize it. Why is writing data through Serial.write() not work?
Note: If I misunderstood anything about how the sketch works, any comments would be much appreciated. Thank you!