Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "BluetoothSerial.h"
- BluetoothSerial SerialBT;
- const char* targetDeviceName = "HostDeviceName"; // Replace with host name
- const char* pin = "1234"; // Host's pairing PIN
- bool deviceFound = false;
- // Async scan callback
- void btAdvertisedDeviceFound(BTAdvertisedDevice *pDevice) {
- Serial.printf("Found: %s\n", pDevice->toString().c_str());
- if (pDevice->getName().compare(targetDeviceName) == 0) {
- Serial.println("Target device located! Stopping scan...");
- SerialBT.discoverAsyncStop();
- deviceFound = true;
- // Connect using MAC address
- if (SerialBT.connect(pDevice->getAddress())) {
- Serial.println("Successfully connected!");
- } else {
- Serial.println("Connection failed");
- }
- }
- }
- void setup() {
- Serial.begin(115200);
- SerialBT.onConfirmRequest(nullptr); // Disable SSP pairing
- // Initialize as client with PIN
- SerialBT.setPin(pin);
- if (!SerialBT.begin("ESP32_Client", true)) {
- Serial.println("BT init failed!");
- while(1);
- }
- // Start async scan
- if (SerialBT.discoverAsync(btAdvertisedDeviceFound)) {
- Serial.println("Scanning for devices...");
- delay(10000); // Scan for 10 seconds
- if (!deviceFound) {
- SerialBT.discoverAsyncStop();
- Serial.println("Scan timeout - device not found");
- }
- }
- }
- void loop() {
- // Handle data transfer when connected
- if (SerialBT.connected()) {
- // Read from host
- if (SerialBT.available()) {
- String data = SerialBT.readString();
- Serial.print("Received: ");
- Serial.println(data);
- }
- // Send to host
- if (Serial.available()) {
- SerialBT.write(Serial.read());
- }
- } else if (deviceFound) {
- // Reconnection logic
- Serial.println("Attempting reconnect...");
- delay(5000);
- SerialBT.connect();
- }
- }
Advertisement
Comments
-
- Add to platformio.ini:
- lib_deps =
- esp32/BluetoothSerial @ ^2.0.5
Add Comment
Please, Sign In to add comment