How to easily parse the AT command response from a GSM module?

雨燕双飞 提交于 2019-12-11 23:29:38

问题


I'm trying to parse the following output taken from a GSM module in Arduino, to get the Voltage (3.900V) part only. However, I can't get it to work.

"    
+CBC: 0,66,3.900V

OK
"

I have tried the following code, but it fails and even crashes.

    float getVoltage() {
        if (atCmd("AT+CBC\r") == 1) {
            char *p = strchr(buffer, ',');
            if (p) {
                p += 3; // get voltage 
                int vo = atof(p) ;
                p = strchr(p, '.');
                if (p) vo += *(p + 1) - '0';    // ??
                return vo;
            }
        }
        return 0;
    }

How can this be done in a better or more transparent way?


回答1:


You can do it using the C function strtok to tokenize the buffer

void setup() {
  Serial.begin(115200);

  char buffer[20]  = "+CBC: 1,66,3.900V";

  const char* delims = " ,V";
  char* tok = strtok(buffer, delims); // +CVB:

  tok = strtok(NULL, delims);
  int first = atoi(tok);

  tok = strtok(NULL, delims);
  int second = atoi(tok);

  tok = strtok(NULL, delims);
  float voltage = atof(tok);

  Serial.println(first);
  Serial.println(second);
  Serial.println(voltage);

}

void loop() {
}



回答2:


This fixed it:

    float getVoltage() {
        if (atCmd("AT+CBC\r") == 1) {
            char *p = strchr(buffer, 'V');
            if (p) {
                p -= 5;  // get voltage
                double vo = atof(p) ;
                //printf("%1.3f\n", vo);
                return vo;
            }
        }
        return 0;
    }


来源:https://stackoverflow.com/questions/56939302/how-to-easily-parse-the-at-command-response-from-a-gsm-module

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!