0

I have an Arduino UNO with Atmega 328 SMD, and I am trying to use PWM, but by setting registers, not using analogWrite(). My code is:

DDRD |= (1 << PORTD6); //Setting pin D6 as output
OCR0A = 128; //50% duty cycle
TCCR0A |= (1 << COM0A1)|(1 << WGM01)|(1 << WGM00); //setting mode and fast pwm
TCCR0B |= (1 << CS01); //setting the prescaler to 8, which should yield PWM with frequency of 8 kHz

The problem is with the last line. No matter what I do, it results in PWM with frequency of 1 kHz. Setting different prescaler bits just yield 1 kHz PWM again. I was thinking that maybe its because I am programming this in Arduino IDE, and I kHz is Arduinos default frequency? Or where am I making the mistake? Thanks for any answers.

  • but when I write this instead of the last line, it works: TCCR0B = TCCR0B & B11111000 | B00000010; – user72028 Jan 28 '16 at 16:59
5

Your code assumes that TCCR0n are zero. But what if they are not. What if there is some hidden initialization?

Timer0 is used by the Arduino micro/millis counter and the prescale (TCCR0B) is initiated by setting bits CS00 and CS01 in init() before setup() is called.

If you really want to use Timer0 you will need to set/clear all the prescale bits. Alternatively clear the register before setting any bit.

  • 1
    To clarify; |= doesn't overwrite any previously set bits. So instead you should use =. – Gerben Jan 28 '16 at 17:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.