/* Some functional code borrowed from xreef/PCF8574_library here : https://github.com/xreef/PCF8574_library/blob/master/examples/Arduino4Leds4ButtonsWithInterrupt/Arduino4Leds4ButtonsWithInterrupt.ino
KeyPressed and leds with interrupt
by Mischianti Renzo <http://www.mischianti.org>
https://www.mischianti.org/2019/01/02/pcf8574-i2c-digital-i-o-expander-fast-easy-usage/
*/
#include "PCF8574.h"
// For arduino uno only pin 1 and 2 are interrupted
const int INTERRUPT_PIN = 2;
const int INTERRUPT_LED_PIN = 13;
// Starting address is 0x20 with A2-A0 set at 0
const int PCF_ADDR = 0x20;
// Function interrupt
void keyPressInterruptHandler();
// Set i2c address
PCF8574 pcf8574(PCF_ADDR, INTERRUPT_PIN, keyPressInterruptHandler);
void setup() {
Serial.begin(9600);
pinMode(INTERRUPT_PIN, INPUT);
pinMode(INTERRUPT_LED_PIN, OUTPUT);
pcf8574.pinMode(P0, INPUT);
pcf8574.pinMode(P1, INPUT);
pcf8574.pinMode(P2, INPUT);
pcf8574.pinMode(P3, INPUT);
pcf8574.pinMode(P4, OUTPUT);
pcf8574.pinMode(P5, OUTPUT);
pcf8574.pinMode(P6, OUTPUT);
pcf8574.pinMode(P7, OUTPUT);
Serial.print("Checking I2C Address... ");
if (pcf8574.begin()) {
Serial.println("OK");
} else {
Serial.println("Change PCF_ADDR");
}
}
bool * ledValues[] = {HIGH, HIGH, HIGH, HIGH}; //HIGH means off, which is where we want to start.
bool keyPressed = false;
void loop() {
if (keyPressed) { //if any pin changes
ledValues[0] = pcf8574.digitalRead(P0); //set corresponding LED to switch value on dip-8
ledValues[1] = pcf8574.digitalRead(P1);
ledValues[2] = pcf8574.digitalRead(P2);
ledValues[3] = pcf8574.digitalRead(P3);
//Could have updated lights without interrupt, but wanted to show functionality
pcf8574.digitalWrite(P4, ledValues[0]);
pcf8574.digitalWrite(P5, ledValues[1]);
pcf8574.digitalWrite(P6, ledValues[2]);
pcf8574.digitalWrite(P7, ledValues[3]);
keyPressed = false;
}
}
void keyPressInterruptHandler() {
// Interrupt called (No Serial no read no wire in this function, and DEBUG disabled on PCF library)
keyPressed = true;
digitalWrite(INTERRUPT_LED_PIN, HIGH);
delay(20); //not supposed to have delays in interrupts; this is just to show functionality
digitalWrite(INTERRUPT_LED_PIN, LOW);
}