Hi Forum. I have copied and pasted this apparently ultra simple code for blinking a led inside the loop using 16-bit timer 1 of an Arduino Uno.
For some reason the code provided by GolamMostafa in a reply does not work for me. Just copying and pasting it gives me a period of 2ms not 50ms. Could you please try it at home? it takes only 4seconds to try.
Here the code and the reference:
https://forum.arduino.cc/t/using-timer1-to-blink-a-led-once-per-second-for-50ms/588721/5
And here is the code with Direct Port Manipulation to not waste time with Digital Read and Write routine.
void setup()
{
Serial.begin(9600);
DDRB |= B00110000; // set pin12&pin13 to output without affecting other pins
TCCR1A = 0x00;
TCCR1B = 0x00;
TCNT1 = 0xF3CB; //pre-set value at clkTC1 = 16 MHz/256
TCCR1B = 0x04; //TC1 is running
}
void loop()
{
while (bitRead(TIFR1, 0) != HIGH) //checking if TOV1 flag is active; see data sheets for TIFR1 Register
{
; //wait until TOV1 becomes active at the elapse of 50 ms time
}
bitClear(TIFR1, 0); //clear TOV1 flag
TCNT1 = 0xF3CB; //reload pre-set value
PORTB ^= B00110000;// toggles bit which affects pin13&12
}
It gives me a period of 2us. ( 2 microseconds) Any help Appreciated. Regards.
I am wondering why he does not use WGM4 or 12 and using OCR1A or ICR1 register.
Instead he sets with TCCR1B to 0x04 the 256 prescaler only..
Seems at first glance it does to enter the while (bitRead(TIFR1, 0) != HIGH) loop
Could you please help me?
Bets regards