import serial
# Replace with your Arduino's serial port (check device manager)
arduino_port = '/dev/ttyUSB0' # Linux/macOS
# arduino_port = 'COM3' # Windows (replace with actual port)
# Baud rate (needs to match Arduino code)
baud_rate = 9600
# Create serial connection
try:
ser = serial.Serial(arduino_port, baud_rate)
print("Connected to Arduino on", arduino_port)
except serial.SerialException as e:
print("Error connecting to Arduino:", e)
exit()
# Define key mapping (modify as needed)
key_map = {
'w': 'U', # Up
's': 'D', # Down
'a': 'L', # Left
'd': 'R' # Right
}
while True:
# Get key press (non-blocking to avoid waiting for key)
key = input("Press a key (w, s, a, d, or q to quit): ", timeout=0)
# Check if a key is pressed and handle commands
if key in key_map:
command = key_map[key]
print("Sending command:", command)
ser.write(command.encode()) # Encode to bytes for serial transmission
elif key == 'q':
print("Exiting...")
ser.close()
break # Exit the loop
print("Program terminated.")
CPP (for Ardiuno)
// Define motor control pins
const int motorPin1 = 3; // Motor pin 1
const int motorPin2 = 4; // Motor pin 2
void setup() {
// Set motor control pins as outputs
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
// Start serial communication at 9600 baud rate
Serial.begin(9600);
}
void loop() {
// Check if data is available to read
if (Serial.available() > 0) {
char command = [Serial.read](https://serial.read/)(); // Read the incoming byte
// Check the command and control the motor direction
if (command == 'U') {
digitalWrite(motorPin1, HIGH); // Set motorPin1 HIGH to move forward
digitalWrite(motorPin2, LOW); // Set motorPin2 LOW
} else if (command == 'W') {
digitalWrite(motorPin1, LOW); // Set motorPin1 LOW to move backward
digitalWrite(motorPin2, HIGH); // Set motorPin2 HIGH
} else {
// Stop the motor if any other character is received
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
}
}
}
Python(Rpi4)
CPP (for Ardiuno)