一、功能说明
- 使用nodeMCU + DHT11 自动采集温湿度数据,采用JSON格式
- 上传温湿度数据到局域网的树莓派
- 树莓派接收JSON数据,存入数据库,上传阿里云IOT
功能花里胡哨不是特别实用,2020年课设闲的无聊做的一个玩意,有些内容太久远了忘记了,想起来再添加吧
二、电路设计
1.nodeMCU与DHT11
image.png2.实物
image.png三、Arduino添加对ESP8266的支持
- 在文件->首选项->附加开发板管理器网站添加:
http://arduino.esp8266.com/stable/package_esp8266com_index.json
image.png
-
打开工具->开发板->开发板管理器
-
等待开发板管理器启动完成后,移动到开发板管理器的最下方,可以看到一个esp8266 by esp8266 Community,右下角有个选择版本,选好2.0.0之后点击安装。
4.工具->开发板->Esp8266Module
选择nodeMCU1.0
image.png
四、nodeMCU代码
// Import required libraries
#include "ESP8266WiFi.h"
#include <aREST.h>
#include "DHT.h"
// DHT11 sensor pins
#define DHTPIN 5
#define DHTTYPE DHT11
// The port to listen for incoming TCP connections
#define LISTEN_PORT 80
// WiFi parameters
const char* ssid = "Wifi_Name";
const char* password = "Wifi_Passwd";
// Variables to be exposed to the API
float temperature;
float humidity;
//int id for trans to String and number the data
int id = 0;
// Create aREST instance
aREST rest = aREST();
// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE, 15);
// Create an instance of the server
WiFiServer server(LISTEN_PORT);
void setup(void)
{
// Start Serial
Serial.begin(115200);
// Init DHT
dht.begin();
// Init variables and expose them to REST API
rest.variable("temperature",&temperature);
rest.variable("humidity",&humidity);
// Set device name
rest.set_name("esp8266");
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
}
void loop() {
//Number the data from no.0 begin
//set_id is const String.Using force format
//id -> int
//id_str -> String
String id_str = (String) id;
id = id + 1;
rest.set_id(id_str);
// Reading temperature and humidity
humidity = dht.readHumidity();
temperature = dht.readTemperature();
//Print the Data
Serial.println("=======================================");
Serial.print("This is No.");
Serial.print(id_str);
Serial.println("data");
Serial.print("temperature is :");
Serial.print(temperature);
Serial.print("℃");
Serial.print(" ");
Serial.print("humidity is :");
Serial.print(humidity);
Serial.println("H");
Serial.print("API IP is :");
Serial.println(WiFi.localIP());
Serial.println("=======================================");
Serial.println("\n");
//delay nearly 1 second
delay(1000);
// Handle REST calls
WiFiClient client = server.available();
if (!client) {
return;
}
while(!client.available()){
delay(1);
}
rest.handle(client);
}
五、树莓派服务器端代码
#import libraries
import urllib.request
import json
import json.decoder
import datetime
import pymysql
import socket
import re
from linkkit import linkkit
#API IP
url_temp = 'http://ESP8266_IP/temperature'
url_hum = 'http://ESP8266_IP/humidity'
# http headers
firefox_headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
#Ali JSON settings
lk = linkkit.LinkKit(
host_name="cn-shanghai",
product_key="",
device_name="",
device_secret="")
# ALI connect
lk.thing_setup("tsl.json")
lk.connect_async()
# http requeset and get data
# http Response is a Json and actually type is str
# turn it into dict and split the data.
# while insert into databases.if get No database error then create it.
# finally print the data
while True:
try:
#Temp Request
temp_request = urllib.request.Request(url_temp,headers = firefox_headers)
temp_response = urllib.request.urlopen(temp_request,timeout=3)
#Hum Request
hum_request = urllib.request.Request(url_hum,headers = firefox_headers)
hum_response = urllib.request.urlopen(hum_request,timeout=3)
#Str DATA
temp_response_str = temp_response.read().decode('utf-8')
hum_response_str = hum_response.read().decode('utf-8')
except socket.timeout:
print("time out ! Please Check Connection")
exit(1)
#str->dict
try:
temp_response_dict = json.loads(temp_response_str)
hum_response_dict = json.loads(hum_response_str)
except json.decoder.JSONDecodeError:
print("Get an Error while receving json data!")
print("Please Check Connection")
exit(1)
#result data type<dict>
temp_result = temp_response_dict['temperature']
temp_id = temp_response_dict['id']
hum_result = hum_response_dict['humidity']
hum_id = hum_response_dict['id']
time = datetime.datetime.now()
# MysqlConnetcion
try:
conn = pymysql.connect(host='localhost',user='mysql_users',passwd='mysql_passwd',db='mysqldatabase',charset='utf8')
except:
print("Mysql Connection Error!Please Check Mysql")
exit(1)
cur = conn.cursor()
sql_create_table = """
CREATE TABLE dht11(
TIME TIMESTAMP,
TEMP_ID INT(10),
TEMP_VALUE INT(10),
HUM_ID INT(10),
HUM_VALUE INT(10))
"""
into = "INSERT INTO dht11(temp_id,temp_value,hum_id,hum_value,time) VALUES (%s,%s,%s,%s,%s)"
values = (temp_id,temp_result,hum_id,hum_result,time)
# excute mysql
try:
cur.execute(into,values)
except:
try:
cur.execute(sql_create_table)
finally:
cur.execute(into,values)
exit(1)
conn.commit()
conn.close()
# update to ALI
prop_data = {
"CurrentTemperature": round(temp_result, 2),
"CurrentHumidity": round(hum_result, 2)
}
try:
rc, request_id = lk.thing_post_property(prop_data)
print("===============================")
print(time)
print("Sending TO ALIIOT OK Insert into databases OK")
print("Temperature is:",temp_result," ","Humidity is:",hum_result)
print("===============================")
print("\n")
except Exception as e:
print('ERROR:', e)
exit(1)
六、内容展示
-
NodeMCU获取温湿度、IP地址,通过串口显示
image.png -
树莓派接收温湿度数据并插入数据库、上传阿里云IOT
image.png
3.阿里云IOT数据
image.png image.png
4.树莓派本地Sql插入的数据
image.png
网友评论