简体   繁体   English

LED保持点亮。 不会打开和关闭

[英]LED stays on. Wont' turn on and off

So all I'm trying to do is make a function to turn on and turn off the LED which will be called into the main. 因此,我要做的只是使一个功能打开和关闭将被调用到主LED中。 The LED turns on but it doesn't turn on and off. LED点亮,但不点亮和熄灭。 What's wrong with my code? 我的代码有什么问题?

I'm using ATmega328p board and Atmel Studio 6.2 我正在使用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
}

Read about bit-operators. 了解有关位运算符的信息。 a |= b sets all bits in a which are set in a or b . a |= b设置a b中设置的a中的所有位。 So if b == 0 , it does not alter a . 因此,如果b == 0 ,则不会更改a

You need the bit-and operator after the first delay. 在第一个延迟之后,您需要位与运算符。 This sets all bits which are set in a and b : 这将设置在a b设置的所有位:

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

The inversion operator ~ inverts the mask, so it leaves only the relevant bit 0 , all other bits are 1 . 反转运算符~反转掩码,因此它只保留相关的位0 ,所有其他位为1 So bit number PORTB5 will be cleared, all other are left unchanged. 因此,将清除位PORTB5位,所有其他位保持不变。

Note using an unsigned constant. 注意使用无符号常量。 This is in general recommended, as bit-operators and shifts are implementation defined for negative values or if the sign changes - at best and undefined behaviour at worst. 通常建议这样做,因为对位运算符和移位的实现是为负值定义的,或者在符号发生变化时定义 -最佳情况下行为未定义

Or |= can't make 1 to 0 . 否则|=不能为10 use and &= . 使用和&=

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM