"-38" keeps appearing in serial monitor, led always switches on

Hi Guys. I'm new to this forum but hope to be a regular. I've programmed in Python before but wanted to take my programming in a new and interesting direction.

My dad (who's very experienced in C) set me a task to program an "Even number tester". A simple enough task in which a single digit number is entered and the light stays on for three seconds if the number is easy, and stays off if not. The issue is the LED always switches on. When I tried to debug this by printing the number that's being tested for, it printed correctly, but also returned "-38" on the next line. Here's the code:

int ledPin = 3;

void setup() { pinMode(ledPin, OUTPUT); Serial.begin(9600); Serial.print("Enter a number:"); Serial.println(" "); }

void loop() { if(Serial.available()>0){ int nu = Serial.read()-48; Serial.println(nu); if(nu%2==0){ digitalWrite(ledPin, HIGH); delay(3000); digitalWrite(ledPin, LOW); } } }

And here's the result on the serial monitor when 3, 4, 5, and 6 are used:

Enter a number: 3 -38 4 -38 5 -38 6 -38

I've tried googling, but couldn't find anything important about the number thirty eight, or about numbers mysteriously appearing. No doubt the light comes on because it tests for -38, not the original number.

See the attached image


How is this an installation and troubleshooting question?

Did I post this in the wrong place? My mistake. I'll move it elsewhere if you want me to!

I’ll move it elsewhere if you want me to!

You can’t.

You’d be better off posting things people actually need to know to help you.
You know, like,your code.

Carriage return, line feed

1 Like

Set your serial monitor to no line ending. Your code is picking up a LF character (10).

Oh, that worked! Why does the LED remain lit though?