当前位置:网站首页>Environment regulation system based on Internet of things (esp32-c3+onenet+ wechat applet)
Environment regulation system based on Internet of things (esp32-c3+onenet+ wechat applet)
2022-07-26 15:03:00 【Pafasil】
This is a course design I recently did , Real time monitoring of indoor temperature, humidity and light intensity , Display the monitoring data in real time on the wechat applet and issue commands to control the fan switch and the forward and reverse rotation of the steering gear ( So as to realize the switch of simulation curtain ). There are two modes of control , One is manual control , Remotely control the device switch through wechat applet , One is equipment automatic control , Set the threshold of temperature and humidity to control the switch of the fan , By setting the threshold of light intensity, we can control the forward and reverse rotation of the steering gear ( switch ).
List of articles
- 1、 Overall block diagram of hardware system
- 2、 Hardware design flow chart
- 3、 Software design flow chart of lower computer
- 4、 Device selection
- 5、Onenet Cloud platform
- 6、 Lower computer code writing
- 7、 WeChat developer tools
- 1、 Wechat interface
- 2、 obtain Onenet Of API Interface
- 3、 Inquire about OneNet Platform multi protocol access document , Here's a direct look at MQTT Of API Use
- 4、 I use ApiPost To test whether data can be obtained
- 5、 Wechat applet access OneNet data
- 6、 Wechat applet sends commands
- 7、 Data Refresh
- 8、 Select the corresponding instruction in the drop-down list to send data
- 9、 Data visualization
- 10、 Check whether the equipment is online
- 11、 Effect display
- Conclusion
1、 Overall block diagram of hardware system
System to MCU Design sensing control nodes for core devices . Air temperature and humidity sensor 、 Light sensor 、 The gas sensor will collect the analog data through AD Convert to digital signal transmission and input directly MCU Of I/O mouth ; All perceptual data passes WiFi The module is sent to the cloud . At the same time, the control equipment is driven by setting parameters .

2、 Hardware design flow chart

3、 Software design flow chart of lower computer

4、 Device selection
1、 Air temperature and humidity sensor
choose DHT11 Compound digital air temperature and humidity sensor , The temperature and humidity sensing module is integrated inside , When the sensor module works, it will call the calibrated coefficient in the production process for calibration . It uses the one on the right DHT11

2、 Light sensor :
Photodiodes LM393 Optical signals can be ( Light intensity ) Convert to electrical signal ; Then the comparison circuit compares the voltage passing through the photosensitive resistor with the voltage passing through the potentiometer , And to DO The port outputs high voltage or low voltage for users ; and AO The port is a circuit that directly passes through the photosensitive resistance to reduce the voltage , So the output is in GND and VCC Any voltage value between ; Of course VCC and GND It is the basic condition for the normal operation of module components and chips , Indispensable ! The light sensor is shown in the figure 10 Shown .

3、 Steering gear selection
choose SG90 The steering gear receives PWM The signal , Make it enter the internal circuit to generate a bias voltage , Trigger the motor to drive the potentiometer to move through the reduction gear , When the voltage difference is zero , The motor stops , So as to achieve the effect of servo . That is to give the steering gear a specific PWM The signal , The steering gear rotates to a specific angle . I bought it 360 Rotatable steering gear 
4、 Fan
I bought this kind of two thread 
5、Onenet Cloud platform
1、 Create products
Console —> Multiple access –> Add product
About product name 、 industry 、 Those categories can be selected by yourself , Here is chosen mqtt Old agreement


Click on the one we just created dht11, Then click Product Overview , Remember our products id, You can use it in the back
2、 Create device
Click on the device list -> Click Add Device on the right , Equipment name and authentication information need to be filled in , Authentication information device connection onenet It works , And equipment id Number
3、 Create data flow
First click on data flow , Then click data flow template management , Finally, add a data flow template
The data stream name set here will be followed by , Here I created the temperature 、 humidity 、 The lamp 、 Data flow of illumination and so on .

