HomeKit Dimmable Lamp

This article will show you how to create a dimmable smart table lamp compatible with the HomeKit system.

Normally I would just buy a dimmable bulb and call it a day, but I couldn't find any dimmable G9 smart bulbs compatible with HomeKit. I also couldn't just use a smart switch because my table lamp has a wireless charger that I wanted to have continuous power. So, I needed to install some smarts inside the lamp itself.

Equipment Needed:

How does AC dimming work?

You're probably familiar with using PWM to dim an LED but since our bulb uses AC power, PWM won't work. AC power comes as a sine wave with a period of 60Hz (US) or 50 Hz (most other countries). PWM would chop up that signal terribly out of phase and the results would be chaotic. A TRIAC AC dimmer module like the one we're using switches power On and Off, similar to PWM, but it includes a handy “zero cross” output that allows us to switch this power On/Off more intelligently. The zero cross point is the point of the AC sine wave where the voltage is zero. The dimmer module sends this signal to the ESP-32 when the phase crosses the zero voltage point.

The zero cross signal runs an interrupt routine that delays some microseconds then turns on the TRIAC output, sending power to the bulb. The TRIAC latches on for the rest of the cycle (until the AC phase hits zero volts again). By changing the delay you can change the amount of power sent to the bulb.

AC sine wave dimming

Tear apart your Lamp

This lamp has a few components in the base:

We'll tap in to the 1 amp power supply to power our ESP-32 from the 5v there. We'll alo rewire the rotary switch from it's prior function (passing 120VAC through to the bulb) to a DC switch that our ESP-32 uses as an input. This will let us manually turn the lamp on and off.

Cut out the felt base with a knife

Wire it up

We'll use 3 GPIO on the ESP-32:

The 120 VAC power from the lamp's plug will feed into the AC dimmer and the 5V PSU.

Wiring schematic

Homespan

Integration with Apple's ecosystem is acommplished with HomeSpan, a library that implements conformance to Apple's HAP (Homekit Accessory Protocol). With just a few lines of code, HomeSpan lets your ESP device talk to other HomeKit-compatible devices and shows up in the Home app on your iPhone. Install HomeKit like you would any other library in the Arduino IDE.

Install the HomeSpan library

The Code

Download the code and start running, or read below for an explanation of what it does.