LED on/off with ESP32 and Thunkable

Question that Prompted this Tutorial:

How can I control an LED or other device via BLE with my Thunkable app.

Goal:

Create an app using an ESP 32 to turn on/off an LED.

Explanation:

Once you master this topic, you can expand the concept to larger applications such by switching out the LED for a relay and controlling a powered device in your home via BLE or even could be used to toggle a lever that opens up a secret compartment in your desk where you hid your best coding tips!

Types of Apps You Might Use This In:

  • Hobby Apps
  • Health Care Products
  • Remote Monitoring Systems
  • Alarm/Security Systems
  • Educational Apps

Blocks / Components Used:

Buttons
Labels
BLE component
ESP32 (and related items)

Link to Template / Example:

https://x.thunkable.com/projects/62796cba31b26e00117da1b4/4b53d1dc-ea36-4d1d-9f88-2180c49e0bb3/designer

ESP32 Code


#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
const byte ledG = 33;


#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"

class MyCallbacks: public BLECharacteristicCallbacks {
    void onWrite(BLECharacteristic *pCharacteristic) {
      std::string value = pCharacteristic->getValue();
      
      if (value == "0") {

        digitalWrite(ledG, HIGH);

      }
      else {
        digitalWrite(ledG, LOW);
      }
    }
};


void setup() {
  Serial.begin(115200);
  pinMode(ledG, OUTPUT);
  BLEDevice::init("Thunkable & esp32");
  BLEServer *pServer = BLEDevice::createServer();
  BLEService *pService = pServer->createService(SERVICE_UUID);
  BLECharacteristic *pCharacteristic = pService->createCharacteristic(
                                         CHARACTERISTIC_UUID,
                                         BLECharacteristic::PROPERTY_READ |
                                         BLECharacteristic::PROPERTY_WRITE
                                       );

  pCharacteristic->setCallbacks(new MyCallbacks());
  pCharacteristic->setValue("Turn me on/off");
  pService->start();

  BLEAdvertising *pAdvertising = pServer->getAdvertising();
  pAdvertising->start();
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(2000);
 
}

that’s a 220 Ω resistor

1 Like