all: Reformat C and Python source code with tools/codeformat.py.

This is run with uncrustify 0.70.1, and black 19.10b0.
This commit is contained in:
Damien George 2020-02-27 15:36:53 +11:00
parent 3f39d18c2b
commit 69661f3343
539 changed files with 10496 additions and 8254 deletions

View File

@ -6,6 +6,7 @@ try:
except: except:
from pyb import dht_readinto from pyb import dht_readinto
class DHTBase: class DHTBase:
def __init__(self, pin): def __init__(self, pin):
self.pin = pin self.pin = pin
@ -14,9 +15,10 @@ class DHTBase:
def measure(self): def measure(self):
buf = self.buf buf = self.buf
dht_readinto(self.pin, buf) dht_readinto(self.pin, buf)
if (buf[0] + buf[1] + buf[2] + buf[3]) & 0xff != buf[4]: if (buf[0] + buf[1] + buf[2] + buf[3]) & 0xFF != buf[4]:
raise Exception("checksum error") raise Exception("checksum error")
class DHT11(DHTBase): class DHT11(DHTBase):
def humidity(self): def humidity(self):
return self.buf[0] return self.buf[0]
@ -24,12 +26,13 @@ class DHT11(DHTBase):
def temperature(self): def temperature(self):
return self.buf[2] return self.buf[2]
class DHT22(DHTBase): class DHT22(DHTBase):
def humidity(self): def humidity(self):
return (self.buf[0] << 8 | self.buf[1]) * 0.1 return (self.buf[0] << 8 | self.buf[1]) * 0.1
def temperature(self): def temperature(self):
t = ((self.buf[2] & 0x7f) << 8 | self.buf[3]) * 0.1 t = ((self.buf[2] & 0x7F) << 8 | self.buf[3]) * 0.1
if self.buf[2] & 0x80: if self.buf[2] & 0x80:
t = -t t = -t
return t return t

View File

@ -29,16 +29,17 @@ _uart_baud_table = {
460800: 8, 460800: 8,
} }
class LCD160CR: class LCD160CR:
def __init__(self, connect=None, *, pwr=None, i2c=None, spi=None, i2c_addr=98): def __init__(self, connect=None, *, pwr=None, i2c=None, spi=None, i2c_addr=98):
if connect in ('X', 'Y', 'XY', 'YX'): if connect in ("X", "Y", "XY", "YX"):
i = connect[-1] i = connect[-1]
j = connect[0] j = connect[0]
y = j + '4' y = j + "4"
elif connect == 'C': elif connect == "C":
i = 2 i = 2
j = 2 j = 2
y = 'A7' y = "A7"
else: else:
if pwr is None or i2c is None or spi is None: if pwr is None or i2c is None or spi is None:
raise ValueError('must specify valid "connect" or all of "pwr", "i2c" and "spi"') raise ValueError('must specify valid "connect" or all of "pwr", "i2c" and "spi"')
@ -74,8 +75,8 @@ class LCD160CR:
# set default orientation and window # set default orientation and window
self.set_orient(PORTRAIT) self.set_orient(PORTRAIT)
self._fcmd2b('<BBBBBB', 0x76, 0, 0, self.w, self.h) # viewport 'v' self._fcmd2b("<BBBBBB", 0x76, 0, 0, self.w, self.h) # viewport 'v'
self._fcmd2b('<BBBBBB', 0x79, 0, 0, self.w, self.h) # window 'y' self._fcmd2b("<BBBBBB", 0x79, 0, 0, self.w, self.h) # window 'y'
def _send(self, cmd): def _send(self, cmd):
i = self.i2c.writeto(self.i2c_addr, cmd) i = self.i2c.writeto(self.i2c_addr, cmd)
@ -135,7 +136,7 @@ class LCD160CR:
@staticmethod @staticmethod
def rgb(r, g, b): def rgb(r, g, b):
return ((b & 0xf8) << 8) | ((g & 0xfc) << 3) | (r >> 3) return ((b & 0xF8) << 8) | ((g & 0xFC) << 3) | (r >> 3)
@staticmethod @staticmethod
def clip_line(c, w, h): def clip_line(c, w, h):
@ -207,43 +208,43 @@ class LCD160CR:
sleep_ms(15) sleep_ms(15)
def set_orient(self, orient): def set_orient(self, orient):
self._fcmd2('<BBB', 0x14, (orient & 3) + 4) self._fcmd2("<BBB", 0x14, (orient & 3) + 4)
# update width and height variables # update width and height variables
self.iflush() self.iflush()
self._send(b'\x02g0') self._send(b"\x02g0")
self._waitfor(4, self.buf[5]) self._waitfor(4, self.buf[5])
self.w = self.buf[5][1] self.w = self.buf[5][1]
self.h = self.buf[5][2] self.h = self.buf[5][2]
def set_brightness(self, value): def set_brightness(self, value):
self._fcmd2('<BBB', 0x16, value) self._fcmd2("<BBB", 0x16, value)
def set_i2c_addr(self, addr): def set_i2c_addr(self, addr):
# 0x0e set i2c addr # 0x0e set i2c addr
if addr & 3: if addr & 3:
raise ValueError('must specify mod 4 aligned address') raise ValueError("must specify mod 4 aligned address")
self._fcmd2('<BBW', 0x0e, 0x433249 | (addr << 24)) self._fcmd2("<BBW", 0x0E, 0x433249 | (addr << 24))
def set_uart_baudrate(self, baudrate): def set_uart_baudrate(self, baudrate):
try: try:
baudrate = _uart_baud_table[baudrate] baudrate = _uart_baud_table[baudrate]
except KeyError: except KeyError:
raise ValueError('invalid baudrate') raise ValueError("invalid baudrate")
self._fcmd2('<BBB', 0x18, baudrate) self._fcmd2("<BBB", 0x18, baudrate)
def set_startup_deco(self, value): def set_startup_deco(self, value):
self._fcmd2('<BBB', 0x19, value) self._fcmd2("<BBB", 0x19, value)
def save_to_flash(self): def save_to_flash(self):
self._send(b'\x02fn') self._send(b"\x02fn")
#### PIXEL ACCESS #### #### PIXEL ACCESS ####
def set_pixel(self, x, y, c): def set_pixel(self, x, y, c):
self._fcmd2b('<BBBBH', 0x41, x, y, c) self._fcmd2b("<BBBBH", 0x41, x, y, c)
def get_pixel(self, x, y): def get_pixel(self, x, y):
self._fcmd2('<BBBB', 0x61, x, y) self._fcmd2("<BBBB", 0x61, x, y)
t = 1000 t = 1000
while t: while t:
self.i2c.readfrom_into(self.i2c_addr, self.buf1) self.i2c.readfrom_into(self.i2c_addr, self.buf1)
@ -256,7 +257,7 @@ class LCD160CR:
def get_line(self, x, y, buf): def get_line(self, x, y, buf):
l = len(buf) // 2 l = len(buf) // 2
self._fcmd2b('<BBBBB', 0x10, l, x, y) self._fcmd2b("<BBBBB", 0x10, l, x, y)
l *= 2 l *= 2
t = 1000 t = 1000
while t: while t:
@ -293,7 +294,7 @@ class LCD160CR:
def screen_load(self, buf): def screen_load(self, buf):
l = self.w * self.h * 2 + 2 l = self.w * self.h * 2 + 2
self._fcmd2b('<BBHBBB', 0x70, l, 16, self.w, self.h) self._fcmd2b("<BBHBBB", 0x70, l, 16, self.w, self.h)
n = 0 n = 0
ar = memoryview(buf) ar = memoryview(buf)
while n < len(buf): while n < len(buf):
@ -303,19 +304,24 @@ class LCD160CR:
else: else:
self._send(ar[n:]) self._send(ar[n:])
while n < self.w * self.h * 2: while n < self.w * self.h * 2:
self._send(b'\x00') self._send(b"\x00")
n += 1 n += 1
#### TEXT COMMANDS #### #### TEXT COMMANDS ####
def set_pos(self, x, y): def set_pos(self, x, y):
self._fcmd2('<BBBB', 0x58, x, y) self._fcmd2("<BBBB", 0x58, x, y)
def set_text_color(self, fg, bg): def set_text_color(self, fg, bg):
self._fcmd2('<BBHH', 0x63, fg, bg) self._fcmd2("<BBHH", 0x63, fg, bg)
def set_font(self, font, scale=0, bold=0, trans=0, scroll=0): def set_font(self, font, scale=0, bold=0, trans=0, scroll=0):
self._fcmd2('<BBBB', 0x46, (scroll << 7) | (trans << 6) | ((font & 3) << 4) | (bold & 0xf), scale & 0xff) self._fcmd2(
"<BBBB",
0x46,
(scroll << 7) | (trans << 6) | ((font & 3) << 4) | (bold & 0xF),
scale & 0xFF,
)
def write(self, s): def write(self, s):
# TODO: eventually check for room in LCD input queue # TODO: eventually check for room in LCD input queue
@ -324,14 +330,14 @@ class LCD160CR:
#### PRIMITIVE DRAWING COMMANDS #### #### PRIMITIVE DRAWING COMMANDS ####
def set_pen(self, line, fill): def set_pen(self, line, fill):
self._fcmd2('<BBHH', 0x50, line, fill) self._fcmd2("<BBHH", 0x50, line, fill)
def erase(self): def erase(self):
self._send(b'\x02\x45') self._send(b"\x02\x45")
def dot(self, x, y): def dot(self, x, y):
if 0 <= x < self.w and 0 <= y < self.h: if 0 <= x < self.w and 0 <= y < self.h:
self._fcmd2('<BBBB', 0x4b, x, y) self._fcmd2("<BBBB", 0x4B, x, y)
def rect(self, x, y, w, h, cmd=0x72): def rect(self, x, y, w, h, cmd=0x72):
if x + w <= 0 or y + h <= 0 or x >= self.w or y >= self.h: if x + w <= 0 or y + h <= 0 or x >= self.w or y >= self.h:
@ -348,19 +354,19 @@ class LCD160CR:
y = 0 y = 0
if cmd == 0x51 or cmd == 0x72: if cmd == 0x51 or cmd == 0x72:
# draw interior # draw interior
self._fcmd2b('<BBBBBB', 0x51, x, y, min(w, 255), min(h, 255)) self._fcmd2b("<BBBBBB", 0x51, x, y, min(w, 255), min(h, 255))
if cmd == 0x57 or cmd == 0x72: if cmd == 0x57 or cmd == 0x72:
# draw outline # draw outline
if left: if left:
self._fcmd2b('<BBBBBB', 0x57, x, y, 1, min(h, 255)) self._fcmd2b("<BBBBBB", 0x57, x, y, 1, min(h, 255))
if top: if top:
self._fcmd2b('<BBBBBB', 0x57, x, y, min(w, 255), 1) self._fcmd2b("<BBBBBB", 0x57, x, y, min(w, 255), 1)
if x + w < self.w: if x + w < self.w:
self._fcmd2b('<BBBBBB', 0x57, x + w, y, 1, min(h, 255)) self._fcmd2b("<BBBBBB", 0x57, x + w, y, 1, min(h, 255))
if y + h < self.h: if y + h < self.h:
self._fcmd2b('<BBBBBB', 0x57, x, y + h, min(w, 255), 1) self._fcmd2b("<BBBBBB", 0x57, x, y + h, min(w, 255), 1)
else: else:
self._fcmd2b('<BBBBBB', cmd, x, y, min(w, 255), min(h, 255)) self._fcmd2b("<BBBBBB", cmd, x, y, min(w, 255), min(h, 255))
def rect_outline(self, x, y, w, h): def rect_outline(self, x, y, w, h):
self.rect(x, y, w, h, 0x57) self.rect(x, y, w, h, 0x57)
@ -375,48 +381,48 @@ class LCD160CR:
ar4[2] = x2 ar4[2] = x2
ar4[3] = y2 ar4[3] = y2
if self.clip_line(ar4, self.w, self.h): if self.clip_line(ar4, self.w, self.h):
self._fcmd2b('<BBBBBB', 0x4c, ar4[0], ar4[1], ar4[2], ar4[3]) self._fcmd2b("<BBBBBB", 0x4C, ar4[0], ar4[1], ar4[2], ar4[3])
def dot_no_clip(self, x, y): def dot_no_clip(self, x, y):
self._fcmd2('<BBBB', 0x4b, x, y) self._fcmd2("<BBBB", 0x4B, x, y)
def rect_no_clip(self, x, y, w, h): def rect_no_clip(self, x, y, w, h):
self._fcmd2b('<BBBBBB', 0x72, x, y, w, h) self._fcmd2b("<BBBBBB", 0x72, x, y, w, h)
def rect_outline_no_clip(self, x, y, w, h): def rect_outline_no_clip(self, x, y, w, h):
self._fcmd2b('<BBBBBB', 0x57, x, y, w, h) self._fcmd2b("<BBBBBB", 0x57, x, y, w, h)
def rect_interior_no_clip(self, x, y, w, h): def rect_interior_no_clip(self, x, y, w, h):
self._fcmd2b('<BBBBBB', 0x51, x, y, w, h) self._fcmd2b("<BBBBBB", 0x51, x, y, w, h)
def line_no_clip(self, x1, y1, x2, y2): def line_no_clip(self, x1, y1, x2, y2):
self._fcmd2b('<BBBBBB', 0x4c, x1, y1, x2, y2) self._fcmd2b("<BBBBBB", 0x4C, x1, y1, x2, y2)
def poly_dot(self, data): def poly_dot(self, data):
if len(data) & 1: if len(data) & 1:
raise ValueError('must specify even number of bytes') raise ValueError("must specify even number of bytes")
self._fcmd2('<BBB', 0x71, len(data) // 2) self._fcmd2("<BBB", 0x71, len(data) // 2)
self._send(data) self._send(data)
def poly_line(self, data): def poly_line(self, data):
if len(data) & 1: if len(data) & 1:
raise ValueError('must specify even number of bytes') raise ValueError("must specify even number of bytes")
self._fcmd2('<BBB', 0x78, len(data) // 2) self._fcmd2("<BBB", 0x78, len(data) // 2)
self._send(data) self._send(data)
#### TOUCH COMMANDS #### #### TOUCH COMMANDS ####
def touch_config(self, calib=False, save=False, irq=None): def touch_config(self, calib=False, save=False, irq=None):
self._fcmd2('<BBBB', 0x7a, (irq is not None) << 2 | save << 1 | calib, bool(irq) << 7) self._fcmd2("<BBBB", 0x7A, (irq is not None) << 2 | save << 1 | calib, bool(irq) << 7)
def is_touched(self): def is_touched(self):
self._send(b'\x02T') self._send(b"\x02T")
b = self.buf[4] b = self.buf[4]
self._waitfor(3, b) self._waitfor(3, b)
return b[1] >> 7 != 0 return b[1] >> 7 != 0
def get_touch(self): def get_touch(self):
self._send(b'\x02T') # implicit LCD output flush self._send(b"\x02T") # implicit LCD output flush
b = self.buf[4] b = self.buf[4]
self._waitfor(3, b) self._waitfor(3, b)
return b[1] >> 7, b[2], b[3] return b[1] >> 7, b[2], b[3]
@ -424,11 +430,13 @@ class LCD160CR:
#### ADVANCED COMMANDS #### #### ADVANCED COMMANDS ####
def set_spi_win(self, x, y, w, h): def set_spi_win(self, x, y, w, h):
pack_into('<BBBHHHHHHHH', self.buf19, 0, 2, 0x55, 10, x, y, x + w - 1, y + h - 1, 0, 0, 0, 0xffff) pack_into(
"<BBBHHHHHHHH", self.buf19, 0, 2, 0x55, 10, x, y, x + w - 1, y + h - 1, 0, 0, 0, 0xFFFF
)
self._send(self.buf19) self._send(self.buf19)
def fast_spi(self, flush=True): def fast_spi(self, flush=True):
self._send(b'\x02\x12') self._send(b"\x02\x12")
if flush: if flush:
self.oflush() self.oflush()
return self.spi return self.spi
@ -437,27 +445,27 @@ class LCD160CR:
self.fast_spi().write(buf) self.fast_spi().write(buf)
def set_scroll(self, on): def set_scroll(self, on):
self._fcmd2('<BBB', 0x15, on) self._fcmd2("<BBB", 0x15, on)
def set_scroll_win(self, win, x=-1, y=0, w=0, h=0, vec=0, pat=0, fill=0x07e0, color=0): def set_scroll_win(self, win, x=-1, y=0, w=0, h=0, vec=0, pat=0, fill=0x07E0, color=0):
pack_into('<BBBHHHHHHHH', self.buf19, 0, 2, 0x55, win, x, y, w, h, vec, pat, fill, color) pack_into("<BBBHHHHHHHH", self.buf19, 0, 2, 0x55, win, x, y, w, h, vec, pat, fill, color)
self._send(self.buf19) self._send(self.buf19)
def set_scroll_win_param(self, win, param, value): def set_scroll_win_param(self, win, param, value):
self._fcmd2b('<BBBBH', 0x75, win, param, value) self._fcmd2b("<BBBBH", 0x75, win, param, value)
def set_scroll_buf(self, s): def set_scroll_buf(self, s):
l = len(s) l = len(s)
if l > 32: if l > 32:
raise ValueError('length must be 32 or less') raise ValueError("length must be 32 or less")
self._fcmd2('<BBB', 0x11, l) self._fcmd2("<BBB", 0x11, l)
self._send(s) self._send(s)
def jpeg_start(self, l): def jpeg_start(self, l):
if l > 0xffff: if l > 0xFFFF:
raise ValueError('length must be 65535 or less') raise ValueError("length must be 65535 or less")
self.oflush() self.oflush()
self._fcmd2('<BBH', 0x6a, l) self._fcmd2("<BBH", 0x6A, l)
def jpeg_data(self, buf): def jpeg_data(self, buf):
self._send(buf) self._send(buf)
@ -467,8 +475,8 @@ class LCD160CR:
self.jpeg_data(buf) self.jpeg_data(buf)
def feed_wdt(self): def feed_wdt(self):
self._send(b'\x02\x17') self._send(b"\x02\x17")
def reset(self): def reset(self):
self._send(b'\x02Y\xef\xbe\xad\xde') self._send(b"\x02Y\xef\xbe\xad\xde")
sleep_ms(15) sleep_ms(15)

View File

@ -3,11 +3,13 @@
import time, math, framebuf, lcd160cr import time, math, framebuf, lcd160cr
def get_lcd(lcd): def get_lcd(lcd):
if type(lcd) is str: if type(lcd) is str:
lcd = lcd160cr.LCD160CR(lcd) lcd = lcd160cr.LCD160CR(lcd)
return lcd return lcd
def show_adc(lcd, adc): def show_adc(lcd, adc):
data = [adc.read_core_temp(), adc.read_core_vbat(), 3.3] data = [adc.read_core_temp(), adc.read_core_vbat(), 3.3]
try: try:
@ -22,11 +24,11 @@ def show_adc(lcd, adc):
else: else:
lcd.set_font(2, trans=1) lcd.set_font(2, trans=1)
lcd.set_pos(0, lcd.h - 60 + i * 16) lcd.set_pos(0, lcd.h - 60 + i * 16)
lcd.write('%4s: ' % ('TEMP', 'VBAT', 'VREF')[i]) lcd.write("%4s: " % ("TEMP", "VBAT", "VREF")[i])
if i > 0: if i > 0:
s = '%6.3fV' % data[i] s = "%6.3fV" % data[i]
else: else:
s = '%5.1f°C' % data[i] s = "%5.1f°C" % data[i]
if lcd.h == 160: if lcd.h == 160:
lcd.set_font(1, bold=0, scale=1) lcd.set_font(1, bold=0, scale=1)
else: else:
@ -34,11 +36,13 @@ def show_adc(lcd, adc):
lcd.set_pos(45, lcd.h - 60 + i * 16) lcd.set_pos(45, lcd.h - 60 + i * 16)
lcd.write(s) lcd.write(s)
def test_features(lcd, orient=lcd160cr.PORTRAIT): def test_features(lcd, orient=lcd160cr.PORTRAIT):
# if we run on pyboard then use ADC and RTC features # if we run on pyboard then use ADC and RTC features
try: try:
import pyb import pyb
adc = pyb.ADCAll(12, 0xf0000)
adc = pyb.ADCAll(12, 0xF0000)
rtc = pyb.RTC() rtc = pyb.RTC()
except: except:
adc = None adc = None
@ -53,7 +57,7 @@ def test_features(lcd, orient=lcd160cr.PORTRAIT):
# create M-logo # create M-logo
mlogo = framebuf.FrameBuffer(bytearray(17 * 17 * 2), 17, 17, framebuf.RGB565) mlogo = framebuf.FrameBuffer(bytearray(17 * 17 * 2), 17, 17, framebuf.RGB565)
mlogo.fill(0) mlogo.fill(0)
mlogo.fill_rect(1, 1, 15, 15, 0xffffff) mlogo.fill_rect(1, 1, 15, 15, 0xFFFFFF)
mlogo.vline(4, 4, 12, 0) mlogo.vline(4, 4, 12, 0)
mlogo.vline(8, 1, 12, 0) mlogo.vline(8, 1, 12, 0)
mlogo.vline(12, 4, 12, 0) mlogo.vline(12, 4, 12, 0)
@ -85,10 +89,13 @@ def test_features(lcd, orient=lcd160cr.PORTRAIT):
# create and show the inline framebuf # create and show the inline framebuf
fbuf.fill(lcd.rgb(128 + int(64 * math.cos(0.1 * i)), 128, 192)) fbuf.fill(lcd.rgb(128 + int(64 * math.cos(0.1 * i)), 128, 192))
fbuf.line(w // 2, h // 2, fbuf.line(
w // 2,
h // 2,
w // 2 + int(40 * math.cos(0.2 * i)), w // 2 + int(40 * math.cos(0.2 * i)),
h // 2 + int(40 * math.sin(0.2 * i)), h // 2 + int(40 * math.sin(0.2 * i)),
lcd.rgb(128, 255, 64)) lcd.rgb(128, 255, 64),
)
fbuf.hline(0, ty, w, lcd.rgb(64, 64, 64)) fbuf.hline(0, ty, w, lcd.rgb(64, 64, 64))
fbuf.vline(tx, 0, h, lcd.rgb(64, 64, 64)) fbuf.vline(tx, 0, h, lcd.rgb(64, 64, 64))
fbuf.rect(tx - 3, ty - 3, 7, 7, lcd.rgb(64, 64, 64)) fbuf.rect(tx - 3, ty - 3, 7, 7, lcd.rgb(64, 64, 64))
@ -97,9 +104,12 @@ def test_features(lcd, orient=lcd160cr.PORTRAIT):
y = h // 2 - 8 + int(32 * math.sin(0.05 * i + phase)) y = h // 2 - 8 + int(32 * math.sin(0.05 * i + phase))
fbuf.blit(mlogo, x, y) fbuf.blit(mlogo, x, y)
for j in range(-3, 3): for j in range(-3, 3):
fbuf.text('MicroPython', fbuf.text(
5, h // 2 + 9 * j + int(20 * math.sin(0.1 * (i + j))), "MicroPython",
lcd.rgb(128 + 10 * j, 0, 128 - 10 * j)) 5,
h // 2 + 9 * j + int(20 * math.sin(0.1 * (i + j))),
lcd.rgb(128 + 10 * j, 0, 128 - 10 * j),
)
lcd.show_framebuf(fbuf) lcd.show_framebuf(fbuf)
# show results from the ADC # show results from the ADC
@ -111,7 +121,10 @@ def test_features(lcd, orient=lcd160cr.PORTRAIT):
lcd.set_pos(2, 0) lcd.set_pos(2, 0)
lcd.set_font(1) lcd.set_font(1)
t = rtc.datetime() t = rtc.datetime()
lcd.write('%4d-%02d-%02d %2d:%02d:%02d.%01d' % (t[0], t[1], t[2], t[4], t[5], t[6], t[7] // 100000)) lcd.write(
"%4d-%02d-%02d %2d:%02d:%02d.%01d"
% (t[0], t[1], t[2], t[4], t[5], t[6], t[7] // 100000)
)
# compute the frame rate # compute the frame rate
t1 = time.ticks_us() t1 = time.ticks_us()
@ -120,13 +133,14 @@ def test_features(lcd, orient=lcd160cr.PORTRAIT):
# show the frame rate # show the frame rate
lcd.set_pos(2, 9) lcd.set_pos(2, 9)
lcd.write('%.2f fps' % (1000000 / dt)) lcd.write("%.2f fps" % (1000000 / dt))
def test_mandel(lcd, orient=lcd160cr.PORTRAIT): def test_mandel(lcd, orient=lcd160cr.PORTRAIT):
# set orientation and clear screen # set orientation and clear screen
lcd = get_lcd(lcd) lcd = get_lcd(lcd)
lcd.set_orient(orient) lcd.set_orient(orient)
lcd.set_pen(0, 0xffff) lcd.set_pen(0, 0xFFFF)
lcd.erase() lcd.erase()
# function to compute Mandelbrot pixels # function to compute Mandelbrot pixels
@ -148,24 +162,26 @@ def test_mandel(lcd, orient=lcd160cr.PORTRAIT):
spi = lcd.fast_spi() spi = lcd.fast_spi()
# draw the Mandelbrot set line-by-line # draw the Mandelbrot set line-by-line
hh = ((h - 1) / 3.2) hh = (h - 1) / 3.2
ww = ((w - 1) / 2.4) ww = (w - 1) / 2.4
for v in range(h): for v in range(h):
for u in range(w): for u in range(w):
c = in_set((v / hh - 2.3) + (u / ww - 1.2) * 1j) c = in_set((v / hh - 2.3) + (u / ww - 1.2) * 1j)
if c < 16: if c < 16:
rgb = c << 12 | c << 6 rgb = c << 12 | c << 6
else: else:
rgb = 0xf800 | c << 6 rgb = 0xF800 | c << 6
line[2 * u] = rgb line[2 * u] = rgb
line[2 * u + 1] = rgb >> 8 line[2 * u + 1] = rgb >> 8
spi.write(line) spi.write(line)
def test_all(lcd, orient=lcd160cr.PORTRAIT): def test_all(lcd, orient=lcd160cr.PORTRAIT):
lcd = get_lcd(lcd) lcd = get_lcd(lcd)
test_features(lcd, orient) test_features(lcd, orient)
test_mandel(lcd, orient) test_mandel(lcd, orient)
print('To run all tests: test_all(<lcd>)')
print('Individual tests are: test_features, test_mandel') print("To run all tests: test_all(<lcd>)")
print("Individual tests are: test_features, test_mandel")
print('<lcd> argument should be a connection, eg "X", or an LCD160CR object') print('<lcd> argument should be a connection, eg "X", or an LCD160CR object')

View File

@ -6,22 +6,22 @@ import framebuf
# register definitions # register definitions
SET_CONTRAST = const(0x81) SET_CONTRAST = const(0x81)
SET_ENTIRE_ON = const(0xa4) SET_ENTIRE_ON = const(0xA4)
SET_NORM_INV = const(0xa6) SET_NORM_INV = const(0xA6)
SET_DISP = const(0xae) SET_DISP = const(0xAE)
SET_MEM_ADDR = const(0x20) SET_MEM_ADDR = const(0x20)
SET_COL_ADDR = const(0x21) SET_COL_ADDR = const(0x21)
SET_PAGE_ADDR = const(0x22) SET_PAGE_ADDR = const(0x22)
SET_DISP_START_LINE = const(0x40) SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP = const(0xa0) SET_SEG_REMAP = const(0xA0)
SET_MUX_RATIO = const(0xa8) SET_MUX_RATIO = const(0xA8)
SET_COM_OUT_DIR = const(0xc0) SET_COM_OUT_DIR = const(0xC0)
SET_DISP_OFFSET = const(0xd3) SET_DISP_OFFSET = const(0xD3)
SET_COM_PIN_CFG = const(0xda) SET_COM_PIN_CFG = const(0xDA)
SET_DISP_CLK_DIV = const(0xd5) SET_DISP_CLK_DIV = const(0xD5)
SET_PRECHARGE = const(0xd9) SET_PRECHARGE = const(0xD9)
SET_VCOM_DESEL = const(0xdb) SET_VCOM_DESEL = const(0xDB)
SET_CHARGE_PUMP = const(0x8d) SET_CHARGE_PUMP = const(0x8D)
# Subclassing FrameBuffer provides support for graphics primitives # Subclassing FrameBuffer provides support for graphics primitives
# http://docs.micropython.org/en/latest/pyboard/library/framebuf.html # http://docs.micropython.org/en/latest/pyboard/library/framebuf.html
@ -39,25 +39,35 @@ class SSD1306(framebuf.FrameBuffer):
for cmd in ( for cmd in (
SET_DISP | 0x00, # off SET_DISP | 0x00, # off
# address setting # address setting
SET_MEM_ADDR, 0x00, # horizontal SET_MEM_ADDR,
0x00, # horizontal
# resolution and layout # resolution and layout
SET_DISP_START_LINE | 0x00, SET_DISP_START_LINE | 0x00,
SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0 SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0
SET_MUX_RATIO, self.height - 1, SET_MUX_RATIO,
self.height - 1,
SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0 SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0
SET_DISP_OFFSET, 0x00, SET_DISP_OFFSET,
SET_COM_PIN_CFG, 0x02 if self.height == 32 else 0x12, 0x00,
SET_COM_PIN_CFG,
0x02 if self.height == 32 else 0x12,
# timing and driving scheme # timing and driving scheme
SET_DISP_CLK_DIV, 0x80, SET_DISP_CLK_DIV,
SET_PRECHARGE, 0x22 if self.external_vcc else 0xf1, 0x80,
SET_VCOM_DESEL, 0x30, # 0.83*Vcc SET_PRECHARGE,
0x22 if self.external_vcc else 0xF1,
SET_VCOM_DESEL,
0x30, # 0.83*Vcc
# display # display
SET_CONTRAST, 0xff, # maximum SET_CONTRAST,
0xFF, # maximum
SET_ENTIRE_ON, # output follows RAM contents SET_ENTIRE_ON, # output follows RAM contents
SET_NORM_INV, # not inverted SET_NORM_INV, # not inverted
# charge pump # charge pump
SET_CHARGE_PUMP, 0x10 if self.external_vcc else 0x14, SET_CHARGE_PUMP,
SET_DISP | 0x01): # on 0x10 if self.external_vcc else 0x14,
SET_DISP | 0x01,
): # on
self.write_cmd(cmd) self.write_cmd(cmd)
self.fill(0) self.fill(0)
self.show() self.show()
@ -92,11 +102,11 @@ class SSD1306(framebuf.FrameBuffer):
class SSD1306_I2C(SSD1306): class SSD1306_I2C(SSD1306):
def __init__(self, width, height, i2c, addr=0x3c, external_vcc=False): def __init__(self, width, height, i2c, addr=0x3C, external_vcc=False):
self.i2c = i2c self.i2c = i2c
self.addr = addr self.addr = addr
self.temp = bytearray(2) self.temp = bytearray(2)
self.write_list = [b'\x40', None] # Co=0, D/C#=1 self.write_list = [b"\x40", None] # Co=0, D/C#=1
super().__init__(width, height, external_vcc) super().__init__(width, height, external_vcc)
def write_cmd(self, cmd): def write_cmd(self, cmd):
@ -120,6 +130,7 @@ class SSD1306_SPI(SSD1306):
self.res = res self.res = res
self.cs = cs self.cs = cs
import time import time
self.res(1) self.res(1)
time.sleep_ms(1) time.sleep_ms(1)
self.res(0) self.res(0)

View File

@ -12,11 +12,11 @@ SETUP_RETR = const(0x04)
RF_CH = const(0x05) RF_CH = const(0x05)
RF_SETUP = const(0x06) RF_SETUP = const(0x06)
STATUS = const(0x07) STATUS = const(0x07)
RX_ADDR_P0 = const(0x0a) RX_ADDR_P0 = const(0x0A)
TX_ADDR = const(0x10) TX_ADDR = const(0x10)
RX_PW_P0 = const(0x11) RX_PW_P0 = const(0x11)
FIFO_STATUS = const(0x17) FIFO_STATUS = const(0x17)
DYNPD = const(0x1c) DYNPD = const(0x1C)
# CONFIG register # CONFIG register
EN_CRC = const(0x08) # enable CRC EN_CRC = const(0x08) # enable CRC
@ -44,10 +44,11 @@ RX_EMPTY = const(0x01) # 1 if RX FIFO is empty
# constants for instructions # constants for instructions
R_RX_PL_WID = const(0x60) # read RX payload width R_RX_PL_WID = const(0x60) # read RX payload width
R_RX_PAYLOAD = const(0x61) # read RX payload R_RX_PAYLOAD = const(0x61) # read RX payload
W_TX_PAYLOAD = const(0xa0) # write TX payload W_TX_PAYLOAD = const(0xA0) # write TX payload
FLUSH_TX = const(0xe1) # flush TX FIFO FLUSH_TX = const(0xE1) # flush TX FIFO
FLUSH_RX = const(0xe2) # flush RX FIFO FLUSH_RX = const(0xE2) # flush RX FIFO
NOP = const(0xff) # use to read STATUS register NOP = const(0xFF) # use to read STATUS register
class NRF24L01: class NRF24L01:
def __init__(self, spi, cs, ce, channel=46, payload_size=16): def __init__(self, spi, cs, ce, channel=46, payload_size=16):
@ -232,7 +233,7 @@ class NRF24L01:
self.spi.readinto(self.buf, W_TX_PAYLOAD) self.spi.readinto(self.buf, W_TX_PAYLOAD)
self.spi.write(buf) self.spi.write(buf)
if len(buf) < self.payload_size: if len(buf) < self.payload_size:
self.spi.write(b'\x00' * (self.payload_size - len(buf))) # pad out data self.spi.write(b"\x00" * (self.payload_size - len(buf))) # pad out data
self.cs(1) self.cs(1)
# enable the chip so it can send the data # enable the chip so it can send the data

View File

@ -14,27 +14,28 @@ _RX_POLL_DELAY = const(15)
# master may be a slow device. Value tested with Pyboard, ESP32 and ESP8266. # master may be a slow device. Value tested with Pyboard, ESP32 and ESP8266.
_SLAVE_SEND_DELAY = const(10) _SLAVE_SEND_DELAY = const(10)
if sys.platform == 'pyboard': if sys.platform == "pyboard":
cfg = {'spi': 2, 'miso': 'Y7', 'mosi': 'Y8', 'sck': 'Y6', 'csn': 'Y5', 'ce': 'Y4'} cfg = {"spi": 2, "miso": "Y7", "mosi": "Y8", "sck": "Y6", "csn": "Y5", "ce": "Y4"}
elif sys.platform == 'esp8266': # Hardware SPI elif sys.platform == "esp8266": # Hardware SPI
cfg = {'spi': 1, 'miso': 12, 'mosi': 13, 'sck': 14, 'csn': 4, 'ce': 5} cfg = {"spi": 1, "miso": 12, "mosi": 13, "sck": 14, "csn": 4, "ce": 5}
elif sys.platform == 'esp32': # Software SPI elif sys.platform == "esp32": # Software SPI
cfg = {'spi': -1, 'miso': 32, 'mosi': 33, 'sck': 25, 'csn': 26, 'ce': 27} cfg = {"spi": -1, "miso": 32, "mosi": 33, "sck": 25, "csn": 26, "ce": 27}
else: else:
raise ValueError('Unsupported platform {}'.format(sys.platform)) raise ValueError("Unsupported platform {}".format(sys.platform))
# Addresses are in little-endian format. They correspond to big-endian # Addresses are in little-endian format. They correspond to big-endian
# 0xf0f0f0f0e1, 0xf0f0f0f0d2 # 0xf0f0f0f0e1, 0xf0f0f0f0d2
pipes = (b'\xe1\xf0\xf0\xf0\xf0', b'\xd2\xf0\xf0\xf0\xf0') pipes = (b"\xe1\xf0\xf0\xf0\xf0", b"\xd2\xf0\xf0\xf0\xf0")
def master(): def master():
csn = Pin(cfg['csn'], mode=Pin.OUT, value=1) csn = Pin(cfg["csn"], mode=Pin.OUT, value=1)
ce = Pin(cfg['ce'], mode=Pin.OUT, value=0) ce = Pin(cfg["ce"], mode=Pin.OUT, value=0)
if cfg['spi'] == -1: if cfg["spi"] == -1:
spi = SPI(-1, sck=Pin(cfg['sck']), mosi=Pin(cfg['mosi']), miso=Pin(cfg['miso'])) spi = SPI(-1, sck=Pin(cfg["sck"]), mosi=Pin(cfg["mosi"]), miso=Pin(cfg["miso"]))
nrf = NRF24L01(spi, csn, ce, payload_size=8) nrf = NRF24L01(spi, csn, ce, payload_size=8)
else: else:
nrf = NRF24L01(SPI(cfg['spi']), csn, ce, payload_size=8) nrf = NRF24L01(SPI(cfg["spi"]), csn, ce, payload_size=8)
nrf.open_tx_pipe(pipes[0]) nrf.open_tx_pipe(pipes[0])
nrf.open_rx_pipe(1, pipes[1]) nrf.open_rx_pipe(1, pipes[1])
@ -45,16 +46,16 @@ def master():
num_failures = 0 num_failures = 0
led_state = 0 led_state = 0
print('NRF24L01 master mode, sending %d packets...' % num_needed) print("NRF24L01 master mode, sending %d packets..." % num_needed)
while num_successes < num_needed and num_failures < num_needed: while num_successes < num_needed and num_failures < num_needed:
# stop listening and send packet # stop listening and send packet
nrf.stop_listening() nrf.stop_listening()
millis = utime.ticks_ms() millis = utime.ticks_ms()
led_state = max(1, (led_state << 1) & 0x0f) led_state = max(1, (led_state << 1) & 0x0F)
print('sending:', millis, led_state) print("sending:", millis, led_state)
try: try:
nrf.send(struct.pack('ii', millis, led_state)) nrf.send(struct.pack("ii", millis, led_state))
except OSError: except OSError:
pass pass
@ -69,43 +70,50 @@ def master():
timeout = True timeout = True
if timeout: if timeout:
print('failed, response timed out') print("failed, response timed out")
num_failures += 1 num_failures += 1
else: else:
# recv packet # recv packet
got_millis, = struct.unpack('i', nrf.recv()) (got_millis,) = struct.unpack("i", nrf.recv())
# print response and round-trip delay # print response and round-trip delay
print('got response:', got_millis, '(delay', utime.ticks_diff(utime.ticks_ms(), got_millis), 'ms)') print(
"got response:",
got_millis,
"(delay",
utime.ticks_diff(utime.ticks_ms(), got_millis),
"ms)",
)
num_successes += 1 num_successes += 1
# delay then loop # delay then loop
utime.sleep_ms(250) utime.sleep_ms(250)
print('master finished sending; successes=%d, failures=%d' % (num_successes, num_failures)) print("master finished sending; successes=%d, failures=%d" % (num_successes, num_failures))
def slave(): def slave():
csn = Pin(cfg['csn'], mode=Pin.OUT, value=1) csn = Pin(cfg["csn"], mode=Pin.OUT, value=1)
ce = Pin(cfg['ce'], mode=Pin.OUT, value=0) ce = Pin(cfg["ce"], mode=Pin.OUT, value=0)
if cfg['spi'] == -1: if cfg["spi"] == -1:
spi = SPI(-1, sck=Pin(cfg['sck']), mosi=Pin(cfg['mosi']), miso=Pin(cfg['miso'])) spi = SPI(-1, sck=Pin(cfg["sck"]), mosi=Pin(cfg["mosi"]), miso=Pin(cfg["miso"]))
nrf = NRF24L01(spi, csn, ce, payload_size=8) nrf = NRF24L01(spi, csn, ce, payload_size=8)
else: else:
nrf = NRF24L01(SPI(cfg['spi']), csn, ce, payload_size=8) nrf = NRF24L01(SPI(cfg["spi"]), csn, ce, payload_size=8)
nrf.open_tx_pipe(pipes[1]) nrf.open_tx_pipe(pipes[1])
nrf.open_rx_pipe(1, pipes[0]) nrf.open_rx_pipe(1, pipes[0])
nrf.start_listening() nrf.start_listening()
print('NRF24L01 slave mode, waiting for packets... (ctrl-C to stop)') print("NRF24L01 slave mode, waiting for packets... (ctrl-C to stop)")
while True: while True:
if nrf.any(): if nrf.any():
while nrf.any(): while nrf.any():
buf = nrf.recv() buf = nrf.recv()
millis, led_state = struct.unpack('ii', buf) millis, led_state = struct.unpack("ii", buf)
print('received:', millis, led_state) print("received:", millis, led_state)
for led in leds: for led in leds:
if led_state & 1: if led_state & 1:
led.on() led.on()
@ -118,23 +126,25 @@ def slave():
utime.sleep_ms(_SLAVE_SEND_DELAY) utime.sleep_ms(_SLAVE_SEND_DELAY)
nrf.stop_listening() nrf.stop_listening()
try: try:
nrf.send(struct.pack('i', millis)) nrf.send(struct.pack("i", millis))
except OSError: except OSError:
pass pass
print('sent response') print("sent response")
nrf.start_listening() nrf.start_listening()
try: try:
import pyb import pyb
leds = [pyb.LED(i + 1) for i in range(4)] leds = [pyb.LED(i + 1) for i in range(4)]
except: except:
leds = [] leds = []
print('NRF24L01 test module loaded') print("NRF24L01 test module loaded")
print('NRF24L01 pinout for test:') print("NRF24L01 pinout for test:")
print(' CE on', cfg['ce']) print(" CE on", cfg["ce"])
print(' CSN on', cfg['csn']) print(" CSN on", cfg["csn"])
print(' SCK on', cfg['sck']) print(" SCK on", cfg["sck"])
print(' MISO on', cfg['miso']) print(" MISO on", cfg["miso"])
print(' MOSI on', cfg['mosi']) print(" MOSI on", cfg["mosi"])
print('run nrf24l01test.slave() on slave, then nrf24l01test.master() on master') print("run nrf24l01test.slave() on slave, then nrf24l01test.master() on master")

View File

@ -4,8 +4,9 @@
from micropython import const from micropython import const
_CONVERT = const(0x44) _CONVERT = const(0x44)
_RD_SCRATCH = const(0xbe) _RD_SCRATCH = const(0xBE)
_WR_SCRATCH = const(0x4e) _WR_SCRATCH = const(0x4E)
class DS18X20: class DS18X20:
def __init__(self, onewire): def __init__(self, onewire):
@ -26,7 +27,7 @@ class DS18X20:
self.ow.writebyte(_RD_SCRATCH) self.ow.writebyte(_RD_SCRATCH)
self.ow.readinto(self.buf) self.ow.readinto(self.buf)
if self.ow.crc8(self.buf): if self.ow.crc8(self.buf):
raise Exception('CRC error') raise Exception("CRC error")
return self.buf return self.buf
def write_scratch(self, rom, buf): def write_scratch(self, rom, buf):
@ -40,12 +41,12 @@ class DS18X20:
if rom[0] == 0x10: if rom[0] == 0x10:
if buf[1]: if buf[1]:
t = buf[0] >> 1 | 0x80 t = buf[0] >> 1 | 0x80
t = -((~t + 1) & 0xff) t = -((~t + 1) & 0xFF)
else: else:
t = buf[0] >> 1 t = buf[0] >> 1
return t - 0.25 + (buf[7] - buf[6]) / buf[7] return t - 0.25 + (buf[7] - buf[6]) / buf[7]
else: else:
t = buf[1] << 8 | buf[0] t = buf[1] << 8 | buf[0]
if t & 0x8000: # sign bit set if t & 0x8000: # sign bit set
t = -((t ^ 0xffff) + 1) t = -((t ^ 0xFFFF) + 1)
return t / 16 return t / 16

View File

@ -4,13 +4,15 @@
from micropython import const from micropython import const
import _onewire as _ow import _onewire as _ow
class OneWireError(Exception): class OneWireError(Exception):
pass pass
class OneWire: class OneWire:
SEARCH_ROM = const(0xf0) SEARCH_ROM = const(0xF0)
MATCH_ROM = const(0x55) MATCH_ROM = const(0x55)
SKIP_ROM = const(0xcc) SKIP_ROM = const(0xCC)
def __init__(self, pin): def __init__(self, pin):
self.pin = pin self.pin = pin
@ -51,7 +53,7 @@ class OneWire:
devices = [] devices = []
diff = 65 diff = 65
rom = False rom = False
for i in range(0xff): for i in range(0xFF):
rom, diff = self._search_rom(rom, diff) rom, diff = self._search_rom(rom, diff)
if rom: if rom:
devices += [rom] devices += [rom]

View File

@ -33,9 +33,9 @@ _R1_ILLEGAL_COMMAND = const(1 << 2)
# R1_ERASE_SEQUENCE_ERROR = const(1 << 4) # R1_ERASE_SEQUENCE_ERROR = const(1 << 4)
# R1_ADDRESS_ERROR = const(1 << 5) # R1_ADDRESS_ERROR = const(1 << 5)
# R1_PARAMETER_ERROR = const(1 << 6) # R1_PARAMETER_ERROR = const(1 << 6)
_TOKEN_CMD25 = const(0xfc) _TOKEN_CMD25 = const(0xFC)
_TOKEN_STOP_TRAN = const(0xfd) _TOKEN_STOP_TRAN = const(0xFD)
_TOKEN_DATA = const(0xfe) _TOKEN_DATA = const(0xFE)
class SDCard: class SDCard:
@ -47,7 +47,7 @@ class SDCard:
self.dummybuf = bytearray(512) self.dummybuf = bytearray(512)
self.tokenbuf = bytearray(1) self.tokenbuf = bytearray(1)
for i in range(512): for i in range(512):
self.dummybuf[i] = 0xff self.dummybuf[i] = 0xFF
self.dummybuf_memoryview = memoryview(self.dummybuf) self.dummybuf_memoryview = memoryview(self.dummybuf)
# initialise the card # initialise the card
@ -72,7 +72,7 @@ class SDCard:
# clock card at least 100 cycles with cs high # clock card at least 100 cycles with cs high
for i in range(16): for i in range(16):
self.spi.write(b'\xff') self.spi.write(b"\xff")
# CMD0: init card; should return _R1_IDLE_STATE (allow 5 attempts) # CMD0: init card; should return _R1_IDLE_STATE (allow 5 attempts)
for _ in range(5): for _ in range(5):
@ -82,7 +82,7 @@ class SDCard:
raise OSError("no SD card") raise OSError("no SD card")
# CMD8: determine card version # CMD8: determine card version
r = self.cmd(8, 0x01aa, 0x87, 4) r = self.cmd(8, 0x01AA, 0x87, 4)
if r == _R1_IDLE_STATE: if r == _R1_IDLE_STATE:
self.init_card_v2() self.init_card_v2()
elif r == (_R1_IDLE_STATE | _R1_ILLEGAL_COMMAND): elif r == (_R1_IDLE_STATE | _R1_ILLEGAL_COMMAND):
@ -96,9 +96,9 @@ class SDCard:
raise OSError("no response from SD card") raise OSError("no response from SD card")
csd = bytearray(16) csd = bytearray(16)
self.readinto(csd) self.readinto(csd)
if csd[0] & 0xc0 == 0x40: # CSD version 2.0 if csd[0] & 0xC0 == 0x40: # CSD version 2.0
self.sectors = ((csd[8] << 8 | csd[9]) + 1) * 1024 self.sectors = ((csd[8] << 8 | csd[9]) + 1) * 1024
elif csd[0] & 0xc0 == 0x00: # CSD version 1.0 (old, <=2GB) elif csd[0] & 0xC0 == 0x00: # CSD version 1.0 (old, <=2GB)
c_size = csd[6] & 0b11 | csd[7] << 2 | (csd[8] & 0b11000000) << 4 c_size = csd[6] & 0b11 | csd[7] << 2 | (csd[8] & 0b11000000) << 4
c_size_mult = ((csd[9] & 0b11) << 1) | csd[10] >> 7 c_size_mult = ((csd[9] & 0b11) << 1) | csd[10] >> 7
self.sectors = (c_size + 1) * (2 ** (c_size_mult + 2)) self.sectors = (c_size + 1) * (2 ** (c_size_mult + 2))
@ -148,24 +148,24 @@ class SDCard:
self.spi.write(buf) self.spi.write(buf)
if skip1: if skip1:
self.spi.readinto(self.tokenbuf, 0xff) self.spi.readinto(self.tokenbuf, 0xFF)
# wait for the response (response[7] == 0) # wait for the response (response[7] == 0)
for i in range(_CMD_TIMEOUT): for i in range(_CMD_TIMEOUT):
self.spi.readinto(self.tokenbuf, 0xff) self.spi.readinto(self.tokenbuf, 0xFF)
response = self.tokenbuf[0] response = self.tokenbuf[0]
if not (response & 0x80): if not (response & 0x80):
# this could be a big-endian integer that we are getting here # this could be a big-endian integer that we are getting here
for j in range(final): for j in range(final):
self.spi.write(b'\xff') self.spi.write(b"\xff")
if release: if release:
self.cs(1) self.cs(1)
self.spi.write(b'\xff') self.spi.write(b"\xff")
return response return response
# timeout # timeout
self.cs(1) self.cs(1)
self.spi.write(b'\xff') self.spi.write(b"\xff")
return -1 return -1
def readinto(self, buf): def readinto(self, buf):
@ -173,7 +173,7 @@ class SDCard:
# read until start byte (0xff) # read until start byte (0xff)
for i in range(_CMD_TIMEOUT): for i in range(_CMD_TIMEOUT):
self.spi.readinto(self.tokenbuf, 0xff) self.spi.readinto(self.tokenbuf, 0xFF)
if self.tokenbuf[0] == _TOKEN_DATA: if self.tokenbuf[0] == _TOKEN_DATA:
break break
else: else:
@ -187,11 +187,11 @@ class SDCard:
self.spi.write_readinto(mv, buf) self.spi.write_readinto(mv, buf)
# read checksum # read checksum
self.spi.write(b'\xff') self.spi.write(b"\xff")
self.spi.write(b'\xff') self.spi.write(b"\xff")
self.cs(1) self.cs(1)
self.spi.write(b'\xff') self.spi.write(b"\xff")
def write(self, token, buf): def write(self, token, buf):
self.cs(0) self.cs(0)
@ -199,36 +199,36 @@ class SDCard:
# send: start of block, data, checksum # send: start of block, data, checksum
self.spi.read(1, token) self.spi.read(1, token)
self.spi.write(buf) self.spi.write(buf)
self.spi.write(b'\xff') self.spi.write(b"\xff")
self.spi.write(b'\xff') self.spi.write(b"\xff")
# check the response # check the response
if (self.spi.read(1, 0xff)[0] & 0x1f) != 0x05: if (self.spi.read(1, 0xFF)[0] & 0x1F) != 0x05:
self.cs(1) self.cs(1)
self.spi.write(b'\xff') self.spi.write(b"\xff")
return return
# wait for write to finish # wait for write to finish
while self.spi.read(1, 0xff)[0] == 0: while self.spi.read(1, 0xFF)[0] == 0:
pass pass
self.cs(1) self.cs(1)
self.spi.write(b'\xff') self.spi.write(b"\xff")
def write_token(self, token): def write_token(self, token):
self.cs(0) self.cs(0)
self.spi.read(1, token) self.spi.read(1, token)
self.spi.write(b'\xff') self.spi.write(b"\xff")
# wait for write to finish # wait for write to finish
while self.spi.read(1, 0xff)[0] == 0x00: while self.spi.read(1, 0xFF)[0] == 0x00:
pass pass
self.cs(1) self.cs(1)
self.spi.write(b'\xff') self.spi.write(b"\xff")
def readblocks(self, block_num, buf): def readblocks(self, block_num, buf):
nblocks = len(buf) // 512 nblocks = len(buf) // 512
assert nblocks and not len(buf) % 512, 'Buffer length is invalid' assert nblocks and not len(buf) % 512, "Buffer length is invalid"
if nblocks == 1: if nblocks == 1:
# CMD17: set read address for single block # CMD17: set read address for single block
if self.cmd(17, block_num * self.cdv, 0, release=False) != 0: if self.cmd(17, block_num * self.cdv, 0, release=False) != 0:
@ -250,12 +250,12 @@ class SDCard:
self.readinto(mv[offset : offset + 512]) self.readinto(mv[offset : offset + 512])
offset += 512 offset += 512
nblocks -= 1 nblocks -= 1
if self.cmd(12, 0, 0xff, skip1=True): if self.cmd(12, 0, 0xFF, skip1=True):
raise OSError(5) # EIO raise OSError(5) # EIO
def writeblocks(self, block_num, buf): def writeblocks(self, block_num, buf):
nblocks, err = divmod(len(buf), 512) nblocks, err = divmod(len(buf), 512)
assert nblocks and not err, 'Buffer length is invalid' assert nblocks and not err, "Buffer length is invalid"
if nblocks == 1: if nblocks == 1:
# CMD24: set write address for single block # CMD24: set write address for single block
if self.cmd(24, block_num * self.cdv, 0) != 0: if self.cmd(24, block_num * self.cdv, 0) != 0:

View File

@ -2,59 +2,60 @@
# Peter hinch 30th Jan 2016 # Peter hinch 30th Jan 2016
import os, sdcard, machine import os, sdcard, machine
def sdtest(): def sdtest():
spi = machine.SPI(1) spi = machine.SPI(1)
spi.init() # Ensure right baudrate spi.init() # Ensure right baudrate
sd = sdcard.SDCard(spi, machine.Pin.board.X21) # Compatible with PCB sd = sdcard.SDCard(spi, machine.Pin.board.X21) # Compatible with PCB
vfs = os.VfsFat(sd) vfs = os.VfsFat(sd)
os.mount(vfs, '/fc') os.mount(vfs, "/fc")
print('Filesystem check') print("Filesystem check")
print(os.listdir('/fc')) print(os.listdir("/fc"))
line = 'abcdefghijklmnopqrstuvwxyz\n' line = "abcdefghijklmnopqrstuvwxyz\n"
lines = line * 200 # 5400 chars lines = line * 200 # 5400 chars
short = '1234567890\n' short = "1234567890\n"
fn = '/fc/rats.txt' fn = "/fc/rats.txt"
print() print()
print('Multiple block read/write') print("Multiple block read/write")
with open(fn,'w') as f: with open(fn, "w") as f:
n = f.write(lines) n = f.write(lines)
print(n, 'bytes written') print(n, "bytes written")
n = f.write(short) n = f.write(short)
print(n, 'bytes written') print(n, "bytes written")
n = f.write(lines) n = f.write(lines)
print(n, 'bytes written') print(n, "bytes written")
with open(fn,'r') as f: with open(fn, "r") as f:
result1 = f.read() result1 = f.read()
print(len(result1), 'bytes read') print(len(result1), "bytes read")
fn = '/fc/rats1.txt' fn = "/fc/rats1.txt"
print() print()
print('Single block read/write') print("Single block read/write")
with open(fn,'w') as f: with open(fn, "w") as f:
n = f.write(short) # one block n = f.write(short) # one block
print(n, 'bytes written') print(n, "bytes written")
with open(fn,'r') as f: with open(fn, "r") as f:
result2 = f.read() result2 = f.read()
print(len(result2), 'bytes read') print(len(result2), "bytes read")
os.umount('/fc') os.umount("/fc")
print() print()
print('Verifying data read back') print("Verifying data read back")
success = True success = True
if result1 == ''.join((lines, short, lines)): if result1 == "".join((lines, short, lines)):
print('Large file Pass') print("Large file Pass")
else: else:
print('Large file Fail') print("Large file Fail")
success = False success = False
if result2 == short: if result2 == short:
print('Small file Pass') print("Small file Pass")
else: else:
print('Small file Fail') print("Small file Fail")
success = False success = False
print() print()
print('Tests', 'passed' if success else 'failed') print("Tests", "passed" if success else "failed")

View File

@ -16,10 +16,10 @@ pyb.LED(3).off() # indicate that we finished waiting for the swit
pyb.LED(4).on() # indicate that we are selecting the mode pyb.LED(4).on() # indicate that we are selecting the mode
if switch_value: if switch_value:
pyb.usb_mode('VCP+MSC') pyb.usb_mode("VCP+MSC")
pyb.main('cardreader.py') # if switch was pressed, run this pyb.main("cardreader.py") # if switch was pressed, run this
else: else:
pyb.usb_mode('VCP+HID') pyb.usb_mode("VCP+HID")
pyb.main('datalogger.py') # if switch wasn't pressed, run this pyb.main("datalogger.py") # if switch wasn't pressed, run this
pyb.LED(4).off() # indicate that we finished selecting the mode pyb.LED(4).off() # indicate that we finished selecting the mode

View File

@ -19,13 +19,13 @@ while True:
if switch(): if switch():
pyb.delay(200) # delay avoids detection of multiple presses pyb.delay(200) # delay avoids detection of multiple presses
blue.on() # blue LED indicates file open blue.on() # blue LED indicates file open
log = open('/sd/log.csv', 'w') # open file on SD (SD: '/sd/', flash: '/flash/) log = open("/sd/log.csv", "w") # open file on SD (SD: '/sd/', flash: '/flash/)
# until switch is pressed again # until switch is pressed again
while not switch(): while not switch():
t = pyb.millis() # get time t = pyb.millis() # get time
x, y, z = accel.filtered_xyz() # get acceleration data x, y, z = accel.filtered_xyz() # get acceleration data
log.write('{},{},{},{}\n'.format(t,x,y,z)) # write data to file log.write("{},{},{},{}\n".format(t, x, y, z)) # write data to file
# end after switch is pressed again # end after switch is pressed again
log.close() # close file log.close() # close file

View File

@ -17,10 +17,10 @@ accel_pwr.value(1)
i2c = I2C(1, baudrate=100000) i2c = I2C(1, baudrate=100000)
addrs = i2c.scan() addrs = i2c.scan()
print("Scanning devices:", [hex(x) for x in addrs]) print("Scanning devices:", [hex(x) for x in addrs])
if 0x4c not in addrs: if 0x4C not in addrs:
print("Accelerometer is not detected") print("Accelerometer is not detected")
ACCEL_ADDR = 0x4c ACCEL_ADDR = 0x4C
ACCEL_AXIS_X_REG = 0 ACCEL_AXIS_X_REG = 0
ACCEL_MODE_REG = 7 ACCEL_MODE_REG = 7

View File

@ -6,7 +6,7 @@ accel = pyb.Accel() # create object of accelerom
blue = pyb.LED(4) # create object of blue LED blue = pyb.LED(4) # create object of blue LED
# open file to write data - /sd/ is the SD-card, /flash/ the internal memory # open file to write data - /sd/ is the SD-card, /flash/ the internal memory
log = open('/sd/log.csv', 'w') log = open("/sd/log.csv", "w")
blue.on() # turn on blue LED blue.on() # turn on blue LED
@ -14,7 +14,7 @@ blue.on() # turn on blue LED
for i in range(100): for i in range(100):
t = pyb.millis() # get time since reset t = pyb.millis() # get time since reset
x, y, z = accel.filtered_xyz() # get acceleration data x, y, z = accel.filtered_xyz() # get acceleration data
log.write('{},{},{},{}\n'.format(t,x,y,z)) # write data to file log.write("{},{},{},{}\n".format(t, x, y, z)) # write data to file
log.close() # close file log.close() # close file
blue.off() # turn off LED blue.off() # turn off LED

View File

@ -2,8 +2,8 @@
# this version is overly verbose and uses word stores # this version is overly verbose and uses word stores
@micropython.asm_thumb @micropython.asm_thumb
def flash_led(r0): def flash_led(r0):
movw(r1, (stm.GPIOA + stm.GPIO_BSRRL) & 0xffff) movw(r1, (stm.GPIOA + stm.GPIO_BSRRL) & 0xFFFF)
movt(r1, ((stm.GPIOA + stm.GPIO_BSRRL) >> 16) & 0x7fff) movt(r1, ((stm.GPIOA + stm.GPIO_BSRRL) >> 16) & 0x7FFF)
movw(r2, 1 << 13) movw(r2, 1 << 13)
movt(r2, 0) movt(r2, 0)
movw(r3, 0) movw(r3, 0)
@ -17,8 +17,8 @@ def flash_led(r0):
str(r2, [r1, 0]) str(r2, [r1, 0])
# delay for a bit # delay for a bit
movw(r4, 5599900 & 0xffff) movw(r4, 5599900 & 0xFFFF)
movt(r4, (5599900 >> 16) & 0xffff) movt(r4, (5599900 >> 16) & 0xFFFF)
label(delay_on) label(delay_on)
sub(r4, r4, 1) sub(r4, r4, 1)
cmp(r4, 0) cmp(r4, 0)
@ -28,8 +28,8 @@ def flash_led(r0):
str(r3, [r1, 0]) str(r3, [r1, 0])
# delay for a bit # delay for a bit
movw(r4, 5599900 & 0xffff) movw(r4, 5599900 & 0xFFFF)
movt(r4, (5599900 >> 16) & 0xffff) movt(r4, (5599900 >> 16) & 0xFFFF)
label(delay_off) label(delay_off)
sub(r4, r4, 1) sub(r4, r4, 1)
cmp(r4, 0) cmp(r4, 0)
@ -41,6 +41,7 @@ def flash_led(r0):
cmp(r0, 0) cmp(r0, 0)
bgt(loop1) bgt(loop1)
# flash LED #2 using inline assembler # flash LED #2 using inline assembler
# this version uses half-word sortes, and the convenience assembler operation 'movwt' # this version uses half-word sortes, and the convenience assembler operation 'movwt'
@micropython.asm_thumb @micropython.asm_thumb
@ -81,5 +82,6 @@ def flash_led_v2(r0):
cmp(r0, 0) cmp(r0, 0)
bgt(loop1) bgt(loop1)
flash_led(5) flash_led(5)
flash_led_v2(5) flash_led_v2(5)

View File

@ -22,6 +22,7 @@ def asm_sum_words(r0, r1):
mov(r0, r2) mov(r0, r2)
@micropython.asm_thumb @micropython.asm_thumb
def asm_sum_bytes(r0, r1): def asm_sum_bytes(r0, r1):
@ -46,12 +47,13 @@ def asm_sum_bytes(r0, r1):
mov(r0, r2) mov(r0, r2)
import array import array
b = array.array('l', (100, 200, 300, 400)) b = array.array("l", (100, 200, 300, 400))
n = asm_sum_words(len(b), b) n = asm_sum_words(len(b), b)
print(b, n) print(b, n)
b = array.array('b', (10, 20, 30, 40, 50, 60, 70, 80)) b = array.array("b", (10, 20, 30, 40, 50, 60, 70, 80))
n = asm_sum_bytes(len(b), b) n = asm_sum_bytes(len(b), b)
print(b, n) print(b, n)

View File

@ -26,9 +26,12 @@ def advertising_payload(limited_disc=False, br_edr=False, name=None, services=No
def _append(adv_type, value): def _append(adv_type, value):
nonlocal payload nonlocal payload
payload += struct.pack('BB', len(value) + 1, adv_type) + value payload += struct.pack("BB", len(value) + 1, adv_type) + value
_append(_ADV_TYPE_FLAGS, struct.pack('B', (0x01 if limited_disc else 0x02) + (0x00 if br_edr else 0x04))) _append(
_ADV_TYPE_FLAGS,
struct.pack("B", (0x01 if limited_disc else 0x02) + (0x00 if br_edr else 0x04)),
)
if name: if name:
_append(_ADV_TYPE_NAME, name) _append(_ADV_TYPE_NAME, name)
@ -44,7 +47,7 @@ def advertising_payload(limited_disc=False, br_edr=False, name=None, services=No
_append(_ADV_TYPE_UUID128_COMPLETE, b) _append(_ADV_TYPE_UUID128_COMPLETE, b)
# See org.bluetooth.characteristic.gap.appearance.xml # See org.bluetooth.characteristic.gap.appearance.xml
_append(_ADV_TYPE_APPEARANCE, struct.pack('<h', appearance)) _append(_ADV_TYPE_APPEARANCE, struct.pack("<h", appearance))
return payload return payload
@ -61,25 +64,29 @@ def decode_field(payload, adv_type):
def decode_name(payload): def decode_name(payload):
n = decode_field(payload, _ADV_TYPE_NAME) n = decode_field(payload, _ADV_TYPE_NAME)
return str(n[0], 'utf-8') if n else '' return str(n[0], "utf-8") if n else ""
def decode_services(payload): def decode_services(payload):
services = [] services = []
for u in decode_field(payload, _ADV_TYPE_UUID16_COMPLETE): for u in decode_field(payload, _ADV_TYPE_UUID16_COMPLETE):
services.append(bluetooth.UUID(struct.unpack('<h', u)[0])) services.append(bluetooth.UUID(struct.unpack("<h", u)[0]))
for u in decode_field(payload, _ADV_TYPE_UUID32_COMPLETE): for u in decode_field(payload, _ADV_TYPE_UUID32_COMPLETE):
services.append(bluetooth.UUID(struct.unpack('<d', u)[0])) services.append(bluetooth.UUID(struct.unpack("<d", u)[0]))
for u in decode_field(payload, _ADV_TYPE_UUID128_COMPLETE): for u in decode_field(payload, _ADV_TYPE_UUID128_COMPLETE):
services.append(bluetooth.UUID(u)) services.append(bluetooth.UUID(u))
return services return services
def demo(): def demo():
payload = advertising_payload(name='micropython', services=[bluetooth.UUID(0x181A), bluetooth.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E')]) payload = advertising_payload(
name="micropython",
services=[bluetooth.UUID(0x181A), bluetooth.UUID("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")],
)
print(payload) print(payload)
print(decode_name(payload)) print(decode_name(payload))
print(decode_services(payload)) print(decode_services(payload))
if __name__ == '__main__':
if __name__ == "__main__":
demo() demo()

View File

@ -10,26 +10,36 @@ import time
from ble_advertising import advertising_payload from ble_advertising import advertising_payload
from micropython import const from micropython import const
_IRQ_CENTRAL_CONNECT = const(1 << 0) _IRQ_CENTRAL_CONNECT = const(1 << 0)
_IRQ_CENTRAL_DISCONNECT = const(1 << 1) _IRQ_CENTRAL_DISCONNECT = const(1 << 1)
# org.bluetooth.service.environmental_sensing # org.bluetooth.service.environmental_sensing
_ENV_SENSE_UUID = bluetooth.UUID(0x181A) _ENV_SENSE_UUID = bluetooth.UUID(0x181A)
# org.bluetooth.characteristic.temperature # org.bluetooth.characteristic.temperature
_TEMP_CHAR = (bluetooth.UUID(0x2A6E), bluetooth.FLAG_READ|bluetooth.FLAG_NOTIFY,) _TEMP_CHAR = (
_ENV_SENSE_SERVICE = (_ENV_SENSE_UUID, (_TEMP_CHAR,),) bluetooth.UUID(0x2A6E),
bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY,
)
_ENV_SENSE_SERVICE = (
_ENV_SENSE_UUID,
(_TEMP_CHAR,),
)
# org.bluetooth.characteristic.gap.appearance.xml # org.bluetooth.characteristic.gap.appearance.xml
_ADV_APPEARANCE_GENERIC_THERMOMETER = const(768) _ADV_APPEARANCE_GENERIC_THERMOMETER = const(768)
class BLETemperature: class BLETemperature:
def __init__(self, ble, name='mpy-temp'): def __init__(self, ble, name="mpy-temp"):
self._ble = ble self._ble = ble
self._ble.active(True) self._ble.active(True)
self._ble.irq(handler=self._irq) self._ble.irq(handler=self._irq)
((self._handle,),) = self._ble.gatts_register_services((_ENV_SENSE_SERVICE,)) ((self._handle,),) = self._ble.gatts_register_services((_ENV_SENSE_SERVICE,))
self._connections = set() self._connections = set()
self._payload = advertising_payload(name=name, services=[_ENV_SENSE_UUID], appearance=_ADV_APPEARANCE_GENERIC_THERMOMETER) self._payload = advertising_payload(
name=name, services=[_ENV_SENSE_UUID], appearance=_ADV_APPEARANCE_GENERIC_THERMOMETER
)
self._advertise() self._advertise()
def _irq(self, event, data): def _irq(self, event, data):
@ -46,7 +56,7 @@ class BLETemperature:
def set_temperature(self, temp_deg_c, notify=False): def set_temperature(self, temp_deg_c, notify=False):
# Data is sint16 in degrees Celsius with a resolution of 0.01 degrees Celsius. # Data is sint16 in degrees Celsius with a resolution of 0.01 degrees Celsius.
# Write the local value, ready for a central to read. # Write the local value, ready for a central to read.
self._ble.gatts_write(self._handle, struct.pack('<h', int(temp_deg_c * 100))) self._ble.gatts_write(self._handle, struct.pack("<h", int(temp_deg_c * 100)))
if notify: if notify:
for conn_handle in self._connections: for conn_handle in self._connections:
# Notify connected centrals to issue a read. # Notify connected centrals to issue a read.
@ -72,5 +82,5 @@ def demo():
time.sleep_ms(1000) time.sleep_ms(1000)
if __name__ == '__main__': if __name__ == "__main__":
demo() demo()

View File

@ -9,6 +9,7 @@ import micropython
from ble_advertising import decode_services, decode_name from ble_advertising import decode_services, decode_name
from micropython import const from micropython import const
_IRQ_CENTRAL_CONNECT = const(1 << 0) _IRQ_CENTRAL_CONNECT = const(1 << 0)
_IRQ_CENTRAL_DISCONNECT = const(1 << 1) _IRQ_CENTRAL_DISCONNECT = const(1 << 1)
_IRQ_GATTS_WRITE = const(1 << 2) _IRQ_GATTS_WRITE = const(1 << 2)
@ -24,18 +25,25 @@ _IRQ_GATTC_READ_RESULT = const(1 << 11)
_IRQ_GATTC_WRITE_STATUS = const(1 << 12) _IRQ_GATTC_WRITE_STATUS = const(1 << 12)
_IRQ_GATTC_NOTIFY = const(1 << 13) _IRQ_GATTC_NOTIFY = const(1 << 13)
_IRQ_GATTC_INDICATE = const(1 << 14) _IRQ_GATTC_INDICATE = const(1 << 14)
_IRQ_ALL = const(0xffff) _IRQ_ALL = const(0xFFFF)
# org.bluetooth.service.environmental_sensing # org.bluetooth.service.environmental_sensing
_ENV_SENSE_UUID = bluetooth.UUID(0x181A) _ENV_SENSE_UUID = bluetooth.UUID(0x181A)
# org.bluetooth.characteristic.temperature # org.bluetooth.characteristic.temperature
_TEMP_UUID = bluetooth.UUID(0x2A6E) _TEMP_UUID = bluetooth.UUID(0x2A6E)
_TEMP_CHAR = (_TEMP_UUID, bluetooth.FLAG_READ|bluetooth.FLAG_NOTIFY,) _TEMP_CHAR = (
_ENV_SENSE_SERVICE = (_ENV_SENSE_UUID, (_TEMP_CHAR,),) _TEMP_UUID,
bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY,
)
_ENV_SENSE_SERVICE = (
_ENV_SENSE_UUID,
(_TEMP_CHAR,),
)
# org.bluetooth.characteristic.gap.appearance.xml # org.bluetooth.characteristic.gap.appearance.xml
_ADV_APPEARANCE_GENERIC_THERMOMETER = const(768) _ADV_APPEARANCE_GENERIC_THERMOMETER = const(768)
class BLETemperatureCentral: class BLETemperatureCentral:
def __init__(self, ble): def __init__(self, ble):
self._ble = ble self._ble = ble
@ -72,8 +80,10 @@ class BLETemperatureCentral:
if connectable and _ENV_SENSE_UUID in decode_services(adv_data): if connectable and _ENV_SENSE_UUID in decode_services(adv_data):
# Found a potential device, remember it and stop scanning. # Found a potential device, remember it and stop scanning.
self._addr_type = addr_type self._addr_type = addr_type
self._addr = bytes(addr) # Note: addr buffer is owned by caller so need to copy it. self._addr = bytes(
self._name = decode_name(adv_data) or '?' addr
) # Note: addr buffer is owned by caller so need to copy it.
self._name = decode_name(adv_data) or "?"
self._ble.gap_scan(None) self._ble.gap_scan(None)
elif event == _IRQ_SCAN_COMPLETE: elif event == _IRQ_SCAN_COMPLETE:
@ -104,7 +114,9 @@ class BLETemperatureCentral:
# Connected device returned a service. # Connected device returned a service.
conn_handle, start_handle, end_handle, uuid = data conn_handle, start_handle, end_handle, uuid = data
if conn_handle == self._conn_handle and uuid == _ENV_SENSE_UUID: if conn_handle == self._conn_handle and uuid == _ENV_SENSE_UUID:
self._ble.gattc_discover_characteristics(self._conn_handle, start_handle, end_handle) self._ble.gattc_discover_characteristics(
self._conn_handle, start_handle, end_handle
)
elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT: elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT:
# Connected device returned a characteristic. # Connected device returned a characteristic.
@ -132,7 +144,6 @@ class BLETemperatureCentral:
if self._notify_callback: if self._notify_callback:
self._notify_callback(self._value) self._notify_callback(self._value)
# Returns true if we've successfully connected and discovered characteristics. # Returns true if we've successfully connected and discovered characteristics.
def is_connected(self): def is_connected(self):
return self._conn_handle is not None and self._value_handle is not None return self._conn_handle is not None and self._value_handle is not None
@ -174,7 +185,7 @@ class BLETemperatureCentral:
def _update_value(self, data): def _update_value(self, data):
# Data is sint16 in degrees Celsius with a resolution of 0.01 degrees Celsius. # Data is sint16 in degrees Celsius with a resolution of 0.01 degrees Celsius.
self._value = struct.unpack('<h', data)[0] / 100 self._value = struct.unpack("<h", data)[0] / 100
return self._value return self._value
def value(self): def value(self):
@ -189,12 +200,12 @@ def demo():
def on_scan(addr_type, addr, name): def on_scan(addr_type, addr, name):
if addr_type is not None: if addr_type is not None:
print('Found sensor:', addr_type, addr, name) print("Found sensor:", addr_type, addr, name)
central.connect() central.connect()
else: else:
nonlocal not_found nonlocal not_found
not_found = True not_found = True
print('No sensor found.') print("No sensor found.")
central.scan(callback=on_scan) central.scan(callback=on_scan)
@ -204,7 +215,7 @@ def demo():
if not_found: if not_found:
return return
print('Connected') print("Connected")
# Explicitly issue reads, using "print" as the callback. # Explicitly issue reads, using "print" as the callback.
while central.is_connected(): while central.is_connected():
@ -216,7 +227,8 @@ def demo():
# print(central.value()) # print(central.value())
# time.sleep_ms(2000) # time.sleep_ms(2000)
print('Disconnected') print("Disconnected")
if __name__ == '__main__':
if __name__ == "__main__":
demo() demo()

View File

@ -4,24 +4,37 @@ import bluetooth
from ble_advertising import advertising_payload from ble_advertising import advertising_payload
from micropython import const from micropython import const
_IRQ_CENTRAL_CONNECT = const(1 << 0) _IRQ_CENTRAL_CONNECT = const(1 << 0)
_IRQ_CENTRAL_DISCONNECT = const(1 << 1) _IRQ_CENTRAL_DISCONNECT = const(1 << 1)
_IRQ_GATTS_WRITE = const(1 << 2) _IRQ_GATTS_WRITE = const(1 << 2)
_UART_UUID = bluetooth.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E') _UART_UUID = bluetooth.UUID("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
_UART_TX = (bluetooth.UUID('6E400003-B5A3-F393-E0A9-E50E24DCCA9E'), bluetooth.FLAG_NOTIFY,) _UART_TX = (
_UART_RX = (bluetooth.UUID('6E400002-B5A3-F393-E0A9-E50E24DCCA9E'), bluetooth.FLAG_WRITE,) bluetooth.UUID("6E400003-B5A3-F393-E0A9-E50E24DCCA9E"),
_UART_SERVICE = (_UART_UUID, (_UART_TX, _UART_RX,),) bluetooth.FLAG_NOTIFY,
)
_UART_RX = (
bluetooth.UUID("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"),
bluetooth.FLAG_WRITE,
)
_UART_SERVICE = (
_UART_UUID,
(_UART_TX, _UART_RX,),
)
# org.bluetooth.characteristic.gap.appearance.xml # org.bluetooth.characteristic.gap.appearance.xml
_ADV_APPEARANCE_GENERIC_COMPUTER = const(128) _ADV_APPEARANCE_GENERIC_COMPUTER = const(128)
class BLEUART: class BLEUART:
def __init__(self, ble, name='mpy-uart', rxbuf=100): def __init__(self, ble, name="mpy-uart", rxbuf=100):
self._ble = ble self._ble = ble
self._ble.active(True) self._ble.active(True)
self._ble.irq(handler=self._irq) self._ble.irq(handler=self._irq)
((self._tx_handle, self._rx_handle,),) = self._ble.gatts_register_services((_UART_SERVICE,)) ((self._tx_handle, self._rx_handle,),) = self._ble.gatts_register_services(
(_UART_SERVICE,)
)
# Increase the size of the rx buffer and enable append mode. # Increase the size of the rx buffer and enable append mode.
self._ble.gatts_set_buffer(self._rx_handle, rxbuf, True) self._ble.gatts_set_buffer(self._rx_handle, rxbuf, True)
self._connections = set() self._connections = set()
@ -82,7 +95,7 @@ def demo():
uart = BLEUART(ble) uart = BLEUART(ble)
def on_rx(): def on_rx():
print('rx: ', uart.read().decode().strip()) print("rx: ", uart.read().decode().strip())
uart.irq(handler=on_rx) uart.irq(handler=on_rx)
nums = [4, 8, 15, 16, 23, 42] nums = [4, 8, 15, 16, 23, 42]
@ -90,7 +103,7 @@ def demo():
try: try:
while True: while True:
uart.write(str(nums[i]) + '\n') uart.write(str(nums[i]) + "\n")
i = (i + 1) % len(nums) i = (i + 1) % len(nums)
time.sleep_ms(1000) time.sleep_ms(1000)
except KeyboardInterrupt: except KeyboardInterrupt:
@ -99,5 +112,5 @@ def demo():
uart.close() uart.close()
if __name__ == '__main__': if __name__ == "__main__":
demo() demo()

View File

@ -15,7 +15,7 @@ _MP_STREAM_POLL = const(3)
_MP_STREAM_POLL_RD = const(0x0001) _MP_STREAM_POLL_RD = const(0x0001)
# TODO: Remove this when STM32 gets machine.Timer. # TODO: Remove this when STM32 gets machine.Timer.
if hasattr(machine, 'Timer'): if hasattr(machine, "Timer"):
_timer = machine.Timer(-1) _timer = machine.Timer(-1)
else: else:
_timer = None _timer = None
@ -24,11 +24,13 @@ else:
def schedule_in(handler, delay_ms): def schedule_in(handler, delay_ms):
def _wrap(_arg): def _wrap(_arg):
handler() handler()
if _timer: if _timer:
_timer.init(mode=machine.Timer.ONE_SHOT, period=delay_ms, callback=_wrap) _timer.init(mode=machine.Timer.ONE_SHOT, period=delay_ms, callback=_wrap)
else: else:
micropython.schedule(_wrap, None) micropython.schedule(_wrap, None)
# Simple buffering stream to support the dupterm requirements. # Simple buffering stream to support the dupterm requirements.
class BLEUARTStream(io.IOBase): class BLEUARTStream(io.IOBase):
def __init__(self, uart): def __init__(self, uart):
@ -38,7 +40,7 @@ class BLEUARTStream(io.IOBase):
def _on_rx(self): def _on_rx(self):
# Needed for ESP32. # Needed for ESP32.
if hasattr(os, 'dupterm_notify'): if hasattr(os, "dupterm_notify"):
os.dupterm_notify(None) os.dupterm_notify(None)
def read(self, sz=None): def read(self, sz=None):
@ -74,7 +76,7 @@ class BLEUARTStream(io.IOBase):
def start(): def start():
ble = bluetooth.BLE() ble = bluetooth.BLE()
uart = BLEUART(ble, name='mpy-repl') uart = BLEUART(ble, name="mpy-repl")
stream = BLEUARTStream(uart) stream = BLEUARTStream(uart)
os.dupterm(stream) os.dupterm(stream)

View File

@ -1,7 +1,7 @@
# import essential libraries # import essential libraries
import pyb import pyb
lcd = pyb.LCD('x') lcd = pyb.LCD("x")
lcd.light(1) lcd.light(1)
# do 1 iteration of Conway's Game of Life # do 1 iteration of Conway's Game of Life
@ -9,14 +9,16 @@ def conway_step():
for x in range(128): # loop over x coordinates for x in range(128): # loop over x coordinates
for y in range(32): # loop over y coordinates for y in range(32): # loop over y coordinates
# count number of neighbours # count number of neighbours
num_neighbours = (lcd.get(x - 1, y - 1) + num_neighbours = (
lcd.get(x, y - 1) + lcd.get(x - 1, y - 1)
lcd.get(x + 1, y - 1) + + lcd.get(x, y - 1)
lcd.get(x - 1, y) + + lcd.get(x + 1, y - 1)
lcd.get(x + 1, y) + + lcd.get(x - 1, y)
lcd.get(x + 1, y + 1) + + lcd.get(x + 1, y)
lcd.get(x, y + 1) + + lcd.get(x + 1, y + 1)
lcd.get(x - 1, y + 1)) + lcd.get(x, y + 1)
+ lcd.get(x - 1, y + 1)
)
# check if the centre cell is alive or not # check if the centre cell is alive or not
self = lcd.get(x, y) self = lcd.get(x, y)
@ -27,6 +29,7 @@ def conway_step():
elif not self and num_neighbours == 3: elif not self and num_neighbours == 3:
lcd.pixel(x, y, 1) # exactly 3 neighbours around an empty cell: cell is born lcd.pixel(x, y, 1) # exactly 3 neighbours around an empty cell: cell is born
# randomise the start # randomise the start
def conway_rand(): def conway_rand():
lcd.fill(0) # clear the LCD lcd.fill(0) # clear the LCD
@ -34,6 +37,7 @@ def conway_rand():
for y in range(32): # loop over y coordinates for y in range(32): # loop over y coordinates
lcd.pixel(x, y, pyb.rng() & 1) # set the pixel randomly lcd.pixel(x, y, pyb.rng() & 1) # set the pixel randomly
# loop for a certain number of frames, doing iterations of Conway's Game of Life # loop for a certain number of frames, doing iterations of Conway's Game of Life
def conway_go(num_frames): def conway_go(num_frames):
for i in range(num_frames): for i in range(num_frames):
@ -41,6 +45,7 @@ def conway_go(num_frames):
lcd.show() # update the LCD lcd.show() # update the LCD
pyb.delay(50) pyb.delay(50)
# testing # testing
conway_rand() conway_rand()
conway_go(100) conway_go(100)

View File

@ -4,11 +4,13 @@ from hwconfig import LED, BUTTON
# machine.time_pulse_us() function demo # machine.time_pulse_us() function demo
print("""\ print(
"""\
Let's play an interesting game: Let's play an interesting game:
You click button as fast as you can, and I tell you how slow you are. You click button as fast as you can, and I tell you how slow you are.
Ready? Cliiiiick! Ready? Cliiiiick!
""") """
)
while 1: while 1:
delay = machine.time_pulse_us(BUTTON, 1, 10 * 1000 * 1000) delay = machine.time_pulse_us(BUTTON, 1, 10 * 1000 * 1000)

View File

@ -1,7 +1,6 @@
# This is hwconfig for "emulation" for cases when there's no real hardware. # This is hwconfig for "emulation" for cases when there's no real hardware.
# It just prints information to console. # It just prints information to console.
class LEDClass: class LEDClass:
def __init__(self, id): def __init__(self, id):
self.id = "LED(%d):" % id self.id = "LED(%d):" % id

View File

@ -1,13 +1,13 @@
from machine import Pin, Signal from machine import Pin, Signal
# Red LED on pin LED_RED also kown as A13 # Red LED on pin LED_RED also kown as A13
LED = Signal('LED_RED', Pin.OUT) LED = Signal("LED_RED", Pin.OUT)
# Green LED on pin LED_GREEN also known as A14 # Green LED on pin LED_GREEN also known as A14
LED2 = Signal('LED_GREEN', Pin.OUT) LED2 = Signal("LED_GREEN", Pin.OUT)
# Yellow LED on pin LED_YELLOW also known as A15 # Yellow LED on pin LED_YELLOW also known as A15
LED3 = Signal('LED_YELLOW', Pin.OUT) LED3 = Signal("LED_YELLOW", Pin.OUT)
# Blue LED on pin LED_BLUE also known as B4 # Blue LED on pin LED_BLUE also known as B4
LED4 = Signal('LED_BLUE', Pin.OUT) LED4 = Signal("LED_BLUE", Pin.OUT)

View File

@ -1,5 +1,6 @@
import pyb import pyb
def led_angle(seconds_to_run_for): def led_angle(seconds_to_run_for):
# make LED objects # make LED objects
l1 = pyb.LED(1) l1 = pyb.LED(1)

View File

@ -3,6 +3,7 @@ try:
except: except:
pass pass
def mandelbrot(): def mandelbrot():
# returns True if c, complex, is in the Mandelbrot set # returns True if c, complex, is in the Mandelbrot set
# @micropython.native # @micropython.native
@ -21,7 +22,9 @@ def mandelbrot():
lcd.set(u, v) lcd.set(u, v)
lcd.show() lcd.show()
# PC testing # PC testing
import lcd import lcd
lcd = lcd.LCD(128, 32) lcd = lcd.LCD(128, 32)
mandelbrot() mandelbrot()

View File

@ -2,7 +2,9 @@
# Dummy function decorators # Dummy function decorators
def nodecor(x): def nodecor(x):
return x return x
bytecode = native = viper = nodecor bytecode = native = viper = nodecor

View File

@ -2,20 +2,22 @@
import array import array
def isclose(a, b): def isclose(a, b):
return abs(a - b) < 1e-3 return abs(a - b) < 1e-3
def test(): def test():
tests = [ tests = [
isclose(add(0.1, 0.2), 0.3), isclose(add(0.1, 0.2), 0.3),
isclose(add_f(0.1, 0.2), 0.3), isclose(add_f(0.1, 0.2), 0.3),
] ]
ar = array.array('f', [1, 2, 3.5]) ar = array.array("f", [1, 2, 3.5])
productf(ar) productf(ar)
tests.append(isclose(ar[0], 7)) tests.append(isclose(ar[0], 7))
if 'add_d' in globals(): if "add_d" in globals():
tests.append(isclose(add_d(0.1, 0.2), 0.3)) tests.append(isclose(add_d(0.1, 0.2), 0.3))
print(tests) print(tests)
@ -23,4 +25,5 @@ def test():
if not all(tests): if not all(tests):
raise SystemExit(1) raise SystemExit(1)
test() test()

View File

@ -10,6 +10,7 @@ HTTP/1.0 200 OK
Hello #%d from MicroPython! Hello #%d from MicroPython!
""" """
def main(micropython_optimize=False): def main(micropython_optimize=False):
s = socket.socket() s = socket.socket()

View File

@ -12,6 +12,7 @@ HTTP/1.0 200 OK
Hello #%d from MicroPython! Hello #%d from MicroPython!
""" """
def main(): def main():
s = socket.socket() s = socket.socket()
ai = socket.getaddrinfo("0.0.0.0", 8080) ai = socket.getaddrinfo("0.0.0.0", 8080)

View File

@ -20,6 +20,7 @@ HTTP/1.0 200 OK
Hello #%d from MicroPython! Hello #%d from MicroPython!
""" """
def main(): def main():
s = socket.socket() s = socket.socket()

View File

@ -1,4 +1,5 @@
import ubinascii as binascii import ubinascii as binascii
try: try:
import usocket as socket import usocket as socket
except: except:
@ -9,30 +10,32 @@ import ussl as ssl
# This self-signed key/cert pair is randomly generated and to be used for # This self-signed key/cert pair is randomly generated and to be used for
# testing/demonstration only. You should always generate your own key/cert. # testing/demonstration only. You should always generate your own key/cert.
key = binascii.unhexlify( key = binascii.unhexlify(
b'3082013b020100024100cc20643fd3d9c21a0acba4f48f61aadd675f52175a9dcf07fbef' b"3082013b020100024100cc20643fd3d9c21a0acba4f48f61aadd675f52175a9dcf07fbef"
b'610a6a6ba14abb891745cd18a1d4c056580d8ff1a639460f867013c8391cdc9f2e573b0f' b"610a6a6ba14abb891745cd18a1d4c056580d8ff1a639460f867013c8391cdc9f2e573b0f"
b'872d0203010001024100bb17a54aeb3dd7ae4edec05e775ca9632cf02d29c2a089b563b0' b"872d0203010001024100bb17a54aeb3dd7ae4edec05e775ca9632cf02d29c2a089b563b0"
b'd05cdf95aeca507de674553f28b4eadaca82d5549a86058f9996b07768686a5b02cb240d' b"d05cdf95aeca507de674553f28b4eadaca82d5549a86058f9996b07768686a5b02cb240d"
b'd9f1022100f4a63f5549e817547dca97b5c658038e8593cb78c5aba3c4642cc4cd031d86' b"d9f1022100f4a63f5549e817547dca97b5c658038e8593cb78c5aba3c4642cc4cd031d86"
b'8f022100d598d870ffe4a34df8de57047a50b97b71f4d23e323f527837c9edae88c79483' b"8f022100d598d870ffe4a34df8de57047a50b97b71f4d23e323f527837c9edae88c79483"
b'02210098560c89a70385c36eb07fd7083235c4c1184e525d838aedf7128958bedfdbb102' b"02210098560c89a70385c36eb07fd7083235c4c1184e525d838aedf7128958bedfdbb102"
b'2051c0dab7057a8176ca966f3feb81123d4974a733df0f958525f547dfd1c271f9022044' b"2051c0dab7057a8176ca966f3feb81123d4974a733df0f958525f547dfd1c271f9022044"
b'6c2cafad455a671a8cf398e642e1be3b18a3d3aec2e67a9478f83c964c4f1f') b"6c2cafad455a671a8cf398e642e1be3b18a3d3aec2e67a9478f83c964c4f1f"
)
cert = binascii.unhexlify( cert = binascii.unhexlify(
b'308201d53082017f020203e8300d06092a864886f70d01010505003075310b3009060355' b"308201d53082017f020203e8300d06092a864886f70d01010505003075310b3009060355"
b'0406130258583114301206035504080c0b54686550726f76696e63653110300e06035504' b"0406130258583114301206035504080c0b54686550726f76696e63653110300e06035504"
b'070c075468654369747931133011060355040a0c0a436f6d70616e7958595a3113301106' b"070c075468654369747931133011060355040a0c0a436f6d70616e7958595a3113301106"
b'0355040b0c0a436f6d70616e7958595a3114301206035504030c0b546865486f73744e61' b"0355040b0c0a436f6d70616e7958595a3114301206035504030c0b546865486f73744e61"
b'6d65301e170d3139313231383033333935355a170d3239313231353033333935355a3075' b"6d65301e170d3139313231383033333935355a170d3239313231353033333935355a3075"
b'310b30090603550406130258583114301206035504080c0b54686550726f76696e636531' b"310b30090603550406130258583114301206035504080c0b54686550726f76696e636531"
b'10300e06035504070c075468654369747931133011060355040a0c0a436f6d70616e7958' b"10300e06035504070c075468654369747931133011060355040a0c0a436f6d70616e7958"
b'595a31133011060355040b0c0a436f6d70616e7958595a3114301206035504030c0b5468' b"595a31133011060355040b0c0a436f6d70616e7958595a3114301206035504030c0b5468"
b'65486f73744e616d65305c300d06092a864886f70d0101010500034b003048024100cc20' b"65486f73744e616d65305c300d06092a864886f70d0101010500034b003048024100cc20"
b'643fd3d9c21a0acba4f48f61aadd675f52175a9dcf07fbef610a6a6ba14abb891745cd18' b"643fd3d9c21a0acba4f48f61aadd675f52175a9dcf07fbef610a6a6ba14abb891745cd18"
b'a1d4c056580d8ff1a639460f867013c8391cdc9f2e573b0f872d0203010001300d06092a' b"a1d4c056580d8ff1a639460f867013c8391cdc9f2e573b0f872d0203010001300d06092a"
b'864886f70d0101050500034100b0513fe2829e9ecbe55b6dd14c0ede7502bde5d46153c8' b"864886f70d0101050500034100b0513fe2829e9ecbe55b6dd14c0ede7502bde5d46153c8"
b'e960ae3ebc247371b525caeb41bbcf34686015a44c50d226e66aef0a97a63874ca5944ef' b"e960ae3ebc247371b525caeb41bbcf34686015a44c50d226e66aef0a97a63874ca5944ef"
b'979b57f0b3') b"979b57f0b3"
)
CONTENT = b"""\ CONTENT = b"""\
@ -41,6 +44,7 @@ HTTP/1.0 200 OK
Hello #%d from MicroPython! Hello #%d from MicroPython!
""" """
def main(use_stream=True): def main(use_stream=True):
s = socket.socket() s = socket.socket()

View File

@ -4,6 +4,7 @@
import pyb import pyb
import pins_af import pins_af
def af(): def af():
max_name_width = 0 max_name_width = 0
max_af_width = 0 max_af_width = 0
@ -13,21 +14,22 @@ def af():
max_af_width = max(max_af_width, len(af_entry[1])) max_af_width = max(max_af_width, len(af_entry[1]))
for pin_entry in pins_af.PINS_AF: for pin_entry in pins_af.PINS_AF:
pin_name = pin_entry[0] pin_name = pin_entry[0]
print('%-*s ' % (max_name_width, pin_name), end='') print("%-*s " % (max_name_width, pin_name), end="")
for af_entry in pin_entry[1:]: for af_entry in pin_entry[1:]:
print('%2d: %-*s ' % (af_entry[0], max_af_width, af_entry[1]), end='') print("%2d: %-*s " % (af_entry[0], max_af_width, af_entry[1]), end="")
print('') print("")
def pins(): def pins():
mode_str = { pyb.Pin.IN : 'IN', mode_str = {
pyb.Pin.OUT_PP : 'OUT_PP', pyb.Pin.IN: "IN",
pyb.Pin.OUT_OD : 'OUT_OD', pyb.Pin.OUT_PP: "OUT_PP",
pyb.Pin.AF_PP : 'AF_PP', pyb.Pin.OUT_OD: "OUT_OD",
pyb.Pin.AF_OD : 'AF_OD', pyb.Pin.AF_PP: "AF_PP",
pyb.Pin.ANALOG : 'ANALOG' } pyb.Pin.AF_OD: "AF_OD",
pull_str = { pyb.Pin.PULL_NONE : '', pyb.Pin.ANALOG: "ANALOG",
pyb.Pin.PULL_UP : 'PULL_UP', }
pyb.Pin.PULL_DOWN : 'PULL_DOWN' } pull_str = {pyb.Pin.PULL_NONE: "", pyb.Pin.PULL_UP: "PULL_UP", pyb.Pin.PULL_DOWN: "PULL_DOWN"}
width = [0, 0, 0, 0] width = [0, 0, 0, 0]
rows = [] rows = []
for pin_entry in pins_af.PINS_AF: for pin_entry in pins_af.PINS_AF:
@ -42,17 +44,17 @@ def pins():
pin_af = pin.af() pin_af = pin.af()
for af_entry in pin_entry[1:]: for af_entry in pin_entry[1:]:
if pin_af == af_entry[0]: if pin_af == af_entry[0]:
af_str = '%d: %s' % (pin_af, af_entry[1]) af_str = "%d: %s" % (pin_af, af_entry[1])
break break
else: else:
af_str = '%d' % pin_af af_str = "%d" % pin_af
else: else:
af_str = '' af_str = ""
row.append(af_str) row.append(af_str)
for col in range(len(width)): for col in range(len(width)):
width[col] = max(width[col], len(row[col])) width[col] = max(width[col], len(row[col]))
rows.append(row) rows.append(row)
for row in rows: for row in rows:
for col in range(len(width)): for col in range(len(width)):
print('%-*s ' % (width[col], row[col]), end='') print("%-*s " % (width[col], row[col]), end="")
print('') print("")

View File

@ -1,17 +1,22 @@
# pyboard testing functions for CPython # pyboard testing functions for CPython
import time import time
def delay(n): def delay(n):
# time.sleep(float(n) / 1000) # time.sleep(float(n) / 1000)
pass pass
rand_seed = 1 rand_seed = 1
def rng(): def rng():
global rand_seed global rand_seed
# for these choice of numbers, see P L'Ecuyer, "Tables of linear congruential generators of different sizes and good lattice structure" # for these choice of numbers, see P L'Ecuyer, "Tables of linear congruential generators of different sizes and good lattice structure"
rand_seed = (rand_seed * 653276) % 8388593 rand_seed = (rand_seed * 653276) % 8388593
return rand_seed return rand_seed
# LCD testing object for PC # LCD testing object for PC
# uses double buffering # uses double buffering
class LCD: class LCD:
@ -30,12 +35,12 @@ class LCD:
self.buf1[y][x] = self.buf2[y][x] = value self.buf1[y][x] = self.buf2[y][x] = value
def show(self): def show(self):
print('') # blank line to separate frames print("") # blank line to separate frames
for y in range(self.height): for y in range(self.height):
for x in range(self.width): for x in range(self.width):
self.buf1[y][x] = self.buf2[y][x] self.buf1[y][x] = self.buf2[y][x]
for y in range(self.height): for y in range(self.height):
row = ''.join(['*' if self.buf1[y][x] else ' ' for x in range(self.width)]) row = "".join(["*" if self.buf1[y][x] else " " for x in range(self.width)])
print(row) print(row)
def get(self, x, y): def get(self, x, y):

View File

@ -24,6 +24,7 @@ orange_led = pyb.LED(3)
blue_led = pyb.LED(4) blue_led = pyb.LED(4)
all_leds = (red_led, green_led, orange_led, blue_led) all_leds = (red_led, green_led, orange_led, blue_led)
def run_loop(leds=all_leds): def run_loop(leds=all_leds):
""" """
Start the loop. Start the loop.
@ -31,7 +32,7 @@ def run_loop(leds=all_leds):
:param `leds`: Which LEDs to light up upon switch press. :param `leds`: Which LEDs to light up upon switch press.
:type `leds`: sequence of LED objects :type `leds`: sequence of LED objects
""" """
print('Loop started.\nPress Ctrl+C to break out of the loop.') print("Loop started.\nPress Ctrl+C to break out of the loop.")
while 1: while 1:
try: try:
if switch(): if switch():
@ -41,5 +42,6 @@ def run_loop(leds=all_leds):
except OSError: # VCPInterrupt # Ctrl+C in interpreter mode. except OSError: # VCPInterrupt # Ctrl+C in interpreter mode.
break break
if __name__ == '__main__':
if __name__ == "__main__":
run_loop() run_loop()

View File

@ -24,12 +24,14 @@ print("errno value:", errno.get())
perror("perror after error") perror("perror after error")
print() print()
def cmp(pa, pb): def cmp(pa, pb):
a = uctypes.bytearray_at(pa, 1) a = uctypes.bytearray_at(pa, 1)
b = uctypes.bytearray_at(pb, 1) b = uctypes.bytearray_at(pb, 1)
print("cmp:", a, b) print("cmp:", a, b)
return a[0] - b[0] return a[0] - b[0]
cmp_cb = ffi.callback("i", cmp, "PP") cmp_cb = ffi.callback("i", cmp, "PP")
print("callback:", cmp_cb) print("callback:", cmp_cb)

View File

@ -6,4 +6,4 @@
import umachine as machine import umachine as machine
print(hex(machine.mem16[0xc0000])) print(hex(machine.mem16[0xC0000]))

View File

@ -71,9 +71,15 @@ STATIC mp_obj_t machine_mem_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t va
uintptr_t addr = MICROPY_MACHINE_MEM_GET_READ_ADDR(index, self->elem_size); uintptr_t addr = MICROPY_MACHINE_MEM_GET_READ_ADDR(index, self->elem_size);
uint32_t val; uint32_t val;
switch (self->elem_size) { switch (self->elem_size) {
case 1: val = (*(uint8_t*)addr); break; case 1:
case 2: val = (*(uint16_t*)addr); break; val = (*(uint8_t *)addr);
default: val = (*(uint32_t*)addr); break; break;
case 2:
val = (*(uint16_t *)addr);
break;
default:
val = (*(uint32_t *)addr);
break;
} }
return mp_obj_new_int(val); return mp_obj_new_int(val);
} else { } else {
@ -81,9 +87,15 @@ STATIC mp_obj_t machine_mem_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t va
uintptr_t addr = MICROPY_MACHINE_MEM_GET_WRITE_ADDR(index, self->elem_size); uintptr_t addr = MICROPY_MACHINE_MEM_GET_WRITE_ADDR(index, self->elem_size);
uint32_t val = mp_obj_get_int_truncated(value); uint32_t val = mp_obj_get_int_truncated(value);
switch (self->elem_size) { switch (self->elem_size) {
case 1: (*(uint8_t*)addr) = val; break; case 1:
case 2: (*(uint16_t*)addr) = val; break; (*(uint8_t *)addr) = val;
default: (*(uint32_t*)addr) = val; break; break;
case 2:
(*(uint16_t *)addr) = val;
break;
default:
(*(uint32_t *)addr) = val;
break;
} }
return mp_const_none; return mp_const_none;
} }

View File

@ -90,8 +90,7 @@ STATIC mp_obj_t signal_make_new(const mp_obj_type_t *type, size_t n_args, size_t
pin = MICROPY_PY_MACHINE_PIN_MAKE_NEW(NULL, n_args, n_kw, pin_args); pin = MICROPY_PY_MACHINE_PIN_MAKE_NEW(NULL, n_args, n_kw, pin_args);
mp_local_free(pin_args); mp_local_free(pin_args);
} } else
else
#endif #endif
// Otherwise there should be 1 or 2 args // Otherwise there should be 1 or 2 args
{ {

View File

@ -143,7 +143,8 @@ STATIC mp_obj_t bluetooth_uuid_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
// Use the QSTR hash function. // Use the QSTR hash function.
return MP_OBJ_NEW_SMALL_INT(qstr_compute_hash(self->data, self->type)); return MP_OBJ_NEW_SMALL_INT(qstr_compute_hash(self->data, self->type));
} }
default: return MP_OBJ_NULL; // op not supported default:
return MP_OBJ_NULL; // op not supported
} }
} }

