Created
March 12, 2024 17:08
-
-
Save maagmirror/4f1ba1afbed6bce5cb4ce7f573fe16e0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <avr/sleep.h> | |
#include <avr/power.h> | |
#include <Servo.h> | |
#include <ezButton.h> | |
// Constants | |
const int BUTTON_PIN_1 = 7; | |
const int BUTTON_PIN_2 = 6; | |
const int SERVO_PIN = 8; | |
const int LED_PIN = 13; | |
ezButton button1(BUTTON_PIN_1); | |
ezButton button2(BUTTON_PIN_2); | |
Servo servo; | |
int angle = 0; | |
bool servoActive = false; | |
unsigned long lastDebounceTime = 0; | |
unsigned long debounceDelay = 50; | |
unsigned long lastToggleTime = 0; | |
const long toggleInterval = 500; | |
void setup() { | |
Serial.begin(9600); | |
servo.attach(SERVO_PIN); | |
pinMode(LED_PIN, OUTPUT); | |
servo.write(angle); | |
// Configura los pines de los botones para generar interrupciones externas | |
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN_1), wakeUp, CHANGE); | |
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN_2), wakeUp, CHANGE); | |
// Configura el modo sleep | |
set_sleep_mode(SLEEP_MODE_PWR_DOWN); | |
} | |
void loop() { | |
button1.loop(); | |
button2.loop(); | |
if (millis() - lastDebounceTime > debounceDelay) { | |
handleButtonPress(button1); | |
handleButtonPress(button2); | |
} | |
updateLED(); | |
// Si no hay acción, pon el microcontrolador en modo sleep | |
goToSleep(); | |
} | |
void handleButtonPress(ezButton& button) { | |
if (button.isPressed()) { | |
if (millis() - lastToggleTime > toggleInterval) { | |
toggleServo(); | |
lastToggleTime = millis(); | |
} | |
} | |
} | |
void toggleServo() { | |
angle = servoActive ? 0 : 90; | |
servo.write(angle); | |
servoActive = !servoActive; | |
lastDebounceTime = millis(); | |
} | |
void updateLED() { | |
digitalWrite(LED_PIN, servoActive && abs(servo.read() - 90) <= 2 ? HIGH : LOW); | |
} | |
void goToSleep() { | |
sleep_enable(); | |
sleep_cpu(); | |
sleep_disable(); | |
} | |
void wakeUp() { | |
// Esta función es llamada por la interrupción externa | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment