I try to execute a scetch for my Ard.Uno, based on a tutorial example.
Here's the link to the example Serial.read() - Arduino Reference
Here's the code.
int incomingByte = 0; // for incoming serial data
int incomread = 0;
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.available();
incomread = Serial.read();
// say what you got:
Serial.print("I received: ");
Serial.println(incomread, DEC);
}
}
But when I enter any character my Ser.monitor it doesn't displays them in a proper way - see attach. It looks like SM perceives it as ASCII character?
Give this code a try and, in the Serial monitor at the bottom, select "No line ending" as the option for the first textbox.
int incomingByte = 0; // for incoming serial data
int incomread = 0;
char c;
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.available();
// incomread = Serial.read();
c = Serial.read();
// say what you got:
Serial.print("I received: ");
// Serial.print(incomread, DEC);
Serial.println(c);
}
}
The difference is the read() method returns a byte and I want to interprete it as a char, not an int. If you have the Newline option selected, it treats the '\n' as a character appended to the character you did enter...two bytes, not one. This would cause the prompt to be printed a second time followed by the newline character. However, since the newline is non-printing, all you see is the prompt.
the first byte of incoming serial data available (or -1 if no data is available) - int
It returns a int so you can tell the difference between 0xFFFF (-1) and 0x00FF ('ÿ'). If you use .available() properly you don't need to detect the -1 and can store the return value in a byte/char.