I'm working with XBEE radios for a little remote control project. One Arduino Fio v3+XBEE combo is using the following code to simply send a capital 'D' when a button is pushed:
Another Arduino Fio v3+XBEE is receiving that signal and flashing an LED with each capital 'D' it reads:
int LED = 5;
void setup() {
pinMode(LED,OUTPUT);
Serial.begin(9600);
Serial1.begin(9600);
}
void loop() {
if (Serial1.available() > 0) {
if (Serial1.read() == 'D') {
Serial.write('D');
digitalWrite(LED,HIGH);
delay(10);
}
}
else {
digitalWrite(LED,LOW);
}
}
This code pair works fine with no problems because the receiving Arduino can keep up with the sending Arduino without a problem. However, in the next version of the receiving Arduino's code, I want it to trigger 2 pins with a specific timing sequence lasting about 4 seconds. This is causing me a problem, because when I hit the button on the sending unit usually about 5 'D''s get sent, which means on the receiving side, it will try to go through the sequence 5 times when I only want it to go through once. Is there a way to flush the Serial1 buffer on the receiving side after the first 'D' is received and ignore the buffer until the sequence is finished, then start listening again? Would I just use Serial1.end() as soon as the first 'D' is read and then Serial1(begin(9600) when the sequence is complete, or is there a better way?
If all you want to do is flush the input stream, just read characters and toss them until available() returns 0. Doing a Serial.end() is using a sledge hammer to swat a fly.
Thanks for the suggestions, everyone. I didn't want to limit the sending side by restricting how often the button could be pushed because I thought that might lead to timing issues between sending and receiving that I couldn't anticipate. I may try to pull in all the data and throw it away as long as the timed sequence is running, but for now things are working. Thanks, everyone!
fr0zone:
I didn't want to limit the sending side by restricting how often the button could be pushed because I thought that might lead to timing issues between sending and receiving that I couldn't anticipate
I don't think that was exactly the suggestion. It was more along the lines of "send only one character each time the button is pushed".
You need to look at the state change detection example. You want, I think, to send a letter when the switch BECOMES pressed, not when the switch IS pressed.