2015-09-21 34 views
1

所以我所要做的就是打開一個功能來打開和關閉將被調入主顯示屏的LED。 LED亮起,但不打開和關閉。我的代碼有什麼問題?LED保持點亮。不會打開和關閉

我使用ATMEGA328P板和愛特梅爾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 
} 

回答

4

閱讀關於位運算符。 a |= b設置在ab中設置的所有位。所以如果b == 0,它不會改變a

您需要第一次延遲後的位和運算符。這其中設置在ab將所有的位:

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

反轉操作~反轉的面具,所以只留下相關位0,其它位全部爲1。所以位號PORTB5將被清除,所有其他都保持不變。

注意使用無符號常量。通常建議這樣做,因爲位操作符和位移是針對負值實施定義的,或者符號是否改變 - 最好是未定義行爲最差。

+0

非常感謝。我會閱讀更多關於位和操作符的信息。 –

2

|=不能使10。使用和&=

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