A reader contacted me and asked if I would be so kind to put an example up showing you how to use the Arduino Port Expander Shield as digital inputs. I primarily used this as digital outputs before, but after writing the sketch I've got quite a few ideas for new projects (as always). Here's the code you need to read a pcf8574 pin:
#include <Wire.h>
#define expander B0111000 //pcf8574 with all address pins grounded
/* see <a href="http://www.practicalmaker.com/tutorials/port-expander-shield-documentation
for">http://www.practicalmaker.com/tutorials/port-expander-shield-documentati...</a> more info on configuring a pcf8574.
That article will also give you sample code as to how to toggle pcf8574 pins on
and off.
on the port expander shield the top row of pins is the one which you use to test statuses
*/
void setup() {
Wire.begin();
Serial.begin(9600);
expanderWrite(B11111111);
pinMode(13, OUTPUT);
}
void loop() {
byte pin_number = 0; //check status of pin 0
/* querying the pcf8574 returns a byte. each bit is the current status of each of
the 8 pins. 0 = low, 1 = high */
byte returnByte = expanderRead();
// we can use a funciton called bitread to get the status of any bit in the byte
// pin number starts at 0
boolean bitStatus = bitRead(returnByte, pin_number);
if(bitStatus == 1) {
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}
Serial.println(bitStatus, BIN);
delay(500);
}
void expanderWrite(byte _data ) {
Wire.beginTransmission(expander);
Wire.send(_data);
Wire.endTransmission();
}
byte expanderRead() {
byte _data;
Wire.requestFrom(expander, 1);
if(Wire.available()) {
_data = Wire.receive();
}
return _data;
}And of course it wouldn't be complete without a demo video:
Comments
Hello, nice test but I found
Hello,
nice test but I found some bugs, when I tried to run the Sketch:
-include "Wire.h" not include "wire.h" with Capital first Letter
-define expander B0100000 not define expander B0111000
-/wire.h at the end has to be deleted
Now its running fine and I can use it for my HomeAutomation Projekt. Thank You
Berry07
Thanks, fixed those typos. I
Thanks, fixed those typos. I never got the expander to work with address B0100000 though.
hmm, the PCF8574 has as
hmm,
the PCF8574 has as address 0100xxx, while the PCF857A has 0111xxx.
So it depends which chip has been used.
In my case it was PCF8574AN (0111xxx).
So, I suppose you can have up to 128 I/O channels by selecting different chips in the port expander shield...
Good to know!
Good to know!
Hi all, a little answer...if
Hi all,
a little answer...if i use a PCF8574AP and i have set A0, A1,A2 to +5 witch is the address i have to use??
Thx!!!
This is with all pins
This is with all pins grounded: B0111000
and if they're all high: B0111111
hello, I am looking for a
Can you post some more
"-define expander B0100000
Add new comment