Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /********* Pleasedontcode.com **********
- Pleasedontcode thanks you for automatic code generation! Enjoy your code!
- - Terms and Conditions:
- You have a non-exclusive, revocable, worldwide, royalty-free license
- for personal and commercial use. Attribution is optional; modifications
- are allowed, but you're responsible for code maintenance. We're not
- liable for any loss or damage. For full terms,
- please visit pleasedontcode.com/termsandconditions.
- - Project: # Temperature Logger
- - Source Code NOT compiled for: Arduino Nano
- - Source Code created on: 2026-01-13 08:57:45
- ********* Pleasedontcode.com **********/
- /****** SYSTEM REQUIREMENTS *****/
- /****** SYSTEM REQUIREMENT 1 *****/
- /* Establezca una conexión WiFi usando la biblioteca */
- /* WiFiEspAT en Arduino Nano y realice solicitudes de */
- /* cliente HTTP para transmitir datos al servicio en */
- /* la nube de Excel usando ArduinoHttpClient. */
- /****** END SYSTEM REQUIREMENTS *****/
- /****** DEFINITION OF LIBRARIES *****/
- // Compatible with Arduino Nano using
- // ESP8266/ESP32 as WiFi module
- #include <WiFiEspAT.h>
- // Compatible with Arduino Nano for HTTP requests
- #include <ArduinoHttpClient.h>
- /****** DEFINITION OF CONSTANTS *****/
- // WiFi credentials
- const char* ssid = "Despacho 2.4";
- const char* password = "Nabucodonosor33";
- // Google Sheets API endpoint
- // Using HTTP instead of HTTPS for WiFiEspAT compatibility
- const char* host = "script.google.com";
- const int port = 80;
- // Google Apps Script ID
- // Your unique script identifier
- const char* scriptId = "AKfycbx0EOD-SCOrNhGs2lFm3gV3dZPP9_oqAbImZEhhzojHJEIgrE2XOdH7OMA8DMAuhEmg";
- // Timing constants (in milliseconds)
- // 10 seconds between data transmissions
- const unsigned long TRANSMISSION_INTERVAL = 10000;
- // WiFi connection timeout
- const unsigned long WIFI_TIMEOUT = 10000;
- // HTTP request timeout
- const unsigned long HTTP_TIMEOUT = 5000;
- /****** GLOBAL VARIABLES *****/
- // WiFi and HTTP client instances
- // Using WiFiClient instead of WiFiClientSecure
- WiFiClient client;
- HttpClient httpClient = HttpClient(client, host, port);
- // Timing variables
- unsigned long lastTransmissionTime = 0;
- unsigned long wifiConnectionStartTime = 0;
- // WiFi status flag
- boolean wifiConnected = false;
- /****** FUNCTION PROTOTYPES *****/
- void setup(void);
- void loop(void);
- void initializeSerialCommunication(void);
- void initializeWiFiConnection(void);
- void checkWiFiStatus(void);
- void sendDataToGoogleSheets(float temperature, float humidity);
- void printDebugMessage(const char* message);
- void printIPAddress(void);
- float generateTemperatureData(void);
- float generateHumidityData(void);
- void printSensorData(float temperature, float humidity);
- /****** INITIALIZATION FUNCTION *****/
- void setup(void)
- {
- // Initialize serial communication
- initializeSerialCommunication();
- // Print startup message
- printDebugMessage("=== WiFi HTTP Cloud Data Transmission Started ===");
- // Initialize WiFi connection
- initializeWiFiConnection();
- }
- /****** MAIN LOOP FUNCTION *****/
- void loop(void)
- {
- // Check WiFi connection status
- checkWiFiStatus();
- // Check if it's time to transmit data
- unsigned long currentTime = millis();
- unsigned long timeSinceLastTransmission = currentTime - lastTransmissionTime;
- if (wifiConnected && (timeSinceLastTransmission >= TRANSMISSION_INTERVAL)) {
- // Update transmission time
- lastTransmissionTime = millis();
- // Generate sample sensor data
- float temperature = generateTemperatureData();
- float humidity = generateHumidityData();
- // Print sensor data
- printSensorData(temperature, humidity);
- // Send data to Google Sheets
- sendDataToGoogleSheets(temperature, humidity);
- }
- // Short delay to prevent overwhelming the loop
- delay(100);
- }
- /****** SERIAL COMMUNICATION INITIALIZATION *****/
- void initializeSerialCommunication(void)
- {
- // Initialize serial communication at 9600 baud
- Serial.begin(9600);
- // Wait for serial port to be ready
- delay(2000);
- }
- /****** WIFI CONNECTION INITIALIZATION *****/
- void initializeWiFiConnection(void)
- {
- printDebugMessage("Initiating WiFi connection...");
- Serial.print("Connecting to SSID: ");
- Serial.println(ssid);
- // Start WiFi connection using WiFiEspAT
- WiFi.begin(ssid, password);
- // Store connection start time for timeout handling
- wifiConnectionStartTime = millis();
- // Wait for connection with timeout
- int connectionAttempts = 0;
- // 40 attempts * 500ms = 20 seconds max
- int maxAttempts = 40;
- while (WiFi.status() != WL_CONNECTED && connectionAttempts < maxAttempts) {
- delay(500);
- Serial.print(".");
- connectionAttempts++;
- // Check timeout
- unsigned long connectionElapsedTime = millis() - wifiConnectionStartTime;
- if (connectionElapsedTime > WIFI_TIMEOUT) {
- break;
- }
- }
- Serial.println();
- // Verify connection status
- if (WiFi.status() == WL_CONNECTED) {
- wifiConnected = true;
- printDebugMessage("WiFi connected successfully!");
- printIPAddress();
- } else {
- wifiConnected = false;
- printDebugMessage("Failed to connect to WiFi after timeout");
- }
- }
- /****** WIFI STATUS CHECKING *****/
- void checkWiFiStatus(void)
- {
- // Check current WiFi connection status
- if (WiFi.status() == WL_CONNECTED) {
- if (!wifiConnected) {
- // Connection was re-established
- wifiConnected = true;
- printDebugMessage("WiFi reconnected!");
- printIPAddress();
- }
- } else {
- if (wifiConnected) {
- // Connection was lost
- wifiConnected = false;
- printDebugMessage("WiFi connection lost!");
- // Attempt to reconnect
- printDebugMessage("Attempting to reconnect to WiFi...");
- WiFi.begin(ssid, password);
- wifiConnectionStartTime = millis();
- }
- }
- }
- /****** GENERATE TEMPERATURE DATA *****/
- float generateTemperatureData(void)
- {
- // Generate random temperature between 20.0 - 30.0 Celsius
- float temperature = random(200, 300) / 10.0;
- return temperature;
- }
- /****** GENERATE HUMIDITY DATA *****/
- float generateHumidityData(void)
- {
- // Generate random humidity between 40.0 - 60.0 percent
- float humidity = random(400, 600) / 10.0;
- return humidity;
- }
- /****** PRINT SENSOR DATA *****/
- void printSensorData(float temperature, float humidity)
- {
- Serial.println("\n========================================");
- Serial.println("--- Sensor Data ---");
- Serial.print("Temperature: ");
- Serial.print(temperature);
- Serial.println(" °C");
- Serial.print("Humidity: ");
- Serial.print(humidity);
- Serial.println(" %");
- Serial.println("========================================");
- }
- /****** SEND DATA TO GOOGLE SHEETS *****/
- void sendDataToGoogleSheets(float temperature, float humidity)
- {
- // Verify WiFi connection before attempting to send
- if (WiFi.status() != WL_CONNECTED) {
- printDebugMessage("ERROR: WiFi not connected. Cannot send data.");
- return;
- }
- printDebugMessage("Transmitting data to Google Sheets...");
- // Create URL encoded parameters for GET request
- String parameters = "?temperatura=";
- parameters += String(temperature);
- parameters += "&humedad=";
- parameters += String(humidity);
- parameters += "×tamp=";
- parameters += String(millis());
- // Build the complete path
- String pathWithParameters = "/macros/s/";
- pathWithParameters += scriptId;
- pathWithParameters += "/exec";
- pathWithParameters += parameters;
- Serial.print("Path: ");
- Serial.println(pathWithParameters);
- // Begin HTTP GET request
- httpClient.setTimeout(HTTP_TIMEOUT);
- // Make GET request (simpler than POST for this use case)
- int httpCode = httpClient.get(pathWithParameters);
- // Print HTTP response code
- Serial.print("HTTP Response Code: ");
- Serial.println(httpCode);
- // Read and print response body
- if (httpCode > 0) {
- String responseBody = httpClient.responseBody();
- Serial.print("Server Response: ");
- Serial.println(responseBody);
- if (httpCode == 200) {
- printDebugMessage("Data successfully transmitted to Google Sheets!");
- } else {
- printDebugMessage("HTTP request completed with non-200 status.");
- }
- } else {
- Serial.print("HTTP Error: ");
- Serial.println(httpCode);
- printDebugMessage("ERROR: Failed to connect or request timed out.");
- }
- // Close the connection
- httpClient.stop();
- }
- /****** PRINT DEBUG MESSAGE *****/
- void printDebugMessage(const char* message)
- {
- Serial.print("[DEBUG] ");
- Serial.println(message);
- }
- /****** PRINT IP ADDRESS *****/
- void printIPAddress(void)
- {
- Serial.print("IP Address: ");
- Serial.println(WiFi.localIP());
- Serial.print("Gateway: ");
- Serial.println(WiFi.gatewayIP());
- Serial.print("DNS Server: ");
- Serial.println(WiFi.dnsIP());
- }
- /* END CODE */
Advertisement
Add Comment
Please, Sign In to add comment