Untitled

mail@pastecode.io avatar
unknown
plain_text
21 days ago
2.1 kB
3
Indexable
Never
Bluetooth Server (Peripheral) ESP32

#include <BluetoothSerial.h>
#include <WiFi.h>
#include <WiFiServer.h>

BluetoothSerial BTSerial;
WiFiServer server(1234); // Port for TCP communication

void setup() {
  Serial.begin(115200);
  
  // Initialize Bluetooth
  BTSerial.begin("ESP32_BT_Server");

  // Initialize Wi-Fi
  WiFi.begin("SSID", "PASSWORD");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  // Start TCP server
  server.begin();
}

void loop() {
  // Accept new client
  WiFiClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        String data = client.readStringUntil('\n');
        BTSerial.println(data);
      }
      
      if (BTSerial.available()) {
        String btData = BTSerial.readStringUntil('\n');
        client.println(btData);
      }
    }
    client.stop();
  }
}

Bluetooth Client (Central) ESP32

#include <BluetoothSerial.h>
#include <WiFi.h>
#include <WiFiClient.h>

BluetoothSerial BTSerial;
WiFiClient client;

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

  // Initialize Bluetooth
  BTSerial.begin("ESP32_BT_Client");

  // Initialize Wi-Fi
  WiFi.begin("SSID", "PASSWORD");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  // Connect to TCP server
  while (!client.connect("Server_IP", 1234)) {
    delay(1000);
    Serial.println("Connecting to server...");
  }
  Serial.println("Connected to server");
}

void loop() {
  if (client.connected()) {
    if (BTSerial.available()) {
      String btData = BTSerial.readStringUntil('\n');
      client.println(btData);
    }

    if (client.available()) {
      String data = client.readStringUntil('\n');
      BTSerial.println(data);
    }
  } else {
    Serial.println("Disconnected from server");
    client.stop();
    while (!client.connect("Server_IP", 1234)) {
      delay(1000);
      Serial.println("Reconnecting to server...");
    }
  }
}
Leave a Comment