#include <ESP32Servo.h>
#define VRX_PIN 34 // ESP32 pin GPIO36 (ADC0) connected to VRX pin
#define VRY_PIN 35 // ESP32 pin GPIO39 (ADC0) connected to VRY pin
#define SERVO_X_PIN 13 // ESP32 pin GPIO13 connected to Servo motor 1
#define SERVO_Y_PIN 25 // ESP32 pin GPIO25 connected to Servo motor 2
#define BUTTON_PIN 18 // ESP32 pin GPIO18, which is connected to the button
#define LED_PIN 21 // ESP32 pin GPIO21, which is connected to the LED
Servo xServo; // create a servo object to control servo 1
Servo yServo; // create a servo object to control servo 2
int led_state = LOW; // the current state of the LED
int button_state; // the current state of the button
int last_button_state; // the previous state of the button
void setup() {
Serial.begin(9600);
xServo.attach(SERVO_X_PIN);
yServo.attach(SERVO_Y_PIN);
pinMode(BUTTON_PIN, INPUT_PULLUP); // set ESP32 pin to input pull-up mode
pinMode(LED_PIN, OUTPUT); // set ESP32 pin to output mode
button_state = digitalRead(BUTTON_PIN);
}
void loop() {
// read X and Y analog values
int valueX = analogRead(VRX_PIN);
int valueY = analogRead(VRY_PIN);
int xAngle = map(valueX, 0, 4095, 180, 0); // scale it to the servo's angle (0 to 180)
int yAngle = map(valueY, 0, 4095, 0, 180); // scale it to the servo's angle (0 to 180)
xServo.write(xAngle); // set the servo angle for X-axis
yServo.write(yAngle); // set the servo angle for Y-axis
last_button_state = button_state; // save the last state
button_state = digitalRead(BUTTON_PIN); // read the new state
if (last_button_state == HIGH && button_state == LOW) {
Serial.println("The button is pressed");
// toggle the state of the LED
led_state = !led_state;
digitalWrite(LED_PIN, led_state); // control the LED according to the toggled state
}
}