int joystickX; // Store X-axis joystick value
int joystickY; // Store Y-axis joystick value
int motor1Pin1 = 2; // Motor 1 control pins
int motor1Pin2 = 4;
int motor2Pin1 = 3; // Motor 2 control pins
int motor2Pin2 = 5;
void setup() {
pinMode(motor1Pin1, OUTPUT);
pinMode(motor1Pin2, OUTPUT);
pinMode(motor2Pin1, OUTPUT);
pinMode(motor2Pin2, OUTPUT);
}
void loop() {
// Read joystick values
joystickX = analogRead(A0);
joystickY = analogRead(A1);
// Forward or backward motion
if (joystickY < 500)
{
moveForward();
}
else if (joystickY > 520)
{
moveBackward();
}
else
{
stopMotors();
}
// Left or right motion
if (joystickX < 500)
{
turnLeft();
}
else if (joystickX > 520)
{
turnRight();
}
else
{
stopMotors();
}
}
void moveForward() {
digitalWrite(motor1Pin1, HIGH);
digitalWrite(motor1Pin2, LOW);
digitalWrite(motor2Pin1, HIGH);
digitalWrite(motor2Pin2, LOW);
}
void moveBackward() {
digitalWrite(motor1Pin1, LOW);
digitalWrite(motor1Pin2, HIGH);
digitalWrite(motor2Pin1, LOW);
digitalWrite(motor2Pin2, HIGH);
}
void stopMotors() {
digitalWrite(motor1Pin1, LOW);
digitalWrite(motor1Pin2, LOW);
digitalWrite(motor2Pin1, LOW);
digitalWrite(motor2Pin2, LOW);
}
void turnLeft() {
digitalWrite(motor1Pin1, LOW);
digitalWrite(motor1Pin2, HIGH);
digitalWrite(motor2Pin1, HIGH);
digitalWrite(motor2Pin2, LOW);
}
void turnRight() {
digitalWrite(motor1Pin1, HIGH);
digitalWrite(motor1Pin2, LOW);
digitalWrite(motor2Pin1, LOW);
digitalWrite(motor2Pin2, HIGH);
}
/* Components you'll need:
Arduino board (e.g., Arduino Uno)
Joystick module
Two DC motors
Wheels
H-bridge motor driver (e.g., L298N)
Chassis for the car
Battery pack or power source
Jumper wires
Circuit Connections:
Connect the X-axis of the joystick module to analog pin A0 on the Arduino.
Connect the Y-axis of the joystick module to analog pin A1 on the Arduino.
Connect the motor driver inputs to the Arduino:
Motor 1: Connect one terminal to digital pin 2 (for control in one direction) and the other terminal to digital pin 4 (for control in the other direction).
Motor 2: Connect one terminal to digital pin 3 (for control in one direction) and the other terminal to digital pin 5 (for control in the other direction).
Connect the motor driver outputs to the DC motors and power source.
This code reads the X and Y values from the joystick and controls the movement of the car.
When you move the joystick forward, the car moves forward, and similarly, for other directions.
The H-bridge motor driver is used to control the direction of the motors.
Remember to adjust the pin connections and threshold values as needed for your specific components.
*/