Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Servo.h>
- // Pin Definitions
- const int switchPin = 2; // Digital pin for the switch
- const int servoPin = 9; // Digital pin for the servo
- // Servo Settings
- const int servoMinAngle = 0; // Minimum angle for the servo
- const int servoMaxAngle = 45; // Maximum angle for the servo
- const int servoSpeed = 1; // Speed of servo movement (range: 1-9)
- // Global Variables
- Servo myServo;
- bool switchState = false;
- int currentAngle = 0;
- void setup() {
- // Set switch pin as input with internal pull-up resistor
- pinMode(switchPin, INPUT_PULLUP);
- // Attach servo to the corresponding pin
- myServo.attach(servoPin);
- // Initial position of the servo
- myServo.write(currentAngle);
- }
- void loop() {
- // Read the state of the switch
- switchState = digitalRead(switchPin);
- if (switchState == HIGH) {
- // Switch is pressed, move servo from 0 to 45 degrees
- if (currentAngle < servoMaxAngle) {
- currentAngle += servoSpeed;
- myServo.write(currentAngle);
- delay(15);
- }
- }
- else {
- // Switch is released, move servo from 45 to 0 degrees
- if (currentAngle > servoMinAngle) {
- currentAngle -= servoSpeed;
- myServo.write(currentAngle);
- delay(15);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment