pleasedontcode

# WiFi Data Logger rev_01

Jan 13th, 2026
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /********* Pleasedontcode.com **********
  2.  
  3.     Pleasedontcode thanks you for automatic code generation! Enjoy your code!
  4.  
  5.     - Terms and Conditions:
  6.     You have a non-exclusive, revocable, worldwide, royalty-free license
  7.     for personal and commercial use. Attribution is optional; modifications
  8.     are allowed, but you're responsible for code maintenance. We're not
  9.     liable for any loss or damage. For full terms,
  10.     please visit pleasedontcode.com/termsandconditions.
  11.  
  12.     - Project: # WiFi Data Logger
  13.     - Source Code NOT compiled for: Arduino Nano
  14.     - Source Code created on: 2026-01-13 08:09:52
  15.  
  16. ********* Pleasedontcode.com **********/
  17.  
  18. /****** SYSTEM REQUIREMENTS *****/
  19. /****** SYSTEM REQUIREMENT 1 *****/
  20.     /* Establezca una conexión WiFi usando la biblioteca */
  21.     /* WiFiEspAT en Arduino Nano y realice solicitudes de */
  22.     /* cliente HTTP para transmitir datos al servicio en */
  23.     /* la nube de Excel usando ArduinoHttpClient. */
  24. /****** END SYSTEM REQUIREMENTS *****/
  25.  
  26.  
  27. /****** DEFINITION OF LIBRARIES *****/
  28. #include <WiFiEspAT.h>          // Compatible with Arduino Nano using ESP8266/ESP32 as WiFi module
  29. #include <ArduinoHttpClient.h>  // Compatible with Arduino Nano for HTTP requests
  30.  
  31. /****** DEFINITION OF CONSTANTS *****/
  32. // WiFi credentials
  33. const char* ssid = "Despacho 2.4";                           // Replace with your router SSID
  34. const char* password = "Nabucodonosor33";                    // Replace with your router password
  35.  
  36. // Google Sheets API endpoint
  37. const char* host = "script.google.com";
  38. const int port = 443;  // HTTPS port
  39. const char* scriptId = "AKfycbx0EOD-SCOrNhGs2lFm3gV3dZPP9_oqAbImZEhhzojHJEIgrE2XOdH7OMA8DMAuhEmg";  // Your Google Apps Script ID
  40.  
  41. // Timing constants (in milliseconds)
  42. const unsigned long TRANSMISSION_INTERVAL = 10000;  // 10 seconds between data transmissions
  43. const unsigned long WIFI_TIMEOUT = 10000;            // WiFi connection timeout
  44. const unsigned long HTTP_TIMEOUT = 5000;             // HTTP request timeout
  45.  
  46. /****** GLOBAL VARIABLES *****/
  47. // WiFi and HTTP client instances
  48. WiFiClientSecure client;
  49. HttpClient httpClient = HttpClient(client, host, port);
  50.  
  51. // Timing variables
  52. unsigned long lastTransmissionTime = 0;
  53. unsigned long wifiConnectionStartTime = 0;
  54.  
  55. // WiFi status flag
  56. boolean wifiConnected = false;
  57.  
  58. /****** FUNCTION PROTOTYPES *****/
  59. void setup(void);
  60. void loop(void);
  61. void initializeSerialCommunication(void);
  62. void initializeWiFiConnection(void);
  63. void checkWiFiStatus(void);
  64. void sendDataToGoogleSheets(float temperature, float humidity);
  65. void printDebugMessage(const char* message);
  66. void printIPAddress(void);
  67.  
  68. /****** INITIALIZATION FUNCTION *****/
  69. void setup(void)
  70. {
  71.     // Initialize serial communication
  72.     initializeSerialCommunication();
  73.    
  74.     // Print startup message
  75.     printDebugMessage("=== WiFi HTTP Cloud Data Transmission System Started ===");
  76.    
  77.     // Initialize WiFi connection
  78.     initializeWiFiConnection();
  79. }
  80.  
  81. /****** MAIN LOOP FUNCTION *****/
  82. void loop(void)
  83. {
  84.     // Check WiFi connection status
  85.     checkWiFiStatus();
  86.    
  87.     // Check if it's time to transmit data
  88.     if (wifiConnected && (millis() - lastTransmissionTime >= TRANSMISSION_INTERVAL)) {
  89.         // Update transmission time
  90.         lastTransmissionTime = millis();
  91.        
  92.         // Generate sample sensor data
  93.         float temperature = generateTemperatureData();
  94.         float humidity = generateHumidityData();
  95.        
  96.         // Print sensor data
  97.         printSensorData(temperature, humidity);
  98.        
  99.         // Send data to Google Sheets
  100.         sendDataToGoogleSheets(temperature, humidity);
  101.     }
  102.    
  103.     // Short delay to prevent overwhelming the loop
  104.     delay(100);
  105. }
  106.  
  107. /****** SERIAL COMMUNICATION INITIALIZATION *****/
  108. void initializeSerialCommunication(void)
  109. {
  110.     // Initialize serial communication at 9600 baud
  111.     Serial.begin(9600);
  112.    
  113.     // Wait for serial port to be ready
  114.     delay(2000);
  115. }
  116.  
  117. /****** WIFI CONNECTION INITIALIZATION *****/
  118. void initializeWiFiConnection(void)
  119. {
  120.     printDebugMessage("Initiating WiFi connection...");
  121.     Serial.print("Connecting to SSID: ");
  122.     Serial.println(ssid);
  123.    
  124.     // Start WiFi connection using WiFiEspAT
  125.     WiFi.begin(ssid, password);
  126.    
  127.     // Store connection start time for timeout handling
  128.     wifiConnectionStartTime = millis();
  129.    
  130.     // Wait for connection with timeout
  131.     int connectionAttempts = 0;
  132.     int maxAttempts = 40;  // 40 attempts * 500ms = 20 seconds max
  133.    
  134.     while (WiFi.status() != WL_CONNECTED && connectionAttempts < maxAttempts) {
  135.         delay(500);
  136.         Serial.print(".");
  137.         connectionAttempts++;
  138.        
  139.         // Check timeout
  140.         if (millis() - wifiConnectionStartTime > WIFI_TIMEOUT) {
  141.             break;
  142.         }
  143.     }
  144.    
  145.     Serial.println();
  146.    
  147.     // Verify connection status
  148.     if (WiFi.status() == WL_CONNECTED) {
  149.         wifiConnected = true;
  150.         printDebugMessage("WiFi connected successfully!");
  151.         printIPAddress();
  152.     } else {
  153.         wifiConnected = false;
  154.         printDebugMessage("Failed to connect to WiFi after timeout");
  155.     }
  156. }
  157.  
  158. /****** WIFI STATUS CHECKING *****/
  159. void checkWiFiStatus(void)
  160. {
  161.     // Check current WiFi connection status
  162.     if (WiFi.status() == WL_CONNECTED) {
  163.         if (!wifiConnected) {
  164.             // Connection was re-established
  165.             wifiConnected = true;
  166.             printDebugMessage("WiFi reconnected!");
  167.             printIPAddress();
  168.         }
  169.     } else {
  170.         if (wifiConnected) {
  171.             // Connection was lost
  172.             wifiConnected = false;
  173.             printDebugMessage("WiFi connection lost!");
  174.            
  175.             // Attempt to reconnect
  176.             printDebugMessage("Attempting to reconnect to WiFi...");
  177.             WiFi.begin(ssid, password);
  178.             wifiConnectionStartTime = millis();
  179.         }
  180.     }
  181. }
  182.  
  183. /****** GENERATE TEMPERATURE DATA *****/
  184. float generateTemperatureData(void)
  185. {
  186.     // Generate random temperature between 20.0 - 30.0 degrees Celsius
  187.     float temperature = random(200, 300) / 10.0;
  188.     return temperature;
  189. }
  190.  
  191. /****** GENERATE HUMIDITY DATA *****/
  192. float generateHumidityData(void)
  193. {
  194.     // Generate random humidity between 40.0 - 60.0 percent
  195.     float humidity = random(400, 600) / 10.0;
  196.     return humidity;
  197. }
  198.  
  199. /****** PRINT SENSOR DATA *****/
  200. void printSensorData(float temperature, float humidity)
  201. {
  202.     Serial.println("\n========================================");
  203.     Serial.println("--- Sensor Data ---");
  204.     Serial.print("Temperature: ");
  205.     Serial.print(temperature);
  206.     Serial.println(" °C");
  207.     Serial.print("Humidity: ");
  208.     Serial.print(humidity);
  209.     Serial.println(" %");
  210.     Serial.println("========================================");
  211. }
  212.  
  213. /****** SEND DATA TO GOOGLE SHEETS *****/
  214. void sendDataToGoogleSheets(float temperature, float humidity)
  215. {
  216.     // Verify WiFi connection before attempting to send
  217.     if (WiFi.status() != WL_CONNECTED) {
  218.         printDebugMessage("ERROR: WiFi not connected. Cannot send data.");
  219.         return;
  220.     }
  221.    
  222.     printDebugMessage("Transmitting data to Google Sheets...");
  223.    
  224.     // Create URL encoded parameters for GET request
  225.     String parameters = "?temperatura=";
  226.     parameters += String(temperature);
  227.     parameters += "&humedad=";
  228.     parameters += String(humidity);
  229.     parameters += "&timestamp=";
  230.     parameters += String(millis());
  231.    
  232.     // Build the complete path
  233.     String pathWithParameters = "/macros/s/";
  234.     pathWithParameters += scriptId;
  235.     pathWithParameters += "/exec";
  236.     pathWithParameters += parameters;
  237.    
  238.     Serial.print("Path: ");
  239.     Serial.println(pathWithParameters);
  240.    
  241.     // Begin HTTP GET request
  242.     httpClient.setTimeout(HTTP_TIMEOUT);
  243.    
  244.     // Make GET request (simpler than POST for this use case)
  245.     int httpCode = httpClient.get(pathWithParameters);
  246.    
  247.     // Print HTTP response code
  248.     Serial.print("HTTP Response Code: ");
  249.     Serial.println(httpCode);
  250.    
  251.     // Read and print response body
  252.     if (httpCode > 0) {
  253.         String responseBody = httpClient.responseBody();
  254.         Serial.print("Server Response: ");
  255.         Serial.println(responseBody);
  256.        
  257.         if (httpCode == 200) {
  258.             printDebugMessage("Data successfully transmitted to Google Sheets!");
  259.         } else {
  260.             printDebugMessage("HTTP request completed with non-200 status code.");
  261.         }
  262.     } else {
  263.         Serial.print("HTTP Error: ");
  264.         Serial.println(httpCode);
  265.         printDebugMessage("ERROR: Failed to connect to server or request timed out.");
  266.     }
  267.    
  268.     // Close the connection
  269.     httpClient.stop();
  270. }
  271.  
  272. /****** PRINT DEBUG MESSAGE *****/
  273. void printDebugMessage(const char* message)
  274. {
  275.     Serial.print("[DEBUG] ");
  276.     Serial.println(message);
  277. }
  278.  
  279. /****** PRINT IP ADDRESS *****/
  280. void printIPAddress(void)
  281. {
  282.     Serial.print("IP Address: ");
  283.     Serial.println(WiFi.localIP());
  284.     Serial.print("Gateway: ");
  285.     Serial.println(WiFi.gatewayIP());
  286.     Serial.print("DNS Server: ");
  287.     Serial.println(WiFi.dnsIP());
  288. }
  289.  
  290. /* END CODE */
  291.  
Advertisement
Add Comment
Please, Sign In to add comment