如何数字读取处于 pinMode OUTPUT 的引脚? [英] How can I digitalRead a pin that is in pinMode OUTPUT?

查看:40
本文介绍了如何数字读取处于 pinMode OUTPUT 的引脚?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的测试 sketch,其中我试图将一个引脚设置为 HIGH 然后用 digitalRead 读取它的状态.这是我的草图.

void setup(){Serial.begin(9600);}空循环(){延迟(1000);pinMode(3,输出);数字写入(3,高);延迟(1000);pinMode(3, 输入);Serial.println(digitalRead(3));}

串口监控结果:

<预><代码>0000

我已经明白改变 pinMode 会阻止它成为 HIGH.因此,在OUTPUT 模式下将引脚设置为HIGH,然后更改为INPUT 模式会将其更改为LOW.因此 digitalRead 将始终返回 0.如果我不更改 pinMode,它将无法读取 pin.那么如何在不丢失值的情况下读取处于 OUTPUT 模式的引脚的当前设置?

解决方案

在这种情况下,您只想访问数据寄存器本身.

PORTB 和 PORTD 寄存器包含您要查找的引脚数据.我终于可以使用 Arduino 来解决这个问题.您想使用 bitRead(PORTD, pin).

Serial.println(bitRead(PORTD,3));//读取寄存器 PORTD 的第 3 位,其中包含引脚 3 的当前状态(高/低).

参考 位读取操作了解更多信息.

I have a very simple test sketch in which I'm trying to set a pin to HIGH and then read its state with digitalRead. Here is my sketch.

void setup()
{
    Serial.begin(9600);
}

void loop()
{
    delay(1000);

    pinMode(3, OUTPUT);
    digitalWrite(3, HIGH);
    delay(1000);

    pinMode(3, INPUT);
    Serial.println(digitalRead(3));
}

Serial monitor result:

0
0
0
0

I have come to understand that changing the pinMode will stop it from being HIGH. So setting a pin to HIGH in OUTPUT mode and then changing to INPUT mode will change it to LOW. So the digitalRead will always return 0. If I don't change the pinMode it won't be able to read the pin. So how can I read the current setting of a pin that is in OUTPUT mode without losing the value?

解决方案

In this case you just want to access the data register itself.

PORTB and PORTD registers contain the pin data you are looking for. I finally got access to an Arduino to figure it out. You want to use bitRead(PORTD, pin).

Serial.println(bitRead(PORTD,3)); //Reads bit 3 of register PORTD which contains the current state (high/low) of pin 3.

Reference Bit Read Operation for more information.

这篇关于如何数字读取处于 pinMode OUTPUT 的引脚?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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