#include <BLEDevice.h>
const int ledPin = 5; // LED connected to pin 13
const int buttonPin = 4; // Button connected to pin 2
int blinkDelay = 1000; // Initial blink delay (milliseconds)
unsigned long lastDebounceTime = 0; // Last time button was checked
const unsigned long debounceDelay = 50; // Debounce time (milliseconds)
BLEAdvertising *pAdvertising;
const char *names[] = {"Led Control 1", "Led Control 2", "Led Control 3", "Led Control 4"};
int currentNameIndex = 0;
void setup() {
Serial.begin(115200);
Serial.println("Starting BLE advertising...");
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP); // Enable internal pull-up resistor for button
BLEDevice::init(""); // Initialize BLE with a placeholder name
pAdvertising = BLEDevice::getAdvertising();
updateAdvertisementName(); // Set initial name
pAdvertising->start();
}
void loop() {
unsigned long currentMillis = millis();
// Check for button press with debouncing
if (currentMillis - lastDebounceTime >= debounceDelay) {
if (digitalRead(buttonPin) == LOW) {
lastDebounceTime = currentMillis;
// Decrease blink delay (increase frequency)
blinkDelay = blinkDelay > 200 ? blinkDelay - 200 : 200; // Ensure minimum delay of 50ms
}
}
// Blink the LED with the current delay
digitalWrite(ledPin, LOW);
delay(blinkDelay);
digitalWrite(ledPin, HIGH);
delay(blinkDelay);
// BLE name change logic
delay(5000); // Change name every 5 seconds
currentNameIndex = (currentNameIndex + 1) % 4; // Rotate through names
updateAdvertisementName();
}
void updateAdvertisementName() {
const char *newName = names[currentNameIndex];
Serial.println("Setting new name: " + String(newName));
esp_ble_gap_set_device_name(newName); // Set device name
BLEAdvertisementData advData;
advData.setFlags(0x06); // General Discoverable + BR/EDR Not Supported
advData.setName(newName);
pAdvertising->setAdvertisementData(advData);
pAdvertising->start(); // Restart advertising
}