简体   繁体   中英

How to clear the bytes of Serial interface in an Arduino?

I'm trying to interrupt the serial monitor to execute a certain function and continue with the previous function after completion of the interrupted function, my code is as bellow

#define red1 13
#define amber1 12
#define green1 11

void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);  
    pinMode(red1, OUTPUT);
    pinMode(amber1, OUTPUT);
    pinMode(green1, OUTPUT);
}

void Delay(int sec) {
    for(int i=0;i<sec;i++){
        if (Serial.available())
        {
            Button();
            break;
        }
        delay(1);
     }
}

void Light()
{
    digitalWrite(red1,HIGH);
    Delay(5000);
    digitalWrite(red1,LOW);
    digitalWrite(amber1,HIGH);
    Delay(5000);
    digitalWrite(amber1,LOW);
}

void Button()
{
    digitalWrite(red1,LOW);
    digitalWrite(amber1,LOW);      
    digitalWrite(green1,HIGH);
    delay(1000);
    digitalWrite(green1,LOW);
}

void loop() 
{
    Light();  
}

Whenever I enter a value in serial monitor Button() function is executed, it should end as soon as function completes due to a break, but this function keeps repeating continuously? How can I fix this such that whenever a serial monitor is interrupted, Button() is executed onetime and then continues with Light(). I tried using a break but the serial interface buffer is not cleared so its keep continuing this function also it exits if loop, so I tried using return

void Delay(int sec) {
                for(int i=0;i<sec;i++){
                    if (Serial.available())
                    {
                        Button();
                        return;
                    }
                    delay(1);
                 }
            }
the same thing happens 

the function doesn't exit it keeps repeating the same since the serial interface is not cleared from an earlier encounter, I could've used serial.available in void loop() but whenever Arduino is at delay function its sleeping so it doesn't read a serial interrupter, so I created separate Delay() so how can I change the code to end this function and go back to Light()

but the serial interface buffer is not cleared

Then you have to clear it:

while (Serial.available())
  Serial.read(); // remove 1 character

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM