when I touch the pin or the buttons connected to the pin I am getting false readings does anyone know the cause
here's the code
#include <BleMouse.h>
BleMouse bleMouse; // Declare an instance of the BleMouse class
// Pin assignments for joystick, buttons, LED
const int JoyPinX = 32;
const int JoyPinY = 25;
const int BtnL = 15;
const int BtnR = 18;
const int LedPin = 2;
bool LBP = false;
bool RBP = false;
const int InvX = -1; // Inversion factors for joystick values
const int InvY = 1;
int MouseX, MouseY, JoyX, JoyY = 0; // Variables for storing joystick and mouse values
int STP = 4; // Mouse movement step size
// Function to read joystick values
void Joy_Get_Val(){
// Read analog joystick values and scale them
JoyX = (analogRead(JoyPinX) / 100) - 30 ;
JoyY = (analogRead(JoyPinY) / 100) - 29 ;
// Determine mouse movement in the X-axis
if (JoyX > 5) {
MouseX = STP * InvX;
} else if (JoyX < -5) {
MouseX = -STP * InvX;
} else {
MouseX = 0;
}
// Determine mouse movement in the Y-axis
if (JoyY > 4) {
MouseY = STP * InvY;
} else if (JoyY < -4) {
MouseY = -STP * InvY;
} else {
MouseY = 0;
}
}
// Function to blink the LED as an indicator
void Start_Indicator (){
for (int i = 0; i < 2; i++){
digitalWrite(LedPin, HIGH);
delay(500);
digitalWrite(LedPin, LOW);
delay(500);
}
}
// Function to move the mouse based on joystick values
void Move_Mouse() {
unsigned long startTime = millis();
while (millis() < startTime + 10) {
bleMouse.move(MouseX, MouseY); // Move the mouse
delay(10); // Small delay for stability
}
}
// Function to handle button presses
void Button_Press(){
if (digitalRead(BtnL) == 1 && LBP == false) {
//bleMouse.press(MOUSE_LEFT);
LBP = true;
//Serial.println("LEFT Press");
} else if (digitalRead(BtnL) == 0 && LBP == true){
//bleMouse.release(MOUSE_LEFT);
LBP = false;
//Serial.println("LEFT Release");
delay(50);
}
if (digitalRead(BtnR) == 1 && RBP == false) {
//bleMouse.press(MOUSE_RIGHT);
RBP = true;
//Serial.println("RIGHT Press");
} else if (digitalRead(BtnR) == 0 && RBP == true){
//bleMouse.release(MOUSE_RIGHT);
RBP = false;
//Serial.println("RIGHT Release");
delay(50);
}
}
// Function for testing and debugging
void test () {
Serial.print("X : ");
Serial.println(MouseX);
Serial.print("Y : ");
Serial.println(MouseY);
Serial.print("L : ");
Serial.println(digitalRead(BtnL));
Serial.print("R : ");
Serial.println(digitalRead(BtnR));
delay(500);
}
void setup() {
pinMode(JoyPinX, INPUT);
pinMode(JoyPinY, INPUT);
pinMode(BtnL, INPUT);
pinMode(BtnR, INPUT);
pinMode(LedPin, OUTPUT);
Serial.begin(115200);
bleMouse.begin(); // Initialize the BLE mouse
Start_Indicator(); // Blink LED to indicate start
}
void test2 () {
Serial.print("LFT :");
Serial.println(LBP);
Serial.print("RIG :");
Serial.println(RBP);
delay (200);
}
void loop() {
Joy_Get_Val(); // Read joystick values
if (bleMouse.isConnected()) {
Move_Mouse(); // Move mouse if connected
Button_Press(); // Handle button presses
test2 ();
}
//test(); // Uncomment this line for testing
}