Go Down

Topic: Arduino Leonardo and PCF8574 (Read 158 times) previous topic - next topic

Lebois

Oct 11, 2018, 07:08 pm Last Edit: Oct 11, 2018, 08:07 pm by Lebois
Hi all !

I am trying to use one pcf8574 with my Leonardo to read 6 push-pull buttons. Diagram is below :


Code is :

Code: [Select]
#include <Wire.h>

uint8_t address;

uint8_t ReadIo()

  WriteIo(B11111111); // PCF8574 require us to set all outputs to 1 before doing a read.
 
  Wire.beginTransmission(address);
  Wire.requestFrom((int)address, 1); // Ask for 1 byte from slave
  uint8_t bits = Wire.read(); // read that one byte
  Wire.endTransmission();
 
  return bits;
}

void WriteIo(uint8_t bits)
{
  Wire.beginTransmission(address);
  Wire.write(bits);
  Wire.endTransmission();
}

void setup() {
  Wire.begin(); // Arduino needs (SDA=A4,SCL=A5)
  //Wire.begin(0,2); // ESP8266 needs (SDA=GPIO0,SCL=GPIO2)
  address = 0x20;
  Serial.begin(9600);
 
}

void loop() {
 
 
Serial.println("hello you");
delay(1000);
uint8_t bits = ReadIo(); // Read all switches
Serial.println(bits);
}


For the moment, I just try to have the bits, but nothing work... If you have any idea...

adwsystems

If all bits are inputs you don't need to write for every read. Just once in setup is enough. If there is a mix of inputs and outputs, then something else is required.

I believe you need to wait or check for a response

if (Wire.requestFrom(address,1) == 1)
{}

pylon

#2
Oct 11, 2018, 07:43 pm Last Edit: Oct 11, 2018, 07:45 pm by pylon
First: Always use code tags to post code!

Code: [Select]
  Wire.beginTransmission(address);
  Wire.requestFrom((int)address, 1); // Ask for 1 byte from slave
  uint8_t bits = Wire.read(); // read that one byte
  Wire.endTransmission();


You must not put Wire.beginTransmission() and Wire.endTransmission() calls around Wire.requestFrom(). The *Transmission calls are used only for writing to the bus.

Code: [Select]
uint8_t address;

That code won't work as no address is defined.

And post schematics and not Fritzing's breadboard view!

adwsystems

Code: [Select]
uint8_t address;

That code won't work as no address is defined.
Psst. I noticed that too. It's in setup() (set to 0x20).

Lebois

Psst. I noticed that too. It's in setup() (set to 0x20).
Is there a problem with the way address is set ?

adwsystems

No. Since the address can't change, most people would declare and assign the value at the same time in the same line.

Replacing

uint8_t address;

with


uint8_t address = 0x20; (and removing the line address = 0x20;)

pylon

Quote
Psst. I noticed that too. It's in setup() (set to 0x20).
I apologize, haven't seen that.

Go Up