i need help to upload data from sensor to mongodb atlas using arduino uno ethernet shield i was using this code and it cann’t to connect to mongodb atlasi was testing code with static values in currentReading & voltageReading
#include <SPI.h>#include <Ethernet.h>#include <ArduinoJson.h>// Define your sensor pinsconst int currentSensorPin = A0;const int voltageSensorPin = A1;// Initialize Ethernetbyte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};EthernetClient client;// MongoDB cluster hostnamechar hostname[] = "mongodb+srv://mongo:XXXXXXXXXX@cluster0.vkdjf70.mongodb.net"; // Change this to your cluster hostnamevoid setup() { Ethernet.begin(mac); Serial.begin(9600); // Initialize other setup routines}void loop() { // Read sensor values int currentReading = 21; int voltageReading = 220; // Calculate watt float watt = currentReading * voltageReading / 1000.0; // Create a JSON object to hold the data StaticJsonDocument<128> doc; doc["Timestamp"] = millis(); doc["Current"] = currentReading; doc["Voltage"] = voltageReading; doc["Watt"] = watt; // Convert JSON to string String jsonString; serializeJson(doc, jsonString); // Send data to MongoDB if (client.connect(hostname, 27017)) { client.println("POST /HEMS.HEMS1 HTTP/1.1"); client.println("Host: " + String(hostname)); client.println("Content-Type: application/json"); client.print("Content-Length: "); client.println(jsonString.length()); client.println(); client.println(jsonString); client.flush(); // Flush the data // Read the response from the server while (client.connected()) { if (client.available()) { char c = client.read(); Serial.print(c); // Print the response } } client.stop(); // Close the connection Serial.println("Data sent successfully!"); // Print success message } else { Serial.println("Error connecting to MongoDB!"); // Print error message } delay(1000);}
and i’m sure make network access to 0.0.0.0/0(databasename : HEMScollectionname: HEMS1)