1 votes

Help with Arduino serial communication

I am learning to program in Arduino and I need that when entering any number of "n" digits, an LED blinks the number of times of the entered number. I must do it with while. I have been trying my code, but the LED does not stop when reaching the number entered.

 int numero;
int i=0;
void setup()
{
pinMode(13, OUTPUT);
Serial.begin(9600);
}
void loop()
{
  if(Serial.available()>0){
    char numero=Serial.read();
    if(numero>=1){
      while(numero>i){
      digitalWrite(13, HIGH);
      delay(500);
      digitalWrite(13, LOW);
      delay(500);
      i++;     
      }   
    }
  }
}

0voto

Candid Moe Points 9202

The problem is that the following statement is incorrect.

 char numero = Serial.read();

Serial.read() returns int , not char .

Besides, you only read one digit; if you want to read any value, you must implement your own reading routine, like this:

 int leerEntero();

void setup()
{
  pinMode(13, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  int numero;
  if (Serial.available()) {
    numero = leerEntero();
    for (int i = 0; i < numero; i++) {
      digitalWrite(13, HIGH);
      delay(500);
      digitalWrite(13, LOW);
      delay(500);
    }
  }
}

int leerEntero() {
  char numero[10];
  int c = 0;
  int i = 0;

  while (i < 9 && c != '\r') {
    if (Serial.available() > 0) {
      c = Serial.read();
      if (isdigit(c)) {
        numero[i++] = c;
      }
    }
  }
  numero[i] = 0;
  return atoi(numero);
}

Note: Tested with Arduino Uno.

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X