Skip to content

Instantly share code, notes, and snippets.

@labajo
Created November 15, 2016 14:54
Show Gist options
  • Save labajo/4fbbe3b29ce92cadd7ef7b2e8820cfe5 to your computer and use it in GitHub Desktop.
Save labajo/4fbbe3b29ce92cadd7ef7b2e8820cfe5 to your computer and use it in GitHub Desktop.
#include <Servo.h>
String inputString = ""; // a string to hold incoming data
boolean stringComplete = false; // whether the string is complete
Servo servoX;
int posX = 0;
void setup() {
// initialize serial:
Serial.begin(115200);
// reserve 200 bytes for the inputString:
inputString.reserve(200);
servoX.attach(9);
servoX.write(posX);
}
void loop() {
// print the string when a newline arrives:
if (stringComplete) {
Serial.println(inputString);
// clear the string:
inputString = "";
stringComplete = false;
}
}
/*
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();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inChar == '\n') {
//int intValue = inputString.toInt();
//posX = posX + intValue;
//servoX.write(posX);
char *inputChar = new char[inputString.length() + 1];
strcpy(inputChar, inputString.c_str());
char *axis = strtok(inputChar, ":");
//Serial.println(axis);
char *value = strtok(NULL, ":");
int intValue = atoi(value);
if (strcmp(axis, "x") == 0) {
//Serial.println("eje x");
if (posX + intValue > 180) {
posX = 180;
}
else {
posX += intValue;
}
}
servoX.write(posX);
stringComplete = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment