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

1.4k Views Asked by At

I have a code for Arduino Nano and NodeMCU ESP8266. Both are working correctly and giving the ouput but the output is not that what I want.

NodeMCU code that is getting data from database and sending it to Arduino:

#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);
  }
}

Arduino code that is recieving data from NodeMCU:

#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 code that for querying the database when it is called from 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"];
}
}
?>

The above is all that I wrote and it is working. It is giving continously output, but I want only 1 value on the serial monitor.

Thank you for the help, as I am new in Arduino world. I tried and search too much but I can't solve this issue.

Edit Another issue is that when data in the database column is 1 then the output on the serial monitor is changing sometime but if the data is 0 in the database column it remains constant. Look at output in the pictures.

Data change when 1 is coming from database No change in the output when 0 is coming from database

1

There are 1 best solutions below

1
On BEST ANSWER

The problem is that your code in the loop function is repeated incessantly. So you have to add a variable on the top of your program and set it to true when your code is executed.

Try this code example:

// 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;
  }
}