pleasedontcode

# Sensor Logger rev_03

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: # Sensor Logger
  13.     - Source Code NOT compiled for: Arduino Nano
  14.     - Source Code created on: 2026-01-13 08:51:25
  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.  
  28. /****** DEFINITION OF LIBRARIES *****/
  29. // Compatible with Arduino Nano using
  30. // ESP8266/ESP32 as WiFi module
  31. #include <WiFiEspAT.h>
  32.  
  33. // Compatible with Arduino Nano for HTTP requests
  34. #include <ArduinoHttpClient.h>
  35.  
  36. /****** DEFINITION OF CONSTANTS *****/
  37. // WiFi credentials
  38. const char* ssid = "Despacho 2.4";
  39. const char* password = "Nabucodonosor33";
  40.  
  41. // Google Sheets API endpoint
  42. // Using HTTP instead of HTTPS for WiFiEspAT compatibility
  43. const char* host = "script.google.com";
  44. const int port = 80;
  45.  
  46. // Google Apps Script ID
  47. // Your unique script identifier
  48. const char* scriptId =
  49.   "AKfycbx0EOD-SCOrNhGs2lFm3gV3dZPP9_oqAbImZEhhzojHJEIgrE2XOdH7OMA8DMAuhEmg";
  50.  
  51. // Timing constants (in milliseconds)
  52. // 10 seconds between data transmissions
  53. const unsigned long TRANSMISSION_INTERVAL = 10000;
  54.  
  55. // WiFi connection timeout
  56. const unsigned long WIFI_TIMEOUT = 10000;
  57.  
  58. // HTTP request timeout
  59. const unsigned long HTTP_TIMEOUT = 5000;
  60.  
  61. /****** GLOBAL VARIABLES *****/
  62. // WiFi and HTTP client instances
  63. // Using WiFiClient instead of WiFiClientSecure
  64. WiFiClient client;
  65. HttpClient httpClient = HttpClient(client, host, port);
  66.  
  67. // Timing variables
  68. unsigned long lastTransmissionTime = 0;
  69. unsigned long wifiConnectionStartTime = 0;
  70.  
  71. // WiFi status flag
  72. boolean wifiConnected = false;
  73.  
  74. /****** FUNCTION PROTOTYPES *****/
  75. void setup(void);
  76. void loop(void);
  77. void initializeSerialCommunication(void);
  78. void initializeWiFiConnection(void);
  79. void checkWiFiStatus(void);
  80. void sendDataToGoogleSheets(float temperature, float humidity);
  81. void printDebugMessage(const char* message);
  82. void printIPAddress(void);
  83. float generateTemperatureData(void);
  84. float generateHumidityData(void);
  85. void printSensorData(float temperature, float humidity);
  86.  
  87. /****** INITIALIZATION FUNCTION *****/
  88. void setup(void)
  89. {
  90.     // Initialize serial communication
  91.     initializeSerialCommunication();
  92.    
  93.     // Print startup message
  94.     printDebugMessage(
  95.       "=== WiFi HTTP Cloud Data Transmission Started ==="
  96.     );
  97.    
  98.     // Initialize WiFi connection
  99.     initializeWiFiConnection();
  100. }
  101.  
  102. /****** MAIN LOOP FUNCTION *****/
  103. void loop(void)
  104. {
  105.     // Check WiFi connection status
  106.     checkWiFiStatus();
  107.    
  108.     // Check if it's time to transmit data
  109.     unsigned long currentTime = millis();
  110.     unsigned long timeSinceLastTransmission =
  111.       currentTime - lastTransmissionTime;
  112.    
  113.     if (wifiConnected &&
  114.         (timeSinceLastTransmission >= TRANSMISSION_INTERVAL)) {
  115.        
  116.         // Update transmission time
  117.         lastTransmissionTime = millis();
  118.        
  119.         // Generate sample sensor data
  120.         float temperature = generateTemperatureData();
  121.         float humidity = generateHumidityData();
  122.        
  123.         // Print sensor data
  124.         printSensorData(temperature, humidity);
  125.        
  126.         // Send data to Google Sheets
  127.         sendDataToGoogleSheets(temperature, humidity);
  128.     }
  129.    
  130.     // Short delay to prevent overwhelming the loop
  131.     delay(100);
  132. }
  133.  
  134. /****** SERIAL COMMUNICATION INITIALIZATION *****/
  135. void initializeSerialCommunication(void)
  136. {
  137.     // Initialize serial communication at 9600 baud
  138.     Serial.begin(9600);
  139.    
  140.     // Wait for serial port to be ready
  141.     delay(2000);
  142. }
  143.  
  144. /****** WIFI CONNECTION INITIALIZATION *****/
  145. void initializeWiFiConnection(void)
  146. {
  147.     printDebugMessage("Initiating WiFi connection...");
  148.     Serial.print("Connecting to SSID: ");
  149.     Serial.println(ssid);
  150.    
  151.     // Start WiFi connection using WiFiEspAT
  152.     WiFi.begin(ssid, password);
  153.    
  154.     // Store connection start time for timeout handling
  155.     wifiConnectionStartTime = millis();
  156.    
  157.     // Wait for connection with timeout
  158.     int connectionAttempts = 0;
  159.     // 40 attempts * 500ms = 20 seconds max
  160.     int maxAttempts = 40;
  161.    
  162.     while (WiFi.status() != WL_CONNECTED &&
  163.            connectionAttempts < maxAttempts) {
  164.         delay(500);
  165.         Serial.print(".");
  166.         connectionAttempts++;
  167.        
  168.         // Check timeout
  169.         unsigned long connectionElapsedTime =
  170.           millis() - wifiConnectionStartTime;
  171.         if (connectionElapsedTime > WIFI_TIMEOUT) {
  172.             break;
  173.         }
  174.     }
  175.    
  176.     Serial.println();
  177.    
  178.     // Verify connection status
  179.     if (WiFi.status() == WL_CONNECTED) {
  180.         wifiConnected = true;
  181.         printDebugMessage("WiFi connected successfully!");
  182.         printIPAddress();
  183.     } else {
  184.         wifiConnected = false;
  185.         printDebugMessage(
  186.           "Failed to connect to WiFi after timeout"
  187.         );
  188.     }
  189. }
  190.  
  191. /****** WIFI STATUS CHECKING *****/
  192. void checkWiFiStatus(void)
  193. {
  194.     // Check current WiFi connection status
  195.     if (WiFi.status() == WL_CONNECTED) {
  196.         if (!wifiConnected) {
  197.             // Connection was re-established
  198.             wifiConnected = true;
  199.             printDebugMessage("WiFi reconnected!");
  200.             printIPAddress();
  201.         }
  202.     } else {
  203.         if (wifiConnected) {
  204.             // Connection was lost
  205.             wifiConnected = false;
  206.             printDebugMessage("WiFi connection lost!");
  207.            
  208.             // Attempt to reconnect
  209.             printDebugMessage(
  210.               "Attempting to reconnect to WiFi..."
  211.             );
  212.             WiFi.begin(ssid, password);
  213.             wifiConnectionStartTime = millis();
  214.         }
  215.     }
  216. }
  217.  
  218. /****** GENERATE TEMPERATURE DATA *****/
  219. float generateTemperatureData(void)
  220. {
  221.     // Generate random temperature between 20.0 - 30.0 Celsius
  222.     float temperature = random(200, 300) / 10.0;
  223.     return temperature;
  224. }
  225.  
  226. /****** GENERATE HUMIDITY DATA *****/
  227. float generateHumidityData(void)
  228. {
  229.     // Generate random humidity between 40.0 - 60.0 percent
  230.     float humidity = random(400, 600) / 10.0;
  231.     return humidity;
  232. }
  233.  
  234. /****** PRINT SENSOR DATA *****/
  235. void printSensorData(float temperature, float humidity)
  236. {
  237.     Serial.println("\n========================================");
  238.     Serial.println("--- Sensor Data ---");
  239.     Serial.print("Temperature: ");
  240.     Serial.print(temperature);
  241.     Serial.println(" °C");
  242.     Serial.print("Humidity: ");
  243.     Serial.print(humidity);
  244.     Serial.println(" %");
  245.     Serial.println("========================================");
  246. }
  247.  
  248. /****** SEND DATA TO GOOGLE SHEETS *****/
  249. void sendDataToGoogleSheets(
  250.   float temperature,
  251.   float humidity
  252. )
  253. {
  254.     // Verify WiFi connection before attempting to send
  255.     if (WiFi.status() != WL_CONNECTED) {
  256.         printDebugMessage(
  257.           "ERROR: WiFi not connected. Cannot send data."
  258.         );
  259.         return;
  260.     }
  261.    
  262.     printDebugMessage("Transmitting data to Google Sheets...");
  263.    
  264.     // Create URL encoded parameters for GET request
  265.     String parameters = "?temperatura=";
  266.     parameters += String(temperature);
  267.     parameters += "&humedad=";
  268.     parameters += String(humidity);
  269.     parameters += "&timestamp=";
  270.     parameters += String(millis());
  271.    
  272.     // Build the complete path
  273.     String pathWithParameters = "/macros/s/";
  274.     pathWithParameters += scriptId;
  275.     pathWithParameters += "/exec";
  276.     pathWithParameters += parameters;
  277.    
  278.     Serial.print("Path: ");
  279.     Serial.println(pathWithParameters);
  280.    
  281.     // Begin HTTP GET request
  282.     httpClient.setTimeout(HTTP_TIMEOUT);
  283.    
  284.     // Make GET request (simpler than POST for this use case)
  285.     int httpCode = httpClient.get(pathWithParameters);
  286.    
  287.     // Print HTTP response code
  288.     Serial.print("HTTP Response Code: ");
  289.     Serial.println(httpCode);
  290.    
  291.     // Read and print response body
  292.     if (httpCode > 0) {
  293.         String responseBody = httpClient.responseBody();
  294.         Serial.print("Server Response: ");
  295.         Serial.println(responseBody);
  296.        
  297.         if (httpCode == 200) {
  298.             printDebugMessage(
  299.               "Data successfully transmitted to Google Sheets!"
  300.             );
  301.         } else {
  302.             printDebugMessage(
  303.               "HTTP request completed with non-200 status."
  304.             );
  305.         }
  306.     } else {
  307.         Serial.print("HTTP Error: ");
  308.         Serial.println(httpCode);
  309.         printDebugMessage(
  310.           "ERROR: Failed to connect or request timed out."
  311.         );
  312.     }
  313.    
  314.     // Close the connection
  315.     httpClient.stop();
  316. }
  317.  
  318. /****** PRINT DEBUG MESSAGE *****/
  319. void printDebugMessage(const char* message)
  320. {
  321.     Serial.print("[DEBUG] ");
  322.     Serial.println(message);
  323. }
  324.  
  325. /****** PRINT IP ADDRESS *****/
  326. void printIPAddress(void)
  327. {
  328.     Serial.print("IP Address: ");
  329.     Serial.println(WiFi.localIP());
  330.     Serial.print("Gateway: ");
  331.     Serial.println(WiFi.gatewayIP());
  332.     Serial.print("DNS Server: ");
  333.     Serial.println(WiFi.dnsIP());
  334. }
  335.  
  336. /* END CODE */
  337.  
Advertisement
Add Comment
Please, Sign In to add comment