forked from elecfreaks/Octopus_MicroPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtmp36.py
More file actions
64 lines (49 loc) · 1.58 KB
/
tmp36.py
File metadata and controls
64 lines (49 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from microbit import *
class TMP36:
def __init__(self, pin):
"""基本描述
TMP36温度传感器
Args:
pin: 连接TMP36的模拟引脚
Returns:
temperature 摄氏温度
"""
self._pin = pin
self._temperature = 25.0 # 初始温度值
def read(self, unit='C'):
"""
读取温度
Args:
unit: 温度单位, 'C' 表示摄氏温度, 'F' 表示华氏温度
Returns:
float: 温度值
"""
# 读取模拟值 (0-1023)
analog_value = self._pin.read_analog()
# 转换为电压 (0-3.3V)
voltage = analog_value * 3.3 / 1023.0
# 应用TMP36公式: 温度 = (电压 - 0.5) * 100
self._temperature = (voltage - 0.5) * 100
if unit.upper() == 'F':
# 转换为华氏温度
return self._temperature * 9 / 5 + 32
else:
# 返回摄氏温度
return self._temperature
def get_temperature(self, unit='C'):
"""
读取温度
Args:
unit: 温度单位, 'C' 表示摄氏温度, 'F' 表示华氏温度
Returns:
float: 温度值
"""
return self.read(unit)
if __name__ == '__main__':
sensor = TMP36(pin1) # 假设TMP36连接到pin1
while True:
temp_c = sensor.get_temperature('C')
temp_f = sensor.get_temperature('F')
print("TMP36_temperature_C: {:.2f}C".format(temp_c))
print("TMP36_temperature_F: {:.2f}F".format(temp_f))
sleep(1000)