Last active
September 11, 2021 04:18
-
-
Save cassc/3a18ce80a675fb5a79b7d8d7d9312a45 to your computer and use it in GitHub Desktop.
福申FS005甲醛传感器
This file contains hidden or 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
# FS005009 Formaldehyde (HCHO) sensor | |
# 0 1 2 3 4 5 6 7 8 | |
# 起始位 设备类型 单位 小数位数 气体浓度高位 气体浓度低位 满量程高位 满量程低位 校验值 | |
# ff 17 04 00 00 1b 07 d0 f3 | |
# | |
# 气体浓度值=气体浓度高位*256+气体浓度低位, 单位:mg/m3 | |
# Sample output: | |
# ff 17 04 00 00 1b 07 d0 f3 | |
import _thread as thread | |
import time | |
import serial | |
import json | |
import base64 | |
import re | |
class FS005(): | |
def __init__(self, port='/dev/ttyUSB0'): | |
self.port = port | |
self.baudrate = 9600 | |
self.concentration = 0 | |
self.ser = None | |
def start(self): | |
self.ser = serial.Serial( | |
# 这里设置串口端口 | |
port=self.port, | |
baudrate=self.baudrate, | |
parity=serial.PARITY_NONE, | |
stopbits=serial.STOPBITS_ONE, | |
) | |
thread.start_new_thread(self.start_reader, ()) | |
def read(self): | |
return self.concentration | |
def start_reader(self): | |
# wait for serial port | |
while not self.ser.isOpen(): | |
print(f'Waiting device on port {self.port} ...') | |
time.sleep(3) | |
# clear previous data from serial port | |
while self.ser.inWaiting() > 0: | |
n = self.ser.inWaiting() | |
self.ser.read(self.ser.inWaiting()) | |
time.sleep(0.1) | |
# start reading loop | |
while True: | |
data = self.ser.read_all() | |
if not data: | |
time.sleep(1) | |
continue | |
if len(data) != 9: | |
print(f'Invalid data len: {data}') | |
continue | |
if list(data[:4]) != [0xff, 0x17, 0x04, 0x00]: | |
print(f'Invalid data: {data[:4]}') | |
continue | |
low = data[5] | |
high = data[4] | |
val = (high * 256 + low) / 1000.0 | |
self.concentration = val | |
if __name__ == '__main__': | |
reader = FS005('/dev/ttyUSB0') | |
reader.start() | |
while True: | |
print(f'val: {reader.read()}') | |
time.sleep(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment