《Raspberry Pi安裝套件》
sudo apt-get install -y python3-libgpiod
《Raspberry Pi範例程式(Python3),檔名pigpiod_read_g5.py》
#!/usr/bin/python3
#
# source: https://github.com/raspberrypi-tw/PiM25/
#
# 使用方法
# python3 pigpiod_read_g5.py 23
import sys
import time
import pigpio
import subprocess
try:
G5T_GPIO = int(sys.argv[1])
except Exception as e:
print(e)
print("Usage: python3 pigpiod_read_g5t.py <PIN>")
exit()
ret = subprocess.Popen("sudo pidof pigpiod", shell=True, stdout=subprocess.PIPE).stdout.read()
if ret:
pi = pigpio.pi()
else:
print("pigpiod was not running")
ret = subprocess.call("sudo pigpiod", shell=True)
time.sleep(0.5)
pi = pigpio.pi()
def read_g5t(pin=G5T_GPIO):
try:
pi.bb_serial_read_open(G5T_GPIO, 9600)
time.sleep(1)
size, data = pi.bb_serial_read(G5T_GPIO)
try:
import struct
except ImportError:
import ustruct as struct
buffer = []
data = list(data)
buffer += data
while buffer and buffer[0] != 0x42:
buffer.pop(0)
if len(buffer) > 200:
buffer = [] # avoid an overrun if all bad data
if buffer[1] != 0x4d:
buffer.pop(0)
check = sum(buffer[0:30])
chksum = buffer[30]*256 + buffer[31]
if check == chksum:
print("==========", time.ctime(),"==========")
PM1 = buffer[10]*256 + buffer[11]
PM25 = buffer[12]*256 + buffer[13]
PM10 = buffer[14]*256 + buffer[15]
#print(PM1, PM25, PM10)
print("PM1: {} ug/m3".format(PM1))
print("PM2.5: {} ug/m3".format(PM25))
print("PM10: {} ug/m3".format(PM10))
Temp = (buffer[24]*256 + buffer[25])/10
Humd = (buffer[26]*256 + buffer[27])/10
print("Temp: {} ℃".format(Temp))
print("Humd: {} %".format(Humd))
#print(buffer[28])
except Exception as e:
print("No data received!")
print(e)
finally:
pi.bb_serial_read_close(G5T_GPIO)
if __name__ == '__main__':
while True:
read_g5t()
time.sleep(1)