Control Servo Motor’s motion by using pushbuttons
- input: 2 pins for two pushbuttons
- output: 1 pin for Servo Motor
- Components Requirements
- Arduino Uno x 1
- Servo motor . x 1
- Mini-BreadBoard x 1
- 1 k-ohm Resistor x 2
- Jumpers.
- Battery 9V x 1
- Mini-BreadBoard x 1
- 1 k-ohm Resistor x 2
- Jumpers.
- Battery 9V x 1
- Button x 2
- Making
- Coding
#include <Servo.h>
Servo servo;
int angle = 90;
int angleStep = 5;
#define LEFT 2 // pin 2 is connected to left button
#define RIGHT 4 // pin 4 is connected to right button
void setup() {
Serial.begin(9600); // setup serial
servo.attach(6); // attaches the servo on pin 6 to the servo object
pinMode(LEFT,INPUT_PULLUP); // assign pin 2 as input for Left button
pinMode(RIGHT,INPUT_PULLUP); // assing pin 4 as input for Right button
servo.write(angle); // send servo to the middle at 90 degrees
Serial.println(" AngleStep of Servo :");
}
void loop() {
while(digitalRead(RIGHT) == LOW){
if (angle > 0 && angle <= 180) {
angle = angle - angleStep;
if(angle < 0){
angle = 0;
}else{
servo.write(angle); // move the servo to desired angle
Serial.print("Moved to: ");
Serial.print(angle); // print the angle
Serial.println(" degree");
}
}
delay(100);
}
while(digitalRead(LEFT) == LOW){
if (angle >= 0 && angle <= 180) {
angle = angle + angleStep;
if(angle >180){
angle =180;
}else{
servo.write(angle); // move the servo to desired angle
Serial.print("Moved to: ");
Serial.print(angle); // print the angle
Serial.println(" degree");
}
}
delay(100);
}
}
No comments:
Post a Comment