Arduino UNO code for fast PWM mode 7



#include <avr/io.h>
#include <util/delay.h>

int potinputval = A0;
volatile int duty; 

void setup() {

// WGM22/WGM21/WGM20 all set -> Mode 7, fast PWM 
  TCCR2A = (1 << COM2B1) + (1 << WGM21) + (1 << WGM20); // Set OC2B at bottom, clear OC2B at compare match
  TCCR2B = (1 << CS20) + (1 << WGM22); // prescaler = 1, result = 61KHz 
  OCR2A = 249;
  OCR2B = 49;
  DDRD |= (1 << PD3);  // fast pwm output at OC2B, physical pin 5
  pinMode(potinputval, INPUT);
  duty = 0;
  delay(100);
}

void loop() {
  potinputval = analogRead(A0);
  duty = map(potinputval, 0, 1023, 0, 255);
  // duty cycle of 65% gives the best result = 61 volt without load.
  duty = constrain(duty, 5, 163);
  OCR2B = duty;
  delay(100);
}