Hello! I want to use RF modules ( transmitter and receiver ) to send commands from Serial Monitor to another arduino via the RF modules to switch on/off a relay module. I'm using the Virtual Wire library, and i've got stuck with the code ( i've used the example code from a site as a base code ). This is my code so far:
Transmitter:
#include <stdlib.h>
#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <wiring.h>
#endif
#include <VirtualWire.h>
int radio = 12; // The radio pin
void setup(){
Serial.begin(9600);
pinMode(radio, OUTPUT);
vw_set_tx_pin(radio); // Setting the transmission pin to the radio pin
vw_setup(2000);
}
void loop(){
char on = '1'; // I couldn't get it working with words so i just used 0 and 1 as commands
char off = '0';
delay(1000);
char res = Serial.read();
if (Serial.available()){
if (res == '1'){
vw_send((uint8_t *)on, 1);
Serial.println("Command sent! On!");
}
else if (res == '0'){
vw_send((uint8_t *)off, 1);
Serial.println("Command Sent! Off!");
}
}
}
Receiver:
#include <VirtualWire.h>
const int relay_pin = 7;
const int receive_pin = 11;
void setup()
{
pinMode(receive_pin, INPUT);
delay(1000);
Serial.begin(9600); // Debugging only
Serial.println("setup");
// Initialise the IO and ISR
vw_set_rx_pin(receive_pin);
vw_setup(2000); // Bits per sec
vw_rx_start(); // Start the receiver PLL running
}
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_get_message(buf, &buflen)) // Non-blocking
{
char(buf);
if (buf == '1'){
digitalWrite(relay_pin, HIGH); // Turn on the relay module
}
else if (buf == '0'){
digitalWrite(relay_pin, LOW); // Turn off the relay module
}
}
}
}