6、 Lower computer code writing
1、 How to connect the device to the Internet
Here you can call wifi library
#include <WiFi.h>
const char* ssid = "3671"; //wifi name
const char* password = "05210835";//wifi password
2、 Temperature and humidity
My sensor is DHT11, You can also call the library here ( You can go to the management library to download DHT sersor library This library )
#include "DHT.h"
Definition DHT11, I connect the data pin to IO7 mouth
#define DHTPIN 7 // io7
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
3、 photosensitive
Here I choose Io0 The port is equipped with an analog-to-digital converter io mouth , Convenient data conversion
#define LDR_PIN 0 // Photosensitive interface 0
const float GAMMA = 0.7;
const float RL10 = 50;
float guang(){
int analogValue = analogRead(LDR_PIN);
float voltage = analogValue / 1024. * 5;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
Serial.print(lux);
return lux;
}
4、 The steering gear
// setting PWM properties
#define do 10 // Steering gear interface
const int freq = 5000;// Set the frequency
const int ledChannel = 0;// Channel number , Value 0 ~ 15
const int resolution = 8;// Count digits , Value 0 ~ 20
unsigned long time1=544;
bool direction1=true;
setup function
// Steering gear module
pinMode(do, OUTPUT);
digitalWrite(do,HIGH);
delayMicroseconds(544);
digitalWrite(do,LOW);
loop function
driection1 It is used to judge whether the current state of the steering gear is on or off
// The steering gear
if(direction1 && vm <400)
{
time1+=10;
digitalWrite(do,HIGH);
delayMicroseconds(time1);
digitalWrite(do,LOW);
delay(5);
if (time1>=2600)
direction1=false;
dji=1;
}
if(direction1==false && vm >400)
{
time1-=10;
digitalWrite(do,HIGH);
delayMicroseconds(time1);
digitalWrite(do,LOW);
delay(5);
if (time1<=544)
direction1=true;
dji=0;
}
5、 Fan
Here, the fan switch is controlled by the high and low level of the relay
const int fengshan=8; // Relay in Interface
setup function
pinMode(fengshan,OUTPUT);
loop function
If the temperature exceeds 30 Just start the fan
if(t>30){
digitalWrite(fengshan, HIGH); //
shan =1;
}
6、OLED
My previous blog has a detailed introduction , If you don't have environment configuration or don't understand, you can click the link below to jump to the past to learn
https://blog.csdn.net/weixin_44107116/article/details/122491820
7 、 Access address
mqtt The interface pin number of the protocol is 6002
const char *mqtt_server = "183.230.40.96"; //onenet Of IP Address
const int port = 6002; // Port number

8、 How to send data to onenet
Here we need to check onenet Related documents of
https://open.iot.10086.cn/doc/v5/develop/detail/463

#define mqtt_devid "884337606" // equipment ID
#define mqtt_pubid "487632" // product ID
// Authentication information
#define mqtt_password "20222222" // Authentication information
char msg_buf[200]; // Send message buffer
char msgJson[80]; // To send json Formatted data
unsigned short json_len = 0; //json length
// Information templates
char dataTemplate[] = "{\"temp\":%.2f,\"humi\":%.2f,\"led\":%d,\"feng\":%d,\"guang\":%.2f,\"doji\":%d,\"Air\":%d}"; // temp humi Wait, we need to onenet Corresponding
void sendTempAndHumi()
{
if (client.connected())
{
//dht.readHumidity()
snprintf(msgJson,80,dataTemplate,dht.readTemperature(),dht.readHumidity(),god,shan,guang(),dji,Air());
json_len = strlen(msgJson); //msgJson The length of
msg_buf[0] = char(0x03); // The data to be sent must be in accordance with ONENET Send your request , According to the requirements , The number one data is 3
msg_buf[1] = char(json_len >> 8); // The second bit of data is the upper eight bits of the data length to be sent
msg_buf[2] = char(json_len & 0xff); // The third bit of data is the lower eight bits of the length of the data to be sent
memcpy(msg_buf + 3, msgJson, strlen(msgJson)); // from msg_buf Starting from the fourth place , Put in the data to be transmitted msgJson
msg_buf[3 + strlen(msgJson)] = 0; // Add one 0 As the last , So what to send msg_buf Be on it
Serial.print("public the data:");
Serial.print(msgJson);
client.publish("$dp", (uint8_t *)msg_buf, 3+strlen(msgJson));
// Send data to the subject
delay(500);
}
}
stay setup() The function defines each 5 Send data to... Once per second onenet
tim1.attach(5, sendTempAndHumi); // Every time 5 Call the send data function once every second sendTempAndHumi
9、 Issue order
stay setup() Function subscription command issue topic
client.setCallback(callback); // Subscribe to the command and issue the topic
// Received callback from subject , Note that this callback implements three formal parameters 1:topic The theme , 2: payload: The message 3: length: length
void callback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
if ((char)payload[0] == '0') {
digitalWrite(led, LOW); //
god=0;
}
else if ((char)payload[0] == '1') {
digitalWrite(led, HIGH); //
god=1;
}
else if ((char)payload[0] == '2') {
digitalWrite(fengshan, HIGH); //
shan=1;
}
else if ((char)payload[0] == '3') {
digitalWrite(fengshan, LOW); //
shan=0;
}
// Turn off
else if ((char)payload[0] == '5') {
for(time1;time1>=544;time1-=10){
digitalWrite(do,HIGH);
delayMicroseconds(time1);
digitalWrite(do,LOW);
delay(5);
if(time1<=544){
direction1=true;
dji=0;
delay(5000);
}
}
}
// open
else if ((char)payload[0] == '4') {
for(time1;time1<=2600;time1+=10){
digitalWrite(do,HIGH);
delayMicroseconds(time1);
digitalWrite(do,LOW);
delay(5);
if (time1>=2600){
direction1=false;
dji=1;
delay(5000);
}
}
}
else{
}
}
10、led The lamp
About lights , It was meant to be connected externally , But I want to be lazy after checking the schematic diagram , After all, the development board comes with two lights and RGB The lamp . So here's what I chose 18 The light of the interface , because 19 The light is always on , So don't choose it .

