Shubham Santosh
Published © GPL3+

Joystick controlled mouse

Controls cursor using a simple joystick

BeginnerFull instructions provided33,052
Joystick controlled mouse

Things used in this project

Story

Read more

Schematics

Sketch

Code

Arduino Code

Arduino
////////////////////////////////
// Joystick controlled mouse///
/// by Shubham Santosh////////
/////////////////////////////


void setup() 
{
  Serial.begin(9600);
  pinMode(9,INPUT);     // SW pin
  digitalWrite(9,HIGH);

}
int prev_state=0;   // previous state of switch
void loop() {
  int z=0,xpos=0,ypos=0;
  int x=analogRead(A0);
  int y=analogRead(A1);
  int sensitivity=10;    // you can adjust the sensitivity based on your comfort
  if(x>=550)                     // when moved up 
  xpos=map(x,550,1023,0,sensitivity); 
  if(x<=450)                   // when moved down
  xpos=map(x,450,0,0,-sensitivity);   
  if(y>=550)                    // when moved right
  ypos=map(y,550,1023,0,sensitivity);  
  if(y<=450)                  // when moved left
  ypos=map(y,450,0,0,-sensitivity); 
  int curr_state=digitalRead(9);
  if(curr_state==1 && prev_state==0)   // when SW is pressed 
  z=1;
  else
  z=0;
  if(xpos!=0 or ypos!=0 or z==1) // prints only when the joystick is moved
  {
  Serial.print(xpos);    // print the data and separating by ":"
  Serial.print(":");
  Serial.print(ypos);
  Serial.print(":");
  Serial.println(z);
  }
  prev_state=curr_state;
  delay(10);         // for normal operation
}

Python Code

Python
# Joystick controlled mouse
# By Shubham Santosh
# last edited 12/11/2020
import mouse, sys
import time 
import serial

mouse.FAILSAFE=False
ArduinoSerial=serial.Serial('com3',9600)  #Specify the correct COM port
time.sleep(1)                             #delay of 1 second

while 1:
   data=str(ArduinoSerial.readline().decode('ascii'))   #read the data
   (x,y,z)=data.split(":")           # assigns to x,y and z
   (X,Y)=mouse.get_position()        #read the cursor's current position
   (x,y)=(int(x),int(y))                           #convert to int
   mouse.move(X+x,Y-y)           #move cursor to desired position
   if '1' in z:                        # read the Status of SW
      mouse.click(button="left")    # clicks left button
     

Credits

Shubham Santosh

Shubham Santosh

13 projects • 100 followers
I am a 25 yo electronic enthusiast.

Comments