ds18b20温度传感器quecpython的代码
时间: 2023-07-02 22:20:19 浏览: 134
51单片机读取DS18B20温度传感器代码
5星 · 资源好评率100%
下面是使用QuecPython编写的ds18b20温度传感器的代码:
```python
from machine import Pin
import time
pin = Pin(Pin.GPIO3, Pin.OUT)
def delay_us(us):
time.sleep_us(us)
def write_bit(bit):
pin.value(0)
delay_us(2)
if bit:
pin.value(1)
delay_us(60)
pin.value(1)
def read_bit():
pin.value(0)
delay_us(2)
pin.value(1)
delay_us(14)
bit = pin.value()
delay_us(45)
return bit
def write_byte(byte):
for i in range(8):
write_bit(byte & 0x01)
byte >>= 1
def read_byte():
byte = 0
for i in range(8):
byte |= (read_bit() << i)
return byte
def read_temperature():
t_low, t_high = 0, 0
temperature = 0
pin.value(1)
time.sleep_us(500)
pin.value(0)
time.sleep_us(500)
pin.value(1)
time.sleep_us(80)
write_byte(0xcc) # skip ROM
write_byte(0x44) # convert T
time.sleep_ms(750)
pin.value(0)
time.sleep_us(2)
pin.value(1)
time.sleep_us(10)
write_byte(0xcc) # skip ROM
write_byte(0xbe) # read scratchpad
t_low = read_byte()
t_high = read_byte()
temperature = ((t_high << 8) | t_low) * 0.0625
return temperature
while True:
temperature = read_temperature()
print("Temperature:", temperature)
time.sleep_ms(1000)
```
这个程序使用了QuecPython的GPIO库来控制GPIO口,读取ds18b20的温度值。程序的主函数里无限循环地读取温度并输出。你可以根据需要修改程序。
阅读全文