Hi guys,
I'm struggling with a problem that seems easy.
My goal is to create a variable that will be changed by timer0
. I need this variable for further PWM signal generation.
So far:
1.Basic frequency = 16 MHz
2.My prescaler is 1024, so the output clock frequency is 15.625 kHz
3.My timer0
is set as phase correct, so counting is 0...255...0 (510 steps) for one cycle.
4.full count 0...255...0 takes 1/30 s (15.625 kHz/510 ≈ 30 Hz)
5.After 1 full count, my variable will increase by 1. If it reaches 255, it decreases by 1 to 0 and then increases again like the timer, but at a slower frequency.
The program seems very easy:
- First, the clock is set up.
- Secondly, timer overflow is being checked.
int16_t duty = 0, value = 1;
void setup() {
TCCR0A |= (1 << WGM00); // WGM02:0 - counting type bits for timer 0, 001 - phase correct TOP = 0xFF (Flag TOV0 is activated when the timer reaches BOTTOM)
TCCR0A &= ~(1 << WGM01);
TCCR0B &= ~(1 << WGM02);
TCCR0B |= (1 << CS00); // CS02:0 - clock source and prescaler. Fout = (Fclk/prescaler). 101 - prescaler-> 1024. 15.625 kHz = (16 MHz/1024)
TCCR0B |= (1 << CS01);
TCCR0B &= ~(1 << CS02);
Serial.begin(1000000);
}
void loop() {
if (TIFR0 & (1 << TOV0)) {
TIFR0 |= (1 << TOV0); // Overflow flag reset by writing 1 to it.
duty += value;
if (duty == 0 || duty == 255) {
value = value * (-1);
}
}
Serial.println("Timer = " + String(TCNT0) + ", Flag = " + String(TOV0) + ", duty = " + String(duty) + ", value = " + String(value));
}
BUT the problem is that the flag is ALWAYS 0, and my code cannot work properly.
Here are the readings from serial communication:
Timer = 4, Flag = 0, duty = 0, value = 1
Timer = 16, Flag = 0, duty = 0, value = 1
Timer = 29, Flag = 0, duty = 0, value = 1
...
Timer = 9, Flag = 0, duty = 0, value = 1
Timer = 4, Flag = 0, duty = 0, value = 1
Timer = 16, Flag = 0, duty = 0, value = 1