Go Down

Topic: Frequency Generator (Read 968 times) previous topic - next topic


I am using the Arduino Uno to generate different frequency square waves to modulate an LED. I am using the toggle on compare match mode of the 16MHz clock on the ATMega 328 to do this. The datasheet for the ATMega 328 has a nice formula for calculating the OCRnA register value needed to generate the desired output frequency. When I calculate the register value and hardcode the OCR1A register, for 500Hz the register value is 1999, it outputs the correct frequency. What I would like to do is just to have a int variable frequency where I can simply enter 500 and then it will calculate the OCR1A value but when I try to implement this the frequency that is outputted is random. I can't seem to figure out why this is. Here is a little bit of my code:
For 500Hz
//This works
OCR1A =1999 ;

//This doesn't work
int freq = 500;
int eq = ((16*10^6)/(2*8*500))-1; //This is the formula from the datasheet and
                                              // what I used to get 1999 above
OCR1A = eq;

Can anyone see what I am doing wrong? Thanks in advance.


Don't send me technical questions via Private Message.



Please post technical questions on the forum, not by personal message. Thanks!

More info: http://www.gammon.com.au/electronics

Go Up