Go Down

Topic: Checking if a device is transmitting serial data before taking an action? (Read 368 times) previous topic - next topic

jerseyguy1996

I have a GPS module that you can cycle between "active" and "hibernate" mode by giving a 200ms pulse on its "ON/OFF" pin.  It transmits data once per second when it is "active" and doesn't transmit any data when it is in "hibernate" mode.  The only way for me to know which state it is in is to see if it is transmitting data so for instance, when I am ready to start receiving location data i will need to toggle the "ON/OFF" pin but first I want to check and make sure that it isn't already active or else my pulse is just going to turn it off instead of on.  Likewise when I go to put it into "hibernate" mode I want to be sure that it isn't already in "hibernate" mode or else my pulse is going to inadvertently turn it on.  I wrote some code to try to check this because in my mind I need to first empty out the Serial buffer, wait a bit more than a second, and then check to see if any Serial data has come in.  I would like some guidance on the most reasonable way to do this.  My attempt at it is below.

Code: [Select]
boolean GPSisAwake()
{
  //check to see if GPS is already awake by purging serial data and then
  //checking to see if Serial data is still coming in
  while(softSerial.available()) softSerial.read();
  delay(1200);
  if(softSerial.available()) return true;
}
Arduino Uno;
Mega328

PeterH

That might work, but limits you to a sketch that blocks on serial input.

It's much better to use a non-blocking approach for this type of thing, because it lets other processing continue while you're waiting.

The non-blocking approach is to handle serial input when it's available, and record the current each time you receive some input. To know whether you are receiving input you just compare the current time with the time of the last input to see how recent it was.
I only provide help via the forum - please do not contact me for private consultancy.

johncc

Did your code work as you expected?

Another way would be to (elsewhere in your code) store the the most recent time you recieved expected data, then in this code just check to see if more than 1 sec has elapsed since then, and if so, send the turn-on pulse..

John

jerseyguy1996

Now see.....this is why I love this forum!  Thanks both of you for the solution to this!
Arduino Uno;
Mega328

GoForSmoke

Does it change to hibernate by itself to save power after some time?

If your code explicitly turned the thing off after each read then you'd know the state for the next wouldn't you?

Nick Gammon on multitasking Arduinos:
1) http://gammon.com.au/blink
2) http://gammon.com.au/serial
3) http://gammon.com.au/interrupts

Go Up