I'm trying to program my Arduino Mega to work with a TSL1401 line scan module and while looking over someone else code I came across this:
void loop()
{
int b = Serial.read(); //Reads incoming serial data. Returns the first byte of
//incoming serial data available (or -1 if no data is available)
if (b == 's')
{
getCamera();
delay(2000);
}
}
For the most part I understand what it's doing but I got confused when I saw that he was setting the return value of Serial.read()
equal to a variable and then checking to see if that variable was a character. To my understanding Serial.read()
returns an integer so why would you compare it to a character?
2 Answers 2
On an 8 bit arduino a character is a byte. A byte can represent values between -128 and 127, or between 0 and 255, depending on how you "look" at them (signed or unsigned).
The whole concept of a character is a purely human thing. The Arduino only knows numbers.
For instance the character 'A' is actually the number 65. We, as humans, choose to represent it as an 'A' and call it "ASCII".
Again, the character 'a' is actually the number 97. You can also subtract characters from each other. 'a' - 'A' = 32
Part of the answer is in the comment in your given example:
int b = Serial.read(); //Reads incoming serial data. Returns the first
//byte of incoming serial data available
//(or -1 if no data is available)
If you're reading raw 8-bit data from the serial port (basically, could be any value from 0-255), how do you represent errors? Per the comment: if nothing is available, it returns -1. But... as @Majenko pointed out, -1 is a valid CHAR too, it all depends on how you look at the data (signed, or unsigned).
But an INT can hold a value from 0-255 easily, and also a -1 to represent 'nothing'. The Serial.read function is non-blocking (it doesn't WAIT for a data byte), so it needs to be able to return a status that indicates 'empty bucket', meaning there's actually 257 (256+1) different possible values... thus you need more than 8 bits.
It's a painful lesson with usage of fgetc(3), getc(3) and similar functions. You need to be able to represent EOF, while also returning valid 8 bit data. Hence the use of INT's as return value size. Often someone (ok, me... but it was a long time ago!) will figure that since they're reading CHAR's, you can use a CHAR sized variable... but then EOF never seems to be found... oops!
Hope this helps.
-
On the Arduino an
int
value can range from -32,768 to 32,767. You can easily differentiate that from achar
value. And Serial.read() returns aint
value.ott--– ott--2016年06月04日 20:55:13 +00:00Commented Jun 4, 2016 at 20:55 -
@ott why this example uses
char
? arduino.cc/en/Reference/SoftwareSerialReadMarki555– Marki5552019年10月03日 22:19:31 +00:00Commented Oct 3, 2019 at 22:19