#include <BluetoothSerial.h>
#include <WiFi.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);
// Replace with the actual MAC address of Device 1
uint8_t serverMacAddress[] = {0x24, 0x0A, 0xC4, 0xXX, 0xXX, 0xXX}; // Update this
void setup() {
Serial.begin(115200);
// Start Bluetooth with the name "ESP32_Device2"
if (!SerialBT.begin("ESP32_Device2")) {
Serial.println("An error occurred while starting Bluetooth.");
while (1); // Halt if Bluetooth fails to start
}
Serial.println("Device 2 Bluetooth Started.");
// Initialize the OLED display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // I2C address 0x3C
Serial.println(F("SSD1306 allocation failed"));
while (1); // Halt if display initialization fails
}
display.clearDisplay(); // Clear the buffer
display.setTextSize(1); // Set text size to 1
display.setTextColor(WHITE); // Set text color to white
display.setCursor(0, 0); // Set the cursor to top-left corner
display.println("Connecting to Device 1...");
display.display(); // Display the text
// Try to connect to Device 1 via MAC address
while (!SerialBT.connect(serverMacAddress)) {
Serial.println("Device 2: Connecting...");
delay(1000); // Wait for 1 second before retrying
}
Serial.println("Device 2 Connected to Device 1");
// Update OLED display after successful 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); // Small delay for stability
}