Instructables
loading
loading
Picture of Arduino controlled light dimmer
dimmer2.jpg
dimmer-print2b.JPG

WARNING: Some people try to build this with an optocoupler with zerocrossing coz 'that is better' right? Some are even told in electronics shops it is better to use such an optocoupler. WRONG. This will only work with a random fire optocoupler: NOT igniting at zerocrossing is the principle of this dimmer.

Switching an AC load with an Arduino is rather simpel: either a mechanical relay or a solid state relay with an optically isolated Triac. (I say Arduino, but if you use an 8051 or PIC16F877A microcontroller, there is stuff for you too here.)

It becomes a bit more tricky if one wants to dim a mains AC lamp with an arduino: just limiting the current through e.g. a transistor is not really possible due to the large power the transistor then will need to dissipate, resulting in much heat and it is also not efficient from an energy use point of view.

Phase cutting
One way of doing it is through phase control with a Triac: the Triac then is fully opened, but only during a part of the sinus AC wave. This is called leading edge cutting.
One could let an Arduino just open the Triac for a number of microseconds, but that has the problem that it is unpredictable during what part of the sinus wave the triac opens and therefore the dimming level is unpredictable. One needs a reference point in the sinus wave.
For that a zero crossing detector is necessary. This is a circuit that tells the Arduino (or another micro controller) when the sinus-wave goes through zero and therefore gives a defined point on that sinus wave.
Opening the Triac after a number of microseconds delay starting from the zero crossing therefore gives a predictable level of dimming.

Pulse Skip Modulation
Another way of doing this is by Pulse Skip Modulation. With PSM, one or more full cycles (sinuswaves) are transferred to the load and then one or more cycles are not. Though effective, it is not a good way to dim lights as there is a chance for flickering. Though it might be tempting, in PSM one should always allow a full sinuswave to be passed to the load, not a half sinus as in that case the load will be fed factually from DC which is not a good thing for most AC loads. The difference between leading edge cutting and PSM is mainly in the software: in both cases one will need a circuit that detects the zero crossing and that can control a triac.

A circuit that can do this is easy to build: The zero crossing is directly derived from the rectified mains AC lines – via an optocoupler of course- and gives a signal every time the wave goes through zero. Because the sine wave first goes through double phased rectification, the zero-crossing signal is given regardless whether the sinus wave goes up through zero or down through zero. This signal then can be used to trigger an interrupt in the Arduino.

It goes without saying that there needs to be a galvanic separation between the Arduino side of things and anything connected to the mains. For those who do not understand 'galvanic separation' it means 'no metal connections' thus ---> opto-couplers. BUT, if you do not understand 'galvanic separation', maybe you should not build this.

The circuit pictured here does just that. The mains 220Volt voltage is led through two 30k resistors to a bridge rectifier that gives a double phased rectified signal to a 4N25 opto-coupler. The LED in this opto-coupler thus goes low with a frequency of 100Hz and the signal on the collector is going high with a frequency of 100Hz, in line with the sinusoid wave on the mains net. The signal of the 4N25 is fed to an interrupt pin in the Arduino (or other microprocessor). The interrupt routine feeds a signal of a specific length to one of the I/O pins. The I/O pin signal goes back to our circuit and opens the LED and a MOC3021, that triggers the Opto-Thyristor briefly. The LED in series with the MOC3021 indicates if there is any current going through the MOC3021. Mind you though that in dimming operation that light will not be very visible because it is very short lasting. Should you chose to use the triac switch for continuous use, the LED will light up clearly.

Mind you that only regular incandescent lamps are truly suitable for dimming. It will work with a halogen lamp as well, but it will shorten the life span of the halogen lamp. It will not work with any cfl lamps, unless they are specifically stated to be suited for a dimmer. The same goes for LED lamps

If you are interested in an AC dimmer such as this but you do not want to try building it yourself, there is a somewhat similar dimmer available at www.inmojo.com, however, that is a 110 Volt 60Hz version (but adaptable for 220 50Hz), that has been out of stock for a while. You will also find a schedule here.

NOTE! It is possible that depending on the LED that is used, the steering signal just does not cut it and you may end up with a lamp that just flickers rather than being smoothly regulated. Replacing the LED with a wire bridge will cure that. The LED is not really necessary. increase the 220 ohm resistor to 470 then


STOP: This circuit is attached to a 110-220 Voltage. Do not build this if you are not confident about what you are doing. Unplug it before coming even close to the PCB. The cooling plate of the Triac is attached to the mains. Do not touch it while in operation. Put it in a proper enclosure/container.

WAIT: Let me just add a stronger warning here: This circuit is safe if it is built and implemented only by people who know what they are doing. If you have no clue or if you are doubting about what you do, chances are you are going to be DEAD!
DO NOT TOUCH WHEN IT IS CONNECTED TO THE GRID

Materials
Zerocrossing
4N25 €0.25 or H11AA1 or IL250, IL251, IL252, LTV814 (see text in the next step)
Resistor 10k €0.10
bridge rectifier 400 Volt €0.30
2x 30 k resistor 1/2 Watt (resistors will probably dissipate 400mW max each €0.30
1 connector €0.20
5.1 Volt zenerdiode (optional)

Lamp driver
LED (Note: you can replace the LED with a wire bridge as the LED may sometimes cause the lamp to flicker rather than to regulate smoothly)
MOC3021 If you chose another type, make sure it has NO zero-crossing detection, I can't stress this enough DO NOT use e.g. a MOC3042
Resistor 220 Ohm €0.10 (I actually used a 330 Ohm and that worked fine)
Resistor 470 Ohm-1k (I ended up using a 560 Ohm and that worked well)
TRIAC TIC206 €1.20 or BR136 €0.50
1 connector €0.20

Other
Piece of PCB 6x3cm
electric wiring

That is about €3 in parts

 
Remove these adsRemove these ads by Signing Up

about the trailing edge dimmer, would you have a schematic should the parts and configuration that would need?

i have tried the TRIAC dimming but am reading how trailing edge would be better for AC-LED light bulbs.

thanks,

stephan

diy_bloke (author)  stephanschulz2 days ago

I am not sure if trailing edge dimmers are better for AC lamps, perhaps, I just dont know for sure. I was working on a trailing edge dimmer, but it required conversion to DC, which is not a problem, but then PWM became another option. Anyway, havent finished it yet, you may want to look here for some ideas:

http://www.ledjournal.com/main/blogs/leading-edge-vs-trailing-edge-dimmers/

quocanh837 days ago

Can i change DB104 = DB107, 4N25 to 4N35?

diy_bloke (author)  quocanh837 days ago

yes you can. the DB107 can take 1000 Volt. that is more than sufficient

nodoubtman14 days ago

/*
AC Light Control
Uses up and down buttons to set levels
makes use of a timer interrupt to set the level of dimming
*/

#include <IRremote.h>
#include <TimerOne.h> // Avaiable from http://www.arduino.cc/playground/Code/Timer1

const int RECV_PIN = 6;

IRrecv irrecv(RECV_PIN);
decode_results results;
unsigned long last = millis();

// Hex code for remote control buttons
#define POWER 0x10EFD827
#define A 0x10EFF807
#define B 0x10EF7887
#define C 0x10EF58A7
#define UP 0x10EFA05F
#define DOWN 0x10EF00FF
#define LEFT 0x10EF10EF
#define RIGHT 0x10EF807F
#define SELECT 0x10EF20DF



volatile int i=0; // Variable to use as a counter of dimming steps. It is volatile since it is passed between interrupts
volatile boolean zero_cross=0; // Flag to indicate we have crossed zero
int AC_pin = 3; // Output to Opto Triac

int dim2 = 0; // led control
int dim = 128; // Dimming level (0-128) 0 = on, 128 = 0ff
int pas = 8; // step for count;
int freqStep = 65; // This is the delay-per-brightness step in microseconds. It allows for 128 steps
// If using 60 Hz grid frequency set this to 65


void setup() { // Begin setup
Serial.begin(9600);
pinMode(AC_pin, OUTPUT); // Set the Triac pin as output

irrecv.enableIRIn(); // Start the IR receiver

attachInterrupt(0, zero_cross_detect, RISING); // Attach an Interupt to Pin 2 (interupt 0) for Zero Cross Detection
Timer1.initialize(freqStep); // Initialize TimerOne library for the freq we need
Timer1.attachInterrupt(dim_check, freqStep); // Go to dim_check procedure every 75 uS (50Hz) or 65 uS (60Hz)
// Use the TimerOne Library to attach an interrupt

}

void zero_cross_detect() {
zero_cross = true; // set flag for dim_check function that a zero cross has occured
i=0; // stepcounter to 0.... as we start a new cycle
digitalWrite(AC_pin, LOW);
}

// Turn on the TRIAC at the appropriate time
// We arrive here every 75 (65) uS
// First check if a flag has been set
// Then check if the counter 'i' has reached the dimming level
// if so.... switch on the TRIAC and reset the counter
void dim_check() {
if(zero_cross == true) {
if(i>=dim) {
digitalWrite(AC_pin, HIGH); // turn on light
i=0; // reset time step counter
zero_cross=false; // reset zero cross detection flag
}
else {
i++; // increment time step counter
}
}
}

void test_dimmer(){
dim+=inc;
if((dim_ac>=128) || (dim_ac<=0))
inc*=-1;
delay(18);
}


void loop() {

if (irrecv.decode(&results))
{

if (results.value == UP){
// If it's been at least 1/4 second since the last
if (millis() - last > 250) {
Serial.print("Dimming up --> ");
Serial.println(dim);
if (dim<127)
{
dim = dim + pas;
if (dim>127){
dim=128;
}
}
}
}

if (results.value == DOWN ){
// If it's been at least 1/4 second since the last
if (millis() - last > 250) {
Serial.print("Dimming down --> ");
Serial.println(dim);

if (dim>5)
{
dim = dim - pas;
if (dim<0){
dim=0;
}
}
}
}
} // loop

there's not dimming at all, IR receiver doesnt work with this code..

Do you think you can help me?

thank you sooo much!

marC:)

diy_bloke (author)  nodoubtman14 days ago

you may have a timer conflict. I am not sure anymore what timer the receive function uses, I thought it was timer2, but not sure.
But I do know the IRremote library to have many problems when timers are used. Check your library and if necessary change the timer

nodoubtman16 days ago

Hi! Nice project. I tried to use IR remote control library to use it. But when i start the program, the lamp is turning on, and i cannot do anything with the remote .

can you help?

thank you!
marC:)

diy_bloke (author)  nodoubtman16 days ago

Hi Marc.
kinda hard to say whjat is wrong as I have no idea what your program looks like. can you dim the lamp without an IR remote, like with the program i provided, so at least it is clear the circuit is OK?
As far as the remote goes, start with printing the dim values to your serial port so at least you know the commands are received.

Thank you for answering diy_bloke, i can send you the program with the ir code, just let me know what is wrong?

Where can i send you my program? at what email address?

thank you so much! :)

marC:)

diy_bloke (author)  nodoubtman15 days ago

just send it in a private message in instructables

yes your program works very well :)

I just want to create and IR dimmer with your program , is it possible?

thank you!

marC:)

Also how would the values be effected for a 120V 60Hz application? Like the 220 Vin resistors and anything else?

diy_bloke (author)  Ian.McElhenny15 days ago

yes, I describe that in the article

What is the purpose of the LED in series with the 220 ohm resistor for the dimmer signal? Is that just for a reference to see if the arduino is sending a signal?

diy_bloke (author)  Ian.McElhenny15 days ago

indeed it is. Ofcourse not much will be visible if you are sending a short signal, but one can use the circuit also to just switch on or off and then the LED has an indicator function. Should be red or green, with blue and white the voltage drop may be too big

Murphi1 month ago

Hi, after reading several times the post I decided to do it, but I have two questions..

-For make the pcb, we must print at paper something like this:

http://img42.imageshack.us/img42/9082/pcb2.gif

But I don´t see in fritzing this option..I select the PCB tab in the soft and I see this:

http://es.tinypic.com/r/2djw0oj/8

If I print, it prints as the second capture, no? What I have to do to see tracks in black ?? Sorry, but it´s first time that I use Fritzing...

-The triac that I have is BTA12-600 BW (12a and up to 800v), and I guess it works fine, right??

Thanks and regards

diy_bloke (author)  Murphi1 month ago

Go to 'File-Export-As Image-pdf'
Then just print that pdf on some glossy paper.
depending on your settings you may get more than 1 pdf: for the coppertracks, for the silkscreen etc. Pick the one that is right. as the ink layer is put on the copper, make sure it is the one that is mirrorred. THAT IS USUALLY NOT THE ONE THAT IS CALLED 'MIRRORRED'
Th epicture you showed is just the component lay-out
BTA12-600 is fine

Ok, thanks for your advice..In fritzing I select "maximum" for width..

I will make the circuit tomorrow and the print monday or tuesday (I don´t have laser printer and the correct paper..)

Thank you for your support and regards.

diy_bloke (author)  Murphi1 month ago

good luck

diy_bloke (author)  Murphi1 month ago

just a final piece of advice: the standard coppertracks in Fritzing are a bit narrow. Make them wider by selecting a larger track width

Where do you connect the zero-crossing pin in arduino
diy_bloke (author)  Tanishq Jaiswal1 month ago

that depends on the interrupt you want to use, but the example program I provided it should be attached to D2

muhammad861 month ago

Hi DIY bloke.Thanks becoz it works and furthermore it works with a LED lamp(the dimmable one).However i realised that the i value should be from i=10 to i=120 for incandescent light. It should not go to i=128 becoz it will ficker at i=128.Somewhere from i=120 to i=125 should be a good point to end. Please correct me if i am wrong.This is what i observed.

diy_bloke (author)  muhammad861 month ago

That is good to hear. You are lucky on the LED lamp as some work and some do no.
With regard to the lowest and higehst values, yes, because the zerocross detection is not an ideal narrow pulse and the period length of the grid may vary, choosing extreme values like <5 or >125 may give some flickering.
If you have time, add a picture in the 'I made it' section. I always like to see how peoples makes turn out

MuratE11 month ago

can you show me links to Arduino?

diy_bloke (author)  MuratE11 month ago

u asked this also in a pm. i replied there

choucsou1 month ago

Hi,

Thanks for this tutorial.

You have two AC wires on input and two "AC" wires on output.

What if we try to deal with one only on each side ? This mean the light will be in serial with the dimmer. And that the zero crossing signal will be read on the "corrected" AC (by the triac).

So the triac and the lamp are in serial and the zero crossing detection is on the triac in parallel.

Do you think it could work ?

Please have a look at

http://www.yokis.fr/domotique-eclairage/variateur-...

You install it in serial with the lamp. The third wire is for command

Regards

diy_bloke (author)  choucsou1 month ago

sure that works. after all it is just a switch.

but.............. the zerocross signal needs to get input from both terminals onthe grid

MuratE11 month ago

can you show me links to Arduino?

MuratE11 month ago

can you show me links to Arduino?

andre66351 month ago

Hello,

What is the maximum load power(W) for the bulb? Would it work with 2 or 3 incandescent bulbs connected in parallel in which all the bulbs would dim at the same time?

diy_bloke (author)  andre66351 month ago

Andre6635
The maximumload depends on the TRIAC. The TIC 206 can handle 4 amps RMS, so if you are using it 2ith 220 Volt, the max load is 880 Watt.
You can put as many incandescent bulbs in parallel as you like, as long as the total load does not exceed 880 Watts.
So 2 or 3 lamps of say 100 Watt is no problem at all

Thanks for the info. I will also add a radiator for the triac just to keep it safe.

Today I started to make holes in the PCB. I was using a 1 mm bit, and it seems large to me. Should I use an 0.8 mm bit? I also have an 0.6 mm one but I think it is too small for some holes. What drill bit sizes have you used? I tried to see in Fritzing the hole size, but I didn't found this option.

diy_bloke (author)  andre66351 month ago

I think I used 0.8

diy_bloke (author)  diy_bloke1 month ago

*2ith=with

muhammad861 month ago

hi the ground is it common ground for the neutral wire and arduino ground?

diy_bloke (author)  muhammad861 month ago

No please never connect those. See my earlier reply

Hi thanks just needed to confirm.I kind of realised it when i saw the neutral wire not being connected to common ground on your diagram.Anyway i found out my MOC3052 is spoilt.I don know why maybe becoz i connected to common ground.

Also i realised that the optotriac and triac is not able to take huge voltages(240V).Is it ok to increase the resistance of the resistor connected to the optotriac(right now u only put 1k)? and is it ok to connect a resistor to the MT2 terminal of the triac, T1(CONNECTED directly to mains supply) .

diy_bloke (author)  muhammad861 month ago

Muhammed, I do not have much experience with the 3052 but it should be able to take 600 volts on its output leads.
The TIC206 should be able to work with a 1k gate resistor. In fact I am using a 560 Ohm resistor.
I am not sure why or where you exactly want to connect the resistor to M2 to. Yes, M2, but leading where?
The circuit as I supplied is proven to work many times so I am not sure why you would want to change it.

Hi thanks just needed to confirm.I kind of realised it when i saw the neutral wire not being connected to common ground on your diagram.Anyway i found out my MOC3052 is spoilt.I don know why maybe becoz i connected to common ground.

Also i realised that the optotriac and triac is not able to take huge voltages(240V).Is it ok to increase the resistance of the resistor connected to the optotriac(right now u only put 1k)? and is it ok to connect a resistor to the MT2 terminal of the triac, T1(CONNECTED directly to mains supply) .

muhammad861 month ago

Oh man my comment also went off.

Hi DIY_bloke,Is the ground from arduino and the neutral wire connected as a common ground or do you SEPARATE them?

diy_bloke (author)  muhammad861 month ago

indeed sometimes I have to press 'make comment' twice. If I dont pay attention, the comment gets lost.

PLEASE NEVER EVER CONNECT THE GROUND FROM ARDUINO TO THE NEUTRAL OF THE GRID.

the optocoplers are there to completely isolate the arduino from the mains voltage.
Please reread everything I wrote in bold as well as what I write about galvanic isolation.

At best you will blow up yr Arduino but at worst you will be toast!!

Hi DiY_Bloke, I made both the circuits according to your given diagrams. zero-crossing works fine and the dimmer input generated by arduino is totally fine. when i fire triac without any delay the bulb is on. But when we fire triac after 1 ms delay the bulb doesnt get on and the output voltage is dropped to zero and all the voltage appears accross triac. So we are only able to fire triac without delay. But when delay of 1 ms or greater is introduced the circuit doesnt work.
Kindly help us!!
we are using BT136 and Moc3021.
the pulse width to triac for latch is set to 600us.
If u say we can also show you output waveforms.
thank you

diy_bloke (author)  Arslan Waheed1 month ago

there is something very wrong with instructables as i replied almost immediately and now i cant see my reply. Anyway, it is a very odd problem you describe.
It kinda makes me nervous that you talk about two circuits that you built, coz it is in reality only one circuit, but i presume you mean the zerocrossing section and the trigger section.
the strange thing is that you should be able to ignite yr triac at practically every moment in the cycle, so also at 1mS after the zero cross.
Which software are u using? Have you tried my program that cycles through a number of levels??

What i like you to try is to disrefard tge zerocrossing for a while and just make the input on the optocoupler high and low a few times randomly, to make sure the triac does ignite at random moments.
Please let me know how that goes and make sure you also try the first program i provided

Harry022 months ago

Hi DiY_Bloke

I have made it work, it is really great I had found this I had made few mod on to the PCB, I add a fuse and separated the two AC input/Output to the PCB sides (so I had to print my PCB using two sides)

I have tested the SW and it also works! :) tested the inmojo sample and also works (I'm based on the UK) but I'm trying to send the dimming value via serial, and I cant make it work, (the Sample III here, did not work either) , do you have any advise as I need to send the dimming value via serial

Thank you

diy_bloke (author)  Harry022 months ago

Well let me start by saying I am happy you made it :-)
It seems to be one of my most popular designs :-)
I always appreciate hearing about builds and if you like, post a picture with the 'I made it' option :-)
Anyway as your module works, your problem must be in the software. In principe you need to send a number to the Serial port that is then read and used as 'dim value'
You say you used Sample III but I presume you mean Sample II. Anyway, now I look at it more diligently (it isnt my code), I wonder how that could work as the 'light' procedure, that checks the serial port, isnt called anywhere.
You need to call that from your 'loop' or even use it as the 'loop'.
Let me know if that works

Harry02 diy_bloke2 months ago

