Hi,
I don't get what you're doing here. Why are you using PWM? You have to use phase angle control or pulse skipping. If you use phase angle control, you can't use the opto-triac that you used, you have to use a regular opto-triac such as MOC3021.
Why are you using 5kHz? You have to fire the triac with respect to the line frequency (50 Hz or 60 Hz). You have to sense the zero-crossing, and then decide how much time to wait before firing the triac and you repeat this the next cycle.
Assuming you're using an MOC3021 or something similar, when you set PWM duty cycle (the traditional DC-DC controlling PWM) at 20%, the output is high for the first 2ms and low for 8ms. But as soon as the output goes high, the MOC3021 fires the triac, which gets latched (on) until the next zero crossing.
Take any duty cycle and you'll see that the lamp will always light upto full brightness.
What you have to do is, if you need 20% brightness:
Half period is 10ms. So, your output needs to be on for 20% first half, then 20% second half. So, that means 80% off, this 80% is "cut" through phase control. Wait for 80% of the half-time, ie, 8ms and THEN send a high pulse to the MOC for about 100us and then turn the pulse low. Repeat this for the second half as well, and THEN you will get 20% brightness.
Take a look at this:
Phase fired controllers - Wikipedia, the free encyclopedia
Hope this helps.
Tahmid.
---------- Post added at 17:00 ---------- Previous post was at 16:57 ----------
Plus, you really need to use a resistor between the LED and mains. Add a 100k resistor. Add a resistor between the opto-triac output and the triac gate.