Search code examples
while-looparduinoinfinite-loop

How to auto increment in Arduino Mega Board while loop?


Please understand that the tone is awkward using a translator

I coded the below code for Arduino Mega Board.

However, the value of buf_i is not increasing in the second while loop.

char buf[] = {0, };

if (Serial3.available()) {
    int inByte = Serial3.read();
    int nextChar = 0;
    if (inByte == 90) { //find Header 1
        nextChar = Serial3.read();
        if (nextChar == 165) { // find Header 2

            int buf_i = 0;
            int dataLen = Serial3.read(); // get Message Length

            //save data [ char buf[] ]  ---> works well!
            while (buf_i < dataLen) {
                buf[buf_i] = Serial3.read();
                buf_i++;
            }

            buf_i = 0;
            //print data to Serial ---> not work (Does not increase buf_i) 
            while (buf_i < dataLen) {
                Serial.print(" ");
                Serial.println(buf[buf_i]);
                buf_i++;
            }
        }
    }
    Serial.write(inByte);
}

and this is Serial Moniter Log

  1. in Serial3 Message 5A A5 06 83 21 00 01 00 11

  2. in Serial Message enter image description here

Thank you for your help :)


Solution

  • The buffer you created has only one element. If you try to insert more than one, then the behavior is undefined.

    char buf[] = {0, };
    

    You must make this buffer large enough for the largest message.

    char buf[maximum_data_length] = {0};