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

后端 未结 11 1057
不知归路
不知归路 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条回答
  •  Happy的楠姐
    2020-12-09 03:25

    Didn't like any of the previous answers, because they would not be cross-arduino-platform compatible. You need to access through the pin reference tables. The following expression does the trick.

    bool value = (0!=(*portOutputRegister( digitalPinToPort(pin) ) & digitalPinToBitMask(pin)));
    

    Let me break that down for better understanding

    digitalPinToPort(pin) look up you the gpio bank [port] that the pin is assigned to on your selected hardware

    portOutputRegister(...) gives you a pointer to the port containing the value you are looking for. * dereferences the pointer and gives the full value of all 8 pins assigned to that port. It is not yet uniquely useful, but the bit you are looking for is in there.

    &digitalPinToBitMask(pin) selects only the bit you are interested in for the pin, all other bits will be zero.

    0!= tests to see if the resulting expression is zero, or something else. If it is zero, then your output is zero on that pin. Otherwise the output is one.

提交回复
热议问题