Skip to content

Instantly share code, notes, and snippets.

@ingamedeo
Last active August 29, 2015 14:02
Show Gist options
  • Save ingamedeo/ff3a9bda6f1e07d45cd2 to your computer and use it in GitHub Desktop.
Save ingamedeo/ff3a9bda6f1e07d45cd2 to your computer and use it in GitHub Desktop.
Arduino Serial Com Wrapper
int pinNum = 0;
unsigned long tempMillis;
int count = 0;
void flush() {
while(Serial.available() > 0) { //Consume all other data remaining
Serial.read();
}
}
void setup() {
Serial.begin(9600);
Serial.println("");
Serial.println(" --- Serial Com Wrapper ---");
Serial.println("Written by; <Amedeo Arch> - ingamedeo");
Serial.println("");
Serial.println("> Available commands: | p PIN_NUMBER | n ON | f OFF | s STATUS |");
}
void loop() {
if (Serial.available() > 0) {
byte input = Serial.read();
delay(50); //This is important! Overwhise this will not work
switch(input) {
case 'p':
//Init Everything here
pinNum = 0;
tempMillis = millis();
count = 0; //How many digits already read
while(millis() - tempMillis < 500) {
if (Serial.available() > 0) { //Search for next
count++;
byte next = Serial.read(); //Read next byte
if ((next >= '0') && (next <= '9')) { //Number is between 0-9
pinNum = (pinNum * 10) + (next - '0'); //Move to the left current digit and sum the new number I get...it's like building a number 10 > 100 and next = 5 >>> 105
} else if ((next == 10) || (next == 13)) { //Enter or new line detected
break;
} //If it's everything else I just skip over it
} else {
if (count == 0) { //available() NOT and count is 0...Nothing after p > Throw an error
Serial.println("Invalid command. You should specify a PIN number like ... p 13");
break;
}
}
}
if (count>0) {
Serial.print("PIN ");
Serial.print(pinNum);
Serial.println(" selected.");
pinMode(pinNum, OUTPUT);
}
break;
case 'n':
if (count>0) { //Check if the user prev defined a PIN Number
digitalWrite(pinNum, HIGH);
Serial.print("PIN ");
Serial.print(pinNum);
Serial.println(" is now ON/HIGH");
} else {
Serial.println("No PIN selected. Run p PIN_NUMBER first!");
}
break;
case 'f':
if (count>0) { //Check if the user prev defined a PIN Number
digitalWrite(pinNum, LOW);
Serial.print("PIN ");
Serial.print(pinNum);
Serial.println(" is now OFF/LOW");
} else {
Serial.println("No PIN selected. Run p PIN_NUMBER first!");
}
break;
case 's':
if (count>0) {
int status = digitalRead(pinNum);
if (status == 0) {
Serial.println("Current Status is 0, PIN is OFF/LOW");
} else if (status == 1) {
Serial.println("Current Status is 1, PIN is ON/HIGH");
}
} else {
Serial.println("No PIN selected. Run p PIN_NUMBER first!");
}
break;
}
}
}
/*
while(Serial.available() > 0) {
Serial.read();
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment