// 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 to get exactly 50kHz. Changing PWM in the loop.
// 24 January 2023:
// I thought there was a difference between Wokwi simulation and real life.
// Because of that, I made an Issue on Github:
// https://github.com/wokwi/avr8js/issues/137
// It turned out that my measurements was wrong and Wokwi did it right.
// 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
// frequency = 16MHz / (2 * prescaleFactor * (TOP + 1))
const unsigned TOP = 160; // 160 for exactly 50kHz
// frequency = 16MHz / (2 * 1 * 160)
// frequency = 16MHz / 320
// frequency = 50,000
int delta = 10;
void setup()
{
Serial.begin(115200);
delay(200);
digitalWrite(9, LOW);
pinMode(9, OUTPUT);
digitalWrite(10, LOW);
pinMode(10, OUTPUT);
// 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); // WGM=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
}
void loop()
{
// Should I turn off something while changing OCR1A and OCR1B ?
OCR1A += delta;
OCR1B += delta;
if( OCR1A < 20 or OCR1A > (TOP-20))
delta = -delta;
delayMicroseconds(20);
}