Dimming LED using ZCD

Hi community,

Im trying to dim a LED using zero cross detection, but cant make it work.


Here is my connection diagram, exept i havent used the trafo yet.

And here is the software:

int mydelay = 0;
int myvalue=0;
int last_CH1_state = 0;

void setup() {
  // put your setup code here, to run once:

  PCICR |= (1 << PCIE0);                                      
  PCMSK0 |= (1 << PCINT0);
  pinMode(3,OUTPUT); 

}

void loop() {
  // put your main code here, to run repeatedly:

 myvalue = map(analogRead(A0),0,1024,10000,10);
    if (mydelay)
    {
      delayMicroseconds(myvalue);
      digitalWrite(3,HIGH);       // Fire triac
      delayMicroseconds(100);  
      digitalWrite(3,LOW);        // Triac off
      mydelay=0;                
    } 

}

//Interruption routine:
 
ISR(PCINT0_vect){
//Input from optoisolator:
  if(PINB & B00000001){                //Is pin 8 is HIGH?
    if(last_CH1_state == 0){           //If the last state was 0, then there is a state change!
      mydelay=1;                       //Yes, it is
    }
  }
  else if(last_CH1_state == 1){        //If pin 8 is LOW and the last state was HIGH then we have a state change      
    mydelay=1;                         //We have detected a state change!
    last_CH1_state = 0;                //Store the current state into the last state for the next loop (reset)
    }
}

Any help will be highly appriciated, im new to Arduino!
:slight_smile:

Welcome to the forum

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the </> icon above the compose window) to make it easier to read and copy for examination

is your AC bulb dimmable?

Hi Juraj,

Yes, i have dimmed it using DALI before..
Here is my phsyical connection:

I am coder so I use electronic modules. I will not comment on the circuit.

mydelay is changed in the interrupt and should be declared volatile. It's better declared as a byte if you are not going to protect the access

//int mydelay = 0;
volatile byte mydelay = 0;

The state is never set to one, so this conditional is never entered. You are only going to be chopping your wave on one half of the cycle.

else if(last_CH1_state == 1){

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.