Instructables

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. (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.

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.

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!


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)
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
ksun411 days 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)  ksun410 days ago

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

ksun411 days 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)  ksun410 days 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)  ksun410 days 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

Knakworst1 month 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)  Knakworst1 month 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)  Knakworst1 month 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)  Knakworst1 month 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_bloke1 month 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

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 mcwareg1 month ago

Sorry, inside:

dim_func()

{

if(ZCD==1)

{

all code

}

}

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)  Knakworst1 month ago

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

OK, no luck so far :(

diy_bloke (author)  Knakworst1 month ago

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

thank you)

xLQAmEM2MHo.jpg
diy_bloke (author)  МихаилК1 month 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)  МихаилК2 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)  МихаилК2 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)  МихаилК2 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)  МихаилК2 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!3 months ago

Thanks diy_bloke

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

virkar1.JPG
diy_bloke (author)  guttih3 months ago

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

rathodmanoj3 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)  rathodmanoj3 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_bloke3 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 :-)

john2355 months ago

is this the same as pulse skipping modulation?

diy_bloke (author)  john2355 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)  egrabhishek4 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)  egrabhishek4 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_bloke4 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)  egrabhishek4 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)  egrabhishek4 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)  egrabhishek4 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)  egrabhishek4 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)  egrabhishek4 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)  egrabhishek4 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)  egrabhishek4 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)  john2355 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_bloke5 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)  john2355 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_bloke5 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)  john2354 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_bloke4 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)  john2354 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_bloke4 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_bloke4 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)  john2354 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_bloke5 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

john2354 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)  john2354 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'

john235 diy_bloke4 months ago
(removed by author or community request)
john235 john2354 months ago

the lamp is still continuously on..can you correct my code

I just want the lamp to go up and down.

while (1)

{

if (ZC){ //zero crossing occurred

for( x=120; x>=5; x--)

{

dimming=x;

PORTC.B0 = 1;

delay_us(250);

PORTC.B0 = 0;

ZC = 0;

}

}

}

diy_bloke (author)  john2354 months ago

John I was just replyig yr removed message :-) and came up with this:

for (int i=5; i <= 128; i++){
if (ZC){
dimming=i;
delay(dimming);
PORTD,B0=1
delay_us(250);
PORTD.BO=0;
ZC=0;
delay(10);
}
}

The reason why yr lamp is continuously on is probably because you have no delay between the different steps

diy_bloke (author)  diy_bloke4 months ago

also.... 'x' is already used in the program. If you let one variable do two loops that might not be a good idea

diy_bloke (author)  diy_bloke4 months ago

and another problem with yr code is that you try to go through yr luminosity loop at every zerocrossing. That means that you will stay at the same level each time

john235 diy_bloke4 months ago

thanks for your time :)
btw, i already test that code, & the lamp is flickering
and not dimming

diy_bloke (author)  john2354 months ago

John, sorry to hear that, but as my knowledge of PIC's is very limited (rather say: non existent), I have come a bit at the end of my rope. I will give it some thought but maybe someone more proficient here can help you. Did you check the edaboard link I gave?
What you could do for now.. go back to the code that had the value '20' for 'dimming' and try a few different values and see how that goes because i get the feeling the problem might be in the loop :-)
Let me know how that goes. :-)

john235 diy_bloke4 months ago

I already post on that site

but no response. You are the only one

who always help me. Thanks diy_bloke :)

diy_bloke (author)  john2354 months ago

well, try the various values for 'dimming' as I suggested and see if the lamp then burns steadily at that one specific level. That way we can pinpoint errors in the code

diy_bloke (author)  diy_bloke4 months ago

mind you, where I write "PORTD,B0=1"
Obviously that should be:
"PORTD.B0=1;" (correcected for full stop and semicolon)

john2354 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!5 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)  iamdebjyoti5 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)  iamdebjyoti5 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.

john2355 months 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)  john2355 months ago

what resistor do you mean?

john235 diy_bloke5 months ago

all of the resistor value. tq

diy_bloke (author)  john2355 months ago

by calculating or knowing what current was needed john235

msyazwan35 months ago

This also function like a camera flash right?

diy_bloke (author)  msyazwan35 months ago

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

mattard15 months 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)  mattard15 months 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)  mattard15 months 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)  mattard15 months 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_bloke5 months 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)  mattard15 months 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

john2355 months 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)  john2355 months ago

check my reply above

diy_bloke (author)  john2355 months ago

check my reply above

john2355 months 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)  john2355 months 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

john235 diy_bloke5 months 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

diy_bloke (author)  john2355 months 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.

john235 diy_bloke5 months ago

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

thanks again!

diy_bloke (author)  john2355 months ago

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

Scipione5 months 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)  Scipione5 months 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_bloke5 months 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)  Scipione5 months 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)  Scipione5 months ago

It is a BT 139. not a T139

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

msyazwan35 months 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)  msyazwan35 months 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')

john2355 months 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)  john2355 months 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

john2355 months 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)  john2355 months 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

john235 diy_bloke5 months 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."

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

diy_bloke (author)  john2355 months 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

john235 diy_bloke5 months ago

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
john235 john2355 months ago

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)  john2355 months 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)  john2355 months 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

john2355 months 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

john235 john2355 months ago

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)  john2355 months 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

john235 diy_bloke5 months ago

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

john235 john2355 months ago

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)  john2355 months 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

john235 diy_bloke5 months ago

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)  john2355 months 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

john2355 months 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)  john2355 months 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.kushwah955 months 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.kushwah955 months 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.kushwah955 months 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.kushwah955 months 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.kushwah955 months 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_bloke5 months 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.kushwah955 months 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.kushwah955 months 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);

}

msyazwan35 months ago

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

diy_bloke (author)  msyazwan35 months 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

msyazwan36 months 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)  msyazwan36 months 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

amidar6 months 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)  amidar6 months 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

amidar diy_bloke6 months ago

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)  amidar6 months 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

amidar diy_bloke6 months ago

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 ?

msyazwan36 months 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)  msyazwan36 months 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

Myp6 months ago

repeated, but it works strange, especially after 28 seconds

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

msyazwan36 months ago

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

diy_bloke (author)  msyazwan36 months 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)  msyazwan36 months ago

I am glad you liked it

msyazwan36 months ago

What type of bridge rectifier you are using?

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

thanks

diy_bloke (author)  msyazwan36 months ago

I am using a DF02 rated at 400 Volts 1 amp

msyazwan36 months 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)  lasanthalikitha7 months 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)  lasanthalikitha7 months ago

my pleasure :-), glad you enjoyed making this

Can i use 4N35 instead of 4N25?

diy_bloke (author)  lasanthalikitha7 months 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 sada7 months 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 sada7 months 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 sada7 months 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 sada7 months 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

ricciolini7 months 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)  ricciolini7 months 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 :)

secretsather7 months ago

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)  secretsather7 months 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_bloke7 months 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_bloke7 months 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

jairson8 months ago

porque el puente rectificador debe ser a 400v??

diy_bloke (author)  jairson8 months 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 :-)

alozano alca8 months ago
Gracias!
diy_bloke (author)  alozano alca8 months ago

my pleasure

