encoderWithBasicLibraryFunction.ino 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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.pinMode(encoderPinA, INPUT_PULLUP);
  36. pcf8574.pinMode(encoderPinB, INPUT_PULLUP);
  37. // encoder button
  38. pcf8574.pinMode(P2, INPUT_PULLUP);
  39. // Set low latency with this method or uncomment LOW_LATENCY define in the library
  40. // Needed for encoder
  41. pcf8574.setLatency(0);
  42. // Start library
  43. Serial.print("Init pcf8574...");
  44. if (pcf8574.begin()){
  45. Serial.println("OK");
  46. }else{
  47. Serial.println("KO");
  48. }
  49. }
  50. bool changed = false;
  51. void loop()
  52. {
  53. if (changed){
  54. Serial.print("ENCODER --> ");
  55. Serial.print(encoderValue);
  56. Serial.print(" - BUTTON --> ");
  57. Serial.println(encoderButtonVal?"HIGH":"LOW");
  58. changed = false;
  59. }
  60. }
  61. uint8_t encoderPinALast = LOW;
  62. uint8_t valPrecEncoderButton = LOW;
  63. void updateEncoder(){
  64. // Encoder management
  65. uint8_t n = pcf8574.digitalRead(encoderPinA);
  66. if ((encoderPinALast == LOW) && (n == HIGH)) {
  67. if (pcf8574.digitalRead(encoderPinB) == LOW) {
  68. encoderValue--;
  69. changed = true; // Chnged the value
  70. } else {
  71. encoderValue++;
  72. changed = true; // Chnged the value
  73. }
  74. }
  75. encoderPinALast = n;
  76. // Button management
  77. encoderButtonVal = pcf8574.digitalRead(P2);
  78. if (encoderButtonVal!=valPrecEncoderButton){
  79. changed = true; // Chnged the value of button
  80. valPrecEncoderButton = encoderButtonVal;
  81. }
  82. }