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

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.

Related

Reading multiple bytes in Arduino sent using Pyserial

I'm constantly sending structs of int64 via Pyserial with:
with serial.Serial(port='COM4', baudrate=115200, timeout=.1) as arduino:
value = write_read(struct.pack(">q", int_array[1][i])) #this sends signed int.64 in bytes
print(value)
the struct.pack has this shape, for example:
b'\xff\xff\xff\xff\xff\xff\xff\xef'
and the function write_read consists of:
def write_read(x):
arduino.write((x))
data = arduino.readline()
#the idea is to receive an ACK from the Arduino after 8 bytes (the full
#number)
return data
The code I'm trying to develop in arduino is the following:
void loop() {
// send data only when you receive data:
if (Serial.available() \> 0) {
// read the incoming byte:
incomingByte = Serial.read();
//read 8 bytes and create the result
r= function_to_read_8_last_bytes // or similar
// say what you got:
Serial.print("I received: ");
Serial.printlesultn(r, DEC);
Serial.write("ACK");
}
}
I'm very curious how I could do a robust "read 8 bytes" function.
Should I add some especial character in the Python part to indentify when it ends one value?
Thanks! I'll appreciate any help :)
Given the discussion in the comments, it's hard to receive a stream of bytes and be sure that the receiver is completely synchronized. However let's make some assumptions to ease the problem:
The serial buffer is empty when you connect your laptop to Arduino. This ensures you won't receive spurious data with no meaning. I had this problem happens a lot when the serial connection was ended abruptly by any cause.
You are not constantly sending bytes, Arduino has time to process them until the start of the new sequence.
You only send this data, so there is no need to create a higher level protocol on top of it. Bare in mind that the serial communication is almost just an hardware stack, you receive bytes with no headers.
For assumption 1 you can write a simple piece of code to consume all the spurious bytes in the serial buffer as soon as your main starts from Arudino, so this will be done everytime you connect the serial (as this is also where the power supply comes from). Something like this:
void serialFlush(){
while(Serial.available() > 0) {
char t = Serial.read();
}
}
You can send a "READY" signal back to the Python interface, so that the program knows you are ready to receive data.
Going on with the solution you can implement an easy CRC in python, an additional byte which contains a XOR of all the previous bytes, and you check that in Arduino upon reception complete.
def xor_reduce_long_int(li):
res = 0;
for i in range(8):
mask = (0xFF)<<(i*8)
print(hex(mask))
masked = (li&mask)>>(i*8)
res ^= masked
return res
with serial.Serial(port='COM4', baudrate=115200, timeout=.1) as arduino:
crc=xor_reduce_long_int(int_array[1][i])
value = write_read(struct.pack(">qc", int_array[1][i],crc)) #this sends signed int.64 in bytes
print(value)
And with Arduino I would read 8 bytes when they are available and put them into an unsigned char buffer. I would then define a union that alias such buffer to interpret it as long long int.
typedef struct long_int_CRC
{
union
{
unsigned char bytes[8];
long int data;
};
unsigned char CRC;
}data_T;
// .. Later in main
data_T = received_data;
int received_bytes=0
unsigned char my_CRC = 0;
unsigned char rec_byte= 0;
while( received_bytes < 8 )
{
if(Serial.available() )
{
// Get the byte
rec_byte = Serial.read()
// Store the byte and calc CRC
received_data.bytes[received_bytes] = rec_byte;
my_CRC ^= rec_byte;
// Increment counter for next byte
received_bytes++;
}
}
// Reception complete, check CRC
unsigned char rec_CRC;
if(Serial.available() )
{
rec_CRC = Serial.read()
}
if( my_CRC != rec_CRC )
{
// Something was wrong!
}
// Now access your data as a long int
Serial.print("I received: ");
Serial.printlesultn(received_data.data, DEC);
Serial.write("ACK");

How to program own Wifi "Mute" Stomp Box to remote control a Behringer X32 Rack?

I´m totally new to coding, this is even my first post here. Im tryng this because nobody sells what I want/need ;-).
I achived already quite a bit, but at this moment I´m getting lost with a lot of things (I read a lot about coding in general and in special with Arduino the last 8 dayas)... but let me explain first what my intention on this project is:
I want to build a "Stomp Box" to mute a Behringer X32 Rack (wireless) Channels/Mutegroups/Buses, just Mute On/Off.. nothing else.
This Box should have 4-6 "stompers" (buttons), each of this buttons should have a different Mute function.
Also the current state of the Channel/Mutegroup/Bus should be indicated by LED´s green if unmuted or red if muted.
Therfore the box needs to evaulate the current state of the designated Channel/Mutegroup/Bus, because it could change also from other remote devices.
And then switch to the opposite state when pressing/stomping on designated button.
I´d like to have code where I can easily change the action of a button, Like:
button1 = /ch/01/mix/on ,i 1
button2 = /config/mute/1 ,i 1
button3 = /dca/1/on ,i 1
so in case I need a differnt Channel/Mutegroup/Bus for another event simply edit and recode my ESP32 Node Kit
So here is my code I already have:
#include "WiFi.h"
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <SPI.h>
#include <OSCMessage.h> //https://github.com/CNMAT/OSC
#define WIFI_NETWORK "xxxxxxxxxx" //SSID of you Wifi
#define WIFI_PASSWORD "xxxxxxxxxxx" //Your Wifi Password
#define WIFI_TIMEOUT_MS 20000 // 20 second WiFi connection timeout
#define WIFI_RECOVER_TIME_MS 30000 // Wait 30 seconds after a failed connection attempt
int muteOn = 0;// 0=Mute
int muteOff = 1;// 1=Unmute
int input;
WiFiUDP Udp;
const IPAddress outIp (192, 168, 10, 129); //Mixers IP
const unsigned int outPort = 10023; //X32 Port
//variables for blinking an LED with Millis
const int led = 2; // ESP32 Pin to which onboard LED is connected
unsigned long previousMillis = 0; // will store last time LED was updated
const long interval = 300; // interval at which to blink (milliseconds)
int ledState = LOW; // ledState used to set the LED
void connectToWiFi(){
Serial.print("Zu WLAN verbinden...");
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_NETWORK, WIFI_PASSWORD);
unsigned long startAttemptTime = millis();
while(WiFi.status() != WL_CONNECTED && millis() - startAttemptTime < WIFI_TIMEOUT_MS){
Serial.println(".");
delay(100);
}
if(WiFi.status() != WL_CONNECTED){
Serial.println("Nicht Verbunden!");
//optional take action
}else{
Serial.print("WLAN Verbunden mit ");
Serial.println(WIFI_NETWORK);
Serial.println(WiFi.localIP( ));
}
}
void setup() {
Serial.begin(115200);
connectToWiFi();
Udp.begin(8888);
pinMode(led, OUTPUT);
// Port defaults to 3232
// ArduinoOTA.setPort(3232);
// Hostname defaults to esp3232-[MAC]
// ArduinoOTA.setHostname("myesp32");
// No authentication by default
// ArduinoOTA.setPassword("admin");
// Password can be set with it's md5 value as well
// MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
// ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");
ArduinoOTA
.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
type = "sketch";
else // U_SPIFFS
type = "filesystem";
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("Start updating " + type);
})
.onEnd([]() {
Serial.println("\nEnd");
})
.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
})
.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
Serial.println("Ready");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop(){
ArduinoOTA.handle();
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
ledState = not(ledState);
// set the LED with the ledState of the variable:
digitalWrite(led, ledState);
}
input=Serial.read();
if (input=='0'){
// welcher status hat der kanal?
// wenn Kanal gemutet dann unmute und umgekehrt
Serial.println("Mute!");
delay(100);
sendMute(); //send Mute to Mixer
Serial.println("...");
}
if (input=='1'){
Serial.println("UnMute!");
delay(100);
sendUnMute();
Serial.println("...");
}
}
void sendMute() {
//the message wants an OSC address as first argument
OSCMessage msg("/ch/01/mix/on");
msg.add(muteOn);
Udp.beginPacket(outIp, outPort);
msg.send(Udp); // send the bytes to the SLIP stream
Udp.endPacket(); // mark the end of the OSC Packet
msg.empty(); // free space occupied by message
delay(20);
}
void sendUnMute() {
//the message wants an OSC address as first argument
OSCMessage msg("/ch/01/mix/on");
msg.add(muteOff);
Udp.beginPacket(outIp, outPort);
msg.send(Udp); // send the bytes to the SLIP stream
Udp.endPacket(); // mark the end of the OSC Packet
msg.empty(); // free space occupied by message
delay(20);
}
So I testet this via serial Monitor, when I input "0" and click send, the mixer mutes channel 1 and on input "1" channel 1 becomes unmuted, so far so good... (OSCMessage msg("/ch/01/mix/on"); ... section.
What bothers me here in special is, I had to hardcode the command "/ch/01/mix/on", because I am not able to declare a variable? for this string? I am already so confused that I don´t know if I even have the terms right :-(
BTW: There are a lot solutions out there how to do it with MIDI, but MIDI is not wireles and I think for my project overkill. I also did some some research on github.com/CNMAT/OSC but I don´t get it... (crying)...
I found also a post here, but this didn´t helped either... :-(
Any advice on that how I can reach my goal?--
Any help is much apprceiated... even in German (my native language... )
PS: Yes I´m a begginner and I admit it. But at least I managed how to connect and flash this thing even via OTA in the last 8 days, so please be easy on me.
Not wanting to hardcode your commands is a good instinct.
The Arduino language is C++, which is (mostly) a superset of C. C and C++ use a preprocessor which lets you define constants and test for their presence.
For instance, you could write:
#define CHAN01_MIX_ON_COMMAND "/ch/01/mix/on"
and then use CHAN01_MIX_ON_COMMAND anywhere you want to use that constant, like so:
void sendMute() {
//the message wants an OSC address as first argument
OSCMessage msg(CHAN01_MIX_ON_COMMAND);
Then if you ever need to change the string "/ch/01/mix/on" you can just change it in one location and not worry about finding every instance of it in your code.
Writing the names in #define statements is a convention people usually follow in order to make it more clear that they're constants.
You have to write the #define line before you use the constant you defined, so putting it at the start of the file (after any #include lines and before your first function) is a good practice. Or if you have several you might put them all in their own file called something like commands.h (the .h means header file)and then include that at the start of any file that needs it like so:
#include "commands.h"
This #include statement would insert the contents of the file commands.h into the file that the statement is in.
When you have several #define statements, keeping them all together in one place (whether it's at the top of the file or in their own file) is also a good practice so that you have one central place to find them and update them if you need to.
Some people will assign the string constant to a variable like so:
char *channel01_mix_on_cmd = "/ch/01/mix/on";
Here char means "a character" - like one letter or number or symbol. The * means pointer to, which lets you use an array of characters. Simple strings in C and C++ are just arrays of characters (or a pointer to the first character), with a special hidden character at the end set to numeric value 0 (not the character '0'). C++ also has a string datatype called std::string and Arduino programs have String but those are both overkill here. They all let you work with strings; String is much easier to use than char * but both have strengths and weaknesses.
Like the #define, you'd also place that outside a function near the start of the file. It defines a global variable that would be available to any function that references it.
You'd also use the variable anywhere they want the string. It's the same idea as using #define, just done slightly differently. For instance:
void sendMute() {
//the message wants an OSC address as first argument
OSCMessage msg(channel01_mix_on_cmd);
Using a variable here is an attempt to save storage by not having multiple copies of the string. It's not necessary; C/C++ compilers have for a very long time detected this and stored only one copy of the string. It might save space if your code is split into multiple files.
Saving space on CPUs like the ESP32 and ESP8266 is important because they have so little memory. #define is fine here because the compiler does it automatically for you.
You can create the command string with sprintf.
so for example:
#define CHANNELON "on"
#define CHANNELOFF "off"
int channel;
int mute;
char messageString[100];
// some code that calculates the channel number and the mute state:
channel = 1;
mute = 1;
// then check the mute state and create the command string:
if (mute)
{
// to turn off a channel:
sprintf(messageString,"/ch/%02d/mix/%s",channel,CHANNELOFF);
}
else
{
// to turn on a channel:
sprintf(messageString,"/ch/%02d/mix/%s",channel,CHANNELON);
}
// send the command:
OSCMessage msg(messageString);
the %02d will substitute an integer with a zero in front,
if it's smaller than 10 and that is always 2 characters long.
so if channel is 1, the result would be 01

Arduino sketch with Serial.available() passes twice

When I test Serial.available() or Serial.available() > 0 in my loop() function, it appears to return true twice each time I enter serial data. The second time, it sets the throttle value in my code to 0. Here is the code:
#include <Servo.h>
Servo rc_rotor;
int throttle = 0; // servo position indicates throttle position.
String s_throttle_set = "Throttle set to: ";
String s_throttle_read = "Reading throttle value: ";
String s_action_error = "No action known for input value: ";
void setup()
{
rc_rotor.attach(9);
Serial.begin(9600);
while(! Serial);
Serial.println("Throttle value: 0 through 255, or 999 to read current value.");
}
void loop()
{
rc_rotor.write(throttle);
delay(20);
if (Serial.available())
{
int temp_throttle = Serial.parseInt();
if (temp_throttle >= 0 && temp_throttle <= 180)
{
throttle = temp_throttle;
Serial.println(s_throttle_set + throttle);
}
else if (temp_throttle == 999)
{
Serial.println(s_throttle_read + throttle);
}
else
{
Serial.println(s_action_error + temp_throttle);
}
}
}
Please note this code is not my final masterpiece. Much of it is from publicly available examples. Anyway, the statement if (Serial.available()) succeeds twice. By that I mean, it is true when I type in a value such as 125, and a moment later it will be 'true' again when I have typed in nothing additional. I only expect one value to go through this way. The result is that my throttle is being set to the value I enter, and then almost immediately re-set to 0. Why would something like this happen?
It turns out there is no mysterious problem with the hardware or the code, as I first suspected there was. Actually, the solution is simply to select "no line ending" in the Arduino Serial Monitor's dropdown option (by default, I guess mine was set to "New Line"). Without the additional character being inserted by the Serial Monitor, everything behaves as expected.
One thing I did not expect is how the Arduino software interprets the newline. I debugged by printing the ascii values that were making it through my if-statement. First of all, the Serial Monitor sent the number I typed in, followed moments later by ascii 10, which is the line feed character. Fine, no problem. But then Serial.parseInt() chewed on that line feed for a moment (there was a slight but noticeable delay), then fed the numeral 0 to my function. It took me a little while to figure out why. Here is an explanation from the Serial part of the Arduino Language Reference:
parseInt()
Description
Looks for the next valid integer in the incoming serial stream.
parseInt() inherits from the Stream utility class.
In particular:
Initial characters that are not digits or a minus sign, are skipped;
Parsing stops when no characters have been read for a configurable
time-out value, or a non-digit is read;
If no valid digits were read
when the time-out (see Serial.setTimeout()) occurs, 0 is returned;
So Serial.available() is true after the line feed character enters the buffer, but there is no "valid digit" according to Serial.parseInt(). Understandably... we are looking at an empty buffer that finally times out. Therefore Serial.parseInt() returns 0 and the code that follows proceeds with that value.
The code in the question assumed that the only input would be integers coming over the serial connection, which is actually a pretty fragile assumption. If you need to use Serial.parseInt in a situation where empty buffers (null), line feeds or other unexpected characters might come through, it should just be a matter of filtering the input better than I did in the example code.

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");
}

Resources