#include <Servo.h>
Servo leftServo; // Declare left servo object
Servo rightServo; // Declare right servo object
Servo randomServo; // Declare random servo object
int joystickXPin = A0; // Analog pin for X-axis of joystick
int joystickYPin = A1; // Analog pin for Y-axis of joystick
int buttonPin = A2; // Analog pin for button
int joystickXValue; // Variable to store X-axis joystick value
int joystickYValue; // Variable to store Y-axis joystick value
int buttonState = 0; // Variable for storing button state
int buttonPressCount = 0; // Counter for button presses
void setup() {
leftServo.attach(9); // Attach left servo to pin 9
rightServo.attach(10); // Attach right servo to pin 10
randomServo.attach(8); // Attach random servo to pin 8
pinMode(buttonPin, INPUT_PULLUP); // Set button pin as input with pull-up resistor
}
void loop() {
joystickXValue = analogRead(joystickXPin); // Read X-axis value from joystick
joystickYValue = analogRead(joystickYPin); // Read Y-axis value from joystick
buttonState = digitalRead(buttonPin); // Read button state
// Map joystick values to servo range (0-180)
int leftServoPos = map(joystickYValue, 0, 1023, 0, 180);
int rightServoPos = map(joystickYValue, 0, 1023, 0, 180);
// Apply V-tail mixing for turning with X-axis of joystick
leftServoPos += map(joystickXValue, 0, 1023, -180, 180);
rightServoPos -= map(joystickXValue, 0, 1023, -180, 180);
// Ensure servo positions are within valid range
leftServoPos = constrain(leftServoPos, 0, 180);
rightServoPos = constrain(rightServoPos, 0, 180);
// Write the positions to the servos
leftServo.write(leftServoPos);
rightServo.write(rightServoPos);
// Check button press and alternate actions
if (buttonState == LOW) {
delay(50); // Debounce delay
if (buttonState == LOW) { // Check button state again after debounce
buttonPressCount++; // Increment button press count
// Every odd press (1st, 3rd, 5th, etc.)
if (buttonPressCount % 2 == 1) {
int randomPosition = random(0, 180); // Generate random position (0-179)
randomServo.write(randomPosition); // Move random servo to the random position
}
// Every even press (2nd, 4th, 6th, etc.)
else {
randomServo.write(90); // Set random servo to 90 degrees
}
delay(500); // Delay for a short time to observe movement, adjust as needed
}
}
delay(20); // Small delay for stability, adjust as needed
}