Jaap Goldhoorn
Jaap Goldhoorn

Reputation: 11

Arduino communication through 'Serial Monitor'

I've taken my Arduino out of the box about an hour ago and I'm trying to get some bits of code working.

The code below is supposed to wait for an input from the Serial Monitor and set the LED connected at terminal 9 to the input value.

The Arduino reads the value the first time, but it always sets the LED to full brightness and never prints the "input invalid". The Arduino also doesn't read any value after the first one. What is the reason?

int A;

void setup()
{
  Serial.begin(9600);
  Serial.println("input value");
}


void loop()
{
  A = 0;                      /* Reset A */
  if (Serial.available() > 0) /* Wait for input */
  {
    A = Serial.read();        /* Read input */
    if(A >= 0 && A <= 255)    /* Check for valid input */
    {
      analogWrite(9, A);      /* Set value of an LED */
    }
    else
    {
      Serial.println("input invalid");
    }
  }

  delay(100);                 /* Wait 0.1 second */
}

Upvotes: 0

Views: 105

Answers (1)

KIIV
KIIV

Reputation: 3739

According to the rest of code the Serial.parseInt() should be used instead of reading one character by Serial.read().

Upvotes: 0

Related Questions