yes, I had tested it too, I had added the light() onto the loop, and it just keep flickering and no actual dimming occurs

I'm a bit confused, as I had tested the same without the loop, as this works as the interruption will call the serial and the light() function is executed, but again I try to add a value via serial and its not taken

int AC_pin = 3;//Pin to OptoTriac

int dim = 0; //Initial brightness level from 0 to 255, change as you like!

void setup() {

Serial.begin(9600);

pinMode(AC_pin, OUTPUT);

attachInterrupt(0, light, FALLING);//When arduino Pin 2 is FALLING from HIGH to LOW, run light procedure!

}

void light() {

if (Serial.available()) {

dim = Serial.read();

if (dim < 1) {

//Turn TRIAC completely OFF if dim is 0

digitalWrite(AC_pin, LOW);

Serial.println ("im low");

}

if (dim > 254) { //Turn TRIAC completely ON if dim is 255

digitalWrite(AC_pin, HIGH);

Serial.println ("im High");

}

}

if (dim > 2 && dim < 254) {

//Dimming part, if dim is not 0 and not 255

delayMicroseconds(75*dim);

digitalWrite(AC_pin, HIGH);

delayMicroseconds(10);

digitalWrite(AC_pin, LOW);

Serial.write (dim);

Serial.println();

}

}

void loop() {

}

ebjorno2 months ago
Are you able to sell me one for £10?
diy_bloke (author)  ebjorno2 months ago

@ebjorno
I haven't really considered that till now, but I have no idea how much it would cost to send it to UK.. Also.. how much in a hurry are you?

ebjorno diy_bloke2 months ago
I'm going to use it to control some lights for a film production. Can you find a price that you're happy with and email me at eivind.bjorno@gmail.com? I'm not in a hurry, but would appreciate if you could send it within a week or so. Thanks!

Little bit confusing on the PCB printed what was up and what down or which pin is actually connected. But with that solver nice work

diy_bloke (author)  ralf.vandenburg2 months ago

I am glad u like it ralf.
With regard to the pin connections: in Step 1 there is a picture with clear indication what is what:

http://cdn.instructables.com/F17/BJ7O/HO7XKD6O/F17...

but maybe it is easy to overlook that one. I am happy though u figured it out.enjoy

oh i forgot to mention that i also liked the detail explaination of the matter you gave well done.

i've encountered a really weird issue only i used the components you descibed and after a few hours of operations time it seems the TRIAC (TIC206 4A ) is leaking current. I've used the diagnostics you're suggested. Also the fritzing file uses a 1Kohm resistor while in the picture 3 (right bellow) on step 1 suggests a 560 Ohms resistor.

(I've build this part 3 times and it happend all 3 times, so I suppose i got something wrong here)

diy_bloke (author)  ralf.vandenburg2 months ago

Hmm With regard to the resistor, I explained that in the text (BOM) one can use a 470Ohm-1k and I ended up using a 560 Ohm.
With regard to your other problem: why you think it is leaking current? Because it will not shut off?
Did you build it on a PCB or on a breadboard?
using for incandescent lamps or other devices?
Did you put any snubbers on it?
I have build it several times and actually never had any problems with it. I have had fresh from the shop faulty Triacs or Thyristors before, but that is really an incident and if it happened with all 3 circuits you built that would be unlikely.
Anyway, let me know and maybe we can find out what the problem is.

I've build it upon a test PCB, used the lamp on the photo attached. The board has the Zero cross detector in the center and the white pieces are the MOC3021. I think the TRIAC is leaking because the octocoupler is still functioning when i put a +5V the lamp is fully on but when off the lamp burns dimmed. Also i've had the demo program working the lamp goes slowly off only after a few hours it wouldn't go off it remains dimmed on.

TRIAC : https://www.conrad.nl/nl/triac-tic206d-to220-400v...

Optocoupler: https://www.conrad.nl/nl/fairchild-semiconductor-1265949.html

Hope you could give any suggestions

WP_20150207_001.jpgWP_20150207_002.jpg
diy_bloke (author)  ralf.vandenburg2 months ago

interesting. I see you use a halogen lamp. In itself that shldnt be a problem.
For now two suggestions:
Make sure yr Arduino is not attached so there is really no input on the optocoupler. Is the lamp then completely OFF or still glowing?
Briefly try with a regulat incandescent bulb
What exactly is te value of the gate resistor you used? it looks like a 470 Ohm
Als je het makkelijker vind om Nederlands te schrijven is dat ook goed

Dat is idd wel makkelijker, De arduino heb ik er idd helemaal af gehaald - Lamp blijft gloeien. Als ik er nu een 1 op zet zie je dat de lamp vol aangaat en bij een nul blijft ie gloeien. eerst had ik idd 470 ohm gebruikt maar bij de twee volgende schakelingen heb ik er twee van 470 gebruikt in serie. Ik ga is opzoek naar een gloeilamp 's kijken of ik nog ergens zo'n ding heb.

diy_bloke (author)  ralf.vandenburg2 months ago

Wat gebeurd er als je de MOC3021 even verwijderd? TRIAC krijgt dan geen gatestroom meer. dat zou moten uitwijzen of het lekken is of toch nog een kleine Gatestroom

diy_bloke (author)  diy_bloke2 months ago

Als je een halogeen lamp gebruikt is die waarschijnlijk zon 35 wat max?. 'Leakage' wil ook nog wele eens optreden bij aan lage load omdat dan de off state leakage groot genoeg is om de load aan te houden. probeer eens met een 60-100 wat gloei;amp

diy_bloke (author)  ralf.vandenburg2 months ago

oh, and thanks for your compliment. I wasn't quite an expert on the matter when i started this so I just shared what I learned.

Hello my friend...no its not working yet..I found the problem..The problem is the triac, current is not passing throught the triac...I am using the BT136... I will try replace the triac with another one...What do you suggest?
diy_bloke (author)  christodoulos.menelaou2 months ago

with 'no current passing through the triac´ you mean from M1 to M2.
That can have various reasons:
-Triac broken
-wrong connection
-Triac not opened by gate
-Nothing gets any current

So I suggest in case you havent done so:
Check all connections
Check if there is a voltage over the triac
Check the voltage on the gate with and without a signal on the Iotocoupler.

If that is all ok, take out the optocoupler and insert a 220 Ohm resistor between the gate resistor and the gate (so a resistor in place of the secunday site of the optocoupler)
If that makes the Triac ignite (i.e. the lamp goes on) the problem is in your optocoupler or primary circuit.

Did you try the tests I suggested earlier?

Ok I umderstand...the mystery is that when i connected the lamp straight without the triac in the circuit lamp gies on(flickering). Plus the circuit I made it with a very experience person who is working in the research departnent of the University of Cyprus. He told ne tha probably the problem is the triac...
diy_bloke (author)  christodoulos.menelaou2 months ago

Well I can only say that if there is NO triac, that mans that yr lamp should only be connected to the grid at ONE side so it should not be able to pass any current.
Look at the circuit and then think away the TRIAC there. There then is just NO connection. A lamp that is connected to the grid only at one side cannot burn.
Have a look at the circuit I attach. Blue line would normally go to the lamp through the triac, but if there is no triac, it cannot go to the lamp. Ergo, there must be a mistake in your circuit.
I am not mitigating yr friend who helped u build the circuit, but even experienced people make mistakes. How can it be your triac if there is a problem when you TAKE OUT the triac.

If you take out the triac and your lamp then is ON, that means that it is somehow connected outside of that TRIAC, which it shouldnt be.
Look at it this way: yr TRIAC is a switch. How can yr lamp suddenly go ON if you remove the entire switch.

Sure you can put in another TRIAC but that is not going to solve your problem.
Your best bet is to again realy check all the connections, or just to rebuild your circuit and then test every step, as I just outlined before

triaclos.jpg
I am also confused...i upload a picture before with the circuit ...I cant see any problem to the connections
diy_bloke (author)  christodoulos.menelaou2 months ago

well from personal experience I know one can be repeatedly blind for ones own mistakes.
Can I suggest the following:
-Start new or take a new breadboard:
-stick in a TRIAC
-Attach the lamp
-connect the gate resistor from the terminal, to the gate
-plug it in
-Lamp should go ON
If that doesnt work, check yr connections and if necessary try a new TRIAC
-Then insert the optocoupler
-connect your gate resistor via the optocoupler
- plug it all in: Lamp should be OFF
- attach 5 Volt via a 560 k resistor to the optocopler
-plug it back in the mains: Lamp should be ON
- remove the 5 Volt from the optocoupler and attach your arduino.
-Let the arduino make the attached pin high and low with say a 1 sec delay: lamp should go on and off
If that all works, you know your output circuit works well
-Then build up yr zerocrossing circuit
If that doesnt work, the problem is in that circuit

I made the tests you mentioned before...Also when I remove the triac the lamp goes on(flickering instead of dimming which is normal). I also use another triac,the same one (BT136) and again the lamp not firing. I will but another type of triac in order to see if it is the model of triac I used the problem... I don't know what alse to do...all seems to work fine instead triac that is not firing...
diy_bloke (author)  christodoulos.menelaou2 months ago

I am kinda confused. WITH the TRIAC inserted the lamp is OFF, but WITHOUT the TRIAC present the lamp goes ON?? When the TRIAC isnt inserted there shouldnt be any closed circuit to the lamp and it should be off as one side shldnt be in touch with the grid.
Aside from that.
You say you did the tests but what was the outcome?

I am posting a better picture of the circuit. The arduino is not connected .. If you could see a problem please mention to be.. Thanks indeed
15 - 17:43.jpg
diy_bloke (author)  christodoulos.menelaou2 months ago

looks OK at first sight, please do the tests as i described and let me know the results.
You can also add the following to your setup and see what the lamp does:

void setup()
{
pinMode(AC_LOAD, OUTPUT); // Set the AC Load as output
for (int i=0; i < 10; i++) {
digitalWrite(AC_LOAD, HIGH); // triac firing
delay(1000);
digitalWrite(AC_LOAD, LOW); // triac Off
delay(1000);
}
}

Ok thanks a lot
diy_bloke (author)  christodoulos.menelaou2 months ago

working now?

This is the circuit
15 - 12:12.jpg
diy_bloke (author)  christodoulos.menelaou2 months ago

it is quite a collection of wires and not easy to follow... but as far as I can see your optocoupler, th eone that needs to trigger the TRiac, doesnt get the required input. See that brown wire? that seems to be only connected at one side... as far as I can see

diy_bloke (author)  diy_bloke2 months ago

though it could be it is connected to the LED, difficult to see

Ok thanks a lot ...the problem seams to be the load part...is it safe to measure the voltsge over the "220" vlamps..?
diy_bloke (author)  christodoulos.menelaou2 months ago

Well if you make sure not to touch anything with yr bare hands, it is safe, The reason I ask you to do this is to make sure that the board is getting 220 Voltage.
But if you think he problem is the load part, please just recheck the connections.
Even if you think it is OK, recheck again. I do not know how many times I was sure I connected something right, only to find several wiring mistakes when I really checked.

I made the circuit. But I have a problem. The LED dim OK but the lamp is always switched off. No flickering no dimming. Can anybody help me with this ?

diy_bloke (author)  christodoulos.menelaou2 months ago

Well that is odd, but here is what I like you to do:
-check and double check all your connections.
-make sure the lamp you are using works
-measure the voltage over the clamps that say "220V" in the circuit. Is that 220 V?
-remove your Arduino and put 5Volt on the entrance of your circuit.
-- both the LED and the Lamp should be full on. If the lamp is NOT on please check the voltage over the 1k resistor, remove the 5V voltage and check the voltage over the 1k resistor again and let me know if that is different.

I cannot stress enough to be careful when measuring when this circuit is connected to the mains voltage BE CAREFULL. This voltage can kill you.

Yes of course I have connected it to the main...I am in cyprus its 220/240 V ,50 hz
diy_bloke (author)  christodoulos.menelaou2 months ago

well then the answer to your earlier question should be clear: you apply 5Volt to the entrance of the circuit, the optocoupler opens, the Triac gets triggered, the lamp gets current and burns.

diy_bloke (author)  diy_bloke2 months ago

anyway, please go through the steps as i described and let me know what the result is

How a 220V lamp could be full on when applying 5 volts?
diy_bloke (author)  christodoulos.menelaou2 months ago

I start to suspect you do not really grasp the workings of this circuit.
Have you connected this circuit to the 220Volt grid at all?

How a 220V lamp will be full pn when applying just 5V ?
andre66353 months ago

Hi, Thank you for your guide.

I was wondering if the phase control would work if I used 50W power resistors like this:

http://www.tme.eu/en/details/ax50wr-1k/50w-wirewou...

Or do I need to change some components in the circuit? I plan to use 3 x 50W power resistors connected in series. Even the incandescent bulbs are 90% heat source so I assume that there are no significant differences between the power resistors and the incandescent bulbs. At home I have 220AC.

Or is it better to use an on/off circuit to control the power resistors? I plan to build a cooker with arduino pro mini + lcd in which I will make fermented food like yoghurt, etc. I hope you can help.

Thanks again!

diy_bloke (author)  andre66353 months ago

Andre: I am not sure if i fully understand you. Do you mean you want to connect the power resistors in place of the lamp? (I presume you do).
Well, yes the phase control is working then as a lamp to this circuit just looks like a resistor.

You could use an OFF/ON circuit, but as it is AC, the dose of power is difficult to regulate as you do not know at what time you are switching if you do not have the zerocrossing.
Having said that.. many thermostatic cookers work with a simple OFF/On circuit and you could decide for that as well, with just a temperature sensor giving feedback. It might be the easiest in your case

Thank you for your answer. Yes, I plan to use the power resistors instead of the lamp.

Indeed, I will use a temperature sensor and then I will try to use the phase control or the OFF/ON circuit to control the power resistors.

I will test the phase control with an incandescent bulb to make sure that I'm doing it right and then I will switch the bulb with the power resistors.

Thanks again.

diy_bloke (author)  andre66353 months ago

the phase control enables you to let the yeaster/bioreactor simmer for a long time on a low temperature. With the on/off you can only send bursts of full power to yr yeaster/bioreactor. That might be OK for your use, especially if you have something to retain heat (i.e. isolated reactor or a heatsink around yr resistors)

diy_bloke (author)  diy_bloke3 months ago

forgot some interpunction that makes a sentence hard to read:
Well, yes: The phase control is working then, as a lamp - to this circuit- just looks like a resistor.

I can't make it work with attachInterrupt()... So, I can use it to switch a lamp ON or OFF using digitalWrite(AC_LOAD, HIGH) or digitalWrite(AC_LOAD, LOW), but when I use interrupt it stop working, i.e. regardless to dimming value, the lamp is always off:

int AC_LOAD = 3;

int dimming = 0;

void setup(){

pinMode(AC_LOAD, OUTPUT); // Set the AC Load as output

attachInterrupt(0, zero_crosss_int, RISING);

}

void zero_crosss_int() {

int dimtime = (65*dimming);

float propTime = 8.33;

delayMicroseconds(dimtime); // Off cycle

digitalWrite(AC_LOAD, HIGH); // triac firing

delayMicroseconds(propTime); // triac On propogation delay

digitalWrite(AC_LOAD, LOW); // triac Off

}

void loop() {

dimming = 64; // Any value does nothing, i.e. lamp is always off

delay(20);

}

I use regular 60W incandescent lamp. Am I doing something wrong? Or may be i did something wrong in pcb?

Photo Dec 27, 16 08 13.jpgPhoto Dec 27, 16 08 46.jpgPhoto Dec 27, 16 09 17.jpg
diy_bloke (author)  robert.tarasov.73 months ago

Robert, I am sorry you are having problems. As many have built it succesfully, and the software is tested... my firts guess is that somehow the arduino might not be piking up the interrupt signal. So there are a few tests you can do:
1 Check your PCB. Is really everything soldered correct ly and connected correctly? Dont think too soon it is OK. I have had veroboard circuits that i was sure I had soldered up correctly, only to find 4-5 mistakes when i really checked.
2 If it is correct, measure with a multimeter. First check if the bridge rectifier is indeed getting a voltage on the primary side and if it is giving off a voltage on the secundary side
3 Then check if your optocoupler gets any voltage. Also test the secundary side of the optocoupler. Though it is true that that only gets a pulse every 10mS, you should be able to measur something there.
4 Check if you made the connection to the proper pin on the arduino.

If that is all ok, write a small routine in the ISR (i.e. the zero cross interrupt routine) that increases a counter on every interrupt and output that counter to the serial port (in your main loop).
That way you can test if any zerocross signal is detected.

Let me know what the outcome is

Thank you very much for your tips! I'm learning now and this is my first "big" pcb :) I will report about results soon.

diy_bloke (author)  robert.tarasov.73 months ago

ok, check the missing connection i mentioned first :-)

diy_bloke (author)  robert.tarasov.73 months ago

I might have found your problem already. It seems that your 4N25 only has one connection on th eprimary side.You have that red wire bridge coming off the '+'... but judging fromth e underside of yr pcb that isnt connected to anything

if i want to use this for control 3 lighting load which can dim 3 level and 3 load can dim different level in the same time and 3 load can work in the same time.

example have level 1 2 3 and load A is level 1 load B is 3 and load C is 2 .

please recommend me, what i should to do????

diy_bloke (author)  ซันซันแ4 months ago

ซันซันแ, I temporarily suspended facebook but i will look into yr recent question.

merry xmas

diy_bloke (author)  ซันซันแ4 months ago

it is possible to use this for 3 loads that you regulate independently.
Say you have an RGB setup, what you need to do is maintain 3 level variables (that are basically time delays). You then need to count from the zero crossing till the shortest delay, fire the necessary TRIAC, count further till the next delay, fire that Triac etc.
Mind you though that the processor will spend a lot of time just waiting.
When you dim one lamp, it is possible to use a delay or use a timer, as the examples show, but if you have 3 lamps, you just do not have timers enough, so you have to use delays.
Just to make sure: you would ofcourse only need ONE zerocrossing circuit, but three Triacs that you can fire

thank you so much

if you have some example code please can you give it for me

diy_bloke (author)  ซันซันแ4 months ago

I know I started some but I am not sure if i still can find it. Will look, but dont wait for that

TomazS4 months ago

Deardiy_bloke,

first let me thank you for sharing. Superb project! I managed to assemble the circuit, however I cannot find a way to make dimming time dependant. Let us say, I want to have 100% output for 20 minutes, then 80% for 30 minutes. Somehow it does not work with if statments:

if (millis()<60000){

dimming=20;}

....

With for loop it works fine, so it must be the code...

Regards,T

diy_bloke (author)  TomazS4 months ago

I am not sure what your code exactly looks like, but you cannot just check for a number of millis()asthey just keep on running. Try the following:
put the following lines in your initialisation (so at the beginning of yr code, not in the setup):

long previousMillis = 0;
long interval = 60000;

Then in your loop:

unsigned long currentMillis = millis();

if(currentMillis - previousMillis > interval) {

dimming=20;

------------------------------------

another possibility is to have an interrupt generated that sets a minute counter. Then just keep track of the counter.
How you can do that I describe in an article here:

https://arduinodiy.wordpress.com/2012/02/28/timer-...

check for the "Arduino timer CTC interrupt example"

TomazS diy_bloke4 months ago

Thank you for the answer. I don not really understand. The millis() in if statment works fine with my PID algorithm, when I change Setpoint accordingly. I will try your code and see.

diy_bloke (author)  TomazS4 months ago

ThomasZ as i do not know your code it is hard to say.
I recently had some unexpected effects in using Millis() after i changed the code in an aspect that shouldnt really affect the millis() but it did.
Anyway, I hope it works :-)

diy_bloke (author)  TomazS4 months ago

just let me add (just to make sure) that in millis, 60000= 60 sec = 1 min so in yr code you have to keep track of that

PrinsNathan6 months ago
Hi, diybloke! When I tried your code with this circuit today it didn't work, when I ran a simple analog write to the input pin it did, but it wasn't in sync of course so it faded. I think there might me a problem with my zero cross signal. I don't have a scope so I can't check that, should I replace my 4N27 or try and borrow a scope?
diy_bloke (author)  PrinsNathan6 months ago

sorry to hear you had a problem. as it seems your output works well, and provided you have made no mistakes in the program, it mist be the input signal.
before u buy a new optocoupler, I advise the following: measure the voltage over the input of the optocoupler. Does it get any voltage at all?
if so measure the voltage over the output, oventough it should pulsate at 100 Hz, you should be able to get a reading. If so, measure the voltage over the interrupt pin.
Are you sure all the connections are OK?
If that all fails get a new optocoupler

