I have an atmega168a chip. I use Counter 0 to toggle PORTC by using ISR(TIMER0_COMPA_vect) and ISR(TIMERB_COMPA_vect) interrupt sub-routines. I would like to activate the 16-bit timer when if condition is true. So, I use TIMSK1 = (1<<OCIE1A), but this line calls ISR(TIMER1_COMPA_vect) interrupt instantly where I want 16 bit timer to be interrupted only when the counter reaches to OCR1A value. How can I activate the 16-bit timer on the run-time without causing an instant interrupt?
here is my code:
#define F_CPU 8000000
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdint.h>
volatile uint8_t counter;
int main (void){
DDRC = 0xFF; //sets PORTC as output
PORTC = 0xFF; //initial output value
/*COUNTER0 settings*/
TIMSK0 = ((1<<OCIE0A) | (1<<OCIE0B)); // Enable Interrupt TimerCounter0 Compare Match A & B
TCCR0A = (1<<WGM01); // Mode = CTC
TCCR0B = (1<<CS01) | (1<<CS00); // Clock/64, 1/(8000000/64)= 0.000008 seconds per tick
OCR0A = 200; // 0.000008 *230 = 1.6 ms
OCR0B = 100; // 0.8 ms
/*16bit timer - counter1 settings*/
TIMSK1 &= ~(1<<OCIE1A); // Disable Interrupt Counter 1, output compare A (TIMER1_CMPA_vect)
TCCR1B = ((1<<CS12) | (1<<CS10) | (1<<WGM12)); // Clock/1024, 1/(8000000/1024) = 0.000128 seconds per tick, Mode=CTC
OCR1A = 40; // 0.000128*40 ~= 5.12 milliseconds
sei(); //interrupts are globally switched on
counter =0;
while(1){
if(counter >= 4){
TCNT1 = 0; // clear the counter 1
TIMSK1 = (1<<OCIE1A);// Enables the interrupt for Counter 1,(TIMER1_CMPA_vect)
TIMSK0 &= ~((1<<OCIE0A) | (1<<OCIE0B)); //disables the Counter 0's interrupts
counter = 0;
}
}
return 0;
}
ISR(TIMER0_COMPA_vect){ //1.6ms
PORTC = 0xFF;
counter++;
}
ISR(TIMER0_COMPB_vect){ //0.8 ms
PORTC = ~PORTC;
}
ISR(TIMER1_COMPA_vect){ // 5.2 milisecond interrupt
PORTC = 0x00;
TCNT0 = 0; //clear the counter of counter0
// TIMSK0 = ((1<<OCIE0A) | (1<<OCIE0B)); //Enable the Counter 0 interrupts
// TIMSK1 &= ~(1<<OCIE1A);// Disable Interrupt Counter 1, output compare A (TIMER1_CMPA_vect)
}
here is an oscilloscope output that shows why I don't want the interrupt to be set instantly, because it set the signal 0 instantly.
I think the problem might be that in CTC mode, interrupt is generated when OCF1A flag is set (in TIFR). Since your timer is always running, just not generating interrupts, it sets OCF1A flag, which never gets cleared. On page 142 in the datasheet it says:
OCF1B is automatically cleared when the Output Compare Match B
Interrupt Vector is executed. Alternatively, OCF1B can be cleared by
writing a logic one to its bit location.
This means that when you set up timer 1, you also need to clear OCF1A:
TIFR1 &= ~(1<<OCF1A)
However, I think you can do better. You could just stop the timer when not needed, and start it when you do, instead of twiddling the TIMSK and having timer 1 run always. If you set TCCR1B to zero, that clears CS12, CS11, and CS10, which, according to the datasheet means "Timer stopped." Then, when your counter reaches 4 you can turn on timer1 as you have it above:
TCCR1B = ((1<<CS12) | (1<<CS10) | (1<<WGM12));
If you do this, you shouldn't need to turn timer 1 interrupts on and off: just leave them on, and only turn the counting on when you need it.
Also I am wondering if it is actually necessary to fire off two interrupts to toggle pins on PORTC? Are you not using PWM for that because it doesn't give you the pulse lengths precisely enough?
Related
unsigned long slptime=0;
unsigned long wdttime_count = 0;
void timer1_init()
{
//TCNT1=0xFF4E;//16ms
TCNT1=0xFFF5;//1ms
// TCNT1=0xFF9B; //10ms
TIMSK1=0x01;
TCCR1A &= ~(1<<WGM10); // RV09_H, Date: 05-May-2022, set Normal mode operation
TCCR1A &= ~(1<<WGM11);
TCCR1B &= ~(1<<WGM13);
TCCR1B &= ~(1<<WGM12);
TCCR1B |= (1<<CS12) | (1<<CS10); //1024 prescalar; fosc=11059200hz; freq=fosc/1024 = 10800hz; t=0.092ms;
}
void timer1_stop()
{
TCCR1B = 0x00;
TIMSK1 = 0x00;
}
ISR(TIMER1_OVF_vect)
{
//TCNT1=0xFF4E;//16ms
TCNT1=0xFFF5;
//TCNT1=0xFF9B;
wdttime_count=wdttime_count+1;
}
void main()
{
timer1_init();
_delay_ms(250);
timer1_stop();
sendtimediff((wdttime_count*1000)/1080);
}
The timer1 is configured for 1080Hz by counting upto 10 at 10800hz. I was just checking the timer accuracy but the above code return 227ms instead of 250ms.
What I am missing in it? Or _delay_ms() is causing the error?
When you set timer value to 0xFFF5 it increments 11 times before the overflow.
11059200 / 1024 / 11 = 981,8 Hz == 1,0185 ms.
It counts 245 times.
245 * 1000 / 1080 = 227
You probably want to set value to 0xFFF6
There is no need to set the timer in each interrupt. Instead, you can use CTC mode, forcing the timer to count from zero to a value in OCR1A (Mode 4) or ICR1 (Mode 12). E.g.:
void timer1_init()
{
TCNT1=0;
OCR1A = 9; // from 0 to 9 == 10 timer (prescaled) clock cycles
TIMSK1 = (1 << OCIE1A); // Use Output Compare interrupt
TCCR1A &= ~(1<<WGM10); // Set Mode 4 (CTC)
TCCR1A &= ~(1<<WGM11);
TCCR1B &= ~(1<<WGM13);
TCCR1B |= (1<<WGM12);
TCCR1B |= (1<<CS12) | (1<<CS10); //1024 prescalar; fosc=11059200hz; freq=fosc/1024 = 10800hz; t=0.092ms;
}
ISR(TIMER1_COMPA_vect) // use Output Compare A vector, instead of Overflow
{
// No need to reset the timer
wdttime_count=wdttime_count+1;
}
...
Keep in mind that _delay_ms macro just counts CPU cycles, therefore if there are interrupts happened during the delay, the delay can take longer time. _delay_ms and _delay_us macros are generating plain CPU loop, which counts with accuracy up to single CPU clock cycle, but only when the loop itself is not interrupted.
There is no point to compare _delay_ms to timer clocked from the same main clock, as the CPU itself. The comparison result will be always the same, no matter what actual CPU speed is.
Classic bug for free running timers, TCNT1=interval; in the ISR won't work. It needs to be something like:
volatile uint16_t next_TCNT1 = TCNT1;
next_TCNT1 += interval;
TCNT1 = next_TCNT1;
The reason for this is: you have set the interrupt to trigger when the timer compare hits a certain value. That's the point when the timer flag is set, but from the point where that happens until you reach the actual code inside the ISR, a lot of time has passed, interrupt latency. This was particularly nasty on the various old, crap architecture 8-bitters.
So by the time you update the timer counter, it isn't sitting at "interval", but rather at "interval plus interrupt latency plus execution overhead" which means the next interrupt will come much sooner than expected.
By reading the current value inside the ISR and adding the timer interval to it, you compensate for interrupt latency. Now the only real-time delay you have is those few lines inside the ISR, which are likely negligible.
my microcontroller is attiny85.Actually I have a few questions.
I simply turn on the LED 8 seconds later with the code below.
1)Should I turn the interrupts off and on while reading the counter value? I've seen something like this in the wiring.c file, the millis function.
2)How can I safely set the counter variable to 0 whenever I want? Do I have to turn the interrupts off and on here? Should I set the variables TCCR0A, TCCR0A, TCNT0 to zero?How should a safe reset function be?
Actually, all my purpose is to make a safe counter in the main function that can count 8 seconds whenever I want and start from zero whenever I want.
My basic code in below :
#define F_CPU 1000000UL
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdlib.h>
#include <stdio.h>
volatile unsigned int counter = 0;
ISR(TIM0_COMPA_vect){
//interrupt commands for TIMER 0 here
counter++;
}
void timerprogram_init()
{
// TIMER 0 for interrupt frequency 1000 Hz:
cli(); // stop interrupts
TCCR0A = 0; // set entire TCCR0A register to 0
TCCR0B = 0; // same for TCCR0B
TCNT0 = 0; // initialize counter value to 0
// set compare match register for 1000 Hz increments
OCR0A = 124; // = 1000000 / (8 * 1000) - 1 (must be <256)
// turn on CTC mode
TCCR0A |= (1 << WGM01);
// Set CS02, CS01 and CS00 bits for 8 prescaler
TCCR0B |= (0 << CS02) | (1 << CS01) | (0 << CS00);
// enable timer compare interrupt
TIMSK0 |= (1 << OCIE0A);
sei(); // allow interrupts
}
int main(void)
{
/* Replace with your application code */
timerprogram_init();
DDRA|=(1<<7);
PORTA &=~ (1<<7);
while (1)
{
if(counter>8000)
PORTA |= (1<<7);
}
}
First, there is no need to check the "counter" value in the super loop; In fact, this variable changes when an interrupt is created, so checking the variable should be done in the interrupt itself and if necessary, take only one flag from it.
Secondly, a safe way to reset the counter is to first deactivate the frequency divider(TCCR0B) of the timer section (the counter timer is practically turned off) and then set the TCNT0 value to zero to reset the timer; And if necessary, you can safely force the counter timer to count by returning the divider value.
Good luck.
The While(busy); loop is instantly skipped. But the only place where busy can be set to 0 is in the Timer1 ISR. But Timer 1 is stopped and only ever starts when in the Pin Change ISR.
From the UART output I can tell that Timer 1 ISR happens, while Pin Change ISR never does. which should not be possible, right?
What am I missing?
In my main function:
...
uint32_t temp = 0;
busy = 1;
mode = 1;
// Timer Interrupt Init
TCCR1B &= ~((1<<2) | (1<<1) | (1<<0)); // Makeing sure timer is not running
TIMSK1 |= (1 << TOIE1); // Timer 1 overflow interrupt enable
TCNT1 = 0; // Makeing sure Timer is on 0
// Pin Change Interrupt Init
PCICR |= (1<<2); // Activating PCMSK2
PCMSK2 |= (1<<6); // PCMSK2 -> PCINT23.. 16 seem to correspond to physical pins D 0-7
UartSendstring("1");
// Scanning (see ISR)
sei();
TCCR1B &= ~((1<<2) | (1<<1) | (1<<0));
while(busy);
cli();
...
Timer 1 ISR:
ISR(TIMER1_OVF_vect)
{
UartSendstring("3");
busy = 0;
}
Pin Change ISR:
ISR(PCINT2_vect)
{
UartSendstring("2");
//todo make first values not empty
TCCR1B &= ~((1<<2) | (1<<1) | (1<<0));// CS12 - CS10 are set to 0 to stop the timer
data[addr] |= TCNT1L;
data[addr] |= (TCNT1H << 8); // High and low byte are saved to data
TCNT1 = 0; // Timer is reset
TCCR1B |= ((1<<1) | (1<<0)); // CS12 is set to 1 to restart the timer with prescaler 64 -> tick time = 4us
// Signal period duration is 1s / 38 000 = 26us
// -> at least on timer tick in one signal period
addr++; // Prepares to write to the next address with next edge
}
Uart output is:
13
edit
I tried moving the TIMSK1 |= (1 << TOIE1); to the Pin Change ISR. Now it goes in there at least once like I want it but as soon as I enable the Interrupt it triggers the ISR again and ends.
As the Arduino core starts all timers by default (because of PWM), there is possibility that interrupt flags are already set and they fires as soon as you enable the corresponding interrupts. So you have to clear them before reenabling interrupts. But there is a tiny little obstacle: interrupt flags are cleared by writing logic one into corresponding bit. Therefore you have to use something like this TIFR1 = _BV(ICF1) | _BV(OCF1B) | _BV(OCF1A) | _BV(TOV1); (however as you don't use any other Timer1 interrupt, you can clear TOV1 flag only).
Hello good people of stack overflow. My problem is an interrupt service routine (ISR) that seemingly never executes! Here's some info on my set up:
I am flashing an avr attiny85. I have the bare bones of a project set up so far with simply a main.c and two modules: timer and hardwareInit. In the timer module, I have a timer0_init function that I am using to set up timer0 for CTC mode to overflow ever 1 ms. Here is the function:
void timer0_init( void )
{
cli();
TCCR0B |= 3; //clock select is divided by 64.
TCCR0A |= 2; //sets mode to CTC
OCR0A = 0x7C; //sets TOP to 124 so the timer will overflow every 1 ms.
TIMSK |= 2; //Enable overflow interrupt
sei(); //enable global interrupts
}
with the timer set up, I added an ISR to increment ticks every time the counter overflows, so I can keep track of how much time has elapsed, etc.
ISR(TIMER0_OVF_vect)
{
cli();
//ticks ++;
PORTB |= ( 1 << PORTB0 );
sei();
}
as you can see, I commented out the ticks++ because it wasn't working, and replaced it with PORTB |= ( 1 << PORTB0 ); which simply turns on an LED, so if the interrupt is ever executed, I will know by proof of the LED being on.
Unfortunately, I can't get it to turn on and can't see what I'm missing. (to prove that I 1. have the LED set up on the right pin, and 2. am manipulating the correct bit in the correct register, I put just this statement PORTB |= ( 1 << PORTB0 ); in my infinite loop and confirmed the LED came on)
For further explanation, here is my main.c:
/*================================= main.c =================================*/
#define F_CPU 8000000UL
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include "timer.h"
#include "hardwareInit.h"
int main(){
//Initialize hardware HERE
DDRB |= ( 1 << PORTB0 ); //set this pin as an output for an LED
SetClockPrescale(1); //internal clock divided by 1 = 8 MHz, from hardwareInit
timer0_init(); //set up timer0 for 1 ms overflow
while(1)
{
/* if( getTicks() > 0 )
{
PORTB |= ( 1 << PORTB0 );
_delay_ms(1000);
PORTB &= ~( 1 << PORTB0 );
_delay_ms(1000);
} */
}
return 0;
}
So, what you see in the infinite loop is what I tried first, but after that didn't work, I tried something simpler, just having an empty loop (commented out previous stuff), and waiting for the interrupt to get triggered which would turn on the LED.
Any help you could give would be really appreciated. I'm quite puzzled why this hasn't been working.
You are using the wrong ISR as #andars has pointed out correctly. In CTC "Clear Timer on Compare" mode the timer will never overflow as it will be cleared on compare match.
So you enabled the wrong interrupt of the timer as well. Bit 1 of TIMSK register enables timer overflow interrupt on timer0. That won't be triggered because of the previous reason. Taken from datasheet.
As you are using OCR0A to set the compare value, you have to enable Bit 4 – OCIE0A: Timer/Counter0 Output Compare Match A Interrupt Enable.
Back to the ISR, you need the ISR(TIMER1_COMPA_vect) or ISR(TIMER1_COMPB_vect) depending on which bit you set in TIMSK. Note that the compare value should be written into the matching registers as well, OCR0A or OCR0B.
Note that, you can use the bit names in your code just like the register names, in my opinion it makes the code more transparent.
Your code should be changed as follows to enable the corresponding interrupt:
void timer0_init( void )
{
cli();
TCCR0B |= (1<<CS01) | (1<<CS00); //clock select is divided by 64.
TCCR0A |= (1<<WGM01); //sets mode to CTC
OCR0A = 0x7C; //sets TOP to 124 so the timer will overflow every 1 ms.
TIMSK |= (1<<OCIE0A); //Output Compare Match A Interrupt Enable
sei(); //enable global interrupts
}
The ISR:
ISR(TIMER0_COMPA_vect)
{
cli();
//ticks ++;
PORTB |= ( 1 << PORTB0 );
sei();
}
I have an ATMega8515 and I am trying to setup a timer interrupt so that if a process takes too long it will shut off.
I setup the timer with:
void init_software_interupt(double time)
{
OCR1A = time;
TCCR1A = 0;
TCCR1B = 0;
TCCR1B |= (1 << WGM12);
TCCR1B |= (1<<CS10);
TCCR1B |= (1<<CS12);
TIMSK |= (1 << OCIE1A);
sei();
}
This works great. I calculated a clock second to be 7812 for an 8MHz clock and it works exactly as expect printing stuff once every second:
//Timer Interupt
int seconds = 0;
ISR(TIMER1_COMPA_vect){
seconds++;
printf("in timer overflow: %d seconds have passed\r\n",seconds);
in_progress = FALSE;
}
The problem is that I might call the function unlock_door() 750ms into the 1 second overflow count and it would only allow the operation to take 250ms which isn't long enough.
I've tried to just set the output compare register before I call the function but it doesn't seem to have an affect:
OCR1A = 7812;
unlock_door();
But it doesn't change the current overflow.
How can I reset the overflow timer before I call a function to ensure it will take 1 second?
It looks like you're using the compare interrupt, not the overflow interrupt. OCR1A stores the value that the counter is being compared to, and I believe that TCNT1 stores the actual timer value. Try:
TCNT1 = 0;
unlock_door();
Here's a good article on AVR timers, by the way. It's called "The Newbie's Guide to AVR Timers", but it works really well as a reference as well.