Arduino4Leds4ButtonsWithInterrupt.ino 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. KeyPressed and leds with interrupt
  3. by Mischianti Renzo <http://www.mischianti.org>
  4. https://www.mischianti.org/2019/01/02/pcf8574-i2c-digital-i-o-expander-fast-easy-usage/
  5. */
  6. #include "Arduino.h"
  7. #include "PCF8574.h"
  8. // For arduino uno only pin 1 and 2 are interrupted
  9. #define ARDUINO_UNO_INTERRUPTED_PIN 2
  10. // Function interrupt
  11. void keyPressedOnPCF8574();
  12. // Set i2c address
  13. PCF8574 pcf8574(0x38, ARDUINO_UNO_INTERRUPTED_PIN, keyPressedOnPCF8574);
  14. unsigned long timeElapsed;
  15. void setup()
  16. {
  17. Serial.begin(115200);
  18. pcf8574.pinMode(P0, INPUT_PULLUP);
  19. pcf8574.pinMode(P1, INPUT_PULLUP);
  20. pcf8574.pinMode(P2, INPUT);
  21. pcf8574.pinMode(P3, INPUT);
  22. pcf8574.pinMode(P7, OUTPUT);
  23. pcf8574.pinMode(P6, OUTPUT, HIGH);
  24. pcf8574.pinMode(P5, OUTPUT);
  25. pcf8574.pinMode(P4, OUTPUT, LOW);
  26. Serial.print("Init pcf8574...");
  27. if (pcf8574.begin()){
  28. Serial.println("OK");
  29. }else{
  30. Serial.println("KO");
  31. }
  32. timeElapsed = millis();
  33. }
  34. unsigned long lastSendTime = 0; // last send time
  35. unsigned long interval = 4000; // interval between sends
  36. bool startVal = HIGH;
  37. bool keyPressed = false;
  38. void loop()
  39. {
  40. if (keyPressed){
  41. uint8_t val0 = pcf8574.digitalRead(P0);
  42. uint8_t val1 = pcf8574.digitalRead(P1);
  43. uint8_t val2 = pcf8574.digitalRead(P2);
  44. uint8_t val3 = pcf8574.digitalRead(P3);
  45. Serial.print("P0 ");
  46. Serial.print(val0);
  47. Serial.print(" P1 ");
  48. Serial.print(val1);
  49. Serial.print(" P2 ");
  50. Serial.print(val2);
  51. Serial.print(" P3 ");
  52. Serial.println(val3);
  53. keyPressed= false;
  54. }
  55. if (millis() - lastSendTime > interval) {
  56. pcf8574.digitalWrite(P7, startVal);
  57. if (startVal==HIGH) {
  58. startVal = LOW;
  59. }else{
  60. startVal = HIGH;
  61. }
  62. lastSendTime = millis();
  63. Serial.print("P7 ");
  64. Serial.println(startVal);
  65. }
  66. }
  67. void keyPressedOnPCF8574(){
  68. // Interrupt called (No Serial no read no wire in this function, and DEBUG disabled on PCF library)
  69. keyPressed = true;
  70. }