hi all,
new to Adurino. i have a MEGA 2560 board.
learning basic coding and stuck at Serial.read().
i followed the example on adurino.cc, and my serial monitor output is different to my input.
can you please offer some help?
thanks
andy
int incomingByte = 0; // for incoming serial data
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
// say what you got:
Serial.print("I received: ");
Serial.println(incomingByte, DEC);
}
}
the input:
6
the output: (not looping)
I received: 54
I received: 10
if i use Serial1.read() or Serial2.read() or Serial3.read(), no matter what i enter as a value,
the output is always looping this line "I received: -1"
54 is the ASCII code for the character 6. 10 is the ASCII code for new line. This means you have "Newline" selected from the line endings menu at the bottom of the Arduino IDE. You can change that menu selection to determine whether a line ending is sent and which line ending is used.
huiyeah:
the output is always looping this line "I received: -1"
I can't reproduce that. Are you sure that output is from the code you posted?
huiyeah:
if i want to to print as "6", what should i do?
Change the type of incomingByte to char and don't pass the DEC argument to Serial.println(). Serial.println() is pretty smart in that it can take all sorts of input and try to display it correctly. So if you pass it an int then it's going to display it as a number. If you pass it an int, or tell it to format the output as a decimal number then it will assume you want to print the numerical value. But if you pass it a char or string then it will assume you want it to print as text. You need to understand that there is a difference between the number 6 and the character 6. When you type a 6 into the input field in Serial Monitor, you are sending the character 6, just like if you had typed a letter.
The continued looping is because you checked if Serial has a character available and then you tried to take a character from Serial1. Since you didn't take the character which was available then it's still available and the condition is still true.