/*
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>
// https://youyouyou.pixnet.net/blog/post/121477396-arduino%E7%9A%84split%E5%87%BD%E6%95%B8
String Split(String data, char separator, int index){
int found = 0;
int strIndex[] = { 0, -1 };
int maxIndex = data.length() - 1;
for (int i = 0; i <= maxIndex && found <= index; i++) {
if (data.charAt(i) == separator || i == maxIndex) {
found++;
strIndex[0] = strIndex[1] + 1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}
Servo myservo; // create servo object to control a servo
int potpin = 0; // analog pin used to connect the potentiometer
int val; // variable to read the value from the analog pin
String inputString = ""; // a String to hold incoming data
bool stringComplete = false; // whether the string is complete
void setup() {
// initialize serial:
Serial.begin(115200);
// reserve 256 bytes for the inputString:
inputString.reserve(256);
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023)
Serial.print("potentiometer:");
Serial.print(val);
Serial.print(", ");
val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)
Serial.print("angle:");
Serial.println(val);
// when a newline arrives:
if (stringComplete) {
String key = Split(inputString, ':', 0);
if (key == "angle") {
String value = Split(inputString, ':', 1);
val = value.toInt();
myservo.write(val); // sets the servo position according to the scaled value
}
// clear the string:
inputString = "";
stringComplete = false;
}
delay(150); // waits for the servo to get there
}
/*
SerialEvent occurs whenever a new data comes in the hardware serial RX. This
routine is run between each time loop() runs, so using delay inside loop can
delay response. Multiple bytes of data may be available.
*/
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// if the incoming character is a newline, set a flag so the main loop can
// do something about it:
if (inChar == '\n') {
stringComplete = true;
} else {
// add it to the inputString:
inputString += inChar;
}
}
}