#include <TimerOne.h>
const int pin1 = 9; // Timer1 uses pin 9 and 10 for most Arduino boards
const int pin2 = 10;
const long frequency = 50; // 50Hz
const long period = 1000000 / frequency; // in microseconds
const long halfPeriod = period / 2;
const long pulseWidth = halfPeriod - 2; // Deducting 2 microseconds for the deadtime
void setup() {
pinMode(pin1, OUTPUT);
pinMode(pin2, OUTPUT);
// Set up Timer1
Timer1.initialize(period);
// Set the PWM period for each pin
Timer1.pwm(pin1, 512); // 50% duty cycle
Timer1.setPwmDuty(pin2, 512); // Set the duty but do not start it yet
// We create a manual interrupt to precisely control the phase difference
Timer1.attachInterrupt(togglePins);
}
void togglePins() {
static bool toggleState = false;
if(toggleState) {
digitalWrite(pin1, HIGH);
delayMicroseconds(pulseWidth);
digitalWrite(pin1, LOW);
} else {
digitalWrite(pin2, HIGH);
delayMicroseconds(pulseWidth);
digitalWrite(pin2, LOW);
} toggleState = !toggleState; // Switch states
} void loop() {
// No logic in loop. The Timer1 library and ISR handle the toggling.
}