Search code examples
bluetoothesp32

ESP32 Bluetooth. Redirecting serial output


I have an ESP32 dev board to which I have attached a MMA8451 accelerometer which outputs it's data via serial. Is there an easy way to output the data to a bluetooth serial reciever on an android phone? In part of the code I am using Serial.print statements. Is there a bluetooth equivalent ?

// Read the 'raw' data in 14-bit counts
  mma.read();
  Serial.print("X:\t"); Serial.print(mma.x); 
  Serial.print("\tY:\t"); Serial.print(mma.y); 
  Serial.print("\tZ:\t"); Serial.print(mma.z); 
  Serial.println();

Solution

  • I found this with some quick googling. Or if you want to use the ESP32-idf.

    Seems to me that there are two possibilities. You could either use the Arduino BluetoothSerial library or the ESP-IDF SPP GATT CLIENT demo

    The Arduino solutions looks something like this:

    #include "BluetoothSerial.h"
    
    BluetoothSerial SerialBT;
    
    void setup() {
      SerialBT.begin("ESP32");
    }
    
    void loop() {
    
      SerialBT.println("Hello World");
      delay(1000);
    }
    

    The ESP-IDF version is a bit more complex, but this is the code to send a periodic heartbeat using the bluetooth api:

    #ifdef SUPPORT_HEARTBEAT
    void spp_heart_beat_task(void * arg)
    {
        uint16_t cmd_id;
    
        for(;;) {
            vTaskDelay(50 / portTICK_PERIOD_MS);
            if(xQueueReceive(cmd_heartbeat_queue, &cmd_id, portMAX_DELAY)) {
                while(1){
                    if((is_connect == true) && (db != NULL) && ((db+SPP_IDX_SPP_HEARTBEAT_VAL)->properties & (ESP_GATT_CHAR_PROP_BIT_WRITE_NR | ESP_GATT_CHAR_PROP_BIT_WRITE))){
                        esp_ble_gattc_write_char( spp_gattc_if,
                                                  spp_conn_id,
                                                  (db+SPP_IDX_SPP_HEARTBEAT_VAL)->attribute_handle,
                                                  sizeof(heartbeat_s),
                                                  (uint8_t *)heartbeat_s,
                                                  ESP_GATT_WRITE_TYPE_RSP,
                                                  ESP_GATT_AUTH_REQ_NONE);
                        vTaskDelay(5000 / portTICK_PERIOD_MS);
                    }else{
                        ESP_LOGI(GATTC_TAG,"disconnect\n");
                        break;
                    }
                }
            }
        }
    }
    #endif