I have developed a program and the idea is that when it receives serial data (any single character) it returns a single random number.

I have it working but it returns 3 x random numbers one after another for each read that it does and I can't figure out why.

int led = 13;
char incomingByte = 10;
long randNumber;
// the setup routine runs once when you press reset:
void setup() {                
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);  

// the loop routine runs over and over again forever:
void loop() {

//  delay(1000);               // wait for a second

   if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();
                // say what you got:
              //  Serial.print("I received: ");

                randNumber = random(1, 2000);
                Serial.println('PL' + randNumber);
                  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
                  delay(1000);               // wait for a second
                  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW



1 Answer 1


When you enter a single character into the Serial Monitor and press Enter, three bytes are sent: the character, a carriage return, and a linefeed. Serial.read() only reads a single byte, so data is available three times.

Either loop reading until no more bytes are available, check for and discard any CRs and LFs, or use a serial terminal that doesn't require pressing Enter to send data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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