Week 9
This week, I tried controlling servo motor with joystick, I used my existing board to achive this, here is a video demonstrating how it works!
And here is the code I used!
#include
Servo myservo; // create servo object to control a servo
// Define joystick pins
const int joyX = A0; // joystick X-axis
const int joyY = A2; // joystick Y-axis
void setup() {
myservo.attach(2); // attaches the servo on pin 9 to the servo object
// Initialize joystick pins
pinMode(joyX, INPUT);
pinMode(joyY, INPUT);
}
void loop() {
int xVal = analogRead(joyX); // read the value from the joystick X-axis
int yVal = analogRead(joyY); // read the value from the joystick Y-axis
// Map the joystick value to a servo position
int servoPos = map(xVal, 0, 1023, 0, 180); // map X-axis value to a range of 0-180
myservo.write(servoPos); // set servo position
delay(15); // delay for the servo to reach the position
}