sht40.py 文件 温湿度传感器 3.3V 【5v 也可以】
import machine
import time
class SHT40:
def __init__(self, i2c, address=0x44):
self.i2c = i2c
self.address = address
def read_temperature_humidity(self):
# Send measurement command (High Precision)
self.i2c.writeto(self.address, b'\xFD')
time.sleep(0.01) # Wait for measurement to complete
# Read 6 bytes of data
data = self.i2c.readfrom(self.address, 6)
# Convert raw data to temperature and humidity
temp_raw = int.from_bytes(data[0:2], 'big')
humidity_raw = int.from_bytes(data[3:5], 'big')
temperature = -45 + (175 * (temp_raw / 65535.0))
humidity = 100 * (humidity_raw / 65535.0)
return temperature, humidity
调用
form sht40 import SHT40
import machine
i2c = machine.I2C(i2scl=machine.Pin(6), sda=machine.Pin(5), freq=100000)
# Initialize SHT40 sensor
sht40 = SHT40(i2c)
# Read and print temperature and humidity
while True:
temp, hum = sht40.read_temperature_humidity()
print("Temperature: {:.2f} °C".format(temp))
print("Humidity: {:.2f} %".format(hum))
time.sleep(1)
import machine
import time
class SHT40:
def __init__(self, i2c, address=0x44):
self.i2c = i2c
self.address = address
def read_temperature_humidity(self):
# Send measurement command (High Precision)
self.i2c.writeto(self.address, b'\xFD')
time.sleep(0.01) # Wait for measurement to complete
# Read 6 bytes of data
data = self.i2c.readfrom(self.address, 6)
# Convert raw data to temperature and humidity
temp_raw = int.from_bytes(data[0:2], 'big')
humidity_raw = int.from_bytes(data[3:5], 'big')
temperature = -45 + (175 * (temp_raw / 65535.0))
humidity = 100 * (humidity_raw / 65535.0)
return temperature, humidity
# Initialize I2C
i2c = machine.I2C(i2scl=machine.Pin(6), sda=machine.Pin(5), freq=100000)
# Initialize SHT40 sensor
sht40 = SHT40(i2c)
# Read and print temperature and humidity
while True:
temp, hum = sht40.read_temperature_humidity()
print("Temperature: {:.2f} °C".format(temp))
print("Humidity: {:.2f} %".format(hum))
time.sleep(1)