一诈豌、功能說明
- 使用nodeMCU + DHT11 自動采集溫濕度數(shù)據(jù)仆救,采用JSON格式
- 上傳溫濕度數(shù)據(jù)到局域網(wǎng)的樹莓派
- 樹莓派接收J(rèn)SON數(shù)據(jù),存入數(shù)據(jù)庫队询,上傳阿里云IOT
功能花里胡哨不是特別實用派桩,2020年課設(shè)閑的無聊做的一個玩意,有些內(nèi)容太久遠(yuǎn)了忘記了蚌斩,想起來再添加吧
二铆惑、電路設(shè)計
1.nodeMCU與DHT11
2.實物
三、Arduino添加對ESP8266的支持
- 在文件->首選項->附加開發(fā)板管理器網(wǎng)站添加:
http://arduino.esp8266.com/stable/package_esp8266com_index.json
打開工具->開發(fā)板->開發(fā)板管理器
等待開發(fā)板管理器啟動完成后送膳,移動到開發(fā)板管理器的最下方员魏,可以看到一個esp8266 by esp8266 Community,右下角有個選擇版本叠聋,選好2.0.0之后點擊安裝撕阎。
4.工具->開發(fā)板->Esp8266Module
選擇nodeMCU1.0
四、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);
}
五碌补、樹莓派服務(wù)器端代碼
#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)
六虏束、內(nèi)容展示
-
NodeMCU獲取溫濕度棉饶、IP地址,通過串口顯示
-
樹莓派接收溫濕度數(shù)據(jù)并插入數(shù)據(jù)庫镇匀、上傳阿里云IOT
3.阿里云IOT數(shù)據(jù)
4.樹莓派本地Sql插入的數(shù)據(jù)