espd

BT code new Perplexity

Mar 18th, 2025
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. #include "BluetoothSerial.h"
  2.  
  3. BluetoothSerial SerialBT;
  4.  
  5. const char* targetDeviceName = "HostDeviceName"; // Replace with the name of your host device
  6. const char* pin = "1234"; // Replace with the correct PIN for pairing
  7.  
  8. void setup() {
  9. Serial.begin(115200);
  10. Serial.println("Starting ESP32 Bluetooth...");
  11.  
  12. // Initialize Bluetooth as a client
  13. if (!SerialBT.begin("ESP32_Client", true)) { // Enable Secure Simple Pairing (SSP)
  14. Serial.println("Failed to initialize Bluetooth!");
  15. while (1);
  16. }
  17. Serial.println("Bluetooth initialized as client.");
  18.  
  19. // Set the PIN for pairing
  20. esp_bt_gap_set_pin(ESP_BT_PIN_TYPE_FIXED, 4, (uint8_t*)pin);
  21.  
  22. // Scan for devices and connect to the target
  23. connectToHost();
  24. }
  25.  
  26. void loop() {
  27. // Check if data is available from the host device
  28. if (SerialBT.available()) {
  29. String receivedData = "";
  30. while (SerialBT.available()) {
  31. char c = SerialBT.read();
  32. receivedData += c;
  33. }
  34. Serial.print("Received: ");
  35. Serial.println(receivedData);
  36. }
  37.  
  38. delay(100); // Add a small delay to avoid overwhelming the host device
  39. }
  40.  
  41. void connectToHost() {
  42. Serial.println("Scanning for devices...");
  43.  
  44. int numDevices = SerialBT.discover();
  45. if (numDevices == 0) {
  46. Serial.println("No devices found. Retrying...");
  47. delay(5000);
  48. connectToHost();
  49. return;
  50. }
  51.  
  52. bool found = false;
  53. for (int i = 0; i < numDevices; i++) {
  54. String deviceName = SerialBT.getDiscoveredDeviceName(i);
  55. if (deviceName == targetDeviceName) {
  56. found = true;
  57. Serial.print("Found target device: ");
  58. Serial.println(deviceName);
  59.  
  60. if (SerialBT.connect(deviceName)) {
  61. Serial.println("Connected to host device.");
  62. } else {
  63. Serial.println("Failed to connect. Retrying...");
  64. delay(5000);
  65. connectToHost();
  66. }
  67. break;
  68. }
  69. }
  70.  
  71. if (!found) {
  72. Serial.println("Target device not found. Retrying...");
  73. delay(5000);
  74. connectToHost();
  75. }
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment