You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
79 lines
2.1 KiB
Python
79 lines
2.1 KiB
Python
5 years ago
|
from dht import DHT11
|
||
|
from machine import Pin, SPI, ADC
|
||
|
from ssd1306 import SSD1306_SPI
|
||
|
from time import sleep
|
||
|
|
||
|
# Buttons and Knobs Pins
|
||
|
BUTTON_PIN = Pin(34, Pin.IN)
|
||
|
POT_PIN = ADC(Pin(35))
|
||
|
|
||
|
# DHT Sensor
|
||
|
DHT_PIN = DHT11(Pin(26))
|
||
|
|
||
|
# SPI PINS
|
||
|
MISO_PIN = Pin(19)
|
||
|
MOSI_PIN = Pin(23)
|
||
|
SCK_PIN = Pin(18)
|
||
|
DC_PIN = Pin(4, Pin.OUT)
|
||
|
CS_PIN = Pin(5, Pin.OUT)
|
||
|
RST_PIN = Pin(2, Pin.OUT)
|
||
|
|
||
|
# VSPI Hardware channel. 80 MHz signal rate
|
||
|
vspi = SPI(2, baudrate=2600000, polarity=0, phase=0, bits=8, firstbit=0, sck=SCK_PIN, mosi=MOSI_PIN, miso=MISO_PIN)
|
||
|
|
||
|
oled = SSD1306_SPI(128, 64, vspi, DC_PIN, RST_PIN, CS_PIN)
|
||
|
|
||
|
|
||
|
class DisplayWriter:
|
||
|
|
||
|
def __init__(self, spi):
|
||
|
self.spi = spi
|
||
|
self.height = spi.height
|
||
|
self.width = spi.width
|
||
|
|
||
|
def msg(self, msg: str, l_offset=0, top_offset=0) -> None:
|
||
|
"""Writes a message to an OLED display.
|
||
|
|
||
|
Will wrap text as needed.
|
||
|
"""
|
||
|
self.spi.fill(0)
|
||
|
formatted_msg = self._split_msg(msg, l_offset, top_offset)
|
||
|
for s, left, top in formatted_msg:
|
||
|
self.spi.text(s, left, top)
|
||
|
self.spi.show()
|
||
|
|
||
|
# Todo make this a generator
|
||
|
def _split_msg(self, msg, l_offset, top_offset) -> list:
|
||
|
"""Splits a message at screen width to be used for text wrapping."""
|
||
|
_top_offset = top_offset
|
||
|
result = []
|
||
|
for e in msg.split('\n'):
|
||
|
result.append((e, l_offset, _top_offset))
|
||
|
_top_offset += 10
|
||
|
return result
|
||
|
|
||
|
|
||
|
def dht_report(dht_pin):
|
||
|
dht_pin.measure()
|
||
|
_temp = dht_pin.temperature()
|
||
|
_hum = dht_pin.humidity()
|
||
|
return _temp, _hum
|
||
|
|
||
|
|
||
|
def celsius_to_fahrenheit(celsius: int):
|
||
|
return (celsius * (9 / 5)) + 32
|
||
|
|
||
|
|
||
|
display = DisplayWriter(oled)
|
||
|
|
||
|
while True:
|
||
|
button_val = BUTTON_PIN.value()
|
||
|
light_sensor = round(POT_PIN.read() / 4096 * 100)
|
||
|
temp, hum = dht_report(DHT_PIN)
|
||
|
report = "Temp: {}C/{}F\nHum: {}%\nButton: {}\nLight: {}%".format(temp, celsius_to_fahrenheit(temp), hum,
|
||
|
button_val, light_sensor)
|
||
|
# print(report)
|
||
|
oled.invert(button_val)
|
||
|
display.msg(report)
|
||
|
sleep(0.1)
|