pleasedontcode

# Temperature Logger rev_04

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