下载整份代码code.rar
传感器到SQL
//引入各种库
#include <ESP8266WiFi.h>
#include <SPI.h>
#include <Wire.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
//定义屏幕宽度和高度
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
//定义屏幕的连线GPIO号
#define OLED_MOSI 13
#define OLED_CLK 12
#define OLED_DC 3
#define OLED_CS 1
#define OLED_RESET 15
#define SEALEVELPRESSURE_HPA (1013.25) //定义QNH海压 方便计算高度
//输入参数到库
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT,
OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);
Adafruit_BME280 bme;
IPAddress server_addr(xxxxxxx); //服务器ip
char user[] = "8266"; //MySQL 用户名
char password[] = "xxxxx"; //MySQL 密码
char INSERT_SQL[] = "INSERT INTO `8266`.`bmedata` (Temp, Humi, Pres, Device) VALUES (%s, %s, %s, %d)";
char Temp[15];//定义几个字符串 分别是 温度 湿度 气压
char Humi[15];
char Pres[15];
char deviceid[] = "fkun06"; //设备名 方便管理
char ssid[] = "F_KUN"; //WiFi名称
char pass[] = "xxxxx"; //WiFi密码
WiFiClient client;
MySQL_Connection conn((Client *)&client);
//初始化
void setup() {
Serial.begin(9600); //串口波特率
Serial.println(F("Serial Start!")); //串口输出一些内容测试
display.begin(SSD1306_SWITCHCAPVCC); //屏幕相关
bme.begin(); //传感器相关
display.clearDisplay(); //清屏
display.setTextSize(2); //字体大小
display.setTextColor(WHITE); //字体颜色
display.setCursor(30, 20); //位置
display.print(F("Start!")); //屏幕输出一些文字
display.display(); //屏幕输出
delay(1000); //延迟1秒
display.clearDisplay(); //清屏
display.setTextSize(1); //字体大小
display.setTextColor(WHITE); //字体颜色
display.setCursor(0, 0); //位置
display.print(F("WiFi Connecting")); //屏幕输出一些文字
display.display();
Serial.print(F("WiFi Connecting")); //串口输出一些文字
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) { // 如果WiFi没有连接,一直循环打印点
delay(500);
Serial.print(".");
display.print(".");
display.display();
}
display.clearDisplay();
display.setTextSize(1); //字体大小
display.setTextColor(WHITE); //字体颜色
display.setCursor(0, 0); //位置
display.print(F("WiFi Connected !!!")); //屏幕输出一些文字
Serial.print(F("WiFi Connected")); //串口输出一些文字
Serial.printf("\nConnected to %s", ssid);
Serial.print("\nLocal IP address: ");
Serial.print(WiFi.localIP()); // 打印开发板的IP地址
Serial.print("\nDevice MAC:");
Serial.println(WiFi.macAddress());
display.display();
delay(1000);
}
void getdata() {
float h = bme.readHumidity(); //定义浮点数 h等于传感器获取到的湿度数据 下类同
float t = bme.readTemperature();
float p = (bme.readPressure() / 100.0F);
dtostrf(h, 1, 2, Humi); //将上面的浮点数保留两位小数输出到最开始定义的几个字符串名下
dtostrf(t, 1, 2, Temp);
dtostrf(p, 1, 2, Pres);
}
void dataprint() {
Serial.print(F("Humidity: ")); //串口内输出传感器获取的参数
Serial.print(Humi);
Serial.print(F("% Temperature: "));
Serial.print(Temp);
Serial.print(F("°C "));
Serial.print("Temperature = ");
Serial.print(bme.readTemperature());
Serial.println(" *C");
Serial.print("Pressure = ");
Serial.print(bme.readPressure() / 100.0F);
Serial.println(" hPa");
Serial.print("Approx. Altitude = ");
Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
Serial.println(" m");
Serial.print("Humidity = ");
Serial.print(bme.readHumidity());
Serial.println(" %");
Serial.println();
display.setTextSize(1); //屏幕输出传感器参数
display.setTextColor(WHITE);
display.setCursor(0, 0);
display.clearDisplay();
display.print(F("Humidity: "));
display.print(Humi);
display.print(F(" %"));
display.setCursor(0, 16);
display.print(F("Temperature: "));
display.print(Temp);
display.print(F(" *C"));
display.setCursor(0, 32);
display.print(F("Pressure: "));
display.print(Pres);
display.print(F(" hPa"));
display.setCursor(0, 48);
display.print(F("Altitude: "));
display.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
display.print(F(" m"));
display.display();
}
void sqldata() {
char query[128];
sprintf(query, INSERT_SQL, Temp, Humi, Pres, deviceid); //转化数据格式匹配数据表
Serial.print("Ready to Push: ");
Serial.println(query);
MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
cur_mem->execute(query);
delete cur_mem;
}
void pushdata(){
if (WiFi.status() == WL_CONNECTED)
{
if (conn.connect(server_addr, 3306, user, password)) { // 连接数据库
Serial.print("Start Pushing Data!");
sqldata();
display.clearDisplay();
display.setTextSize(1); //屏幕输出传感器参数
display.setTextColor(WHITE);
display.setCursor(15, 30);
display.print(F("Data Pushed !"));
display.display();
Serial.print("Data Pushed !");
} else {
Serial.print("Connection to Server FAILED !!!");
}
}
}
//循环
void loop() {
int i = 0;
while(i<=10){ //计数小于等于10保持循环
delay(2000); //等待2秒
getdata();
dataprint();
i++;
}
pushdata();
}
PHP文件
<?php
header("content-type:text/json;charset=utf-8");
$con = mysqli_connect("localhost", "8266", "xxxx");
if (!$con)
{
die('Could not connect database: ' . mysqli_error());
}
$db_selected = mysqli_select_db($con,"8266");
if (!$db_selected)
{
die ("Can\'t use yxz : " . mysqli_error());
}
mysqli_query($con,"SET CHARACTER SET utf8");
$sql = mysqli_query($con,"SELECT * FROM `bmedata` ");
$arr = array();
while($row = mysqli_fetch_array($sql)) {
$count=count($row);//不能在循环语句中,由于每次删除 row数组长度都减小
for($i=0;$i<$count;$i++){
unset($row[$i]);//删除冗余数据
}
array_push($arr,$row);
}
echo json_encode($arr,JSON_UNESCAPED_UNICODE);
mysqli_close($con);
?>
HTML页面 温度为例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>FKUN SMARTHOME VIEW</title>
<!-- 引入 echarts.js -->
<script src="./echarts.min.js"></script>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 800px;height:400px;"></div>
<script type="text/javascript">
var myChart = echarts.init(document.getElementById('main'));
// 初始化两个数组,盛装从数据库中获取到的数据
var Temp=[], Time=[];
function TestAjax(){
$.ajax({
type: "post",
async: false, //异步执行
url: "bmedata.php", //SQL数据库文件
data: {}, //发送给数据库的数据
dataType: "json", //json类型
success: function(result) {
if (result) {
for (var i = 0; i < result.length; i++) {
Temp.push(result[i].Temp);
Time.push(result[i].Time);
console.log(result[i].Temp);
console.log(result[i].Time);
}
}
}
})
return Temp, Time;
}
//执行异步请求
TestAjax();
// 指定图表的配置项和数据
myChart.setOption(option = {
tooltip: {
trigger: 'axis',
position: function (pt) {
return [pt[0], '10%'];
}
},
title: {
text: 'Temperature'
},
tooltip: {
trigger: 'axis'
},
xAxis: {
data: Time
},
yAxis: {
splitLine: {
show: false
},
min: function(value) {
return value.min = -5
},
max: function(value) {
return value.max = 35
},
},
toolbox: {
left: 'center',
feature: {
dataZoom: {
yAxisIndex: 'none'
},
restore: {},
saveAsImage: {}
}
},
dataZoom: [{
startValue: '2020-01-04'
}, {
type: 'inside'
}],
series: {
name: 'Temp',
type: 'line',
smooth:true,
data: Temp,
}
});
myChart.setOption(option);
</script>
</body>
</html>