harvsch9 months ago
Nicely done.
diy_bloke (author)  harvsch8 months ago
Thank you
gc9n9 months 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)  gc9n9 months 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_bloke9 months ago
OK my 4N25 was upside down, thats why this was happening,,, all good , i continue to my project
diy_bloke (author)  gc9n8 months ago
That explains. We have all been there :)
gc9n diy_bloke9 months 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 gc9n9 months ago
Dimmer circuits typically can only reach about 90% of full brightness on an incandescent light load.
craque9 months 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)  craque9 months 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
craque diy_bloke9 months ago
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)  craque9 months 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
freegreentech9 months ago
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)  freegreentech9 months 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
ekpamaku9 months 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)  ekpamaku9 months 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)  ekpamaku9 months 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)  ekpamaku9 months ago
great :-)
Happy i could be of assistance
mbialkowski19 months ago
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)  mbialkowski19 months 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_bloke9 months 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_bloke9 months ago
oops: where it says 'greepin' that should be 'greenpin'
NikWing10 months 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)  NikWing10 months 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)  NikWing10 months 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
blacktrooper210 months ago
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)  blacktrooper210 months 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)  blacktrooper210 months 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)  blacktrooper210 months ago
yes I understood. I presume the one Watt will solve that. Sorry about the confusuin
ankitjainak4611 months ago
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)  ankitjainak4611 months 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
eelkenet11 months 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)  eelkenet11 months 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
indrakp11 months 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)  indrakp11 months 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
indrakp diy_bloke11 months ago
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)  indrakp11 months 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)  indrakp11 months 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)  blacktrooper21 year 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
karlkr1 year 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)  karlkr1 year 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
eli60931 year 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!
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)  eli60931 year 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)  eli60931 year 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
barshad1 year ago
Can someone please post the eagle schematic files? I tried to make this circuit many time but for me its not working. I am not good in electronics :(
if possible then only with H11A1.
I want to make this circuit so please help me.

Thank you so much,
diy_bloke (author)  barshad1 year ago
what Eagle schematic files do you mean. I did not make it in Eagle, but the circuit in Eagle will look exactly the same as in the circuit provided.

What exactly is not working? Did you use the PCB as provided or did you make your own design?
tell me what is wrong and I will try to guide you through it step by step
Thank you so much for answer.
Yes I am using the PCB as provided. I am not that good to make my own design.

In PCB layout (the black and white one) you are connecting 560ohm resistor with BT136 on top leg but in Step 1 picture 1 you are connecting resistor with middle leg of BT136, which one is right?

In PCB layout (the black and white one) you are load wire with BT136 on top leg but in Step 1 picture 1 you are connecting that middle leg of BT136, which one is right?

Thank you once again for your help and this nice DIY.

Regards,
diy_bloke (author)  barshad1 year ago
Barshad there is a difference between the way a Trica is drawn in a circuit and the way it looks in reality. The circuit shows the gate as the ' middle leg' that is the way it is for all TRIAC's. The Triac I used (I did not use a BT136, but a TIC206) has one of the outer legs as its gate. Check e.g. this image: http://eduardopaulo.no.sapo.pt/TIC%20206%20D.jpg
The same goes for the BT136:
http://www.electronicecircuits.com/wp-content/uploads/2010/04/bt136-triac-pin-configuration-Passivated-sensitive-gate-triac.jpg
deltaman1 year ago
Really nice article for newbs like me to understand how electricity works, keep up the good job. I have a newbie question, if somebody could answer that . In the schematic the 240 v DC is directly fed to the 4n25 opto isolator, my question is isn't this voltage too much for the 4n25 opto - isolator?
I checked the datasheet for the 4n25 and the Max forward voltage is 1.5 v and also the Max current allowed is 60mA. Shouldn't we be using some current limiting resistor and also bring down the voltage to the allowed Max ?
Thanks in advance
diy_bloke (author)  deltaman1 year ago
Hi Deltaman
perhaps I do not understand you completely but there are current limiting resistors that bring the voltage down. They are 30 k each, bringing the total resistance to 60 k. , so the current flowing to the rectifier will be 3,6mA max.
The voltage drop over the resistors therefore sees to it that there will be no 220 Volt fed to teh rectifier and thus only a small voltage will come out of it.
Hi,

There is 2 things I didn't get :
Why in the first delayMicroseconds(34*(255-dim)) the value is 34 ?
Could you explain me why the delay in microseconds is 500 ?

Thanks in advance for your answer,

K
diy_bloke (author)  blacktrooper21 year ago
Hi Blacktrooper
The 2nd piece of Software is -as stated- just provided as is. It was not used or develope by me, I provided it as an example on how other people are doing it. The 500 delay is a random delay that determines the speed of the change the 34 I would not know
deltaman1 year ago
Really nice article for newbs like me to understand how electricity works, keep up the good job. I have a newbie question, if somebody could answer that . In the schematic the 240 v DC is directly fed to the 4n45 opto isolator, my question is isn't this voltage too much for the 4n25 opto - isolator? I checked the datasheet for the 4n25 and the Max forward voltage is 1.5 v and also the Max current allowed is 60mA. Shouldn't we be using some current limiting resistor and also bring down the voltage to the allowed Max .
Thanks in advance
keekisses1 year ago
does it work if i use SCR instead Triac ?
diy_bloke (author)  keekisses1 year ago
@keekisses
No it won't, sorry. An SCR is used to switch DC current. In theory you could use 2 anti-parallel scr's but thet gets complicated. The qyestion arises.. why would you want to?
pul_se1 year ago
Hi diy_bloke,

First I wanted to say thank you, this is exactly what I was looking for and it is AWESOME!
In an effort to reduce the circuit even further I wanted to try out the IL 250, 251 or 252 but before I go ahead and buy any on these I wanted to ask you what is the difference? I see from the data sheet that: "The IL250 has a minimum CTR of 50 %, the IL251 has a minimum CTR of 20 %, and the IL252 has a minimum CTR of 100 %."
I know that CTR stands for Current Transfer Rate but I don't really get which would be the best to use? And how they differ.
As you probably guessed already I am a novice electronics DIY'er.

Referenced Data sheet URL: http://www.vishay.com/docs/83618/83618.pdf

Thanks for the help.
diy_bloke (author)  pul_se1 year ago
Thanks for your kind words. The term current transfer ratio (CTR) defines the relationship of output current, IOUT, to input current, IIN and thus to some extend the sensitivity of the optocoupler.
In circuits like this I usually do not really worry that nuch about the CTR especially not since you only need the IL25x to give a pulse for the interrupt. I think you would be ok with teh 250 or the 252
nabokova1 year ago
I'm sorry for this long silent but work is going to kill me!
However I tried the code you had posted here but it doesn't work for me.
After the fading (in or out) the lamp is totally off and I'm not able to turn it on in any ways.
Now I'm going to buy an RTC module from dx.com. I'll let you know when I receive one of that :)

Bye!

diy_bloke (author)  nabokova1 year ago
Just a question. I presume you tried the code with shorter intervals. Is that where the problem already arose of only at longer intervals
diy_bloke (author)  nabokova1 year ago
sorry to hear that. The code I sent was just quickly put together and I did not test it. It is odd that you would not be able to turn on the light again. I will try to test it myself when I have some time
nabokova1 year ago
Thank you so much, as soon as I get to try it I will let you know the results.
nabokova1 year ago
Thanks for the fast reply.
Sadly an RTC module is a little bit difficult to find in my city and I've to buy it online (waiting for shipping from foreign countries).
Thus for now I can't help but use Arduino just for this project. It would be awesome if you could help me writing a sketch.

PS: By the way I'll use this particular game of lights to simulate sunrise and sunset using a terrarium's spot lamp. Thank you from me and my chameleon :)
diy_bloke (author)  nabokova1 year ago
Replace the 'void loop' with this:

void loop() {
// first we do 123 cycles of 5 seconds=615 secs is abt 10 minutes
for (int i=5; i <= 128; i++){
dimming=i;
delay(5000);
}
// --- now stay on for 8 hrs =28800 secs or 480 minutes-----
for (int i=0; i <=480;i++){
delay(60000);
}
// ---- now fade off in 15 minutes=900 sec hence 123 cycles of 7 secs
for int i=128; i >= 5; i--) {
dimming=i;
delay (7000);
{
//------ now stay off for about 16 hrs=960 minutes-----
for (int i=0; i <=960;i++){
delay(60000);
}
}

This is very crude code, yr arduino wont be able to do anything else while in a delay. You may want to look into the 'Milis' command, use an interrupt or google for arduino software clock.
Also, I did not test this code, you may geta few errors if i forgot a semicolon somewhere, but that should be easy to fix.

Good luck. Still, I advice an RTC, easy to build yourself as well for a few bucks, but also available for a few bucks from e.g. dx.com
diy_bloke (author)  diy_bloke1 year ago
I already notice one mistake. The accolade '{' below 'delay(7000)' should be an '}'
diy_bloke (author)  diy_bloke1 year ago
You may want to read this article: http://www.uchobby.com/index.php/2012/01/21/replacing-delay-in-arduino-sketches-istime-to-the-rescue/
and this one: http://arduino.cc/forum/index.php/topic,37520.0.html
diy_bloke (author)  nabokova1 year ago
OK. i'll give that a try. however, I can be a bit forgetful, so if you have not received anyrhing by februar 1, dont hesitate to send me a reminder
nabokova1 year ago
Hi,

First, I wanted to thank you for this instructable, I followed it carefully and it's been quite useful to me. Now though, I wanted to try something more. I have the need of turning on a 60-80W lamp dimming for about ten minutes and then it has to be on for approximately eight hours. After that it should be turning off in about ten to fifteen minutes and stay off for about sixteen hours. I tried modifying your sketch but being new to PIC electronics (therefore Arduino) my knowledge in this subject are near to zero. Could you point me in the right direction along with a sketch? It would be really appreciated.

Thanks!
diy_bloke (author)  nabokova1 year ago
Thank you for your appreciation.
I would almost start to wonder why you would need such an awkward lighting scheme :-)
Although you could do what you want with a series of delays (but your code would not be able to do anything else) or a timer interrupt, really the easiest thing would be to attach an RTC module which will only be a few dollars, whereas your code without an RTC would be either a bit complicated or leave no room for anything else
diy_bloke (author)  diy_bloke1 year ago
If however you would want to do it all in code, let me know and I'll provide a basic sketch
dazer_r1 year ago
Thank you for your reply. I will try lowering the value to 330 ohms. I do not know how to test the opto triac. Hence all i did was the part that was supposed to have the delayed clock cycle from the arduino, i just placed that part into VCC just to check if i can get the lamp to flicker(as the diac would concduct randomly hence fire the track ditto.)
Just a question, what made you choose the 1k resistor, i.e how did you calculate that value..?
diy_bloke (author)  dazer_r1 year ago
Actually I did not calculate it as there are many circuits available with a variety of resistor values for the TIC226.
Same goes for the BT136. Have seen values between 0 and 1k. Sometimes the BT's seem to profit from a second resistor. You may be helped by this circuit http://www.ostergaard.biz/MrAlvin/ac/AC-board-schematic.jpg

I did not test the MOC as my circuit worked right out of the box, but you may test if th eproblem is in your moc or not by removing it from the socket and shortcircuiting the secundary (high voltage side) pins with a piece of wire. That way the gate of the BT will be connected to mains via the 330-1k resistor. If a lamp then lights up, you know th eproblem is not with yr Triac but with the MOC
diy_bloke (author)  diy_bloke1 year ago
sorry, TIC206 ofcourse
diy_bloke (author) 1 year ago
I am sorry to hear that dazer_r. Let's see if we can get things to work
The 1 k is there to limit the gate current through the Triac.
If your BT136 does not work it may have several reasons.
you may try to lower the 1k resistor to 330 ohm
I was not quite sure how you tested the MOC. Was there a difference in output depending on wether you had the 5V attached ir not? Was the LED ligthing up when you attached 5Volts?
I have heard different stories about wether it would matter where the Load is, but as one can see the TRIAC circuit more or less as a switch in series with the load, I do not think it really matters
You van test the functionality of the TRIAC. Have a look here: http://www.circuitstoday.com/how-to-test-a-triac
dazer_r1 year ago
I cant seem to get the triac to fire whatsoever. Im a bit new to high volatge circuits.
In order to test the high volatge side of the circuit i connected the input of the MOC3021 to 5 volts (i.e anode of the internal led is 5 volts driven through the 220 ohms).
All i can see on the output of my meter is 30 Volts Vac. Im using a BT136 Triac.
I need to know a few things:
1) how can i check if the MOC is working correctly?
2) What is the use of the 1K resistor at one end of the diac?
3) does M1 and M2 matter for the traic cause i read somewhere it does but ive tried both combinations to no effect. What am i doing wrong.
4) How can i test the triac for functionality.

Thanks,
mmilan1 year ago
diy_bloke, by code, I meant something like this. I haven't run this, of course. :) Millisec based timing means 1ms accuracy (flicker?), and 10 step dimming (to few?). The millis() call can be replaced with micros() - then extra care sould be taken because of the numeric overflow after 70 minutes. (35 mins. I have used signed variables.)

// setup
#define PIN_ZEROCROSSING 2
#define LIGHT_COUNT 4
byte pinLights[LIGHT_COUNT] = { 3, 4, 5, 6 };

// running parameters
byte lightDelay[LIGHT_COUNT]; // 0-9ms out of 10ms

// state management
long zeroCrossingCooldown;
long lightSetAt[LIGHT_COUNT];
long lightClearAt[LIGHT_COUNT];

void setup()
{
  pinMode(PIN_ZEROCROSSING, INPUT);
  for (byte i = 0; i < LIGHT_COUNT; ++i)
  {
    pinMode(pinLights[i], OUTPUT);
    digitalWrite(pinLights[i], LOW);
  }
}

void loop()
{
  long runStart = millis();
  // check for new phase
  if (runStart >= zeroCrossingCooldown && digitalRead(PIN_ZEROCROSSING) == HIGH)
  {
    for (byte i = 0; i < LIGHT_COUNT; ++i)
      lightSetAt[i] = runStart+(long)lightDelay[i];     
    zeroCrossingCooldown = runStart + 5; // plus 5ms garantees jump to the next phase, expected 10ms later
  }
  // set/clear lights
  for (byte i = 0; i < LIGHT_COUNT; ++i)
  {
    if (lightSetAt[i] && runStart >= lightSetAt[i])
    {
      digitalWrite(pinLights[i], HIGH);
      lightSetAt[i] = 0;
      lightClearAt[i] = runStart+1;
    }
    if (lightClearAt[i] && runStart >= lightClearAt[i])
    {
      digitalWrite(pinLights[i], LOW);
      lightClearAt[i] = 0;
    }
  }
  // play the song
  for (byte i = 0; i < LIGHT_COUNT; ++i)
    lightDelay[i] = 8-(runStart/250)%(9-i);
}
diy_bloke (author)  mmilan1 year ago
Looks interesting but ofcourse need to see it run :-) 10 steps might be OK, my 1 channel software had 128 steps, but that could be too much
mmilan1 year ago
diy_bloke, thank you for your reply!

The processing power of the arduino is the only one I'm not concerned about. :) It needs definitely a new code, without delay()-s. I might not get 8 bit accuracy, but I don't think the bulbs will flicker.

The DC way seems more expensive to me just because I have to buy a power supply too.

(I can't reply properly under your text, no captcha shows up to type in...)
diy_bloke (author)  mmilan1 year ago
Thanks for your reply. I understand your point about the DC, but if you already have 24 V AC, maybe all it needs would be a bridge and a snmoothing capacitor. Nevertheless, would be interesting to see yr code. I have something for 3 lamps, I guess 4 lamps would not be so much extra :-)
mmilan1 year ago
Hello, I'd like to slightly modify this to my needs and local store stock. Please correct me before I set some christmas fire. :)

- using H11AA1 to eliminate the bridge rectifier
- using BT136 to save cost
- I've got 24V AC input (may save life :)), so I have to replace 2x30k resistors with 2x3.3k? Anything else (560Ohm resistor) needs modification?
- To drive 4 channels, just replicate the driver without shortcuts? I mean, for example, is there an array of 2 or 4 MOC3021's or BT136's in one part available?

Sorry for my bad English and thank you in anticipation!
diy_bloke (author)  mmilan1 year ago
Hi Mmilan. Nothing wrong with your English.
In using the H11AA1, you best aim at a current of 10-20mA, so one resistor of 2k4 (2k2) or 1k1 would be ok. It does not need to be 2 resistors. I only did that in order to divide the power dissipation.
With regard to the '560 Ohm' resistor, you need to make sure that the 24 Volts in combination with the gate resistor can still deliver that Gate trigger current which for the BT136 is I think between 5 and 25 mA so you have a good chance that 560 is OK, but if I were you I'd make it a 470.
I think your best bet would be to just replicate the TRIAC circuit 4 times. There are as far as I know Quad optoisolators (CNY74-4, ILQ1, ILQ55, ILQ74, K847P) but I do not know of any double or quad TRIACs.

