Two HC-05 modules won't stay paired

I'm new here and didn't realize there are rules for posting. Where do I find those? Anyway, here is the code. I'll have to work on making drawings of the circuits.

Code for the slave (Uno) module (not sure how the code formatting is supposed to be):

const int button = 8;
int buttonState = 0;

void setup() 
{
  pinMode(button, INPUT);
  Serial.begin(38400); //
}
void loop() 
{
    // Reading the button
    buttonState = digitalRead(button);
        if (buttonState == HIGH) 
        {
        Serial.write('1'); // Sends '1' to the master to turn on LED
        }
        else 
        {
        Serial.write('0');
        }  
}

and here is for the master (Mega) module:

#define ledPin 7
int state = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  Serial1.begin(38400); // UART communication rate set on the HC05
}
void loop() {
 if(Serial1.available() > 0){ // Checks whether data is coming from the serial port  
 state = Serial1.read(); // Reads the data from the serial port
 }
 // Controlling the LED
  if (state == '1') {
  digitalWrite(ledPin, HIGH); // LED ON
  state = 0;
 }
 else if (state == '0') {
  digitalWrite(ledPin, LOW); // LED ON
  state = 0;
 }
 delay(10);
 
}

1 Like