#include "TimerHelpers.h" // https://www.gammon.com.au/forum/?id=11504
// for https://forum.arduino.cc/t/two-pwm-signals-on-pins-9-and-10-with-input-on-a1-signals-need-to-be-180-degrees-apart/1280072/4?u=davex
const unsigned long duty = 30;
void setup() {
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
TCCR1A = 0; // reset timer 1
TCCR1B = 0;
// set up Timer 1
Timer1::setMode (8, Timer1::PRESCALE_256, Timer1::CLEAR_A_ON_COMPARE | Timer1::SET_B_ON_COMPARE);
ICR1 = 31250; // 31250 -> 1Hz Sets frequency with prescaler as f=F_CPU/PRESCALE/ICR/2
// ICR1 = 250; // 250 -> 32kHz w PRESCALE_1 Sets frequency with prescaler as f=F_CPU/PRESCALE/ICR/2
TCNT1 = 0; // reset counter
OCR1A = ICR1 * duty / 100; // compare A register value
//OCR1B = OCR1A;
OCR1B = ICR1 - OCR1A; // compare B register value
Serial.begin(115200);
reportTimer1();
}
void loop() {
static int lastADC = -1;
int pot = analogRead(A0);
if(pot != lastADC){ // change detection on potentiometer
lastADC = pot;
OCR1A = ICR1 * 1UL * pot/1023; // duty cycle
OCR1B = ICR1 - OCR1A; // complement for inversion
reportTimer1();
}
}
void reportTimer1(void){
Serial.print("TCCR1A:0b");
Serial.println(TCCR1A, BIN);
Serial.print("TCCR1B:0b");
Serial.println(TCCR1B, BIN);
Serial.print("ICR1:");
Serial.println(ICR1);
Serial.print("OCR1A:");
Serial.println(OCR1A);
Serial.print("OCR1B:");
Serial.println(OCR1B);
Serial.print("Duty:");
Serial.println(OCR1A*100.0/ICR1,3);
Serial.print("Freq:");
Serial.print(F_CPU / 256.0 / ICR1 / 2, 4);
Serial.println("Hz\n");
}