I created an API here the endpoint
PUT: https://localhost:7213/api/BinLevel/PutBinById?binId=1&binStatus=3
This is working using Postman
Now, my challenges when I using arduino to update the level of the bin it is not working the api
#include <WiFiNINA.h>
#include <WiFiSSLClient.h>
#include <ArduinoHttpClient.h>
const char* ssid = "WIFI SSID";
const char* password = "WIFI PASSWORD";
const char* serverAddress = "192.168.1.13";
int port = 7213;
String apiUrl = "/api/BinLevel/PutBinById?binId=1&binStatus=";
WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
#define TRIGGER_PIN 7
#define ECHO_PIN 6
#define BIN_HEIGHT_CM 121.92
void setup() {
Serial.begin(9600);
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
connectToWiFi(ssid, password);
}
void loop() {
long duration, distance;
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = duration * 0.034 / 2;
if (distance < 0 || distance > BIN_HEIGHT_CM) {
distance = BIN_HEIGHT_CM;
}
float fillLevelPercentage = ((BIN_HEIGHT_CM - distance) / BIN_HEIGHT_CM) * 100;
int binStatus = categorizeBinStatus(fillLevelPercentage);
Serial.print("Fill Level Percentage: ");
Serial.println(fillLevelPercentage);
Serial.print("Bin Status: ");
Serial.println(binStatus);
sendBinStatusToAPI(binStatus);
delay(5000);
}
void connectToWiFi(const char* ssid, const char* password) {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("nConnected to WiFi");
}
void sendBinStatusToAPI(int binStatus) {
String fullUrl = apiUrl + binStatus;
Serial.print("API URL: ");
Serial.println(fullUrl);
client.beginRequest();
client.put(fullUrl); // Use PUT method
// client.sendHeader("Content-Type", "application/json"); // May not be necessary
client.endRequest();
int statusCode = client.responseStatusCode();
if (statusCode == 204) {
Serial.println("Bin status updated successfully");
} else {
Serial.print("Error on HTTP request: ");
Serial.println(statusCode);
String response = client.responseBody();
Serial.print("Response: ");
Serial.println(response);
}
}
int categorizeBinStatus(float fillLevelPercentage) {
if (fillLevelPercentage >= 75 && fillLevelPercentage <= 100) {
return 4;
} else if (fillLevelPercentage >= 50 && fillLevelPercentage < 75) {
return 3;
} else if (fillLevelPercentage >= 25 && fillLevelPercentage < 50) {
return 2;
} else {
return 1;
}
}
This is the serial monitor
Connected to WiFi
Fill Level Percentage: 0.75
Bin Status: 1
API URL: /api/BinLevel/PutBinById?binId=1&binStatus=1
Error on HTTP request: -3
Response:
3