การทดลองนี้เพื่อส่งค่าอุณหภูมิจาก Raspberry Pi เข้าไปเก็บไว้ ใน Google Spread Sheet ที่เราสร้างไว้
อุปกรณ์การทดลอง
1.Raspberry pi Board 2.สาย LAN สำหรับ Remote จาก PC 3.Resistor 10k 4.DS18B20 sensor
ขั้นตอนการเตรียมการ
$ sudo apt-get install python-smbus $ sudo apt-get install i2c-tools $ sudo raspi-config Select "Advanced Options" Select "I2C" Select "Yes" Select "Yes" $ sudo apt-get update $ sudo apt-get install python-pip $ sudo pip install gspread oauth2client $ sudo apt-get install python-openssl
Exception Can't install oauth2client
หากเจอปัญหา ไม่สามารถลง oauth2client ได้
แก้ไขได้โดย $ sudo python -m pip install --upgrade --force setuptools $ sudo python -m pip install --upgrade --force pip
อ้างอิงจาก link นี้
เตรียม OAuth.json download จาก Window แล้วนำไปใส่ใน Rpi
(1.)ไปยัง https://console.developers.google.com และ log in Google IDของท่าน
(2.)เลือก Create Credential -> OAuth client ID
![]()
(3.)เลือก Other แล้วตั้งชื่อ
![]()
(4.)Enable APi เพื่อให้สามารถเข้าถึง Google sheetได้
![]()
(5.)คลิก Download JSON จะได้ ไฟล์ .JSON มา แล้วนำไปไว้ใน RPi
![]()
เข้าไปสร้าง Google Sheet
สร้างไฟล์และตั้งชื่อ ตัวอย่างเช่น tempDS18B20
![]()
เตรียมการเรียบร้อย
ลุยโค้ดเลยจร้า
Code python for live temperature google sheet
import os
import glob
import time
import datetime
import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('My Project Raspberry-8d52fa6a989c.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open("tempDS18B20").sheet1 #ชื่อไฟล์ต้องตรงกับที่สร้างไว้ใน Google Sheet
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
def read_temp_raw():
f = open(device_file, 'r')
lines = f.readlines()
f.close()
return lines
def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
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
while True:
x = 0
temp_c = read_temp()
times = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
for values in wks.col_values(1):
x = x + 1
rowToAdd = [times,temp_c]
wks.resize(x)
wks.append_row(rowToAdd)
print"temperature = " + str(read_temp())
time.sleep(0.3)
Per Akt's Thanachai
base_dir = '/sys/bus/w1/devices/'
ตอบลบdevice_folder = glob.glob(base_dir + '28*')[0]
อยากสอบถามความหมายของ2บรรทัดนี้ค่ะ