#include <Arduino.h>
#include <WiFi.h>
#include <HardwareSerial.h> //导入ESP32串口操作库,使用这个库我们可以把串口映射到其他的引脚上使用
#include<ESP32Servo.h>
HardwareSerial MySerial(2);
hw_timer_t*timer = NULL;
Servo myservo1; //舵机引脚
Servo myservo2;
const int Trig =21; //超声波引脚设置蓝线VCC绿线Trig黄线Echo橘线GND
const int Echo =5;
int data2;
float count,distance;
////我们测试需要用到的串口,ESP32一共有3个串口,串口0应该是用于程序烧写和打印输出调试用的,所以我们只用1和2
int state_flag;
char temp;
#define server_ip "bemfa.com" //巴法云服务器地址默认即可
#define server_port "8344" //服务器端口,tcp创客云端口8344
//********************需要修改的部分*******************//
String upstr;
String data1;
#define wifi_name "small" //WIFI名称,区分大小写,不要写错
#define wifi_password "1234567890" //WIFI密码
String UID1 = "23d0980f53474e66aabef9abc8d7d579"; //用户私钥,可在控制台获取,修改为自己的UID
String TOPIC1 = "Light001"; //主题名字,可在控制台新建
String UID2 = "23d0980f53474e66aabef9abc8d7d579"; //测试私钥
String TOPIC2 = "mytemp01"; //主题名字,可在控制台新建esp发给把巴法云的主题名字
int LED_Pin = 2; //单片机LED引脚值,D2是NodeMcu引脚命名方式,其他esp8266型号将D2改为自己的引脚
//**************************************************//
//最大字节数
#define MAX_PACKETSIZE 512
//设置心跳值60s
#define KEEPALIVEATIME 60*1000
//tcp客户端相关初始化,默认即可
WiFiClient TCPclient;
String TcpClient_Buff = "";//初始化字符串,用于接收服务器发来的数据
unsigned int TcpClient_BuffIndex = 0;
unsigned long TcpClient_preTick = 0;
unsigned long preHeartTick = 0;//心跳
unsigned long preTCPStartTick = 0;//连接
bool preTCPConnected = false;
//相关函数初始化
//连接WIFI
void doWiFiTick();
void startSTA();
//TCP初始化连接
void doTCPClientTick();
void startTCPClient();
void sendtoTCPServer(String p);
//led控制函数,具体函数内容见下方
//void turnOnLed();
//void turnOffLed();
void read_usart();
void IRAM_ATTR onTimer(){
count++;
}
void read_usart(){
// i = MySerial.a/able(); //返回目前串口接收区内的已经接受的数据量
temp = MySerial.read(); //读取一个数据并且将它从缓存区删除
//Serial.println(temp);
// if((distance>=50)&&(temp=='B')) //没车
// {
// MySerial.println(temp);
// myservo1.write(90); //右舵机抬起
// myservo2.write(90); //左舵机抬起
// data7 = "^A^5^N^"; //车场车位无
// data2 = 7 ; //A
// digitalWrite(pin,0); //蜂鸣器不叫
// delay(20);
// }
// else if((temp=='A')&&(distance<=50))//有能源车
// {
// MySerial.println(temp);
// myservo1.write(175); //右舵机倒下
// myservo2.write(5); //左舵机倒下
// data7 = "^A^5^Y^"; //车场车位有
// data2 = 1 ; //A
// digitalWrite(pin,1); //蜂鸣器叫
// delay(20);
// digitalWrite(pin,0);
// delay(20);
// }
}
/*
*发送数据到TCP服务器
*/
void sendtoTCPServer(String p){
if (!TCPclient.connected())
{
Serial.println("Client is not readly");
return;
}
TCPclient.print(p);
preHeartTick = millis();//心跳计时开始,需要每隔60秒发送一次数据
}
/*
*初始化和服务器建立连接
*/
void startTCPClient(){
if(TCPclient.connect(server_ip, atoi(server_port))){
Serial.print("\nConnected to server:");
Serial.printf("%s:%d\r\n",server_ip,atoi(server_port));
String tcpTemp=""; //初始化字符串
tcpTemp = "cmd=1&uid="+UID1+"&topic="+TOPIC1+"\r\n"; //构建订阅指令
sendtoTCPServer(tcpTemp); //发送订阅指令
tcpTemp="";//清空
/*
//如果需要订阅多个主题,可发送 cmd=1&uid=xxxxxxxxxxxxxxxxxxxxxxx&topic=xxx1,xxx2,xxx3,xxx4\r\n
教程:https://bbs.bemfa.com/64
*/
preTCPConnected = true;
TCPclient.setNoDelay(true);
}
else{
Serial.print("Failed connected to server:");
Serial.println(server_ip);
TCPclient.stop();
preTCPConnected = false;
}
preTCPStartTick = millis();
}
/*
*检查数据,发送心跳
*/
void doTCPClientTick(){
//检查是否断开,断开后重连
if(WiFi.status() != WL_CONNECTED) return;
if (!TCPclient.connected()) {//断开重连
if(preTCPConnected == true){
preTCPConnected = false;
preTCPStartTick = millis();
Serial.println();
Serial.println("TCP Client disconnected.");
TCPclient.stop();
}
else if(millis() - preTCPStartTick > 1*1000)//重新连接
startTCPClient();
}
else
{
if (TCPclient.available()) {//收数据
char c =TCPclient.read();
TcpClient_Buff +=c;
TcpClient_BuffIndex++;
TcpClient_preTick = millis();
if(TcpClient_BuffIndex>=MAX_PACKETSIZE - 1){
TcpClient_BuffIndex = MAX_PACKETSIZE-2;
TcpClient_preTick = TcpClient_preTick - 200;
}
}
if(millis() - preHeartTick >= KEEPALIVEATIME){//保持心跳
preHeartTick = millis();
Serial.println("--Keep alive:");
sendtoTCPServer("ping\r\n"); //发送心跳,指令需\r\n结尾,详见接入文档介绍
}
}
if((TcpClient_Buff.length() >= 1) && (millis() - TcpClient_preTick>=200))
{
TCPclient.flush();
Serial.print("Rev string: ");
TcpClient_Buff.trim(); //去掉首位空格
Serial.println(TcpClient_Buff); //打印接收到的消息
String getTopic = "";
String getMsg = "";
if(TcpClient_Buff.length() > 15){//注意TcpClient_Buff只是个字符串,在上面开头做了初始化 String TcpClient_Buff = "";
//此时会收到推送的指令,指令大概为 cmd=2&uid=xxx&topic=light002&msg=off
int topicIndex = TcpClient_Buff.indexOf("&topic=")+7; //c语言字符串查找,查找&topic=位置,并移动7位,不懂的可百度c语言字符串查找
int msgIndex = TcpClient_Buff.indexOf("&msg=");//c语言字符串查找,查找&msg=位置
getTopic = TcpClient_Buff.substring(topicIndex,msgIndex);//c语言字符串截取,截取到topic,不懂的可百度c语言字符串截取
getMsg = TcpClient_Buff.substring(msgIndex+5);//c语言字符串截取,截取到消息
Serial.print("topic:------");
Serial.println(getTopic); //打印截取到的主题值
Serial.print("msg:--------");
Serial.println(getMsg); //打印截取到的消息值
}
if((getMsg == "A6Y")||((temp=='A')&&(distance<=50))){ //如果是消息==打开
digitalWrite(LED_Pin,HIGH);
MySerial.println(temp);
myservo1.write(175); //右舵机倒下
myservo2.write(5); //左舵机倒下
data1="^A^5^Y^";
upstr = "cmd=2&uid="+UID2+"&topic="+TOPIC2+"&msg=#"+data1+"#\r\n";
sendtoTCPServer(upstr);
}else if((getMsg == "A6N")||((distance>=50)&&(temp=='B'))){ //如果是消息==关闭
digitalWrite(LED_Pin,LOW);
MySerial.println(temp);
myservo1.write(90); //右舵机抬起
myservo2.write(90); //左舵机抬起
data1="^A^5^N^";
upstr = "cmd=2&uid="+UID2+"&topic="+TOPIC2+"&msg=#"+data1+"#\r\n";
sendtoTCPServer(upstr);
// di/alWrite(pin,0); //蜂鸣器不叫
delay(20);
}
TcpClient_Buff="";
TcpClient_BuffIndex = 0;
}
}
/*
*初始化wifi连接
*/
void startSTA(){
WiFi.disconnect();
WiFi.mode(WIFI_STA);
WiFi.begin(wifi_name, wifi_password);
}
/**************************************************************************
WIFI
***************************************************************************/
/*
WiFiTick
检查是否需要初始化WiFi
检查WiFi是否连接上,若连接成功启动TCP Client
控制指示灯
*/
void doWiFiTick(){
static bool startSTAFlag = false;
static bool taskStarted = false;
static uint32_t lastWiFiCheckTick = 0;
if (!startSTAFlag) {
startSTAFlag = true;
startSTA();
}
//未连接1s重连
if ( WiFi.status() != WL_CONNECTED ) {
if (millis() - lastWiFiCheckTick > 1000) {
lastWiFiCheckTick = millis();
}
}
//连接成功建立
else {
if (taskStarted == false) {
taskStarted = true;
Serial.print("\r\nGet IP Address: ");
Serial.println(WiFi.localIP());
startTCPClient();
}
}
}
// 初始化,相当于main 函数
void setup() {
MySerial.begin(115200, SERIAL_8N1, 16, 17);
Serial.begin(115200);
pinMode(LED_Pin,OUTPUT);
digitalWrite(LED_Pin,LOW);
pinMode(Trig, OUTPUT);
pinMode(Echo, INPUT);
myservo1.attach(18);
myservo2.attach(19);
delay(10);
myservo1.write(90); //右舵机
myservo2.write(90); //左舵机
delay(20);
// timer = timerBegin(1, 80, false); //定时器0,分频系数80,向下计数
// timerAttachInterrupt(timer,&onTimer,true);//绑定定时器的中断处理函数
// timerAlarmWrite(timer,1000000,true);//us触发时的中断计数值
//timerAlarmEnable(timer);
Serial.println("Beginning...");
}
//循环
void loop() {
digitalWrite(Trig, 0);
delayMicroseconds(2);
digitalWrite(Trig, 1); //触发信号
delayMicroseconds(10);
digitalWrite(Trig, 0);
while(!Echo){}
// while(Echo){
// timerAlarmEnable(timer); //开启定时器
// }
// count = pulseIn(Echo, HIGH);
if((count>=1)&&(count<=60000))
{
distance = count*0.034/2; //距离转换cm
//Serial.println(distance);
}
delay(10);
doWiFiTick();
doTCPClientTick();
}
离线
把loop里的count = pulseIn(Echo, HIGH);这一行注释掉就可以接收到巴法云发过来的,wifi接受数据是在巴法云的历程上改的,是和pulseIn函数有什么关系吗?
离线
const int Trig =15;
const int Echo =2;
float count,distance;
long start_ticks=0;
void interrupt_handle() //外部中断函数
{
if (digitalRead(Echo) == HIGH)
{
start_ticks = micros();
}
else
{
count = micros()-start_ticks;
}
}
void setup()
{
Serial.begin(115200);
pinMode(Trig,OUTPUT);
pinMode(Echo,INPUT);
attachInterrupt(Echo,interrupt_handle,RISING); //外部中断,Echo变为高电平触发
delay(10);
}
void loop(){
digitalWrite(Trig, 1); //触发信号
delay(20);
digitalWrite(Trig, 0);
if((count>=1)&&(count<=60000))
{
distance = count*0.034/2; //距离转换cm
}
Serial.println(distance);
delay(1000);
}
这样使用外部中断可以实现超声波测距吗
离线
能够说一下什么是异步式吗?
离线
能够说一下什么是异步式吗?
看了下,pulseIn这个函数可检测的脉冲间隔时间范围是10微秒到3分钟,如果没有引脚没有脉冲的话,它的阻塞时间太长了,那么加上超时让其不要检测那么长时间就可以了:
原型是 pulseIn(pin, value, timeout),再加上一个timeout参数即可,不用搞异步。
最近编辑记录 海石生风 (2022-08-20 08:46:46)
离线