I'm using Timer1 on the Attiny85 clocked at 1MHz to toggle an LED every 1 second. However, I'm having some issues regarding prescaler and OSC value selection.
I'm using this formula, which I found in the datasheet for the Attiny.
fOCnx = fclk/(2*N*(1+OCRnx))
N = Prescaler
I'm taking fOCnx = 0.5Hz as I want a square wave
So based on the above formula, I tried the following cases
- N = 2048, OCR1C = 243
- N = 4096, OCR1C = 122
- N = 8192, OCR1C = 61
- N = 16384, OCR1C = 30
The LED toggles after an interval of 1s for cases 3 and 4. However, for cases 1 and, it seems to toggle after 2 seconds. Can anyone tell me why this is happening? Eventually, I want to use this to time data acquisition from a sensor I have so I need to be accurate.
Here's my code
#include <SoftwareSerial.h>
int ledPin = 1;
int state = 0;
SoftwareSerial ser(3, 4);
void setup() {
// put your setup code here, to run once:
TCCR1 |= 0x8F;
OCR1C = 30;
TIMSK = (1 << OCIE1A);
pinMode(ledPin, OUTPUT);
ser.begin(9600);
}
ISR(TIMER1_COMPA_vect)
{
state = !state;
digitalWrite(ledPin, state);
ser.println(state);
}
void loop() {
// put your main code here, to run repeatedly:
}
fOCnx = fclk/(2*N*(1+OCRnx))
I mean I have no glue why it is in the nominator of the fraction. If I I insert one of the value pairs above I get 1 Hz. If I multiply both sides with 2. I get 2 Herz but not 0.5 Hz. Do you see my problem?