Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "BluetoothSerial.h"
- BluetoothSerial SerialBT;
- const char* targetDeviceName = "HostDeviceName"; // Replace with the name of your host device
- const char* pin = "1234"; // Replace with the correct PIN for pairing
- void setup() {
- Serial.begin(115200);
- Serial.println("Starting ESP32 Bluetooth...");
- // Initialize Bluetooth as a client
- if (!SerialBT.begin("ESP32_Client", true)) { // Enable Secure Simple Pairing (SSP)
- Serial.println("Failed to initialize Bluetooth!");
- while (1);
- }
- Serial.println("Bluetooth initialized as client.");
- // Set the PIN for pairing
- esp_bt_gap_set_pin(ESP_BT_PIN_TYPE_FIXED, 4, (uint8_t*)pin);
- // Scan for devices and connect to the target
- connectToHost();
- }
- void loop() {
- // Check if data is available from the host device
- if (SerialBT.available()) {
- String receivedData = "";
- while (SerialBT.available()) {
- char c = SerialBT.read();
- receivedData += c;
- }
- Serial.print("Received: ");
- Serial.println(receivedData);
- }
- delay(100); // Add a small delay to avoid overwhelming the host device
- }
- void connectToHost() {
- Serial.println("Scanning for devices...");
- int numDevices = SerialBT.discover();
- if (numDevices == 0) {
- Serial.println("No devices found. Retrying...");
- delay(5000);
- connectToHost();
- return;
- }
- bool found = false;
- for (int i = 0; i < numDevices; i++) {
- String deviceName = SerialBT.getDiscoveredDeviceName(i);
- if (deviceName == targetDeviceName) {
- found = true;
- Serial.print("Found target device: ");
- Serial.println(deviceName);
- if (SerialBT.connect(deviceName)) {
- Serial.println("Connected to host device.");
- } else {
- Serial.println("Failed to connect. Retrying...");
- delay(5000);
- connectToHost();
- }
- break;
- }
- }
- if (!found) {
- Serial.println("Target device not found. Retrying...");
- delay(5000);
- connectToHost();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment