Introduction: Servo Motor + Push Button + Arduino
Hello World!
Welcome back to another Unicorn ClockWorks Instructable. Here, we will be setting up and interfacing a servo motor to the Arduino and controlling it using a push button switch. The servo motor is a very popular and useful tool among hobbyist and I am sure you will find yourself needing to use it in numerous occasions. As such, we will be learning how to interface control it!
This is made to be broad ranging and generic so you can apply it to any projects with any microcontroller!
Step 1: Materials
- Arduino or any Arduino-compatible microcontroller
- Servo motor
- Push button switch
- 10k Ohm Resistor - brown-black-orange
Step 2: Push Button Connections
1a
- The Black wire connects pin 1 of the switch (on the left hand side) to the GND pin on the Arduino.
- The Yellow wire connects pin 2 of the switch (on the right-hand side) to pin 8 on the Arduino.
- Connect a 10kΩ resistor -- brown-black-orange -- to pin 2 and the other terminal to the 3.3V pin on the Arduino.
Step 3: Servo Connections
2a
- The Blue wire is connected from the signal pin of the servo motor to pin 3 of the Arduino.
- The Red wire is connected from the signal pin of the servo motor to the 5V pin of the Arduino
- The Black wire is connected from the ground pin of the servo motor to the GND pin of the Arduino. Note that the switch is also connected here. so we can also connect it there on the breadboard, but the Arduino has multiple GNDs that are all common.
Step 4: Code
#include <Servo.h>;
// pushbutton pin const int buttonPin = 8;
// servo pin const int servoPin = 3; Servo servo;
//create a variable to store a counter and set it to 0 int counter = 0; void setup() { servo.attach (servoPin); // Set up the pushbutton pins to be an input: pinMode(buttonPin, INPUT); }
void loop() { // local variable to hold the pushbutton states int buttonState;
//read the digital state of buttonPin with digitalRead() function and store the //value in buttonState variable buttonState = digitalRead(buttonPin);
//if the button is pressed increment counter and wait a tiny bit to give us some //time to release the button if (buttonState == LOW) // light the LED { counter++; delay(150); }
if(counter == 0) servo.write (20); // zero degrees else if(counter == 1) servo.write(90); else if(counter == 2) servo.write (150); else if(counter == 3) servo.write (180); //else reset the counter to 0 which resets thr servo to 0 degrees else counter = 0; }
Attachments
Step 5: It Moves!
Push the button and watch the servo move to a different angle each time.
I hope you enjoyed making this project and learned something along the way!
Unicorn Clockworks Out!