Advertisement
Guest User

ESP32 to Google Sheet

a guest
Mar 14th, 2025
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.10 KB | None | 0 0
  1. /*
  2. Rui Santos
  3. Complete project details at https://RandomNerdTutorials.com/esp32-datalogging-google-sheets/
  4.  
  5. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
  6. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  7. Adapted from the examples of the Library Google Sheet Client Library for Arduino devices: https://github.com/mobizt/ESP-Google-Sheet-Client
  8. */
  9.  
  10. #include <Arduino.h>
  11. #include <WiFi.h>
  12. #include <Adafruit_Sensor.h>
  13. #include <Adafruit_BME280.h>
  14. #include "time.h"
  15. #include <ESP_Google_Sheet_Client.h>
  16.  
  17. // For SD/SD_MMC mounting helper
  18. #include <GS_SDHelper.h>
  19.  
  20. #define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
  21. #define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"
  22.  
  23. // Google Project ID
  24. #define PROJECT_ID "REPLACE_WITH_YOUR_PROJECT_ID"
  25.  
  26. // Service Account's client email
  27. #define CLIENT_EMAIL "REPLACE_WITH_YOUR_CLIENT_EMAIL"
  28.  
  29. // Service Account's private key
  30. const char PRIVATE_KEY[] PROGMEM = "-----BEGIN PRIVATE KEY-----\ REPLACE_WITH_YOUR_PRIVATE_KEY\n-----END PRIVATE KEY-----\n";
  31.  
  32. // The ID of the spreadsheet where you'll publish the data
  33. const char spreadsheetId[] = "YOUR_SPREADSHEET_ID";
  34.  
  35. // Timer variables
  36. unsigned long lastTime = 0;
  37. unsigned long timerDelay = 30000;
  38.  
  39. // Token Callback function
  40. void tokenStatusCallback(TokenInfo info);
  41.  
  42. // BME280 I2C
  43. Adafruit_BME280 bme;
  44. // Variables to hold sensor readings
  45. float temp;
  46. float hum;
  47. float pres;
  48.  
  49. // NTP server to request epoch time
  50. const char* ntpServer = "pool.ntp.org";
  51.  
  52. // Variable to save current epoch time
  53. unsigned long epochTime;
  54.  
  55. // Function that gets current epoch time
  56. unsigned long getTime() {
  57. time_t now;
  58. struct tm timeinfo;
  59. if (!getLocalTime(&timeinfo)) {
  60. //Serial.println("Failed to obtain time");
  61. return(0);
  62. }
  63. time(&now);
  64. return now;
  65. }
  66.  
  67. void setup(){
  68.  
  69. Serial.begin(115200);
  70. Serial.println();
  71. Serial.println();
  72.  
  73. //Configure time
  74. configTime(0, 0, ntpServer);
  75.  
  76. // Initialize BME280 sensor
  77. if (!bme.begin(0x76)) {
  78. Serial.println("Could not find a valid BME280 sensor, check wiring!");
  79. while (1);
  80. }
  81.  
  82. GSheet.printf("ESP Google Sheet Client v%s\n\n", ESP_GOOGLE_SHEET_CLIENT_VERSION);
  83.  
  84. // Connect to Wi-Fi
  85. WiFi.setAutoReconnect(true);
  86. WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  87.  
  88. Serial.print("Connecting to Wi-Fi");
  89. while (WiFi.status() != WL_CONNECTED) {
  90. Serial.print(".");
  91. delay(1000);
  92. }
  93. Serial.println();
  94. Serial.print("Connected with IP: ");
  95. Serial.println(WiFi.localIP());
  96. Serial.println();
  97.  
  98. // Set the callback for Google API access token generation status (for debug only)
  99. GSheet.setTokenCallback(tokenStatusCallback);
  100.  
  101. // Set the seconds to refresh the auth token before expire (60 to 3540, default is 300 seconds)
  102. GSheet.setPrerefreshSeconds(10 * 60);
  103.  
  104. // Begin the access token generation for Google API authentication
  105. GSheet.begin(CLIENT_EMAIL, PROJECT_ID, PRIVATE_KEY);
  106. }
  107.  
  108. void loop(){
  109. // Call ready() repeatedly in loop for authentication checking and processing
  110. bool ready = GSheet.ready();
  111.  
  112. if (ready && millis() - lastTime > timerDelay){
  113. lastTime = millis();
  114.  
  115. FirebaseJson response;
  116.  
  117. Serial.println("\nAppend spreadsheet values...");
  118. Serial.println("----------------------------");
  119.  
  120. FirebaseJson valueRange;
  121.  
  122. // New BME280 sensor readings
  123. temp = bme.readTemperature();
  124. //temp = 1.8*bme.readTemperature() + 32;
  125. hum = bme.readHumidity();
  126. pres = bme.readPressure()/100.0F;
  127. // Get timestamp
  128. epochTime = getTime();
  129.  
  130. valueRange.add("majorDimension", "COLUMNS");
  131. valueRange.set("values/[0]/[0]", epochTime);
  132. valueRange.set("values/[1]/[0]", temp);
  133. valueRange.set("values/[2]/[0]", hum);
  134. valueRange.set("values/[3]/[0]", pres);
  135.  
  136. // For Google Sheet API ref doc, go to https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append
  137. // Append values to the spreadsheet
  138. bool success = GSheet.values.append(&response /* returned response */, spreadsheetId /* spreadsheet Id to append */, "Sheet1!A1" /* range to append */, &valueRange /* data range to append */);
  139. if (success){
  140. response.toString(Serial, true);
  141. valueRange.clear();
  142. }
  143. else{
  144. Serial.println(GSheet.errorReason());
  145. }
  146. Serial.println();
  147. Serial.println(ESP.getFreeHeap());
  148. }
  149. }
  150.  
  151. void tokenStatusCallback(TokenInfo info){
  152. if (info.status == token_status_error){
  153. GSheet.printf("Token info: type = %s, status = %s\n", GSheet.getTokenType(info).c_str(), GSheet.getTokenStatus(info).c_str());
  154. GSheet.printf("Token error: %s\n", GSheet.getTokenError(info).c_str());
  155. }
  156. else{
  157. GSheet.printf("Token info: type = %s, status = %s\n", GSheet.getTokenType(info).c_str(), GSheet.getTokenStatus(info).c_str());
  158. }
  159. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement