Arduino-ESP8266传感器获取温度湿度[联网版]

2023-10-06 23:10

本文主要是介绍Arduino-ESP8266传感器获取温度湿度[联网版],希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

基础配置

  1. 数据库:Mysql
  2. 服务器:Linux
  3. 后端:php
  4. 前端:html,css,echar
  5. 开发板:esp8266
  6. 传感器:温湿度传感器,型号不会看

成品演示

esp8266把传感器的数据上传到服务器,
手机上访问网址就能看到当前的温度湿度。
在这里插入图片描述

流程图

流程图应该挺详细了。
在这里插入图片描述

接口设计

简单安全考虑,增加一个密钥验证,
防止被恶意写入乱七八糟数据;

接口:http://zxyoyo.com/sky/iot123.php
传输方式:GET
参数:
token:"123abc" //安全参数,随意设置
temp: 22.6 //温度,浮点数
humi: 46.9 //湿度,浮点数
maker: 123 // 程序的id,随意设置,用于区分不同设备

php接口代码

<?php//设置编码为UTF-8,以避免中文乱码header('Content-Type:text/plain;charset=utf-8');//验证--- token,温度,湿度,设备id$token = $_GET['token'];$temp = $_GET['temp'];$humi = $_GET['humi'];$maker = $_GET['maker'];$mytoken = "123abc";//固定的token// 判断是否为空if(empty($token)||empty($temp)||empty($humi) || empty($maker)){die("-null-");}// token 校验if($token != $mytoken){die("token error!");}// 导入数据库连接配置信息//示例:$link=mysqli_connect("localhost","root","123456","database_name")or die ('Error connecting to MySQL server.');include  __DIR__.'/../con_mysql.php';// 编写sql 插入数据到 表中$sql = "INSERT INTO iot_th_one(temp,humi,maker) VALUES ("."'".$temp."',"."'".$humi."',"."'".$maker."');";// 执行sql$rowresult = mysqli_query($link, $sql);$result= "";if($rowresult){//保存到数据库成功$result = "ok";}else{// 保存到数据库失败$result = "add error";}//关闭数据库连接mysqli_close($link);// 返回结果die($result);
?>

Arduino程序设计

主要是用到wifi库,http网络请求库

// 导入dht库,用于传感器的库
#include <DHT.h>
//连接多个wifi
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
//网络请求
#include <ESP8266HTTPClient.h>// 定义一个dht对象,5是GPIO5,具体看开发板
DHT dht(5, DHT11);ESP8266WiFiMulti wifiMulti; //创建一个ESP8266WiFiMulti对象
//创建 HTTPClient 对象
HTTPClient httpClient;
WiFiClient wifiClient;
//上传数据的接口
String api = "http://zxyoyo.com/sky/iot123.php";void setup() {// put your setup code here, to run once://开启串口监视器Serial.begin(9600);//初始化dht传感器dht.begin();//设置ESP8266工作模式为无线终端模式WiFi.mode(WIFI_STA);// 通过 addAP函数存储  wifi 名称,wifi密码wifiMulti.addAP("00QAQ", "00QAQ123!");wifiMulti.addAP("00qaq", "00qaq123!");Serial.println("Please wait, Connecting");int i = 0;while (wifiMulti.run() != WL_CONNECTED) {delay(1000);Serial.print(".");if(i>10) Serial.println("\n");//print(i++);}//连接wifi成功后,输出连接成功信息Serial.println("\n");Serial.print("connected to ");Serial.println(WiFi.SSID());Serial.print("IP address: \t");Serial.println(WiFi.localIP());//添加api的校验信息api += "?token=123abc";//添加api的设备信息api += "&maker=esp8266";}void loop() {// put your main code here, to run repeatedly://延迟10s 打印delay(10000);// 获取摄氏温度float temp = dht.readTemperature();// 获取空气湿度float humi = dht.readHumidity();// 判断读取到的数据if(isnan(temp)){//没有读取到摄氏温度Serial.println("failed to read temp");temp = 8266.0;}else {//读取到摄氏温度,打印Serial.print("Read temp = ");Serial.println(temp);}if(isnan(humi)){//没有读取空气湿度Serial.println("failed to read humi");humi = 8266.0;}else {//读取空气湿度,打印Serial.print("Read humi = ");Serial.println(humi);}//如果温度或者湿度有一个有读数,上传数据if(temp != 8266.0 || humi != 8266.0){uploadData(temp,humi);}else{Serial.println("read data failed");}}//上传数据到服务器
void uploadData(float temp, float humi){String tempUrl = api +"&temp=";tempUrl += temp;tempUrl += "&humi=";tempUrl += humi;httpClient.begin(wifiClient,tempUrl);//启动连接并发送http请求int code = httpClient.GET();if(code == HTTP_CODE_OK){String resp = httpClient.getString();Serial.print("Server resp: ");Serial.println(resp); }else{Serial.println("request server error");Serial.print("code=");Serial.println(code);Serial.println(tempUrl);Serial.println(httpClient.errorToString(code).c_str());}}

前端设计

访问接口

http://zxyoyo.com/skx/iot1.php

基本的html,css代码,使用echar设计图表,不用额外接口获取数据了,直接用php方便多了。

<!DOCTYPE html>
<html lang="ch"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><link rel="shortcut icon" href="./favicon.ico"><link href="./assets/css/iot1.css" rel="stylesheet"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>温湿度</title><script src="./assets/js/echarts.min.js"></script>
</head>
<!-- 0摄氏度以下:16e6fb,26cbfd一般天气20-30;47a8fb高温黄色预警信号:连续三天温度达到35℃; f7bb13高温橙色预警信号:当日气温达到37℃; ff5d3a高温红色预警信号:当日温度达到40℃。 ff0b0b-->
<body><!-- 获取数据 --><?php // 导入数据库连接配置信息//示例:$link=mysqli_connect("localhost","root","123456","database_name")or die ('Error connecting to MySQL server.');include  __DIR__.'/../con_mysql.php';$maker = "deviceid";//获取最新的 温度湿度数据$curTemp = 1.23;//当前温度$curHumi = 1.23;//当前湿度$updateTime = '';//更新时间$sql = "SELECT * from iot_th_one WHERE maker='".$maker."' order by id desc limit 1;";$rowresult = mysqli_query($link, $sql);if (!$rowresult) {printf("Error: %s\n", mysqli_error($link));mysqli_close($link);echo 'error';}if($rowresult->num_rows > 0){$row = mysqli_fetch_assoc($rowresult);if($row['id']>0){mysqli_close($link);$curHumi = $row['humi'];$curTemp = $row['temp'];$updateTime = $row['createtime'];//小数点后一位if(strpos($curTemp,'.') !== false){$curTemp = number_format($curTemp,1);}}mysqli_close($link);}else{mysqli_close($link);}?><div style="position: relative;color: #107bff;"><!-- 为 ECharts 准备一个定义了宽高的 DOM --><div id="main" style=""></div><div id="content" style="" >当前温度:<?php echo $curTemp;?>,当前湿度:<?php echo $curHumi;?><br>数据更新时间: <?php echo $updateTime;?><br><a style="text-decoration: none;" href="./iot1.php">点击更新</a></div></div><script type="text/javascript">// 基于准备好的dom,初始化echarts实例var myChart = echarts.init(document.getElementById('main'));// 指定图表的配置项和数据var option = {series: [{type: 'gauge',min: -20,max: 60,axisLine: {lineStyle: {width: 20,color: [[1,new echarts.graphic.LinearGradient(0,0,1,0,[{offset: 0,color: '#26cbfd'},{offset: 0.1,color: '#16e6fb'},{offset: 0.375,color: '#47a8fb'},{offset: 0.7125,color: '#f7bb13'},{offset: 1,color: '#ff0b0b'},])]]}},pointer: {itemStyle: {color: 'auto'}},axisTick: {distance: -20,length: 8,lineStyle: {color: '#fff',width: 2}},splitLine: {distance: -30,length: 30,lineStyle: {color: '#fff',width: 4}},axisLabel: {color: 'auto',distance: 22,fontSize: 14},detail: {valueAnimation: true,formatter: '{value} ℃',color: 'auto',fontSize: 20},data: [{value: <?php echo $curTemp;?>,name: <?php echo "'湿度:".$curHumi."'";?>}]}]};// 使用刚指定的配置项和数据显示图表。myChart.setOption(option);</script></body></html>

总结

感谢您阅读到最后。做个东西的灵感来源是之前在某宝买了一个电子温度湿度显示,在小米的app能看到实时数据,其实还是很方便的。自己动手做一个,几乎把所学都用到了(c 写arduino,php写接口,html写页面展示,Mysql存储数据),很是满意,后面继续完善。共勉!

这篇关于Arduino-ESP8266传感器获取温度湿度[联网版]的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/154467

相关文章

arduino ide安装详细步骤

​ 大家好,我是程序员小羊! 前言: Arduino IDE 是一个专为编程 Arduino 微控制器设计的集成开发环境,使用起来非常方便。下面将介绍如何在不同平台上安装 Arduino IDE 的详细步骤,包括 Windows、Mac 和 Linux 系统。 一、在 Windows 上安装 Arduino IDE 1. 下载 Arduino IDE 打开 Arduino 官网

Android Environment 获取的路径问题

1. 以获取 /System 路径为例 /*** Return root of the "system" partition holding the core Android OS.* Always present and mounted read-only.*/public static @NonNull File getRootDirectory() {return DIR_ANDR

JS和jQuery获取节点的兄弟,父级,子级元素

原文转自http://blog.csdn.net/duanshuyong/article/details/7562423 先说一下JS的获取方法,其要比JQUERY的方法麻烦很多,后面以JQUERY的方法作对比。 JS的方法会比JQUERY麻烦很多,主要则是因为FF浏览器,FF浏览器会把你的换行也当最DOM元素。 <div id="test"><div></div><div></div

vcpkg子包路径批量获取

获取vcpkg 子包的路径,并拼接为set(CMAKE_PREFIX_PATH “拼接路径” ) import osdef find_directories_with_subdirs(root_dir):# 构建根目录下的 "packages" 文件夹路径root_packages_dir = os.path.join(root_dir, "packages")# 如果 "packages"

Weex入门教程之4,获取当前全局环境变量和配置信息(屏幕高度、宽度等)

$getConfig() 获取当前全局环境变量和配置信息。 Returns: config (object): 配置对象;bundleUrl (string): bundle 的 url;debug (boolean): 是否是调试模式;env (object): 环境对象; weexVersion (string): Weex sdk 版本;appName (string): 应用名字;

MFC中App,Doc,MainFrame,View各指针的互相获取

纸上得来终觉浅,为了熟悉获取方法,我建了个SDI。 首先说明这四个类的执行顺序是App->Doc->Main->View 另外添加CDialog类获得各个指针的方法。 多文档的获取有点小区别,有时间也总结一下。 //  App void CSDIApp::OnApp() {      //  App      //  Doc     CDocument *pD

android两种日志获取log4j

android   log4j 加载日志使用方法; 先上图: 有两种方式: 1:直接使用架包 加载(两个都要使用); 架包:android-logging-log4j-1.0.3.jar 、log4j-1.2.15.jar  (说明:也可以使用架包:log4j-1.2.17.jar)  2:对架包输入日志的二次封装使用; 1:直接使用 log4j 日志框架获取日志信息: A:配置 日志 文

17 通过ref代替DOM用来获取元素和组件的引用

重点 ref :官网给出的解释是: ref: 用于注册对元素或子组件的引用。引用将在父组件的$refs 对象下注册。如果在普通DOM元素上使用,则引用将是该元素;如果在子组件上使用,则引用将是组件实例: <!-- vm.$refs.p will be the DOM node --><p ref="p">hello</p><!-- vm.$refs.child will be the c

react笔记 8-19 事件对象、获取dom元素、双向绑定

1、事件对象event 通过事件的event对象获取它的dom元素 run=(event)=>{event.target.style="background:yellowgreen" //event的父级为他本身event.target.getAttribute("aid") //这样便获取到了它的自定义属性aid}render() {return (<div><h2>{

react笔记 8-18 事件 方法 定义方法 获取/改变数据 传值

1、定义方法并绑定 class News extends React.Component {constructor(props) {super(props)this.state = {msg:'home组件'}}run(){alert("我是一个run") //方法写在类中}render() {return (<div><h2>{this.state.msg}</h2><button onCli