#include <Arduino.h>
#include "driver/ledc.h"
#define SERVO_PIN 4
#define SERVO_FREQ 50
#define SERVO_CHANNEL 9
#define SERVO_RESOLUTION 16
int angle = 90; // Initial position for the servo
int angleStep = 5;
#define LEFT 2 // Pin 2 is connected to the left-oriented button
#define RIGHT 5 // Pin 5 is connected to the right-oriented button
void setup() {
Serial.begin(9600); // Serial setup
ledcSetup(SERVO_CHANNEL, SERVO_FREQ, SERVO_RESOLUTION);
ledcAttachPin(SERVO_PIN, SERVO_CHANNEL);
pinMode(LEFT, INPUT_PULLUP); // Assign pin 2 as input for the left button
pinMode(RIGHT, INPUT_PULLUP); // Assign pin 5 as input for the right button
ledcWrite(SERVO_CHANNEL, angleToDutyCycle(angle)); // Move the servo to the initial angle
}
void loop() {
while (digitalRead(RIGHT) == LOW) {
decreaseAngle();
delay(100); // Wait for the servo to reach the desired position
}
while (digitalRead(LEFT) == LOW) {
increaseAngle();
delay(100); // Wait for the servo to reach the desired position
}
}
void decreaseAngle() {
if (angle > 0) {
angle -= angleStep;
if (angle < 0) {
angle = 0;
}
updateServo();
}
}
void increaseAngle() {
if (angle < 180) {
angle += angleStep;
if (angle > 180) {
angle = 180;
}
updateServo();
}
}
void updateServo() {
ledcWrite(SERVO_CHANNEL, angleToDutyCycle(angle));
Serial.print("En: ");
Serial.print(angle);
Serial.println(" grados");
}
int angleToDutyCycle(int angle) {
return map(angle, 0, 180, 20, 260); // Map angle to the corresponding duty cycle (adjust min and max values as needed)
}