Problems with interruptions and synchronization

Very good with everyone. My problem is how to synchronize a pwm with registers to an external interrupt using switch mode. I would like that every time the interrupt occurs in int0 the pwm is started according to the duty cycle. I am using arduino uno. and 60hz frequency

1-. I would like it to be as follows as shown in sync

2-.This is the result that shows me the pwm signal is out of sync.

#define f 60

unsigned int conv = 0;
unsigned int maximo = 0;

volatile boolean zero_cross=0;// indica cruce cero

int value = 0;
void setup() {
  attachInterrupt(0, zero_cross_detect, RISING);

  pinMode(9, OUTPUT);
  pinMode(4, OUTPUT);
 
  cli();
  TCCR1A = 0B10000000;
  TCCR1B = 0B00010001;

  //maximo = (16e6/(2*f))-1; //
 maximo = 65535;  // 60 hz
 // ICR1 = maximo;
  ICR1 = maximo;

  //OCR1A = maximo >> 1;
  OCR1A = maximo >> 1;

  TIMSK1 = 0B00100000;
  sei();

}

void loop() {
  digitalWrite(4, HIGH);
  delay(10);
digitalWrite(4, LOW);
 delay(10);

ISR (TIMER1_CAPT_vect)
{
  conv = analogRead(A0);
  conv = map(conv,0,1023,0,maximo);
// conv = (6000*65535)/8500;

  OCR1A = conv;
  
   //zero_cross=false; 
}
void zero_cross_detect() {
   
  zero_cross = true;               //señal de cruce cero
  

Your topic was MOVED to its current forum category as it is more suitable than the original

When you write about synchronizing a output to a input signal, then I think: "PLL".
That is not easy: https://arduino.stackexchange.com/questions/13499/can-i-implement-a-pll-on-an-arduino

Your 8200 microseconds is too fast. 1/2 of a 60 Hz wave is 8333.333... microseconds.

16 MHz / 120 Hz is 133333.333... system clock cycles per PWM cycle.

133k won't fit in a 16-bit timer so you need a prescale of at least 2.03. The smallest prescale is 8 so the timer will be running at 2 MHz.

2 MHz / 120 Hz = 16666.66 so we set TOP to 16667 - 1.

I think I would use the Input Capture feature of Timer1 to measure the difference between the Input Capture interrupt and the expected timer count. If the zero crossing is early, add a bit to the timer so the PWM goes a little faster. If the zero croing i slow, subtract a bit from the timer so the PWM goes a little faster.

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