9.- App sends three values for a tricolor LED RGB. Receive those same values.
p110i_esp32_ble_LED.aia (236.1 KB)
// Juan Antonio Villalpando.
// http://kio4.com/arduino/160_Wemos_ESP32_BLE.htm
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#include <Arduino.h>
#include <analogWrite.h>
String valor;
String red;
String green;
String blue;
int ind1;
int ind2;
int ind3;
#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.length() > 0) {
valor = "";
for (int i = 0; i < value.length(); i++){
valor = valor + value[i];
}
Serial.print("valor = ");
Serial.println(valor);
ind1 = valor.indexOf(',');
red = valor.substring(0, ind1);
ind2 = valor.indexOf(',', ind1+1 );
green = valor.substring(ind1+1, ind2);
ind3 = valor.indexOf(',', ind2+1 );
blue = valor.substring(ind2+1);
Serial.print("red = ");
Serial.println(red);
Serial.print("green = ");
Serial.println(green);
Serial.print("blue = ");
Serial.println(blue);
Serial.println();
analogWrite(12, red.toInt());
analogWrite(14, green.toInt());
analogWrite(27, blue.toInt());
pCharacteristic->setValue(valor.c_str()); // Devuelve el valor.
}
}
};
void setup() {
analogWriteResolution(12, 8); // Resolución 8 bits
analogWriteResolution(14, 8);
analogWriteResolution(27, 8);
Serial.begin(115200);
BLEDevice::init("MyESP32");
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("Iniciado.");
pService->start();
BLEAdvertising *pAdvertising = pServer->getAdvertising();
pAdvertising->start();
}
void loop() {
//
}
-
ESP32 does not have the AnalogWrite function, therefore we must download and install the analogWrite library from:
https://github.com/ERROPiX/ESP32_AnalogWrite -
Modifications:
Comment this line:
// pCharacteristic->setValue(valor.c_str()); // Return value.
Change this block:
-
http://kio4.com/arduino/160_Wemos_ESP32_BLE.htm#7 (in Spanish).