Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Program to control LED (ON/OFF) from ESP32 using Serial Bluetooth
- by Daniel Carrasco -> https://www.electrosoftcloud.com/
- */
- #include "BluetoothSerial.h"
- #if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
- #error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
- #endif
- BluetoothSerial BT; // Objeto Bluetooth
- String clientName = "ESP32_LED_Control";
- bool connected;
- TaskHandle_t ConnectBluetoothHandle;
- // Function prototype
- void callback_function(esp_spp_cb_event_t event, esp_spp_cb_param_t *param);
- void ConnectBluetooth(void *pvParameters) {
- // connect to bluetooth.
- for (;;) { // A Task shall never return or exit.
- connected = BT.connect(clientName);
- if(connected) {
- Serial.println("¡Conectado exitosamente!");
- // Pause the task until bluetooth is disconnected again
- vTaskSuspend(NULL);
- }
- else {
- Serial.println("No se pudo conectar. Asegúrese de que el dispositivo remoto esté disponible y dentro del alcance.");
- // Wait a second to retry the connection
- vTaskDelay( pdMS_TO_TICKS(1000) );
- }
- }
- }
- void setup() {
- Serial.begin(9600); // Inicialización de la conexión en serie para la depuración
- BT.begin("ESP32_client", true); // Nombre de su dispositivo Bluetooth y en modo maestro
- Serial.println("El dispositivo Bluetooth está en modo maestro. Conectando con el anfitrión ...");
- BT.register_callback(callback_function);
- xTaskCreatePinnedToCore(
- ConnectBluetooth, // Function to call
- "ConnectBluetooth", // Name for this task, mainly for debug
- 1024, // Stack size
- NULL, // pvParameters to pass to the function
- 1, // Priority
- &ConnectBluetoothHandle, // Task handler to use
- 1
- );
- }
- void loop() {
- if (connected) {
- delay(500);
- BT.write(49); // Envía 1 en ASCII
- delay(500);
- BT.write(48); // Envía 0 en ASCII
- }
- else {
- delay(1000);
- }
- }
- void callback_function(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) {
- if (event == ESP_SPP_CLOSE_EVT ) {
- Serial.println("Cliente desconectado. Activando función de reconexión.");
- vTaskResume(ConnectBluetoothHandle);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement