我怎么获取脉冲数那?
写了这个代码, 可是结果都不对
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 07-01 13:30
# @Author : iie075
# @File : control_hwd.py
# vol_number 单位为
# YF-S201 黑色 F=7.5*Q(L/Min) 误差:±2% 1L: 450个脉冲
# YF-S401 白色 F=5.5*Q(L/Min) 误差:±2% 1L: 330个脉冲
import sys
import time
import os
import RPi.GPIO as GPIO
import subprocess
i = subprocess.call("clear", shell = True)
sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
sys.path.append("..")
pin = 13
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pin, GPIO.IN, pull_up_down = GPIO.PUD_UP)
minutes = 0
# rate of cocunt L/min
# 计数
# tot_cnt = 0
# 常数
constant = 1 / 5.5 / 2
time_new = None
# 计算频率
cf = 1
counter = 0
# 检测到一个脉冲则脉冲数加1
def my_callback(channel):
global counter
if GPIO.event_detected(pin):
counter = counter + 1
# print('counter, 得到脉冲数', counter)
# 在通道上添加上升临界值检测,忽略由于开关抖动引起的小于 200ms 的边缘操作
GPIO.add_event_detect(pin, GPIO.RISING, callback = my_callback, bouncetime = 200)
def calc(t_col = 1):
print('收到流量为: ', t_col, 'L ,开始计算....')
tol_rf = 0
rf = 0
receive_counter = 0
try:
while tol_rf <= t_col:
# print('------------------------------------', tol_rf, t_col)
# 每两秒计算一次, 计算流量
time_new = time.time() + cf
while time.time() <= time_new:
try:
# 计算这个时间内的脉冲数
# 等待脉冲数
pass
except KeyboardInterrupt:
print('\nCTRL C -exit')
GPIO.cleanup()
sys.exit()
# print(rate_cnt, tot_cnt)
counter_tmp = counter - receive_counter
print('得到脉冲数----------------->>>>', counter_tmp, '当前值', counter)
print('\n计算2s')
# 流速
# vf = round(counter_tmp * constant, 4)
vf_s = round(counter_tmp * constant / 60, 4)
# print('Liters / min 流速每分', vf)
print('Liters / s 流速每秒', vf_s)
# 此时间段算出的流量
rf = round(vf_s * 2, 4)
print('Total Liters 此时间段算出的流量', rf)
# print('Time (min & clock) ', minutes, '\t', time.asctime(time.localtime()))
tol_rf = tol_rf + rf
print('此时间段打出的流量: ', tol_rf)
receive_counter = counter
except Exception as e:
print('error !', e)
return 'error'
else:
return 'ok'
finally:
GPIO.remove_event_detect(pin)
GPIO.cleanup()
print('exit !')
def main():
while True:
calc()
if __name__ == '__main__':
# main()
calc()
|