// https://forum.arduino.cc/t/complementary-pwm-signals-at-50-khz-with-dead-time/1081473/
// Code by John Wasser
// Changes: TOP from 159 to 160 for Wokwi, generate changing PWM in the loop.

// 24 January 2023:
// Wokwi simulation needs 160 and in real life 159 is needed for the TOP.
// Issue on Github: https://github.com/wokwi/avr8js/issues/137


// Generating Two 180° Out of Phase 50 kHz Square 
// Waves with dead time on Timer1 of an 
// Arduino UNO (Pins 9 and 10)
// Written January 23rd, 2023 by John Wasser

const unsigned TOP = 159;      // 159 for 50kHz, Wokwi needs 160
int delta = 10;

void setup()
{
  // Stop Timer/Counter1
  TCCR1A = 0;  // Timer/Counter1 Control Register A
  TCCR1B = 0;  // Timer/Counter1 Control Register B
  TIMSK1 = 0;  // Timer/Counter1 Interrupt Mask Register

  // Set Timer/Counter1 to Waveform Generation Mode 8:
  // Phase and Frequency correct PWM with TOP set by ICR1
  TCCR1B |= _BV(WGM13) | _BV(CS11);                 // WGM=8, Divider=8
  TCCR1A |= _BV(COM1A1);                // Normal PWM on Pin 9
  TCCR1A |= _BV(COM1B1) | _BV(COM1B0);  // Inverted PWM on Pin 10

  ICR1 = TOP;
  // Difference between OCR1A and OCR1B is Dead Time
  OCR1A = (TOP / 2) - 8;
  OCR1B = (TOP / 2) + 8;

  // Start timer by setting the clock-select bits to non-zero
  TCCR1B |= _BV(CS10);   // prescale = 1

  cli();
  DDRD = 0xff;
  for (;;) {
    PORTD = TCNT1L;
    asm("nop");
    asm("nop");
    asm("nop");
  }
}

void loop() 
{
}
D0D1D2D3D4D5D6D7GNDLOGIC