#1. 在 Google Cloud Consel 要啟用 Google Sheet API ,並且將產生的 json 檔案存放到 pythont 程式的相同目錄
#2. 在 Google Sheets的工作表上要新增共享權限到剛剛啟用的 Google Sheet API 的 service account
#3. 安裝 python 的 google-api-python-client 模組
pip3 install --upgrade google-api-python-client
#4. 安裝 python 的 pygsheets 模組
pip3 install pygsheets
========= python 端程式 ===========
#coding:utf-8
import serial
import sys
import time
import pygsheets
port = "/dev/tty.usbmodem1421"
serialArduino = serial.Serial(port, 9600)
serialArduino.flushInput()
#google API
gc = pygsheets.authorize(service_file='pythongoogle.json')
sh = gc.open('pythontest')
wks = sh[0]
rowCount = 2
while True:
input = serialArduino.readline()
temp = str(input[0:5],'utf-8')
humi = str(input[-7:-2],'utf-8')
now = time.strftime("%Y/%m/%d %H:%M:%S")
print(now + ' > ' + 'Temperature: ' + temp + '°C ,Humidity: ' + humi + '%')
# proc cells
try:
rowCount=int(wks.get_value('A1'))
if rowCount > 998 :
print("google sheet row is full , exit the process")
sys.exit()
wks.update_cell((rowCount,1), now)
wks.update_cell((rowCount,2), temp)
wks.update_cell((rowCount,3), humi)
print("writen " + str(rowCount-2) + " records in sheets")
rowCount = rowCount + 1
wks.update_cell((1,1), rowCount)
except Exception as exec:
print('update the google sgeet is fail, pls check the networking connect ....')
sys.exit()
===============================
=============================== Arduino 程式 ===============
#include <SHT1x.h>
// Specify data and clock connections and instantiate SHT1x object
#define dataPin 10
#define clockPin 11
SHT1x sht1x(dataPin, clockPin);
void setup()
{
Serial.begin(9600); // Open serial connection to report values to host
// Serial.println("Starting up");
}
void loop()
{
float temp_c;
float temp_f;
float humidity;
// Read values from the sensor
temp_c = sht1x.readTemperatureC();
temp_f = sht1x.readTemperatureF();
humidity = sht1x.readHumidity();
// Print the values to the serial port
Serial.print(temp_c, DEC);
Serial.print(",");
Serial.println(humidity);
delay(300000);
}
沒有留言:
張貼留言