0

I'm working to develop a simple code for MCP23017 that I want to use to run LCD128x64.

I was succeeded to set IODIRB as output and blink LED as a test.

Now I want to read the pin state, but I couldn't. Here's my code. I'm using the nice twi library that comes with Wire library.

uint8_t mcp23017_read(uint8_t add_reg){
    uint8_t data;
    twi_writeTo(MCP23017_ADD,add_reg,2,1,0);    
    twi_readFrom(MCP23017_ADD,data,1,1);

    return data;
}

I've tried this version too:

uint8_t *mcp23017_read(uint8_t add_reg){
    uint8_t data[1];
    twi_writeTo(MCP23017_ADD,add_reg,2,1,0);    
    twi_readFrom(MCP23017_ADD,data,1,1);

    return *data;
}

==================================================

Here's Arduino call function:

void loop() {
  // put your main code here, to run repeatedly:
  data = mcp23017_read(GPIOB);
  Serial.println(data);
  delay(100);
}
R1S8K
  • 283
  • 3
  • 21

2 Answers2

2

I don't know how this lib works. But I'm pretty sure that you have to pass a pointer onto the data variable into the twi_readFrom method.

uint8_t mcp23017_read( uint8_t add_reg )
{
    uint8_t data;
    twi_writeTo( MCP23017_ADD, add_reg, 2, 1, 0 );    
    // I inserted an & below
    twi_readFrom( MCP23017_ADD, &data, 1, 1 );

    return data;
}

Or in case of the second function:

// I removed the star operator
uint8_t mcp23017_read(uint8_t add_reg)
{
    uint8_t data[1];

    twi_writeTo( MCP23017_ADD, add_reg, 2, 1, 0 );    
    // you pass the pointer to the array element 0
    twi_readFrom( MCP23017_ADD, data, 1, 1 );

    // I returned the element 0
    return data[0];
}

Update:

Just for completeness: The OP found also a failure on the write function. He had posted a separate answer, I voted up to mark it. Because this is the accepted answer, I also copied his post to here for completeness and the readers convenience.

Original post by R1S8K:

OK, I found a the answer and it was a good lesson in dealing with functions that receives pointers.

I forgot that the writeTo function also receives a pointer and I have to pass an array for both read/write functions.

void mcp23017_read(uint8_t *add_reg, uint8_t *buffer){
    twi_writeTo(MCP23017_ADD, add_reg, 1, 1, 1);    
    twi_readFrom(MCP23017_ADD, buffer, 1, 1);
}
Peter Paul Kiefer
  • 1,893
  • 9
  • 11
1

OK, I found one little mistake in my coding.

I forgot that the writeTo function also receives a pointer and I have to pass an array for both read/write functions.

void mcp23017_read(uint8_t *add_reg, uint8_t *buffer){
    twi_writeTo(MCP23017_ADD, add_reg, 1, 1, 1);    
    twi_readFrom(MCP23017_ADD, buffer, 1, 1);
}
R1S8K
  • 283
  • 3
  • 21