当前位置:   article > 正文

微信小程序+esp8266NodeMcu(cp2102)+onenet物联平台(二)_esp8266cp2102驱动

esp8266cp2102驱动

目录

一、搭建环境

1、esp8266NodeMcu(cp2102)驱动安装

 2、为esp8266NodeMcu搭建Arduino开发环境

3、安装PubSubClient库

二、编写代码


上一篇文章微信小程序+esp8266NodeMcu(cp2102)+onenet物联平台(一)介绍了onenet平台注册及设备连接,接下来介绍,如何使用Arduino IDE编写代码,控制esp8266,使用MQTT协议与onenet平台进行数据交互。关于MQTT协议,可参考太极创客的教程,非常详细。零基础入门学用物联网 – MQTT基础篇 – 目录 – 太极创客

一、搭建环境

1、esp8266NodeMcu(cp2102)驱动安装

下载地址:CP210x USB 至 UART 桥 VCP 驱动器 - 芯科科技

解压缩后安装驱动,根据自己电脑系统选择安装文件,我安装的是64位驱动。

安装后,使用usb数据线连接8266,然后打开设备管理器,查看端口(我的端口为com5)。

 

 2、为esp8266NodeMcu搭建Arduino开发环境

Arduino IDE下载地址:国外官网   或者 太极创客百度网盘 请输入提取码0ig4

打开“文件”-“首选项”

在Arduino IDE的“首选项”对话框中找到“附加开发板管理网址”,复制网址:

http://arduino.esp8266.com/stable/package_esp8266com_index.json

然后点击“好”

 打开Arduino IDE的“开发板管理器”

 

 安装时间比较长,也可以取消安装,然后去网盘下载: https://pan.baidu.com/s/1b0vs8SG5pCAji7MrsE3Aiw?pwd=ag4s 提取码: ag4s 

安装完毕后,在Arduino IDE的开发板菜单中选中“NodeMCU开发板”

 设置Arduino IDE的NodeMCU开发板端口

3、安装PubSubClient库

PubSubClient库是一个MQTT库,进行主题的发布与订阅,

打开Arduino,按下图安装,或前往1-6 ESP8266发布MQTT消息 – 太极创客下载。 

二、编写代码

15年前学过c语言,不过,早都忘光了,调试过程中废了很大劲,勉强可以用。

  1. #include <ESP8266WiFi.h>
  2. #include <PubSubClient.h>
  3. #include <Ticker.h>
  4. // 设置wifi接入信息(请根据您的WiFi信息进行修改)
  5. const char* ssid = "wifi名称";//wifi名称
  6. const char* password = "wifi密码";//wifi密码
  7. //MQTT连接设置
  8. const char* mqttServer = "mqtts.heclouds.com";//onenet 的 域名
  9. //const char *mqtt_server = "183.230.40.96"; //onenet 的 IP地址
  10. const int mqtt_port = 1883;//onenet 的 端口
  11. #define mqtt_devName "d1"//设备名
  12. #define mqtt_pubid "558037"//产品ID
  13. //鉴权信息,即onenet生成的设备连接token
  14. #define mqtt_authorization "version=2018-10-31&res=products%2F558....."
  15. WiFiClient wifiClient;//创建一个WIFI连接客户端
  16. PubSubClient mqttClient(wifiClient);// 创建一个PubSub客户端, 传入创建的WIFI客户端
  17. Ticker tim1; //定时器,用来循环上传数据
  18. void setup() {
  19. // put your setup code here, to run once:
  20. pinMode(LED_BUILTIN, OUTPUT); // 设置板上LED引脚为输出模式
  21. digitalWrite(LED_BUILTIN, HIGH); // 启动后关闭板上LED
  22. Serial.begin(9600);
  23. //设置ESP8266工作模式为无线终端模式
  24. WiFi.mode(WIFI_STA);
  25. // 连接WiFi
  26. connectWifi();
  27. // 设置MQTT服务器和端口号
  28. mqttClient.setServer(mqttServer, mqtt_port);
  29. // 设置MQTT订阅回调函数
  30. mqttClient.setCallback(receiveCallback);
  31. // 连接MQTT服务器
  32. connectMQTTServer();
  33. //定时 每隔10秒发送一次温度数据点
  34. tim1.attach(10, sendDpData);
  35. }
  36. void loop() {
  37. // put your main code here, to run repeatedly:
  38. if (mqttClient.connected()) { // 如果开发板成功连接服务器
  39. // 保持心跳
  40. mqttClient.loop();
  41. } else { // 如果开发板未能成功连接服务器
  42. connectMQTTServer(); // 则尝试连接服务器
  43. }
  44. }

