#include <Servo.h>
Servo servoPan;
Servo servoTilt;
const int vrxPin = A1; // x-axis of joystick
const int vryPin = A0; // y-axis of joystick
const int swPin = 2; // button on joystick
const int panPin = 9; // servo pan
const int tiltPin = 10; // servo tilt
bool sweeping = false; // Flag to track sweeping state
bool lastButtonState = HIGH; // Variable to store last button state
void setup() {
servoPan.attach(panPin);
servoTilt.attach(tiltPin);
pinMode(vrxPin, INPUT);
pinMode(vryPin, INPUT);
pinMode(swPin, INPUT_PULLUP); // Use internal pull-up resistor
}
void loop() {
int vrxValue = analogRead(vrxPin);
int vryValue = analogRead(vryPin);
int swState = digitalRead(swPin); // Read the state of the button
// Check for button press
if (swState == LOW && lastButtonState == HIGH) {
sweeping = !sweeping; // Toggle sweeping state
delay(50); // Debounce delay
}
lastButtonState = swState; // Update last button state
if (sweeping) {
sweepServoPan();
} else {
// Inverted direction for pan servo
int panAngle = map(vrxValue, 0, 1023, 180, 0); // Mapping joystick x-axis value to servo angle
servoPan.write(panAngle);
// Inverted direction for tilt servo
int tiltAngle = map(vryValue, 0, 1023, 180, 0); // Mapping joystick y-axis value to servo angle
servoTilt.write(tiltAngle);
}
delay(15); // Small delay to prevent jitter
}
void sweepServoPan() {
static int pos = 0;
static int increment = 1;
servoPan.write(pos);
pos += increment;
if (pos >= 180 || pos <= 0) {
increment = -increment; // Reverse direction
}
delay(15); // Adjust delay for sweep speed
}