硬件:Arduino UNO + ESP-01 (串口)
思路:Arduino通过软串口(2,3)发送AT命令,当监听到ESP模块返回“OK”字符串时,表示AT命令执行成功。
之所以用ESP模块,主要是其串口发送和接受串口的字符串都需要较长时间的延时及超时检查。本实验测试包含了多层调用关系的验证。调用者通过传递参数doCmdStep不同的值,和根据返回值及doCmdStep的赋值,控制程序流程、逻辑。基础函数doCMD()就是孙悟空,参数doCmdStep就是猴毛,是孙悟空的复制品,各自做自己的事情,互不冲突,还可以协助打牛魔王 :)
/*
* ESP-01模块支持库
*
*/
#include <SoftwareSerial.h>
// RX, TX交叉接线
SoftwareSerial EspSerial(2, 3);
/*
* doCMD success ret 0;failed ret 1;timeout ret -1
*
*/
#define SUCCESS_CMD 0
#define WAITING_CMD 1
#define TIMEOUT_CMD -1
String str;
int doCmdInvokeNo1=0;
int doCmdInvokeNo2=0;
int lastDelayTime4doCMD;
int delayCount4doCMD; //timeout
int doCMD(String cmd,String flag,long timeout,int* doCmdStep){
if(*doCmdStep==0){
Serial.print(timeout);
Serial.println("doCmdStep==0");
str="";
delayCount4doCMD=timeout/100;
flag.toLowerCase();//小写
EspSerial.println(cmd);//发送命令
//delay 10ms
if((millis()-lastDelayTime4doCMD)>10){
//Serial.println("delay 10ms");
lastDelayTime4doCMD=millis();
*doCmdStep=1;
}
return WAITING_CMD;//keep waiting...
}
if(*doCmdStep==1){
Serial.print(timeout);
Serial.println("doCmdStep==1");
//delay 2ms
if((millis()-lastDelayTime4doCMD)>2){
//Serial.println("delay 2ms");
if(EspSerial.available()){
str+=(char)EspSerial.read();
}else{
*doCmdStep=2;
}
lastDelayTime4doCMD=millis();
}
return WAITING_CMD;//keep waiting...
}
if(*doCmdStep==2){
Serial.print(timeout);
Serial.println("doCmdStep==2");
if(str!=""){
str.toLowerCase();
String flag1="",flag2="";
int indexPosition=flag.indexOf('|');
//有"|",多个关键字符串
if(indexPosition>-1){
flag1=flag.substring(0,indexPosition);
flag2=flag.substring(indexPosition+1,flag.length());
}
if(flag1!=""&&flag2!=""){
if(str.indexOf(flag1)>-1||str.indexOf(flag2)){
Serial.print(timeout);
Serial.println("find the key!");
*doCmdStep=0;
return SUCCESS_CMD;
}
}
//没有"|",单个关键字符串
if(str.indexOf(flag)>-1){
Serial.print(timeout);
Serial.println("find the key!!");
*doCmdStep=0;
return SUCCESS_CMD;
}
}
//delay 100ms
if((millis()-lastDelayTime4doCMD)>100){
//Serial.println("delay 100ms");
lastDelayTime4doCMD=millis();
*doCmdStep=1;
delayCount4doCMD>0 ? delayCount4doCMD--:*doCmdStep=3;
}
return WAITING_CMD;//keep waiting...
}
if(*doCmdStep==3){
Serial.print(timeout);
Serial.println("doCmdStep==3 timeout!!!!!!!!!");
*doCmdStep=0;
return TIMEOUT_CMD;
}
}
void setup() {
Serial.begin(9600);
while (!Serial) {} //清除串口缓存
EspSerial.begin(115200);
while (!EspSerial) {}
// 开始监听
EspSerial.listen();
}
void loop() {
if(doCMD(F("AT"),"ok",3000,&doCmdInvokeNo1)==SUCCESS_CMD){
Serial.println("First invoked Done!!!");
}
if(doCMD(F("AT"),"ok",1000,&doCmdInvokeNo2)==SUCCESS_CMD){
Serial.println("Second invoked Done!!!");
}
}
---------------------
作者:holmes_sun5
来源:CSDN
原文:https://blog.csdn.net/holmes_sun5/article/details/105634662
版权声明:本文为作者原创文章,转载请附上博文链接!
内容解析By:CSDN,CNBLOG博客文章一键转载插件