[英]Sending Arduino data to mySQL database using NodeMCU ESP8266
請在我的代碼中幫助我。 我有從 mySql 發送和獲取數據的 arduino 代碼。 它運行良好並將數據存儲到數據庫中。 問題是,如果我打開按鈕,值 1 會存儲在數據庫中,但是當我關閉按鈕時,值 0 不會存儲在數據庫中。
這是我的arduino代碼:
//Arduino Code
#include <SoftwareSerial.h>
SoftwareSerial s(5,6);//Rx,Tx
int buttonPinBulb = 11;
int relay1 = 10;
int buttonBulb;
int currentStatus = LOW;
unsigned long lastMillis = 0;
const unsigned long debounceTime = 100;
void setup() {
// put your setup code here, to run once:
pinMode(buttonPinBulb, INPUT_PULLUP);
pinMode(relay1, OUTPUT);
s.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
buttonBulb = digitalRead(buttonPinBulb);
bulbOnOff(buttonBulb);
}
int bulbOnOff(int buttonBulb) {
unsigned long currentMillis = millis();
// protect against overflow
if ( (currentMillis - lastMillis > debounceTime) || (currentMillis < lastMillis)) {
if (buttonBulb != currentStatus) {
digitalWrite(relay1, buttonBulb);
//Serial.println(!buttonBulb);
currentStatus = buttonBulb;
// update database here
if(s.available()>0)
{
s.write(!buttonBulb);
}
lastMillis = currentMillis;
}
}
return 0;
}
以下是nodeMCU ESP8266代碼
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <SoftwareSerial.h>
SoftwareSerial s(D6, D5); //RX,TX
int buttonBulb;
int Led_OnBoard = 2;
const char* ssid = "iPhone"; // Your wifi Name
const char* password = "Qaser.shah.123"; // Your wifi Password
const char *host = "172.20.10.6"; //Your pc or server (database) IP, example : 192.168.0.0 , if you are a windows os user, open cmd, then type ipconfig then look at IPv4 Address.
void setup() {
// put your setup code here, to run once:
wifiConnection();
s.begin(115200);
}
int wifiConnection() {
pinMode(Led_OnBoard, OUTPUT); // Initialize the Led_OnBoard pin as an output
Serial.begin(115200);
WiFi.mode(WIFI_OFF); //Prevents reconnection issue (taking too long to connect)
delay(1000);
WiFi.mode(WIFI_STA); //This line hides the viewing of ESP as wifi hotspot
WiFi.begin(ssid, password); //Connect to your WiFi router
Serial.println("");
Serial.print("Connecting");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
digitalWrite(Led_OnBoard, LOW);
delay(250);
Serial.print(".");
digitalWrite(Led_OnBoard, HIGH);
delay(250);
}
digitalWrite(Led_OnBoard, HIGH);
//If connection successful show IP address in serial monitor
Serial.println("");
Serial.println("Connected to Network/SSID");
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
s.write("s");
if (s.available() > 0)
{
buttonBulb = s.read();
Serial.println(buttonBulb);
int result = updateDatabase(buttonBulb);
if(result != 0){
//error updating database
Serial.print("error updating database");
}
}
}
int updateDatabase(int buttonBulb){
HTTPClient http; //Declare object of class HTTPClient
//String ButtonState;
String buttonValueSend, postData;
buttonValueSend = String(buttonBulb); //String to interger conversion
//Post Data
postData = "buttonBulb=" + buttonValueSend;
http.begin("http://172.20.10.6/Nodemcu_db_record_view/InsertDB.php"); //Specify request destination
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header
int httpCode = http.POST(postData); //Send the request
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
Serial.println("Button Value send=" + buttonValueSend);
http.end(); //Close connection
return 0;
}
以下是我存儲 Arduino 數據的 php 代碼
<?php
//Creates new record as per request
//Connect to database
$servername = "localhost"; //example = localhost or 192.168.0.0
$username = "root"; //example = root
$password = "";
$dbname = "automation";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Database Connection failed: " . $conn->connect_error);
}
//Get current date and time
date_default_timezone_set('Asia/Karachi');
$d = date("Y-m-d");
$t = date("H:i:s");
if(!empty($_POST['buttonBulb']))
{
$buttonBulb = $_POST['buttonBulb'];
$sql = "INSERT INTO project (ButtonState, Date, Time) VALUES ('".$buttonBulb."', '".$d."', '".$t."')"; //nodemcu_ldr_table = Youre_table_name
if ($conn->query($sql) === TRUE) {
echo "OK";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
查看輸出圖像 在此圖像中,OK 以值 1 打印,但未以值 0 打印 OK
我認為有什么問題或者我忘記了一些事情,這就是它沒有發生的原因。
非常感謝您的任何贊賞。
您可以創建一個單獨的函數來更新數據庫,並僅在按鈕狀態更改時調用更新。
結合我對您上一個問題的回答,它看起來像這樣:
void loop() {
unsigned long currentMillis = millis();
if ( (currentMillis - lastMillis > debounceTime)
|| (currentMillis < lastMillis)) { // protect against overflow
int buttonBulb = digitalRead(buttonPinBulb);
if (buttonBulb != currentStatus) {
digitalWrite(relay1, buttonBulb);
Serial.println(buttonBulb);
currentStatus = buttonBulb;
// update database
int result = updateDatabase(buttonBulb);
if (result != 0) {
// error updating database
}
}
lastMillis = currentMillis;
}
}
int updateDatabase(int buttonvalue) {
HTTPClient http; //Declare object of class HTTPClient
String buttonValueSend, postData;
buttonValueSend = String(buttonvalue); //String to integer conversion
// ...
http.end(); //Close connection
return 0; // for example return 0 on success, -1 on error
}
我找到了問題所在。 問題出在我的 php 代碼中,這就是為什么 1 會存儲在數據庫中而 0 不會。
這是我在 php 代碼中所做的更改,我剛剛刪除了if(!empty(&_POST['buttonBulb'])){}
在 if 語句中使用的代碼現在不在 if 語句中。 原因背后的原因是,當我向此代碼發送 1 時,它是可以的,但是如果發送 0,則 is 語句假定沒有值並且 buttonBulb 變量為空。
感謝所有在此代碼中幫助我的人。 現在我要進行這個項目的下一步,如果我有一些問題,我會問。
特別感謝@Danny_ds
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.