1

I have written a simple code to delay the blinking of LED 13, the delay time is set by us.I have incurred a problem when I enter a 2 digit value in the serial monitor.There is some problem with the ASCII. Is there a way to solve this problem without using Serial.parseInt().

void setup()
{
  Serial.begin(9600);
  Serial.println("Programming is starting"); 
  pinMode(13,OUTPUT);
}

void loop()
{
  if(Serial.available())
  {
    int val=Serial.read();
    int val1=val-'0';
    Serial.println(val1);
    digitalWrite(13,HIGH);
    delay(val1*1000);
    digitalWrite(13,LOW);
  }  
}
2

Here you have.

No error checking. Anything not digit produce zero as output.

void setup()
{
    Serial.begin(9600);
    Serial.println("Programming is starting");
    pinMode(13,OUTPUT);
}

void loop()
{
    static int value = 0;

    while(Serial.available() > 0) {
        int c = Serial.read();

        if(isDigit(c)) {
            value = value * 10 + (c - '0');
        } else {
            Serial.println(value);
            digitalWrite(13,HIGH);
            delay(value*1000);
            digitalWrite(13,LOW);
            value = 0;
        }
    }

It convert chars to values as they are being readed, one by one. There are no size limit for the input string, other that final value must fit in an int

You write a value in the Serial Monitor and end it with return, space bar or whatever non digit key you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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