Advertisement
Guest User

Untitled

a guest
Aug 8th, 2021
515
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. import serial
  2. import struct
  3. import binascii
  4. # import pyb
  5. from binascii import hexlify
  6. import time
  7.  
  8. ser = serial.Serial(
  9.     port='COM6',
  10.     baudrate=9600,
  11.     parity=serial.PARITY_NONE,
  12.     stopbits=serial.STOPBITS_ONE,
  13.     bytesize=serial.EIGHTBITS
  14. )
  15. #11 02 0B 01 E1
  16. while 1:
  17.    
  18.     buf = bytearray(19)
  19.     mv = memoryview(buf)
  20.     idx = 0
  21.     #polling the sensor
  22.     ser.write(serial.to_bytes([0x11, 0x02, 0x0b, 0x01, 0xE1]))
  23.     while idx < len(buf):
  24.         if ser.read():
  25.             bytes_read = ser.readinto(mv[idx:])
  26.             # print('Got {} bytes of data'.format(bytes_read), hexlify(buf[idx:idx+bytes_read], b':'))
  27.             idx += bytes_read
  28.     # print('Final buffer =', hexlify(buf, ':'))
  29.     headerValid = False
  30.     #((buf[0] == 0x16) and (buf[1] == 0x11) and (buf[2] == 0x0B))
  31.     #Bug if sensor polling is active: Missing first byte "0x16", maybe because of bad hardware.
  32.     if ((buf[0] == 0x11) and (buf[1] == 0x0B)):  headerValid = True
  33.     if (headerValid==True):
  34.         pm25 = buf[4] * 256  + buf[5]   #PM2.5(μg/m³)= DF3*256+DF4
  35.         pm1 = buf[8]*256^1 + buf[9]     #DF7*256^1 + DF8
  36.         pm10 = buf[12]+256^1 + buf[13]  #DF11*256^1 + DF12
  37.         print('=======================================')
  38.         # print('Received PM 1.0 reading: ', pm1, 'μg/m³') #Wrong sensor?!
  39.         print('Received PM 2.5 reading: ', pm25, 'μg/m³')
  40.         # print('Received PM 10 reading:  ', pm10, 'μg/m³') #Wrong sensor?!
  41.     time.sleep(8)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement