SunFounder ESP32 Starter Kit
This code is an extension of a previous project(7.1 Bluetooth), adding RGB LED configurations and custom commands
such as “led_off”, “red”, “green”, etc. These commands allow the RGB LED to be controlled by sending commands
from a mobile device using LightBlue.
Let’s break down the code step by step:
• Add new global variables for the RGB LED pins, PWM channels, frequency, and resolution.
...
// Define RGB LED pins
const int redPin = 27;
const int greenPin = 26;
const int bluePin = 25;
// Define PWM channels
const int redChannel = 0;
const int greenChannel = 1;
const int blueChannel = 2;
...
• Within the setup() function, the PWM channels are initialized with the predefined frequency and resolution.
The RGB LED pins are then attached to their respective PWM channels.
void setup() {
...
// Set up PWM channels
ledcSetup(redChannel, freq, resolution);
ledcSetup(greenChannel, freq, resolution);
ledcSetup(blueChannel, freq, resolution);
// Attach pins to corresponding PWM channels
ledcAttachPin(redPin, redChannel);
ledcAttachPin(greenPin, greenChannel);
ledcAttachPin(bluePin, blueChannel);
}
• Modify the onWrite method in the MyCharacteristicCallbacks class. This function listens for data coming
from the Bluetooth connection. Based on the received string (like "led_off", "red", "green", etc.), it controls
the RGB LED.
// Define the BLE characteristic callbacks
class MyCharacteristicCallbacks : public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic) {
std::string value = pCharacteristic->getValue();
if (value == "led_off") {
setColor(0, 0, 0); // turn the RGB LED off
Serial.println("RGB LED turned off");
} else if (value == "red") {
setColor(255, 0, 0); // Red
Serial.println("red");
}
(continues on next page)
146 Chapter 1. For Arduino User