ArduinoCore-API icon indicating copy to clipboard operation
ArduinoCore-API copied to clipboard

Retrieve current pin mode

Open mikaelpatel opened this issue 9 years ago • 4 comments

There is currently no function to get the current pin mode. A possible implementation is:

int pinMode(uint8_t pin)
{
  if (pin >= NUM_DIGITAL_PINS) return (-1);

  uint8_t bit = digitalPinToBitMask(pin);
  uint8_t port = digitalPinToPort(pin);
  volatile uint8_t *reg = portModeRegister(port);
  if (*reg & bit) return (OUTPUT);

  volatile uint8_t *out = portOutputRegister(port);
  return ((*out & bit) ? INPUT_PULLUP : INPUT);
}

The return value is the pin mode or error code (-1) for illegal pin number.

Cheers!

mikaelpatel avatar Feb 23 '16 13:02 mikaelpatel

Any news? it's very useful feature!

objque avatar May 27 '17 16:05 objque

Only negative I can think of is the fact that for some variants the return type of portModeRegister() is of type volatile uint16_t *. On personal projects I have used the auto type specifier to fix this, but I don't know if Arduino is using c++11 by default. For now change I suggest changing it to uint16_t rather than uint8_t

liamkinne avatar Dec 30 '17 14:12 liamkinne

No news on this one? I'd love to have it native! Thanks

Benjalien avatar Jan 30 '23 21:01 Benjalien

No news on this one? I'd love to have it native! Thanks

If you (or anyone else for that matter) could provide a PR then we'd have something to discuss :wink:

aentinger avatar Feb 06 '23 06:02 aentinger