简体   繁体   中英

How to exit a 'for' loop while serial.available in Arduino

Background: I am using an XBee connected with a PC and a XBee + Arduino (sensor too). I want to send a command from the PC to the Arduino side. The Arduino side will get the command and send sensor data.

Now the problem: I want the Arduino to keep sending the data (current sensor data - so it will may change in value), suppose 20 times if there is no command from the PC side. What I mean is that if after sending 5 sensor data, the Arduino sees that there is another command from PC, it has to stop sending the sensor data; it will get the new command from the PC, read it and then start sending again.

My requirement is that the Arduino will send sensor data after getting a command from the PC side and will keep sending for 20 times, but in this meantime, if new command comes, it will stop sending the sensor data, will read the command and then start once again to send the sensor data 20 times. How can I write the code so that it will check in every loop whether there is any command from the PC or not?

I know the below code is not even close for what I am looking for:

void loop()
{
    while (Serial.available()) {
        delay(2);
        char c = Serial.read();
        readString += c;
    }
    if (readString.length() >0) {
        Serial.println(readString);
        for (int i=0; i<20; i++) {
            //Send the temperature, or send a simple message
            Serial.println("The command has been received");
        }
    }
}

The while loop and the delay() call don't help. Say that the PC sends the START command to enable temperature sampling and STOP to tell it to stop updating them. You'll need a bool variable to indicate state. Something like this:

bool sendTemperatures;
String readString;

void executeCommand(String cmd)
{
    if (cmd == "START") sendTemperatures = true;
    else if (cmd == "STOP") sendTemperatures = false;
    // etc...
    else Serial.println("Bad command");
}

void checkSerial()
{
    if (!Serial.available()) return;
    char c = Serial.read();
    if (c == '\n') {
        executeCommand(readString);
        readString = "";
    }
    else readString += c;
}

void sendSensorData() 
{
    // etc..
}


void loop() 
{
    checkSerial();
    if (sendTemperatures) sendSensorData();
}
String recievedData;  //readString

void setup() {
  Serial.begin(9600);
}

 void loop() {

  if (Serial.available() > 0) {
   recievedData = Serial.readString();//read full recieved data 
   Serial.println(recievedData);

    for (int i = 0; i < 20 && Serial.available() <= 0; i++) {
     //Send the temperature, or send a simple message
    }
   }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM