Created
September 12, 2018 07:19
-
-
Save furushei/391f54ed174b59278039531d6f09f92f to your computer and use it in GitHub Desktop.
M5Cloud (MicroPython) でDHT12センサを使うサンプルプログラム
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
MicroPython Aosong DHT12 I2C driver | |
""" | |
class DHTBaseI2C: | |
def __init__(self, i2c=None, addr=0x5c): | |
if i2c == None: | |
from machine import I2C | |
self.i2c = I2C(sda=21, scl=22) | |
else: | |
self.i2c = i2c | |
self.addr = addr | |
self.buf = bytearray(5) | |
def measure(self): | |
buf = self.buf | |
self.i2c.readfrom_mem_into(self.addr, 0, buf) | |
if (buf[0] + buf[1] + buf[2] + buf[3]) & 0xff != buf[4]: | |
raise Exception("checksum error") | |
class DHT12(DHTBaseI2C): | |
def humidity(self): | |
return self.buf[0] + self.buf[1] * 0.1 | |
def temperature(self): | |
t = self.buf[2] + (self.buf[3] & 0x7f) * 0.1 | |
if self.buf[3] & 0x80: | |
t = -t | |
return t |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from m5stack import lcd | |
import dht12 | |
import utime | |
sensor = dht12.DHT12() | |
sensor.measure() | |
temperature = sensor.temperature() | |
humidity = sensor.humidity() | |
lcd.clear() | |
lcd.setCursor(0, 0) | |
while True: | |
lcd.println('Temperature: {:.1f} `C Humidity: {:.1f} %'.format(temperature, humidity)) | |
utime.sleep(3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment