本帖最后由 Gameparkwing 于 2017-3-12 15:16 编辑
程序可以分为两部分,读取一行和解析一行。
串口读入的字符保存到 str_from_uart[] 数组中,用变量 p_from_uart 做数量指示。
串口每接收到一个字节,调用一次 RespondReadLine() 函数。
变量 respond_string 和 respond_value 为每一次读取到的返回的数据值。
变量 respond_done 默认为 -1 ,表示无应答内容, respond_done == 0/1/2... 时,读取到一行返回的数据,程序中做相应的处理。
- unsigned int p_from_uart;
- unsigned char str_from_uart[255];
- unsigned char respond_string[16];
- unsigned int respond_value;
- signed int respond_done;
- /* 解析一行应答数据。 */
- void RespondParser()
- {
- if (strstr(str_from_uart, "+CIEV") != NULL) { // 存在有效应答值。
- sscanf(str_from_uart, "%*[^"]"%[^"]"%*[^0-9]%d", respond_string, &respond_value); // 提取应答值。
- respond_done = 2; // 提取到应答数据。
- } else {
- // 判断应答结果, OK 或 ERROR。
- if (strstr(str_from_uart, "OK") != NULL) {
- respond_done = 1; // 返回值为 OK 的情况。
- } else if (strstr(str_from_uart, "ERROR") != NULL) {
- respond_done = 0; // 返回值为 ERROR 的情况。
- } else {
- respond_done = -1; // 无内容,不处理。
- }
- }
- }
- /* 读取一行应答数据。 */
- void RespondReadLine()
- {
- if (str_from_uart[p_from_uart] == '\n') { // 遇到换行符,读取一行。
- RespondParser(); // 解析一行应答数据。
- p_from_uart = 0; // 串口接收游标清零。
- } else {
- p_from_uart ++; // 串口接收游标递增。
- }
- }
|