Light and Temp logging to Google Doc`s

This is a quick one which pulls in two off previous tutorials the photocell one comes from Adafruit and the Temp is mine..

Photcell and DS18B20 (temp logging and upload to google doc`s).

I combined the code so both the light values and temp readings were both being uploaded to the spread sheet. In order for the upload to google doc`s to work please follow the instructions on the DS18B20 tutorial.

If you want to code to run unattended just put a & at the end and it will create and give you a process ID. One note – you must have the spreadsheet open on a machine , it will not log the data otherwise.


import os, glob, time, gspread, sys, datetime , RPi.GPIO as GPIO


#Google account details
email = 'your gmail address'
password = 'your gmail password'
spreadsheet = 'the name of your spread sheet' #the name of the spreadsheet already created

#attempt to log in to your google account
    gc = gspread.login(email,password)

#open the spreadsheet
worksheet =

#initiate the temperature sensor
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

#set up the location of the sensor in the system
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
print ("Code is running")

def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c

def RCtime (RCpin):
        reading = 0
        GPIO.setup(RCpin, GPIO.OUT)
        GPIO.output(RCpin, GPIO.LOW)

        GPIO.setup(RCpin, GPIO.IN)
        # This takes about 1 millisecond per loop cycle
        while (GPIO.input(RCpin) == GPIO.LOW):
                reading += 1
        return reading

# Return CPU temperature as a character string
def getCPUtemperature():
    res = os.popen('vcgencmd measure_temp').readline()
    return res

while True: #infinite loop
    print ("loop is running")
    tempin = read_temp() #get the temp sensor
    temppi = getCPUtemperature() #get the pi temp
    light = RCtime(18) #get light value
    values = [, tempin , temppi , light]
    worksheet.append_row(values) #write to the spreadsheet
    time.sleep(300) #wait 5 minutes
Tagged , , , . Bookmark the permalink.

Comments are closed.