python - 如何执行第二个功能?
问题描述
我已将心率传感器正确连接到 Raspberry Pi。
现在:[程序运行没有错误,但第二个函数(send_data)不起作用。]
第一个功能:读取传感器值。第二个功能:发送数据。
传感器工作正常。但是传感器数据没有发送,第二个功能不起作用。为了解决这个问题,我付出了很多努力。
'''
import requests
import time
import Adafruit_ADS1x15
thingspeak_key = "API_KEY"
class hr:
def __init__(self):
adc = Adafruit_ADS1x15.ADS1015()
GAIN = 2/3
curState = 0
thresh = 525
P = 512
T = 512
stateChanged = 0
sampleCounter = 0
lastBeatTime = 0
firstBeat = True
secondBeat = False
Pulse = False
IBI = 600
rate = [0]*10
amp = 100
lastTime = int(time.time()*1000)
while True:
Signal = adc.read_adc(0, gain=GAIN)
curTime = int(time.time()*1000)
sampleCounter += curTime - lastTime;
lastTime = curTime
N = sampleCounter - lastBeatTime;
if Signal < thresh and N > (IBI/5.0)*3.0 :
if Signal < T :
T = Signal;
if Signal > thresh and Signal > P:
P = Signal;
if N > 250 :
if (Signal > thresh) and (Pulse == False) and (N > (IBI/5.0)*3.0) :
Pulse = True;
IBI = sampleCounter - lastBeatTime;
lastBeatTime = sampleCounter;
if secondBeat :
secondBeat = False;
for i in range(0,10):
rate[i] = IBI;
if firstBeat :
firstBeat = False;
secondBeat = True;
continue
runningTotal = 0;
for i in range(0,9):
rate[i] = rate[i+1];
runningTotal += rate[i];
rate[9] = IBI;
runningTotal += rate[9];
runningTotal /= 10;
BPM = 60000/runningTotal;
self.data_hr=str(BPM)
print ('BPM: {}'.format(self.data_hr))
if Signal < thresh and Pulse == True :
Pulse = False;
amp = P - T;
thresh = amp/2 + T;
P = thresh;
T = thresh;
if N > 2500 :
thresh = 512;
P = 512;
T = 512;
lastBeatTime = sampleCounter;
firstBeat = True;
secondBeat = False;
print ("no beats found")
def send_data(self):
r = requests.post('https://api.thingspeak.com/update?api_key=API_KEY', data = {'api_key':thingspeak_key, 'field1':format(self.data_hr)})
time.sleep(0.005)
if __name__ == "__main__":
x=hr()
x.self.send_data()
'''
解决方案
您的问题来自:
if __name__ == "__main__":
__init__("self")
您正在尝试直接调用该类的构造函数,并且由于它是本地范围,python 不知道__init__
它已在其中定义的类之外的内容。此外,"self"
是一个字符串,而不是一个对象。
您可以将其替换为:
if __name__ == '__main__':
heartrate = hr()
这将创建一个对象并调用构造函数。您不需要添加self
,因为 python 已经知道类构造函数指的是什么。
但是,您会陷入hr
类构造函数的 while 循环中,因此我建议将您的构造函数(__init__
函数)拆分为单独的函数并分别调用它们。
推荐阅读
- python - 如何在给定的边界框(lon1,lon2,lat1,lat2)内通过时间获得变量的平均值?
- dart - Matrix4 参数在间接传递给 Transform 时表现不同
- wsdl - 如何在 First Data 全球网关 e4 中使用第一个数据令牌?
- android - 我以编程方式使用来自 android 的内容值添加了谷歌日历事件
- phpspreadsheet - 使用 phpspreadsheet 的多行标题
- ionic-framework - 如何在离子滑块中延迟加载图像?
- chromecast - 用 chromecast 连接谷歌助手(如 netflix)
- docker - 当我在 gitlab ci before_script 中使用 apt 时找不到 apt
- mysql - 具有子值的 MySQL 递归查询
- angular - Angular 5:材质下拉列表的事件处理