Hmmm I do get readings, some nearly non existent and some around 500mv.. But it does work now for some reason! If I use the code with the timer library it works but not with the other code. And it seems to work better on interupt 4 than 0.... Do you know why that might be? And lastly, is it possible to run multiple dimmers with different values at the same time? Thanks so much!
diy_bloke (author)  PrinsNathan6 months ago

I am glad you got it working. I do not know why the one code didnt and the other does, unless u are trying to have the arduino do something else in the mean time as well, then the timer is a better option. Also the interrupts should not make a difference. I take it u are using an Arduino Mega?
yes you can run different dimmers at the same time with different values. Currently busy with an RGB (=3 channel) dimmer

My apologies for the late response! I made my 'final' version! I used the photoresist technique to make a PCB, my first stab at custom PCB's and it was awesome. Now I'll add a cheap chinese Arduino pro mini, bluetooth connectivity, and a potentiometer and put it in a nice case... So I can change the value on my phone and manually! Thanks for the fritzing files btw :)

IMG_20141106_232909[1].jpgIMG_20141106_232850[1].jpgIMG-20141106-WA0006[1].jpeg
zapro PrinsNathan4 months ago

Hi. You should scrape off the "perimeter" track with a knife - otherwise not much insulation between primary and secondary as you see.

diy_bloke (author)  PrinsNathan5 months ago

looks great, thanks for sharing.
Chinese Arduino pro mini's are unbelievably cheap right now. I got them for 1.58 euro a piece.

ahmedmahrous6 months ago

can i use tic106 instead of tic206 ??

diy_bloke (author)  ahmedmahrous6 months ago

no the TIC106 is a thyristor, not a triac

What about BTA16
diy_bloke (author)  ahmedmahrous6 months ago

yes can use

Please tell me triac number that I can use it instead of tic206
diy_bloke (author)  ahmedmahrous6 months ago

i already did, below, i advised BT(A)136. BTA16 also good

AbuW6 months ago

hi, this board can work with raspberry pi? can show the connection for raspberry pi? thanks.

20141008011105.jpg
diy_bloke (author)  AbuW6 months ago

yes it can work with Raspberry PI
All you need is an interrupt Pin and and an output pin. You are free to chose those.
The old kernell in the raspberry didnt have interrupts I think but the new one has.
I like yr picture

AbuW diy_bloke6 months ago

thanks for the comment, can you guide which pin to use as interrupt and output pin? in raspberry pi GPIO 18 is PWM. thanks.

diy_bloke (author)  AbuW6 months ago

I know I answered this question but the answer seems to have not logged.
u are sort of free to chose but pin22 is often used for interrupts. for the output pin u do not need pwm, just a pin that can switch on and off

AbuW diy_bloke6 months ago

so, that means, gpio22 is the dimmer signal in right? and i will use gpio23 as zc signal out? which coding to run the dimmer program? care to explain it. thanks.

images.jpg
diy_bloke (author)  AbuW6 months ago

made a start with a program for raspberry, but dont have time right now to finish and test it, but this may help you along:

#!/usr/bin/env python

import time
import RPi.GPIO as GPIO


# handle the ZC event
def ZC_EventHandler (pin):
print "handling ZC event"
# set dimming in your main routine
time.sleep(dimming)

# turn the TRIAC
GPIO.output(25,True)



# main function
def main():

# tell the GPIO module that we want to use
# the chip's pin numbering scheme
GPIO.setmode(GPIO.BCM)

# setup pin 23 as an input
# and set up pins 24 and 25 as outputs
GPIO.setup(23,GPIO.IN)
GPIO.setup(24,GPIO.OUT)


# tell the GPIO library to look out for an
# event on pin 23 and deal with it by calling
# the buttonEventHandler function
GPIO.add_event_detect(23,GPIO.RISING)
GPIO.add_event_callback(23,ZC_EventHandler,100)

#

# set your timing variable here


GPIO.cleanup()



if __name__=="__main__":
main()

diy_bloke (author)  AbuW6 months ago

let me just add that the raspberry might be tricky to use for this as i understand the timing isnt always that easy to control.

diy_bloke (author)  AbuW6 months ago

I am not sure what you mean with Zero crossing out, but I presume you mean the signal to drive the Triac.. I think i may choose pin 18 for that but 23 is also ok.
Unfortunately i do not have time to write a program for every microcontroller that people want to port this to but you may find some help here:

http://www.adafruit.com/blog/2013/03/22/how-to-use...

the only thing that you would need to do in yr code is to wait for the zerocrossing signal, wait a desired time and fire the triac.
good luck :-)

ahmedmahrous6 months ago

please i cant find TIC206 in the stores ,, what can i use instead of it ??

diy_bloke (author)  ahmedmahrous6 months ago

oddly my replies seem to not register unless I post twice. I answered this but it has disappeared.
Anyway, if u cant find a TIC 206 basically every TRIAC that is suitable for your local voltage is OK. try a BT136

didin.ok made it!6 months ago

Thanks diy_bloke. This work with the last code !

IMG_4816_800x533.JPG
diy_bloke (author)  didin.ok6 months ago

great. your setup looks good. thanks for sharing

Fr3dy made it!6 months ago

I really needed this circuit for a project.. fortunately you posted it here.. it works flawlessly with the last code.. thank you very much!!

photo 1.JPGphoto 2.JPG
diy_bloke (author)  Fr3dy6 months ago

I am happy you liked it Fr3dy. Always enjoy seeing pics showing what others made of it :-)

ksun47 months ago

hey guys! i really need help. the circuit and program code doesnt work with a 220volts AC DIMMABLE LED BULB. i really dont know what to do about it. it works perfectly with ordinary bulbs but i need to let it work with LED bulb for my project. please help me. my defend is in a week. please! please please!

diy_bloke (author)  ksun47 months ago

Hmmm seems my earlier reply didn’t store. It is however largely the same as my mail to you

ksun47 months ago

hey guys! i really need help. the circuit and program code doesnt work with a 220volts AC DIMMABLE LED BULB. i really dont know what to do about it. it works perfectly with ordinary bulbs but i need to let it work with LED bulb for my project. please help me. my defend is in a week. please! please please!

diy_bloke (author)  ksun47 months ago

you also may find this article interesting:

http://www.digikey.com/en/articles/techzone/2011/j...

All in all I am not sure what your procet needs to adhere to, but if DC is an option I would go for that

diy_bloke (author)  ksun47 months ago

See my earlier reply and my mail to you. Just let me add that pulse skip modulation works well in say motors and though it works well in incandescent lamps, it is not the best method for incandescent lamps coz of a possibility of flickering.
How that will be on LED's I am not sure.. they may flicker too at low output.

yet, if u are bound to using LED's, I would always consider using DC steering as you then can do away with the entire zerocross detection and use pwm instead

Knakworst8 months ago

Hi everybody,

I am building an Arduino terrarium climate controller and I've some problems with the TRIAC dimmer.

Maybe I have overlooked the solution in the comments but I have not found a solution yet. I built the analog board and tested it with several different software solutions, all went well until I integrated it into my own software.
In the software several temperature sensors are checked in the terrarium, during those checks the lamp flickers slightly. When I change the firing calculated value for 50Hz from 75 to 60 it looks ok but only for one dimming value if I want to dim more or want to have more light the problem occurs again.

Does this sound familiar to someone? I hope somebody can help.

thanks Rob

diy_bloke (author)  Knakworst8 months ago
there are a number of possibilities.
which sensors are you using? can you post the code you are using?

Thanks for your response.

Since this is an addition to an already running climate control unit I created a test setup with a onewire DS18B20 temperature sensor. Below you see the code I created for the test setup. I basically took your code and modified it a bit. When I comment out the call to the temperature sensor all goes well, but with the call the light starts flickering.

#include <OneWire.h>

#include <DallasTemperature.h>

float tempMeasured = 0;

int AC_LOAD = 3; // Output to Opto Triac pin

int dimming = 115; // Dimming level (0-128) 0 = ON, 128 = OFF

// Data wire of the OneWire is plugged into pin 10 on the Arduino

#define ONE_WIRE_BUS 10

// Setup a oneWire instance to communicate with any OneWire devices

// (not just Maxim/Dallas temperature ICs)

OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.

DallasTemperature sensors(&oneWire);

void setup()

{

Serial.begin(9600);

pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output

attachInterrupt(0, zero_crosss_int, RISING); // Choose the zero cross interrupt # from the table above

}

//the interrupt function must take no parameters and return nothing

void zero_crosss_int() //function to be fired at the zero crossing to dim the light

{

// Firing angle calculation : 1 full 50Hz wave =1/50=20ms

// Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle)

// For 60Hz => 8.33ms (10.000/120)

// 10ms=10000us

// (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65

int dimtime = (60*dimming); // For 60Hz =>65

delayMicroseconds(dimtime); // Wait till firing the TRIAC

digitalWrite(AC_LOAD, HIGH); // Fire the TRIAC

delayMicroseconds(10); // triac On propogation delay (for 60Hz use 8.33)

digitalWrite(AC_LOAD, LOW); // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC

}

void loop() {

tempMeasured = temperatureSensor1();

if (tempMeasured > 26){

dimming = 75;

delay(20);

}

}

void getSensorData(){

// call sensors.requestTemperatures() to issue a global temperature

// request to all devices on the bus

sensors.requestTemperatures();

delay(2000);

}

float temperatureSensor1(){

// Basking sensor (blue wire)

getSensorData();

float tempS1 = sensors.getTempCByIndex(0);

delay(2000);

return (tempS1);

}

diy_bloke (author)  Knakworst8 months ago

Thanks for yr posting.

Let me begin by saying that the code I gave only serves as an example and it is not the most optimal code as it spends most of its time waiting. Your problem is akin to what commenter МихаилК describes below.

As I understand the onewire and Ds18b20 library can cause some problems with interrupts... at least, that is what various people have reported.
Other than that there is a timing problem because of what I mentioned at the beginning.
The time that you have to let the processor do everything you want is a half cycle=10mSecs. (at 50 Hz)
if you have your dimming level set at 115, that means that you are in a waiting loop for 8.9mS and have 1.1 mS left to do something.
Add to that that a reading of the DS18b20 can take up to 50mSec or more and you see the problem.
Sure, interrupts are made for that, to interrupt the processor for the Interrupt service routine, but as said,,, the OneWire library seems to screw up interrupts (see here). In the OneWire.cpp file you will find the following description for a modification that was made:
"Disable interrupts during timing critical sections
(this solves many random communication errors)"
Further studying of the cpp file shows that regularly the interrupts are disabled for over 50 uSec and sometimes even for more than 500uSec
I would start with using the other code that I describe in my ibble, that uses a timer interrupt to keep track of the dim time, rather than a waiting loop. That might already take care of yr problem to some extent. but probably not completely

Another thing to consider is to change the flow of your code: now you read your temperature sensor continuously. I understand that as it is the easiest, but in a terrarium the temperature probably will not become critical within a second, or a minute, or 5 minutes so you could decide to not read your sensor continuously but say every 5 minutes, at least you would not have the problem continuously.

You could also opt for another sensor(if that is practical). One that doesn’t take much time to read, possibly even an ntc if that is accurate enough for yr purpose.

You could take the interrupt disable out of the .cpp file

You could take a more drastic solution and let the DS18B20 be read by say an Attiny 13/45/85, that then sends that to yr arduino, either as a treshhold, or as complete temp info.

If you have further questions, please do not hesitate to ask

ok, thanks. I have already tried the other code and with same result, so no Onewire, everything OK, but with the Onewire the flickering occurs again. Replacing the Onewire is not an option, at least not anymore. Disable the interrupt sounds interesting in combination with altering the temperature sample rate. I am going to try that and see what happens.

Thanks for the info.

Rob

diy_bloke (author)  Knakworst8 months ago

Rob
If you consider to maybe read yr sensors say every 10 secs, remember that you can use the built-in ISRs to extend timer
functionality. For example, if you wanted to read a sensor every 10
seconds, there’s no timer setup that can go this long without
overflowing. However, you can use the ISR to increment a counter
variable in your program once per second, then read the sensor when the
variable hits 10. The ISR would look something like this:

ISR(TIMER1_COMPA_vect)

{

seconds++;

if(seconds == 10)

{

seconds = 0;

readSensor();

}

}

For a variable to be modified within an ISR, it must be declared as volatile. In this case, you need to declare volatile byte seconds; or similar at the start of the program.

For full description, check here:

http://arduinodiy.wordpress.com/2012/02/28/timer-interrupts/

diy_bloke (author)  diy_bloke8 months ago

If your system happens to have an RTC, say the DS1307, it would be worth considering to use the sqw to trigger an interrupt every second and use that in an interrupt routine to count to say 5 or 10 secs.
You would need to set the RTC SQW to 1 sec, which you do with:

void sqw1() // set to 1Hz
{
Wire.beginTransmission(DS1307_I2C_ADDRESS);
Wire.write(0x07); // move pointer to SQW address
Wire.write(0x10); // sends 0x10 (hex) 00010000 (binary)
Wire.endTransmission();
}

both options are a possibility. I have to look at the pros and cons and figure out which option works best with the current code. But definitly good suggestions, thanks.

Rob

mcwareg Knakworst8 months ago

H, I solved this taking out the delay from the ISR, you could do:

volatile byte ZCD=0;

void zero_crosss_int()

{

ZCD=1;

}

void loop() {

dim_func();

tempMeasured = temperatureSensor1();

if (tempMeasured > 26){

dimming = 75;

delay(20);

}

}

dim_func()

{

// Firing angle calculation : 1 full 50Hz wave =1/50=20ms

// Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle)

// For 60Hz => 8.33ms (10.000/120)

// 10ms=10000us

// (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65

int dimtime = (60*dimming); // For 60Hz =>65

delayMicroseconds(dimtime); // Wait till firing the TRIAC

digitalWrite(AC_LOAD, HIGH); // Fire the TRIAC

delayMicroseconds(10); // triac On propogation delay (for 60Hz use 8.33)

digitalWrite(AC_LOAD, LOW); // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC

}

Remarks:

- This would free the ISR system.

- This would only work if the main_loop < 8.3 ms

If I were you:

after detect the zero_crosss_int() I would only start a timer (for example timer 1) for the dimtime, and in the ISR(of the timer), turn on, delay 10 us and off exit (fast, no wait).

My problem was to wait INSIDE the ISR.

Actually works like a charm, I can dim and I can use comm libs, (serial, Wire, ISP,etc) at any speed without any problems, also external interrupts.

Hope it helps.

Regards

mcwareg mcwareg8 months ago

Sorry, inside:

dim_func()

{

if(ZCD==1)

{

all code

}

}

Knakworst mcwareg8 months ago

thanks for your input. I've decided to create a master-slave configuration with an ATtiny85. The fact is I don't have 1 sensor but 4 in the terrarium, also for future extensions I think that is the safest way to go.

Rob

diy_bloke (author)  Knakworst8 months ago

good luck. wld like to get some feedback later how you did :-) tnx

OK, no luck so far :(

diy_bloke (author)  Knakworst8 months ago

OK thanks. did you try mcwareg's suggestion as well?

thank you)

xLQAmEM2MHo.jpg
diy_bloke (author)  МихаилК8 months ago

Looks very nice. thanks for showing. I always like seeing what other people eventually made

How can I use this scheme and IR Control?

diy_bloke (author)  МихаилК9 months ago

