如何平均一个变量的最后十个实例,并显示

问题描述:

喜女士和先生们,如何平均一个变量的最后十个实例,并显示

,请原谅我,如果我输入下面的代码错了,因为这是我第一次在这里发布。我在这里有一个python脚本,每隔十分之一秒轮询一个电容器,目前正在使用一个光敏电阻来确定外部亮度。

唯一的问题是数值通常会偏差+/- 5左右。我想实现一行代码,它每秒钟平均最后10次民意调查并打印出来。我不知道从哪里开始,任何帮助将不胜感激!

#!/usr/local/bin/python 
import RPi.GPIO as GPIO 
import time 
import I2C_LCD_driver 
GPIO.setmode(GPIO.BOARD) 
mylcd = I2C_LCD_driver.lcd() 
#define the pin that goes to the circuit 
pin_to_circuit = 40 
def rc_time (pin_to_circuit): 
    count = 0 

    #Output on the pin for 
    GPIO.setup(pin_to_circuit, GPIO.OUT) 
    GPIO.output(pin_to_circuit, GPIO.LOW) 
    time.sleep(0.1) 

    #Change the pin back to input 
    GPIO.setup(pin_to_circuit, GPIO.IN) 

    #Count until the pin goes high 
    while (GPIO.input(pin_to_circuit) == GPIO.LOW): 
     count += 1 

    return count 

#Catch when script is interrupted, cleanup correctly 
try: 
    # Main loop 
    while True: 
     print "Current date & time " + time.strftime("%c") 
     print rc_time(pin_to_circuit) 
     a = rc_time(pin_to_circuit) 
     mylcd.lcd_display_string("->%s" %a) 
     mylcd.lcd_display_string("%s" %time.strftime("%m/%d/%Y %H:%M"), 2) 
     except KeyboardInterrupt: 
    pass 
finally: 
    GPIO.cleanup() 

你可以在你的主循环定义的列表:

polls = [] 
#Catch when script is interrupted, cleanup correctly 
try: 
    # Main loop 
    while True: 
     print "Current date & time " + time.strftime("%c") 
     print rc_time(pin_to_circuit) 
     a = rc_time(pin_to_circuit) 
     #add current poll to list of polls 
     polls.append(a) 
     #remove excess history 
     if len(polls) > 10: 
      polls.pop(0) 
     #calculate average 
     avg = sum(polls)/len(polls) 
     mylcd.lcd_display_string("->%s" %avg) 
     mylcd.lcd_display_string("%s" %time.strftime("%m/%d/%Y %H:%M"), 2) 
except KeyboardInterrupt: 
    pass 
finally: 
    GPIO.cleanup() 
+0

文件 “lightres1.py”,行43 除了一个KeyboardInterrupt: ^ 语法错误:无效的语法 –

+0

感谢您的帮助,上面的错误是我在尝试执行脚本时收到的内容 –

+0

我现在还没有在我面前有一个pi,所以无法直接测试,但如果您复制并粘贴了我的代码,则可能是缩进。我编辑了我的帖子来修复缩进。 – BHawk