Arduino Mega+ESP8266 ESP-01S sending data to Google Sheets

Hello everyone. My goal is to send temperature values from an DHT sensor, that is connected to a Arduino Mega with a ESP8266 ESP-01S module, to a Google Sheet.

The closest and easiest thing that I found is the following video.

The problem is that in the video it uses an Nodemcu instead of an Arduino Mega.
I have managed to set up the part for the Google Sheets but I don’t have the skill to modify the code to use the Mega.

This is the code for the Nodemcu:

#include <ESP8266WiFi.h>
#include "DHT.h"

// ----------------------------------------------------------------------------------------------
DHT dht;

// ----------------------------------------------------------------------------------------------
// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "YourNetworkName";
char pass[] = "YourPassword";
String GAS_ID = "SHEET_ID"; //--> spreadsheet script ID

//Your Domain name with URL path or IP address with path
const char* host = "script.google.com"; // only google.com not https://google.com

// ----------------------------------------------------------------------------------------------
#define DHT_PIN               D1
#define UPDATE_INTERVAL_HOUR  (0)
#define UPDATE_INTERVAL_MIN   (0)
#define UPDATE_INTERVAL_SEC   (30)

#define UPDATE_INTERVAL_MS    ( ((UPDATE_INTERVAL_HOUR*60*60) + (UPDATE_INTERVAL_MIN * 60) + UPDATE_INTERVAL_SEC ) * 1000 )

// ----------------------------------------------------------------------------------------------
int Temperature;
int Humidity;

// ----------------------------------------------------------------------------------------------
void update_google_sheet()
{
    Serial.print("connecting to ");
    Serial.println(host);
  
    // Use WiFiClient class to create TCP connections
    WiFiClientSecure client;
    const int httpPort = 443; // 80 is for HTTP / 443 is for HTTPS!
    
    client.setInsecure(); // this is the magical line that makes everything work
    
    if (!client.connect(host, httpPort)) { //works!
      Serial.println("connection failed");
      return;
    }
       
    //----------------------------------------Processing data and sending data
    String url = "/macros/s/" + GAS_ID + "/exec?temperature=";
   
    url += String(Temperature);
    
    url += "&humidity=";
    url += String(Humidity);
    
    Serial.print("Requesting URL: ");
    Serial.println(url);
  
    // This will send the request to the server
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: " + host + "\r\n" + 
                 "Connection: close\r\n\r\n");
  
    Serial.println();
    Serial.println("closing connection");  
}

// ----------------------------------------------------------------------------------------------
void setup()
{
  // Debug console
  Serial.begin(9600);

  // Digital output pin
  pinMode(LED_BUILTIN, OUTPUT);

  // DHT Setup
  dht.setup(DHT_PIN); 

//----------------------------------------Wait for connection
  Serial.print("Connecting");
  WiFi.begin(ssid, pass); //--> Connect to your WiFi router
  while (WiFi.status() != WL_CONNECTED) 
  {
    Serial.print(".");
    digitalWrite(LED_BUILTIN, LOW);
    delay(50);
    digitalWrite(LED_BUILTIN, HIGH);
    delay(50);
  }

}

// ----------------------------------------------------------------------------------------------
unsigned long time_ms;
unsigned long time_1000_ms_buf;
unsigned long time_sheet_update_buf;
unsigned long time_dif;

void loop()
{
  time_ms = millis();
  time_dif = time_ms - time_1000_ms_buf;

  // Read and print serial data every 1 sec
  if ( time_dif >= 1000 ) // 1sec 
  {
    time_1000_ms_buf = time_ms;
    Temperature = dht.getTemperature();
    Humidity = dht.getHumidity();
  
    // Print serial messages
    Serial.print("Humidity: " + String(Humidity) + " %");
    Serial.print("\t");
    Serial.println("Temperature: " + String(Temperature) + " C");

    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
  }

  // Update data to google sheet in specific period
  time_ms = millis();
  time_dif = time_ms - time_sheet_update_buf;  
  if ( time_dif >= UPDATE_INTERVAL_MS ) // Specific period
  {
    time_sheet_update_buf = time_ms;
    update_google_sheet();
  }
 
}

and this is the script for the Google Sheets:

function doGet(e) { 
Logger.log( JSON.stringify(e) );
var result = 'Ok';
if (e.parameter == 'undefined') {
result = 'No Parameters';
}
else {
var sheet_id = 'SHEET_ID'; // Spreadsheet ID
var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet();
var newRow = sheet.getLastRow() + 1; 
var rowData = [];
var Curr_Date = new Date();
rowData[0] = Curr_Date; // Date in column A
var Curr_Time = Utilities.formatDate(Curr_Date, "Asia/Bangkok", 'HH:mm:ss');
rowData[1] = Curr_Time; // Time in column B
for (var param in e.parameter) {
Logger.log('In for loop, param=' + param);
var value = stripQuotes(e.parameter[param]);
Logger.log(param + ':' + e.parameter[param]);
switch (param) {

case 'temperature':
rowData[2] = value; 
result = 'OK'; 
break;

case 'humidity':
rowData[3] = value; 
result += ', OK'; 
break; 
  
default:
result = "unsupported parameter";
}
}
Logger.log(JSON.stringify(rowData));
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
return ContentService.createTextOutput(result);
}
function stripQuotes( value ) {
return value.replace(/^["']|['"]$/g, "");
}

Can anyone guide me on how to modify the code so I can use the Mega?

why goto the complexity of programming two microcontrollers plus the communication protocol
connect the DHT sensor to the ESP8266, read it and transmit data to google sheets

It is part of a bigger project and I need the extra pins of the Mega.

how many pins do you require? what interfaces (I2C, SPI, ADC, DAC, etc)? what logic levels?
consider a ESP32

I have used a Mega with a ESP-01S using the following circuit

note the voltage divider on the Mega Tx pin 18 5V logic to the ESP-01s GPIO3 3.3V logic

the following Mega and ESP-01s programs communicate via serial using above circuit

// Mega - read Serial1 0101010 input from ESP8266 to blink LED
//    ESP-01 transmits 0 or 1 to Serial1 to switch LED OFF/ON
//    enter new blink period in mSec on keyboard, e.g. 500 for 0.5sec

void setup() {
  Serial.begin(115200);
  Serial.println("\nMega to ESP-01 Serial1 test");
  Serial.println("ESP-01 transmits 0 or 1 to Serial1 to switch LED OFF/ON");
  Serial.println("enter new blink period in mSec on keyboard, e.g. 500 for 0.5sec");
  Serial1.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  // if text available read next time value and send to ESP8266 over Serial1
  if (Serial.available() > 0) {         // wait for serial input
    int timeonoff = Serial.parseInt();  // read time value
    Serial1.println(timeonoff);         // send to ESP8266
    Serial.print("\n\Period in mSec sent to ESP-01 ");
    Serial.println(timeonoff);
    delay(10);
    while (Serial.available()) Serial.read();  // flush input
  }
  if (Serial1.available() > 0) {  // wait for Serial1 input
    char ch = Serial1.read();     // should 0 or 1 to blient LED
    Serial.print(ch);
    if (ch == '0') digitalWrite(LED_BUILTIN, LOW);  // turn the LED off by making the voltage LOW
    else if (ch == '1') digitalWrite(LED_BUILTIN, HIGH);           // turn the LED on (HIGH is the voltage level)
  }
}

ESP-01S code

// ESP8266 - transmit 0101010 in timing loop - read new loop time from keyboard
//  Serial 0101010 output will be sent to mega to blink LED

void setup() {
  Serial.begin(9600);    // <<<<<<< note 9600baud
}

void loop() {
  static long timer=millis();
  //  send 010101 etc every time interval
  static int onoff=0, timeonoff=1000;
  if((millis()-timer)>timeonoff) {
    timer=millis();
    Serial.print(onoff);
    onoff=!onoff;                   // invert value 0 or 1
  }
  // if text available read next time value
  if(Serial.available()==0) return; // wait for serial input
  timeonoff=Serial.parseInt();      // read time value
  //Serial.println(timeonoff);
  delay(10);
  while(Serial.available()) Serial.read(); // flush input
}

This is part of a larger project. I have used first the ESP32 but I run out of pins. Now I’m using a schematic similar to yours. In the project I’m using the Remotexy to get data from multiple sensors and control relays. I want to log the data from the sensors to do some graphs.

you should be able to
1 read your sensors etc using the Mega and transmit the results using Serial1 to
2. the ESP-01 reads Serial and transmits the data to Googlesheets

initially write the Mega code to read the sensors and output data to Serial - when it is OK change to output to Serial1

write ESP-01S code to read the serial data from the Mega and transmit to Googlesheets

I have read already the sensor, but I don’t know enough coding to do the transmit to Googlesheets.

never used Googlesheets - recommend you do a web search for arduino googlesheets you will get plenty of links

never used Googlesheets - recommend you do a web search for arduino googlesheets you will get plenty of links

I have searched, but all the example that I have found are for the esp32. If you can provide a link for the Mega I will greatly appreciated.

the Mega samples your sensors and transmit results over serial to the ESP-01S

it is the ESP-01S which would connect to Googlesheets to upload the serial data from the mega

I understand the logic, but I don’t know enough coding to do that.

having to program two microcontrollers and managing the communications protocol between them make the overall task an order of magnitude more complex
how many IO devices do you need to connect? what interfaces are used (I2C, SPI, ADC, etc)?
the ESP32 Devkit V1 has plenty of IO capabilities

The coding for the sensors is done. All I want now is to also send the data from them to google sheets. The interfaces are ADC. I have a wind speed monitor, a rain monitor, a light sensor and several relays, and I plan to add more relays and also several DHT temperature sensors.

First, learn how to write the code for serial communication between two microcontrollers, there are many tutorials out there.

Can you point to a good one?

in post 4 there is a mega to ESP-01 wiring diagram plus mega code and ESP-01 communicating over serial
try it - see if you can load the programs into the ESP-01 and Mega and get the example code running and communicating

Right now I have the code that connects to the wifi and sends data to the remotexy app and it all works well. I just need the code to send the some of the date to a googlesheet.

Here is a very basic tutorial that transmits data to Google Sheets. It just logs random number values to Google Sheets. Once you get that script working, you can just replace the random number variables with the data you want to send.

Thank you for the link, but it seems like the example is for ESP8266 not for an ESP8266 conected to the Mega. I get an "ESP8266WiFi.h: No such file or directory" error.

you are probably trying to build the program with the Tools>Board set to Arduino Mega - this code with not compile and run on a Mega it is designed for a ES8266 processor

try building it for the ESP-01, e.g. set Tools>Board to "Generic ESP8266 Module"

in practice the Mega will have to transmit the sensor data over the serial connection to the ESP-01 which will transmit it to googlesheets

as I stated in post 12 having to program two microcontrollers and managing the communications protocol between them make the overall task an order of magnitude more complex