Book Image

Raspberry Pi Sensors

By : Rushi Gajjar
Book Image

Raspberry Pi Sensors

By: Rushi Gajjar

Overview of this book

Table of Contents (16 chapters)
Raspberry Pi Sensors
Credits
About the Author
Acknowledgements
About the Reviewers
www.PacktPub.com
Preface
Index

Uploading data on Google spreadsheets


We are all set with the synced time to the local time zone. We can create an application that does the same data logging as we did in the previous chapter, but this time it is different and cool. We will upload the data on Google spreadsheets, and the data can then be accessed from any corner of the world. You can monitor home temperature and humidity by sitting in your office. Either you can grab the project you did in Chapter 4, Monitoring the Atmosphere Using Sensors, and observe the temperature and humidity with the DHT11 sensor, or you can just bring the sensor station built in the previous chapter using MCP3008.

Before we get into the code, we need to prepare the things listed here. Use your personal computer's Internet browser to perform these steps:

  1. Log in to your Gmail account or create a new one.

  2. Open or link Google Drive by logging onto http://www.drive.google.com with your Gmail ID.

  3. In the user interface of Google Drive, on the left-side panel, click on the New button and select Spreadsheet from the drop-down menu. You will be redirected to a new tab.

  4. In the new tab, name the spreadsheet Logging. Avoid blank spaces in the name to reduce errors, as we are going to use this name in our code.

  5. Click on the Add-ons drop-down menu from one of the spreadsheet menus, and then check out Get Add-ons…. In the search bar, type Remove Blank Rows. Click on the free button and install it.

  6. In the first row of the spreadsheet, enter the column titles as Time and Temperature.

  7. Click on the Add-ons menu again and then on the Remove Blank Rows add-on. Check out the Delete or hide blank rows option. You will be able to see the sidebar with some options. Click on the top-left corner of the spreadsheet to select all rows and columns. Then, in the sidebar, select the All row cells must be blank option and delete all blank rows. It should look like what is shown in the following screenshot.

    Tip

    The reason for doing this is that the code will start entering the data from the last blank row of the sheet by creating a new row. If you have a thousand rows, it could be difficult to manage the data as it will start entering data from 1001st row.

  8. Close the tab, and we are ready to code in the RasPi.

Now, on the RasPi, install the library that provides support to push the data to the Google spreadsheets. Open a PuTTY session to enter these commands to install the gspread library:

git clone https://github.com/burnash/gspread.git
cd gspread
python setup.py install

It is really important to install the gspread library, as it gives us the handy functions to upload the data on the desired spreadsheet document on the selected sheets, cells, and much more.

Here, we are going to use MCP3008, as it can be useful to interface as many sensors as we can. We will recall the functions used to get data from the SPI port:

#start the SPI bus by opening the spi port
spi = spidev.SpiDev()
spi.open(0,0)
#function to read the channels of MCP3008 
def readadc(channel):
     value = spi.xfer2([1,(8+channel)<<4,0])
     read = ((value[1]&3) << 8) + value[2]
     return read

The explanation of fetching data using the readadc() function has already been given in the previous chapter. We will use the same generic function to fetch the data from the sensor and send it over the Internet.

Observe the following Python code and get an understanding from the description given just beneath it:

import os
import spidev
import glob
import time
import sys
import datetime
import gspread

#start the SPI bus by opening the spi port
spi = spidev.SpiDev()
spi.open(0,0)

# Enter your account details (Your Gmail ID and Password) as shown here
email = '[email protected]'
password = 'raspberrypi'

#Name of Spreadsheet created in Google Drive
spreadsheet = 'Logging' 

#Putting the exception call in python to attempt for logging in Gmail
try:
     ret = gspread.login(email,password)
except:
     print('Oops! Check Internet Connection or Login Credentials')
     sys.exit()

#open the spreadsheet by either of these two options
worksheet = ret.open(spreadsheet).sheet1
#or with the spreadsheet key
#worksheet = ret.open_by_key('1eQth-TY4FXFKChB5RFPhelQ6zn47NWDESh13WkXGQAk')
#prefer First Option

def readadc(channel):
     value = spi.xfer2([1,(8+channel)<<4,0])
     read = ((value[1]&3) << 8) + value[2]
     return read

while True:
     #Get data from Channel 0, TMP36 Temperature Sensor
     val = readadc(0)
     temperature = ((val * 330)/float(1023))-50
     values = [datetime.datetime.now(), temperature]
     worksheet.append_row(values)
     time.sleep(5)

At the top of the code, you can see that some libraries are imported for basic OS functionalities and to fetch the date and time. After importing these libraries, the SPI port is opened to fetch the data from MCP3008. Next to the SPI port, we will assign variables to store the Gmail ID and password. These values must be the same as your Gmail login credentials. Then the Python code tries to log in to your Gmail account using the e-mail ID and password variables. Exceptions are best handled by the try-except functions. The code should not hang somewhere if there is no Internet access or login access to the RasPi. Rather, it should show that something is wrong. You will understand the try-except function in detail when we discuss e-mail notification in upcoming sections.

After successful login, it searches for the spreadsheet named Logging and selects sheet1 in the Logging spreadsheet. If you will observe the link to the spreadsheet in the web browser in your desktop computer, you will see a long, random number stated as 1eQth-TY4FXFKChB5RFPhelQ6zn47NWDESh13WkXGQAk. This is the key to your spreadsheet. However, you should preferably select the sheet by the ret.open() function as it is a direct and clean way to access the Google spreadsheet.

On calling the function of the SPI, the temperature value will be stored in a variable, which will be then passed to the worksheet.append_row() function to be pushed to the Google spreadsheet.

By running the code, you will be able to see that a new blank row is automatically created and then the temperature value is added, with the latest date and time. Add a graph in the Temperature column and see the live feed updated in the Temperature column.

Tip

To add a graph, click on Insert, select the Chart option, and type Sheet1!B:B in the data range textbox. Give titles to the horizontal and vertical axes and select the type of chart.

I took some ice cubes and a matchbox to simulate the results, and the data feed looks amazing, as shown in the following screenshot:

This experiment will give you a kickstart to interface more sensors. Interface two or more sensors now and you can append the data in the third and fourth columns using the following function:

values = [datetime.datetime.now(), value1, value2, value3]
worksheet.append_row(values)

That's all! You can share this sheet (by clicking on the Share button located at the right corner in the Google spreadsheet and adding the Gmail IDs) with your friends and cousins living far away from you so that they can just check out this cool new featured product developed by you.

Live feed on mobile phones

You can install the Google sheets application in your Android- or iOS-based phone and just see the feed coming from the RasPi on your mobile phone. Just download it from the Play Store or an iStore (the App Store) and enjoy the live feed right from your office. My Android phone's screenshot is as follows: