Arduino 如何检测 LED 的状态? [英] How can Arduino detect the state of an LED?

查看:44
本文介绍了Arduino 如何检测 LED 的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 Arduino 开发一个闪烁/渐隐的灯光程序.我正在尝试建立一些基于 LED 状态和某些开关组合的交互性.考虑:当按下按钮时,如果 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 状态存储在一个布尔值中,并在按下按钮时将其取反并将其写入 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