LED继续亮着。惯于'打开和关闭

时间:2015-09-21 01:15:33

标签: c led atmega atmel

所以我要做的就是打开一个功能来打开和关闭将被调用到主电源的LED。 LED亮起但不会打开和关闭。我的代码出了什么问题?

我正在使用ATmega328p主板和Atmel Studio 6.2

#define F_CPU 16000000UL // 16MHz clock from the debug processor
#include <avr/io.h>
#include <util/delay.h>

dot();

int main()
{
    DDRB |= (1<<DDB5);
    while(1)
    {
    dot();
    }
}

int dot()
{
    PORTB |= (1<<PORTB5); // Set port bit B5 to 1 to turn on the LED
    _delay_ms(200); // delay 200mS
    PORTB |= (0<<PORTB5); // Set port bit B5 to 0 to turn on the LED
    _delay_ms(200); // delay 200mS
}

2 个答案:

答案 0 :(得分:4)

了解位运算符。 a |= b设置a b中设置的所有位。因此,如果b == 0,它不会改变a

第一次延迟后需要位操作符。这将设置a b中设置的所有位:

PORTB &= ~(1U<<PORTB5);

反转运算符~反转掩码,因此只留下相关位0,所有其他位都是1。因此,位号PORTB5将被清除,所有其他位置保持不变。

注意使用无符号常量。这通常是推荐的,因为位操作符和移位是针对负值定义的实现,或者如果符号发生变化 - 最好是未定义的行为

答案 1 :(得分:2)

|=无法10。使用和&=

// dummy line to enable highlight
PORTB &= ~(1<<PORTB5); // Set port bit B5 to 0 to turn on the LED
相关问题