Skip to content

Instantly share code, notes, and snippets.

@futureshocked
Created February 23, 2017 21:52
Show Gist options
  • Save futureshocked/42cd2bf0afd3ab292f60aed90528d503 to your computer and use it in GitHub Desktop.
Save futureshocked/42cd2bf0afd3ab292f60aed90528d503 to your computer and use it in GitHub Desktop.
/* <--- Arduino SbS Simple String Parser example --->
*
* This sketch shows how to receive a String from the serial
* monitor and parse it so that the first and second characters
* are returned. Once you have this information, you can use
* it to control connected devices, like an array of LEDs.
*
* For example, if you type '03O' (letter 'O'), the parses
* will detect '3' as the pin number and 'O' as the
* command, and will turn On an LED conected to digital pin 3.
*
*
* Components used in this sketch
* ----------
* - Arduino Uno
* - Breadboard
* - 3 x 5V LED
* - 3 x 220 Ohm resistor
*
* Libraries
* ---------
* - None
*
* Connections
* -----------
* Connect the LEDs to any available digital pins,
* except for 0 and 1 (used for serial communications).
*
* Other information
* -----------------
* Reminder: The long leg of the LED connects to 5V
* through the resistor and the short leg connects
* to Ground.
*
*
* Created on February 24 2017 by Peter Dalmaris
*
*/
String val; // variable to receive data from the serial port
String pin;
int ledpin1 = 7; // LED connected to pin 7
int ledpin2 = 8; // LED connected to pin 8
int ledpin3 = 9; // LED connected to pin 9
void setup() {
pinMode(ledpin1, OUTPUT);
pinMode(ledpin2, OUTPUT);
pinMode(ledpin3, OUTPUT);
Serial.begin(9600);
}
void loop() {
if( Serial.available() ) // If data is available to read
{
val = Serial.readString(); // Read a string for the monitor and store it in 'val'
Serial.print(val);
Serial.print("Pin number:");
pin = val.substring(0,2); // Get the first two characters, these make up the pin number
// which can be any valid pin number (0 .. 13 for the Uno)
Serial.println(pin);
Serial.print("Command:");
Serial.println(val[2]); // Simply read the character in position 2 of the string
// this is the instruction. For no particular reason, an 'O'
// will turn on the LED
if (val[2] == 'O')
{
Serial.print("Turning on LED at pin ");
Serial.println(pin);
digitalWrite(pin.toInt(), HIGH); // The digitalWrite function needs an integer in the
// first parameter, so convert the 'pin' string to
// an int using the 'toInt()' function
} else
{
Serial.print("Turning off LED at pin ");
Serial.println(pin);
digitalWrite(pin.toInt(), LOW);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment