问题
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());
}
回答1:
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 \r\n
. This means you can try to receive data until the final \n
. Make use of readBytesUntil or readStringUntil like:
void printSerialData()
{
String read = myGsm.readStringUntil('\n');
Serial.write(read);
}
Don't forget to set a correct timeout by calling setTimeout before.
来源:https://stackoverflow.com/questions/59518216/how-to-remove-delay