encoderWithFullLibraryFunction.ino 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * PCF8574 GPIO Port Expand
  3. * https://www.mischianti.org/2020/03/13/pcf8574-i2c-digital-i-o-expander-rotary-encoder-part-2/
  4. *
  5. * PCF8574 ----- WeMos
  6. * A0 ----- GRD
  7. * A1 ----- GRD
  8. * A2 ----- GRD
  9. * VSS ----- GRD
  10. * VDD ----- 5V/3.3V
  11. * SDA ----- D1(PullUp)
  12. * SCL ----- D2(PullUp)
  13. * INT ----- INT(PullUp)
  14. *
  15. * P0 ----------------- ENCODER PIN A
  16. * P1 ----------------- ENCODER PIN B
  17. * P2 ----------------- ENCODER BUTTON
  18. *
  19. */
  20. #include "Arduino.h"
  21. #include "PCF8574.h"
  22. int encoderPinA = P0;
  23. int encoderPinB = P1;
  24. #define INTERRUPTED_PIN D7
  25. void ICACHE_RAM_ATTR updateEncoder();
  26. // initialize library
  27. PCF8574 pcf8574(0x38, INTERRUPTED_PIN, updateEncoder);
  28. volatile long encoderValue = 0;
  29. uint8_t encoderButtonVal = HIGH;
  30. void setup()
  31. {
  32. Serial.begin (9600);
  33. delay(500);
  34. // encoder pins
  35. pcf8574.encoder(encoderPinA, encoderPinB);
  36. // encoder button
  37. pcf8574.pinMode(P2, INPUT);
  38. // Start library
  39. Serial.print("Init pcf8574...");
  40. if (pcf8574.begin()){
  41. Serial.println("OK");
  42. }else{
  43. Serial.println("KO");
  44. }
  45. }
  46. bool changed = false;
  47. // The loop function is called in an endless loop
  48. void loop()
  49. {
  50. if (changed){
  51. Serial.print("ENCODER --> ");
  52. Serial.print(encoderValue);
  53. Serial.print(" - BUTTON --> ");
  54. Serial.println(encoderButtonVal?"HIGH":"LOW");
  55. changed = false;
  56. }
  57. }
  58. bool valPrecEncoderButton = LOW;
  59. void updateEncoder(){
  60. changed = pcf8574.readEncoderValue(encoderPinA, encoderPinB, &encoderValue);
  61. // int vale = pcf8574.readEncoderValue(encoderPinA, encoderPinB);
  62. // if (vale!=0){
  63. // changed = true;
  64. // }
  65. // encoderValue = encoderValue + vale;
  66. // Button management
  67. encoderButtonVal = pcf8574.digitalRead(P2);
  68. if (encoderButtonVal!=valPrecEncoderButton){
  69. changed = true; // Chnged the value of button
  70. valPrecEncoderButton = encoderButtonVal;
  71. }
  72. }