Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

arduino - How can I digitalRead a pin that is in pinMode OUTPUT?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...