[英]How can I reset timer0?
我的微控制器是 attiny85。實際上我有幾個問題。 我只需在 8 秒后使用下面的代碼打開 LED。
1)我應該在讀取計數器值時關閉和打開中斷嗎? 我在wiring.c文件中看到過類似的東西,millis function。
2)我怎樣才能安全地將計數器變量設置為0? 我必須在這里關閉和打開中斷嗎? 我應該將變量 TCCR0A、TCCR0A、TCNT0 設置為零嗎?應該如何安全復位 function?
實際上,我的全部目的是在主 function 中創建一個安全計數器,它可以隨時計算 8 秒,並隨時從零開始。
我的基本代碼如下:
#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);
}
}
首先,不需要在超級循環中檢查“計數器”值; 事實上,這個變量在創建中斷時會發生變化,所以應該在中斷本身中檢查變量,如果需要,只取一個標志。 其次,重置計數器的安全方法是先停用定時器部分的分頻器( TCCR0B )(計數器定時器實際上已關閉),然后將TCNT0值設置為零以重置定時器; 如有必要,您可以通過返回分頻器值安全地強制計數器定時器計數。 祝你好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.