Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

import turtle

import serial

# Set up the turtle screen and draw a black background


screen = turtle.Screen()
screen.bgcolor("black")

# Create a turtle for the joystick


joystick = turtle.Turtle()
joystick.shape("circle")
joystick.color("white")
joystick.pensize(4)
joystick.penup()

# Create a turtle for the center button


button = turtle.Turtle()
button.shape("square")
button.color("blue")
button.penup()

# Define a function to handle joystick movement


def moveJoystick(x, y):
joystick.clear()
joystick.goto(x, y)
joystick.pendown()
joystick.dot(30, "blue")
joystick.penup()
print("Joystick position: x =", x, ", y =", y)
# Scale the joystick coordinates to the range [-255, 255]
scaled_x = int(x * 255 / screen.window_width())
scaled_y = int(y * 255 / screen.window_height())
# Send the joystick coordinates to the Arduino via serial
ser.write(f"{scaled_x},{scaled_y}\n".encode())

# Bind the joystick movement function to the screen


screen.onscreenclick(moveJoystick)

# Open a serial connection to the Arduino via the HC-05 module


ser = serial.Serial('COM3', 9600)

# Hide the turtle cursor and start the main loop


joystick.hideturtle()
button.hideturtle()
turtle.done()
NJHGY67hubndso9

You might also like