我正在使用模数转换器测量电池参数(电流、电压等)。 “While 循环”循环还包含在此上下文中未显示的测量函数,因为这不是我的问题的一部分。
使用下面的代码,我试图计算循环 (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”。 任何帮助表示赞赏。谢谢
答案 0 :(得分:1)
如果您只想保留两个测量值(当前和上一个),您可以保留大小为 2 的数组,并在循环末尾使用 idx = 1 - idx
使其在 0 和 1 之间触发器。>
timeMeas = [None, None]
currInst = [None, None]
TotAh = 0.0
idx = 0
while True: # no need for parentheses
try:
if (P2 < 0):
Tnow = datetime.now()
timeMeas[idx] = Tnow
currInst[idx] = P2
if currInst[1] is not None: #meaning we have at least two measurements
elapsed = (timeMeas[idx]-timeMeas[1-idx]).total_seconds()
TotAh + = currInst[idx]/3600*elapsed
elif (P2 > 0): # is "elif" really correct here?
TotAh = 0.0
# Do we want to reset these, too?
timeMeas = [None, None]
currInst = [None, None]
# should this really be inside the elif?
time.sleep(1)
idx = 1 - idx
except KeyboardInterrupt:
break
从某种意义上说,拥有两个 dict
变量 curr
和 prev
会更简单,并在您启动或重置它们时设置 prev = None
。然后只需在循环结束时设置 curr = prev
,并在每次迭代中使用新值填充 curr
,例如 curr['when'] = datetime.now()
和 curr['measurement'] = P2
。