#include <Servo.h>
// Define pin numbers
const int servoPin = 9; // Pin connected to servo signal
const int relayPin = 8; // Pin connected to relay control
const int buttonPin = 7; // Pin connected to button
// Create a Servo object
Servo myServo;
// Variables for state management
bool relayState = false; // Relay state (true = on, false = off)
int servoPosition = 0; // Servo position (0, 90, 180 degrees)
bool lastButtonState = LOW; // Previous button state
unsigned long lastDebounceTime = 0; // Time of last button state change
unsigned long debounceDelay = 50; // Delay to debounce the button
void setup() {
pinMode(relayPin, OUTPUT); // Set relay pin as output
pinMode(buttonPin, INPUT); // Set button pin as input
myServo.attach(servoPin); // Attach servo to the pin
// Initialize relay and servo
digitalWrite(relayPin, LOW); // Relay initially off
myServo.write(servoPosition); // Servo initially at 0 degrees
}
void loop() {
// Read the button state
int buttonState = digitalRead(buttonPin);
// Check for button state change
if (buttonState != lastButtonState) {
lastDebounceTime = millis(); // Update debounce timer
}
// If the button state has been stable for longer than the debounce delay
if ((millis() - lastDebounceTime) > debounceDelay) {
// If the button state has changed
if (buttonState != lastButtonState) {
lastButtonState = buttonState; // Update last button state
if (buttonState == HIGH) { // If button is pressed
// Update the servo position
servoPosition += 90;
if (servoPosition > 180) {
servoPosition = 0; // Reset to 0 if it exceeds 180
}
// Update the relay and servo
if (servoPosition == 0) {
digitalWrite(relayPin, LOW); // Turn off relay
} else {
digitalWrite(relayPin, HIGH); // Turn on relay
}
// Move the servo to the new position
myServo.write(servoPosition);
}
}
}
}