Hi,
I’m a relative newbie on the IOT front, and am trying to build a project that logs data from a sensor. I’ve purchased an Arduino Un R4 Wifi board, ands have managed to connect an ultrasonic distance sensor that seems to be logging data correctly to the Serial Monitor.
The problem I am having is sending my sensor data to an Azure Web Function via a Https Pos method.
My sketch:
- Connects to my local wifi
- Logs data for 15 seconds, and then creates a JSON object
- Serialises the Json object to a string
- When I try and ‘Post’ via an HttpClient, the wheels fall off.
I have created an Azure Web Function that accepts a Post request. Testing this with PostMan works fine.
It looks like it might be the wifi client not being able to create a secure https connection, but I’m just not sure. I can’t seem to find any examples on-line and am wondering if this is an unusual path?
Does anyone have any suggestions of guidance? Below is the code I am using …
#include <ArduinoHttpClient.h>
#include <ArduinoJson.h>
#include <WiFiS3.h>
// WiFi credentials
char ssid[] = "ssid";
char pass[] = ""; // Add your WiFi password if required
// Web API server details
char serverAddress[] = "https://website.azurewebsites.net"; // Azure Function Web Site Address
int port = 443; // HTTPS port
String apiUrl = "/api/fnLevelReading?code=random_auth_code";
WiFiClient wifi; // Secure WiFi client
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
etc.
And the code to make the post is:
void pushToWebAPI(float avgdistance) {
// Create JSON object
StaticJsonDocument<200> doc;
doc["LevelReading"] = avgdistance;
doc["LevelIdentifier"] = "Sensor2"; // Change as necessary
// Serialize JSON object to string
String output;
serializeJson(doc, output);
// Post JSON data to server
Serial.println("making POST request");
String contentType = "application/json";
Serial.println(output);
Serial.println(serverAddress);
client.beginRequest();
client.post(apiUrl);
client.sendHeader("Content-Type", contentType);
client.sendHeader("Content-Length", output.length());
client.beginBody();
client.print(output);
client.endRequest();
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
Serial.println("Wait five seconds");
}