ESP32 MicroPython Publish Sensor Readings to Google Sheets via IFTTT

In this user guide, we will learn how to publish sensor readings from ESP32 using MicroPython and Thonny IDE to Google Sheets using IFTTT as a third-party service. This guide will be helpful for the users who want to access data for a predetermined amount of time and also store it appropriately. Any preferred sensor, such as DS18B20, BME680, and MPPU6050, can be used but for this article, we will use a BME280 sensor which will be used to measure temperature, pressure, and humidity. The sensor readings will be accessed from the BME280 sensor connected with the ESP32 module. These readings will get updated on Google Sheets after every few minutes. To integrate Google Sheets with ESP32, we will use IFTTT which is an open-source web service. Via IFTTT, it will become extremely simple to publish updated sensor data to Google Sheets promptly.

ESP32 MicroPython Publish Sensor Readings to Google Sheets via IFTTT

This article is divided into these sub-topics:

  • Introduction of BME280 Sensor Module and interfacing it with ESP32
  • Setting up and testing IFTTT webhook for Google sheet

We have a similar guide with ESP32 and ESP8266 using Arduino IDE:

Prerequisites

Before we start this lesson make sure you are familiar with and have the latest version of MicroPython firmware installed in your ESP32 board and have a running Integrated Development Environment (IDE) in which we will be doing the programming such as uPyCraft IDE or Thonny IDE.

If you want to use VS Code, you can follow this guide:

Project Overview – MicroPython Send Sesnor Readings to Google Sheet

This project starts by booting ESP32 and connecting it to the local WiFi network. The BME280 sensor will be connected to the ESP board through the I2C GPIO pins which we will specify later. When ESP32 boots, the BME280 sensor gets readings of temperature, pressure, and humidity. After that, it makes an HTTP request to IFTTT API to log sensor readings to Google sheet. The Google Sheets will be linked to the user’s Google Drive. After every 10 minutes, new sensor readings will get published to Google Sheet. The rest of the time the ESP32 will remain in deep sleep mode.

Publish sensor readings to Google Sheets project Overview

Recommended Readings:

  • MicroPython: ESP32 Deep Sleep Mode and Wake Up Sources
  • ESP32 HTTP POST using Arduino IDE (ThingSpeak and IFTTT)
  • MicroPython: Send Sensor Readings via Email (IFTTT) with ESP32 and ESP8266

Introduction of IFTTT

IFTTT means ‘If this, then that.’ It is an open-source service that gives the user the freedom to program a response to an event according to their likes. We can create an applet which are chains of conditional statements by a combination of several app services and add triggering parameters. For our project, we will be using this service, whenever the ESP board makes a request and hence send the sensor readings to our email. To work with this web service, we will have to follow a series of steps to ensure the proper functionality.

Creating an Account

Although the IFTTT service is free to use, we will have to create an account. First go to the following website: https://ifttt.com/
The following window will appear. Click on the ‘Get Started’ button.

Getting started with IFTTT 1

The following window will appear. You can select any one from these three options (Apple, Google or Facebook) to connect. Or you can simply ‘sign up’ with your own given email. We will be following this scheme.

IFTTT sign up page 2

Click the ‘sign up’ tag. You will see the following window pop up. Enter your email address and password to start working in IFTTT. This whole process is free of cost for the first three applets.

IFTTT sign up page 3

Creating an Applet

After you have created your account, we will be directed to the page where we will create our applet. Click on ‘Create.’

IFTTT create applets 4

The following window opens up. Click the following Add button in the ‘If This’ section.

IFTTT create applets webhock alert 5

Another page will open in which we will have to choose our service. There is a lot of options to choose from. Write down ‘webhooks’ in the search option and its icon will appear:

IFTTT search webhock from available services 7

Select Trigger

Next, choose the trigger as: ‘Receive a web request’ by clicking on it. Whenever webhooks will receive a web request, some action will take place. This we will define in the ‘THAT’ section.

IFTTT webhock create an alert web request 8

After clicking the Receive a web request, the following window will open up. We will write down BME280_Sensor_Readings as the event name for the web request. You can use any other name of your choice. Click ‘Create Trigger’ button.

Publish sensor readings to Google Sheets IFTTT1

After the trigger is created, we are taken back to the web page where we first added the service for the ‘IF THIS’ section. Now we will click the ADD button for the ‘THEN THAT’ section.

IFTTT create gmail service 10

Now we will choose the service. We have to choose what will happen if a web request is received. Thus, we will type ‘google sheets’ in the search option and click on its icon. This is because we want to publish updated sensor reading to Google Sheets send whenever a web request is received.

Publish sensor readings to Google Sheets IFTTT2

The following window opens up where we will choose ‘Add row to spreadsheet.’

Publish sensor readings to Google Sheets IFTTT3

Next click ‘Connect.’

Publish sensor readings to Google Sheets IFTTT4

Another window will open which will prompt you to choose an email account and then will ask for your permission. Click “Allow” to proceed.

Publish sensor readings to Google Sheets permission IFTTT

Now fill in all the entries as given below and click ‘Create Action.’

Publish sensor readings to Google Sheets IFTTT6

After we have created the action, we will be guided towards the initial web page of IFTTT. Click Continue to proceed.

Publish sensor readings to Google Sheets IFTTT7

You have successfully created the applet. Make sure to turn on the notifications whenever the applet becomes active.

Publish sensor readings to Google Sheets IFTTT8

Testing the Applet

Before we proceed further with our project, let us first test our applet. Go to your applet and select “My Services” or open a webpage with the link: ifttt.com/my_services. The following windows will appear. Afterward, click on Webhooks.

ESP32 HTTP POST IFTTT testing webhooks

This will take you to the following web page. Click on ‘Documentation.’

IFTTT testing applet 20

You will receive a key that should be secure with you. Next, enter the details as shown to trigger the event. We will give hypothetical values for the three variables for now. At the end click, ‘Test it.’

Note: Save the URL highlighted in the blue box. This is the IFTTT URL resource which we will use later on in our program code.

Publish sensor readings to Google Sheets IFTTT9

You will get a notification on top of the web page: ‘Event has been triggered.’ Now go to your google drive and you will find a folder named ‘IFTTT.’ Open it and you will find the spreadsheet inside it.

Publish sensor readings to Google Sheets Google drive1

Click to open it. You will be able to see the same hypothetical values that you entered. This means that the applet is running successfully. Now let us learn how to incorporate real sensor readings from the BME280 sensor.

Publish sensor readings to Google Sheets Google drive2

Interfacing BME280 sensor with ESP32

BME280 sensor interfacing with ESP32

The connection of BME280 with the ESP32 is very easy. We have to connect the VCC terminal with 3.3V, ground with the ground (common ground), SCL of the sensor with SCL of the module, and SDA of the sensor with the SDA pin of the ESP modules.

The I2C pin in ESP32 for SDA is GPIO21 and for SCL is GPIO22.

The connections between the two devices can be seen below.

ESP32BME280
VCC=3.3VVin
GPIO21(I2C SDA)SDA
GPIO22 (I2C SCL)SCL
GROUNDGROUND

We will need the following components to connect ESP32 with BME280 sensor.

  1. ESP32
  2. BME280 Sensor
  3. Connecting Wires
  4. Breadboard

Follow the schematic diagrams below to connect the ESP32 with BME280 as shown in the schematic diagram below:

BME280 with ESP32 MicroPython

Install BME280 Libraries in Thonny IDE

We will have to install the BME280 library for MicroPython to continue with our project.

To successfully do that, open your Thonny IDE with your ESP32 or ESP8266 plugged in with your laptop. Go to Tools > Manage Packages. This will open up the Thonny Package Manager.

Raspberry Pi Pico Installing ssd1306 OLED library MicoPython 1

Search for “bme280” in the search bar by typing its name and clicking the button ‘Search on PyPI.’ From the following search results click on the one highlighted below: micropython-bme280. Install this library.

Installing BME280 Micropython library Thonny

After few moments, this library will get successfully.

ESP32 MicroPython Code to Send Sensor Readings to Google Sheets

