#include <Servo.h>
// Define pins
const int buttonPin = 7;
const int servoPin = 11;
const int greenLedPin = 12;
const int redLedPin = 13;
// Create servo object
Servo myServo;
// Button state
bool buttonPressed = false;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set the pin modes
pinMode(buttonPin, INPUT_PULLUP); // Use internal pull-up resistor
pinMode(greenLedPin, OUTPUT);
pinMode(redLedPin, OUTPUT);
// Attach the servo motor to the servoPin
myServo.attach(servoPin);
// Initially set the servo to 0 degrees
myServo.write(0);
digitalWrite(greenLedPin, LOW);
digitalWrite(redLedPin, HIGH);
}
void loop() {
// Read the state of the push button
buttonPressed = digitalRead(buttonPin) == LOW; // LOW when pressed
if (buttonPressed) {
// If the button is pressed, turn the servo to 90 degrees and light up the green LED
myServo.write(0);
digitalWrite(greenLedPin, HIGH);
digitalWrite(redLedPin, LOW);
} else {
// If the button is not pressed, set the servo to 0 degrees and light up the red LED
myServo.write(90);
digitalWrite(greenLedPin, LOW);
digitalWrite(redLedPin, HIGH);
}
// Delay for debounce
delay(50);
}