#include <Arduino.h>
#include <driver/ledc.h>
const int LEFT = 2; // Replace with the pin number for the left button
const int RIGHT = 5; // Replace with the pin number for the right button
const int servoChannel = 1; // Replace with the desired PWM channel for your servo
const int servoPin = 4; // Replace with the pin number to which the servo is connected
const int angleStep = 5; // Adjust the step for changing the angle
int angle = 90; // Starting angle, adjust as needed
void setup() {
pinMode(LEFT, INPUT_PULLUP);
pinMode(RIGHT, INPUT_PULLUP);
// Setup PWM channel for servo
ledcSetup(servoChannel, 60, 16); // 60 Hz frequency, 16-bit resolution (0-65535)
ledcAttachPin(servoPin, servoChannel);
// Initialize servo to default position (90 degrees)
ledcWrite(servoChannel, map(angle, 0, 180, 20, 260));
Serial.begin(9600);
}
void loop() {
// Read the state of the buttons
int increaseState = digitalRead(LEFT);
int decreaseState = digitalRead(RIGHT);
// Map the angle (in degrees) to a duty cycle value (0 to 260) for the servo
int servoDutyCycle = map(angle, 0, 180, 20, 260);
// Increase the angle if the increase button is pressed
if (increaseState == LOW && angle < 180) {
angle = angle + angleStep;
if (angle > 180) {
angle = 180;
}
servoDutyCycle = map(angle, 0, 180, 20, 260);
ledcWrite(servoChannel, servoDutyCycle);
Serial.print("Angle: ");
Serial.println(angle);
delay(200); // Adjust delay as needed for button debouncing
}
// Decrease the angle if the decrease button is pressed
if (decreaseState == LOW && angle > 0) {
angle = angle - angleStep;
if (angle < 0) {
angle = 0;
}
servoDutyCycle = map(angle, 0, 180, 20, 260);
ledcWrite(servoChannel, servoDutyCycle);
Serial.print("Angle: ");
Serial.println(angle);
delay(200); // Adjust delay as needed for button debouncing
}
delay(50); //Esperanding a que el servo llegue ahí
}