光敏传感器通过ESP8266模块采集,运用SQL数据库
时间: 2023-08-16 10:08:43 浏览: 65
好的,我为您提供一个简单的代码示例,用于通过ESP8266模块采集光敏传感器数据,将其存储到MySQL数据库中,并通过Web页面展示数据。请注意,这只是一个基本示例,您可能需要根据具体情况进行修改。
1. 采集传感器数据并将其存储到MySQL数据库中
```c
#include <ESP8266WiFi.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
// 定义WiFi信息
const char* ssid = "your_ssid";
const char* password = "your_password";
// 定义MySQL数据库信息
IPAddress server_addr(192,168,1,100); // 替换为您的MySQL服务器IP地址
String user = "your_username"; // 替换为您的MySQL用户名
String password = "your_password"; // 替换为您的MySQL密码
String database = "your_database"; // 替换为您的数据库名称
// 定义光敏传感器引脚
const int sensor_pin = A0;
// 定义数据上传间隔时间(毫秒)
const unsigned long interval = 10000;
// 定义上次数据上传时间
unsigned long last_upload_time = 0;
// 定义WiFi客户端和MySQL客户端
WiFiClient client;
MySQL_Connection conn(&client);
void setup() {
// 初始化串口
Serial.begin(115200);
// 连接WiFi网络
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// 连接MySQL服务器
Serial.print("Connecting to MySQL server...");
if (conn.connect(server_addr, 3306, user, password)) {
Serial.println("success");
} else {
Serial.println("failed");
return;
}
// 选择数据库
MySQL_Cursor* cursor = new MySQL_Cursor(&conn);
cursor->execute("USE " + database);
delete cursor;
}
void loop() {
// 读取光敏传感器值
int sensor_value = analogRead(sensor_pin);
// 检查是否需要上传数据
unsigned long current_time = millis();
if (current_time - last_upload_time >= interval) {
// 构建SQL INSERT语句
String sql = "INSERT INTO sensor_data (value) VALUES (" + String(sensor_value) + ")";
// 执行SQL INSERT语句
MySQL_Cursor* cursor = new MySQL_Cursor(&conn);
cursor->execute(sql);
delete cursor;
// 更新上次数据上传时间
last_upload_time = current_time;
}
}
```
2. 通过Web页面展示数据
您可以使用PHP和JavaScript来实现Web页面数据展示。以下是一个简单的PHP代码示例,用于从MySQL数据库中读取传感器数据,并通过Web页面展示数据。
```php
<?php
// 定义MySQL数据库信息
$servername = "your_servername"; // 替换为您的MySQL服务器名称
$username = "your_username"; // 替换为您的MySQL用户名
$password = "your_password"; // 替换为您的MySQL密码
$database = "your_database"; // 替换为您的数据库名称
// 创建MySQL连接
$conn = new mysqli($servername, $username, $password, $database);
// 检查连接是否成功
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 从数据库中读取传感器数据
$sql = "SELECT * FROM sensor_data";
$result = $conn->query($sql);
// 构建数据表格
echo "<table>";
echo "<tr><th>ID</th><th>Value</th><th>Timestamp</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["id"] . "</td>";
echo "<td>" . $row["value"] . "</td>";
echo "<td>" . $row["timestamp"] . "</td>";
echo "</tr>";
}
echo "</table>";
// 关闭MySQL连接
$conn->close();
?>
```
您可以在Web页面上使用JavaScript定期刷新数据表格,以显示最新的传感器数据。