Arduino MySQL是一種智能化開發工具,它具有實時數據采集,數據存儲等多種功能。該工具與現代物聯網技術有很大的關聯。Arduino MySQL是物流與工業界廣泛應用的技術。這項技術應用范圍廣泛,在數據存儲上極為便捷實用。
使用Arduino MySQL的過程非常簡單,首先需安裝MySQL數據庫庫。使用Arduino的庫"ESP8266WiFi.h"將Wireless Sensor Network(WNS)傳感器與MySQL數據庫相連。該代碼可通過pre標簽給出如下:
#include#include #include byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; IPAddress server_addr(192,168,0,10); // MySQL服務器地址 char user[] = "username"; // 用戶名 char password[] = "password"; // 密碼 WiFiClient client; MySQL_Connection conn((Client *)&client); void setup() { Serial.begin(115200); WiFi.begin("ssid", "password"); // Wifi名字和密碼 Serial.print("Connecting to WiFi"); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.print("."); } Serial.println(""); Serial.print("Connecting to MySQL Server "); while (conn.connect(server_addr, 3306, user, password) != true) { delay(1000); Serial.print("."); } Serial.println(""); } void loop() { delay(1000); char INSERT_SQL[] = "INSERT INTO test.temperature (value) VALUES ('25');"; Serial.println(INSERT_SQL); MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn); cur_mem->execute(INSERT_SQL); delete cur_mem; }
在數據庫上,建立表“test”和item“temperature”會適應代碼的語言和邏輯運行,查詢指令為“SELECT* FROM test.temperature ORDER BY ID DESC LIMIT 1”。以下代碼將實時數據插入MySQL數據庫,同樣采用pre標簽:
void setup() { Serial.begin(9600); while (!Serial); } void loop() { float temp = readTemp(); //從傳感器中讀取溫度 if (temp != -127.0) { //如果溫度讀取成功 Serial.print("Temperature is: "); Serial.print(temp); Serial.println("C"); WiFiClient client; if (client.connect(serverName, serverPort)) {//Wi-Fi連接 String request = "GET /welcome.php?temp=" + String(temp) + " HTTP/1.1\r\n" + //傳遞一個請求給Web服務器 "Host: "+ serverName +"\r\n" + "Connection: close\r\n\r\n"; client.print(request); delay(1000); while (client.available()) { String recvLine = client.readStringUntil('\r'); Serial.print(recvLine); } client.stop(); } } } float readTemp(void) { sensors.requestTemperatures(); //請求溫度編號 float tempC = sensors.getTempCByIndex(0); //獲取傳感器中的溫度 return tempC ; }
如以上這些代碼所示,Arduino MySQL是如何將傳感器數據上傳到MySQL數據庫上,將數據實時存儲、管理非常方便。