Skip to content

Instantly share code, notes, and snippets.

@jotathebest
Created August 20, 2018 18:58
Show Gist options
  • Save jotathebest/414f09e8e38664a31e76edf348ed0333 to your computer and use it in GitHub Desktop.
Save jotathebest/414f09e8e38664a31e76edf348ed0333 to your computer and use it in GitHub Desktop.
Script to read ASCII strings using Arduino Serial port
/************************************************
* Auxiliar Functions
***********************************************/
// Function to read command from serial port
char* readSerial(int max_char_length=40) {
int i = 0;
char command[max_char_length];
for (i = 0; i < max_char_length; i++) {
command[i] = '\0';
}
i = 0;
while(Serial.available()) {
command[i++] = (char) Serial.read();
if (i == max_char_length) {
break;
}
}
return command;
}
/************************************************
* Main Functions
***********************************************/
void setup() {
Serial.begin(115200);
pinMode(13, OUTPUT);
}
void loop() {
// Reads command
char* command = readSerial();
// Logic to control led
if (strcmp(command, "on") == 0) {
Serial.println("turning on ..");
digitalWrite(13, HIGH);
}
else if (strcmp(command, "off") == 0){
Serial.println("turning off ..");
digitalWrite(13, LOW);
}
delay(1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment