Created
April 11, 2017 08:23
-
-
Save cwyark/d0c8ed50b9ff41a934c3679407e8f277 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from umachine import UART | |
import utime as time | |
debug = False | |
class Driver: | |
def __init__(self, uart): | |
if type(uart) is not UART: | |
raise ValueError("%s is not a valid type" % uart) | |
self.uart = uart | |
def readMsg(self): | |
# At least wait for 1 sec for incomming message | |
time.sleep_ms(1200) | |
buffer = bytearray(7) | |
counter = 0 | |
while True: | |
char = self.uart.read(1) | |
if char == b'\xaa': | |
counter = 0 | |
buffer[counter] = int.from_bytes(char, 'little') | |
counter += 1 | |
if char == b'\xff': | |
break | |
if debug: | |
print("recvived buffer :" + buffer) | |
if buffer[0] != 0xAA and buffer[6] != 0xFF: | |
raise OSError("Invalid MSG format") | |
return buffer | |
def parseMsg(self, msg): | |
pm25 = (msg[1] * 256 + msg[2]) * 0.1 | |
pm10 = (msg[3] * 256 + msg[4]) * 0.1 | |
# should check the CRC | |
crc = msg[5] | |
if debug: | |
print("parse message: pm25 = %d, pm10=%d, crc = 0x%x" % (pm25, pm10, crc)) | |
return (pm25, pm10, crc) | |
def getData(self): | |
msg = self.readMsg() | |
pm25, pm10, crc = self.parseMsg(msg) | |
return (pm25, pm10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment