Bluetooth communication between two microcontrollers

Hey, everyone!

I am trying to build a bluetooth communication between two ESP32 boards, but I have issues sending the data.

The Serial Monitor only shows: Connected Succesfully! but nothing happens after that.
So, I assume that the SerialBT.available() is not true in my loop(), but I have no clue why thats the case.

void loop() 
{
  if (SerialBT.available())
  {
    Serial.println(SerialBT.read());
    Serial.println("");
  }
  delay(2000);
}

If anyone has any idea what the problem here is, I would be very thankful for any help.

Master code:

#include <Arduino.h>
#include "BluetoothSerial.h"

BluetoothSerial SerialBT;

//Setup bluetooth
String name = "ESP32_num2"; //                  <------- set this to be the name of the other ESP32!!!!!!!!!
bool connected;

//data to send
int data;

void setup() 
{
  Serial.begin(115200);

  //Setup Bluetooth
  SerialBT.begin("ESP32_num1", true); 
  connected = SerialBT.connect("name");
    
  if(connected) {
    Serial.println("Connected Succesfully!");
  } 
  else 
  {
    while(!SerialBT.connected(10000)) 
    {
      Serial.println("Failed to connect"); 
    }
  }
}

void loop() 
{
  if (SerialBT.available()) 
  {
    data=random(1,21);
    SerialBT.write(data);
    Serial.print("sent!");
  }
  delay(2000);
}

Slave code:

#include <Arduino.h>
#include "BluetoothSerial.h"

BluetoothSerial SerialBT;

void setup() 
{
  Serial.begin(115200);
  SerialBT.begin("ESP32_num2"); 
}

void loop() 
{
  if (SerialBT.available()) {
    Serial.println(SerialBT.read());
    Serial.println("");
  }
  delay(2000);
}

In your master code, you only write data to the slave after the if (SerialBT.available()) is true. The slave code never ends anything so the master will never see anything available. So how is the master ever going to send anything for the slave to read? Move the sending of data to the slave out of the if (SerialBT.available()) block.

I am not sure that the Bluetooth on the ESP32 even works that way without pairing.

An easy and better (faster, more range) way for ESP32s to communicate is ESP-NOW.

Ok, now it works. Thank you very much!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.