Using the joystick with Arduino

 https://www.robotique.tech/robotics/using-the-joystick-with-arduino/







#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 20, 4);
int VRx = A0;
int VRy = A1;
int SW = 2;
int xPosition = 0;
int yPosition = 0;
int SW_state = 0;
int mapX = 0;
int mapY = 0;

void setup() {
lcd.init();
pinMode(VRx, INPUT);
pinMode(VRy, INPUT);
pinMode(SW, INPUT_PULLUP);
}

void loop() {
lcd.backlight();
lcd.clear(); 
xPosition = analogRead(VRx);
yPosition = analogRead(VRy);
SW_state = digitalRead(SW);
mapX = map(xPosition, 0, 1023, -512, 512);
mapY = map(yPosition, 0, 1023, -512, 512);

if ((mapX>=-515)&& (mapX<=-510)&&(mapY>=-175)&& (mapY<=-168))
lcd.print("Forward");//When the user points the joystick controller forward, the word “Forward” is displayed.
if ((mapX>=168)&& (mapX<=175)&&(mapY>=-175)&& (mapY<=-168))
lcd.print("Backward");//When the user moves the joystick to the rear, the word “Backward” is displayed.
if ((mapX<=-166)&& (mapX>=-175)&&(mapY>=-515)&& (mapY<=-510))
lcd.print("Right");//When the user points the joystick to the right, the word “Right” is displayed
if ((mapX>=-175)&& (mapX<=-170)&&(mapY>=165)&& (mapY<=175))
lcd.print("Left");//When the user points the joystick to the left, the word “Left” is displayed.
if (SW_state==0)
lcd.print("Pressed button");
delay(1000);
}



留言