如何平均变量和显示的最后十个实例

时间:2017-09-22 22:13:56

标签: python raspberry-pi

嗨女士们,先生们,

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

唯一的问题是数值经常变化大约+/- 5.我想实现一行代码,每秒平均最后十次轮询并打印它们。我不知道从哪里开始,任何帮助将不胜感激!!

#!/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()

1 个答案:

答案 0 :(得分:0)

您可以在主循环中定义一个列表:

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()