1
1
Fork 0

initial commit

main
Alina Marquardt 2023-04-04 21:35:00 +02:00
commit 4c11f7fc4b
5 changed files with 543 additions and 0 deletions

22
.micropythonrc Normal file
View File

@ -0,0 +1,22 @@
{
"upload": {
"port": "/dev/tty.usbserial-1410",
"baud": 115200
},
"serial": {
"port": "/dev/tty.usbserial-1410",
"baud": 115200
},
"ignore": {
"extensions": [
".micropythonrc"
],
"directories": [
".vscode"
]
},
"tools": {
"ampy": "/usr/local/bin/ampy",
"rshell": "/Library/Frameworks/Python.framework/Versions/3.7/bin/rshell"
}
}

13
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,13 @@
{
"python.languageServer": "Pylance",
"python.linting.pylintEnabled": false,
"python.analysis.diagnosticSeverityOverrides": {
"reportMissingModuleSource": "none"
},
"python.analysis.extraPaths": [
"",
"/Users/peter/.vscode/extensions/joedevivo.vscode-circuitpython-0.1.19-darwin-x64/stubs",
"/Users/peter/Library/Application Support/Code/User/globalStorage/joedevivo.vscode-circuitpython/bundle/20220820/adafruit-circuitpython-bundle-py-20220820/lib"
],
"circuitpython.board.version": null
}

36
ConnectWiFi.py Normal file
View File

@ -0,0 +1,36 @@
def connect():
import network
from time import sleep_ms
ssid = "-Netzlein-"
password = "Lau5Buam!"
#ssid = "Phaser"
#password = "toolbelt555"
print("Connecting to WiFi")
station = network.WLAN(network.STA_IF)
if station.isconnected() == True:
print("Already connected")
return True
station.active(True)
station.connect(ssid, password) # Timeout 10 Seconds
while station.status() == 1:
# 1 connecting?
# 2 ???
# 3 failed?
# 5 connected?
sleep_ms(500)
print("Connection status")
print(station.status())
if station.isconnected():
print("Connection successful")
print(station.ifconfig())
return True
else:
return False

317
main.py Normal file
View File

