#include <Servo.h>
const int BTN_PIN = 2;
const int X_SERVO_PIN = 4;
const int Y_SERVO_PIN = 3;
const int X_JOY_PIN = A0;
const int Y_JOY_PIN = A1;
Servo xServo;
Servo yServo;
// globals to hold joystick values
int oldXVal = 0;
int oldYVal = 0;
int oldBtnState = 1; // pin idles HIGH
void checkButton() {
int btnState = digitalRead(BTN_PIN);
if (btnState != oldBtnState) { // if it changed
oldBtnState = btnState; // remember state for next time
if (btnState == LOW) { // was just pressed
Serial.println("Button pressed");
} else { // was just released
Serial.println("Button released");
}
delay(20); // debounce
}
}
void setup() {
Serial.begin(9600);
pinMode(BTN_PIN, INPUT_PULLUP);
xServo.attach(X_SERVO_PIN);
yServo.attach(Y_SERVO_PIN);
}
void loop() {
char buffer[16];
// check button
checkButton();
// check joysticks
int xValue = map(analogRead(X_JOY_PIN), 1024, 0, 0, 180);
if (xValue != oldXVal) {
oldXVal = xValue;
xServo.write(xValue);
snprintf(buffer, 16, "X servo°: %d", xValue);
Serial.println(buffer);
}
int yValue = map(analogRead(Y_JOY_PIN), 1024, 0, 180, 0);
if (yValue != oldYVal) {
oldYVal = yValue;
yServo.write(yValue);
snprintf(buffer, 16, "Y servo°: %d", yValue);
Serial.println(buffer);
}
}