This example uses a MCP2221 with a BME280 pressure/temperature/humidity sensor accessed over an I2C wired connection. Links to setup the MCP2221 were provided early in the guide. To install the library for the BME280, see here:

Here is the wiring diagram:

Create a new Sheet to hold this data and give it a name. Here we also add some column titles:

Add just like we did in the test example, share the sheet with the "client email" address from the .json file. Click the SHARE button:

And add the "client email" address from the .json file.

Also, grab the gibberish spreadsheetID from the URL so you can use it in the code below. See previous section of guide for more info on this.

And here's the code for logging BME280 sensor data to you Google Sheet. Be sure to replace YOUR_CREDENTIALS_FILE and YOUR_SHEET_ID with the actual values for your setup.

# SPDX-FileCopyrightText: 2020 Carter Nelson for Adafruit Industries
#
# SPDX-License-Identifier: MIT

import time
from datetime import datetime
import board
import adafruit_bme280
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build

#--| User Config |-----------------------------------------------
SERVICE_ACCOUNT_FILE = 'YOUR_CREDENTIALS_FILE.json'
SPREADSHEET_ID = 'YOUR_SHEET_ID'
DATA_LOCATION = 'A1'
UPDATE_RATE = 60
#--| User Config |-----------------------------------------------

# Sensor setup
i2c = board.I2C()  # uses board.SCL and board.SDA
# i2c = board.STEMMA_I2C()  # For using the built-in STEMMA QT connector on a microcontroller
bme = adafruit_bme280.Adafruit_BME280_I2C(i2c)

# Google Sheets API setup
SCOPES = ['https://spreadsheets.google.com/feeds',
          'https://www.googleapis.com/auth/drive']
CREDS = Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
SHEET = build('sheets', 'v4', credentials=CREDS).spreadsheets()

# Logging loop
print("Logging...")
while True:
    values = [[datetime.now().isoformat(), bme.pressure, bme.temperature, bme.humidity]]
    SHEET.values().append(spreadsheetId=SPREADSHEET_ID,
                          valueInputOption='RAW',
                          range=DATA_LOCATION,
                          body={'values' : values}).execute()
    time.sleep(UPDATE_RATE)
Don't forget to also set the BLINKA_MCP2221 environment variable.

Save that as something like bme280_logger.py and then run it with:

python3 bme280_logger.py

It should run without errors and start logging:

After a couple of minutes, go back and look at your sheet. It should be updated with new values:

This guide was first published on Jan 17, 2020. It was last updated on Jan 17, 2020.

This page (MCP2221 with BME280 on I2C) was last updated on May 31, 2023.

Text editor powered by tinymce.