无法让定时器工作
Unable to get the timer working
我已经在正常模式下为Atmega328 编写了简单的定时器程序。但是如果我在 Atmel Studio 6.2 中编译代码,我无法使 LED 闪烁。但是如果我在 arduino IDE 中编译,同样的代码可以完美运行。我在下面给出了 Arduino 和 Atmel Studio 的代码。某处似乎有小问题。 F_CPU 值有问题吗?
// Code compiled using Atmel Studio:
#include <avr/io.h>
#include <avr/interrupt.h>
#define F_CPU 16000000
unsigned char x=0;
ISR(TIMER1_OVF_vect) {
x=!x;
}
void setup() {
DDRB=0x01;
TIMSK1=0x01; // enabled global and timer overflow interrupt;
TCCR1A = 0x00; // normal operation page 148 (mode0);
TCNT1=0x0000; // 16bit counter register
TCCR1B = 0x04; // start timer/ set clock
};
int main (void)
{
setup();
while(1)
{
PORTB= x;
}
return(0);
}
用 Arduino 编写的代码 IDE:
#define LED 8
boolean x=false;
ISR(TIMER1_OVF_vect) {
x=!x;
}
void setup() {
pinMode(LED, OUTPUT);
TIMSK1=0x01; // enabled global and timer overflow interrupt;
TCCR1A = 0x00; // normal operation page 148 (mode0);
TCNT1=0x0000; // 16bit counter register
TCCR1B = 0x04; // start timer/ set clock
};
void loop() {
PORTB= x;
}
使用中断时,您需要同时启用全局中断(在定时器寄存器中)和本地中断(在状态寄存器中)才能触发中断向量。
这可以通过在您准备好接收本地中断时调用 sei()
(设置启用中断)来完成。通常,您希望在设置全局中断后执行此操作,接近 setup
方法的末尾。
我怀疑在使用 Arduino 时会自动启用中断 IDE。
我已经在正常模式下为Atmega328 编写了简单的定时器程序。但是如果我在 Atmel Studio 6.2 中编译代码,我无法使 LED 闪烁。但是如果我在 arduino IDE 中编译,同样的代码可以完美运行。我在下面给出了 Arduino 和 Atmel Studio 的代码。某处似乎有小问题。 F_CPU 值有问题吗?
// Code compiled using Atmel Studio:
#include <avr/io.h>
#include <avr/interrupt.h>
#define F_CPU 16000000
unsigned char x=0;
ISR(TIMER1_OVF_vect) {
x=!x;
}
void setup() {
DDRB=0x01;
TIMSK1=0x01; // enabled global and timer overflow interrupt;
TCCR1A = 0x00; // normal operation page 148 (mode0);
TCNT1=0x0000; // 16bit counter register
TCCR1B = 0x04; // start timer/ set clock
};
int main (void)
{
setup();
while(1)
{
PORTB= x;
}
return(0);
}
用 Arduino 编写的代码 IDE:
#define LED 8
boolean x=false;
ISR(TIMER1_OVF_vect) {
x=!x;
}
void setup() {
pinMode(LED, OUTPUT);
TIMSK1=0x01; // enabled global and timer overflow interrupt;
TCCR1A = 0x00; // normal operation page 148 (mode0);
TCNT1=0x0000; // 16bit counter register
TCCR1B = 0x04; // start timer/ set clock
};
void loop() {
PORTB= x;
}
使用中断时,您需要同时启用全局中断(在定时器寄存器中)和本地中断(在状态寄存器中)才能触发中断向量。
这可以通过在您准备好接收本地中断时调用 sei()
(设置启用中断)来完成。通常,您希望在设置全局中断后执行此操作,接近 setup
方法的末尾。
我怀疑在使用 Arduino 时会自动启用中断 IDE。