使用NodeMCU ESP8266将Arduino数据发送到mySQL数据库

TinyCoder

请帮助我的代码。我有从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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用Spring时数据未发送到MySQL数据库

使用PHP将JSON信息发送到数据库?

NodeMCU ESP8266使用C连接到iPhone热点

使用NodeMCU ESP8266发送GET请求

如何使用ajax javascript PHP将大型json数据(250kb)发送到mysql数据库

我有问题使用laravel将多个用户ID发送到数据库中

立即使用esp将数据从NodeMcu(ESP266)发送到ESP32?

将Float数据类型从Arduino发送到ESP32(NodeMCU)

如何使用PHP将时间发送到MySql数据库?

使用Jquery / ajax将数据发送到数据库

使用EtherCard.h库将arduino数据发送到我的数据库

使用Android将图像发送到MySQL数据库

使用SqlDataSource将数据从FormView发送到我的数据库

AJAX到PHP不会使用NODEJS将数据发送到数据库

使用pyserial将数据从python发送到arduino

如何使用Jquery和Ajax将Json数据发送到数据库中?

在使用jQuery将数据发送到数据库时,如何使按钮处于活动状态?

使用Cucumber将输出发送到数据库时,如何测试组件?

使用XHR将图像发送到在线存储/数据库

使用AJAX将数据发送到数据库失败

使用Ajax将图像发送到数据库(php),而无需重新加载

如何使用vue.js(ajax)将数据发送到数据库

无法使用Volley将数据发送到数据库

使用javaservlet将数据从数据库发送到jsp

在 NodeMCU ESP8266 中使用 MicroPython 的 RSSI 值

不使用代码的nodemcu(esp8266)的静态IP

使用 Python 将值发送到数据库(SenseHAT 项目)

如何使用用户帐户从 Firebase 将数据发送到数据库?

如何使用 python Flask 应用程序将文本从输入字段发送到 MySQL 数据库