system
December 29, 2010, 7:13pm
1
Hello, I am trying to control an arduino using virtual wire and I'm having trouble with my code. My transmitter is connected to the computer and I'm trying to send things like: 'a' or 'b' through the serial. The second arduino should receive these and turn an led on and off. What could be the problem?
Transmitter:
#include <VirtualWire.h>
#undef int
#undef abs
#undef double
#undef float
#undef round
void setup()
{
Serial.begin(9600);
Serial.println("Activated");
vw_set_ptt_inverted(true);
vw_setup(2000);
vw_set_tx_pin(13);
}
void loop()
{
if (Serial.available() > 0)
{
char message = Serial.read();
vw_send((uint8_t *)&message, 1);
vw_wait_tx();
}
}
Receiver:
#include <VirtualWire.h>
#undef int
#undef abs
#undef double
#undef float
#undef round
void setup()
{
vw_set_ptt_inverted(true);
vw_setup(2000);
vw_set_rx_pin(12);
vw_rx_start();
pinMode(13, OUTPUT);
}
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_get_message(buf, &buflen))
{
if (buf[buflen] == 'a') {
digitalWrite(13, HIGH);
}
if (buf[buflen] == 'b') {
digitalWrite(13, LOW);
}
}
}
system
December 29, 2010, 9:11pm
2
On the receiver side, this code is wrong:
if (buf[buflen] == 'a') {
If buflen equals 1, the value is in buf[0], not buf[1].
system
December 29, 2010, 9:28pm
3
Ok, I tried:
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_get_message(buf, &buflen))
{
if (buf[0] == 'a') {
digitalWrite(13, HIGH);
}
if (buf[0] == 'b') {
digitalWrite(13, LOW);
}
}
}
It dosen't seem to work.
system
December 29, 2010, 9:46pm
4
You can also use Serial.begin() and Serial.print() on the receiver, to see whether you are getting any data, and what that data is, if you are getting any.
system
December 29, 2010, 9:55pm
5
ok, Thanks. I'll try that.
Take a look at 4.5 of the manual.
Order is important for some of the calls, you have to move vw_setup.
system
January 5, 2011, 1:44am
7
it finally works!
I lowered the rate from 2000 to 1200
so for future reference:
transmitter:
#include <VirtualWire.h>
#undef int
#undef abs
#undef double
#undef float
#undef round
void setup()
{
Serial.begin(9600);
Serial.println("Activated");
vw_set_ptt_inverted(true);
vw_set_tx_pin(12);
vw_setup(1200);
}
void loop()
{
if (Serial.available() > 0)
{
char message = Serial.read();
vw_send((uint8_t *)&message, strlen(&message));
vw_wait_tx();
}
}
receiver:
#include <VirtualWire.h>
#undef int
#undef abs
#undef double
#undef float
#undef round
void setup()
{
vw_set_ptt_inverted(true);
vw_set_rx_pin(12);
vw_setup(1200);
vw_rx_start();
pinMode(13, OUTPUT);
}
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_get_message(buf, &buflen))
{
if (buf[0] == 'a') {
digitalWrite(13, HIGH);
}
if (buf[0] == 'b') {
digitalWrite(13, LOW);
}
}
}
thanks all for your help!