Hardware Reference
In-Depth Information
void loop()
{
Serial1.println(digitalRead(BUTTON)); //Send the button's state
delay(50); //Small delay so we don't flood the receiver
}
In the setup, the serial port connected to the XBee starts to run at 9600 baud.
Every 50ms, the value of the digital input is read and printed out to the radio.
digitalRead() can be placed directly inside of the println statement because
the output value doesn't need to be used anywhere else in the program.
ReceiverSoftware
The receiver software is more complicated than the transmitter program. The
example code provided in Listing 11-6 was written for an Arduino Uno. If you
are using a Leonardo-type board, replace Serial with Serial1 .
This software needs to listen to the serial port, determine whether the remote
button is being pressed, and modulate light/sound while still listening for new
incoming data. The last part is what makes this program tricky; you need to
use a “nonblocking” technique so that program doesn't have to call delay()
at any point. A blocking function is anything that prevents the system from
performing other tasks. delay() is an example of a blocking function. When it
is invoked, nothing else happens in the program until delay() has finished. If
you were to use a delay() statement in a communication scheme like this, you
would run into two problems: The receiver's response to the transmitter's signal
would not be instantaneous, and the input buffer could overflow because the
transmitter may be sending data at a rate faster than the receiver can read it.
The goal is to have the light blink back and forth between red and green,
and to have the Piezo's pitch go back and forth between two frequencies. You
can't use a delay() for the reasons mentioned earlier. Instead of a delay() , you
use the millis() function, which returns the number of milliseconds since
the Arduino started running the sketch. The light and speaker switch at a rate
of once every 100ms. So, you store the time at which the previous switch was
made and look for a new millis() value to be at least 100ms greater than the
previous switch time. When that happens, you swap the pins for the LED and
adjust the frequency. Also in loop() , you check the serial buffer for a '0' or
'1' and adjust the lights and sound accordingly.
The setup() initializes the program's values. To facilitate switching, you keep
track of the pin states of the LEDs. You also keep track of the current frequency
and the previous toggle time returned from millis() .
Consider the code in Listing 11-6 and load it on to your receiving Arduino.
Before uploading the code, remember to set any necessary jumpers or remove
the XBee shield to program the board.
Search WWH ::




Custom Search