파이썬/마이크로파이썬 센서 로거: 센서 데이터를 구글 시트에 원활하게 저장하기
센서 값을 구글 시트에 직접 기록하는 강력한 시스템입니다. 마이크로컨트롤러를 가벼운 서버와 간단한 HTTP 요청으로 연결하고, gspread 라이브러리로 데이터를 씁니다.
시작 전 gspread 문서의 OAuth2 설정 지침을 따라 대상 스프레드시트 접근 권한을 스크립트에 부여하세요.
하드웨어 연결
- D0 to RST: 딥슬립에서 보드 깨우기 위해 필수.
- + to 3.3V on the Wemos.
- – to GND on the Wemos.
- Signal to A0 on the Wemos.
문제 발생 시 댓글로 알려주시면 문제 해결을 도와드리겠습니다.
회로도
코드
import machine
import urequests
import time
# RTC handles deep-sleep wake-ups
rtc = machine.RTC()
rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
# ADC pin for sensor voltage
adc = machine.ADC(0)
######################
# Sensor calibration
######################
# Reference values (inverse ×1000)
# Dry air = 759 (0 %) → 1.31752305665349143610013175231
# Water = 382 (100 %) → 2.61780104712041884816753926702
# Difference = 1.30027799046692741206740751471
# 1 % relative humidity = 0.0130027799046692741206740751471
hours = str(time.localtime()[3])
mins = str(time.localtime()[4])
secs = str(time.localtime()[5])
if int(secs) < 10:
secs = '0' + secs
if int(mins) < 10:
mins = '0' + mins
timestr = f"{hours}:{mins}:{secs}"
# Convert ADC reading to relative humidity (%)
variable = (((1 / adc.read()) * 1000) / 0.0130027799046692741206740751471) - 101
variable = max(0, min(100, variable))
# Send data to local endpoint
url = 'https://192.168.1.2:8000/solomon'
headers = {'content-type': 'application/json'}
data = f'{{"Value":"{variable}","Time":"{timestr}"}}'
resp = urequests.post(url, data=data, headers=headers)
print(resp.json())
# Schedule next reading after 25 s and enter deep-sleep
rtc.alarm(rtc.ALARM0, 25000)
machine.deepsleep()
출처: Python/MicroPython Sensor Logger for Google Sheets