This serial capture works, but I do not understand why....

Thread Starter

Gibson486

Joined Jul 20, 2012
334
I had to get a serial string on an arduino and read it back out.

This is what I got to work...but I am confused.

Code:
   char buf[MAX_MESSAGE];
   char readS;
   int count = 0;
   while (Serial.available())
   {
       //read what is in buffer when something shows up

      readS = Serial.read();

      delay(5);
      
      if (readS == '\r') {
        Serial.print("You entered: ");
        Serial.println(buf);
        }
        
      else {       
        if (count < MAX_MESSAGE-1) {
          buf[count++] = readS;
          buf[count] = 0;
        }
      }
      
    }
I am a little perplexed at the "else" statement...

1. Why do you need buf[count] = 0?

2. Doesn't doing the count++ make the next count equal to that? It works, but I thought it would turn the that value to 0 immediately.

3. Wouldn't this code always lead to buf[0] being 0? since it stores at buf[count++], wouldn't the first stored value be at buf[1]?
 

michael8

Joined Jan 11, 2015
134
1. Why do you need buf[count] = 0?

This makes sure the string in buf has an ending 0 byte at the end of the current valid data.
Serial.println(buf); is going to print the characters in buf until it hits a 0 byte. See the arduino reference for string.
https://www.arduino.cc/reference/en/language/variables/data-types/string/

2. buf[count++] = readS;

count++ increments count but the count gets used as the subscript *before* it's incremented.
This is call post increment.

3 No, it puts the current character in readS into buf[count] and sets buf[count+1] to 0.
 

Thread Starter

Gibson486

Joined Jul 20, 2012
334
1. Why do you need buf[count] = 0?

This makes sure the string in buf has an ending 0 byte at the end of the current valid data.
Serial.println(buf); is going to print the characters in buf until it hits a 0 byte. See the arduino reference for string.
https://www.arduino.cc/reference/en/language/variables/data-types/string/

2. buf[count++] = readS;

count++ increments count but the count gets used as the subscript *before* it's incremented.
This is call post increment.

3 No, it puts the current character in readS into buf[count] and sets buf[count+1] to 0.

Thanks! explains a lot!
 
Top