Arduino - Button - Servo Motor
We will learn:
If button is pressed, rotate servo motor to 90 degree
If button is pressed again, rotate servo motor back to 0 degree.
That process is repeated.
The tutorial includes two main parts:
Or you can buy the following sensor kits:
Please note: These are Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.
If you do not know about servo motor and button (pinout, how it works, how to program ...), learn about them in the following tutorials:
This image is created using Fritzing. Click to enlarge image
#include <Servo.h>
const int BUTTON_PIN = 7;
const int SERVO_PIN = 9;
Servo servo;
int angle = 0;
int lastButtonState;
int currentButtonState;
void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT_PULLUP);
servo.attach(SERVO_PIN);
servo.write(angle);
currentButtonState = digitalRead(BUTTON_PIN);
}
void loop() {
lastButtonState = currentButtonState;
currentButtonState = digitalRead(BUTTON_PIN);
if(lastButtonState == HIGH && currentButtonState == LOW) {
Serial.println("The button is pressed");
if(angle == 0)
angle = 90;
else
if(angle == 90)
angle = 0;
servo.write(angle);
}
}
Connect Arduino to PC via USB cable
Open Arduino IDE, select the right board and port
Copy the above code and open with Arduino IDE
Click Upload button on Arduino IDE to upload code to Arduino
Press the button several times.
See the change of servo motor
※ NOTE THAT:
In practice, the above code does not work correctly sometimes. To make it always work correctly, we need to debounce for the button. Debouncing for the button is not easy for beginners. Fortunately, thanks to the ezButton library, We can do it easily.
Why do we need debouncing? ⇒ see Arduino - Button Debounce tutorial
#include <Servo.h>
#include <ezButton.h>
const int BUTTON_PIN = 7;
const int SERVO_PIN = 9;
ezButton button(BUTTON_PIN);
Servo servo;
int angle = 0;
void setup() {
Serial.begin(9600);
button.setDebounceTime(50);
servo.attach(SERVO_PIN);
servo.write(angle);
}
void loop() {
button.loop();
if(button.isPressed()) {
Serial.println("The button is pressed");
if(angle == 0)
angle = 90;
else
if(angle == 90)
angle = 0;
servo.write(angle);
}
}
Install ezButton library. See
How To
Copy the above code and open with Arduino IDE
Click Upload button on Arduino IDE to upload code to Arduino
Press button several times
See the change of servo motor
We are considering to make the video tutorials. If you think the video tutorials are essential, please subscribe to our YouTube channel to give us motivation for making the videos.
Most electronic products have a reset button. Additionally, the button also keeps other functionalities in many products.
※ OUR MESSAGES
You can share the link of this tutorial anywhere. Howerver, please do not copy the content to share on other websites. We took a lot of time and effort to create the content of this tutorial, please respect our work!