Arduino Parsing for Occurrence of String from Serial Port

The Plan

For the next phase of my project, I will need to parse incoming text from the ESP8266 over a serial port and do something if I find some key words.  I started trying to dive straight in with my auto start ESP8266 server code and trying to parse responses from remote client but ended using a lot of time rebooting and starting up the client TTY session.  I got smarter and decided to just see if I can parse from the serial port from the PC.

The Implementation

Concept is simple.

  1. Read a string from the serial port
  2. Check if there is an occurrence of a certain string within the string.
  3. Do something like toggle an IO that blinks an LED.

Would be easy in C+ or Visual Basic but same commands do not exist for Arduino.  After some searching around various forums that came close to what I was looking for, I stumbled onto the function needed at the Arduino reference page.  Now that I found them, it is quite simple.  The two key finds were:

Once I found these, the code was very trivial.

The Code

#include <string.h>

void setup(){
 Serial.begin(9600);
 Serial.setTimeout(100);
 pinMode(13,OUTPUT);
 digitalWrite(13,LOW);
}

void loop(){
 String IncomingString="";
 char SingleChar;
 boolean StringReady = false;
 

 while (Serial.available()) 
 {
   IncomingString=Serial.readString();
   StringReady= true; 
 }
 if (StringReady){
   Serial.println("Received String: " + IncomingString); 
   if (IncomingString.indexOf("key") != -1) {
     Serial.println("I found 'key' in there");
     BlinkLED(13,3,300);
   } 
 }

}

void BlinkLED(int LEDPin, int NumberOfBlinks, int OnDuration)
{
 for (int x=1; x <= NumberOfBlinks ; x ++){
   digitalWrite(LEDPin,HIGH);
   delay(OnDuration);
   digitalWrite(LEDPin,LOW);
   delay(OnDuration); 
 }
}
Advertisements

2 thoughts on “Arduino Parsing for Occurrence of String from Serial Port

  1. Pingback: LED’s Control through TTY | PetesTechProjects

  2. Pingback: Mini Server on Arduino + ESP8266 | PetesTechProjects

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s