Arduino 从数据库中获取数据,但它是无穷无尽的。如何控制它只获得 1 个值?

Arduino getting data from database but it's endless. How to control this to get only 1 value?

我有 Arduino Nano 和 NodeMCU ESP8266 的代码。两者都正常工作并提供输出,但输出不是我想要的。

从数据库获取数据并将其发送到 Arduino 的 NodeMCU 代码:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <SoftwareSerial.h>
#include <ArduinoJson.h>

SoftwareSerial s(D6, D5);
int Led_OnBoard = 2;                  // Initialize the Led_OnBoard

const char* ssid = "ssid";                  // Your wifi Name
const char* password = "password";          // Your wifi Password

const char *host = "pc/server IP"; //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() {
  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
  s.begin(115200);
}

void loop() {
  HTTPClient http;    //Declare object of class HTTPClient
  http.begin("http://pc/server IP/Nodemcu_db_record_view/GetValue.php");
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");

  int httpCode = http.GET();   //Get the request
  String payload = http.getString();    //Get the response payload

  Serial.println(httpCode);   //Print HTTP return code
  Serial.println(payload);
http.end();  //Close connection

  StaticJsonBuffer<1000> jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  root["data1"] = payload;
  if (s.available() >= 0)
  {
    root.printTo(s);
  }
}

从 NodeMCU 接收数据的 Arduino 代码:

#include <SoftwareSerial.h>
SoftwareSerial s(5,6);
#include <ArduinoJson.h>
 
void setup() {
  // Initialize Serial port
  Serial.begin(115200);
  s.begin(115200);
  while (!Serial) continue;
 
}
 
void loop() {
 StaticJsonBuffer<1000> jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(s);
  if (root == JsonObject::invalid())
    return;
 
  int data1=root["data1"];
  Serial.println(data1); 
}

PHP 从NodeMCU调用时查询数据库的代码:

<?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");
$sql="SELECT ButtonState FROM project WHERE Date = '2020-10-14'";
$result=mysqli_query($con,$sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {    
      echo  $row["ButtonState"];
}
}
?>

以上是我写的所有内容,并且可以正常工作。它不断地输出,但我只想要串口监视器上的 1 个值。

感谢您的帮助,因为我是 Arduino 世界的新手。 我尝试和搜索了太多,但我无法解决这个问题。

编辑 另一个问题是,当数据库列中的数据为 1 时,串行监视器上的输出有时会发生变化,但如果数据库列中的数据为 0,则它保持不变。查看图片中的输出。

问题是您在 loop 函数中的代码是 repeated incessantly。因此,您必须 add a variable on the top of your program 并在执行代码时将其设置为 true。

试试这个代码示例:

// add a variable on the top
bool printed = false;

void loop() {
  // only execute if the variable is false
  if (printed == false) {
    StaticJsonBuffer<1000> jsonBuffer;
    JsonObject& root = jsonBuffer.parseObject(s);
    if (root == JsonObject::invalid())
      return;
  
    int data1 = root["data1"];
    Serial.println(data1); 

    // set the variable to true so that it is not executed twice
    printed = true;
  }
}