1

How to clear the serial buffer of arduino uno? This is my code to on and off the LED using sms from mobile using gsm module

#include <SoftwareSerial.h>
int Led=7;

SoftwareSerial mySerial(9, 10);

void setup()
{
  pinMode(Led,OUTPUT);
  mySerial.begin(9600);   // Setting the baud rate of GSM Module  
  Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
  delay(100);
}


void loop()
{
  if (mySerial.available()>0)
  {

  }
   switch(mySerial.read())
  {
    case 'a':
           digitalWrite(Led,HIGH);
           delay(10000);
           digitalWrite(Led,LOW);
           delay(100);
           break;

    case 'b' :
           digitalWrite(Led,LOW);
           break;


  }}

problem is whenever i on the module or the connection is restablished it automatically gets even without an sms.I need it to be fully in my control so i need to clear the serial buffer.

1

If you are receiving unsolicited message (reading junk) then you could extend the bit pattern you are expecting so that there is almost no possibility of you accidentally receiving it.

Rather than 'a' and 'b' as triggers user LED="0" and LED="1". Doing this makes reading the data much harder, because what you are looking for may start on character 4 of the string you read. This is what I think you will need to do.

  1. Read each character in turn and store them in a buffer until you have 7.
  2. Is the first character an L.
  3. If it isn't then delete the first character, shuffle the buffer left one place and load in the next character before returning to step 1.
  4. If it was, check the next character matches the expected.
  5. If it doesn't match delete all character to the left and this one and return to step one.
  6. If you have a matching token then parse it (get the 1 or 0) and do the action.
| improve this answer | |
0

You can simply clear it by reading it until its empty.

while(Serial.available()){
    Serial.read();
}

There also used to be a

Serial.flush();

to clear the serial. However they changed it to some other functionality. For further details you can look at the arduino reference page on Serial.

| improve this answer | |

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.