Serial.read single number - what isn't working?

Hi,

Been a while since I've played with my arduinos, can't say I'm a fan of the new forum layout but I'm sure it will grow on me.

I'm trying to use the serial input for debugging some code and want to switch 'state' between 0-3 by sending a 0,1,2 or 3 via the serial monitor tool.

I only want to receive a single number and looked at the serial.read() guide but I can't get it to work due to two extra characters (I'm assuming these are CLR and NL)...

Here is the code snippet (being run as a subroutine) - can't find the old code button either... :confused:

char incomingByte = 0; // for serial debugging
int state = 0;

void checkSerial(){
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
Serial.print("RECEIVED - ");Serial.println(incomingByte);
state = incomingByte;
}

Now this works to begin with but then I receive two 'blank' entries (have seen -35 and -38 when playing around) which completely messes things up... I just want to receive the single number and for that to be stored in 'state'.

I tried using an 'if' range between 0 and 3 but that still didn't work.

I know there's something simple wrong here but my sleep deprived brain this morning cannot figure it out. How do I get it to ignore those extra characters?

EDIT: NEW ISSUE
When sending without CLR & NL through the monitor (I'm an idiot!) those extra characters vanish BUT the value still does not end up in state... when serial printing state back it comes up empty.

Thanks

35 is the ascii code for '5' and 38 the ascii code for '8' in hexadecimal

if you are communicating in ASCII, a number can be represented by multiple bytes (ASCII codes), even if that number fits on a byte. eg 255 is composed of 3 bytes '2' (ascii 0x32) then '5' (ascii 0x35) and again '5' (ascii 0x35) for example but does fit in 1 byte once converted to a number (0xFF)

I would suggest to study Serial Input Basics to handle this

Fixed it, like a complete dummy I was trying to put a char into an int without conversion.

The revised code that now works is

void checkSerial(){
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
newData = true;
if (newData == true){
Serial.print("RECEIVED - ");Serial.println(incomingByte);
state = incomingByte - '0';
newData = false;
}
}
}

highlighted the issue just incase anybody else is having a brain shutdown moment like myself!

we have all been there, don't worry :slight_smile: that's how we learn.

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