Technology
Controlling a Servo Motor with a Switch using Arduino
Controlling a Servo Motor with a Switch using Arduino
To control a servo motor with a switch on an Arduino, you need to understand the basic setup and a simple code that manages the switch input and servo movement. In this article, we will guide you through the necessary components, wiring, and code to achieve this functionality.
Components Needed
The components required for this project include:
Arduino Board Servo Motor Single-Pole Single-Throw (SPST) Switch 10k Omega; Resistor (Pull-Down) Breadboard and Jumper Wires Power Source for the ServoCircuit Diagram
Servo Connections:
Signal wire (usually yellow or white) to a PWM-capable pin (e.g., pin 9) Power wire (usually red) to the 5V pin on the Arduino Ground wire (usually black or brown) to the GND pin on the ArduinoSwitch Connections:
One terminal of the switch to a digital pin (e.g., pin 2) The other terminal to GND Optionally, a 10k Omega; resistor from the digital pin to GND for pull-downArduino Code Example
Below is a simple Arduino code to control the servo based on the switch input:
#include Servo myServo; // Create a Servo object const int switchPin 2; // Pin connected to the switch bool switchState false; // Variable to hold the current state of the switch void setup() { pinMode(9, OUTPUT); // Attach the servo to pin 9 pinMode(switchPin, INPUT); // Set the switch pin as input myServo.write(0); // Start at 0 degrees } void loop() { int currentState digitalRead(switchPin); // Read the state of the switch // Check if the switch is pressed if (currentState HIGH !switchState) { myServo.write(90); // Move servo to 90 degrees delay(500); // Delay to prevent multiple triggers } // Update the switchState switchState currentState; }Explanation of the Code
Servo Library:
The Servo.h library is included to control the servo motor.
Setup:
The servo is attached to pin 9. The switch pin is set as an input. The servo starts at 0 degrees.Loop:
The state of the switch is continuously read. When the switch is pressed (HIGH), the servo moves to 90 degrees. A delay is added to prevent the servo from moving multiple times with one press.Additional Notes
Power Supply: Ensure the power supply for the servo is adequate, particularly if using a larger servo.
Debouncing: You might want to add debouncing for the switch to avoid false triggers.
This setup allows you to control the servo to move to 90 degrees with a simple switch press.