sending integers over serial in arduino - arduino

I am trying to send integers over serial using the serial monitor in the ardunio IDE (then python from a raspberry pi after I debug using serial monitor), and can get single numbers to work with code below, but as soon as I use 10 or 100 it will automatically fill the next variable as 0. I have tried to use serial.readString then convert to an int afterwards, but this is throwing an error also.
int varX = 0;
int varY = 0;
int varZ = 0;
int varCounter = 0;
void setup() {
Serial.begin(115200);
grabNewVars();
}
void grabNewVars()
{
while (varCounter < 3)
{
if (Serial.available() > 0) {
if (varCounter ==0)
{
varX = Serial.parseInt();
}
if (varCounter ==1)
{
varY = Serial.parseInt();
}
if (varCounter ==2)
{
varZ = Serial.parseInt();
}
varCounter++;
}
}
}
void loop()
{
Serial.println("varX = " + String(varX));
Serial.println("varY = " + String(varY));
Serial.println("varZ = " + String(varZ));
Serial.println("variables received, run main loop");
delay(100000);
}

Let's think about what your functions are doing.
Serial.available() returns the number of bytes available in the receive buffer.
Serial.parseInt() reads any digit until a non-digit character is received or it times out if no digit is received within 1 second (default).
In that case it returns 0.
So, in your while loop you wait until something is in the receive buffer by checking Serial.available() > 0.
Note that You enter: 100 (without a line ending).
Now that “something” is in the receive buffer and varCounter is 0, you execute varX = Serial.parseInt();
parseInt will time out after 1 second and return the 100, that has been received within “that” 1 second.
The 100 is stored in varX and varCounter is incremented by 1.
Now you execute varY = Serial.parseInt();
As you most likely did not enter another number within a second, this will timeout and you'll store 0 in varY.
Terminate your number with a non digit character.
For example: by selecting a line ending in the serial monitor or by sending a newline or carriage return from Python code (Or any other single non-digit character).
That way, Arduino knows that the complete Integer has been received and it does not have to wait until it times out.
If you want your code to wait forever: for your next input, check Serial.available > 0 before your next call to parseInt.
You already read every number form the receive buffer so: calling parseInt right away doesn't make sense, unless you know for sure that you'll receive another number within a second.

Related

Arduino Anomalous Second Run on Serial

When running the following program, it works as expected but adds an additional output for -38 as an input. It doesn't matter what input I use, it will print out for -38 as well.
int number;
void setup()
{
Serial.begin(9600);
}
void loop()
{
number=0;
Serial.flush();
while(Serial.available() == 0)
{
//just waiting while nothing entered
}
while (Serial.available()>0)
{
number = Serial.read() - '0';
// read the number in buffer and
//remove ASCII text for "0"
}
Serial.print("You entered: ");
Serial.println(number);
Serial.print(number);
Serial.print(" multiplied by two is ");
number = number * 2;
Serial.println(number);
}
Output looks like:
>You entered: 4
>4 multiplied by two is 8
>You entered: -38
>-38 multiplied by two is -76
Your problem might be the Serial.flush. As the documentation states, it
Waits for the transmission of outgoing serial data to complete. (Prior to Arduino 1.0, this instead removed any buffered incoming serial data.)
You seem to try to achieve the pre 1.0 behavior of flushing the incoming buffer. So basically Serial.flush does nothing in your sketch, which leads to the second run reading and calculating with the line feed character (which is 10 in ASCII).
You could clear the buffer like so:
while ( Serial.available() > 0 ) {
Serial.read();
}
But please note that this part
while (Serial.available()>0)
{
number = Serial.read() - '0';
// read the number in buffer and
//remove ASCII text for "0"
}
may not do exactly what you intend it to to. If for example you would send 12 via serial, it may only print the result for the last character (the 2). It would be equally possible for your program to only output the -38 result, because the last character always is a line feed. You basically just got lucky and the serial data wasn't sent fast enough for this to happen, but as soon as your loop gets longer it likely will happen.
I would rather suggest you moving the calculation part inside the loop too and checking the input data instead of flushing the buffer after the first character. Consider this:
while ( Serial.available() > 0 )
{
// read the number in buffer and
number = Serial.read();
// make sure the character is 0 - 9 in ASCII
if( number < '0' || number > '9' ){
// invalid character, skip
continue;
}
//remove ASCII text for "0"
number = number - '0';
Serial.print("You entered: ");
Serial.println(number);
Serial.print(number);
Serial.print(" multiplied by two is ");
number = number * 2;
Serial.println(number);
}
This would read your buffer byte by byte and would apply the multiplication to each (valid) character.

Arduino - sending large amount of data over Serial