With regard to the BT136, it is usually cheaper than the TIC206 (up to more than 2 times cheaper (1.20 euro vs 0.50 euro), But I have seen shops that were substantially more expensive with both, with the BT136 even being the most expensive.
You may consider using the T1M5F600A (1A 600V) (watch the different pin lay out though) as that is available for 0.20 euro, but ofcourse you could only use a max of 24 Watts then while the BT136 allows you 98 Watts

As a matter of fact, I am currently designing a 3channel dimmer (RGB) . Realise though that for serous use, your microcontroller will need to do a lot of work with 4 channels so it wont have much time for much else
diy_bloke (author)  diy_bloke1 year ago
Just a thought.... if you go for 24 Volts, you might be better of using DC current because you need no phasesyncing then. A powertransistor is sufficient, you can then open and close the powertransistor with PWM. MAkes the software and the hardware easier
diy_bloke (author)  diy_bloke1 year ago
The attached circuit is meant for LEDs but could easily be used for 24 Volt lamps as well
led-driver4.JPG
diy_bloke (author)  diy_bloke1 year ago
You may want to look at this circuit, just for reference:
http://www.pindari.com/triac.html
voor some calculations you may check here: http://www.simpleio.com/design/triacout/AppTriacOutGateResistor.asp
Ronh1231 year ago
Hello, Anyone who can help me building one or two of these dimmers. It's for a test with a Arduino board and I don't like to spend a lot of money on a test.
Power and soldering is no problemn but I'm no electronical expert.
I presume I can find the parts, but need to know how to connect the Arduino and what load I can put on the board on 220/230 volt.
Thanks RonH - ronh@freeler.nl
diy_bloke (author)  Ronh1231 year ago
Hi Ron
Just so I understand.... you can build them yourself but you need someone to tell you how to connect them with the Arduino?
It kinda says in the text. The zero crossing signal goes to D2 and the signal to steer the Triac comes from D3 although you can change that.

The load is depending on the Triac used a TIC206 can endure 4 amps continuously and thus supply 880 Watt. If you want to do that however, I would advise to solder a seperate copper core over the PCB tracks leading to the Triac Terminals (not the gate)
Does that answer your question or do you need more help
mayank07381 year ago
Nice work!!
diy_bloke (author)  mayank07381 year ago
Thanks!
bx19tri1 year ago
The 30 k resistors will burn up 440 mW each, not 200, which means they will get pretty hot.

It is better use an optocoupler with a low-current led (and darlington output), such as a 6N138 or 6N139. These work with currents as low as 0.5 mA, so the two 30k resistors can be replaced by 100k or even 200k. Unfortunately they are not pin compatible with the 4n25.

Idea and picture from http://www.circuitsonline.net/forum/view/84403 .
6n138-zerocrossdetector.png
diy_bloke (author)  bx19tri1 year ago
You could use the lesser known 4N32 or 4N33, these will have enough with 1mA and they are pin compatible with the 4n25. The 4N32 and 4N33 are both photdarlingtons as well, like the 6N138
diy_bloke (author)  bx19tri1 year ago
Tnx bx19tri. I have done so many calculations that I could very well have had the wrong number in my head. let's see. roughly speaking there will be a current of 220/60k=0,0036 Ampere (3,6 mA) that is a power of 0,0036*0,0036*30.000= 400mW. Seems you are right. I knew there was a reason why I had chosen 1/2 Watt resistors. :-)

Thanks for pointing it out. I will correct it.

I know the circuit with the 6N318 and that certainly will work too. Too bad that it is not pincompatible indeed :-)
Nevertheless, it is a very easy print design people can easily adapt it. If I find the time I may do it myself.

Another option of course is to feed the 4N25 from the secundary side of a transformer as I suggested earlier.

I Have not had any problems with the resistors even after Ietting the circuit on for many hours.
thin1 year ago
finally i found something - this looks so great !

i am pretty new to the matter of making pcb's and driving them with a microcontroller, so please excuse my newbie questions.

leaving out the programming side, would it be possible to build -and drive- a bank of 6 of these dimmers with an arduino, too?
for an indoor light installation i need a tiny control unit for 6 small 220V lamps. before i could use a rented stage dimmer, which is huge and expensive, but now i need to transform it to a cosmetic and permanent installation on a low cost level.

