I have the following simple code to read commands sent from the computer to an Arduino Mega board:
void get_command()
{
char received;
int index = 0;
while (Serial.available() > 0) {
if (index < BUFFER_SIZE -1) {
received = Serial.read();
if (received == '\n') {
buffer[index] = '\0';
parse_command(buffer);
} else {
buffer[index++] = received;
}
} else {
Serial.println('666'); // buffer overflow
}
}
}
The commands are like A123 B123 C123 D123\n
Basically a sequence of space separated instructions, were each instruction starts by a letter and follows by a number. A command ends with a "\n".
Reading this seems to be very unstable. Sometimes I get the command perfectly, sometimes I miss the first letter, sometimes a pair of them, sometimes it starts by the number,...
I am sending the commands through the serial monitor, set to newline.
Before having this code, I'd simply check for the size using Serial.available, then Id wait a second to fill the buffer, and then I'd copy the buffer to a char*. This worked flawlessly. I am doing now this loop waiting for a \n, which seems more elegant, but it is being very unstable.
Code works by simply adding a delay(100) after the first Serial.available()
This is the code:
void get_command()
{
char received;
if (Serial.available() > 0) {
delay(100); // let the buffer fill up
int index = 0;
while (Serial.available() > 0) {
if (index < BUFFER_SIZE -1) {
received = Serial.read();
if (received != '\n') {
buffer[index] = received;
index++;
} else {
buffer[index] = '\0';
parse_command(buffer);
}
} else {
Serial.println('666'); // buffer overflow
}
}
}
}
Related
Below is the code being used by Arduino to extract two integers at a time, from formatted text in the serial. The format being two numbers. each followed by a comma, eg 51,7, After reading in the ints, it is supposed to do stuff with them, then loop back and go again, unless there is no data, then it is supposed to skip past the if and do stuff using the current int values.
void setup() {
Serial.begin(9600);
}
char rx_byte = 0;
String rx_str[2] = {""};
int nums[2] = {0}, a;
int PIN = 13;
boolean not_read = true;
void loop() {
if (Serial.available() > 0) { // is a character available?
memset(nums, 0, sizeof(nums));
rx_str[0] = "";
rx_str[1] = "";
a = 0;
while( a < 2 ){
not_read = true;
while(not_read){
rx_byte = Serial.read(); // get the character
if ((rx_byte >= '0') && (rx_byte <= '9')) {
rx_str[a] += rx_byte;
} // if ((rx_byte >= '0') && (rx_byte <= '9'))
else if (rx_byte == ',') {
not_read = false;
a++;
} // else if (rx_byte == ',')
} // while(not_read)
} // while(int a < 2)
nums[0] = rx_str[0].toInt();
nums[1] = rx_str[1].toInt();
} // if (Serial.available() > 0)
// do stuff with ints
} // void loop
This turnout works fine when the Arduino is plugged into the usb and the right data is entered into the serial monitor. The problem is, when the data is written by another program in c, using bluetooth with an HC-05-1 module, when there is no data, arduino hangs at the if statement waiting for serial input, instead of skipping past and doing stuff. Below is the C++ code for writing the data.
void right( double times[3] ) {
nums[0] = (int) times[0];
nums[1] = (int) times[1];
int bytes_written = 0; // bytes_read = 0;
printf( "\n nums[0]: %d ", nums[0]);
printf( "\n nums[1]: %d ", nums[1]);
sprintf( buf, "%d,%d,", nums[0],nums[1] );
printf( "\n writing ");
puts(buf);
bytes_written = write(s, buf, sizeof(buf));
printf("\n %d Bytes written to bluetooth", bytes_written);
printf("\n +----------------------------------+\n\n");
}
And this is sample output from function right()
nums[0]: 4
nums[1]: 2
writing 4,2,
15 Bytes written to bluetooth
+----------------------------------+
I dont kmow how relevant this is but here some output from function right() when the bluetooth and board are not powered up.
nums[0]: 16
nums[1]: 5
writing 16,5,
16,5,
15 Bytes written to bluetooth
+----------------------------------+
Not sure where that extra line of output comes from. Last week it used to output 0 Bytes written to bluetooth without the extra line, but changes have been made since then.
Edit....
Patrick Trentin's diagnosis was right.
sprintf( buf, "%d,%d,", nums[0],nums[1] );
needed to be changed to
int str_len = sprintf( buf, "%d,%d,", nums[0],nums[1] );
and
bytes_written = write(s, buf, sizeof(buf));
needed to be changed to
bytes_written = write(s, buf, str_len);
It was a bit disappointing how long the read process took, so some pretty serious optimization is needed, but it does seem to do what was intended... eventually.
I assume that for messages that are of only 1 byte (a char), I will use read() and write() directly.
For those messages having size > 1 bytes, I use two subfunctions to read and write them over sockets.
For example, I have the server construct a string called strcities (list of city) and print it out --> nothing strange. Then send the number of bytes of this string to the client, and then the actual string.
The client will first read the number of bytes, then the actual city list.
For some reason my code sometimes work and sometimes doesn't. If it works, it also prints out some extra characters that I have no idea where they come from. If it doesn't, it hangs and forever waits in the client, while the server goes back to the top of the loop and wait for next command from the client. Could you please take a look at my codes below and let me know where I did wrong?
Attempt_read
string attempt_read(int rbytes) { // rbytes = number of bytes of message to be read
int count1, bytes_read;
char buffer[rbytes+1];
bool notdone = true;
count1 = read(sd, buffer, rbytes);
while (notdone) {
if (count1 == -1){
perror("Error on write call");
exit(1);
}
else if (count1 < rbytes) {
rbytes = rbytes - count1; // update remaining bytes to be read
count1 = read(sd, buffer, rbytes);
}
else {notdone = false;}
} // end while
string returnme;
returnme = string(buffer);
return returnme;
}
Attempt_write
void attempt_write(string input1, int wbytes) { // wbytes = number of bytes of message
int count1;
bool notdone = true;
count1 = write(sd, input1.c_str(), wbytes);
while (notdone) {
if (count1 == -1){
perror("Error on write call");
exit(1);
}
else if (count1 < wbytes) {
wbytes = wbytes - count1;
count1 = write(sd, input1.c_str(), wbytes);
}
else {notdone = false;}
} // end while
return;
}
1) string class has a method size() that will return the length of the string, so you do not actually need a second attempt_write parameter.
2) You can transfer length of message before message or you can transfer a terminating 0 after, if you only will sent an ASCII strings. Because your connection could terminate at any time, it is better to send exact length before sending the string, so your client could know, what to expect.
3) What compilator do you use, that would allow char buffer[rbytes+1]; ? A standard c++ would require char buffer = new char[rbytes+1]; and corresponding delete to avoid a memory leaks.
4) In your code, the second read function call use same buffer with no adjustment to length, so you, practically, overwrite the already received data and the function will only work, if all data will be received in first function call. Same goes for write function
I would suggest something like this:
void data_read(unsigned char * buffer, int size) {
int readed, total = 0;
do {
readed = read(sd, buffer + total, size - total);
if (-1 == writted) {
perror("Error on read call");
exit(1);
}
total += readed;
} while (total < size);
}
string attempt_read() {
int size = 0;
data_read((unsigned char *) &size, sizeof(int));
string output(size, (char) 0x0);
data_read((unsigned char *) output.c_str(), size);
return output;
}
void data_write(unsigned char * buffer, int size) {
int writted, total = 0;
do {
writted = write(sd, buffer + total, size - total);
if (-1 == writted) {
perror("Error on write call");
exit(1);
}
total += writted;
} while (total < size);
}
void attempt_write(string input) {
int size = input.size();
data_write((unsigned char *) &size, sizeof(int));
data_write((unsigned char *) input.c_str(), size);
}
Good day all!
I am working on a project with Arduino UNO and a SIM908.
I am trying to understand the AT command.
When I enter
Serial.print("AT")
Serial.println("AT+CGPSSTATUS?");
Serial retuen a value and I would like to save that value into a buffer
char buffer[size]
I do not want to have other string than the return value of an AT command.
I also red that document
SIM908 AT Command Manual_V1.01
At the page 13, you can read (NB. < CR>< LF> : I added a space after the first <, other there are not display)
The "AT" or "at" prefix must be set at the beginning of each Command
line. To terminate a Command line enter < CR>. Commands are usually
followed by a response that includes. "< CR>< LF>< CR>< LF>"
Throughout this document, only the responses are presented, < CR>< LF>
are omitted intentionally
Then, I am asking how I can "extract" the response between < CR>< LF> and < CR>< LF>
Looking at this exemple (let me know if I am wrong), how can I detect the < CR>< LF>
void setup()
{
char buffer[200];
Serial.println("AT+CGPSSTATUS?");
}
void loop()
{
if (Serial.available())
{
// HERE I SHOULD CHECK IF CR ANF LF
Serial.write(Serial.read());
// AND SAVE IT IN buffer. IS'T NOT?
}
}
}
Do you see what I means?
How could you help me to store in a buffer, only the return value of an AT command?
Many thank for your help
It's very interresting what you show me. Here is how I adapt my code
I adapted my code and by the way I created a file for testing Serail while we send a AT command.
The concern function are loop() and read_AT_string(). (I renamed the read_String to read_AT_string().
Here my code and I explain, after the issue, regardin your proposal
#include <SoftwareSerial.h>
int baud_rate = 9600;
int pin_gsm = 3;
int pin_gps = 4;
int pin_power = 5;
//int pin_dtr = 6;
boolean debug = true;
boolean raedy_to_go = false;
// Reading String
#define BUFFERSIZE 200
char buffer[BUFFERSIZE];
char inChar;
int index;
void setup()
{
Serial.begin(baud_rate);
delay(5000); // Wait for 5sec after begin
if(debug)
{
Serial.println(F("\n****************************"));
Serial.println(F("STARTING SYSTEM Read AT stream"));
Serial.println(F("******************************"));
}
pinMode(pin_gsm,OUTPUT); // Set the pins
pinMode(pin_gps,OUTPUT);
pinMode(pin_power,OUTPUT);
powerUpSim908:
if(powerUpSim908())
{
delay(1000);
if(gps_power()){
gsm_enable();
raedy_to_go = true;
if(debug)
{
Serial.println(F("\n****************************"));
Serial.println(F("READY TO GO\n"));
Serial.println(F("****************************\n"));
}
}
else
{
raedy_to_go = false;
if(debug)
{
Serial.println(F("\nNOT READY TO GO.\nGPS could not be power\nRestart the module\nor/and check the battery level.\n"));
}
goto powerUpSim908;
}
}
else
{
raedy_to_go = false;
if(debug)
{
Serial.println(F("\nNOT READY TO GO.\nCheck the battery level.\n"));
}
};
}
void loop()
{
/*
if (Serial.available())
{
Serial.print("Character received: ");
Serial.write(Serial.read());
Serial.println("");
}
*/
if(raedy_to_go)
{
read_AT_string("AT",5000);
delay(10000);
}
}
char read_AT_string(char* command, int timeout)
{
unsigned long previous;
previous = millis();
Serial.println(F("\nDISPLAY BUFFER:"));
index=0;
Serial.println(command);
do
{
if(Serial.available() > 0) // Don't read unless
// there you know there is data
{
Serial.println("1");
if (Serial.peek() == 13) // check if CR (without reading)
{
Serial.println("13");
if(Serial.available() > 0)
{
Serial.read(); // read and ignore
if (Serial.peek()==10) // then check if LF (without reading)
{
Serial.println("10");
if(index < Serial.readBytesUntil(13, buffer, BUFFERSIZE-1)) // One less than the size of the buffer array
{
Serial.println("b");
inChar = Serial.read(); // Read a character
buffer[index] = inChar; // Store it
index++; // Increment where to write next
buffer[index] = '\0'; // Null terminate the string
}
}
}
}
}
}while(((millis() - previous) < timeout));
Serial.println(buffer);
buffer[0]='\0';
Serial.println(F("END DISPLAY BUFFER"));
}
/* FUNCTION */
boolean powerUpSim908(void)
{
if(debug)
{
Serial.println(F("Powering up SIM908"));
}
boolean turnedON = false;
//uint8_t answer=0;
int cont;
for (cont=0; cont<3; cont++)
{
digitalWrite(pin_power,HIGH);
delay(1500);
digitalWrite(pin_power,LOW);
Serial.println(F("Checking if the module is up"));
if(sendATcommand("AT", "OK", 5000))
{
cont = 4; // Leave the loop
turnedON = true;
}
else
{
turnedON = false;
if(debug)
{
Serial.println(F("\nTrying agin to turn on SIM908"));
}
};
}
if(turnedON)
{
if(debug)
{
Serial.println(F("Module is tunrned up\n"));
}
}
else
{
if(debug)
{
Serial.println(F("Module is NOT tunrned ON\n"));
}
}
return turnedON;
}
boolean sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout)
{
uint8_t x=0;
bool answer=false;
//åchar response[100];
//buffer[0]='\0';
unsigned long previous;
//memset(response, '\0', 100); // Initialice the string
//Serial.println(response);
delay(100);
while( Serial.available() > 0) Serial.read(); // Clean the input buffer
if (ATcommand[0] != '\0')
{
Serial.println(ATcommand); // Send the AT command
}
x = 0;
previous = millis();
index=0;
do
{
if(Serial.available() > 0)
// there you know there is data
{
if(index < BUFFERSIZE-1) // One less than the size of the array // Same as buffer size
{
inChar = Serial.read(); // Read a character
buffer[index] = inChar; // Store it
index++; // Increment where to write next
//Serial.println(index);
buffer[index] = '\0'; // Null terminate the string
}
}
}while(((millis() - previous) < timeout));
if(strstr(buffer,"NORMAL POWER DOWN") != NULL)
{
answer = false;
}
else if (strstr(buffer, expected_answer) != NULL) // check if the desired answer (OK) is in the response of the module
{
/*
Serial.println(F("### BUFFER"));
Serial.println(buffer);
Serial.println(F("### END BUFFER"));
*/
answer = true;
}
else
{
answer = false;
}
if(debug)
{
if(answer)
{
//Serial.println(F("Expected answer : OK!\n"));
}
else
{
//Serial.println(F("Expected answer : KO!\n"));
};
}
return answer;
}
void gps_enable(void)
{
if(debug)
{
Serial.println(F("\nEnabling GPS ..."));
}
digitalWrite(pin_gps,LOW); //Enable GPS mode
digitalWrite(pin_gsm,HIGH); //Disable GSM mode
delay(2000);
}
void gsm_enable(void)
{
if(debug)
{
Serial.println(F("\nEnabling GSM ..."));
}
digitalWrite(pin_gsm,LOW); //Enable GSM mode
digitalWrite(pin_gps,HIGH); //Disable GPS mode
delay(2000);
}
/* UTILISTIES */
/* GPS */
boolean gps_power(void) //turn on GPS power supply
{
/*
Serial.println("AT");
delay(2000);
*/
boolean gpspwr = false;
boolean gpsrst = false;
if(sendATcommand("AT+CGPSPWR=1","OK",2000))
{
gpspwr = true;
if(debug)
{
Serial.println("turn on GPS power supply => OK");
}
}
else
{
if(debug)
{
Serial.println("turn on GPS power supply => KO");
}
};
//delay(1000);
if(sendATcommand("AT+CGPSRST=1","OK",2000))
{
gpsrst = true;
if(debug)
{
Serial.println("reset GPS in autonomy mode => OK");
}
}
else
{
if(debug)
{
Serial.println("reset GPS in autonomy mode => KO");
}
}; //reset GPS in autonomy mode
delay(1000);
if(gpspwr && gpsrst)
{
return true;
}else
{
return false;
}
}
At the read_AT_string, the first if(Serial.peek()==13) always return false.
1 is printed, but '13' is not, then I supposed
if(Serial.peek()==13)
return false
Here is what is printed within 5 sec
AT DISPLAY BUFFER:
1
1
1
1
1
1
1
1
1
[...] // It prints 1 until now
1
END DISPLAY BUFFER
Here a piece of code to detect and remove CR+LF (Attention: if A CR is read but it's not followed by a LF, it is removed as well):
if (Serial.peek()==13) { // check if CR (without reading)
Serial.read(); // read and ignore
if (Serial.peek()==10) // then check if LF (without reading)
Serial.read();
}
To read the rest of the response from Serial you could use:
buffer[Serial.readBytesUntil(13, buffer, 199)]=0; // readbytes returns the number of bytes read
You then have to discard the ending CRLF (same as above).
Edit
There are several issues with the code that you've posted in a separate answer.
When you powerUpSim908() you have to be aware that the gsm module may send unrequested data (see documentation, chapter 1.4):
Note: A HEX string such as "00 49 49 49 49 FF FF FF FF" will be sent
out through serial port at the baud rate of 115200 immediately after
SIM908 is powered on. The string shall be ignored since it is used for
synchronization with PC tool. Only enter AT Command through serial
port after SIM908 is powered on and Unsolicited Result Code "RDY" is
received from serial port.
This means that before you send anything, you have to discard this data by reading it. I guess this is why you don't get CRLF when reading the response: you first get the HEX string or "RDY".
Then readBytesUntil() reads as many bytes as available (maxi 199 in my example above), stores them in the buffer. It stops reading when it encounters the byte 13 (i.e.CR). There is no need to loop on an index. The function returns the number of chars that could be read, and it doesn't put an ending 0 at the end of the buffer (i.e. no valid C string). If you want to use the function in another way than what I proposed, you must store the length returned, because you have no other way to find it out later on.
I am trying to read data from an Arduino serial port. My current code:
if(Serial.available()>0){
if(Serial.available()==9){...}
When I type 9 characters in the serial monitor it works fine.
So when I add a second if in the
if(Serial.available()>0)
after the
if(Serial.available()==9){}
it recognizes each character as a single reading. For example when i type 4 characters it says Serial.available()=1 4 times.
real code:
if(Serial.available() > 0){
if(Serial.available()==9){
for(int i =0;i<9;i++){
RGB[i]=Serial.read() - '0';
}
//get the data from the integer array
R= RGB[0]*100+RGB[1]*10+RGB[2];
G= RGB[3]*100+RGB[4]*10+RGB[5];
B= RGB[6]*100+RGB[7]*10+RGB[8];
for(int q=0; q<=255; q++){
if(R>Rp){
Rp+=1;
analogWrite(8, Rp);
}else if(R<Rp){
Rp-=1;
analogWrite(8, Rp);
}
if(G>Gp){
Gp+=1;
analogWrite(9, Gp);
}else if(G<Gp){
Gp-=1;
analogWrite(9, Gp);
}
if(B>Bp){
Bp+=1;
analogWrite(10, Bp);
}else if(B<Bp){
Bp-=1;
analogWrite(10, Bp);
}
delay(10);
}
}
// if(Serial.read()=='r'){
// if(readinglstate==0){
// analogWrite(readinglight, 5);
// readinglstate=1;
// }else if(readinglstate==1){
// analogWrite(readinglight, 70);
// readinglstate=2;
// }else if(readinglstate==2){
// analogWrite(readinglight, 255);
// readinglstate=3;
// }else if(readinglstate==3){
// analogWrite(readinglight, 0);
// readinglstate=0;
// }
// }
}
The commented code is the one that changes the things...
The
Serial.read()=='r'
is popping the byte off the receive buffer. Think of it more like...
input = Serial.read(); // pop the next byte off, regardless of its value.
if (input == 'r') {
hence all your bytes in the buffer are read off the buffer. until "Serial.available() == 0"
I recommend the peek function.
if(Serial.peek()=='r'){
Serial.read(); // already know it, so pop it.
if(readinglstate==0){
...
Input data can arrive in several chunks, so you need to slightly rework approach to read data, please check the following code for reference:
int bytesToRead = 0;
int currBytePtr = 0;
int RGB[9];
while (9 > currBytePtr) { // we need 9 bytes of data
if (0 < (bytesToRead = Serial.available())) { // have something to read
for (int i = 0; i < bytesToRead; ++i ) {
RGB[currBytePtr++] = Serial.read();
if (9 == currBytePtr) { // we have enough data
break;
}
}
} else {
delay(1000); // sleep a bit
}
} // while
// process data received
...
why not just read the data till you have 9 bytes then process.
char buffer[10];
int index=0;
while (Serial.available()){
buffer[index++]=Serial.read();
if (index>8) {
ProcessData(buffer);
index=0;
}
}
I have the following bit of code. it is meant to recieved data via the serial port and then print it back to the serial port.
char inData[20]; // Allocate some space for the string
char inChar=-1; // Where to store the character read
byte index = 0; // Index into array; where to store the character
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
Serial.write("Power On");
pinMode(pin, OUTPUT);
}
char getValue()
{
index =0 ;
int code =-1;
while(Serial.available() > 0)
{
if(index < 19) // One less than the size of the array
{
inChar = Serial.read(); // Read a character
inData[index] = inChar; // Store it
index++; // Increment where to write next
inData[index] = '\0'; // Null terminate the string
code=1;
}
}
return code;
}
the main loop:
void loop()
{
char response = getValue();
if(response != -1)
{
Serial.println("ok");
Serial.println( inData);
}
The problem i am having which I cant figure out, is if i send it "45" it the prints :
"ok
4
ok
5"
and not "ok 45"
Why is this? Serial.avalible returns the number of bytes available to read, it should return 2 if i send it 45 ?
I gett that in your loop your calling getvalue so quickly that you did not receive all the caracters already.
A simple solution for that is to send a code for the begining and the end of your message.
For instance use '\n' to say end of message.
Then modify get value to wait and continue to read until it find a '\n' as you never know how long it will take