Hello,
first of all i have my arduino that is connected via Wifi with my Web Server.
The Arduino is used as a recylingcenter, and should give me a value of the Scale.
But somehow the Get/Post Parameter from my .PHP file that im using to retrieve the data, isnt sending it and it always says Undefined array key in my WebServer when i look under error.log.
Arduino.ino
`#include "SSD1306Wire.h"
#include "HX711.h"
#include <ESP32QRCodeReader.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <Bounce2.h>
//Debounce switch
#define BUTTON_PIN 12
Bounce2::Button button = Bounce2::Button();
//Scheduler
#include <TaskScheduler.h>
//**************** Defining variables and constants ************
// I/O
#define OUT1 16
#define IN1 12
#define FLASHLIGHT 4
// OLED Display
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define I2C_SDA 13
#define I2C_SCL 15
#define OLED_ADDR 0x3C
SSD1306Wire display(OLED_ADDR, I2C_SDA, I2C_SCL);
// QR
ESP32QRCodeReader reader(CAMERA_MODEL_AI_THINKER);
struct QRCodeData qrCodeData;
String Payload = "NULL";
//Weighting
#define HX711_SCK 14
#define HX711_DOUT 2
HX711 SCALE;
int new_weight = 0;
int old_weight = -1;
int MEASURE = 0;
//linear equation f(x)=ax+b (set first values to one (a=1, b=0))
int scale_scale = 811; //=a (515)
int scale_offset = 4420; // =-b (2)
//ID of balance
String idBalance = "11";
String state = "Scanning";
// WIFI
const char *ssid = "INSEL"; //REPLACE_WITH_YOUR_SSID
const char *password = "nootherperson"; //REPLACE_WITH_YOUR_PASSWORD
WiFiClient espClient;
//Your Domain name with URL path or IP address with path
String host = "http://172.17.248.90";
String file_to_access = "/includes/ReceivingScript.php";
String URL = host + file_to_access;
//Scheduler
Scheduler ts;
void switchStatus();
void onQrCodeTask();
// Tasks
// Task taskSwitch runs every 50 milliseconds forever and adding task to the chain on creation
Task taskSwitch(50, TASK_FOREVER, &switchStatus, &ts, true);
Task taskQR(100, TASK_FOREVER, &onQrCodeTask, &ts, true);
//************************************************** Basic functions ********************************************
//Function to show 3 lines (given as parameters) on the OLED display
void showOLEDMessage(String line1, String line2, String line3) {
display.init(); // clears screen
display.flipScreenVertically();
display.setFont(ArialMT_Plain_16);
display.drawString(0, 0, line1); // adds to buffer
display.drawString(0, 20, line2);
display.drawString(0, 40, line3);
display.display(); // displays content in buffer
}
//Function to connect to WIFI
void wifi_connect() {
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
Serial.print("Attempting to connect");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
showOLEDMessage("Connecting", "...", "");
}
showOLEDMessage("WIFI", "connected", "");
delay(1000);
}
//Function initialising and calibrating the scale
void SCALE_INIT() {
SCALE.begin(HX711_DOUT, HX711_SCK);
SCALE.power_down();
SCALE.power_up();
while (SCALE.is_ready() != 1) {
//HX711 not found
}
//HX711 ready!
SCALE.set_scale(scale_scale);
SCALE.set_offset(scale_offset);
SCALE.tare();
}
//Function to get the measurement of the weight
int SCALE_GET() {
new_weight = SCALE.get_units(10);
if (new_weight != old_weight) {
return (new_weight);
}
}
//************************************************** Checking status of switch ********************************************
//Function to check the status of the switch and trigger the according action
void switchStatus() {
button.update();
if (button.pressed()){
//based on the current state start QR-code or measuring of weight
if (state == "Scanning" && Payload == "NULL" && !taskQR.isEnabled()) {
showOLEDMessage("Reading", "QR", "Code");
reader.beginOnCore(1);
taskQR.enable();
taskSwitch.abort();
} else if (state == "Measuring" && !taskQR.isEnabled()) {
startWeighting();
}
}
}
//************************************************** Start weighting process *******************************************
void startWeighting() {
MEASURE = SCALE_GET(); //get the measurement
if (MEASURE != 0) {
showOLEDMessage("2. Weight:", String(MEASURE), "g");
delay(1000);
// Transfer data
showOLEDMessage("3. Transfer", "QR " + Payload, String(MEASURE) + " g");
delay(2000);
String response = httpGETConfirm(Payload, String(MEASURE));
Serial.println("Response from server: " + response); // Debugging output
showOLEDMessage("4. Remove", "your", "trash!");
Payload = "NULL";
state = "Scanning";
delay(2000);
showOLEDMessage("1. Press switch", "to start reading", "QR-code");
} else {
showOLEDMessage("No trash measured", "1.Put your Trash", "2.Press switch");
}
}
//************************************************** QR Code Scanner ********************************************
void onQrCodeTask() {
taskSwitch.disable();
struct QRCodeData qrCodeData;
if (reader.receiveQrCode(&qrCodeData, 100) && qrCodeData.valid) {
Payload = ((const char *)qrCodeData.payload);
if (Payload != "NULL") {
reader.end();
taskQR.disable();
//check if access granted
if (httpGETAuthentication(Payload) == "access granted") {
SCALE_INIT();
state = "Measuring";
showOLEDMessage("Access granted", "for", Payload);
delay(2000);
showOLEDMessage(Payload, "1.Put your Trash", "2.Press switch");
} else {
state = "Scanning";
Payload = "NULL";
showOLEDMessage("Access denied", "press Switch", "to read again");
}
}
}
taskSwitch.enable();
}
//************************************************** Communication with server ********************************************
//Function sending a request with the measured weight and QR code to the server and receive an answer
String httpGETConfirm(String pQR, String pWeight) {
String status = "";
//Check WiFi connection status
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = URL + "?QRCodeMeasure=" + pQR + "&hostname=" + idBalance + "&measuredValue=" + pWeight;
http.begin(url); // Specify the target URL
// Send the GET request
int httpResponseCode = http.GET();
//save the HTTP response from the server.
if (httpResponseCode > 0) {
//HTTP response code:
String payload_response = http.getString();
status = payload_response;
} else {
status = "Error code: " + String(httpResponseCode);
}
// Free resources
http.end();
} else {
status = "WiFi Disconnected";
}
showOLEDMessage("Server reply:", status, "");
delay(1000);
return status;
}
//Function sending a request to the server and getting the user authenticated based on the QR code
//Reply from server: access granted or access denied
String httpGETAuthentication(String pQR) {
String status = "";
//Check WiFi connection status
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = URL + "?QRCodeAuthenticate=" + pQR;
http.begin(url); // Specify the target URL
// Send the GET request
int httpResponseCode = http.GET();
//save the HTTP response from the server.
if (httpResponseCode > 0) {
//HTTP response code:
String payload_response = http.getString();
status = payload_response;
} else {
status = "Error code: " + String(httpResponseCode);
}
http.end(); // Free resources
} else {
status = "WiFi Disconnected";
}
showOLEDMessage("Server reply:", status, "");
return status;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(FLASHLIGHT, OUTPUT);
//Debounce the switch
button.attach(BUTTON_PIN, INPUT);
// Debounce interval in milliseconds
button.interval(5);
// Indicate that the low state corresponds to physically pressing the switch
button.setPressedState(LOW);
//Flashing light when starting up
digitalWrite(FLASHLIGHT, HIGH);
delay(100);
digitalWrite(FLASHLIGHT, LOW);
taskQR.disable();
showOLEDMessage("", "Startup", "");
delay(1000);
wifi_connect();
reader.setup();
showOLEDMessage("Press switch", "to start reading", "QR-code");
}
void loop() {
// put your main code here, to run repeatedly:
ts.execute();
}
`
ReceivingScript.php
`<?php
$dbc = f_db_connect();
// Check if connection was successful
if ($dbc->connect_error) {
die("Connection failed: " . $dbc->connect_error);
}
// Initialize variables
$access = "";
$QRCodeMeasure = $_GET['QRCodeMeasure'] ?? ''; // Get the QR code measure from the GET request
$hostname = $_GET['hostname'] ?? ''; // Get the hostname from the GET request
$value = $_GET['measuredValue'] ?? ''; // Get the measured value from the GET request
// Check if any required parameter is empty
if (empty($QRCodeMeasure) || empty($hostname) || empty($value)) {
die("Missing parameters in the request.");
}
// Check if the QR code is authorized
$queryCheckAccess = "SELECT * FROM tblBenutzer WHERE dtRandomCode = '$QRCodeMeasure'";
$resultCheckAccess = $dbc->query($queryCheckAccess);
if ($resultCheckAccess->num_rows > 0) {
echo "access granted";
$access = "granted";
} else {
echo "Access denied: QR code not authorized.";
$access = "denied";
}
// If access is granted, insert data into the database
if ($access == "granted") {
// Get the current timestamp
date_default_timezone_set('UTC');
$time = date('Y-m-d H:i:s');
// Insert data into the database
$sql = "INSERT INTO tblAbfall (idAbfall, dtGewicht, dtDatum, fiAbfallTyp, fiRechnung, fiMessstation, fiBenutzer)
VALUES (NULL, '$value', '$time', 'PLA', 2, 2, '$hostname')";
// Execute the SQL query
if ($dbc->query($sql) === TRUE) {
echo "Data inserted successfully.";
} else {
echo "Error: " . $sql . "<br>" . $dbc->error;
}
}
// Close the database connection
$dbc->close();
?>`
Error.log