const int buttonPin = 25; // Pin connected to the button
const int ledPin = 26; // Pin connected to the LED
const int servoPin = 27; // Pin connected to the servo motor
int buttonState = 0; // Variable for storing the button state
bool isLedOn = false; // Variable to track the LED state
int servoPos = 0; // Variable to store servo position
void setup() {
pinMode(ledPin, OUTPUT); // Set the LED pin as an output
pinMode(buttonPin, INPUT); // Set the button pin as an input
pinMode(servoPin, OUTPUT); // Set the servo pin as an output
}
void loop() {
buttonState = digitalRead(buttonPin); // Read the state of the button
if (buttonState == HIGH) {
if (!isLedOn) {
digitalWrite(ledPin, HIGH); // Turn on the LED if it's currently off
isLedOn = true;
moveServo(90); // Move the servo to 90 degrees position
} else {
digitalWrite(ledPin, LOW); // Turn off the LED if it's currently on
isLedOn = false;
moveServo(0); // Move the servo to 0 degrees position
}
// A small delay to debounce the button
delay(200);
}
}
void moveServo(int degrees) {
int pos = map(degrees, 0, 180, 0, 180); // Map degrees to servo range
digitalWrite(servoPin, HIGH); // Start the pulse
delayMicroseconds(500 + (pos * 11.11)); // 500 microseconds + angle * 11.11 microseconds
digitalWrite(servoPin, LOW); // Stop the pulse
delay(20); // A small delay between pulses
}