This MicroPython code reads sensor data from a BME280 sensor and sends the data to Google Sheets using IFTTT as a third party service. It imports the required libraries, sets up network credentials, initializes the I2C method, and reads the BME280 sensor for temperature, humidity, and pressure values. It then connects to a network and sends the sensor data to Google Sheets.

# Import necessary libraries
import urequests
import network
import time
import ubinascii
import machine
import network
import esp
from machine import Pin, I2C
from time import sleep
import bme280        #importing BME280 library
esp.osdebug(None)
import gc
gc.collect()

ssid = 'replace_with_your_wifi_ssid'  # Write your SSID
password = 'replace_with_your_wifi_password'  # Write your Password

IFTTT_URL = '/trigger/BME280_Sensor_Readings/with/key/enter_your_key_here'
server = 'maker.ifttt.com'

i2c = I2C(scl=Pin(22), sda=Pin(21), freq=10000)     #initializing the I2C method for ESP32
bme = bme280.BME280(i2c=i2c)

# Define function to connect to WiFi network
def connect_wifi(ssid, password):
  # Connect to your network
  station = network.WLAN(network.STA_IF)
  station.active(True)
  station.connect(ssid, password)
  while station.isconnected() == False:
    pass
  print('Connection successful')
  print(station.ifconfig())

def make_ifttt_request():
    print('Connecting to', server)
    json_data = '{"value1":"' + bme.values[0] + '","value2":"' + bme.values[1]  + \
        '","value3":"' + bme.values[2] + '"}'
    headers = {'Content-Type': 'application/json'}
    response = urequests.post('https://' + server + IFTTT_URL, data=json_data, headers=headers)
    print('Response:', response.content.decode())
    response.close()
    print('Closing Connection')

while True:
    print('Sensor reading in progress...')
    connect_wifi(ssid, password)
    make_ifttt_request()
    time.sleep(1)
    print('Going to sleep now')
    machine.deepsleep(10000)     #10000ms sleep time

Before uploading the above MicroPython script to ESP32 replace ssid, password, and IFTTT key with your own details.

How MicroPython Script Works?

First import the necessary libraries for this MicroPython script to run. This includes libraries for network connectivity, timekeeping, I2C communication, HTTP requests, deep sleep and BME280 sensor.

# Import necessary libraries
import urequests
import network
import time
import ubinascii
import machine
import network
import esp
from machine import Pin, I2C
from time import sleep
import bme280        #importing BME280 library
esp.osdebug(None)
import gc
gc.collect()

Set the SSID and password of the WiFi network to which the ESP32 will connect.

ssid = 'replace_with_your_ssid' # Replace with the name of your network
password = 'replace_with_your_password' # Replace with your network password

Next, we will connect the ESP32 to the Wi-Fi network. The network.WLAN() is used to create a WLAN network interface object. 

Supported interfaces are:

  • network.STA_IF (station mode)
  • network.AP_IF (Soft access point mode)

After that, activate the station by passing the “True” argument to the sta_if.active() method. The connect() method is used to connect to the specified wireless network using the specified Wi-Fi name (SSID) and password. 

In station mode, isconnected() method returns “True” if ESP32 successfully connects to a Wi-Fi network and a device also assigned a valid IP address. Otherwise, it returns “False”. This statement checks if the ESP32 connects to the Wi-Fi or not. The code does not move to the next step till the board is not connected to the Wi-Fi network.

After a Wi-Fi connection is established on the ESP32, an IP address gets assigned. The ifconfig() method provides an IP address assigned to the ESP32. In this statement, we print the IP address using the ifconfig() method on the station object which we created previously.

# Define function to connect to WiFi network
def connect_wifi(ssid, password):
  # Connect to your network
  station = network.WLAN(network.STA_IF)
  station.active(True)
  station.connect(ssid, password)
  while station.isconnected() == False:
    pass
  print('Connection successful')
  print(station.ifconfig())

Call the “connect_wifi” function to connect to the network.

# Connect to your network
connect_wifi(ssid, password)

Initialize BME280 Sensor Pins

Now, we initialize the I2C method by giving it three arguments. The first argument specifies the GPIO pin for SCL. This is given as GPIO22 for ESP32. The second parameter specifies the GPIO pin for the SDA. This is given as GPIO21 for ESP32. Keep in mind, these are the default I2C pins for SCL and SDA which we have used for the ESP32. The third parameter specifies the maximum frequency for SCL to be used.

# Assign pins for BME280 sensor on ESP32
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=10000)     #initializing the I2C method for ESP32

Send Sensor Reading to Google Sheet

These lines set the URL and server address for the IFTTT web service.

IFTTT_URL = '/trigger/BME280_Sensor_Readings/with/key/enter_your_key_here'
server = 'maker.ifttt.com'

Next define a method make_ifttt_request(). This MicroPython functions sends BME280 sensor data to a service called IFTTT (If This Then That). It starts by printing a message to the console to show that it’s connecting to the IFTTT server. It then creates a JSON-formatted string that contains the sensor readings for temperature, pressure, and humidity. The JSON string is sent to the IFTTT server using the HTTP POST method, with the correct headers set. Once the data has been sent, the function prints the server’s response to the console and then closes the connection.

def make_ifttt_request():
    print('Connecting to', server)
    json_data = '{"value1":"' + bme.values[0] + '","value2":"' + bme.values[1]  + \
        '","value3":"' + bme.values[2] + '"}'
    headers = {'Content-Type': 'application/json'}
    response = urequests.post('https://' + server + IFTTT_URL, data=json_data, headers=headers)
    print('Response:', response.content.decode())
    response.close()
    print('Closing Connection')

This line prints the string “Connecting to” followed by the value of the variable server to the console.

print('Connecting to', server)

Next, create a JSON-formatted string with three key-value pairs for temperature, pressure and humditiy values from BME280 sensor. The values for the keys “value1”, “value2”, and “value3” are taken from the bme.values list output of bme object.

json_data = '{"value1":"' + bme.values[0] + '","value2":"' + bme.values[1] + \ '","value3":"' + bme.values[2] + '"}'

Create a dictionary called headers with one key-value pair. The key is “Content-Type” and the value is “application/json” which is used to set headers for HTTP requests to IFTTT API.

headers = {'Content-Type': 'application/json'}

This line makes an HTTP POST request to the IFTTT service using the urequests MicroPython library. The URL for the request is constructed by concatenating the server variable and the IFTTT_URL constant. The json_data and headers variables are used as the payload and headers for the request, respectively. The response from the request is stored in the response variable.

response = urequests.post('https://' + server + IFTTT_URL, data=json_data, headers=headers)

Next print the content of the response from IFTTT server to the console.

print('Response:', response.content.decode())

At the end close the response object.

response.close()

This line prints the string “Closing Connection” to the console.

print('Closing Connection')

At the end, create an infinite loop that calls the connect_wifi and make_ifttt_request functions, sleeps for 1 second, and then puts the ESP32 into deep sleep mode for 10 seconds. This loop will continue to run until the script is interrupted. In other words, it will send the BME280 sensor values to Google sheets every 10 seconds and after sending sensor values to Google sheet, ES32 will go into deep sleep to save power.

while True:
    print('Sensor reading in progress...')
    connect_wifi(ssid, password)
    make_ifttt_request()
    time.sleep(1)
    print('Going to sleep now')
    machine.deepsleep(10000)     #10000ms sleep time

Demonstration

Copy the above code to Thonny IDE and save it with the name of main.py and save it to ESP32 board.

After uploading main.py file to ESP32, click on the run button on Thonny IDE.

As soon as you click on the run button and if everything goes well, you will see a success message on the Thonny ID console as shown below:

ESP32 MicroPython save data to google sheet

Now go to your Google Drive and open the IFTTT folder. Inside it you will find the google spreadsheet. Open it to view a set of sensor readings.

After a few seconds, you will sensor readings in google sheets in your google drive as shown below:

BME280 sensor readings to google sheet

You can also see that the ESP32 is going to deep sleep and waking up after every 10 seconds:

ESP32 MicroPython save data to google sheet with deep sleep

In summary:

In this tutorial, we have learned how to send sensor readings to Google sheets with ESP32 using MicroPython and IFTTT as a third party service.

You may also like to read:

Leave a Comment