I am trying to build a simple FLASH memory programmer (for 39SF020A) using my arduino mega. I wrote the C code and Python script to send the data over (And it all works as expected).
I need to transfer about 32k of hexadecimal data, but with my settings only 10k of data took about 4 minutes (115200 BAUD), which i found unnecessary long. Currently, i am sending over serial (from Python) my value with a terminator (i chose '$'), so for exmple '3F$'. adresses are calulated on the arduino, so no need to send them.
In my arduino code, i have
String received_string = Serial.readStringUntil('$');
and after programming every byte to teh FLASH using arduino, it sends back a '\n' to let the Python know, that it is ready to receive next byte (the python is waiting for receiving a 'line' and then continues). I am not really sure if this is a way to do it, if sending only one byte at the time is good idea and if not, how many and how do i parse them on the arduino? Is the feedback loop useful?
Thanks.
Python Code:
('file' contains all data)
for item in file[1:]:
ser.write((item + "$").encode("ascii"))
line = ser.readline()
i += 1
if i >= top:
break
elif (i % 100) == 0:
print(i)
Arduino code (just part of it)
if (Serial.available() > 0){
String received_string = Serial.readStringUntil('$');
programData(received_string.toInt(),program_adress);
program_adress++;
}
void programData(char data_in, unsigned long adress)
{
digitalWrite(OE,HIGH);
digitalWrite(CE,LOW);
writeByte(0xAA, 0x5555);
writeByte(0x55, 0x2AAA);
writeByte(0xA0, 0x5555);
writeByte(data_in, adress);
Serial.print("\n"); // Feedback for Python
delayMicroseconds(30); // Just to be on the safe side
}
void writeByte(char data_in, unsigned long adress)
{
setDataAs(OUTPUT);
digitalWrite(OE,HIGH);
digitalWrite(WE,HIGH);
setAdress(adress);
setData(data_in);
digitalWrite(WE,LOW);
delayMicroseconds(1);
digitalWrite(WE,HIGH);
}
// Sets data BUS to input or output
void setDataAs(char dir){
for (unsigned int i = 0; i < data_size ;i++) pinMode(data[i],dir);
}
// Sets data to specific values
void setData(char data_i){
setDataAs(OUTPUT);
for (int i = 0; i < data_size;i++) { digitalWrite(data[i],bitRead(data_i,i)); }
}
void setAdress(long adr){
// Set all adresses
for (int i = 0; i < adresses_size;i++)
digitalWrite(adresses[i],bitRead(adr,i));
}

How to read string using Serial.read outside of loop()?

I want to read a String in Arduino from the keyboard outside of the loop() method.
I have the following method:
void readFromKeyboard(byte arrayAddress[])
{
int count = 0, i = 0;
while ((count = Serial.available()) == 0);
while (i<count)
{
arrayAddress[i++] = Serial.read();
}
}
In the loop() method I am calling it like:
readFromKeyboard(userInput);
where userInput is a byte[];
The problem is that when I input more than one characters it read the 1st character initially and it call the readFromKeyboard again an then reads the rest.
Example; if I input "asdf":
--the 1st time it will do ==> userInput = "a"
--the 2nd time it will do ==> userInput = "sdf"
I have tryed many things but the same happens again and again...
Any suggestions??
So that's what worked:
In the loop():
while(Serial.available() == 0);
delay(100);
readInputFlag = readFromKeyboard(userInput);`
And in the readFromKeyboard method:
void readFromKeyboard(byte arrayAddress[])
{
int i = 0;
while (Serial.available() > 0)
{
arrayAddress[i++] = Serial.read();
}
}
This delay, in the loop method, somehow makes the Serial get the whole string instead of just the first letter.
I know you got it working, but I wanted to show you something that I use to deal with this issue. This is a two-tiered delay system for catching bytes that come in a bit late for whatever reason. It's designed to minimize the delay needed to accomplish that task.
int received_length = 0;
byte serial_incoming_buffer[200];
while(Serial.available()) {
serial_incoming_buffer[received_length++] = Serial.read();
if(!Serial.available()) {
delay(3);
if(!Serial.available()) {
delay(20);
}
}
}
Sometimes the Arduino falls behind in picking up serial from the sender and sometimes it grabs serial too fast. Sometimes the sender lags a little bit. This code will wait 3 ms for more bytes, and if they come in it goes back to receiving as many as are available having only had that very brief delay. This repeats as necessary, then when 3 ms goes by without anything being available, it waits a bit longer (20 ms here) for more bytes. If nothing comes in after the long delay, then the transmission is most likely done and you can safely move on.
I recommend tweaking the delays based on your baud rate.

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

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