Open the Arduino sketch ble-light-with-powertail.ino and read along with the comments to see how your Smart Light Switch code will establish the service:
» Create a peripheral instance using the BLEPeripheral library.
» Create a lightswitch service with UUID of 0×FF10.
» Create the Switch and State characteristics and descriptors.
BLEPeripheral blePeripheral = BLEPeripheral (BLE_REQ, BLE_RDY, BLE_RST);
BLEService lightswitch = BLEService("FF10");
BLECharCharacteristic switchCharacteristic = BLECharCharacteristic("FF11", BLERead | BLEWrite);
BLEDescriptor switchDescriptor = BLEDescrip tor("2901", "Switch");
BLECharCharacteristic stateCharacteristic = BLECharCharacteristic("FF12", BLENotify);
BLEDescriptor stateDescriptor = BLEDescrip tor("2901", "State");
And then configure it:
» Set the Local Name (for generic Bluetooth access) and Device Name (for broadcast in the peripheral’s advertising packet).
» Add your service characteristics and descriptors as Attributes of your peripherals instance.
» Advertise the Bluetooth LE service, and poll for Bluetooth LE messages.
» Set both the switch and state to be on if the button is pushed, off if it’s released.
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT);
blePeripheral.setLocalName("Light Switch");
blePeripheral.setDeviceName("Smart Light Switch");
blePeripheral.setAdvertisedServiceUuid(lightswitch.uuid());
blePeripheral.addAttribute(lightswitch);
blePeripheral.addAttribute(switchCharacteristic);
blePeripheral.addAttribute(switchDescrip tor);
blePeripheral.addAttribute(stateCharacteristic);
blePeripheral.addAttribute(stateDescriptor);
blePeripheral.begin();
Save and upload the sketch to the board. Now you can turn the LED on and off as normal using the button, and if you open the Serial Console you’ll see the string Smart Light Switch appear, with further messages every time you push the button to turn the LED on or off.
In addition, now you can “throw” the switch using Bluetooth LE, because we’ve assigned an event handler to be called when a write command is made on the peripheral:
switchCharacteristic.setEventHandler(BLEWritten, switchCharacteristicWritten);
And at the bottom of the sketch, after the loop( ) function, we’ve added the handler function itself. Now you can control the LED via Bluetooth LE!