#include <BluetoothSerial.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
BluetoothSerial SerialBT;
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
void setup() {
Serial.begin(115200);
SerialBT.begin("ESP32_Device2"); // Start Bluetooth with the name "ESP32_Device2"
Serial.println("Device 2 Bluetooth Started.");
// Initialize the OLED display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0, 0);
display.println("Connecting to Device 1...");
display.display();
// Try to connect to Device 1
while (!SerialBT.connect("ESP32_Device1")) {
Serial.println("Device 2: Connecting...");
delay(1000);
}
Serial.println("Device 2 Connected to Device 1");
// Update OLED display after connection
display.clearDisplay();
display.setCursor(0, 0);
display.println("Connected to Device 1");
display.display();
}
void loop() {
if (SerialBT.connected()) {
// Send a message to Device 1
String message = "Hello from Device 2";
SerialBT.println(message);
Serial.println("Device 2 Sent: " + message);
// Check for incoming data from Device 1
if (SerialBT.available()) {
String receivedData = SerialBT.readString();
Serial.println("Device 2 Received: " + receivedData);
// Display the received data on the OLED
display.clearDisplay();
display.setCursor(0, 0);
display.println("Received:");
display.setCursor(0, 10);
display.println(receivedData);
display.display();
}
delay(2000); // Send message every 2 seconds
}
delay(20);
}