somehow i can't find on my german suppliers' sites (reichelt.de or conrad.de) neither the bridge rectifier nor the H11AA11 (which i would prefer because it possibly could make the pcb smaller (if i manage to transform it).
what do i need to look for?

thanks again for this great tutorial!
diy_bloke (author)  thin1 year ago
Peter I found about 100 bridgerectifiers at reichelt.de, whereas Conrad.de had about 200. I am sure you know look for "Brückengleichrichter"
diy_bloke (author)  thin1 year ago
Yes that is definitely possible. You would still need only 1 zero crossing signal, but you should not let the arduino do much other stuff coz timing could get a bit critical.
I am surprised that reichelt or conrad would not have a small bridge rectifier it is such a standard component.
If you are going to build this as a stand alone unit with power drawn from a transformer, you mau want to consider drawing your zero crossing signal from the secundary end of that transformer as well as it eliminates another point of touch for 220Volts.

If you ahve any questions left, dont hesitate to ask
diy_bloke (author) 1 year ago
Peter,
If you want to pick up the zero crossing from the secundary side of the transformer, you could use something like this:
voeding2.JPG
davebe1 year ago
A nice board. One problem with 220V AC is that the dissipation increases in the zero crossing circuit. You can also use a zero crossing opto to get both transitions.

I've written a library for driving a triac which would probably work well with your hardware.

see http://www.rotwang.co.uk/projects/kettle.html
diy_bloke (author)  davebe1 year ago
Dave, I found your project quite interesting. I also had consideredpicking up the interrupt from the secundary side of the transformer in the psu but as i currently feed all my controllers with a wallwart that was not quite possible + I wanted to make a satndalone board and that was a bit easier as a project for instructables as well.
For a dedicated system with its own transformer it is surely a good idea as it limits any possible contact with the mains a bit more.
I saw that you used a 3020 that has no zero crossing either I belive, but maybe you already tried.

No doubt your library will work with my board. My software uses interrupt '0' and yours interrupt 1, but as mine is a seperate board one is free to connect the zeroX-ing signal to any pin one likes.

I am no expert in writing libraries, but maybe it would not be so hard to adapt your libary so as to make it possible to create more instances of 'TRIAC' for steering of additional triacs or even to chose the interrupt pin. Maybe I will give that a try as practice of learning to write libraries.

I had considered the H11AA1M optocoupler as well as it saves a bridge rectifier, but I could not easily find it and presuemed that would go for other people as well so that is why i added the bridge rectifier (also a 4n25+rectifier was still cheaper than the H11AA1M).

Anyway in the mean time I found some other circuits about dimming an AC load with the arduino and most seem to use the 3020 series and the 3021 is working for me.

I wanted to add a video but would have to put that on youtube which might be a bit odd to have a picture of a fluctuating lamp there. Maybe i will put it somewhere else :-)

I also came across another progarm that could easily be used on this board and that allows dimming via the serial port. I will add it here and I will adapt it for the software step after I test it:
int AC_pin = 10;
//Pin to MOC3020 - OptoTriac
byte 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);
}
if (dim > 254) { //Turn TRIAC completely ON if dim is 255
digitalWrite(AC_pin, HIGH);
}
}
if (dim > 0 && dim < 255) {
//Dimming part, if dim is not 0 and not 255
delayMicroseconds(34*(255-dim));
digitalWrite(AC_pin, HIGH);
delayMicroseconds(500);
digitalWrite(AC_pin, LOW);
}
}
void loop() { }
diy_bloke (author)  davebe1 year ago
Thanks Dave,
You may be right. I took a non zerocrossing opto for the TRIAc because I get my trigger signal already from the zerocrossing (via the 4N25. As there is a slight delay in processing, I feared that subsequently steering another zerocrossing optoisolater (the 3021). would mean that that would wait for the next zerocrossing and screw up things.
Nevertheless it could mean that each signal is delayed 1/2 a period and that would be ok.
It is simple to test as the MOC3021 and MOC3041 are pin compatible so i can just pop in a zerocrossing opto and see what happens

I am gonna have a look at your library. Is that suitable for the IDE 1.0?
ddoss1 year ago
Nice !
diy_bloke (author)  ddoss1 year ago
Thank you ddos :-)