Skip to content

Instantly share code, notes, and snippets.

@gnawux
Created December 24, 2015 17:04
Show Gist options
  • Save gnawux/bce023fd769368db0c2d to your computer and use it in GitHub Desktop.
Save gnawux/bce023fd769368db0c2d to your computer and use it in GitHub Desktop.
Display the PM 2.5 numbers on 1602 LCD via I2C Bus
#!/usr/bin/env python
import RPi.GPIO as GPIO
import serial
import pylcdlib
# pylcdlib from https://gist.github.com/gnawux/4f68b8e301b203489336
def readbe16(s, pos):
return ( ord(s[pos])<<8) + ord(s[pos+1])
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)
GPIO.output(17, True)
# define bus address, port, and pins
display = pylcdlib.lcd(0x27,1, Rs=0, Rw=1, En=2, Backlight=3, D4=4, D5=5, D6=6, D7=7)
display.lcd_clear()
ser = serial.Serial("/dev/ttyAMA0")
ser.baudrate=9600
data = ser.read(32)
pos = 0
while True:
pos = data[pos:].index(chr(0x42))
if ord(data[(pos+1)&31]) == 0x4d:
print('found BM at %d' % (pos))
ser.read(pos)
break
pos = pos + 1
if pos > 31:
print('frame format error')
exit(1)
l1d=-1
l2d=-1
while True:
data = ser.read(32)
if data[0] != 'B' or data[1] != 'M':
print('frame format error while reading data: %s, %s' % (data[:2], data))
exit(1)
length = readbe16(data, 2)
if length != 28:
print('length error : %d' % (length))
exit(1)
pm25std = readbe16(data, 6)
pm25atm = readbe16(data, 12)
if l1d != pm25std:
l1d = pm25std
display.lcd_puts('std: %d ug/m3' % l1d,1)
if l2d != pm25atm:
l2d = pm25atm
display.lcd_puts('atm: %d ug/m3'% l2d,2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment