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

后端 未结 11 956
不知归路
不知归路 2020-12-09 02:30

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.

<         


        
相关标签:
11条回答
  • 2020-12-09 03:07
    digitalWrite(3,HIGH);
    digitalRead(3);
    
    0 讨论(0)
  • 2020-12-09 03:09

    Why do you want to do that? If you are doing this to validate that the pin is really high, this will not confirm it to you, because maybe there is a short circuit on the high pin from the external circuit, the best way is to create a feedback through another pin; configure another pin as input, and connect the output pin to the new input pin, and read its value. Reading the internal register will always return for you what the controller is trying to put on the pin, not the actual pin value.

    0 讨论(0)
  • 2020-12-09 03:12

    Keep a separate boolean map of the output pin states.

    If a microcontroller GPIO pin is set as an input, then its value, when read, depends on what it's connected to externally. That's kind of the point.

    0 讨论(0)
  • 2020-12-09 03:14

    Keep your pinMode() selection in the setup() function, and try the digitalWrite() and digitalRead() functions.

    setup() will be executed when controller starts and loop() will be the function which keep executing.

    int pin22 = 22;
    void setup()
    {
      Serial.begin(9600);
      pinMode(pin22,output);
    }
    
    void loop()
    {
      digitalWrite(pin22,HIGH);
      digitalRead(pin22);
      digitalWrite(pin22,LOW);
      digitalRead(pin22);
    }
    
    0 讨论(0)
  • 2020-12-09 03:14

    You can try:

    int Pin22 = 22;
    int valuePin22 = 0;
    
    void setup() {
    
        pinMode(Pin22, OUTPUT);
        digitalWrite(Pin22, LOW);
    
    }
    
    void loop() {
    
        digitalWrite(Pin22, HIGH)
        valuePin22 = 1;
        Serial.println(valuePin22);
        delay(100);
    
        digitalWrite(Pin22, LOW)
        valuePin22 = 0;
        Serial.println(valuePin22);
        delay(1000)
    
    }
    
    0 讨论(0)
  • 2020-12-09 03:16

    Are you trying to set the default input to HIGH?
    If so you are looking to activate the pull-up register:

    void setup() 
    {
        Serial.begin(9600);
    }
    
    void loop() 
    {
        delay(1000);
    
        pinMode(3,INPUT);         // default mode is INPUT  
        digitalWrite(3, HIGH);    // Turn on the internal pull-up resistor, default state is HIGH  
    
        delay(1000);
        Serial.println(digitalRead(3));
    }
    

    Excerpt from DigitalWrite:

    If the pin is configured as an INPUT, writing a HIGH value with digitalWrite() will enable an internal 20K pullup resistor.

    0 讨论(0)
提交回复
热议问题