espd

esp32 cyd BT 6 with MAC

Mar 20th, 2025
20
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. #include "BluetoothSerial.h"
  2.  
  3. BluetoothSerial SerialBT;
  4. const char* targetDeviceName = "HostDeviceName"; // Replace with host name
  5. const char* pin = "1234"; // Host's pairing PIN
  6. bool deviceFound = false;
  7.  
  8. // Async scan callback
  9. void btAdvertisedDeviceFound(BTAdvertisedDevice *pDevice) {
  10. Serial.printf("Found: %s\n", pDevice->toString().c_str());
  11.  
  12. if (pDevice->getName().compare(targetDeviceName) == 0) {
  13. Serial.println("Target device located! Stopping scan...");
  14. SerialBT.discoverAsyncStop();
  15. deviceFound = true;
  16.  
  17. // Connect using MAC address
  18. if (SerialBT.connect(pDevice->getAddress())) {
  19. Serial.println("Successfully connected!");
  20. } else {
  21. Serial.println("Connection failed");
  22. }
  23. }
  24. }
  25.  
  26. void setup() {
  27. Serial.begin(115200);
  28. SerialBT.onConfirmRequest(nullptr); // Disable SSP pairing
  29.  
  30. // Initialize as client with PIN
  31. SerialBT.setPin(pin);
  32. if (!SerialBT.begin("ESP32_Client", true)) {
  33. Serial.println("BT init failed!");
  34. while(1);
  35. }
  36.  
  37. // Start async scan
  38. if (SerialBT.discoverAsync(btAdvertisedDeviceFound)) {
  39. Serial.println("Scanning for devices...");
  40. delay(10000); // Scan for 10 seconds
  41. if (!deviceFound) {
  42. SerialBT.discoverAsyncStop();
  43. Serial.println("Scan timeout - device not found");
  44. }
  45. }
  46. }
  47.  
  48. void loop() {
  49. // Handle data transfer when connected
  50. if (SerialBT.connected()) {
  51. // Read from host
  52. if (SerialBT.available()) {
  53. String data = SerialBT.readString();
  54. Serial.print("Received: ");
  55. Serial.println(data);
  56. }
  57.  
  58. // Send to host
  59. if (Serial.available()) {
  60. SerialBT.write(Serial.read());
  61. }
  62. } else if (deviceFound) {
  63. // Reconnection logic
  64. Serial.println("Attempting reconnect...");
  65. delay(5000);
  66. SerialBT.connect();
  67. }
  68. }
  69.  
Advertisement
Comments
Add Comment
Please, Sign In to add comment