Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import serial
- import struct
- import binascii
- # import pyb
- from binascii import hexlify
- import time
- ser = serial.Serial(
- port='COM6',
- baudrate=9600,
- parity=serial.PARITY_NONE,
- stopbits=serial.STOPBITS_ONE,
- bytesize=serial.EIGHTBITS
- )
- #11 02 0B 01 E1
- while 1:
- buf = bytearray(19)
- mv = memoryview(buf)
- idx = 0
- #polling the sensor
- ser.write(serial.to_bytes([0x11, 0x02, 0x0b, 0x01, 0xE1]))
- while idx < len(buf):
- if ser.read():
- bytes_read = ser.readinto(mv[idx:])
- # print('Got {} bytes of data'.format(bytes_read), hexlify(buf[idx:idx+bytes_read], b':'))
- idx += bytes_read
- # print('Final buffer =', hexlify(buf, ':'))
- headerValid = False
- #((buf[0] == 0x16) and (buf[1] == 0x11) and (buf[2] == 0x0B))
- #Bug if sensor polling is active: Missing first byte "0x16", maybe because of bad hardware.
- if ((buf[0] == 0x11) and (buf[1] == 0x0B)): headerValid = True
- if (headerValid==True):
- pm25 = buf[4] * 256 + buf[5] #PM2.5(μg/m³)= DF3*256+DF4
- pm1 = buf[8]*256^1 + buf[9] #DF7*256^1 + DF8
- pm10 = buf[12]+256^1 + buf[13] #DF11*256^1 + DF12
- print('=======================================')
- # print('Received PM 1.0 reading: ', pm1, 'μg/m³') #Wrong sensor?!
- print('Received PM 2.5 reading: ', pm25, 'μg/m³')
- # print('Received PM 10 reading: ', pm10, 'μg/m³') #Wrong sensor?!
- time.sleep(8)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement