arduino現在很火啊,arduino的MCU是ATmega328P。
328p 有3個定時計數器,分別是8bit的 T/C0 ,16bit的 T/C1和8bit的 T/C2。
T/C0:
Timer/Counter0 is a general purpose 8-bit Timer/Counter module, with two independent Output.Compare Units, and with PWM support. It allows accurate program execution timing (event management) and wave generation.
主要來看一下一個寄存器的配置:
TCCR0:控制寄存器。328p這個傢伙有2個8bit的寄存器來控制這個,分別是 TCCR0A和 TCCR0B。可以認為這個TCCR0是一個 16bit的。
TCCR0A:T/C的控制寄存器A
bit 0和bit 1用的非常的多: 其實就是控制啥時候計時結束的
2. TCCR0B:T/C的控制寄存器B
bit0~bit2用的很多:用來設置分頻數的,這個和top的值的計算有很大的關係,mytop = 定時時間/(分頻數*(1/晶振頻率))
TCNT0 :這個就很簡單的,計數寄存器,給一個初值就好了。
OCR0:輸出比較寄存器,這個也有2個8bit的寄存器,分別是: OCR0A和 OCR0B
OCR0A:對比A的
OCR0B:對比B的
它的這個值呢其實就是mytop的這個值,當然這個還是得看模式的設置啊,可以設置top是默認的,要看WGM0這些bit的設置
TIMSK0:中斷屏蔽寄存器,說白了其實就是可以來控制什麼時候來啟動time,什麼時候來停止這個time。
這個也很簡單,
Bit 0 – TOIE0: Timer/Counter0 Overflow Interrupt Enable
Bit 1 – OCIE0A: Timer/Counter0 Output Compare Match A Interrupt Enable
Bit 2 – OCIE0B: Timer/Counter Output Compare Match B Interrupt Enable
具體選擇哪個bit,看你開始自己設置的OCR0用的是A還是B。
TIFR0:中斷標誌寄存器
很簡單的一設置就好了。
Bit 1 – OCF0A: Timer/Counter 0 Output Compare A Match Flag
Bit 2 – OCF0B: Timer/Counter 0 Output Compare B Match Flag
The OCF0B bit is set when a Compare Match occurs between the Timer/Counter and the data in OCR0B – Output Compare Register0 B. OCF0B is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, OCF0B is cleared by writing a logic one to the flag. When the I-bit in SREG, OCIE0B (Timer/Counter Compare B Match Interrupt Enable),and OCF0B are set, the Timer/Counter Compare Match Interrupt is executed.
time1和time2 就不在這裡面寫了。
在舉一個簡答的例子的主要代碼:
timer_start(){
cli(); // Disable Timer2 interrupt.
ASSR &= ~(1< TCCR2A = (1< TCCR2B = (1< TCNT2 = 0; // Reset Timer2 counter. OCR2A = 50; sei();// 開全局中斷 } timer_stop() { // Disable timer interrupt. TIMSK2 &= ~(1< } timer_setup() { OCR2B = 0; // Timer2B follow Timer2A; TIMSK2 |= (1< } ISR(TIMER2_COMPB_vect) { TIMSK2 &= ~(1< }
閱讀更多 小5嵌入式 的文章