#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const int irSSwi1 = 12;
const int irSSwi2 = 13;
const int irSSwi3 = 14;
int nowAt=0;
void setup() {
Serial.begin(9600);
connectToWiFi();
pinMode(irSSwi1, INPUT);
pinMode(irSSwi2, INPUT);
pinMode(irSSwi3, INPUT);
}
void connectToWiFi() {
Serial.print("Connecting to WiFi");
WiFi.begin(ssid, password);
//WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
}
bool makeAPICall(int productId, float weight) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin("http://apiesp32.000webhostapp.com/myAPI/weight_api.php");
http.setTimeout(5000);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
String httpRequestData = "weight=" + String(weight) + "&product_id=" + String(productId);
int httpResponseCode = http.POST(httpRequestData);
if (httpResponseCode > 1) {
String response = http.getString();
Serial.println("HTTP Response code: " + String(httpResponseCode));
Serial.println("Response: " + response);
http.end();
return true;
} else {
Serial.println("Error on sending POST: " + String(httpResponseCode));
http.end();
return false;
}
} else {
Serial.println("Error in WiFi connection");
return false;
}
}
void loop() {
int irSSwi1S = digitalRead(irSSwi1);
int irSSwi2S = digitalRead(irSSwi2);
int irSSwi3S = digitalRead(irSSwi3);
if (WiFi.status() == WL_CONNECTED) {
switch (irSSwi1S) {
case HIGH:
// Serial.println("Object detected by Sensor One!");
break;
default:
if (nowAt != 1) {
Serial.println("No object detected by Sensor One.");
if (makeAPICall(1, 10)) {
nowAt = 1;
}
}
break;
}
switch (irSSwi2S) {
case HIGH:
// Serial.println("Object detected by Sensor Two!");
break;
default:
if (nowAt != 2) {
Serial.println("No object detected by Sensor Two.");
if (makeAPICall(2, 10)) {
nowAt = 2;
}
}
break;
}
switch (irSSwi3S) {
case HIGH:
// Serial.println("Object detected by Sensor Three!");
break;
default:
if (nowAt != 3) {
Serial.println("No object detected by Sensor Three.");
if (makeAPICall(3, 10)) {
nowAt = 3;
}
}
break;
}
}else{
connectToWiFi();
}
}