0

Kindly help me in my code. I have arduino code that is sending and getting data from mySql. It is running well and storing data to the database. The problem is that, if I switch ON the button the value 1 is stored in the database, but when I switch OFF the button the value 0 is not stored in the database.

Here is my arduino code:

//Arduino Code
#include <SoftwareSerial.h>

SoftwareSerial s(5,6);//Rx,Tx
int buttonPinBulb = 11;
int relay1 = 10;
int buttonBulb;
int currentStatus = LOW;
unsigned long lastMillis = 0;
const unsigned long debounceTime = 100;

void setup() {
  // put your setup code here, to run once:
  pinMode(buttonPinBulb, INPUT_PULLUP);
  pinMode(relay1, OUTPUT);
  s.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
  buttonBulb = digitalRead(buttonPinBulb);
  bulbOnOff(buttonBulb);
}

int bulbOnOff(int buttonBulb) {
  unsigned long currentMillis = millis();
  // protect against overflow
  if ( (currentMillis - lastMillis > debounceTime) || (currentMillis < lastMillis)) {

    if (buttonBulb != currentStatus) {
      digitalWrite(relay1, buttonBulb);
      //Serial.println(!buttonBulb);
      currentStatus = buttonBulb;

      // update database here
      if(s.available()>0)
            {
            s.write(!buttonBulb);
            }

      lastMillis = currentMillis;
    }
  }
  return 0;
}

The following is nodeMCU ESP8266 code

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

SoftwareSerial s(D6, D5); //RX,TX
int buttonBulb;
int Led_OnBoard = 2;
const char* ssid = "iPhone";                  // Your wifi Name
const char* password = "Qaser.shah.123";          // 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:
  wifiConnection();
  s.begin(115200);
}

int wifiConnection() {
  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
  Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
  s.write("s");
  if (s.available() > 0)
  {
    buttonBulb = s.read();
    Serial.println(buttonBulb);
    int result = updateDatabase(buttonBulb);
    if(result != 0){
      //error updating database
      Serial.print("error updating database");
      }
  }
}

int updateDatabase(int buttonBulb){
    HTTPClient http;    //Declare object of class HTTPClient

  //String ButtonState;
  String buttonValueSend, postData;
  
  buttonValueSend = String(buttonBulb);   //String to interger conversion
 
  //Post Data
  postData = "buttonBulb=" + 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(httpCode);   //Print HTTP return code
  Serial.println(payload);    //Print request response payload
  Serial.println("Button Value send=" + buttonValueSend);

  http.end();  //Close connection
  return 0;
  }

The following is my php code which stores the Arduino data

<?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['buttonBulb']))
    {
        $buttonBulb = $_POST['buttonBulb'];
        
        $sql = "INSERT INTO project (ButtonState, Date, Time) VALUES ('".$buttonBulb."', '".$d."', '".$t."')"; //nodemcu_ldr_table = Youre_table_name

        if ($conn->query($sql) === TRUE) {
            echo "OK";
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
    }

    $conn->close();
?>

See the image of output enter image description here In this image OK is printing at Value 1 but not printing OK at value 0

I think there is something wrong or I forgot something, that is why it is not happening.

Thanks a lot for any appericiation.

1
  • @Dharman Thank you for the suggestion. I will use it when my project complete. For the time being I am just using escap sequences. Commented Oct 11, 2020 at 5:11

2 Answers 2

1

You can create a separate function to update the database and only call the update when the button state is changed.

Combined with my answer on your previous question it would look like this:

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
}
Sign up to request clarification or add additional context in comments.

7 Comments

will this update the database without using NodeMCU ESP8266?
@TinyCoder I just copied a small part of your database code as an example. Since you have that already working, all you need to do is put that code in the updateDatabase() function and call it from loop() when the button status changes.
Thank you for the help. It is working but there is a little problem I am facing. Can you help me more? Or may I ask another question about this problem?
@TinyCoder What is the problem?
The database storing the value when I switch ON but When I switch OFF, it is not storing. However the value, both ON and OFF printing on serial monitor.
|
0

I have found the problem. The problem was in my php code that is why the 1 will stored in the database but 0 would not.

Here is what I have change in php code I just removed if(!empty(&_POST['buttonBulb'])){} The code that was used in if statement now it is outside from if statement. Reason The behind that, when I send 1 to this code it is OK but if send 0 the is statement assumes there is no value and buttonBulb variable is empty.

Thankyou all of you who help me in this code. Now I am going to next step of this project and if I have some problems I will ask.

Specially thanks to @Danny_ds

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.