5

I am doing some byte manipulation in Arduino, but when I enter an integer into the serial monitor, such as 1, and my program stores it as byte incomingByte, the value stored in incomingByte is 49 and not 1. How do I enter the ASCII equivalent of an integer?

2
  • 2
    The serial monitor is meant to let you enter text, not arbitrary binary data. You can parse the text into numbers in the Arduino. Nov 9, 2016 at 15:11
  • 2
    You can convert it in your program. For a single digit you can easily convert using value = incomingByte - '0'; For multiple digits you need to separate the ascii out into digits, subtract 48 ('0' is a simple way to do that without having to remember the ascii value of 0) and then add them together with the appropriate *10^n scale factors.
    – Andrew
    Nov 9, 2016 at 15:27

3 Answers 3

3

Using the Arduino IDE Serial Monitor, there's not much you can do. But you can use a different serial-port terminal such as RealTerm (for Windows, if that's your thing) which allows for a wide array of serial port nitty-gritty details.

2

Check out the ASCII table.

When you enter 1 into the Serial Monitor you are telling it to send the (ASCII) character 1 - which is represented by the decimal value 49, so the byte that is sent is 49.

I don't believe it is possible to enter the decimal value 1 into the Serial Monitor (you'd have to find some way of entering SOH via the keyboard), so the only option is to recognize and accommodate that on the Arduino end.

The usual way to do this is to subtract 48 from the received value. However this is typically written as - '0' which is actually subtract the ASCII value of 0 (this helps indicate that you converting from ASCII)

So...

int intVal = incomingByte -'0';

... should work fine for you if you are receiving single digit integers. However, if you also want to accommodate multi digit integers (e.g. 123) then it becomes more complex requiring converting each byte to it's integer equivalent and then multiplying it by 10 to the power of it's position/column...

123 = (1 * 10^2) + (2 * 10^1) + (3 * 10^0)

This is a fun little coding task in itself, but if you're not into that kind of thing then parseInt('123'); will get you going faster...

1

You can do this little trick:

void loop()    
{
while (Serial.available() == 0); //waiting for input    
int val = Serial.parseInt(); //read as integer
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.