我正在使用模拟数字转换器测量电池的参数(电流、电压等)。“While-loop”循环还包含测量函数,这些函数在此上下文中未显示,因为它们不是我问题的一部分
使用下面的代码,我试图计算循环(Ahinst)每次迭代的安培/小时数,简单地将测量的电流乘以两次测量之间经过的时间。我还对Ah进行了汇总,得到了电池电量的累积值(TotAh)。最后一个值仅在电流(P2)为负时显示(蓄电池未处于充电模式)。当电流(P2)反向进入充电模式时,我清除TotAh并仅显示0
timeMeas=[]
currInst=[]
Ah=[]
TotAh=0
while(True):
try:
#measurements routines are also running here
#......................
#Ah() in development
if (P2 < 0): #if current is negative (discharging)
Tnow = datetime.now() #get time_start reference to calculate elapsed time until next current measure
timeMeas.append (Tnow) #save time_start
currInst.append (P2) #save current at time_start
if (len(currInst) >1): #if current measurements are two
elapsed=(timeMeas[1]-timeMeas[0]).total_seconds() #calculate time elapsed between two mesurements
Ahinst=currInst[1]/3600*elapsed #calculate Ah per time interval
Ah.append(Ahinst) #save Ah per time interval
TotAh=round(sum(Ah),3)* -1 #update cumulative Ah
timeMeas=[] #cleanup data in array
currInst=[] #cleanup data in array
elif (P2 > 0):
TotAh=0
Ah=[]
time.sleep(1)
except KeyboardInterrupt:
break
代码正在运行,但显然没有给出正确的结果,因为在第二个“if”条件下,我总是清除两个数组(timeMeas和CurrInst)。由于计算需要至少两个实际测量值“if(len(currInst)>;1)”才能工作,因此清除两个阵列会导致在循环的每次迭代中丢失一个测量值。我曾考虑过在每次迭代时将数组中的值位置从0移到1,但在值P2反转为充电然后再次放电模式后重新开始循环时,这会导致计算错误
我对编码很生疏,做这件事是出于爱好。我正在努力找到一个解决方案,用实际值计算每个周期的“Ahinst”。 感谢您的帮助。谢谢
如果您只想保留两个测量值(当前和以前),那么可以保留大小为2的数组,并在循环末尾使用
idx = 1 - idx
使其在0和1之间进行触发器转换在某种意义上,使用两个
dict
变量curr
和prev
并在启动或重置它们时设置prev = None
会更简单。然后只需在循环结束时设置curr = prev
,并在每次迭代中用新值填充curr
,如curr['when'] = datetime.now()
和curr['measurement'] = P2
相关问题 更多 >
编程相关推荐