not difficult at all. include the IR library (from Ken Shirriff, include an IR diode and make the value of the 'dimming' variable change by e.g. pressing the up and down buttons on your remote

diy_bloke (author)  МихаилК9 months ago

Have given it some more thought in the mean time and i will post the same answer here as I have done on the stackexchange website:

It seems that the jaydeep might have been building my circuit and used the provided code: http://www.instructables.com/id/Arduino-controlled-light-dimmer-The-circuit/step4/Arduino-controlled-light-dimmer-The-software/
so obviously this problem has my interest.
With regard to the 'dimming' variable, that will not go beyond 128 so I might as well have used 'byte' to define it.
The IR remote library is I presume that of Ken Shirrif and that one uses the Timer2 interrupt. In principle, combining those two interrupts shouldnt necessarily cause a problem as I have done so as well (in using the timer interrupt rather than 'delay to trigger the TRIAC).
But in that case the entire timer interrupt was handled within the period of the mains wavelength (100 or 83 ms depending on frequency).

I don’t think the access to the 'dimming' variable -as jfpoilpret mentions- is the problem (though he makes some sound remarks), as that will just remain as is for a specific light level.

The problem -as is also suggested above- might well be in the fact that the IR receive takes too long.

So... disregarding interrupt priority for a moment, if the code is hanging around in the timer interrupt routine and there is a zerocrossing, that won't be detected, or, if the code is just doing a zero crossing detection, the timer is screwed up.

In comes interrupt priority: The external interrupt has the highest priority (other than reset). So.. when the IR receive routine is busy in the Timer service routine and a zerocrossing arrives, it will be taken out of that routine, zerocrossing will be handled and ideally, it should continue with the timer routine again.
However, your remote has no idea what is going on in the Arduino and some of the code sent will be missed.

all of this shouldn’t need to be a problem if the external interrupt was fast, but as most of the waiting is actually done within this interrupt, it could take up to almost 10mS/8.3mS (when 'dimming' approaches 128).

Solution?
Well, I can't say much about the Timer2 interrupts in Ken's library, But on 'my side' of the software, what could be done is to shorten the external interrupt by removing the delays and use (yet another) timer interrupt.
Ken uses Timer2, so this would have to be timer1.
So, whenever there is a zerocross, there is no waiting in a delay, but it will be handled by timer1
An example is given in [Step 6 of my instructable][1]. There is no guarantee this will work but there is a good chance

Let me just point out that the basic program I supplied was just given as an example, It uses much computer time in waiting and therefore isn’t the best to combine with other actions of the processor.


[1]: http://www.instructables.com/id/Arduino-controlled-light-dimmer-The-circuit/step6/Arduino-controlled-light-dimmer-The-software-III/

HI, ttp://www.instructables.com/id/Arduino-controlled-light-dimmer-The-circuit/step6/Arduino-controlled-light-dimmer-The-software-III/

this code to work fine =) but again trouble ((((this code is not a fan dimmer 220V, although the previous version Horchow deal with it, vchem could be the problem?

diy_bloke (author)  МихаилК8 months ago

i am not sure what you mean.
you mean the code woks with the IR receiver?
what does the fandimmer have todo with it

who is Horchow? what is vchem?

With this code http://www.instructables.com/id/Arduino-controlled-light-dimmer-The-circuit/step6/Arduino-controlled-light-dimmer-The-software-III/ can not control the fan on 220V, what could be the problem?

I have tried to do so, but unfortunately IR takes a lot of garbage in the end nothing works. ((((When I disable dimmeer from Arduino, debris present.

diy_bloke (author)  МихаилК9 months ago

Hmm as I haven't tried this myself it is hard to give a reply. The link you refer to gives some possible solutions/workarounds. Have you tried those?
The IR library uses the timer interrupt which in itself shldnt be a problem as I have combined that too with the interrupt in the dimmer program.
whether the slowness of the IR receiver is the culprit remains to be seen as that is what interrupts are for.
I wonder though how the problem presents itself to you: is it the receiving of the IR codes or the setting of the dimmer variable?
The 'debris' you talk about.. I presume that i sserial output you are looking at. What exactly is it you are sending to the serial monitor and that is 'debris'?

If you haven’t done already, try to send the following variables to the serial monitor:
-dimtime
-dimming
-the received IR code
and let me know what is hapening
Then disable the ISR in the dimmer program and send the same to the serial monitor and let me know what's happening

guttih made it!10 months ago

Thanks diy_bloke

https://www.youtube.com/watch?v=9NCnCmaYa_s

virkar1.JPG
diy_bloke (author)  guttih10 months ago

takk fyrir athugasemdir. Það lítur vel út

rathodmanoj10 months ago

Hi,

Many thanks for writing this article and explaining the functionality in simple steps yet providing all information.

I plan to use this in controlling the ceiling fan.

I plan to put the PCB in some kind of ABS plastic enclosure and fix it inside the switch board panel so that it is not visible to end user.

I have few queries.Does the TRIAC warm up and require ventilation or some kind of cooling? Is there a requirement of a Heat Sink?

Also if we do require a Heat Sink, can I connect multiple TRIACs in parallel (space constraints)?

Thanks,

Manoj.

diy_bloke (author)  rathodmanoj10 months ago

Thanks rathodmanoj
the heating up of the TRIAC is largely depend on the load it needs to drive. But if you tend to use it to regulate a fan of any considerable size I would add a heatsink
It is possible to mount various TRIAC's on one heatsink as long as you keep a few things in mind: With the TIC 206 the metal housing is connected to M2. If you therefore put several TIC206 TRIACs on one heatsink, they are all connected at M2.
That doesnt need to be a problem as long as the circuit allows for that.
In my circuit M2 is connected to the Mains, not to the load. That means that indeed, various TRIACS can be mounted on 1 plate.
However, if you use other TRIACS you have to make very sure that that is the case for them too.
Some airvents in the enclosure is a good idea.
If u use the TRIAC to drive a fan, it is best to add a snubber network as described in my article

diy_bloke (author)  diy_bloke10 months ago

Also, if you plan on mounting more than 1 Triac on 1 heatsink, make sure you dont make any mistakes in the wiring. Connect the wire from the mains to M2 only once.. they will be electrically connected throught the heatsink, or, if you have doubts on that.. connect them with a wire via the screws that mount them on the plate.

That way you avoid mixing up the 2 wires from the mains and get the best fireworks ever in yr ABS plastic case :-)

john23511 months ago

is this the same as pulse skipping modulation?

diy_bloke (author)  john23511 months ago

Let me add that PSM is in this case just a matter of software. The circuit here can be used for PSM. PSM however is not so suitable for incandescent lamps because of the inherent flickering.

Should you wish to use this circuit for PSM, then what you have to do is count the number of zerocrossings the cycle should be on and count the number of zerocrossings the cycle shld be off. So if you want to have a duty cycle of 50%, the software needs to switch on the triac at the first zerocrossing, kept open another after the 2nd zerocrossing, but switch off at the third zerocrossing, kept off at the 4th zerocrossing, until the 5th zerocrossing, when it should be switched on again.
The resulting output voltage is equal to:
Vrms x sqrt n
in which n is the duty cycle.
At a 50% duty cycle the output voltage thus is:
220 * sqrt 0.5 = 220 * 0.7 = 154 Volt
In determining the dutycycle, one should be careful to always send an even number of half cycles in order to avoid a dc component that could harm e.g. a motor.
a dutycycle of 50% therefure is done by conducting an entire cycle and stopping an entire cycle, not by conducting half a cycle and blocking the other half

Hi,

I completed my TRIAC switching circuit and am back with few more queries for you. :)

Thanks for great and crystal clear explanation about PSM. I also understood your point about TRIAC firing angles. What I am really not sure about is the efficiency about this circuit in controlling fan speed (inductive load). I have read at several place that speed control using phase control method creates some harmonics in the power line which makes the motor turn hot and similar stuff. If that is the case what would you suggest ? PSM or Phase control ? Which one should be used say in case of controlling a ceiling fan ?

Just want to know that can I use this circuit to control an inductive load like I mentioned a ceiling fan. I certainly will incorporate my FAVORITE Snubber circuits :). And to control it properly what is that I need to keep in mind. Any suggestion would be highly appreciated.

Thanks,

Abhishek.

diy_bloke (author)  egrabhishek11 months ago

I am not entirely shure abt the efficacy but I guess both methods may not differ that much in efficacy. I would guess though that the phase control would make for a better torque at low speeds.
You can use this circuit for a ceiling fan. I am surprised you havent tried it yet :-).
PSM or Pulse Skip Modulation, is sometimes also called cycle skip modulation. it does produce less rfi than phase cutting.
I am not sure if it has more harmonic interference.
You can always give bot methods a try and see what works best. The circuit can handle both as it is all in the software

Hi,

I have a small idea. Just need your thoughts on the same.

I understand the importance of ZC detector and its use. However, I am a bit worried about putting 30K - 1/2 watt resistor with direct AC. I understand it will work and its already tested. However I have a small idea.

I am anyways using a 6v/12v AC step down transformer. I intend to take my A.C signal from that and fed it to 4n25/4n35 OC. Since transformer is an inductive load there will be issues with phase shifting and due to this the zero crossing will also shift a bit. It might happen earlier or a bit later which will result in appropriate trigerring.

What I plan to do is to get the first zero cross detection. See the deviation on my scope and then accordingly adjust the delay for first time and then create 20 ms delays from there.

To tune my circuit, assume my first time the zero crossing happens 2 ms after the actual time due to the presence of the transformer.

Now I will see this on scope and then adjust the next zero crossing event to happen after 18 ms and then subsequent will happen after every 20 ms (1/50 = 20 ms ). I wont be taking the zero crossing event from OC anymore it will happen just for the first time to get a hold of it.

Let me know your thoughts on it.

The idea is to make firing more accurate and use a bit more of isolation.

Regards,

Abhishek.

diy_bloke (author)  egrabhishek11 months ago

Abishek, as a matter of fact if you scroll through the replies to
someone called 'Peter'(about a year ago), you will see that I already
gave that as a possibility :-)
I actually have tried it myself and
didn’t get that many problems with a phase shift, but I didn't put a
scope to it. I am no expert on AC but I had the impression there is no phase shift between a HV and LV side of a transformer, depending of course how you would connect the secundary side, meaning that there is either a 0 or a 180 degree shift.
Would
be interesting to see your results though.
I understand from your question that you want to sync only once with the zerocrossing signal and afterwards just use timing.
I would advise against that: the mains frequency may show slight variations and you would need to keep track of a lot of time.There is a problem though:
If there indeed is a phase delay (and I dont think so) then you would notice the zerocrossing a few micro or miliseconds late, i.e. AFTER the actual zerocrossing.
If you are on 50Hz you only have 10mSec to do all you need to do with the TRIAC. Obviously, if you would have a say 2 mSec delay in your phasing, you would not be able to ignite the TRIAC at the ZC anymore and thus would be unable to regulate to full power.
If you would say: "Yes, I know I am 2mS behind, I know that my next REAL ZC is actually 8mS AFTER I measured mine, So from that point on I will just use a timer to predict or guess my REAL ZC", you will run into some potential problems: There might be small variations in the grid frequency, that add up, and you would have to keep track of a lot of timing.

Again, I dont think there is a phase shift, but if there is I would advise to still have the measured ZC trigger a say 8mS timer (if the delay indeed would be 2mS) every cycle.

You talk about 20mS delays but remember that if you use a double phase rectification you will have a 100Hz signal=10mS

Still, I think there won't be a delay, but would be interested in your results

voeding2.JPG
diy_bloke (author)  diy_bloke11 months ago

you also may want to read this article:

http://opensourcemeter.com/CTtheory.html

Hi thanks for your input.

I tried detecting zero cross with a 12 vac transformer.

In the attached images,

Red signal = ZC via transformer with the same circuit as in this post. (Slight change here. Instead of 30K resistor as you have suggested, I am using 33K + 33K). This gives the higher time period signal (2nd image).

First image with red signal with comparatively lower time period is after I removed one 33k resitor so now there exists only one of it.

Yellow Signal = ZC via circuit suggested in this post.

I m not able to make any sense out of this. Also why does the ZC singal time period reduced after removing one 33k resistor ?

Kindly let me your thoughts .

I am not sure whether ZC is happening before or after actual zero crossing.

Please suggest.

Red_12_33K_0K.jpgRed_12_33K_33K.jpg
diy_bloke (author)  egrabhishek11 months ago

Those are very interesting pics Abishek.
regarding the first picture, I take it yr base is 25mSec? I presume that you have no capacitors on that secundary side of the transformer, just simply a bridge and an optocoupler.
The slight shift in time probably has all to do with the quality of your transformer. I am no expert on this, but have been reading up yesterday and this was one of the things that was suggested. Actually, if you look at the picture, there isn’t much difference between the start of the pulses, it is just that the secundary side has a wider peak that comes a bit later.
If your interrupt is set to be at the rising edge, this might well be possible to use.

regarding your second pic, that is actually not so surprising when you think of it. Now just to make sure I understand you correct: The 2nd pic is with 2x 33k and the first one is with 1x33k right?
That means that in the first picture the optocoupler will get all in all more current throughout the cycle and therefore is in saturation most of the time. Only when the wave comes very close to zero, the current wont be big enough anymore to open the transistor and the voltage on the collector will quickly rise till it peaks and quickly drop again when the wave is through its zero crossing because it soon will give enough voltage again to send the optocoupler in saturation, thanks to the smaller resistance.
In the 2nd picture where the resistance is much higher, relatively far before the actual zerocrossing the wave voltage is already low enough to prevent the optocoupler remain in saturation (coz of the higher resistance, and once it is through the zerocrossing, the voltage needs to rise higher (= further in the cycle) in order to saturate the optocoupler again.
What it teaches me is that maybe I should lower the resistance in my circuit.

It could well be that by tinkering a bit with the resistors on yr secundary side, you could move the rising flank a bit earlier.

Very very interesting graphs. I am very happy with them. Thanks

Hi Buddy,

Thanks for your wonderful feedback. You are absolutely right in all your understanding.

My base is 2.5 mSec (As you can see the ZC is ocurring after every 4 blocks / 10 mSec).

There is no smoothing capacitor and the one with smaller time period is 1 X 33k and the bigger time period is 2 X 33k.

One more thing, I do not think you need to decrease the resistance in your circuit. I decreased because I was working with 12VAC.

Also tell me one more thing. My resistances get a bit hot. Should I increase them to a bit more value say 100 K (1/2 watt). But I think that will make them dissipate more energy as heat. What do you say ?

Also I can make use of these ZC that I am getting but to make it more accurate I need to compare it against actual signal and see how much deviation is there from the waveform. I am not feeling confident although I know it will work. What do you say ?

I have a scope : OWON PDS5022T.

Here's the link to the manual:

http://akizukidenshi.com/download/ds/owon/PDS%20Se...

Sorry for bothering you much but in case you have some time to spare, please let me know if I can see the AC waveform on it. Although I do not think so.

What I want to achieve is see the actual waveform and zero crossing and the ZC event that I am getting and sync them together.

I feel after adding some heavy resistances (100k x 4) I can add my probe to the stepped down AC voltage and that should give me the actual voltage waveform.

Please know your thoughts. I intend to test it now.

And I am based at India. (Frequency: 50Hz / 240 VAC)

diy_bloke (author)  egrabhishek11 months ago

Don't worry Anishek, you are not bothering me. Somehow I already figured you were somewhere in India :-)
You can increase the resistors and they will not dissipate more heat, but less. After all P=I²xR but if R goes up, I goes down.
In order to synchronise you need one channel of yr scope on the 240 and one channel on yr secondary site. However, you can only do that if you have completely seperated channels, so not with a common earth and I am not sure if yr scope has that. But ofcourse you can always measure the waveform if you add resistors, maybe even without as yr maximum input voltage is 300 Volt, but I am sure there is a range you need to set with a knob or something. Take into account though that yr iinput impedance is 1 Mohm so even with 1MOhm resistors you will only have halved the signal

Thanks for your time buddy.

Well I do not want to mess up my new scope with A.C.:-).There is so much of complexity involved I feel.

However, to verify the zero crossing detector efficiency I am going to compare the ZC spikes against the actual zero cross point in time, but not with A.C voltage. Rather than using A.C, I will rectify it and make it DC certainly with no smoothing capacitor. I thing the zero crossing point in A.C will certainly be in phase with the zero touching point of D.C. If this works then I will try to see how much is the deviation in case of ZC circuit with transformer.

Let me know your thoughts.

diy_bloke (author)  egrabhishek11 months ago

That seems the best solution. The ZC is just as visible in a rectified (but not smoothed) wave.
I suggest you experiment a bit with the resistor I presume you are using to feed yr OC from the secundary side

Hi.

I will try to see if the ZC points matches the actual DC zero touching points I am not clear about what should I try with the resistors value ?

Currently I am getting around < 50 volts as rectified DC. I think I can see that wave form directly on the scope. Any comments ?

Also I will try this first your circuit with 220 v as input and rectified DC as output and then with 12 v AC as input.

diy_bloke (author)  egrabhishek11 months ago

I meant that it is best to choose the resistance such that u have a narrow peak

Hi,

I compared the rectified dc zero touching points and the circuit's ZC detection signals against time. The one without transformer is quite accurate as compared to the one with the transformer. I think its better to stay away from the transformer for now. However, I have 2 small queries here:

1. With transformer why does zero crossing occur before actual zero crossing.

2. I am using 2 watt resistor instead of 1/2 watt since I have to run the system 24 X 7. Even they get a bit hot. Should I try increasing the value a bit to reduce power dissipation but in that case the ZC curve will get a bit extended. What do you suggest ?

-Abhishek.

1_No_Trans.jpg2_No_Trans.jpg3_No_Trans.jpg4_No_Trans.jpg5_Trans.jpg6_Trans.jpg
diy_bloke (author)  egrabhishek11 months ago

Abishek, before i can answer yr first question i would need to get a bit more info on yr graphs because I am not entirely sure what I see there/

with regard to yr second question, I would keep the resistance as it is. are you now using 2x33k? then 2 watt should be definitely enough.
If power consumption is a problem, there are some zerocrossing detectors that supposedly use minimal power

Yeah those are 2 X 33 K resistors , 2 watt each.

Can you give me an idea how much power will get wasted if I got your way with 2 x 33K resistors ?

Sorry for not providing enuf for graph

The yellow waveform is rectifier output and the red one is ZC out.

The last 2 pics are with transformer in place and there u see some lag. Others are without transformer.

diy_bloke (author)  egrabhishek11 months ago

well then is seems that when using the transformer your resistors are too high in value, so the optocoupler is already closing at a low voltage.
The dissipated power with 240V 2x33k will be U²/R=240*240/66.000=870mW. There are ways of getting this down, e.g. by using a more sensitive optocoupler and increase your resistors. You may want to experiment with the 6N138

diy_bloke (author)  egrabhishek11 months ago

well then is seems that when using the transformer your resistors are too high in value, so the optocoupler is already closing at a low voltage.
The dissipated power with 240V 2x33k will be U²/R=240*240/66.000=870mW. There are ways of getting this down, e.g. by using a more sensitive optocoupler and increase your resistors. You may want to experiment with the 6N138

Yeah. 20 ms was a typo. It should be corrected. Thanks for pointing that out.

I will see what I get on the Scope. Will post my results soon.

diy_bloke (author)  john23511 months ago

no, Not really. In PSM aTriac will connect a number of cycles but disconnect another number of cycles. What happens here however is phase control in each cycle

john235 diy_bloke11 months ago

Thanks for the explanation .

What I'm trying to do right now is right in the picture below

I want the lamp to act light a camera flash

can you help me regarding the code for arduino & if possible

can you also show me on how to do it using mikroC

10322687_10202740587730323_7482639038477746324_n.jpg
diy_bloke (author)  john23511 months ago

I am not sure what acting like a camera flash relates to the picture below.
With a camera flash there is a short burst of high intensity. This circuit is really not suitable for that. The maximum output is if the Triac is open during the entire cycle, so you would need to switch between 0 and 128 to basvally make the lamp go on and off again

john235 diy_bloke11 months ago

This is the output waveform of camera flash. How to code so that I can achieve the output waveform like this?

Untitled.png
diy_bloke (author)  john23511 months ago

I really think you are going the wrong way here, and you wouldn't even need this circuit for what you want to do, but in code you need to fully open the lamp (dimming=0) and then shut it off (dimming =128)

john235 diy_bloke11 months ago

What should i change on the code?..sorry for asking because i'm still new in electronic

int AC_LOAD = 3; // Output to Opto Triac pin

int dimming = 128; // Dimming level (0-128) 0 = ON, 128 = OFF

void setup()

{

pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output

attachInterrupt(0, zero_crosss_int, RISING); // Choose the zero cross interrupt # from the table above

}

//the interrupt function must take no parameters and return nothing

void zero_crosss_int() //function to be fired at the zero crossing to dim the light

{

// Firing angle calculation : 1 full 50Hz wave =1/50=20ms

// Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle)

// For 60Hz => 8.33ms (10.000/120)

// 10ms=10000us

// (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65

int dimtime = (75*dimming); // For 60Hz =>65

delayMicroseconds(dimtime); // Wait till firing the TRIAC

digitalWrite(AC_LOAD, HIGH); // Fire the TRIAC

delayMicroseconds(10); // triac On propogation delay (for 60Hz use 8.33)

digitalWrite(AC_LOAD, LOW); // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC

}

void loop() {

for (int i=5; i <= 128; i++){

dimming=i;

delay(10);

}

}

diy_bloke (author)  john23511 months ago

Mattard, I am not sure how much clearer i can tell you: you have to switch between on and off which is dimming 0 and 128

change the void loop() into
void loop() {
dimming =0;

delay(5);

dimming=128;

delay(500);

}
But you really do not need a circuit like this for it. You dont even need the zero cross detection because all you do is switch a lamp on and off

diy_bloke (author)  diy_bloke11 months ago

John, I hope I have not sounded brief in my reply. If so that was not my intention. Please feel free to ask as much as you want

john235 diy_bloke11 months ago

Thanks mate. But I want to adjust the input like i don't want it to rise in full power but start it in low then sudden rise in full then dim it slowly . Anyway thanks for your help. Really appreciate it

diy_bloke (author)  john23511 months ago

In that case, decrease 'dimming' from 128 till desired level, then bring it to 0 and then slowly increase up again.

for (int i=128; i >= 75; i--){

dimming=i;

delay(10);

}

dimming=0;

for (int i=5; i <= 128; i++){

dimming=i;

delay(10);

}

john235 diy_bloke11 months ago

The high intensity i will make it by connecting the lamp parallel with another 9 lamps. But i don't have the idea on how to code it so that it will act like a camera flash. It does not necessary to act 100% like camera flash but as long as it is almost like one. thanks

john23511 months ago

I already tried this code
& the lamp is continuously on
what are you suggesting to make it function like the one when using arduino?

diy_bloke (author)  john23511 months ago

John, Ias I have no PIC system and no expert on PIC's, I gave the code as a start but I have no way of testing it.
The code with the example 'dimming=20' just sends ONE value to the lamp and that is an 'almost fully on' value so it is understandable if yr lamp is on.

Try the following: Change 'int dimming=20; ' into 'int dimming=120;'
Is your lamp almost off then? then everything is functioning OK.

What you need to do is to get a value from whatever program you are writing and using that for the value 'dimming'

As I do not know what it is that you want to do, I can only point you in a general direction: Suppose you want a variable resistor to determine the level, then you read the value off yr variable resistor through an analogue port, map that value to 128 and use that as 'dimming'

if you just want to have your light level go up and down then make a for next loop in which you vary the value of 'dimming'

john23511 months ago

Hi. I tried to used pic16f873

for this dimming using mikroC

but the result was the lamp is flickering

Can you please check this code for me
& if you know how to repair it can you please show the correction for me.

thanks mate

unsigned char FlagReg;

sbit ZC at FlagReg.B0;

int steps=128;

int flashtime;

int pause;

int i;

void interrupt(){

flashtime = (75*steps);

pause = flashtime;

Vdelay_ms(pause/1000);

PORTC.B0=1;

delay_us(10);

PORTC.B0=0;

if (INTCON.INTF){ //INTF flag raised, so external interrupt occured

ZC = 1;

INTCON.INTF = 0;

}

}

void main() {

PORTB = 0;

TRISB = 0x01; //RB0 utk external interrupt

PORTC = 0;

TRISC = 0; //PORTC semua output

OPTION_REG.INTEDG = 0; //interrupt on falling edge

INTCON.INTF = 0; //clear interrupt flag

INTCON.INTE = 1; //enable external interrupt

INTCON.GIE = 1; //enable global interrupt

while (1){

if (ZC){ //zero crossing occurred

for(i=5; i<=128;i++){

steps=i;

delay_us(10);}

}

}

}

iamdebjyoti made it!12 months ago

I have successfully build the circuit and it works fine. I want to see the waveform in an oscilloscope, but having some doubts. Can you please help.

IMG_0724.jpg
diy_bloke (author)  iamdebjyoti12 months ago

looks great iamdebjyoti :-)
which waveform you want to see? The one on the load? that is just a matter of attaching yr scope. What doubts do you have?

Yup, the one on the load. But since it is directly connected to the 220V mains, should I use a voltage divider or an isolation transformer. Another doubt which I'm having is that where should I connect the ground probe of the oscilloscope because connecting the ground probe to neutral will create some problem.

diy_bloke (author)  iamdebjyoti12 months ago

well what you want to measure is the waveform over the Load so that is where you connect both of yr probes.
Wether to use a voltage divider depends on your scope. I would think it has a range selector for the expected input. An isolation transformer is always safe, but it would be an inductive load and may influence the timing of yr signal.

john2351 year ago

Hi. Can you explain to me

how did you know on what is the resistor value

that need to be used. Thanks!

diy_bloke (author)  john23512 months ago

what resistor do you mean?

john235 diy_bloke12 months ago

all of the resistor value. tq

diy_bloke (author)  john23512 months ago

by calculating or knowing what current was needed john235

msyazwan312 months ago

This also function like a camera flash right?

diy_bloke (author)  msyazwan312 months ago

no it doesn't msyazwan, though you can use incandescent light for photography, this circuit has nothing to do with flash light

mattard11 year ago

hi, thanks for all this info it was very helpful bit i have a problem. i was checking out the your 8051 program and i have an error on this part ``int dimtime=(75*dimming);`` saying dimming is undefined identifier. would you mind helping me. thanks a lot

diy_bloke (author)  mattard11 year ago

mattard, I was under the impression i replied, but seems I have not.
your error is caused by the fact that you have not declared the variable dimming
The code snippet I gave was not a full working program, just a partial code. you need to declare all variables used

Thanks for replying Diy .i just starting learning how to use c++ so im still green at it. I did as you said but im have an error because of delayMicroseconds. this is the program:

#include<T89C51AC2.h>

int dimming;

int i ;

void ex0_isr (void) interrupt 0

{

int dimtime=(75*dimming);

delayMicroseconds(dimtime);

P0=0xFF; // sets entire PORT 0 high, can also use e.g. P0_1 =1 ;

delayMicroseconds(10); //propogationdelay

P0=0x00;

}

void msdelay(unsigned int value){

unsigned int x,y;

for(x=0;x<value;x++)

for(y=0;y<1275;y++);

}

/*===================================================*/

void main (void)

{

/*———————————————–

Configure INT0 (external interrupt 0) to generate

an interrupt on the falling-edge of /INT0 (P3.2).

Enable the EX0 interrupt and then enable the

global interrupt flag.

———————————————–*/

IT0 = 1; // Configure interrupt 0 for falling edge on /INT0 (P3.2)

EX0 = 1; // Enable EX0 Interrupt

EA = 1; // Enable Global Interrupt Flag

P0 = 0x00; //all pin of PORT0 declared as output

/*———————————————–

Wait forever.

———————————————–*/

while (1)

{

for(i=5;i<128;i++){

dimming=i;

msdelay(10);

}

}

diy_bloke (author)  mattard11 year ago

and what exactly is your error message?

external.c(11): warning C206: 'delayMicroseconds': missing function-prototype

external.c(11): error C267: 'delayMicroseconds': requires ANSI-style prototype

diy_bloke (author)  mattard11 year ago

As far as I know C (I am no expert) 'delayMicroseconds' is a function and needs to be declared as well, e.g. by:
void delayMicroseconds (unsignedchar);

but again I am no expert on C, havent used it for years, but the error you mention points to an undeclared function

diy_bloke (author)  diy_bloke1 year ago

sorry, I mean "(unsigned char); " ofcourse, but it probably needs to be : "(unsigned int); "

All without the quotes ofcourse

Thanks for replying Diy .i just starting learning how to use c++ so im still green at it. I did as you said but im have an error because of delayMicroseconds. this is the program:

#include<T89C51AC2.h>

int dimming;

int i ;

void ex0_isr (void) interrupt 0

{

int dimtime=(75*dimming);

delayMicroseconds(dimtime);

P0=0xFF; // sets entire PORT 0 high, can also use e.g. P0_1 =1 ;

delayMicroseconds(10); //propogationdelay

P0=0x00;

}

void msdelay(unsigned int value){

unsigned int x,y;

for(x=0;x<value;x++)

for(y=0;y<1275;y++);

}

/*===================================================*/

void main (void)

{

/*———————————————–

Configure INT0 (external interrupt 0) to generate

an interrupt on the falling-edge of /INT0 (P3.2).

Enable the EX0 interrupt and then enable the

global interrupt flag.

———————————————–*/

IT0 = 1; // Configure interrupt 0 for falling edge on /INT0 (P3.2)

EX0 = 1; // Enable EX0 Interrupt

EA = 1; // Enable Global Interrupt Flag

P0 = 0x00; //all pin of PORT0 declared as output

/*———————————————–

Wait forever.

———————————————–*/

while (1)

{

for(i=5;i<128;i++){

dimming=i;

msdelay(10);

}

}

diy_bloke (author)  mattard11 year ago

mattard, I was under the impression i replied, but seems I have not.
your error is caused by the fact that you have not declared the variable dimming
The code snippet I gave was not a full working program, just a partial code. you need to declare all variables used

john2351 year ago

Does it work if I put some kind of button to control the intensity

if I achieve the intensity i want then i let it flash

can you please help me with this. thanks!

diy_bloke (author)  john2351 year ago

check my reply above

diy_bloke (author)  john2351 year ago

check my reply above

john2351 year ago

Hi.

Can you help me with the coding

of how to control the intensity of light, set it to desire intensity
& then let it flash

i want to use it for my home. Thanks!

btw, can i use this circuit but not with arduino
like for example use with microcontroller pic16f** somethings

without using the one in step 9

diy_bloke (author)  john2351 year ago

John, of course you can use it with a pic. in principle can use it with any microcontroller.
the coding for what you want is rather simple. set the value for the variable 'dimming' to the value for the intensity you want and then switch between that value and the value of 128 or 127. put a delay in between that determines the rate of flashing. If you want to use it with a pic microcontroller, it is not much use that i write it out for the arduino, but the principle is the same for any microcontroller

Does it work if I put some kind of button to control the intensity

if I achieve the intensity i want then i let it flash

diy_bloke (author)  john2351 year ago

Sure. that is just a matter of software.
There are several ways to do it. You could use a variable resistor that you read via an analogue port.
Now the easiest way is to map the reading of that port to a value for the dimtime, but since you want it to flash, you need some extra programming, you need to know if your variable resistor is actually moving to its desired light level, or that it already has reached that. So you need to compare the value read by your analogue port with the previous value so you know your knob is on the move or not.
If the value is the same for say half a second, you switch between that value and say 127 to let it flash.
You could do the same with push buttons, but you would need two push buttons (up and down) sure, you could do it with one push button, but that would take some extra programming.

so, i can use it with pic microcontroller without using the one in step 9 right?

thanks again!

diy_bloke (author)  john2351 year ago

yes. what i described in step 9 is just a link to a pic project

Scipione1 year ago

Hello,

I'm a filmmaker (in high school I realized the impossible with PICs xD but now I'm a bit rusty with electronics xD ), and for an indie movie I need to control up to six lights using the PC (with Arduino). For an unrgent scene, wich we will shoot in 2 weeks maximum, we need at least to control 2 lights (1KW each...).

Since my future use will be 6 channels, with up to 2.5KW for each channel, I would like to improve this design for high load and modular upgradeability.

For a load up to 2.5 KW (I will use 2 KW maximum, but I want to overbuild for safety), I need to change the optocoupler and TRIAC (and also to oversize the copper traces). What to use?

Carlo

diy_bloke (author)  Scipione1 year ago

For a load of 2.5kW you need 11.4 amps. so that is what yr Triac needs to be able to endure, so BT138-600 with a BT139-600 you would have 16 amperes while it si only a dime more expensive.
Obviously you need some serious cooling on that TRIAC.
No need for a different optocoupler.
You may want to lower the 1k resistor to a 330 ohm resistor and add a gate resistor as well, according to this circuit (only look at the triac circuit, no need for the MOC3041)
If you really want to handle 12 amps. I am not sure what oversized traces you would need, but what I do in cases like that is to either solder a copper core thick enough onto the coppertrace really directly from the component to the connector itself.
Since you will need some adequate cooling of the TRIAC, I can imagine you will mount them directly on a cooling plate and use 12 amp capable wire to connect the terminal leads to Load and Mains and use regular wire to connect to the trigger and zerocrossing.
For 12 amps you would need I guess 2.5 mm diameter wire which is AWG 11

diy_bloke (author)  diy_bloke1 year ago

sorry, part of a sentence got lost:

so a BT138-600 would give you 12 Amperes, but with a BT139-600 you would have 16 amperes while it is only a dime more expensive.

Thank you. For the copper traces there are calculations to do. I don't rememer the formula, however recently I found this useful tool:

http://www.desmith.net/NMdS/Electronics/TraceWidth...

Today after work I will check datasheet and A.N.'s of T138-600 and T139-600.

Then I will do a post aout that with reference to your work and advices on:

http://indiemotionpictures.blogspot.it/

and when the project is finished I will also do an instructales and release every file; everything will e CC-BY-NC . I don't know what kind of license did you choosed for your project, please tell me if that is ok for you.

Thanks!

diy_bloke (author)  Scipione1 year ago

Tnx Scipione. I know the calculations tool but then i always have to figure out how thick the copper is. I rather just solder a piece of wire on top of it. Saves space as well.

reference to my work is always appreciated. I am ok with yr licence. I dont feel i have been doing any trailblazing work on this circuit, other than making a workable project/ibble of it.

Good luck with yr movie

hello Bloke,

tnx again. Today I will go to the electronics spare shop and I hope to find the T139-600; then I will build one zero-crossing circuit and two dimmers. Then I will play. xD I will figure out how to handle the heat on the triacs however, I will choose the appropriate heatsink

diy_bloke (author)  Scipione1 year ago

It is a BT 139. not a T139

yes yes I know, however today I was too late to go to the shop :(

msyazwan31 year ago

Hi

Can I control the intensity of light & then let it flash
Would you guide me or give me some suggestions on how to do it..

thank you

diy_bloke (author)  msyazwan31 year ago

yes of course. You can just set the desired intensity with the variable 'dimmer' and then change it between that intensity and 128 (which is 'off')

john2351 year ago

Thanks for your help

I really2 appreciate it. If i could meet you in person

i would glad to treat you a lunch

my project already went well
thanks again :D

diy_bloke (author)  john2351 year ago

Thanks John, so I presume the connection to the MOC was the problem :-)
I appreciate the offer, but I am sure you are at the other end of the globe somewhere, so I will take a rain check on that one.
Take care

john2351 year ago

I just found out that if i connect the feet 1 & 2 of the triac

the lamp will start to turn on

but it doesn't flash like it suppose to

what do you think about this?
tq

diy_bloke (author)  john2351 year ago

well that is why I advised to put a resistor between pin 4 and 6 of the IC foot.
and of course it doesn’t flash because you give a continuous trigger signal by connecting the gate with one of the terminal leads.
Anyway, it shows your TRIAC is probably functioning OK. So the suspicion falls on your MOC3021.
Please do the following:
double check the connections to that MOC3021. Are you sure you had inserted it the right way around?
If you are convinced the connections are OK, insert a new MOC3021 because yours is most likely broken.
Please check the resistor that gives the MOC its input from the arduino. hard to see which one you used but since you left out the LED I would suggest a 470-560 ohm resistor.
After you replace the MOC (make sure it goes in the right way)
apply a 5 Volt input voltage again (via the resistor) and see what happens

"well that is why I advised to put a resistor between pin 4 and 6 of the IC foot.

and of course it doesn’t flash because you give a continuous trigger signal by connecting the gate with one of the terminal leads."

which IC, both the 4n25 and 3021?
btw, while testing this, i should not connect it with arduino right?

diy_bloke (author)  john2351 year ago

only the MOC. we were only testing the TRIAC function for now. But you no longer need to do it i guess as you connected pin 1 and 2 which is the gate and a terminal. Tht is what I wanted you to test albeit through a resistor.
Anyway, go fortht as I said in my previous message as most likely your MOC is faulty. check all the connections and make sure you inserted the moc the right way

I already did as you suggest

& the lamp is on..so, what do you think?

btw, the optocoupler i'm using is this one

10245432_10202560697353176_7586304768954098155_n.jpg

I also test the optocoupler, if i applied 5v between foot 1 & 3
there exist voltage between them.

How to check whether my optocoupler is still good or damage?

diy_bloke (author)  john2351 year ago

the optocoupler isnt really tested by measuring the voltage on pin 1 and 3. that only makes sure that it is receiving a voltage.
What you need to do to test the optocoupler is to measure if the AC voltage over the secundary site of the optocoupler drops when you apply a 5 Volt signal to the circuit. For this you need to hook up yr meter to pin 4 & 6 and plug in your circuit. then apply 5 volt to the entrance and see if the voltage drops.

Now you mentioned something else that found intriguing. You said you measured a voltage over pin 1 and 3 .

Hmm that gives me an uneasy feeling as the MOC3021 needs a voltage over pin 1 and 2 NOT 1 and 3.
I suggest you check first if you have your MOC3021 connected correctly

moc3021.jpeg
diy_bloke (author)  john2351 year ago

John, I know the lamp is on, that is why i tell you the triac is most likely fine and you need to replace your MOC3021. Is that what you mean by 'I already did as you suggested'?
that sounds a bit odd coz the lamp cant be on just by putting in a new MOC as you also need a trigger signnal for that.
So, can you confirm that you replaced the MOC? are you sure it is the right way around?
The picture doesnt tell me much because I cannot see from the outside if it is working.

But just to reiterate:
there can be 3 things wrong in your circuit:

1-the wiring.. but you checked that several times
2- the triac, but when you connect the gate to 1 of the terminals, yr lamp goes on, so yr triac is probably OK

3. leaves the MOC3021, so i sugegst you replace that, OR, measure the voltage over it on the secundary site when you send a trigger signal

john2351 year ago

My circuit totally fail

The lamp in not even on

Can you please tell me what are may be the cause that it did not work

I did some of your suggestion on step 10

unattached the circuit from arduino

I already test with multimeter that
there are no connection between the arduino part & main 230V part...

when 230V is apply, there exist voltage on the 230V part

but the lamp is still not on

diy_bloke (author)  john2351 year ago

Always a bad feeling when you build something and it just doesnt do anything. However, there are only a few components in the circuit so it shouldnt be too hard to find out. So let's go about this systematically.
First we will check the function of the TRIAC circuit. Please do the following:

1) disconnect from the mains and put the Arduino away, you wont need that for now
2) Check your circuit. Is really everything connected as it should be?
3) take your 5 Volt PSU and connect it to the Ground and to the Plus to the connection 'Dimmer signal in'
4) measure if there is a voltage over Pin 1 and 2 of your MOC3021
5) leave the 5Volt applied and connect your circuit to the mains.
6) check if your lamp is burning and let me know
If it isnt and you are sure the connections are correct and your lamp is ok Then the problem must be with your optocoupler or with the triac.
Let me know and then i can help you further

Yup..i already test step 4

there exist 5v on pin 1 & pin 2

lamp is still not on after i connected it with main

btw,
tq for your response. really appreciate that

i also test for continuity & it seems like there is short circuit

between the lamp output
is it suppose to be that way?

1514624_10202554798525709_8093668262450601085_n.jpg
diy_bloke (author)  john2351 year ago

well no it is not supposed to be that way. if the lamp is shortcircuited ofcourse it will never go on.
Please check if you really wired it right and if there are no shortcircuits between the copper traces on your board.
If it was short circuited, there is a fair chance you destroyed your triac as well.
No thanks necessary, it sucks when something doesnt work and if i can help I gladly do so

I tried unconnect the lamp from the board

& check the continuity again at the board, this time no shortcircuit

then i checked the continuity directly with the lamp & there exist shortcircuit

but if i connect the lamp directly to supply the lamp is on

it's really confusing.

p/s: sorry for asking lots of questions

diy_bloke (author)  john2351 year ago

well are you sure it is a shortcut? lamps have in general a low resistance. a 220 Volt 100 wat lamp is about 490 Ohm.

Well if u are sure the connections are all ok do the following: remove the optocoupler and stick a 470 Ohm (or something close) in the pins 4 and 6 of your circuit. dont add any 5 Volt, just the resistor and plug it into the mains

john2351 year ago

Hi

Can you explain more about the coding please

You said that you used pin 2

but in the coding, you declare pin 3
" In the program pin 2 is chosen

*/

int AC_LOAD = 3; // Output to Opto Triac pin "

..

i'm using arduino uno

can you help me regarding this connection with the software(coding) from arduino to the board. like from pin 2 arduino to num 3 on the board..here i attach the circuit that i build it

1513182_10202550862227304_3206919043635761337_n.jpg
diy_bloke (author)  john2351 year ago

Hi John
there are 2 connections with the arduino: the zerocrossing signal (an input to the arduino) and the Triac triggering signal (an outout from the arduino)
the zerocrossing is fed to pin 2 (i.e. interrupt 0) and the triggering for the Triac is taken from D3

Perhaps this picture can help you a bit:

http://www.pighixxx.com/pgdev/Temp/Arduino_uno_Pin...

As I am not sure what exactly the numbers in your photo are I presume the following
1=Vcc
2=zerocrossing
3-Triactriggering
4=0Volt

so what you do is to connect '1' to any 5Volt pin on yr arduino. You connect '2' (the zerocrossing) with interrupt 0 which is Pin 2 on your Arduino. You connect '3' to 'Pin 3' on your arduino and you connect '4' to any Ground pin.

when i say 'Pin 2' and 'Pin 3' I mean the pins that are literally called pin 2 and 3. They are next to the Rx (pin 0) and the Tx (Pin 1). Logically they are referred to as D2 and D3.
I hope the schematic below will clarify any doubts left

dimmer-ard-connection.jpg

hy i have build this whole setup problem is when i use simple increasing or decreasing loop of dimming in program it works fine but when i set a fix value of dimming level it do not work well, it just starts flickring. i want to control the dimming level with two input buttons please help me.

diy_bloke (author)  deependra.kushwah951 year ago

hi deependra, sorry to hear that. Can you send me the code you are using?

int AC_LOAD = 4; // Output to Opto Triac pin

int dimming = 128; // Dimming level (0-128) 0 = ON, 128 = OFF

void setup()

{

pinMode(AC_LOAD, OUTPUT); // Set the AC Load as output

attachInterrupt(0, zero_crosss_int, RISING); // Choose the zero cross interrupt # from the table above

}

void zero_crosss_int() // function to be fired at the zero crossing to dim the light

{

// Firing angle calculation :: 50Hz-> 10ms (1/2 Cycle)

// (10000us - 10us) / 128 = 75 (Approx)

int dimtime = (75*dimming);

delayMicroseconds(dimtime); // Off cycle

digitalWrite(AC_LOAD, HIGH); // triac firing

delayMicroseconds(10); // triac On propogation delay

digitalWrite(AC_LOAD, LOW); // triac Off

}

void loop()

{

dimming = 75;

}

diy_bloke (author)  deependra.kushwah951 year ago

I am a bit surprised that it should flickr. What I would like you to try is to add a slight delay after the 'dimming=75;'

e.g.

{
dimming = 75;
delay(200);

}

and see how that works

It shldnt make much difference theoretically, but one never knows.
I will try a fixed setting myself as well this weekend.

Also. how is your PSU? Sometimes a PSU is a bit 'dirty', leading to extra triggering of your interrupt routine

Once we get this sorted out I will help you with the buttons if you wish

ok i will check this too and post result. and about the power supply i am using sony mobile adopter which provide 5.1v output but if you have doubt on that i will change that too, and then post the result. thanks for the help

diy_bloke (author)  deependra.kushwah951 year ago

well th esony mobile adaptor is there to charge batteries. That means that the output doesnt really need to be a 'clean' DC and maybe the output smoothing capacitor is a bit small, leaving some peaks that maybe sometimes could trigger the interrupt. Nevertheless, the delay seemed to work for you

yes you were right. i tried 9v battery with 7805 + a 10uf filter capacitor it also worked without providing any delay. but may please check this code for me even if i am using battery its again started flick-ring. please tell me where i am doing wrong.

int dimmer_up = 0;

int dimmer_down = 1;

int AC_LOAD = 4; // Output to Opto Triac pin

int dimming = 128; // Dimming level (0-128) 0 = ON, 128 = OFF

void setup()

{

pinMode(AC_LOAD, OUTPUT);

pinMode(dimmer_up, INPUT);

pinMode(dimmer_down, INPUT); // Set the AC Load as output

attachInterrupt(0, zero_crosss_int, RISING); // Choose the zero cross interrupt # from the table above

}

void zero_crosss_int() // function to be fired at the zero crossing to dim the light

{

// Firing angle calculation :: 50Hz-> 10ms (1/2 Cycle)

// (10000us - 10us) / 128 = 75 (Approx)

int dimtime = (75*dimming);

delayMicroseconds(dimtime); // Off cycle

digitalWrite(AC_LOAD, HIGH); // triac firing

delayMicroseconds(10); // triac On propogation delay

digitalWrite(AC_LOAD, LOW); // triac Off

}

void loop()

{

if(digitalRead(dimmer_up) == HIGH)

{

if(dimming==128)

{

dimming=100;

delay(300);

}

else if(dimming==100)

{

dimming=75;

delay(300);

}

else if(dimming==75)

{

dimming=50;

delay(300);

}

else if(dimming==50)

{

dimming=25;

delay(300);

}

else if(dimming==25)

{

dimming=0;

delay(300);

}

else

{

dimming=0;

delay(300);

}

}

if(digitalRead(dimmer_down) == HIGH)

{

if(dimming==128)

{

dimming=128;

delay(300);

}

else if(dimming==100)

{ dimming=128;

delay(300);

}

else if(dimming==75)

{ dimming=100;

delay(300);

}

else if(dimming==50)

{ dimming=75;

delay(300);

}

else if(dimming==25)

{ dimming=50;

delay(300);

}

else if(dimming==0)

{ dimming=25;

delay(300);

}

}

}

diy_bloke (author)  deependra.kushwah951 year ago

deependra. your code is rather complicated coz of all the if statements.
could you just for testing purposes use this code:

void loop()
{
if(digitalRead(dimmer_up)==HIGH
{
dimming=dimming-10;
delay(300);
}
if(digitalRead(dimmer_down) == HIGH)
{
dimming=dimming+10;
delay(300);
}
}
I know it is not perfect as it doesnt protect against <0 or >128 but it is just to test the concept.
As 'dimming' starts out as 128, you may want to try the UP button first.

Also, you do not have to use the 'dimming' variable. I only introduced that to have 128 steps to set the light level, but it is actually the product of 'dimming' x 75 that sets the dimtime. You could of course set 'dimtime' directly

i even tried this code its working. but i don't know my circuit has very unstable behavior. when i tried above code it do no flicker but even without touching the input dimming level increases automatically and after crossing 128 it starts flickring. i checked all the possible false inputs which could be triggering microcontroller input but there in no such thing. i designed this whole on a single PCB and my design is very clear i don't understand whats going wrong. i even replaced power supply with a high quality 5 v 1amp adopter. do you have any idea where i am going wrong.

diy_bloke (author)  deependra.kushwah951 year ago

Well as I said, my code was just for testing and you should not go above 128 because then you get in the new cycle already so then yes it starts to flicker.
As your circuit was working with my original code, the one that was in te article, your circuit is OK
It is just the your software that seemed problematic.
As there was a lot of If statements in your code, I had you replace it with a simpeler code that however does not prevent you from going over 128 or even into negative numbers. It is just to prove concept.
Can you confirm that the up and down code is working as long as you stay between 0 and 128?

diy_bloke (author)  diy_bloke1 year ago

i overlooked something in your question, the fact that it goes over 128 by itself. Are the buttons on the same PCB as the Triac and the Atmega, or do you use an arduino board with buttons connected to my design?
Can you send me a picture of your setup and possibly a schematic and print design?

i dont have arduino board. i use atmega 8 controller with usbasp programer. and yes the controller and triac are on the same pcb. i am adding some pictures of my setup but it will be hard to understand because i have not done naming on design

Screenshot (23).pngScreenshot (25).png20140406_201935.jpg20140406_201951.jpg

for driving triac i have used the schematic given in the MOC3021 Datasheet. rest is save as your design

thats what i am saying up and down code working but the dimming level automatically increasing without touching "up" button and if i want to keep it below 128 then i have to continuously press the down button as long as i am doing that it works once i leave it , it cross the 128 level and start flickering. you are rite dimmer circuit is working fine. problem is with micro controller part plus the code is not perfect. i will work on code, i tried different micro controller coz i thought there might be some problem with that but that did not solve the problem. i checked the PCB traces they are clean and not having any fault connection with any VCC or ground connection. i will work on it then post the final result. but as far i got to know is this post is perfect something is wrong with my PCB or code, Thanks for the help man. :-)

diy_bloke (author)  deependra.kushwah951 year ago

good luck. could it be that your button is a bit faulty?

not 200 but delay(300) worked for me thankss alot. this means when i will write if else for button input then after every dimming level i need to add this delay. this post is really good very detailed explanation thanks for that too.

diy_bloke (author)  deependra.kushwah951 year ago

I am happy it got solved.

when i use this loop it works very fine. i feel somthing is wrong with hardware part

void loop()

{

dimming = 128;

delay(100);

dimming = 75;

delay(100);

dimming = 25;

delay(100);

}

msyazwan31 year ago

If i don't put the led on the circuit
will it effect the operation of the circuit?
not right?

diy_bloke (author)  msyazwan31 year ago

I actually wrote something about that. You do not need the LED, but if you remove it, increase the resistor to 470-560 Ohm and ofcourse dont just leave out the led, you have to short the LED connections on the PCB

msyazwan31 year ago

I already finished build the circuit but

i'm a little bit confuse by the input & output connection

like the input/output connector

from arduino to board, the first input which one should be connect to

& the output connection for the 230V supply why you connect it to neutral wire first instead of live wire?

If you don't mind, can you help me by giving the correct one for i/p & o/p..thanks again!

diy_bloke (author)  msyazwan31 year ago

I am a bit confused as the connections are clearly indicated in the circuit.
However, if you hold the PCB as it is in the picture, the mains connection goes to the top connector on the right side and yr lamp goes to the bottom connector at the right side.
Then on the left side of the pcb the connections are as follows from top to bottom:
+5 Volt

zero crossing

output from Arduino to circuit (the On and OFF signal)

Ground

I am not sure what you mean with : "the output connection for the 230V supply why you connect it to neutral wire first instead of live wire?"
I never stated anything about which to connect first. it doesnt matter which you connect first because you connect the wires while there is no voltage on it. Only then you plug in the mains so they get connected at the same time anyway.

Can I just stress again that when you are working on the circuit you should NOT have it connected to the mains

amidar1 year ago

For the zcd i will use the proposed circuit, but, can i simply replace the second part completely with SSR, say Sharp S202T02 ?

As much as i can see, internaly it is the same thing.

diy_bloke (author)  amidar1 year ago

amidar, no, you cannot. If you look at the datasheet:

http://html.alldatasheet.com/html-pdf/43483/SHARP/...
you will see in the drawing, bottom right corner an arrow point at the 'zerocross circuit'
This means that the S202T02 has its own zerocross detection. Therefore it doesnt matter what time delay you will give the trigger signal, the SSR will wait for the next zerocross. These SSR's are meant to have two states: ON and OFF. they dont have an in between state

It seems that SSR's are switched on AND off only AT THE ZCD event, so they does not matter whether you politely say "please turn off". :-)

diy_bloke (author)  amidar1 year ago

seems you have answered your own question (though i already stated it in my first reply) but yes, irrespective of the timing of your ON signal, the ssr will always wait till the next zero crossing and switch on, same for your OFF signal.

To be complete. In my software/circuit, I also do not tell the TRIAC to go 'off' The triac is switched off by the next zerocrossing

Hi diy_bloke,

well, if we forget for a moment about ZCD inside SSR and use our own ZCD circuitry (Your own actually. :-) ) to detect that event, and at that moment turn SSR ON, wait for some time and then turn SSR OFF after that, i really do not see why that should not work ?

msyazwan31 year ago

You said that you used

df02 bridge, from the datasheet it only have 4 feets

but by looking at your pcb diagram it have 6 feets

can you expain it. sorry for asking lots of questions, i'm a beginner

thanks for your help

diy_bloke (author)  msyazwan31 year ago

msyazwan
if you look at the picture you see an IC with 4 legs sit in a holder with 6 legs. That is because the df02 is a DIL IC in which the pins have 2x the regular 0.1 inch spacing, or as you might see it, looks like a 6 pin DIL with the middle pins removed.
As there are no holders for 4 pin dil with double spacing, i put it in a 6 foot holder, not using the middle 2 pins

Myp1 year ago

repeated, but it works strange, especially after 28 seconds

http://youtu.be/QjyumBveW5E?t=27s

msyazwan31 year ago

Can I use the coding provided directly into arduino uno or should I make some adjustment? thanks

diy_bloke (author)  msyazwan31 year ago

msyazwan3
regarding your two questions:
"It's like a flasher right"
No, not really. but you can use it as a flasher if you want. What it does is it functions as a dimmer circuit for a lamp, but instead of with a knob, the lightlevel is set by the computer.
"Can I use the code provided or do i need to make adjustments"
Well, yes and no. it depends what you want. The code merely shows the light going from bright to zero and back. If that is all you want, you are set. But you could do other things with it. How about a circuit that measures the light outside in the evening and gradually puts more light in your living room at night, or attach it to a clock and gradually wake up by an increasing light level in your bedroom.
One thing that you have to set in your code is wether you work with 60Hz or with 50Hz

Thanks a lot..that's really helpful

I'm more eager of learning about Electronic now

although i'm someone with Power background.

diy_bloke (author)  msyazwan31 year ago

I am glad you liked it

msyazwan31 year ago

What type of bridge rectifier you are using?

can you give the specific type, what model for example.

thanks

diy_bloke (author)  msyazwan31 year ago

I am using a DF02 rated at 400 Volts 1 amp

msyazwan31 year ago

It's function like a flasher right?

Oh that's work...thanks..

but I want to hold the bulb in a one dimming level.(e.g. dimming level = 100)Please give me a solution program and tel me how it's work.plz..

diy_bloke (author)  lasanthalikitha1 year ago

that is not that hard, you have to feed a constant value for the 'dimming' variable.

so the loop of the program goes from this:
void loop() {
for (int i=5; i <= 128; i++){
dimming=i;
delay(10);
}

to this:
void loop()
{
dimming=100;
}

Thanks

diy_bloke (author)  lasanthalikitha1 year ago

my pleasure :-), glad you enjoyed making this

Can i use 4N35 instead of 4N25?

diy_bloke (author)  lasanthalikitha1 year ago

yes

Hello , I made the circuit on this link http://fleck.rullz.lv/acdimmer/ac_dimmer_220V_circuit.png .

But i used 4N25 instead
of 4N35.

My problem is the lamp turn on continuously and I can't control on it , I don't know my
problem is on code or on My electronic devices???

i used this electronic devices Tric "BT139" , ZCD is "4N25", Driver is "MOC 3020" applied voltage is 220 V50 Hz .

Thank you .

diy_bloke (author)  waleed abu sada1 year ago

Waleed, the circuit on fleck.rulz.lv should work. Please dubbelcheck if you built it correctly.
Have you connected it to the right pins on the Arduino? So it is in confirmation with the code? The code uses pin 2 for the interrupt and pin 3 for the output.
As the code is working on my device. I presume the code is not the problem. Since yr lamp burns continuously there is a simple check to do: remove all the connections with the arduino. The lamp should be off then. If it is not then there is a problem with yr circuit.
please check that first and let me know

I've to rebuilt the cct , and I've double check on the connection, my problem is still exists . I've remove all the connections with the arduino and my lamp is still work !! .. But if i remove the connection between gate pin on taric and A2 pin on triac the lamp turn off !!!

diy_bloke (author)  waleed abu sada1 year ago
Well then the problem is in yr circuit. As i am on mobile i cant check much so i will write more tomoro but i suggest for now u try it with just the rrsistorvalue u find in my circuit and only use one resistor

thank you very much , i will try on it Now and i waiting your suggestion tomorrow to solve this problem .

Best regards

diy_bloke (author)  waleed abu sada1 year ago

Let's first clarify what you call A2 coz there might be confusion. A2, M2 or T2 is usually the pin that is on the top if you look at the circuit. That is the one that is connected via a resistor and the optocoupler to the Gate.
A1 is the one on the bottom that in yr case is connected to the gate via a resistor.
I guess it is that resistor that you disconnected, between gate and A1.

So what happens if you let that resistor disconnected but you applt a 5 volt voltage to the input of the circuit (meaning via the 330 ohm resistor to the primary side of the MOC)

oops , ya ya i mean that connection between gate and A1 , when i remove the 330 ohm between gate and A1 the lamp is turn off , but i don't know what do you mean !!? do you mean remove the 330 ohm between gate and A1 ? and connect gate to 5 volt on arduino ?!

diy_bloke (author)  waleed abu sada1 year ago

remove that resistor and put 5 volt on the entrance of the circuit.
Forget about the arduino for now. just put 5 volt on th eentrance of the circuit

and whatever you do, only work on it when it is disconnected from the mains, so.... unplug it, commect yr 5 volt to the entance of the circuit and then connect to mains again

ricciolini1 year ago

Hi, thank you for posting this. It might be the solution I was looking for.

Would it be possible to publish the full circuit diagram? I intent to use it for controlling an AC 220V heat element.

Thank you

diy_bloke (author)  ricciolini1 year ago

tnx ricciolini, this is the full circuit diagram. Is there something extra you were looking for?

That's brilliant diy_bloke! I think that's all I'll need.

Thank you very much :)

The code in the image above looks very familiar to me. Oh, wait, that's because I wrote it. Yes, that's me. I'm the author of the code (and the video you stole it from) in your image. Thanks for the credit.

diy_bloke (author)  secretsather1 year ago

As you can see the code in the image is not complete and is therefore unusable.
I use it merely as an illustration and it serves no further purpose.
It seems a bit odd to 'steal code from a video' as that would involve retyping it. In fact it was given to me.

It is not always clear where code comes from, but as said, as it is incomplete, therefore unusable and not even intended for this specific circuit, I didn't really start a manhunt for whom had written it.
But since you found it yourself, please accept the credit, or if you prefer, I replace it by a picture of other random code.

diy_bloke (author)  diy_bloke1 year ago

let me just add that as you can see in other software -that IS relevant for this circuit- I have given credit. I have no desire to 'steal from a video' a piece of not relevant software, just to use it -incomplete- as an illustration, whereas I could have used any other lines of code without having to retype them from a video.
But thanks for letting me know.

diy_bloke (author)  diy_bloke1 year ago

@secretsather
I put in another illustration and removed the one you seemed upset about. As said it was just an illustration. One snippet of incomplete code or another doesn't really make a difference in that aspect

jairson1 year ago

porque el puente rectificador debe ser a 400v??

diy_bloke (author)  jairson1 year ago

it is a safety margin for the 220 Volt. If you should be using 110 Volts, you could chose a 250 Volt.
Additionally, the 400 volts was most widely available :-)

Gracias!
diy_bloke (author)  alozano alca1 year ago

my pleasure

harvsch1 year ago
Nicely done.
diy_bloke (author)  harvsch1 year ago
Thank you
gc9n1 year ago
Hello there, i made the circuit but instead of MOC3021 i used MOC3011 i have 2 problems first is that It works ONLY if i disconnect the +5V from Arduino the second problem is that the lamp (load) is not going into maximum voltage.
diy_bloke (author)  gc9n1 year ago
That seems indeed odd and I am going to need some more information. Are you saying that the program is still able to steer the lamp when the arduino is NOT connected to 5 Volt???
Anyway, what happens if you connect the input of the circuit directly to 5 Volt?
Which color LED have you been using?
The MOC3011 needs I think 10mA, it is very well possible that the MOC3011 in series with the LED and the resistor just doesn't get enough current to trigger. Try shorting the LED and connect the input to +5Volt

and just a warning: disconnect everything from the mains when you are working on it!!!!!
gc9n diy_bloke1 year ago
OK my 4N25 was upside down, thats why this was happening,,, all good , i continue to my project
diy_bloke (author)  gc9n1 year ago
That explains. We have all been there :)
gc9n diy_bloke1 year ago
yes of course, when i conect the 5V the lamp is off, when i disconnect the 5v the lamp is working as it should
, i have a small green led, that it doesnt light up.
also the bridge that i use is round , not square,


harvsch gc9n1 year ago
Dimmer circuits typically can only reach about 90% of full brightness on an incandescent light load.
craque1 year ago
Hi, I've been reading over this Instructable for the past week. I'm deciding on what kind of resistor(s) I require for the 4N33 from mains. The 4N33 uses an input of 60 mA at 1.5 V, right? My mains voltage is 230 V. I'm terribly rusty with maths, and I've worked out numerous values and it's 8am (without sleep). Could you enlighten me what kind of values of resistors I should focus on buying, perhaps with the formulas you used too? Thank you.
diy_bloke (author)  craque1 year ago
Hi craque,
Thanks for yr kind words. It is really not that hard but you make a small mistake. The 60mA that you mention (from the data sheet) is the absolute maximum current that may go through it. Using that you would need minimally a 4k resistor (U/I) but of course that is not the optimal value.
If you would use 60k the current through the optocoupler is about 4 mA (3.8 actually). I am no master in reading datasheets, but In the Normalized CE current vs LED current it shows that at 4mA the CE current is about 0.4mA. As the Collector Resistor is 1k there will be a drop of 0.4x10= 4 Volt at the top of the Sin Wave.
The Zero crossing pin will thus vary between 1 volt (=5-4) and 5 Volt which is definitely enough to trigger the interrupt.
With regard to the Wattage. that is also simple: P=IxIxR or (UxU)/R = (230x230)/60.000=882mW You thus need one resistor of 60k 882 mW or 2 resistors of 30k at 441mW each in real live that would be 1 Watt resp 0.5 Watt
Hi. You're right, that is the absolute maximum. I'm thinking about constructing a proper zero-cross detection circuit, I think it would be more efficient and with less heat dissipation overall. The idea of connecting a resistor to mains and directly to a very low voltage component really makes me nervous. Additionally, the precision of zero-crossing can't be that great either. Do you have any experience with more suitable zero-crossing circuitry?
I think you made a mistake with the values at the end also. You said one 1W resistor of 60K, or two 1/2W resistors of 30K... surely that would be two 1/2W resistors of 120K instead? This arrangement still gives off more heat than I would like. I'm very much a beginner, but I always prefer learning the most efficient methods methods before the lazy methods :D
I know you created this tutorial over a year ago and I love your dedication to answer comments; is it possible a more efficient zero-cross detection circuit could be worked out and implemented here? I know cost is a factor to most people, but cost isn't really a bother for me. I have seen example circuitry online and I have questions about the way they work. Is it possible I could ask you to explain them to me? Perhaps in PM to avoid too many comments? Thanks again!
diy_bloke (author)  craque1 year ago
thank you for your comment.
I don't think I made a mistake with the resistors as they are in series 30k+30k= 60k and as they each dissipate the same current, the reduction in resistance also gives a reduction in dissipated wattage.
In reality the connection of a component to the mains voltage isn't really a problem as long as it is an optoisolator. Yet, it is possible to get the zerocrosing signal from a secondary transformer as well.
The precision of the zerocross signal is dependant on the reaction time of the optoisolator and in fact it can be a pretty broad signal. I am sure there are different ones, more precise ones but as this worked for me and for many others I just left it as it is..
I'd be happy to look into some other possibilities so if you want some opinion on circuitry that you have seen, don't hesitate to ask
I believe you should add a noise filter to this circuit. Search the net for "filtering noise in triac circuits" or something similar. Your hi-fi-aficionado neighbor will not be very happy about you running the circuit unfiltered, and neither will the utility company.
diy_bloke (author)  freegreentech1 year ago
One could do that indeed. Honestly though I do not hear anything on my hi-fi system and any hi-fi system worth its salt should already have a noise filter. Yet, it won't hurt to add one
ekpamaku1 year ago
Hi, I have a buck system that dims (via analog) with a pot meter and I would like to do diming also via a remote control, but I do have much ideas on programming! do you already have a circuit that I can combine for this or whats is you sugestion?
diy_bloke (author)  ekpamaku1 year ago
I am not entirely sure what a 'buck system' is, so it is difficult to come up with a solution. It is enticing to presume that the pot meter just feeds a voltage and that therefore feeding a voltage from a microcontroller would be a solution, but that is too simple. The potmeter could well be a feedback regulator and I have no idea if it is a low voltage or high voltage circuit.
Sticking with an Arduino as solution, there are many projects of IR remote control with an arduino and if any you could control a servo that turns yr potmeter to the desired position, but there might be easier, non mechanical solutions.
I therefore suggest you first clarify yr 'buck system' a bit, coz i have no idea what that is :-)
Hi Diy_bloke,
my buck system is just a buck LED driver IC that drives my LEDs and the pot meter only fed the dim pin of the IC with a voltage of about 0-3.5Vdc and does not do any regulating apart from the diming. It would be nice to see if I can use a microcontroller to fed dis voltage to the dim pin of the ic and the control the microcontroller with an IR remote! or whats the best solution to this can you please send me a part list, code, and schematic of how I can attach it to my system. Thanks alot for your support
diy_bloke (author)  ekpamaku1 year ago
You need to replace the input from yr potmeter by input coming from a DAC. The Arduino doesnt have true analog outputs. The Arduino library provides a function called analogWrite(), that seems to imply DAC functionality, but it just controls the PWM output. For many applications, such as the case of motor control, PWM is sufficient. For other applications, such as creating a linear voltage or current driver, a real DAC is needed. There are various ways to do that. You could use a DAC chip, but there is a simpler method described here with just a capacitor and a resistor.

