If you haven’t check on the first part on RF module explanation, you might want to read it before proceed with RF using library. Here we going to discuss how to implement VirtualWire library with low cost RF module. VirtualWire library does not use the Arduino UART pin (digital pin 0 and digital pin 1).

You can download the VirtualWire library here.

Before we look into the code, let us see some of the functions.

Configuration function

vw_set_tx_pin(transmit pin)

– Configure the transmit pin.

vw_set_rx_pin(receive pin)

– Configure the receive pin.

vw_setup(baudrate)

– Configure the baud rate of communication. Need to be same for both transmitter and receiver. Similar to Serial.begin(baud rate).

Transmission function

vw_send(message,length)

– Use to transmit message. “message” is an array of byte to be sent and “length” is the number of bytes in the array.

vw_wait_tx()

– Wait for all the message to be fully transmitted.

Reception function

vw_rx_start()

– Activate the receiver process.

vw_get_message(buf, &buflen))

– Read the last message received. “buf” is an array where the message is copied and “&buflen” is the array maximum size.

The set up of transmitter and receiver on two different Arduino.

rf2
Transmitter. Digital pin 11 as Tx.
rf1
Receiver. Digital pin 12 is set as Rx.

Lets look at the sample code:

Transmitter

#include <VirtualWire.h>

void setup()
{
 Serial.begin(9600);
 Serial.println("setup");
 vw_set_tx_pin(11);
 vw_setup(2000);
}

void loop()
{
 const char *msg = "hello";
 vw_send((uint8_t *)msg, strlen(msg));
 vw_wait_tx();
 delay(200);
}

Receiver

#include <VirtualWire.h>

void setup()
{
 Serial.begin(9600);
 Serial.println("setup");
 vw_set_rx_pin(12);
 vw_setup(2000);
 vw_rx_start();
}

void loop()
{
 uint8_t buf[VW_MAX_MESSAGE_LEN];
 uint8_t buflen = VW_MAX_MESSAGE_LEN;

if (vw_get_message(buf, &buflen))
 {
 int i;
 Serial.print("Got: ");
 for (i = 0; i < buflen; i++)
 {
 Serial.print(buf[i], HEX);
 Serial.print(" ");
 }
 Serial.println("");
 }
}

Video demo for RF module with VirtualWire library.

Advertisements