Why does serial.available does not work in this code snippet? - serial-port

I have a processing sketch which needs to set up 2 connections with USB devices. I cannot tell in advance which device is USB0 and which is USB1. (not that I am aware off atleast)
One of the devices awnsers with hello the other one does not answer at all. Therefor I have written code with a simple timeout. In the setup I check continously if there are bytes to read. But both a while and an if statement yield incorrect results
while( dccCentral.available() < 5 ) {
if( dccCentral.available() >= 5) break;
if(millis() > 5000 ) {
println("timeout occured");
println(dccCentral.available());
break;
}
}
These lines are in setup. The text "timeout occured" is always printed. Underneath it, the result of dccCentral.available() is printed. This number is 12 which is correct.
regardless, if dccCentral.available() prints 12 at that time. The first if-statement:
if( dccCentral.available() >= 5) break;
should already have break'ed out of the while loop before this time-out should occur. The while-loop itself should also quit itself when 5 or more bytes are received.
Why do both these lines
while( dccCentral.available() < 5 ) {
if( dccCentral.available() >= 5) break;
fail?

Personally I try to avoid while loops unless there isn't another way (e.g. inside a thread) and that is avoid both logic pitfalls and messing with the lifecycle of other objects that might need a bit of time to initialise.
If you send strings from Arduino and also use println() you could init the port to easily catch that using Serial's bufferUntil() in conjuction with serialEvent() to finally readString().
Once you start getting data in, you could:
use references to the serial ports you're after and a couple of extra ones until you know which port is which
use a boolean "toggle" to only handle the "hello" once
if the hello was received, you can use the serialEvent() Serial argument to assign dccCentral and by process of elimination assign the other port
Here's a commented sketch to illustrate the idea:
import processing.serial.*;
// be sure to set this to the baud rate your device use with Arduino as well
final int BAUD_RATE = 115200;
// reference to Serial port sending "Hello" (when that get's detected)
Serial dccCentral;
// reference to the other Serial port
Serial otherDevice;
// temporary references
Serial usb0;
Serial usb1;
// 'toggle' to keep track where the hello was received and handled or not (by default initialised as false)
boolean wasHelloReceived;
void setup(){
usb0 = initSerial("/dev/ttyUSB0", BAUD_RATE);
usb1 = initSerial("/dev/ttyUSB1", BAUD_RATE);
}
Serial initSerial(String portName, int baudRate){
Serial port = null;
try{
port = new Serial(this, portName, baudRate);
// if sending strings and using println() from Arduino
// you can buffer all chars until the new line ('\n') character is found
port.bufferUntil('\n');
}catch(Exception e){
println("error initialising port: " + portName);
println("double check name, cable connections and close other software using the same port");
e.printStackTrace();
}
return port;
}
void draw(){
background(0);
text("wasHelloReceived: " + wasHelloReceived + "\n"
+"dccCentral: " + dccCentral + "\n"
+"otherDevice: " + otherDevice , 10 ,15);
// do something with the devices once they're ready (e.g. send a message every 3 seconds)
if(millis() % 3000 == 0){
if(dccCentral != null){
dccCentral.write("ping\n");
}
if(otherDevice != null){
otherDevice.write("pong\n");
}
}
}
void serialEvent(Serial port){
try{
String serialString = port.readString();
// if the received string is not null, nor empty
if(serialString != null && !serialString.isEmpty()){
// for debugging purposes display the data received
println("received from serial: " + serialString);
// trim any white space
serialString = serialString.trim();
// check if "hello" was received
if(serialString.equals("hello")){
println("hello detected!");
// if the dccCEntral (hello sending) serial port wasn't assigned yet, assign it
// think of this as debouncing a button: setting the port once "hello" was received should happen only once
if(!wasHelloReceived){
// now what dccCentral is found, assign it to the named reference
dccCentral = port;
// by process elimiation, assign the other port
// (e.g. if dccCentral == usb0, then other is usb1 and vice versa)
otherDevice = (dccCentral == usb0 ? usb1 : usb0);
/*
the above is the same as
if(dccCentral == usb0){
otherDevice = usb1;
}else{
otherDevice = usb0;
}
*/
wasHelloReceived = true;
}
}
}
}catch(Exception e){
println("error processing serial data");
e.printStackTrace();
}
}
Note the above code hasn't been tested so it may include syntax errors, but hopefully the point gets across.
I can't help notice that USB0/USB1 are how serial devices sometimes show up on Linux.
If you're working with a Raspberry Pi I can recommend a slightly easier way if you're comfortable with Python. The PySerial has a few tricks up it's sleeve:
You can simply call: python -m serial.tools.list_ports -v which will list ports with extra information such as serial number of the serial converter chipset. This could be useful to tell which device is which, regardless of the manufacturer and USB port used
Other than the serial port name/location, it supports multiple ways (URLs) of accessing the port with a very clever: hwgrep:// will allow you to filter a device by it's unique serial number
Here's a basic list_ports -v output for two devices with the same chipset:
column 1
/dev/ttyUSB9
desc: TTL232R-3V3
hwid: USB VID:PID=0403:6001 SER=FT94O21P LOCATION=1-2.2
column 2
/dev/ttyUSB8
desc: TTL232R-3V3
hwid: USB VID:PID=0403:6001 SER=FT94MKCI LOCATION=1-2.1.4
To assign the devices using serial you would use something like:
"hwgrep://FT94O21P"
"hwgrep://FT94MKCI"
Update
It might help to step by step debug the system and try one port a time.
The idea is to get the bit of code reading the expected serial string tight.
Here's a basic example that should simply accumulate one char at a time into a string and display it:
import processing.serial.*;
Serial port;
String fromSerial = "";
void setup(){
size(300,300);
port = initSerial("/dev/ttyUSB0", 115200);
}
Serial initSerial(String portName, int baudRate){
Serial port = null;
try{
port = new Serial(this, portName, baudRate);
// if sending strings and using println() from Arduino
// you can buffer all chars until the new line ('\n') character is found
port.bufferUntil('\n');
}catch(Exception e){
println("error initialising port: " + portName);
println("double check name, cable connections and close other software using the same port");
e.printStackTrace();
}
return port;
}
void draw(){
if(port != null){
if(port.available() > 0){
char inChar = port.readChar();
fromSerial += inChar;
if(inChar == '\n'){
println("newline encountered");
println(fromSerial.split("\n"));
}
}
}
background(0);
text("from serial:" + fromSerial, 10,15);
}
If the data from dccCentral comes in a expected: great, the code can be simplfied and right conditions applied to filter the device in the future,
otherwise it should help pin point communication issues getting the "hello" in the first place (which would be 6 bytes ("hello"(5) + '\n') if sent with Serial.println() from Arduino)
Regarding Python, no problem at all. Should the idea help in the future you can check out this answer. (AFAIK Processing Serial uses JSSC behind the scenes)

Related

arduino and esp8266 - how to get AT command response into variable

So i have my arduino and esp8266 wifi module. Everything is connected correctly and sending data to arduino lets me control connection via AT commands.
My skletch looks like this:
void setup()
{
Serial.begin(9600);
Serial1.begin(9600);
}
void loop()
{
if (Serial.available() > 0) {
char ch = Serial.read();
Serial1.print(ch);
}
if (Serial1.available() > 0) {
char ch = Serial1.read();
Serial.print(ch);
}
The code above lets me send commands and see response from esp. In spite of different response time and different answers I need to store response in variable when wifi module such a response creates. Unfortunatelly I cant do this because of Serial1.read() grabing only one char from Serial1.available() buffer instead of full buffer.
I tried approach like this:
if (Serial1.available() > 0) {
while (Serial1.available() > 0) {
char ch = Serial1.read();
Serial.print(ch);
response = response.concat(ch);
}
} else {
String response = "";
}
So as long ther eis something in a buffer it is sent to response variable that concatens last char with itself. And later it can be searched via indefOf command for "OK" marker or "ERROR". But that doesnt work as intended :( It for example may print my variable 8 times (dont know why).
I need full response from wifi module to analaze it for example to make the led on in my arduino board if proper command comes from wifi network, but also send some data if i press button on arduino to the network. Any ideas would be appreciated.
Kalreg.
Try this rather:
String response = ""; // No need to recreate the String each time no data is available
char ch; // No need to recreate the variable in a loop
while (Serial1.available() > 0) {
ch = Serial1.read();
response = response.concat(ch);
}
// Now do whatever you want with the string by first checking if it is empty or not. Then do something with it
Also remember to clear the buffer before you send a command like I suggested in your previous question: how to get AT response from ESP8266 connected to arduino

SD card image transfer using xbee

I trying to read SD card image from arduino (20KB - JPEG -using SD library) and transfer through Xbee (series 2) Due to limitation on xbee, have to break to 60 bytes and send until the complete file send. I think, the image stored in ASCII character.
void setup() {
Serial.begin(115200);
if (!SD.begin()) {
Serial.println("begin failed");
return;
}
file = SD.open("PIC00.JPG");
}
void loop() {
Serial.flush();
char buf[64];
if(file) {
while (file.position() < file.size())
{
while (file.read(buf, sizeof(buf)) == sizeof(buf)) // read chunk of 64bytes
{
Serial.write(buf); // Send to xbee via serial
delay(50);
}
}
file.close();
} }
But this method, i can not see complete image transfer at Serial Write. After a while, i came to know the start of image is Y (ascii chracter) and U (end character). I can see only end start character Y can not see the proper end character.
Please advise...trying hard solve this issue. Big Thanks...
The JPEG is actually binary data. To send it, use the version of Serial.write() that includes a length parameter for the number of bytes to send. Otherwise, it thinks you're trying to send a null-terminated string.
(Declare bytesread as a byte at the top of your function.)
while ((bytesread = file.read(buf, sizeof(buf))) > 0)
{
Serial.write(buf, bytesread); // Send to xbee via serial
delay(50);
}
Also note that the delay might not be sufficient -- you should really be using a serial port with hardware flow control (monitoring /CTS from the XBee module) so you know when it's clear to send data to it.

Arduino stepper control by program

I try to control a stepper motor with a program that uses a protocol (see below)
I am able to control the stepper with the Accelstepper (see below) but have no idea how i can program the Arduino so it is able to communicate according te protocol through the serial port.
#include <AccelStepper.h>
// Define a stepper and the pins it will use
AccelStepper stepper(1, 3, 4);
int pos = 8192;
void setup()
{
stepper.setMaxSpeed(5000);
stepper.setAcceleration(1500);
}
void loop()
{
if (stepper.distanceToGo() == 0)
{
delay(500);
pos = -pos;
stepper.moveTo(pos);
}
stepper.run();
}
All commands sent to the rotary table are in simple character format including the motor numbers. Only the parts marked as xxx passed to the table as byte data. For example if you want table 1 rotate 4 steps instead of passing "I1M004" you pass "I1M" + (char)0 + (char)0 + (char)4
In general all commands get a reply in the form of: ^XXXXXX
Commands
V
Request the status of the rotary table. Usual reply would be ^R1R2R3R4 indicating rotary 1 ready, rotary 2 ready, etc. ^B1xxxR2R3R4 means rotary 1 is busy where xxx are 3 bytes indicates how many steps the rotary still has to perform.
SmMxxx
Sets the speed of the motor m to xxx, where xxx is a 3 bytes of data indicating the speed. Example code: port.Write("S1M" + (char)0 + (char)6 + (char)255); // set motor 1 to speed 1791. The standard speed range of our rotary table is: 0x000001 to 0x0012FF (1 to 4863). Controller will respond with ^mxx mirroring the motor number and 2 last bytes of speed setting.
ImMxxx
Turns motor m xxx number of steps. Controller will acknowledge with ^Bmxxx
DmCWLO
Set motor number m to rotate clockwise (So each consecutive command to rotate the motor m will rotate it clockwise).
DmCWHi
Sets rotary m to rotate counterclockwise.
EmHALT
Rotary m stop.
Rotary Sample Command Sequence
Motor numbers are passed as characters but the number of steps and speed are passed as 3 bytes of binary for simplicity.
send: V reply: ^R1R2R3R4
send: S1M1791 reply: ^191
send: D1CWLO reply: ^
send: I1M100 reply: ^B1100
I had a similar project for my dissertation work where I controlled an inverted pendulum from a PC via an arduino uno. I'm assuming you have a PC program what sends out the commands to the arduino, and the problem is to receive and interpret it on the Arduino board.
I wrote the code below with major help (some copy paste modify) from here
It basically opens the com port and then listens to the incoming commands from the PC. When a command is received, it breaks it up (the incoming commands come in a #00parameter format). All commands start with #. The following 2 digits define the command itself, and the following text/numbers are the parameters for the command.
Once the command and its parameters are known, the actual process related to the command can be executed. In your case this supposed to be the motor control related to the incoming commands. The below code obviously needs to be updated to match with your motor control functions, but the incoming command handling works just fine.
String inputString = ""; // a string to hold incoming data
boolean stringComplete = false; // whether the incloming string is complete
float kp = 10; //sample parameter 1
float kd = 5; //sample parameter 2
float ki = 2; //sample parameter 3
void setup()
{
Serial.begin(9600); //Start serial communication
inputString.reserve(200); //Reserves 200 bytes for the string
}
void loop()
{
//This becomes true when the serial port receives a "\n" character (end of line)
if (stringComplete)
{
SerialProc(); //the function which runs when a full line is received
inputString = ""; //once processed, the string is cleared
stringComplete = false; //set flag to false to indicate there is nothing in the buffer waiting
}
}
void serialEvent() //This serial event runs between each loop cycles
{
while (Serial.available()) //if there is anything in the incoming buffer this while loop runs
{
// get the next 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')
{
stringComplete = true; //This indicates the line is complete, and the main program can process it
}
}
}
void SerialProc() //the function which processes the incoming commands. It needs to be modified to your needs
{
//cmd is the first three characters of the incoming string / line
String cmd = inputString.substring(0,3); //first three characters in incoming string specifies the command
//param is the rest of the string to the end of the line (excluding the first three characters)
String param = inputString.substring(3, inputString.length()); //rest of incoming string is making up the parameter
//creating a buffer as an array of characters, same size as the length of the parameters string
char buf[param.length()];
//moving the parameters from string to the char array
param.toCharArray(buf,param.length());
//the above string to char array conversion is required for the string to float
//conversion below (atof)
//the below part is the command execution. Could have used a switch below, but the series of ifs
//just did the trick
if (cmd == "#00")
SendReply(); //Executing command 1
else if (cmd == "#01")
kp = atof(buf); //executing command 2 (setting parameter kp)
else if (cmd == "#02")
kd = atof(buf); //executing command 3 (setting parameter kd)
else if (cmd == "#03")
ki = atof(buf); //executing command 4 (setting parameter ki)
}
void SendReply()
{
//This is called from the SerialProc function when the #00 command is received
//After the last parameter (TimeDelay) it sends the carrige return characters via the Serial.println
Serial.println("reply");
}

Temboo Yahoo to Xively

So I am using Temboo after recently acquiring a Arduino Yun, however I am having an issue with getting and posting data by combining Choreos.
I am using the Yahoo GetWeatherByAddress Choreo and trying to post the individual values I want to a Xively Feed. I am using the Xively Write Choreo and inputting FeedData in JSON format.
So far I have had some success with posting 2 values (humidity and pressure) at a time. Unfortunately I want to use more than this and have Humidity, Temperature, WeatherConditions(Fair, Windy etc) and a LDR reading from a breadboard. So It loops every 10 seconds, reads all those values and then posts them to Xively. The Temperature value seems to have an issue with even printing to Serial Monitor if I have any more than the Temperature value uncommented. It also doesn't go through with the whole process (returning Http 200 for success) It posts the values and the just goes straight to "waiting" for the next set of values to be retrieved. Where am I going wrong here?
/*
YahooWeather
This example code is in the public domain.
*/
#include <Bridge.h>
#include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information
// the address for which a weather forecast will be retrieved
String ADDRESS_FOR_FORECAST = "Plymouth, United Kingdom";
int numRuns = 1; // execution count, so that this doesn't run forever
int maxRuns = 10; // max number of times the Yahoo WeatherByAddress Choreo should be run
String pData;
String qData;
String rData;
String tData;
String cData;
void setup() {
Serial.begin(9600);
// for debugging, wait until a serial console is connected
delay(4000);
while(!Serial);
Bridge.begin();
pinMode(A0, INPUT);
pinMode(13, OUTPUT);
}
void loop()
{
if (numRuns <= maxRuns) {
int sensorValue = analogRead(A0);
if (sensorValue < 100) {
digitalWrite(13,HIGH);
delay(1000);
digitalWrite(13,LOW);
}
// while we haven't reached the max number of runs...
Serial.println("Sensor value: " + String(sensorValue)); }
TembooChoreo WriteDataChoreo;
// Invoke the Temboo client
WriteDataChoreo.begin();
// Set Temboo account credentials
WriteDataChoreo.setAccountName(TEMBOO_ACCOUNT);
WriteDataChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
WriteDataChoreo.setAppKey(TEMBOO_APP_KEY);
// print status
Serial.println("Running GetWeatherByAddress - Run #" + String(numRuns++) + "...");
// create a TembooChoreo object to send a Choreo request to Temboo
TembooChoreo GetWeatherByAddressChoreo;
// invoke the Temboo client
GetWeatherByAddressChoreo.begin();
// add your temboo account info
GetWeatherByAddressChoreo.setAccountName(TEMBOO_ACCOUNT);
GetWeatherByAddressChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
GetWeatherByAddressChoreo.setAppKey(TEMBOO_APP_KEY);
// set the name of the choreo we want to run
GetWeatherByAddressChoreo.setChoreo("/Library/Yahoo/Weather/GetWeatherByAddress");
// set choreo inputs; in this case, the address for which to retrieve weather data
// the Temboo client provides standardized calls to 100+ cloud APIs
GetWeatherByAddressChoreo.addInput("Address", ADDRESS_FOR_FORECAST);
// add an output filter to extract the name of the city.
GetWeatherByAddressChoreo.addOutputFilter("pressure", "/rss/channel/yweather:atmosphere/#pressure", "Response");
GetWeatherByAddressChoreo.addOutputFilter("humidity", "/rss/channel/yweather:atmosphere/#humidity", "Response");
GetWeatherByAddressChoreo.addOutputFilter("text", "/rss/channel/item/yweather:condition/#text", "Response");
// GetWeatherByAddressChoreo.addOutputFilter("temperature", "/rss/channel/item/yweather:condition/#temp", "Response"); //
// add an output filter to extract the current temperature
// add an output filter to extract the date and time of the last report.
// run the choreo
GetWeatherByAddressChoreo.run();
// parse the results and print them to the serial monitor
while(GetWeatherByAddressChoreo.available()) {
// read the name of the next output item
String name = GetWeatherByAddressChoreo.readStringUntil('\x1F');
name.trim(); // use “trim” to get rid of newlines
// read the value of the next output item
String data = GetWeatherByAddressChoreo.readStringUntil('\x1E');
data.trim(); // use “trim” to get rid of newlines
if (name == "humidity") {
qData = data;
Serial.println("The humidity is " + qData);
}
else if (name == "temperature") {
tData = data;
Serial.println("The temperature is " + tData);
}
else if (name == "pressure") {
rData = data;
Serial.println("The pressure is " + rData);
}
else if (name == "text") {
cData = data;
Serial.println("The code is " + cData);
}
}
WriteDataChoreo.addInput("FeedID", "1508368369");
WriteDataChoreo.addInput("APIKey", "6Z4tvi6jUOC0VhFkgngijR3bZWMXr2NNu1PHl4Js0hHGqE6C");
// WriteDataChoreo.addInput("FeedData", "{\"version\":\"1.0.0\",\"datastreams\":[ {\"id\" : \"Pressure\",\"current_value\" : \"" + rData + "\"} ,{\"id\" : \"Humidity\",\"current_value\" : \"" + qData + "\"} ,{\"id\" : \"Conditions\",\"current_value\" : \"" + cData + "\"}]}");
WriteDataChoreo.addInput("FeedData", "{\"version\":\"1.0.0\",\"datastreams\":[{\"id\":\"Humidity\",\"current_value\":\""+qData+"\"},{\"id\":\"Pressure\",\"current_value\":\""+rData+"\"},{\"id\":\"Conditions\",\"current_value\":\""+cData+"\"},{\"id\":\"Temp\",\"current_value\":\""+tData+"\"}]}");
// Identify the Choreo to run
// Identify the Choreo to run
WriteDataChoreo.setChoreo("/Library/Xively/ReadWriteData/WriteData");
// Run the Choreo; when results are available, print them to serial
WriteDataChoreo.run();
while(WriteDataChoreo.available()) {
char c = WriteDataChoreo.read();
//Serial.print(c);
}
while(GetWeatherByAddressChoreo.available()) {
char c = GetWeatherByAddressChoreo.read();
//Serial.print(c);
}
WriteDataChoreo.close();
GetWeatherByAddressChoreo.close();
Serial.println("");
Serial.println("Waiting...");
Serial.println("");
delay(10000); // wait 30 seconds between GetWeatherByAddress calls
}
I work at Temboo. I believe we've resolved this issue already via Temboo support, so I'm answering here for posterity.
Generally, if a sketch is working intermittently and you haven't changed any code, then it's likely that you're running out of RAM (a common issue on resource-constrained devices). When your board is out of RAM it causes Choreo input data to get overwritten and corrupted on the 32U4 side of your Yún. Your sketch is probably right at the RAM limit, which explains why it's working sometimes but not others, dependent on the amount of String data involved.
You can free up some RAM by putting the inputs that don't change (your Temboo creds, your Xively creds, the address you're searching for, any other static strings) into settings files that are stored on the Linino side, as described at the link below:
https://temboo.com/arduino/using-settings-files
If that doesn't free enough memory, you can free some more by eliminating any unnecessary Serial or Console print statements.
Hopefully this will help solve the issue you're seeing. Please let me know if it doesn't and we will continue to investigate.
Finally, here's some info on how you can check on how much memory a sketch is using:
http://jeelabs.org/2011/05/22/atmega-memory-use/
Good luck,
Cormac

How to capture a variable stream of characters and process them on a Arduino using serial?

I'm trying to read variable streams of characters and process them on the Arduino once a certain string of bytes is read on the Arduino. I have a sample sketch like the following, but I can't figure out how to compare the "readString" to process something on the Arduino. I would like the Arduino to process "commands" such as {blink}, {open_valve}, {close_valve}, etc.
// Serial - read bytes into string variable for string
String readString;
// Arduino serial read - example
int incomingByte;
// flow_A LED
int led = 4;
void setup() {
Serial.begin(2400); // Open serial port and set Baud rate to 2400.
Serial.write("Power on test");
}
void loop() {
while (Serial.available()) {
delay(10);
if (Serial.available() > 0) {
char c = Serial.read(); // Gets one byte from serial buffer
readString += c; // Makes the string readString
}
}
if (readString.length() > 0) {
Serial.println( readString); // See what was received
}
if (readString == '{blink_Flow_A}') {
digitalWrite(led, HIGH); // Turn the LED on (HIGH is the voltage level).
delay(1000); // Wait for one second.
digitalWrite(led, LOW); // Turn the LED off by making the voltage LOW.
delay(1000); // Wait for a second.
}
Some definitions first:
SOP = Start Of Packet (in your case, an opening brace)
EOP = End Of Packet (in your case, a closing brace)
PAYLOAD = the characters between SOP and EOP
PACKET = SOP + PAYLOAD + EOP
Example:
PACKET= {Abc}
SOP = {
EOP = }
PAYLOAD = Abc
Your code should process one character at a time, and should be structured as a state machine.
When the code starts, the parser state is "I'm waiting for the SOP character". While in this state, you throw away every character you receive unless it's equal to SOP.
When you find you received a SOP char, you change the parser state to "I'm receiving the payload". You store every character from now on into a buffer, until you either see an EOP character or exhaust the buffer (more on this in a moment). If you see the EOP char, you "close" the buffer by appending a NULL character (i.e. 0x00) so that it becomes a standard NULL-terminated C-string, and you can work on it with the standard functions (strcmp, strstr, strchr, etc.).
At this point you pass the buffer to a "process()" function, which executes the operation specified by the payload (1)
You have to specify the maximum length of a packet, and size the receive buffer accordingly. You also have to keep track of the current payload length during the "payload receive" state, so you don't accidentally try to store more payload bytes into the temporary buffer than it can hold (otherwise you get memory corruption).
If you fill the receive buffer without seeing an EOP character, then that packet is either malformed (too long) or a transmission error changed the EOP character into something else. In either case you should discard the buffer contents and go back to "Waiting for SOP" state.
Depending on the protocol design, you could send an error code to the PC so the person typing at the terminal or the software on that side knows the last command it sent was invalid or not received correctly.
Finally, the blink code in you snipped should be replaced by non-blocking "blink-without-delay"-style code (look at the example that come with the Arduino IDE).
(1) Example of a "process" function:
void process(char* cmd) {
if (strcmp(cmd, "open_valve") == 0) {
open_valve();
}
else if (strcmp(cmd, "close_valve") == 0) {
close_valve();
}
else {
print_error("Unrecognized command.");
}
}
It seems you are comparing the string in this statement:
if( readString == '{blink_Flow_A}' )
So I don't get your question re :
but I can't figure out how to compare the "readString" to process something
Are you really asking:
How do I extract the commands from an incoming stream of characters?
If that is the case then treat each command as a "packet". The packet is enclosed in brackets: {}. Knowing that the {} brackets are start and end of a packet, it is easy to write a routine to get at the command in the packet.
Once the command is extracted just go through a if-then-else statement to do what each command is supposed to do.
If I totally misunderstood your question I apologize :)
EDIT:
see http://arduino.cc/en/Tutorial/StringComparisonOperators
if( readString == "{blink_Flow_A}" ) should be correct syntax.
Since you have a statement
Serial.println( readString);
you should see the string received.

Resources