Serial Port not working well

I started with arduino last week and now Im trying a project where I have to use the serial port but this one when I try to read inputs from the computer doesnt read them well.
In this code if I dont write anything it prints the number -1 but if I write a number between 0-9 it prints 48-57 and then a 10 always. Someone can help me with that pls Im using an arduino UNO.

#include <LedControl.h>

LedControl lc = LedControl(11,10,9,0);
int r;

void setup() {
  // put your setup code here, to run once:
  lc.shutdown(0,true);
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
r=Serial.read();
Serial.println(r);
delay(4000);

}

You need to check if there is data available before you read the from port.

The serial input basics tutorial will help you to reliably read serial data.

You posted in the wrong forum category.

"-1" is means that nothing to read in the port
Before reading from Serial port, first you need to check if there is something to read there

From buffer instead of port?

change type of r variable to char instead of int, because if you type something in the Monitor - it send chars to Serial

If you will.

1 Like

If you do that, you can not test for a character available by the usual method of checking for -1 because char is unsigned. You would have to use the available() method instead.

@carloszb07, Your topic moved to programming questions.

You issue relates to confusion between ASCII character numbers and the characters themselves as alluded to in reply #6

In Arduino -- since when?

Right. 'char' is signed. An int will cast in an assignment to a char correctly as long as it doesn't overflow the char.

1 Like

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