首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >咖啡烘焙程序,我如何编写一个程序,对温度读数的样本进行排序,并且只返回最低的10个平均值?

咖啡烘焙程序,我如何编写一个程序,对温度读数的样本进行排序,并且只返回最低的10个平均值?
EN

Stack Overflow用户
提问于 2019-06-25 08:44:28
回答 1查看 105关注 0票数 1

我正在使用Python为Artisan范围内的烘焙软件运行的程序构建脚本。这个程序已经可以在我的设备( 1045_1B)上运行了,但我需要对温度读数做更多的过滤。我希望程序以32ms的速度采样,并按升序组织每秒30个样本。然后,我希望最低的10个样本是平均的,并返回到Artisan软件中进行绘图。

这就是我到目前为止所拥有的,但在给Artisan一个温度读数之前,我需要帮助弄清楚如何组织样本并对它们进行平均。

代码语言:javascript
复制
import sys
import time
import traceback

from Phidget22.Devices.TemperatureSensor import *
from Phidget22.PhidgetException import *
from Phidget22.Phidget import *
from Phidget22.Net import *

try:
    from PhidgetHelperFunctions import *
except ImportError:
    sys.stderr.write("\nCould not find PhidgetHelperFunctions. Either add PhdiegtHelperFunctions.py to your project folder "
                      "or remove the import from your project.")
    sys.stderr.write("\nPress ENTER to end program.")
    readin = sys.stdin.readline()
    sys.exit()


def onAttachHandler(self):

    ph = self
    try:
        #If you are unsure how to use more than one Phidget channel with this event, we recommend going to
        #www.phidgets.com/docs/Using_Multiple_Phidgets for information

        print("\nAttach Event:")


        channelClassName = ph.getChannelClassName()
        serialNumber = ph.getDeviceSerialNumber()
        channel = ph.getChannel()



        ph.setDataInterval(32)


        ph.setTemperatureChangeTrigger(0)



    except PhidgetException as e:
        print("\nError in Attach Event:")
        DisplayError(e)
        traceback.print_exc()
        return


def onDetachHandler(self):

    ph = self
    try:





    except PhidgetException as e:
        print("\nError in Detach Event:")
        DisplayError(e)
        traceback.print_exc()
        return


def onErrorHandler(self, errorCode, errorString):

    sys.stderr.write("[Phidget Error Event] -> " + errorString + " (" + str(errorCode) + ")\n")

"""
* Outputs the TemperatureSensor's most recently reported temperature.
* Fired when a TemperatureSensor channel with onTemperatureChangeHandler registered meets DataInterval and ChangeTrigger criteria
*
* @param self The TemperatureSensor channel that fired the TemperatureChange event
* @param temperature The reported temperature from the TemperatureSensor channel
"""
def onTemperatureChangeHandler(self, temperature):

    #If you are unsure how to use more than one Phidget channel with this event, we recommend going to
    #www.phidgets.com/docs/Using_Multiple_Phidgets for information

    print("[Temperature Event] -> Temperature: " + str(temperature))


"""
* Prints descriptions of how events related to this class work
"""
def PrintEventDescriptions():

    print("\n--------------------\n"
        "\n  | Temperature change events will call their associated function every time new temperature data is received from the device.\n"
        "  | The rate of these events can be set by adjusting the DataInterval for the channel.\n"
        "  | Press ENTER once you have read this message.")
    readin = sys.stdin.readline(1)

    print("\n--------------------")

"""
* Creates, configures, and opens a TemperatureSensor channel.
* Displays Temperature events for 10 seconds
* Closes out TemperatureSensor channel
*
* @return 0 if the program exits successfully, 1 if it exits with errors.
"""
def main():
    try:

        ch = TemperatureSensor()
        ch.setOnAttachHandler(onAttachHandler)

        ch.setDeviceSerialNumber(424909)
        ch.setChannel(0)
        ch.openWaitForAttachment(5000)
        ch.setTemperatureChangeTrigger(0)



        ch.setOnDetachHandler(onDetachHandler)

        ch.setOnErrorHandler(onErrorHandler)

        #This call may be harmlessly removed
        PrintEventDescriptions()

        ch.setOnTemperatureChangeHandler(onTemperatureChangeHandler)


        try:
            ch.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch)
            raise EndProgramSignal("Program Terminated: Open Failed")


        time.sleep(1)

        return 0

    except PhidgetException as e:
        sys.stderr.write("\nExiting with error(s)...")
        DisplayError(e)
        traceback.print_exc()
        print("Cleaning up...")
        ch.close()
        return 1
    except EndProgramSignal as e:
        print(e)
        print("Cleaning up...")
        ch.close()
        return 1
    except RuntimeError as e:
         sys.stderr.write("Runtime Error: \n\t" + e)
         traceback.print_exc()
         return 1
    finally:
        print("Press ENTER to end program.")
        readin = sys.stdin.readline()

main()
EN

回答 1

Stack Overflow用户

发布于 2019-06-25 13:16:22

您首先需要的是某种类型的缓冲区来保存记录值,直到您有足够的值来处理它们。例如,您可以使用python列表::

代码语言:javascript
复制
# in onAttachHandler:
# init buffer
global buffer
buffer = []

在onTemperatureChangeHandler中,将值存储在缓冲区中。一旦缓冲区满了,计算你的平均值,然后传递该值。

代码语言:javascript
复制
# in onTEmperatureChangeHandler
global buffer
buffer.append(temperature)
if len(buffer) > 30:
    buffer.sort()
    mean_temperature = sum(buffer[:10]) / 10.0
    buffer = []
    # Do something with mean_temperature here

也就是说,这里使用的全局变量被认为是糟糕的风格,这是有充分理由的。应该通过定义一个类来改进代码,该类将缓冲区和所有处理程序作为属性。有很多关于这方面的Python教程。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56745473

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档