IR control of your Arduino is in fact pretty simple as well. There is the IR Remote library from Ken Shirriff that is extensively described. Take  for instance a look here

So, all you would need are a 3 pin IR receiver, an arduino, and an RC network.
Good luck
Hi,
Thanks alot your link was really helpful chears!!
diy_bloke (author)  ekpamaku1 year ago
great :-)
Happy i could be of assistance
Hi I jut wonder there is possible to run two dimmers like this one from one arduino uno for example? Looking on switching times looks like there will be impossible to control two independent dimmers at this same time???
diy_bloke (author)  mbialkowski11 year ago
Apologies for my late reply. Somehow I overlooked yr question.
In fact it is possible. The interrupt just signals the zero crossing and you can set two values for the delay time.
I have software somewhere that even regulates 3 lamps. Have to go find that :-)
diy_bloke (author)  diy_bloke1 year ago
Try this. It doesnt use an interrupt but is polling. I am sure the code can be improved but it is a begin
//3 channel dimmer

int redpin= 10;
int greenpin=9;
int bluepin=8;
int R[]={500, 0, 500, 500, 500, 0, 0, 0, 500, 250,0,0,0, 100, 200, 300, 400, 500, 500};
int G[]={500, 500, 0, 500, 500, 500, 0, 0, 0, 500, 250,0,0,0, 100, 200, 300, 400, 500};
int B[]={500, 500, 500, 0, 500, 500, 500, 0, 0, 0, 500, 250,0,0,0, 100, 200, 300, 400};

int Ra=500;
int Ga= 500;
int Ba= 500;

int nextstep=0;
int timeline=0;
int maxtime=18;

long crosstime= 0;
long currentcycle= 0;

void setup()

{
//Serial.begin(9600);
pinMode(redpin, OUTPUT);
pinMode(greenpin, OUTPUT);
pinMode(bluepin, OUTPUT);
pinMode(2, INPUT);
}

void loop() {
if (digitalRead(2)) {
zeroCross();
}
}

void zeroCross() {
crosstime= micros();
while ((micros() - crosstime) < 8200) {
currentcycle=micros()-crosstime;
if (currentcycle >(Ra *16))digitalWrite(redpin, 1);
if (currentcycle >(Ga *16))digitalWrite(greepin, 1);
if (currentcycle >(Ba *16))digitalWrite(bluepin, 1);
digitalWrite(redpin,0);
digitalWrite(greenpin,0);
digitalWrite(bluepin,0);
}
if(R[timeline] != Ra){
if(R[timeline] > Ra) Ra++;
if(R[timeline] < Ra) Ra--;
}
if(G[timeline] != Ga){
if(G[timeline] > Ga) Ga++;
if(G[timeline] < Ga) Ga--;
}
if(B[timeline] != Ba){
if(B[timeline] > Ba) Ba++;
if(B[timeline] < Ba) Ba--;
}
}
diy_bloke (author)  diy_bloke1 year ago
oops: where it says 'greepin' that should be 'greenpin'
NikWing1 year ago
hey, that's a great tut :)

I'm currently looking for something similar. I want to control an universal motor with around 400-500W using arduino.
But I find different informations on the WWW.
One says, you can't use the zero-crossing part with motors, since voltage and current are not in sync (90°).
Some say it works perfectly using this way, all you need is the 0-crossing because the current will do "what's right", and the moment the triac is off it's not important anymore ... etc.
So I'm not really sure how to approach that problem.

All I know is: I need either 0-crossing or detection of the voltage over the triac, a hall sensor to measure the speed/rpm of the motor to adjust it to the needed rpm value/speed and a potentiometer connected to the ADC to achieve some rpm presets. (min 200, max. 2500 rpm)

But beside the hardware part (especially the 0-crossing) I'm not sure how to get the software right.
Measuring the rpm needs an interrupt, 0-crossing needs an interrupt, reading the ADC takes some cycles and I have to make it work for 110V@60Hz and 230V@50Hz, so I might measure the mains frequency before the main loop does its work ... beside that it means that I have to use different resistors for the zero-crossing part, not sure if zener-diodes would make this problem easier hmm ...
And what part of the code/sketch has priority. While I measure the rpm I can't control the triac.
As you can see, many problems to solve for me and too many different informations found via google D:
Would you maybe help me figure something out if ever you've got some free time? :)

Best regards,
Nik
diy_bloke (author)  NikWing1 year ago
Interesting issue. This circuit does work with inductive load but it might not be the optimal circuit for it. I know from my past that I could regulate electric drills with a normal triac dimmer. But I have not tried this circuit yet for that. I am no expert on AC but of course it could be that the fact the current and the voltage are out of sync it would screw up yr triac switching off. The internet gives much conflicting info on this though one would expect someone would have found out already for sure. One solution I have seen for the out of phase problem is to pick up the voltage triggering the gate, from the full mains voltage, rather than from behind the load, whereas others claim success just as is with a circuit similar to mine albeit that they are not clear about the triggering. Others  say a bridge and MOSFET is the way to go. Found an interesting solution here too.
Generally it seems that a circuit as I suggested in "Step 2" should be OK (check here too, and  here too). As I included the Fritzing file, it should be easy to adapt the PCB for this.

With regard to the software, yes i see yr point. Ideally the circuit as is, already needs 2 interrupts, One for the zero crossing and one to set the delay, unless you want the software to just wait most of the time.
The Atmega328 has enough interrupts though (read up here) and should be able to handle it. While you measure RPM you can just leave the  triac delay as is until you have a new value.
With regard to using it for 110 and 230 Volts, that is another issue that requires both hardware and  software modifications.
A zenerdiode would help, but in order not to dissipate too much power in your resistors I would suggest using a sensitive optocoupler like the 4N33 and up your resistors to about 82 k.
You would also need to measure your voltage in order to set the parameters for the right frequency (provided the 60Hz will only come from 110 Volts). For that I suggest another optocoupler  with a resistor, whose value you chose such that it is in conduction at 230 Volts and isnt at 110 volts, Measure that as a high or low with a digital input and set your variables accordingly.
If anybody else has a better idea, please let it be known.
Good luck and dont hesitate to ask if you need to know more
diy_bloke (author)  NikWing1 year ago
Interesting issue. This circuit does work with inductive load but it might not be the optimal circuit for it. I know from my past that I could regulate electric drills with a normal triac dimmer. But I have not tried this circuit yet for that. I am no expert on AC but of course it could be that the fact the current and the voltage are out of sync it would screw up yr triac switching off. The internet gives much conflicting info on this though one would expect someone would have found out already for sure. One solution I have seen for the out of phase problem is to pick up the voltage triggering the gate, from the full mains voltage, rather than from behind the load, whereas others claim success just as is with a circuit similar to mine albeit that they are not clear about the triggering. Others  say a bridge and MOSFET is the way to go. Found an interesting solution here too.
Generally it seems that a circuit as I suggested in "Step 2" should be OK (check here too, and  here too). As I included the Fritzing file, it should be easy to adapt the PCB for this.

With regard to the software, yes i see yr point. Ideally the circuit as is, already needs 2 interrupts, One for the zero crossing and one to set the delay, unless you want the software to just wait most of the time.
The Atmega328 has enough interrupts though (read up here) and should be able to handle it. While you measure RPM you can just leave the  triac delay as is until you have a new value.
With regard to using it for 110 and 230 Volts, that is another issue that requires both hardware and  software modifications.
A zenerdiode would help, but in order not to dissipate too much power in your resistors I would suggest using a sensitive optocoupler like the 4N33 and up your resistors to about 82 k.
You would also need to measure your voltage in order to set the parameters for the right frequency (provided the 60Hz will only come from 110 Volts). For that I suggest another optocoupler  with a resistor, whose value you chose such that it is in conduction at 230 Volts and isnt at 110 volts, Measure that as a high or low with a digital input and set your variables accordingly.
If anybody else has a better idea, please let it be known.
Good luck and dont hesitate to ask if you need to know more
Is it a big deal if I remove a 30k resistor ?
Why is there two of them ?
If I can, should I use a 60k resistor 0.5 watt or better with 30k 1W or last possibility as 60k 1W ?

Thanks im advance,

By the way, my question is due to the provided printable circuit (link) which looks a bit different in this part and as well for tic 206 which seems to be inverted between mt1 and mt2 -> I tried "as is" and felt)
Ps 2 : my first is due to a light burnt smell ...

Christophe
diy_bloke (author)  blacktrooper21 year ago
Christophe
I would not remove a 30k resistor if i were you. If you would replace that by a wire bridge the rectifier would get a bit overloaded, unless you were working with 115 Volts.
Yoy can however use one 60 or 68 k resistor. 1W is a bit over the top :-) 0.5 is enough
The reason why I used two is so i could keep the tracks that were connected directly to the mains as short as possible, for safety reasons.

Thanks for pointing out the difference in the printed circuit boards. I indeed have changed the pcb, though I am not sure anymore why i made the changes, probably to add some copper surface and to simplify a bit. I should however have updated the drawing as well.
That M1 and M2 now are switched should not really make a difference as the circuit is in series with the load.
nevertheless, I may just put the old PCB back. That might be the best option.
Thanking you for pointing it out.
The light burnt smell?? is it still working though? did you use the proper wattage for the resistors?
Hi,

Thanks for the reply
No I wanted to know if 2 resistors were necessary ?
Because on the pcb there is only one 30k.

PS : it seems to not work on my board if I change the order of M1 and M2. but I agree with you, it should not !

PS : The circuit smells burnt. Not the light.
diy_bloke (author)  blacktrooper21 year ago
Hi Sorry if i was not clear earlier. 2 resistors are not necessary as long as the total resistance is correct: 60 kOhm
I also meant "A light burnt smell?" not that the light smelled burnt.

I feel a bit ashamed that somehow the link to the print design got mixed up. The design you used works, but it was never my intention to publish that as there is no correspondence to a scheme of where to put the components. I now let the link go the the correct fritzing file. Sorry about that. You are the first one to let me know.

The burnt smell is hard to say: did you in fact use only one 30k resistor? That might be an issue then because that is then a bit too low both in resistance as well as in wattage, which could easily cause the smell a 30k resistor will probably dissipate 1.2 Watts.
If you use a 60 k the dissipation will be around 0.8Watt. So 1 watt would be ok.
in my original design with 2 30 k resistors 0.5 watt/resistor would suffice.

I am very sorry for the confusion

I meant "it smells a little bit burnt"
:D

And no worries for the discrepancies betwwen schemes. We have almost solved the point : I'll try this week end to replace the resistor by a 60Kohm 1W and we'll see !

Thanks for your support,

Christophe
diy_bloke (author)  blacktrooper21 year ago
yes I understood. I presume the one Watt will solve that. Sorry about the confusuin
will bta16 triac be suitable for this project ?? if not,then suggst something other than tic206 because it is not avalable in market
diy_bloke (author)  ankitjainak461 year ago
Yes, the BTA16 is usable. Though the BTA16-400 should do, I suggest you take the BTA16-600 if there is no big price difference.
BTA136 will also do. In fact, most TRIACS wil work but you may need to adapt the Gate resistor a bit. I expect the 1k to be sufficient for the BTA16
eelkenet1 year ago
I just wanted to say: thank you for the circuit. I built it on an Arduino prototype shield (as I don't have the skills / materials for etching) and it works perfect.
diy_bloke (author)  eelkenet1 year ago
good to hear that Eelkenet. just a word of warning. if you put the shield on top of teh arduino, the high voltage lines may get awfully close to the arduino itself. please be careful. Nevertheless, thanks for yr kind words
indrakp1 year ago
Hi, I tried my board with the code which I have written for 89V51RD2 .
I receive the interrupt from Zerocrossing output pin …

But load(bulb) which I am connected is not varying, its always ON .. if I remove the triac input signal also my load is ON”.. I checked traic with multimeter .. It is good ...

what may be the problem?

Since I did not get 30k(1.2 watt resistor) , I connected 33k(1/2watt) all other or normal resistor ..

here is my delay and ISR code

void delayMicroseconds(unsigned int i)
{

for(j=0;j<=i;j++)
{

for(k=0;k<256;k++);
}

}

void ex0_isr (void) interrupt 0
{
P0 =0×01; // triac firing
delayMicroseconds(10); // triac On propogation delay

P0 =0X00;// triac Off
}

and I need to support Constant dim Levels so will be changing the Delay between triac ON and OFF work well ?
Like Below .


//for Level: 0
P0 =0×01; // triac firing
delayMicroseconds(8); // triac On propogation delay for Level: 0
P0 =0X00;// triac Off

//for Level: 1
P0 =0×01; // triac firing
delayMicroseconds(10); // triac On propogation delay for Level: 1
P0 =0X00;// triac Off

//for Level: 3
P0 =0×01; // triac firing
delayMicroseconds(12); // triac On propogation delay for Level: 2
P0 =0X00;// triac Off
diy_bloke (author)  indrakp1 year ago
Hi Indrakp. Oddly I thought I had replied a few days ago already but cant find my reply right now so maybe something went wrong in posting it.
Anyway, using 33k instead of 30 k is no problem.

If your Tria is always on, regardless of what kind of signal-or no signal you are sending then the problem is not in yr code. there are actually 2 places where i suspect a problem then: If you are sure the circuit you built is correct and there are no shorts on yr PCB, the problem is in your Triac or yr opto-coupler.
her is what to do:
Remove all connections to the mains:
If you have used a 6 pins DIL foot for the MOC3021, remove the MOC3021 from its socket.
Keep yr 8051 away, you dont need that now.
attach a load (a lamp) and attach mains voltage again.
If your lamp does not light up, the problem was in your MOC3021.
If your lamp does light up, the problem is in your TRIAC

If you did not use a 6 pin DIL foot then desoldering the MOC3021 is a bit too much just for testing. in that case just desolder one end of the 560 ohm resistor and try the test described above.
Please let me know what happened
Hi, I replaced the moc3021 .. Now its not always ON ..
I am directly connected the micro controller out PIN to 220ohm resistor . it seems A voltage from the micro-controller is not sufficient for MOC3021 .. My load is not turning ON when I send HIGH on the PIN .. But If I directly Connect 5vcc to the 220Ohm , load switches ON .. So I am adding simple switch (using TIP122) to drive the MOC3021 from VCC .. Pls let me know is this approach is correct or not ..?

and I need to support Constant dim Levels so will be changing the Delay between triac ON and OFF work well ?
Like Below .


//for Level: 0
P0 =0×01; // triac firing
delayMicroseconds(8); // triac On propagation delay for Level: 0
P0 =0X00;// triac Off

//for Level: 1
P0 =0×01; // triac firing
delayMicroseconds(10); // triac On propogation delay for Level: 1
P0 =0X00;// triac Off

//for Level: 3
P0 =0×01; // triac firing
delayMicroseconds(12); // triac On propogation delay for Level: 2
P0 =0X00;// triac Off

diy_bloke (author)  indrakp1 year ago
let me also add that though yr setup with a TIP122 will work it is serious overkill to direct a small current through an optocoupler. You are better off using a BC547 or something. Use a 1k base resistor
diy_bloke (author)  indrakp1 year ago
Indra, I am getting a bit confused as in our discussion on http://arduinodiy.wordpress.com/2012/10/19/dimmer-arduino/ I had the impression the hardware was working. Nevertheless if you need a bit of extra punch for yr MOC3021 yr solution is a good one. With regard to your program, I have laid out a structure already on http://arduinodiy.wordpress.com/2012/10/19/dimmer-arduino/
and I am not sure why you dont follow that. The program as sketched above by you will not work as wanted: what you do is you lengthen the "On" pulse to the triac and that is of no use. The triac will go ON and will be switched off bu the zerocrossing.

What you need to do and what I described in a reply to you on my blog already is to add the  delay BEFORE you fire the triac. Like so:

interrupt {
delayMicroseconds(dimtime);
P0=0×01;
delayMicroseconds(10); //propogationdelay
P0=0×00;
}

loop {
IF condition dimtime=9000;
ELSE IF condition dimtime = 7000;
ELSE IF condition dimtime= 5000;
ELSE dimtime=2000;
}

What that does is that at every zerocrossing the interrupt will be called. That will then get its delay (dimtime) from the mainloop and wait dimtime microseconds before firing the Triac.
Hi everybody,

I tried this circuit but have some issue with it. I'm trying to use it with a SR04 ultrasonic distance detector. My goal is to dim a light depending on the distance. I've modified the code and added distance ranging procedure in loop.
My problem is I have flickerings and sometimes complete freezing (nothing on Serial.print).

And can someone explain me why in void zero_cross_int(), the delay is 34*(I_LED_max-I_LED) ?
For me at 50Hz, 1 period is 20ms, then half period 10ms. I want 255 dimming level so I want to divide 10ms in 255 = 39us.
Isn't it ? Then why 34 us ?
And second thing : the second delay of 500us should depend on how long was the previous delay (delayMicroseconds(34*(I_LED_max-I_LED));), shouldn't it ? Because this delay open the gate until the next half period ?
So if it's too long, then the gate is still open at the next gate, and if it's too short, we don't have the good light level.

NB 1 : sorry, for my poor english
NB 2 : sorry , comments are in french
NB 2 : sorry, I'm beginner in Arduino / electronic but love to understand what is happening !!!




// ***************************************** Déclaration variables globales ****************************************
     const    boolean   DEBUG_MODE       = 0   ;    // envoie le table par usb pour debug (ON = 1 / OFF = 0)
     const    int       Dim_pin          = 3   ;    // Broche de sortie vers Opto Triac
              int       I_LED                  ;    // Valeur envoyé à l'optotriac
              int       I_LED_NEW              ;    // Valeur la plus récente qui sera comparé avant envoi à l'optotriac
  volatile    int       I_LED_OLD              ;    // Valeur de la précédente boucle
              long      T_A1                   ;    // Définition variable stockage durée
              long      D_A1                   ;    // Définition variable stockage distance
     const    long      D_min            = 1   ;    // Définition distance min à partir de laquelle la lumiere est à fond en cm - valeur compris entre 0 et D_max (MODIFIER SI NECESSAIRE)
     const    long      D_max            = 100 ;    // Définition distance max de détection en cm - valeur max : 400 cm environ (MODIFIER SI NECESSAIRE)
     const    long      I_LED_min        = 0   ;    // Définition intensité lumineuse min
     const    long      I_LED_max        = 255 ;    // Définition intensité lumineuse max
              int       VAR                    ;    // Variable de stockage des calculs intermédiaires
     const    int       Delta_I_LED  = 20  ;    // Delta admissible entre OLD et NEW (MODIFIER SI NECESSAIRE)
     const    int       MOD              = 5   ;    // Réactivité pour lisser les pics
     const    long      T_auto           = 30  ;    // Rapidité en mode auto (MODIFIER SI NECESSAIRE)
// *****************************************************************************************************************

// ************************************************ FONCTION SETUP *************************************************
void setup() {
  Serial.begin(9600);                             // Initialise communication USB (A UTILISER POUR DEBUG)
  pinMode (Dim_pin, OUTPUT)  ;                    // Définition broche de commande dimmer
  attachInterrupt(0, zero_cross_int, FALLING);    // Définition broche passage par zéro
}// ****************************************************************************************************************

// ********************************************** FONCTION ZERO CROSS **********************************************
void zero_cross_int() {                                // Processus lancé lors du passage à zéro de la ligne 220V
  if (I_LED < 1) {digitalWrite(Dim_pin, LOW);}         // Turn TRIAC completely OFF if dim is 0
  else if (I_LED > (I_LED_max-1)) {digitalWrite(Dim_pin, HIGH);} // Turn TRIAC completely ON if dim is 255
  else if (I_LED > I_LED_min && I_LED < I_LED_max) {                 // Dimming part, if dim is not 0 and not 255
    delayMicroseconds(34*(I_LED_max-I_LED));                 // Calcul du retard à l'allumage
    digitalWrite(Dim_pin, HIGH);                       // Allumage
    delayMicroseconds(500);                             // temporisation
    digitalWrite(Dim_pin, LOW);}                       // Extinction
}// ****************************************************************************************************************

// ************************************************* FONCTION LOOP *************************************************
void loop(){
  // Déclaration des broches Entrées/Sorties capteurs de distance SR04 (ne pas oublier les broches Vcc et GND vers module Arduino section PWM
  pinMode(30,OUTPUT);                   // Trig
  pinMode(31,INPUT);                    // Echo
 
  // Envoie signal par broche COMMANDE pour un relevé propre : eteint/allumé/eteind
  noInterrupts();                       // Arret interruption
  digitalWrite(30,HIGH);                // Allumage
  delayMicroseconds(3);                 // Tempo
  digitalWrite(30,LOW);                 // Extinction
  T_A1 = pulseIn(31,HIGH,28000);        // Récupère signal par broche LECTURE en ms (4 m => 27200 us)
  interrupts();                         // Remise en route interruption

  // Calcul distance en cm
  D_A1 = T_A1 / 68 ;                    // = T_A1 / 34 / 2

  // Conversion distance en intensité lumineuse pour commande circuit UNO
  if (D_A1 == 0) {I_LED_NEW = I_LED_min;}                               // Cas distance infini ou trop proche
  else if (D_A1 > D_max) {I_LED_NEW = I_LED_min;}                       // Cas distance supérieure à la limite D_max
  else if (D_A1<=D_min) {I_LED_NEW = I_LED_max;}                        // Cas distance inférieure à la limite D_min
  else  {I_LED_NEW = map(D_A1, D_min, D_max, I_LED_min, I_LED_max);}    // Cas des valeurs intermédiaires

  // Gestion Pic intensité lumineuse
if (abs(I_LED_OLD - I_LED_NEW) > Delta_I_LED_LOW) {
    if (I_LED_OLD > I_LED_NEW) {
      for (VAR = I_LED_OLD; VAR >= I_LED_NEW; VAR = VAR - MOD) {
        I_LED = VAR;
        delay(T_auto);}}
    else if (I_LED_OLD < I_LED_NEW) {
      for (VAR = I_LED_OLD; VAR <= I_LED_NEW; VAR = VAR + MOD) {
        I_LED = VAR;
        delay(T_auto);}}}

  I_LED = I_LED_NEW;                                                   // Validation nouvelle valeur

  // Mise à jour de la dernière valeur validée
  I_LED_OLD = I_LED_NEW; 
 
}// ****************************************************************************************************************
diy_bloke (author)  blacktrooper22 years ago
There is nothing wrong with yr English.
I provided the 2nd program as is and did not use it myself. You show good insight in programming and there is no harm playing with the times a bit
Good luck
This is a fantastic tutorial, thanks so much. Faved :) I'm noticing you don't mention LEDs anywhere. Is this circuit suitable for LED lamps? I'm reading up on the subject and I'm seeing that when it comes to LED lamps vs halogen or incandescent the necessary circuitry and approach changes. Do you have any insights?
(btw, sry for posting in reply to a different thread. The comment editor was misbehaving, this was the only thing that was working. Maybe I need an instructable on how to comment ;)
diy_bloke (author)  Bombarie1 year ago
That's OK. You know I think there actually IS s tutorial on that :-)
Thanks for the answers. My quest is now for a solid dimming solution for 12v LED lamps. You're right that they have internal circuitry that makes them not suitable for dimming. That seems to be the case for all 220V/120V lamps and for *some* 12V lamps (I'm disappointed that the manufacturers aren't clear about this).
diy_bloke (author)  Bombarie1 year ago
Bombarie, dimming of 12 Volt LED lamps may be a bit of a problem, depending on the type of lamp. There are basically 2 types: the LED matrix and the current source.
In the LED matrix a number of leds are placed in series with a current limiting resistor to make them suitable for 12 Volt. a number of these strings may be in parallel as well, and there are the LED's that are fed with aconstant current.
The former are quite easy to dim with a PWM signal and a Logic level FET (such as the RFP30N06LE MOSFET). Wether the constant current source lED's are easy to regulate with a PWM I am not sure if the constant current source is that easy.
Most PWM signals are of course an on off signal and in theory, if the signal is off, the current source should have no way toi maintain current and the leds should be off, but I am not sure if in practice this will work smoothly.
Should you find out, I would love to hear.
I plan to explore that further in a few weeks. If I learn more I'll let you know. I can only hope it's of use to you, I'm really not that experiences with electronics yet.
diy_bloke (author)  Bombarie1 year ago
any experience, good or bad is useful. If you fail 100 times then at least you learned 100 ways how not to do something
diy_bloke (author)  diy_bloke1 year ago
Bombarie (are you dutch?), I added a little circuit for you to switch 12 Volt AC, maybe that is of some help.
AC_laagspanning.JPG
diy_bloke (author)  diy_bloke1 year ago
if you are interested, you will find a print design here: https://www.dropbox.com/s/knx5emkbbyr5dmd/ac_laagspanning.fzz
not that I have not built it on this PCB yet so you may want to dubbelcheck if it is OK. The TIC 206 needs good cooling if you are going to use a lamp of 20 watt
diy_bloke (author)  diy_bloke1 year ago
In the mean time I have built the 12V AC circuit on the PCB and it is working. Just if anybody is interested:
http://www.instructables.com/id/Simple-Low-Voltage-AC-switching-with-a-microcontro/
Hi, I did not get any kind of these module in india ,, I am trying to build by own circuite.. I did not get 4N25 opto coupler but I got 4N35, is it okay to go with 4N35 .. and I am using 5v at vcc pin ... is this okay to move?
be nice
Hi,

I'm actually not sure because I checked the datasheet and need 7VDC to light the led. But what I would do is to try by making the circuit with connectors. Like this : http://www.gotronic.fr/art-connecteur-secable-fh050-4463.htm
Then tou can with the one you found and if it doesn't work, you can seek for the original one and replace easily.

K
diy_bloke (author)  indrakp1 year ago
I am always nice indrakp :-)
yes it is ok to use the 4n35 and 5 Volt at the Vcc pin is exactly what you need :-)
Unfortunately the 12v AC circuit is not what I'm looking for atm. I'll be trying out the 12v DC approach in a few weeks. Untill then I'm using non-dimmable LEDs with a relay, which is perfectly acceptable for my current project.
Btw, I am Dutch :) The name give it away?
diy_bloke (author)  Bombarie1 year ago
Yes, the name did :-)
For 12 Volt there are ofcourse I number of possibilities, but the simplest would be a logic level MOSFE. Other than the RFP30N06LE that I already mentioned, the BUZ11 should be usable and it is quite cheap:
http://www.dickbest.nl/index.php?_a=viewProd&productId=1279
diy_bloke (author)  Bombarie1 year ago
Though you put this under the wrong thread as you mentioned, I will give a brief general answer. Nope this circuit is not really suited for LEDś in fact LEDś are much easier to dom.
However, with regard to LED lamps... the ones that work on a mains voltage: I have not tried but I doubt it. These lamps contain some electronics, that is not really built to deal with phase cutting as it's input.
With regard to Halogen bulbs, there is a lot of discussion on wether this should work with a conventional dimmer (which this in fact is as well) and the consensus seems to be: "yes it does work, but it will shorten the lifespan of the bulbs". True 240 or 120 volt halogen lamps may be a bit more forgiving with this circuit than 12 Volt lamps that are fed via a transformer.
I am not an expert on the matter, but I understand inductive loads have a phase shift and therefore the program may need to be altered for a different timing for best results
muddu11 year ago
hey it has the same design as the one featured in sunrom.com
diy_bloke (author)  muddu11 year ago
Actually it is not. the sumrum board: http://sunrom.com/249 has a microcontroller embedded to regulate in total 16 levels depending on the state of 4 input lines
diy_bloke (author)  muddu11 year ago
as I did not find the one featured in sunrom com, I cannot comment on that but it would not surprise me as the basics of zero crossing detection and triac use are quite simple and the same all over the board. I already pointed out the inmojo board
jvarghese31 year ago
OK here are my doubts plz help.
No 1:the MOC ratings say that the forward voltage drop across the photodiode is about 1.5(10mA) so including the LED shouldnt the resistor be 350ohms(3.5/10mA) .
No 2:the triac gate trigger current if I was using a BT136 is 5mA rated so does that mean for a 230 V supply i use a 230/5mA =46K resistor ??
diy_bloke (author)  jvarghese31 year ago
Tnx for yr reaction jvarghese No.1 In hindsight the way I placed the LED (in series with the MOC), though a good solution for me, may be a less wise choice for a project for self build because people may chose different LED's that have a different voltage drop. Your calculation of a 350 Ohm resistor goes wrong because you do not take the voltage drop over the LED into account. If I would have a red LED with say a voltage drop of 1.7 Volts there is 5-(1.7+1.5)=1.8Volts left which leads to 1.6/220=8.18mA. The typical trigger/latching current for a MOC3021 is 8 mA so that is close enough. However, would you use a blue LED with a voltage drop of say 3 volts that would give: (5-(3+1.5))/220=2.3mA and that would not be enough. I suggest therefore you forget about the LED and use a 470-560 ohm resistor. No.2 I understand your point but you forget to take a few things into account, e.g. that there is a load resistance as well. I am not an electronics engineer but people who are have told me that there are a few factors determining that gate resistor. The minimum value of the resistor is determined by the peak gate current of the triac (2A) or the peak surge current of the MOC3021 (1A) whichever is lower. If you would assume that briefly the full mains voltage (220 Volt) would be over the TRIAC, the minimum value of that resistor is 220 Ohm in practice that is already safe as a lamp of say 100 Watts has a resistance of 480 Ohm (a bit more when the filament is cold). The trigger current of the BT136 is not exactly 5mA as it depends a bit on the quadrant: it ranges from 5-30mA. It is the holding current that is 5mA. Subsequently you have to take the gate voltage into account Anyway, rather than going into extensive calculations, what I did is to use a tried and tested value for the gate resistor, using a TIC 206. Applying the same philosophy to using a BT136 would suggest a value of 1k as well
diy_bloke (author)  diy_bloke1 year ago
jvarghese3:
After browsing around a bit more I have seen the MOC3021 and BT136 used with resistor values varying between 1 and 100k.
The problem with many circuits on the internet though is that they might be wrong. 100k, even if there is the full 220 V available, will give 2.2mA which might be a bit low for the BT136.
diy_bloke (author)  diy_bloke1 year ago
dkundu1 year ago
Hi,
I am following your circuit, as given by the schematic, not by the PCB, where some component values are different.
However I have chosen a different software implemented by Timer/Counter1, as I want to control more than one dimmer.
The software is running fine and testing seems to be OK.
I am using simple filament light bulb as dimming load, and when I run the circuit, even for full time triac on value (off time for triac is zero), the bulb is almost blinking, and not getting dimmed.
If I decrease the triac turn on time (by increasing the delay), then it is acting like on-off circuit.
I also tried your softwares with same results. Where I am going wrong. Please help me to sort this issue out.
This is my first arduino project, and I am getting very frustrated very much.
Parts used: 1. at mega 328 based board (16 mhz internal clock) 2. 4n25 with 400 v br as zc ckt 3. el3021 as triac driver and bt136 as the triac.

Thanks in advance,
Debojit
diy_bloke (author)  dkundu1 year ago
it is hard to say what exactly the problem is. What happens if you try the software i provided, rather than the Timer/Counter software?
What is the wattage of yr lamp? sometimes lower loads don't regulate that smooth.
The PCB values, really aren't different from the circuit, with the exception of one resistor. You may want to lower the value of the gate resistor of 1 k to indeed 560 ohm and see what happens.
The el3021 is similar to my MOC so the only thing you have different are the TRIAC and that resistor
Let me know. In the mean time I'll try to think of other possibilities
diy_bloke (author)  diy_bloke1 year ago
sorry, I see you already tried my software. the only thing i can think of then is that the BT136 may need a different value for its gate resistor so try to change that one.
What is the wattage of yr load?
diy_bloke (author)  diy_bloke1 year ago
Not sure if you already found a solution, but it could be that your trigger signal is a bit weak. Try replacing the LED by a wire bridge. You don't really need the LED
diy_bloke (author)  dkundu1 year ago
I am not sure if you got it working but you may have a look at the R-values in this circuit: http://obrazki.elektroda.pl/8217509000_1353486022.jpg. It has a resistor of 390 Ohm between M1 and the MOC and a resistor of 470 Ohm between the Gate and M2
mondalaci1 year ago
Yours is THE tutorial on the subject! I'm on my way to build this circuit to speed-control a fan.

What's the point of the zener diode?
diy_bloke (author)  mondalaci1 year ago
Thanks Mondalaci.
Yje idea of teh zener is to protet the 4n25, but in all honesty: I did not mount it and I think it is not really necessary
diy_bloke (author)  diy_bloke1 year ago
Sorry for the typoś that is what one gets by using a mobile phone to answer. Good luck with your fan project
mondalaci1 year ago
Also, what should be the power rating of the 1K resistor next to the TIC206?

Thanks!
diy_bloke (author)  mondalaci1 year ago
I have used a 1/4 watt
Hey I found that your code didn't work no matter how much I tweaked it. I found that using TimerOne /with/ an interrupt works much better. I borrowed some code that I found on a forum and expanded it to work with 6 other lightbulbs: http://pastebin.com/HVYX07U4

Hope this helps someone.
diy_bloke (author)  jacobclarke921 year ago
Thanks Jacob. The code provided is really the simplest to have but using a timer with it is more elegant.
The code you mention in your link actually is presented in step 4 with some adaptations.
Glad you got it working although I am not entirely sure why the code in its simplest form was not working
tonysofla1 year ago
I have used this for zero-cross detection: PS2505L-1-A
Pin1: a 47k ohm in series to 115v mains (100k ohm for 220v)
Pin2: Neutral (Earth Ground would work too, but thrown on)
Pin3: MCU ground (Vss)
Pin4:Signal to MCU, pull-up with 10k resistor to 3.3v or 5v (Vdd)
diy_bloke (author)  tonysofla1 year ago
Thanks for your input Tony. The PS2505L-1-A is a bidirectional optocoupler with the antiparallel led's between pin 1 and 2, the collector of a phototransistor on pin 4 and the emitter on pin 3. Using this one makes the bridge rectifier redundant. In your setup there should roughly go 2.5 mA through each diode. That might be a tad low but if it works it works.
Thanks for your info. I had pointed out the H11AA1or IL 250, 251 or 252 opto-coupler already but always good to have one confirmed to work.
bdpak1 year ago
Good one... But how can i control the brightness of the lamp over a continuous range.. is it possible.. like using a potentiometer... in this ciruit...
diy_bloke (author)  bdpak1 year ago
Yes it is, but just to make sure... if all you want is yo use a potentiometer to control the brightness of a lamp, then you do not need the arduino. then there are simpler circuits.
If you want to do it with the arduino or another microcontroller then what you need to do is to connevt the steady ends of the potentiometer to the + and - resp. and the middle contact to an analog port. Subsequently read the voltage on that port and translate that to a delay in firing the TRIAC.
You will find a program to do just that here:
http://wiki.dxarts.washington.edu/groups/general/wiki/4dd69/attachments/3acd6/acdimmer_pot.zip
If you have further questions please do not hesitate to ask
diy_bloke (author)  diy_bloke1 year ago
And in case I misunderstand you wand you want to "like using a potentiometer" Well that is what the program i supplied already does, it regulates up and down as you can see in the youtube clip in the last Step
Hi. I had problems with this scheme and code on my Leonardo. But I found how to fix it, so if you are on Leonardo and have probs, read more:

One thing is that Leonardo has different system of interrupts: Int.0 = pin 3 and Int.1 = pin 2 (instead of Int.0 = pin 2 and Int.1 = pin 3 on UNO and Mega2560). Also you can use int. 2, 3 and 4 on Leonardo. See this link: http://arduino.cc/en/Reference/attachInterrupt.

But it was just a minor problem in my Leonardo case. It still didn't work. I checked my circuit and it was OK. So I started trying another codes. One I found working is this: http://wiki.dxarts.washington.edu/groups/general/wiki/4dd69/AC_Dimmer_Circuit.html

I don't know why this code is working and code from this site isn't, but I don't care for now. Maybe somebody here should know it...

Hope this will help some Leonardo folks.
BTW: Thanks for nice tut. (It would be nice, if you add some info with interrupt change on Leonardos).
diy_bloke (author)  Andre Bleton1 year ago
Thank you for your feedback and your link
diy_bloke (author)  diy_bloke1 year ago
and i will add the Leonardo interrupts
diy_bloke (author)  diy_bloke1 year ago
I see I already had the link you gave under "Step 3" but it is good to know it is working on the Leonardo. I agree, I see no reason why the first program gave you problems, but as I don't have a Leomardo, I can't test it.
AnKOne1 year ago
Hey can you suggest me how i can use this circuit for triggering with 8051(P89RD2). Because i want to achieve dimming only at the certain levels.If 128 = OFF then for 64 it should be with half brightness. I tried by giving delay but for 128 it's not getting OFF. I don't want to do this in loop but in switch or if statements. Glad if you help me out.
diy_bloke (author)  AnKOne1 year ago
the use with an 8051 is kinda similar. The 8051 has as i recall 6 interrupts, 4 of which are negative and 2 positive triggered.
I suggest you use INT0/PD2.
The number of steps (128) that I have chosen is just a personal choice and it is free to use another amount of steps.
What you have to make sure in your software is that at step 128 (or any other number you have chosen) you do not let the Triac fire and at say 64 the Triac is open only half of the time (between peak and zero, where peak is halfway between your zerodetections.
The values of 128 and 64 are as you probably understand not lengths of time but just steps in which i divided the total cycle, so if at 128 your lamp is not OFF, somehow you are still firing the TRIAC

It is difficult to exactly tell you how to do that because I do not know the software you are using (C???) and I have no idea what yr program should do, but it is certainly possible with IF statements rather than a loop but then you would not be using loop values 128 and 64 anymore

The software I provided is just an example of how to use the circuit and I have chosen a loop to let the fade on and off and I have done that in an arbitrary128 steps loop. If your software does something completely different and does not use a loop, you need some other input than a loop to determine the firing time of the TRIAC. Hope that helps, but if you have further questions please do not hesitate to ask.
Remember that at 50Hz the phase length is 10ms. To be OFF the phasedelay should be 10ms to be ON it should be 0
karlkr2 years ago
Hi! This is almost the project i am looking for. What i would like to do is drive an AC inductive load, like a motor, with it. Do you think it is possible if I add two snubbers with the coupler and TRIAC where the load is?
Just like in the datasheet of the opto-coupler:

www.datasheetcatalog.org/datasheet/motorola/MOC3021.pdf.

Thanks in advance.
diy_bloke (author)  karlkr2 years ago
Yes that is certainly possible. Snubbers would be advisable. You may want to check this article: http://electronics.stackexchange.com/questions/19273/when-should-i-fire-the-triacs-gate-when-controlling-an-inductive-load-ac-motor
eli60932 years ago
Hi! This looks like a nice project, and I will probably use it as part of my home automation project, but I would just like to know what is the "pinout" of the screw terminals and headers. Thanks in advance!
eli6093 eli60932 years ago
I also would like to know if you could give me some more specific specs about the bridge rectifier, because "400V" could be either "Peak Reverse Voltage" or "Maximum RMS Reverse Voltage". Thanks in advance (again)!
diy_bloke (author)  eli60932 years ago
I have used a bridge labelled as 400 V. as far as I know this is always RMS. In fact one only need 230V RMS but I like a bit of a safety margin. There won't be many peaks with a 4N25 fed through 60k as 'load'
diy_bloke (author)  eli60932 years ago
Hi eli
Thanks for your nice words. I am sorry if the pinout was not clear. It is easy to see though by following the circuit + the pcb has it written on the copper side:
If you look at the components with the terminals to the right, the top one is for the mains connection and the bottem one is for the load (lamp).
Good luck