Unit 19: Motor Movement
Code:
#include
Servo myServo; // Create a Servo object
// Joystick axis pins
const int joystickX = A0; // Horizontal position
const int joystickY = A1; // Vertical position
// Servo range and limits
const int minAngle = 0; // Minimum servo angle (left)
const int maxAngle = 180; // Maximum servo angle (right)
void setup() {
Serial.begin(9600); // Start serial communication for debugging
myServo.attach(7); // Attach servo to pin 9
myServo.write(90); // Start servo at the center position (90 degrees)
}
void loop() {
// Read joystick positions
int xPos = analogRead(joystickX); // Horizontal axis
int yPos = analogRead(joystickY); // Vertical axis
// Map joystick X position (0 to 1023) to servo angle (0 to 180 degrees)
int servoAngle = map(xPos, 0, 1023, minAngle, maxAngle);
// Print the joystick and servo information for debugging
Serial.print("Joystick X: ");
Serial.print(xPos);
Serial.print(" | Servo Angle: ");
Serial.println(servoAngle);
// Move the servo to the corresponding angle
myServo.write(servoAngle);
delay(50); // Small delay for smooth movement
}