How can Arduino detect the state of an LED?

不打扰是莪最后的温柔 提交于 2019-12-12 10:05:25

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!