2024 Arduino Standard Servo & Input

This page includes the Arduino program and circuit for ONE servo controlled by a button/switch.  It is ready to run.

You can copy/paste the code into the Arduino program.  There is a circuit diagram below the code.

Build the circuit in Tinkercad and copy/paste the program to make it run.

After you are done, move on to Part 2: Two servos, Two Buttons

#include <Servo.h>
int button =2; //assignments button/switch to pin 2
Servo servo1;// assigns the variable servo1 to the servo

void setup()
{
pinMode (button, INPUT);
servo1.attach (3);
Serial.begin (9600);
}

void loop()
{
if (digitalRead (button) == HIGH)//this is what happens when the button is pressed

{
servo1.write(0);//servo moves
delay(1000);//waits one second
Serial.println("Button pressed");//sends a text message to serial monitor
delay (2000);//waits two seconds
servo1.write (180);//servo moves
delay (1000);//waits one second
}
else//this is what happens when the button is NOT pressed
{
servo1.write(0);//servo resets to ZERO
Serial.println("Button NOT pressed");//sends a text message to serial monitor
}
}