问题
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.
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?
回答1:
You have several options:
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);
}
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
}
回答2:
It is absolutely OK to read output ports. That is
digitalWrite(LED_PORT, !digitalRead(LED_PORT));
will toggle the pin.
You might also want to consider the toggle library: http://playground.arduino.cc/Code/DigitalToggle
来源:https://stackoverflow.com/questions/14138176/how-can-arduino-detect-the-state-of-an-led