/*
Controlling a servo position using a potentiometer (variable resistor)
by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>
modified on 8 Nov 2013
by Scott Fitzgerald
http://www.arduino.cc/en/Tutorial/Knob
*/
#include <Servo.h> //include library/info
Servo myservo; // create servo object to control a servo
const int pushButton = 2; // button wired up to D2
int pushState = 0; // variable for if the button is HIGH or LOW
int mode = 0; // variable for what to do after each "button click"
int potpin = 0; // analog pin used to connect the potentiometer
int val; // variable to read the value from the analog pin
int pos = 0; //position variable for sweep
void setup() {
Serial.begin(9600); //serial moniter
Serial.println("helloworld"); //test
myservo.attach(9); // attaches the servo on pin 9 to the servo object
pinMode(pushButton, INPUT_PULLUP); //button kept at HIGH by internal resitor
}
void loop() {
pushState = digitalRead(pushButton); //state of the button (HIGH or LOW) is known when you "read" the push button
if (pushState == LOW){ //add 1 to the value of "mode" each time button is pressed, value determines what is going on after the click
mode++;
if (mode > 3){ //only 3 modes, go back to one/cycle back
mode = 1;
}
Serial.println(mode); //let user know what mode they are in/testing
delay(150); //need time, otherwise one press will add too much to the mode value for one click
}
if (mode == 1){ //knob
val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023)
val = map(val, 0, 1023, 900, 2160); // scale it to use it with the servo (value between 0 and 180)
myservo.write(val); // sets the servo position according to the scaled value
//delay(15); // waits for the servo to get there
}
if (mode == 3){ //sweep
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees // in steps of 1 degree
myservo.write(pos);
Serial.println(pos);
delay(15);
}
for (pos = 180; pos >= 0; pos -= 1) { //opposite
myservo.write(pos);
Serial.println(pos);
delay(15);
}
}
if (mode == 2){ //set
myservo.write(1530);
delay(15);
}
}