Arduino的如何检测LED的状态呢? [英] How can Arduino detect the state of an LED?
问题描述
我工作了Arduino的闪烁/褪色灯程序。我试图建立的是基于LED的状态和某些开关组合一些交互。试想一下:当一个按钮为pressed,如果一个LED指示灯亮我想将其关闭,如果一个LED指示灯灭我想打开它
I'm working on a blinking/fading lights program for Arduino. I'm trying to build in some interactivity that's based on LED state and certain switch combinations. Consider: When a button is pressed, if an LED is ON I want to turn it off and if an LED is OFF I want to turn it on.
不过,我没能找到有关确定LED状态的任何信息。最接近的是这个问题关于Android,但我想,如果我找到了可以从Arduino的平台做到这一点。有没有人有任何实际经验或建议吗?
However, I've not been able to find any information about determining LED state. The closest was this question about Android, but I'm trying to find out if I can do this from the Arduino platform. Does anyone have any practical experience or advice?
推荐答案
您有几种选择:
一,可以将LED状态保存在一个布尔值,并在按钮preSS,否定的,并将其写入到LED端口:
One, you can store the LED state in a boolean, and on button press, negate that and write it to the LED port:
void loop()
{
static int ledState = 0; // off
while (digitalRead(BUTTON_PIN) == 0)
; // wait for button press
ledState = !ledState;
digitalWrite(LED_PORT, ledState);
}
二,如果你不介意直接访问AVR的端口:
Two, if you don't mind accessing the ports of the AVR directly:
void init()
{
DDRD = 0x01; // for example: LED on port B pin 0, button on port B pin 1
PORTB = 0x00;
}
void loop()
{
while (PINB & 0x02 == 0)
; // loop until the button is pressed
PORTB ^= 0x01; // flip the bit where the LED is connected
}
这篇关于Arduino的如何检测LED的状态呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!