const int led =18; // Lamp interface
stay setup() Define that the lamp is output
pinMode(led,OUTPUT);// Output
I set up one here god Variable , Initialization is 0, That is, the light is not on , Wait until the command is received before changing ,1 Turn on the lights .
11、PCB plate
Because there are too many devices , I can't connect it with DuPont cable , It's not beautiful to use bread board , Later, I spent a little time learning EDA, With jialichuang's Lichuang EDA Draw a board to use , Here Amway jialichuang , It's really easy to use , And no more than ten centimeters of punching board is completely free , This domestic super nice!!!( Dexter type-A The interface doesn't work , For reference only )

7、 WeChat developer tools
This is a development tool provided by wechat , There's a framework , It is also convenient for us to deploy the project online . Here I focus on how to get onene Data and send instructions
1、 Wechat interface

2、 obtain Onenet Of API Interface
go back to onenet Device list for , Then click the details on the right to see the details of the device , Copy API Address and API-key, One device can have more than one apikey, Add by yourself .
3、 Inquire about OneNet Platform multi protocol access document , Here's a direct look at MQTT Of API Use

4、 I use ApiPost To test whether data can be obtained

5、 Wechat applet access OneNet data
1、 stay wxml I added a click event to the button , Name it points, The corresponding is in index.js You also need to add corresponding functions
points:function(e) {
},
2、 Refer to the applet documentation , I use wx.request get data
points:function(e) {
var that = this
wx.request({
url: 'http://api.heclouds.com/devices/xxxxxxxxxx/datapoints?', //xxz Fill in your equipment here id
// equipment ID
//api-key
header:{
"api-key":"xxxxxxx" // Here's your api-key
},
data:{
limit:1
},
method :"GET",
// To be successful
success:function(res){
that.setData({
wendu:res.data.data.datastreams[0].datapoints[0].value,
time:res.data.data.datastreams[0].datapoints[0].at,
shidu:res.data.data.datastreams[1].datapoints[0].value,
led:res.data.data.datastreams[2].datapoints[0].value, // there shidu Want to follow wxml{
{shidu}} The same name
})
}
})
},
3、 About how to display to specific numbers , Differ from man to man , The following two lines of code are based on json Data to locate
shidu:res.data.data.datastreams[0].datapoints[0].value,
wendu:res.data.data.datastreams[1].datapoints[0].value,

