{"id":21,"date":"2025-01-26T13:27:05","date_gmt":"2025-01-26T13:27:05","guid":{"rendered":"https:\/\/blogs.stei.itb.ac.id\/waskita\/?p=21"},"modified":"2025-01-26T13:46:24","modified_gmt":"2025-01-26T13:46:24","slug":"analyzing-esp32-code","status":"publish","type":"post","link":"https:\/\/blogs.stei.itb.ac.id\/waskita\/2025\/01\/26\/analyzing-esp32-code\/","title":{"rendered":"Analyzing ESP32 Code"},"content":{"rendered":"\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"960\" height=\"1280\" src=\"https:\/\/blogs.stei.itb.ac.id\/waskita\/wp-content\/uploads\/sites\/2\/2025\/01\/esp32-with-switch.jpg\" alt=\"\" class=\"wp-image-24\"\/><\/figure>\n\n\n\n<p>Let&#8217;s  analyze a short ESP32 Wifi code with DeepSeek R1<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ https:\/\/docs.arduino.cc\/libraries\/httpclient\/\n\/\/ receiving JSON POST https:\/\/www.geeksforgeeks.org\/how-to-receive-json-post-with-php\/\n\n#include &lt;ArduinoJson.h&gt;\n#include &lt;HTTPClient.h&gt;\n#include &lt;WiFiMulti.h&gt;\n\nconst char *AP_SSID = \"AP_NAME\";\nconst char *AP_PWD = \"AP_PASSWORD\";\n\nvoid setup() {\n  Serial.begin(115200);\n\n  WiFi.begin(AP_SSID, AP_PWD);\n  while (WiFi.status() != WL_CONNECTED) {\n    delay(1000);\n    Serial.println(\"Connecting to WiFi...\");\n  }\n  Serial.println(\"Connected to WiFi\");\n  Serial.print(\"ESP32 Web Server's IP address: \");\n  Serial.println(WiFi.localIP());\n}\n\nvoid loop() {\n  postDataToServer();\n  delay(10000);  \/\/ delay 10 seconds\n}\n\nint counter=0;\n\nvoid postDataToServer() {\n\n  Serial.println(\"Posting JSON data to server...\");\n  \/\/ Block until we are able to connect to the WiFi access point\n  if (WiFi.status() == WL_CONNECTED) {\n\n    HTTPClient http;\n\n    http.begin(\"http:\/\/192.168.0.115\/post_json.php\");\n    http.addHeader(\"Content-Type\", \"application\/json\");\n\n    StaticJsonDocument&lt;200&gt; doc;\n    \/\/ Add values in the document\n    \/\/\n    doc&#91;\"sensor\"] = \"gps\";\n    doc&#91;\"time\"] = 1351824120;\n    doc&#91;\"counter\"] = counter;\n    counter++;\n\n    \/\/ Add an array.\n    \/\/\n    JsonArray data = doc.createNestedArray(\"data\");\n    data.add(48.756080);\n    data.add(2.302038);\n\n    String requestBody;\n    serializeJson(doc, requestBody);\n\n    int httpResponseCode = http.POST(requestBody);\n\n    if (httpResponseCode &gt; 0) {\n\n      String response = http.getString();\n\n      Serial.println(httpResponseCode);\n      Serial.println(response);\n\n    } else {\n      Serial.print(\"error code\");\n      Serial.print(httpResponseCode);\n      \/\/ error codes from https:\/\/github.com\/amcewen\/HttpClient\/blob\/master\/HttpClient.h\n      \/\/ static const int HTTP_ERROR_CONNECTION_FAILED =-1;\n      \/\/ static const int HTTP_ERROR_API =-2;\n      \/\/ static const int HTTP_ERROR_TIMED_OUT =-3;\n      \/\/ static const int HTTP_ERROR_INVALID_RESPONSE =-4;\n    }\n  }\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Prompt<\/h2>\n\n\n\n<p>Analyze the following ESP32 code:<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Chain of Thought<\/h2>\n\n\n\n<p>Okay, I&#8217;m trying to understand this ESP32 code that someone provided. Let me go through it step by step.<\/p>\n\n\n\n<p>First, the code starts with some includes: ArduinoJson for handling JSON data, HTTPClient for making HTTP requests, and WiFiMulti for connecting to Wi-Fi. That makes sense because the code is sending data over the internet.<\/p>\n\n\n\n<p>In the setup function, they initialize the serial port at 115200 baud. Then they try to connect to a Wi-Fi network using the SSID and password stored in AP_SSID and AP_PWD. There&#8217;s a while loop that waits until the connection is successful, printing dots or messages while waiting. Once connected, it prints the local IP address. That seems standard for ESP32 sketches.<\/p>\n\n\n\n<p>Moving on to the loop function, it calls postDataToServer every 10 seconds. So this is where all the data sending happens periodically.<\/p>\n\n\n\n<p>The postDataToServer function first checks if the WiFi connection is active. If so, it creates an HTTPClient object and starts a POST request to &#8220;http:\/\/192.168.0.115\/post_json.php&#8221;. The Content-Type header is set to application\/json, which is correct for sending JSON data.<\/p>\n\n\n\n<p>They create a StaticJsonDocument with 200 bytes size. Then they add some key-value pairs: &#8220;sensor&#8221; as &#8220;gps&#8221;, &#8220;time&#8221; as a specific timestamp, and &#8220;counter&#8221; which increments each time. There&#8217;s also an array called &#8220;data&#8221; with two float values, probably latitude and longitude.<\/p>\n\n\n\n<p>They serialize the JSON document into a String called requestBody. This is important because it converts the structured data into a string that can be sent over HTTP.<\/p>\n\n\n\n<p>Then they send a POST request using http.POST(requestBody). The response code is stored in httpResponseCode. If the response code is positive (meaning success), they read the server&#8217;s response and print both the code and the message. Otherwise, they handle errors by printing an error code, which includes possible connection issues or timeouts.<\/p>\n\n\n\n<p>I think this code should work if everything is set up correctly. The ESP32 connects to Wi-Fi, sends JSON data every 10 seconds, and handles responses or errors appropriately. But I wonder about a few things:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Error handling: It checks for httpResponseCode &gt; 0, but what are the possible success codes? Usually, 200 is OK, but other 2xx codes could also be valid. So maybe checking if it&#8217;s between 200 and 299 would be better.<\/li>\n\n\n\n<li>Buffer size: The StaticJsonDocument uses 200 bytes. If the JSON data grows larger than that, it might cause issues or overflow. Maybe dynamic memory allocation with JsonDocument could be safer, but I know that&#8217;s more complex.<\/li>\n\n\n\n<li>IP address and endpoint: They&#8217;re using a local IP (192.168.0.115) which is fine for testing on the same network. But in a real setup, they might want to use a public URL or set up port forwarding.<\/li>\n\n\n\n<li>Security: The Wi-Fi credentials are hardcoded. In production, it&#8217;s better to have them stored securely or read from another source without exposing them in the code.<\/li>\n\n\n\n<li>Memory management: Since it&#8217;s using StaticJsonDocument, which is allocated on the stack, and assuming 200 bytes is enough, but for larger data, this could be a problem.<\/li>\n\n\n\n<li>Counter variable: The counter increments each time postDataToServer is called, so it should correctly track how many times data has been sent. But since it&#8217;s an int, after about 4 billion increments, it would overflow. That&#8217;s probably not an issue here but something to consider for long-term use.<\/li>\n\n\n\n<li>Delay in loop: They have a delay of 10 seconds between each POST. This is manageable as the ESP32 can handle that without issues.<\/li>\n<\/ol>\n\n\n\n<p>I think this code is a good starting point for sending JSON data from ESP32 to a server. It covers connecting to Wi-Fi, creating and sending JSON, handling HTTP responses, and error checking. However, there might be improvements in terms of robustness, security, and resource management depending on the specific use case.<\/p>\n\n\n\n<p>If I were to run this code, I&#8217;d need to make sure my ESP32 is connected to the same network as the server running post_json.php at 192.168.0.115. Also, I should have PHP installed and set up correctly on that server to handle incoming POST requests and process the JSON data.<\/p>\n\n\n\n<p>Another thing to note is that in some environments, especially if the ESP32 is behind a router or firewall, the POST request might be blocked unless the necessary ports are open. So ensuring that the server is accessible from the ESP32&#8217;s network is crucial.<\/p>\n\n\n\n<p>I think I&#8217;ve covered the main points of this code. It seems straightforward but effective for its intended purpose.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Answer<\/h2>\n\n\n\n<p>The provided ESP32 code is designed to connect to a Wi-Fi network, periodically send JSON data via an HTTP POST request to a specified server endpoint, and handle responses or errors accordingly. Here&#8217;s a detailed analysis:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Key Components and Functionality:<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong class=\"\">Wi-Fi Connection Setup:<\/strong>\n<ul class=\"wp-block-list\">\n<li>The sketch connects to a predefined Wi-Fi network using&nbsp;<code>AP_SSID<\/code>&nbsp;(SSID) and&nbsp;<code>AP_PWD<\/code>&nbsp;(password).<\/li>\n\n\n\n<li>It waits until the connection is established, printing status messages during the process.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong class=\"\">HTTP POST Request with JSON Data:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Every 10 seconds,&nbsp;<code>postDataToServer()<\/code>&nbsp;sends a POST request to &#8220;http:\/\/192.168.0.115\/post_json.php&#8221;.<\/li>\n\n\n\n<li>A JSON payload is constructed with fields including sensor type, timestamp, counter (incrementing each time), and an array of two float values.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong class=\"\">JSON Construction:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Uses&nbsp;<code>ArduinoJson<\/code>&nbsp;library to build a JSON document, ensuring structured data before serialization into a string for transmission.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong class=\"\">Response Handling:<\/strong>\n<ul class=\"wp-block-list\">\n<li>The server&#8217;s response is captured if the HTTP request succeeds (indicated by a positive status code).<\/li>\n\n\n\n<li>Error codes are logged if the request fails, providing insight into potential issues like connection problems or timeouts.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Considerations and Enhancements:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong class=\"\">Error Code Handling:<\/strong>&nbsp;While the current implementation checks for positive responses, it might benefit from handling specific success ranges (e.g., 200-299) to better interpret server responses.<\/li>\n\n\n\n<li><strong class=\"\">Buffer Management:<\/strong>&nbsp;The&nbsp;<code>StaticJsonDocument&lt;200&gt;<\/code>&nbsp;uses a fixed buffer size. If the JSON data exceeds this, consider using dynamic memory allocation with&nbsp;<code>DynamicJsonDocument<\/code>&nbsp;for scalability.<\/li>\n\n\n\n<li><strong class=\"\">Network Configuration:<\/strong>&nbsp;Ensure the server at 192.168.0.115 is reachable from the ESP32&#8217;s network. For external access, use a public URL and configure port forwarding if necessary.<\/li>\n\n\n\n<li><strong class=\"\">Security Practices:<\/strong>&nbsp;Avoid hardcoding sensitive information like Wi-Fi credentials in production. Consider secure storage methods or alternative credential retrieval mechanisms.<\/li>\n\n\n\n<li><strong class=\"\">Memory Concerns:<\/strong>&nbsp;Be mindful of buffer sizes to prevent overflow, especially with larger datasets.<\/li>\n\n\n\n<li><strong class=\"\">Counter Management:<\/strong>&nbsp;The integer counter will eventually overflow after ~4 billion increments. Depending on usage duration, consider using a larger data type or reset mechanism.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion:<\/h3>\n\n\n\n<p>This code effectively demonstrates sending JSON data from an ESP32 to a server via HTTP POST. It is suitable for testing and small-scale applications but may require enhancements for production environments, such as improved security, robust error handling, and efficient memory management.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Let&#8217;s analyze a short ESP32 Wifi code with DeepSeek R1 Prompt Analyze the following ESP32 code: Chain of Thought Okay, I&#8217;m trying to understand this ESP32 code that someone provided. Let me go through it step by step. First, the code starts with some includes: ArduinoJson for handling JSON data, HTTPClient for making HTTP requests, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":24,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-21","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/blogs.stei.itb.ac.id\/waskita\/wp-json\/wp\/v2\/posts\/21","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blogs.stei.itb.ac.id\/waskita\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.stei.itb.ac.id\/waskita\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.stei.itb.ac.id\/waskita\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.stei.itb.ac.id\/waskita\/wp-json\/wp\/v2\/comments?post=21"}],"version-history":[{"count":3,"href":"https:\/\/blogs.stei.itb.ac.id\/waskita\/wp-json\/wp\/v2\/posts\/21\/revisions"}],"predecessor-version":[{"id":25,"href":"https:\/\/blogs.stei.itb.ac.id\/waskita\/wp-json\/wp\/v2\/posts\/21\/revisions\/25"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blogs.stei.itb.ac.id\/waskita\/wp-json\/wp\/v2\/media\/24"}],"wp:attachment":[{"href":"https:\/\/blogs.stei.itb.ac.id\/waskita\/wp-json\/wp\/v2\/media?parent=21"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.stei.itb.ac.id\/waskita\/wp-json\/wp\/v2\/categories?post=21"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.stei.itb.ac.id\/waskita\/wp-json\/wp\/v2\/tags?post=21"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}