'Clearing Arduino's serial buffer
i have a simple arduino code:
void loop()
{
if serial.available
{
c = serial.read();
if (c == 'a')
{
blinkled();
}
else
offled();
}
}
it should glow the led if i send a character 'a'. and it shld go off when i dont give anything when the loop goes into the next itration.
but once i give 'a'. it starts glowing and never goes off.
is it reading the char 'a' from the buffer? if so then how to clear it ?
Serial.flush() not working.
any ideas please. am new to arduino. sorry if its silly.
Solution 1:[1]
You have put your offled function INSIDE the Serial.available() path. You could only turn it off by Serial.available() being true and you pushing a different character so it reads something other than 'a'
Unfortunately the example above makes the same mistake.
Construct it so that the led turns off outside that if statement
Solution 2:[2]
You could use something like this:
void loop() {
while (Serial.available() > 0)
{
char received = Serial.read();
inData += received;
// Process message when new line character is received
if (received == '\n')
{
Serial.print("Arduino Received: ");
Serial.print(inData);
// You can put some if and else here to process the message juste like that:
if(inData == "a\n"){ // DON'T forget to add "\n" at the end of the string.
Serial.println("OK, I'll blink now.");
blinkled();
}
else if (inData == "b\n") {
offled();
}
inData = ""; // to flush the value.
}
}
}
EDIT : I've modified my answer based on the correct answer.
Solution 3:[3]
This could be a solution:
void loop()
{
offled();
char c = Serial.read();
while (Serial.available() <= 0 || c != 'a') {
blinkled();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | djUniversal |
Solution 2 | |
Solution 3 | rfgdfg |