6、 Wechat applet sends commands
Here I also encapsulate two functions , One is hair 1 value , One hair 0 value , Because our embedded code is written 1 Means turn on the light ,0 For turning off the lights . Here, the function of turning on the light is used to introduce
openled:function(e){
wx.request({
url: 'http://api.heclouds.com/cmds?device_id=*****',//* Write your device number here id
// equipment ID
//api-key
header:{
'content-type':'application/json',
"api-key":"xxxxxxx" // Here's your api-key
},
method :"POST",
data:1,// data 1 It's for the light
success(res){
console.log(" Control success , Lights on ")
console.log(res)
console.log(res.data);
}
})
},
7、 Data Refresh
In fact, these online function examples , I tried page refresh 、 Refresh regularly , If there is no click event on the page, you can use the following two methods . But if there is a click event, it is still refreshed regularly
Refresh regularly
/** * Life cycle function -- Monitor page loading */
onLoad: function (options) {
this.points() // This is what I got onenet Functions of data
var that=this
setInterval(function(){
that.points();
},3000 // Here I set 3 Refresh every second
)
},
8、 Select the corresponding instruction in the drop-down list to send data
Here I have written a separate blog, which can be learned in detail by clicking the link below
https://blog.csdn.net/weixin_44107116/article/details/125520404
9、 Data visualization
Here I refer to another blogger's blog , Simple and easy to understand , I made a little improvement here , Show dates only , The year is not displayed . Click the picture to switch to the visual interface , I wrote the temperature 】 I 、 humidity 、 Light these three .
https://blog.csdn.net/qq_52827563/article/details/121726546?

10、 Check whether the equipment is online
Then I set a precondition based on the drop-down list , Instructions can only be sent when the device is online , Otherwise, only the information prompt box will pop up .

postdata:function(shuj){
wx.request({
url: 'https://api.heclouds.com/cmds?device_id= equipment id',
// equipment ID
//api-key
header:{
'content-type':'application/json',
"api-key":" Yours api-key"
},
method :"POST",
data:shuj, // Data command
success(res){
wx.showToast({
title: ' Control command sent ',
image:"/images/gong.png",
duration:2000,
mask:true
})
console.log(" Control success , Control command completed ")
console.log(res)
console.log(res.data);
},
fail(res){
wx.showToast({
title: ' request was aborted ',
image:"/images/errer.png",
duration:2000,
mask:true
})
console.log(" request was aborted ")
console.log(res)
console.log(res.data);
}
})
},
devicedata:function(){
var that =this;
wx.request({
url: 'https://api.heclouds.com/devices/884337606',
// equipment ID
//api-key
header:{
'content-type':'application/json',
"api-key":"9zHJfKbQN=dyGflCM0yaICWHmi8="
},
method :"GET",
success(res){
if (res.data.data.online){
console.log(" The device is connected ");
that.setData({
deviceSwitch:1})
}
else{
console.log(" Device not connected ");
that.setData({
deviceSwitch:0})
}
},
fail(res){
console.log(" request was aborted ");
}
})
},
11、 Effect display
Environment regulation system based on Internet of things
Conclusion
Probably the whole IOT process has been completed , By the way, the hardware is wirelessly integrated , The interface and functions of wechat applet have been upgraded and added new things than before , If you want the source code or related information, you can confide in me , But it's not free , This is my personal effort to find out , Also please understand .
边栏推荐
- Pdf translation, which translation company in Beijing is good
- Unity URP入门实战
- 中值滤波器
- Postman environment variable setting code storage
- Deep Packet Inspection Using Quotient Filter论文总结
- 有哪些科研人员看文献必用的软件?
- selenium 代码存放
- CAS single sign on
- Siamfc: full convolution twin network for target tracking
- OSPF and mGRE experiments
猜你喜欢
随机推荐
Use of delve for go development and debugging
The leader took credit for it. I changed the variable name and laid him off
Brief description of llcc68 broadcast wake-up
Advanced Qt development: how to fit the window width and height when displaying (fitwidth+fitheight)
AMB | towards sustainable agriculture: rhizosphere microbial engineering
Siamrpn++: evolution of deep network connected visual tracking
postman 环境变量设置代码存放
Introduction to C language must brush the daily question of the collection of 100 questions (1-20)
Data permissions should be designed like this, yyyds!
JS to realize the number to amount price thousand separator
Winscp transfer file and VNC connection problem
JS wave animation effect menu style
Establishment of SSO single sign on environment based on CAS
[Huawei online battle service] how can new players make up frames when the client quits reconnection or enters the game halfway?
CVE-2022-33891漏洞复现
基于CAS的SSO单点客户端配置
Cve-2022-33891 vulnerability recurrence
Minecraft 1.16.5 module development (52) modify the original biological trophy (lot table)
Create Yum warehouse inside the enterprise
下一代视觉Transformer:解锁CNN和Transformer正确结合方法








