Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

arduino - How to remove delay?

I am working on a very important project that needs to have maximum efficiency and speed. Basically I use the serial ports of Arduino to communicate to a SIM900 GSM, but I think this can apply to any other device that is connected to the Serial port of Arduino. The problem is that after each command I send to the SIM900 I put a delay because I don't know how much time it will take to be executed, but sometimes commands can be executed really fast or really slow. My question is: How can I display the output of the SIM900 WITHOUT using the delay but maybe a do {} while; a cycle that checks if something new needs to be displayed? I would appreciate if you guys could help me. Thank You!

Here are some commands I used for the serial communication:

 myGsm.begin(19200);  
 Serial.begin(9600);  
 delay(500);

 myGsm.println("AT+CGATT=1");
 delay(200);



 printSerialData();

 myGsm.println("AT+SAPBR=3,1,"CONTYPE","GPRS"");//setting the SAPBR,connection type is GPRS
 delay(1000);
 printSerialData();


 myGsm.println("AT+SAPBR=3,1,"APN","internet.wind"");//setting the APN,2nd parameter empty works for all networks 
 delay(5000);
 printSerialData();


 myGsm.println("AT+SAPBR=0,1");
 delay(1000);
printSerialData();

 myGsm.println("AT+SAPBR=1,1");
 delay(10000);
printSerialData();

 myGsm.println("AT+HTTPINIT"); //init the HTTP request
 delay(2000); 
printSerialData();


void printSerialData()
{
 while(myGsm.available()!=0)
 Serial.write(myGsm.read());
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are several ways to solve your problem. One way is a blocking loop until data was received:

void printSerialData()
{
    //Block until data is received
    while(myGsm.available() <= 0);

    //Get received
    while(myGsm.available() > 0)
    {
        while(myGsm.available() > 0)
        {
            Serial.write(myGsm.read());
        }
        //Give chance to receive more
        delay(10);
    }
}

An alternative way makes use of the fact, that AT commands are typically finalized by . This means you can try to receive data until the final . Make use of readBytesUntil or readStringUntil like:

void printSerialData()
{
    String read = myGsm.readStringUntil('
');
    Serial.write(read);
}

Don't forget to set a correct timeout by calling setTimeout before.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...