Unit 19: Motor Movement

 

 

 

 

Code:  


  #include 

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

// Variables
Servo servoMotor;            // Create a servo object

void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP);   // Set button pin as input with internal pull-up resistor
  servoMotor.attach(SERVO_PIN);        // Attach the servo to its pin
}

void loop() {
  if (digitalRead(BUTTON_PIN) == LOW) {   // Check if button is pressed (active low)
    servoMotor.write(90);                  // Move servo to 90 degrees
    delay(1000);                           // Wait for 1 second
    servoMotor.write(0);                   // Move servo back to 0 degrees
    delay(1000);                           // Wait for 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.