1

My program reads the input and plays the appropriate note for 500 milliseconds. If I type in 'a', tone(8, 440, 500) will be called. I now want to add different note lengths so that in the future, I can play songs by sending code to Arduino. I was thinking that if 'a' is typed in, the program checks the next character. If it's a 1, it's a whole note. If it's a 2, it's a half note. My code doesn't work. What is wrong with it?

    if(Serial.available()>0){
    char character=Serial.read();
    if(character=='a'){
    char leng=Serial.read();
    if(leng=='1'){
    tone(8, 440, 1000);
    delay(1000);
    }
    else if(leng=='2'){
    tone(8, 440, 500);
    delay(500);
    }

    }
    }
  • Welcome to Arduino SE! Could you please include the full code? – Avamander Mar 26 '16 at 23:25
3

Presuming that code is the interior of loop(), your Arduino will spin until a character arrives, that is, until Serial.available()>0 becomes true.

It then reads the character with Serial.read() and if it's an 'a' immediately does another Serial.read(). In general, some delay occurs between characters arriving via a serial interface. Whenever the serial buffer is empty, an immediate Serial.read() will return -1 instead of an ASCII character.

To fix this problem, test for availability of a character before doing the second read. For example, you could add

while (!Serial.available()){}

before the read, to delay until a character is available.

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.