Unit 10: Servo and Protect

 

 

Code (check notes at base): 


#include 

// Pin definitions
const int BUTTON_PIN = 2;    // Button input pin
const int SERVO_PIN = 11;    // Servo control pin

// Servo object
Servo servoMotor;

void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP);  // Enable internal pull-up resistor
  servoMotor.attach(SERVO_PIN);       // Attach servo to pin
}

void loop() {
  if (digitalRead(BUTTON_PIN) == LOW) {  // Button is pressed (active LOW)
    servoMotor.write(90);     // Rotate to 90 degrees
    delay(1000);              // Wait 1 second
    servoMotor.write(0);      // Rotate back to 0 degrees
    delay(1000);              // Wait 1 second
  }
}

  

 

Notes: 

Use the Servo library by writing: #include <Servo.h> at the top of the sketch. This page treats it as instruction, so will not let us show it in the main code itself.