@ -0,0 +1,317 @@
# -*- coding: utf-8 -*-
from machine import Pin, I2C
import ssd1306
from time import sleep_ms
import onewire, ds18x20
import urequests
import ConnectWiFi
# ESP8266 Pin assignment
i2c = I2C(-1, scl=Pin(5), sda=Pin(4))
ds18b20 = ds18x20.DS18X20(onewire.OneWire(Pin(0)))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
oled.contrast(100)
roms = ds18b20.scan()
print('Found DS devices: ', roms)
errortemp = 99
inner_temp_default = 22
outer_temp_default = 18
bar_height = 20
bar_center = 40
tick_height = 6
outer_bar_offset = oled_height-30
inner_bar_offset = 0
log_length = 120
outer_refresh_interval = 15
outer_temp = errortemp
inner_temp = errortemp
inner_msg = ""
outer_msg = ""
inner_templog_buffer = []
outer_templog_buffer = []
inner_templog = []
outer_templog = []
refresh_counter = 1
burn_in_counter = 0
"""
def rand( floor, mod=0, negative = False):
# return random value from -floor.mod to floor.mod if negative is True
from os import urandom as rnd
sign = 1 if ord(rnd(1))%10 > 5 else -1
sign = sign if negative else 1
if mod:
value = float(('{}.{}').format(ord(rnd(1))%floor, ord(rnd(1))%mod))
else:
value = int(('{}').format(ord(rnd(1))%floor))
return sign*value
"""
def cleanedlist(list):
return [i for i in list if i != errortemp]
def drawoutlinetext(string, x, y, color):
oled.text(string, x+1, y, not color)
oled.text(string, x-1, y, not color)
oled.text(string, x, y+1, not color)
oled.text(string, x, y-1, not color)
oled.text(string, x+1, y+1, not color)
oled.text(string, x-1, y+1, not color)
oled.text(string, x+1, y-1, not color)
oled.text(string, x-1, y-1, not color)
oled.text(string, x+2, y, not color)
oled.text(string, x-2, y, not color)
oled.text(string, x+2, y+1, not color)
oled.text(string, x-2, y+1, not color)
oled.text(string, x+2, y-1, not color)
oled.text(string, x-2, y-1, not color)
oled.text(string, x, y+2, not color)
oled.text(string, x+1, y+2, not color)
oled.text(string, x-1, y+2, not color)
oled.text(string, x, y, color)
def drawlabels(minval, maxval, inner_templog_clean, outer_templog_clean, inner_temp, outer_temp):
label_height = 13
label_width = 8*4
inner_temp_label = inner_temp
outer_temp_label = outer_temp
if inner_temp == errortemp:
if len(inner_templog_clean) > 0:
inner_temp = inner_templog_clean[-1]
else:
inner_temp = inner_temp_default
if outer_temp == errortemp:
if len(outer_templog_clean) > 0:
outer_temp = outer_templog_clean[-1]
else:
outer_temp = outer_temp_default
inner_label_y = oled_height-int((float(inner_temp)-minval)/(maxval-minval)*(oled_height))
outer_label_y = oled_height-int((float(outer_temp)-minval)/(maxval-minval)*(oled_height))
label_xpos = oled_width-label_width-4
inner_label_ypos = max(min(int(inner_label_y-(label_height/2)), oled_height-label_height), 0)-1
outer_label_ypos = max(min(int(outer_label_y-(label_height/2)), oled_height-label_height), 0)-1
if inner_label_ypos > outer_label_ypos:
while inner_label_ypos-outer_label_ypos < label_height:
inner_label_ypos = min(inner_label_ypos+1, oled_height-label_height)
outer_label_ypos = max(outer_label_ypos-1, 0)
if inner_label_ypos <= outer_label_ypos:
while outer_label_ypos-inner_label_ypos < label_height:
inner_label_ypos = max(inner_label_ypos-1, 0)
outer_label_ypos = min(outer_label_ypos+1, oled_height-label_height)
inner_temp_pad = " "
outer_temp_pad = " "
if int(round(inner_temp, 0)) >= 0 and int(round(inner_temp, 0)) < 10:
inner_temp_pad = " "
elif int(round(inner_temp, 0)) < -9:
inner_temp_pad = ""
if int(round(outer_temp, 0)) >= 0 and int(round(outer_temp, 0)) < 10:
outer_temp_pad = " "
elif int(round(outer_temp, 0)) < -9:
outer_temp_pad = ""
if (inner_temp_label == errortemp):
inner_temp_string = " --"
else:
inner_temp_string = inner_temp_pad+str(int(round(inner_temp, 0)))
if (outer_temp_label == errortemp):
outer_temp_string = " --"
else:
outer_temp_string = outer_temp_pad+str(int(round(outer_temp, 0)))
drawoutlinetext(inner_temp_string, label_xpos+4, inner_label_ypos+3, 1)
drawoutlinetext(outer_temp_string, label_xpos+4, outer_label_ypos+3, 1)
def drawgraph(tempdata, temp, minval, maxval, x, y, width, height, style):
tempdata = tempdata + [temp]
if (len(tempdata) > 1):
normalized = [int((float(i)-minval)/(maxval-minval)*(height)) for i in tempdata]
stepwidth = width/(len(normalized)-1)
for i in range(0, len(normalized)-1):
if tempdata[i] == errortemp or tempdata[i+1] == errortemp:
pass
else:
if style == 'line':
oled.line(x+int(i*stepwidth), y+height-normalized[i]-1, x+int(i*stepwidth+stepwidth), y+height-normalized[i+1]-1, 0)
oled.line(x+int(i*stepwidth), y+height-normalized[i]+1, x+int(i*stepwidth+stepwidth), y+height-normalized[i+1]+1, 0)
oled.line(x+int(i*stepwidth), y+height-normalized[i], x+int(i*stepwidth+stepwidth), y+height-normalized[i+1], 1)
elif style == 'dashed':
for j in range(0, int(stepwidth)+1):
localx = x+int(i*stepwidth)+j
if (localx+4) % 9 < 6:
value = int( normalized[i] + (normalized[i+1]-normalized[i]) * (j/stepwidth) )
oled.pixel(localx, y+height-value-1, 0)
oled.pixel(localx, y+height-value+1, 0)
oled.pixel(localx, y+height-value, 1)
elif style == 'solid':
for j in range(0, int(stepwidth)+1):
localx = x+int(i*stepwidth)+j
if (localx+3)%4 == 2:
value = int( normalized[i] + (normalized[i+1]-normalized[i]) * (j/stepwidth) )
for localy in range(y+height-value+2, y+height):
if (localy+localx/2+burn_in_counter) % 4 > 2:
oled.pixel(localx, localy, 1)
elif style == 'halfsolid':
for j in range(0, int(stepwidth)+1):
localx = x+int(i*stepwidth)+j
if (localx+1)%4 == 2:
value = int( normalized[i] + (normalized[i+1]-normalized[i]) * (j/stepwidth) )
for localy in range(y+height-value+2, y+height):
if (localy+localx/2+burn_in_counter) % 4 > 3:
oled.pixel(localx, localy, 1)
def refresh_inner():
global inner_msg
global inner_temp
inner_msg = "Temp Read Error"
for rom in roms:
inner_temp = ds18b20.read_temp(rom)
inner_msg = ""
#print('DS: '+str(inner_temp))
def refresh_outer():
global outer_msg
global outer_temp
outer_msg = ""
connection_success = ConnectWiFi.connect()
if connection_success:
try:
response = urequests.get('http://api.openweathermap.org/data/2.5/weather?zip=79106,de&appid=50fdc9dbace8903dae0ac4ee4143b3b5')
parsed = response.json()
if 'cod' in parsed:
if parsed["cod"] != 200:
outer_msg = "Error "+str(parsed["cod"])
outer_temp = errortemp
if 'main' in parsed and 'temp' in parsed["main"]:
outer_temp = float(parsed["main"]["temp"]) - 273.15
else:
outer_msg = "No Temperature"
outer_temp = errortemp
except:
outer_msg = "No Response"
print("no response")
outer_temp = errortemp
else:
outer_msg = "No WiFi"
outer_temp = errortemp
def showgraph():
oled.fill(0)
graphmin = outer_temp_default
graphmax = inner_temp_default
inner_templog_clean = cleanedlist(inner_templog+[inner_temp])
outer_templog_clean = cleanedlist(outer_templog+[outer_temp])
if len(inner_templog_clean) >= 1 and len(outer_templog_clean) >= 1:
graphmin = min(min(inner_templog_clean), min(outer_templog_clean))
graphmax = max(max(inner_templog_clean), max(outer_templog_clean))
graphmin -= 5
graphmax += 5
drawgraph(inner_templog, inner_temp, graphmin, graphmax, 0, 0, oled_width-1, oled_height-1, 'halfsolid')
drawgraph(outer_templog, outer_temp, graphmin, graphmax, 0, 0, oled_width-1, oled_height-1, 'solid')
drawgraph(inner_templog, inner_temp, graphmin, graphmax, 0, 0, oled_width-1, oled_height-1, 'dashed')
drawgraph(outer_templog, outer_temp, graphmin, graphmax, 0, 0, oled_width-1, oled_height-1, 'line')
drawlabels(graphmin, graphmax, inner_templog_clean, outer_templog_clean, inner_temp, outer_temp)
if inner_msg != "" and outer_msg == "":
drawoutlinetext(inner_msg, 5, oled_height-15, 1)
elif inner_msg != "" and outer_msg != "":
drawoutlinetext(inner_msg, 5, oled_height-25, 1)
if outer_msg != "":
drawoutlinetext(outer_msg, 5, oled_height-15, 1)
oled.show()
#setup/init
ds18b20.convert_temp()
sleep_ms(750)
refresh_inner()
inner_templog_buffer.append(inner_temp)
inner_templog.append(inner_temp)
showgraph()
refresh_outer()
if outer_temp != errortemp:
outer_templog_buffer.append(outer_temp)
outer_templog.append(outer_temp)
showgraph()
while True:
refresh_counter += 1
burn_in_counter = burn_in_counter+1 % 4*9
do_refresh_outer = False
ds18b20.convert_temp() # refresh value ahead of time for minimum latency
sleep_ms(1000) # refresh inner temp every second
print('.', end='')
if refresh_counter >= outer_refresh_interval: # refresh outer temp every 30 sec
do_refresh_outer = True
refresh_counter = 0
refresh_inner()
inner_templog_buffer.append(inner_temp)
if do_refresh_outer:
print('#')
inner_templog.append(sum(inner_templog_buffer)/len(inner_templog_buffer))
inner_templog = inner_templog[(0-log_length):]
inner_templog_buffer = []
refresh_outer()
if outer_temp != errortemp:
outer_templog_buffer.append(outer_temp)
outer_templog.append(sum(outer_templog_buffer)/len(outer_templog_buffer))
outer_templog_buffer = outer_templog_buffer[-6:]
else:
outer_templog.append(errortemp)
outer_templog_buffer = []
outer_templog = outer_templog[(0-log_length):]
showgraph()

155
ssd1306.py Normal file
View File

@ -0,0 +1,155 @@
# MicroPython SSD1306 OLED driver, I2C and SPI interfaces
from micropython import const
import framebuf
# register definitions
SET_CONTRAST = const(0x81)
SET_ENTIRE_ON = const(0xA4)
SET_NORM_INV = const(0xA6)
SET_DISP = const(0xAE)
SET_MEM_ADDR = const(0x20)
SET_COL_ADDR = const(0x21)
SET_PAGE_ADDR = const(0x22)
SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP = const(0xA0)
SET_MUX_RATIO = const(0xA8)
SET_COM_OUT_DIR = const(0xC0)
SET_DISP_OFFSET = const(0xD3)
SET_COM_PIN_CFG = const(0xDA)
SET_DISP_CLK_DIV = const(0xD5)
SET_PRECHARGE = const(0xD9)
SET_VCOM_DESEL = const(0xDB)
SET_CHARGE_PUMP = const(0x8D)
# Subclassing FrameBuffer provides support for graphics primitives
# http://docs.micropython.org/en/latest/pyboard/library/framebuf.html
class SSD1306(framebuf.FrameBuffer):
def __init__(self, width, height, external_vcc):
self.width = width
self.height = height
self.external_vcc = external_vcc
self.pages = self.height // 8
self.buffer = bytearray(self.pages * self.width)
super().__init__(self.buffer, self.width, self.height, framebuf.MONO_VLSB)
self.init_display()
def init_display(self):
for cmd in (
SET_DISP | 0x00, # off
# address setting
SET_MEM_ADDR,
0x00, # horizontal
# resolution and layout
SET_DISP_START_LINE | 0x00,
SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0
SET_MUX_RATIO,
self.height - 1,
SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0
SET_DISP_OFFSET,
0x00,
SET_COM_PIN_CFG,
0x02 if self.width > 2 * self.height else 0x12,
# timing and driving scheme
SET_DISP_CLK_DIV,
0x80,
SET_PRECHARGE,
0x22 if self.external_vcc else 0xF1,
SET_VCOM_DESEL,
0x30, # 0.83*Vcc
# display
SET_CONTRAST,
0xFF, # maximum
SET_ENTIRE_ON, # output follows RAM contents
SET_NORM_INV, # not inverted
# charge pump
SET_CHARGE_PUMP,
0x10 if self.external_vcc else 0x14,
SET_DISP | 0x01,
): # on
self.write_cmd(cmd)
self.fill(0)
self.show()
def poweroff(self):
self.write_cmd(SET_DISP | 0x00)
def poweron(self):
self.write_cmd(SET_DISP | 0x01)
def contrast(self, contrast):
self.write_cmd(SET_CONTRAST)
self.write_cmd(contrast)
def invert(self, invert):
self.write_cmd(SET_NORM_INV | (invert & 1))
def show(self):
x0 = 0
x1 = self.width - 1
if self.width == 64:
# displays with width of 64 pixels are shifted by 32
x0 += 32
x1 += 32
self.write_cmd(SET_COL_ADDR)
self.write_cmd(x0)
self.write_cmd(x1)
self.write_cmd(SET_PAGE_ADDR)
self.write_cmd(0)
self.write_cmd(self.pages - 1)
self.write_data(self.buffer)
class SSD1306_I2C(SSD1306):
def __init__(self, width, height, i2c, addr=0x3C, external_vcc=False):
self.i2c = i2c
self.addr = addr
self.temp = bytearray(2)
self.write_list = [b"\x40", None] # Co=0, D/C#=1
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.temp[0] = 0x80 # Co=1, D/C#=0
self.temp[1] = cmd
self.i2c.writeto(self.addr, self.temp)
def write_data(self, buf):
self.write_list[1] = buf
self.i2c.writevto(self.addr, self.write_list)
class SSD1306_SPI(SSD1306):
def __init__(self, width, height, spi, dc, res, cs, external_vcc=False):
self.rate = 10 * 1024 * 1024
dc.init(dc.OUT, value=0)
res.init(res.OUT, value=0)
cs.init(cs.OUT, value=1)
self.spi = spi
self.dc = dc
self.res = res
self.cs = cs
import time
self.res(1)
time.sleep_ms(1)
self.res(0)
time.sleep_ms(10)
self.res(1)
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.spi.init(baudrate=self.rate, polarity=0, phase=0)
self.cs(1)
self.dc(0)
self.cs(0)
self.spi.write(bytearray([cmd]))
self.cs(1)
def write_data(self, buf):
self.spi.init(baudrate=self.rate, polarity=0, phase=0)
self.cs(1)
self.dc(1)
self.cs(0)
self.spi.write(buf)
self.cs(1)