blemasle / arduino-mcp23017

Complete support of MCP23017
MIT License
71 stars 40 forks source link

Problem with digitalRead #6

Closed pspastushkov closed 5 years ago

pspastushkov commented 5 years ago

Hi!

program code

#include <Wire.h>
#include <MCP23017.h>
#define i2c_mcp23017_ADDR_000 0x20
MCP23017 mcp23017_0x20 = MCP23017(i2c_mcp23017_ADDR_000);

void setup() {
  Serial.begin(9600);
  Wire.begin();
  mcp23017_0x20.init();
  for (uint8_t i = 0; i < 16; i++) mcp23017_0x20.pinMode(i, INPUT);
  Wire.beginTransmission(i2c_mcp23017_ADDR_000);
  Wire.write(0x02);
  Wire.write(0xFF);
  Wire.endTransmission();
  Wire.beginTransmission(i2c_mcp23017_ADDR_000);
  Wire.write(0x03);
  Wire.write(0xFF);
  Wire.endTransmission();
}

void loop() {
  if (mcp23017_0x20.digitalRead(2)) {
    Serial.println("pin2 = HIGH");
  }
  else {
    Serial.println("pin2 = LOW");
  }
  Serial.println(mcp23017_0x20.readPort(MCP23017_PORT::A), BIN);
  Serial.println(mcp23017_0x20.readPort(MCP23017_PORT::B), BIN);
  delay(1000);
}

COM port monitor

pin2 = LOW 10000000 10000000 pin2 = LOW 10000100 10000000 pin2 = LOW 10000100 10000100 pin2 = HIGH 10000101 10000100 pin2 = LOW 10000100 10000100

When inverted ports with any choice of pin (0-7 / 8-15), the condition is triggered when a signal is applied to 0 or 8, respectively. Help me!

Pavel

blemasle commented 5 years ago

Hi,

Sorry about the delay, your issue came at the same time I moved house and it's been a crazy week. Hopefully I'll be able to have a look a the it tomorrow.

Regards

blemasle commented 5 years ago

Hi,

Again, sorry for the delay. I'm having trouble understand your issue. You're setting the IOPOLA & IOPOLB registers to 0xFF to invert the reflected state on the pins. By the way, you could have used either of those two solutions for readability ;)

mcp23017_0x20.writeRegister(MCP23017_REGISTER::IOPOLA, 0xff)
mcp23017_0x20.writeRegister(MCP23017_REGISTER::IOPOLB, 0xff)

//or
mcp23017_0x20.writeRegister(MCP23017_REGISTER::IOPOLA, 0xff, 0xff)

What you're saying is in that case, digitalRead(x) is true when a signal is applied to the first pin of x corresponding port. Am I getting this right ? Since you set IOPOL, we both agree that

pin2 = LOW 10000100 10000100

Means that pin 2, 7, 10 and 15 are actually low and everything else is high, right ?

trycoon commented 5 years ago

GCC complains with: .pio/libdeps/nodemcuv2/MCP23017_ID6001/src/MCP23017.cpp:75:10: warning: suggest parentheses around comparison in operand of '&' [-Wparentheses] if(gpio & _BV(pin) == _BV(pin)) return HIGH;

https://github.com/blemasle/arduino-mcp23017/blob/master/src/MCP23017.cpp#L75

I think it should be:

if((gpio & _BV(pin)) == _BV(pin)) return HIGH;
blemasle commented 5 years ago

You (and GCC) are absolutely right. I'll change it as soon as possible !

Thank you !