View File

@ -436,9 +436,15 @@ STATIC mp_obj_t framebuf_line(size_t n_args, const mp_obj_t *args) {
bool steep; bool steep;
if (dy > dx) { if (dy > dx) {
mp_int_t temp; mp_int_t temp;
temp = x1; x1 = y1; y1 = temp; temp = x1;
temp = dx; dx = dy; dy = temp; x1 = y1;
temp = sx; sx = sy; sy = temp; y1 = temp;
temp = dx;
dx = dy;
dy = temp;
temp = sx;
sx = sy;
sy = temp;
steep = true; steep = true;
} else { } else {
steep = false; steep = false;

View File

@ -600,7 +600,9 @@ STATIC mp_uint_t lwip_raw_udp_receive(lwip_socket_obj_t *socket, byte *buf, mp_u
if (socket->timeout != -1) { if (socket->timeout != -1) {
for (mp_uint_t retries = socket->timeout / 100; retries--;) { for (mp_uint_t retries = socket->timeout / 100; retries--;) {
mp_hal_delay_ms(100); mp_hal_delay_ms(100);
if (socket->incoming.pbuf != NULL) break; if (socket->incoming.pbuf != NULL) {
break;
}
} }
if (socket->incoming.pbuf == NULL) { if (socket->incoming.pbuf == NULL) {
*_errno = MP_ETIMEDOUT; *_errno = MP_ETIMEDOUT;
@ -837,7 +839,8 @@ STATIC mp_obj_t lwip_socket_make_new(const mp_obj_type_t *type, size_t n_args, s
break; break;
} }
#endif #endif
default: mp_raise_OSError(MP_EINVAL); default:
mp_raise_OSError(MP_EINVAL);
} }
if (socket->pcb.tcp == NULL) { if (socket->pcb.tcp == NULL) {
@ -1073,7 +1076,9 @@ STATIC mp_obj_t lwip_socket_connect(mp_obj_t self_in, mp_obj_t addr_in) {
if (socket->timeout != -1) { if (socket->timeout != -1) {
for (mp_uint_t retries = socket->timeout / 100; retries--;) { for (mp_uint_t retries = socket->timeout / 100; retries--;) {
mp_hal_delay_ms(100); mp_hal_delay_ms(100);
if (socket->state != STATE_CONNECTING) break; if (socket->state != STATE_CONNECTING) {
break;
}
} }
if (socket->state == STATE_CONNECTING) { if (socket->state == STATE_CONNECTING) {
mp_raise_OSError(MP_EINPROGRESS); mp_raise_OSError(MP_EINPROGRESS);
@ -1514,9 +1519,13 @@ STATIC mp_uint_t lwip_socket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_
} }
break; break;
} }
case MOD_NETWORK_SOCK_DGRAM: udp_remove(socket->pcb.udp); break; case MOD_NETWORK_SOCK_DGRAM:
udp_remove(socket->pcb.udp);
break;
#if MICROPY_PY_LWIP_SOCK_RAW #if MICROPY_PY_LWIP_SOCK_RAW
case MOD_NETWORK_SOCK_RAW: raw_remove(socket->pcb.raw); break; case MOD_NETWORK_SOCK_RAW:
raw_remove(socket->pcb.raw);
break;
#endif #endif
} }

View File

@ -186,8 +186,7 @@ mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) {
if (i == 2) { if (i == 2) {
*out++ = (in[0] & 0x03) << 4 | (in[1] & 0xF0) >> 4; *out++ = (in[0] & 0x03) << 4 | (in[1] & 0xF0) >> 4;
*out++ = (in[1] & 0x0F) << 2; *out++ = (in[1] & 0x0F) << 2;
} } else {
else {
*out++ = (in[0] & 0x03) << 4; *out++ = (in[0] & 0x03) << 4;
*out++ = 64; *out++ = 64;
} }

View File

@ -148,8 +148,12 @@ STATIC void uctypes_struct_print(const mp_print_t *print, mp_obj_t self_in, mp_p
mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]); mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]);
uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS); uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS);
switch (agg_type) { switch (agg_type) {
case PTR: typen = "PTR"; break; case PTR:
case ARRAY: typen = "ARRAY"; break; typen = "PTR";
break;
case ARRAY:
typen = "ARRAY";
break;
} }
} else { } else {
typen = "ERROR"; typen = "ERROR";
@ -324,11 +328,14 @@ static inline mp_uint_t get_aligned_basic(uint val_type, void *p) {
static inline void set_aligned_basic(uint val_type, void *p, mp_uint_t v) { static inline void set_aligned_basic(uint val_type, void *p, mp_uint_t v) {
switch (val_type) { switch (val_type) {
case UINT8: case UINT8:
*(uint8_t*)p = (uint8_t)v; return; *(uint8_t *)p = (uint8_t)v;
return;
case UINT16: case UINT16:
*(uint16_t*)p = (uint16_t)v; return; *(uint16_t *)p = (uint16_t)v;
return;
case UINT32: case UINT32:
*(uint32_t*)p = (uint32_t)v; return; *(uint32_t *)p = (uint32_t)v;
return;
} }
assert(0); assert(0);
} }
@ -378,17 +385,23 @@ STATIC void set_aligned(uint val_type, void *p, mp_int_t index, mp_obj_t val) {
mp_int_t v = mp_obj_get_int_truncated(val); mp_int_t v = mp_obj_get_int_truncated(val);
switch (val_type) { switch (val_type) {
case UINT8: case UINT8:
((uint8_t*)p)[index] = (uint8_t)v; return; ((uint8_t *)p)[index] = (uint8_t)v;
return;
case INT8: case INT8:
((int8_t*)p)[index] = (int8_t)v; return; ((int8_t *)p)[index] = (int8_t)v;
return;
case UINT16: case UINT16:
((uint16_t*)p)[index] = (uint16_t)v; return; ((uint16_t *)p)[index] = (uint16_t)v;
return;
case INT16: case INT16:
((int16_t*)p)[index] = (int16_t)v; return; ((int16_t *)p)[index] = (int16_t)v;
return;
case UINT32: case UINT32:
((uint32_t*)p)[index] = (uint32_t)v; return; ((uint32_t *)p)[index] = (uint32_t)v;
return;
case INT32: case INT32:
((int32_t*)p)[index] = (int32_t)v; return; ((int32_t *)p)[index] = (int32_t)v;
return;
case INT64: case INT64:
case UINT64: case UINT64:
if (sizeof(mp_int_t) == 8) { if (sizeof(mp_int_t) == 8) {
@ -629,7 +642,8 @@ STATIC mp_obj_t uctypes_struct_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
} }
/* fallthru */ /* fallthru */
default: return MP_OBJ_NULL; // op not supported default:
return MP_OBJ_NULL; // op not supported
} }
} }

View File

@ -147,11 +147,21 @@ STATIC mp_obj_t mod_ujson_load(mp_obj_t stream_obj) {
if (c == '\\') { if (c == '\\') {
c = S_NEXT(s); c = S_NEXT(s);
switch (c) { switch (c) {
case 'b': c = 0x08; break; case 'b':
case 'f': c = 0x0c; break; c = 0x08;
case 'n': c = 0x0a; break; break;
case 'r': c = 0x0d; break; case 'f':
case 't': c = 0x09; break; c = 0x0c;
break;
case 'n':
c = 0x0a;
break;
case 'r':
c = 0x0d;
break;
case 't':
c = 0x09;
break;
case 'u': { case 'u': {
mp_uint_t num = 0; mp_uint_t num = 0;
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
@ -177,7 +187,16 @@ STATIC mp_obj_t mod_ujson_load(mp_obj_t stream_obj) {
next = mp_obj_new_str(vstr.buf, vstr.len); next = mp_obj_new_str(vstr.buf, vstr.len);
break; break;
case '-': case '-':
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': {
bool flt = false; bool flt = false;
vstr_reset(&vstr); vstr_reset(&vstr);
for (;;) { for (;;) {

View File

@ -41,15 +41,14 @@ STATIC uint32_t yasmarang_pad = 0xeda4baba, yasmarang_n = 69, yasmarang_d = 233;
STATIC uint8_t yasmarang_dat = 0; STATIC uint8_t yasmarang_dat = 0;
#endif #endif
STATIC uint32_t yasmarang(void) STATIC uint32_t yasmarang(void) {
{
yasmarang_pad += yasmarang_dat + yasmarang_d * yasmarang_n; yasmarang_pad += yasmarang_dat + yasmarang_d * yasmarang_n;
yasmarang_pad = (yasmarang_pad << 3) + (yasmarang_pad >> 29); yasmarang_pad = (yasmarang_pad << 3) + (yasmarang_pad >> 29);
yasmarang_n = yasmarang_pad | 2; yasmarang_n = yasmarang_pad | 2;
yasmarang_d ^= (yasmarang_pad << 31) + (yasmarang_pad >> 1); yasmarang_d ^= (yasmarang_pad << 31) + (yasmarang_pad >> 1);
yasmarang_dat ^= (char) yasmarang_pad ^ (yasmarang_d >> 8) ^ 1; yasmarang_dat ^= (char) yasmarang_pad ^ (yasmarang_d >> 8) ^ 1;
return (yasmarang_pad^(yasmarang_d<<5)^(yasmarang_pad>>18)^(yasmarang_dat<<1)); return yasmarang_pad ^ (yasmarang_d << 5) ^ (yasmarang_pad >> 18) ^ (yasmarang_dat << 1);
} /* yasmarang */ } /* yasmarang */
// End of Yasmarang // End of Yasmarang

View File

@ -190,9 +190,12 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_utimeq_dump_obj, mod_utimeq_dump);
STATIC mp_obj_t utimeq_unary_op(mp_unary_op_t op, mp_obj_t self_in) { STATIC mp_obj_t utimeq_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
mp_obj_utimeq_t *self = MP_OBJ_TO_PTR(self_in); mp_obj_utimeq_t *self = MP_OBJ_TO_PTR(self_in);
switch (op) { switch (op) {
case MP_UNARY_OP_BOOL: return mp_obj_new_bool(self->len != 0); case MP_UNARY_OP_BOOL:
case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(self->len); return mp_obj_new_bool(self->len != 0);
default: return MP_OBJ_NULL; // op not supported case MP_UNARY_OP_LEN:
return MP_OBJ_NEW_SMALL_INT(self->len);
default:
return MP_OBJ_NULL; // op not supported
} }
} }

View File

@ -57,8 +57,7 @@ DRESULT disk_read (
BYTE *buff, /* Data buffer to store read data */ BYTE *buff, /* Data buffer to store read data */
DWORD sector, /* Sector address (LBA) */ DWORD sector, /* Sector address (LBA) */
UINT count /* Number of sectors to read (1..128) */ UINT count /* Number of sectors to read (1..128) */
) ) {
{
fs_user_mount_t *vfs = disk_get_device(pdrv); fs_user_mount_t *vfs = disk_get_device(pdrv);
if (vfs == NULL) { if (vfs == NULL) {
return RES_PARERR; return RES_PARERR;
@ -78,8 +77,7 @@ DRESULT disk_write (
const BYTE *buff, /* Data to be written */ const BYTE *buff, /* Data to be written */
DWORD sector, /* Sector address (LBA) */ DWORD sector, /* Sector address (LBA) */
UINT count /* Number of sectors to write (1..128) */ UINT count /* Number of sectors to write (1..128) */
) ) {
{
fs_user_mount_t *vfs = disk_get_device(pdrv); fs_user_mount_t *vfs = disk_get_device(pdrv);
if (vfs == NULL) { if (vfs == NULL) {
return RES_PARERR; return RES_PARERR;
@ -104,8 +102,7 @@ DRESULT disk_ioctl (
bdev_t pdrv, /* Physical drive nmuber (0..) */ bdev_t pdrv, /* Physical drive nmuber (0..) */
BYTE cmd, /* Control code */ BYTE cmd, /* Control code */
void *buff /* Buffer to send/receive control data */ void *buff /* Buffer to send/receive control data */
) ) {
{
fs_user_mount_t *vfs = disk_get_device(pdrv); fs_user_mount_t *vfs = disk_get_device(pdrv);
if (vfs == NULL) { if (vfs == NULL) {
return RES_PARERR; return RES_PARERR;

View File

@ -1 +1 @@
freeze('.', ('webrepl.py', 'webrepl_setup.py', 'websocket_helper.py',)) freeze(".", ("webrepl.py", "webrepl_setup.py", "websocket_helper.py",))

View File

@ -9,6 +9,7 @@ import _webrepl
listen_s = None listen_s = None
client_s = None client_s = None
def setup_conn(port, accept_handler): def setup_conn(port, accept_handler):
global listen_s global listen_s
listen_s = socket.socket() listen_s = socket.socket()
@ -44,7 +45,7 @@ def accept_conn(listen_sock):
ws = _webrepl._webrepl(ws) ws = _webrepl._webrepl(ws)
cl.setblocking(False) cl.setblocking(False)
# notify REPL on socket incoming data (ESP32/ESP8266-only) # notify REPL on socket incoming data (ESP32/ESP8266-only)
if hasattr(uos, 'dupterm_notify'): if hasattr(uos, "dupterm_notify"):
cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify) cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)
uos.dupterm(ws) uos.dupterm(ws)
@ -63,6 +64,7 @@ def start(port=8266, password=None):
if password is None: if password is None:
try: try:
import webrepl_cfg import webrepl_cfg
_webrepl.password(webrepl_cfg.PASS) _webrepl.password(webrepl_cfg.PASS)
setup_conn(port, accept_conn) setup_conn(port, accept_conn)
print("Started webrepl in normal mode") print("Started webrepl in normal mode")

View File

@ -1,4 +1,5 @@
import sys import sys
# import uos as os # import uos as os
import os import os
import machine import machine
@ -6,15 +7,18 @@ import machine
RC = "./boot.py" RC = "./boot.py"
CONFIG = "./webrepl_cfg.py" CONFIG = "./webrepl_cfg.py"
def input_choice(prompt, choices): def input_choice(prompt, choices):
while 1: while 1:
resp = input(prompt) resp = input(prompt)
if resp in choices: if resp in choices:
return resp return resp
def getpass(prompt): def getpass(prompt):
return input(prompt) return input(prompt)
def input_pass(): def input_pass():
while 1: while 1:
passwd1 = getpass("New password (4-9 chars): ") passwd1 = getpass("New password (4-9 chars): ")
@ -77,7 +81,9 @@ def main():
if resp == "E": if resp == "E":
if exists(CONFIG): if exists(CONFIG):
resp2 = input_choice("Would you like to change WebREPL password? (y/n) ", ("y", "n", "")) resp2 = input_choice(
"Would you like to change WebREPL password? (y/n) ", ("y", "n", "")
)
else: else:
print("To enable WebREPL, you must set password for it") print("To enable WebREPL, you must set password for it")
resp2 = "y" resp2 = "y"
@ -87,7 +93,6 @@ def main():
with open(CONFIG, "w") as f: with open(CONFIG, "w") as f:
f.write("PASS = %r\n" % passwd) f.write("PASS = %r\n" % passwd)
if resp not in ("D", "E") or (resp == "D" and not status) or (resp == "E" and status): if resp not in ("D", "E") or (resp == "D" and not status) or (resp == "E" and status):
print("No further action required") print("No further action required")
sys.exit() sys.exit()
@ -99,4 +104,5 @@ def main():
if resp == "y": if resp == "y":
machine.reset() machine.reset()
main() main()

View File

@ -1,4 +1,5 @@
import sys import sys
try: try:
import ubinascii as binascii import ubinascii as binascii
except: except:
@ -10,6 +11,7 @@ except:
DEBUG = 0 DEBUG = 0
def server_handshake(sock): def server_handshake(sock):
clr = sock.makefile("rwb", 0) clr = sock.makefile("rwb", 0)
l = clr.readline() l = clr.readline()
@ -27,7 +29,7 @@ def server_handshake(sock):
h, v = [x.strip() for x in l.split(b":", 1)] h, v = [x.strip() for x in l.split(b":", 1)]
if DEBUG: if DEBUG:
print((h, v)) print((h, v))
if h == b'Sec-WebSocket-Key': if h == b"Sec-WebSocket-Key":
webkey = v webkey = v
if not webkey: if not webkey:
@ -43,11 +45,13 @@ def server_handshake(sock):
if DEBUG: if DEBUG:
print("respkey:", respkey) print("respkey:", respkey)
sock.send(b"""\ sock.send(
b"""\
HTTP/1.1 101 Switching Protocols\r HTTP/1.1 101 Switching Protocols\r
Upgrade: websocket\r Upgrade: websocket\r
Connection: Upgrade\r Connection: Upgrade\r
Sec-WebSocket-Accept: """) Sec-WebSocket-Accept: """
)
sock.send(respkey) sock.send(respkey)
sock.send("\r\n\r\n") sock.send("\r\n\r\n")
@ -57,18 +61,22 @@ Sec-WebSocket-Accept: """)
# servers. # servers.
def client_handshake(sock): def client_handshake(sock):
cl = sock.makefile("rwb", 0) cl = sock.makefile("rwb", 0)
cl.write(b"""\ cl.write(
b"""\
GET / HTTP/1.1\r GET / HTTP/1.1\r
Host: echo.websocket.org\r Host: echo.websocket.org\r
Connection: Upgrade\r Connection: Upgrade\r
Upgrade: websocket\r Upgrade: websocket\r
Sec-WebSocket-Key: foo\r Sec-WebSocket-Key: foo\r
\r \r
""") """
)
l = cl.readline() l = cl.readline()
# print(l) # print(l)
while 1: while 1:
l = cl.readline() l = cl.readline()
if l == b"\r\n": if l == b"\r\n":
break break
# sys.stdout.write(l) # sys.stdout.write(l)

View File

@ -44,10 +44,14 @@ static void dump_hex_bytes(const mp_print_t *print, size_t len, const uint8_t *b
static const char *ethertype_str(uint16_t type) { static const char *ethertype_str(uint16_t type) {
// A value between 0x0000 - 0x05dc (inclusive) indicates a length, not type // A value between 0x0000 - 0x05dc (inclusive) indicates a length, not type
switch (type) { switch (type) {
case 0x0800: return "IPv4"; case 0x0800:
case 0x0806: return "ARP"; return "IPv4";
case 0x86dd: return "IPv6"; case 0x0806:
default: return NULL; return "ARP";
case 0x86dd:
return "IPv6";
default:
return NULL;
} }
} }
@ -113,14 +117,30 @@ void netutils_ethernet_trace(const mp_print_t *print, size_t len, const uint8_t
buf += n; buf += n;
mp_printf(print, " opts:"); mp_printf(print, " opts:");
switch (buf[6]) { switch (buf[6]) {
case 1: mp_printf(print, " DISCOVER"); break; case 1:
case 2: mp_printf(print, " OFFER"); break; mp_printf(print, " DISCOVER");
case 3: mp_printf(print, " REQUEST"); break; break;
case 4: mp_printf(print, " DECLINE"); break; case 2:
case 5: mp_printf(print, " ACK"); break; mp_printf(print, " OFFER");
case 6: mp_printf(print, " NACK"); break; break;
case 7: mp_printf(print, " RELEASE"); break; case 3:
case 8: mp_printf(print, " INFORM"); break; mp_printf(print, " REQUEST");
break;
case 4:
mp_printf(print, " DECLINE");
break;
case 5:
mp_printf(print, " ACK");
break;
case 6:
mp_printf(print, " NACK");
break;
case 7:
mp_printf(print, " RELEASE");
break;
case 8:
mp_printf(print, " INFORM");
break;
} }
} }
} else { } else {

View File

@ -241,7 +241,8 @@ MP_NOINLINE int main_(int argc, char **argv) {
MP_STATE_VM(mp_optimise_value) = argv[a][2] & 0xf; MP_STATE_VM(mp_optimise_value) = argv[a][2] & 0xf;
} else { } else {
MP_STATE_VM(mp_optimise_value) = 0; MP_STATE_VM(mp_optimise_value) = 0;
for (char *p = argv[a] + 1; *p && *p == 'O'; p++, MP_STATE_VM(mp_optimise_value)++); for (char *p = argv[a] + 1; *p && *p == 'O'; p++, MP_STATE_VM(mp_optimise_value)++) {;
}
} }
} else if (strcmp(argv[a], "-o") == 0) { } else if (strcmp(argv[a], "-o") == 0) {
if (a + 1 >= argc) { if (a + 1 >= argc) {

View File

@ -44,11 +44,15 @@ mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs)
MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open); MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
void nlr_jump_fail(void *val) { void nlr_jump_fail(void *val) {
while (1); while (1) {
;
}
} }
void NORETURN __fatal_error(const char *msg) { void NORETURN __fatal_error(const char *msg) {
while (1); while (1) {
;
}
} }
#ifndef NDEBUG #ifndef NDEBUG
@ -71,26 +75,63 @@ int _fstat() {return 0;}
int _isatty() {return 0;} int _isatty() {return 0;}
*/ */
void *malloc(size_t n) {return NULL;} void *malloc(size_t n) {
void *calloc(size_t nmemb, size_t size) {return NULL;} return NULL;
void *realloc(void *ptr, size_t size) {return NULL;} }
void free(void *p) {} void *calloc(size_t nmemb, size_t size) {
int printf(const char *m, ...) {return 0;} return NULL;
void *memcpy(void *dest, const void *src, size_t n) {return NULL;} }
int memcmp(const void *s1, const void *s2, size_t n) {return 0;} void *realloc(void *ptr, size_t size) {
void *memmove(void *dest, const void *src, size_t n) {return NULL;} return NULL;
void *memset(void *s, int c, size_t n) {return NULL;} }
int strcmp(const char *s1, const char* s2) {return 0;} void free(void *p) {
int strncmp(const char *s1, const char* s2, size_t n) {return 0;} }
size_t strlen(const char *s) {return 0;} int printf(const char *m, ...) {
char *strcat(char *dest, const char *src) {return NULL;} return 0;
char *strchr(const char *dest, int c) {return NULL;} }
void *memcpy(void *dest, const void *src, size_t n) {
return NULL;
}
int memcmp(const void *s1, const void *s2, size_t n) {
return 0;
}
void *memmove(void *dest, const void *src, size_t n) {
return NULL;
}
void *memset(void *s, int c, size_t n) {
return NULL;
}
int strcmp(const char *s1, const char *s2) {
return 0;
}
int strncmp(const char *s1, const char *s2, size_t n) {
return 0;
}
size_t strlen(const char *s) {
return 0;
}
char *strcat(char *dest, const char *src) {
return NULL;
}
char *strchr(const char *dest, int c) {
return NULL;
}
#include <stdarg.h> #include <stdarg.h>
int vprintf(const char *format, va_list ap) {return 0;} int vprintf(const char *format, va_list ap) {
int vsnprintf(char *str, size_t size, const char *format, va_list ap) {return 0;} return 0;
}
int vsnprintf(char *str, size_t size, const char *format, va_list ap) {
return 0;
}
#undef putchar #undef putchar
int putchar(int c) {return 0;} int putchar(int c) {
int puts(const char *s) {return 0;} return 0;
}
int puts(const char *s) {
return 0;
}
void _start(void) {main(0, NULL);} void _start(void) {
main(0, NULL);
}

View File

@ -8,20 +8,22 @@ import sys
import csv import csv
SUPPORTED_AFS = { 'UART': ('TX', 'RX', 'RTS', 'CTS'), SUPPORTED_AFS = {
'SPI': ('CLK', 'MOSI', 'MISO', 'CS0'), "UART": ("TX", "RX", "RTS", "CTS"),
"SPI": ("CLK", "MOSI", "MISO", "CS0"),
#'I2S': ('CLK', 'FS', 'DAT0', 'DAT1'), #'I2S': ('CLK', 'FS', 'DAT0', 'DAT1'),
'I2C': ('SDA', 'SCL'), "I2C": ("SDA", "SCL"),
'TIM': ('PWM'), "TIM": ("PWM"),
'SD': ('CLK', 'CMD', 'DAT0'), "SD": ("CLK", "CMD", "DAT0"),
'ADC': ('CH0', 'CH1', 'CH2', 'CH3') "ADC": ("CH0", "CH1", "CH2", "CH3"),
} }
def parse_port_pin(name_str): def parse_port_pin(name_str):
"""Parses a string and returns a (port, gpio_bit) tuple.""" """Parses a string and returns a (port, gpio_bit) tuple."""
if len(name_str) < 3: if len(name_str) < 3:
raise ValueError("Expecting pin name to be at least 3 characters") raise ValueError("Expecting pin name to be at least 3 characters")
if name_str[:2] != 'GP': if name_str[:2] != "GP":
raise ValueError("Expecting pin name to start with GP") raise ValueError("Expecting pin name to start with GP")
if not name_str[2:].isdigit(): if not name_str[2:].isdigit():
raise ValueError("Expecting numeric GPIO number") raise ValueError("Expecting numeric GPIO number")
@ -32,6 +34,7 @@ def parse_port_pin(name_str):
class AF: class AF:
"""Holds the description of an alternate function""" """Holds the description of an alternate function"""
def __init__(self, name, idx, fn, unit, type): def __init__(self, name, idx, fn, unit, type):
self.name = name self.name = name
self.idx = idx self.idx = idx
@ -42,11 +45,16 @@ class AF:
self.type = type self.type = type
def print(self): def print(self):
print (' AF({:16s}, {:4d}, {:8s}, {:4d}, {:8s}), // {}'.format(self.name, self.idx, self.fn, self.unit, self.type, self.name)) print(
" AF({:16s}, {:4d}, {:8s}, {:4d}, {:8s}), // {}".format(
self.name, self.idx, self.fn, self.unit, self.type, self.name
)
)
class Pin: class Pin:
"""Holds the information associated with a pin.""" """Holds the information associated with a pin."""
def __init__(self, name, port, gpio_bit, pin_num): def __init__(self, name, port, gpio_bit, pin_num):
self.name = name self.name = name
self.port = port self.port = port
@ -59,20 +67,32 @@ class Pin:
self.afs.append(af) self.afs.append(af)
def print(self): def print(self):
print('// {}'.format(self.name)) print("// {}".format(self.name))
if len(self.afs): if len(self.afs):
print('const pin_af_t pin_{}_af[] = {{'.format(self.name)) print("const pin_af_t pin_{}_af[] = {{".format(self.name))
for af in self.afs: for af in self.afs:
af.print() af.print()
print('};') print("};")
print('pin_obj_t pin_{:4s} = PIN({:6s}, {:1d}, {:3d}, {:2d}, pin_{}_af, {});\n'.format( print(
self.name, self.name, self.port, self.gpio_bit, self.pin_num, self.name, len(self.afs))) "pin_obj_t pin_{:4s} = PIN({:6s}, {:1d}, {:3d}, {:2d}, pin_{}_af, {});\n".format(
self.name,
self.name,
self.port,
self.gpio_bit,
self.pin_num,
self.name,
len(self.afs),
)
)
else: else:
print('pin_obj_t pin_{:4s} = PIN({:6s}, {:1d}, {:3d}, {:2d}, NULL, 0);\n'.format( print(
self.name, self.name, self.port, self.gpio_bit, self.pin_num)) "pin_obj_t pin_{:4s} = PIN({:6s}, {:1d}, {:3d}, {:2d}, NULL, 0);\n".format(
self.name, self.name, self.port, self.gpio_bit, self.pin_num
)
)
def print_header(self, hdr_file): def print_header(self, hdr_file):
hdr_file.write('extern pin_obj_t pin_{:s};\n'.format(self.name)) hdr_file.write("extern pin_obj_t pin_{:s};\n".format(self.name))
class Pins: class Pins:
@ -95,7 +115,7 @@ class Pins:
return pin return pin
def parse_af_file(self, filename, pin_col, pinname_col, af_start_col): def parse_af_file(self, filename, pin_col, pinname_col, af_start_col):
with open(filename, 'r') as csvfile: with open(filename, "r") as csvfile:
rows = csv.reader(csvfile) rows = csv.reader(csvfile)
for row in rows: for row in rows:
try: try:
@ -103,15 +123,17 @@ class Pins:
except: except:
continue continue
if not row[pin_col].isdigit(): if not row[pin_col].isdigit():
raise ValueError("Invalid pin number {:s} in row {:s}".format(row[pin_col]), row) raise ValueError(
"Invalid pin number {:s} in row {:s}".format(row[pin_col]), row
)
# Pin numbers must start from 0 when used with the TI API # Pin numbers must start from 0 when used with the TI API
pin_num = int(row[pin_col]) - 1; pin_num = int(row[pin_col]) - 1
pin = Pin(row[pinname_col], port_num, gpio_bit, pin_num) pin = Pin(row[pinname_col], port_num, gpio_bit, pin_num)
self.board_pins.append(pin) self.board_pins.append(pin)
af_idx = 0 af_idx = 0
for af in row[af_start_col:]: for af in row[af_start_col:]:
af_splitted = af.split('_') af_splitted = af.split("_")
fn_name = af_splitted[0].rstrip('0123456789') fn_name = af_splitted[0].rstrip("0123456789")
if fn_name in SUPPORTED_AFS: if fn_name in SUPPORTED_AFS:
type_name = af_splitted[1] type_name = af_splitted[1]
if type_name in SUPPORTED_AFS[fn_name]: if type_name in SUPPORTED_AFS[fn_name]:
@ -120,7 +142,7 @@ class Pins:
af_idx += 1 af_idx += 1
def parse_board_file(self, filename, cpu_pin_col): def parse_board_file(self, filename, cpu_pin_col):
with open(filename, 'r') as csvfile: with open(filename, "r") as csvfile:
rows = csv.reader(csvfile) rows = csv.reader(csvfile)
for row in rows: for row in rows:
# Pin numbers must start from 0 when used with the TI API # Pin numbers must start from 0 when used with the TI API
@ -132,29 +154,39 @@ class Pins:
pin.board_pin = True pin.board_pin = True
def print_named(self, label, pins): def print_named(self, label, pins):
print('') print("")
print('STATIC const mp_rom_map_elem_t pin_{:s}_pins_locals_dict_table[] = {{'.format(label)) print(
"STATIC const mp_rom_map_elem_t pin_{:s}_pins_locals_dict_table[] = {{".format(label)
)
for pin in pins: for pin in pins:
if pin.board_pin: if pin.board_pin:
print(' {{ MP_ROM_QSTR(MP_QSTR_{:6s}), MP_ROM_PTR(&pin_{:6s}) }},'.format(pin.name, pin.name)) print(
print('};') " {{ MP_ROM_QSTR(MP_QSTR_{:6s}), MP_ROM_PTR(&pin_{:6s}) }},".format(
print('MP_DEFINE_CONST_DICT(pin_{:s}_pins_locals_dict, pin_{:s}_pins_locals_dict_table);'.format(label, label)); pin.name, pin.name
)
)
print("};")
print(
"MP_DEFINE_CONST_DICT(pin_{:s}_pins_locals_dict, pin_{:s}_pins_locals_dict_table);".format(
label, label
)
)
def print(self): def print(self):
for pin in self.board_pins: for pin in self.board_pins:
if pin.board_pin: if pin.board_pin:
pin.print() pin.print()
self.print_named('board', self.board_pins) self.print_named("board", self.board_pins)
print('') print("")
def print_header(self, hdr_filename): def print_header(self, hdr_filename):
with open(hdr_filename, 'wt') as hdr_file: with open(hdr_filename, "wt") as hdr_file:
for pin in self.board_pins: for pin in self.board_pins:
if pin.board_pin: if pin.board_pin:
pin.print_header(hdr_file) pin.print_header(hdr_file)
def print_qstr(self, qstr_filename): def print_qstr(self, qstr_filename):
with open(qstr_filename, 'wt') as qstr_file: with open(qstr_filename, "wt") as qstr_file:
pin_qstr_set = set([]) pin_qstr_set = set([])
af_qstr_set = set([]) af_qstr_set = set([])
for pin in self.board_pins: for pin in self.board_pins:
@ -162,67 +194,69 @@ class Pins:
pin_qstr_set |= set([pin.name]) pin_qstr_set |= set([pin.name])
for af in pin.afs: for af in pin.afs:
af_qstr_set |= set([af.name]) af_qstr_set |= set([af.name])
print('// Board pins', file=qstr_file) print("// Board pins", file=qstr_file)
for qstr in sorted(pin_qstr_set): for qstr in sorted(pin_qstr_set):
print('Q({})'.format(qstr), file=qstr_file) print("Q({})".format(qstr), file=qstr_file)
print('\n// Pin AFs', file=qstr_file) print("\n// Pin AFs", file=qstr_file)
for qstr in sorted(af_qstr_set): for qstr in sorted(af_qstr_set):
print('Q({})'.format(qstr), file=qstr_file) print("Q({})".format(qstr), file=qstr_file)
def main(): def main():
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
prog="make-pins.py", prog="make-pins.py",
usage="%(prog)s [options] [command]", usage="%(prog)s [options] [command]",
description="Generate board specific pin file" description="Generate board specific pin file",
) )
parser.add_argument( parser.add_argument(
"-a", "--af", "-a",
"--af",
dest="af_filename", dest="af_filename",
help="Specifies the alternate function file for the chip", help="Specifies the alternate function file for the chip",
default="cc3200_af.csv" default="cc3200_af.csv",
) )
parser.add_argument( parser.add_argument(
"-b", "--board", "-b", "--board", dest="board_filename", help="Specifies the board file",
dest="board_filename",
help="Specifies the board file",
) )
parser.add_argument( parser.add_argument(
"-p", "--prefix", "-p",
"--prefix",
dest="prefix_filename", dest="prefix_filename",
help="Specifies beginning portion of generated pins file", help="Specifies beginning portion of generated pins file",
default="cc3200_prefix.c" default="cc3200_prefix.c",
) )
parser.add_argument( parser.add_argument(
"-q", "--qstr", "-q",
"--qstr",
dest="qstr_filename", dest="qstr_filename",
help="Specifies name of generated qstr header file", help="Specifies name of generated qstr header file",
default="build/pins_qstr.h" default="build/pins_qstr.h",
) )
parser.add_argument( parser.add_argument(
"-r", "--hdr", "-r",
"--hdr",
dest="hdr_filename", dest="hdr_filename",
help="Specifies name of generated pin header file", help="Specifies name of generated pin header file",
default="build/pins.h" default="build/pins.h",
) )
args = parser.parse_args(sys.argv[1:]) args = parser.parse_args(sys.argv[1:])
pins = Pins() pins = Pins()
print('// This file was automatically generated by make-pins.py') print("// This file was automatically generated by make-pins.py")
print('//') print("//")
if args.af_filename: if args.af_filename:
print('// --af {:s}'.format(args.af_filename)) print("// --af {:s}".format(args.af_filename))
pins.parse_af_file(args.af_filename, 0, 1, 3) pins.parse_af_file(args.af_filename, 0, 1, 3)
if args.board_filename: if args.board_filename:
print('// --board {:s}'.format(args.board_filename)) print("// --board {:s}".format(args.board_filename))
pins.parse_board_file(args.board_filename, 1) pins.parse_board_file(args.board_filename, 1)
if args.prefix_filename: if args.prefix_filename:
print('// --prefix {:s}'.format(args.prefix_filename)) print("// --prefix {:s}".format(args.prefix_filename))
print('') print("")
with open(args.prefix_filename, 'r') as prefix_file: with open(args.prefix_filename, "r") as prefix_file:
print(prefix_file.read()) print(prefix_file.read())
pins.print() pins.print()
pins.print_qstr(args.qstr_filename) pins.print_qstr(args.qstr_filename)

View File

@ -95,7 +95,8 @@ int main (void) {
osi_start(); osi_start();
for ( ; ; ); for ( ; ;) {;
}
} }
// We need this when configSUPPORT_STATIC_ALLOCATION is enabled // We need this when configSUPPORT_STATIC_ALLOCATION is enabled

View File

@ -158,8 +158,7 @@ soft_reset:
// when waking up from hibernate we just want // when waking up from hibernate we just want
// to enable simplelink and leave it as is // to enable simplelink and leave it as is
wlan_first_start(); wlan_first_start();
} } else {
else {
// only if not comming out of hibernate or a soft reset // only if not comming out of hibernate or a soft reset
mptask_enter_ap_mode(); mptask_enter_ap_mode();
} }

View File

@ -97,16 +97,14 @@ void TASK_Servers (void *pvParameters) {
// now set/clear the flags // now set/clear the flags
servers_data.enabled = true; servers_data.enabled = true;
servers_data.do_enable = false; servers_data.do_enable = false;
} } else if (servers_data.do_disable) {
else if (servers_data.do_disable) {
// disable network services // disable network services
telnet_disable(); telnet_disable();
ftp_disable(); ftp_disable();
// now clear the flags // now clear the flags
servers_data.do_disable = false; servers_data.do_disable = false;
servers_data.enabled = false; servers_data.enabled = false;
} } else if (servers_data.do_reset) {
else if (servers_data.do_reset) {
// resetting the servers is needed to prevent half-open sockets // resetting the servers is needed to prevent half-open sockets
servers_data.do_reset = false; servers_data.do_reset = false;
if (servers_data.enabled) { if (servers_data.enabled) {
@ -120,8 +118,7 @@ void TASK_Servers (void *pvParameters) {
if (cycle) { if (cycle) {
telnet_run(); telnet_run();
} } else {
else {
ftp_run(); ftp_run();
} }

View File

@ -12,13 +12,15 @@ python3 run-tests --target wipy --device 192.168.1.1 ../cc3200/tools/smoke.py
pin_map = [23, 24, 11, 12, 13, 14, 15, 16, 17, 22, 28, 10, 9, 8, 7, 6, 30, 31, 3, 0, 4, 5] pin_map = [23, 24, 11, 12, 13, 14, 15, 16, 17, 22, 28, 10, 9, 8, 7, 6, 30, 31, 3, 0, 4, 5]
test_bytes = os.urandom(1024) test_bytes = os.urandom(1024)
def test_pin_read(pull): def test_pin_read(pull):
# enable the pull resistor on all pins, then read the value # enable the pull resistor on all pins, then read the value
for p in pin_map: for p in pin_map:
pin = Pin('GP' + str(p), mode=Pin.IN, pull=pull) pin = Pin("GP" + str(p), mode=Pin.IN, pull=pull)
# read the pin value # read the pin value
print(pin()) print(pin())
def test_pin_shorts(pull): def test_pin_shorts(pull):
if pull == Pin.PULL_UP: if pull == Pin.PULL_UP:
pull_inverted = Pin.PULL_DOWN pull_inverted = Pin.PULL_DOWN
@ -26,41 +28,42 @@ def test_pin_shorts (pull):
pull_inverted = Pin.PULL_UP pull_inverted = Pin.PULL_UP
# enable all pulls of the specified type # enable all pulls of the specified type
for p in pin_map: for p in pin_map:
pin = Pin('GP' + str(p), mode=Pin.IN, pull=pull_inverted) pin = Pin("GP" + str(p), mode=Pin.IN, pull=pull_inverted)
# then change the pull one pin at a time and read its value # then change the pull one pin at a time and read its value
i = 0 i = 0
while i < len(pin_map): while i < len(pin_map):
pin = Pin('GP' + str(pin_map[i]), mode=Pin.IN, pull=pull) pin = Pin("GP" + str(pin_map[i]), mode=Pin.IN, pull=pull)
Pin('GP' + str(pin_map[i - 1]), mode=Pin.IN, pull=pull_inverted) Pin("GP" + str(pin_map[i - 1]), mode=Pin.IN, pull=pull_inverted)
i += 1 i += 1
# read the pin value # read the pin value
print(pin()) print(pin())
test_pin_read(Pin.PULL_UP) test_pin_read(Pin.PULL_UP)
test_pin_read(Pin.PULL_DOWN) test_pin_read(Pin.PULL_DOWN)
test_pin_shorts(Pin.PULL_UP) test_pin_shorts(Pin.PULL_UP)
test_pin_shorts(Pin.PULL_DOWN) test_pin_shorts(Pin.PULL_DOWN)
# create a test directory # create a test directory
os.mkdir('/flash/test') os.mkdir("/flash/test")
os.chdir('/flash/test') os.chdir("/flash/test")
print(os.getcwd()) print(os.getcwd())
# create a new file # create a new file
f = open('test.txt', 'w') f = open("test.txt", "w")
n_w = f.write(test_bytes) n_w = f.write(test_bytes)
print(n_w == len(test_bytes)) print(n_w == len(test_bytes))
f.close() f.close()
f = open('test.txt', 'r') f = open("test.txt", "r")
r = bytes(f.read(), 'ascii') r = bytes(f.read(), "ascii")
# check that we can write and read it correctly # check that we can write and read it correctly
print(r == test_bytes) print(r == test_bytes)
f.close() f.close()
os.remove('test.txt') os.remove("test.txt")
os.chdir('..') os.chdir("..")
os.rmdir('test') os.rmdir("test")
ls = os.listdir() ls = os.listdir()
print('test' not in ls) print("test" not in ls)
print(ls) print(ls)
# test the real time clock # test the real time clock
@ -73,4 +76,3 @@ time.sleep_ms(1000)
time2 = rtc.now() time2 = rtc.now()
print(time2[5] - time1[5] == 1) print(time2[5] - time1[5] == 1)
print(time2[6] - time1[6] < 5000) # microseconds print(time2[6] - time1[6] < 5000) # microseconds

View File

@ -19,7 +19,7 @@ import subprocess
def print_exception(e): def print_exception(e):
print ('Exception: {}, on line {}'.format(e, sys.exc_info()[-1].tb_lineno)) print("Exception: {}, on line {}".format(e, sys.exc_info()[-1].tb_lineno))
def execute(command): def execute(command):
@ -29,7 +29,7 @@ def execute(command):
# Poll process for new output until finished # Poll process for new output until finished
while True: while True:
nextline = process.stdout.readline() nextline = process.stdout.readline()
if nextline == '' and process.poll() != None: if nextline == "" and process.poll() != None:
break break
sys.stdout.write(nextline) sys.stdout.write(nextline)
sys.stdout.flush() sys.stdout.flush()
@ -43,25 +43,58 @@ def execute(command):
else: else:
raise ProcessException(command, exitCode, output) raise ProcessException(command, exitCode, output)
def main(): def main():
cmd_parser = argparse.ArgumentParser(description='Flash the WiPy and optionally run a small test on it.') cmd_parser = argparse.ArgumentParser(
cmd_parser.add_argument('-u', '--uniflash', default=None, help='the path to the uniflash cli executable') description="Flash the WiPy and optionally run a small test on it."
cmd_parser.add_argument('-c', '--config', default=None, help='the path to the uniflash config file') )
cmd_parser.add_argument('-p', '--port', default=8, help='the com serial port') cmd_parser.add_argument(
cmd_parser.add_argument('-s', '--servicepack', default=None, help='the path to the servicepack file') "-u", "--uniflash", default=None, help="the path to the uniflash cli executable"
)
cmd_parser.add_argument(
"-c", "--config", default=None, help="the path to the uniflash config file"
)
cmd_parser.add_argument("-p", "--port", default=8, help="the com serial port")
cmd_parser.add_argument(
"-s", "--servicepack", default=None, help="the path to the servicepack file"
)
args = cmd_parser.parse_args() args = cmd_parser.parse_args()
output = "" output = ""
com_port = 'com=' + str(args.port) com_port = "com=" + str(args.port)
servicepack_path = 'spPath=' + args.servicepack servicepack_path = "spPath=" + args.servicepack
try: try:
if args.uniflash == None or args.config == None: if args.uniflash == None or args.config == None:
raise ValueError('uniflash path and config path are mandatory') raise ValueError("uniflash path and config path are mandatory")
if args.servicepack == None: if args.servicepack == None:
output += execute([args.uniflash, '-config', args.config, '-setOptions', com_port, '-operations', 'format', 'program']) output += execute(
[
args.uniflash,
"-config",
args.config,
"-setOptions",
com_port,
"-operations",
"format",
"program",
]
)
else: else:
output += execute([args.uniflash, '-config', args.config, '-setOptions', com_port, servicepack_path, '-operations', 'format', 'servicePackUpdate', 'program']) output += execute(
[
args.uniflash,
"-config",
args.config,
"-setOptions",
com_port,
servicepack_path,
"-operations",
"format",
"servicePackUpdate",
"program",
]
)
except Exception as e: except Exception as e:
print_exception(e) print_exception(e)
output = "" output = ""
@ -77,5 +110,6 @@ def main():
print("======================================") print("======================================")
sys.exit(1) sys.exit(1)
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -23,12 +23,12 @@ from telnetlib import Telnet
def print_exception(e): def print_exception(e):
print ('Exception: {}, on line {}'.format(e, sys.exc_info()[-1].tb_lineno)) print("Exception: {}, on line {}".format(e, sys.exc_info()[-1].tb_lineno))
def ftp_directory_exists(ftpobj, directory_name): def ftp_directory_exists(ftpobj, directory_name):
filelist = [] filelist = []
ftpobj.retrlines('LIST',filelist.append) ftpobj.retrlines("LIST", filelist.append)
for f in filelist: for f in filelist:
if f.split()[-1] == directory_name: if f.split()[-1] == directory_name:
return True return True
@ -37,34 +37,34 @@ def ftp_directory_exists(ftpobj, directory_name):
def transfer_file(args): def transfer_file(args):
with FTP(args.ip, timeout=20) as ftp: with FTP(args.ip, timeout=20) as ftp:
print ('FTP connection established') print("FTP connection established")
if '230' in ftp.login(args.user, args.password): if "230" in ftp.login(args.user, args.password):
print ('Login successful') print("Login successful")
if '250' in ftp.cwd('/flash'): if "250" in ftp.cwd("/flash"):
if not ftp_directory_exists(ftp, 'sys'): if not ftp_directory_exists(ftp, "sys"):
print ('/flash/sys directory does not exist') print("/flash/sys directory does not exist")
if not '550' in ftp.mkd('sys'): if not "550" in ftp.mkd("sys"):
print ('/flash/sys directory created') print("/flash/sys directory created")
else: else:
print ('Error: cannot create /flash/sys directory') print("Error: cannot create /flash/sys directory")
return False return False
if '250' in ftp.cwd('sys'): if "250" in ftp.cwd("sys"):
print("Entered '/flash/sys' directory") print("Entered '/flash/sys' directory")
with open(args.file, "rb") as fwfile: with open(args.file, "rb") as fwfile:
print ('Firmware image found, initiating transfer...') print("Firmware image found, initiating transfer...")
if '226' in ftp.storbinary("STOR " + 'mcuimg.bin', fwfile, 512): if "226" in ftp.storbinary("STOR " + "mcuimg.bin", fwfile, 512):
print ('File transfer complete') print("File transfer complete")
return True return True
else: else:
print ('Error: file transfer failed') print("Error: file transfer failed")
else: else:
print ('Error: cannot enter /flash/sys directory') print("Error: cannot enter /flash/sys directory")
else: else:
print ('Error: cannot enter /flash directory') print("Error: cannot enter /flash directory")
else: else:
print ('Error: ftp login failed') print("Error: ftp login failed")
return False return False
@ -76,20 +76,24 @@ def reset_board(args):
tn = Telnet(args.ip, timeout=5) tn = Telnet(args.ip, timeout=5)
print("Connected via Telnet, trying to login now") print("Connected via Telnet, trying to login now")
if b'Login as:' in tn.read_until(b"Login as:", timeout=5): if b"Login as:" in tn.read_until(b"Login as:", timeout=5):
tn.write(bytes(args.user, 'ascii') + b"\r\n") tn.write(bytes(args.user, "ascii") + b"\r\n")
if b'Password:' in tn.read_until(b"Password:", timeout=5): if b"Password:" in tn.read_until(b"Password:", timeout=5):
# needed because of internal implementation details of the WiPy's telnet server # needed because of internal implementation details of the WiPy's telnet server
time.sleep(0.2) time.sleep(0.2)
tn.write(bytes(args.password, 'ascii') + b"\r\n") tn.write(bytes(args.password, "ascii") + b"\r\n")
if b'Type "help()" for more information.' in tn.read_until(b'Type "help()" for more information.', timeout=5): if b'Type "help()" for more information.' in tn.read_until(
b'Type "help()" for more information.', timeout=5
):
print("Telnet login succeeded") print("Telnet login succeeded")
tn.write(b'\r\x03\x03') # ctrl-C twice: interrupt any running program tn.write(b"\r\x03\x03") # ctrl-C twice: interrupt any running program
time.sleep(1) time.sleep(1)
tn.write(b'\r\x02') # ctrl-B: enter friendly REPL tn.write(b"\r\x02") # ctrl-B: enter friendly REPL
if b'Type "help()" for more information.' in tn.read_until(b'Type "help()" for more information.', timeout=5): if b'Type "help()" for more information.' in tn.read_until(
b'Type "help()" for more information.', timeout=5
):
tn.write(b"import machine\r\n") tn.write(b"import machine\r\n")
tn.write(b"machine.reset()\r\n") tn.write(b"machine.reset()\r\n")
time.sleep(2) time.sleep(2)
@ -112,7 +116,7 @@ def reset_board(args):
def verify_update(args): def verify_update(args):
success = False success = False
firmware_tag = '' firmware_tag = ""
def find_tag(tag): def find_tag(tag):
if tag in firmware_tag: if tag in firmware_tag:
@ -135,21 +139,26 @@ def verify_update(args):
print("Timeout while connecting via telnet, retrying...") print("Timeout while connecting via telnet, retrying...")
retries += 1 retries += 1
else: else:
print('Error: Telnet connection timed out!') print("Error: Telnet connection timed out!")
return False return False
try: try:
firmware_tag = tn.read_until (b'with CC3200') firmware_tag = tn.read_until(b"with CC3200")
tag_file_path = args.file.rstrip('mcuimg.bin') + 'genhdr/mpversion.h' tag_file_path = args.file.rstrip("mcuimg.bin") + "genhdr/mpversion.h"
if args.tag is not None: if args.tag is not None:
success = find_tag(bytes(args.tag, 'ascii')) success = find_tag(bytes(args.tag, "ascii"))
else: else:
with open(tag_file_path) as tag_file: with open(tag_file_path) as tag_file:
for line in tag_file: for line in tag_file:
bline = bytes(line, 'ascii') bline = bytes(line, "ascii")
if b'MICROPY_GIT_HASH' in bline: if b"MICROPY_GIT_HASH" in bline:
bline = bline.lstrip(b'#define MICROPY_GIT_HASH ').replace(b'"', b'').replace(b'\r', b'').replace(b'\n', b'') bline = (
bline.lstrip(b"#define MICROPY_GIT_HASH ")
.replace(b'"', b"")
.replace(b"\r", b"")
.replace(b"\n", b"")
)
success = find_tag(bline) success = find_tag(bline)
break break
@ -164,24 +173,28 @@ def verify_update(args):
def main(): def main():
cmd_parser = argparse.ArgumentParser(description='Update the WiPy firmware with the specified image file') cmd_parser = argparse.ArgumentParser(
cmd_parser.add_argument('-f', '--file', default=None, help='the path of the firmware file') description="Update the WiPy firmware with the specified image file"
cmd_parser.add_argument('-u', '--user', default='micro', help='the username') )
cmd_parser.add_argument('-p', '--password', default='python', help='the login password') cmd_parser.add_argument("-f", "--file", default=None, help="the path of the firmware file")
cmd_parser.add_argument('--ip', default='192.168.1.1', help='the ip address of the WiPy') cmd_parser.add_argument("-u", "--user", default="micro", help="the username")
cmd_parser.add_argument('--verify', action='store_true', help='verify that the update succeeded') cmd_parser.add_argument("-p", "--password", default="python", help="the login password")
cmd_parser.add_argument('-t', '--tag', default=None, help='git tag of the firmware image') cmd_parser.add_argument("--ip", default="192.168.1.1", help="the ip address of the WiPy")
cmd_parser.add_argument(
"--verify", action="store_true", help="verify that the update succeeded"
)
cmd_parser.add_argument("-t", "--tag", default=None, help="git tag of the firmware image")
args = cmd_parser.parse_args() args = cmd_parser.parse_args()
result = 1 result = 1
try: try:
if args.file is None: if args.file is None:
raise ValueError('the image file path must be specified') raise ValueError("the image file path must be specified")
if transfer_file(args): if transfer_file(args):
if reset_board(args): if reset_board(args):
if args.verify: if args.verify:
print ('Waiting for the WiFi connection to come up again...') print("Waiting for the WiFi connection to come up again...")
# this time is to allow the system's wireless network card to # this time is to allow the system's wireless network card to
# connect to the WiPy again. # connect to the WiPy again.
time.sleep(5) time.sleep(5)

View File

@ -1,2 +1,2 @@
include('$(PORT_DIR)/boards/manifest.py') include("$(PORT_DIR)/boards/manifest.py")
freeze("modules") freeze("modules")

View File

@ -63,8 +63,7 @@ class DotStar:
dotstar[0] = (128, 0, 0) # Red dotstar[0] = (128, 0, 0) # Red
""" """
def __init__(self, spi, n, *, brightness=1.0, auto_write=True, def __init__(self, spi, n, *, brightness=1.0, auto_write=True, pixel_order=BGR):
pixel_order=BGR):
self._spi = spi self._spi = spi
self._n = n self._n = n
# Supply one extra clock cycle for each two pixels in the strip. # Supply one extra clock cycle for each two pixels in the strip.
@ -79,10 +78,10 @@ class DotStar:
self._buf[i] = 0x00 self._buf[i] = 0x00
# Mark the beginnings of each pixel. # Mark the beginnings of each pixel.
for i in range(START_HEADER_SIZE, self.end_header_index, 4): for i in range(START_HEADER_SIZE, self.end_header_index, 4):
self._buf[i] = 0xff self._buf[i] = 0xFF
# 0xff bytes at the end. # 0xff bytes at the end.
for i in range(self.end_header_index, len(self._buf)): for i in range(self.end_header_index, len(self._buf)):
self._buf[i] = 0xff self._buf[i] = 0xFF
self._brightness = 1.0 self._brightness = 1.0
# Set auto_write to False temporarily so brightness setter does _not_ # Set auto_write to False temporarily so brightness setter does _not_
# call show() while in __init__. # call show() while in __init__.
@ -129,7 +128,7 @@ class DotStar:
offset = index * 4 + START_HEADER_SIZE offset = index * 4 + START_HEADER_SIZE
rgb = value rgb = value
if isinstance(value, int): if isinstance(value, int):
rgb = (value >> 16, (value >> 8) & 0xff, value & 0xff) rgb = (value >> 16, (value >> 8) & 0xFF, value & 0xFF)
if len(rgb) == 4: if len(rgb) == 4:
brightness = value[3] brightness = value[3]
@ -171,15 +170,15 @@ class DotStar:
out = [] out = []
for in_i in range(*index.indices(self._n)): for in_i in range(*index.indices(self._n)):
out.append( out.append(
tuple(self._buf[in_i * 4 + (3 - i) + START_HEADER_SIZE] for i in range(3))) tuple(self._buf[in_i * 4 + (3 - i) + START_HEADER_SIZE] for i in range(3))
)
return out return out
if index < 0: if index < 0:
index += len(self) index += len(self)
if index >= self._n or index < 0: if index >= self._n or index < 0:
raise IndexError raise IndexError
offset = index * 4 offset = index * 4
return tuple(self._buf[offset + (3 - i) + START_HEADER_SIZE] return tuple(self._buf[offset + (3 - i) + START_HEADER_SIZE] for i in range(3))
for i in range(3))
def __len__(self): def __len__(self):
return self._n return self._n
@ -222,7 +221,7 @@ class DotStar:
buf[i] = self._buf[i] if i % 4 == 0 else int(self._buf[i] * self._brightness) buf[i] = self._buf[i] if i % 4 == 0 else int(self._buf[i] * self._brightness)
# Four 0xff bytes at the end. # Four 0xff bytes at the end.
for i in range(self.end_header_index, len(buf)): for i in range(self.end_header_index, len(buf)):
buf[i] = 0xff buf[i] = 0xFF
if self._spi: if self._spi:
self._spi.write(buf) self._spi.write(buf)

View File

@ -53,6 +53,7 @@ def get_battery_voltage():
measuredvbat *= 3.7 # Multiply by 3.7V, our reference voltage measuredvbat *= 3.7 # Multiply by 3.7V, our reference voltage
return measuredvbat return measuredvbat
# Return the current charge state of the battery - we need to read the value multiple times # Return the current charge state of the battery - we need to read the value multiple times
# to eliminate false negatives due to the charge IC not knowing the difference between no battery # to eliminate false negatives due to the charge IC not knowing the difference between no battery
# and a full battery not charging - This is why the charge LED flashes # and a full battery not charging - This is why the charge LED flashes
@ -64,7 +65,9 @@ def get_battery_charging():
measuredVal = 0 # start our reading at 0 measuredVal = 0 # start our reading at 0
io = Pin(BAT_CHARGE, Pin.IN) # Assign the pin to read io = Pin(BAT_CHARGE, Pin.IN) # Assign the pin to read
for y in range(0, 10): # loop through 10 times adding the read values together to ensure no false positives for y in range(
0, 10
): # loop through 10 times adding the read values together to ensure no false positives
measuredVal += io.value() measuredVal += io.value()
return measuredVal == 0 # return True if the value is 0 return measuredVal == 0 # return True if the value is 0
@ -85,11 +88,16 @@ def set_dotstar_power(state):
else: else:
Pin(13, Pin.IN, Pin.PULL_HOLD) # Set PULL_HOLD on the pin to allow the 3V3 pull-up to work Pin(13, Pin.IN, Pin.PULL_HOLD) # Set PULL_HOLD on the pin to allow the 3V3 pull-up to work
Pin(DOTSTAR_CLK, Pin.OUT if state else Pin.IN) # If power is on, set CLK to be output, otherwise input Pin(
Pin(DOTSTAR_DATA, Pin.OUT if state else Pin.IN) # If power is on, set DATA to be output, otherwise input DOTSTAR_CLK, Pin.OUT if state else Pin.IN
) # If power is on, set CLK to be output, otherwise input
Pin(
DOTSTAR_DATA, Pin.OUT if state else Pin.IN
) # If power is on, set DATA to be output, otherwise input
# A small delay to let the IO change state # A small delay to let the IO change state
time.sleep(.035) time.sleep(0.035)
# Dotstar rainbow colour wheel # Dotstar rainbow colour wheel
def dotstar_color_wheel(wheel_pos): def dotstar_color_wheel(wheel_pos):
@ -105,6 +113,7 @@ def dotstar_color_wheel(wheel_pos):
wheel_pos -= 170 wheel_pos -= 170
return wheel_pos * 3, 255 - wheel_pos * 3, 0 return wheel_pos * 3, 255 - wheel_pos * 3, 0
# Go into deep sleep but shut down the APA first to save power # Go into deep sleep but shut down the APA first to save power
# Use this if you want lowest deep sleep current # Use this if you want lowest deep sleep current
def go_deepsleep(t): def go_deepsleep(t):

View File

@ -1,6 +1,6 @@
freeze('$(PORT_DIR)/modules') freeze("$(PORT_DIR)/modules")
freeze('$(MPY_DIR)/tools', ('upip.py', 'upip_utarfile.py')) freeze("$(MPY_DIR)/tools", ("upip.py", "upip_utarfile.py"))
freeze('$(MPY_DIR)/ports/esp8266/modules', 'ntptime.py') freeze("$(MPY_DIR)/ports/esp8266/modules", "ntptime.py")
freeze('$(MPY_DIR)/drivers/dht', 'dht.py') freeze("$(MPY_DIR)/drivers/dht", "dht.py")
freeze('$(MPY_DIR)/drivers/onewire') freeze("$(MPY_DIR)/drivers/onewire")
include('$(MPY_DIR)/extmod/webrepl/manifest.py') include("$(MPY_DIR)/extmod/webrepl/manifest.py")

View File

@ -1,6 +1,6 @@
include('manifest.py') include("manifest.py")
freeze('$(MPY_LIB_DIR)/upysh', 'upysh.py') freeze("$(MPY_LIB_DIR)/upysh", "upysh.py")
freeze('$(MPY_LIB_DIR)/urequests', 'urequests.py') freeze("$(MPY_LIB_DIR)/urequests", "urequests.py")
freeze('$(MPY_LIB_DIR)/umqtt.simple', 'umqtt/simple.py') freeze("$(MPY_LIB_DIR)/umqtt.simple", "umqtt/simple.py")
freeze('$(MPY_LIB_DIR)/umqtt.robust', 'umqtt/robust.py') freeze("$(MPY_LIB_DIR)/umqtt.robust", "umqtt/robust.py")

View File

@ -180,17 +180,23 @@ STATIC mp_obj_t esp32_partition_ioctl(mp_obj_t self_in, mp_obj_t cmd_in, mp_obj_
esp32_partition_obj_t *self = MP_OBJ_TO_PTR(self_in); esp32_partition_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_int_t cmd = mp_obj_get_int(cmd_in); mp_int_t cmd = mp_obj_get_int(cmd_in);
switch (cmd) { switch (cmd) {
case MP_BLOCKDEV_IOCTL_INIT: return MP_OBJ_NEW_SMALL_INT(0); case MP_BLOCKDEV_IOCTL_INIT:
case MP_BLOCKDEV_IOCTL_DEINIT: return MP_OBJ_NEW_SMALL_INT(0); return MP_OBJ_NEW_SMALL_INT(0);
case MP_BLOCKDEV_IOCTL_SYNC: return MP_OBJ_NEW_SMALL_INT(0); case MP_BLOCKDEV_IOCTL_DEINIT:
case MP_BLOCKDEV_IOCTL_BLOCK_COUNT: return MP_OBJ_NEW_SMALL_INT(self->part->size / BLOCK_SIZE_BYTES); return MP_OBJ_NEW_SMALL_INT(0);
case MP_BLOCKDEV_IOCTL_BLOCK_SIZE: return MP_OBJ_NEW_SMALL_INT(BLOCK_SIZE_BYTES); case MP_BLOCKDEV_IOCTL_SYNC:
return MP_OBJ_NEW_SMALL_INT(0);
case MP_BLOCKDEV_IOCTL_BLOCK_COUNT:
return MP_OBJ_NEW_SMALL_INT(self->part->size / BLOCK_SIZE_BYTES);
case MP_BLOCKDEV_IOCTL_BLOCK_SIZE:
return MP_OBJ_NEW_SMALL_INT(BLOCK_SIZE_BYTES);
case MP_BLOCKDEV_IOCTL_BLOCK_ERASE: { case MP_BLOCKDEV_IOCTL_BLOCK_ERASE: {
uint32_t offset = mp_obj_get_int(arg_in) * BLOCK_SIZE_BYTES; uint32_t offset = mp_obj_get_int(arg_in) * BLOCK_SIZE_BYTES;
check_esp_err(esp_partition_erase_range(self->part, offset, BLOCK_SIZE_BYTES)); check_esp_err(esp_partition_erase_range(self->part, offset, BLOCK_SIZE_BYTES));
return MP_OBJ_NEW_SMALL_INT(0); return MP_OBJ_NEW_SMALL_INT(0);
} }
default: return mp_const_none; default:
return mp_const_none;
} }
} }
STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp32_partition_ioctl_obj, esp32_partition_ioctl); STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp32_partition_ioctl_obj, esp32_partition_ioctl);

View File

@ -36,18 +36,28 @@ void IRAM_ATTR esp_neopixel_write(uint8_t pin, uint8_t *pixels, uint32_t numByte
uint32_t irq_state = mp_hal_quiet_timing_enter(); uint32_t irq_state = mp_hal_quiet_timing_enter();
for (t = time0;; t = time0) { for (t = time0;; t = time0) {
if (pix & mask) t = time1; // Bit high duration if (pix & mask) {
while (((c = mp_hal_ticks_cpu()) - startTime) < period); // Wait for bit start t = time1; // Bit high duration
}
while (((c = mp_hal_ticks_cpu()) - startTime) < period) {
; // Wait for bit start
}
GPIO_REG_WRITE(GPIO_OUT_W1TS_REG, pinMask); // Set high GPIO_REG_WRITE(GPIO_OUT_W1TS_REG, pinMask); // Set high
startTime = c; // Save start time startTime = c; // Save start time
while (((c = mp_hal_ticks_cpu()) - startTime) < t); // Wait high duration while (((c = mp_hal_ticks_cpu()) - startTime) < t) {
; // Wait high duration
}
GPIO_REG_WRITE(GPIO_OUT_W1TC_REG, pinMask); // Set low GPIO_REG_WRITE(GPIO_OUT_W1TC_REG, pinMask); // Set low
if (!(mask >>= 1)) { // Next bit/byte if (!(mask >>= 1)) { // Next bit/byte
if(p >= end) break; if (p >= end) {
break;
}
pix = *p++; pix = *p++;
mask = 0x80; mask = 0x80;
} }
} }
while ((mp_hal_ticks_cpu() - startTime) < period); // Wait for last bit while ((mp_hal_ticks_cpu() - startTime) < period) {
; // Wait for last bit
}
mp_hal_quiet_timing_exit(irq_state); mp_hal_quiet_timing_exit(irq_state);
} }

View File

@ -36,6 +36,6 @@ DWORD get_fattime(void) {
timeutils_struct_time_t tm; timeutils_struct_time_t tm;
timeutils_seconds_since_2000_to_struct_time(tv.tv_sec, &tm); timeutils_seconds_since_2000_to_struct_time(tv.tv_sec, &tm);
return (((DWORD)(tm.tm_year - 1980) << 25) | ((DWORD)tm.tm_mon << 21) | ((DWORD)tm.tm_mday << 16) | return ((DWORD)(tm.tm_year - 1980) << 25) | ((DWORD)tm.tm_mon << 21) | ((DWORD)tm.tm_mday << 16) |
((DWORD)tm.tm_hour << 11) | ((DWORD)tm.tm_min << 5) | ((DWORD)tm.tm_sec >> 1)); ((DWORD)tm.tm_hour << 11) | ((DWORD)tm.tm_min << 5) | ((DWORD)tm.tm_sec >> 1);
} }

View File

@ -69,11 +69,18 @@ STATIC mp_obj_t madc_make_new(const mp_obj_type_t *type, size_t n_args, size_t n
gpio_num_t pin_id = machine_pin_get_id(args[0]); gpio_num_t pin_id = machine_pin_get_id(args[0]);
const madc_obj_t *self = NULL; const madc_obj_t *self = NULL;
for (int i = 0; i < MP_ARRAY_SIZE(madc_obj); i++) { for (int i = 0; i < MP_ARRAY_SIZE(madc_obj); i++) {
if (pin_id == madc_obj[i].gpio_id) { self = &madc_obj[i]; break; } if (pin_id == madc_obj[i].gpio_id) {
self = &madc_obj[i];
break;
}
}
if (!self) {
mp_raise_ValueError("invalid Pin for ADC");
} }
if (!self) mp_raise_ValueError("invalid Pin for ADC");
esp_err_t err = adc1_config_channel_atten(self->adc1_id, ADC_ATTEN_0db); esp_err_t err = adc1_config_channel_atten(self->adc1_id, ADC_ATTEN_0db);
if (err == ESP_OK) return MP_OBJ_FROM_PTR(self); if (err == ESP_OK) {
return MP_OBJ_FROM_PTR(self);
}
mp_raise_ValueError("Parameter Error"); mp_raise_ValueError("Parameter Error");
} }
@ -96,7 +103,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(madc_read_u16_obj, madc_read_u16);
STATIC mp_obj_t madc_read(mp_obj_t self_in) { STATIC mp_obj_t madc_read(mp_obj_t self_in) {
madc_obj_t *self = self_in; madc_obj_t *self = self_in;
int val = adc1_get_raw(self->adc1_id); int val = adc1_get_raw(self->adc1_id);
if (val == -1) mp_raise_ValueError("Parameter Error"); if (val == -1) {
mp_raise_ValueError("Parameter Error");
}
return MP_OBJ_NEW_SMALL_INT(val); return MP_OBJ_NEW_SMALL_INT(val);
} }
MP_DEFINE_CONST_FUN_OBJ_1(madc_read_obj, madc_read); MP_DEFINE_CONST_FUN_OBJ_1(madc_read_obj, madc_read);
@ -105,7 +114,9 @@ STATIC mp_obj_t madc_atten(mp_obj_t self_in, mp_obj_t atten_in) {
madc_obj_t *self = self_in; madc_obj_t *self = self_in;
adc_atten_t atten = mp_obj_get_int(atten_in); adc_atten_t atten = mp_obj_get_int(atten_in);
esp_err_t err = adc1_config_channel_atten(self->adc1_id, atten); esp_err_t err = adc1_config_channel_atten(self->adc1_id, atten);
if (err == ESP_OK) return mp_const_none; if (err == ESP_OK) {
return mp_const_none;
}
mp_raise_ValueError("Parameter Error"); mp_raise_ValueError("Parameter Error");
} }
MP_DEFINE_CONST_FUN_OBJ_2(madc_atten_obj, madc_atten); MP_DEFINE_CONST_FUN_OBJ_2(madc_atten_obj, madc_atten);
@ -117,11 +128,20 @@ STATIC mp_obj_t madc_width(mp_obj_t cls_in, mp_obj_t width_in) {
mp_raise_ValueError("Parameter Error"); mp_raise_ValueError("Parameter Error");
} }
switch (width) { switch (width) {
case ADC_WIDTH_9Bit: adc_bit_width = 9; break; case ADC_WIDTH_9Bit:
case ADC_WIDTH_10Bit: adc_bit_width = 10; break; adc_bit_width = 9;
case ADC_WIDTH_11Bit: adc_bit_width = 11; break; break;
case ADC_WIDTH_12Bit: adc_bit_width = 12; break; case ADC_WIDTH_10Bit:
default: break; adc_bit_width = 10;
break;
case ADC_WIDTH_11Bit:
adc_bit_width = 11;
break;
case ADC_WIDTH_12Bit:
adc_bit_width = 12;
break;
default:
break;
} }
return mp_const_none; return mp_const_none;
} }

View File

@ -54,15 +54,22 @@ STATIC mp_obj_t mdac_make_new(const mp_obj_type_t *type, size_t n_args, size_t n
gpio_num_t pin_id = machine_pin_get_id(args[0]); gpio_num_t pin_id = machine_pin_get_id(args[0]);
const mdac_obj_t *self = NULL; const mdac_obj_t *self = NULL;
for (int i = 0; i < MP_ARRAY_SIZE(mdac_obj); i++) { for (int i = 0; i < MP_ARRAY_SIZE(mdac_obj); i++) {
if (pin_id == mdac_obj[i].gpio_id) { self = &mdac_obj[i]; break; } if (pin_id == mdac_obj[i].gpio_id) {
self = &mdac_obj[i];
break;
}
}
if (!self) {
mp_raise_ValueError("invalid Pin for DAC");
} }
if (!self) mp_raise_ValueError("invalid Pin for DAC");
esp_err_t err = dac_output_enable(self->dac_id); esp_err_t err = dac_output_enable(self->dac_id);
if (err == ESP_OK) { if (err == ESP_OK) {
err = dac_output_voltage(self->dac_id, 0); err = dac_output_voltage(self->dac_id, 0);
} }
if (err == ESP_OK) return MP_OBJ_FROM_PTR(self); if (err == ESP_OK) {
return MP_OBJ_FROM_PTR(self);
}
mp_raise_ValueError("Parameter Error"); mp_raise_ValueError("Parameter Error");
} }
@ -74,10 +81,14 @@ STATIC void mdac_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_
STATIC mp_obj_t mdac_write(mp_obj_t self_in, mp_obj_t value_in) { STATIC mp_obj_t mdac_write(mp_obj_t self_in, mp_obj_t value_in) {
mdac_obj_t *self = self_in; mdac_obj_t *self = self_in;
int value = mp_obj_get_int(value_in); int value = mp_obj_get_int(value_in);
if (value < 0 || value > 255) mp_raise_ValueError("Value out of range"); if (value < 0 || value > 255) {
mp_raise_ValueError("Value out of range");
}
esp_err_t err = dac_output_voltage(self->dac_id, value); esp_err_t err = dac_output_voltage(self->dac_id, value);
if (err == ESP_OK) return mp_const_none; if (err == ESP_OK) {
return mp_const_none;
}
mp_raise_ValueError("Parameter Error"); mp_raise_ValueError("Parameter Error");
} }
MP_DEFINE_CONST_FUN_OBJ_2(mdac_write_obj, mdac_write); MP_DEFINE_CONST_FUN_OBJ_2(mdac_write_obj, mdac_write);

View File

@ -222,7 +222,8 @@ STATIC mp_obj_t machine_sdcard_make_new(const mp_obj_type_t *type, size_t n_args
.gpio_wp = SDSPI_SLOT_NO_WP, .gpio_wp = SDSPI_SLOT_NO_WP,
.dma_channel = 2 .dma_channel = 2
}, },
SDSPI_SLOT_CONFIG_DEFAULT() }; SDSPI_SLOT_CONFIG_DEFAULT()
};
DEBUG_printf(" Setting up SPI slot configuration"); DEBUG_printf(" Setting up SPI slot configuration");
sdspi_slot_config_t slot_config = slot_defaults[slot_num]; sdspi_slot_config_t slot_config = slot_defaults[slot_num];
@ -352,14 +353,16 @@ STATIC mp_obj_t machine_sdcard_ioctl(mp_obj_t self_in, mp_obj_t cmd_in, mp_obj_t
case MP_BLOCKDEV_IOCTL_BLOCK_COUNT: case MP_BLOCKDEV_IOCTL_BLOCK_COUNT:
err = sdcard_ensure_card_init(self, false); err = sdcard_ensure_card_init(self, false);
if (err != ESP_OK) if (err != ESP_OK) {
return MP_OBJ_NEW_SMALL_INT(-1); return MP_OBJ_NEW_SMALL_INT(-1);
}
return MP_OBJ_NEW_SMALL_INT(self->card.csd.capacity); return MP_OBJ_NEW_SMALL_INT(self->card.csd.capacity);
case MP_BLOCKDEV_IOCTL_BLOCK_SIZE: case MP_BLOCKDEV_IOCTL_BLOCK_SIZE:
err = sdcard_ensure_card_init(self, false); err = sdcard_ensure_card_init(self, false);
if (err != ESP_OK) if (err != ESP_OK) {
return MP_OBJ_NEW_SMALL_INT(-1); return MP_OBJ_NEW_SMALL_INT(-1);
}
return MP_OBJ_NEW_SMALL_INT(_SECTOR_SIZE(self)); return MP_OBJ_NEW_SMALL_INT(_SECTOR_SIZE(self));
default: // unknown command default: // unknown command

View File

@ -62,9 +62,14 @@ STATIC mp_obj_t mtp_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_
gpio_num_t pin_id = machine_pin_get_id(args[0]); gpio_num_t pin_id = machine_pin_get_id(args[0]);
const mtp_obj_t *self = NULL; const mtp_obj_t *self = NULL;
for (int i = 0; i < MP_ARRAY_SIZE(touchpad_obj); i++) { for (int i = 0; i < MP_ARRAY_SIZE(touchpad_obj); i++) {
if (pin_id == touchpad_obj[i].gpio_id) { self = &touchpad_obj[i]; break; } if (pin_id == touchpad_obj[i].gpio_id) {
self = &touchpad_obj[i];
break;
}
}
if (!self) {
mp_raise_ValueError("invalid pin for touchpad");
} }
if (!self) mp_raise_ValueError("invalid pin for touchpad");
static int initialized = 0; static int initialized = 0;
if (!initialized) { if (!initialized) {
@ -73,7 +78,9 @@ STATIC mp_obj_t mtp_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_
initialized = 1; initialized = 1;
} }
esp_err_t err = touch_pad_config(self->touchpad_id, 0); esp_err_t err = touch_pad_config(self->touchpad_id, 0);
if (err == ESP_OK) return MP_OBJ_FROM_PTR(self); if (err == ESP_OK) {
return MP_OBJ_FROM_PTR(self);
}
mp_raise_ValueError("Touch pad error"); mp_raise_ValueError("Touch pad error");
} }
@ -81,7 +88,9 @@ STATIC mp_obj_t mtp_config(mp_obj_t self_in, mp_obj_t value_in) {
mtp_obj_t *self = self_in; mtp_obj_t *self = self_in;
uint16_t value = mp_obj_get_int(value_in); uint16_t value = mp_obj_get_int(value_in);
esp_err_t err = touch_pad_config(self->touchpad_id, value); esp_err_t err = touch_pad_config(self->touchpad_id, value);
if (err == ESP_OK) return mp_const_none; if (err == ESP_OK) {
return mp_const_none;
}
mp_raise_ValueError("Touch pad error"); mp_raise_ValueError("Touch pad error");
} }
MP_DEFINE_CONST_FUN_OBJ_2(mtp_config_obj, mtp_config); MP_DEFINE_CONST_FUN_OBJ_2(mtp_config_obj, mtp_config);
@ -90,7 +99,9 @@ STATIC mp_obj_t mtp_read(mp_obj_t self_in) {
mtp_obj_t *self = self_in; mtp_obj_t *self = self_in;
uint16_t value; uint16_t value;
esp_err_t err = touch_pad_read(self->touchpad_id, &value); esp_err_t err = touch_pad_read(self->touchpad_id, &value);
if (err == ESP_OK) return MP_OBJ_NEW_SMALL_INT(value); if (err == ESP_OK) {
return MP_OBJ_NEW_SMALL_INT(value);
}
mp_raise_ValueError("Touch pad error"); mp_raise_ValueError("Touch pad error");
} }
MP_DEFINE_CONST_FUN_OBJ_1(mtp_read_obj, mtp_read); MP_DEFINE_CONST_FUN_OBJ_1(mtp_read_obj, mtp_read);

View File

@ -5,21 +5,21 @@ OFFSET_PARTITIONS = 0x8000
OFFSET_APPLICATION = 0x10000 OFFSET_APPLICATION = 0x10000
files_in = [ files_in = [
('bootloader', OFFSET_BOOTLOADER, sys.argv[1]), ("bootloader", OFFSET_BOOTLOADER, sys.argv[1]),
('partitions', OFFSET_PARTITIONS, sys.argv[2]), ("partitions", OFFSET_PARTITIONS, sys.argv[2]),
('application', OFFSET_APPLICATION, sys.argv[3]), ("application", OFFSET_APPLICATION, sys.argv[3]),
] ]
file_out = sys.argv[4] file_out = sys.argv[4]
cur_offset = OFFSET_BOOTLOADER cur_offset = OFFSET_BOOTLOADER
with open(file_out, 'wb') as fout: with open(file_out, "wb") as fout:
for name, offset, file_in in files_in: for name, offset, file_in in files_in:
assert offset >= cur_offset assert offset >= cur_offset
fout.write(b'\xff' * (offset - cur_offset)) fout.write(b"\xff" * (offset - cur_offset))
cur_offset = offset cur_offset = offset
with open(file_in, 'rb') as fin: with open(file_in, "rb") as fin:
data = fin.read() data = fin.read()
fout.write(data) fout.write(data)
cur_offset += len(data) cur_offset += len(data)
print('%-12s% 8d' % (name, len(data))) print("%-12s% 8d" % (name, len(data)))
print('%-12s% 8d' % ('total', cur_offset)) print("%-12s% 8d" % ("total", cur_offset))

View File

@ -103,7 +103,9 @@ NORETURN void _esp_exceptions(esp_err_t e) {
} }
static inline void esp_exceptions(esp_err_t e) { static inline void esp_exceptions(esp_err_t e) {
if (e != ESP_OK) _esp_exceptions(e); if (e != ESP_OK) {
_esp_exceptions(e);
}
} }
#define ESP_EXCEPTIONS(x) do { esp_exceptions(x); } while (0); #define ESP_EXCEPTIONS(x) do { esp_exceptions(x); } while (0);
@ -520,12 +522,16 @@ STATIC mp_obj_t esp_ifconfig(size_t n_args, const mp_obj_t *args) {
// To set a static IP we have to disable DHCP first // To set a static IP we have to disable DHCP first
if (self->if_id == WIFI_IF_STA || self->if_id == ESP_IF_ETH) { if (self->if_id == WIFI_IF_STA || self->if_id == ESP_IF_ETH) {
esp_err_t e = tcpip_adapter_dhcpc_stop(self->if_id); esp_err_t e = tcpip_adapter_dhcpc_stop(self->if_id);
if (e != ESP_OK && e != ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED) _esp_exceptions(e); if (e != ESP_OK && e != ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED) {
_esp_exceptions(e);
}
ESP_EXCEPTIONS(tcpip_adapter_set_ip_info(self->if_id, &info)); ESP_EXCEPTIONS(tcpip_adapter_set_ip_info(self->if_id, &info));
ESP_EXCEPTIONS(tcpip_adapter_set_dns_info(self->if_id, TCPIP_ADAPTER_DNS_MAIN, &dns_info)); ESP_EXCEPTIONS(tcpip_adapter_set_dns_info(self->if_id, TCPIP_ADAPTER_DNS_MAIN, &dns_info));
} else if (self->if_id == WIFI_IF_AP) { } else if (self->if_id == WIFI_IF_AP) {
esp_err_t e = tcpip_adapter_dhcps_stop(WIFI_IF_AP); esp_err_t e = tcpip_adapter_dhcps_stop(WIFI_IF_AP);
if (e != ESP_OK && e != ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED) _esp_exceptions(e); if (e != ESP_OK && e != ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED) {
_esp_exceptions(e);
}
ESP_EXCEPTIONS(tcpip_adapter_set_ip_info(WIFI_IF_AP, &info)); ESP_EXCEPTIONS(tcpip_adapter_set_ip_info(WIFI_IF_AP, &info));
ESP_EXCEPTIONS(tcpip_adapter_set_dns_info(WIFI_IF_AP, TCPIP_ADAPTER_DNS_MAIN, &dns_info)); ESP_EXCEPTIONS(tcpip_adapter_set_dns_info(WIFI_IF_AP, TCPIP_ADAPTER_DNS_MAIN, &dns_info));
ESP_EXCEPTIONS(tcpip_adapter_dhcps_start(WIFI_IF_AP)); ESP_EXCEPTIONS(tcpip_adapter_dhcps_start(WIFI_IF_AP));

View File

@ -293,7 +293,9 @@ STATIC mp_obj_t socket_bind(const mp_obj_t arg0, const mp_obj_t arg1) {
_socket_getaddrinfo(arg1, &res); _socket_getaddrinfo(arg1, &res);
int r = lwip_bind(self->fd, res->ai_addr, res->ai_addrlen); int r = lwip_bind(self->fd, res->ai_addr, res->ai_addrlen);
lwip_freeaddrinfo(res); lwip_freeaddrinfo(res);
if (r < 0) exception_from_errno(errno); if (r < 0) {
exception_from_errno(errno);
}
return mp_const_none; return mp_const_none;
} }
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_bind_obj, socket_bind); STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_bind_obj, socket_bind);
@ -302,7 +304,9 @@ STATIC mp_obj_t socket_listen(const mp_obj_t arg0, const mp_obj_t arg1) {
socket_obj_t *self = MP_OBJ_TO_PTR(arg0); socket_obj_t *self = MP_OBJ_TO_PTR(arg0);
int backlog = mp_obj_get_int(arg1); int backlog = mp_obj_get_int(arg1);
int r = lwip_listen(self->fd, backlog); int r = lwip_listen(self->fd, backlog);
if (r < 0) exception_from_errno(errno); if (r < 0) {
exception_from_errno(errno);
}
return mp_const_none; return mp_const_none;
} }
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_listen_obj, socket_listen); STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_listen_obj, socket_listen);
@ -318,8 +322,12 @@ STATIC mp_obj_t socket_accept(const mp_obj_t arg0) {
MP_THREAD_GIL_EXIT(); MP_THREAD_GIL_EXIT();
new_fd = lwip_accept(self->fd, &addr, &addr_len); new_fd = lwip_accept(self->fd, &addr, &addr_len);
MP_THREAD_GIL_ENTER(); MP_THREAD_GIL_ENTER();
if (new_fd >= 0) break; if (new_fd >= 0) {
if (errno != EAGAIN) exception_from_errno(errno); break;
}
if (errno != EAGAIN) {
exception_from_errno(errno);
}
check_for_exceptions(); check_for_exceptions();
} }
if (new_fd < 0) { if (new_fd < 0) {
@ -445,8 +453,9 @@ void _socket_settimeout(socket_obj_t *sock, uint64_t timeout_ms) {
STATIC mp_obj_t socket_settimeout(const mp_obj_t arg0, const mp_obj_t arg1) { STATIC mp_obj_t socket_settimeout(const mp_obj_t arg0, const mp_obj_t arg1) {
socket_obj_t *self = MP_OBJ_TO_PTR(arg0); socket_obj_t *self = MP_OBJ_TO_PTR(arg0);
if (arg1 == mp_const_none) _socket_settimeout(self, UINT64_MAX); if (arg1 == mp_const_none) {
else { _socket_settimeout(self, UINT64_MAX);
} else {
#if MICROPY_PY_BUILTINS_FLOAT #if MICROPY_PY_BUILTINS_FLOAT
_socket_settimeout(self, mp_obj_get_float(arg1) * 1000L); _socket_settimeout(self, mp_obj_get_float(arg1) * 1000L);
#else #else
@ -459,8 +468,11 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_settimeout_obj, socket_settimeout);
STATIC mp_obj_t socket_setblocking(const mp_obj_t arg0, const mp_obj_t arg1) { STATIC mp_obj_t socket_setblocking(const mp_obj_t arg0, const mp_obj_t arg1) {
socket_obj_t *self = MP_OBJ_TO_PTR(arg0); socket_obj_t *self = MP_OBJ_TO_PTR(arg0);
if (mp_obj_is_true(arg1)) _socket_settimeout(self, UINT64_MAX); if (mp_obj_is_true(arg1)) {
else _socket_settimeout(self, 0); _socket_settimeout(self, UINT64_MAX);
} else {
_socket_settimeout(self, 0);
}
return mp_const_none; return mp_const_none;
} }
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking); STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking);
@ -559,11 +571,17 @@ int _socket_send(socket_obj_t *sock, const char *data, size_t datalen) {
MP_THREAD_GIL_EXIT(); MP_THREAD_GIL_EXIT();
int r = lwip_write(sock->fd, data + sentlen, datalen - sentlen); int r = lwip_write(sock->fd, data + sentlen, datalen - sentlen);
MP_THREAD_GIL_ENTER(); MP_THREAD_GIL_ENTER();
if (r < 0 && errno != EWOULDBLOCK) exception_from_errno(errno); if (r < 0 && errno != EWOULDBLOCK) {
if (r > 0) sentlen += r; exception_from_errno(errno);
}
if (r > 0) {
sentlen += r;
}
check_for_exceptions(); check_for_exceptions();
} }
if (sentlen == 0) mp_raise_OSError(MP_ETIMEDOUT); if (sentlen == 0) {
mp_raise_OSError(MP_ETIMEDOUT);
}
return sentlen; return sentlen;
} }
@ -583,7 +601,9 @@ STATIC mp_obj_t socket_sendall(const mp_obj_t arg0, const mp_obj_t arg1) {
mp_buffer_info_t bufinfo; mp_buffer_info_t bufinfo;
mp_get_buffer_raise(arg1, &bufinfo, MP_BUFFER_READ); mp_get_buffer_raise(arg1, &bufinfo, MP_BUFFER_READ);
int r = _socket_send(sock, bufinfo.buf, bufinfo.len); int r = _socket_send(sock, bufinfo.buf, bufinfo.len);
if (r < bufinfo.len) mp_raise_OSError(MP_ETIMEDOUT); if (r < bufinfo.len) {
mp_raise_OSError(MP_ETIMEDOUT);
}
return mp_const_none; return mp_const_none;
} }
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_sendall_obj, socket_sendall); STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_sendall_obj, socket_sendall);
@ -606,7 +626,9 @@ STATIC mp_obj_t socket_sendto(mp_obj_t self_in, mp_obj_t data_in, mp_obj_t addr_
MP_THREAD_GIL_EXIT(); MP_THREAD_GIL_EXIT();
int ret = lwip_sendto(self->fd, bufinfo.buf, bufinfo.len, 0, (struct sockaddr *)&to, sizeof(to)); int ret = lwip_sendto(self->fd, bufinfo.buf, bufinfo.len, 0, (struct sockaddr *)&to, sizeof(to));
MP_THREAD_GIL_ENTER(); MP_THREAD_GIL_ENTER();
if (ret > 0) return mp_obj_new_int_from_uint(ret); if (ret > 0) {
return mp_obj_new_int_from_uint(ret);
}
if (ret == -1 && errno != EWOULDBLOCK) { if (ret == -1 && errno != EWOULDBLOCK) {
exception_from_errno(errno); exception_from_errno(errno);
} }
@ -638,8 +660,13 @@ STATIC mp_uint_t socket_stream_write(mp_obj_t self_in, const void *buf, mp_uint_
MP_THREAD_GIL_EXIT(); MP_THREAD_GIL_EXIT();
int r = lwip_write(sock->fd, buf, size); int r = lwip_write(sock->fd, buf, size);
MP_THREAD_GIL_ENTER(); MP_THREAD_GIL_ENTER();
if (r > 0) return r; if (r > 0) {
if (r < 0 && errno != EWOULDBLOCK) { *errcode = errno; return MP_STREAM_ERROR; } return r;
}
if (r < 0 && errno != EWOULDBLOCK) {
*errcode = errno;
return MP_STREAM_ERROR;
}
check_for_exceptions(); check_for_exceptions();
} }
*errcode = sock->retries == 0 ? MP_EWOULDBLOCK : MP_ETIMEDOUT; *errcode = sock->retries == 0 ? MP_EWOULDBLOCK : MP_ETIMEDOUT;
@ -650,13 +677,22 @@ STATIC mp_uint_t socket_stream_ioctl(mp_obj_t self_in, mp_uint_t request, uintpt
socket_obj_t *socket = self_in; socket_obj_t *socket = self_in;
if (request == MP_STREAM_POLL) { if (request == MP_STREAM_POLL) {
fd_set rfds; FD_ZERO(&rfds); fd_set rfds;
fd_set wfds; FD_ZERO(&wfds); FD_ZERO(&rfds);
fd_set efds; FD_ZERO(&efds); fd_set wfds;
FD_ZERO(&wfds);
fd_set efds;
FD_ZERO(&efds);
struct timeval timeout = { .tv_sec = 0, .tv_usec = 0 }; struct timeval timeout = { .tv_sec = 0, .tv_usec = 0 };
if (arg & MP_STREAM_POLL_RD) FD_SET(socket->fd, &rfds); if (arg & MP_STREAM_POLL_RD) {
if (arg & MP_STREAM_POLL_WR) FD_SET(socket->fd, &wfds); FD_SET(socket->fd, &rfds);
if (arg & MP_STREAM_POLL_HUP) FD_SET(socket->fd, &efds); }
if (arg & MP_STREAM_POLL_WR) {
FD_SET(socket->fd, &wfds);
}
if (arg & MP_STREAM_POLL_HUP) {
FD_SET(socket->fd, &efds);
}
int r = select((socket->fd) + 1, &rfds, &wfds, &efds, &timeout); int r = select((socket->fd) + 1, &rfds, &wfds, &efds, &timeout);
if (r < 0) { if (r < 0) {
@ -665,9 +701,15 @@ STATIC mp_uint_t socket_stream_ioctl(mp_obj_t self_in, mp_uint_t request, uintpt
} }
mp_uint_t ret = 0; mp_uint_t ret = 0;
if (FD_ISSET(socket->fd, &rfds)) ret |= MP_STREAM_POLL_RD; if (FD_ISSET(socket->fd, &rfds)) {
if (FD_ISSET(socket->fd, &wfds)) ret |= MP_STREAM_POLL_WR; ret |= MP_STREAM_POLL_RD;
if (FD_ISSET(socket->fd, &efds)) ret |= MP_STREAM_POLL_HUP; }
if (FD_ISSET(socket->fd, &wfds)) {
ret |= MP_STREAM_POLL_WR;
}
if (FD_ISSET(socket->fd, &efds)) {
ret |= MP_STREAM_POLL_HUP;
}
return ret; return ret;
} else if (request == MP_STREAM_CLOSE) { } else if (request == MP_STREAM_CLOSE) {
if (socket->fd >= 0) { if (socket->fd >= 0) {
@ -761,7 +803,9 @@ STATIC mp_obj_t esp_socket_getaddrinfo(size_t n_args, const mp_obj_t *args) {
mp_obj_list_append(ret_list, mp_obj_new_tuple(5, addrinfo_objs)); mp_obj_list_append(ret_list, mp_obj_new_tuple(5, addrinfo_objs));
} }
if (res) lwip_freeaddrinfo(res); if (res) {
lwip_freeaddrinfo(res);
}
return ret_list; return ret_list;
} }
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(esp_socket_getaddrinfo_obj, 2, 6, esp_socket_getaddrinfo); STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(esp_socket_getaddrinfo_obj, 2, 6, esp_socket_getaddrinfo);

View File

@ -4,9 +4,10 @@ from flashbdev import bdev
try: try:
if bdev: if bdev:
uos.mount(bdev, '/') uos.mount(bdev, "/")
except OSError: except OSError:
import inisetup import inisetup
vfs = inisetup.setup() vfs = inisetup.setup()
gc.collect() gc.collect()

View File

@ -1,4 +1,4 @@
from esp32 import Partition from esp32 import Partition
bdev = Partition.find(Partition.TYPE_DATA, label='vfs') bdev = Partition.find(Partition.TYPE_DATA, label="vfs")
bdev = bdev[0] if bdev else None bdev = bdev[0] if bdev else None

View File

@ -1,41 +1,49 @@
import uos import uos
from flashbdev import bdev from flashbdev import bdev
def check_bootsec(): def check_bootsec():
buf = bytearray(bdev.ioctl(5, 0)) # 5 is SEC_SIZE buf = bytearray(bdev.ioctl(5, 0)) # 5 is SEC_SIZE
bdev.readblocks(0, buf) bdev.readblocks(0, buf)
empty = True empty = True
for b in buf: for b in buf:
if b != 0xff: if b != 0xFF:
empty = False empty = False
break break
if empty: if empty:
return True return True
fs_corrupted() fs_corrupted()
def fs_corrupted(): def fs_corrupted():
import time import time
while 1: while 1:
print("""\ print(
"""\
FAT filesystem appears to be corrupted. If you had important data there, you FAT filesystem appears to be corrupted. If you had important data there, you
may want to make a flash snapshot to try to recover it. Otherwise, perform may want to make a flash snapshot to try to recover it. Otherwise, perform
factory reprogramming of MicroPython firmware (completely erase flash, followed factory reprogramming of MicroPython firmware (completely erase flash, followed
by firmware programming). by firmware programming).
""") """
)
time.sleep(3) time.sleep(3)
def setup(): def setup():
check_bootsec() check_bootsec()
print("Performing initial setup") print("Performing initial setup")
uos.VfsFat.mkfs(bdev) uos.VfsFat.mkfs(bdev)
vfs = uos.VfsFat(bdev) vfs = uos.VfsFat(bdev)
uos.mount(vfs, '/') uos.mount(vfs, "/")
with open("boot.py", "w") as f: with open("boot.py", "w") as f:
f.write("""\ f.write(
"""\
# This file is executed on every boot (including wake-boot from deepsleep) # This file is executed on every boot (including wake-boot from deepsleep)
#import esp #import esp
#esp.osdebug(None) #esp.osdebug(None)
#import webrepl #import webrepl
#webrepl.start() #webrepl.start()
""") """
)
return vfs return vfs

View File

@ -22,8 +22,7 @@ class NeoPixel:
def __getitem__(self, index): def __getitem__(self, index):
offset = index * self.bpp offset = index * self.bpp
return tuple(self.buf[offset + self.ORDER[i]] return tuple(self.buf[offset + self.ORDER[i]] for i in range(self.bpp))
for i in range(self.bpp))
def fill(self, color): def fill(self, color):
for i in range(self.n): for i in range(self.n):

View File

@ -114,7 +114,8 @@ STATIC void freertos_entry(void *arg) {
ext_thread_entry(arg); ext_thread_entry(arg);
} }
vTaskDelete(NULL); vTaskDelete(NULL);
for (;;); for (;;) {;
}
} }
void mp_thread_create_ex(void *(*entry)(void *), void *arg, size_t *stack_size, int priority, char *name) { void mp_thread_create_ex(void *(*entry)(void *), void *arg, size_t *stack_size, int priority, char *name) {
@ -197,7 +198,7 @@ void mp_thread_mutex_init(mp_thread_mutex_t *mutex) {
} }
int mp_thread_mutex_lock(mp_thread_mutex_t *mutex, int wait) { int mp_thread_mutex_lock(mp_thread_mutex_t *mutex, int wait) {
return (pdTRUE == xSemaphoreTake(mutex->handle, wait ? portMAX_DELAY : 0)); return pdTRUE == xSemaphoreTake(mutex->handle, wait ? portMAX_DELAY : 0);
} }
void mp_thread_mutex_unlock(mp_thread_mutex_t *mutex) { void mp_thread_mutex_unlock(mp_thread_mutex_t *mutex) {

View File

@ -1,5 +1,5 @@
freeze('$(PORT_DIR)/modules') freeze("$(PORT_DIR)/modules")
freeze('$(MPY_DIR)/tools', ('upip.py', 'upip_utarfile.py')) freeze("$(MPY_DIR)/tools", ("upip.py", "upip_utarfile.py"))
freeze('$(MPY_DIR)/drivers/dht', 'dht.py') freeze("$(MPY_DIR)/drivers/dht", "dht.py")
freeze('$(MPY_DIR)/drivers/onewire') freeze("$(MPY_DIR)/drivers/onewire")
include('$(MPY_DIR)/extmod/webrepl/manifest.py') include("$(MPY_DIR)/extmod/webrepl/manifest.py")

View File

@ -1,27 +1,27 @@
include('manifest.py') include("manifest.py")
# drivers # drivers
freeze('$(MPY_DIR)/drivers/display', 'ssd1306.py') freeze("$(MPY_DIR)/drivers/display", "ssd1306.py")
# file utilities # file utilities
freeze('$(MPY_LIB_DIR)/upysh', 'upysh.py') freeze("$(MPY_LIB_DIR)/upysh", "upysh.py")
# uasyncio # uasyncio
freeze('$(MPY_LIB_DIR)/uasyncio', 'uasyncio/__init__.py') freeze("$(MPY_LIB_DIR)/uasyncio", "uasyncio/__init__.py")
freeze('$(MPY_LIB_DIR)/uasyncio.core', 'uasyncio/core.py') freeze("$(MPY_LIB_DIR)/uasyncio.core", "uasyncio/core.py")
# requests # requests
freeze('$(MPY_LIB_DIR)/urequests', 'urequests.py') freeze("$(MPY_LIB_DIR)/urequests", "urequests.py")
freeze('$(MPY_LIB_DIR)/urllib.urequest', 'urllib/urequest.py') freeze("$(MPY_LIB_DIR)/urllib.urequest", "urllib/urequest.py")
# umqtt with examples # umqtt with examples
freeze('$(MPY_LIB_DIR)/umqtt.simple', 'umqtt/simple.py') freeze("$(MPY_LIB_DIR)/umqtt.simple", "umqtt/simple.py")
freeze('$(MPY_LIB_DIR)/umqtt.robust', 'umqtt/robust.py') freeze("$(MPY_LIB_DIR)/umqtt.robust", "umqtt/robust.py")
freeze('$(MPY_LIB_DIR)/umqtt.simple', 'example_pub_button.py') freeze("$(MPY_LIB_DIR)/umqtt.simple", "example_pub_button.py")
freeze('$(MPY_LIB_DIR)/umqtt.simple', 'example_sub_led.py') freeze("$(MPY_LIB_DIR)/umqtt.simple", "example_sub_led.py")
# HTTP examples # HTTP examples
freeze('$(MPY_DIR)/examples/network', 'http_client.py') freeze("$(MPY_DIR)/examples/network", "http_client.py")
freeze('$(MPY_DIR)/examples/network', 'http_client_ssl.py') freeze("$(MPY_DIR)/examples/network", "http_client_ssl.py")
freeze('$(MPY_DIR)/examples/network', 'http_server.py') freeze("$(MPY_DIR)/examples/network", "http_server.py")
freeze('$(MPY_DIR)/examples/network', 'http_server_ssl.py') freeze("$(MPY_DIR)/examples/network", "http_server_ssl.py")

View File

@ -46,19 +46,29 @@ void /*ICACHE_RAM_ATTR*/ esp_neopixel_write(uint8_t pin, uint8_t *pixels, uint32
uint32_t irq_state = mp_hal_quiet_timing_enter(); uint32_t irq_state = mp_hal_quiet_timing_enter();
for (t = time0;; t = time0) { for (t = time0;; t = time0) {
if(pix & mask) t = time1; // Bit high duration if (pix & mask) {
while(((c = mp_hal_ticks_cpu()) - startTime) < period); // Wait for bit start t = time1; // Bit high duration
}
while (((c = mp_hal_ticks_cpu()) - startTime) < period) {
; // Wait for bit start
}
GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, pinMask); // Set high GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, pinMask); // Set high
startTime = c; // Save start time startTime = c; // Save start time
while(((c = mp_hal_ticks_cpu()) - startTime) < t); // Wait high duration while (((c = mp_hal_ticks_cpu()) - startTime) < t) {
; // Wait high duration
}
GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, pinMask); // Set low GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, pinMask); // Set low
if (!(mask >>= 1)) { // Next bit/byte if (!(mask >>= 1)) { // Next bit/byte
if(p >= end) break; if (p >= end) {
break;
}
pix = *p++; pix = *p++;
mask = 0x80; mask = 0x80;
} }
} }
while((mp_hal_ticks_cpu() - startTime) < period); // Wait for last bit while ((mp_hal_ticks_cpu() - startTime) < period) {
; // Wait for last bit
}
mp_hal_quiet_timing_exit(irq_state); mp_hal_quiet_timing_exit(irq_state);
} }

View File

@ -81,8 +81,7 @@ typedef enum {
} TIMER_INT_MODE; } TIMER_INT_MODE;
STATIC void ICACHE_FLASH_ATTR STATIC void ICACHE_FLASH_ATTR
pwm_insert_sort(struct pwm_single_param pwm[], uint8 n) pwm_insert_sort(struct pwm_single_param pwm[], uint8 n) {
{
uint8 i; uint8 i;
for (i = 1; i < n; i++) { for (i = 1; i < n; i++) {
@ -118,8 +117,7 @@ STATIC volatile uint8 critical = 0;
} while (0) } while (0)
void ICACHE_FLASH_ATTR void ICACHE_FLASH_ATTR
pwm_start(void) pwm_start(void) {
{
uint8 i, j; uint8 i, j;
PWM_DBG("--Function pwm_start() is called\n"); PWM_DBG("--Function pwm_start() is called\n");
PWM_DBG("pwm_gpio:%x,pwm_channel_num:%d\n",pwm_gpio,pwm_channel_num); PWM_DBG("pwm_gpio:%x,pwm_channel_num:%d\n",pwm_gpio,pwm_channel_num);
@ -212,8 +210,7 @@ pwm_start(void)
* Returns : NONE * Returns : NONE
*******************************************************************************/ *******************************************************************************/
void ICACHE_FLASH_ATTR void ICACHE_FLASH_ATTR
pwm_set_duty(int16_t duty, uint8 channel) pwm_set_duty(int16_t duty, uint8 channel) {
{
uint8 i; uint8 i;
for (i = 0; i < pwm_channel_num; i++) { for (i = 0; i < pwm_channel_num; i++) {
if (pwm_out_io_num[i] == channel) { if (pwm_out_io_num[i] == channel) {
@ -221,8 +218,9 @@ pwm_set_duty(int16_t duty, uint8 channel)
break; break;
} }
} }
if(i==pwm_channel_num) // non found if (i == pwm_channel_num) { // non found
return; return;
}
LOCK_PWM(critical); // enter critical LOCK_PWM(critical); // enter critical
if (duty < 1) { if (duty < 1) {
@ -242,8 +240,7 @@ pwm_set_duty(int16_t duty, uint8 channel)
* Returns : NONE * Returns : NONE
*******************************************************************************/ *******************************************************************************/
void ICACHE_FLASH_ATTR void ICACHE_FLASH_ATTR
pwm_set_freq(uint16 freq, uint8 channel) pwm_set_freq(uint16 freq, uint8 channel) {
{
LOCK_PWM(critical); // enter critical LOCK_PWM(critical); // enter critical
if (freq > PWM_FREQ_MAX) { if (freq > PWM_FREQ_MAX) {
pwm.freq = PWM_FREQ_MAX; pwm.freq = PWM_FREQ_MAX;
@ -264,8 +261,7 @@ pwm_set_freq(uint16 freq, uint8 channel)
* Returns : NONE * Returns : NONE
*******************************************************************************/ *******************************************************************************/
uint16 ICACHE_FLASH_ATTR uint16 ICACHE_FLASH_ATTR
pwm_get_duty(uint8 channel) pwm_get_duty(uint8 channel) {
{
uint8 i; uint8 i;
for (i = 0; i < pwm_channel_num; i++) { for (i = 0; i < pwm_channel_num; i++) {
if (pwm_out_io_num[i] == channel) { if (pwm_out_io_num[i] == channel) {
@ -273,8 +269,9 @@ pwm_get_duty(uint8 channel)
break; break;
} }
} }
if(i==pwm_channel_num) // non found if (i == pwm_channel_num) { // non found
return 0; return 0;
}
return pwm.duty[channel]; return pwm.duty[channel];
} }
@ -286,8 +283,7 @@ pwm_get_duty(uint8 channel)
* Returns : uint16 : pwm frequency * Returns : uint16 : pwm frequency
*******************************************************************************/ *******************************************************************************/
uint16 ICACHE_FLASH_ATTR uint16 ICACHE_FLASH_ATTR
pwm_get_freq(uint8 channel) pwm_get_freq(uint8 channel) {
{
return pwm.freq; return pwm.freq;
} }
@ -299,8 +295,7 @@ pwm_get_freq(uint8 channel)
* Returns : NONE * Returns : NONE
*******************************************************************************/ *******************************************************************************/
STATIC void ICACHE_RAM_ATTR STATIC void ICACHE_RAM_ATTR
pwm_tim1_intr_handler(void *dummy) pwm_tim1_intr_handler(void *dummy) {
{
(void)dummy; (void)dummy;
uint8 local_toggle = pwm_toggle; // pwm_toggle may change outside uint8 local_toggle = pwm_toggle; // pwm_toggle may change outside
RTC_CLR_REG_MASK(FRC1_INT_ADDRESS, FRC1_INT_CLR_MASK); RTC_CLR_REG_MASK(FRC1_INT_ADDRESS, FRC1_INT_CLR_MASK);
@ -335,8 +330,7 @@ pwm_tim1_intr_handler(void *dummy)
* Returns : NONE * Returns : NONE
*******************************************************************************/ *******************************************************************************/
void ICACHE_FLASH_ATTR void ICACHE_FLASH_ATTR
pwm_init(void) pwm_init(void) {
{
uint8 i; uint8 i;
RTC_REG_WRITE(FRC1_CTRL_ADDRESS, //FRC2_AUTO_RELOAD| RTC_REG_WRITE(FRC1_CTRL_ADDRESS, //FRC2_AUTO_RELOAD|
@ -376,8 +370,9 @@ pwm_add(uint8_t pin_id, uint32_t pin_mux, uint32_t pin_func){
} }
uint8 i; uint8 i;
for (i = 0; i < PWM_CHANNEL; i++) { for (i = 0; i < PWM_CHANNEL; i++) {
if(pwm_out_io_num[i]==channel) // already exist if (pwm_out_io_num[i] == channel) { // already exist
return channel; return channel;
}
if (pwm_out_io_num[i] == -1) { // empty exist if (pwm_out_io_num[i] == -1) { // empty exist
LOCK_PWM(critical); // enter critical LOCK_PWM(critical); // enter critical
pwm_out_io_num[i] = channel; pwm_out_io_num[i] = channel;

View File

@ -38,7 +38,9 @@ static inline int prio2id(uint8_t prio) {
int id = PRIO2ID(prio); int id = PRIO2ID(prio);
if (id < 0 || id >= MP_ARRAY_SIZE(emu_tasks)) { if (id < 0 || id >= MP_ARRAY_SIZE(emu_tasks)) {
printf("task prio out of range: %d\n", prio); printf("task prio out of range: %d\n", prio);
while (1); while (1) {
;
}
} }
return id; return id;
} }

View File

@ -38,6 +38,6 @@ DWORD get_fattime(void) {
timeutils_struct_time_t tm; timeutils_struct_time_t tm;
timeutils_seconds_since_2000_to_struct_time(secs, &tm); timeutils_seconds_since_2000_to_struct_time(secs, &tm);
return (((DWORD)(tm.tm_year - 1980) << 25) | ((DWORD)tm.tm_mon << 21) | ((DWORD)tm.tm_mday << 16) | return ((DWORD)(tm.tm_year - 1980) << 25) | ((DWORD)tm.tm_mon << 21) | ((DWORD)tm.tm_mday << 16) |
((DWORD)tm.tm_hour << 11) | ((DWORD)tm.tm_min << 5) | ((DWORD)tm.tm_sec >> 1)); ((DWORD)tm.tm_hour << 11) | ((DWORD)tm.tm_min << 5) | ((DWORD)tm.tm_sec >> 1);
} }

View File

@ -188,7 +188,9 @@ uint32_t spi_transaction(uint8_t spi_no, uint8_t cmd_bits, uint16_t cmd_data,
uint32_t addr_bits, uint32_t addr_data, uint32_t addr_bits, uint32_t addr_data,
uint32_t dout_bits, uint32_t dout_data, uint32_t dout_bits, uint32_t dout_data,
uint32_t din_bits, uint32_t dummy_bits) { uint32_t din_bits, uint32_t dummy_bits) {
while (spi_busy(spi_no)) {}; // Wait for SPI to be ready while (spi_busy(spi_no)) {
}
; // Wait for SPI to be ready
// Enable SPI Functions // Enable SPI Functions
// Disable MOSI, MISO, ADDR, COMMAND, DUMMY in case previously set. // Disable MOSI, MISO, ADDR, COMMAND, DUMMY in case previously set.
@ -280,7 +282,9 @@ uint32_t spi_transaction(uint8_t spi_no, uint8_t cmd_bits, uint16_t cmd_data,
// Return DIN data // Return DIN data
if (din_bits) { if (din_bits) {
while (spi_busy(spi_no)) {}; // Wait for SPI transaction to complete while (spi_busy(spi_no)) {
}
; // Wait for SPI transaction to complete
if (READ_PERI_REG(SPI_USER(spi_no)) & SPI_RD_BYTE_ORDER) { if (READ_PERI_REG(SPI_USER(spi_no)) & SPI_RD_BYTE_ORDER) {
// Assuming data in is written to MSB. TBC // Assuming data in is written to MSB. TBC
return READ_PERI_REG(SPI_W0(spi_no)) >> (32 - din_bits); return READ_PERI_REG(SPI_W0(spi_no)) >> (32 - din_bits);
@ -301,7 +305,9 @@ uint32_t spi_transaction(uint8_t spi_no, uint8_t cmd_bits, uint16_t cmd_data,
Just do minimal work needed to send 8 bits. Just do minimal work needed to send 8 bits.
*/ */
inline void spi_tx8fast(uint8_t spi_no, uint8_t dout_data) { inline void spi_tx8fast(uint8_t spi_no, uint8_t dout_data) {
while (spi_busy(spi_no)) {}; // Wait for SPI to be ready while (spi_busy(spi_no)) {
}
; // Wait for SPI to be ready
// Enable SPI Functions // Enable SPI Functions
// Disable MOSI, MISO, ADDR, COMMAND, DUMMY in case previously set. // Disable MOSI, MISO, ADDR, COMMAND, DUMMY in case previously set.

View File

@ -8,33 +8,33 @@ assert len(sys.argv) == 4
md5 = hashlib.md5() md5 = hashlib.md5()
with open(sys.argv[3], 'wb') as fout: with open(sys.argv[3], "wb") as fout:
with open(sys.argv[1], 'rb') as f: with open(sys.argv[1], "rb") as f:
data_flash = f.read() data_flash = f.read()
fout.write(data_flash) fout.write(data_flash)
# First 4 bytes include flash size, etc. which may be changed # First 4 bytes include flash size, etc. which may be changed
# by esptool.py, etc. # by esptool.py, etc.
md5.update(data_flash[4:]) md5.update(data_flash[4:])
print('flash ', len(data_flash)) print("flash ", len(data_flash))
with open(sys.argv[2], 'rb') as f: with open(sys.argv[2], "rb") as f:
data_rom = f.read() data_rom = f.read()
pad = b'\xff' * (SEGS_MAX_SIZE - len(data_flash)) pad = b"\xff" * (SEGS_MAX_SIZE - len(data_flash))
assert len(pad) >= 4 assert len(pad) >= 4
fout.write(pad[:-4]) fout.write(pad[:-4])
md5.update(pad[:-4]) md5.update(pad[:-4])
len_data = struct.pack("I", SEGS_MAX_SIZE + len(data_rom)) len_data = struct.pack("I", SEGS_MAX_SIZE + len(data_rom))
fout.write(len_data) fout.write(len_data)
md5.update(len_data) md5.update(len_data)
print('padding ', len(pad)) print("padding ", len(pad))
fout.write(data_rom) fout.write(data_rom)
md5.update(data_rom) md5.update(data_rom)
print('irom0text', len(data_rom)) print("irom0text", len(data_rom))
fout.write(md5.digest()) fout.write(md5.digest())
print('total ', SEGS_MAX_SIZE + len(data_rom)) print("total ", SEGS_MAX_SIZE + len(data_rom))
print('md5 ', md5.hexdigest()) print("md5 ", md5.hexdigest())

View File

@ -1,13 +1,15 @@
import gc import gc
gc.threshold((gc.mem_free() + gc.mem_alloc()) // 4) gc.threshold((gc.mem_free() + gc.mem_alloc()) // 4)
import uos import uos
from flashbdev import bdev from flashbdev import bdev
if bdev: if bdev:
try: try:
uos.mount(bdev, '/') uos.mount(bdev, "/")
except: except:
import inisetup import inisetup
inisetup.setup() inisetup.setup()
gc.collect() gc.collect()

View File

@ -1,11 +1,12 @@
import esp import esp
class FlashBdev: class FlashBdev:
SEC_SIZE = 4096 SEC_SIZE = 4096
RESERVED_SECS = 1 RESERVED_SECS = 1
START_SEC = esp.flash_user_start() // SEC_SIZE + RESERVED_SECS START_SEC = esp.flash_user_start() // SEC_SIZE + RESERVED_SECS
NUM_BLK = 0x6b - RESERVED_SECS NUM_BLK = 0x6B - RESERVED_SECS
def __init__(self, blocks=NUM_BLK): def __init__(self, blocks=NUM_BLK):
self.blocks = blocks self.blocks = blocks
@ -32,6 +33,7 @@ class FlashBdev:
esp.flash_erase(arg + self.START_SEC) esp.flash_erase(arg + self.START_SEC)
return 0 return 0
size = esp.flash_size() size = esp.flash_size()
if size < 1024 * 1024: if size < 1024 * 1024:
bdev = None bdev = None

View File

@ -2,45 +2,55 @@ import uos
import network import network
from flashbdev import bdev from flashbdev import bdev
def wifi(): def wifi():
import ubinascii import ubinascii
ap_if = network.WLAN(network.AP_IF) ap_if = network.WLAN(network.AP_IF)
essid = b"MicroPython-%s" % ubinascii.hexlify(ap_if.config("mac")[-3:]) essid = b"MicroPython-%s" % ubinascii.hexlify(ap_if.config("mac")[-3:])
ap_if.config(essid=essid, authmode=network.AUTH_WPA_WPA2_PSK, password=b"micropythoN") ap_if.config(essid=essid, authmode=network.AUTH_WPA_WPA2_PSK, password=b"micropythoN")
def check_bootsec(): def check_bootsec():
buf = bytearray(bdev.SEC_SIZE) buf = bytearray(bdev.SEC_SIZE)
bdev.readblocks(0, buf) bdev.readblocks(0, buf)
empty = True empty = True
for b in buf: for b in buf:
if b != 0xff: if b != 0xFF:
empty = False empty = False
break break
if empty: if empty:
return True return True
fs_corrupted() fs_corrupted()
def fs_corrupted(): def fs_corrupted():
import time import time
while 1: while 1:
print("""\ print(
"""\
The FAT filesystem starting at sector %d with size %d sectors appears to The FAT filesystem starting at sector %d with size %d sectors appears to
be corrupted. If you had important data there, you may want to make a flash be corrupted. If you had important data there, you may want to make a flash
snapshot to try to recover it. Otherwise, perform factory reprogramming snapshot to try to recover it. Otherwise, perform factory reprogramming
of MicroPython firmware (completely erase flash, followed by firmware of MicroPython firmware (completely erase flash, followed by firmware
programming). programming).
""" % (bdev.START_SEC, bdev.blocks)) """
% (bdev.START_SEC, bdev.blocks)
)
time.sleep(3) time.sleep(3)
def setup(): def setup():
check_bootsec() check_bootsec()
print("Performing initial setup") print("Performing initial setup")
wifi() wifi()
uos.VfsFat.mkfs(bdev) uos.VfsFat.mkfs(bdev)
vfs = uos.VfsFat(bdev) vfs = uos.VfsFat(bdev)
uos.mount(vfs, '/') uos.mount(vfs, "/")
with open("boot.py", "w") as f: with open("boot.py", "w") as f:
f.write("""\ f.write(
"""\
# This file is executed on every boot (including wake-boot from deepsleep) # This file is executed on every boot (including wake-boot from deepsleep)
#import esp #import esp
#esp.osdebug(None) #esp.osdebug(None)
@ -50,5 +60,6 @@ import gc
#import webrepl #import webrepl
#webrepl.start() #webrepl.start()
gc.collect() gc.collect()
""") """
)
return vfs return vfs

View File

@ -21,8 +21,7 @@ class NeoPixel:
def __getitem__(self, index): def __getitem__(self, index):
offset = index * self.bpp offset = index * self.bpp
return tuple(self.buf[offset + self.ORDER[i]] return tuple(self.buf[offset + self.ORDER[i]] for i in range(self.bpp))
for i in range(self.bpp))
def fill(self, color): def fill(self, color):
for i in range(self.n): for i in range(self.n):

View File

@ -13,9 +13,10 @@ NTP_DELTA = 3155673600
# The NTP host can be configured at runtime by doing: ntptime.host = 'myhost.org' # The NTP host can be configured at runtime by doing: ntptime.host = 'myhost.org'
host = "pool.ntp.org" host = "pool.ntp.org"
def time(): def time():
NTP_QUERY = bytearray(48) NTP_QUERY = bytearray(48)
NTP_QUERY[0] = 0x1b NTP_QUERY[0] = 0x1B
addr = socket.getaddrinfo(host, 123)[0][-1] addr = socket.getaddrinfo(host, 123)[0][-1]
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try: try:
@ -27,11 +28,13 @@ def time():
val = struct.unpack("!I", msg[40:44])[0] val = struct.unpack("!I", msg[40:44])[0]
return val - NTP_DELTA return val - NTP_DELTA
# There's currently no timezone support in MicroPython, so # There's currently no timezone support in MicroPython, so
# utime.localtime() will return UTC time (as if it was .gmtime()) # utime.localtime() will return UTC time (as if it was .gmtime())
def settime(): def settime():
t = time() t = time()
import machine import machine
import utime import utime
tm = utime.localtime(t) tm = utime.localtime(t)
machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0)) machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))

View File

@ -10,13 +10,16 @@ def main():
fid = esp.flash_id() fid = esp.flash_id()
print("FlashROM:") print("FlashROM:")
print("Flash ID: %x (Vendor: %x Device: %x)" % (fid, fid & 0xff, fid & 0xff00 | fid >> 16)) print("Flash ID: %x (Vendor: %x Device: %x)" % (fid, fid & 0xFF, fid & 0xFF00 | fid >> 16))
print("Flash bootloader data:") print("Flash bootloader data:")
SZ_MAP = {0: "512KB", 1: "256KB", 2: "1MB", 3: "2MB", 4: "4MB"} SZ_MAP = {0: "512KB", 1: "256KB", 2: "1MB", 3: "2MB", 4: "4MB"}
FREQ_MAP = {0: "40MHZ", 1: "26MHZ", 2: "20MHz", 0xf: "80MHz"} FREQ_MAP = {0: "40MHZ", 1: "26MHZ", 2: "20MHz", 0xF: "80MHz"}
print("Byte @2: %02x" % ROM[2]) print("Byte @2: %02x" % ROM[2])
print("Byte @3: %02x (Flash size: %s Flash freq: %s)" % (ROM[3], SZ_MAP.get(ROM[3] >> 4, "?"), FREQ_MAP.get(ROM[3] & 0xf))) print(
"Byte @3: %02x (Flash size: %s Flash freq: %s)"
% (ROM[3], SZ_MAP.get(ROM[3] >> 4, "?"), FREQ_MAP.get(ROM[3] & 0xF))
)
print("Firmware checksum:") print("Firmware checksum:")
print(esp.check_fw()) print(esp.check_fw())
@ -24,7 +27,9 @@ def main():
print("STA ifconfig:", network.WLAN(network.STA_IF).ifconfig()) print("STA ifconfig:", network.WLAN(network.STA_IF).ifconfig())
print("AP ifconfig:", network.WLAN(network.AP_IF).ifconfig()) print("AP ifconfig:", network.WLAN(network.AP_IF).ifconfig())
print("Free WiFi driver buffers of type:") print("Free WiFi driver buffers of type:")
for i, comm in enumerate(("1,2 TX", "4 Mngmt TX(len: 0x41-0x100)", "5 Mngmt TX (len: 0-0x40)", "7", "8 RX")): for i, comm in enumerate(
("1,2 TX", "4 Mngmt TX(len: 0x41-0x100)", "5 Mngmt TX (len: 0-0x40)", "7", "8 RX")
):
print("%d: %d (%s)" % (i, esp.esf_free_bufs(i), comm)) print("%d: %d (%s)" % (i, esp.esf_free_bufs(i), comm))
print("lwIP PCBs:") print("lwIP PCBs:")
lwip.print_pcbs() lwip.print_pcbs()

View File

@ -131,11 +131,15 @@ mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs)
MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open); MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
void nlr_jump_fail(void *val) { void nlr_jump_fail(void *val) {
while (1); while (1) {
;
}
} }
void NORETURN __fatal_error(const char *msg) { void NORETURN __fatal_error(const char *msg) {
while (1); while (1) {
;
}
} }
#ifndef NDEBUG #ifndef NDEBUG

View File

@ -1,7 +1,7 @@
print('uPy') print("uPy")
print('a long string that is not interned') print("a long string that is not interned")
print('a string that has unicode αβγ chars') print("a string that has unicode αβγ chars")
print(b'bytes 1234\x01') print(b"bytes 1234\x01")
print(123456789) print(123456789)
for i in range(4): for i in range(4):
print(i) print(i)

View File

@ -84,11 +84,15 @@ mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs)
MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open); MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
void nlr_jump_fail(void *val) { void nlr_jump_fail(void *val) {
while (1); while (1) {
;
}
} }
void NORETURN __fatal_error(const char *msg) { void NORETURN __fatal_error(const char *msg) {
while (1); while (1) {
;
}
} }
#ifndef NDEBUG #ifndef NDEBUG

Some files were not shown because too many files have changed in this diff Show More