1

I want Serial.read() to return an integer instead of an ASCII value. For example, in the below code if I input 2, I want the output as 2 instead of 50

void setup(){
 Serial.begin();
}
void loop(){
 if(Serial.available()){
 int t = Serial.read();
 Serial.println(t);
}
Edgar Bonet
45.1k4 gold badges42 silver badges81 bronze badges
asked Jul 12, 2020 at 11:23
2
  • your code does not compile because of a syntax error Commented Jul 12, 2020 at 18:53
  • Serial.read() returns a byte ... what that byte means to you, is not realted to that fact Commented Jul 12, 2020 at 19:00

2 Answers 2

1

If it's a single digit:

if (t >= '0' && t <= '9') {
 int numeric_value = t - '0';
} else {
 // Handle the input error.
}
answered Jul 12, 2020 at 12:18
1

You can use an alternate method like this

void setup()
{
Serial.begin(9600);
}
void loop()
{
 if(Serial.available()){
 String a = Serial.read();
 int b = a.toInt();
 Serial.println(b);
}
answered Jul 13, 2020 at 17:46

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.