Electronic – Control PWM with potentiometer using atmega328p

adcatmegaavrpwm

I'm using an atmega328p and I want to control the PWM duty cycle with a potentiometer.

The frequency is 20ms and the duty cycle is between 0 ms and 2 ms.
Problem : when I simulate this in Proteus the PWM did not work, this is my code:

#ifndef F_CPU
#define F_CPU 16000000UL // 16 MHz clock speed
#endif

#include <avr/io.h>
#include <avr/interrupt.h>


int main(void)
{
    DDRB |= 1<< PINB1 ;

    TCCR1A |= 1<< COM1A0 | 1<< COM1A1 | 1<<WGM11 ;
    TCCR1B |= 1<< WGM12 | 1<<WGM13 | 1<<CS10 | 1<<CS11 ;
    ICR1 = 4999 ; // 50 Hz

    ADCSRA |= 1<<ADEN | 1<< ADIE | 1<<ADPS2 | 1<<ADPS1 ;  // 64 prescaler
    ADMUX |= REFS0 ;
    sei();
    ADCSRA |= 1<<ADSC ;
    while (1) 
    {
    }
}

ISR(ADC_vect)
{
 uint8_t low = ADCL ;
 uint16_t tenvar = ADCH << 8 | low ;  // value from potentiometer 10 bit

 OCR1A = 4999 - ((499/1024)*tenvar ); // OCR1A is between 4999 and 4500 (4500 represent 2ms )


 ADCSRA |= 1<< ADSC ;
 }

Best Answer

((499/1024)*tenvar )

Oops.

(tenvar * 499L / 1024)

Unless you really don't care about the result always being 0.