如何使Atmega328微调器中断每1秒钟滴答一次? [英] How to make Atmega328 timmer interrupt tick every 1 second?

查看:62
本文介绍了如何使Atmega328微调器中断每1秒钟滴答一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Atmega328p,我已经将一个LED连接到它的D4引脚,我希望它每隔一秒钟打开/关闭一个LED.

I've an Atmega328p and I've connected an LED to it's D4 pin and I want it to turn LED on/off every one second.

我发现了本教程并且我已经基于一些在线AVR调光计算器和我使用的12MHZ外部晶体对此进行了更改:

I found this tutorial and I've change it base on some online AVR timmer calculator and the 12MHZ external crystal which I've used, to this :

#define F_CPU 12000000UL
#include <avr/io.h>
#include <avr/interrupt.h>


int main(void)
{

    DDRD |= 1 << 4;
    PORTD |= 1 << 4;

    ICR1 = 0xB71B;

    TCCR1B |= (1 << WGM12);
    // Mode 4, CTC on OCR1A

    TIMSK1 |= (1 << ICIE1);
    //Set interrupt on compare match

    TCCR1B |= (1 << CS12);
    // set prescaler to 256 and starts the timer


    sei();
    // enable interrupts


    while (1)
    {
        // we have a working Timer
    }
}

ISR (TIMER1_COMPA_vect)
{
    PORTD |= 0 << 4;
    // action to be done every 200ms
}

无论我如何更改ICR1值,LED始终点亮或熄灭.我该如何运作?

The LED is always on or off no mater how I change ICR1 value. How can I make it work?

推荐答案

计时器初始化看起来不错 (请参见其他答案),但是看起来您没有在进行切换LED正确.

The timer initialization looks fine (see other answer), but it looks like you are not toggling the LED correctly.

PORTD | = 0<<4; 不会执行任何操作.

假设您直接驱动LED,请使用 PORTD | =(1<< 4); 来打开LED, PORTD& =〜(1<< 4); 关闭LED,并 PORTD ^ =(1<< 4); 切换输出状态.

Assuming you drive the LED directly, use PORTD |= (1 << 4); to turn LED on, PORTD &= ~(1 << 4); to turn LED off and PORTD ^= (1 << 4); to toggle the output state.

由于您只想切换LED状态,因此最后一个选项显然是最佳选择,因为您不必检查输出引脚的当前状态来决定是否需要打开或关闭.

Since you just want to toggle the LED state, the last option is obviously the best choice, because you do not have to check the current state of the output pin to decide if you need to switch on or off.

这篇关于如何使Atmega328微调器中断每1秒钟滴答一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