Skip to content

Instantly share code, notes, and snippets.

@mai1015
Last active September 21, 2017 19:46
Show Gist options
  • Save mai1015/c38f5b08b2edc33d1ba1ffab3676d663 to your computer and use it in GitHub Desktop.
Save mai1015/c38f5b08b2edc33d1ba1ffab3676d663 to your computer and use it in GitHub Desktop.
Servo button example
#include <Servo.h>
// Declear the servo
Servo myservo;
// Declear pins
const int buttonPin = 2;
const int servoPin = 13;
// Declear variables
int lastButtonState = LOW;
int bottonState = LOW;
// use in control flow
int mode = 0; // current mode
int angle = 0; //current angle
bool forward = true; // turning direction
// Setup function
void setup() {
// initialize the pin
pinMode(servoPin, OUTPUT);
pinMode(buttonPin, INPUT);
// attach to servo
myservo.attach(servoPin);
}
// the loop routine runs over and over again forever:
void loop() {
// read the button state from pin
bottonState = digitalRead(buttonPin);
// check if button change state for sure
if (bottonState == HIGH && lastButtonState == LOW) {
// change mode
if (mode <= 2) {
mode++;
} else {
// if mode is over 3, reset it.
mode = 0;
}
// make sure button works by putting delay to make sure it did not repeated
delay(30);
}
// make sure to change the last button state
lastButtonState = bottonState;
// start running the mode
switch (mode) {
case 0: // reset to 0 angle
angle = 0;
break;
case 1: // set to 90 angle
angle = 90;
break;
case 2: //moving forward and backward by 10
if (forward == true) {
angle+=10;
} else {
angle-=10;
}
delay(30); // slow it down, it might go crazy without it.
break;
case 3: //moving forward and backward by 30
if (forward == true) {
angle+=30;
} else {
angle-=30;
}
delay(30); // same
break;
}
// vilidating the angle, make sure it goes between 0 and 180
if (angle >= 180) {
angle = 180;
forward = false;
}
if (angle <= 0) {
angle = 0;
forward = true;
}
// Final result goes to the servo
myservo.write(angle);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment