Writing and Reading on Serial Port.

Hi Everyone!

I would like to ask if how can I access the most recent data on the Serial Port?

The idea of my project would be this, I use the Serial monitor to enter data so the board will do a certain routine. For example, if I entered "a" the board will do RoutineA, and when I entered "b" the board will do RoutineB.

If I entered 5 a's
e.g. aaaaa ---- the board will do RoutineA 5times

If I entered 5 b's
e.g. bbbbb ---- the board will do RoutineB 5times

What I want now is, when I enter 5 a's
e.g. aaaaa
while the board is doing the RoutineA....
and then I suddenly entered "b"
I want my Board to do the RoutineB and ignore all the remaining a's that I have entered.

I want to always access the most recent data on the Serial Port.
How can I possibly do this?

Thankyou!

If you need the most recent, you’ll need to read all the data available, so each time round loop, read it all and add up the a’s and the b’s. Whichever you read last tells you whether you’re in a mode or b mode. Decrement the count for the mode you’re in, run that mode’s function once.

thankyou wildbill.

how about if I actually don't know how many a's and b's are there on the serial port on a given time but I still want to get the last and recent data available on the port.

Just call RoutineX every time you get a single character. Something like

loop () {

  if (serial.available() > 0) {
      switch (serial.read()) {
         case 'a':
            RoutineA();
            break;

         case 'b':
            RoutineB();
            break;
      }
   }

Rob

gilberto:
how about if I actually don't know how many a's and b's are there on the serial port on a given time but I still want to get the last and recent data available on the port.

It doesn't matter how many there are, just read them all from the serial port and keep one counter each for a & b. Whichever one you read last is the routine you should execute. Call it once and next time round the loop you'll check serial again to see whether it's been overruled with newer data.