Arduino code, countif door sensor locked, server

Code For Galib's Project (Mamia)
 avatar
abrarhamimsajid
plain_text
a year ago
1.5 kB
7
Indexable
Never
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "<SSID>";        // Your WiFi SSID
const char* password = "<PASSWORD>";    // Your WiFi password
const char* serverUrl = "<SERVER_URL>"; // URL of the server to send data to

const int doorSensorPin = 2;  // Pin connected to the door sensor
int lockedCount = 0;

void setup() {
  Serial.begin(115200);
  pinMode(doorSensorPin, INPUT_PULLUP);
  connectToWiFi();
}

void loop() {
  int doorState = digitalRead(doorSensorPin);

  if (doorState == LOW) { // Door is locked
    lockedCount++;
    sendToServer(lockedCount);
    delay(1000); // Avoid multiple readings in quick succession
  }

  delay(100);
}

void connectToWiFi() {
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println("\nConnected to WiFi");
}

void sendToServer(int count) {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;

    http.begin(serverUrl);
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");

    String postData = "locked_count=" + String(count);
    int httpResponseCode = http.POST(postData);

    if (httpResponseCode > 0) {
      Serial.print("Data sent to server. Response code: ");
      Serial.println(httpResponseCode);
    } else {
      Serial.print("Error sending data. Error code: ");
      Serial.println(httpResponseCode);
    }

    http.end();
  }
}