连接wifi

  1. // ESP8266连接wifi
  2. void connectWifi() {
  3. WiFi.begin(ssid, password);
  4. //等待WiFi连接,成功连接后输出成功信息
  5. while (WiFi.status() != WL_CONNECTED) {
  6. delay(1000);
  7. Serial.print(".");
  8. }
  9. Serial.println("");
  10. Serial.println("WiFi Connected!");
  11. Serial.println("");
  12. }

连接MQTT服务器

  1. //连接MQTT
  2. void connectMQTTServer() {
  3. if (mqttClient.connect(mqtt_devName, mqtt_pubid, mqtt_authorization)) {
  4. Serial.println("MQTT Server Connected.");
  5. Serial.println("Server Address: ");
  6. Serial.println(mqttServer);
  7. //订阅主题
  8. subscribeTopic();
  9. } else {
  10. Serial.print("MQTT Server Connect Failed. Client State:");
  11. Serial.println(mqttClient.state());
  12. delay(3000);
  13. }
  14. }

发布数据,向数据流temperatrue发送数据

  1. //发送数据 向主题发送数据流,即设备数据点上传
  2. void sendDpData() {
  3. // payload,需要发送的数据格式
  4. // {
  5. // "id": 123,
  6. // "dp": {
  7. // "temperatrue": [{
  8. // "v": 30,
  9. // }]
  10. // }
  11. // }
  12. //将payload转为字符串,传递的参数格式化为浮点数,保留2位小数
  13. char dataTemplate[] = "{\"id\":123,\"dp\":{\"temperatrue\":[{\"v\":%.2f,}]}}";
  14. //生成1-100的随机数,作为温度值
  15. srand((unsigned int)time(NULL));
  16. int temp = rand() % 100 + 1;
  17. // Serial.println("随机数");
  18. // Serial.println(temp);
  19. //发送信息缓冲区
  20. char msgJson[56];
  21. //将temp放入dataTemplate,复制给msgJson
  22. snprintf(msgJson, 56, dataTemplate, (float)temp);
  23. //设置发布主题
  24. String topicString = "$sys/558037/d1/dp/post/json";
  25. char publishTopic[topicString.length() + 1];
  26. strcpy(publishTopic, topicString.c_str());//将字符串转为字符数组
  27. // 实现ESP8266向主题发布信息
  28. if (mqttClient.publish(publishTopic, msgJson)) {
  29. Serial.println("发布数据点主题:"); Serial.println(publishTopic);
  30. Serial.println("发布信息:"); Serial.println(msgJson);
  31. } else {
  32. Serial.println("Message Publish Failed.");
  33. }
  34. }

订阅用户发送命令主题

  1. //订阅命令主题
  2. void subscribeTopic() {
  3. // 建立主题
  4. String topicString = "$sys/558037/d1/cmd/request/+";
  5. char subTopic[topicString.length() + 1];
  6. strcpy(subTopic, topicString.c_str());
  7. // 通过串口监视器输出是否成功订阅主题以及订阅的主题名称
  8. if (mqttClient.subscribe(subTopic)) {
  9. Serial.println("订阅的主题为:");
  10. Serial.println(subTopic);
  11. } else {
  12. Serial.print("Subscribe Fail...");
  13. }
  14. }

