Probleme with Serial.read() and or Serial.available ()

I'm, no expert but do have a problem with the Serial.read() and the the Serial.available(). I have use the example sketch from this website to counter verify my own sketch.

char receivedChar;
boolean newData = false;

void setup() {
    Serial.begin(9600);
    Serial.println("<Arduino is ready>");
}

void loop() {
    recvOneChar();
    showNewData();
}

void recvOneChar() {
    if (Serial.available() > 0) {
        receivedChar = Serial.read();
        newData = true;
    }
}

void showNewData() {
    if (newData == true) {
        Serial.print("This just in ... ");
        Serial.println(receivedChar);
        newData = false;
    }
}

For some reason, there always 2 characters returned to the monitor text. My character like [A] and the [carriage return] ASCII codes. How can I strictly get the character that I'm interested? The above code only prints the characters that where send through the terminal.

Whether I use the SEND button or press the Return key, the last character is always the [carriage return] that is stored in the variable receivedChar!

The final objective is to use the + and - signs ASCII codes to increase or decrease a PWM duty cycle. See the output of the terminal.

Note that this code was compiled with on linux and Windows 10 machines with 2 different Arduino MEGA boards.

Thanks for your help and Happy New Year

Try changing "Nouvelle ligne".

The serial monitor will terminate any message sent from the serial monitor with the New Line, New Line and Carriage Return or No terminator (No line endings) as selected in the Line Endings box. Try selecting No line endings.

line endings small

Thanks to both of you.

I did manage to get around this situation by first verifying if the byte from Serial.read was note the [carriage return] (0xA). If not, then append the Serial.read() to receivedChar, else, append the Serial.read to a dummy variable. OK, I comment out all my modified code to have the original code and tested your recommendation by modifying the parameter for "No line ending" and works!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.