Double pulse for encoder with ESP32 and PCF8574

  arduino-esp32, c++, esp32, joystick

I’m trying to make a Bluetooth console/joystick. Because of limited amount of buttons on the ESP32-WROOM-32, I planned to put 4 rotary encoders on a I²C pin expander. As seen in the schematic and code, I’m just testing the first one here which should just push button_1 one time when going clockwise and button_2 for anti-clockwise.

schematic of the temporary setup

#include <Arduino.h>
#include <BleGamepad.h>
#include <Wire.h>
#include "PCF8574.h"

BleGamepad bleGamepad("EESSPP", "FoxSrk", 30);
PCF8574 pcf8574(Addr_PCF01);

void ReadPcfEnc(int btn)
{
  bleGamepad.press(btn);bleGamepad.sendReport();delay(20);
  bleGamepad.release(btn);bleGamepad.sendReport();delay(20);
}

void setup(){
  Serial.begin(9600);
  Wire.begin();
  delay(500);
  bleGamepad.setAutoReport(false);
  bleGamepad.setControllerType(CONTROLLER_TYPE_MULTI_AXIS); //CONTROLLER_TYPE_JOYSTICK, CONTROLLER_TYPE_GAMEPAD (DEFAULT), CONTROLLER_TYPE_MULTI_AXIS
  bleGamepad.begin(numOfButtons, numOfHatSwitches, enableX, enableY, enableZ, enableRZ, enableRX, enableRY, enableSlider1, enableSlider2, enableRudder, enableThrottle, enableAccelerator, enableBrake, enableSteering);

  pcf8574.pinMode(P0, INPUT_PULLUP);
    pcf8574.pinMode(P1, INPUT_PULLUP);

  // Start library
  Serial.print("Init pcf8574...");
}

float counter = 0.5;
int aState;
int aLastState;

void updateEncoder(int PN1, int PN2) {
  aState = pcf8574.digitalRead(PN1); // Reads the "current" state of the outputA
  // If the previous and the current state of the outputA are different, that means a Pulse has occured
  if (aState != aLastState){    
    // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
    if (pcf8574.digitalRead(PN2) != aState) {
      counter += 0.5;
      ReadPcfEnc(BUTTON_1);
    } else {
      counter -= 0.5;
      ReadPcfEnc(BUTTON_2);
    }
  }
  aLastState = aState; // Updates the previous state of the outputA with the current state
}

void loop(){
  if(bleGamepad.isConnected())
    updateEncoder(P0, P1);
  delay(20);
}

The code will be cleaned up after this works of course and for the sake of not taking up tons of space, all the bool and int values of bleGamepad.setControllerType() haven’t been declared in the post. ( lib used )

Problem now is, when going clockwise it triggers BUTTON_1 twice and when going anti-clockwise it triggers first BUTTON_0 then BUTTON_1.
All help, tips or things I can try would be greatly appreciated. If you need more info to help, let me know.

Source: Windows Questions C++

LEAVE A COMMENT