MQTT订阅回调函数,根据用户发送的命令,执行开关灯,及调节灯的亮度

  1. /*
  2. 订阅回调函数,参数固定
  3. 当用户端发送cmd命令后,esp8266进行的回调处理
  4. */
  5. void receiveCallback(char* topic, byte* payload, unsigned int length) {
  6. Serial.print("收到的cmd主题 [");
  7. Serial.print(topic);
  8. Serial.println("] ");
  9. //获取主题topic//$sys/558037/d1/cmd/request/b790bdca-5528-4469-8639-7439046bf39a 中的 cmdid 90977789-5c61-4bb9-9387-ba9a676ff9f5
  10. char cmdStr[strlen(topic) - 27];//声明cmdStr,保存cmdid
  11. strcpy(cmdStr, topic + 27);//从topic字符串第27个位置开始向后取值
  12. //输出payload内容
  13. Serial.print("收到的数据:");
  14. char payload_char[length + 1];
  15. memset(payload_char, 0, sizeof(payload_char));
  16. for (int i = 0; i < length; i++) {
  17. Serial.print((char)payload[i]);
  18. payload_char[i] = (char)payload[i];
  19. }
  20. Serial.println();
  21. Serial.println("--------------");
  22. /*
  23. 判断收到的命令类型
  24. led 开关灯,led:0关灯,led:1开灯
  25. bright 调节灯亮度,bright:数字,数字为PWD调节灯的亮度,范围0-1023
  26. */
  27. char *dataPtr = NULL;//传递的数据
  28. char numBuf[10];
  29. int num = 0;
  30. dataPtr = strchr((char *)payload_char, ':');//查找冒号
  31. if (dataPtr != NULL) //如果找到了
  32. {
  33. dataPtr++;//后移一位,指向数据
  34. while (*dataPtr >= '0' && *dataPtr <= '9') //循环取出数据
  35. {
  36. numBuf[num++] = *dataPtr++;
  37. }
  38. //numBuf[num] = 0;
  39. num = atoi((const char *)numBuf); //转为数值
  40. if (strstr((char *)payload_char, "led")) //搜索"led"
  41. {
  42. Serial.println("控制类型led");
  43. Serial.print("数值:");
  44. Serial.println(num);
  45. if (num == 1) //控制数据如果为1,代表开
  46. {
  47. digitalWrite(BUILTIN_LED, LOW); // 则点亮LED。
  48. Serial.println("LED ON");
  49. }
  50. else if (num == 0) //控制数据如果为0,代表关
  51. {
  52. digitalWrite(BUILTIN_LED, HIGH); // 否则熄灭LED。
  53. Serial.println("LED OFF");
  54. }
  55. }
  56. if (strstr((char *)payload_char, "bright")) //搜索"bright"
  57. {
  58. Serial.println("控制类型bright");
  59. Serial.print("数值:");
  60. Serial.println(num);
  61. analogWrite(4, num); //GPIO4接Led灯,pwm输出
  62. }
  63. }
  64. //向服务器返回信息,即已收到命令
  65. sendCmdResponse(cmdStr);
  66. }

向服务器发送确认信息,通知服务器已收到cmd命令信息。

  1. //接受到cmd命令后,返回的数据信息
  2. void sendCmdResponse(char* cmdStr) {
  3. //返回OK
  4. char responseData[] = "ok";
  5. //设置主题的模板字符串
  6. char topicString[] = "$sys/558037/d1/cmd/response/%s";
  7. //计算发布主题publicTopic需要的字符空间,topicString长度 + cmdStr长度
  8. int slength = strlen(topicString) + strlen(cmdStr);
  9. //定义发布主题
  10. char publicTopic[slength];
  11. //将topicString和cmdStr进行拼接
  12. snprintf(publicTopic, slength, topicString, cmdStr);
  13. // 实现ESP8266向主题发布信息
  14. if (mqttClient.publish(publicTopic, responseData)) {
  15. Serial.println("发布命令回复主题:"); Serial.println(publicTopic);
  16. Serial.println("主题信息:"); Serial.println(responseData);
  17. } else {
  18. Serial.println("Message Publish Failed.");
  19. }
  20. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/644220
推荐阅读
相关标签
  

闽ICP备14008679号