我正在编写一个需要每 0.5 秒检查一次传感器输入的代码。我想使用 ISR,因为我希望我的代码一直执行到传感器的输入发生变化。
我将如何设置此 ISR 以每 0.5 秒执行一次?
谢谢 :)
我建议使用定时器中断。举个例子去这里。http://www.avrfreaks.net/forum/tut-c-newbies-guide-avr-timers?page=all
我自己没有测试过,但这里有一段代码。
#include
#include
int main (void)
{
DDRB |= (1 << 0); // Set LED as output
TCCR1B |= (1 << WGM12); // Configure timer 1 for CTC mode
TIMSK |= (1 << OCIE1A); // Enable CTC interrupt
sei(); // Enable global interrupts
OCR1A = 15624; // Set CTC compare value to 1Hz at 1MHz AVR clock, with a prescaler of 64
TCCR1B |= ((1 << CS10) | (1 << CS11)); // Start timer at Fcpu/64
for (;;)
{
}
}
ISR(TIMER1_COMPA_vect)
{
PORTB ^= (1 << 0); // Toggle the LED
}