D
@dnear1 said in Fipy issues with IF statements:
')
Cleaned up and comments added
import os
import math
from machine import UART
uart = UART(1, 9600) # init with given baudrate
uart.init(9600, bits=8, parity=None, stop=1) # init with given parameters
#while True:
# data = uart.readall()
# if data is not None:
# print(data)
while 1:
data = uart.readall()# get everything from the serial buffer
if data is not None:#make sure it's not an empty buffer
bytestream=data.split(b'BM')[1][0:31]# HPMA sends 32 byte packets that start with \x42\x4D ('BM')
if len(bytestream)==30:#check that we actually got 30 bytes (excluding the data we split out)
if bytestream[0:2]==b'\x00\x1c':#HPMA packet is always 28 data bytes(excluding start header and checksum)
checksum=143#since split command removed the \x42\x4D, add them back to get correct checksum
validated=0
for i in range(0,28):
checksum+=bytestream[i]#cycle thru the data values and add them up
validated=int(bytestream[28])*256+int(bytestream[29])#read checksum bytes from packet and make them a 2-byte integer
if checksum==validated:# both values should match, else we have a corrupt packet
pm25=int(bytestream[4])*256+int(bytestream[5])#these two bytes represent the particulate detected that's 2.5um large
pm10=int(bytestream[6])*256+int(bytestream[7])#these two bytes represent the particulate detected that's 10um large
print('pm2.5 = ',pm25)
print('pm10 = ',pm10)
else:
print('checksum failed')
else:
print('invalid packet length')
else:
print('incomplete packet')