简体   繁体   English

在python中编程温度传感器

[英]Programming a temperature sensor in python

I'm trying to make code for my temperature sensor. 我正在尝试为我的温度传感器制作代码。 Been stuck on a NameError when I try to execute the code. 当我尝试执行代码时,卡在了NameError My question is, does anyone have a clue what I am doing wrong? 我的问题是,有没有人知道我做错了什么?

Code: 码:

import datetime
from sense_hat import SenseHat

def hotwater():
    sense = SenseHat()
    sense.clear()
    celcius = round(sense.get_temperature(), 1)

result = 'temp. C' + str(celcius)
print(result)
result_list = [(datetime.datetime.now(), celcius)]

while __name__ == '__main__':
    Hotwater()

Error: 错误:

Traceback (most recent call last):
    file "/home/pi/Web_test.py", line 9 in <module>
       results= 'temp. C' + str(celcius)
NameError: name 'celcius' is not defined

The variable Celsius is only accessible in the hotwater function. 变量Celsius只能在热水功能中访问。 It cannot be accessed outside of it. 它不能在它之外访问。 To fix the issue, you could move the printing into the hotwater function: 要解决此问题,您可以将打印移动到热水功能:

def hotwater():
    sense = SenseHat()
    sense.clear()
    celcius = round(sense.get_temperature(), 1)
    result = 'temp. C' + str(celcius)
    print(result)
    result_list = [(datetime.datetime.now(), celcius)]

hotwater()

Or, you could have hotwater return celsius: 或者,你可能有热水回流摄氏温度:

def hotwater():
    sense = SenseHat()
    sense.clear()
    celcius = round(sense.get_temperature(), 1)
    return celcius

celcius= hotwater()
result = 'temp. C' + str(celcius)
print(result)
result_list = [(datetime.datetime.now(), celcius)]

Although you could use the global keyword to make celsius accessible everywhere, that is generally frowned upon. 虽然您可以使用global关键字在任何地方访问摄像头,但这通常是不受欢迎的。

Your function fails to returned the value to the main program. 您的函数无法将值返回到主程序。 Variable celcius [sic] is local to the function. 变量celcius [sic]是函数的局部变量。 Also, you've failed to invoke the function where you try to use the value. 此外,您无法调用尝试使用该值的函数。

Follow the examples in your learning materials: call the function, return the value to the main program, and save or use it as needed: 按照学习材料中的示例进行操作:调用函数,将值返回到主程序,并根据需要保存或使用它:

def hotwater():
    sense = SenseHat()
    sense.clear()
    return round(sense.get_temperature(), 1)


if __name__ == '__main__':
    while True:
        celsius = hotwater()
        result = 'temp. C' + str(celcius)
        print(result)
        result_list = [(datetime.datetime.now(), celcius)]

I'm not sure what plans you have for result_list , but I think you'll need to update the code above. 我不确定你对result_list有什么计划,但我认为你需要更新上面的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM