It took me some time to solder everything together, but finally I got it working. Bulbs and lamps supplied with 230V are not so easy to dim. You cannot just take PWM signal from uC and simply use it as for DC powered lights. However, there are various ways to accomplish dimming. You can check some other methods online, for instance, the method to relay power from the bulb to some resistor, but still you have to pay for this wasted energy. There is a better way to use only some percentage of energy, the one you need to supply the lights. First, let's check the theory.
The following project deals with 230V which can be dangerous and cause injury or even death. Be smart about it!
In Poland (Europe) we have 230V, 50 Hz mains (if you want to use this in other sources, like 110V or 60 Hz, you will have to adjust some things), that means the signal that goes to our standard bulb looks like this:
To supply less power to our bulb decreases the brightness of the bulb. So, all we need to do is to block some of this sinusoidal energy signal. In result we can get something like this:
If we want to use uC, it is wise to design isolated circuit. There are some open hardware/software solution for this. One of them is presented below:
It works like this: 230V mains goes through the bridge and the sinusoidal signal is all positive (abs(sin(x))). In two moments every one period the signal crosses zero. So, thanks to optocoupler, twice a period we will have rising slope on the zero-crossing pin (Pin_ZEROCROSSING), which is connected to uC. The triac on the bottom in simple words blocks (if you want to better understand how triac works, please check wikipedia or some other source) load – bulb – from the supply … until the triac is fired. So when uC detects the zero-crossing it can wait for some time (it depends how much power we want to provide to the bulb) and then it sets the dimming pin (Pin_DIMMER) for a short time (little over 10 us is sufficient). So from the time when uC fired triac to the next zero -crossing moment, the current will flow from mains to the bulb. The sooner it fires, the more bright the light gets.
Following this analog circuit short explanation, check how I implemented this algorithm into PSoC kit.
There is IRQ from zero-crossing on Pin_ZERO (rising slope), then I start Timer_1 for some time (depends when I want the triac to be fired). When the Timer_1 runs out, the triac is being fired by setting Pin_DIMMER high for 10 us and after that this pin goes low again. And so on and so on.
I stumbled upon a problem with resetting the Timer_1 (I wanted it to run in 'one shot' mode). I had to use Control Register in pulse mode in order to avoid false triggering when slow clock is being used.
This example can be used to dim the 230V bulbs, some LED lights and some other loads like thermal blankets or thermal cables in terrariums.
You can check a photo of this example and I will upload a video shortly.