nodeMCU+树莓派+阿里云IOT实现局域网温湿度数据采集

一、功能说明

  1. 使用nodeMCU + DHT11 自动采集温湿度数据,采用JSON格式
  2. 上传温湿度数据到局域网的树莓派
  3. 树莓派接收JSON数据,存入数据库,上传阿里云IOT

功能花里胡哨不是特别实用,2020年课设闲的无聊做的一个玩意,有些内容太久远了忘记了,想起来再添加吧

二、电路设计

1.nodeMCU与DHT11

image.png

2.实物

image.png

三、Arduino添加对ESP8266的支持

  1. 在文件->首选项->附加开发板管理器网站添加:

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

image.png

  1. 打开工具->开发板->开发板管理器

  2. 等待开发板管理器启动完成后,移动到开发板管理器的最下方,可以看到一个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)

六、内容展示

  1. NodeMCU获取温湿度、IP地址,通过串口显示


    image.png
  2. 树莓派接收温湿度数据并插入数据库、上传阿里云IOT


    image.png

3.阿里云IOT数据


image.png
image.png

4.树莓派本地Sql插入的数据


image.png
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容