我正在尝试制作蓝牙控制台/操纵杆。由于 ESP32-WROOM-32 上的按钮数量有限,我计划在 I²C 引脚扩展器上放置 4 个旋转编码器。从原理图和代码中可以看出,我只是在这里测试第一个,它应该在顺时针方向按一次 button_1,在逆时针方向按一次 button_2。
#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);
}
当然,在此工作之后代码将被清理,并且为了不占用大量空间,bleGamepad.setControllerType() 的所有 bool 和 int 值都没有在帖子中声明。(使用的库)
现在的问题是,顺时针方向会触发 BUTTON_1 两次,逆时针方向方向会先触发 BUTTON_0,然后触发 BUTTON_1。我可以尝试的所有帮助、提示或事情将不胜感激。如果您需要更多信息来帮助,请告诉我。