Control a blinking light with a master and slave HC-05

I am trying to make a project with a master and slave HC-05 module. Right now I'm just trying to make sure that it works and is connected properly. I have written this code for the master module:

#include <SoftwareSerial.h>

SoftwareSerial serial(2,3);

void setup() {
  // put your setup code here, to run once:
  serial.begin(38400);

}

void loop() {
  // put your main code here, to run repeatedly:
  serial.write('1');
  delay(1000);
  serial.write('0');
  delay(1000);
  
}

and this for the slave module:

#include <SoftwareSerial.h>

SoftwareSerial serial(2,3);
int led = 8;
int data;

void setup() {
  // put your setup code here, to run once:
  serial.begin(38400);
  pinMode(led, OUTPUT);

}

void loop() {
  if (serial.available() > 0) {
    data = serial.read();
  }

  if (data == "1") {
    digitalWrite(led, HIGH);
  }
  
  else if (data == "0") {
    digitalWrite(led, LOW);
  }
  
}

I have been reading the SerialSoftware documentation, and I believe that the master code should simply send a 1, wait a second, send a 0, and then wait a second. And the slave should be receiving this data, turning on the LED, waiting a second, then turning it off. I see the synchronized blinking lights so I believe that my HC-05s are connected, and I paired the successfully. It may be something I did wrong with the wiring? On both of them, RX of the HC-05 is connected to pin 2 and TX is connected to pin 3. And on the slave I simply have pin 8 connected to an led. When I plug in both arduinos and upload the sketches, the LED doesn't do anything. Is there a way I can make sure data is being transmitted? Did I do something wrong in my code to make it not work? Thanks for any help!

Try

if (data == '1') {

I'm a little surprised you didn't get a compilation error

You can write a simple loopback sketch to re-transmit any characters that are received. If that works, you can try the LED code.

You may want to limit your changes to when data comes in.

void loop() {
   if (serial.available() > 0) {
      data = serial.read();
      if (data == '1') {
         digitalWrite(led, HIGH);
      } else if (data == '0') {
         digitalWrite(led, LOW);
      }
   }
}

-jim lee

I have tried changing the double quotes to single quotes, as well as moving the if statement to right after we read the data and neither fix the problem. I did quickly just write the LED pin on with the slave module, and the pin turned on as expected. How can I make sure serial data is being sent or received?

Why in the world would you name you SoftwareSerial instances "serial"? That's one capitalization mistake away from the standard Arduino "Serial" object. Seems like a very confusing mistake waiting to happen.

ithortureu:
How can I make sure serial data is being sent or received?

reply #2

Aarg, how would I go about doing that? It sounds like what I wan to do but I'm not sure how. Could you link me to a reference or something? Thanks!