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.

Gerben
11.3k3 gold badges22 silver badges34 bronze badges
asked Jan 28, 2016 at 16:48
1
  • but when I write this instead of the last line, it works: TCCR0B = TCCR0B & B11111000 | B00000010; Commented Jan 28, 2016 at 16:59

1 Answer 1

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.

answered Jan 28, 2016 at 17:02
1
  • 1
    To clarify; |= doesn't overwrite any previously set bits. So instead you should use =. Commented Jan 28, 2016 at 17:06

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.