Arduino从数据库获取数据,但是它是无止境的如何控制此值以获得仅1个值?

问题描述

我有一个针对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); 
}

用于从NodeMCU调用数据库时查询数据库的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");
$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,则它​​保持不变。查看图片中的输出。

Data change when 1 is coming from database

No change in the output when 0 is coming from database

解决方法

问题是您在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;
  }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...