请帮助我的代码。我有从MySql发送和获取数据的arduino代码。它运行良好,并将数据存储到数据库中。但是数据一次又一次地发送到数据库,我希望一次只将一个值发送到数据库。假设变量值是HIGH,则仅当变量值是LOW时才发送此值,然后将该值发送到数据库。
这是我的代码:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
int Led_OnBoard = 2; // Initialize the Led_OnBoard
const char* ssid = "mySsid"; // Your wifi Name
const char* password = "myWifipass"; // 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:
delay(1000);
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
}
void loop() {
// put your main code here, to run repeatedly:
HTTPClient http; //Declare object of class HTTPClient
String buttonValueSend, postData;
int buttonvalue = HIGH;
buttonValueSend = String(buttonvalue); //String to interger conversion
//Post Data to database
postData = 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("Button Value=" + buttonvalue);
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
Serial.println("Button Value send=" + buttonValueSend);
//Getting data from database
http.begin("http://172.20.10.6/Nodemcu_db_record_view/GetValue.php");
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
httpCode = http.GET(); //Get the request
String payload = http.getString(); //Get the response payload
Serial.println("Button State " + payload); //Print request response payload
http.end(); //Close connection
}
请注意,上面的代码会发送太多我不想要的数据。请在我的代码中帮助我,该代码在接收到buttonvalue
变量中的数据时将数据发送到数据库一次,如果变量中没有值,则它一定不能将数据发送到数据库。
以下是我的php代码,用于存储Arduino数据
<?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['buttonvalue']))
{
$buttonvalue = $_POST['buttonvalue'];
$sql = "INSERT INTO project (ButtonState, Date, Time) VALUES ('".$buttonvalue."', '".$d."', '".$t."')"; //nodemcu_ldr_table = Youre_table_name
if ($conn->query($sql) === TRUE) {
echo "OK";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
这是从mySql获取数据的php代码:
<?php
$server="localhost";
$username="root";//THE DEFAULT USERNAME OF THE DATABASE
$password="";
$dbname="automation";
$con=mysqli_connect($server,$username,$password,$dbname) or die("unable to connect");
//$Ldr=$_GET['Ldr'];
$sql="SELECT ButtonState from project WHERE Date = '2020-10-06'";
$result=mysqli_query($con,$sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["ButtonState"];
}
}
?>
非常感谢您的贴士。
您可以创建一个单独的函数来更新数据库,并且仅在按钮状态更改时才调用更新。
结合我对上一个问题的回答,它看起来像这样:
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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句