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

This is run with uncrustify 0.70.1, and black 19.10b0.
diff --git a/drivers/dht/dht.py b/drivers/dht/dht.py
index eed61df..1163b38 100644
--- a/drivers/dht/dht.py
+++ b/drivers/dht/dht.py
@@ -6,6 +6,7 @@
 except:
     from pyb import dht_readinto
 
+
 class DHTBase:
     def __init__(self, pin):
         self.pin = pin
@@ -14,9 +15,10 @@
     def measure(self):
         buf = self.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")
 
+
 class DHT11(DHTBase):
     def humidity(self):
         return self.buf[0]
@@ -24,12 +26,13 @@
     def temperature(self):
         return self.buf[2]
 
+
 class DHT22(DHTBase):
     def humidity(self):
         return (self.buf[0] << 8 | self.buf[1]) * 0.1
 
     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:
             t = -t
         return t
diff --git a/drivers/display/lcd160cr.py b/drivers/display/lcd160cr.py
index cf562a4..f792418 100644
--- a/drivers/display/lcd160cr.py
+++ b/drivers/display/lcd160cr.py
@@ -29,16 +29,17 @@
     460800: 8,
 }
 
+
 class LCD160CR:
     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]
             j = connect[0]
-            y = j + '4'
-        elif connect == 'C':
+            y = j + "4"
+        elif connect == "C":
             i = 2
             j = 2
-            y = 'A7'
+            y = "A7"
         else:
             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"')
@@ -74,8 +75,8 @@
 
         # set default orientation and window
         self.set_orient(PORTRAIT)
-        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", 0x76, 0, 0, self.w, self.h)  # viewport 'v'
+        self._fcmd2b("<BBBBBB", 0x79, 0, 0, self.w, self.h)  # window 'y'
 
     def _send(self, cmd):
         i = self.i2c.writeto(self.i2c_addr, cmd)
@@ -135,7 +136,7 @@
 
     @staticmethod
     def rgb(r, g, b):
-        return ((b & 0xf8) << 8) | ((g & 0xfc) << 3) | (r >> 3)
+        return ((b & 0xF8) << 8) | ((g & 0xFC) << 3) | (r >> 3)
 
     @staticmethod
     def clip_line(c, w, h):
@@ -207,43 +208,43 @@
         sleep_ms(15)
 
     def set_orient(self, orient):
-        self._fcmd2('<BBB', 0x14, (orient & 3) + 4)
+        self._fcmd2("<BBB", 0x14, (orient & 3) + 4)
         # update width and height variables
         self.iflush()
-        self._send(b'\x02g0')
+        self._send(b"\x02g0")
         self._waitfor(4, self.buf[5])
         self.w = self.buf[5][1]
         self.h = self.buf[5][2]
 
     def set_brightness(self, value):
-        self._fcmd2('<BBB', 0x16, value)
+        self._fcmd2("<BBB", 0x16, value)
 
     def set_i2c_addr(self, addr):
         # 0x0e set i2c addr
         if addr & 3:
-            raise ValueError('must specify mod 4 aligned address')
-        self._fcmd2('<BBW', 0x0e, 0x433249 | (addr << 24))
+            raise ValueError("must specify mod 4 aligned address")
+        self._fcmd2("<BBW", 0x0E, 0x433249 | (addr << 24))
 
     def set_uart_baudrate(self, baudrate):
         try:
             baudrate = _uart_baud_table[baudrate]
         except KeyError:
-            raise ValueError('invalid baudrate')
-        self._fcmd2('<BBB', 0x18, baudrate)
+            raise ValueError("invalid baudrate")
+        self._fcmd2("<BBB", 0x18, baudrate)
 
     def set_startup_deco(self, value):
-        self._fcmd2('<BBB', 0x19, value)
+        self._fcmd2("<BBB", 0x19, value)
 
     def save_to_flash(self):
-        self._send(b'\x02fn')
+        self._send(b"\x02fn")
 
     #### PIXEL ACCESS ####
 
     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):
-        self._fcmd2('<BBBB', 0x61, x, y)
+        self._fcmd2("<BBBB", 0x61, x, y)
         t = 1000
         while t:
             self.i2c.readfrom_into(self.i2c_addr, self.buf1)
@@ -256,7 +257,7 @@
 
     def get_line(self, x, y, buf):
         l = len(buf) // 2
-        self._fcmd2b('<BBBBB', 0x10, l, x, y)
+        self._fcmd2b("<BBBBB", 0x10, l, x, y)
         l *= 2
         t = 1000
         while t:
@@ -280,42 +281,47 @@
             # split line if more than 254 bytes needed
             buflen = (w + 1) // 2
             line = bytearray(2 * buflen + 1)
-            line2 = memoryview(line)[:2 * (w - buflen) + 1]
+            line2 = memoryview(line)[: 2 * (w - buflen) + 1]
         for i in range(min(len(buf) // (2 * w), h)):
             ix = i * w * 2
             self.get_line(x, y + i, line)
-            buf[ix:ix + len(line) - 1] = memoryview(line)[1:]
+            buf[ix : ix + len(line) - 1] = memoryview(line)[1:]
             ix += len(line) - 1
             if line2:
                 self.get_line(x + buflen, y + i, line2)
-                buf[ix:ix + len(line2) - 1] = memoryview(line2)[1:]
+                buf[ix : ix + len(line2) - 1] = memoryview(line2)[1:]
                 ix += len(line2) - 1
 
     def screen_load(self, buf):
-        l = self.w * self.h * 2+2
-        self._fcmd2b('<BBHBBB', 0x70, l, 16, self.w, self.h)
+        l = self.w * self.h * 2 + 2
+        self._fcmd2b("<BBHBBB", 0x70, l, 16, self.w, self.h)
         n = 0
         ar = memoryview(buf)
         while n < len(buf):
             if len(buf) - n >= 0x200:
-                self._send(ar[n:n + 0x200])
+                self._send(ar[n : n + 0x200])
                 n += 0x200
             else:
                 self._send(ar[n:])
                 while n < self.w * self.h * 2:
-                    self._send(b'\x00')
+                    self._send(b"\x00")
                     n += 1
 
     #### TEXT COMMANDS ####
 
     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):
-        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):
-        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):
         # TODO: eventually check for room in LCD input queue
@@ -324,14 +330,14 @@
     #### PRIMITIVE DRAWING COMMANDS ####
 
     def set_pen(self, line, fill):
-        self._fcmd2('<BBHH', 0x50, line, fill)
+        self._fcmd2("<BBHH", 0x50, line, fill)
 
     def erase(self):
-        self._send(b'\x02\x45')
+        self._send(b"\x02\x45")
 
     def dot(self, x, y):
         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):
         if x + w <= 0 or y + h <= 0 or x >= self.w or y >= self.h:
@@ -348,19 +354,19 @@
                 y = 0
             if cmd == 0x51 or cmd == 0x72:
                 # 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:
                 # draw outline
                 if left:
-                    self._fcmd2b('<BBBBBB', 0x57, x, y, 1, min(h, 255))
+                    self._fcmd2b("<BBBBBB", 0x57, x, y, 1, min(h, 255))
                 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:
-                    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:
-                    self._fcmd2b('<BBBBBB', 0x57, x, y + h, min(w, 255), 1)
+                    self._fcmd2b("<BBBBBB", 0x57, x, y + h, min(w, 255), 1)
         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):
         self.rect(x, y, w, h, 0x57)
@@ -375,48 +381,48 @@
         ar4[2] = x2
         ar4[3] = y2
         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):
-        self._fcmd2('<BBBB', 0x4b, x, y)
+        self._fcmd2("<BBBB", 0x4B, x, y)
 
     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):
-        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):
-        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):
-        self._fcmd2b('<BBBBBB', 0x4c, x1, y1, x2, y2)
+        self._fcmd2b("<BBBBBB", 0x4C, x1, y1, x2, y2)
 
     def poly_dot(self, data):
         if len(data) & 1:
-            raise ValueError('must specify even number of bytes')
-        self._fcmd2('<BBB', 0x71, len(data) // 2)
+            raise ValueError("must specify even number of bytes")
+        self._fcmd2("<BBB", 0x71, len(data) // 2)
         self._send(data)
 
     def poly_line(self, data):
         if len(data) & 1:
-            raise ValueError('must specify even number of bytes')
-        self._fcmd2('<BBB', 0x78, len(data) // 2)
+            raise ValueError("must specify even number of bytes")
+        self._fcmd2("<BBB", 0x78, len(data) // 2)
         self._send(data)
 
     #### TOUCH COMMANDS ####
 
     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):
-        self._send(b'\x02T')
+        self._send(b"\x02T")
         b = self.buf[4]
         self._waitfor(3, b)
         return b[1] >> 7 != 0
 
     def get_touch(self):
-        self._send(b'\x02T') # implicit LCD output flush
+        self._send(b"\x02T")  # implicit LCD output flush
         b = self.buf[4]
         self._waitfor(3, b)
         return b[1] >> 7, b[2], b[3]
@@ -424,11 +430,13 @@
     #### ADVANCED COMMANDS ####
 
     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)
 
     def fast_spi(self, flush=True):
-        self._send(b'\x02\x12')
+        self._send(b"\x02\x12")
         if flush:
             self.oflush()
         return self.spi
@@ -437,27 +445,27 @@
         self.fast_spi().write(buf)
 
     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):
-        pack_into('<BBBHHHHHHHH', self.buf19, 0, 2, 0x55, win, x, y, w, h, vec, pat, fill, color)
+    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)
         self._send(self.buf19)
 
     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):
         l = len(s)
         if l > 32:
-            raise ValueError('length must be 32 or less')
-        self._fcmd2('<BBB', 0x11, l)
+            raise ValueError("length must be 32 or less")
+        self._fcmd2("<BBB", 0x11, l)
         self._send(s)
 
     def jpeg_start(self, l):
-        if l > 0xffff:
-            raise ValueError('length must be 65535 or less')
+        if l > 0xFFFF:
+            raise ValueError("length must be 65535 or less")
         self.oflush()
-        self._fcmd2('<BBH', 0x6a, l)
+        self._fcmd2("<BBH", 0x6A, l)
 
     def jpeg_data(self, buf):
         self._send(buf)
@@ -467,8 +475,8 @@
         self.jpeg_data(buf)
 
     def feed_wdt(self):
-        self._send(b'\x02\x17')
+        self._send(b"\x02\x17")
 
     def reset(self):
-        self._send(b'\x02Y\xef\xbe\xad\xde')
+        self._send(b"\x02Y\xef\xbe\xad\xde")
         sleep_ms(15)
diff --git a/drivers/display/lcd160cr_test.py b/drivers/display/lcd160cr_test.py
index 8b7ef45..883c7d3 100644
--- a/drivers/display/lcd160cr_test.py
+++ b/drivers/display/lcd160cr_test.py
@@ -3,11 +3,13 @@
 
 import time, math, framebuf, lcd160cr
 
+
 def get_lcd(lcd):
     if type(lcd) is str:
         lcd = lcd160cr.LCD160CR(lcd)
     return lcd
 
+
 def show_adc(lcd, adc):
     data = [adc.read_core_temp(), adc.read_core_vbat(), 3.3]
     try:
@@ -21,24 +23,26 @@
             lcd.set_pos(0, 100 + i * 16)
         else:
             lcd.set_font(2, trans=1)
-            lcd.set_pos(0, lcd.h-60 + i * 16)
-        lcd.write('%4s: ' % ('TEMP', 'VBAT', 'VREF')[i])
+            lcd.set_pos(0, lcd.h - 60 + i * 16)
+        lcd.write("%4s: " % ("TEMP", "VBAT", "VREF")[i])
         if i > 0:
-            s = '%6.3fV' % data[i]
+            s = "%6.3fV" % data[i]
         else:
-            s = '%5.1f°C' % data[i]
+            s = "%5.1f°C" % data[i]
         if lcd.h == 160:
             lcd.set_font(1, bold=0, scale=1)
         else:
             lcd.set_font(1, bold=0, scale=1, trans=1)
-            lcd.set_pos(45, lcd.h-60 + i * 16)
+            lcd.set_pos(45, lcd.h - 60 + i * 16)
         lcd.write(s)
 
+
 def test_features(lcd, orient=lcd160cr.PORTRAIT):
     # if we run on pyboard then use ADC and RTC features
     try:
         import pyb
-        adc = pyb.ADCAll(12, 0xf0000)
+
+        adc = pyb.ADCAll(12, 0xF0000)
         rtc = pyb.RTC()
     except:
         adc = None
@@ -53,7 +57,7 @@
     # create M-logo
     mlogo = framebuf.FrameBuffer(bytearray(17 * 17 * 2), 17, 17, framebuf.RGB565)
     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(8, 1, 12, 0)
     mlogo.vline(12, 4, 12, 0)
@@ -80,15 +84,18 @@
             if tx2 >= 0 and ty2 >= 0 and tx2 < w and ty2 < h:
                 tx, ty = tx2, ty2
         else:
-             tx = (tx + 1) % w
-             ty = (ty + 1) % h
+            tx = (tx + 1) % w
+            ty = (ty + 1) % h
 
         # create and show the inline framebuf
         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)),
             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.vline(tx, 0, h, lcd.rgb(64, 64, 64))
         fbuf.rect(tx - 3, ty - 3, 7, 7, lcd.rgb(64, 64, 64))
@@ -97,9 +104,12 @@
             y = h // 2 - 8 + int(32 * math.sin(0.05 * i + phase))
             fbuf.blit(mlogo, x, y)
         for j in range(-3, 3):
-            fbuf.text('MicroPython',
-                5, h // 2 + 9 * j + int(20 * math.sin(0.1 * (i + j))),
-                lcd.rgb(128 + 10 * j, 0, 128 - 10 * j))
+            fbuf.text(
+                "MicroPython",
+                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)
 
         # show results from the ADC
@@ -111,7 +121,10 @@
             lcd.set_pos(2, 0)
             lcd.set_font(1)
             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
         t1 = time.ticks_us()
@@ -120,13 +133,14 @@
 
         # show the frame rate
         lcd.set_pos(2, 9)
-        lcd.write('%.2f fps' % (1000000 / dt))
+        lcd.write("%.2f fps" % (1000000 / dt))
+
 
 def test_mandel(lcd, orient=lcd160cr.PORTRAIT):
     # set orientation and clear screen
     lcd = get_lcd(lcd)
     lcd.set_orient(orient)
-    lcd.set_pen(0, 0xffff)
+    lcd.set_pen(0, 0xFFFF)
     lcd.erase()
 
     # function to compute Mandelbrot pixels
@@ -148,24 +162,26 @@
     spi = lcd.fast_spi()
 
     # draw the Mandelbrot set line-by-line
-    hh = ((h - 1) / 3.2)
-    ww = ((w - 1) / 2.4)
+    hh = (h - 1) / 3.2
+    ww = (w - 1) / 2.4
     for v in range(h):
         for u in range(w):
             c = in_set((v / hh - 2.3) + (u / ww - 1.2) * 1j)
             if c < 16:
                 rgb = c << 12 | c << 6
             else:
-                rgb = 0xf800 | c << 6
+                rgb = 0xF800 | c << 6
             line[2 * u] = rgb
             line[2 * u + 1] = rgb >> 8
         spi.write(line)
 
+
 def test_all(lcd, orient=lcd160cr.PORTRAIT):
     lcd = get_lcd(lcd)
     test_features(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')
diff --git a/drivers/display/ssd1306.py b/drivers/display/ssd1306.py
index f93a451..4893b20 100644
--- a/drivers/display/ssd1306.py
+++ b/drivers/display/ssd1306.py
@@ -5,23 +5,23 @@
 
 
 # register definitions
-SET_CONTRAST        = const(0x81)
-SET_ENTIRE_ON       = const(0xa4)
-SET_NORM_INV        = const(0xa6)
-SET_DISP            = const(0xae)
-SET_MEM_ADDR        = const(0x20)
-SET_COL_ADDR        = const(0x21)
-SET_PAGE_ADDR       = const(0x22)
+SET_CONTRAST = const(0x81)
+SET_ENTIRE_ON = const(0xA4)
+SET_NORM_INV = const(0xA6)
+SET_DISP = const(0xAE)
+SET_MEM_ADDR = const(0x20)
+SET_COL_ADDR = const(0x21)
+SET_PAGE_ADDR = const(0x22)
 SET_DISP_START_LINE = const(0x40)
-SET_SEG_REMAP       = const(0xa0)
-SET_MUX_RATIO       = const(0xa8)
-SET_COM_OUT_DIR     = const(0xc0)
-SET_DISP_OFFSET     = const(0xd3)
-SET_COM_PIN_CFG     = const(0xda)
-SET_DISP_CLK_DIV    = const(0xd5)
-SET_PRECHARGE       = const(0xd9)
-SET_VCOM_DESEL      = const(0xdb)
-SET_CHARGE_PUMP     = const(0x8d)
+SET_SEG_REMAP = const(0xA0)
+SET_MUX_RATIO = const(0xA8)
+SET_COM_OUT_DIR = const(0xC0)
+SET_DISP_OFFSET = const(0xD3)
+SET_COM_PIN_CFG = const(0xDA)
+SET_DISP_CLK_DIV = const(0xD5)
+SET_PRECHARGE = const(0xD9)
+SET_VCOM_DESEL = const(0xDB)
+SET_CHARGE_PUMP = const(0x8D)
 
 # Subclassing FrameBuffer provides support for graphics primitives
 # http://docs.micropython.org/en/latest/pyboard/library/framebuf.html
@@ -37,27 +37,37 @@
 
     def init_display(self):
         for cmd in (
-            SET_DISP | 0x00, # off
+            SET_DISP | 0x00,  # off
             # address setting
-            SET_MEM_ADDR, 0x00, # horizontal
+            SET_MEM_ADDR,
+            0x00,  # horizontal
             # resolution and layout
             SET_DISP_START_LINE | 0x00,
-            SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0
-            SET_MUX_RATIO, self.height - 1,
-            SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0
-            SET_DISP_OFFSET, 0x00,
-            SET_COM_PIN_CFG, 0x02 if self.height == 32 else 0x12,
+            SET_SEG_REMAP | 0x01,  # column addr 127 mapped to SEG0
+            SET_MUX_RATIO,
+            self.height - 1,
+            SET_COM_OUT_DIR | 0x08,  # scan from COM[N] to COM0
+            SET_DISP_OFFSET,
+            0x00,
+            SET_COM_PIN_CFG,
+            0x02 if self.height == 32 else 0x12,
             # timing and driving scheme
-            SET_DISP_CLK_DIV, 0x80,
-            SET_PRECHARGE, 0x22 if self.external_vcc else 0xf1,
-            SET_VCOM_DESEL, 0x30, # 0.83*Vcc
+            SET_DISP_CLK_DIV,
+            0x80,
+            SET_PRECHARGE,
+            0x22 if self.external_vcc else 0xF1,
+            SET_VCOM_DESEL,
+            0x30,  # 0.83*Vcc
             # display
-            SET_CONTRAST, 0xff, # maximum
-            SET_ENTIRE_ON, # output follows RAM contents
-            SET_NORM_INV, # not inverted
+            SET_CONTRAST,
+            0xFF,  # maximum
+            SET_ENTIRE_ON,  # output follows RAM contents
+            SET_NORM_INV,  # not inverted
             # charge pump
-            SET_CHARGE_PUMP, 0x10 if self.external_vcc else 0x14,
-            SET_DISP | 0x01): # on
+            SET_CHARGE_PUMP,
+            0x10 if self.external_vcc else 0x14,
+            SET_DISP | 0x01,
+        ):  # on
             self.write_cmd(cmd)
         self.fill(0)
         self.show()
@@ -92,15 +102,15 @@
 
 
 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.addr = addr
         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)
 
     def write_cmd(self, cmd):
-        self.temp[0] = 0x80 # Co=1, D/C#=0
+        self.temp[0] = 0x80  # Co=1, D/C#=0
         self.temp[1] = cmd
         self.i2c.writeto(self.addr, self.temp)
 
@@ -120,6 +130,7 @@
         self.res = res
         self.cs = cs
         import time
+
         self.res(1)
         time.sleep_ms(1)
         self.res(0)
diff --git a/drivers/nrf24l01/nrf24l01.py b/drivers/nrf24l01/nrf24l01.py
index a95d2b5..76d5531 100644
--- a/drivers/nrf24l01/nrf24l01.py
+++ b/drivers/nrf24l01/nrf24l01.py
@@ -5,49 +5,50 @@
 import utime
 
 # nRF24L01+ registers
-CONFIG      = const(0x00)
-EN_RXADDR   = const(0x02)
-SETUP_AW    = const(0x03)
-SETUP_RETR  = const(0x04)
-RF_CH       = const(0x05)
-RF_SETUP    = const(0x06)
-STATUS      = const(0x07)
-RX_ADDR_P0  = const(0x0a)
-TX_ADDR     = const(0x10)
-RX_PW_P0    = const(0x11)
+CONFIG = const(0x00)
+EN_RXADDR = const(0x02)
+SETUP_AW = const(0x03)
+SETUP_RETR = const(0x04)
+RF_CH = const(0x05)
+RF_SETUP = const(0x06)
+STATUS = const(0x07)
+RX_ADDR_P0 = const(0x0A)
+TX_ADDR = const(0x10)
+RX_PW_P0 = const(0x11)
 FIFO_STATUS = const(0x17)
-DYNPD	    = const(0x1c)
+DYNPD = const(0x1C)
 
 # CONFIG register
-EN_CRC      = const(0x08) # enable CRC
-CRCO        = const(0x04) # CRC encoding scheme; 0=1 byte, 1=2 bytes
-PWR_UP      = const(0x02) # 1=power up, 0=power down
-PRIM_RX     = const(0x01) # RX/TX control; 0=PTX, 1=PRX
+EN_CRC = const(0x08)  # enable CRC
+CRCO = const(0x04)  # CRC encoding scheme; 0=1 byte, 1=2 bytes
+PWR_UP = const(0x02)  # 1=power up, 0=power down
+PRIM_RX = const(0x01)  # RX/TX control; 0=PTX, 1=PRX
 
 # RF_SETUP register
-POWER_0     = const(0x00) # -18 dBm
-POWER_1     = const(0x02) # -12 dBm
-POWER_2     = const(0x04) # -6 dBm
-POWER_3     = const(0x06) # 0 dBm
-SPEED_1M    = const(0x00)
-SPEED_2M    = const(0x08)
-SPEED_250K  = const(0x20)
+POWER_0 = const(0x00)  # -18 dBm
+POWER_1 = const(0x02)  # -12 dBm
+POWER_2 = const(0x04)  # -6 dBm
+POWER_3 = const(0x06)  # 0 dBm
+SPEED_1M = const(0x00)
+SPEED_2M = const(0x08)
+SPEED_250K = const(0x20)
 
 # STATUS register
-RX_DR       = const(0x40) # RX data ready; write 1 to clear
-TX_DS       = const(0x20) # TX data sent; write 1 to clear
-MAX_RT      = const(0x10) # max retransmits reached; write 1 to clear
+RX_DR = const(0x40)  # RX data ready; write 1 to clear
+TX_DS = const(0x20)  # TX data sent; write 1 to clear
+MAX_RT = const(0x10)  # max retransmits reached; write 1 to clear
 
 # FIFO_STATUS register
-RX_EMPTY    = const(0x01) # 1 if RX FIFO is empty
+RX_EMPTY = const(0x01)  # 1 if RX FIFO is empty
 
 # constants for instructions
-R_RX_PL_WID  = const(0x60) # read RX payload width
-R_RX_PAYLOAD = const(0x61) # read RX payload
-W_TX_PAYLOAD = const(0xa0) # write TX payload
-FLUSH_TX     = const(0xe1) # flush TX FIFO
-FLUSH_RX     = const(0xe2) # flush RX FIFO
-NOP          = const(0xff) # use to read STATUS register
+R_RX_PL_WID = const(0x60)  # read RX payload width
+R_RX_PAYLOAD = const(0x61)  # read RX payload
+W_TX_PAYLOAD = const(0xA0)  # write TX payload
+FLUSH_TX = const(0xE1)  # flush TX FIFO
+FLUSH_RX = const(0xE2)  # flush RX FIFO
+NOP = const(0xFF)  # use to read STATUS register
+
 
 class NRF24L01:
     def __init__(self, spi, cs, ce, channel=46, payload_size=16):
@@ -84,7 +85,7 @@
         self.reg_write(SETUP_RETR, (6 << 4) | 8)
 
         # set rf power and speed
-        self.set_power_speed(POWER_3, SPEED_250K) # Best for point to point links
+        self.set_power_speed(POWER_3, SPEED_250K)  # Best for point to point links
 
         # init CRC
         self.set_crc(2)
@@ -218,7 +219,7 @@
         start = utime.ticks_ms()
         result = None
         while result is None and utime.ticks_diff(utime.ticks_ms(), start) < timeout:
-            result = self.send_done() # 1 == success, 2 == fail
+            result = self.send_done()  # 1 == success, 2 == fail
         if result == 2:
             raise OSError("send failed")
 
@@ -232,18 +233,18 @@
         self.spi.readinto(self.buf, W_TX_PAYLOAD)
         self.spi.write(buf)
         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)
 
         # enable the chip so it can send the data
         self.ce(1)
-        utime.sleep_us(15) # needs to be >10us
+        utime.sleep_us(15)  # needs to be >10us
         self.ce(0)
 
     # returns None if send still in progress, 1 for success, 2 for fail
     def send_done(self):
         if not (self.reg_read(STATUS) & (TX_DS | MAX_RT)):
-            return None # tx not finished
+            return None  # tx not finished
 
         # either finished or failed: get and clear status flags, power down
         status = self.reg_write(STATUS, RX_DR | TX_DS | MAX_RT)
diff --git a/drivers/nrf24l01/nrf24l01test.py b/drivers/nrf24l01/nrf24l01test.py
index 4db9571..14efbff 100644
--- a/drivers/nrf24l01/nrf24l01test.py
+++ b/drivers/nrf24l01/nrf24l01test.py
@@ -14,27 +14,28 @@
 # master may be a slow device. Value tested with Pyboard, ESP32 and ESP8266.
 _SLAVE_SEND_DELAY = const(10)
 
-if sys.platform == 'pyboard':
-    cfg = {'spi': 2, 'miso': 'Y7', 'mosi': 'Y8', 'sck': 'Y6', 'csn': 'Y5', 'ce': 'Y4'}
-elif sys.platform == 'esp8266':  # Hardware SPI
-    cfg = {'spi': 1, 'miso': 12, 'mosi': 13, 'sck': 14, 'csn': 4, 'ce': 5}
-elif sys.platform == 'esp32':  # Software SPI
-    cfg = {'spi': -1, 'miso': 32, 'mosi': 33, 'sck': 25, 'csn': 26, 'ce': 27}
+if sys.platform == "pyboard":
+    cfg = {"spi": 2, "miso": "Y7", "mosi": "Y8", "sck": "Y6", "csn": "Y5", "ce": "Y4"}
+elif sys.platform == "esp8266":  # Hardware SPI
+    cfg = {"spi": 1, "miso": 12, "mosi": 13, "sck": 14, "csn": 4, "ce": 5}
+elif sys.platform == "esp32":  # Software SPI
+    cfg = {"spi": -1, "miso": 32, "mosi": 33, "sck": 25, "csn": 26, "ce": 27}
 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
 # 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():
-    csn = Pin(cfg['csn'], mode=Pin.OUT, value=1)
-    ce = Pin(cfg['ce'], mode=Pin.OUT, value=0)
-    if cfg['spi'] == -1:
-        spi = SPI(-1, sck=Pin(cfg['sck']), mosi=Pin(cfg['mosi']), miso=Pin(cfg['miso']))
+    csn = Pin(cfg["csn"], mode=Pin.OUT, value=1)
+    ce = Pin(cfg["ce"], mode=Pin.OUT, value=0)
+    if cfg["spi"] == -1:
+        spi = SPI(-1, sck=Pin(cfg["sck"]), mosi=Pin(cfg["mosi"]), miso=Pin(cfg["miso"]))
         nrf = NRF24L01(spi, csn, ce, payload_size=8)
     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_rx_pipe(1, pipes[1])
@@ -45,16 +46,16 @@
     num_failures = 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:
         # stop listening and send packet
         nrf.stop_listening()
         millis = utime.ticks_ms()
-        led_state = max(1, (led_state << 1) & 0x0f)
-        print('sending:', millis, led_state)
+        led_state = max(1, (led_state << 1) & 0x0F)
+        print("sending:", millis, led_state)
         try:
-            nrf.send(struct.pack('ii', millis, led_state))
+            nrf.send(struct.pack("ii", millis, led_state))
         except OSError:
             pass
 
@@ -69,43 +70,50 @@
                 timeout = True
 
         if timeout:
-            print('failed, response timed out')
+            print("failed, response timed out")
             num_failures += 1
 
         else:
             # recv packet
-            got_millis, = struct.unpack('i', nrf.recv())
+            (got_millis,) = struct.unpack("i", nrf.recv())
 
             # 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
 
         # delay then loop
         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():
-    csn = Pin(cfg['csn'], mode=Pin.OUT, value=1)
-    ce = Pin(cfg['ce'], mode=Pin.OUT, value=0)
-    if cfg['spi'] == -1:
-        spi = SPI(-1, sck=Pin(cfg['sck']), mosi=Pin(cfg['mosi']), miso=Pin(cfg['miso']))
+    csn = Pin(cfg["csn"], mode=Pin.OUT, value=1)
+    ce = Pin(cfg["ce"], mode=Pin.OUT, value=0)
+    if cfg["spi"] == -1:
+        spi = SPI(-1, sck=Pin(cfg["sck"]), mosi=Pin(cfg["mosi"]), miso=Pin(cfg["miso"]))
         nrf = NRF24L01(spi, csn, ce, payload_size=8)
     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_rx_pipe(1, pipes[0])
     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:
         if nrf.any():
             while nrf.any():
                 buf = nrf.recv()
-                millis, led_state = struct.unpack('ii', buf)
-                print('received:', millis, led_state)
+                millis, led_state = struct.unpack("ii", buf)
+                print("received:", millis, led_state)
                 for led in leds:
                     if led_state & 1:
                         led.on()
@@ -118,23 +126,25 @@
             utime.sleep_ms(_SLAVE_SEND_DELAY)
             nrf.stop_listening()
             try:
-                nrf.send(struct.pack('i', millis))
+                nrf.send(struct.pack("i", millis))
             except OSError:
                 pass
-            print('sent response')
+            print("sent response")
             nrf.start_listening()
 
+
 try:
     import pyb
+
     leds = [pyb.LED(i + 1) for i in range(4)]
 except:
     leds = []
 
-print('NRF24L01 test module loaded')
-print('NRF24L01 pinout for test:')
-print('    CE on', cfg['ce'])
-print('    CSN on', cfg['csn'])
-print('    SCK on', cfg['sck'])
-print('    MISO on', cfg['miso'])
-print('    MOSI on', cfg['mosi'])
-print('run nrf24l01test.slave() on slave, then nrf24l01test.master() on master')
+print("NRF24L01 test module loaded")
+print("NRF24L01 pinout for test:")
+print("    CE on", cfg["ce"])
+print("    CSN on", cfg["csn"])
+print("    SCK on", cfg["sck"])
+print("    MISO on", cfg["miso"])
+print("    MOSI on", cfg["mosi"])
+print("run nrf24l01test.slave() on slave, then nrf24l01test.master() on master")
diff --git a/drivers/onewire/ds18x20.py b/drivers/onewire/ds18x20.py
index 2726422..ad2d9f5 100644
--- a/drivers/onewire/ds18x20.py
+++ b/drivers/onewire/ds18x20.py
@@ -4,8 +4,9 @@
 from micropython import const
 
 _CONVERT = const(0x44)
-_RD_SCRATCH = const(0xbe)
-_WR_SCRATCH = const(0x4e)
+_RD_SCRATCH = const(0xBE)
+_WR_SCRATCH = const(0x4E)
+
 
 class DS18X20:
     def __init__(self, onewire):
@@ -26,7 +27,7 @@
         self.ow.writebyte(_RD_SCRATCH)
         self.ow.readinto(self.buf)
         if self.ow.crc8(self.buf):
-            raise Exception('CRC error')
+            raise Exception("CRC error")
         return self.buf
 
     def write_scratch(self, rom, buf):
@@ -40,12 +41,12 @@
         if rom[0] == 0x10:
             if buf[1]:
                 t = buf[0] >> 1 | 0x80
-                t = -((~t + 1) & 0xff)
+                t = -((~t + 1) & 0xFF)
             else:
                 t = buf[0] >> 1
             return t - 0.25 + (buf[7] - buf[6]) / buf[7]
         else:
             t = buf[1] << 8 | buf[0]
-            if t & 0x8000: # sign bit set
-                t = -((t ^ 0xffff) + 1)
+            if t & 0x8000:  # sign bit set
+                t = -((t ^ 0xFFFF) + 1)
             return t / 16
diff --git a/drivers/onewire/onewire.py b/drivers/onewire/onewire.py
index 3309ba0..dd8c274 100644
--- a/drivers/onewire/onewire.py
+++ b/drivers/onewire/onewire.py
@@ -4,13 +4,15 @@
 from micropython import const
 import _onewire as _ow
 
+
 class OneWireError(Exception):
     pass
 
+
 class OneWire:
-    SEARCH_ROM = const(0xf0)
+    SEARCH_ROM = const(0xF0)
     MATCH_ROM = const(0x55)
-    SKIP_ROM = const(0xcc)
+    SKIP_ROM = const(0xCC)
 
     def __init__(self, pin):
         self.pin = pin
@@ -51,7 +53,7 @@
         devices = []
         diff = 65
         rom = False
-        for i in range(0xff):
+        for i in range(0xFF):
             rom, diff = self._search_rom(rom, diff)
             if rom:
                 devices += [rom]
@@ -73,10 +75,10 @@
             for bit in range(8):
                 b = self.readbit()
                 if self.readbit():
-                    if b: # there are no devices or there is an error on the bus
+                    if b:  # there are no devices or there is an error on the bus
                         return None, 0
                 else:
-                    if not b: # collision, two devices with different bit meaning
+                    if not b:  # collision, two devices with different bit meaning
                         if diff > i or ((l_rom[byte] & (1 << bit)) and diff != i):
                             b = 1
                             next_diff = i
diff --git a/drivers/sdcard/sdcard.py b/drivers/sdcard/sdcard.py
index fc67875..c991fe5 100644
--- a/drivers/sdcard/sdcard.py
+++ b/drivers/sdcard/sdcard.py
@@ -27,15 +27,15 @@
 _CMD_TIMEOUT = const(100)
 
 _R1_IDLE_STATE = const(1 << 0)
-#R1_ERASE_RESET = const(1 << 1)
+# R1_ERASE_RESET = const(1 << 1)
 _R1_ILLEGAL_COMMAND = const(1 << 2)
-#R1_COM_CRC_ERROR = const(1 << 3)
-#R1_ERASE_SEQUENCE_ERROR = const(1 << 4)
-#R1_ADDRESS_ERROR = const(1 << 5)
-#R1_PARAMETER_ERROR = const(1 << 6)
-_TOKEN_CMD25 = const(0xfc)
-_TOKEN_STOP_TRAN = const(0xfd)
-_TOKEN_DATA = const(0xfe)
+# R1_COM_CRC_ERROR = const(1 << 3)
+# R1_ERASE_SEQUENCE_ERROR = const(1 << 4)
+# R1_ADDRESS_ERROR = const(1 << 5)
+# R1_PARAMETER_ERROR = const(1 << 6)
+_TOKEN_CMD25 = const(0xFC)
+_TOKEN_STOP_TRAN = const(0xFD)
+_TOKEN_DATA = const(0xFE)
 
 
 class SDCard:
@@ -47,7 +47,7 @@
         self.dummybuf = bytearray(512)
         self.tokenbuf = bytearray(1)
         for i in range(512):
-            self.dummybuf[i] = 0xff
+            self.dummybuf[i] = 0xFF
         self.dummybuf_memoryview = memoryview(self.dummybuf)
 
         # initialise the card
@@ -72,7 +72,7 @@
 
         # clock card at least 100 cycles with cs high
         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)
         for _ in range(5):
@@ -82,7 +82,7 @@
             raise OSError("no SD card")
 
         # CMD8: determine card version
-        r = self.cmd(8, 0x01aa, 0x87, 4)
+        r = self.cmd(8, 0x01AA, 0x87, 4)
         if r == _R1_IDLE_STATE:
             self.init_card_v2()
         elif r == (_R1_IDLE_STATE | _R1_ILLEGAL_COMMAND):
@@ -96,15 +96,15 @@
             raise OSError("no response from SD card")
         csd = bytearray(16)
         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
-        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_mult = ((csd[9] & 0b11) << 1) | csd[10] >> 7
             self.sectors = (c_size + 1) * (2 ** (c_size_mult + 2))
         else:
             raise OSError("SD card CSD format not supported")
-        #print('sectors', self.sectors)
+        # print('sectors', self.sectors)
 
         # CMD16: set block length to 512 bytes
         if self.cmd(16, 512, 0) != 0:
@@ -118,7 +118,7 @@
             self.cmd(55, 0, 0)
             if self.cmd(41, 0, 0) == 0:
                 self.cdv = 512
-                #print("[SDCard] v1 card")
+                # print("[SDCard] v1 card")
                 return
         raise OSError("timeout waiting for v1 card")
 
@@ -130,7 +130,7 @@
             if self.cmd(41, 0x40000000, 0) == 0:
                 self.cmd(58, 0, 0, 4)
                 self.cdv = 1
-                #print("[SDCard] v2 card")
+                # print("[SDCard] v2 card")
                 return
         raise OSError("timeout waiting for v2 card")
 
@@ -148,24 +148,24 @@
         self.spi.write(buf)
 
         if skip1:
-            self.spi.readinto(self.tokenbuf, 0xff)
+            self.spi.readinto(self.tokenbuf, 0xFF)
 
         # wait for the response (response[7] == 0)
         for i in range(_CMD_TIMEOUT):
-            self.spi.readinto(self.tokenbuf, 0xff)
+            self.spi.readinto(self.tokenbuf, 0xFF)
             response = self.tokenbuf[0]
             if not (response & 0x80):
                 # this could be a big-endian integer that we are getting here
                 for j in range(final):
-                    self.spi.write(b'\xff')
+                    self.spi.write(b"\xff")
                 if release:
                     self.cs(1)
-                    self.spi.write(b'\xff')
+                    self.spi.write(b"\xff")
                 return response
 
         # timeout
         self.cs(1)
-        self.spi.write(b'\xff')
+        self.spi.write(b"\xff")
         return -1
 
     def readinto(self, buf):
@@ -173,7 +173,7 @@
 
         # read until start byte (0xff)
         for i in range(_CMD_TIMEOUT):
-            self.spi.readinto(self.tokenbuf, 0xff)
+            self.spi.readinto(self.tokenbuf, 0xFF)
             if self.tokenbuf[0] == _TOKEN_DATA:
                 break
         else:
@@ -183,15 +183,15 @@
         # read data
         mv = self.dummybuf_memoryview
         if len(buf) != len(mv):
-            mv = mv[:len(buf)]
+            mv = mv[: len(buf)]
         self.spi.write_readinto(mv, buf)
 
         # 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.spi.write(b'\xff')
+        self.spi.write(b"\xff")
 
     def write(self, token, buf):
         self.cs(0)
@@ -199,42 +199,42 @@
         # send: start of block, data, checksum
         self.spi.read(1, token)
         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
-        if (self.spi.read(1, 0xff)[0] & 0x1f) != 0x05:
+        if (self.spi.read(1, 0xFF)[0] & 0x1F) != 0x05:
             self.cs(1)
-            self.spi.write(b'\xff')
+            self.spi.write(b"\xff")
             return
 
         # wait for write to finish
-        while self.spi.read(1, 0xff)[0] == 0:
+        while self.spi.read(1, 0xFF)[0] == 0:
             pass
 
         self.cs(1)
-        self.spi.write(b'\xff')
+        self.spi.write(b"\xff")
 
     def write_token(self, token):
         self.cs(0)
         self.spi.read(1, token)
-        self.spi.write(b'\xff')
+        self.spi.write(b"\xff")
         # wait for write to finish
-        while self.spi.read(1, 0xff)[0] == 0x00:
+        while self.spi.read(1, 0xFF)[0] == 0x00:
             pass
 
         self.cs(1)
-        self.spi.write(b'\xff')
+        self.spi.write(b"\xff")
 
     def readblocks(self, block_num, buf):
         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:
             # CMD17: set read address for single block
             if self.cmd(17, block_num * self.cdv, 0, release=False) != 0:
                 # release the card
                 self.cs(1)
-                raise OSError(5) # EIO
+                raise OSError(5)  # EIO
             # receive the data and release card
             self.readinto(buf)
         else:
@@ -242,7 +242,7 @@
             if self.cmd(18, block_num * self.cdv, 0, release=False) != 0:
                 # release the card
                 self.cs(1)
-                raise OSError(5) # EIO
+                raise OSError(5)  # EIO
             offset = 0
             mv = memoryview(buf)
             while nblocks:
@@ -250,23 +250,23 @@
                 self.readinto(mv[offset : offset + 512])
                 offset += 512
                 nblocks -= 1
-            if self.cmd(12, 0, 0xff, skip1=True):
-                raise OSError(5) # EIO
+            if self.cmd(12, 0, 0xFF, skip1=True):
+                raise OSError(5)  # EIO
 
     def writeblocks(self, block_num, buf):
         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:
             # CMD24: set write address for single block
             if self.cmd(24, block_num * self.cdv, 0) != 0:
-                raise OSError(5) # EIO
+                raise OSError(5)  # EIO
 
             # send the data
             self.write(_TOKEN_DATA, buf)
         else:
             # CMD25: set write address for first block
             if self.cmd(25, block_num * self.cdv, 0) != 0:
-                raise OSError(5) # EIO
+                raise OSError(5)  # EIO
             # send the data
             offset = 0
             mv = memoryview(buf)
@@ -277,5 +277,5 @@
             self.write_token(_TOKEN_STOP_TRAN)
 
     def ioctl(self, op, arg):
-        if op == 4: # get number of blocks
+        if op == 4:  # get number of blocks
             return self.sectors
diff --git a/drivers/sdcard/sdtest.py b/drivers/sdcard/sdtest.py
index 01fe65a..018ef7c 100644
--- a/drivers/sdcard/sdtest.py
+++ b/drivers/sdcard/sdtest.py
@@ -2,59 +2,60 @@
 # Peter hinch 30th Jan 2016
 import os, sdcard, machine
 
+
 def sdtest():
     spi = machine.SPI(1)
     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)
-    os.mount(vfs, '/fc')
-    print('Filesystem check')
-    print(os.listdir('/fc'))
+    os.mount(vfs, "/fc")
+    print("Filesystem check")
+    print(os.listdir("/fc"))
 
-    line = 'abcdefghijklmnopqrstuvwxyz\n'
-    lines = line * 200 # 5400 chars
-    short = '1234567890\n'
+    line = "abcdefghijklmnopqrstuvwxyz\n"
+    lines = line * 200  # 5400 chars
+    short = "1234567890\n"
 
-    fn = '/fc/rats.txt'
+    fn = "/fc/rats.txt"
     print()
-    print('Multiple block read/write')
-    with open(fn,'w') as f:
+    print("Multiple block read/write")
+    with open(fn, "w") as f:
         n = f.write(lines)
-        print(n, 'bytes written')
+        print(n, "bytes written")
         n = f.write(short)
-        print(n, 'bytes written')
+        print(n, "bytes written")
         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()
-        print(len(result1), 'bytes read')
+        print(len(result1), "bytes read")
 
-    fn = '/fc/rats1.txt'
+    fn = "/fc/rats1.txt"
     print()
-    print('Single block read/write')
-    with open(fn,'w') as f:
-        n = f.write(short) # one block
-        print(n, 'bytes written')
+    print("Single block read/write")
+    with open(fn, "w") as f:
+        n = f.write(short)  # one block
+        print(n, "bytes written")
 
-    with open(fn,'r') as f:
+    with open(fn, "r") as f:
         result2 = f.read()
-        print(len(result2), 'bytes read')
+        print(len(result2), "bytes read")
 
-    os.umount('/fc')
+    os.umount("/fc")
 
     print()
-    print('Verifying data read back')
+    print("Verifying data read back")
     success = True
-    if result1 == ''.join((lines, short, lines)):
-        print('Large file Pass')
+    if result1 == "".join((lines, short, lines)):
+        print("Large file Pass")
     else:
-        print('Large file Fail')
+        print("Large file Fail")
         success = False
     if result2 == short:
-        print('Small file Pass')
+        print("Small file Pass")
     else:
-        print('Small file Fail')
+        print("Small file Fail")
         success = False
     print()
-    print('Tests', 'passed' if success else 'failed')
+    print("Tests", "passed" if success else "failed")
diff --git a/examples/SDdatalogger/boot.py b/examples/SDdatalogger/boot.py
index 4ac94bb..bc42cef 100644
--- a/examples/SDdatalogger/boot.py
+++ b/examples/SDdatalogger/boot.py
@@ -8,18 +8,18 @@
 
 import pyb
 
-pyb.LED(3).on()                 # indicate we are waiting for switch press
-pyb.delay(2000)                 # wait for user to maybe press the switch
-switch_value = pyb.Switch()()   # sample the switch at end of delay
-pyb.LED(3).off()                # indicate that we finished waiting for the switch
+pyb.LED(3).on()  # indicate we are waiting for switch press
+pyb.delay(2000)  # wait for user to maybe press the switch
+switch_value = pyb.Switch()()  # sample the switch at end of delay
+pyb.LED(3).off()  # indicate that we finished waiting for the switch
 
-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:
-    pyb.usb_mode('VCP+MSC')
-    pyb.main('cardreader.py')           # if switch was pressed, run this
+    pyb.usb_mode("VCP+MSC")
+    pyb.main("cardreader.py")  # if switch was pressed, run this
 else:
-    pyb.usb_mode('VCP+HID')
-    pyb.main('datalogger.py')           # if switch wasn't pressed, run this
+    pyb.usb_mode("VCP+HID")
+    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
diff --git a/examples/SDdatalogger/datalogger.py b/examples/SDdatalogger/datalogger.py
index 0690c20..3d6f98b 100644
--- a/examples/SDdatalogger/datalogger.py
+++ b/examples/SDdatalogger/datalogger.py
@@ -17,17 +17,17 @@
 
     # start if switch is pressed
     if switch():
-        pyb.delay(200)                      # delay avoids detection of multiple presses
-        blue.on()                           # blue LED indicates file open
-        log = open('/sd/log.csv', 'w')       # open file on SD (SD: '/sd/', flash: '/flash/)
+        pyb.delay(200)  # delay avoids detection of multiple presses
+        blue.on()  # blue LED indicates file open
+        log = open("/sd/log.csv", "w")  # open file on SD (SD: '/sd/', flash: '/flash/)
 
         # until switch is pressed again
         while not switch():
-            t = pyb.millis()                            # get time
-            x, y, z = accel.filtered_xyz()              # get acceleration data
-            log.write('{},{},{},{}\n'.format(t,x,y,z))  # write data to file
+            t = pyb.millis()  # get time
+            x, y, z = accel.filtered_xyz()  # get acceleration data
+            log.write("{},{},{},{}\n".format(t, x, y, z))  # write data to file
 
         # end after switch is pressed again
-        log.close()                         # close file
-        blue.off()                          # blue LED indicates file closed
-        pyb.delay(200)                      # delay avoids detection of multiple presses
+        log.close()  # close file
+        blue.off()  # blue LED indicates file closed
+        pyb.delay(200)  # delay avoids detection of multiple presses
diff --git a/examples/accel_i2c.py b/examples/accel_i2c.py
index d635e3c..7229c22 100644
--- a/examples/accel_i2c.py
+++ b/examples/accel_i2c.py
@@ -17,10 +17,10 @@
 i2c = I2C(1, baudrate=100000)
 addrs = i2c.scan()
 print("Scanning devices:", [hex(x) for x in addrs])
-if 0x4c not in addrs:
+if 0x4C not in addrs:
     print("Accelerometer is not detected")
 
-ACCEL_ADDR = 0x4c
+ACCEL_ADDR = 0x4C
 ACCEL_AXIS_X_REG = 0
 ACCEL_MODE_REG = 7
 
diff --git a/examples/accellog.py b/examples/accellog.py
index a2fbe14..e8b5d10 100644
--- a/examples/accellog.py
+++ b/examples/accellog.py
@@ -2,19 +2,19 @@
 
 import pyb
 
-accel = pyb.Accel()                                 # create object of accelerometer
-blue = pyb.LED(4)                                   # create object of blue LED
+accel = pyb.Accel()  # create object of accelerometer
+blue = pyb.LED(4)  # create object of blue LED
 
 # 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
 
 # do 100 times (if the board is connected via USB, you can't write longer because the PC tries to open the filesystem which messes up your file.)
 for i in range(100):
-        t = pyb.millis()                            # get time since reset
-        x, y, z = accel.filtered_xyz()              # get acceleration data
-        log.write('{},{},{},{}\n'.format(t,x,y,z))  # write data to file
+    t = pyb.millis()  # get time since reset
+    x, y, z = accel.filtered_xyz()  # get acceleration data
+    log.write("{},{},{},{}\n".format(t, x, y, z))  # write data to file
 
-log.close()                                         # close file
-blue.off()                                          # turn off LED
+log.close()  # close file
+blue.off()  # turn off LED
diff --git a/examples/asmled.py b/examples/asmled.py
index 917d9ba..09a06c1 100644
--- a/examples/asmled.py
+++ b/examples/asmled.py
@@ -2,8 +2,8 @@
 # this version is overly verbose and uses word stores
 @micropython.asm_thumb
 def flash_led(r0):
-    movw(r1, (stm.GPIOA + stm.GPIO_BSRRL) & 0xffff)
-    movt(r1, ((stm.GPIOA + stm.GPIO_BSRRL) >> 16) & 0x7fff)
+    movw(r1, (stm.GPIOA + stm.GPIO_BSRRL) & 0xFFFF)
+    movt(r1, ((stm.GPIOA + stm.GPIO_BSRRL) >> 16) & 0x7FFF)
     movw(r2, 1 << 13)
     movt(r2, 0)
     movw(r3, 0)
@@ -17,8 +17,8 @@
     str(r2, [r1, 0])
 
     # delay for a bit
-    movw(r4, 5599900 & 0xffff)
-    movt(r4, (5599900 >> 16) & 0xffff)
+    movw(r4, 5599900 & 0xFFFF)
+    movt(r4, (5599900 >> 16) & 0xFFFF)
     label(delay_on)
     sub(r4, r4, 1)
     cmp(r4, 0)
@@ -28,8 +28,8 @@
     str(r3, [r1, 0])
 
     # delay for a bit
-    movw(r4, 5599900 & 0xffff)
-    movt(r4, (5599900 >> 16) & 0xffff)
+    movw(r4, 5599900 & 0xFFFF)
+    movt(r4, (5599900 >> 16) & 0xFFFF)
     label(delay_off)
     sub(r4, r4, 1)
     cmp(r4, 0)
@@ -41,6 +41,7 @@
     cmp(r0, 0)
     bgt(loop1)
 
+
 # flash LED #2 using inline assembler
 # this version uses half-word sortes, and the convenience assembler operation 'movwt'
 @micropython.asm_thumb
@@ -81,5 +82,6 @@
     cmp(r0, 0)
     bgt(loop1)
 
+
 flash_led(5)
 flash_led_v2(5)
diff --git a/examples/asmsum.py b/examples/asmsum.py
index 07e71c7..f465b25 100644
--- a/examples/asmsum.py
+++ b/examples/asmsum.py
@@ -22,6 +22,7 @@
 
     mov(r0, r2)
 
+
 @micropython.asm_thumb
 def asm_sum_bytes(r0, r1):
 
@@ -46,12 +47,13 @@
 
     mov(r0, r2)
 
+
 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)
 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)
 print(b, n)
diff --git a/examples/bluetooth/ble_advertising.py b/examples/bluetooth/ble_advertising.py
index 3a06beb..3fb1281 100644
--- a/examples/bluetooth/ble_advertising.py
+++ b/examples/bluetooth/ble_advertising.py
@@ -26,9 +26,12 @@
 
     def _append(adv_type, value):
         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:
         _append(_ADV_TYPE_NAME, name)
@@ -44,7 +47,7 @@
                 _append(_ADV_TYPE_UUID128_COMPLETE, b)
 
     # 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
 
@@ -54,32 +57,36 @@
     result = []
     while i + 1 < len(payload):
         if payload[i + 1] == adv_type:
-            result.append(payload[i + 2:i + payload[i] + 1])
+            result.append(payload[i + 2 : i + payload[i] + 1])
         i += 1 + payload[i]
     return result
 
 
 def decode_name(payload):
     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):
     services = []
     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):
-        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):
         services.append(bluetooth.UUID(u))
     return services
 
 
 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(decode_name(payload))
     print(decode_services(payload))
 
-if __name__ == '__main__':
+
+if __name__ == "__main__":
     demo()
diff --git a/examples/bluetooth/ble_temperature.py b/examples/bluetooth/ble_temperature.py
index d901e2a..01d2f74 100644
--- a/examples/bluetooth/ble_temperature.py
+++ b/examples/bluetooth/ble_temperature.py
@@ -10,26 +10,36 @@
 from ble_advertising import advertising_payload
 
 from micropython import const
-_IRQ_CENTRAL_CONNECT                 = const(1 << 0)
-_IRQ_CENTRAL_DISCONNECT              = const(1 << 1)
+
+_IRQ_CENTRAL_CONNECT = const(1 << 0)
+_IRQ_CENTRAL_DISCONNECT = const(1 << 1)
 
 # org.bluetooth.service.environmental_sensing
 _ENV_SENSE_UUID = bluetooth.UUID(0x181A)
 # org.bluetooth.characteristic.temperature
-_TEMP_CHAR = (bluetooth.UUID(0x2A6E), bluetooth.FLAG_READ|bluetooth.FLAG_NOTIFY,)
-_ENV_SENSE_SERVICE = (_ENV_SENSE_UUID, (_TEMP_CHAR,),)
+_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
 _ADV_APPEARANCE_GENERIC_THERMOMETER = const(768)
 
+
 class BLETemperature:
-    def __init__(self, ble, name='mpy-temp'):
+    def __init__(self, ble, name="mpy-temp"):
         self._ble = ble
         self._ble.active(True)
         self._ble.irq(handler=self._irq)
         ((self._handle,),) = self._ble.gatts_register_services((_ENV_SENSE_SERVICE,))
         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()
 
     def _irq(self, event, data):
@@ -46,7 +56,7 @@
     def set_temperature(self, temp_deg_c, notify=False):
         # Data is sint16 in degrees Celsius with a resolution of 0.01 degrees Celsius.
         # 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:
             for conn_handle in self._connections:
                 # Notify connected centrals to issue a read.
@@ -72,5 +82,5 @@
         time.sleep_ms(1000)
 
 
-if __name__ == '__main__':
+if __name__ == "__main__":
     demo()
diff --git a/examples/bluetooth/ble_temperature_central.py b/examples/bluetooth/ble_temperature_central.py
index 5c23a06..14ea694 100644
--- a/examples/bluetooth/ble_temperature_central.py
+++ b/examples/bluetooth/ble_temperature_central.py
@@ -9,33 +9,41 @@
 from ble_advertising import decode_services, decode_name
 
 from micropython import const
-_IRQ_CENTRAL_CONNECT                 = const(1 << 0)
-_IRQ_CENTRAL_DISCONNECT              = const(1 << 1)
-_IRQ_GATTS_WRITE                     = const(1 << 2)
-_IRQ_GATTS_READ_REQUEST              = const(1 << 3)
-_IRQ_SCAN_RESULT                     = const(1 << 4)
-_IRQ_SCAN_COMPLETE                   = const(1 << 5)
-_IRQ_PERIPHERAL_CONNECT              = const(1 << 6)
-_IRQ_PERIPHERAL_DISCONNECT           = const(1 << 7)
-_IRQ_GATTC_SERVICE_RESULT            = const(1 << 8)
-_IRQ_GATTC_CHARACTERISTIC_RESULT     = const(1 << 9)
-_IRQ_GATTC_DESCRIPTOR_RESULT         = const(1 << 10)
-_IRQ_GATTC_READ_RESULT               = const(1 << 11)
-_IRQ_GATTC_WRITE_STATUS              = const(1 << 12)
-_IRQ_GATTC_NOTIFY                    = const(1 << 13)
-_IRQ_GATTC_INDICATE                  = const(1 << 14)
-_IRQ_ALL                             = const(0xffff)
+
+_IRQ_CENTRAL_CONNECT = const(1 << 0)
+_IRQ_CENTRAL_DISCONNECT = const(1 << 1)
+_IRQ_GATTS_WRITE = const(1 << 2)
+_IRQ_GATTS_READ_REQUEST = const(1 << 3)
+_IRQ_SCAN_RESULT = const(1 << 4)
+_IRQ_SCAN_COMPLETE = const(1 << 5)
+_IRQ_PERIPHERAL_CONNECT = const(1 << 6)
+_IRQ_PERIPHERAL_DISCONNECT = const(1 << 7)
+_IRQ_GATTC_SERVICE_RESULT = const(1 << 8)
+_IRQ_GATTC_CHARACTERISTIC_RESULT = const(1 << 9)
+_IRQ_GATTC_DESCRIPTOR_RESULT = const(1 << 10)
+_IRQ_GATTC_READ_RESULT = const(1 << 11)
+_IRQ_GATTC_WRITE_STATUS = const(1 << 12)
+_IRQ_GATTC_NOTIFY = const(1 << 13)
+_IRQ_GATTC_INDICATE = const(1 << 14)
+_IRQ_ALL = const(0xFFFF)
 
 # org.bluetooth.service.environmental_sensing
 _ENV_SENSE_UUID = bluetooth.UUID(0x181A)
 # org.bluetooth.characteristic.temperature
 _TEMP_UUID = bluetooth.UUID(0x2A6E)
-_TEMP_CHAR = (_TEMP_UUID, bluetooth.FLAG_READ|bluetooth.FLAG_NOTIFY,)
-_ENV_SENSE_SERVICE = (_ENV_SENSE_UUID, (_TEMP_CHAR,),)
+_TEMP_CHAR = (
+    _TEMP_UUID,
+    bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY,
+)
+_ENV_SENSE_SERVICE = (
+    _ENV_SENSE_UUID,
+    (_TEMP_CHAR,),
+)
 
 # org.bluetooth.characteristic.gap.appearance.xml
 _ADV_APPEARANCE_GENERIC_THERMOMETER = const(768)
 
+
 class BLETemperatureCentral:
     def __init__(self, ble):
         self._ble = ble
@@ -72,8 +80,10 @@
             if connectable and _ENV_SENSE_UUID in decode_services(adv_data):
                 # Found a potential device, remember it and stop scanning.
                 self._addr_type = addr_type
-                self._addr = bytes(addr) # Note: addr buffer is owned by caller so need to copy it.
-                self._name = decode_name(adv_data) or '?'
+                self._addr = bytes(
+                    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)
 
         elif event == _IRQ_SCAN_COMPLETE:
@@ -104,7 +114,9 @@
             # Connected device returned a service.
             conn_handle, start_handle, end_handle, uuid = data
             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:
             # Connected device returned a characteristic.
@@ -132,7 +144,6 @@
                 if self._notify_callback:
                     self._notify_callback(self._value)
 
-
     # Returns true if we've successfully connected and discovered characteristics.
     def is_connected(self):
         return self._conn_handle is not None and self._value_handle is not None
@@ -174,7 +185,7 @@
 
     def _update_value(self, data):
         # 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
 
     def value(self):
@@ -189,12 +200,12 @@
 
     def on_scan(addr_type, addr, name):
         if addr_type is not None:
-            print('Found sensor:', addr_type, addr, name)
+            print("Found sensor:", addr_type, addr, name)
             central.connect()
         else:
             nonlocal not_found
             not_found = True
-            print('No sensor found.')
+            print("No sensor found.")
 
     central.scan(callback=on_scan)
 
@@ -204,7 +215,7 @@
         if not_found:
             return
 
-    print('Connected')
+    print("Connected")
 
     # Explicitly issue reads, using "print" as the callback.
     while central.is_connected():
@@ -216,7 +227,8 @@
     #     print(central.value())
     #     time.sleep_ms(2000)
 
-    print('Disconnected')
+    print("Disconnected")
 
-if __name__ == '__main__':
+
+if __name__ == "__main__":
     demo()
diff --git a/examples/bluetooth/ble_uart_peripheral.py b/examples/bluetooth/ble_uart_peripheral.py
index 14f7102..c013d96 100644
--- a/examples/bluetooth/ble_uart_peripheral.py
+++ b/examples/bluetooth/ble_uart_peripheral.py
@@ -4,24 +4,37 @@
 from ble_advertising import advertising_payload
 
 from micropython import const
-_IRQ_CENTRAL_CONNECT                 = const(1 << 0)
-_IRQ_CENTRAL_DISCONNECT              = const(1 << 1)
-_IRQ_GATTS_WRITE                     = const(1 << 2)
 
-_UART_UUID = bluetooth.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E')
-_UART_TX = (bluetooth.UUID('6E400003-B5A3-F393-E0A9-E50E24DCCA9E'), bluetooth.FLAG_NOTIFY,)
-_UART_RX = (bluetooth.UUID('6E400002-B5A3-F393-E0A9-E50E24DCCA9E'), bluetooth.FLAG_WRITE,)
-_UART_SERVICE = (_UART_UUID, (_UART_TX, _UART_RX,),)
+_IRQ_CENTRAL_CONNECT = const(1 << 0)
+_IRQ_CENTRAL_DISCONNECT = const(1 << 1)
+_IRQ_GATTS_WRITE = const(1 << 2)
+
+_UART_UUID = bluetooth.UUID("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
+_UART_TX = (
+    bluetooth.UUID("6E400003-B5A3-F393-E0A9-E50E24DCCA9E"),
+    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
 _ADV_APPEARANCE_GENERIC_COMPUTER = const(128)
 
+
 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.active(True)
         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.
         self._ble.gatts_set_buffer(self._rx_handle, rxbuf, True)
         self._connections = set()
@@ -82,7 +95,7 @@
     uart = BLEUART(ble)
 
     def on_rx():
-        print('rx: ', uart.read().decode().strip())
+        print("rx: ", uart.read().decode().strip())
 
     uart.irq(handler=on_rx)
     nums = [4, 8, 15, 16, 23, 42]
@@ -90,7 +103,7 @@
 
     try:
         while True:
-            uart.write(str(nums[i]) + '\n')
+            uart.write(str(nums[i]) + "\n")
             i = (i + 1) % len(nums)
             time.sleep_ms(1000)
     except KeyboardInterrupt:
@@ -99,5 +112,5 @@
     uart.close()
 
 
-if __name__ == '__main__':
+if __name__ == "__main__":
     demo()
diff --git a/examples/bluetooth/ble_uart_repl.py b/examples/bluetooth/ble_uart_repl.py
index 430a571..9e8a38f 100644
--- a/examples/bluetooth/ble_uart_repl.py
+++ b/examples/bluetooth/ble_uart_repl.py
@@ -15,7 +15,7 @@
 _MP_STREAM_POLL_RD = const(0x0001)
 
 # TODO: Remove this when STM32 gets machine.Timer.
-if hasattr(machine, 'Timer'):
+if hasattr(machine, "Timer"):
     _timer = machine.Timer(-1)
 else:
     _timer = None
@@ -24,11 +24,13 @@
 def schedule_in(handler, delay_ms):
     def _wrap(_arg):
         handler()
+
     if _timer:
         _timer.init(mode=machine.Timer.ONE_SHOT, period=delay_ms, callback=_wrap)
     else:
         micropython.schedule(_wrap, None)
 
+
 # Simple buffering stream to support the dupterm requirements.
 class BLEUARTStream(io.IOBase):
     def __init__(self, uart):
@@ -38,7 +40,7 @@
 
     def _on_rx(self):
         # Needed for ESP32.
-        if hasattr(os, 'dupterm_notify'):
+        if hasattr(os, "dupterm_notify"):
             os.dupterm_notify(None)
 
     def read(self, sz=None):
@@ -74,7 +76,7 @@
 
 def start():
     ble = bluetooth.BLE()
-    uart = BLEUART(ble, name='mpy-repl')
+    uart = BLEUART(ble, name="mpy-repl")
     stream = BLEUARTStream(uart)
 
     os.dupterm(stream)
diff --git a/examples/conwaylife.py b/examples/conwaylife.py
index 323f42e..44c1a50 100644
--- a/examples/conwaylife.py
+++ b/examples/conwaylife.py
@@ -1,46 +1,51 @@
-#import essential libraries
+# import essential libraries
 import pyb
 
-lcd = pyb.LCD('x')
+lcd = pyb.LCD("x")
 lcd.light(1)
 
 # do 1 iteration of Conway's Game of Life
 def conway_step():
-    for x in range(128):        # loop over x coordinates
-        for y in range(32):     # loop over y coordinates
+    for x in range(128):  # loop over x coordinates
+        for y in range(32):  # loop over y coordinates
             # count number of neighbours
-            num_neighbours = (lcd.get(x - 1, y - 1) +
-                lcd.get(x, y - 1) +
-                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, y + 1) +
-                lcd.get(x - 1, y + 1))
+            num_neighbours = (
+                lcd.get(x - 1, y - 1)
+                + lcd.get(x, y - 1)
+                + 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, y + 1)
+                + lcd.get(x - 1, y + 1)
+            )
 
             # check if the centre cell is alive or not
             self = lcd.get(x, y)
 
             # apply the rules of life
             if self and not (2 <= num_neighbours <= 3):
-                lcd.pixel(x, y, 0) # not enough, or too many neighbours: cell dies
+                lcd.pixel(x, y, 0)  # not enough, or too many neighbours: cell dies
             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
 def conway_rand():
-    lcd.fill(0)                 # clear the LCD
-    for x in range(128):        # loop over x coordinates
-        for y in range(32):     # loop over y coordinates
-            lcd.pixel(x, y, pyb.rng() & 1)   # set the pixel randomly
+    lcd.fill(0)  # clear the LCD
+    for x in range(128):  # loop over x coordinates
+        for y in range(32):  # loop over y coordinates
+            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
 def conway_go(num_frames):
     for i in range(num_frames):
-        conway_step()           # do 1 iteration
-        lcd.show()              # update the LCD
+        conway_step()  # do 1 iteration
+        lcd.show()  # update the LCD
         pyb.delay(50)
 
+
 # testing
 conway_rand()
 conway_go(100)
diff --git a/examples/hwapi/button_reaction.py b/examples/hwapi/button_reaction.py
index b72e813..e5a139a 100644
--- a/examples/hwapi/button_reaction.py
+++ b/examples/hwapi/button_reaction.py
@@ -4,14 +4,16 @@
 
 # machine.time_pulse_us() function demo
 
-print("""\
+print(
+    """\
 Let's play an interesting game:
 You click button as fast as you can, and I tell you how slow you are.
 Ready? Cliiiiick!
-""")
+"""
+)
 
 while 1:
-    delay = machine.time_pulse_us(BUTTON, 1, 10*1000*1000)
+    delay = machine.time_pulse_us(BUTTON, 1, 10 * 1000 * 1000)
     if delay < 0:
         print("Well, you're *really* slow")
     else:
diff --git a/examples/hwapi/hwconfig_console.py b/examples/hwapi/hwconfig_console.py
index bbcc0e8..1b49d52 100644
--- a/examples/hwapi/hwconfig_console.py
+++ b/examples/hwapi/hwconfig_console.py
@@ -1,7 +1,6 @@
 # This is hwconfig for "emulation" for cases when there's no real hardware.
 # It just prints information to console.
 class LEDClass:
-
     def __init__(self, id):
         self.id = "LED(%d):" % id
 
diff --git a/examples/hwapi/hwconfig_pyboard.py b/examples/hwapi/hwconfig_pyboard.py
index fb26003..a74a1ae 100644
--- a/examples/hwapi/hwconfig_pyboard.py
+++ b/examples/hwapi/hwconfig_pyboard.py
@@ -1,13 +1,13 @@
 from machine import Pin, Signal
 
 # 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
-LED2 = Signal('LED_GREEN', Pin.OUT)
+LED2 = Signal("LED_GREEN", Pin.OUT)
 
 # 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
-LED4 = Signal('LED_BLUE', Pin.OUT)
+LED4 = Signal("LED_BLUE", Pin.OUT)
diff --git a/examples/ledangle.py b/examples/ledangle.py
index 8c8d9e9..3d47e8f 100644
--- a/examples/ledangle.py
+++ b/examples/ledangle.py
@@ -1,5 +1,6 @@
 import pyb
 
+
 def led_angle(seconds_to_run_for):
     # make LED objects
     l1 = pyb.LED(1)
diff --git a/examples/mandel.py b/examples/mandel.py
index bbb8086..2f3d7da 100644
--- a/examples/mandel.py
+++ b/examples/mandel.py
@@ -3,13 +3,14 @@
 except:
     pass
 
+
 def mandelbrot():
     # returns True if c, complex, is in the Mandelbrot set
-    #@micropython.native
+    # @micropython.native
     def in_set(c):
         z = 0
         for i in range(40):
-            z = z*z + c
+            z = z * z + c
             if abs(z) > 60:
                 return False
         return True
@@ -21,7 +22,9 @@
                 lcd.set(u, v)
     lcd.show()
 
+
 # PC testing
 import lcd
+
 lcd = lcd.LCD(128, 32)
 mandelbrot()
diff --git a/examples/micropython.py b/examples/micropython.py
index f91da94..5b87ba1 100644
--- a/examples/micropython.py
+++ b/examples/micropython.py
@@ -2,7 +2,9 @@
 
 # Dummy function decorators
 
+
 def nodecor(x):
     return x
 
+
 bytecode = native = viper = nodecor
diff --git a/examples/natmod/features2/test.py b/examples/natmod/features2/test.py
index 2e9db00..5ac8012 100644
--- a/examples/natmod/features2/test.py
+++ b/examples/natmod/features2/test.py
@@ -2,20 +2,22 @@
 
 import array
 
+
 def isclose(a, b):
     return abs(a - b) < 1e-3
 
+
 def test():
     tests = [
         isclose(add(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)
     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))
 
     print(tests)
@@ -23,4 +25,5 @@
     if not all(tests):
         raise SystemExit(1)
 
+
 test()
diff --git a/examples/network/http_server.py b/examples/network/http_server.py
index e3a66e8..76be3ab 100644
--- a/examples/network/http_server.py
+++ b/examples/network/http_server.py
@@ -10,6 +10,7 @@
 Hello #%d from MicroPython!
 """
 
+
 def main(micropython_optimize=False):
     s = socket.socket()
 
diff --git a/examples/network/http_server_simplistic.py b/examples/network/http_server_simplistic.py
index 67ecb1a..7194941 100644
--- a/examples/network/http_server_simplistic.py
+++ b/examples/network/http_server_simplistic.py
@@ -12,6 +12,7 @@
 Hello #%d from MicroPython!
 """
 
+
 def main():
     s = socket.socket()
     ai = socket.getaddrinfo("0.0.0.0", 8080)
diff --git a/examples/network/http_server_simplistic_commented.py b/examples/network/http_server_simplistic_commented.py
index b58e9ee..da042c6 100644
--- a/examples/network/http_server_simplistic_commented.py
+++ b/examples/network/http_server_simplistic_commented.py
@@ -20,6 +20,7 @@
 Hello #%d from MicroPython!
 """
 
+
 def main():
     s = socket.socket()
 
diff --git a/examples/network/http_server_ssl.py b/examples/network/http_server_ssl.py
index 47d83bf..1116c71 100644
--- a/examples/network/http_server_ssl.py
+++ b/examples/network/http_server_ssl.py
@@ -1,4 +1,5 @@
 import ubinascii as binascii
+
 try:
     import usocket as socket
 except:
@@ -9,30 +10,32 @@
 # 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.
 key = binascii.unhexlify(
-    b'3082013b020100024100cc20643fd3d9c21a0acba4f48f61aadd675f52175a9dcf07fbef'
-    b'610a6a6ba14abb891745cd18a1d4c056580d8ff1a639460f867013c8391cdc9f2e573b0f'
-    b'872d0203010001024100bb17a54aeb3dd7ae4edec05e775ca9632cf02d29c2a089b563b0'
-    b'd05cdf95aeca507de674553f28b4eadaca82d5549a86058f9996b07768686a5b02cb240d'
-    b'd9f1022100f4a63f5549e817547dca97b5c658038e8593cb78c5aba3c4642cc4cd031d86'
-    b'8f022100d598d870ffe4a34df8de57047a50b97b71f4d23e323f527837c9edae88c79483'
-    b'02210098560c89a70385c36eb07fd7083235c4c1184e525d838aedf7128958bedfdbb102'
-    b'2051c0dab7057a8176ca966f3feb81123d4974a733df0f958525f547dfd1c271f9022044'
-    b'6c2cafad455a671a8cf398e642e1be3b18a3d3aec2e67a9478f83c964c4f1f')
+    b"3082013b020100024100cc20643fd3d9c21a0acba4f48f61aadd675f52175a9dcf07fbef"
+    b"610a6a6ba14abb891745cd18a1d4c056580d8ff1a639460f867013c8391cdc9f2e573b0f"
+    b"872d0203010001024100bb17a54aeb3dd7ae4edec05e775ca9632cf02d29c2a089b563b0"
+    b"d05cdf95aeca507de674553f28b4eadaca82d5549a86058f9996b07768686a5b02cb240d"
+    b"d9f1022100f4a63f5549e817547dca97b5c658038e8593cb78c5aba3c4642cc4cd031d86"
+    b"8f022100d598d870ffe4a34df8de57047a50b97b71f4d23e323f527837c9edae88c79483"
+    b"02210098560c89a70385c36eb07fd7083235c4c1184e525d838aedf7128958bedfdbb102"
+    b"2051c0dab7057a8176ca966f3feb81123d4974a733df0f958525f547dfd1c271f9022044"
+    b"6c2cafad455a671a8cf398e642e1be3b18a3d3aec2e67a9478f83c964c4f1f"
+)
 cert = binascii.unhexlify(
-    b'308201d53082017f020203e8300d06092a864886f70d01010505003075310b3009060355'
-    b'0406130258583114301206035504080c0b54686550726f76696e63653110300e06035504'
-    b'070c075468654369747931133011060355040a0c0a436f6d70616e7958595a3113301106'
-    b'0355040b0c0a436f6d70616e7958595a3114301206035504030c0b546865486f73744e61'
-    b'6d65301e170d3139313231383033333935355a170d3239313231353033333935355a3075'
-    b'310b30090603550406130258583114301206035504080c0b54686550726f76696e636531'
-    b'10300e06035504070c075468654369747931133011060355040a0c0a436f6d70616e7958'
-    b'595a31133011060355040b0c0a436f6d70616e7958595a3114301206035504030c0b5468'
-    b'65486f73744e616d65305c300d06092a864886f70d0101010500034b003048024100cc20'
-    b'643fd3d9c21a0acba4f48f61aadd675f52175a9dcf07fbef610a6a6ba14abb891745cd18'
-    b'a1d4c056580d8ff1a639460f867013c8391cdc9f2e573b0f872d0203010001300d06092a'
-    b'864886f70d0101050500034100b0513fe2829e9ecbe55b6dd14c0ede7502bde5d46153c8'
-    b'e960ae3ebc247371b525caeb41bbcf34686015a44c50d226e66aef0a97a63874ca5944ef'
-    b'979b57f0b3')
+    b"308201d53082017f020203e8300d06092a864886f70d01010505003075310b3009060355"
+    b"0406130258583114301206035504080c0b54686550726f76696e63653110300e06035504"
+    b"070c075468654369747931133011060355040a0c0a436f6d70616e7958595a3113301106"
+    b"0355040b0c0a436f6d70616e7958595a3114301206035504030c0b546865486f73744e61"
+    b"6d65301e170d3139313231383033333935355a170d3239313231353033333935355a3075"
+    b"310b30090603550406130258583114301206035504080c0b54686550726f76696e636531"
+    b"10300e06035504070c075468654369747931133011060355040a0c0a436f6d70616e7958"
+    b"595a31133011060355040b0c0a436f6d70616e7958595a3114301206035504030c0b5468"
+    b"65486f73744e616d65305c300d06092a864886f70d0101010500034b003048024100cc20"
+    b"643fd3d9c21a0acba4f48f61aadd675f52175a9dcf07fbef610a6a6ba14abb891745cd18"
+    b"a1d4c056580d8ff1a639460f867013c8391cdc9f2e573b0f872d0203010001300d06092a"
+    b"864886f70d0101050500034100b0513fe2829e9ecbe55b6dd14c0ede7502bde5d46153c8"
+    b"e960ae3ebc247371b525caeb41bbcf34686015a44c50d226e66aef0a97a63874ca5944ef"
+    b"979b57f0b3"
+)
 
 
 CONTENT = b"""\
@@ -41,6 +44,7 @@
 Hello #%d from MicroPython!
 """
 
+
 def main(use_stream=True):
     s = socket.socket()
 
diff --git a/examples/pins.py b/examples/pins.py
index aafdb48..3a8472e 100644
--- a/examples/pins.py
+++ b/examples/pins.py
@@ -4,6 +4,7 @@
 import pyb
 import pins_af
 
+
 def af():
     max_name_width = 0
     max_af_width = 0
@@ -13,21 +14,22 @@
             max_af_width = max(max_af_width, len(af_entry[1]))
     for pin_entry in pins_af.PINS_AF:
         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:]:
-            print('%2d: %-*s ' % (af_entry[0], max_af_width, af_entry[1]), end='')
-        print('')
+            print("%2d: %-*s " % (af_entry[0], max_af_width, af_entry[1]), end="")
+        print("")
+
 
 def pins():
-    mode_str = { pyb.Pin.IN     : 'IN',
-                 pyb.Pin.OUT_PP : 'OUT_PP',
-                 pyb.Pin.OUT_OD : 'OUT_OD',
-                 pyb.Pin.AF_PP  : 'AF_PP',
-                 pyb.Pin.AF_OD  : 'AF_OD',
-                 pyb.Pin.ANALOG : 'ANALOG' }
-    pull_str = { pyb.Pin.PULL_NONE : '',
-                 pyb.Pin.PULL_UP   : 'PULL_UP',
-                 pyb.Pin.PULL_DOWN : 'PULL_DOWN' }
+    mode_str = {
+        pyb.Pin.IN: "IN",
+        pyb.Pin.OUT_PP: "OUT_PP",
+        pyb.Pin.OUT_OD: "OUT_OD",
+        pyb.Pin.AF_PP: "AF_PP",
+        pyb.Pin.AF_OD: "AF_OD",
+        pyb.Pin.ANALOG: "ANALOG",
+    }
+    pull_str = {pyb.Pin.PULL_NONE: "", pyb.Pin.PULL_UP: "PULL_UP", pyb.Pin.PULL_DOWN: "PULL_DOWN"}
     width = [0, 0, 0, 0]
     rows = []
     for pin_entry in pins_af.PINS_AF:
@@ -42,17 +44,17 @@
             pin_af = pin.af()
             for af_entry in pin_entry[1:]:
                 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
             else:
-                af_str = '%d' % pin_af
+                af_str = "%d" % pin_af
         else:
-            af_str = ''
+            af_str = ""
         row.append(af_str)
         for col in range(len(width)):
             width[col] = max(width[col], len(row[col]))
         rows.append(row)
     for row in rows:
         for col in range(len(width)):
-            print('%-*s ' % (width[col], row[col]), end='')
-        print('')
+            print("%-*s " % (width[col], row[col]), end="")
+        print("")
diff --git a/examples/pyb.py b/examples/pyb.py
index b303777..67620e7 100644
--- a/examples/pyb.py
+++ b/examples/pyb.py
@@ -1,17 +1,22 @@
 # pyboard testing functions for CPython
 import time
 
+
 def delay(n):
-    #time.sleep(float(n) / 1000)
+    # time.sleep(float(n) / 1000)
     pass
 
+
 rand_seed = 1
+
+
 def rng():
     global rand_seed
     # 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
     return rand_seed
 
+
 # LCD testing object for PC
 # uses double buffering
 class LCD:
@@ -30,12 +35,12 @@
                 self.buf1[y][x] = self.buf2[y][x] = value
 
     def show(self):
-        print('') # blank line to separate frames
+        print("")  # blank line to separate frames
         for y in range(self.height):
             for x in range(self.width):
                 self.buf1[y][x] = self.buf2[y][x]
         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)
 
     def get(self, x, y):
diff --git a/examples/switch.py b/examples/switch.py
index 0efaf22..c099a35 100644
--- a/examples/switch.py
+++ b/examples/switch.py
@@ -24,6 +24,7 @@
 blue_led = pyb.LED(4)
 all_leds = (red_led, green_led, orange_led, blue_led)
 
+
 def run_loop(leds=all_leds):
     """
     Start the loop.
@@ -31,15 +32,16 @@
     :param `leds`: Which LEDs to light up upon switch press.
     :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:
         try:
             if switch():
                 [led.on() for led in leds]
             else:
                 [led.off() for led in leds]
-        except OSError: # VCPInterrupt # Ctrl+C in interpreter mode.
+        except OSError:  # VCPInterrupt # Ctrl+C in interpreter mode.
             break
 
-if __name__ == '__main__':
+
+if __name__ == "__main__":
     run_loop()
diff --git a/examples/unix/ffi_example.py b/examples/unix/ffi_example.py
index 3c3c3d2..a8f02c7 100644
--- a/examples/unix/ffi_example.py
+++ b/examples/unix/ffi_example.py
@@ -24,12 +24,14 @@
 perror("perror after error")
 print()
 
+
 def cmp(pa, pb):
     a = uctypes.bytearray_at(pa, 1)
     b = uctypes.bytearray_at(pb, 1)
     print("cmp:", a, b)
     return a[0] - b[0]
 
+
 cmp_cb = ffi.callback("i", cmp, "PP")
 print("callback:", cmp_cb)
 
diff --git a/examples/unix/machine_bios.py b/examples/unix/machine_bios.py
index f62e4db..878f3fd 100644
--- a/examples/unix/machine_bios.py
+++ b/examples/unix/machine_bios.py
@@ -6,4 +6,4 @@
 
 import umachine as machine
 
-print(hex(machine.mem16[0xc0000]))
+print(hex(machine.mem16[0xC0000]))
diff --git a/extmod/machine_i2c.c b/extmod/machine_i2c.c
index 0687aa9..32ec3dd 100644
--- a/extmod/machine_i2c.c
+++ b/extmod/machine_i2c.c
@@ -183,7 +183,7 @@
 //  >=0 - success; for read it's 0, for write it's number of acks received
 //   <0 - error, with errno being the negative of the return value
 int mp_machine_soft_i2c_transfer(mp_obj_base_t *self_in, uint16_t addr, size_t n, mp_machine_i2c_buf_t *bufs, unsigned int flags) {
-    machine_i2c_obj_t *self = (machine_i2c_obj_t*)self_in;
+    machine_i2c_obj_t *self = (machine_i2c_obj_t *)self_in;
 
     // start the I2C transaction
     int ret = mp_hal_i2c_start(self);
@@ -267,7 +267,7 @@
         }
     }
 
-    mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol;
+    mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol;
     int ret = i2c_p->transfer_single(self, addr, len, buf, flags);
 
     if (n > 1) {
@@ -286,15 +286,15 @@
 }
 
 STATIC int mp_machine_i2c_readfrom(mp_obj_base_t *self, uint16_t addr, uint8_t *dest, size_t len, bool stop) {
-    mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol;
+    mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol;
     mp_machine_i2c_buf_t buf = {.len = len, .buf = dest};
     unsigned int flags = MP_MACHINE_I2C_FLAG_READ | (stop ? MP_MACHINE_I2C_FLAG_STOP : 0);
     return i2c_p->transfer(self, addr, 1, &buf, flags);
 }
 
 STATIC int mp_machine_i2c_writeto(mp_obj_base_t *self, uint16_t addr, const uint8_t *src, size_t len, bool stop) {
-    mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol;
-    mp_machine_i2c_buf_t buf = {.len = len, .buf = (uint8_t*)src};
+    mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol;
+    mp_machine_i2c_buf_t buf = {.len = len, .buf = (uint8_t *)src};
     unsigned int flags = stop ? MP_MACHINE_I2C_FLAG_STOP : 0;
     return i2c_p->transfer(self, addr, 1, &buf, flags);
 }
@@ -364,8 +364,8 @@
 MP_DEFINE_CONST_FUN_OBJ_1(machine_i2c_scan_obj, machine_i2c_scan);
 
 STATIC mp_obj_t machine_i2c_start(mp_obj_t self_in) {
-    mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(self_in);
-    mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol;
+    mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(self_in);
+    mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol;
     if (i2c_p->start == NULL) {
         mp_raise_msg(&mp_type_OSError, "I2C operation not supported");
     }
@@ -378,8 +378,8 @@
 MP_DEFINE_CONST_FUN_OBJ_1(machine_i2c_start_obj, machine_i2c_start);
 
 STATIC mp_obj_t machine_i2c_stop(mp_obj_t self_in) {
-    mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(self_in);
-    mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol;
+    mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(self_in);
+    mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol;
     if (i2c_p->stop == NULL) {
         mp_raise_msg(&mp_type_OSError, "I2C operation not supported");
     }
@@ -392,8 +392,8 @@
 MP_DEFINE_CONST_FUN_OBJ_1(machine_i2c_stop_obj, machine_i2c_stop);
 
 STATIC mp_obj_t machine_i2c_readinto(size_t n_args, const mp_obj_t *args) {
-    mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]);
-    mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol;
+    mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
+    mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol;
     if (i2c_p->read == NULL) {
         mp_raise_msg(&mp_type_OSError, "I2C operation not supported");
     }
@@ -416,8 +416,8 @@
 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_i2c_readinto_obj, 2, 3, machine_i2c_readinto);
 
 STATIC mp_obj_t machine_i2c_write(mp_obj_t self_in, mp_obj_t buf_in) {
-    mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(self_in);
-    mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol;
+    mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(self_in);
+    mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol;
     if (i2c_p->write == NULL) {
         mp_raise_msg(&mp_type_OSError, "I2C operation not supported");
     }
@@ -438,12 +438,12 @@
 MP_DEFINE_CONST_FUN_OBJ_2(machine_i2c_write_obj, machine_i2c_write);
 
 STATIC mp_obj_t machine_i2c_readfrom(size_t n_args, const mp_obj_t *args) {
-    mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]);
+    mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
     mp_int_t addr = mp_obj_get_int(args[1]);
     vstr_t vstr;
     vstr_init_len(&vstr, mp_obj_get_int(args[2]));
     bool stop = (n_args == 3) ? true : mp_obj_is_true(args[3]);
-    int ret = mp_machine_i2c_readfrom(self, addr, (uint8_t*)vstr.buf, vstr.len, stop);
+    int ret = mp_machine_i2c_readfrom(self, addr, (uint8_t *)vstr.buf, vstr.len, stop);
     if (ret < 0) {
         mp_raise_OSError(-ret);
     }
@@ -452,7 +452,7 @@
 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_i2c_readfrom_obj, 3, 4, machine_i2c_readfrom);
 
 STATIC mp_obj_t machine_i2c_readfrom_into(size_t n_args, const mp_obj_t *args) {
-    mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]);
+    mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
     mp_int_t addr = mp_obj_get_int(args[1]);
     mp_buffer_info_t bufinfo;
     mp_get_buffer_raise(args[2], &bufinfo, MP_BUFFER_WRITE);
@@ -466,7 +466,7 @@
 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_i2c_readfrom_into_obj, 3, 4, machine_i2c_readfrom_into);
 
 STATIC mp_obj_t machine_i2c_writeto(size_t n_args, const mp_obj_t *args) {
-    mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]);
+    mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
     mp_int_t addr = mp_obj_get_int(args[1]);
     mp_buffer_info_t bufinfo;
     mp_get_buffer_raise(args[2], &bufinfo, MP_BUFFER_READ);
@@ -481,13 +481,13 @@
 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_i2c_writeto_obj, 3, 4, machine_i2c_writeto);
 
 STATIC mp_obj_t machine_i2c_writevto(size_t n_args, const mp_obj_t *args) {
-    mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]);
+    mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
     mp_int_t addr = mp_obj_get_int(args[1]);
 
     // Get the list of data buffer(s) to write
     size_t nitems;
     const mp_obj_t *items;
-    mp_obj_get_array(args[2], &nitems, (mp_obj_t**)&items);
+    mp_obj_get_array(args[2], &nitems, (mp_obj_t **)&items);
 
     // Get the stop argument
     bool stop = (n_args == 3) ? true : mp_obj_is_true(args[3]);
@@ -513,7 +513,7 @@
     }
 
     // Do the I2C transfer
-    mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol;
+    mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol;
     int ret = i2c_p->transfer(self, addr, nbufs, bufs, stop ? MP_MACHINE_I2C_FLAG_STOP : 0);
     mp_local_free(bufs);
 
@@ -527,7 +527,7 @@
 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_i2c_writevto_obj, 3, 4, machine_i2c_writevto);
 
 STATIC int read_mem(mp_obj_t self_in, uint16_t addr, uint32_t memaddr, uint8_t addrsize, uint8_t *buf, size_t len) {
-    mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(self_in);
+    mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(self_in);
     uint8_t memaddr_buf[4];
     size_t memaddr_len = 0;
     for (int16_t i = addrsize - 8; i >= 0; i -= 8) {
@@ -543,7 +543,7 @@
 }
 
 STATIC int write_mem(mp_obj_t self_in, uint16_t addr, uint32_t memaddr, uint8_t addrsize, const uint8_t *buf, size_t len) {
-    mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(self_in);
+    mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(self_in);
 
     // Create buffer with memory address
     size_t memaddr_len = 0;
@@ -555,11 +555,11 @@
     // Create partial write buffers
     mp_machine_i2c_buf_t bufs[2] = {
         {.len = memaddr_len, .buf = memaddr_buf},
-        {.len = len, .buf = (uint8_t*)buf},
+        {.len = len, .buf = (uint8_t *)buf},
     };
 
     // Do I2C transfer
-    mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol;
+    mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol;
     return i2c_p->transfer(self, addr, 2, bufs, MP_MACHINE_I2C_FLAG_STOP);
 }
 
@@ -582,7 +582,7 @@
 
     // do the transfer
     int ret = read_mem(pos_args[0], args[ARG_addr].u_int, args[ARG_memaddr].u_int,
-        args[ARG_addrsize].u_int, (uint8_t*)vstr.buf, vstr.len);
+        args[ARG_addrsize].u_int, (uint8_t *)vstr.buf, vstr.len);
     if (ret < 0) {
         mp_raise_OSError(-ret);
     }
@@ -658,7 +658,7 @@
 MP_DEFINE_CONST_DICT(mp_machine_soft_i2c_locals_dict, machine_i2c_locals_dict_table);
 
 int mp_machine_soft_i2c_read(mp_obj_base_t *self_in, uint8_t *dest, size_t len, bool nack) {
-    machine_i2c_obj_t *self = (machine_i2c_obj_t*)self_in;
+    machine_i2c_obj_t *self = (machine_i2c_obj_t *)self_in;
     while (len--) {
         int ret = mp_hal_i2c_read_byte(self, dest++, nack && (len == 0));
         if (ret != 0) {
@@ -669,7 +669,7 @@
 }
 
 int mp_machine_soft_i2c_write(mp_obj_base_t *self_in, const uint8_t *src, size_t len) {
-    machine_i2c_obj_t *self = (machine_i2c_obj_t*)self_in;
+    machine_i2c_obj_t *self = (machine_i2c_obj_t *)self_in;
     int num_acks = 0;
     while (len--) {
         int ret = mp_hal_i2c_write_byte(self, *src++);
@@ -685,8 +685,8 @@
 }
 
 STATIC const mp_machine_i2c_p_t mp_machine_soft_i2c_p = {
-    .start = (int(*)(mp_obj_base_t*))mp_hal_i2c_start,
-    .stop = (int(*)(mp_obj_base_t*))mp_hal_i2c_stop,
+    .start = (int (*)(mp_obj_base_t *))mp_hal_i2c_start,
+    .stop = (int (*)(mp_obj_base_t *))mp_hal_i2c_stop,
     .read = mp_machine_soft_i2c_read,
     .write = mp_machine_soft_i2c_write,
     .transfer = mp_machine_soft_i2c_transfer,
@@ -697,7 +697,7 @@
     .name = MP_QSTR_I2C,
     .make_new = machine_i2c_make_new,
     .protocol = &mp_machine_soft_i2c_p,
-    .locals_dict = (mp_obj_dict_t*)&mp_machine_soft_i2c_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&mp_machine_soft_i2c_locals_dict,
 };
 
 #endif // MICROPY_PY_MACHINE_I2C
diff --git a/extmod/machine_mem.c b/extmod/machine_mem.c
index c00dba3..88fa530 100644
--- a/extmod/machine_mem.c
+++ b/extmod/machine_mem.c
@@ -71,9 +71,15 @@
         uintptr_t addr = MICROPY_MACHINE_MEM_GET_READ_ADDR(index, self->elem_size);
         uint32_t val;
         switch (self->elem_size) {
-            case 1: val = (*(uint8_t*)addr); break;
-            case 2: val = (*(uint16_t*)addr); break;
-            default: val = (*(uint32_t*)addr); break;
+            case 1:
+                val = (*(uint8_t *)addr);
+                break;
+            case 2:
+                val = (*(uint16_t *)addr);
+                break;
+            default:
+                val = (*(uint32_t *)addr);
+                break;
         }
         return mp_obj_new_int(val);
     } else {
@@ -81,9 +87,15 @@
         uintptr_t addr = MICROPY_MACHINE_MEM_GET_WRITE_ADDR(index, self->elem_size);
         uint32_t val = mp_obj_get_int_truncated(value);
         switch (self->elem_size) {
-            case 1: (*(uint8_t*)addr) = val; break;
-            case 2: (*(uint16_t*)addr) = val; break;
-            default: (*(uint32_t*)addr) = val; break;
+            case 1:
+                (*(uint8_t *)addr) = val;
+                break;
+            case 2:
+                (*(uint16_t *)addr) = val;
+                break;
+            default:
+                (*(uint32_t *)addr) = val;
+                break;
         }
         return mp_const_none;
     }
diff --git a/extmod/machine_signal.c b/extmod/machine_signal.c
index 8204ef1..f112ddc 100644
--- a/extmod/machine_signal.c
+++ b/extmod/machine_signal.c
@@ -50,8 +50,8 @@
     mp_pin_p_t *pin_p = NULL;
 
     if (n_args > 0 && mp_obj_is_obj(args[0])) {
-        mp_obj_base_t *pin_base = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]);
-        pin_p = (mp_pin_p_t*)pin_base->type->protocol;
+        mp_obj_base_t *pin_base = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
+        pin_p = (mp_pin_p_t *)pin_base->type->protocol;
     }
 
     if (pin_p == NULL) {
@@ -90,8 +90,7 @@
         pin = MICROPY_PY_MACHINE_PIN_MAKE_NEW(NULL, n_args, n_kw, pin_args);
 
         mp_local_free(pin_args);
-    }
-    else
+    } else
     #endif
     // Otherwise there should be 1 or 2 args
     {
@@ -180,7 +179,7 @@
     .make_new = signal_make_new,
     .call = signal_call,
     .protocol = &signal_pin_p,
-    .locals_dict = (void*)&signal_locals_dict,
+    .locals_dict = (void *)&signal_locals_dict,
 };
 
 #endif // MICROPY_PY_MACHINE
diff --git a/extmod/machine_spi.c b/extmod/machine_spi.c
index f0c4896..f16ec26 100644
--- a/extmod/machine_spi.c
+++ b/extmod/machine_spi.c
@@ -64,16 +64,16 @@
 }
 
 STATIC mp_obj_t machine_spi_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
-    mp_obj_base_t *s = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]);
-    mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t*)s->type->protocol;
+    mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
+    mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t *)s->type->protocol;
     spi_p->init(s, n_args - 1, args + 1, kw_args);
     return mp_const_none;
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_KW(machine_spi_init_obj, 1, machine_spi_init);
 
 STATIC mp_obj_t machine_spi_deinit(mp_obj_t self) {
-    mp_obj_base_t *s = (mp_obj_base_t*)MP_OBJ_TO_PTR(self);
-    mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t*)s->type->protocol;
+    mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(self);
+    mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t *)s->type->protocol;
     if (spi_p->deinit != NULL) {
         spi_p->deinit(s);
     }
@@ -82,8 +82,8 @@
 STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_spi_deinit_obj, machine_spi_deinit);
 
 STATIC void mp_machine_spi_transfer(mp_obj_t self, size_t len, const void *src, void *dest) {
-    mp_obj_base_t *s = (mp_obj_base_t*)MP_OBJ_TO_PTR(self);
-    mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t*)s->type->protocol;
+    mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(self);
+    mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t *)s->type->protocol;
     spi_p->transfer(s, len, src, dest);
 }
 
@@ -108,7 +108,7 @@
 STATIC mp_obj_t mp_machine_spi_write(mp_obj_t self, mp_obj_t wr_buf) {
     mp_buffer_info_t src;
     mp_get_buffer_raise(wr_buf, &src, MP_BUFFER_READ);
-    mp_machine_spi_transfer(self, src.len, (const uint8_t*)src.buf, NULL);
+    mp_machine_spi_transfer(self, src.len, (const uint8_t *)src.buf, NULL);
     return mp_const_none;
 }
 MP_DEFINE_CONST_FUN_OBJ_2(mp_machine_spi_write_obj, mp_machine_spi_write);
@@ -223,7 +223,7 @@
 }
 
 STATIC void mp_machine_soft_spi_init(mp_obj_base_t *self_in, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
-    mp_machine_soft_spi_obj_t *self = (mp_machine_soft_spi_obj_t*)self_in;
+    mp_machine_soft_spi_obj_t *self = (mp_machine_soft_spi_obj_t *)self_in;
 
     enum { ARG_baudrate, ARG_polarity, ARG_phase, ARG_sck, ARG_mosi, ARG_miso };
     static const mp_arg_t allowed_args[] = {
@@ -261,7 +261,7 @@
 }
 
 STATIC void mp_machine_soft_spi_transfer(mp_obj_base_t *self_in, size_t len, const uint8_t *src, uint8_t *dest) {
-    mp_machine_soft_spi_obj_t *self = (mp_machine_soft_spi_obj_t*)self_in;
+    mp_machine_soft_spi_obj_t *self = (mp_machine_soft_spi_obj_t *)self_in;
     mp_soft_spi_transfer(&self->spi, len, src, dest);
 }
 
@@ -277,7 +277,7 @@
     .print = mp_machine_soft_spi_print,
     .make_new = mp_machine_spi_make_new, // delegate to master constructor
     .protocol = &mp_machine_soft_spi_p,
-    .locals_dict = (mp_obj_dict_t*)&mp_machine_spi_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&mp_machine_spi_locals_dict,
 };
 
 #endif // MICROPY_PY_MACHINE_SPI
diff --git a/extmod/modbluetooth.c b/extmod/modbluetooth.c
index af0289a..1d8a738 100644
--- a/extmod/modbluetooth.c
+++ b/extmod/modbluetooth.c
@@ -107,7 +107,7 @@
             self->type = MP_BLUETOOTH_UUID_TYPE_128;
             int uuid_i = 32;
             for (int i = 0; i < uuid_bufinfo.len; i++) {
-                char c = ((char*)uuid_bufinfo.buf)[i];
+                char c = ((char *)uuid_bufinfo.buf)[i];
                 if (c == '-') {
                     continue;
                 }
@@ -121,10 +121,10 @@
                 }
                 if (uuid_i % 2 == 0) {
                     // lower nibble
-                    self->data[uuid_i/2] |= c;
+                    self->data[uuid_i / 2] |= c;
                 } else {
                     // upper nibble
-                    self->data[uuid_i/2] = c << 4;
+                    self->data[uuid_i / 2] = c << 4;
                 }
             }
             if (uuid_i > 0) {
@@ -143,7 +143,8 @@
             // Use the QSTR hash function.
             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
     }
 }
 
@@ -323,7 +324,7 @@
                         // Get old buffer sizes and pointers
                         uint8_t *old_ringbuf_buf = self->ringbuf.buf;
                         size_t old_ringbuf_alloc = self->ringbuf.size;
-                        uint8_t *old_irq_data_buf = (uint8_t*)self->irq_data_data.data;
+                        uint8_t *old_irq_data_buf = (uint8_t *)self->irq_data_data.data;
                         size_t old_irq_data_alloc = self->irq_data_data_alloc;
 
                         // Atomically update the ringbuf and irq data
@@ -355,7 +356,7 @@
 STATIC mp_obj_t bluetooth_ble_irq(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
     enum { ARG_handler, ARG_trigger };
     static const mp_arg_t allowed_args[] = {
-        { MP_QSTR_handler, MP_ARG_OBJ|MP_ARG_REQUIRED, {.u_rom_obj = MP_ROM_NONE} },
+        { MP_QSTR_handler, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_rom_obj = MP_ROM_NONE} },
         { MP_QSTR_trigger, MP_ARG_INT, {.u_int = MP_BLUETOOTH_IRQ_ALL} },
     };
     mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
@@ -367,7 +368,7 @@
 
     // Update the callback.
     MICROPY_PY_BLUETOOTH_ENTER
-    mp_obj_bluetooth_ble_t* o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth));
+    mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth));
     o->irq_handler = callback;
     o->irq_trigger = args[ARG_trigger].u_int;
     MICROPY_PY_BLUETOOTH_EXIT
@@ -426,7 +427,7 @@
     mp_obj_t characteristic_obj;
 
     // Lists of characteristic uuids and flags.
-    mp_obj_bluetooth_uuid_t **characteristic_uuids = m_new(mp_obj_bluetooth_uuid_t*, len);
+    mp_obj_bluetooth_uuid_t **characteristic_uuids = m_new(mp_obj_bluetooth_uuid_t *, len);
     uint8_t *characteristic_flags = m_new(uint8_t, len);
 
     // Flattened list of descriptor uuids and flags. Grows (realloc) as more descriptors are encountered.
@@ -471,7 +472,7 @@
             }
 
             // Grow the flattened uuids and flags arrays with this many more descriptors.
-            descriptor_uuids = m_renew(mp_obj_bluetooth_uuid_t*, descriptor_uuids, descriptor_index, descriptor_index + num_descriptors[characteristic_index]);
+            descriptor_uuids = m_renew(mp_obj_bluetooth_uuid_t *, descriptor_uuids, descriptor_index, descriptor_index + num_descriptors[characteristic_index]);
             descriptor_flags = m_renew(uint8_t, descriptor_flags, descriptor_index, descriptor_index + num_descriptors[characteristic_index]);
 
             // Also grow the handles array.
@@ -520,7 +521,7 @@
 
     mp_obj_tuple_t *result = MP_OBJ_TO_PTR(mp_obj_new_tuple(len, NULL));
 
-    uint16_t **handles = m_new0(uint16_t*, len);
+    uint16_t **handles = m_new0(uint16_t *, len);
     size_t *num_handles = m_new0(size_t, len);
 
     // TODO: Add a `append` kwarg (defaulting to False) to make this behavior optional.
@@ -622,7 +623,7 @@
 
 STATIC mp_obj_t bluetooth_ble_gatts_read(mp_obj_t self_in, mp_obj_t value_handle_in) {
     size_t len = 0;
-    uint8_t* buf;
+    uint8_t *buf;
     mp_bluetooth_gatts_read(mp_obj_get_int(value_handle_in), &buf, &len);
     return mp_obj_new_bytes(buf, len);
 }
@@ -756,7 +757,7 @@
     { &mp_type_type },
     .name = MP_QSTR_BLE,
     .make_new = bluetooth_ble_make_new,
-    .locals_dict = (void*)&bluetooth_ble_locals_dict,
+    .locals_dict = (void *)&bluetooth_ble_locals_dict,
 };
 
 STATIC const mp_rom_map_elem_t mp_module_bluetooth_globals_table[] = {
@@ -772,14 +773,14 @@
 
 const mp_obj_module_t mp_module_ubluetooth = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_bluetooth_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_bluetooth_globals,
 };
 
 // Helpers
 
 #include <stdio.h>
 
-STATIC void ringbuf_extract(ringbuf_t* ringbuf, mp_obj_tuple_t *data_tuple, size_t n_u16, size_t n_u8, mp_obj_str_t *bytes_addr, size_t n_b, size_t n_i8, mp_obj_bluetooth_uuid_t *uuid, mp_obj_str_t *bytes_data) {
+STATIC void ringbuf_extract(ringbuf_t *ringbuf, mp_obj_tuple_t *data_tuple, size_t n_u16, size_t n_u8, mp_obj_str_t *bytes_addr, size_t n_b, size_t n_i8, mp_obj_bluetooth_uuid_t *uuid, mp_obj_str_t *bytes_data) {
     assert(ringbuf_avail(ringbuf) >= n_u16 * 2 + n_u8 + (bytes_addr ? 6 : 0) + n_b + n_i8 + (uuid ? 1 : 0) + (bytes_data ? 1 : 0));
     int j = 0;
 
@@ -793,7 +794,7 @@
         bytes_addr->len = 6;
         for (int i = 0; i < bytes_addr->len; ++i) {
             // cast away const, this is actually bt->irq_addr_bytes.
-            ((uint8_t*)bytes_addr->data)[i] = ringbuf_get(ringbuf);
+            ((uint8_t *)bytes_addr->data)[i] = ringbuf_get(ringbuf);
         }
         data_tuple->items[j++] = MP_OBJ_FROM_PTR(bytes_addr);
     }
@@ -815,7 +816,7 @@
         bytes_data->len = ringbuf_get(ringbuf);
         for (int i = 0; i < bytes_data->len; ++i) {
             // cast away const, this is actually bt->irq_data_bytes.
-            ((uint8_t*)bytes_data->data)[i] = ringbuf_get(ringbuf);
+            ((uint8_t *)bytes_data->data)[i] = ringbuf_get(ringbuf);
         }
         data_tuple->items[j++] = MP_OBJ_FROM_PTR(bytes_data);
     }
diff --git a/extmod/modbluetooth_nimble.c b/extmod/modbluetooth_nimble.c
index 903da5a..aa1b032 100644
--- a/extmod/modbluetooth_nimble.c
+++ b/extmod/modbluetooth_nimble.c
@@ -47,36 +47,36 @@
 #define DEBUG_EVENT_printf(...) //printf(__VA_ARGS__)
 
 STATIC int8_t ble_hs_err_to_errno_table[] = {
-    [BLE_HS_EAGAIN]             = MP_EAGAIN,
-    [BLE_HS_EALREADY]           = MP_EALREADY,
-    [BLE_HS_EINVAL]             = MP_EINVAL,
-    [BLE_HS_EMSGSIZE]           = MP_EIO,
-    [BLE_HS_ENOENT]             = MP_ENOENT,
-    [BLE_HS_ENOMEM]             = MP_ENOMEM,
-    [BLE_HS_ENOTCONN]           = MP_ENOTCONN,
-    [BLE_HS_ENOTSUP]            = MP_EOPNOTSUPP,
-    [BLE_HS_EAPP]               = MP_EIO,
-    [BLE_HS_EBADDATA]           = MP_EIO,
-    [BLE_HS_EOS]                = MP_EIO,
-    [BLE_HS_ECONTROLLER]        = MP_EIO,
-    [BLE_HS_ETIMEOUT]           = MP_ETIMEDOUT,
-    [BLE_HS_EDONE]              = MP_EIO,  // TODO: Maybe should be MP_EISCONN (connect uses this for "already connected").
-    [BLE_HS_EBUSY]              = MP_EBUSY,
-    [BLE_HS_EREJECT]            = MP_EIO,
-    [BLE_HS_EUNKNOWN]           = MP_EIO,
-    [BLE_HS_EROLE]              = MP_EIO,
-    [BLE_HS_ETIMEOUT_HCI]       = MP_EIO,
-    [BLE_HS_ENOMEM_EVT]         = MP_EIO,
-    [BLE_HS_ENOADDR]            = MP_EIO,
-    [BLE_HS_ENOTSYNCED]         = MP_EIO,
-    [BLE_HS_EAUTHEN]            = MP_EIO,
-    [BLE_HS_EAUTHOR]            = MP_EIO,
-    [BLE_HS_EENCRYPT]           = MP_EIO,
-    [BLE_HS_EENCRYPT_KEY_SZ]    = MP_EIO,
-    [BLE_HS_ESTORE_CAP]         = MP_EIO,
-    [BLE_HS_ESTORE_FAIL]        = MP_EIO,
-    [BLE_HS_EPREEMPTED]         = MP_EIO,
-    [BLE_HS_EDISABLED]          = MP_EIO,
+    [BLE_HS_EAGAIN] = MP_EAGAIN,
+    [BLE_HS_EALREADY] = MP_EALREADY,
+    [BLE_HS_EINVAL] = MP_EINVAL,
+    [BLE_HS_EMSGSIZE] = MP_EIO,
+    [BLE_HS_ENOENT] = MP_ENOENT,
+    [BLE_HS_ENOMEM] = MP_ENOMEM,
+    [BLE_HS_ENOTCONN] = MP_ENOTCONN,
+    [BLE_HS_ENOTSUP] = MP_EOPNOTSUPP,
+    [BLE_HS_EAPP] = MP_EIO,
+    [BLE_HS_EBADDATA] = MP_EIO,
+    [BLE_HS_EOS] = MP_EIO,
+    [BLE_HS_ECONTROLLER] = MP_EIO,
+    [BLE_HS_ETIMEOUT] = MP_ETIMEDOUT,
+    [BLE_HS_EDONE] = MP_EIO,               // TODO: Maybe should be MP_EISCONN (connect uses this for "already connected").
+    [BLE_HS_EBUSY] = MP_EBUSY,
+    [BLE_HS_EREJECT] = MP_EIO,
+    [BLE_HS_EUNKNOWN] = MP_EIO,
+    [BLE_HS_EROLE] = MP_EIO,
+    [BLE_HS_ETIMEOUT_HCI] = MP_EIO,
+    [BLE_HS_ENOMEM_EVT] = MP_EIO,
+    [BLE_HS_ENOADDR] = MP_EIO,
+    [BLE_HS_ENOTSYNCED] = MP_EIO,
+    [BLE_HS_EAUTHEN] = MP_EIO,
+    [BLE_HS_EAUTHOR] = MP_EIO,
+    [BLE_HS_EENCRYPT] = MP_EIO,
+    [BLE_HS_EENCRYPT_KEY_SZ] = MP_EIO,
+    [BLE_HS_ESTORE_CAP] = MP_EIO,
+    [BLE_HS_ESTORE_FAIL] = MP_EIO,
+    [BLE_HS_EPREEMPTED] = MP_EIO,
+    [BLE_HS_EDISABLED] = MP_EIO,
 };
 
 STATIC int ble_hs_err_to_errno(int err) {
@@ -88,22 +88,22 @@
 }
 
 // Note: modbluetooth UUIDs store their data in LE.
-STATIC ble_uuid_t* create_nimble_uuid(const mp_obj_bluetooth_uuid_t *uuid) {
+STATIC ble_uuid_t *create_nimble_uuid(const mp_obj_bluetooth_uuid_t *uuid) {
     if (uuid->type == MP_BLUETOOTH_UUID_TYPE_16) {
         ble_uuid16_t *result = m_new(ble_uuid16_t, 1);
         result->u.type = BLE_UUID_TYPE_16;
         result->value = (uuid->data[1] << 8) | uuid->data[0];
-        return (ble_uuid_t*)result;
+        return (ble_uuid_t *)result;
     } else if (uuid->type == MP_BLUETOOTH_UUID_TYPE_32) {
         ble_uuid32_t *result = m_new(ble_uuid32_t, 1);
         result->u.type = BLE_UUID_TYPE_32;
         result->value = (uuid->data[1] << 24) | (uuid->data[1] << 16) | (uuid->data[1] << 8) | uuid->data[0];
-        return (ble_uuid_t*)result;
+        return (ble_uuid_t *)result;
     } else if (uuid->type == MP_BLUETOOTH_UUID_TYPE_128) {
         ble_uuid128_t *result = m_new(ble_uuid128_t, 1);
         result->u.type = BLE_UUID_TYPE_128;
         memcpy(result->value, uuid->data, 16);
-        return (ble_uuid_t*)result;
+        return (ble_uuid_t *)result;
     } else {
         return NULL;
     }
@@ -139,7 +139,7 @@
 // modbluetooth (and the layers above it) work in BE for addresses, Nimble works in LE.
 STATIC void reverse_addr_byte_order(uint8_t *addr_out, const uint8_t *addr_in) {
     for (int i = 0; i < 6; ++i) {
-        addr_out[i] = addr_in[5-i];
+        addr_out[i] = addr_in[5 - i];
     }
 }
 
@@ -196,7 +196,7 @@
     }
 
     if (MP_BLUETOOTH_MAX_ATTR_SIZE > 20) {
-        rc = ble_att_set_preferred_mtu(MP_BLUETOOTH_MAX_ATTR_SIZE+3);
+        rc = ble_att_set_preferred_mtu(MP_BLUETOOTH_MAX_ATTR_SIZE + 3);
         assert(rc == 0);
     }
 
@@ -244,7 +244,7 @@
             create_gatts_db_entry(ctxt->dsc.handle);
 
             // Unlike characteristics, we have to manually provide a way to get the handle back to the register method.
-            *((uint16_t*)ctxt->dsc.dsc_def->arg) = ctxt->dsc.handle;
+            *((uint16_t *)ctxt->dsc.dsc_def->arg) = ctxt->dsc.handle;
             break;
 
         default:
@@ -622,7 +622,7 @@
     len = mp_bluetooth_gattc_on_data_available_start(event, conn_handle, value_handle, len);
     while (len > 0 && om != NULL) {
         size_t n = MIN(om->om_len, len);
-        mp_bluetooth_gattc_on_data_available_chunk(OS_MBUF_DATA(om, const uint8_t*), n);
+        mp_bluetooth_gattc_on_data_available_chunk(OS_MBUF_DATA(om, const uint8_t *), n);
         len -= n;
         om = SLIST_NEXT(om, om_next);
     }
@@ -642,7 +642,7 @@
         return 0;
     }
 
-    if (event->disc.event_type == BLE_HCI_ADV_RPT_EVTYPE_ADV_IND || event->disc.event_type ==  BLE_HCI_ADV_RPT_EVTYPE_NONCONN_IND) {
+    if (event->disc.event_type == BLE_HCI_ADV_RPT_EVTYPE_ADV_IND || event->disc.event_type == BLE_HCI_ADV_RPT_EVTYPE_NONCONN_IND) {
         bool connectable = event->disc.event_type == BLE_HCI_ADV_RPT_EVTYPE_ADV_IND;
         uint8_t addr[6];
         reverse_addr_byte_order(addr, event->disc.addr.val);
diff --git a/extmod/modbtree.c b/extmod/modbtree.c
index ffcd5c8..14dc8f3 100644
--- a/extmod/modbtree.c
+++ b/extmod/modbtree.c
@@ -57,9 +57,9 @@
 #endif
 
 #define CHECK_ERROR(res) \
-        if (res == RET_ERROR) { \
-            mp_raise_OSError(errno); \
-        }
+    if (res == RET_ERROR) { \
+        mp_raise_OSError(errno); \
+    }
 
 void __dbpanic(DB *db) {
     mp_printf(&mp_plat_print, "__dbpanic(%p)\n", db);
@@ -97,8 +97,8 @@
     (void)n_args;
     mp_obj_btree_t *self = MP_OBJ_TO_PTR(args[0]);
     DBT key, val;
-    key.data = (void*)mp_obj_str_get_data(args[1], &key.size);
-    val.data = (void*)mp_obj_str_get_data(args[2], &val.size);
+    key.data = (void *)mp_obj_str_get_data(args[1], &key.size);
+    val.data = (void *)mp_obj_str_get_data(args[2], &val.size);
     return MP_OBJ_NEW_SMALL_INT(__bt_put(self->db, &key, &val, 0));
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(btree_put_obj, 3, 4, btree_put);
@@ -106,7 +106,7 @@
 STATIC mp_obj_t btree_get(size_t n_args, const mp_obj_t *args) {
     mp_obj_btree_t *self = MP_OBJ_TO_PTR(args[0]);
     DBT key, val;
-    key.data = (void*)mp_obj_str_get_data(args[1], &key.size);
+    key.data = (void *)mp_obj_str_get_data(args[1], &key.size);
     int res = __bt_get(self->db, &key, &val, 0);
     if (res == RET_SPECIAL) {
         if (n_args > 2) {
@@ -125,7 +125,7 @@
     int flags = MP_OBJ_SMALL_INT_VALUE(args[1]);
     DBT key, val;
     if (n_args > 2) {
-        key.data = (void*)mp_obj_str_get_data(args[2], &key.size);
+        key.data = (void *)mp_obj_str_get_data(args[2], &key.size);
     }
 
     int res = __bt_seq(self->db, &key, &val, flags);
@@ -200,7 +200,7 @@
     if (self->start_key != MP_OBJ_NULL) {
         int flags = R_FIRST;
         if (self->start_key != mp_const_none) {
-            key.data = (void*)mp_obj_str_get_data(self->start_key, &key.size);
+            key.data = (void *)mp_obj_str_get_data(self->start_key, &key.size);
             flags = R_CURSOR;
         } else if (desc) {
             flags = R_LAST;
@@ -218,7 +218,7 @@
 
     if (self->end_key != mp_const_none) {
         DBT end_key;
-        end_key.data = (void*)mp_obj_str_get_data(self->end_key, &end_key.size);
+        end_key.data = (void *)mp_obj_str_get_data(self->end_key, &end_key.size);
         BTREE *t = self->db->internal;
         int cmp = t->bt_cmp(&key, &end_key);
         if (desc) {
@@ -253,7 +253,7 @@
     if (value == MP_OBJ_NULL) {
         // delete
         DBT key;
-        key.data = (void*)mp_obj_str_get_data(index, &key.size);
+        key.data = (void *)mp_obj_str_get_data(index, &key.size);
         int res = __bt_delete(self->db, &key, 0);
         if (res == RET_SPECIAL) {
             mp_raise_type(&mp_type_KeyError);
@@ -263,7 +263,7 @@
     } else if (value == MP_OBJ_SENTINEL) {
         // load
         DBT key, val;
-        key.data = (void*)mp_obj_str_get_data(index, &key.size);
+        key.data = (void *)mp_obj_str_get_data(index, &key.size);
         int res = __bt_get(self->db, &key, &val, 0);
         if (res == RET_SPECIAL) {
             mp_raise_type(&mp_type_KeyError);
@@ -273,8 +273,8 @@
     } else {
         // store
         DBT key, val;
-        key.data = (void*)mp_obj_str_get_data(index, &key.size);
-        val.data = (void*)mp_obj_str_get_data(value, &val.size);
+        key.data = (void *)mp_obj_str_get_data(index, &key.size);
+        val.data = (void *)mp_obj_str_get_data(value, &val.size);
         int res = __bt_put(self->db, &key, &val, 0);
         CHECK_ERROR(res);
         return mp_const_none;
@@ -286,7 +286,7 @@
     switch (op) {
         case MP_BINARY_OP_CONTAINS: {
             DBT key, val;
-            key.data = (void*)mp_obj_str_get_data(rhs_in, &key.size);
+            key.data = (void *)mp_obj_str_get_data(rhs_in, &key.size);
             int res = __bt_get(self->db, &key, &val, 0);
             CHECK_ERROR(res);
             return mp_obj_new_bool(res != RET_SPECIAL);
@@ -320,7 +320,7 @@
     .iternext = btree_iternext,
     .binary_op = btree_binary_op,
     .subscr = btree_subscr,
-    .locals_dict = (void*)&btree_locals_dict,
+    .locals_dict = (void *)&btree_locals_dict,
 };
 #endif
 
@@ -350,14 +350,14 @@
         mp_arg_val_t minkeypage;
     } args;
     mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
-        MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args);
+        MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args);
     BTREEINFO openinfo = {0};
     openinfo.flags = args.flags.u_int;
     openinfo.cachesize = args.cachesize.u_int;
     openinfo.psize = args.pagesize.u_int;
     openinfo.minkeypage = args.minkeypage.u_int;
 
-    DB *db = __bt_open(MP_OBJ_TO_PTR(pos_args[0]), &btree_stream_fvtable, &openinfo, /*dflags*/0);
+    DB *db = __bt_open(MP_OBJ_TO_PTR(pos_args[0]), &btree_stream_fvtable, &openinfo, /*dflags*/ 0);
     if (db == NULL) {
         mp_raise_OSError(errno);
     }
@@ -376,7 +376,7 @@
 
 const mp_obj_module_t mp_module_btree = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_btree_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_btree_globals,
 };
 #endif
 
diff --git a/extmod/modframebuf.c b/extmod/modframebuf.c
index 07b4a24..951cbcd 100644
--- a/extmod/modframebuf.c
+++ b/extmod/modframebuf.c
@@ -45,8 +45,8 @@
 STATIC const mp_obj_type_t mp_type_framebuf;
 #endif
 
-typedef void (*setpixel_t)(const mp_obj_framebuf_t*, int, int, uint32_t);
-typedef uint32_t (*getpixel_t)(const mp_obj_framebuf_t*, int, int);
+typedef void (*setpixel_t)(const mp_obj_framebuf_t *, int, int, uint32_t);
+typedef uint32_t (*getpixel_t)(const mp_obj_framebuf_t *, int, int);
 typedef void (*fill_rect_t)(const mp_obj_framebuf_t *, int, int, int, int, uint32_t);
 
 typedef struct _mp_framebuf_p_t {
@@ -69,20 +69,20 @@
 STATIC void mono_horiz_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) {
     size_t index = (x + y * fb->stride) >> 3;
     int offset = fb->format == FRAMEBUF_MHMSB ? x & 0x07 : 7 - (x & 0x07);
-    ((uint8_t*)fb->buf)[index] = (((uint8_t*)fb->buf)[index] & ~(0x01 << offset)) | ((col != 0) << offset);
+    ((uint8_t *)fb->buf)[index] = (((uint8_t *)fb->buf)[index] & ~(0x01 << offset)) | ((col != 0) << offset);
 }
 
 STATIC uint32_t mono_horiz_getpixel(const mp_obj_framebuf_t *fb, int x, int y) {
     size_t index = (x + y * fb->stride) >> 3;
     int offset = fb->format == FRAMEBUF_MHMSB ? x & 0x07 : 7 - (x & 0x07);
-    return (((uint8_t*)fb->buf)[index] >> (offset)) & 0x01;
+    return (((uint8_t *)fb->buf)[index] >> (offset)) & 0x01;
 }
 
 STATIC void mono_horiz_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) {
     int reverse = fb->format == FRAMEBUF_MHMSB;
     int advance = fb->stride >> 3;
     while (w--) {
-        uint8_t *b = &((uint8_t*)fb->buf)[(x >> 3) + y * advance];
+        uint8_t *b = &((uint8_t *)fb->buf)[(x >> 3) + y * advance];
         int offset = reverse ?  x & 7 : 7 - (x & 7);
         for (int hh = h; hh; --hh) {
             *b = (*b & ~(0x01 << offset)) | ((col != 0) << offset);
@@ -97,16 +97,16 @@
 STATIC void mvlsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) {
     size_t index = (y >> 3) * fb->stride + x;
     uint8_t offset = y & 0x07;
-    ((uint8_t*)fb->buf)[index] = (((uint8_t*)fb->buf)[index] & ~(0x01 << offset)) | ((col != 0) << offset);
+    ((uint8_t *)fb->buf)[index] = (((uint8_t *)fb->buf)[index] & ~(0x01 << offset)) | ((col != 0) << offset);
 }
 
 STATIC uint32_t mvlsb_getpixel(const mp_obj_framebuf_t *fb, int x, int y) {
-    return (((uint8_t*)fb->buf)[(y >> 3) * fb->stride + x] >> (y & 0x07)) & 0x01;
+    return (((uint8_t *)fb->buf)[(y >> 3) * fb->stride + x] >> (y & 0x07)) & 0x01;
 }
 
 STATIC void mvlsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) {
     while (h--) {
-        uint8_t *b = &((uint8_t*)fb->buf)[(y >> 3) * fb->stride + x];
+        uint8_t *b = &((uint8_t *)fb->buf)[(y >> 3) * fb->stride + x];
         uint8_t offset = y & 0x07;
         for (int ww = w; ww; --ww) {
             *b = (*b & ~(0x01 << offset)) | ((col != 0) << offset);
@@ -119,15 +119,15 @@
 // Functions for RGB565 format
 
 STATIC void rgb565_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) {
-    ((uint16_t*)fb->buf)[x + y * fb->stride] = col;
+    ((uint16_t *)fb->buf)[x + y * fb->stride] = col;
 }
 
 STATIC uint32_t rgb565_getpixel(const mp_obj_framebuf_t *fb, int x, int y) {
-    return ((uint16_t*)fb->buf)[x + y * fb->stride];
+    return ((uint16_t *)fb->buf)[x + y * fb->stride];
 }
 
 STATIC void rgb565_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) {
-    uint16_t *b = &((uint16_t*)fb->buf)[x + y * fb->stride];
+    uint16_t *b = &((uint16_t *)fb->buf)[x + y * fb->stride];
     while (h--) {
         for (int ww = w; ww; --ww) {
             *b++ = col;
@@ -139,7 +139,7 @@
 // Functions for GS2_HMSB format
 
 STATIC void gs2_hmsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) {
-    uint8_t *pixel = &((uint8_t*)fb->buf)[(x + y * fb->stride) >> 2];
+    uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride) >> 2];
     uint8_t shift = (x & 0x3) << 1;
     uint8_t mask = 0x3 << shift;
     uint8_t color = (col & 0x3) << shift;
@@ -147,14 +147,14 @@
 }
 
 STATIC uint32_t gs2_hmsb_getpixel(const mp_obj_framebuf_t *fb, int x, int y) {
-    uint8_t pixel = ((uint8_t*)fb->buf)[(x + y * fb->stride) >> 2];
+    uint8_t pixel = ((uint8_t *)fb->buf)[(x + y * fb->stride) >> 2];
     uint8_t shift = (x & 0x3) << 1;
     return (pixel >> shift) & 0x3;
 }
 
 STATIC void gs2_hmsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) {
-    for (int xx=x; xx < x+w; xx++) {
-        for (int yy=y; yy < y+h; yy++) {
+    for (int xx = x; xx < x + w; xx++) {
+        for (int yy = y; yy < y + h; yy++) {
             gs2_hmsb_setpixel(fb, xx, yy, col);
         }
     }
@@ -163,7 +163,7 @@
 // Functions for GS4_HMSB format
 
 STATIC void gs4_hmsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) {
-    uint8_t *pixel = &((uint8_t*)fb->buf)[(x + y * fb->stride) >> 1];
+    uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1];
 
     if (x % 2) {
         *pixel = ((uint8_t)col & 0x0f) | (*pixel & 0xf0);
@@ -174,15 +174,15 @@
 
 STATIC uint32_t gs4_hmsb_getpixel(const mp_obj_framebuf_t *fb, int x, int y) {
     if (x % 2) {
-        return ((uint8_t*)fb->buf)[(x + y * fb->stride) >> 1] & 0x0f;
+        return ((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1] & 0x0f;
     }
 
-    return ((uint8_t*)fb->buf)[(x + y * fb->stride) >> 1] >> 4;
+    return ((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1] >> 4;
 }
 
 STATIC void gs4_hmsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) {
     col &= 0x0f;
-    uint8_t *pixel_pair = &((uint8_t*)fb->buf)[(x + y * fb->stride) >> 1];
+    uint8_t *pixel_pair = &((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1];
     uint8_t col_shifted_left = col << 4;
     uint8_t col_pixel_pair = col_shifted_left | col;
     int pixel_count_till_next_line = (fb->stride - w) >> 1;
@@ -214,16 +214,16 @@
 // Functions for GS8 format
 
 STATIC void gs8_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) {
-    uint8_t *pixel = &((uint8_t*)fb->buf)[(x + y * fb->stride)];
+    uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride)];
     *pixel = col & 0xff;
 }
 
 STATIC uint32_t gs8_getpixel(const mp_obj_framebuf_t *fb, int x, int y) {
-    return ((uint8_t*)fb->buf)[(x + y * fb->stride)];
+    return ((uint8_t *)fb->buf)[(x + y * fb->stride)];
 }
 
 STATIC void gs8_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) {
-    uint8_t *pixel = &((uint8_t*)fb->buf)[(x + y * fb->stride)];
+    uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride)];
     while (h--) {
         memset(pixel, col, w);
         pixel += fb->stride;
@@ -397,9 +397,9 @@
     mp_int_t col = mp_obj_get_int(args[5]);
 
     fill_rect(self, x, y, w, 1, col);
-    fill_rect(self, x, y + h- 1, w, 1, col);
+    fill_rect(self, x, y + h - 1, w, 1, col);
     fill_rect(self, x, y, 1, h, col);
-    fill_rect(self, x + w- 1, y, 1, h, col);
+    fill_rect(self, x + w - 1, y, 1, h, col);
 
     return mp_const_none;
 }
@@ -436,9 +436,15 @@
     bool steep;
     if (dy > dx) {
         mp_int_t temp;
-        temp = x1; x1 = y1; y1 = temp;
-        temp = dx; dx = dy; dy = temp;
-        temp = sx; sx = sy; sy = temp;
+        temp = x1;
+        x1 = y1;
+        y1 = temp;
+        temp = dx;
+        dx = dy;
+        dy = temp;
+        temp = sx;
+        sx = sy;
+        sy = temp;
         steep = true;
     } else {
         steep = false;
@@ -491,7 +497,7 @@
         (y >= self->height) ||
         (-x >= source->width) ||
         (-y >= source->height)
-    ) {
+        ) {
         // Out of bounds, no-op.
         return mp_const_none;
     }
@@ -565,7 +571,7 @@
     // loop over chars
     for (; *str; ++str) {
         // get char and make sure its in range of font
-        int chr = *(uint8_t*)str;
+        int chr = *(uint8_t *)str;
         if (chr < 32 || chr > 127) {
             chr = 127;
         }
@@ -609,7 +615,7 @@
     .name = MP_QSTR_FrameBuffer,
     .make_new = framebuf_make_new,
     .buffer_p = { .get_buffer = framebuf_get_buffer },
-    .locals_dict = (mp_obj_dict_t*)&framebuf_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&framebuf_locals_dict,
 };
 #endif
 
@@ -654,7 +660,7 @@
 
 const mp_obj_module_t mp_module_framebuf = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&framebuf_module_globals,
+    .globals = (mp_obj_dict_t *)&framebuf_module_globals,
 };
 #endif
 
diff --git a/extmod/modlwip.c b/extmod/modlwip.c
index 4358544..b4fe46b 100644
--- a/extmod/modlwip.c
+++ b/extmod/modlwip.c
@@ -103,7 +103,7 @@
 void mod_lwip_deregister_poll(void (*poll)(void *arg), void *poll_arg);
 
 STATIC void slip_lwip_poll(void *netif) {
-    slipif_poll((struct netif*)netif);
+    slipif_poll((struct netif *)netif);
 }
 
 STATIC const mp_obj_type_t lwip_slip_type;
@@ -152,7 +152,7 @@
 
     struct netif *n = &lwip_slip_obj.lwip_netif;
     if (netif_add(n, &iplocal, IP_ADDR_BROADCAST, &ipremote, NULL, slipif_init, ip_input) == NULL) {
-       mp_raise_ValueError("out of memory");
+        mp_raise_ValueError("out of memory");
     }
     netif_set_up(n);
     netif_set_default(n);
@@ -178,7 +178,7 @@
     { &mp_type_type },
     .name = MP_QSTR_slip,
     .make_new = lwip_slip_make_new,
-    .locals_dict = (mp_obj_dict_t*)&lwip_slip_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&lwip_slip_locals_dict,
 };
 
 #endif // MICROPY_PY_LWIP_SLIP
@@ -190,7 +190,7 @@
 // lwIP 2 changed LWIP_VERSION and it can no longer be used in macros,
 // so we define our own equivalent version that can.
 #define LWIP_VERSION_MACRO (LWIP_VERSION_MAJOR << 24 | LWIP_VERSION_MINOR << 16 \
-                            | LWIP_VERSION_REVISION << 8 | LWIP_VERSION_RC)
+        | LWIP_VERSION_REVISION << 8 | LWIP_VERSION_RC)
 
 // Extension to lwIP error codes
 #define _ERR_BADF -16
@@ -313,11 +313,11 @@
 } lwip_socket_obj_t;
 
 static inline void poll_sockets(void) {
-#ifdef MICROPY_EVENT_POLL_HOOK
+    #ifdef MICROPY_EVENT_POLL_HOOK
     MICROPY_EVENT_POLL_HOOK;
-#else
+    #else
     mp_hal_delay_ms(1);
-#endif
+    #endif
 }
 
 STATIC struct tcp_pcb *volatile *lwip_socket_incoming_array(lwip_socket_obj_t *socket) {
@@ -370,7 +370,7 @@
 STATIC u8_t _lwip_raw_incoming(void *arg, struct raw_pcb *pcb, struct pbuf *p, const ip_addr_t *addr)
 #endif
 {
-    lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg;
+    lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg;
 
     if (socket->incoming.pbuf != NULL) {
         pbuf_free(p);
@@ -390,7 +390,7 @@
 STATIC void _lwip_udp_incoming(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *addr, u16_t port)
 #endif
 {
-    lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg;
+    lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg;
 
     if (socket->incoming.pbuf != NULL) {
         // That's why they call it "unreliable". No room in the inn, drop the packet.
@@ -404,7 +404,7 @@
 
 // Callback for general tcp errors.
 STATIC void _lwip_tcp_error(void *arg, err_t err) {
-    lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg;
+    lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg;
 
     // Free any incoming buffers or connections that are stored
     lwip_socket_free_incoming(socket);
@@ -416,7 +416,7 @@
 
 // Callback for tcp connection requests. Error code err is unused. (See tcp.h)
 STATIC err_t _lwip_tcp_connected(void *arg, struct tcp_pcb *tpcb, err_t err) {
-    lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg;
+    lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg;
 
     socket->state = STATE_CONNECTED;
     return ERR_OK;
@@ -425,15 +425,15 @@
 // Handle errors (eg connection aborted) on TCP PCBs that have been put on the
 // accept queue but are not yet actually accepted.
 STATIC void _lwip_tcp_err_unaccepted(void *arg, err_t err) {
-    struct tcp_pcb *pcb = (struct tcp_pcb*)arg;
+    struct tcp_pcb *pcb = (struct tcp_pcb *)arg;
 
     // The ->connected entry is repurposed to store the parent socket; this is safe
     // because it's only ever used by lwIP if tcp_connect is called on the TCP PCB.
-    lwip_socket_obj_t *socket = (lwip_socket_obj_t*)pcb->connected;
+    lwip_socket_obj_t *socket = (lwip_socket_obj_t *)pcb->connected;
 
     // Array is not volatile because thiss callback is executed within the lwIP context
     uint8_t alloc = socket->incoming.connection.alloc;
-    struct tcp_pcb **tcp_array = (struct tcp_pcb**)lwip_socket_incoming_array(socket);
+    struct tcp_pcb **tcp_array = (struct tcp_pcb **)lwip_socket_incoming_array(socket);
 
     // Search for PCB on the accept queue of the parent socket
     struct tcp_pcb **shift_down = NULL;
@@ -475,7 +475,7 @@
         return ERR_OK;
     }
 
-    lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg;
+    lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg;
     tcp_recv(newpcb, _lwip_tcp_recv_unaccepted);
 
     // Search for an empty slot to store the new connection
@@ -494,7 +494,7 @@
         // have a chance to take it off the accept queue.
         // The ->connected entry is repurposed to store the parent socket; this is safe
         // because it's only ever used by lwIP if tcp_connect is called on the TCP PCB.
-        newpcb->connected = (void*)socket;
+        newpcb->connected = (void *)socket;
         tcp_arg(newpcb, newpcb);
         tcp_err(newpcb, _lwip_tcp_err_unaccepted);
 
@@ -507,7 +507,7 @@
 
 // Callback for inbound tcp packets.
 STATIC err_t _lwip_tcp_recv(void *arg, struct tcp_pcb *tcpb, struct pbuf *p, err_t err) {
-    lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg;
+    lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg;
 
     if (p == NULL) {
         // Other side has closed connection.
@@ -600,7 +600,9 @@
         if (socket->timeout != -1) {
             for (mp_uint_t retries = socket->timeout / 100; retries--;) {
                 mp_hal_delay_ms(100);
-                if (socket->incoming.pbuf != NULL) break;
+                if (socket->incoming.pbuf != NULL) {
+                    break;
+                }
             }
             if (socket->incoming.pbuf == NULL) {
                 *_errno = MP_ETIMEDOUT;
@@ -633,20 +635,20 @@
 
 // For use in stream virtual methods
 #define STREAM_ERROR_CHECK(socket) \
-        if (socket->state < 0) { \
-            *_errno = error_lookup_table[-socket->state]; \
-            return MP_STREAM_ERROR; \
-        } \
-        assert(socket->pcb.tcp);
+    if (socket->state < 0) { \
+        *_errno = error_lookup_table[-socket->state]; \
+        return MP_STREAM_ERROR; \
+    } \
+    assert(socket->pcb.tcp);
 
 // Version of above for use when lock is held
 #define STREAM_ERROR_CHECK_WITH_LOCK(socket) \
-        if (socket->state < 0) { \
-            *_errno = error_lookup_table[-socket->state]; \
-            MICROPY_PY_LWIP_EXIT \
-            return MP_STREAM_ERROR; \
-        } \
-        assert(socket->pcb.tcp);
+    if (socket->state < 0) { \
+        *_errno = error_lookup_table[-socket->state]; \
+        MICROPY_PY_LWIP_EXIT \
+        return MP_STREAM_ERROR; \
+    } \
+    assert(socket->pcb.tcp);
 
 
 // Helper function for send/sendto to handle TCP packets
@@ -772,7 +774,7 @@
         len = remaining;
     }
 
-    memcpy(buf, (byte*)p->payload + socket->recv_offset, len);
+    memcpy(buf, (byte *)p->payload + socket->recv_offset, len);
 
     remaining -= len;
     if (remaining == 0) {
@@ -837,7 +839,8 @@
             break;
         }
         #endif
-        default: mp_raise_OSError(MP_EINVAL);
+        default:
+            mp_raise_OSError(MP_EINVAL);
     }
 
     if (socket->pcb.tcp == NULL) {
@@ -847,7 +850,7 @@
     switch (socket->type) {
         case MOD_NETWORK_SOCK_STREAM: {
             // Register the socket object as our callback argument.
-            tcp_arg(socket->pcb.tcp, (void*)socket);
+            tcp_arg(socket->pcb.tcp, (void *)socket);
             // Register our error callback.
             tcp_err(socket->pcb.tcp, _lwip_tcp_error);
             break;
@@ -855,14 +858,14 @@
         case MOD_NETWORK_SOCK_DGRAM: {
             // Register our receive callback now. Since UDP sockets don't require binding or connection
             // before use, there's no other good time to do it.
-            udp_recv(socket->pcb.udp, _lwip_udp_incoming, (void*)socket);
+            udp_recv(socket->pcb.udp, _lwip_udp_incoming, (void *)socket);
             break;
         }
         #if MICROPY_PY_LWIP_SOCK_RAW
         case MOD_NETWORK_SOCK_RAW: {
             // Register our receive callback now. Since raw sockets don't require binding or connection
             // before use, there's no other good time to do it.
-            raw_recv(socket->pcb.raw, _lwip_raw_incoming, (void*)socket);
+            raw_recv(socket->pcb.raw, _lwip_raw_incoming, (void *)socket);
             break;
         }
         #endif
@@ -926,7 +929,7 @@
         socket->incoming.connection.tcp.item = NULL;
     } else {
         socket->incoming.connection.alloc = backlog;
-        socket->incoming.connection.tcp.array = m_new0(struct tcp_pcb*, backlog);
+        socket->incoming.connection.tcp.array = m_new0(struct tcp_pcb *, backlog);
     }
     socket->incoming.connection.iget = 0;
     socket->incoming.connection.iput = 0;
@@ -1010,7 +1013,7 @@
     socket2->state = STATE_CONNECTED;
     socket2->recv_offset = 0;
     socket2->callback = MP_OBJ_NULL;
-    tcp_arg(socket2->pcb.tcp, (void*)socket2);
+    tcp_arg(socket2->pcb.tcp, (void *)socket2);
     tcp_err(socket2->pcb.tcp, _lwip_tcp_error);
     tcp_recv(socket2->pcb.tcp, _lwip_tcp_recv);
 
@@ -1073,7 +1076,9 @@
             if (socket->timeout != -1) {
                 for (mp_uint_t retries = socket->timeout / 100; retries--;) {
                     mp_hal_delay_ms(100);
-                    if (socket->state != STATE_CONNECTING) break;
+                    if (socket->state != STATE_CONNECTING) {
+                        break;
+                    }
                 }
                 if (socket->state == STATE_CONNECTING) {
                     mp_raise_OSError(MP_EINPROGRESS);
@@ -1084,9 +1089,9 @@
                 }
             }
             if (socket->state == STATE_CONNECTED) {
-               err = ERR_OK;
+                err = ERR_OK;
             } else {
-               err = socket->state;
+                err = socket->state;
             }
             break;
         }
@@ -1162,14 +1167,14 @@
     mp_uint_t ret = 0;
     switch (socket->type) {
         case MOD_NETWORK_SOCK_STREAM: {
-            ret = lwip_tcp_receive(socket, (byte*)vstr.buf, len, &_errno);
+            ret = lwip_tcp_receive(socket, (byte *)vstr.buf, len, &_errno);
             break;
         }
         case MOD_NETWORK_SOCK_DGRAM:
         #if MICROPY_PY_LWIP_SOCK_RAW
         case MOD_NETWORK_SOCK_RAW:
         #endif
-            ret = lwip_raw_udp_receive(socket, (byte*)vstr.buf, len, NULL, NULL, &_errno);
+            ret = lwip_raw_udp_receive(socket, (byte *)vstr.buf, len, NULL, NULL, &_errno);
             break;
     }
     if (ret == -1) {
@@ -1234,14 +1239,14 @@
         case MOD_NETWORK_SOCK_STREAM: {
             memcpy(ip, &socket->peer, sizeof(socket->peer));
             port = (mp_uint_t) socket->peer_port;
-            ret = lwip_tcp_receive(socket, (byte*)vstr.buf, len, &_errno);
+            ret = lwip_tcp_receive(socket, (byte *)vstr.buf, len, &_errno);
             break;
         }
         case MOD_NETWORK_SOCK_DGRAM:
         #if MICROPY_PY_LWIP_SOCK_RAW
         case MOD_NETWORK_SOCK_RAW:
         #endif
-            ret = lwip_raw_udp_receive(socket, (byte*)vstr.buf, len, ip, &port, &_errno);
+            ret = lwip_raw_udp_receive(socket, (byte *)vstr.buf, len, ip, &port, &_errno);
             break;
     }
     if (ret == -1) {
@@ -1289,7 +1294,7 @@
                     mp_raise_OSError(_errno);
                 }
                 bufinfo.len -= ret;
-                bufinfo.buf = (char*)bufinfo.buf + ret;
+                bufinfo.buf = (char *)bufinfo.buf + ret;
             }
             break;
         }
@@ -1367,7 +1372,7 @@
             }
 
             // POSIX setsockopt has order: group addr, if addr, lwIP has it vice-versa
-            err_t err = igmp_joingroup((ip_addr_t*)bufinfo.buf + 1, bufinfo.buf);
+            err_t err = igmp_joingroup((ip_addr_t *)bufinfo.buf + 1, bufinfo.buf);
             if (err != ERR_OK) {
                 mp_raise_OSError(error_lookup_table[-err]);
             }
@@ -1514,9 +1519,13 @@
                 }
                 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
-            case MOD_NETWORK_SOCK_RAW: raw_remove(socket->pcb.raw); break;
+            case MOD_NETWORK_SOCK_RAW:
+                raw_remove(socket->pcb.raw);
+                break;
             #endif
         }
 
@@ -1570,7 +1579,7 @@
     .print = lwip_socket_print,
     .make_new = lwip_socket_make_new,
     .protocol = &lwip_socket_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&lwip_socket_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&lwip_socket_locals_dict,
 };
 
 /******************************************************************************/
@@ -1590,18 +1599,18 @@
 // itself a "list" but isn't; we only support a single interface.
 
 typedef struct nic_poll {
-    void (* poll)(void *arg);
+    void (*poll)(void *arg);
     void *poll_arg;
 } nic_poll_t;
 
 STATIC nic_poll_t lwip_poll_list;
 
-void mod_lwip_register_poll(void (* poll)(void *arg), void *poll_arg) {
+void mod_lwip_register_poll(void (*poll)(void *arg), void *poll_arg) {
     lwip_poll_list.poll = poll;
     lwip_poll_list.poll_arg = poll_arg;
 }
 
-void mod_lwip_deregister_poll(void (* poll)(void *arg), void *poll_arg) {
+void mod_lwip_deregister_poll(void (*poll)(void *arg), void *poll_arg) {
     lwip_poll_list.poll = NULL;
 }
 
@@ -1668,9 +1677,9 @@
             }
         }
         if (!((family == 0 || family == MOD_NETWORK_AF_INET)
-            && (type == 0 || type == MOD_NETWORK_SOCK_STREAM)
-            && proto == 0
-            && flags == 0)) {
+              && (type == 0 || type == MOD_NETWORK_SOCK_STREAM)
+              && proto == 0
+              && flags == 0)) {
             mp_warning(MP_WARN_CAT(RuntimeWarning), "unsupported getaddrinfo constraints");
         }
     }
@@ -1679,7 +1688,7 @@
     state.status = 0;
 
     MICROPY_PY_LWIP_ENTER
-    err_t ret = dns_gethostbyname(host, (ip_addr_t*)&state.ipaddr, lwip_getaddrinfo_cb, &state);
+    err_t ret = dns_gethostbyname(host, (ip_addr_t *)&state.ipaddr, lwip_getaddrinfo_cb, &state);
     MICROPY_PY_LWIP_EXIT
 
     switch (ret) {
@@ -1707,8 +1716,8 @@
     tuple->items[1] = MP_OBJ_NEW_SMALL_INT(MOD_NETWORK_SOCK_STREAM);
     tuple->items[2] = MP_OBJ_NEW_SMALL_INT(0);
     tuple->items[3] = MP_OBJ_NEW_QSTR(MP_QSTR_);
-    tuple->items[4] = netutils_format_inet_addr((uint8_t*)&state.ipaddr, port, NETUTILS_BIG);
-    return mp_obj_new_list(1, (mp_obj_t*)&tuple);
+    tuple->items[4] = netutils_format_inet_addr((uint8_t *)&state.ipaddr, port, NETUTILS_BIG);
+    return mp_obj_new_list(1, (mp_obj_t *)&tuple);
 }
 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(lwip_getaddrinfo_obj, 2, 6, lwip_getaddrinfo);
 
@@ -1730,9 +1739,9 @@
     { MP_ROM_QSTR(MP_QSTR_print_pcbs), MP_ROM_PTR(&lwip_print_pcbs_obj) },
     // objects
     { MP_ROM_QSTR(MP_QSTR_socket), MP_ROM_PTR(&lwip_socket_type) },
-#ifdef MICROPY_PY_LWIP_SLIP
+    #ifdef MICROPY_PY_LWIP_SLIP
     { MP_ROM_QSTR(MP_QSTR_slip), MP_ROM_PTR(&lwip_slip_type) },
-#endif
+    #endif
     // class constants
     { MP_ROM_QSTR(MP_QSTR_AF_INET), MP_ROM_INT(MOD_NETWORK_AF_INET) },
     { MP_ROM_QSTR(MP_QSTR_AF_INET6), MP_ROM_INT(MOD_NETWORK_AF_INET6) },
@@ -1754,7 +1763,7 @@
 
 const mp_obj_module_t mp_module_lwip = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_lwip_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_lwip_globals,
 };
 
 #endif // MICROPY_PY_LWIP
diff --git a/extmod/modonewire.c b/extmod/modonewire.c
index 7ef4c3b..210bee3 100644
--- a/extmod/modonewire.c
+++ b/extmod/modonewire.c
@@ -126,7 +126,7 @@
     mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ);
     uint8_t crc = 0;
     for (size_t i = 0; i < bufinfo.len; ++i) {
-        uint8_t byte = ((uint8_t*)bufinfo.buf)[i];
+        uint8_t byte = ((uint8_t *)bufinfo.buf)[i];
         for (int b = 0; b < 8; ++b) {
             uint8_t fb_bit = (crc ^ byte) & 0x01;
             if (fb_bit == 0x01) {
@@ -158,5 +158,5 @@
 
 const mp_obj_module_t mp_module_onewire = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&onewire_module_globals,
+    .globals = (mp_obj_dict_t *)&onewire_module_globals,
 };
diff --git a/extmod/modubinascii.c b/extmod/modubinascii.c
index 8256a50..4a11d3e 100644
--- a/extmod/modubinascii.c
+++ b/extmod/modubinascii.c
@@ -53,7 +53,7 @@
         sep = mp_obj_str_get_str(args[1]);
     }
     vstr_init_len(&vstr, out_len);
-    byte *in = bufinfo.buf, *out = (byte*)vstr.buf;
+    byte *in = bufinfo.buf, *out = (byte *)vstr.buf;
     for (mp_uint_t i = bufinfo.len; i--;) {
         byte d = (*in >> 4);
         if (d > 9) {
@@ -82,7 +82,7 @@
     }
     vstr_t vstr;
     vstr_init_len(&vstr, bufinfo.len / 2);
-    byte *in = bufinfo.buf, *out = (byte*)vstr.buf;
+    byte *in = bufinfo.buf, *out = (byte *)vstr.buf;
     byte hex_byte = 0;
     for (mp_uint_t i = bufinfo.len; i--;) {
         byte hex_ch = *in++;
@@ -172,7 +172,7 @@
     vstr_init_len(&vstr, ((bufinfo.len != 0) ? (((bufinfo.len - 1) / 3) + 1) * 4 : 0) + 1);
 
     // First pass, we convert input buffer to numeric base 64 values
-    byte *in = bufinfo.buf, *out = (byte*)vstr.buf;
+    byte *in = bufinfo.buf, *out = (byte *)vstr.buf;
     mp_uint_t i;
     for (i = bufinfo.len; i >= 3; i -= 3) {
         *out++ = (in[0] & 0xFC) >> 2;
@@ -186,8 +186,7 @@
         if (i == 2) {
             *out++ = (in[0] & 0x03) << 4 | (in[1] & 0xF0) >> 4;
             *out++ = (in[1] & 0x0F) << 2;
-        }
-        else {
+        } else {
             *out++ = (in[0] & 0x03) << 4;
             *out++ = 64;
         }
@@ -195,7 +194,7 @@
     }
 
     // Second pass, we convert number base 64 values to actual base64 ascii encoding
-    out = (byte*)vstr.buf;
+    out = (byte *)vstr.buf;
     for (mp_uint_t j = vstr.len - 1; j--;) {
         if (*out < 26) {
             *out += 'A';
@@ -204,7 +203,7 @@
         } else if (*out < 62) {
             *out += '0' - 52;
         } else if (*out == 62) {
-            *out ='+';
+            *out = '+';
         } else if (*out == 63) {
             *out = '/';
         } else {
@@ -247,7 +246,7 @@
 
 const mp_obj_module_t mp_module_ubinascii = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_binascii_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_binascii_globals,
 };
 
 #endif //MICROPY_PY_UBINASCII
diff --git a/extmod/moducryptolib.c b/extmod/moducryptolib.c
index fd487a8..b15f10c 100644
--- a/extmod/moducryptolib.c
+++ b/extmod/moducryptolib.c
@@ -82,11 +82,11 @@
 typedef struct _mp_obj_aes_t {
     mp_obj_base_t base;
     AES_CTX_IMPL ctx;
-    uint8_t block_mode: 6;
+    uint8_t block_mode : 6;
 #define AES_KEYTYPE_NONE 0
 #define AES_KEYTYPE_ENC  1
 #define AES_KEYTYPE_DEC  2
-    uint8_t key_type: 2;
+    uint8_t key_type : 2;
 } mp_obj_aes_t;
 
 static inline bool is_ctr_mode(int block_mode) {
@@ -99,7 +99,7 @@
 
 static inline struct ctr_params *ctr_params_from_aes(mp_obj_aes_t *o) {
     // ctr_params follows aes object struct
-    return (struct ctr_params*)&o[1];
+    return (struct ctr_params *)&o[1];
 }
 
 #if MICROPY_SSL_AXTLS
@@ -117,7 +117,7 @@
 STATIC void aes_process_ecb_impl(AES_CTX_IMPL *ctx, const uint8_t in[16], uint8_t out[16], bool encrypt) {
     memcpy(out, in, 16);
     // We assume that out (vstr.buf or given output buffer) is uint32_t aligned
-    uint32_t *p = (uint32_t*)out;
+    uint32_t *p = (uint32_t *)out;
     // axTLS likes it weird and complicated with byteswaps
     for (int i = 0; i < 4; i++) {
         p[i] = MP_HTOBE32(p[i]);
@@ -289,7 +289,7 @@
         out_buf_ptr = out_bufinfo.buf;
     } else {
         vstr_init_len(&vstr, in_bufinfo.len);
-        out_buf_ptr = (uint8_t*)vstr.buf;
+        out_buf_ptr = (uint8_t *)vstr.buf;
     }
 
     if (AES_KEYTYPE_NONE == self->key_type) {
@@ -353,26 +353,26 @@
     { &mp_type_type },
     .name = MP_QSTR_aes,
     .make_new = ucryptolib_aes_make_new,
-    .locals_dict = (void*)&ucryptolib_aes_locals_dict,
+    .locals_dict = (void *)&ucryptolib_aes_locals_dict,
 };
 
 STATIC const mp_rom_map_elem_t mp_module_ucryptolib_globals_table[] = {
     { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ucryptolib) },
     { MP_ROM_QSTR(MP_QSTR_aes), MP_ROM_PTR(&ucryptolib_aes_type) },
-#if MICROPY_PY_UCRYPTOLIB_CONSTS
+    #if MICROPY_PY_UCRYPTOLIB_CONSTS
     { MP_ROM_QSTR(MP_QSTR_MODE_ECB), MP_ROM_INT(UCRYPTOLIB_MODE_ECB) },
     { MP_ROM_QSTR(MP_QSTR_MODE_CBC), MP_ROM_INT(UCRYPTOLIB_MODE_CBC) },
     #if MICROPY_PY_UCRYPTOLIB_CTR
     { MP_ROM_QSTR(MP_QSTR_MODE_CTR), MP_ROM_INT(UCRYPTOLIB_MODE_CTR) },
     #endif
-#endif
+    #endif
 };
 
 STATIC MP_DEFINE_CONST_DICT(mp_module_ucryptolib_globals, mp_module_ucryptolib_globals_table);
 
 const mp_obj_module_t mp_module_ucryptolib = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_ucryptolib_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_ucryptolib_globals,
 };
 
 #endif //MICROPY_PY_UCRYPTOLIB
diff --git a/extmod/moductypes.c b/extmod/moductypes.c
index 62bbcba..5446f7b 100644
--- a/extmod/moductypes.c
+++ b/extmod/moductypes.c
@@ -124,7 +124,7 @@
     mp_arg_check_num(n_args, n_kw, 2, 3, false);
     mp_obj_uctypes_struct_t *o = m_new_obj(mp_obj_uctypes_struct_t);
     o->base.type = type;
-    o->addr = (void*)(uintptr_t)mp_obj_int_get_truncated(args[0]);
+    o->addr = (void *)(uintptr_t)mp_obj_int_get_truncated(args[0]);
     o->desc = args[1];
     o->flags = LAYOUT_NATIVE;
     if (n_args == 3) {
@@ -138,18 +138,22 @@
     mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in);
     const char *typen = "unk";
     if (mp_obj_is_type(self->desc, &mp_type_dict)
-      #if MICROPY_PY_COLLECTIONS_ORDEREDDICT
+        #if MICROPY_PY_COLLECTIONS_ORDEREDDICT
         || mp_obj_is_type(self->desc, &mp_type_ordereddict)
-      #endif
-      ) {
+        #endif
+        ) {
         typen = "STRUCT";
     } else if (mp_obj_is_type(self->desc, &mp_type_tuple)) {
         mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->desc);
         mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]);
         uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS);
         switch (agg_type) {
-            case PTR: typen = "PTR"; break;
-            case ARRAY: typen = "ARRAY"; break;
+            case PTR:
+                typen = "PTR";
+                break;
+            case ARRAY:
+                typen = "ARRAY";
+                break;
         }
     } else {
         typen = "ERROR";
@@ -180,10 +184,10 @@
         case STRUCT:
             return uctypes_struct_size(t->items[1], layout_type, max_field_size);
         case PTR:
-            if (sizeof(void*) > *max_field_size) {
-                *max_field_size = sizeof(void*);
+            if (sizeof(void *) > *max_field_size) {
+                *max_field_size = sizeof(void *);
             }
-            return sizeof(void*);
+            return sizeof(void *);
         case ARRAY: {
             mp_int_t arr_sz = MP_OBJ_SMALL_INT_VALUE(t->items[1]);
             uint val_type = GET_TYPE(arr_sz, VAL_TYPE_BITS);
@@ -211,12 +215,12 @@
 
 STATIC mp_uint_t uctypes_struct_size(mp_obj_t desc_in, int layout_type, mp_uint_t *max_field_size) {
     if (!mp_obj_is_type(desc_in, &mp_type_dict)
-      #if MICROPY_PY_COLLECTIONS_ORDEREDDICT
+        #if MICROPY_PY_COLLECTIONS_ORDEREDDICT
         && !mp_obj_is_type(desc_in, &mp_type_ordereddict)
-      #endif
-      ) {
+        #endif
+        ) {
         if (mp_obj_is_type(desc_in, &mp_type_tuple)) {
-            return uctypes_struct_agg_size((mp_obj_tuple_t*)MP_OBJ_TO_PTR(desc_in), layout_type, max_field_size);
+            return uctypes_struct_agg_size((mp_obj_tuple_t *)MP_OBJ_TO_PTR(desc_in), layout_type, max_field_size);
         } else if (mp_obj_is_small_int(desc_in)) {
             // We allow sizeof on both type definitions and structures/structure fields,
             // but scalar structure field is lowered into native Python int, so all
@@ -311,11 +315,11 @@
 static inline mp_uint_t get_aligned_basic(uint val_type, void *p) {
     switch (val_type) {
         case UINT8:
-            return *(uint8_t*)p;
+            return *(uint8_t *)p;
         case UINT16:
-            return *(uint16_t*)p;
+            return *(uint16_t *)p;
         case UINT32:
-            return *(uint32_t*)p;
+            return *(uint32_t *)p;
     }
     assert(0);
     return 0;
@@ -324,11 +328,14 @@
 static inline void set_aligned_basic(uint val_type, void *p, mp_uint_t v) {
     switch (val_type) {
         case UINT8:
-            *(uint8_t*)p = (uint8_t)v; return;
+            *(uint8_t *)p = (uint8_t)v;
+            return;
         case UINT16:
-            *(uint16_t*)p = (uint16_t)v; return;
+            *(uint16_t *)p = (uint16_t)v;
+            return;
         case UINT32:
-            *(uint32_t*)p = (uint32_t)v; return;
+            *(uint32_t *)p = (uint32_t)v;
+            return;
     }
     assert(0);
 }
@@ -336,26 +343,26 @@
 STATIC mp_obj_t get_aligned(uint val_type, void *p, mp_int_t index) {
     switch (val_type) {
         case UINT8:
-            return MP_OBJ_NEW_SMALL_INT(((uint8_t*)p)[index]);
+            return MP_OBJ_NEW_SMALL_INT(((uint8_t *)p)[index]);
         case INT8:
-            return MP_OBJ_NEW_SMALL_INT(((int8_t*)p)[index]);
+            return MP_OBJ_NEW_SMALL_INT(((int8_t *)p)[index]);
         case UINT16:
-            return MP_OBJ_NEW_SMALL_INT(((uint16_t*)p)[index]);
+            return MP_OBJ_NEW_SMALL_INT(((uint16_t *)p)[index]);
         case INT16:
-            return MP_OBJ_NEW_SMALL_INT(((int16_t*)p)[index]);
+            return MP_OBJ_NEW_SMALL_INT(((int16_t *)p)[index]);
         case UINT32:
-            return mp_obj_new_int_from_uint(((uint32_t*)p)[index]);
+            return mp_obj_new_int_from_uint(((uint32_t *)p)[index]);
         case INT32:
-            return mp_obj_new_int(((int32_t*)p)[index]);
+            return mp_obj_new_int(((int32_t *)p)[index]);
         case UINT64:
-            return mp_obj_new_int_from_ull(((uint64_t*)p)[index]);
+            return mp_obj_new_int_from_ull(((uint64_t *)p)[index]);
         case INT64:
-            return mp_obj_new_int_from_ll(((int64_t*)p)[index]);
+            return mp_obj_new_int_from_ll(((int64_t *)p)[index]);
         #if MICROPY_PY_BUILTINS_FLOAT
         case FLOAT32:
-            return mp_obj_new_float(((float*)p)[index]);
+            return mp_obj_new_float(((float *)p)[index]);
         case FLOAT64:
-            return mp_obj_new_float(((double*)p)[index]);
+            return mp_obj_new_float(((double *)p)[index]);
         #endif
         default:
             assert(0);
@@ -368,9 +375,9 @@
     if (val_type == FLOAT32 || val_type == FLOAT64) {
         mp_float_t v = mp_obj_get_float(val);
         if (val_type == FLOAT32) {
-            ((float*)p)[index] = v;
+            ((float *)p)[index] = v;
         } else {
-            ((double*)p)[index] = v;
+            ((double *)p)[index] = v;
         }
         return;
     }
@@ -378,21 +385,27 @@
     mp_int_t v = mp_obj_get_int_truncated(val);
     switch (val_type) {
         case UINT8:
-            ((uint8_t*)p)[index] = (uint8_t)v; return;
+            ((uint8_t *)p)[index] = (uint8_t)v;
+            return;
         case INT8:
-            ((int8_t*)p)[index] = (int8_t)v; return;
+            ((int8_t *)p)[index] = (int8_t)v;
+            return;
         case UINT16:
-            ((uint16_t*)p)[index] = (uint16_t)v; return;
+            ((uint16_t *)p)[index] = (uint16_t)v;
+            return;
         case INT16:
-            ((int16_t*)p)[index] = (int16_t)v; return;
+            ((int16_t *)p)[index] = (int16_t)v;
+            return;
         case UINT32:
-            ((uint32_t*)p)[index] = (uint32_t)v; return;
+            ((uint32_t *)p)[index] = (uint32_t)v;
+            return;
         case INT32:
-            ((int32_t*)p)[index] = (int32_t)v; return;
+            ((int32_t *)p)[index] = (int32_t)v;
+            return;
         case INT64:
         case UINT64:
             if (sizeof(mp_int_t) == 8) {
-                ((uint64_t*)p)[index] = (uint64_t)v;
+                ((uint64_t *)p)[index] = (uint64_t)v;
             } else {
                 // TODO: Doesn't offer atomic store semantics, but should at least try
                 set_unaligned(val_type, p, MP_ENDIANNESS_BIG, val);
@@ -407,11 +420,11 @@
     mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in);
 
     if (!mp_obj_is_type(self->desc, &mp_type_dict)
-      #if MICROPY_PY_COLLECTIONS_ORDEREDDICT
+        #if MICROPY_PY_COLLECTIONS_ORDEREDDICT
         && !mp_obj_is_type(self->desc, &mp_type_ordereddict)
-      #endif
-      ) {
-            mp_raise_TypeError("struct: no fields");
+        #endif
+        ) {
+        mp_raise_TypeError("struct: no fields");
     }
 
     mp_obj_t deref = mp_obj_dict_get(self->desc, MP_OBJ_NEW_QSTR(attr));
@@ -593,7 +606,7 @@
             }
 
         } else if (agg_type == PTR) {
-            byte *p = *(void**)self->addr;
+            byte *p = *(void **)self->addr;
             if (mp_obj_is_small_int(t->items[1])) {
                 uint val_type = GET_TYPE(MP_OBJ_SMALL_INT_VALUE(t->items[1]), VAL_TYPE_BITS);
                 return get_aligned(val_type, p, index);
@@ -623,13 +636,14 @@
                 mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]);
                 uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS);
                 if (agg_type == PTR) {
-                    byte *p = *(void**)self->addr;
+                    byte *p = *(void **)self->addr;
                     return mp_obj_new_int((mp_int_t)(uintptr_t)p);
                 }
             }
-            /* fallthru */
+        /* fallthru */
 
-        default: return MP_OBJ_NULL; // op not supported
+        default:
+            return MP_OBJ_NULL;      // op not supported
     }
 }
 
@@ -660,7 +674,7 @@
 /// captured by reference (and thus memory pointed by bytearray may change
 /// or become invalid at later time). Use bytes_at() to capture by value.
 STATIC mp_obj_t uctypes_struct_bytearray_at(mp_obj_t ptr, mp_obj_t size) {
-    return mp_obj_new_bytearray_by_ref(mp_obj_int_get_truncated(size), (void*)(uintptr_t)mp_obj_int_get_truncated(ptr));
+    return mp_obj_new_bytearray_by_ref(mp_obj_int_get_truncated(size), (void *)(uintptr_t)mp_obj_int_get_truncated(ptr));
 }
 MP_DEFINE_CONST_FUN_OBJ_2(uctypes_struct_bytearray_at_obj, uctypes_struct_bytearray_at);
 
@@ -669,7 +683,7 @@
 /// captured by value, i.e. copied. Use bytearray_at() to capture by reference
 /// ("zero copy").
 STATIC mp_obj_t uctypes_struct_bytes_at(mp_obj_t ptr, mp_obj_t size) {
-    return mp_obj_new_bytes((void*)(uintptr_t)mp_obj_int_get_truncated(ptr), mp_obj_int_get_truncated(size));
+    return mp_obj_new_bytes((void *)(uintptr_t)mp_obj_int_get_truncated(ptr), mp_obj_int_get_truncated(size));
 }
 MP_DEFINE_CONST_FUN_OBJ_2(uctypes_struct_bytes_at_obj, uctypes_struct_bytes_at);
 
@@ -772,7 +786,7 @@
 
 const mp_obj_module_t mp_module_uctypes = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_uctypes_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_uctypes_globals,
 };
 
 #endif
diff --git a/extmod/moduhashlib.c b/extmod/moduhashlib.c
index 603cdb4..fb786f3 100644
--- a/extmod/moduhashlib.c
+++ b/extmod/moduhashlib.c
@@ -78,8 +78,8 @@
     mp_arg_check_num(n_args, n_kw, 0, 1, false);
     mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_sha256_context));
     o->base.type = type;
-    mbedtls_sha256_init((mbedtls_sha256_context*)&o->state);
-    mbedtls_sha256_starts_ret((mbedtls_sha256_context*)&o->state, 0);
+    mbedtls_sha256_init((mbedtls_sha256_context *)&o->state);
+    mbedtls_sha256_starts_ret((mbedtls_sha256_context *)&o->state, 0);
     if (n_args == 1) {
         uhashlib_sha256_update(MP_OBJ_FROM_PTR(o), args[0]);
     }
@@ -90,7 +90,7 @@
     mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
     mp_buffer_info_t bufinfo;
     mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ);
-    mbedtls_sha256_update_ret((mbedtls_sha256_context*)&self->state, bufinfo.buf, bufinfo.len);
+    mbedtls_sha256_update_ret((mbedtls_sha256_context *)&self->state, bufinfo.buf, bufinfo.len);
     return mp_const_none;
 }
 
@@ -98,7 +98,7 @@
     mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
     vstr_t vstr;
     vstr_init_len(&vstr, 32);
-    mbedtls_sha256_finish_ret((mbedtls_sha256_context*)&self->state, (unsigned char *)vstr.buf);
+    mbedtls_sha256_finish_ret((mbedtls_sha256_context *)&self->state, (unsigned char *)vstr.buf);
     return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
 }
 
@@ -110,7 +110,7 @@
     mp_arg_check_num(n_args, n_kw, 0, 1, false);
     mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(CRYAL_SHA256_CTX));
     o->base.type = type;
-    sha256_init((CRYAL_SHA256_CTX*)o->state);
+    sha256_init((CRYAL_SHA256_CTX *)o->state);
     if (n_args == 1) {
         uhashlib_sha256_update(MP_OBJ_FROM_PTR(o), args[0]);
     }
@@ -121,7 +121,7 @@
     mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
     mp_buffer_info_t bufinfo;
     mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ);
-    sha256_update((CRYAL_SHA256_CTX*)self->state, bufinfo.buf, bufinfo.len);
+    sha256_update((CRYAL_SHA256_CTX *)self->state, bufinfo.buf, bufinfo.len);
     return mp_const_none;
 }
 
@@ -129,7 +129,7 @@
     mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
     vstr_t vstr;
     vstr_init_len(&vstr, SHA256_BLOCK_SIZE);
-    sha256_final((CRYAL_SHA256_CTX*)self->state, (byte*)vstr.buf);
+    sha256_final((CRYAL_SHA256_CTX *)self->state, (byte *)vstr.buf);
     return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
 }
 #endif
@@ -148,7 +148,7 @@
     { &mp_type_type },
     .name = MP_QSTR_sha256,
     .make_new = uhashlib_sha256_make_new,
-    .locals_dict = (void*)&uhashlib_sha256_locals_dict,
+    .locals_dict = (void *)&uhashlib_sha256_locals_dict,
 };
 #endif
 
@@ -160,7 +160,7 @@
     mp_arg_check_num(n_args, n_kw, 0, 1, false);
     mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(SHA1_CTX));
     o->base.type = type;
-    SHA1_Init((SHA1_CTX*)o->state);
+    SHA1_Init((SHA1_CTX *)o->state);
     if (n_args == 1) {
         uhashlib_sha1_update(MP_OBJ_FROM_PTR(o), args[0]);
     }
@@ -171,7 +171,7 @@
     mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
     mp_buffer_info_t bufinfo;
     mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ);
-    SHA1_Update((SHA1_CTX*)self->state, bufinfo.buf, bufinfo.len);
+    SHA1_Update((SHA1_CTX *)self->state, bufinfo.buf, bufinfo.len);
     return mp_const_none;
 }
 
@@ -179,7 +179,7 @@
     mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
     vstr_t vstr;
     vstr_init_len(&vstr, SHA1_SIZE);
-    SHA1_Final((byte*)vstr.buf, (SHA1_CTX*)self->state);
+    SHA1_Final((byte *)vstr.buf, (SHA1_CTX *)self->state);
     return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
 }
 #endif
@@ -196,8 +196,8 @@
     mp_arg_check_num(n_args, n_kw, 0, 1, false);
     mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_sha1_context));
     o->base.type = type;
-    mbedtls_sha1_init((mbedtls_sha1_context*)o->state);
-    mbedtls_sha1_starts_ret((mbedtls_sha1_context*)o->state);
+    mbedtls_sha1_init((mbedtls_sha1_context *)o->state);
+    mbedtls_sha1_starts_ret((mbedtls_sha1_context *)o->state);
     if (n_args == 1) {
         uhashlib_sha1_update(MP_OBJ_FROM_PTR(o), args[0]);
     }
@@ -208,7 +208,7 @@
     mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
     mp_buffer_info_t bufinfo;
     mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ);
-    mbedtls_sha1_update_ret((mbedtls_sha1_context*)self->state, bufinfo.buf, bufinfo.len);
+    mbedtls_sha1_update_ret((mbedtls_sha1_context *)self->state, bufinfo.buf, bufinfo.len);
     return mp_const_none;
 }
 
@@ -216,8 +216,8 @@
     mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
     vstr_t vstr;
     vstr_init_len(&vstr, 20);
-    mbedtls_sha1_finish_ret((mbedtls_sha1_context*)self->state, (byte*)vstr.buf);
-    mbedtls_sha1_free((mbedtls_sha1_context*)self->state);
+    mbedtls_sha1_finish_ret((mbedtls_sha1_context *)self->state, (byte *)vstr.buf);
+    mbedtls_sha1_free((mbedtls_sha1_context *)self->state);
     return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
 }
 #endif
@@ -235,7 +235,7 @@
     { &mp_type_type },
     .name = MP_QSTR_sha1,
     .make_new = uhashlib_sha1_make_new,
-    .locals_dict = (void*)&uhashlib_sha1_locals_dict,
+    .locals_dict = (void *)&uhashlib_sha1_locals_dict,
 };
 #endif
 
@@ -247,7 +247,7 @@
     mp_arg_check_num(n_args, n_kw, 0, 1, false);
     mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(MD5_CTX));
     o->base.type = type;
-    MD5_Init((MD5_CTX*)o->state);
+    MD5_Init((MD5_CTX *)o->state);
     if (n_args == 1) {
         uhashlib_md5_update(MP_OBJ_FROM_PTR(o), args[0]);
     }
@@ -258,7 +258,7 @@
     mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
     mp_buffer_info_t bufinfo;
     mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ);
-    MD5_Update((MD5_CTX*)self->state, bufinfo.buf, bufinfo.len);
+    MD5_Update((MD5_CTX *)self->state, bufinfo.buf, bufinfo.len);
     return mp_const_none;
 }
 
@@ -266,7 +266,7 @@
     mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
     vstr_t vstr;
     vstr_init_len(&vstr, MD5_SIZE);
-    MD5_Final((byte*)vstr.buf, (MD5_CTX*)self->state);
+    MD5_Final((byte *)vstr.buf, (MD5_CTX *)self->state);
     return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
 }
 #endif // MICROPY_SSL_AXTLS
@@ -283,8 +283,8 @@
     mp_arg_check_num(n_args, n_kw, 0, 1, false);
     mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_md5_context));
     o->base.type = type;
-    mbedtls_md5_init((mbedtls_md5_context*)o->state);
-    mbedtls_md5_starts_ret((mbedtls_md5_context*)o->state);
+    mbedtls_md5_init((mbedtls_md5_context *)o->state);
+    mbedtls_md5_starts_ret((mbedtls_md5_context *)o->state);
     if (n_args == 1) {
         uhashlib_md5_update(MP_OBJ_FROM_PTR(o), args[0]);
     }
@@ -295,7 +295,7 @@
     mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
     mp_buffer_info_t bufinfo;
     mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ);
-    mbedtls_md5_update_ret((mbedtls_md5_context*)self->state, bufinfo.buf, bufinfo.len);
+    mbedtls_md5_update_ret((mbedtls_md5_context *)self->state, bufinfo.buf, bufinfo.len);
     return mp_const_none;
 }
 
@@ -303,8 +303,8 @@
     mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
     vstr_t vstr;
     vstr_init_len(&vstr, 16);
-    mbedtls_md5_finish_ret((mbedtls_md5_context*)self->state, (byte*)vstr.buf);
-    mbedtls_md5_free((mbedtls_md5_context*)self->state);
+    mbedtls_md5_finish_ret((mbedtls_md5_context *)self->state, (byte *)vstr.buf);
+    mbedtls_md5_free((mbedtls_md5_context *)self->state);
     return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
 }
 #endif // MICROPY_SSL_MBEDTLS
@@ -322,7 +322,7 @@
     { &mp_type_type },
     .name = MP_QSTR_md5,
     .make_new = uhashlib_md5_make_new,
-    .locals_dict = (void*)&uhashlib_md5_locals_dict,
+    .locals_dict = (void *)&uhashlib_md5_locals_dict,
 };
 #endif // MICROPY_PY_UHASHLIB_MD5
 
@@ -343,7 +343,7 @@
 
 const mp_obj_module_t mp_module_uhashlib = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_uhashlib_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_uhashlib_globals,
 };
 
 #endif //MICROPY_PY_UHASHLIB
diff --git a/extmod/moduheapq.c b/extmod/moduheapq.c
index 2e80101..0ba955e 100644
--- a/extmod/moduheapq.c
+++ b/extmod/moduheapq.c
@@ -115,7 +115,7 @@
 
 const mp_obj_module_t mp_module_uheapq = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_uheapq_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_uheapq_globals,
 };
 #endif
 
diff --git a/extmod/modujson.c b/extmod/modujson.c
index b7c5121..048a19a 100644
--- a/extmod/modujson.c
+++ b/extmod/modujson.c
@@ -100,7 +100,7 @@
     mp_obj_t stack_key = MP_OBJ_NULL;
     S_NEXT(s);
     for (;;) {
-        cont:
+    cont:
         if (S_END(s)) {
             break;
         }
@@ -147,11 +147,21 @@
                     if (c == '\\') {
                         c = S_NEXT(s);
                         switch (c) {
-                            case 'b': c = 0x08; break;
-                            case 'f': c = 0x0c; break;
-                            case 'n': c = 0x0a; break;
-                            case 'r': c = 0x0d; break;
-                            case 't': c = 0x09; break;
+                            case 'b':
+                                c = 0x08;
+                                break;
+                            case 'f':
+                                c = 0x0c;
+                                break;
+                            case 'n':
+                                c = 0x0a;
+                                break;
+                            case 'r':
+                                c = 0x0d;
+                                break;
+                            case 't':
+                                c = 0x09;
+                                break;
                             case 'u': {
                                 mp_uint_t num = 0;
                                 for (int i = 0; i < 4; i++) {
@@ -177,7 +187,16 @@
                 next = mp_obj_new_str(vstr.buf, vstr.len);
                 break;
             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;
                 vstr_reset(&vstr);
                 for (;;) {
@@ -259,7 +278,7 @@
             }
         }
     }
-    success:
+success:
     // eat trailing whitespace
     while (unichar_isspace(S_CUR(s))) {
         S_NEXT(s);
@@ -275,7 +294,7 @@
     vstr_clear(&vstr);
     return stack_top;
 
-    fail:
+fail:
     mp_raise_ValueError("syntax error in JSON");
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_load_obj, mod_ujson_load);
@@ -283,7 +302,7 @@
 STATIC mp_obj_t mod_ujson_loads(mp_obj_t obj) {
     mp_buffer_info_t bufinfo;
     mp_get_buffer_raise(obj, &bufinfo, MP_BUFFER_READ);
-    vstr_t vstr = {bufinfo.len, bufinfo.len, (char*)bufinfo.buf, true};
+    vstr_t vstr = {bufinfo.len, bufinfo.len, (char *)bufinfo.buf, true};
     mp_obj_stringio_t sio = {{&mp_type_stringio}, &vstr, 0, MP_OBJ_NULL};
     return mod_ujson_load(MP_OBJ_FROM_PTR(&sio));
 }
@@ -301,7 +320,7 @@
 
 const mp_obj_module_t mp_module_ujson = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_ujson_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_ujson_globals,
 };
 
 #endif //MICROPY_PY_UJSON
diff --git a/extmod/modurandom.c b/extmod/modurandom.c
index 725ac46..594848d 100644
--- a/extmod/modurandom.c
+++ b/extmod/modurandom.c
@@ -41,15 +41,14 @@
 STATIC uint8_t yasmarang_dat = 0;
 #endif
 
-STATIC uint32_t yasmarang(void)
-{
-   yasmarang_pad += yasmarang_dat + yasmarang_d * yasmarang_n;
-   yasmarang_pad = (yasmarang_pad<<3) + (yasmarang_pad>>29);
-   yasmarang_n = yasmarang_pad | 2;
-   yasmarang_d ^= (yasmarang_pad<<31) + (yasmarang_pad>>1);
-   yasmarang_dat ^= (char) yasmarang_pad ^ (yasmarang_d>>8) ^ 1;
+STATIC uint32_t yasmarang(void) {
+    yasmarang_pad += yasmarang_dat + yasmarang_d * yasmarang_n;
+    yasmarang_pad = (yasmarang_pad << 3) + (yasmarang_pad >> 29);
+    yasmarang_n = yasmarang_pad | 2;
+    yasmarang_d ^= (yasmarang_pad << 31) + (yasmarang_pad >> 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 */
 
 // End of Yasmarang
@@ -221,7 +220,7 @@
 
 const mp_obj_module_t mp_module_urandom = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_urandom_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_urandom_globals,
 };
 #endif
 
diff --git a/extmod/modure.c b/extmod/modure.c
index f3a9d88..4f11de5 100644
--- a/extmod/modure.c
+++ b/extmod/modure.c
@@ -73,7 +73,7 @@
         return mp_const_none;
     }
     return mp_obj_new_str_of_type(mp_obj_get_type(self->str),
-        (const byte*)start, self->caps[no * 2 + 1] - start);
+        (const byte *)start, self->caps[no * 2 + 1] - start);
 }
 MP_DEFINE_CONST_FUN_OBJ_2(match_group_obj, match_group);
 
@@ -163,7 +163,7 @@
     { &mp_type_type },
     .name = MP_QSTR_match,
     .print = match_print,
-    .locals_dict = (void*)&match_locals_dict,
+    .locals_dict = (void *)&match_locals_dict,
 };
 #endif
 
@@ -181,12 +181,12 @@
     subj.begin = mp_obj_str_get_data(args[1], &len);
     subj.end = subj.begin + len;
     int caps_num = (self->re.sub + 1) * 2;
-    mp_obj_match_t *match = m_new_obj_var(mp_obj_match_t, char*, caps_num);
+    mp_obj_match_t *match = m_new_obj_var(mp_obj_match_t, char *, caps_num);
     // cast is a workaround for a bug in msvc: it treats const char** as a const pointer instead of a pointer to pointer to const char
-    memset((char*)match->caps, 0, caps_num * sizeof(char*));
+    memset((char *)match->caps, 0, caps_num * sizeof(char *));
     int res = re1_5_recursiveloopprog(&self->re, &subj, match->caps, caps_num, is_anchored);
     if (res == 0) {
-        m_del_var(mp_obj_match_t, char*, caps_num, match);
+        m_del_var(mp_obj_match_t, char *, caps_num, match);
         return mp_const_none;
     }
 
@@ -221,10 +221,10 @@
     }
 
     mp_obj_t retval = mp_obj_new_list(0, NULL);
-    const char **caps = mp_local_alloc(caps_num * sizeof(char*));
+    const char **caps = mp_local_alloc(caps_num * sizeof(char *));
     while (true) {
         // cast is a workaround for a bug in msvc: it treats const char** as a const pointer instead of a pointer to pointer to const char
-        memset((char**)caps, 0, caps_num * sizeof(char*));
+        memset((char **)caps, 0, caps_num * sizeof(char *));
         int res = re1_5_recursiveloopprog(&self->re, &subj, caps, caps_num, false);
 
         // if we didn't have a match, or had an empty match, it's time to stop
@@ -232,7 +232,7 @@
             break;
         }
 
-        mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte*)subj.begin, caps[0] - subj.begin);
+        mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte *)subj.begin, caps[0] - subj.begin);
         mp_obj_list_append(retval, s);
         if (self->re.sub > 0) {
             mp_raise_NotImplementedError("Splitting with sub-captures");
@@ -243,9 +243,9 @@
         }
     }
     // cast is a workaround for a bug in msvc (see above)
-    mp_local_free((char**)caps);
+    mp_local_free((char **)caps);
 
-    mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte*)subj.begin, subj.end - subj.begin);
+    mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte *)subj.begin, subj.end - subj.begin);
     mp_obj_list_append(retval, s);
     return retval;
 }
@@ -272,14 +272,14 @@
 
     vstr_t vstr_return;
     vstr_return.buf = NULL; // We'll init the vstr after the first match
-    mp_obj_match_t *match = mp_local_alloc(sizeof(mp_obj_match_t) + caps_num * sizeof(char*));
+    mp_obj_match_t *match = mp_local_alloc(sizeof(mp_obj_match_t) + caps_num * sizeof(char *));
     match->base.type = &match_type;
     match->num_matches = caps_num / 2; // caps_num counts start and end pointers
     match->str = where;
 
     for (;;) {
         // cast is a workaround for a bug in msvc: it treats const char** as a const pointer instead of a pointer to pointer to const char
-        memset((char*)match->caps, 0, caps_num * sizeof(char*));
+        memset((char *)match->caps, 0, caps_num * sizeof(char *));
         int res = re1_5_recursiveloopprog(&self->re, &subj, match->caps, caps_num, false);
 
         // If we didn't have a match, or had an empty match, it's time to stop
@@ -296,7 +296,7 @@
         vstr_add_strn(&vstr_return, subj.begin, match->caps[0] - subj.begin);
 
         // Get replacement string
-        const char* repl = mp_obj_str_get_str((mp_obj_is_callable(replace) ? mp_call_function_1(replace, MP_OBJ_FROM_PTR(match)) : replace));
+        const char *repl = mp_obj_str_get_str((mp_obj_is_callable(replace) ? mp_call_function_1(replace, MP_OBJ_FROM_PTR(match)) : replace));
 
         // Append replacement string to result, substituting any regex groups
         while (*repl != '\0') {
@@ -381,7 +381,7 @@
     { &mp_type_type },
     .name = MP_QSTR_ure,
     .print = re_print,
-    .locals_dict = (void*)&re_locals_dict,
+    .locals_dict = (void *)&re_locals_dict,
 };
 #endif
 
@@ -402,7 +402,7 @@
     #endif
     int error = re1_5_compilecode(&o->re, re_str);
     if (error != 0) {
-error:
+    error:
         mp_raise_ValueError("Error in regex");
     }
     #if MICROPY_PY_URE_DEBUG
@@ -459,7 +459,7 @@
 
 const mp_obj_module_t mp_module_ure = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_re_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_re_globals,
 };
 #endif
 
diff --git a/extmod/moduselect.c b/extmod/moduselect.c
index 4963b4d..1223656 100644
--- a/extmod/moduselect.c
+++ b/extmod/moduselect.c
@@ -66,9 +66,9 @@
         } else {
             // object exists; update its flags
             if (or_flags) {
-                ((poll_obj_t*)MP_OBJ_TO_PTR(elem->value))->flags |= flags;
+                ((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags |= flags;
             } else {
-                ((poll_obj_t*)MP_OBJ_TO_PTR(elem->value))->flags = flags;
+                ((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags = flags;
             }
         }
     }
@@ -161,13 +161,13 @@
                 }
                 poll_obj_t *poll_obj = MP_OBJ_TO_PTR(poll_map.table[i].value);
                 if (poll_obj->flags_ret & MP_STREAM_POLL_RD) {
-                    ((mp_obj_list_t*)MP_OBJ_TO_PTR(list_array[0]))->items[rwx_len[0]++] = poll_obj->obj;
+                    ((mp_obj_list_t *)MP_OBJ_TO_PTR(list_array[0]))->items[rwx_len[0]++] = poll_obj->obj;
                 }
                 if (poll_obj->flags_ret & MP_STREAM_POLL_WR) {
-                    ((mp_obj_list_t*)MP_OBJ_TO_PTR(list_array[1]))->items[rwx_len[1]++] = poll_obj->obj;
+                    ((mp_obj_list_t *)MP_OBJ_TO_PTR(list_array[1]))->items[rwx_len[1]++] = poll_obj->obj;
                 }
                 if ((poll_obj->flags_ret & ~(MP_STREAM_POLL_RD | MP_STREAM_POLL_WR)) != 0) {
-                    ((mp_obj_list_t*)MP_OBJ_TO_PTR(list_array[2]))->items[rwx_len[2]++] = poll_obj->obj;
+                    ((mp_obj_list_t *)MP_OBJ_TO_PTR(list_array[2]))->items[rwx_len[2]++] = poll_obj->obj;
                 }
             }
             mp_map_deinit(&poll_map);
@@ -220,7 +220,7 @@
     if (elem == NULL) {
         mp_raise_OSError(MP_ENOENT);
     }
-    ((poll_obj_t*)MP_OBJ_TO_PTR(elem->value))->flags = mp_obj_get_int(eventmask_in);
+    ((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags = mp_obj_get_int(eventmask_in);
     return mp_const_none;
 }
 MP_DEFINE_CONST_FUN_OBJ_3(poll_modify_obj, poll_modify);
@@ -345,7 +345,7 @@
     .name = MP_QSTR_poll,
     .getiter = mp_identity_getiter,
     .iternext = poll_iternext,
-    .locals_dict = (void*)&poll_locals_dict,
+    .locals_dict = (void *)&poll_locals_dict,
 };
 
 /// \function poll()
@@ -373,7 +373,7 @@
 
 const mp_obj_module_t mp_module_uselect = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_select_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_select_globals,
 };
 
 #endif // MICROPY_PY_USELECT
diff --git a/extmod/modussl_axtls.c b/extmod/modussl_axtls.c
index aae1c86..f102f6a 100644
--- a/extmod/modussl_axtls.c
+++ b/extmod/modussl_axtls.c
@@ -55,11 +55,11 @@
 STATIC const mp_obj_type_t ussl_socket_type;
 
 STATIC mp_obj_ssl_socket_t *ussl_socket_new(mp_obj_t sock, struct ssl_args *args) {
-#if MICROPY_PY_USSL_FINALISER
+    #if MICROPY_PY_USSL_FINALISER
     mp_obj_ssl_socket_t *o = m_new_obj_with_finaliser(mp_obj_ssl_socket_t);
-#else
+    #else
     mp_obj_ssl_socket_t *o = m_new_obj(mp_obj_ssl_socket_t);
-#endif
+    #endif
     o->base.type = &ussl_socket_type;
     o->buf = NULL;
     o->bytes_left = 0;
@@ -79,13 +79,13 @@
 
     if (args->key.u_obj != mp_const_none) {
         size_t len;
-        const byte *data = (const byte*)mp_obj_str_get_data(args->key.u_obj, &len);
+        const byte *data = (const byte *)mp_obj_str_get_data(args->key.u_obj, &len);
         int res = ssl_obj_memory_load(o->ssl_ctx, SSL_OBJ_RSA_KEY, data, len, NULL);
         if (res != SSL_OK) {
             mp_raise_ValueError("invalid key");
         }
 
-        data = (const byte*)mp_obj_str_get_data(args->cert.u_obj, &len);
+        data = (const byte *)mp_obj_str_get_data(args->cert.u_obj, &len);
         res = ssl_obj_memory_load(o->ssl_ctx, SSL_OBJ_X509_CERT, data, len, NULL);
         if (res != SSL_OK) {
             mp_raise_ValueError("invalid cert");
@@ -98,7 +98,7 @@
         SSL_EXTENSIONS *ext = ssl_ext_new();
 
         if (args->server_hostname.u_obj != mp_const_none) {
-            ext->host_name = (char*)mp_obj_str_get_str(args->server_hostname.u_obj);
+            ext->host_name = (char *)mp_obj_str_get_str(args->server_hostname.u_obj);
         }
 
         o->ssl_sock = ssl_client_new(o->ssl_ctx, (long)sock, NULL, 0, ext);
@@ -155,7 +155,7 @@
                 return 0;
             }
             if (r == SSL_EAGAIN) {
-eagain:
+            eagain:
                 r = MP_EAGAIN;
             }
             *errcode = r;
@@ -219,9 +219,9 @@
     { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
     { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&ussl_socket_setblocking_obj) },
     { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) },
-#if MICROPY_PY_USSL_FINALISER
+    #if MICROPY_PY_USSL_FINALISER
     { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) },
-#endif
+    #endif
 };
 
 STATIC MP_DEFINE_CONST_DICT(ussl_socket_locals_dict, ussl_socket_locals_dict_table);
@@ -240,7 +240,7 @@
     .getiter = NULL,
     .iternext = NULL,
     .protocol = &ussl_socket_stream_p,
-    .locals_dict = (void*)&ussl_socket_locals_dict,
+    .locals_dict = (void *)&ussl_socket_locals_dict,
 };
 
 STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
@@ -258,7 +258,7 @@
 
     struct ssl_args args;
     mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
-        MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args);
+        MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args);
 
     return MP_OBJ_FROM_PTR(ussl_socket_new(sock, &args));
 }
@@ -273,7 +273,7 @@
 
 const mp_obj_module_t mp_module_ussl = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_ssl_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_ssl_globals,
 };
 
 #endif // MICROPY_PY_USSL
diff --git a/extmod/modussl_mbedtls.c b/extmod/modussl_mbedtls.c
index 5c41ea2..7fcd939 100644
--- a/extmod/modussl_mbedtls.c
+++ b/extmod/modussl_mbedtls.c
@@ -75,7 +75,7 @@
 #endif
 
 STATIC int _mbedtls_ssl_send(void *ctx, const byte *buf, size_t len) {
-    mp_obj_t sock = *(mp_obj_t*)ctx;
+    mp_obj_t sock = *(mp_obj_t *)ctx;
 
     const mp_stream_p_t *sock_stream = mp_get_stream(sock);
     int err;
@@ -92,7 +92,7 @@
 }
 
 STATIC int _mbedtls_ssl_recv(void *ctx, byte *buf, size_t len) {
-    mp_obj_t sock = *(mp_obj_t*)ctx;
+    mp_obj_t sock = *(mp_obj_t *)ctx;
 
     const mp_stream_p_t *sock_stream = mp_get_stream(sock);
     int err;
@@ -113,11 +113,11 @@
     // Verify the socket object has the full stream protocol
     mp_get_stream_raise(sock, MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL);
 
-#if MICROPY_PY_USSL_FINALISER
+    #if MICROPY_PY_USSL_FINALISER
     mp_obj_ssl_socket_t *o = m_new_obj_with_finaliser(mp_obj_ssl_socket_t);
-#else
+    #else
     mp_obj_ssl_socket_t *o = m_new_obj(mp_obj_ssl_socket_t);
-#endif
+    #endif
     o->base.type = &ussl_socket_type;
     o->sock = sock;
 
@@ -141,9 +141,9 @@
     }
 
     ret = mbedtls_ssl_config_defaults(&o->conf,
-                    args->server_side.u_bool ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT,
-                    MBEDTLS_SSL_TRANSPORT_STREAM,
-                    MBEDTLS_SSL_PRESET_DEFAULT);
+        args->server_side.u_bool ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT,
+        MBEDTLS_SSL_TRANSPORT_STREAM,
+        MBEDTLS_SSL_PRESET_DEFAULT);
     if (ret != 0) {
         goto cleanup;
     }
@@ -171,7 +171,7 @@
 
     if (args->key.u_obj != mp_const_none) {
         size_t key_len;
-        const byte *key = (const byte*)mp_obj_str_get_data(args->key.u_obj, &key_len);
+        const byte *key = (const byte *)mp_obj_str_get_data(args->key.u_obj, &key_len);
         // len should include terminating null
         ret = mbedtls_pk_parse_key(&o->pkey, key, key_len + 1, NULL, 0);
         if (ret != 0) {
@@ -180,7 +180,7 @@
         }
 
         size_t cert_len;
-        const byte *cert = (const byte*)mp_obj_str_get_data(args->cert.u_obj, &cert_len);
+        const byte *cert = (const byte *)mp_obj_str_get_data(args->cert.u_obj, &cert_len);
         // len should include terminating null
         ret = mbedtls_x509_crt_parse(&o->cert, cert, cert_len + 1);
         if (ret != 0) {
@@ -230,7 +230,7 @@
     if (!mp_obj_is_true(binary_form)) {
         mp_raise_NotImplementedError(NULL);
     }
-    const mbedtls_x509_crt* peer_cert = mbedtls_ssl_get_peer_cert(&o->ssl);
+    const mbedtls_x509_crt *peer_cert = mbedtls_ssl_get_peer_cert(&o->ssl);
     if (peer_cert == NULL) {
         return mp_const_none;
     }
@@ -318,9 +318,9 @@
     { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
     { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) },
     { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) },
-#if MICROPY_PY_USSL_FINALISER
+    #if MICROPY_PY_USSL_FINALISER
     { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) },
-#endif
+    #endif
     { MP_ROM_QSTR(MP_QSTR_getpeercert), MP_ROM_PTR(&mod_ssl_getpeercert_obj) },
 };
 
@@ -340,7 +340,7 @@
     .getiter = NULL,
     .iternext = NULL,
     .protocol = &ussl_socket_stream_p,
-    .locals_dict = (void*)&ussl_socket_locals_dict,
+    .locals_dict = (void *)&ussl_socket_locals_dict,
 };
 
 STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
@@ -358,7 +358,7 @@
 
     struct ssl_args args;
     mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
-        MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args);
+        MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args);
 
     return MP_OBJ_FROM_PTR(socket_new(sock, &args));
 }
@@ -373,7 +373,7 @@
 
 const mp_obj_module_t mp_module_ussl = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_ssl_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_ssl_globals,
 };
 
 #endif // MICROPY_PY_USSL
diff --git a/extmod/modutimeq.c b/extmod/modutimeq.c
index 0183a0f..a5640a4 100644
--- a/extmod/modutimeq.c
+++ b/extmod/modutimeq.c
@@ -190,9 +190,12 @@
 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);
     switch (op) {
-        case MP_UNARY_OP_BOOL: return mp_obj_new_bool(self->len != 0);
-        case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(self->len);
-        default: return MP_OBJ_NULL; // op not supported
+        case MP_UNARY_OP_BOOL:
+            return mp_obj_new_bool(self->len != 0);
+        case MP_UNARY_OP_LEN:
+            return MP_OBJ_NEW_SMALL_INT(self->len);
+        default:
+            return MP_OBJ_NULL;      // op not supported
     }
 }
 
@@ -212,7 +215,7 @@
     .name = MP_QSTR_utimeq,
     .make_new = utimeq_make_new,
     .unary_op = utimeq_unary_op,
-    .locals_dict = (void*)&utimeq_locals_dict,
+    .locals_dict = (void *)&utimeq_locals_dict,
 };
 
 STATIC const mp_rom_map_elem_t mp_module_utimeq_globals_table[] = {
@@ -224,7 +227,7 @@
 
 const mp_obj_module_t mp_module_utimeq = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_utimeq_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_utimeq_globals,
 };
 
 #endif //MICROPY_PY_UTIMEQ
diff --git a/extmod/moduwebsocket.c b/extmod/moduwebsocket.c
index d90ee49..a9bfd85 100644
--- a/extmod/moduwebsocket.c
+++ b/extmod/moduwebsocket.c
@@ -71,11 +71,11 @@
     if (n_args > 1 && args[1] == mp_const_true) {
         o->opts |= BLOCKING_WRITE;
     }
-    return  MP_OBJ_FROM_PTR(o);
+    return MP_OBJ_FROM_PTR(o);
 }
 
 STATIC mp_uint_t websocket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) {
-    mp_obj_websocket_t *self =  MP_OBJ_TO_PTR(self_in);
+    mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in);
     const mp_stream_p_t *stream_p = mp_get_stream(self->sock);
     while (1) {
         if (self->to_recv != 0) {
@@ -183,7 +183,7 @@
                 self->msg_sz -= out_sz;
                 if (self->msg_sz == 0) {
                     byte last_state;
-no_payload:
+                no_payload:
                     last_state = self->state;
                     self->state = FRAME_HEADER;
                     self->to_recv = 2;
@@ -217,7 +217,7 @@
 }
 
 STATIC mp_uint_t websocket_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) {
-    mp_obj_websocket_t *self =  MP_OBJ_TO_PTR(self_in);
+    mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in);
     assert(size < 0x10000);
     byte header[4] = {0x80 | (self->opts & FRAME_OPCODE_MASK)};
     int hdr_sz;
@@ -296,7 +296,7 @@
     .name = MP_QSTR_websocket,
     .make_new = websocket_make_new,
     .protocol = &websocket_stream_p,
-    .locals_dict = (void*)&websocket_locals_dict,
+    .locals_dict = (void *)&websocket_locals_dict,
 };
 
 STATIC const mp_rom_map_elem_t uwebsocket_module_globals_table[] = {
@@ -308,7 +308,7 @@
 
 const mp_obj_module_t mp_module_uwebsocket = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&uwebsocket_module_globals,
+    .globals = (mp_obj_dict_t *)&uwebsocket_module_globals,
 };
 
 #endif // MICROPY_PY_UWEBSOCKET
diff --git a/extmod/moduzlib.c b/extmod/moduzlib.c
index 9d3ca7d..30522e1 100644
--- a/extmod/moduzlib.c
+++ b/extmod/moduzlib.c
@@ -49,9 +49,9 @@
 } mp_obj_decompio_t;
 
 STATIC int read_src_stream(TINF_DATA *data) {
-    byte *p = (void*)data;
+    byte *p = (void *)data;
     p -= offsetof(mp_obj_decompio_t, decomp);
-    mp_obj_decompio_t *self = (mp_obj_decompio_t*)p;
+    mp_obj_decompio_t *self = (mp_obj_decompio_t *)p;
 
     const mp_stream_p_t *stream = mp_get_stream(self->src_stream);
     int err;
@@ -91,7 +91,7 @@
     } else if (dict_opt >= 0) {
         dict_opt = uzlib_zlib_parse_header(&o->decomp);
         if (dict_opt < 0) {
-header_error:
+        header_error:
             mp_raise_ValueError("compression header");
         }
         dict_sz = 1 << dict_opt;
@@ -110,7 +110,7 @@
     }
 
     o->decomp.dest = buf;
-    o->decomp.dest_limit = (byte*)buf + size;
+    o->decomp.dest_limit = (byte *)buf + size;
     int st = uzlib_uncompress_chksum(&o->decomp);
     if (st == TINF_DONE) {
         o->eof = true;
@@ -119,7 +119,7 @@
         *errcode = MP_EINVAL;
         return MP_STREAM_ERROR;
     }
-    return o->decomp.dest - (byte*)buf;
+    return o->decomp.dest - (byte *)buf;
 }
 
 #if !MICROPY_ENABLE_DYNRUNTIME
@@ -142,7 +142,7 @@
     .name = MP_QSTR_DecompIO,
     .make_new = decompio_make_new,
     .protocol = &decompio_stream_p,
-    .locals_dict = (void*)&decompio_locals_dict,
+    .locals_dict = (void *)&decompio_locals_dict,
 };
 #endif
 
@@ -162,7 +162,7 @@
     decomp->dest_limit = dest_buf + dest_buf_size;
     DEBUG_printf("uzlib: Initial out buffer: " UINT_FMT " bytes\n", dest_buf_size);
     decomp->source = bufinfo.buf;
-    decomp->source_limit = (byte*)bufinfo.buf + bufinfo.len;
+    decomp->source_limit = (byte *)bufinfo.buf + bufinfo.len;
 
     int st;
     bool is_zlib = true;
@@ -195,13 +195,13 @@
 
     mp_uint_t final_sz = decomp->dest - dest_buf;
     DEBUG_printf("uzlib: Resizing from " UINT_FMT " to final size: " UINT_FMT " bytes\n", dest_buf_size, final_sz);
-    dest_buf = (byte*)m_renew(byte, dest_buf, dest_buf_size, final_sz);
+    dest_buf = (byte *)m_renew(byte, dest_buf, dest_buf_size, final_sz);
     mp_obj_t res = mp_obj_new_bytearray_by_ref(final_sz, dest_buf);
     m_del_obj(TINF_DATA, decomp);
     return res;
 
 error:
-        nlr_raise(mp_obj_new_exception_arg1(&mp_type_ValueError, MP_OBJ_NEW_SMALL_INT(st)));
+    nlr_raise(mp_obj_new_exception_arg1(&mp_type_ValueError, MP_OBJ_NEW_SMALL_INT(st)));
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_uzlib_decompress_obj, 1, 3, mod_uzlib_decompress);
 
@@ -216,7 +216,7 @@
 
 const mp_obj_module_t mp_module_uzlib = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_uzlib_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_uzlib_globals,
 };
 #endif
 
diff --git a/extmod/modwebrepl.c b/extmod/modwebrepl.c
index b532431..3c398f6 100644
--- a/extmod/modwebrepl.c
+++ b/extmod/modwebrepl.c
@@ -155,7 +155,7 @@
         open_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_wb);
     }
 
-    self->cur_file = mp_builtin_open(2, open_args, (mp_map_t*)&mp_const_empty_map);
+    self->cur_file = mp_builtin_open(2, open_args, (mp_map_t *)&mp_const_empty_map);
 
     #if 0
     struct mp_stream_seek_t seek = { .offset = self->hdr.offset, .whence = 0 };
@@ -196,7 +196,7 @@
     }
 
     if (self->state == STATE_PASSWD) {
-        char c = *(char*)buf;
+        char c = *(char *)buf;
         if (c == '\r' || c == '\n') {
             self->hdr.fname[self->data_to_recv] = 0;
             DEBUG_printf("webrepl: entered password: %s\n", self->hdr.fname);
@@ -224,8 +224,8 @@
     DEBUG_printf("webrepl: received bin data, hdr_to_recv: %d, data_to_recv=%d\n", self->hdr_to_recv, self->data_to_recv);
 
     if (self->hdr_to_recv != 0) {
-        char *p = (char*)&self->hdr + sizeof(self->hdr) - self->hdr_to_recv;
-        *p++ = *(char*)buf;
+        char *p = (char *)&self->hdr + sizeof(self->hdr) - self->hdr_to_recv;
+        *p++ = *(char *)buf;
         if (--self->hdr_to_recv != 0) {
             mp_uint_t hdr_sz = sock_stream->read(self->sock, p, self->hdr_to_recv, errcode);
             if (hdr_sz == MP_STREAM_ERROR) {
@@ -250,7 +250,7 @@
         static
         #endif
         byte filebuf[512];
-        filebuf[0] = *(byte*)buf;
+        filebuf[0] = *(byte *)buf;
         mp_uint_t buf_sz = 1;
         if (--self->data_to_recv != 0) {
             size_t to_read = MIN(sizeof(filebuf) - 1, self->data_to_recv);
@@ -348,7 +348,7 @@
     .name = MP_QSTR__webrepl,
     .make_new = webrepl_make_new,
     .protocol = &webrepl_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&webrepl_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&webrepl_locals_dict,
 };
 
 STATIC const mp_rom_map_elem_t webrepl_module_globals_table[] = {
@@ -361,7 +361,7 @@
 
 const mp_obj_module_t mp_module_webrepl = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&webrepl_module_globals,
+    .globals = (mp_obj_dict_t *)&webrepl_module_globals,
 };
 
 #endif // MICROPY_PY_WEBREPL
diff --git a/extmod/network_cyw43.c b/extmod/network_cyw43.c
index ad46714..dac49c6 100644
--- a/extmod/network_cyw43.c
+++ b/extmod/network_cyw43.c
@@ -71,7 +71,7 @@
         netif->ip_addr.addr >> 8 & 0xff,
         netif->ip_addr.addr >> 16 & 0xff,
         netif->ip_addr.addr >> 24
-    );
+        );
 }
 
 STATIC mp_obj_t network_cyw43_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
@@ -135,7 +135,7 @@
     mp_obj_get_array(list, &len, &items);
     for (size_t i = 0; i < len; ++i) {
         mp_obj_tuple_t *t = MP_OBJ_TO_PTR(items[i]);
-        if (memcmp(res->bssid, ((mp_obj_str_t*)MP_OBJ_TO_PTR(t->items[1]))->data, sizeof(res->bssid)) == 0) {
+        if (memcmp(res->bssid, ((mp_obj_str_t *)MP_OBJ_TO_PTR(t->items[1]))->data, sizeof(res->bssid)) == 0) {
             if (res->rssi > MP_OBJ_SMALL_INT_VALUE(t->items[3])) {
                 t->items[3] = MP_OBJ_NEW_SMALL_INT(res->rssi);
             }
@@ -289,7 +289,7 @@
                 mp_obj_t tuple[1] = {
                     mp_obj_new_bytes(&macs[i * 6], 6),
                 };
-                ((mp_obj_list_t*)MP_OBJ_TO_PTR(list))->items[i] = mp_obj_new_tuple(1, tuple);
+                ((mp_obj_list_t *)MP_OBJ_TO_PTR(list))->items[i] = mp_obj_new_tuple(1, tuple);
             }
             return list;
         }
@@ -334,12 +334,12 @@
                 if (self->itf == CYW43_ITF_STA) {
                     uint8_t buf[36];
                     cyw43_ioctl(self->cyw, CYW43_IOCTL_GET_SSID, 36, buf, self->itf);
-                    return mp_obj_new_str((const char*)buf + 4, nw_get_le32(buf));
+                    return mp_obj_new_str((const char *)buf + 4, nw_get_le32(buf));
                 } else {
                     size_t len;
                     const uint8_t *buf;
                     cyw43_wifi_ap_get_ssid(self->cyw, &len, &buf);
-                    return mp_obj_new_str((const char*)buf, len);
+                    return mp_obj_new_str((const char *)buf, len);
                 }
             }
             case MP_QSTR_mac: {
@@ -379,7 +379,7 @@
                     case MP_QSTR_essid: {
                         size_t len;
                         const char *str = mp_obj_str_get_data(e->value, &len);
-                        cyw43_wifi_ap_set_ssid(self->cyw, len, (const uint8_t*)str);
+                        cyw43_wifi_ap_set_ssid(self->cyw, len, (const uint8_t *)str);
                         break;
                     }
                     case MP_QSTR_monitor: {
@@ -400,7 +400,7 @@
                     case MP_QSTR_password: {
                         size_t len;
                         const char *str = mp_obj_str_get_data(e->value, &len);
-                        cyw43_wifi_ap_set_password(self->cyw, len, (const uint8_t*)str);
+                        cyw43_wifi_ap_set_password(self->cyw, len, (const uint8_t *)str);
                         break;
                     }
                     case MP_QSTR_pm: {
@@ -454,7 +454,7 @@
     .name = MP_QSTR_CYW43,
     .print = network_cyw43_print,
     .make_new = network_cyw43_make_new,
-    .locals_dict = (mp_obj_dict_t*)&network_cyw43_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&network_cyw43_locals_dict,
 };
 
 #endif // MICROPY_PY_NETWORK_CYW43
diff --git a/extmod/uos_dupterm.c b/extmod/uos_dupterm.c
index 9a8f0af..8b6e865 100644
--- a/extmod/uos_dupterm.c
+++ b/extmod/uos_dupterm.c
@@ -106,9 +106,9 @@
             mp_uint_t out_sz = stream_p->read(MP_STATE_VM(dupterm_objs[idx]), buf, 1, &errcode);
             if (errcode == 0 && out_sz != 0) {
                 return buf[0];
-             } else {
+            } else {
                 continue;
-             }
+            }
         }
         #endif
 
diff --git a/extmod/utime_mphal.c b/extmod/utime_mphal.c
index 0fe3a3b..6aff2ca 100644
--- a/extmod/utime_mphal.c
+++ b/extmod/utime_mphal.c
@@ -86,7 +86,7 @@
     // Optimized formula avoiding if conditions. We adjust difference "forward",
     // wrap it around and adjust back.
     mp_int_t diff = ((end - start + MICROPY_PY_UTIME_TICKS_PERIOD / 2) & (MICROPY_PY_UTIME_TICKS_PERIOD - 1))
-                   - MICROPY_PY_UTIME_TICKS_PERIOD / 2;
+        - MICROPY_PY_UTIME_TICKS_PERIOD / 2;
     return MP_OBJ_NEW_SMALL_INT(diff);
 }
 MP_DEFINE_CONST_FUN_OBJ_2(mp_utime_ticks_diff_obj, time_ticks_diff);
diff --git a/extmod/vfs.c b/extmod/vfs.c
index 8e3a0f1..d8bc02c 100644
--- a/extmod/vfs.c
+++ b/extmod/vfs.c
@@ -103,7 +103,7 @@
     mp_vfs_mount_t *vfs = mp_vfs_lookup_path(path, &p_out);
     if (vfs != MP_VFS_NONE && vfs != MP_VFS_ROOT) {
         *path_out = mp_obj_new_str_of_type(mp_obj_get_type(path_in),
-            (const byte*)p_out, strlen(p_out));
+            (const byte *)p_out, strlen(p_out));
     }
     return vfs;
 }
@@ -231,7 +231,7 @@
     vfs->next = NULL;
 
     // call the underlying object to do any mounting operation
-    mp_vfs_proxy_call(vfs, MP_QSTR_mount, 2, (mp_obj_t*)&args);
+    mp_vfs_proxy_call(vfs, MP_QSTR_mount, 2, (mp_obj_t *)&args);
 
     // check that the destination mount point is unused
     const char *path_out;
@@ -315,7 +315,7 @@
     #endif
 
     mp_vfs_mount_t *vfs = lookup_path(args[ARG_file].u_obj, &args[ARG_file].u_obj);
-    return mp_vfs_proxy_call(vfs, MP_QSTR_open, 2, (mp_obj_t*)&args);
+    return mp_vfs_proxy_call(vfs, MP_QSTR_open, 2, (mp_obj_t *)&args);
 }
 MP_DEFINE_CONST_FUN_OBJ_KW(mp_vfs_open_obj, 0, mp_vfs_open);
 
@@ -395,7 +395,7 @@
             mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(3, NULL));
             t->items[0] = mp_obj_new_str_of_type(
                 self->is_str ? &mp_type_str : &mp_type_bytes,
-                (const byte*)vfs->str + 1, vfs->len - 1);
+                (const byte *)vfs->str + 1, vfs->len - 1);
             t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFDIR);
             t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // no inode number
             return MP_OBJ_FROM_PTR(t);
diff --git a/extmod/vfs.h b/extmod/vfs.h
index 004b002..de899dd 100644
--- a/extmod/vfs.h
+++ b/extmod/vfs.h
@@ -31,8 +31,8 @@
 
 // return values of mp_vfs_lookup_path
 // ROOT is 0 so that the default current directory is the root directory
-#define MP_VFS_NONE ((mp_vfs_mount_t*)1)
-#define MP_VFS_ROOT ((mp_vfs_mount_t*)0)
+#define MP_VFS_NONE ((mp_vfs_mount_t *)1)
+#define MP_VFS_ROOT ((mp_vfs_mount_t *)0)
 
 // MicroPython's port-standardized versions of stat constants
 #define MP_S_IFDIR (0x4000)
diff --git a/extmod/vfs_blockdev.c b/extmod/vfs_blockdev.c
index 90675aa..57c83b4 100644
--- a/extmod/vfs_blockdev.c
+++ b/extmod/vfs_blockdev.c
@@ -48,10 +48,10 @@
 
 int mp_vfs_blockdev_read(mp_vfs_blockdev_t *self, size_t block_num, size_t num_blocks, uint8_t *buf) {
     if (self->flags & MP_BLOCKDEV_FLAG_NATIVE) {
-        mp_uint_t (*f)(uint8_t*, uint32_t, uint32_t) = (void*)(uintptr_t)self->readblocks[2];
+        mp_uint_t (*f)(uint8_t *, uint32_t, uint32_t) = (void *)(uintptr_t)self->readblocks[2];
         return f(buf, block_num, num_blocks);
     } else {
-        mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, num_blocks * self->block_size, buf};
+        mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, num_blocks *self->block_size, buf};
         self->readblocks[2] = MP_OBJ_NEW_SMALL_INT(block_num);
         self->readblocks[3] = MP_OBJ_FROM_PTR(&ar);
         mp_call_method_n_kw(2, 0, self->readblocks);
@@ -80,10 +80,10 @@
     }
 
     if (self->flags & MP_BLOCKDEV_FLAG_NATIVE) {
-        mp_uint_t (*f)(const uint8_t*, uint32_t, uint32_t) = (void*)(uintptr_t)self->writeblocks[2];
+        mp_uint_t (*f)(const uint8_t *, uint32_t, uint32_t) = (void *)(uintptr_t)self->writeblocks[2];
         return f(buf, block_num, num_blocks);
     } else {
-        mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, num_blocks * self->block_size, (void*)buf};
+        mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, num_blocks *self->block_size, (void *)buf};
         self->writeblocks[2] = MP_OBJ_NEW_SMALL_INT(block_num);
         self->writeblocks[3] = MP_OBJ_FROM_PTR(&ar);
         mp_call_method_n_kw(2, 0, self->writeblocks);
@@ -98,7 +98,7 @@
         return -MP_EROFS;
     }
 
-    mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, len, (void*)buf};
+    mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, len, (void *)buf};
     self->writeblocks[2] = MP_OBJ_NEW_SMALL_INT(block_num);
     self->writeblocks[3] = MP_OBJ_FROM_PTR(&ar);
     self->writeblocks[4] = MP_OBJ_NEW_SMALL_INT(block_off);
diff --git a/extmod/vfs_fat.c b/extmod/vfs_fat.c
index f8cb1f5..e7af405 100644
--- a/extmod/vfs_fat.c
+++ b/extmod/vfs_fat.c
@@ -142,7 +142,7 @@
         if (self->is_str) {
             t->items[0] = mp_obj_new_str(fn, strlen(fn));
         } else {
-            t->items[0] = mp_obj_new_bytes((const byte*)fn, strlen(fn));
+            t->items[0] = mp_obj_new_bytes((const byte *)fn, strlen(fn));
         }
         if (fno.fattrib & AM_DIR) {
             // dir
@@ -318,7 +318,7 @@
         (fno.ftime >> 11) & 0x1f,
         (fno.ftime >> 5) & 0x3f,
         2 * (fno.ftime & 0x1f)
-    );
+        );
     t->items[0] = MP_OBJ_NEW_SMALL_INT(mode); // st_mode
     t->items[1] = MP_OBJ_NEW_SMALL_INT(0); // st_ino
     t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // st_dev
@@ -425,7 +425,7 @@
     .name = MP_QSTR_VfsFat,
     .make_new = fat_vfs_make_new,
     .protocol = &fat_vfs_proto,
-    .locals_dict = (mp_obj_dict_t*)&fat_vfs_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&fat_vfs_locals_dict,
 
 };
 
diff --git a/extmod/vfs_fat_diskio.c b/extmod/vfs_fat_diskio.c
index 76a918f..ae1bef5 100644
--- a/extmod/vfs_fat_diskio.c
+++ b/extmod/vfs_fat_diskio.c
@@ -45,7 +45,7 @@
 
 typedef void *bdev_t;
 STATIC fs_user_mount_t *disk_get_device(void *bdev) {
-    return (fs_user_mount_t*)bdev;
+    return (fs_user_mount_t *)bdev;
 }
 
 /*-----------------------------------------------------------------------*/
@@ -57,8 +57,7 @@
     BYTE *buff,        /* Data buffer to store read data */
     DWORD sector,    /* Sector address (LBA) */
     UINT count        /* Number of sectors to read (1..128) */
-)
-{
+    ) {
     fs_user_mount_t *vfs = disk_get_device(pdrv);
     if (vfs == NULL) {
         return RES_PARERR;
@@ -78,8 +77,7 @@
     const BYTE *buff,    /* Data to be written */
     DWORD sector,        /* Sector address (LBA) */
     UINT count            /* Number of sectors to write (1..128) */
-)
-{
+    ) {
     fs_user_mount_t *vfs = disk_get_device(pdrv);
     if (vfs == NULL) {
         return RES_PARERR;
@@ -104,8 +102,7 @@
     bdev_t pdrv,      /* Physical drive nmuber (0..) */
     BYTE cmd,        /* Control code */
     void *buff        /* Buffer to send/receive control data */
-)
-{
+    ) {
     fs_user_mount_t *vfs = disk_get_device(pdrv);
     if (vfs == NULL) {
         return RES_PARERR;
@@ -130,24 +127,24 @@
             return RES_OK;
 
         case GET_SECTOR_COUNT: {
-            *((DWORD*)buff) = mp_obj_get_int(ret);
+            *((DWORD *)buff) = mp_obj_get_int(ret);
             return RES_OK;
         }
 
         case GET_SECTOR_SIZE: {
             if (ret == mp_const_none) {
                 // Default sector size
-                *((WORD*)buff) = 512;
+                *((WORD *)buff) = 512;
             } else {
-                *((WORD*)buff) = mp_obj_get_int(ret);
+                *((WORD *)buff) = mp_obj_get_int(ret);
             }
             // need to store ssize because we use it in disk_read/disk_write
-            vfs->blockdev.block_size = *((WORD*)buff);
+            vfs->blockdev.block_size = *((WORD *)buff);
             return RES_OK;
         }
 
         case GET_BLOCK_SIZE:
-            *((DWORD*)buff) = 1; // erase block size in units of sector size
+            *((DWORD *)buff) = 1; // erase block size in units of sector size
             return RES_OK;
 
         case IOCTL_INIT:
@@ -161,7 +158,7 @@
             } else {
                 stat = 0;
             }
-            *((DSTATUS*)buff) = stat;
+            *((DSTATUS *)buff) = stat;
             return RES_OK;
         }
 
diff --git a/extmod/vfs_fat_file.c b/extmod/vfs_fat_file.c
index 5867c20..537101d 100644
--- a/extmod/vfs_fat_file.c
+++ b/extmod/vfs_fat_file.c
@@ -107,7 +107,7 @@
     pyb_file_obj_t *self = MP_OBJ_TO_PTR(o_in);
 
     if (request == MP_STREAM_SEEK) {
-        struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)(uintptr_t)arg;
+        struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)(uintptr_t)arg;
 
         switch (s->whence) {
             case 0: // SEEK_SET
@@ -251,7 +251,7 @@
     .getiter = mp_identity_getiter,
     .iternext = mp_stream_unbuffered_iter,
     .protocol = &vfs_fat_fileio_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&vfs_fat_rawfile_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&vfs_fat_rawfile_locals_dict,
 };
 #endif
 
@@ -270,7 +270,7 @@
     .getiter = mp_identity_getiter,
     .iternext = mp_stream_unbuffered_iter,
     .protocol = &vfs_fat_textio_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&vfs_fat_rawfile_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&vfs_fat_rawfile_locals_dict,
 };
 
 // Factory function for I/O stream classes
diff --git a/extmod/vfs_lfs.c b/extmod/vfs_lfs.c
index f34d160..90a1996 100644
--- a/extmod/vfs_lfs.c
+++ b/extmod/vfs_lfs.c
@@ -44,13 +44,13 @@
 #include "lib/littlefs/lfs1.h"
 
 #define LFS_BUILD_VERSION (1)
-#define LFSx_MACRO(s) LFS1 ## s
-#define LFSx_API(s) lfs1_ ## s
-#define MP_VFS_LFSx(s) mp_vfs_lfs1_ ## s
+#define LFSx_MACRO(s) LFS1##s
+#define LFSx_API(s) lfs1_##s
+#define MP_VFS_LFSx(s) mp_vfs_lfs1_##s
 #define MP_OBJ_VFS_LFSx mp_obj_vfs_lfs1_t
 #define MP_OBJ_VFS_LFSx_FILE mp_obj_vfs_lfs1_file_t
 #define MP_TYPE_VFS_LFSx mp_type_vfs_lfs1
-#define MP_TYPE_VFS_LFSx_(s) mp_type_vfs_lfs1 ## s
+#define MP_TYPE_VFS_LFSx_(s) mp_type_vfs_lfs1##s
 
 typedef struct _mp_obj_vfs_lfs1_t {
     mp_obj_base_t base;
@@ -90,13 +90,13 @@
 #include "lib/littlefs/lfs2.h"
 
 #define LFS_BUILD_VERSION (2)
-#define LFSx_MACRO(s) LFS2 ## s
-#define LFSx_API(s) lfs2_ ## s
-#define MP_VFS_LFSx(s) mp_vfs_lfs2_ ## s
+#define LFSx_MACRO(s) LFS2##s
+#define LFSx_API(s) lfs2_##s
+#define MP_VFS_LFSx(s) mp_vfs_lfs2_##s
 #define MP_OBJ_VFS_LFSx mp_obj_vfs_lfs2_t
 #define MP_OBJ_VFS_LFSx_FILE mp_obj_vfs_lfs2_file_t
 #define MP_TYPE_VFS_LFSx mp_type_vfs_lfs2
-#define MP_TYPE_VFS_LFSx_(s) mp_type_vfs_lfs2 ## s
+#define MP_TYPE_VFS_LFSx_(s) mp_type_vfs_lfs2##s
 
 typedef struct _mp_obj_vfs_lfs2_t {
     mp_obj_base_t base;
diff --git a/extmod/vfs_lfsx.c b/extmod/vfs_lfsx.c
index 4f5ad5f..b381056 100644
--- a/extmod/vfs_lfsx.c
+++ b/extmod/vfs_lfsx.c
@@ -34,7 +34,7 @@
 #include "py/mperrno.h"
 #include "extmod/vfs.h"
 
-STATIC int MP_VFS_LFSx(dev_ioctl)(const struct LFSx_API(config) *c, int cmd, int arg, bool must_return_int) {
+STATIC int MP_VFS_LFSx(dev_ioctl)(const struct LFSx_API (config) * c, int cmd, int arg, bool must_return_int) {
     mp_obj_t ret = mp_vfs_blockdev_ioctl(c->context, cmd, arg);
     int ret_i = 0;
     if (must_return_int || ret != mp_const_none) {
@@ -43,27 +43,27 @@
     return ret_i;
 }
 
-STATIC int MP_VFS_LFSx(dev_read)(const struct LFSx_API(config) *c, LFSx_API(block_t) block, LFSx_API(off_t) off, void *buffer, LFSx_API(size_t) size) {
+STATIC int MP_VFS_LFSx(dev_read)(const struct LFSx_API (config) * c, LFSx_API(block_t) block, LFSx_API(off_t) off, void *buffer, LFSx_API(size_t) size) {
     return mp_vfs_blockdev_read_ext(c->context, block, off, size, buffer);
 }
 
-STATIC int MP_VFS_LFSx(dev_prog)(const struct LFSx_API(config) *c, LFSx_API(block_t) block, LFSx_API(off_t) off, const void *buffer, LFSx_API(size_t) size) {
+STATIC int MP_VFS_LFSx(dev_prog)(const struct LFSx_API (config) * c, LFSx_API(block_t) block, LFSx_API(off_t) off, const void *buffer, LFSx_API(size_t) size) {
     return mp_vfs_blockdev_write_ext(c->context, block, off, size, buffer);
 }
 
-STATIC int MP_VFS_LFSx(dev_erase)(const struct LFSx_API(config) *c, LFSx_API(block_t) block) {
+STATIC int MP_VFS_LFSx(dev_erase)(const struct LFSx_API (config) * c, LFSx_API(block_t) block) {
     return MP_VFS_LFSx(dev_ioctl)(c, MP_BLOCKDEV_IOCTL_BLOCK_ERASE, block, true);
 }
 
-STATIC int MP_VFS_LFSx(dev_sync)(const struct LFSx_API(config) *c) {
+STATIC int MP_VFS_LFSx(dev_sync)(const struct LFSx_API (config) * c) {
     return MP_VFS_LFSx(dev_ioctl)(c, MP_BLOCKDEV_IOCTL_SYNC, 0, false);
 }
 
-STATIC void MP_VFS_LFSx(init_config)(MP_OBJ_VFS_LFSx *self, mp_obj_t bdev, size_t read_size, size_t prog_size, size_t lookahead) {
+STATIC void MP_VFS_LFSx(init_config)(MP_OBJ_VFS_LFSx * self, mp_obj_t bdev, size_t read_size, size_t prog_size, size_t lookahead) {
     self->blockdev.flags = MP_BLOCKDEV_FLAG_FREE_OBJ;
     mp_vfs_blockdev_init(&self->blockdev, bdev);
 
-    struct LFSx_API(config) *config = &self->config;
+    struct LFSx_API (config) * config = &self->config;
     memset(config, 0, sizeof(*config));
 
     config->context = &self->blockdev;
@@ -98,7 +98,7 @@
     #endif
 }
 
-const char *MP_VFS_LFSx(make_path)(MP_OBJ_VFS_LFSx *self, mp_obj_t path_in) {
+const char *MP_VFS_LFSx(make_path)(MP_OBJ_VFS_LFSx * self, mp_obj_t path_in) {
     const char *path = mp_obj_str_get_str(path_in);
     if (path[0] != '/') {
         size_t l = vstr_len(&self->cur_dir);
@@ -111,7 +111,7 @@
     return path;
 }
 
-STATIC mp_obj_t MP_VFS_LFSx(make_new)(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
+STATIC mp_obj_t MP_VFS_LFSx(make_new)(const mp_obj_type_t * type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
     mp_arg_val_t args[MP_ARRAY_SIZE(lfs_make_allowed_args)];
     mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(lfs_make_allowed_args), lfs_make_allowed_args, args);
 
@@ -147,7 +147,7 @@
 // Implementation of mp_vfs_lfs_file_open is provided in vfs_lfsx_file.c
 STATIC MP_DEFINE_CONST_FUN_OBJ_3(MP_VFS_LFSx(open_obj), MP_VFS_LFSx(file_open));
 
-typedef struct MP_VFS_LFSx(_ilistdir_it_t) {
+typedef struct MP_VFS_LFSx (_ilistdir_it_t) {
     mp_obj_base_t base;
     mp_fun_1_t iternext;
     bool is_str;
@@ -156,9 +156,9 @@
 } MP_VFS_LFSx(ilistdir_it_t);
 
 STATIC mp_obj_t MP_VFS_LFSx(ilistdir_it_iternext)(mp_obj_t self_in) {
-    MP_VFS_LFSx(ilistdir_it_t) *self = MP_OBJ_TO_PTR(self_in);
+    MP_VFS_LFSx(ilistdir_it_t) * self = MP_OBJ_TO_PTR(self_in);
 
-    struct LFSx_API(info) info;
+    struct LFSx_API (info) info;
     for (;;) {
         int ret = LFSx_API(dir_read)(&self->vfs->lfs, &self->dir, &info);
         if (ret == 0) {
@@ -166,7 +166,7 @@
             return MP_OBJ_STOP_ITERATION;
         }
         if (!(info.name[0] == '.' && (info.name[1] == '\0'
-            || (info.name[1] == '.' && info.name[2] == '\0')))) {
+                                      || (info.name[1] == '.' && info.name[2] == '\0')))) {
             break;
         }
     }
@@ -176,7 +176,7 @@
     if (self->is_str) {
         t->items[0] = mp_obj_new_str(info.name, strlen(info.name));
     } else {
-        t->items[0] = mp_obj_new_bytes((const byte*)info.name, strlen(info.name));
+        t->items[0] = mp_obj_new_bytes((const byte *)info.name, strlen(info.name));
     }
     t->items[1] = MP_OBJ_NEW_SMALL_INT(info.type == LFSx_MACRO(_TYPE_REG) ? MP_S_IFREG : MP_S_IFDIR);
     t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // no inode number
@@ -198,7 +198,7 @@
         path = vstr_null_terminated_str(&self->cur_dir);
     }
 
-    MP_VFS_LFSx(ilistdir_it_t) *iter = m_new_obj(MP_VFS_LFSx(ilistdir_it_t));
+    MP_VFS_LFSx(ilistdir_it_t) * iter = m_new_obj(MP_VFS_LFSx(ilistdir_it_t));
     iter->base.type = &mp_type_polymorph_iter;
     iter->iternext = MP_VFS_LFSx(ilistdir_it_iternext);
     iter->is_str = is_str_type;
@@ -267,7 +267,7 @@
     const char *path = MP_VFS_LFSx(make_path)(self, path_in);
     if (path[1] != '\0') {
         // Not at root, check it exists
-        struct LFSx_API(info) info;
+        struct LFSx_API (info) info;
         int ret = LFSx_API(stat)(&self->lfs, path, &info);
         if (ret < 0 || info.type != LFSx_MACRO(_TYPE_DIR)) {
             mp_raise_OSError(-MP_ENOENT);
@@ -305,7 +305,7 @@
 STATIC mp_obj_t MP_VFS_LFSx(stat)(mp_obj_t self_in, mp_obj_t path_in) {
     MP_OBJ_VFS_LFSx *self = MP_OBJ_TO_PTR(self_in);
     const char *path = mp_obj_str_get_str(path_in);
-    struct LFSx_API(info) info;
+    struct LFSx_API (info) info;
     int ret = LFSx_API(stat)(&self->lfs, path, &info);
     if (ret < 0) {
         mp_raise_OSError(-ret);
@@ -329,7 +329,7 @@
 
 STATIC int LFSx_API(traverse_cb)(void *data, LFSx_API(block_t) bl) {
     (void)bl;
-    uint32_t *n = (uint32_t*)data;
+    uint32_t *n = (uint32_t *)data;
     *n += 1;
     return LFSx_MACRO(_ERR_OK);
 }
@@ -399,7 +399,7 @@
 
 STATIC mp_import_stat_t MP_VFS_LFSx(import_stat)(void *self_in, const char *path) {
     MP_OBJ_VFS_LFSx *self = self_in;
-    struct LFSx_API(info) info;
+    struct LFSx_API (info) info;
     int ret = LFSx_API(stat)(&self->lfs, path, &info);
     if (ret == 0) {
         if (info.type == LFSx_MACRO(_TYPE_REG)) {
@@ -424,5 +424,5 @@
     #endif
     .make_new = MP_VFS_LFSx(make_new),
     .protocol = &MP_VFS_LFSx(proto),
-    .locals_dict = (mp_obj_dict_t*)&MP_VFS_LFSx(locals_dict),
+    .locals_dict = (mp_obj_dict_t *)&MP_VFS_LFSx(locals_dict),
 };
diff --git a/extmod/vfs_lfsx_file.c b/extmod/vfs_lfsx_file.c
index 113c3ec..f74b418 100644
--- a/extmod/vfs_lfsx_file.c
+++ b/extmod/vfs_lfsx_file.c
@@ -32,13 +32,13 @@
 #include "py/mperrno.h"
 #include "extmod/vfs.h"
 
-STATIC void MP_VFS_LFSx(check_open)(MP_OBJ_VFS_LFSx_FILE *self) {
+STATIC void MP_VFS_LFSx(check_open)(MP_OBJ_VFS_LFSx_FILE * self) {
     if (self->vfs == NULL) {
         mp_raise_ValueError(NULL);
     }
 }
 
-STATIC void MP_VFS_LFSx(file_print)(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
+STATIC void MP_VFS_LFSx(file_print)(const mp_print_t * print, mp_obj_t self_in, mp_print_kind_t kind) {
     (void)self_in;
     (void)kind;
     mp_printf(print, "<io.%s>", mp_obj_get_type_str(self_in));
@@ -147,7 +147,7 @@
     }
 
     if (request == MP_STREAM_SEEK) {
-        struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)(uintptr_t)arg;
+        struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)(uintptr_t)arg;
         int res = LFSx_API(file_seek)(&self->vfs->lfs, &self->file, s->offset, s->whence);
         if (res < 0) {
             *errcode = -res;
@@ -214,7 +214,7 @@
     .getiter = mp_identity_getiter,
     .iternext = mp_stream_unbuffered_iter,
     .protocol = &MP_VFS_LFSx(fileio_stream_p),
-    .locals_dict = (mp_obj_dict_t*)&MP_VFS_LFSx(file_locals_dict),
+    .locals_dict = (mp_obj_dict_t *)&MP_VFS_LFSx(file_locals_dict),
 };
 #endif
 
@@ -232,5 +232,5 @@
     .getiter = mp_identity_getiter,
     .iternext = mp_stream_unbuffered_iter,
     .protocol = &MP_VFS_LFSx(textio_stream_p),
-    .locals_dict = (mp_obj_dict_t*)&MP_VFS_LFSx(file_locals_dict),
+    .locals_dict = (mp_obj_dict_t *)&MP_VFS_LFSx(file_locals_dict),
 };
diff --git a/extmod/vfs_posix.c b/extmod/vfs_posix.c
index 22471e4..55a3e71 100644
--- a/extmod/vfs_posix.c
+++ b/extmod/vfs_posix.c
@@ -64,7 +64,7 @@
     }
 }
 
-STATIC mp_obj_t vfs_posix_fun1_helper(mp_obj_t self_in, mp_obj_t path_in, int (*f)(const char*)) {
+STATIC mp_obj_t vfs_posix_fun1_helper(mp_obj_t self_in, mp_obj_t path_in, int (*f)(const char *)) {
     mp_obj_vfs_posix_t *self = MP_OBJ_TO_PTR(self_in);
     int ret = f(vfs_posix_get_path_str(self, path_in));
     if (ret != 0) {
@@ -193,7 +193,7 @@
         if (self->is_str) {
             t->items[0] = mp_obj_new_str(fn, strlen(fn));
         } else {
-            t->items[0] = mp_obj_new_bytes((const byte*)fn, strlen(fn));
+            t->items[0] = mp_obj_new_bytes((const byte *)fn, strlen(fn));
         }
 
         #ifdef _DIRENT_HAVE_D_TYPE
@@ -382,7 +382,7 @@
     .name = MP_QSTR_VfsPosix,
     .make_new = vfs_posix_make_new,
     .protocol = &vfs_posix_proto,
-    .locals_dict = (mp_obj_dict_t*)&vfs_posix_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&vfs_posix_locals_dict,
 };
 
 #endif // MICROPY_VFS_POSIX
diff --git a/extmod/vfs_posix_file.c b/extmod/vfs_posix_file.c
index c817e51..1a5c0eb 100644
--- a/extmod/vfs_posix_file.c
+++ b/extmod/vfs_posix_file.c
@@ -79,7 +79,7 @@
             case '+':
                 mode_rw = O_RDWR;
                 break;
-            #if MICROPY_PY_IO_FILEIO
+                #if MICROPY_PY_IO_FILEIO
             // If we don't have io.FileIO, then files are in text mode implicitly
             case 'b':
                 type = &mp_type_vfs_posix_fileio;
@@ -87,7 +87,7 @@
             case 't':
                 type = &mp_type_vfs_posix_textio;
                 break;
-            #endif
+                #endif
         }
     }
 
@@ -189,7 +189,7 @@
             }
             return 0;
         case MP_STREAM_SEEK: {
-            struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)arg;
+            struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)arg;
             MP_THREAD_GIL_EXIT();
             off_t off = lseek(o->fd, s->offset, s->whence);
             MP_THREAD_GIL_ENTER();
@@ -246,7 +246,7 @@
     .getiter = mp_identity_getiter,
     .iternext = mp_stream_unbuffered_iter,
     .protocol = &vfs_posix_fileio_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&vfs_posix_rawfile_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&vfs_posix_rawfile_locals_dict,
 };
 #endif
 
@@ -265,10 +265,10 @@
     .getiter = mp_identity_getiter,
     .iternext = mp_stream_unbuffered_iter,
     .protocol = &vfs_posix_textio_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&vfs_posix_rawfile_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&vfs_posix_rawfile_locals_dict,
 };
 
-const mp_obj_vfs_posix_file_t mp_sys_stdin_obj  = {{&mp_type_textio}, STDIN_FILENO};
+const mp_obj_vfs_posix_file_t mp_sys_stdin_obj = {{&mp_type_textio}, STDIN_FILENO};
 const mp_obj_vfs_posix_file_t mp_sys_stdout_obj = {{&mp_type_textio}, STDOUT_FILENO};
 const mp_obj_vfs_posix_file_t mp_sys_stderr_obj = {{&mp_type_textio}, STDERR_FILENO};
 
diff --git a/extmod/vfs_reader.c b/extmod/vfs_reader.c
index e1ee45a..db13ce3 100644
--- a/extmod/vfs_reader.c
+++ b/extmod/vfs_reader.c
@@ -42,7 +42,7 @@
 } mp_reader_vfs_t;
 
 STATIC mp_uint_t mp_reader_vfs_readbyte(void *data) {
-    mp_reader_vfs_t *reader = (mp_reader_vfs_t*)data;
+    mp_reader_vfs_t *reader = (mp_reader_vfs_t *)data;
     if (reader->pos >= reader->len) {
         if (reader->len < sizeof(reader->buf)) {
             return MP_READER_EOF;
@@ -64,7 +64,7 @@
 }
 
 STATIC void mp_reader_vfs_close(void *data) {
-    mp_reader_vfs_t *reader = (mp_reader_vfs_t*)data;
+    mp_reader_vfs_t *reader = (mp_reader_vfs_t *)data;
     mp_stream_close(reader->file);
     m_del_obj(mp_reader_vfs_t, reader);
 }
@@ -72,7 +72,7 @@
 void mp_reader_new_file(mp_reader_t *reader, const char *filename) {
     mp_reader_vfs_t *rf = m_new_obj(mp_reader_vfs_t);
     mp_obj_t arg = mp_obj_new_str(filename, strlen(filename));
-    rf->file = mp_vfs_open(1, &arg, (mp_map_t*)&mp_const_empty_map);
+    rf->file = mp_vfs_open(1, &arg, (mp_map_t *)&mp_const_empty_map);
     int errcode;
     rf->len = mp_stream_rw(rf->file, rf->buf, sizeof(rf->buf), &errcode, MP_STREAM_RW_READ | MP_STREAM_RW_ONCE);
     if (errcode != 0) {
diff --git a/extmod/virtpin.c b/extmod/virtpin.c
index dbfa21d..71a1123 100644
--- a/extmod/virtpin.c
+++ b/extmod/virtpin.c
@@ -27,13 +27,13 @@
 #include "extmod/virtpin.h"
 
 int mp_virtual_pin_read(mp_obj_t pin) {
-    mp_obj_base_t* s = (mp_obj_base_t*)MP_OBJ_TO_PTR(pin);
-    mp_pin_p_t *pin_p = (mp_pin_p_t*)s->type->protocol;
+    mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(pin);
+    mp_pin_p_t *pin_p = (mp_pin_p_t *)s->type->protocol;
     return pin_p->ioctl(pin, MP_PIN_READ, 0, NULL);
 }
 
 void mp_virtual_pin_write(mp_obj_t pin, int value) {
-    mp_obj_base_t* s = (mp_obj_base_t*)MP_OBJ_TO_PTR(pin);
-    mp_pin_p_t *pin_p = (mp_pin_p_t*)s->type->protocol;
+    mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(pin);
+    mp_pin_p_t *pin_p = (mp_pin_p_t *)s->type->protocol;
     pin_p->ioctl(pin, MP_PIN_WRITE, value, NULL);
 }
diff --git a/extmod/webrepl/manifest.py b/extmod/webrepl/manifest.py
index 0f2b440..6ce7d85 100644
--- a/extmod/webrepl/manifest.py
+++ b/extmod/webrepl/manifest.py
@@ -1 +1 @@
-freeze('.', ('webrepl.py', 'webrepl_setup.py', 'websocket_helper.py',))
+freeze(".", ("webrepl.py", "webrepl_setup.py", "websocket_helper.py",))
diff --git a/extmod/webrepl/webrepl.py b/extmod/webrepl/webrepl.py
index 24c6329..8ddf561 100644
--- a/extmod/webrepl/webrepl.py
+++ b/extmod/webrepl/webrepl.py
@@ -9,6 +9,7 @@
 listen_s = None
 client_s = None
 
+
 def setup_conn(port, accept_handler):
     global listen_s
     listen_s = socket.socket()
@@ -44,7 +45,7 @@
     ws = _webrepl._webrepl(ws)
     cl.setblocking(False)
     # 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)
     uos.dupterm(ws)
 
@@ -63,6 +64,7 @@
     if password is None:
         try:
             import webrepl_cfg
+
             _webrepl.password(webrepl_cfg.PASS)
             setup_conn(port, accept_conn)
             print("Started webrepl in normal mode")
diff --git a/extmod/webrepl/webrepl_setup.py b/extmod/webrepl/webrepl_setup.py
index 129313a..ffc9c77 100644
--- a/extmod/webrepl/webrepl_setup.py
+++ b/extmod/webrepl/webrepl_setup.py
@@ -1,20 +1,24 @@
 import sys
-#import uos as os
+
+# import uos as os
 import os
 import machine
 
 RC = "./boot.py"
 CONFIG = "./webrepl_cfg.py"
 
+
 def input_choice(prompt, choices):
     while 1:
         resp = input(prompt)
         if resp in choices:
             return resp
 
+
 def getpass(prompt):
     return input(prompt)
 
+
 def input_pass():
     while 1:
         passwd1 = getpass("New password (4-9 chars): ")
@@ -77,7 +81,9 @@
 
     if resp == "E":
         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:
             print("To enable WebREPL, you must set password for it")
             resp2 = "y"
@@ -87,7 +93,6 @@
             with open(CONFIG, "w") as f:
                 f.write("PASS = %r\n" % passwd)
 
-
     if resp not in ("D", "E") or (resp == "D" and not status) or (resp == "E" and status):
         print("No further action required")
         sys.exit()
@@ -99,4 +104,5 @@
     if resp == "y":
         machine.reset()
 
+
 main()
diff --git a/extmod/webrepl/websocket_helper.py b/extmod/webrepl/websocket_helper.py
index 9c06db5..5ca8053 100644
--- a/extmod/webrepl/websocket_helper.py
+++ b/extmod/webrepl/websocket_helper.py
@@ -1,4 +1,5 @@
 import sys
+
 try:
     import ubinascii as binascii
 except:
@@ -10,10 +11,11 @@
 
 DEBUG = 0
 
+
 def server_handshake(sock):
     clr = sock.makefile("rwb", 0)
     l = clr.readline()
-    #sys.stdout.write(repr(l))
+    # sys.stdout.write(repr(l))
 
     webkey = None
 
@@ -23,11 +25,11 @@
             raise OSError("EOF in headers")
         if l == b"\r\n":
             break
-    #    sys.stdout.write(l)
+        #    sys.stdout.write(l)
         h, v = [x.strip() for x in l.split(b":", 1)]
         if DEBUG:
             print((h, v))
-        if h == b'Sec-WebSocket-Key':
+        if h == b"Sec-WebSocket-Key":
             webkey = v
 
     if not webkey:
@@ -43,11 +45,13 @@
     if DEBUG:
         print("respkey:", respkey)
 
-    sock.send(b"""\
+    sock.send(
+        b"""\
 HTTP/1.1 101 Switching Protocols\r
 Upgrade: websocket\r
 Connection: Upgrade\r
-Sec-WebSocket-Accept: """)
+Sec-WebSocket-Accept: """
+    )
     sock.send(respkey)
     sock.send("\r\n\r\n")
 
@@ -57,18 +61,22 @@
 # servers.
 def client_handshake(sock):
     cl = sock.makefile("rwb", 0)
-    cl.write(b"""\
+    cl.write(
+        b"""\
 GET / HTTP/1.1\r
 Host: echo.websocket.org\r
 Connection: Upgrade\r
 Upgrade: websocket\r
 Sec-WebSocket-Key: foo\r
 \r
-""")
+"""
+    )
     l = cl.readline()
-#    print(l)
+    #    print(l)
     while 1:
         l = cl.readline()
         if l == b"\r\n":
             break
+
+
 #        sys.stdout.write(l)
diff --git a/lib/netutils/dhcpserver.c b/lib/netutils/dhcpserver.c
index 476eb3d..7f97ee6 100644
--- a/lib/netutils/dhcpserver.c
+++ b/lib/netutils/dhcpserver.c
@@ -99,7 +99,7 @@
     }
 
     // Register callback
-    udp_recv(*udp, cb_udp_recv, (void*)cb_data);
+    udp_recv(*udp, cb_udp_recv, (void *)cb_data);
 
     return 0; // success
 }
@@ -202,7 +202,7 @@
     dhcp_msg.op = DHCPOFFER;
     memcpy(&dhcp_msg.yiaddr, &d->ip.addr, 4);
 
-    uint8_t *opt = (uint8_t*)&dhcp_msg.options;
+    uint8_t *opt = (uint8_t *)&dhcp_msg.options;
     opt += 4; // assume magic cookie: 99, 130, 83, 99
 
     switch (opt[2]) {
@@ -281,7 +281,7 @@
     opt_write_u32(&opt, DHCP_OPT_DNS, DEFAULT_DNS); // can have mulitple addresses
     opt_write_u32(&opt, DHCP_OPT_IP_LEASE_TIME, DEFAULT_LEASE_TIME_S);
     *opt++ = DHCP_OPT_END;
-    dhcp_socket_sendto(&d->udp, &dhcp_msg, opt - (uint8_t*)&dhcp_msg, 0xffffffff, PORT_DHCP_CLIENT);
+    dhcp_socket_sendto(&d->udp, &dhcp_msg, opt - (uint8_t *)&dhcp_msg, 0xffffffff, PORT_DHCP_CLIENT);
 
 ignore_request:
     pbuf_free(p);
diff --git a/lib/netutils/netutils.c b/lib/netutils/netutils.c
index 073f46b..917cd83 100644
--- a/lib/netutils/netutils.c
+++ b/lib/netutils/netutils.c
@@ -64,7 +64,7 @@
     }
     const char *s = addr_str;
     const char *s_top = addr_str + addr_len;
-    for (mp_uint_t i = 3 ; ; i--) {
+    for (mp_uint_t i = 3; ; i--) {
         mp_uint_t val = 0;
         for (; s < s_top && *s != '.'; s++) {
             val = val * 10 + *s - '0';
diff --git a/lib/netutils/trace.c b/lib/netutils/trace.c
index 7c79713..1610966 100644
--- a/lib/netutils/trace.c
+++ b/lib/netutils/trace.c
@@ -44,10 +44,14 @@
 static const char *ethertype_str(uint16_t type) {
     // A value between 0x0000 - 0x05dc (inclusive) indicates a length, not type
     switch (type) {
-        case 0x0800: return "IPv4";
-        case 0x0806: return "ARP";
-        case 0x86dd: return "IPv6";
-        default: return NULL;
+        case 0x0800:
+            return "IPv4";
+        case 0x0806:
+            return "ARP";
+        case 0x86dd:
+            return "IPv6";
+        default:
+            return NULL;
     }
 }
 
@@ -113,14 +117,30 @@
                     buf += n;
                     mp_printf(print, " opts:");
                     switch (buf[6]) {
-                        case 1: mp_printf(print, " DISCOVER"); break;
-                        case 2: mp_printf(print, " OFFER"); break;
-                        case 3: 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;
+                        case 1:
+                            mp_printf(print, " DISCOVER");
+                            break;
+                        case 2:
+                            mp_printf(print, " OFFER");
+                            break;
+                        case 3:
+                            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 {
diff --git a/lib/timeutils/timeutils.c b/lib/timeutils/timeutils.c
index eb3dc80..fc8b5e7 100644
--- a/lib/timeutils/timeutils.c
+++ b/lib/timeutils/timeutils.c
@@ -36,11 +36,11 @@
 
 #define LEAPOCH ((31 + 29) * 86400)
 
-#define DAYS_PER_400Y (365*400 + 97)
-#define DAYS_PER_100Y (365*100 + 24)
-#define DAYS_PER_4Y   (365*4   + 1)
+#define DAYS_PER_400Y (365 * 400 + 97)
+#define DAYS_PER_100Y (365 * 100 + 24)
+#define DAYS_PER_4Y   (365 * 4 + 1)
 
-STATIC const uint16_t days_since_jan1[]= { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
+STATIC const uint16_t days_since_jan1[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
 
 bool timeutils_is_leap_year(mp_uint_t year) {
     return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
diff --git a/lib/timeutils/timeutils.h b/lib/timeutils/timeutils.h
index 9b1abeb..cb7a721 100644
--- a/lib/timeutils/timeutils.h
+++ b/lib/timeutils/timeutils.h
@@ -28,14 +28,14 @@
 #define MICROPY_INCLUDED_LIB_TIMEUTILS_TIMEUTILS_H
 
 typedef struct _timeutils_struct_time_t {
-    uint16_t    tm_year;    // i.e. 2014
-    uint8_t     tm_mon;     // 1..12
-    uint8_t     tm_mday;    // 1..31
-    uint8_t     tm_hour;    // 0..23
-    uint8_t     tm_min;     // 0..59
-    uint8_t     tm_sec;     // 0..59
-    uint8_t     tm_wday;    // 0..6  0 = Monday
-    uint16_t    tm_yday;    // 1..366
+    uint16_t tm_year;       // i.e. 2014
+    uint8_t tm_mon;         // 1..12
+    uint8_t tm_mday;        // 1..31
+    uint8_t tm_hour;        // 0..23
+    uint8_t tm_min;         // 0..59
+    uint8_t tm_sec;         // 0..59
+    uint8_t tm_wday;        // 0..6  0 = Monday
+    uint16_t tm_yday;       // 1..366
 } timeutils_struct_time_t;
 
 bool timeutils_is_leap_year(mp_uint_t year);
diff --git a/lib/utils/mpirq.c b/lib/utils/mpirq.c
index 1bfce64..d04fab6 100644
--- a/lib/utils/mpirq.c
+++ b/lib/utils/mpirq.c
@@ -52,7 +52,7 @@
 mp_irq_obj_t *mp_irq_new(const mp_irq_methods_t *methods, mp_obj_t parent) {
     mp_irq_obj_t *self = m_new0(mp_irq_obj_t, 1);
     self->base.type = &mp_irq_type;
-    self->methods = (mp_irq_methods_t*)methods;
+    self->methods = (mp_irq_methods_t *)methods;
     self->parent = parent;
     self->handler = mp_const_none;
     self->ishard = false;
@@ -120,5 +120,5 @@
     { &mp_type_type },
     .name = MP_QSTR_irq,
     .call = mp_irq_call,
-    .locals_dict = (mp_obj_dict_t*)&mp_irq_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&mp_irq_locals_dict,
 };
diff --git a/lib/utils/pyexec.c b/lib/utils/pyexec.c
index 0c9e979..d5ac4a5 100644
--- a/lib/utils/pyexec.c
+++ b/lib/utils/pyexec.c
@@ -89,7 +89,7 @@
             } else if (exec_flags & EXEC_FLAG_SOURCE_IS_FILENAME) {
                 lex = mp_lexer_new_from_file(source);
             } else {
-                lex = (mp_lexer_t*)source;
+                lex = (mp_lexer_t *)source;
             }
             // source is a lexer, parse and compile the script
             qstr source_name = lex->source_name;
@@ -122,7 +122,7 @@
             mp_hal_stdout_tx_strn("\x04", 1);
         }
         // check for SystemExit
-        if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t*)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) {
+        if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) {
             // at the moment, the value of SystemExit is unused
             ret = pyexec_system_exit;
         } else {
@@ -141,8 +141,8 @@
             size_t n_pool, n_qstr, n_str_data_bytes, n_total_bytes;
             qstr_pool_info(&n_pool, &n_qstr, &n_str_data_bytes, &n_total_bytes);
             printf("qstr:\n  n_pool=%u\n  n_qstr=%u\n  "
-                   "n_str_data_bytes=%u\n  n_total_bytes=%u\n",
-                   (unsigned)n_pool, (unsigned)n_qstr, (unsigned)n_str_data_bytes, (unsigned)n_total_bytes);
+                "n_str_data_bytes=%u\n  n_total_bytes=%u\n",
+                (unsigned)n_pool, (unsigned)n_qstr, (unsigned)n_str_data_bytes, (unsigned)n_total_bytes);
         }
 
         #if MICROPY_ENABLE_GC
@@ -316,10 +316,10 @@
     } else {
 
         if (ret == CHAR_CTRL_C) {
-           // cancel everything
-           mp_hal_stdout_tx_str("\r\n");
-           repl.cont_line = false;
-           goto input_restart;
+            // cancel everything
+            mp_hal_stdout_tx_str("\r\n");
+            repl.cont_line = false;
+            goto input_restart;
         } else if (ret == CHAR_CTRL_D) {
             // stop entering compound statement
             goto exec;
@@ -335,13 +335,13 @@
             return 0;
         }
 
-exec: ;
+    exec:;
         int ret = parse_compile_execute(MP_STATE_VM(repl_line), MP_PARSE_SINGLE_INPUT, EXEC_FLAG_ALLOW_DEBUGGING | EXEC_FLAG_IS_REPL | EXEC_FLAG_SOURCE_IS_VSTR);
         if (ret & PYEXEC_FORCED_EXIT) {
             return ret;
         }
 
-input_restart:
+    input_restart:
         vstr_reset(MP_STATE_VM(repl_line));
         repl.cont_line = false;
         repl.paste_mode = false;
@@ -419,11 +419,11 @@
     vstr_t line;
     vstr_init(&line, 32);
 
-#if defined(USE_HOST_MODE) && MICROPY_HW_HAS_LCD
+    #if defined(USE_HOST_MODE) && MICROPY_HW_HAS_LCD
     // in host mode, we enable the LCD for the repl
     mp_obj_t lcd_o = mp_call_function_0(mp_load_name(qstr_from_str("LCD")));
     mp_call_function_1(mp_load_attr(lcd_o, qstr_from_str("light")), mp_const_true);
-#endif
+    #endif
 
 friendly_repl_reset:
     mp_hal_stdout_tx_str("MicroPython " MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE "; " MICROPY_HW_BOARD_NAME " with " MICROPY_HW_MCU_NAME "\r\n");
diff --git a/lib/utils/sys_stdio_mphal.c b/lib/utils/sys_stdio_mphal.c
index 3fcaf8e..e72facb 100644
--- a/lib/utils/sys_stdio_mphal.c
+++ b/lib/utils/sys_stdio_mphal.c
@@ -65,7 +65,7 @@
             if (c == '\r') {
                 c = '\n';
             }
-            ((byte*)buf)[i] = c;
+            ((byte *)buf)[i] = c;
         }
         return size;
     } else {
@@ -103,9 +103,9 @@
 // TODO gc hook to close the file if not already closed
 
 STATIC const mp_rom_map_elem_t stdio_locals_dict_table[] = {
-#if MICROPY_PY_SYS_STDIO_BUFFER
+    #if MICROPY_PY_SYS_STDIO_BUFFER
     { MP_ROM_QSTR(MP_QSTR_buffer), MP_ROM_PTR(&stdio_buffer_obj) },
-#endif
+    #endif
     { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
     { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
     { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj)},
@@ -134,7 +134,7 @@
     .getiter = mp_identity_getiter,
     .iternext = mp_stream_unbuffered_iter,
     .protocol = &stdio_obj_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&stdio_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&stdio_locals_dict,
 };
 
 const sys_stdio_obj_t mp_sys_stdin_obj = {{&stdio_obj_type}, .fd = STDIO_FD_IN};
@@ -144,7 +144,7 @@
 #if MICROPY_PY_SYS_STDIO_BUFFER
 STATIC mp_uint_t stdio_buffer_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) {
     for (uint i = 0; i < size; i++) {
-        ((byte*)buf)[i] = mp_hal_stdin_rx_chr();
+        ((byte *)buf)[i] = mp_hal_stdin_rx_chr();
     }
     return size;
 }
@@ -168,7 +168,7 @@
     .getiter = mp_identity_getiter,
     .iternext = mp_stream_unbuffered_iter,
     .protocol = &stdio_buffer_obj_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&stdio_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&stdio_locals_dict,
 };
 
 STATIC const sys_stdio_obj_t stdio_buffer_obj = {{&stdio_buffer_obj_type}, .fd = 0}; // fd unused
diff --git a/mpy-cross/gccollect.c b/mpy-cross/gccollect.c
index 9e4b59d..32ce825 100644
--- a/mpy-cross/gccollect.c
+++ b/mpy-cross/gccollect.c
@@ -49,20 +49,20 @@
     register long r13 asm ("r13");
     register long r14 asm ("r14");
     register long r15 asm ("r15");
-#ifdef __clang__
+    #ifdef __clang__
     // TODO:
     // This is dirty workaround for Clang. It tries to get around
     // uncompliant (wrt to GCC) behavior of handling register variables.
     // Application of this patch here is random, and done only to unbreak
     // MacOS build. Better, cross-arch ways to deal with Clang issues should
     // be found.
-    asm("" : "=r"(rbx));
-    asm("" : "=r"(rbp));
-    asm("" : "=r"(r12));
-    asm("" : "=r"(r13));
-    asm("" : "=r"(r14));
-    asm("" : "=r"(r15));
-#endif
+    asm ("" : "=r" (rbx));
+    asm ("" : "=r" (rbp));
+    asm ("" : "=r" (r12));
+    asm ("" : "=r" (r13));
+    asm ("" : "=r" (r14));
+    asm ("" : "=r" (r15));
+    #endif
     arr[0] = rbx;
     arr[1] = rbp;
     arr[2] = r12;
@@ -141,7 +141,7 @@
     regs_t regs;
     gc_helper_get_regs(regs);
     // GC stack (and regs because we captured them)
-    void **regs_ptr = (void**)(void*)&regs;
+    void **regs_ptr = (void **)(void *)&regs;
     gc_collect_root(regs_ptr, ((mp_uint_t)MP_STATE_THREAD(stack_top) - (mp_uint_t)&regs) / sizeof(mp_uint_t));
     gc_collect_end();
 }
diff --git a/mpy-cross/main.c b/mpy-cross/main.c
index e822772..e4c4104 100644
--- a/mpy-cross/main.c
+++ b/mpy-cross/main.c
@@ -45,7 +45,7 @@
 
 // Heap size of GC heap (if enabled)
 // Make it larger on a 64 bit machine, because pointers are larger.
-long heap_size = 1024*1024 * (sizeof(mp_uint_t) / 4);
+long heap_size = 1024 * 1024 * (sizeof(mp_uint_t) / 4);
 
 STATIC void stderr_print_strn(void *env, const char *str, mp_uint_t len) {
     (void)env;
@@ -97,34 +97,34 @@
 
 STATIC int usage(char **argv) {
     printf(
-"usage: %s [<opts>] [-X <implopt>] <input filename>\n"
-"Options:\n"
-"--version : show version information\n"
-"-o : output file for compiled bytecode (defaults to input with .mpy extension)\n"
-"-s : source filename to embed in the compiled bytecode (defaults to input file)\n"
-"-v : verbose (trace various operations); can be multiple\n"
-"-O[N] : apply bytecode optimizations of level N\n"
-"\n"
-"Target specific options:\n"
-"-msmall-int-bits=number : set the maximum bits used to encode a small-int\n"
-"-mno-unicode : don't support unicode in compiled strings\n"
-"-mcache-lookup-bc : cache map lookups in the bytecode\n"
-"-march=<arch> : set architecture for native emitter; x86, x64, armv6, armv7m, armv7em, armv7emsp, armv7emdp, xtensa, xtensawin\n"
-"\n"
-"Implementation specific options:\n", argv[0]
-);
+        "usage: %s [<opts>] [-X <implopt>] <input filename>\n"
+        "Options:\n"
+        "--version : show version information\n"
+        "-o : output file for compiled bytecode (defaults to input with .mpy extension)\n"
+        "-s : source filename to embed in the compiled bytecode (defaults to input file)\n"
+        "-v : verbose (trace various operations); can be multiple\n"
+        "-O[N] : apply bytecode optimizations of level N\n"
+        "\n"
+        "Target specific options:\n"
+        "-msmall-int-bits=number : set the maximum bits used to encode a small-int\n"
+        "-mno-unicode : don't support unicode in compiled strings\n"
+        "-mcache-lookup-bc : cache map lookups in the bytecode\n"
+        "-march=<arch> : set architecture for native emitter; x86, x64, armv6, armv7m, armv7em, armv7emsp, armv7emdp, xtensa, xtensawin\n"
+        "\n"
+        "Implementation specific options:\n", argv[0]
+        );
     int impl_opts_cnt = 0;
     printf(
-#if MICROPY_EMIT_NATIVE
-"  emit={bytecode,native,viper} -- set the default code emitter\n"
-#else
-"  emit=bytecode -- set the default code emitter\n"
-#endif
-);
+        #if MICROPY_EMIT_NATIVE
+        "  emit={bytecode,native,viper} -- set the default code emitter\n"
+        #else
+        "  emit=bytecode -- set the default code emitter\n"
+        #endif
+        );
     impl_opts_cnt++;
     printf(
-"  heapsize=<n> -- set the heap size for the GC (default %ld)\n"
-, heap_size);
+        "  heapsize=<n> -- set the heap size for the GC (default %ld)\n"
+        , heap_size);
     impl_opts_cnt++;
 
     if (impl_opts_cnt == 0) {
@@ -190,9 +190,9 @@
     gc_init(heap, heap + heap_size);
 
     mp_init();
-#ifdef _WIN32
+    #ifdef _WIN32
     set_fmode_binary();
-#endif
+    #endif
     mp_obj_list_init(mp_sys_path, 0);
     mp_obj_list_init(mp_sys_argv, 0);
 
@@ -241,7 +241,8 @@
                     MP_STATE_VM(mp_optimise_value) = argv[a][2] & 0xf;
                 } else {
                     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) {
                 if (a + 1 >= argc) {
diff --git a/mpy-cross/mpconfigport.h b/mpy-cross/mpconfigport.h
index 533f58a..723d1af 100644
--- a/mpy-cross/mpconfigport.h
+++ b/mpy-cross/mpconfigport.h
@@ -141,7 +141,7 @@
 #else
 #define MP_SSIZE_MAX                _I32_MAX
 #endif
-#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)(p)) //Avoid compiler warning about different const qualifiers
+#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)(p)) //Avoid compiler warning about different const qualifiers
 #define restrict
 #define inline                      __inline
 #define alignof(t)                  __alignof(t)
@@ -152,11 +152,11 @@
 #define S_ISDIR(m)                  (((m) & S_IFMT) == S_IFDIR)
 #ifdef _WIN64
 #define SSIZE_MAX                   _I64_MAX
-typedef __int64                     ssize_t;
+typedef __int64 ssize_t;
 #else
 #define SSIZE_MAX                   _I32_MAX
-typedef int                         ssize_t;
+typedef int ssize_t;
 #endif
-typedef mp_off_t                    off_t;
+typedef mp_off_t off_t;
 
 #endif
diff --git a/ports/bare-arm/main.c b/ports/bare-arm/main.c
index 4183944..df66c04 100644
--- a/ports/bare-arm/main.c
+++ b/ports/bare-arm/main.c
@@ -44,11 +44,15 @@
 MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
 
 void nlr_jump_fail(void *val) {
-    while (1);
+    while (1) {
+        ;
+    }
 }
 
 void NORETURN __fatal_error(const char *msg) {
-    while (1);
+    while (1) {
+        ;
+    }
 }
 
 #ifndef NDEBUG
@@ -71,26 +75,63 @@
 int _isatty() {return 0;}
 */
 
-void *malloc(size_t n) {return NULL;}
-void *calloc(size_t nmemb, size_t size) {return NULL;}
-void *realloc(void *ptr, size_t size) {return NULL;}
-void free(void *p) {}
-int printf(const char *m, ...) {return 0;}
-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;}
+void *malloc(size_t n) {
+    return NULL;
+}
+void *calloc(size_t nmemb, size_t size) {
+    return NULL;
+}
+void *realloc(void *ptr, size_t size) {
+    return NULL;
+}
+void free(void *p) {
+}
+int printf(const char *m, ...) {
+    return 0;
+}
+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>
-int vprintf(const char *format, va_list ap) {return 0;}
-int vsnprintf(char *str,  size_t  size,  const  char  *format, va_list ap) {return 0;}
+int vprintf(const char *format, va_list ap) {
+    return 0;
+}
+int vsnprintf(char *str,  size_t size,  const char *format, va_list ap) {
+    return 0;
+}
 
 #undef putchar
-int putchar(int c) {return 0;}
-int puts(const char *s) {return 0;}
+int putchar(int c) {
+    return 0;
+}
+int puts(const char *s) {
+    return 0;
+}
 
-void _start(void) {main(0, NULL);}
+void _start(void) {
+    main(0, NULL);
+}
diff --git a/ports/bare-arm/mpconfigport.h b/ports/bare-arm/mpconfigport.h
index 395659a..273e214 100644
--- a/ports/bare-arm/mpconfigport.h
+++ b/ports/bare-arm/mpconfigport.h
@@ -49,7 +49,7 @@
 
 // type definitions for the specific machine
 
-#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1))
+#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1))
 
 #define UINT_FMT "%lu"
 #define INT_FMT "%ld"
diff --git a/ports/cc3200/boards/make-pins.py b/ports/cc3200/boards/make-pins.py
index 30db4ac..a204561 100644
--- a/ports/cc3200/boards/make-pins.py
+++ b/ports/cc3200/boards/make-pins.py
@@ -8,20 +8,22 @@
 import csv
 
 
-SUPPORTED_AFS = { 'UART': ('TX', 'RX', 'RTS', 'CTS'),
-                  'SPI': ('CLK', 'MOSI', 'MISO', 'CS0'),
-                  #'I2S': ('CLK', 'FS', 'DAT0', 'DAT1'),
-                  'I2C': ('SDA', 'SCL'),
-                  'TIM': ('PWM'),
-                  'SD': ('CLK', 'CMD', 'DAT0'),
-                  'ADC': ('CH0', 'CH1', 'CH2', 'CH3')
-                }
+SUPPORTED_AFS = {
+    "UART": ("TX", "RX", "RTS", "CTS"),
+    "SPI": ("CLK", "MOSI", "MISO", "CS0"),
+    #'I2S': ('CLK', 'FS', 'DAT0', 'DAT1'),
+    "I2C": ("SDA", "SCL"),
+    "TIM": ("PWM"),
+    "SD": ("CLK", "CMD", "DAT0"),
+    "ADC": ("CH0", "CH1", "CH2", "CH3"),
+}
+
 
 def parse_port_pin(name_str):
     """Parses a string and returns a (port, gpio_bit) tuple."""
     if len(name_str) < 3:
         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")
     if not name_str[2:].isdigit():
         raise ValueError("Expecting numeric GPIO number")
@@ -32,6 +34,7 @@
 
 class AF:
     """Holds the description of an alternate function"""
+
     def __init__(self, name, idx, fn, unit, type):
         self.name = name
         self.idx = idx
@@ -42,11 +45,16 @@
         self.type = type
 
     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:
     """Holds the information associated with a pin."""
+
     def __init__(self, name, port, gpio_bit, pin_num):
         self.name = name
         self.port = port
@@ -59,25 +67,37 @@
         self.afs.append(af)
 
     def print(self):
-        print('// {}'.format(self.name))
+        print("// {}".format(self.name))
         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:
                 af.print()
-            print('};')
-            print('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)))
+            print("};")
+            print(
+                "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:
-            print('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))
+            print(
+                "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):
-        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:
     def __init__(self):
-        self.board_pins = []   # list of pin objects
+        self.board_pins = []  # list of pin objects
 
     def find_pin(self, port, gpio_bit):
         for pin in self.board_pins:
@@ -95,7 +115,7 @@
                 return pin
 
     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)
             for row in rows:
                 try:
@@ -103,16 +123,18 @@
                 except:
                     continue
                 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_num = int(row[pin_col]) - 1;        
+                pin_num = int(row[pin_col]) - 1
                 pin = Pin(row[pinname_col], port_num, gpio_bit, pin_num)
                 self.board_pins.append(pin)
                 af_idx = 0
                 for af in row[af_start_col:]:
-                    af_splitted = af.split('_')
-                    fn_name = af_splitted[0].rstrip('0123456789')
-                    if  fn_name in SUPPORTED_AFS:
+                    af_splitted = af.split("_")
+                    fn_name = af_splitted[0].rstrip("0123456789")
+                    if fn_name in SUPPORTED_AFS:
                         type_name = af_splitted[1]
                         if type_name in SUPPORTED_AFS[fn_name]:
                             unit_idx = af_splitted[0][-1]
@@ -120,7 +142,7 @@
                     af_idx += 1
 
     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)
             for row in rows:
                 # Pin numbers must start from 0 when used with the TI API
@@ -132,29 +154,39 @@
                     pin.board_pin = True
 
     def print_named(self, label, pins):
-        print('')
-        print('STATIC const mp_rom_map_elem_t pin_{:s}_pins_locals_dict_table[] = {{'.format(label))
+        print("")
+        print(
+            "STATIC const mp_rom_map_elem_t pin_{:s}_pins_locals_dict_table[] = {{".format(label)
+        )
         for pin in pins:
             if pin.board_pin:
-                print('    {{ MP_ROM_QSTR(MP_QSTR_{:6s}), MP_ROM_PTR(&pin_{:6s}) }},'.format(pin.name, pin.name))
-        print('};')
-        print('MP_DEFINE_CONST_DICT(pin_{:s}_pins_locals_dict, pin_{:s}_pins_locals_dict_table);'.format(label, label));
+                print(
+                    "    {{ MP_ROM_QSTR(MP_QSTR_{:6s}), MP_ROM_PTR(&pin_{:6s}) }},".format(
+                        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):
         for pin in self.board_pins:
             if pin.board_pin:
                 pin.print()
-        self.print_named('board', self.board_pins)
-        print('')
+        self.print_named("board", self.board_pins)
+        print("")
 
     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:
                 if pin.board_pin:
                     pin.print_header(hdr_file)
 
     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([])
             af_qstr_set = set([])
             for pin in self.board_pins:
@@ -162,67 +194,69 @@
                     pin_qstr_set |= set([pin.name])
                     for af in pin.afs:
                         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):
-                print('Q({})'.format(qstr), file=qstr_file)
-            print('\n// Pin AFs', file=qstr_file)
+                print("Q({})".format(qstr), file=qstr_file)
+            print("\n// Pin AFs", file=qstr_file)
             for qstr in sorted(af_qstr_set):
-                print('Q({})'.format(qstr), file=qstr_file)
+                print("Q({})".format(qstr), file=qstr_file)
 
 
 def main():
     parser = argparse.ArgumentParser(
         prog="make-pins.py",
         usage="%(prog)s [options] [command]",
-        description="Generate board specific pin file"
+        description="Generate board specific pin file",
     )
     parser.add_argument(
-        "-a", "--af",
+        "-a",
+        "--af",
         dest="af_filename",
         help="Specifies the alternate function file for the chip",
-        default="cc3200_af.csv"
+        default="cc3200_af.csv",
     )
     parser.add_argument(
-        "-b", "--board",
-        dest="board_filename",
-        help="Specifies the board file",
+        "-b", "--board", dest="board_filename", help="Specifies the board file",
     )
     parser.add_argument(
-        "-p", "--prefix",
+        "-p",
+        "--prefix",
         dest="prefix_filename",
         help="Specifies beginning portion of generated pins file",
-        default="cc3200_prefix.c"
+        default="cc3200_prefix.c",
     )
     parser.add_argument(
-        "-q", "--qstr",
+        "-q",
+        "--qstr",
         dest="qstr_filename",
         help="Specifies name of generated qstr header file",
-        default="build/pins_qstr.h"
+        default="build/pins_qstr.h",
     )
     parser.add_argument(
-        "-r", "--hdr",
+        "-r",
+        "--hdr",
         dest="hdr_filename",
         help="Specifies name of generated pin header file",
-        default="build/pins.h"
+        default="build/pins.h",
     )
     args = parser.parse_args(sys.argv[1:])
 
     pins = Pins()
 
-    print('// This file was automatically generated by make-pins.py')
-    print('//')
+    print("// This file was automatically generated by make-pins.py")
+    print("//")
     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)
 
     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)
 
     if args.prefix_filename:
-        print('// --prefix {:s}'.format(args.prefix_filename))
-        print('')
-        with open(args.prefix_filename, 'r') as prefix_file:
+        print("// --prefix {:s}".format(args.prefix_filename))
+        print("")
+        with open(args.prefix_filename, "r") as prefix_file:
             print(prefix_file.read())
     pins.print()
     pins.print_qstr(args.qstr_filename)
diff --git a/ports/cc3200/fatfs_port.c b/ports/cc3200/fatfs_port.c
index 6cfc17c..993684d 100644
--- a/ports/cc3200/fatfs_port.c
+++ b/ports/cc3200/fatfs_port.c
@@ -68,7 +68,7 @@
     timeutils_struct_time_t tm;
     timeutils_seconds_since_2000_to_struct_time(pyb_rtc_get_seconds(), &tm);
 
-    return ((tm.tm_year - 1980) << 25) | ((tm.tm_mon) << 21)  |
-            ((tm.tm_mday) << 16)       | ((tm.tm_hour) << 11) |
-            ((tm.tm_min) << 5)         | (tm.tm_sec >> 1);
+    return ((tm.tm_year - 1980) << 25) | ((tm.tm_mon) << 21) |
+           ((tm.tm_mday) << 16) | ((tm.tm_hour) << 11) |
+           ((tm.tm_min) << 5) | (tm.tm_sec >> 1);
 }
diff --git a/ports/cc3200/main.c b/ports/cc3200/main.c
index e2299e1..803bbee 100644
--- a/ports/cc3200/main.c
+++ b/ports/cc3200/main.c
@@ -58,7 +58,7 @@
  DECLARE PUBLIC DATA
  ******************************************************************************/
 #ifdef DEBUG
-OsiTaskHandle   mpTaskHandle;
+OsiTaskHandle mpTaskHandle;
 #endif
 
 // This is the FreeRTOS heap, defined here so we can put it in a special segment
@@ -78,30 +78,31 @@
     // Initialize the clocks and the interrupt system
     HAL_SystemInit();
 
-#if MICROPY_HW_ANTENNA_DIVERSITY
+    #if MICROPY_HW_ANTENNA_DIVERSITY
     // configure the antenna selection pins
     antenna_init0();
-#endif
+    #endif
 
     // Init the watchdog
     pybwdt_init0();
 
-#ifndef DEBUG
+    #ifndef DEBUG
     OsiTaskHandle mpTaskHandle;
-#endif
+    #endif
     mpTaskHandle = xTaskCreateStatic(TASK_MicroPython, "MicroPy",
         MICROPY_TASK_STACK_LEN, NULL, MICROPY_TASK_PRIORITY, mpTaskStack, &mpTaskTCB);
     ASSERT(mpTaskHandle != NULL);
 
     osi_start();
 
-    for ( ; ; );
+    for ( ; ;) {;
+    }
 }
 
 // We need this when configSUPPORT_STATIC_ALLOCATION is enabled
 void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer,
-                                    StackType_t **ppxIdleTaskStackBuffer,
-                                    uint32_t *pulIdleTaskStackSize ) {
+    StackType_t **ppxIdleTaskStackBuffer,
+    uint32_t *pulIdleTaskStackSize ) {
     *ppxIdleTaskTCBBuffer = &xIdleTaskTCB;
     *ppxIdleTaskStackBuffer = uxIdleTaskStack;
     *pulIdleTaskStackSize = configMINIMAL_STACK_SIZE;
diff --git a/ports/cc3200/mpconfigport.h b/ports/cc3200/mpconfigport.h
index d5c3c07..3bb10bf 100644
--- a/ports/cc3200/mpconfigport.h
+++ b/ports/cc3200/mpconfigport.h
@@ -187,15 +187,15 @@
 
 
 // type definitions for the specific machine
-#define MICROPY_MAKE_POINTER_CALLABLE(p)            ((void*)((mp_uint_t)(p) | 1))
+#define MICROPY_MAKE_POINTER_CALLABLE(p)            ((void *)((mp_uint_t)(p) | 1))
 #define MP_SSIZE_MAX                                (0x7FFFFFFF)
 
 #define UINT_FMT                                    "%u"
 #define INT_FMT                                     "%d"
 
-typedef int32_t         mp_int_t;                   // must be pointer size
-typedef unsigned int    mp_uint_t;                  // must be pointer size
-typedef long            mp_off_t;
+typedef int32_t mp_int_t;                           // must be pointer size
+typedef unsigned int mp_uint_t;                     // must be pointer size
+typedef long mp_off_t;
 
 #define MP_PLAT_PRINT_STRN(str, len) mp_hal_stdout_tx_strn_cooked(str, len)
 
diff --git a/ports/cc3200/mptask.c b/ports/cc3200/mptask.c
index c253804..b0c32c8 100644
--- a/ports/cc3200/mptask.c
+++ b/ports/cc3200/mptask.c
@@ -81,16 +81,16 @@
 /******************************************************************************
  DECLARE PRIVATE FUNCTIONS
  ******************************************************************************/
-STATIC void mptask_pre_init (void);
-STATIC void mptask_init_sflash_filesystem (void);
-STATIC void mptask_enter_ap_mode (void);
-STATIC void mptask_create_main_py (void);
+STATIC void mptask_pre_init(void);
+STATIC void mptask_init_sflash_filesystem(void);
+STATIC void mptask_enter_ap_mode(void);
+STATIC void mptask_create_main_py(void);
 
 /******************************************************************************
  DECLARE PUBLIC DATA
  ******************************************************************************/
 #ifdef DEBUG
-OsiTaskHandle   svTaskHandle;
+OsiTaskHandle svTaskHandle;
 #endif
 
 /******************************************************************************
@@ -100,12 +100,12 @@
 
 static const char fresh_main_py[] = "# main.py -- put your code here!\r\n";
 static const char fresh_boot_py[] = "# boot.py -- run on boot-up\r\n"
-                                    "# can run arbitrary Python, but best to keep it minimal\r\n"
+    "# can run arbitrary Python, but best to keep it minimal\r\n"
                                     #if MICROPY_STDIO_UART
-                                    "import os, machine\r\n"
-                                    "os.dupterm(machine.UART(0, " MP_STRINGIFY(MICROPY_STDIO_UART_BAUD) "))\r\n"
+    "import os, machine\r\n"
+    "os.dupterm(machine.UART(0, " MP_STRINGIFY(MICROPY_STDIO_UART_BAUD) "))\r\n"
                                     #endif
-                                    ;
+;
 
 /******************************************************************************
  DECLARE PUBLIC FUNCTIONS
@@ -118,9 +118,9 @@
     bool safeboot = false;
     mptask_pre_init();
 
-#ifndef DEBUG
+    #ifndef DEBUG
     safeboot = PRCMGetSpecialBit(PRCM_SAFE_BOOT_BIT);
-#endif
+    #endif
 
 soft_reset:
 
@@ -130,7 +130,7 @@
     #endif
 
     // initialise the stack pointer for the main thread (must be done after mp_thread_init)
-    mp_stack_set_top((void*)sp);
+    mp_stack_set_top((void *)sp);
 
     // GC init
     gc_init(&_boot, &_eheap);
@@ -158,8 +158,7 @@
             // when waking up from hibernate we just want
             // to enable simplelink and leave it as is
             wlan_first_start();
-        }
-        else {
+        } else {
             // only if not comming out of hibernate or a soft reset
             mptask_enter_ap_mode();
         }
@@ -218,7 +217,7 @@
 
     // main script is finished, so now go into REPL mode.
     // the REPL mode can change, or it can request a soft reset.
-    for ( ; ; ) {
+    for ( ; ;) {
         if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
             if (pyexec_raw_repl() != 0) {
                 break;
@@ -286,9 +285,9 @@
 
     //CRYPTOHASH_Init();
 
-#ifndef DEBUG
+    #ifndef DEBUG
     OsiTaskHandle svTaskHandle;
-#endif
+    #endif
     svTaskHandle = xTaskCreateStatic(TASK_Servers, "Servers",
         SERVERS_STACK_LEN, NULL, SERVERS_PRIORITY, svTaskStack, &svTaskTCB);
     ASSERT(svTaskHandle != NULL);
@@ -382,8 +381,8 @@
     bool add_mac = !PRCMGetSpecialBit(PRCM_FIRST_BOOT_BIT);
     // enable simplelink in ap mode (use the MAC address to make the ssid unique)
     wlan_sl_init (ROLE_AP, MICROPY_PORT_WLAN_AP_SSID, strlen(MICROPY_PORT_WLAN_AP_SSID),
-                  MICROPY_PORT_WLAN_AP_SECURITY, MICROPY_PORT_WLAN_AP_KEY, strlen(MICROPY_PORT_WLAN_AP_KEY),
-                  MICROPY_PORT_WLAN_AP_CHANNEL, ANTENNA_TYPE_INTERNAL, add_mac);
+        MICROPY_PORT_WLAN_AP_SECURITY, MICROPY_PORT_WLAN_AP_KEY, strlen(MICROPY_PORT_WLAN_AP_KEY),
+        MICROPY_PORT_WLAN_AP_CHANNEL, ANTENNA_TYPE_INTERNAL, add_mac);
 }
 
 STATIC void mptask_create_main_py (void) {
diff --git a/ports/cc3200/mptask.h b/ports/cc3200/mptask.h
index a1c3eb2..2c9d6c4 100644
--- a/ports/cc3200/mptask.h
+++ b/ports/cc3200/mptask.h
@@ -41,6 +41,6 @@
 /******************************************************************************
  DECLARE PUBLIC FUNCTIONS
  ******************************************************************************/
-extern void TASK_MicroPython (void *pvParameters);
+extern void TASK_MicroPython(void *pvParameters);
 
 #endif // MICROPY_INCLUDED_CC3200_MPTASK_H
diff --git a/ports/cc3200/mpthreadport.c b/ports/cc3200/mpthreadport.c
index f2fc76b..27d2386 100644
--- a/ports/cc3200/mpthreadport.c
+++ b/ports/cc3200/mpthreadport.c
@@ -68,7 +68,7 @@
 void mp_thread_gc_others(void) {
     mp_thread_mutex_lock(&thread_mutex, 1);
     for (thread_t *th = thread; th != NULL; th = th->next) {
-        gc_collect_root((void**)&th, 1);
+        gc_collect_root((void **)&th, 1);
         gc_collect_root(&th->arg, 1); // probably not needed
         if (th->id == xTaskGetCurrentTaskHandle()) {
             continue;
@@ -100,7 +100,7 @@
     mp_thread_mutex_unlock(&thread_mutex);
 }
 
-STATIC void *(*ext_thread_entry)(void*) = NULL;
+STATIC void *(*ext_thread_entry)(void *) = NULL;
 
 STATIC void freertos_entry(void *arg) {
     if (ext_thread_entry) {
@@ -111,7 +111,7 @@
     }
 }
 
-void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size) {
+void mp_thread_create(void *(*entry)(void *), void *arg, size_t *stack_size) {
     // store thread entry function into a global variable so we can access it
     ext_thread_entry = entry;
 
@@ -129,7 +129,7 @@
     mp_thread_mutex_lock(&thread_mutex, 1);
 
     // create thread
-    TaskHandle_t id = xTaskCreateStatic(freertos_entry, "Thread", *stack_size / sizeof(void*), arg, 2, stack, tcb);
+    TaskHandle_t id = xTaskCreateStatic(freertos_entry, "Thread", *stack_size / sizeof(void *), arg, 2, stack, tcb);
     if (id == NULL) {
         mp_thread_mutex_unlock(&thread_mutex);
         mp_raise_msg(&mp_type_OSError, "can't create thread");
diff --git a/ports/cc3200/serverstask.c b/ports/cc3200/serverstask.c
index 100b8d3..1c7249e 100644
--- a/ports/cc3200/serverstask.c
+++ b/ports/cc3200/serverstask.c
@@ -88,7 +88,7 @@
     telnet_init();
     ftp_init();
 
-    for ( ;; ) {
+    for ( ;;) {
 
         if (servers_data.do_enable) {
             // enable network services
@@ -97,16 +97,14 @@
             // now set/clear the flags
             servers_data.enabled = true;
             servers_data.do_enable = false;
-        }
-        else if (servers_data.do_disable) {
+        } else if (servers_data.do_disable) {
             // disable network services
             telnet_disable();
             ftp_disable();
             // now clear the flags
             servers_data.do_disable = 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
             servers_data.do_reset = false;
             if (servers_data.enabled) {
@@ -120,8 +118,7 @@
 
         if (cycle) {
             telnet_run();
-        }
-        else {
+        } else {
             ftp_run();
         }
 
diff --git a/ports/cc3200/serverstask.h b/ports/cc3200/serverstask.h
index c4533d7..612899d 100644
--- a/ports/cc3200/serverstask.h
+++ b/ports/cc3200/serverstask.h
@@ -60,16 +60,16 @@
 /******************************************************************************
  DECLARE PUBLIC FUNCTIONS
  ******************************************************************************/
-extern void TASK_Servers (void *pvParameters);
-extern void servers_start (void);
-extern void servers_stop (void);
-extern void servers_reset (void);
-extern void servers_wlan_cycle_power (void);
-extern bool servers_are_enabled (void);
-extern void servers_close_socket (int16_t *sd);
-extern void servers_set_login (char *user, char *pass);
-extern void server_sleep_sockets (void);
-extern void servers_set_timeout (uint32_t timeout);
-extern uint32_t servers_get_timeout (void);
+extern void TASK_Servers(void *pvParameters);
+extern void servers_start(void);
+extern void servers_stop(void);
+extern void servers_reset(void);
+extern void servers_wlan_cycle_power(void);
+extern bool servers_are_enabled(void);
+extern void servers_close_socket(int16_t *sd);
+extern void servers_set_login(char *user, char *pass);
+extern void server_sleep_sockets(void);
+extern void servers_set_timeout(uint32_t timeout);
+extern uint32_t servers_get_timeout(void);
 
 #endif // MICROPY_INCLUDED_CC3200_SERVERSTASK_H
diff --git a/ports/cc3200/tools/smoke.py b/ports/cc3200/tools/smoke.py
index 3ade11c..4ccc700 100644
--- a/ports/cc3200/tools/smoke.py
+++ b/ports/cc3200/tools/smoke.py
@@ -12,55 +12,58 @@
 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)
 
-def test_pin_read (pull):
+
+def test_pin_read(pull):
     # enable the pull resistor on all pins, then read the value
     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
         print(pin())
 
-def test_pin_shorts (pull):
+
+def test_pin_shorts(pull):
     if pull == Pin.PULL_UP:
         pull_inverted = Pin.PULL_DOWN
     else:
         pull_inverted = Pin.PULL_UP
     # enable all pulls of the specified type
     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
     i = 0
     while i < len(pin_map):
-        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 = Pin("GP" + str(pin_map[i]), mode=Pin.IN, pull=pull)
+        Pin("GP" + str(pin_map[i - 1]), mode=Pin.IN, pull=pull_inverted)
         i += 1
         # read the pin value
         print(pin())
 
+
 test_pin_read(Pin.PULL_UP)
 test_pin_read(Pin.PULL_DOWN)
 test_pin_shorts(Pin.PULL_UP)
 test_pin_shorts(Pin.PULL_DOWN)
 
 # create a test directory
-os.mkdir('/flash/test')
-os.chdir('/flash/test')
+os.mkdir("/flash/test")
+os.chdir("/flash/test")
 print(os.getcwd())
 # create a new file
-f = open('test.txt', 'w')
+f = open("test.txt", "w")
 n_w = f.write(test_bytes)
 print(n_w == len(test_bytes))
 f.close()
-f = open('test.txt', 'r')
-r = bytes(f.read(), 'ascii')
+f = open("test.txt", "r")
+r = bytes(f.read(), "ascii")
 # check that we can write and read it correctly
 print(r == test_bytes)
 f.close()
-os.remove('test.txt')
-os.chdir('..')
-os.rmdir('test')
+os.remove("test.txt")
+os.chdir("..")
+os.rmdir("test")
 
 ls = os.listdir()
-print('test' not in ls)
+print("test" not in ls)
 print(ls)
 
 # test the real time clock
@@ -72,5 +75,4 @@
 time.sleep_ms(1000)
 time2 = rtc.now()
 print(time2[5] - time1[5] == 1)
-print(time2[6] - time1[6] < 5000) # microseconds
-
+print(time2[6] - time1[6] < 5000)  # microseconds
diff --git a/ports/cc3200/tools/uniflash.py b/ports/cc3200/tools/uniflash.py
index 21da46a..0ce9d07 100644
--- a/ports/cc3200/tools/uniflash.py
+++ b/ports/cc3200/tools/uniflash.py
@@ -19,7 +19,7 @@
 
 
 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):
@@ -29,7 +29,7 @@
     # Poll process for new output until finished
     while True:
         nextline = process.stdout.readline()
-        if nextline == '' and process.poll() != None:
+        if nextline == "" and process.poll() != None:
             break
         sys.stdout.write(nextline)
         sys.stdout.flush()
@@ -43,25 +43,58 @@
     else:
         raise ProcessException(command, exitCode, output)
 
+
 def main():
-    cmd_parser = argparse.ArgumentParser(description='Flash the WiPy and optionally run a small test on it.')
-    cmd_parser.add_argument('-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')
+    cmd_parser = argparse.ArgumentParser(
+        description="Flash the WiPy and optionally run a small test on it."
+    )
+    cmd_parser.add_argument(
+        "-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()
 
     output = ""
-    com_port = 'com=' + str(args.port)
-    servicepack_path = 'spPath=' + args.servicepack
+    com_port = "com=" + str(args.port)
+    servicepack_path = "spPath=" + args.servicepack
 
     try:
         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:
-            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:
-            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:
         print_exception(e)
         output = ""
@@ -77,5 +110,6 @@
             print("======================================")
             sys.exit(1)
 
+
 if __name__ == "__main__":
     main()
diff --git a/ports/cc3200/tools/update-wipy.py b/ports/cc3200/tools/update-wipy.py
index 2d5fe57..e0e1266 100644
--- a/ports/cc3200/tools/update-wipy.py
+++ b/ports/cc3200/tools/update-wipy.py
@@ -23,12 +23,12 @@
 
 
 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):
     filelist = []
-    ftpobj.retrlines('LIST',filelist.append)
+    ftpobj.retrlines("LIST", filelist.append)
     for f in filelist:
         if f.split()[-1] == directory_name:
             return True
@@ -37,34 +37,34 @@
 
 def transfer_file(args):
     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):
-            print ('Login successful')
+        if "230" in ftp.login(args.user, args.password):
+            print("Login successful")
 
-            if '250' in ftp.cwd('/flash'):
-                if not ftp_directory_exists(ftp, 'sys'):
-                    print ('/flash/sys directory does not exist')
-                    if not '550' in ftp.mkd('sys'):
-                        print ('/flash/sys directory created')
+            if "250" in ftp.cwd("/flash"):
+                if not ftp_directory_exists(ftp, "sys"):
+                    print("/flash/sys directory does not exist")
+                    if not "550" in ftp.mkd("sys"):
+                        print("/flash/sys directory created")
                     else:
-                        print ('Error: cannot create /flash/sys directory')
+                        print("Error: cannot create /flash/sys directory")
                         return False
-                if '250' in ftp.cwd('sys'):
-                    print ("Entered '/flash/sys' directory")
+                if "250" in ftp.cwd("sys"):
+                    print("Entered '/flash/sys' directory")
                     with open(args.file, "rb") as fwfile:
-                        print ('Firmware image found, initiating transfer...')
-                        if '226' in ftp.storbinary("STOR " + 'mcuimg.bin', fwfile, 512):
-                            print ('File transfer complete')
+                        print("Firmware image found, initiating transfer...")
+                        if "226" in ftp.storbinary("STOR " + "mcuimg.bin", fwfile, 512):
+                            print("File transfer complete")
                             return True
                         else:
-                            print ('Error: file transfer failed')
+                            print("Error: file transfer failed")
                 else:
-                    print ('Error: cannot enter /flash/sys directory')
+                    print("Error: cannot enter /flash/sys directory")
             else:
-                print ('Error: cannot enter /flash directory')
+                print("Error: cannot enter /flash directory")
         else:
-            print ('Error: ftp login failed')
+            print("Error: ftp login failed")
 
     return False
 
@@ -76,20 +76,24 @@
         tn = Telnet(args.ip, timeout=5)
         print("Connected via Telnet, trying to login now")
 
-        if b'Login as:' in tn.read_until(b"Login as:", timeout=5):
-            tn.write(bytes(args.user, 'ascii') + b"\r\n")
+        if b"Login as:" in tn.read_until(b"Login as:", timeout=5):
+            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
                 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")
-                    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)
-                    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):
+                    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
+                    ):
                         tn.write(b"import machine\r\n")
                         tn.write(b"machine.reset()\r\n")
                         time.sleep(2)
@@ -112,9 +116,9 @@
 
 def verify_update(args):
     success = False
-    firmware_tag = ''
+    firmware_tag = ""
 
-    def find_tag (tag):
+    def find_tag(tag):
         if tag in firmware_tag:
             print("Verification passed")
             return True
@@ -135,21 +139,26 @@
                 print("Timeout while connecting via telnet, retrying...")
                 retries += 1
             else:
-                print('Error: Telnet connection timed out!')
+                print("Error: Telnet connection timed out!")
                 return False
 
     try:
-        firmware_tag = tn.read_until (b'with CC3200')
-        tag_file_path = args.file.rstrip('mcuimg.bin') + 'genhdr/mpversion.h'
-        
+        firmware_tag = tn.read_until(b"with CC3200")
+        tag_file_path = args.file.rstrip("mcuimg.bin") + "genhdr/mpversion.h"
+
         if args.tag is not None:
-            success = find_tag(bytes(args.tag, 'ascii'))
+            success = find_tag(bytes(args.tag, "ascii"))
         else:
             with open(tag_file_path) as tag_file:
                 for line in tag_file:
-                    bline = bytes(line, 'ascii')
-                    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 = bytes(line, "ascii")
+                    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"")
+                        )
                         success = find_tag(bline)
                         break
 
@@ -164,24 +173,28 @@
 
 
 def main():
-    cmd_parser = argparse.ArgumentParser(description='Update the WiPy firmware with the specified image file')
-    cmd_parser.add_argument('-f', '--file', default=None, help='the path of the firmware 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('--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')
+    cmd_parser = argparse.ArgumentParser(
+        description="Update the WiPy firmware with the specified image file"
+    )
+    cmd_parser.add_argument("-f", "--file", default=None, help="the path of the firmware 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("--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()
 
     result = 1
 
     try:
         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 reset_board(args):
                 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
                     # connect to the WiPy again.
                     time.sleep(5)
diff --git a/ports/cc3200/version.h b/ports/cc3200/version.h
index fccb95c..81a6999 100644
--- a/ports/cc3200/version.h
+++ b/ports/cc3200/version.h
@@ -1,31 +1,31 @@
-/*

- * This file is part of the MicroPython project, http://micropython.org/

- *

- * The MIT License (MIT)

- *

- * Copyright (c) 2015 Daniel Campora

- *

- * Permission is hereby granted, free of charge, to any person obtaining a copy

- * of this software and associated documentation files (the "Software"), to deal

- * in the Software without restriction, including without limitation the rights

- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell

- * copies of the Software, and to permit persons to whom the Software is

- * furnished to do so, subject to the following conditions:

- *

- * The above copyright notice and this permission notice shall be included in

- * all copies or substantial portions of the Software.

- *

- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR

- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER

- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,

- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN

- * THE SOFTWARE.

- */

-#ifndef MICROPY_INCLUDED_CC3200_VERSION_H

-#define MICROPY_INCLUDED_CC3200_VERSION_H

-

-#define WIPY_SW_VERSION_NUMBER                              "1.2.0"

-

-#endif // MICROPY_INCLUDED_CC3200_VERSION_H

+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2015 Daniel Campora
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#ifndef MICROPY_INCLUDED_CC3200_VERSION_H
+#define MICROPY_INCLUDED_CC3200_VERSION_H
+
+#define WIPY_SW_VERSION_NUMBER                              "1.2.0"
+
+#endif // MICROPY_INCLUDED_CC3200_VERSION_H
diff --git a/ports/esp32/boards/TINYPICO/manifest.py b/ports/esp32/boards/TINYPICO/manifest.py
index 81fff1d..7ae2ed1 100644
--- a/ports/esp32/boards/TINYPICO/manifest.py
+++ b/ports/esp32/boards/TINYPICO/manifest.py
@@ -1,2 +1,2 @@
-include('$(PORT_DIR)/boards/manifest.py')
+include("$(PORT_DIR)/boards/manifest.py")
 freeze("modules")
diff --git a/ports/esp32/boards/TINYPICO/modules/dotstar.py b/ports/esp32/boards/TINYPICO/modules/dotstar.py
index a848e8e..c362eb1 100644
--- a/ports/esp32/boards/TINYPICO/modules/dotstar.py
+++ b/ports/esp32/boards/TINYPICO/modules/dotstar.py
@@ -63,8 +63,7 @@
         dotstar[0] = (128, 0, 0) # Red
     """
 
-    def __init__(self, spi, n, *, brightness=1.0, auto_write=True,
-                 pixel_order=BGR):
+    def __init__(self, spi, n, *, brightness=1.0, auto_write=True, pixel_order=BGR):
         self._spi = spi
         self._n = n
         # Supply one extra clock cycle for each two pixels in the strip.
@@ -79,10 +78,10 @@
             self._buf[i] = 0x00
         # Mark the beginnings of each pixel.
         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.
         for i in range(self.end_header_index, len(self._buf)):
-            self._buf[i] = 0xff
+            self._buf[i] = 0xFF
         self._brightness = 1.0
         # Set auto_write to False temporarily so brightness setter does _not_
         # call show() while in __init__.
@@ -129,7 +128,7 @@
         offset = index * 4 + START_HEADER_SIZE
         rgb = value
         if isinstance(value, int):
-            rgb = (value >> 16, (value >> 8) & 0xff, value & 0xff)
+            rgb = (value >> 16, (value >> 8) & 0xFF, value & 0xFF)
 
         if len(rgb) == 4:
             brightness = value[3]
@@ -171,15 +170,15 @@
             out = []
             for in_i in range(*index.indices(self._n)):
                 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
         if index < 0:
             index += len(self)
         if index >= self._n or index < 0:
             raise IndexError
         offset = index * 4
-        return tuple(self._buf[offset + (3 - i) + START_HEADER_SIZE]
-                     for i in range(3))
+        return tuple(self._buf[offset + (3 - i) + START_HEADER_SIZE] for i in range(3))
 
     def __len__(self):
         return self._n
@@ -222,7 +221,7 @@
                 buf[i] = self._buf[i] if i % 4 == 0 else int(self._buf[i] * self._brightness)
             # Four 0xff bytes at the end.
             for i in range(self.end_header_index, len(buf)):
-                buf[i] = 0xff
+                buf[i] = 0xFF
 
         if self._spi:
             self._spi.write(buf)
diff --git a/ports/esp32/boards/TINYPICO/modules/tinypico.py b/ports/esp32/boards/TINYPICO/modules/tinypico.py
index 2fc379c..846e079 100644
--- a/ports/esp32/boards/TINYPICO/modules/tinypico.py
+++ b/ports/esp32/boards/TINYPICO/modules/tinypico.py
@@ -29,11 +29,11 @@
 SPI_CLK = const(18)
 SPI_MISO = const(19)
 
-#I2C
+# I2C
 I2C_SDA = const(21)
 I2C_SCL = const(22)
 
-#DAC
+# DAC
 DAC1 = const(25)
 DAC2 = const(26)
 
@@ -47,12 +47,13 @@
     Returns the current battery voltage. If no battery is connected, returns 3.7V
     This is an approximation only, but useful to detect of the charge state of the battery is getting low.
     """
-    adc = ADC(Pin(BAT_VOLTAGE))             # Assign the ADC pin to read
-    measuredvbat = adc.read()               # Read the value
-    measuredvbat /= 4095                    # divide by 4095 as we are using the default ADC voltage range of 0-1V
-    measuredvbat *= 3.7                     # Multiply by 3.7V, our reference voltage
+    adc = ADC(Pin(BAT_VOLTAGE))  # Assign the ADC pin to read
+    measuredvbat = adc.read()  # Read the value
+    measuredvbat /= 4095  # divide by 4095 as we are using the default ADC voltage range of 0-1V
+    measuredvbat *= 3.7  # Multiply by 3.7V, our reference voltage
     return measuredvbat
 
+
 # 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
 # and a full battery not charging - This is why the charge LED flashes
@@ -61,13 +62,15 @@
     Returns the current battery charging state.
     This can trigger false positives as the charge IC can't tell the difference between a full battery or no battery connected.
     """
-    measuredVal = 0                         # start our reading at 0
-    io = Pin(BAT_CHARGE, Pin.IN)            # Assign the pin to read
+    measuredVal = 0  # start our reading at 0
+    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()
 
-    return measuredVal == 0                 # return True if the value is 0
+    return measuredVal == 0  # return True if the value is 0
 
 
 # Power to the on-board Dotstar is controlled by a PNP transistor, so low is ON and high is OFF
@@ -80,16 +83,21 @@
     """Set the power for the on-board Dostar to allow no current draw when not needed."""
     # Set the power pin to the inverse of state
     if state:
-        Pin(DOTSTAR_PWR, Pin.OUT, None)     # Break the PULL_HOLD on the pin
-        Pin(DOTSTAR_PWR).value(False)       # Set the pin to LOW to enable the Transistor
+        Pin(DOTSTAR_PWR, Pin.OUT, None)  # Break the PULL_HOLD on the pin
+        Pin(DOTSTAR_PWR).value(False)  # Set the pin to LOW to enable the Transistor
     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(DOTSTAR_DATA, Pin.OUT if state else Pin.IN) # If power is on, set DATA to be output, otherwise input
+    Pin(
+        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
-    time.sleep(.035)
+    time.sleep(0.035)
+
 
 # Dotstar rainbow colour wheel
 def dotstar_color_wheel(wheel_pos):
@@ -105,6 +113,7 @@
         wheel_pos -= 170
         return wheel_pos * 3, 255 - wheel_pos * 3, 0
 
+
 # Go into deep sleep but shut down the APA first to save power
 # Use this if you want lowest deep  sleep current
 def go_deepsleep(t):
diff --git a/ports/esp32/boards/manifest.py b/ports/esp32/boards/manifest.py
index bab2b61..bbd907a 100644
--- a/ports/esp32/boards/manifest.py
+++ b/ports/esp32/boards/manifest.py
@@ -1,6 +1,6 @@
-freeze('$(PORT_DIR)/modules')
-freeze('$(MPY_DIR)/tools', ('upip.py', 'upip_utarfile.py'))
-freeze('$(MPY_DIR)/ports/esp8266/modules', 'ntptime.py')
-freeze('$(MPY_DIR)/drivers/dht', 'dht.py')
-freeze('$(MPY_DIR)/drivers/onewire')
-include('$(MPY_DIR)/extmod/webrepl/manifest.py')
+freeze("$(PORT_DIR)/modules")
+freeze("$(MPY_DIR)/tools", ("upip.py", "upip_utarfile.py"))
+freeze("$(MPY_DIR)/ports/esp8266/modules", "ntptime.py")
+freeze("$(MPY_DIR)/drivers/dht", "dht.py")
+freeze("$(MPY_DIR)/drivers/onewire")
+include("$(MPY_DIR)/extmod/webrepl/manifest.py")
diff --git a/ports/esp32/boards/manifest_release.py b/ports/esp32/boards/manifest_release.py
index 9c898af..b5c7cd1 100644
--- a/ports/esp32/boards/manifest_release.py
+++ b/ports/esp32/boards/manifest_release.py
@@ -1,6 +1,6 @@
-include('manifest.py')
+include("manifest.py")
 
-freeze('$(MPY_LIB_DIR)/upysh', 'upysh.py')
-freeze('$(MPY_LIB_DIR)/urequests', 'urequests.py')
-freeze('$(MPY_LIB_DIR)/umqtt.simple', 'umqtt/simple.py')
-freeze('$(MPY_LIB_DIR)/umqtt.robust', 'umqtt/robust.py')
+freeze("$(MPY_LIB_DIR)/upysh", "upysh.py")
+freeze("$(MPY_LIB_DIR)/urequests", "urequests.py")
+freeze("$(MPY_LIB_DIR)/umqtt.simple", "umqtt/simple.py")
+freeze("$(MPY_LIB_DIR)/umqtt.robust", "umqtt/robust.py")
diff --git a/ports/esp32/esp32_partition.c b/ports/esp32/esp32_partition.c
index 50c2173..a1aa8c9 100644
--- a/ports/esp32/esp32_partition.c
+++ b/ports/esp32/esp32_partition.c
@@ -69,7 +69,7 @@
         self->part->type, self->part->subtype,
         self->part->address, self->part->size,
         &self->part->label[0], self->part->encrypted
-    );
+        );
 }
 
 STATIC mp_obj_t esp32_partition_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
@@ -180,17 +180,23 @@
     esp32_partition_obj_t *self = MP_OBJ_TO_PTR(self_in);
     mp_int_t cmd = mp_obj_get_int(cmd_in);
     switch (cmd) {
-        case MP_BLOCKDEV_IOCTL_INIT: return MP_OBJ_NEW_SMALL_INT(0);
-        case MP_BLOCKDEV_IOCTL_DEINIT: return MP_OBJ_NEW_SMALL_INT(0);
-        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_INIT:
+            return MP_OBJ_NEW_SMALL_INT(0);
+        case MP_BLOCKDEV_IOCTL_DEINIT:
+            return MP_OBJ_NEW_SMALL_INT(0);
+        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: {
             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));
             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);
@@ -231,5 +237,5 @@
     .name = MP_QSTR_Partition,
     .print = esp32_partition_print,
     .make_new = esp32_partition_make_new,
-    .locals_dict = (mp_obj_dict_t*)&esp32_partition_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&esp32_partition_locals_dict,
 };
diff --git a/ports/esp32/esp32_rmt.c b/ports/esp32/esp32_rmt.c
index 1356456..534b901 100644
--- a/ports/esp32/esp32_rmt.c
+++ b/ports/esp32/esp32_rmt.c
@@ -53,7 +53,7 @@
     gpio_num_t pin;
     uint8_t clock_div;
     mp_uint_t num_items;
-    rmt_item32_t* items;
+    rmt_item32_t *items;
 } esp32_rmt_obj_t;
 
 // Defined in machine_time.c; simply added the error message
@@ -69,7 +69,7 @@
 
 STATIC mp_obj_t esp32_rmt_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
     static const mp_arg_t allowed_args[] = {
-        { MP_QSTR_id,        MP_ARG_REQUIRED |                  MP_ARG_INT, {.u_int = -1} },
+        { MP_QSTR_id,        MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = -1} },
         { MP_QSTR_pin,       MP_ARG_REQUIRED | MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
         { MP_QSTR_clock_div,                   MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 8} }, // 100ns resolution
     };
@@ -154,7 +154,7 @@
 STATIC mp_obj_t esp32_rmt_wait_done(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
     static const mp_arg_t allowed_args[] = {
         { MP_QSTR_self,    MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = mp_const_none} },
-        { MP_QSTR_timeout, MP_ARG_KW_ONLY  | MP_ARG_INT, {.u_int = 0} },
+        { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
     };
 
     mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
@@ -178,7 +178,7 @@
     static const mp_arg_t allowed_args[] = {
         { MP_QSTR_self,   MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = mp_const_none} },
         { MP_QSTR_pulses, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = mp_const_none} },
-        { MP_QSTR_start,  MP_ARG_KW_ONLY  | MP_ARG_INT, {.u_int = 1} },
+        { MP_QSTR_start,  MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} },
     };
 
     mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
@@ -193,12 +193,12 @@
     }
 
     size_t pulses_length = 0;
-    mp_obj_t* pulses_ptr = NULL;
+    mp_obj_t *pulses_ptr = NULL;
     mp_obj_get_array(pulses, &pulses_length, &pulses_ptr);
 
     mp_uint_t num_items = (pulses_length / 2) + (pulses_length % 2);
     if (num_items > self->num_items) {
-        self->items = (rmt_item32_t*)m_realloc(self->items, num_items * sizeof(rmt_item32_t *));
+        self->items = (rmt_item32_t *)m_realloc(self->items, num_items * sizeof(rmt_item32_t *));
         self->num_items = num_items;
     }
 
@@ -233,5 +233,5 @@
     .name = MP_QSTR_RMT,
     .print = esp32_rmt_print,
     .make_new = esp32_rmt_make_new,
-    .locals_dict = (mp_obj_dict_t*)&esp32_rmt_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&esp32_rmt_locals_dict,
 };
diff --git a/ports/esp32/esp32_ulp.c b/ports/esp32/esp32_ulp.c
index bf11de3..4e9d768 100644
--- a/ports/esp32/esp32_ulp.c
+++ b/ports/esp32/esp32_ulp.c
@@ -51,7 +51,7 @@
     mp_uint_t period_us = mp_obj_get_int(period_us_in);
     int _errno = ulp_set_wakeup_period(period_index, period_us);
     if (_errno != ESP_OK) {
-	    mp_raise_OSError(_errno);
+        mp_raise_OSError(_errno);
     }
     return mp_const_none;
 }
@@ -63,9 +63,9 @@
     mp_buffer_info_t bufinfo;
     mp_get_buffer_raise(program_binary_in, &bufinfo, MP_BUFFER_READ);
 
-    int _errno = ulp_load_binary(load_addr, bufinfo.buf, bufinfo.len/sizeof(uint32_t));
+    int _errno = ulp_load_binary(load_addr, bufinfo.buf, bufinfo.len / sizeof(uint32_t));
     if (_errno != ESP_OK) {
-	    mp_raise_OSError(_errno);
+        mp_raise_OSError(_errno);
     }
     return mp_const_none;
 }
@@ -73,9 +73,9 @@
 
 STATIC mp_obj_t esp32_ulp_run(mp_obj_t self_in, mp_obj_t entry_point_in) {
     mp_uint_t entry_point = mp_obj_get_int(entry_point_in);
-    int _errno = ulp_run(entry_point/sizeof(uint32_t));
+    int _errno = ulp_run(entry_point / sizeof(uint32_t));
     if (_errno != ESP_OK) {
-	    mp_raise_OSError(_errno);
+        mp_raise_OSError(_errno);
     }
     return mp_const_none;
 }
diff --git a/ports/esp32/espneopixel.c b/ports/esp32/espneopixel.c
index 829c8b1..1736e2a 100644
--- a/ports/esp32/espneopixel.c
+++ b/ports/esp32/espneopixel.c
@@ -13,11 +13,11 @@
     uint8_t *p, *end, pix, mask;
     uint32_t t, time0, time1, period, c, startTime, pinMask;
 
-    pinMask   = 1 << pin;
-    p         =  pixels;
-    end       =  p + numBytes;
-    pix       = *p++;
-    mask      = 0x80;
+    pinMask = 1 << pin;
+    p = pixels;
+    end = p + numBytes;
+    pix = *p++;
+    mask = 0x80;
     startTime = 0;
 
     uint32_t fcpu = ets_get_cpu_frequency() * 1000000;
@@ -36,18 +36,28 @@
 
     uint32_t irq_state = mp_hal_quiet_timing_enter();
     for (t = time0;; t = time0) {
-        if (pix & mask) t = time1;                                  // Bit high duration
-        while (((c = mp_hal_ticks_cpu()) - startTime) < period);    // Wait for bit start
+        if (pix & mask) {
+            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
         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
         if (!(mask >>= 1)) {                                        // Next bit/byte
-            if(p >= end) break;
-            pix  = *p++;
+            if (p >= end) {
+                break;
+            }
+            pix = *p++;
             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);
 }
diff --git a/ports/esp32/fatfs_port.c b/ports/esp32/fatfs_port.c
index 880324e..779ba1c 100644
--- a/ports/esp32/fatfs_port.c
+++ b/ports/esp32/fatfs_port.c
@@ -36,6 +36,6 @@
     timeutils_struct_time_t 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) |
-           ((DWORD)tm.tm_hour << 11) | ((DWORD)tm.tm_min << 5) | ((DWORD)tm.tm_sec >> 1));
+    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);
 }
diff --git a/ports/esp32/gccollect.c b/ports/esp32/gccollect.c
index 9843cef..7d5da57 100644
--- a/ports/esp32/gccollect.c
+++ b/ports/esp32/gccollect.c
@@ -49,7 +49,7 @@
     if (level == XCHAL_NUM_AREGS / 8) {
         // get the sp
         volatile uint32_t sp = (uint32_t)get_sp();
-        gc_collect_root((void**)sp, ((mp_uint_t)MP_STATE_THREAD(stack_top) - sp) / sizeof(uint32_t));
+        gc_collect_root((void **)sp, ((mp_uint_t)MP_STATE_THREAD(stack_top) - sp) / sizeof(uint32_t));
         return;
     }
 
diff --git a/ports/esp32/help.c b/ports/esp32/help.c
index 95d115c..2336d97 100644
--- a/ports/esp32/help.c
+++ b/ports/esp32/help.c
@@ -29,37 +29,37 @@
 #include "py/builtin.h"
 
 const char esp32_help_text[] =
-"Welcome to MicroPython on the ESP32!\n"
-"\n"
-"For generic online docs please visit http://docs.micropython.org/\n"
-"\n"
-"For access to the hardware use the 'machine' module:\n"
-"\n"
-"import machine\n"
-"pin12 = machine.Pin(12, machine.Pin.OUT)\n"
-"pin12.value(1)\n"
-"pin13 = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP)\n"
-"print(pin13.value())\n"
-"i2c = machine.I2C(scl=machine.Pin(21), sda=machine.Pin(22))\n"
-"i2c.scan()\n"
-"i2c.writeto(addr, b'1234')\n"
-"i2c.readfrom(addr, 4)\n"
-"\n"
-"Basic WiFi configuration:\n"
-"\n"
-"import network\n"
-"sta_if = network.WLAN(network.STA_IF); sta_if.active(True)\n"
-"sta_if.scan()                             # Scan for available access points\n"
-"sta_if.connect(\"<AP_name>\", \"<password>\") # Connect to an AP\n"
-"sta_if.isconnected()                      # Check for successful connection\n"
-"\n"
-"Control commands:\n"
-"  CTRL-A        -- on a blank line, enter raw REPL mode\n"
-"  CTRL-B        -- on a blank line, enter normal REPL mode\n"
-"  CTRL-C        -- interrupt a running program\n"
-"  CTRL-D        -- on a blank line, do a soft reset of the board\n"
-"  CTRL-E        -- on a blank line, enter paste mode\n"
-"\n"
-"For further help on a specific object, type help(obj)\n"
-"For a list of available modules, type help('modules')\n"
+    "Welcome to MicroPython on the ESP32!\n"
+    "\n"
+    "For generic online docs please visit http://docs.micropython.org/\n"
+    "\n"
+    "For access to the hardware use the 'machine' module:\n"
+    "\n"
+    "import machine\n"
+    "pin12 = machine.Pin(12, machine.Pin.OUT)\n"
+    "pin12.value(1)\n"
+    "pin13 = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP)\n"
+    "print(pin13.value())\n"
+    "i2c = machine.I2C(scl=machine.Pin(21), sda=machine.Pin(22))\n"
+    "i2c.scan()\n"
+    "i2c.writeto(addr, b'1234')\n"
+    "i2c.readfrom(addr, 4)\n"
+    "\n"
+    "Basic WiFi configuration:\n"
+    "\n"
+    "import network\n"
+    "sta_if = network.WLAN(network.STA_IF); sta_if.active(True)\n"
+    "sta_if.scan()                             # Scan for available access points\n"
+    "sta_if.connect(\"<AP_name>\", \"<password>\") # Connect to an AP\n"
+    "sta_if.isconnected()                      # Check for successful connection\n"
+    "\n"
+    "Control commands:\n"
+    "  CTRL-A        -- on a blank line, enter raw REPL mode\n"
+    "  CTRL-B        -- on a blank line, enter normal REPL mode\n"
+    "  CTRL-C        -- interrupt a running program\n"
+    "  CTRL-D        -- on a blank line, do a soft reset of the board\n"
+    "  CTRL-E        -- on a blank line, enter paste mode\n"
+    "\n"
+    "For further help on a specific object, type help(obj)\n"
+    "For a list of available modules, type help('modules')\n"
 ;
diff --git a/ports/esp32/machine_adc.c b/ports/esp32/machine_adc.c
index 63e4044..db70b78 100644
--- a/ports/esp32/machine_adc.c
+++ b/ports/esp32/machine_adc.c
@@ -56,7 +56,7 @@
 STATIC uint8_t adc_bit_width;
 
 STATIC mp_obj_t madc_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw,
-        const mp_obj_t *args) {
+    const mp_obj_t *args) {
 
     static int initialized = 0;
     if (!initialized) {
@@ -69,11 +69,18 @@
     gpio_num_t pin_id = machine_pin_get_id(args[0]);
     const madc_obj_t *self = NULL;
     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);
-    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");
 }
 
@@ -96,7 +103,9 @@
 STATIC mp_obj_t madc_read(mp_obj_t self_in) {
     madc_obj_t *self = self_in;
     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);
 }
 MP_DEFINE_CONST_FUN_OBJ_1(madc_read_obj, madc_read);
@@ -105,7 +114,9 @@
     madc_obj_t *self = self_in;
     adc_atten_t atten = mp_obj_get_int(atten_in);
     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_DEFINE_CONST_FUN_OBJ_2(madc_atten_obj, madc_atten);
@@ -117,11 +128,20 @@
         mp_raise_ValueError("Parameter Error");
     }
     switch (width) {
-        case ADC_WIDTH_9Bit: adc_bit_width = 9; break;
-        case ADC_WIDTH_10Bit: 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;
+        case ADC_WIDTH_9Bit:
+            adc_bit_width = 9;
+            break;
+        case ADC_WIDTH_10Bit:
+            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;
 }
diff --git a/ports/esp32/machine_dac.c b/ports/esp32/machine_dac.c
index bd0804e..bb441c7 100644
--- a/ports/esp32/machine_dac.c
+++ b/ports/esp32/machine_dac.c
@@ -48,21 +48,28 @@
 };
 
 STATIC mp_obj_t mdac_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw,
-        const mp_obj_t *args) {
+    const mp_obj_t *args) {
 
     mp_arg_check_num(n_args, n_kw, 1, 1, true);
     gpio_num_t pin_id = machine_pin_get_id(args[0]);
     const mdac_obj_t *self = NULL;
     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);
     if (err == ESP_OK) {
         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");
 }
 
@@ -74,10 +81,14 @@
 STATIC mp_obj_t mdac_write(mp_obj_t self_in, mp_obj_t value_in) {
     mdac_obj_t *self = self_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);
-    if (err == ESP_OK) return mp_const_none;
+    if (err == ESP_OK) {
+        return mp_const_none;
+    }
     mp_raise_ValueError("Parameter Error");
 }
 MP_DEFINE_CONST_FUN_OBJ_2(mdac_write_obj, mdac_write);
diff --git a/ports/esp32/machine_hw_spi.c b/ports/esp32/machine_hw_spi.c
index af47711..163ca7b 100644
--- a/ports/esp32/machine_hw_spi.c
+++ b/ports/esp32/machine_hw_spi.c
@@ -94,16 +94,16 @@
 }
 
 STATIC void machine_hw_spi_init_internal(
-    machine_hw_spi_obj_t    *self,
-    int8_t                  host,
-    int32_t                 baudrate,
-    int8_t                  polarity,
-    int8_t                  phase,
-    int8_t                  bits,
-    int8_t                  firstbit,
-    int8_t                  sck,
-    int8_t                  mosi,
-    int8_t                  miso) {
+    machine_hw_spi_obj_t *self,
+    int8_t host,
+    int32_t baudrate,
+    int8_t polarity,
+    int8_t phase,
+    int8_t bits,
+    int8_t firstbit,
+    int8_t sck,
+    int8_t mosi,
+    int8_t miso) {
 
     // if we're not initialized, then we're
     // implicitly 'changed', since this is the init routine
@@ -129,7 +129,7 @@
     }
 
     if (phase != -1 && phase != self->phase) {
-        self->phase =  phase;
+        self->phase = phase;
         changed = true;
     }
 
@@ -295,9 +295,9 @@
 STATIC void machine_hw_spi_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
     machine_hw_spi_obj_t *self = MP_OBJ_TO_PTR(self_in);
     mp_printf(print, "SPI(id=%u, baudrate=%u, polarity=%u, phase=%u, bits=%u, firstbit=%u, sck=%d, mosi=%d, miso=%d)",
-              self->host, self->baudrate, self->polarity,
-              self->phase, self->bits, self->firstbit,
-              self->sck, self->mosi, self->miso);
+        self->host, self->baudrate, self->polarity,
+        self->phase, self->bits, self->firstbit,
+        self->sck, self->mosi, self->miso);
 }
 
 STATIC void machine_hw_spi_init(mp_obj_base_t *self_in, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
@@ -318,7 +318,7 @@
 
     mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
     mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args),
-                     allowed_args, args);
+        allowed_args, args);
     int8_t sck, mosi, miso;
 
     if (args[ARG_sck].u_obj == MP_OBJ_NULL) {
@@ -346,8 +346,8 @@
     }
 
     machine_hw_spi_init_internal(self, args[ARG_id].u_int, args[ARG_baudrate].u_int,
-                                 args[ARG_polarity].u_int, args[ARG_phase].u_int, args[ARG_bits].u_int,
-                                 args[ARG_firstbit].u_int, sck, mosi, miso);
+        args[ARG_polarity].u_int, args[ARG_phase].u_int, args[ARG_bits].u_int,
+        args[ARG_firstbit].u_int, sck, mosi, miso);
 }
 
 mp_obj_t machine_hw_spi_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
diff --git a/ports/esp32/machine_i2c.c b/ports/esp32/machine_i2c.c
index 61a6807..67dae9c 100644
--- a/ports/esp32/machine_i2c.c
+++ b/ports/esp32/machine_i2c.c
@@ -134,7 +134,7 @@
     }
 
     // Get static peripheral object
-    machine_hw_i2c_obj_t *self = (machine_hw_i2c_obj_t*)&machine_hw_i2c_obj[i2c_id];
+    machine_hw_i2c_obj_t *self = (machine_hw_i2c_obj_t *)&machine_hw_i2c_obj[i2c_id];
 
     bool first_init = false;
     if (self->base.type == NULL) {
@@ -175,5 +175,5 @@
     .print = machine_hw_i2c_print,
     .make_new = machine_hw_i2c_make_new,
     .protocol = &machine_hw_i2c_p,
-    .locals_dict = (mp_obj_dict_t*)&mp_machine_soft_i2c_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&mp_machine_soft_i2c_locals_dict,
 };
diff --git a/ports/esp32/machine_pin.c b/ports/esp32/machine_pin.c
index cca7c0e..db853d0 100644
--- a/ports/esp32/machine_pin.c
+++ b/ports/esp32/machine_pin.c
@@ -202,7 +202,7 @@
     int wanted_pin = mp_obj_get_int(args[0]);
     const machine_pin_obj_t *self = NULL;
     if (0 <= wanted_pin && wanted_pin < MP_ARRAY_SIZE(machine_pin_obj)) {
-        self = (machine_pin_obj_t*)&machine_pin_obj[wanted_pin];
+        self = (machine_pin_obj_t *)&machine_pin_obj[wanted_pin];
     }
     if (self == NULL || self->base.type == NULL) {
         mp_raise_ValueError("invalid pin");
@@ -316,7 +316,7 @@
             gpio_isr_handler_remove(self->id);
             MP_STATE_PORT(machine_pin_irq_handler)[self->id] = handler;
             gpio_set_intr_type(self->id, trigger);
-            gpio_isr_handler_add(self->id, machine_pin_isr_handler, (void*)self);
+            gpio_isr_handler_add(self->id, machine_pin_isr_handler, (void *)self);
         }
     }
 
@@ -365,7 +365,7 @@
 STATIC MP_DEFINE_CONST_DICT(machine_pin_locals_dict, machine_pin_locals_dict_table);
 
 STATIC const mp_pin_p_t pin_pin_p = {
-  .ioctl = pin_ioctl,
+    .ioctl = pin_ioctl,
 };
 
 const mp_obj_type_t machine_pin_type = {
@@ -429,7 +429,7 @@
 STATIC mp_obj_t machine_pin_irq_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
     machine_pin_irq_obj_t *self = self_in;
     mp_arg_check_num(n_args, n_kw, 0, 0, false);
-    machine_pin_isr_handler((void*)&machine_pin_obj[self->id]);
+    machine_pin_isr_handler((void *)&machine_pin_obj[self->id]);
     return mp_const_none;
 }
 
@@ -454,5 +454,5 @@
     { &mp_type_type },
     .name = MP_QSTR_IRQ,
     .call = machine_pin_irq_call,
-    .locals_dict = (mp_obj_dict_t*)&machine_pin_irq_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&machine_pin_irq_locals_dict,
 };
diff --git a/ports/esp32/machine_pwm.c b/ports/esp32/machine_pwm.c
index 6c66a66..c98b26c 100644
--- a/ports/esp32/machine_pwm.c
+++ b/ports/esp32/machine_pwm.c
@@ -120,7 +120,7 @@
 }
 
 STATIC void esp32_pwm_init_helper(esp32_pwm_obj_t *self,
-        size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
+    size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
     enum { ARG_freq, ARG_duty };
     static const mp_arg_t allowed_args[] = {
         { MP_QSTR_freq, MP_ARG_INT, {.u_int = -1} },
@@ -181,7 +181,7 @@
     // Set duty cycle?
     int dval = args[ARG_duty].u_int;
     if (dval != -1) {
-        dval &= ((1 << PWRES)-1);
+        dval &= ((1 << PWRES) - 1);
         dval >>= PWRES - timer_cfg.duty_resolution;
         ledc_set_duty(PWMODE, channel, dval);
         ledc_update_duty(PWMODE, channel);
@@ -189,7 +189,7 @@
 }
 
 STATIC mp_obj_t esp32_pwm_make_new(const mp_obj_type_t *type,
-        size_t n_args, size_t n_kw, const mp_obj_t *args) {
+    size_t n_args, size_t n_kw, const mp_obj_t *args) {
     mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
     gpio_num_t pin_id = machine_pin_get_id(args[0]);
 
@@ -215,7 +215,7 @@
 }
 
 STATIC mp_obj_t esp32_pwm_init(size_t n_args,
-        const mp_obj_t *args, mp_map_t *kw_args) {
+    const mp_obj_t *args, mp_map_t *kw_args) {
     esp32_pwm_init_helper(args[0], n_args - 1, args + 1, kw_args);
     return mp_const_none;
 }
@@ -267,7 +267,7 @@
 
     // set
     duty = mp_obj_get_int(args[1]);
-    duty &= ((1 << PWRES)-1);
+    duty &= ((1 << PWRES) - 1);
     duty >>= PWRES - timer_cfg.duty_resolution;
     ledc_set_duty(PWMODE, self->channel, duty);
     ledc_update_duty(PWMODE, self->channel);
@@ -292,5 +292,5 @@
     .name = MP_QSTR_PWM,
     .print = esp32_pwm_print,
     .make_new = esp32_pwm_make_new,
-    .locals_dict = (mp_obj_dict_t*)&esp32_pwm_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&esp32_pwm_locals_dict,
 };
diff --git a/ports/esp32/machine_rtc.c b/ports/esp32/machine_rtc.c
index eaa70e2..4498792 100644
--- a/ports/esp32/machine_rtc.c
+++ b/ports/esp32/machine_rtc.c
@@ -74,7 +74,7 @@
 machine_rtc_config_t machine_rtc_config = {
     .ext1_pins = 0,
     .ext0_pin = -1
-    };
+};
 
 STATIC mp_obj_t machine_rtc_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
     // check arguments
@@ -146,7 +146,7 @@
     if (n_args == 1) {
         // read RTC memory
         uint8_t rtcram[MICROPY_HW_RTC_USER_MEM_MAX];
-        memcpy((char*)rtcram, (char*)rtc_user_mem_data, rtc_user_mem_len);
+        memcpy((char *)rtcram, (char *)rtc_user_mem_data, rtc_user_mem_len);
         return mp_obj_new_bytes(rtcram, rtc_user_mem_len);
     } else {
         // write RTC memory
diff --git a/ports/esp32/machine_rtc.h b/ports/esp32/machine_rtc.h
index e34deb9..6e70f74 100644
--- a/ports/esp32/machine_rtc.h
+++ b/ports/esp32/machine_rtc.h
@@ -4,7 +4,7 @@
  * The MIT License (MIT)
  *
  * Copyright (c) 2017 "Eric Poulsen" <eric@zyxod.com>
- * Copyright (c) 2017 "Tom Manning" <tom@manningetal.com> 
+ * Copyright (c) 2017 "Tom Manning" <tom@manningetal.com>
  *
  * Permission is hereby granted, free of charge, to any person obtaining a copy
  * of this software and associated documentation files (the "Software"), to deal
diff --git a/ports/esp32/machine_sdcard.c b/ports/esp32/machine_sdcard.c
index 8639e41..a11d0d6 100644
--- a/ports/esp32/machine_sdcard.c
+++ b/ports/esp32/machine_sdcard.c
@@ -72,18 +72,18 @@
 #define _SECTOR_SIZE(self) (self->card.csd.sector_size)
 
 STATIC esp_err_t check_esp_err(esp_err_t code) {
-    switch(code) {
-    case ESP_OK:
-        return ESP_OK;
-    case ESP_ERR_NO_MEM:
-        code = MP_ENOMEM;
-        break;
-    case ESP_ERR_TIMEOUT:
-        code = MP_ETIMEDOUT;
-        break;
-    case ESP_ERR_NOT_SUPPORTED:
-        code = MP_EOPNOTSUPP;
-        break;
+    switch (code) {
+        case ESP_OK:
+            return ESP_OK;
+        case ESP_ERR_NO_MEM:
+            code = MP_ENOMEM;
+            break;
+        case ESP_ERR_TIMEOUT:
+            code = MP_ETIMEDOUT;
+            break;
+        case ESP_ERR_NOT_SUPPORTED:
+            code = MP_EOPNOTSUPP;
+            break;
     }
 
     mp_raise_OSError(code);
@@ -100,7 +100,7 @@
 
 #define SET_CONFIG_PIN(config, pin_var, arg_id) \
     if (arg_vals[arg_id].u_obj != mp_const_none) \
-        config.pin_var = pin_or_int(arg_vals[arg_id].u_obj)
+    config.pin_var = pin_or_int(arg_vals[arg_id].u_obj)
 
 STATIC esp_err_t sdcard_ensure_card_init(sdcard_card_obj_t *self, bool force) {
     if (force || !(self->flags & SDCARD_CARD_FLAGS_CARD_INIT_DONE)) {
@@ -165,15 +165,15 @@
     mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
 
     mp_arg_parse_all(n_args, args, &kw_args,
-                     MP_ARRAY_SIZE(allowed_args), allowed_args, arg_vals);
+        MP_ARRAY_SIZE(allowed_args), allowed_args, arg_vals);
 
     DEBUG_printf("  slot=%d, width=%d, cd=%p, wp=%p",
-                 arg_vals[ARG_slot].u_int, arg_vals[ARG_width].u_int,
-                 arg_vals[ARG_cd].u_obj, arg_vals[ARG_wp].u_obj);
+        arg_vals[ARG_slot].u_int, arg_vals[ARG_width].u_int,
+        arg_vals[ARG_cd].u_obj, arg_vals[ARG_wp].u_obj);
 
     DEBUG_printf("  miso=%p, mosi=%p, sck=%p, cs=%p",
-                 arg_vals[ARG_miso].u_obj, arg_vals[ARG_mosi].u_obj,
-                 arg_vals[ARG_sck].u_obj, arg_vals[ARG_cs].u_obj);
+        arg_vals[ARG_miso].u_obj, arg_vals[ARG_mosi].u_obj,
+        arg_vals[ARG_sck].u_obj, arg_vals[ARG_cs].u_obj);
 
     int slot_num = arg_vals[ARG_slot].u_int;
     if (slot_num < 0 || slot_num > 3) {
@@ -216,13 +216,14 @@
             {
                 .gpio_miso = GPIO_NUM_19,
                 .gpio_mosi = GPIO_NUM_23,
-                .gpio_sck  = GPIO_NUM_18,
-                .gpio_cs   = GPIO_NUM_5,
-                .gpio_cd   = SDSPI_SLOT_NO_CD,
-                .gpio_wp   = SDSPI_SLOT_NO_WP,
+                .gpio_sck = GPIO_NUM_18,
+                .gpio_cs = GPIO_NUM_5,
+                .gpio_cd = SDSPI_SLOT_NO_CD,
+                .gpio_wp = SDSPI_SLOT_NO_WP,
                 .dma_channel = 2
             },
-            SDSPI_SLOT_CONFIG_DEFAULT() };
+            SDSPI_SLOT_CONFIG_DEFAULT()
+        };
 
         DEBUG_printf("  Setting up SPI slot configuration");
         sdspi_slot_config_t slot_config = slot_defaults[slot_num];
@@ -352,14 +353,16 @@
 
         case MP_BLOCKDEV_IOCTL_BLOCK_COUNT:
             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(self->card.csd.capacity);
 
         case MP_BLOCKDEV_IOCTL_BLOCK_SIZE:
             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(_SECTOR_SIZE(self));
 
         default: // unknown command
@@ -384,7 +387,7 @@
     { &mp_type_type },
     .name = MP_QSTR_SDCard,
     .make_new = machine_sdcard_make_new,
-    .locals_dict = (mp_obj_dict_t*)&machine_sdcard_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&machine_sdcard_locals_dict,
 };
 
 #endif // MICROPY_HW_ENABLE_SDCARD
diff --git a/ports/esp32/machine_timer.c b/ports/esp32/machine_timer.c
index c941d94..a4662c3 100644
--- a/ports/esp32/machine_timer.c
+++ b/ports/esp32/machine_timer.c
@@ -107,7 +107,7 @@
             return t;
         }
     }
-    
+
     machine_timer_obj_t *self = m_new_obj(machine_timer_obj_t);
     self->base.type = &machine_timer_type;
     self->group = group;
@@ -160,7 +160,7 @@
     check_esp_err(timer_set_counter_value(self->group, self->index, 0x00000000));
     check_esp_err(timer_set_alarm_value(self->group, self->index, self->period));
     check_esp_err(timer_enable_intr(self->group, self->index));
-    check_esp_err(timer_isr_register(self->group, self->index, machine_timer_isr, (void*)self, TIMER_FLAGS, &self->handle));
+    check_esp_err(timer_isr_register(self->group, self->index, machine_timer_isr, (void *)self, TIMER_FLAGS, &self->handle));
     check_esp_err(timer_start(self->group, self->index));
 }
 
@@ -177,11 +177,11 @@
         { MP_QSTR_callback,     MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
         { MP_QSTR_period,       MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
         { MP_QSTR_tick_hz,      MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1000} },
-#if MICROPY_PY_BUILTINS_FLOAT
+        #if MICROPY_PY_BUILTINS_FLOAT
         { MP_QSTR_freq,         MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
-#else
+        #else
         { MP_QSTR_freq,         MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
-#endif
+        #endif
     };
 
     machine_timer_disable(self);
@@ -189,15 +189,15 @@
     mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
     mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
 
-#if MICROPY_PY_BUILTINS_FLOAT
+    #if MICROPY_PY_BUILTINS_FLOAT
     if (args[ARG_freq].u_obj != mp_const_none) {
         self->period = (uint64_t)(TIMER_SCALE / mp_obj_get_float(args[ARG_freq].u_obj));
     }
-#else
+    #else
     if (args[ARG_freq].u_int != 0xffffffff) {
         self->period = TIMER_SCALE / ((uint64_t)args[ARG_freq].u_int);
     }
-#endif
+    #endif
     else {
         self->period = (((uint64_t)args[ARG_period].u_int) * TIMER_SCALE) / args[ARG_tick_hz].u_int;
     }
diff --git a/ports/esp32/machine_touchpad.c b/ports/esp32/machine_touchpad.c
index dd36bdd..63c06d2 100644
--- a/ports/esp32/machine_touchpad.c
+++ b/ports/esp32/machine_touchpad.c
@@ -56,15 +56,20 @@
 };
 
 STATIC mp_obj_t mtp_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw,
-        const mp_obj_t *args) {
+    const mp_obj_t *args) {
 
     mp_arg_check_num(n_args, n_kw, 1, 1, true);
     gpio_num_t pin_id = machine_pin_get_id(args[0]);
     const mtp_obj_t *self = NULL;
     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;
     if (!initialized) {
@@ -73,7 +78,9 @@
         initialized = 1;
     }
     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");
 }
 
@@ -81,7 +88,9 @@
     mtp_obj_t *self = self_in;
     uint16_t value = mp_obj_get_int(value_in);
     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_DEFINE_CONST_FUN_OBJ_2(mtp_config_obj, mtp_config);
@@ -90,7 +99,9 @@
     mtp_obj_t *self = self_in;
     uint16_t 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_DEFINE_CONST_FUN_OBJ_1(mtp_read_obj, mtp_read);
diff --git a/ports/esp32/machine_uart.c b/ports/esp32/machine_uart.c
index c62cd9c..15d4068 100644
--- a/ports/esp32/machine_uart.c
+++ b/ports/esp32/machine_uart.c
@@ -260,7 +260,7 @@
         mp_raise_msg_varg(&mp_type_ValueError, "UART(%d) is disabled (dedicated to REPL)", uart_num);
     }
 
-     // Defaults
+    // Defaults
     uart_config_t uartcfg = {
         .baud_rate = 115200,
         .data_bits = UART_DATA_8_BITS,
@@ -463,5 +463,5 @@
     .getiter = mp_identity_getiter,
     .iternext = mp_stream_unbuffered_iter,
     .protocol = &uart_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&machine_uart_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&machine_uart_locals_dict,
 };
diff --git a/ports/esp32/main.c b/ports/esp32/main.c
index d8705ee..8c416d0 100644
--- a/ports/esp32/main.c
+++ b/ports/esp32/main.c
@@ -79,7 +79,7 @@
     #if CONFIG_ESP32_SPIRAM_SUPPORT || CONFIG_SPIRAM_SUPPORT
     // Try to use the entire external SPIRAM directly for the heap
     size_t mp_task_heap_size;
-    void *mp_task_heap = (void*)0x3f800000;
+    void *mp_task_heap = (void *)0x3f800000;
     switch (esp_spiram_get_chip_size()) {
         case ESP_SPIRAM_SIZE_16MBITS:
             mp_task_heap_size = 2 * 1024 * 1024;
diff --git a/ports/esp32/makeimg.py b/ports/esp32/makeimg.py
index aeedbff..9f27ed6 100644
--- a/ports/esp32/makeimg.py
+++ b/ports/esp32/makeimg.py
@@ -5,21 +5,21 @@
 OFFSET_APPLICATION = 0x10000
 
 files_in = [
-    ('bootloader', OFFSET_BOOTLOADER, sys.argv[1]),
-    ('partitions', OFFSET_PARTITIONS, sys.argv[2]),
-    ('application', OFFSET_APPLICATION, sys.argv[3]),
+    ("bootloader", OFFSET_BOOTLOADER, sys.argv[1]),
+    ("partitions", OFFSET_PARTITIONS, sys.argv[2]),
+    ("application", OFFSET_APPLICATION, sys.argv[3]),
 ]
 file_out = sys.argv[4]
 
 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:
         assert offset >= cur_offset
-        fout.write(b'\xff' * (offset - cur_offset))
+        fout.write(b"\xff" * (offset - cur_offset))
         cur_offset = offset
-        with open(file_in, 'rb') as fin:
+        with open(file_in, "rb") as fin:
             data = fin.read()
             fout.write(data)
             cur_offset += len(data)
-            print('%-12s% 8d' % (name, len(data))) 
-    print('%-12s% 8d' % ('total', cur_offset))
+            print("%-12s% 8d" % (name, len(data)))
+    print("%-12s% 8d" % ("total", cur_offset))
diff --git a/ports/esp32/modesp.c b/ports/esp32/modesp.c
index 9584b78..369649c 100644
--- a/ports/esp32/modesp.c
+++ b/ports/esp32/modesp.c
@@ -119,7 +119,7 @@
     mp_buffer_info_t bufinfo;
     mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_READ);
     esp_neopixel_write(mp_hal_get_pin_obj(pin),
-        (uint8_t*)bufinfo.buf, bufinfo.len, mp_obj_get_int(timing));
+        (uint8_t *)bufinfo.buf, bufinfo.len, mp_obj_get_int(timing));
     return mp_const_none;
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp_neopixel_write_obj, esp_neopixel_write_);
@@ -154,6 +154,6 @@
 
 const mp_obj_module_t esp_module = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&esp_module_globals,
+    .globals = (mp_obj_dict_t *)&esp_module_globals,
 };
 
diff --git a/ports/esp32/modesp32.c b/ports/esp32/modesp32.c
index 9597e0c..e6d9f80 100644
--- a/ports/esp32/modesp32.c
+++ b/ports/esp32/modesp32.c
@@ -166,5 +166,5 @@
 
 const mp_obj_module_t esp32_module = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&esp32_module_globals,
+    .globals = (mp_obj_dict_t *)&esp32_module_globals,
 };
diff --git a/ports/esp32/modesp32.h b/ports/esp32/modesp32.h
index f04bdba..f4c0491 100644
--- a/ports/esp32/modesp32.h
+++ b/ports/esp32/modesp32.h
@@ -2,10 +2,10 @@
 #define MICROPY_INCLUDED_ESP32_MODESP32_H
 
 #define RTC_VALID_EXT_PINS \
-( \
-    (1ll << 0)  | \
-    (1ll << 2)  | \
-    (1ll << 4)  | \
+    ( \
+    (1ll << 0) | \
+    (1ll << 2) | \
+    (1ll << 4) | \
     (1ll << 12) | \
     (1ll << 13) | \
     (1ll << 14) | \
@@ -21,7 +21,7 @@
     (1ll << 37) | \
     (1ll << 38) | \
     (1ll << 39)   \
-)
+    )
 
 #define RTC_LAST_EXT_PIN 39
 #define RTC_IS_VALID_EXT_PIN(pin_id) ((1ll << (pin_id)) & RTC_VALID_EXT_PINS)
diff --git a/ports/esp32/modmachine.c b/ports/esp32/modmachine.c
index 234809f..f2af502 100644
--- a/ports/esp32/modmachine.c
+++ b/ports/esp32/modmachine.c
@@ -124,7 +124,7 @@
         }
     }
 
-    switch(wake_type) {
+    switch (wake_type) {
         case MACHINE_WAKE_SLEEP:
             esp_light_sleep_start();
             break;
@@ -146,7 +146,7 @@
 STATIC MP_DEFINE_CONST_FUN_OBJ_KW(machine_deepsleep_obj, 0,  machine_deepsleep);
 
 STATIC mp_obj_t machine_reset_cause(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
-    switch(rtc_get_reset_reason(0)) {
+    switch (rtc_get_reset_reason(0)) {
         case POWERON_RESET:
             return MP_OBJ_NEW_SMALL_INT(MP_PWRON_RESET);
             break;
@@ -289,7 +289,7 @@
 
 const mp_obj_module_t mp_module_machine = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&machine_module_globals,
+    .globals = (mp_obj_dict_t *)&machine_module_globals,
 };
 
 #endif // MICROPY_PY_MACHINE
diff --git a/ports/esp32/modnetwork.c b/ports/esp32/modnetwork.c
index 29d1ea3..c573b40 100644
--- a/ports/esp32/modnetwork.c
+++ b/ports/esp32/modnetwork.c
@@ -58,52 +58,54 @@
 #define MODNETWORK_INCLUDE_CONSTANTS (1)
 
 NORETURN void _esp_exceptions(esp_err_t e) {
-   switch (e) {
-      case ESP_ERR_WIFI_NOT_INIT:
-        mp_raise_msg(&mp_type_OSError, "Wifi Not Initialized");
-      case ESP_ERR_WIFI_NOT_STARTED:
-        mp_raise_msg(&mp_type_OSError, "Wifi Not Started");
-      case ESP_ERR_WIFI_NOT_STOPPED:
-        mp_raise_msg(&mp_type_OSError, "Wifi Not Stopped");
-      case ESP_ERR_WIFI_IF:
-        mp_raise_msg(&mp_type_OSError, "Wifi Invalid Interface");
-      case ESP_ERR_WIFI_MODE:
-        mp_raise_msg(&mp_type_OSError, "Wifi Invalid Mode");
-      case ESP_ERR_WIFI_STATE:
-        mp_raise_msg(&mp_type_OSError, "Wifi Internal State Error");
-      case ESP_ERR_WIFI_CONN:
-        mp_raise_msg(&mp_type_OSError, "Wifi Internal Error");
-      case ESP_ERR_WIFI_NVS:
-        mp_raise_msg(&mp_type_OSError, "Wifi Internal NVS Error");
-      case ESP_ERR_WIFI_MAC:
-        mp_raise_msg(&mp_type_OSError, "Wifi Invalid MAC Address");
-      case ESP_ERR_WIFI_SSID:
-        mp_raise_msg(&mp_type_OSError, "Wifi SSID Invalid");
-      case ESP_ERR_WIFI_PASSWORD:
-        mp_raise_msg(&mp_type_OSError, "Wifi Invalid Password");
-      case ESP_ERR_WIFI_TIMEOUT:
-        mp_raise_OSError(MP_ETIMEDOUT);
-      case ESP_ERR_WIFI_WAKE_FAIL:
-        mp_raise_msg(&mp_type_OSError, "Wifi Wakeup Failure");
-      case ESP_ERR_WIFI_WOULD_BLOCK:
-        mp_raise_msg(&mp_type_OSError, "Wifi Would Block");
-      case ESP_ERR_WIFI_NOT_CONNECT:
-        mp_raise_msg(&mp_type_OSError, "Wifi Not Connected");
-      case ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS:
-        mp_raise_msg(&mp_type_OSError, "TCP/IP Invalid Parameters");
-      case ESP_ERR_TCPIP_ADAPTER_IF_NOT_READY:
-        mp_raise_msg(&mp_type_OSError, "TCP/IP IF Not Ready");
-      case ESP_ERR_TCPIP_ADAPTER_DHCPC_START_FAILED:
-        mp_raise_msg(&mp_type_OSError, "TCP/IP DHCP Client Start Failed");
-      case ESP_ERR_TCPIP_ADAPTER_NO_MEM:
-        mp_raise_OSError(MP_ENOMEM);
-      default:
-        mp_raise_msg_varg( &mp_type_RuntimeError, "Wifi Unknown Error 0x%04x", e);
-   }
+    switch (e) {
+        case ESP_ERR_WIFI_NOT_INIT:
+            mp_raise_msg(&mp_type_OSError, "Wifi Not Initialized");
+        case ESP_ERR_WIFI_NOT_STARTED:
+            mp_raise_msg(&mp_type_OSError, "Wifi Not Started");
+        case ESP_ERR_WIFI_NOT_STOPPED:
+            mp_raise_msg(&mp_type_OSError, "Wifi Not Stopped");
+        case ESP_ERR_WIFI_IF:
+            mp_raise_msg(&mp_type_OSError, "Wifi Invalid Interface");
+        case ESP_ERR_WIFI_MODE:
+            mp_raise_msg(&mp_type_OSError, "Wifi Invalid Mode");
+        case ESP_ERR_WIFI_STATE:
+            mp_raise_msg(&mp_type_OSError, "Wifi Internal State Error");
+        case ESP_ERR_WIFI_CONN:
+            mp_raise_msg(&mp_type_OSError, "Wifi Internal Error");
+        case ESP_ERR_WIFI_NVS:
+            mp_raise_msg(&mp_type_OSError, "Wifi Internal NVS Error");
+        case ESP_ERR_WIFI_MAC:
+            mp_raise_msg(&mp_type_OSError, "Wifi Invalid MAC Address");
+        case ESP_ERR_WIFI_SSID:
+            mp_raise_msg(&mp_type_OSError, "Wifi SSID Invalid");
+        case ESP_ERR_WIFI_PASSWORD:
+            mp_raise_msg(&mp_type_OSError, "Wifi Invalid Password");
+        case ESP_ERR_WIFI_TIMEOUT:
+            mp_raise_OSError(MP_ETIMEDOUT);
+        case ESP_ERR_WIFI_WAKE_FAIL:
+            mp_raise_msg(&mp_type_OSError, "Wifi Wakeup Failure");
+        case ESP_ERR_WIFI_WOULD_BLOCK:
+            mp_raise_msg(&mp_type_OSError, "Wifi Would Block");
+        case ESP_ERR_WIFI_NOT_CONNECT:
+            mp_raise_msg(&mp_type_OSError, "Wifi Not Connected");
+        case ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS:
+            mp_raise_msg(&mp_type_OSError, "TCP/IP Invalid Parameters");
+        case ESP_ERR_TCPIP_ADAPTER_IF_NOT_READY:
+            mp_raise_msg(&mp_type_OSError, "TCP/IP IF Not Ready");
+        case ESP_ERR_TCPIP_ADAPTER_DHCPC_START_FAILED:
+            mp_raise_msg(&mp_type_OSError, "TCP/IP DHCP Client Start Failed");
+        case ESP_ERR_TCPIP_ADAPTER_NO_MEM:
+            mp_raise_OSError(MP_ENOMEM);
+        default:
+            mp_raise_msg_varg( &mp_type_RuntimeError, "Wifi Unknown Error 0x%04x", 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);
@@ -138,93 +140,93 @@
 // This function is called by the system-event task and so runs in a different
 // thread to the main MicroPython task.  It must not raise any Python exceptions.
 static esp_err_t event_handler(void *ctx, system_event_t *event) {
-   switch(event->event_id) {
-    case SYSTEM_EVENT_STA_START:
-        ESP_LOGI("wifi", "STA_START");
-        break;
-    case SYSTEM_EVENT_STA_CONNECTED:
-        ESP_LOGI("network", "CONNECTED");
-        break;
-    case SYSTEM_EVENT_STA_GOT_IP:
-        ESP_LOGI("network", "GOT_IP");
-        wifi_sta_connected = true;
-        wifi_sta_disconn_reason = 0; // Success so clear error. (in case of new error will be replaced anyway)
-        #if MICROPY_HW_ENABLE_MDNS_QUERIES || MICROPY_HW_ENABLE_MDNS_RESPONDER
-        if (!mdns_initialised) {
-            mdns_init();
-            #if MICROPY_HW_ENABLE_MDNS_RESPONDER
-            const char *hostname = NULL;
-            if (tcpip_adapter_get_hostname(WIFI_IF_STA, &hostname) != ESP_OK || hostname == NULL) {
-                hostname = "esp32";
+    switch (event->event_id) {
+        case SYSTEM_EVENT_STA_START:
+            ESP_LOGI("wifi", "STA_START");
+            break;
+        case SYSTEM_EVENT_STA_CONNECTED:
+            ESP_LOGI("network", "CONNECTED");
+            break;
+        case SYSTEM_EVENT_STA_GOT_IP:
+            ESP_LOGI("network", "GOT_IP");
+            wifi_sta_connected = true;
+            wifi_sta_disconn_reason = 0; // Success so clear error. (in case of new error will be replaced anyway)
+            #if MICROPY_HW_ENABLE_MDNS_QUERIES || MICROPY_HW_ENABLE_MDNS_RESPONDER
+            if (!mdns_initialised) {
+                mdns_init();
+                #if MICROPY_HW_ENABLE_MDNS_RESPONDER
+                const char *hostname = NULL;
+                if (tcpip_adapter_get_hostname(WIFI_IF_STA, &hostname) != ESP_OK || hostname == NULL) {
+                    hostname = "esp32";
+                }
+                mdns_hostname_set(hostname);
+                mdns_instance_name_set(hostname);
+                #endif
+                mdns_initialised = true;
             }
-            mdns_hostname_set(hostname);
-            mdns_instance_name_set(hostname);
             #endif
-            mdns_initialised = true;
-        }
-        #endif
-        break;
-    case SYSTEM_EVENT_STA_DISCONNECTED: {
-        // This is a workaround as ESP32 WiFi libs don't currently
-        // auto-reassociate.
-        system_event_sta_disconnected_t *disconn = &event->event_info.disconnected;
-        char *message = "";
-        wifi_sta_disconn_reason = disconn->reason;
-        switch (disconn->reason) {
-            case WIFI_REASON_BEACON_TIMEOUT:
-                // AP has dropped out; try to reconnect.
-                message = "\nbeacon timeout";
-                break;
-            case WIFI_REASON_NO_AP_FOUND:
-                // AP may not exist, or it may have momentarily dropped out; try to reconnect.
-                message = "\nno AP found";
-                break;
-            case WIFI_REASON_AUTH_FAIL:
-                // Password may be wrong, or it just failed to connect; try to reconnect.
-                message = "\nauthentication failed";
-                break;
-            default:
-                // Let other errors through and try to reconnect.
-                break;
-        }
-        ESP_LOGI("wifi", "STA_DISCONNECTED, reason:%d%s", disconn->reason, message);
+            break;
+        case SYSTEM_EVENT_STA_DISCONNECTED: {
+            // This is a workaround as ESP32 WiFi libs don't currently
+            // auto-reassociate.
+            system_event_sta_disconnected_t *disconn = &event->event_info.disconnected;
+            char *message = "";
+            wifi_sta_disconn_reason = disconn->reason;
+            switch (disconn->reason) {
+                case WIFI_REASON_BEACON_TIMEOUT:
+                    // AP has dropped out; try to reconnect.
+                    message = "\nbeacon timeout";
+                    break;
+                case WIFI_REASON_NO_AP_FOUND:
+                    // AP may not exist, or it may have momentarily dropped out; try to reconnect.
+                    message = "\nno AP found";
+                    break;
+                case WIFI_REASON_AUTH_FAIL:
+                    // Password may be wrong, or it just failed to connect; try to reconnect.
+                    message = "\nauthentication failed";
+                    break;
+                default:
+                    // Let other errors through and try to reconnect.
+                    break;
+            }
+            ESP_LOGI("wifi", "STA_DISCONNECTED, reason:%d%s", disconn->reason, message);
 
-        wifi_sta_connected = false;
-        if (wifi_sta_connect_requested) {
-            wifi_mode_t mode;
-            if (esp_wifi_get_mode(&mode) == ESP_OK) {
-                if (mode & WIFI_MODE_STA) {
-                    // STA is active so attempt to reconnect.
-                    esp_err_t e = esp_wifi_connect();
-                    if (e != ESP_OK) {
-                        ESP_LOGI("wifi", "error attempting to reconnect: 0x%04x", e);
+            wifi_sta_connected = false;
+            if (wifi_sta_connect_requested) {
+                wifi_mode_t mode;
+                if (esp_wifi_get_mode(&mode) == ESP_OK) {
+                    if (mode & WIFI_MODE_STA) {
+                        // STA is active so attempt to reconnect.
+                        esp_err_t e = esp_wifi_connect();
+                        if (e != ESP_OK) {
+                            ESP_LOGI("wifi", "error attempting to reconnect: 0x%04x", e);
+                        }
                     }
                 }
             }
+            break;
         }
-        break;
-    }
-    case SYSTEM_EVENT_GOT_IP6:
-        ESP_LOGI("network", "Got IPv6");
-        break;
-    case SYSTEM_EVENT_ETH_START:
-        ESP_LOGI("ethernet", "start");
-        break;
-    case SYSTEM_EVENT_ETH_STOP:
-        ESP_LOGI("ethernet", "stop");
-        break;
-    case SYSTEM_EVENT_ETH_CONNECTED:
-        ESP_LOGI("ethernet", "LAN cable connected");
-        break;
-    case SYSTEM_EVENT_ETH_DISCONNECTED:
-        ESP_LOGI("ethernet", "LAN cable disconnected");
-        break;
-    case SYSTEM_EVENT_ETH_GOT_IP:
-        ESP_LOGI("ethernet", "Got IP");
-        break;
-    default:
-        ESP_LOGI("network", "event %d", event->event_id);
-        break;
+        case SYSTEM_EVENT_GOT_IP6:
+            ESP_LOGI("network", "Got IPv6");
+            break;
+        case SYSTEM_EVENT_ETH_START:
+            ESP_LOGI("ethernet", "start");
+            break;
+        case SYSTEM_EVENT_ETH_STOP:
+            ESP_LOGI("ethernet", "stop");
+            break;
+        case SYSTEM_EVENT_ETH_CONNECTED:
+            ESP_LOGI("ethernet", "LAN cable connected");
+            break;
+        case SYSTEM_EVENT_ETH_DISCONNECTED:
+            ESP_LOGI("ethernet", "LAN cable disconnected");
+            break;
+        case SYSTEM_EVENT_ETH_GOT_IP:
+            ESP_LOGI("ethernet", "Got IP");
+            break;
+        default:
+            ESP_LOGI("network", "event %d", event->event_id);
+            break;
     }
     return ESP_OK;
 }
@@ -409,7 +411,7 @@
             require_if(args[0], WIFI_IF_AP);
             wifi_sta_list_t station_list;
             ESP_EXCEPTIONS(esp_wifi_ap_get_sta_list(&station_list));
-            wifi_sta_info_t *stations = (wifi_sta_info_t*)station_list.sta;
+            wifi_sta_info_t *stations = (wifi_sta_info_t *)station_list.sta;
             mp_obj_t list = mp_obj_new_list(0, NULL);
             for (int i = 0; i < station_list.num; ++i) {
                 mp_obj_tuple_t *t = mp_obj_new_tuple(1, NULL);
@@ -493,10 +495,10 @@
     if (n_args == 1) {
         // get
         mp_obj_t tuple[4] = {
-            netutils_format_ipv4_addr((uint8_t*)&info.ip, NETUTILS_BIG),
-            netutils_format_ipv4_addr((uint8_t*)&info.netmask, NETUTILS_BIG),
-            netutils_format_ipv4_addr((uint8_t*)&info.gw, NETUTILS_BIG),
-            netutils_format_ipv4_addr((uint8_t*)&dns_info.ip, NETUTILS_BIG),
+            netutils_format_ipv4_addr((uint8_t *)&info.ip, NETUTILS_BIG),
+            netutils_format_ipv4_addr((uint8_t *)&info.netmask, NETUTILS_BIG),
+            netutils_format_ipv4_addr((uint8_t *)&info.gw, NETUTILS_BIG),
+            netutils_format_ipv4_addr((uint8_t *)&dns_info.ip, NETUTILS_BIG),
         };
         return mp_obj_new_tuple(4, tuple);
     } else {
@@ -504,28 +506,32 @@
         if (mp_obj_is_type(args[1], &mp_type_tuple) || mp_obj_is_type(args[1], &mp_type_list)) {
             mp_obj_t *items;
             mp_obj_get_array_fixed_n(args[1], 4, &items);
-            netutils_parse_ipv4_addr(items[0], (void*)&info.ip, NETUTILS_BIG);
+            netutils_parse_ipv4_addr(items[0], (void *)&info.ip, NETUTILS_BIG);
             if (mp_obj_is_integer(items[1])) {
                 // allow numeric netmask, i.e.:
                 // 24 -> 255.255.255.0
                 // 16 -> 255.255.0.0
                 // etc...
-                uint32_t* m = (uint32_t*)&info.netmask;
+                uint32_t *m = (uint32_t *)&info.netmask;
                 *m = htonl(0xffffffff << (32 - mp_obj_get_int(items[1])));
             } else {
-                netutils_parse_ipv4_addr(items[1], (void*)&info.netmask, NETUTILS_BIG);
+                netutils_parse_ipv4_addr(items[1], (void *)&info.netmask, NETUTILS_BIG);
             }
-            netutils_parse_ipv4_addr(items[2], (void*)&info.gw, NETUTILS_BIG);
-            netutils_parse_ipv4_addr(items[3], (void*)&dns_info.ip, NETUTILS_BIG);
+            netutils_parse_ipv4_addr(items[2], (void *)&info.gw, NETUTILS_BIG);
+            netutils_parse_ipv4_addr(items[3], (void *)&dns_info.ip, NETUTILS_BIG);
             // To set a static IP we have to disable DHCP first
             if (self->if_id == WIFI_IF_STA || self->if_id == ESP_IF_ETH) {
                 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_dns_info(self->if_id, TCPIP_ADAPTER_DNS_MAIN, &dns_info));
             } else if (self->if_id == 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_dns_info(WIFI_IF_AP, TCPIP_ADAPTER_DNS_MAIN, &dns_info));
                 ESP_EXCEPTIONS(tcpip_adapter_dhcps_start(WIFI_IF_AP));
@@ -651,28 +657,28 @@
         case QS(MP_QSTR_mac): {
             uint8_t mac[6];
             switch (self->if_id) {
-              case WIFI_IF_AP: // fallthrough intentional
-              case WIFI_IF_STA:
-                  ESP_EXCEPTIONS(esp_wifi_get_mac(self->if_id, mac));
-                  return mp_obj_new_bytes(mac, sizeof(mac));
+                case WIFI_IF_AP: // fallthrough intentional
+                case WIFI_IF_STA:
+                    ESP_EXCEPTIONS(esp_wifi_get_mac(self->if_id, mac));
+                    return mp_obj_new_bytes(mac, sizeof(mac));
 
-              #if !MICROPY_ESP_IDF_4
-              case ESP_IF_ETH:
-                  esp_eth_get_mac(mac);
-                  return mp_obj_new_bytes(mac, sizeof(mac));
-              #endif
+                #if !MICROPY_ESP_IDF_4
+                case ESP_IF_ETH:
+                    esp_eth_get_mac(mac);
+                    return mp_obj_new_bytes(mac, sizeof(mac));
+                #endif
 
-              default:
-                  goto unknown;
+                default:
+                    goto unknown;
             }
         }
         case QS(MP_QSTR_essid):
             switch (self->if_id) {
                 case WIFI_IF_STA:
-                    val = mp_obj_new_str((char*)cfg.sta.ssid, strlen((char*)cfg.sta.ssid));
+                    val = mp_obj_new_str((char *)cfg.sta.ssid, strlen((char *)cfg.sta.ssid));
                     break;
                 case WIFI_IF_AP:
-                    val = mp_obj_new_str((char*)cfg.ap.ssid, cfg.ap.ssid_len);
+                    val = mp_obj_new_str((char *)cfg.ap.ssid, cfg.ap.ssid_len);
                     break;
                 default:
                     req_if = WIFI_IF_AP;
@@ -704,7 +710,7 @@
             goto unknown;
     }
 
-    #undef QS
+#undef QS
 
     // We post-check interface requirements to save on code size
     if (req_if >= 0) {
@@ -753,7 +759,7 @@
     #endif
     { MP_ROM_QSTR(MP_QSTR_phy_mode), MP_ROM_PTR(&esp_phy_mode_obj) },
 
-#if MODNETWORK_INCLUDE_CONSTANTS
+    #if MODNETWORK_INCLUDE_CONSTANTS
     { MP_ROM_QSTR(MP_QSTR_STA_IF), MP_ROM_INT(WIFI_IF_STA)},
     { MP_ROM_QSTR(MP_QSTR_AP_IF), MP_ROM_INT(WIFI_IF_AP)},
 
@@ -790,12 +796,12 @@
     { MP_ROM_QSTR(MP_QSTR_STAT_BEACON_TIMEOUT), MP_ROM_INT(WIFI_REASON_BEACON_TIMEOUT)},
     { MP_ROM_QSTR(MP_QSTR_STAT_ASSOC_FAIL), MP_ROM_INT(WIFI_REASON_ASSOC_FAIL)},
     { MP_ROM_QSTR(MP_QSTR_STAT_HANDSHAKE_TIMEOUT), MP_ROM_INT(WIFI_REASON_HANDSHAKE_TIMEOUT)},
-#endif
+    #endif
 };
 
 STATIC MP_DEFINE_CONST_DICT(mp_module_network_globals, mp_module_network_globals_table);
 
 const mp_obj_module_t mp_module_network = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_network_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_network_globals,
 };
diff --git a/ports/esp32/modsocket.c b/ports/esp32/modsocket.c
index be2a749..1252a18 100644
--- a/ports/esp32/modsocket.c
+++ b/ports/esp32/modsocket.c
@@ -184,7 +184,7 @@
         struct ip4_addr addr = {0};
         esp_err_t err = mdns_query_a(nodename_no_local, MDNS_QUERY_TIMEOUT_MS, &addr);
         if (err != ESP_OK) {
-            if (err == ESP_ERR_NOT_FOUND){
+            if (err == ESP_ERR_NOT_FOUND) {
                 *res = NULL;
                 return 0;
             }
@@ -199,16 +199,16 @@
         }
         memset(ai, 0, sizeof(struct addrinfo) + sizeof(struct sockaddr_storage));
 
-        struct sockaddr_in *sa = (struct sockaddr_in*)((uint8_t*)ai + sizeof(struct addrinfo));
+        struct sockaddr_in *sa = (struct sockaddr_in *)((uint8_t *)ai + sizeof(struct addrinfo));
         inet_addr_from_ip4addr(&sa->sin_addr, &addr);
         sa->sin_family = AF_INET;
         sa->sin_len = sizeof(struct sockaddr_in);
         sa->sin_port = lwip_htons((u16_t)atoi(servname));
         ai->ai_family = AF_INET;
-        ai->ai_canonname = ((char*)sa + sizeof(struct sockaddr_storage));
+        ai->ai_canonname = ((char *)sa + sizeof(struct sockaddr_storage));
         memcpy(ai->ai_canonname, nodename, nodename_len + 1);
         ai->ai_addrlen = sizeof(struct sockaddr_storage);
-        ai->ai_addr = (struct sockaddr*)sa;
+        ai->ai_addr = (struct sockaddr *)sa;
 
         *res = ai;
         return 0;
@@ -293,7 +293,9 @@
     _socket_getaddrinfo(arg1, &res);
     int r = lwip_bind(self->fd, res->ai_addr, res->ai_addrlen);
     lwip_freeaddrinfo(res);
-    if (r < 0) exception_from_errno(errno);
+    if (r < 0) {
+        exception_from_errno(errno);
+    }
     return mp_const_none;
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_bind_obj, socket_bind);
@@ -302,7 +304,9 @@
     socket_obj_t *self = MP_OBJ_TO_PTR(arg0);
     int backlog = mp_obj_get_int(arg1);
     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;
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_listen_obj, socket_listen);
@@ -314,12 +318,16 @@
     socklen_t addr_len = sizeof(addr);
 
     int new_fd = -1;
-    for (int i=0; i<=self->retries; i++) {
+    for (int i = 0; i <= self->retries; i++) {
         MP_THREAD_GIL_EXIT();
         new_fd = lwip_accept(self->fd, &addr, &addr_len);
         MP_THREAD_GIL_ENTER();
-        if (new_fd >= 0) break;
-        if (errno != EAGAIN) exception_from_errno(errno);
+        if (new_fd >= 0) {
+            break;
+        }
+        if (errno != EAGAIN) {
+            exception_from_errno(errno);
+        }
         check_for_exceptions();
     }
     if (new_fd < 0) {
@@ -341,8 +349,8 @@
     _socket_settimeout(sock, UINT64_MAX);
 
     // make the return value
-    uint8_t *ip = (uint8_t*)&((struct sockaddr_in*)&addr)->sin_addr;
-    mp_uint_t port = lwip_ntohs(((struct sockaddr_in*)&addr)->sin_port);
+    uint8_t *ip = (uint8_t *)&((struct sockaddr_in *)&addr)->sin_addr;
+    mp_uint_t port = lwip_ntohs(((struct sockaddr_in *)&addr)->sin_port);
     mp_obj_tuple_t *client = mp_obj_new_tuple(2, NULL);
     client->items[0] = sock;
     client->items[1] = netutils_format_inet_addr(ip, port, NETUTILS_BIG);
@@ -384,7 +392,7 @@
             break;
         }
 
-        #if MICROPY_PY_USOCKET_EVENTS
+            #if MICROPY_PY_USOCKET_EVENTS
         // level: SOL_SOCKET
         // special "register callback" option
         case 20: {
@@ -401,7 +409,7 @@
             }
             break;
         }
-        #endif
+            #endif
 
         // level: IPPROTO_IP
         case IP_ADD_MEMBERSHIP: {
@@ -412,7 +420,7 @@
             }
 
             // POSIX setsockopt has order: group addr, if addr, lwIP has it vice-versa
-            err_t err = igmp_joingroup((const ip4_addr_t*)bufinfo.buf + 1, bufinfo.buf);
+            err_t err = igmp_joingroup((const ip4_addr_t *)bufinfo.buf + 1, bufinfo.buf);
             if (err != ERR_OK) {
                 mp_raise_OSError(-err);
             }
@@ -445,8 +453,9 @@
 
 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);
-    if (arg1 == mp_const_none) _socket_settimeout(self, UINT64_MAX);
-    else {
+    if (arg1 == mp_const_none) {
+        _socket_settimeout(self, UINT64_MAX);
+    } else {
         #if MICROPY_PY_BUILTINS_FLOAT
         _socket_settimeout(self, mp_obj_get_float(arg1) * 1000L);
         #else
@@ -459,8 +468,11 @@
 
 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);
-    if (mp_obj_is_true(arg1)) _socket_settimeout(self, UINT64_MAX);
-    else _socket_settimeout(self, 0);
+    if (mp_obj_is_true(arg1)) {
+        _socket_settimeout(self, UINT64_MAX);
+    } else {
+        _socket_settimeout(self, 0);
+    }
     return mp_const_none;
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking);
@@ -518,7 +530,7 @@
 }
 
 mp_obj_t _socket_recvfrom(mp_obj_t self_in, mp_obj_t len_in,
-        struct sockaddr *from, socklen_t *from_len) {
+    struct sockaddr *from, socklen_t *from_len) {
     size_t len = mp_obj_get_int(len_in);
     vstr_t vstr;
     vstr_init_len(&vstr, len);
@@ -545,8 +557,8 @@
     mp_obj_t tuple[2];
     tuple[0] = _socket_recvfrom(self_in, len_in, &from, &fromlen);
 
-    uint8_t *ip = (uint8_t*)&((struct sockaddr_in*)&from)->sin_addr;
-    mp_uint_t port = lwip_ntohs(((struct sockaddr_in*)&from)->sin_port);
+    uint8_t *ip = (uint8_t *)&((struct sockaddr_in *)&from)->sin_addr;
+    mp_uint_t port = lwip_ntohs(((struct sockaddr_in *)&from)->sin_port);
     tuple[1] = netutils_format_inet_addr(ip, port, NETUTILS_BIG);
 
     return mp_obj_new_tuple(2, tuple);
@@ -555,15 +567,21 @@
 
 int _socket_send(socket_obj_t *sock, const char *data, size_t datalen) {
     int sentlen = 0;
-    for (int i=0; i<=sock->retries && sentlen < datalen; i++) {
+    for (int i = 0; i <= sock->retries && sentlen < datalen; i++) {
         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();
-        if (r < 0 && errno != EWOULDBLOCK) exception_from_errno(errno);
-        if (r > 0) sentlen += r;
+        if (r < 0 && errno != EWOULDBLOCK) {
+            exception_from_errno(errno);
+        }
+        if (r > 0) {
+            sentlen += r;
+        }
         check_for_exceptions();
     }
-    if (sentlen == 0) mp_raise_OSError(MP_ETIMEDOUT);
+    if (sentlen == 0) {
+        mp_raise_OSError(MP_ETIMEDOUT);
+    }
     return sentlen;
 }
 
@@ -583,7 +601,9 @@
     mp_buffer_info_t bufinfo;
     mp_get_buffer_raise(arg1, &bufinfo, MP_BUFFER_READ);
     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;
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_sendall_obj, socket_sendall);
@@ -599,14 +619,16 @@
     struct sockaddr_in to;
     to.sin_len = sizeof(to);
     to.sin_family = AF_INET;
-    to.sin_port = lwip_htons(netutils_parse_inet_addr(addr_in, (uint8_t*)&to.sin_addr, NETUTILS_BIG));
+    to.sin_port = lwip_htons(netutils_parse_inet_addr(addr_in, (uint8_t *)&to.sin_addr, NETUTILS_BIG));
 
     // send the data
-    for (int i=0; i<=self->retries; i++) {
+    for (int i = 0; i <= self->retries; i++) {
         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();
-        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) {
             exception_from_errno(errno);
         }
@@ -634,12 +656,17 @@
 
 STATIC mp_uint_t socket_stream_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) {
     socket_obj_t *sock = self_in;
-    for (int i=0; i<=sock->retries; i++) {
+    for (int i = 0; i <= sock->retries; i++) {
         MP_THREAD_GIL_EXIT();
         int r = lwip_write(sock->fd, buf, size);
         MP_THREAD_GIL_ENTER();
-        if (r > 0) return r;
-        if (r < 0 && errno != EWOULDBLOCK) { *errcode = errno; return MP_STREAM_ERROR; }
+        if (r > 0) {
+            return r;
+        }
+        if (r < 0 && errno != EWOULDBLOCK) {
+            *errcode = errno;
+            return MP_STREAM_ERROR;
+        }
         check_for_exceptions();
     }
     *errcode = sock->retries == 0 ? MP_EWOULDBLOCK : MP_ETIMEDOUT;
@@ -647,27 +674,42 @@
 }
 
 STATIC mp_uint_t socket_stream_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) {
-    socket_obj_t * socket = self_in;
+    socket_obj_t *socket = self_in;
     if (request == MP_STREAM_POLL) {
 
-        fd_set rfds; FD_ZERO(&rfds);
-        fd_set wfds; FD_ZERO(&wfds);
-        fd_set efds; FD_ZERO(&efds);
+        fd_set rfds;
+        FD_ZERO(&rfds);
+        fd_set wfds;
+        FD_ZERO(&wfds);
+        fd_set efds;
+        FD_ZERO(&efds);
         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_WR) FD_SET(socket->fd, &wfds);
-        if (arg & MP_STREAM_POLL_HUP) FD_SET(socket->fd, &efds);
+        if (arg & MP_STREAM_POLL_RD) {
+            FD_SET(socket->fd, &rfds);
+        }
+        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) {
             *errcode = MP_EIO;
             return MP_STREAM_ERROR;
         }
 
         mp_uint_t ret = 0;
-        if (FD_ISSET(socket->fd, &rfds)) ret |= MP_STREAM_POLL_RD;
-        if (FD_ISSET(socket->fd, &wfds)) ret |= MP_STREAM_POLL_WR;
-        if (FD_ISSET(socket->fd, &efds)) ret |= MP_STREAM_POLL_HUP;
+        if (FD_ISSET(socket->fd, &rfds)) {
+            ret |= MP_STREAM_POLL_RD;
+        }
+        if (FD_ISSET(socket->fd, &wfds)) {
+            ret |= MP_STREAM_POLL_WR;
+        }
+        if (FD_ISSET(socket->fd, &efds)) {
+            ret |= MP_STREAM_POLL_HUP;
+        }
         return ret;
     } else if (request == MP_STREAM_CLOSE) {
         if (socket->fd >= 0) {
@@ -761,7 +803,9 @@
         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;
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(esp_socket_getaddrinfo_obj, 2, 6, esp_socket_getaddrinfo);
@@ -800,5 +844,5 @@
 
 const mp_obj_module_t mp_module_usocket = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_socket_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_socket_globals,
 };
diff --git a/ports/esp32/modules/_boot.py b/ports/esp32/modules/_boot.py
index bf40ea3..a7d9813 100644
--- a/ports/esp32/modules/_boot.py
+++ b/ports/esp32/modules/_boot.py
@@ -4,9 +4,10 @@
 
 try:
     if bdev:
-        uos.mount(bdev, '/')
+        uos.mount(bdev, "/")
 except OSError:
     import inisetup
+
     vfs = inisetup.setup()
 
 gc.collect()
diff --git a/ports/esp32/modules/flashbdev.py b/ports/esp32/modules/flashbdev.py
index 45b8686..bf4fec9 100644
--- a/ports/esp32/modules/flashbdev.py
+++ b/ports/esp32/modules/flashbdev.py
@@ -1,4 +1,4 @@
 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
diff --git a/ports/esp32/modules/inisetup.py b/ports/esp32/modules/inisetup.py
index 3196f0c..cb03fd7 100644
--- a/ports/esp32/modules/inisetup.py
+++ b/ports/esp32/modules/inisetup.py
@@ -1,41 +1,49 @@
 import uos
 from flashbdev import bdev
 
+
 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)
     empty = True
     for b in buf:
-        if b != 0xff:
+        if b != 0xFF:
             empty = False
             break
     if empty:
         return True
     fs_corrupted()
 
+
 def fs_corrupted():
     import time
+
     while 1:
-        print("""\
+        print(
+            """\
 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
 factory reprogramming of MicroPython firmware (completely erase flash, followed
 by firmware programming).
-""")
+"""
+        )
         time.sleep(3)
 
+
 def setup():
     check_bootsec()
     print("Performing initial setup")
     uos.VfsFat.mkfs(bdev)
     vfs = uos.VfsFat(bdev)
-    uos.mount(vfs, '/')
+    uos.mount(vfs, "/")
     with open("boot.py", "w") as f:
-        f.write("""\
+        f.write(
+            """\
 # This file is executed on every boot (including wake-boot from deepsleep)
 #import esp
 #esp.osdebug(None)
 #import webrepl
 #webrepl.start()
-""")
+"""
+        )
     return vfs
diff --git a/ports/esp32/modules/neopixel.py b/ports/esp32/modules/neopixel.py
index 91f1d79..aa0de81 100644
--- a/ports/esp32/modules/neopixel.py
+++ b/ports/esp32/modules/neopixel.py
@@ -6,7 +6,7 @@
 
 class NeoPixel:
     ORDER = (1, 0, 2, 3)
-    
+
     def __init__(self, pin, n, bpp=3, timing=1):
         self.pin = pin
         self.n = n
@@ -22,8 +22,7 @@
 
     def __getitem__(self, index):
         offset = index * self.bpp
-        return tuple(self.buf[offset + self.ORDER[i]]
-                     for i in range(self.bpp))
+        return tuple(self.buf[offset + self.ORDER[i]] for i in range(self.bpp))
 
     def fill(self, color):
         for i in range(self.n):
diff --git a/ports/esp32/moduos.c b/ports/esp32/moduos.c
index d68df28..50c0d7e 100644
--- a/ports/esp32/moduos.c
+++ b/ports/esp32/moduos.c
@@ -62,7 +62,7 @@
     (mp_obj_t)&os_uname_info_release_obj,
     (mp_obj_t)&os_uname_info_version_obj,
     (mp_obj_t)&os_uname_info_machine_obj
-);
+    );
 
 STATIC mp_obj_t os_uname(void) {
     return (mp_obj_t)&os_uname_info_obj;
@@ -137,5 +137,5 @@
 
 const mp_obj_module_t uos_module = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&os_module_globals,
+    .globals = (mp_obj_dict_t *)&os_module_globals,
 };
diff --git a/ports/esp32/modutime.c b/ports/esp32/modutime.c
index 1d7583e..1b9e07f 100644
--- a/ports/esp32/modutime.c
+++ b/ports/esp32/modutime.c
@@ -70,8 +70,8 @@
     }
 
     return mp_obj_new_int_from_uint(timeutils_mktime(mp_obj_get_int(elem[0]),
-            mp_obj_get_int(elem[1]), mp_obj_get_int(elem[2]), mp_obj_get_int(elem[3]),
-            mp_obj_get_int(elem[4]), mp_obj_get_int(elem[5])));
+        mp_obj_get_int(elem[1]), mp_obj_get_int(elem[2]), mp_obj_get_int(elem[3]),
+        mp_obj_get_int(elem[4]), mp_obj_get_int(elem[5])));
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_1(time_mktime_obj, time_mktime);
 
@@ -102,5 +102,5 @@
 
 const mp_obj_module_t utime_module = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&time_module_globals,
+    .globals = (mp_obj_dict_t *)&time_module_globals,
 };
diff --git a/ports/esp32/mpconfigport.h b/ports/esp32/mpconfigport.h
index bca6853..3b6fb37 100644
--- a/ports/esp32/mpconfigport.h
+++ b/ports/esp32/mpconfigport.h
@@ -222,9 +222,9 @@
 // type definitions for the specific machine
 
 #define BYTES_PER_WORD (4)
-#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p)))
+#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p)))
 #define MP_PLAT_PRINT_STRN(str, len) mp_hal_stdout_tx_strn_cooked(str, len)
-void *esp_native_code_commit(void*, size_t, void*);
+void *esp_native_code_commit(void *, size_t, void *);
 #define MP_PLAT_COMMIT_EXEC(buf, len, reloc) esp_native_code_commit(buf, len, reloc)
 #define MP_SSIZE_MAX (0x7fffffff)
 
@@ -256,7 +256,7 @@
         extern void mp_handle_pending(bool); \
         mp_handle_pending(true); \
         MICROPY_PY_USOCKET_EVENTS_HANDLER \
-        asm("waiti 0"); \
+        asm ("waiti 0"); \
     } while (0);
 #endif
 
diff --git a/ports/esp32/mphalport.h b/ports/esp32/mphalport.h
index 575cdbe..7cee3fb 100644
--- a/ports/esp32/mphalport.h
+++ b/ports/esp32/mphalport.h
@@ -44,9 +44,9 @@
 
 uint32_t mp_hal_ticks_us(void);
 __attribute__((always_inline)) static inline uint32_t mp_hal_ticks_cpu(void) {
-  uint32_t ccount;
-  __asm__ __volatile__("rsr %0,ccount":"=a" (ccount));
-  return ccount;
+    uint32_t ccount;
+    __asm__ __volatile__ ("rsr %0,ccount" : "=a" (ccount));
+    return ccount;
 }
 
 void mp_hal_delay_us(uint32_t);
diff --git a/ports/esp32/mpthreadport.c b/ports/esp32/mpthreadport.c
index febd01a..7b391ad 100644
--- a/ports/esp32/mpthreadport.c
+++ b/ports/esp32/mpthreadport.c
@@ -75,7 +75,7 @@
 void mp_thread_gc_others(void) {
     mp_thread_mutex_lock(&thread_mutex, 1);
     for (thread_t *th = thread; th != NULL; th = th->next) {
-        gc_collect_root((void**)&th, 1);
+        gc_collect_root((void **)&th, 1);
         gc_collect_root(&th->arg, 1); // probably not needed
         if (th->id == xTaskGetCurrentTaskHandle()) {
             continue;
@@ -107,17 +107,18 @@
     mp_thread_mutex_unlock(&thread_mutex);
 }
 
-STATIC void *(*ext_thread_entry)(void*) = NULL;
+STATIC void *(*ext_thread_entry)(void *) = NULL;
 
 STATIC void freertos_entry(void *arg) {
     if (ext_thread_entry) {
         ext_thread_entry(arg);
     }
     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) {
     // store thread entry function into a global variable so we can access it
     ext_thread_entry = entry;
 
@@ -153,7 +154,7 @@
     mp_thread_mutex_unlock(&thread_mutex);
 }
 
-void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size) {
+void mp_thread_create(void *(*entry)(void *), void *arg, size_t *stack_size) {
     mp_thread_create_ex(entry, arg, stack_size, MP_THREAD_PRIORITY, "mp_thread");
 }
 
@@ -177,7 +178,7 @@
     mp_thread_mutex_lock(&thread_mutex, 1);
     for (thread_t *th = thread; th != NULL; prev = th, th = th->next) {
         // unlink the node from the list
-        if ((void*)th->id == tcb) {
+        if ((void *)th->id == tcb) {
             if (prev != NULL) {
                 prev->next = th->next;
             } else {
@@ -197,7 +198,7 @@
 }
 
 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) {
diff --git a/ports/esp32/network_lan.c b/ports/esp32/network_lan.c
index 2910407..c2365e6 100644
--- a/ports/esp32/network_lan.c
+++ b/ports/esp32/network_lan.c
@@ -55,7 +55,7 @@
 STATIC lan_if_obj_t lan_obj = {{&lan_if_type}, ESP_IF_ETH, false, false};
 
 STATIC void phy_power_enable(bool enable) {
-    lan_if_obj_t* self = &lan_obj;
+    lan_if_obj_t *self = &lan_obj;
 
     if (self->phy_power_pin != -1) {
 
@@ -83,13 +83,13 @@
 }
 
 STATIC void init_lan_rmii() {
-    lan_if_obj_t* self = &lan_obj;
+    lan_if_obj_t *self = &lan_obj;
     phy_rmii_configure_data_interface_pins();
     phy_rmii_smi_configure_pins(self->mdc_pin, self->mdio_pin);
 }
 
 STATIC mp_obj_t get_lan(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
-    lan_if_obj_t* self = &lan_obj;
+    lan_if_obj_t *self = &lan_obj;
 
     if (self->initialized) {
         return MP_OBJ_FROM_PTR(&lan_obj);
@@ -215,7 +215,7 @@
 const mp_obj_type_t lan_if_type = {
     { &mp_type_type },
     .name = MP_QSTR_LAN,
-    .locals_dict = (mp_obj_dict_t*)&lan_if_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&lan_if_locals_dict,
 };
 
 #endif // !MICROPY_ESP_IDF_4
diff --git a/ports/esp32/network_ppp.c b/ports/esp32/network_ppp.c
index eb2181e..506c689 100644
--- a/ports/esp32/network_ppp.c
+++ b/ports/esp32/network_ppp.c
@@ -60,7 +60,7 @@
 const mp_obj_type_t ppp_if_type;
 
 static void ppp_status_cb(ppp_pcb *pcb, int err_code, void *ctx) {
-    ppp_if_obj_t* self = ctx;
+    ppp_if_obj_t *self = ctx;
     struct netif *pppif = ppp_netif(self->pcb);
 
     switch (err_code) {
@@ -101,14 +101,14 @@
 }
 
 static void pppos_client_task(void *self_in) {
-    ppp_if_obj_t *self = (ppp_if_obj_t*)self_in;
+    ppp_if_obj_t *self = (ppp_if_obj_t *)self_in;
     uint8_t buf[256];
 
     while (ulTaskNotifyTake(pdTRUE, 0) == 0) {
         int err;
         int len = mp_stream_rw(self->stream, buf, sizeof(buf), &err, 0);
         if (len > 0) {
-            pppos_input_tcpip(self->pcb, (u8_t*)buf, len);
+            pppos_input_tcpip(self->pcb, (u8_t *)buf, len);
         }
     }
 
@@ -195,8 +195,8 @@
     }
 
     if (parsed_args[ARG_authmode].u_int != PPPAUTHTYPE_NONE) {
-        const char* username_str = mp_obj_str_get_str(parsed_args[ARG_username].u_obj);
-        const char* password_str = mp_obj_str_get_str(parsed_args[ARG_password].u_obj);
+        const char *username_str = mp_obj_str_get_str(parsed_args[ARG_username].u_obj);
+        const char *password_str = mp_obj_str_get_str(parsed_args[ARG_password].u_obj);
         pppapi_set_auth(self->pcb, parsed_args[ARG_authmode].u_int, username_str, password_str);
     }
     if (pppapi_set_default(self->pcb) != ESP_OK) {
@@ -209,7 +209,7 @@
         mp_raise_msg(&mp_type_OSError, "connect failed");
     }
 
-    if (xTaskCreatePinnedToCore(pppos_client_task, "ppp", 2048, self, 1, (TaskHandle_t*)&self->client_task_handle, MP_TASK_COREID) != pdPASS) {
+    if (xTaskCreatePinnedToCore(pppos_client_task, "ppp", 2048, self, 1, (TaskHandle_t *)&self->client_task_handle, MP_TASK_COREID) != pdPASS) {
         mp_raise_msg(&mp_type_RuntimeError, "failed to create worker task");
     }
 
@@ -218,7 +218,7 @@
 MP_DEFINE_CONST_FUN_OBJ_KW(ppp_connect_obj, 1, ppp_connect_py);
 
 STATIC mp_obj_t ppp_delete(mp_obj_t self_in) {
-    ppp_if_obj_t* self = MP_OBJ_TO_PTR(self_in);
+    ppp_if_obj_t *self = MP_OBJ_TO_PTR(self_in);
     mp_obj_t args[] = {self, mp_const_false};
     ppp_active(2, args);
     return mp_const_none;
@@ -234,10 +234,10 @@
             dns = dns_getserver(0);
             struct netif *pppif = ppp_netif(self->pcb);
             mp_obj_t tuple[4] = {
-                netutils_format_ipv4_addr((uint8_t*)&pppif->ip_addr, NETUTILS_BIG),
-                netutils_format_ipv4_addr((uint8_t*)&pppif->gw, NETUTILS_BIG),
-                netutils_format_ipv4_addr((uint8_t*)&pppif->netmask, NETUTILS_BIG),
-                netutils_format_ipv4_addr((uint8_t*)&dns, NETUTILS_BIG),
+                netutils_format_ipv4_addr((uint8_t *)&pppif->ip_addr, NETUTILS_BIG),
+                netutils_format_ipv4_addr((uint8_t *)&pppif->gw, NETUTILS_BIG),
+                netutils_format_ipv4_addr((uint8_t *)&pppif->netmask, NETUTILS_BIG),
+                netutils_format_ipv4_addr((uint8_t *)&dns, NETUTILS_BIG),
             };
             return mp_obj_new_tuple(4, tuple);
         } else {
@@ -247,7 +247,7 @@
     } else {
         mp_obj_t *items;
         mp_obj_get_array_fixed_n(args[1], 4, &items);
-        netutils_parse_ipv4_addr(items[3], (uint8_t*)&dns.u_addr.ip4, NETUTILS_BIG);
+        netutils_parse_ipv4_addr(items[3], (uint8_t *)&dns.u_addr.ip4, NETUTILS_BIG);
         dns_setserver(0, &dns);
         return mp_const_none;
     }
@@ -281,7 +281,7 @@
 const mp_obj_type_t ppp_if_type = {
     { &mp_type_type },
     .name = MP_QSTR_PPP,
-    .locals_dict = (mp_obj_dict_t*)&ppp_if_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&ppp_if_locals_dict,
 };
 
 #endif // !MICROPY_ESP_IDF_4
diff --git a/ports/esp32/nimble.c b/ports/esp32/nimble.c
index 3747ae0..7b62412 100644
--- a/ports/esp32/nimble.c
+++ b/ports/esp32/nimble.c
@@ -35,8 +35,8 @@
 #include "nimble/nimble_port_freertos.h"
 
 STATIC void ble_host_task(void *param) {
-     nimble_port_run(); //This function will return only when nimble_port_stop() is executed.
-     nimble_port_freertos_deinit();
+    nimble_port_run();  //This function will return only when nimble_port_stop() is executed.
+    nimble_port_freertos_deinit();
 }
 
 void mp_bluetooth_nimble_port_preinit(void) {
diff --git a/ports/esp8266/boards/manifest.py b/ports/esp8266/boards/manifest.py
index b6df53f..de719f8 100644
--- a/ports/esp8266/boards/manifest.py
+++ b/ports/esp8266/boards/manifest.py
@@ -1,5 +1,5 @@
-freeze('$(PORT_DIR)/modules')
-freeze('$(MPY_DIR)/tools', ('upip.py', 'upip_utarfile.py'))
-freeze('$(MPY_DIR)/drivers/dht', 'dht.py')
-freeze('$(MPY_DIR)/drivers/onewire')
-include('$(MPY_DIR)/extmod/webrepl/manifest.py')
+freeze("$(PORT_DIR)/modules")
+freeze("$(MPY_DIR)/tools", ("upip.py", "upip_utarfile.py"))
+freeze("$(MPY_DIR)/drivers/dht", "dht.py")
+freeze("$(MPY_DIR)/drivers/onewire")
+include("$(MPY_DIR)/extmod/webrepl/manifest.py")
diff --git a/ports/esp8266/boards/manifest_release.py b/ports/esp8266/boards/manifest_release.py
index f2788c8..ab86fa3 100644
--- a/ports/esp8266/boards/manifest_release.py
+++ b/ports/esp8266/boards/manifest_release.py
@@ -1,27 +1,27 @@
-include('manifest.py')
+include("manifest.py")
 
 # drivers
-freeze('$(MPY_DIR)/drivers/display', 'ssd1306.py')
+freeze("$(MPY_DIR)/drivers/display", "ssd1306.py")
 
 # file utilities
-freeze('$(MPY_LIB_DIR)/upysh', 'upysh.py')
+freeze("$(MPY_LIB_DIR)/upysh", "upysh.py")
 
 # uasyncio
-freeze('$(MPY_LIB_DIR)/uasyncio', 'uasyncio/__init__.py')
-freeze('$(MPY_LIB_DIR)/uasyncio.core', 'uasyncio/core.py')
+freeze("$(MPY_LIB_DIR)/uasyncio", "uasyncio/__init__.py")
+freeze("$(MPY_LIB_DIR)/uasyncio.core", "uasyncio/core.py")
 
 # requests
-freeze('$(MPY_LIB_DIR)/urequests', 'urequests.py')
-freeze('$(MPY_LIB_DIR)/urllib.urequest', 'urllib/urequest.py')
+freeze("$(MPY_LIB_DIR)/urequests", "urequests.py")
+freeze("$(MPY_LIB_DIR)/urllib.urequest", "urllib/urequest.py")
 
 # umqtt with examples
-freeze('$(MPY_LIB_DIR)/umqtt.simple', 'umqtt/simple.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_sub_led.py')
+freeze("$(MPY_LIB_DIR)/umqtt.simple", "umqtt/simple.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_sub_led.py")
 
 # HTTP examples
-freeze('$(MPY_DIR)/examples/network', 'http_client.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_ssl.py')
+freeze("$(MPY_DIR)/examples/network", "http_client.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_ssl.py")
diff --git a/ports/esp8266/esp_init_data.c b/ports/esp8266/esp_init_data.c
index b14de57..eb4d99e 100644
--- a/ports/esp8266/esp_init_data.c
+++ b/ports/esp8266/esp_init_data.c
@@ -36,20 +36,20 @@
 extern char flashchip;
 
 static const uint8_t default_init_data[] __attribute__((aligned(4))) = {
-0x05, 0x00, 0x04, 0x02, 0x05, 0x05, 0x05, 0x02, 0x05, 0x00, 0x04, 0x05, 0x05, 0x04, 0x05, 0x05,
-0x04, 0xfe, 0xfd, 0xff, 0xf0, 0xf0, 0xf0, 0xe0, 0xe0, 0xe0, 0xe1, 0x0a, 0xff, 0xff, 0xf8, 0x00,
-0xf8, 0xf8, 0x52, 0x4e, 0x4a, 0x44, 0x40, 0x38, 0x00, 0x00, 0x01, 0x01, 0x02, 0x03, 0x04, 0x05,
-0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0xe1, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x93, 0x43, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+    0x05, 0x00, 0x04, 0x02, 0x05, 0x05, 0x05, 0x02, 0x05, 0x00, 0x04, 0x05, 0x05, 0x04, 0x05, 0x05,
+    0x04, 0xfe, 0xfd, 0xff, 0xf0, 0xf0, 0xf0, 0xe0, 0xe0, 0xe0, 0xe1, 0x0a, 0xff, 0xff, 0xf8, 0x00,
+    0xf8, 0xf8, 0x52, 0x4e, 0x4a, 0x44, 0x40, 0x38, 0x00, 0x00, 0x01, 0x01, 0x02, 0x03, 0x04, 0x05,
+    0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0xe1, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x93, 0x43, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
 };
 
 void firmware_start(void) {
     // For SDK 1.5.2, either address has shifted and not mirrored in
     // eagle.rom.addr.v6.ld, or extra initial member was added.
-    SpiFlashChip *flash = (SpiFlashChip*)(&flashchip + 4);
+    SpiFlashChip *flash = (SpiFlashChip *)(&flashchip + 4);
 
     char buf[128];
     SPIRead(flash->chip_size - 4 * 0x1000, buf, sizeof(buf));
@@ -73,5 +73,5 @@
         SPIWrite(flash->chip_size - 4 * 0x1000, buf, sizeof(buf));
     }
 
-    asm("j call_user_start");
+    asm ("j call_user_start");
 }
diff --git a/ports/esp8266/esp_mphal.c b/ports/esp8266/esp_mphal.c
index d840cf0..d711345 100644
--- a/ports/esp8266/esp_mphal.c
+++ b/ports/esp8266/esp_mphal.c
@@ -74,7 +74,7 @@
         #if 0
         // Idles CPU but need more testing before enabling
         if (!ets_loop_iter()) {
-            asm("waiti 0");
+            asm ("waiti 0");
         }
         #else
         mp_hal_delay_us(1);
@@ -189,7 +189,7 @@
 void *ets_get_esf_buf_ctlblk(void) {
     // Get literal ptr before start of esf_rx_buf_alloc func
     extern void *esf_rx_buf_alloc();
-    return ((void**)esf_rx_buf_alloc)[-1];
+    return ((void **)esf_rx_buf_alloc)[-1];
 }
 
 // Get number of esf_buf free buffers of given type, as encoded by index
@@ -198,10 +198,10 @@
 // 1 - tx buffer, 5 - management frame tx buffer; 8 - rx buffer
 int ets_esf_free_bufs(int idx) {
     uint32_t *p = ets_get_esf_buf_ctlblk();
-    uint32_t *b = (uint32_t*)p[idx];
+    uint32_t *b = (uint32_t *)p[idx];
     int cnt = 0;
     while (b) {
-        b = (uint32_t*)b[0x20 / 4];
+        b = (uint32_t *)b[0x20 / 4];
         cnt++;
     }
     return cnt;
diff --git a/ports/esp8266/esp_mphal.h b/ports/esp8266/esp_mphal.h
index 8712a2a..eaae18f 100644
--- a/ports/esp8266/esp_mphal.h
+++ b/ports/esp8266/esp_mphal.h
@@ -48,9 +48,9 @@
 
 uint32_t mp_hal_ticks_us(void);
 __attribute__((always_inline)) static inline uint32_t mp_hal_ticks_cpu(void) {
-  uint32_t ccount;
-  __asm__ __volatile__("rsr %0,ccount":"=a" (ccount));
-  return ccount;
+    uint32_t ccount;
+    __asm__ __volatile__ ("rsr %0,ccount" : "=a" (ccount));
+    return ccount;
 }
 
 void mp_hal_delay_us(uint32_t);
@@ -86,16 +86,16 @@
 #define mp_hal_pin_od_low(p) do { \
         if ((p) == 16) { WRITE_PERI_REG(RTC_GPIO_ENABLE, (READ_PERI_REG(RTC_GPIO_ENABLE) & ~1) | 1); } \
         else { gpio_output_set(0, 1 << (p), 1 << (p), 0); } \
-    } while (0)
+} while (0)
 #define mp_hal_pin_od_high(p) do { \
         if ((p) == 16) { WRITE_PERI_REG(RTC_GPIO_ENABLE, (READ_PERI_REG(RTC_GPIO_ENABLE) & ~1)); } \
         else { gpio_output_set(0, 0, 0, 1 << (p)); /* set as input to avoid glitches */ } \
-    } while (0)
+} while (0)
 // The DHT driver requires using the open-drain feature of the GPIO to get it to work reliably
 #define mp_hal_pin_od_high_dht(p) do { \
         if ((p) == 16) { WRITE_PERI_REG(RTC_GPIO_ENABLE, (READ_PERI_REG(RTC_GPIO_ENABLE) & ~1)); } \
         else { gpio_output_set(1 << (p), 0, 1 << (p), 0); } \
-    } while (0)
+} while (0)
 #define mp_hal_pin_read(p) pin_get(p)
 #define mp_hal_pin_write(p, v) pin_set((p), (v))
 
diff --git a/ports/esp8266/espapa102.c b/ports/esp8266/espapa102.c
index 4295fe4..2bea266 100644
--- a/ports/esp8266/espapa102.c
+++ b/ports/esp8266/espapa102.c
@@ -33,7 +33,7 @@
 #include "user_interface.h"
 #include "espapa102.h"
 
-#define NOP asm volatile(" nop \n\t")
+#define NOP asm volatile (" nop \n\t")
 
 static inline void _esp_apa102_send_byte(uint32_t clockPinMask, uint32_t dataPinMask, uint8_t byte) {
     for (uint32_t i = 0; i < 8; i++) {
diff --git a/ports/esp8266/espneopixel.c b/ports/esp8266/espneopixel.c
index 6c76591..d2166a8 100644
--- a/ports/esp8266/espneopixel.c
+++ b/ports/esp8266/espneopixel.c
@@ -18,48 +18,58 @@
 
 void /*ICACHE_RAM_ATTR*/ esp_neopixel_write(uint8_t pin, uint8_t *pixels, uint32_t numBytes, bool is800KHz) {
 
-  uint8_t *p, *end, pix, mask;
-  uint32_t t, time0, time1, period, c, startTime, pinMask;
+    uint8_t *p, *end, pix, mask;
+    uint32_t t, time0, time1, period, c, startTime, pinMask;
 
-  pinMask   = 1 << pin;
-  p         =  pixels;
-  end       =  p + numBytes;
-  pix       = *p++;
-  mask      = 0x80;
-  startTime = 0;
+    pinMask = 1 << pin;
+    p = pixels;
+    end = p + numBytes;
+    pix = *p++;
+    mask = 0x80;
+    startTime = 0;
 
-  uint32_t fcpu = system_get_cpu_freq() * 1000000;
+    uint32_t fcpu = system_get_cpu_freq() * 1000000;
 
-#ifdef NEO_KHZ400
-  if(is800KHz) {
-#endif
-    time0  = fcpu / 2857143; // 0.35us
-    time1  = fcpu / 1250000; // 0.8us
-    period = fcpu /  800000; // 1.25us per bit
-#ifdef NEO_KHZ400
-  } else { // 400 KHz bitstream
-    time0  = fcpu / 2000000; // 0.5uS
-    time1  = fcpu /  833333; // 1.2us
-    period = fcpu /  400000; // 2.5us per bit
-  }
-#endif
+    #ifdef NEO_KHZ400
+    if (is800KHz) {
+    #endif
+    time0 = fcpu / 2857143;  // 0.35us
+    time1 = fcpu / 1250000;  // 0.8us
+    period = fcpu / 800000;  // 1.25us per bit
+    #ifdef NEO_KHZ400
+} else {   // 400 KHz bitstream
+    time0 = fcpu / 2000000;  // 0.5uS
+    time1 = fcpu / 833333;   // 1.2us
+    period = fcpu / 400000;  // 2.5us per bit
+}
+    #endif
 
-  uint32_t irq_state = mp_hal_quiet_timing_enter();
-  for(t = time0;; t = time0) {
-    if(pix & mask) 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
-    startTime = c;                                        // Save start time
-    while(((c = mp_hal_ticks_cpu()) - startTime) < t);      // Wait high duration
-    GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, pinMask);       // Set low
-    if(!(mask >>= 1)) {                                   // Next bit/byte
-      if(p >= end) break;
-      pix  = *p++;
-      mask = 0x80;
+    uint32_t irq_state = mp_hal_quiet_timing_enter();
+    for (t = time0;; t = time0) {
+        if (pix & mask) {
+            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
+        startTime = c;                                    // Save start time
+        while (((c = mp_hal_ticks_cpu()) - startTime) < t) {
+            ;                                               // Wait high duration
+        }
+        GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, pinMask);   // Set low
+        if (!(mask >>= 1)) {                              // Next bit/byte
+            if (p >= end) {
+                break;
+            }
+            pix = *p++;
+            mask = 0x80;
+        }
     }
-  }
-  while((mp_hal_ticks_cpu() - startTime) < period); // Wait for last bit
-  mp_hal_quiet_timing_exit(irq_state);
+    while ((mp_hal_ticks_cpu() - startTime) < period) {
+        ;                                           // Wait for last bit
+    }
+    mp_hal_quiet_timing_exit(irq_state);
 }
 
 #endif // MICROPY_ESP8266_NEOPIXEL
diff --git a/ports/esp8266/esppwm.c b/ports/esp8266/esppwm.c
index 33eaf3b..3759bb5 100644
--- a/ports/esp8266/esppwm.c
+++ b/ports/esp8266/esppwm.c
@@ -61,10 +61,10 @@
 //XXX: 0xffffffff/(80000000/16)=35A
 #define US_TO_RTC_TIMER_TICKS(t)          \
     ((t) ?                                   \
-     (((t) > 0x35A) ?                   \
-      (((t)>>2) * ((APB_CLK_FREQ>>4)/250000) + ((t)&0x3) * ((APB_CLK_FREQ>>4)/1000000))  :    \
-      (((t) *(APB_CLK_FREQ>>4)) / 1000000)) :    \
-     0)
+    (((t) > 0x35A) ?                   \
+    (((t) >> 2) * ((APB_CLK_FREQ >> 4) / 250000) + ((t) & 0x3) * ((APB_CLK_FREQ >> 4) / 1000000))  :    \
+    (((t) * (APB_CLK_FREQ >> 4)) / 1000000)) :    \
+    0)
 
 //FRC1
 #define FRC1_ENABLE_TIMER  BIT7
@@ -81,8 +81,7 @@
 } TIMER_INT_MODE;
 
 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;
 
     for (i = 1; i < n; i++) {
@@ -109,17 +108,16 @@
 STATIC volatile uint8 critical = 0;
 
 #define LOCK_PWM(c)  do {                       \
-    while( (c)==1 );                            \
-    (c) = 1;                                    \
+        while ( (c) == 1);                            \
+        (c) = 1;                                    \
 } while (0)
 
 #define UNLOCK_PWM(c) do {                      \
-    (c) = 0;                                    \
+        (c) = 0;                                    \
 } while (0)
 
 void ICACHE_FLASH_ATTR
-pwm_start(void)
-{
+pwm_start(void) {
     uint8 i, j;
     PWM_DBG("--Function pwm_start() is called\n");
     PWM_DBG("pwm_gpio:%x,pwm_channel_num:%d\n",pwm_gpio,pwm_channel_num);
@@ -169,7 +167,7 @@
     }
 
     // step 5: last channel needs to clean
-    local_single[*local_channel-1].gpio_clear = 0;
+    local_single[*local_channel - 1].gpio_clear = 0;
 
     // step 6: if first channel duty is 0, remove it
     if (local_single[0].h_time == 0) {
@@ -212,17 +210,17 @@
  * Returns      : NONE
 *******************************************************************************/
 void ICACHE_FLASH_ATTR
-pwm_set_duty(int16_t duty, uint8 channel)
-{
+pwm_set_duty(int16_t duty, uint8 channel) {
     uint8 i;
-    for(i=0;i<pwm_channel_num;i++){
-        if(pwm_out_io_num[i] == channel){
+    for (i = 0; i < pwm_channel_num; i++) {
+        if (pwm_out_io_num[i] == channel) {
             channel = i;
             break;
         }
     }
-    if(i==pwm_channel_num)      // non found
+    if (i == pwm_channel_num) {    // non found
         return;
+    }
 
     LOCK_PWM(critical);   // enter critical
     if (duty < 1) {
@@ -242,8 +240,7 @@
  * Returns      : NONE
 *******************************************************************************/
 void ICACHE_FLASH_ATTR
-pwm_set_freq(uint16 freq, uint8 channel)
-{
+pwm_set_freq(uint16 freq, uint8 channel) {
     LOCK_PWM(critical);   // enter critical
     if (freq > PWM_FREQ_MAX) {
         pwm.freq = PWM_FREQ_MAX;
@@ -264,17 +261,17 @@
  * Returns      : NONE
 *******************************************************************************/
 uint16 ICACHE_FLASH_ATTR
-pwm_get_duty(uint8 channel)
-{
+pwm_get_duty(uint8 channel) {
     uint8 i;
-    for(i=0;i<pwm_channel_num;i++){
-        if(pwm_out_io_num[i] == channel){
+    for (i = 0; i < pwm_channel_num; i++) {
+        if (pwm_out_io_num[i] == channel) {
             channel = i;
             break;
         }
     }
-    if(i==pwm_channel_num)      // non found
+    if (i == pwm_channel_num) {    // non found
         return 0;
+    }
 
     return pwm.duty[channel];
 }
@@ -286,8 +283,7 @@
  * Returns      : uint16 : pwm frequency
 *******************************************************************************/
 uint16 ICACHE_FLASH_ATTR
-pwm_get_freq(uint8 channel)
-{
+pwm_get_freq(uint8 channel) {
     return pwm.freq;
 }
 
@@ -299,8 +295,7 @@
  * Returns      : NONE
 *******************************************************************************/
 STATIC void ICACHE_RAM_ATTR
-pwm_tim1_intr_handler(void *dummy)
-{
+pwm_tim1_intr_handler(void *dummy) {
     (void)dummy;
     uint8 local_toggle = pwm_toggle;                        // pwm_toggle may change outside
     RTC_CLR_REG_MASK(FRC1_INT_ADDRESS, FRC1_INT_CLR_MASK);
@@ -310,17 +305,17 @@
         pwm_channel = &pwm_channel_toggle[local_toggle];
 
         gpio_output_set(pwm_single[*pwm_channel - 1].gpio_set,
-                        pwm_single[*pwm_channel - 1].gpio_clear,
-                        pwm_gpio,
-                        0);
+            pwm_single[*pwm_channel - 1].gpio_clear,
+            pwm_gpio,
+            0);
 
         pwm_current_channel = 0;
 
         RTC_REG_WRITE(FRC1_LOAD_ADDRESS, pwm_single[pwm_current_channel].h_time);
     } else {
         gpio_output_set(pwm_single[pwm_current_channel].gpio_set,
-                        pwm_single[pwm_current_channel].gpio_clear,
-                        pwm_gpio, 0);
+            pwm_single[pwm_current_channel].gpio_clear,
+            pwm_gpio, 0);
 
         pwm_current_channel++;
         RTC_REG_WRITE(FRC1_LOAD_ADDRESS, pwm_single[pwm_current_channel].h_time);
@@ -335,14 +330,13 @@
  * Returns      : NONE
 *******************************************************************************/
 void ICACHE_FLASH_ATTR
-pwm_init(void)
-{
+pwm_init(void) {
     uint8 i;
 
     RTC_REG_WRITE(FRC1_CTRL_ADDRESS,  //FRC2_AUTO_RELOAD|
-                  DIVDED_BY_16
-                  | FRC1_ENABLE_TIMER
-                  | TM_EDGE_INT);
+        DIVDED_BY_16
+        | FRC1_ENABLE_TIMER
+        | TM_EDGE_INT);
     RTC_REG_WRITE(FRC1_LOAD_ADDRESS, 0);
 
     for (i = 0; i < PWM_CHANNEL; i++) {
@@ -359,7 +353,7 @@
 }
 
 int ICACHE_FLASH_ATTR
-pwm_add(uint8_t pin_id, uint32_t pin_mux, uint32_t pin_func){
+pwm_add(uint8_t pin_id, uint32_t pin_mux, uint32_t pin_func) {
     PWM_DBG("--Function pwm_add() is called. channel:%d\n", channel);
     PWM_DBG("pwm_gpio:%x,pwm_channel_num:%d\n",pwm_gpio,pwm_channel_num);
     PWM_DBG("pwm_out_io_num[0]:%d,[1]:%d,[2]:%d\n",pwm_out_io_num[0],pwm_out_io_num[1],pwm_out_io_num[2]);
@@ -375,16 +369,17 @@
         return -1;
     }
     uint8 i;
-    for(i=0;i<PWM_CHANNEL;i++){
-        if(pwm_out_io_num[i]==channel)  // already exist
+    for (i = 0; i < PWM_CHANNEL; i++) {
+        if (pwm_out_io_num[i] == channel) { // already exist
             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
             pwm_out_io_num[i] = channel;
             pwm.duty[i] = 0;
             pwm_gpio |= (1 << pin_num[channel]);
             PIN_FUNC_SELECT(pin_mux, pin_func);
-            GPIO_REG_WRITE(GPIO_PIN_ADDR(GPIO_ID_PIN(pin_num[channel])), GPIO_REG_READ(GPIO_PIN_ADDR(GPIO_ID_PIN(pin_num[channel]))) & (~ GPIO_PIN_PAD_DRIVER_SET(GPIO_PAD_DRIVER_ENABLE))); //disable open drain;
+            GPIO_REG_WRITE(GPIO_PIN_ADDR(GPIO_ID_PIN(pin_num[channel])), GPIO_REG_READ(GPIO_PIN_ADDR(GPIO_ID_PIN(pin_num[channel]))) & (~GPIO_PIN_PAD_DRIVER_SET(GPIO_PAD_DRIVER_ENABLE)));  //disable open drain;
             pwm_channel_num++;
             UNLOCK_PWM(critical);   // leave critical
             return channel;
@@ -394,23 +389,23 @@
 }
 
 bool ICACHE_FLASH_ATTR
-pwm_delete(uint8 channel){
+pwm_delete(uint8 channel) {
     PWM_DBG("--Function pwm_delete() is called. channel:%d\n", channel);
     PWM_DBG("pwm_gpio:%x,pwm_channel_num:%d\n",pwm_gpio,pwm_channel_num);
     PWM_DBG("pwm_out_io_num[0]:%d,[1]:%d,[2]:%d\n",pwm_out_io_num[0],pwm_out_io_num[1],pwm_out_io_num[2]);
     PWM_DBG("pwm.duty[0]:%d,[1]:%d,[2]:%d\n",pwm.duty[0],pwm.duty[1],pwm.duty[2]);
     uint8 i,j;
-    for(i=0;i<pwm_channel_num;i++){
-        if(pwm_out_io_num[i]==channel){  // exist
+    for (i = 0; i < pwm_channel_num; i++) {
+        if (pwm_out_io_num[i] == channel) { // exist
             LOCK_PWM(critical);   // enter critical
             pwm_out_io_num[i] = -1;
             pwm_gpio &= ~(1 << pin_num[channel]);   //clear the bit
-            for(j=i;j<pwm_channel_num-1;j++){
-                pwm_out_io_num[j] = pwm_out_io_num[j+1];
-                pwm.duty[j] = pwm.duty[j+1];
+            for (j = i; j < pwm_channel_num - 1; j++) {
+                pwm_out_io_num[j] = pwm_out_io_num[j + 1];
+                pwm.duty[j] = pwm.duty[j + 1];
             }
-            pwm_out_io_num[pwm_channel_num-1] = -1;
-            pwm.duty[pwm_channel_num-1] = 0;
+            pwm_out_io_num[pwm_channel_num - 1] = -1;
+            pwm.duty[pwm_channel_num - 1] = 0;
             pwm_channel_num--;
             UNLOCK_PWM(critical);   // leave critical
             return true;
diff --git a/ports/esp8266/ets_alt_task.c b/ports/esp8266/ets_alt_task.c
index 0b1615d..ce27758 100644
--- a/ports/esp8266/ets_alt_task.c
+++ b/ports/esp8266/ets_alt_task.c
@@ -25,9 +25,9 @@
 static void *idle_arg;
 
 #if ESP_SDK_VERSION >= 010500
-# define FIRST_PRIO 0
+#define FIRST_PRIO 0
 #else
-# define FIRST_PRIO 0x14
+#define FIRST_PRIO 0x14
 #endif
 #define LAST_PRIO 0x20
 #define PRIO2ID(prio) ((prio) - FIRST_PRIO)
@@ -38,7 +38,9 @@
     int id = PRIO2ID(prio);
     if (id < 0 || id >= MP_ARRAY_SIZE(emu_tasks)) {
         printf("task prio out of range: %d\n", prio);
-        while (1);
+        while (1) {
+            ;
+        }
     }
     return id;
 }
@@ -62,9 +64,9 @@
 bool ets_task(os_task_t task, uint8 prio, os_event_t *queue, uint8 qlen) {
     static unsigned cnt;
     printf("#%d ets_task(%p, %d, %p, %d)\n", cnt++, task, prio, queue, qlen);
-#if USE_ETS_TASK
+    #if USE_ETS_TASK
     return _ets_task(task, prio, queue, qlen);
-#else
+    #else
     int id = prio2id(prio);
     emu_tasks[id].task = task;
     emu_tasks[id].queue = queue;
@@ -72,14 +74,14 @@
     emu_tasks[id].i_get = 0;
     emu_tasks[id].i_put = 0;
     return true;
-#endif
+    #endif
 }
 
 bool ets_post(uint8 prio, os_signal_t sig, os_param_t param) {
 //    static unsigned cnt; printf("#%d ets_post(%d, %x, %x)\n", cnt++, prio, sig, param);
-#if USE_ETS_TASK
+    #if USE_ETS_TASK
     return _ets_post(prio, sig, param);
-#else
+    #else
     ets_intr_lock();
 
     const int id = prio2id(prio);
@@ -105,7 +107,7 @@
     ets_intr_unlock();
 
     return 0;
-#endif
+    #endif
 }
 
 int ets_loop_iter_disable = 0;
@@ -193,7 +195,7 @@
     ets_isr_attach(10, my_timer_isr, NULL);
     SET_PERI_REG_MASK(0x3FF00004, 4);
     ETS_INTR_ENABLE(10);
-    ets_task((os_task_t)0x40002E3C, 0x1f, (os_event_t*)0x3FFFDDC0, 4);
+    ets_task((os_task_t)0x40002E3C, 0x1f, (os_event_t *)0x3FFFDDC0, 4);
 
     WRITE_PERI_REG(PERIPHS_TIMER_BASEDDR + 0x30, 0);
     WRITE_PERI_REG(PERIPHS_TIMER_BASEDDR + 0x28, 0x88);
@@ -203,19 +205,19 @@
 #endif
 
 bool ets_run(void) {
-#if USE_ETS_TASK
+    #if USE_ETS_TASK
     #if SDK_BELOW_1_1_1
     ets_isr_attach(10, my_timer_isr, NULL);
     #endif
     _ets_run();
-#else
+    #else
 //    ets_timer_init();
-    *(char*)0x3FFFC6FC = 0;
+    *(char *)0x3FFFC6FC = 0;
     ets_intr_lock();
     printf("ets_alt_task: ets_run\n");
-#if DEBUG
+    #if DEBUG
     dump_tasks();
-#endif
+    #endif
     ets_intr_unlock();
     while (1) {
         if (!ets_loop_iter()) {
@@ -224,11 +226,11 @@
             if (idle_cb) {
                 idle_cb(idle_arg);
             }
-            asm("waiti 0");
+            asm ("waiti 0");
             ets_intr_unlock();
         }
     }
-#endif
+    #endif
 }
 
 void ets_set_idle_cb(void (*handler)(void *), void *arg) {
diff --git a/ports/esp8266/etshal.h b/ports/esp8266/etshal.h
index 8d64573..f7b34b8 100644
--- a/ports/esp8266/etshal.h
+++ b/ports/esp8266/etshal.h
@@ -4,7 +4,7 @@
 #include <os_type.h>
 
 // see http://esp8266-re.foogod.com/wiki/Random_Number_Generator
-#define WDEV_HWRNG ((volatile uint32_t*)0x3ff20e44)
+#define WDEV_HWRNG ((volatile uint32_t *)0x3ff20e44)
 
 void ets_delay_us(uint16_t us);
 void ets_intr_lock(void);
diff --git a/ports/esp8266/fatfs_port.c b/ports/esp8266/fatfs_port.c
index a8865c8..8cef0ac 100644
--- a/ports/esp8266/fatfs_port.c
+++ b/ports/esp8266/fatfs_port.c
@@ -38,6 +38,6 @@
     timeutils_struct_time_t 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) |
-           ((DWORD)tm.tm_hour << 11) | ((DWORD)tm.tm_min << 5) | ((DWORD)tm.tm_sec >> 1));
+    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);
 }
diff --git a/ports/esp8266/gccollect.c b/ports/esp8266/gccollect.c
index dbe7bc1..3618a56 100644
--- a/ports/esp8266/gccollect.c
+++ b/ports/esp8266/gccollect.c
@@ -44,7 +44,7 @@
     mp_uint_t sp = gc_helper_get_regs_and_sp(regs);
 
     // trace the stack, including the registers (since they live on the stack in this function)
-    gc_collect_root((void**)sp, (STACK_END - sp) / sizeof(uint32_t));
+    gc_collect_root((void **)sp, (STACK_END - sp) / sizeof(uint32_t));
 
     // end the GC
     gc_collect_end();
diff --git a/ports/esp8266/help.c b/ports/esp8266/help.c
index 0a851f4..4dd586c 100644
--- a/ports/esp8266/help.c
+++ b/ports/esp8266/help.c
@@ -27,28 +27,28 @@
 #include "py/builtin.h"
 
 const char esp_help_text[] =
-"Welcome to MicroPython!\n"
-"\n"
-"For online docs please visit http://docs.micropython.org/en/latest/esp8266/ .\n"
-"For diagnostic information to include in bug reports execute 'import port_diag'.\n"
-"\n"
-"Basic WiFi configuration:\n"
-"\n"
-"import network\n"
-"sta_if = network.WLAN(network.STA_IF); sta_if.active(True)\n"
-"sta_if.scan()                             # Scan for available access points\n"
-"sta_if.connect(\"<AP_name>\", \"<password>\") # Connect to an AP\n"
-"sta_if.isconnected()                      # Check for successful connection\n"
-"# Change name/password of ESP8266's AP:\n"
-"ap_if = network.WLAN(network.AP_IF)\n"
-"ap_if.config(essid=\"<AP_NAME>\", authmode=network.AUTH_WPA_WPA2_PSK, password=\"<password>\")\n"
-"\n"
-"Control commands:\n"
-"  CTRL-A        -- on a blank line, enter raw REPL mode\n"
-"  CTRL-B        -- on a blank line, enter normal REPL mode\n"
-"  CTRL-C        -- interrupt a running program\n"
-"  CTRL-D        -- on a blank line, do a soft reset of the board\n"
-"  CTRL-E        -- on a blank line, enter paste mode\n"
-"\n"
-"For further help on a specific object, type help(obj)\n"
+    "Welcome to MicroPython!\n"
+    "\n"
+    "For online docs please visit http://docs.micropython.org/en/latest/esp8266/ .\n"
+    "For diagnostic information to include in bug reports execute 'import port_diag'.\n"
+    "\n"
+    "Basic WiFi configuration:\n"
+    "\n"
+    "import network\n"
+    "sta_if = network.WLAN(network.STA_IF); sta_if.active(True)\n"
+    "sta_if.scan()                             # Scan for available access points\n"
+    "sta_if.connect(\"<AP_name>\", \"<password>\") # Connect to an AP\n"
+    "sta_if.isconnected()                      # Check for successful connection\n"
+    "# Change name/password of ESP8266's AP:\n"
+    "ap_if = network.WLAN(network.AP_IF)\n"
+    "ap_if.config(essid=\"<AP_NAME>\", authmode=network.AUTH_WPA_WPA2_PSK, password=\"<password>\")\n"
+    "\n"
+    "Control commands:\n"
+    "  CTRL-A        -- on a blank line, enter raw REPL mode\n"
+    "  CTRL-B        -- on a blank line, enter normal REPL mode\n"
+    "  CTRL-C        -- interrupt a running program\n"
+    "  CTRL-D        -- on a blank line, do a soft reset of the board\n"
+    "  CTRL-E        -- on a blank line, enter paste mode\n"
+    "\n"
+    "For further help on a specific object, type help(obj)\n"
 ;
diff --git a/ports/esp8266/hspi.c b/ports/esp8266/hspi.c
index 554a504..cecf0b7 100644
--- a/ports/esp8266/hspi.c
+++ b/ports/esp8266/hspi.c
@@ -36,7 +36,7 @@
     spi_tx_byte_order(spi_no, SPI_BYTE_ORDER_HIGH_TO_LOW);
     spi_rx_byte_order(spi_no, SPI_BYTE_ORDER_HIGH_TO_LOW);
 
-    SET_PERI_REG_MASK(SPI_USER(spi_no), SPI_CS_SETUP|SPI_CS_HOLD);
+    SET_PERI_REG_MASK(SPI_USER(spi_no), SPI_CS_SETUP | SPI_CS_HOLD);
     CLEAR_PERI_REG_MASK(SPI_USER(spi_no), SPI_FLASH_MODE);
 }
 
@@ -84,14 +84,14 @@
     }
     if (spi_no == SPI) {
         // Set bit 8 if 80MHz sysclock required
-        WRITE_PERI_REG(PERIPHS_IO_MUX, 0x005 | (clock_div_flag<<8));
+        WRITE_PERI_REG(PERIPHS_IO_MUX, 0x005 | (clock_div_flag << 8));
         PIN_FUNC_SELECT(PERIPHS_IO_MUX_SD_CLK_U, 1);
         PIN_FUNC_SELECT(PERIPHS_IO_MUX_SD_CMD_U, 1);
         PIN_FUNC_SELECT(PERIPHS_IO_MUX_SD_DATA0_U, 1);
         PIN_FUNC_SELECT(PERIPHS_IO_MUX_SD_DATA1_U, 1);
     } else if (spi_no == HSPI) {
         // Set bit 9 if 80MHz sysclock required
-        WRITE_PERI_REG(PERIPHS_IO_MUX, 0x105 | (clock_div_flag<<9));
+        WRITE_PERI_REG(PERIPHS_IO_MUX, 0x105 | (clock_div_flag << 9));
         // GPIO12 is HSPI MISO pin (Master Data In)
         PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTDI_U, 2);
         // GPIO13 is HSPI MOSI pin (Master Data Out)
@@ -117,11 +117,11 @@
         WRITE_PERI_REG(SPI_CLOCK(spi_no), SPI_CLK_EQU_SYSCLK);
     } else {
         WRITE_PERI_REG(SPI_CLOCK(spi_no),
-           (((prediv - 1) & SPI_CLKDIV_PRE) << SPI_CLKDIV_PRE_S) |
-           (((cntdiv - 1) & SPI_CLKCNT_N) << SPI_CLKCNT_N_S) |
-           (((cntdiv >> 1) & SPI_CLKCNT_H) << SPI_CLKCNT_H_S) |
-           ((0 & SPI_CLKCNT_L) << SPI_CLKCNT_L_S)
-        );
+            (((prediv - 1) & SPI_CLKDIV_PRE) << SPI_CLKDIV_PRE_S) |
+            (((cntdiv - 1) & SPI_CLKCNT_N) << SPI_CLKCNT_N_S) |
+            (((cntdiv >> 1) & SPI_CLKCNT_H) << SPI_CLKCNT_H_S) |
+            ((0 & SPI_CLKCNT_L) << SPI_CLKCNT_L_S)
+            );
     }
 }
 
@@ -185,15 +185,17 @@
 (for anything <32 bits).
 */
 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 dout_bits, uint32_t dout_data,
-                         uint32_t din_bits, uint32_t dummy_bits) {
-    while (spi_busy(spi_no)) {};  // Wait for SPI to be ready
+    uint32_t addr_bits, uint32_t addr_data,
+    uint32_t dout_bits, uint32_t dout_data,
+    uint32_t din_bits, uint32_t dummy_bits) {
+    while (spi_busy(spi_no)) {
+    }
+    ;                             // Wait for SPI to be ready
 
 // Enable SPI Functions
     // Disable MOSI, MISO, ADDR, COMMAND, DUMMY in case previously set.
     CLEAR_PERI_REG_MASK(SPI_USER(spi_no), SPI_USR_MOSI | SPI_USR_MISO |
-                        SPI_USR_COMMAND | SPI_USR_ADDR | SPI_USR_DUMMY);
+        SPI_USR_COMMAND | SPI_USR_ADDR | SPI_USR_DUMMY);
 
     // Enable functions based on number of bits. 0 bits = disabled.
     // This is rather inefficient but allows for a very generic function.
@@ -213,25 +215,25 @@
     WRITE_PERI_REG(SPI_USER1(spi_no),
         // Number of bits in Address
         ((addr_bits - 1) & SPI_USR_ADDR_BITLEN) << SPI_USR_ADDR_BITLEN_S |
-        // Number of bits to Send
-        ((dout_bits - 1) & SPI_USR_MOSI_BITLEN) << SPI_USR_MOSI_BITLEN_S |
-        // Number of bits to receive
-        ((din_bits - 1) & SPI_USR_MISO_BITLEN) << SPI_USR_MISO_BITLEN_S |
-        // Number of Dummy bits to insert
-        ((dummy_bits - 1) & SPI_USR_DUMMY_CYCLELEN) << SPI_USR_DUMMY_CYCLELEN_S);
+            // Number of bits to Send
+                ((dout_bits - 1) & SPI_USR_MOSI_BITLEN) << SPI_USR_MOSI_BITLEN_S |
+            // Number of bits to receive
+                ((din_bits - 1) & SPI_USR_MISO_BITLEN) << SPI_USR_MISO_BITLEN_S |
+            // Number of Dummy bits to insert
+                ((dummy_bits - 1) & SPI_USR_DUMMY_CYCLELEN) << SPI_USR_DUMMY_CYCLELEN_S);
 
 // Setup Command Data
     if (cmd_bits) {
         // Enable COMMAND function in SPI module
         SET_PERI_REG_MASK(SPI_USER(spi_no), SPI_USR_COMMAND);
         // Align command data to high bits
-        uint16_t command = cmd_data << (16-cmd_bits);
+        uint16_t command = cmd_data << (16 - cmd_bits);
         // Swap byte order
-        command = ((command>>8)&0xff) | ((command<<8)&0xff00);
+        command = ((command >> 8) & 0xff) | ((command << 8) & 0xff00);
         WRITE_PERI_REG(SPI_USER2(spi_no), (
             (((cmd_bits - 1) & SPI_USR_COMMAND_BITLEN) << SPI_USR_COMMAND_BITLEN_S) |
             (command & SPI_USR_COMMAND_VALUE)
-        ));
+            ));
     }
 
 // Setup Address Data
@@ -246,42 +248,44 @@
     if (dout_bits) {
         // Enable MOSI function in SPI module
         SET_PERI_REG_MASK(SPI_USER(spi_no), SPI_USR_MOSI);
-    // Copy data to W0
-    if (READ_PERI_REG(SPI_USER(spi_no))&SPI_WR_BYTE_ORDER) {
-        WRITE_PERI_REG(SPI_W0(spi_no), dout_data << (32 - dout_bits));
-    } else {
-        uint8_t dout_extra_bits = dout_bits%8;
-
-        if (dout_extra_bits) {
-            // If your data isn't a byte multiple (8/16/24/32 bits) and you
-            // don't have SPI_WR_BYTE_ORDER set, you need this to move the
-            // non-8bit remainder to the MSBs. Not sure if there's even a use
-            // case for this, but it's here if you need it... For example,
-            // 0xDA4 12 bits without SPI_WR_BYTE_ORDER would usually be output
-            // as if it were 0x0DA4, of which 0xA4, and then 0x0 would be
-            // shifted out (first 8 bits of low byte, then 4 MSB bits of high
-            // byte - ie reverse byte order).
-            // The code below shifts it out as 0xA4 followed by 0xD as you
-            // might require.
-            WRITE_PERI_REG(SPI_W0(spi_no), (
-                (0xFFFFFFFF << (dout_bits - dout_extra_bits) & dout_data)
-                    << (8-dout_extra_bits) |
-                ((0xFFFFFFFF >> (32 - (dout_bits - dout_extra_bits)))
-                    & dout_data)
-            ));
+        // Copy data to W0
+        if (READ_PERI_REG(SPI_USER(spi_no)) & SPI_WR_BYTE_ORDER) {
+            WRITE_PERI_REG(SPI_W0(spi_no), dout_data << (32 - dout_bits));
         } else {
-            WRITE_PERI_REG(SPI_W0(spi_no), dout_data);
+            uint8_t dout_extra_bits = dout_bits % 8;
+
+            if (dout_extra_bits) {
+                // If your data isn't a byte multiple (8/16/24/32 bits) and you
+                // don't have SPI_WR_BYTE_ORDER set, you need this to move the
+                // non-8bit remainder to the MSBs. Not sure if there's even a use
+                // case for this, but it's here if you need it... For example,
+                // 0xDA4 12 bits without SPI_WR_BYTE_ORDER would usually be output
+                // as if it were 0x0DA4, of which 0xA4, and then 0x0 would be
+                // shifted out (first 8 bits of low byte, then 4 MSB bits of high
+                // byte - ie reverse byte order).
+                // The code below shifts it out as 0xA4 followed by 0xD as you
+                // might require.
+                WRITE_PERI_REG(SPI_W0(spi_no), (
+                    (0xFFFFFFFF << (dout_bits - dout_extra_bits) & dout_data)
+                        << (8 - dout_extra_bits) |
+                            ((0xFFFFFFFF >> (32 - (dout_bits - dout_extra_bits)))
+                        & dout_data)
+                    ));
+            } else {
+                WRITE_PERI_REG(SPI_W0(spi_no), dout_data);
+            }
         }
     }
-}
 
 // Begin SPI Transaction
     SET_PERI_REG_MASK(SPI_CMD(spi_no), SPI_USR);
 
 // Return DIN data
     if (din_bits) {
-        while (spi_busy(spi_no)) {}; // Wait for SPI transaction to complete
-        if (READ_PERI_REG(SPI_USER(spi_no))&SPI_RD_BYTE_ORDER) {
+        while (spi_busy(spi_no)) {
+        }
+        ;                            // Wait for SPI transaction to complete
+        if (READ_PERI_REG(SPI_USER(spi_no)) & SPI_RD_BYTE_ORDER) {
             // Assuming data in is written to MSB. TBC
             return READ_PERI_REG(SPI_W0(spi_no)) >> (32 - din_bits);
         } else {
@@ -301,19 +305,21 @@
 Just do minimal work needed to send 8 bits.
 */
 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
     // Disable MOSI, MISO, ADDR, COMMAND, DUMMY in case previously set.
     CLEAR_PERI_REG_MASK(SPI_USER(spi_no), SPI_USR_MOSI | SPI_USR_MISO |
-                        SPI_USR_COMMAND | SPI_USR_ADDR | SPI_USR_DUMMY);
+        SPI_USR_COMMAND | SPI_USR_ADDR | SPI_USR_DUMMY);
 
 // Setup Bitlengths
     WRITE_PERI_REG(SPI_USER1(spi_no),
         // Number of bits to Send
         ((8 - 1) & SPI_USR_MOSI_BITLEN) << SPI_USR_MOSI_BITLEN_S |
-        // Number of bits to receive
-        ((8 - 1) & SPI_USR_MISO_BITLEN) << SPI_USR_MISO_BITLEN_S);
+            // Number of bits to receive
+                ((8 - 1) & SPI_USR_MISO_BITLEN) << SPI_USR_MISO_BITLEN_S);
 
 
 // Setup DOUT data
diff --git a/ports/esp8266/hspi.h b/ports/esp8266/hspi.h
index c68366e..aae9840 100644
--- a/ports/esp8266/hspi.h
+++ b/ports/esp8266/hspi.h
@@ -58,13 +58,13 @@
 void spi_tx_byte_order(uint8_t spi_no, uint8_t byte_order);
 void spi_rx_byte_order(uint8_t spi_no, uint8_t byte_order);
 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 dout_bits, uint32_t dout_data,
-                         uint32_t din_bits, uint32_t dummy_bits);
+    uint32_t addr_bits, uint32_t addr_data,
+    uint32_t dout_bits, uint32_t dout_data,
+    uint32_t din_bits, uint32_t dummy_bits);
 void spi_tx8fast(uint8_t spi_no, uint8_t dout_data);
 
 // Expansion Macros
-#define spi_busy(spi_no) READ_PERI_REG(SPI_CMD(spi_no))&SPI_USR
+#define spi_busy(spi_no) READ_PERI_REG(SPI_CMD(spi_no)) & SPI_USR
 
 #define spi_txd(spi_no, bits, data) spi_transaction(spi_no, 0, 0, 0, 0, bits, (uint32_t) data, 0, 0)
 #define spi_tx8(spi_no, data)       spi_transaction(spi_no, 0, 0, 0, 0, 8,    (uint32_t) data, 0, 0)
diff --git a/ports/esp8266/lexerstr32.c b/ports/esp8266/lexerstr32.c
index 6fb84bb..a921efb 100644
--- a/ports/esp8266/lexerstr32.c
+++ b/ports/esp8266/lexerstr32.c
@@ -36,7 +36,7 @@
 } mp_lexer_str32_buf_t;
 
 STATIC mp_uint_t str32_buf_next_byte(void *sb_in) {
-    mp_lexer_str32_buf_t *sb = (mp_lexer_str32_buf_t*)sb_in;
+    mp_lexer_str32_buf_t *sb = (mp_lexer_str32_buf_t *)sb_in;
     byte c = sb->val & 0xff;
     if (c == 0) {
         return MP_READER_EOF;
@@ -53,14 +53,14 @@
 }
 
 STATIC void str32_buf_free(void *sb_in) {
-    mp_lexer_str32_buf_t *sb = (mp_lexer_str32_buf_t*)sb_in;
+    mp_lexer_str32_buf_t *sb = (mp_lexer_str32_buf_t *)sb_in;
     m_del_obj(mp_lexer_str32_buf_t, sb);
 }
 
 mp_lexer_t *mp_lexer_new_from_str32(qstr src_name, const char *str, mp_uint_t len, mp_uint_t free_len) {
     mp_lexer_str32_buf_t *sb = m_new_obj(mp_lexer_str32_buf_t);
     sb->byte_off = (uint32_t)str & 3;
-    sb->src_cur = (uint32_t*)(str - sb->byte_off);
+    sb->src_cur = (uint32_t *)(str - sb->byte_off);
     sb->val = *sb->src_cur++ >> sb->byte_off * 8;
     mp_reader_t reader = {sb, str32_buf_next_byte, str32_buf_free};
     return mp_lexer_new(src_name, reader);
diff --git a/ports/esp8266/machine_adc.c b/ports/esp8266/machine_adc.c
index 2318239..b0b458a 100644
--- a/ports/esp8266/machine_adc.c
+++ b/ports/esp8266/machine_adc.c
@@ -59,12 +59,12 @@
     mp_int_t chn = mp_obj_get_int(args[0]);
 
     switch (chn) {
-    case 0:
-        return &machine_adc_adc;
-    case 1:
-        return &machine_adc_vdd3;
-    default:
-        mp_raise_msg_varg(&mp_type_ValueError, "ADC(%d) doesn't exist", chn);
+        case 0:
+            return &machine_adc_adc;
+        case 1:
+            return &machine_adc_vdd3;
+        default:
+            mp_raise_msg_varg(&mp_type_ValueError, "ADC(%d) doesn't exist", chn);
     }
 }
 
@@ -94,5 +94,5 @@
     .name = MP_QSTR_ADC,
     .print = machine_adc_print,
     .make_new = machine_adc_make_new,
-    .locals_dict = (mp_obj_dict_t*)&machine_adc_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&machine_adc_locals_dict,
 };
diff --git a/ports/esp8266/machine_hspi.c b/ports/esp8266/machine_hspi.c
index 07770c8..11c95a3 100644
--- a/ports/esp8266/machine_hspi.c
+++ b/ports/esp8266/machine_hspi.c
@@ -101,7 +101,7 @@
 }
 
 STATIC void machine_hspi_init(mp_obj_base_t *self_in, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
-    machine_hspi_obj_t *self = (machine_hspi_obj_t*)self_in;
+    machine_hspi_obj_t *self = (machine_hspi_obj_t *)self_in;
 
     enum { ARG_baudrate, ARG_polarity, ARG_phase };
     static const mp_arg_t allowed_args[] = {
@@ -111,7 +111,7 @@
     };
     mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
     mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args),
-                     allowed_args, args);
+        allowed_args, args);
 
     if (args[ARG_baudrate].u_int != -1) {
         self->baudrate = args[ARG_baudrate].u_int;
@@ -143,10 +143,10 @@
     spi_tx_byte_order(HSPI, SPI_BYTE_ORDER_HIGH_TO_LOW);
     spi_rx_byte_order(HSPI, SPI_BYTE_ORDER_HIGH_TO_LOW);
     CLEAR_PERI_REG_MASK(SPI_USER(HSPI), SPI_FLASH_MODE | SPI_USR_MISO |
-                        SPI_USR_ADDR | SPI_USR_COMMAND | SPI_USR_DUMMY);
+        SPI_USR_ADDR | SPI_USR_COMMAND | SPI_USR_DUMMY);
     // Clear Dual or Quad lines transmission mode
     CLEAR_PERI_REG_MASK(SPI_CTRL(HSPI), SPI_QIO_MODE | SPI_DIO_MODE |
-                        SPI_DOUT_MODE | SPI_QOUT_MODE);
+        SPI_DOUT_MODE | SPI_QOUT_MODE);
     spi_mode(HSPI, self->phase, self->polarity);
 }
 
@@ -165,7 +165,7 @@
     self->phase = 0;
     mp_map_t kw_args;
     mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
-    machine_hspi_init((mp_obj_base_t*)self, n_args - 1, args + 1, &kw_args);
+    machine_hspi_init((mp_obj_base_t *)self, n_args - 1, args + 1, &kw_args);
     return MP_OBJ_FROM_PTR(self);
 }
 
@@ -180,7 +180,7 @@
     .print = machine_hspi_print,
     .make_new = mp_machine_spi_make_new, // delegate to master constructor
     .protocol = &machine_hspi_p,
-    .locals_dict = (mp_obj_dict_t*)&mp_machine_spi_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&mp_machine_spi_locals_dict,
 };
 
 #endif // MICROPY_PY_MACHINE_SPI
diff --git a/ports/esp8266/machine_pin.c b/ports/esp8266/machine_pin.c
index 1200aa9..c77bd55 100644
--- a/ports/esp8266/machine_pin.c
+++ b/ports/esp8266/machine_pin.c
@@ -43,8 +43,8 @@
     GPIO_PIN_INT_TYPE_GET(GPIO_REG_READ(GPIO_PIN_ADDR(phys_port)))
 #define SET_TRIGGER(phys_port, trig) \
     (GPIO_REG_WRITE(GPIO_PIN_ADDR(phys_port), \
-        (GPIO_REG_READ(GPIO_PIN_ADDR(phys_port)) & ~GPIO_PIN_INT_TYPE_MASK) \
-        | GPIO_PIN_INT_TYPE_SET(trig))) \
+    (GPIO_REG_READ(GPIO_PIN_ADDR(phys_port)) & ~GPIO_PIN_INT_TYPE_MASK) \
+    | GPIO_PIN_INT_TYPE_SET(trig))) \
 
 #define GPIO_MODE_INPUT (0)
 #define GPIO_MODE_OUTPUT (1)
@@ -315,7 +315,7 @@
     int wanted_pin = mp_obj_get_int(args[0]);
     pyb_pin_obj_t *pin = NULL;
     if (0 <= wanted_pin && wanted_pin < MP_ARRAY_SIZE(pyb_pin_obj)) {
-        pin = (pyb_pin_obj_t*)&pyb_pin_obj[wanted_pin];
+        pin = (pyb_pin_obj_t *)&pyb_pin_obj[wanted_pin];
     }
     if (pin == NULL || pin->base.type == NULL) {
         mp_raise_ValueError("invalid pin");
@@ -458,7 +458,7 @@
     .make_new = mp_pin_make_new,
     .call = pyb_pin_call,
     .protocol = &pin_pin_p,
-    .locals_dict = (mp_obj_dict_t*)&pyb_pin_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_pin_locals_dict,
 };
 
 /******************************************************************************/
@@ -514,5 +514,5 @@
     { &mp_type_type },
     .name = MP_QSTR_IRQ,
     .call = pin_irq_call,
-    .locals_dict = (mp_obj_dict_t*)&pin_irq_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pin_irq_locals_dict,
 };
diff --git a/ports/esp8266/machine_pwm.c b/ports/esp8266/machine_pwm.c
index 6bf8fc9..5325580 100644
--- a/ports/esp8266/machine_pwm.c
+++ b/ports/esp8266/machine_pwm.c
@@ -166,5 +166,5 @@
     .name = MP_QSTR_PWM,
     .print = pyb_pwm_print,
     .make_new = pyb_pwm_make_new,
-    .locals_dict = (mp_obj_dict_t*)&pyb_pwm_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_pwm_locals_dict,
 };
diff --git a/ports/esp8266/machine_rtc.c b/ports/esp8266/machine_rtc.c
index bbfc172..3df2dfc 100644
--- a/ports/esp8266/machine_rtc.c
+++ b/ports/esp8266/machine_rtc.c
@@ -266,5 +266,5 @@
     { &mp_type_type },
     .name = MP_QSTR_RTC,
     .make_new = pyb_rtc_make_new,
-    .locals_dict = (mp_obj_dict_t*)&pyb_rtc_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_rtc_locals_dict,
 };
diff --git a/ports/esp8266/machine_uart.c b/ports/esp8266/machine_uart.c
index e4f77fb..735e01b 100644
--- a/ports/esp8266/machine_uart.c
+++ b/ports/esp8266/machine_uart.c
@@ -268,7 +268,7 @@
         *buf++ = uart_rx_char();
         if (--size == 0 || !uart_rx_wait(self->timeout_char * 1000)) {
             // return number of bytes read
-            return buf - (uint8_t*)buf_in;
+            return buf - (uint8_t *)buf_in;
         }
     }
 }
@@ -328,5 +328,5 @@
     .getiter = mp_identity_getiter,
     .iternext = mp_stream_unbuffered_iter,
     .protocol = &uart_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&pyb_uart_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_uart_locals_dict,
 };
diff --git a/ports/esp8266/machine_wdt.c b/ports/esp8266/machine_wdt.c
index fad0b2e..9411e31 100644
--- a/ports/esp8266/machine_wdt.c
+++ b/ports/esp8266/machine_wdt.c
@@ -49,12 +49,12 @@
     }
 
     switch (id) {
-    case 0:
-        ets_loop_dont_feed_sw_wdt = 1;
-        system_soft_wdt_feed();
-        return &wdt_default;
-    default:
-        mp_raise_ValueError(NULL);
+        case 0:
+            ets_loop_dont_feed_sw_wdt = 1;
+            system_soft_wdt_feed();
+            return &wdt_default;
+        default:
+            mp_raise_ValueError(NULL);
     }
 }
 
@@ -82,5 +82,5 @@
     { &mp_type_type },
     .name = MP_QSTR_WDT,
     .make_new = machine_wdt_make_new,
-    .locals_dict = (mp_obj_dict_t*)&machine_wdt_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&machine_wdt_locals_dict,
 };
diff --git a/ports/esp8266/main.c b/ports/esp8266/main.c
index 8bfb2a0..aff5936 100644
--- a/ports/esp8266/main.c
+++ b/ports/esp8266/main.c
@@ -47,7 +47,7 @@
 STATIC char heap[38 * 1024];
 
 STATIC void mp_reset(void) {
-    mp_stack_set_top((void*)0x40000000);
+    mp_stack_set_top((void *)0x40000000);
     mp_stack_set_limit(8192);
     mp_hal_init();
     gc_init(heap, heap + sizeof(heap));
diff --git a/ports/esp8266/makeimg.py b/ports/esp8266/makeimg.py
index 091854f..a81b2d0 100644
--- a/ports/esp8266/makeimg.py
+++ b/ports/esp8266/makeimg.py
@@ -8,33 +8,33 @@
 
 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()
         fout.write(data_flash)
         # First 4 bytes include flash size, etc. which may be changed
         # by esptool.py, etc.
         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()
 
-    pad = b'\xff' * (SEGS_MAX_SIZE - len(data_flash))
+    pad = b"\xff" * (SEGS_MAX_SIZE - len(data_flash))
     assert len(pad) >= 4
     fout.write(pad[:-4])
     md5.update(pad[:-4])
     len_data = struct.pack("I", SEGS_MAX_SIZE + len(data_rom))
     fout.write(len_data)
     md5.update(len_data)
-    print('padding  ', len(pad))
+    print("padding  ", len(pad))
 
     fout.write(data_rom)
     md5.update(data_rom)
-    print('irom0text', len(data_rom))
+    print("irom0text", len(data_rom))
 
     fout.write(md5.digest())
 
-    print('total    ', SEGS_MAX_SIZE + len(data_rom))
-    print('md5      ', md5.hexdigest())
+    print("total    ", SEGS_MAX_SIZE + len(data_rom))
+    print("md5      ", md5.hexdigest())
diff --git a/ports/esp8266/modesp.c b/ports/esp8266/modesp.c
index 6f937e0..95566cd 100644
--- a/ports/esp8266/modesp.c
+++ b/ports/esp8266/modesp.c
@@ -101,7 +101,7 @@
     }
 
     // We know that allocation will be 4-byte aligned for sure
-    SpiFlashOpResult res = spi_flash_read(offset, (uint32_t*)buf, len);
+    SpiFlashOpResult res = spi_flash_read(offset, (uint32_t *)buf, len);
     if (res == SPI_FLASH_RESULT_OK) {
         if (alloc_buf) {
             return mp_obj_new_bytes(buf, len);
@@ -148,7 +148,7 @@
     extern char flashchip;
     // For SDK 1.5.2, either address has shifted and not mirrored in
     // eagle.rom.addr.v6.ld, or extra initial member was added.
-    SpiFlashChip *flash = (SpiFlashChip*)(&flashchip + 4);
+    SpiFlashChip *flash = (SpiFlashChip *)(&flashchip + 4);
     #if 0
     printf("deviceId: %x\n", flash->deviceId);
     printf("chip_size: %u\n", flash->chip_size);
@@ -163,7 +163,7 @@
 
 // If there's just 1 loadable segment at the start of flash,
 // we assume there's a yaota8266 bootloader.
-#define IS_OTA_FIRMWARE() ((*(uint32_t*)0x40200000 & 0xff00) == 0x100)
+#define IS_OTA_FIRMWARE() ((*(uint32_t *)0x40200000 & 0xff00) == 0x100)
 
 extern byte _firmware_size[];
 
@@ -174,13 +174,13 @@
 
 STATIC mp_obj_t esp_check_fw(void) {
     MD5_CTX ctx;
-    char *fw_start = (char*)0x40200000;
+    char *fw_start = (char *)0x40200000;
     if (IS_OTA_FIRMWARE()) {
         // Skip yaota8266 bootloader
         fw_start += 0x3c000;
     }
 
-    uint32_t size = *(uint32_t*)(fw_start + 0x8ffc);
+    uint32_t size = *(uint32_t *)(fw_start + 0x8ffc);
     printf("size: %d\n", size);
     if (size > 1024 * 1024) {
         printf("Invalid size\n");
@@ -204,7 +204,7 @@
     mp_buffer_info_t bufinfo;
     mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_READ);
     esp_neopixel_write(mp_obj_get_pin_obj(pin)->phys_port,
-        (uint8_t*)bufinfo.buf, bufinfo.len, mp_obj_is_true(is800k));
+        (uint8_t *)bufinfo.buf, bufinfo.len, mp_obj_is_true(is800k));
     return mp_const_none;
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp_neopixel_write_obj, esp_neopixel_write_);
@@ -215,7 +215,7 @@
     mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_READ);
     esp_apa102_write(mp_obj_get_pin_obj(clockPin)->phys_port,
         mp_obj_get_pin_obj(dataPin)->phys_port,
-        (uint8_t*)bufinfo.buf, bufinfo.len);
+        (uint8_t *)bufinfo.buf, bufinfo.len);
     return mp_const_none;
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp_apa102_write_obj, esp_apa102_write_);
@@ -238,7 +238,7 @@
 STATIC MP_DEFINE_CONST_FUN_OBJ_1(esp_malloc_obj, esp_malloc);
 
 STATIC mp_obj_t esp_free(mp_obj_t addr_in) {
-    os_free((void*)mp_obj_get_int(addr_in));
+    os_free((void *)mp_obj_get_int(addr_in));
     return mp_const_none;
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_1(esp_free_obj, esp_free);
@@ -294,9 +294,9 @@
 
     void *dest;
     if (esp_native_code_location == ESP_NATIVE_CODE_IRAM1) {
-        dest = (void*)esp_native_code_cur;
+        dest = (void *)esp_native_code_cur;
     } else {
-        dest = (void*)(FLASH_START + esp_native_code_cur);
+        dest = (void *)(FLASH_START + esp_native_code_cur);
     }
     if (reloc) {
         mp_native_relocate(reloc, buf, (uintptr_t)dest);
@@ -381,16 +381,16 @@
     { MP_ROM_QSTR(MP_QSTR_set_native_code_location), MP_ROM_PTR(&esp_set_native_code_location_obj) },
     #endif
 
-#if MODESP_INCLUDE_CONSTANTS
+    #if MODESP_INCLUDE_CONSTANTS
     { MP_ROM_QSTR(MP_QSTR_SLEEP_NONE), MP_ROM_INT(NONE_SLEEP_T) },
     { MP_ROM_QSTR(MP_QSTR_SLEEP_LIGHT), MP_ROM_INT(LIGHT_SLEEP_T) },
     { MP_ROM_QSTR(MP_QSTR_SLEEP_MODEM), MP_ROM_INT(MODEM_SLEEP_T) },
-#endif
+    #endif
 };
 
 STATIC MP_DEFINE_CONST_DICT(esp_module_globals, esp_module_globals_table);
 
 const mp_obj_module_t esp_module = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&esp_module_globals,
+    .globals = (mp_obj_dict_t *)&esp_module_globals,
 };
diff --git a/ports/esp8266/modmachine.c b/ports/esp8266/modmachine.c
index 35d4918..e6be0c1 100644
--- a/ports/esp8266/modmachine.c
+++ b/ports/esp8266/modmachine.c
@@ -84,13 +84,13 @@
 
 STATIC mp_obj_t machine_unique_id(void) {
     uint32_t id = system_get_chip_id();
-    return mp_obj_new_bytes((byte*)&id, sizeof(id));
+    return mp_obj_new_bytes((byte *)&id, sizeof(id));
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_0(machine_unique_id_obj, machine_unique_id);
 
 STATIC mp_obj_t machine_idle(void) {
     uint32_t t = mp_hal_ticks_cpu();
-    asm("waiti 0");
+    asm ("waiti 0");
     t = mp_hal_ticks_cpu() - t;
     ets_event_poll(); // handle any events after possibly a long wait (eg feed WDT)
     return MP_OBJ_NEW_SMALL_INT(t);
@@ -112,7 +112,7 @@
         ets_event_poll();
         if (wifi_mode == NULL_MODE) {
             // Can only idle if the wifi is off
-            asm("waiti 0");
+            asm ("waiti 0");
         }
     }
     return mp_const_none;
@@ -256,11 +256,11 @@
         { MP_QSTR_callback,     MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
         { MP_QSTR_period,       MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
         { MP_QSTR_tick_hz,      MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1000} },
-#if MICROPY_PY_BUILTINS_FLOAT
+        #if MICROPY_PY_BUILTINS_FLOAT
         { MP_QSTR_freq,         MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
-#else
+        #else
         { MP_QSTR_freq,         MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
-#endif
+        #endif
     };
 
     // parse args
@@ -272,7 +272,7 @@
     os_timer_disarm(&self->timer);
     os_timer_setfn(&self->timer, esp_timer_cb, self);
 
-#if MICROPY_PY_BUILTINS_FLOAT
+    #if MICROPY_PY_BUILTINS_FLOAT
     if (args[ARG_freq].u_obj != mp_const_none) {
         mp_float_t freq = mp_obj_get_float(args[ARG_freq].u_obj);
         if (freq < 0.001) {
@@ -281,11 +281,11 @@
             esp_timer_arm_us(self, (mp_int_t)(1000000 / freq), args[ARG_mode].u_int);
         }
     }
-#else
+    #else
     if (args[ARG_freq].u_int != 0xffffffff) {
         esp_timer_arm_us(self, 1000000 / args[ARG_freq].u_int, args[ARG_mode].u_int);
     }
-#endif
+    #endif
     else {
         mp_int_t period = args[ARG_period].u_int;
         mp_int_t hz = args[ARG_tick_hz].u_int;
@@ -333,7 +333,7 @@
     .name = MP_QSTR_Timer,
     .print = esp_timer_print,
     .make_new = esp_timer_make_new,
-    .locals_dict = (mp_obj_dict_t*)&esp_timer_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&esp_timer_locals_dict,
 };
 
 // this bit is unused in the Xtensa PS register
@@ -434,7 +434,7 @@
 
 const mp_obj_module_t mp_module_machine = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&machine_module_globals,
+    .globals = (mp_obj_dict_t *)&machine_module_globals,
 };
 
 #endif // MICROPY_PY_MACHINE
diff --git a/ports/esp8266/modnetwork.c b/ports/esp8266/modnetwork.c
index 6bdbe6e..ef3e02e 100644
--- a/ports/esp8266/modnetwork.c
+++ b/ports/esp8266/modnetwork.c
@@ -204,7 +204,7 @@
                 // but is present in SDK headers since 1.4.0
                 t->items[0] = mp_obj_new_bytes(bs->ssid, bs->ssid_len);
                 #else
-                t->items[0] = mp_obj_new_bytes(bs->ssid, strlen((char*)bs->ssid));
+                t->items[0] = mp_obj_new_bytes(bs->ssid, strlen((char *)bs->ssid));
                 #endif
                 t->items[1] = mp_obj_new_bytes(bs->bssid, sizeof(bs->bssid));
                 t->items[2] = MP_OBJ_NEW_SMALL_INT(bs->channel);
@@ -280,10 +280,10 @@
         // get
         dns_addr = dns_getserver(0);
         mp_obj_t tuple[4] = {
-            netutils_format_ipv4_addr((uint8_t*)&info.ip, NETUTILS_BIG),
-            netutils_format_ipv4_addr((uint8_t*)&info.netmask, NETUTILS_BIG),
-            netutils_format_ipv4_addr((uint8_t*)&info.gw, NETUTILS_BIG),
-            netutils_format_ipv4_addr((uint8_t*)&dns_addr, NETUTILS_BIG),
+            netutils_format_ipv4_addr((uint8_t *)&info.ip, NETUTILS_BIG),
+            netutils_format_ipv4_addr((uint8_t *)&info.netmask, NETUTILS_BIG),
+            netutils_format_ipv4_addr((uint8_t *)&info.gw, NETUTILS_BIG),
+            netutils_format_ipv4_addr((uint8_t *)&dns_addr, NETUTILS_BIG),
         };
         return mp_obj_new_tuple(4, tuple);
     } else {
@@ -291,19 +291,19 @@
         mp_obj_t *items;
         bool restart_dhcp_server = false;
         mp_obj_get_array_fixed_n(args[1], 4, &items);
-        netutils_parse_ipv4_addr(items[0], (void*)&info.ip, NETUTILS_BIG);
+        netutils_parse_ipv4_addr(items[0], (void *)&info.ip, NETUTILS_BIG);
         if (mp_obj_is_integer(items[1])) {
             // allow numeric netmask, i.e.:
             // 24 -> 255.255.255.0
             // 16 -> 255.255.0.0
             // etc...
-            uint32_t* m = (uint32_t*)&info.netmask;
+            uint32_t *m = (uint32_t *)&info.netmask;
             *m = htonl(0xffffffff << (32 - mp_obj_get_int(items[1])));
         } else {
-            netutils_parse_ipv4_addr(items[1], (void*)&info.netmask, NETUTILS_BIG);
+            netutils_parse_ipv4_addr(items[1], (void *)&info.netmask, NETUTILS_BIG);
         }
-        netutils_parse_ipv4_addr(items[2], (void*)&info.gw, NETUTILS_BIG);
-        netutils_parse_ipv4_addr(items[3], (void*)&dns_addr, NETUTILS_BIG);
+        netutils_parse_ipv4_addr(items[2], (void *)&info.gw, NETUTILS_BIG);
+        netutils_parse_ipv4_addr(items[3], (void *)&dns_addr, NETUTILS_BIG);
         // To set a static IP we have to disable DHCP first
         if (self->if_id == STATION_IF) {
             wifi_station_dhcpc_stop();
@@ -312,7 +312,7 @@
             wifi_softap_dhcps_stop();
         }
         if (!wifi_set_ip_info(self->if_id, &info)) {
-          mp_raise_msg(&mp_type_OSError, "wifi_set_ip_info() failed");
+            mp_raise_msg(&mp_type_OSError, "wifi_set_ip_info() failed");
         }
         dns_setserver(0, &dns_addr);
         if (restart_dhcp_server) {
@@ -394,14 +394,14 @@
                         req_if = STATION_IF;
                         if (self->if_id == STATION_IF) {
                             const char *s = mp_obj_str_get_str(kwargs->table[i].value);
-                            wifi_station_set_hostname((char*)s);
+                            wifi_station_set_hostname((char *)s);
                         }
                         break;
                     }
                     default:
                         goto unknown;
                 }
-                #undef QS
+#undef QS
             }
         }
 
@@ -436,9 +436,9 @@
         }
         case MP_QSTR_essid:
             if (self->if_id == STATION_IF) {
-                val = mp_obj_new_str((char*)cfg.sta.ssid, strlen((char*)cfg.sta.ssid));
+                val = mp_obj_new_str((char *)cfg.sta.ssid, strlen((char *)cfg.sta.ssid));
             } else {
-                val = mp_obj_new_str((char*)cfg.ap.ssid, cfg.ap.ssid_len);
+                val = mp_obj_new_str((char *)cfg.ap.ssid, cfg.ap.ssid_len);
             }
             break;
         case MP_QSTR_hidden:
@@ -455,7 +455,7 @@
             break;
         case MP_QSTR_dhcp_hostname: {
             req_if = STATION_IF;
-            char* s = wifi_station_get_hostname();
+            char *s = wifi_station_get_hostname();
             if (s == NULL) {
                 val = MP_OBJ_NEW_QSTR(MP_QSTR_);
             } else {
@@ -495,7 +495,7 @@
 const mp_obj_type_t wlan_if_type = {
     { &mp_type_type },
     .name = MP_QSTR_WLAN,
-    .locals_dict = (mp_obj_dict_t*)&wlan_if_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&wlan_if_locals_dict,
 };
 
 STATIC mp_obj_t esp_phy_mode(size_t n_args, const mp_obj_t *args) {
@@ -513,7 +513,7 @@
     { MP_ROM_QSTR(MP_QSTR_WLAN), MP_ROM_PTR(&get_wlan_obj) },
     { MP_ROM_QSTR(MP_QSTR_phy_mode), MP_ROM_PTR(&esp_phy_mode_obj) },
 
-#if MODNETWORK_INCLUDE_CONSTANTS
+    #if MODNETWORK_INCLUDE_CONSTANTS
     { MP_ROM_QSTR(MP_QSTR_STA_IF), MP_ROM_INT(STATION_IF)},
     { MP_ROM_QSTR(MP_QSTR_AP_IF), MP_ROM_INT(SOFTAP_IF)},
 
@@ -533,12 +533,12 @@
     { MP_ROM_QSTR(MP_QSTR_AUTH_WPA_PSK), MP_ROM_INT(AUTH_WPA_PSK) },
     { MP_ROM_QSTR(MP_QSTR_AUTH_WPA2_PSK), MP_ROM_INT(AUTH_WPA2_PSK) },
     { MP_ROM_QSTR(MP_QSTR_AUTH_WPA_WPA2_PSK), MP_ROM_INT(AUTH_WPA_WPA2_PSK) },
-#endif
+    #endif
 };
 
 STATIC MP_DEFINE_CONST_DICT(mp_module_network_globals, mp_module_network_globals_table);
 
 const mp_obj_module_t network_module = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_network_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_network_globals,
 };
diff --git a/ports/esp8266/modules/_boot.py b/ports/esp8266/modules/_boot.py
index 4c2aa87..1f77d88 100644
--- a/ports/esp8266/modules/_boot.py
+++ b/ports/esp8266/modules/_boot.py
@@ -1,13 +1,15 @@
 import gc
+
 gc.threshold((gc.mem_free() + gc.mem_alloc()) // 4)
 import uos
 from flashbdev import bdev
 
 if bdev:
     try:
-        uos.mount(bdev, '/')
+        uos.mount(bdev, "/")
     except:
         import inisetup
+
         inisetup.setup()
 
 gc.collect()
diff --git a/ports/esp8266/modules/flashbdev.py b/ports/esp8266/modules/flashbdev.py
index 4273b26..404cf36 100644
--- a/ports/esp8266/modules/flashbdev.py
+++ b/ports/esp8266/modules/flashbdev.py
@@ -1,29 +1,30 @@
 import esp
 
+
 class FlashBdev:
 
     SEC_SIZE = 4096
     RESERVED_SECS = 1
     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):
         self.blocks = blocks
 
     def readblocks(self, n, buf, off=0):
-        #print("readblocks(%s, %x(%d), %d)" % (n, id(buf), len(buf), off))
+        # print("readblocks(%s, %x(%d), %d)" % (n, id(buf), len(buf), off))
         esp.flash_read((n + self.START_SEC) * self.SEC_SIZE + off, buf)
 
     def writeblocks(self, n, buf, off=None):
-        #print("writeblocks(%s, %x(%d), %d)" % (n, id(buf), len(buf), off))
-        #assert len(buf) <= self.SEC_SIZE, len(buf)
+        # print("writeblocks(%s, %x(%d), %d)" % (n, id(buf), len(buf), off))
+        # assert len(buf) <= self.SEC_SIZE, len(buf)
         if off is None:
             esp.flash_erase(n + self.START_SEC)
             off = 0
         esp.flash_write((n + self.START_SEC) * self.SEC_SIZE + off, buf)
 
     def ioctl(self, op, arg):
-        #print("ioctl(%d, %r)" % (op, arg))
+        # print("ioctl(%d, %r)" % (op, arg))
         if op == 4:  # MP_BLOCKDEV_IOCTL_BLOCK_COUNT
             return self.blocks
         if op == 5:  # MP_BLOCKDEV_IOCTL_BLOCK_SIZE
@@ -32,8 +33,9 @@
             esp.flash_erase(arg + self.START_SEC)
             return 0
 
+
 size = esp.flash_size()
-if size < 1024*1024:
+if size < 1024 * 1024:
     bdev = None
 else:
     # 20K at the flash end is reserved for SDK params storage
diff --git a/ports/esp8266/modules/inisetup.py b/ports/esp8266/modules/inisetup.py
index cb4fc04..1bbc3d0 100644
--- a/ports/esp8266/modules/inisetup.py
+++ b/ports/esp8266/modules/inisetup.py
@@ -2,45 +2,55 @@
 import network
 from flashbdev import bdev
 
+
 def wifi():
     import ubinascii
+
     ap_if = network.WLAN(network.AP_IF)
     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")
 
+
 def check_bootsec():
     buf = bytearray(bdev.SEC_SIZE)
     bdev.readblocks(0, buf)
     empty = True
     for b in buf:
-        if b != 0xff:
+        if b != 0xFF:
             empty = False
             break
     if empty:
         return True
     fs_corrupted()
 
+
 def fs_corrupted():
     import time
+
     while 1:
-        print("""\
+        print(
+            """\
 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
 snapshot to try to recover it. Otherwise, perform factory reprogramming
 of MicroPython firmware (completely erase flash, followed by firmware
 programming).
-""" % (bdev.START_SEC, bdev.blocks))
+"""
+            % (bdev.START_SEC, bdev.blocks)
+        )
         time.sleep(3)
 
+
 def setup():
     check_bootsec()
     print("Performing initial setup")
     wifi()
     uos.VfsFat.mkfs(bdev)
     vfs = uos.VfsFat(bdev)
-    uos.mount(vfs, '/')
+    uos.mount(vfs, "/")
     with open("boot.py", "w") as f:
-        f.write("""\
+        f.write(
+            """\
 # This file is executed on every boot (including wake-boot from deepsleep)
 #import esp
 #esp.osdebug(None)
@@ -50,5 +60,6 @@
 #import webrepl
 #webrepl.start()
 gc.collect()
-""")
+"""
+        )
     return vfs
diff --git a/ports/esp8266/modules/neopixel.py b/ports/esp8266/modules/neopixel.py
index b13424d..be56ed1 100644
--- a/ports/esp8266/modules/neopixel.py
+++ b/ports/esp8266/modules/neopixel.py
@@ -21,8 +21,7 @@
 
     def __getitem__(self, index):
         offset = index * self.bpp
-        return tuple(self.buf[offset + self.ORDER[i]]
-                     for i in range(self.bpp))
+        return tuple(self.buf[offset + self.ORDER[i]] for i in range(self.bpp))
 
     def fill(self, color):
         for i in range(self.n):
diff --git a/ports/esp8266/modules/ntptime.py b/ports/esp8266/modules/ntptime.py
index 0f51210..92ae6ab 100644
--- a/ports/esp8266/modules/ntptime.py
+++ b/ports/esp8266/modules/ntptime.py
@@ -13,9 +13,10 @@
 # The NTP host can be configured at runtime by doing: ntptime.host = 'myhost.org'
 host = "pool.ntp.org"
 
+
 def time():
     NTP_QUERY = bytearray(48)
-    NTP_QUERY[0] = 0x1b
+    NTP_QUERY[0] = 0x1B
     addr = socket.getaddrinfo(host, 123)[0][-1]
     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     try:
@@ -27,11 +28,13 @@
     val = struct.unpack("!I", msg[40:44])[0]
     return val - NTP_DELTA
 
+
 # There's currently no timezone support in MicroPython, so
 # utime.localtime() will return UTC time (as if it was .gmtime())
 def settime():
     t = time()
     import machine
     import utime
+
     tm = utime.localtime(t)
     machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))
diff --git a/ports/esp8266/modules/port_diag.py b/ports/esp8266/modules/port_diag.py
index ef88003..f2c69ec 100644
--- a/ports/esp8266/modules/port_diag.py
+++ b/ports/esp8266/modules/port_diag.py
@@ -10,13 +10,16 @@
     fid = esp.flash_id()
 
     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:")
     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 @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(esp.check_fw())
 
@@ -24,7 +27,9 @@
     print("STA ifconfig:", network.WLAN(network.STA_IF).ifconfig())
     print("AP ifconfig:", network.WLAN(network.AP_IF).ifconfig())
     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("lwIP PCBs:")
     lwip.print_pcbs()
diff --git a/ports/esp8266/moduos.c b/ports/esp8266/moduos.c
index b66d5cc..f04094f 100644
--- a/ports/esp8266/moduos.c
+++ b/ports/esp8266/moduos.c
@@ -135,5 +135,5 @@
 
 const mp_obj_module_t uos_module = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&os_module_globals,
+    .globals = (mp_obj_dict_t *)&os_module_globals,
 };
diff --git a/ports/esp8266/modutime.c b/ports/esp8266/modutime.c
index f531984..915f193 100644
--- a/ports/esp8266/modutime.c
+++ b/ports/esp8266/modutime.c
@@ -92,8 +92,8 @@
     }
 
     return mp_obj_new_int_from_uint(timeutils_mktime(mp_obj_get_int(elem[0]),
-            mp_obj_get_int(elem[1]), mp_obj_get_int(elem[2]), mp_obj_get_int(elem[3]),
-            mp_obj_get_int(elem[4]), mp_obj_get_int(elem[5])));
+        mp_obj_get_int(elem[1]), mp_obj_get_int(elem[2]), mp_obj_get_int(elem[3]),
+        mp_obj_get_int(elem[4]), mp_obj_get_int(elem[5])));
 }
 MP_DEFINE_CONST_FUN_OBJ_1(time_mktime_obj, time_mktime);
 
@@ -125,5 +125,5 @@
 
 const mp_obj_module_t utime_module = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&time_module_globals,
+    .globals = (mp_obj_dict_t *)&time_module_globals,
 };
diff --git a/ports/esp8266/mpconfigport.h b/ports/esp8266/mpconfigport.h
index ba4b1d0..71c49cd 100644
--- a/ports/esp8266/mpconfigport.h
+++ b/ports/esp8266/mpconfigport.h
@@ -110,13 +110,13 @@
         vm_hook_divisor = MICROPY_VM_HOOK_COUNT; \
         extern void ets_loop_iter(void); \
         ets_loop_iter(); \
-    }
+}
 #define MICROPY_VM_HOOK_LOOP MICROPY_VM_HOOK_POLL
 #define MICROPY_VM_HOOK_RETURN MICROPY_VM_HOOK_POLL
 
 // type definitions for the specific machine
 
-#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p)))
+#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p)))
 
 #define MP_SSIZE_MAX (0x7fffffff)
 
@@ -131,7 +131,7 @@
 #include <sys/types.h>
 
 #define MP_PLAT_PRINT_STRN(str, len) mp_hal_stdout_tx_strn_cooked(str, len)
-void *esp_native_code_commit(void*, size_t, void*);
+void *esp_native_code_commit(void *, size_t, void *);
 #define MP_PLAT_COMMIT_EXEC(buf, len, reloc) esp_native_code_commit(buf, len, reloc)
 
 // printer for debugging output, goes to UART only
diff --git a/ports/esp8266/strtoll.c b/ports/esp8266/strtoll.c
index 4e8a4d0..f095f76 100644
--- a/ports/esp8266/strtoll.c
+++ b/ports/esp8266/strtoll.c
@@ -23,7 +23,7 @@
         val = val * base + v;
     }
 
-    *endptr = (char*)nptr;
+    *endptr = (char *)nptr;
 
     return val;
 }
diff --git a/ports/esp8266/uart.c b/ports/esp8266/uart.c
index 61715f5..64bc78e 100644
--- a/ports/esp8266/uart.c
+++ b/ports/esp8266/uart.c
@@ -65,9 +65,9 @@
     uart_div_modify(uart_no, UART_CLK_FREQ / (UartDev.baut_rate));
 
     WRITE_PERI_REG(UART_CONF0(uart_no), UartDev.exist_parity
-                 | UartDev.parity
-                 | (UartDev.stop_bits << UART_STOP_BIT_NUM_S)
-                 | (UartDev.data_bits << UART_BIT_NUM_S));
+        | UartDev.parity
+        | (UartDev.stop_bits << UART_STOP_BIT_NUM_S)
+        | (UartDev.data_bits << UART_BIT_NUM_S));
 
     // clear rx and tx fifo,not ready
     SET_PERI_REG_MASK(UART_CONF0(uart_no), UART_RXFIFO_RST | UART_TXFIFO_RST);
@@ -76,16 +76,16 @@
     if (uart_no == UART0) {
         // set rx fifo trigger
         WRITE_PERI_REG(UART_CONF1(uart_no),
-                   ((0x10 & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S) |
-                   ((0x10 & UART_RX_FLOW_THRHD) << UART_RX_FLOW_THRHD_S) |
-                   UART_RX_FLOW_EN |
-                   (0x02 & UART_RX_TOUT_THRHD) << UART_RX_TOUT_THRHD_S |
-                   UART_RX_TOUT_EN);
+            ((0x10 & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S) |
+            ((0x10 & UART_RX_FLOW_THRHD) << UART_RX_FLOW_THRHD_S) |
+            UART_RX_FLOW_EN |
+            (0x02 & UART_RX_TOUT_THRHD) << UART_RX_TOUT_THRHD_S |
+                UART_RX_TOUT_EN);
         SET_PERI_REG_MASK(UART_INT_ENA(uart_no), UART_RXFIFO_TOUT_INT_ENA |
-                      UART_FRM_ERR_INT_ENA);
+            UART_FRM_ERR_INT_ENA);
     } else {
         WRITE_PERI_REG(UART_CONF1(uart_no),
-                   ((UartDev.rcv_buff.TrigLvl & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S));
+            ((UartDev.rcv_buff.TrigLvl & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S));
     }
 
     // clear all interrupt
@@ -103,7 +103,7 @@
 *******************************************************************************/
 void uart_tx_one_char(uint8 uart, uint8 TxChar) {
     while (true) {
-        uint32 fifo_cnt = READ_PERI_REG(UART_STATUS(uart)) & (UART_TXFIFO_CNT<<UART_TXFIFO_CNT_S);
+        uint32 fifo_cnt = READ_PERI_REG(UART_STATUS(uart)) & (UART_TXFIFO_CNT << UART_TXFIFO_CNT_S);
         if ((fifo_cnt >> UART_TXFIFO_CNT_S & UART_TXFIFO_CNT) < 126) {
             break;
         }
@@ -113,7 +113,7 @@
 
 void uart_flush(uint8 uart) {
     while (true) {
-        uint32 fifo_cnt = READ_PERI_REG(UART_STATUS(uart)) & (UART_TXFIFO_CNT<<UART_TXFIFO_CNT_S);
+        uint32 fifo_cnt = READ_PERI_REG(UART_STATUS(uart)) & (UART_TXFIFO_CNT << UART_TXFIFO_CNT_S);
         if ((fifo_cnt >> UART_TXFIFO_CNT_S & UART_TXFIFO_CNT) == 0) {
             break;
         }
@@ -155,9 +155,9 @@
 *******************************************************************************/
 
 static void uart0_rx_intr_handler(void *para) {
-  /* uart0 and uart1 intr combine togther, when interrupt occur, see reg 0x3ff20020, bit2, bit0 represents
-    * uart1 and uart0 respectively
-    */
+    /* uart0 and uart1 intr combine togther, when interrupt occur, see reg 0x3ff20020, bit2, bit0 represents
+      * uart1 and uart0 respectively
+      */
 
     uint8 uart_no = UART_REPL;
 
@@ -170,7 +170,7 @@
         // fifo full
         goto read_chars;
     } else if (UART_RXFIFO_TOUT_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_TOUT_INT_ST)) {
-        read_chars:
+    read_chars:
         ETS_UART_INTR_DISABLE();
 
         while (READ_PERI_REG(UART_STATUS(uart_no)) & (UART_RXFIFO_CNT << UART_RXFIFO_CNT_S)) {
diff --git a/ports/esp8266/uart.h b/ports/esp8266/uart.h
index 0e67783..f187c31 100644
--- a/ports/esp8266/uart.h
+++ b/ports/esp8266/uart.h
@@ -58,17 +58,17 @@
 } RcvMsgBuffState;
 
 typedef struct {
-    uint32     RcvBuffSize;
-    uint8     *pRcvMsgBuff;
-    uint8     *pWritePos;
-    uint8     *pReadPos;
-    uint8      TrigLvl; //JLU: may need to pad
-    RcvMsgBuffState  BuffState;
+    uint32 RcvBuffSize;
+    uint8 *pRcvMsgBuff;
+    uint8 *pWritePos;
+    uint8 *pReadPos;
+    uint8 TrigLvl;      //JLU: may need to pad
+    RcvMsgBuffState BuffState;
 } RcvMsgBuff;
 
 typedef struct {
-    uint32   TrxBuffSize;
-    uint8   *pTrxBuff;
+    uint32 TrxBuffSize;
+    uint8 *pTrxBuff;
 } TrxMsgBuff;
 
 typedef enum {
@@ -80,17 +80,17 @@
 } RcvMsgState;
 
 typedef struct {
-    UartBautRate      baut_rate;
-    UartBitsNum4Char  data_bits;
-    UartExistParity   exist_parity;
-    UartParityMode    parity;    // chip size in byte
-    UartStopBitsNum   stop_bits;
-    UartFlowCtrl      flow_ctrl;
-    RcvMsgBuff        rcv_buff;
-    TrxMsgBuff        trx_buff;
-    RcvMsgState       rcv_state;
-    int               received;
-    int               buff_uart_no;  //indicate which uart use tx/rx buffer
+    UartBautRate baut_rate;
+    UartBitsNum4Char data_bits;
+    UartExistParity exist_parity;
+    UartParityMode parity;       // chip size in byte
+    UartStopBitsNum stop_bits;
+    UartFlowCtrl flow_ctrl;
+    RcvMsgBuff rcv_buff;
+    TrxMsgBuff trx_buff;
+    RcvMsgState rcv_state;
+    int received;
+    int buff_uart_no;                //indicate which uart use tx/rx buffer
 } UartDevice;
 
 extern uint8 uart_ringbuf_array[UART0_STATIC_RXBUF_LEN];
diff --git a/ports/esp8266/uart_register.h b/ports/esp8266/uart_register.h
index 6398879..cdf0ba1 100644
--- a/ports/esp8266/uart_register.h
+++ b/ports/esp8266/uart_register.h
@@ -6,7 +6,7 @@
 
 #ifndef UART_REGISTER_H_INCLUDED
 #define UART_REGISTER_H_INCLUDED
-#define REG_UART_BASE( i )  (0x60000000+(i)*0xf00)
+#define REG_UART_BASE( i )  (0x60000000 + (i) * 0xf00)
 //version value:32'h062000
 
 #define UART_FIFO( i )                          (REG_UART_BASE( i ) + 0x0)
diff --git a/ports/esp8266/xtirq.h b/ports/esp8266/xtirq.h
index 595052f..835f06b 100644
--- a/ports/esp8266/xtirq.h
+++ b/ports/esp8266/xtirq.h
@@ -31,7 +31,7 @@
 // returns the value of "intlevel" from the PS register
 static inline uint32_t query_irq(void) {
     uint32_t ps;
-    __asm__ volatile("rsr %0, ps" : "=a" (ps));
+    __asm__ volatile ("rsr %0, ps" : "=a" (ps));
     return ps & 0xf;
 }
 
@@ -45,7 +45,7 @@
 
 // "ps" should be the value returned from raise_irq_pri
 static inline void restore_irq_pri(uint32_t ps) {
-    __asm__ volatile ("wsr %0, ps; rsync" :: "a" (ps));
+    __asm__ volatile ("wsr %0, ps; rsync" : : "a" (ps));
 }
 
 static inline uint32_t disable_irq(void) {
diff --git a/ports/javascript/main.c b/ports/javascript/main.c
index 77b8b87..5d295f9 100644
--- a/ports/javascript/main.c
+++ b/ports/javascript/main.c
@@ -82,10 +82,10 @@
 
 void mp_js_init(int heap_size) {
     int stack_dummy;
-    stack_top = (char*)&stack_dummy;
+    stack_top = (char *)&stack_dummy;
 
     #if MICROPY_ENABLE_GC
-    char *heap = (char*)malloc(heap_size * sizeof(char));
+    char *heap = (char *)malloc(heap_size * sizeof(char));
     gc_init(heap, heap + heap_size);
     #endif
 
@@ -95,7 +95,7 @@
     #endif
 
     mp_init();
-    
+
     mp_obj_list_init(mp_sys_path, 0);
     mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_));
     mp_obj_list_init(mp_sys_argv, 0);
@@ -113,7 +113,7 @@
         longjmp(dummy, 1);
     }
     gc_collect_start();
-    gc_collect_root((void*)stack_top, ((mp_uint_t)(void*)(&dummy + 1) - (mp_uint_t)stack_top) / sizeof(mp_uint_t));
+    gc_collect_root((void *)stack_top, ((mp_uint_t)(void *)(&dummy + 1) - (mp_uint_t)stack_top) / sizeof(mp_uint_t));
     gc_collect_end();
 }
 
@@ -131,11 +131,15 @@
 MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
 
 void nlr_jump_fail(void *val) {
-    while (1);
+    while (1) {
+        ;
+    }
 }
 
 void NORETURN __fatal_error(const char *msg) {
-    while (1);
+    while (1) {
+        ;
+    }
 }
 
 #ifndef NDEBUG
diff --git a/ports/javascript/modutime.c b/ports/javascript/modutime.c
index 6c6bdcf..d05d832 100644
--- a/ports/javascript/modutime.c
+++ b/ports/javascript/modutime.c
@@ -52,5 +52,5 @@
 
 const mp_obj_module_t mp_module_utime = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&time_module_globals,
+    .globals = (mp_obj_dict_t *)&time_module_globals,
 };
diff --git a/ports/javascript/mpconfigport.h b/ports/javascript/mpconfigport.h
index bc4e053..a9da57c 100644
--- a/ports/javascript/mpconfigport.h
+++ b/ports/javascript/mpconfigport.h
@@ -162,7 +162,7 @@
         vm_hook_divisor = MICROPY_VM_HOOK_COUNT; \
         extern void mp_js_hook(void); \
         mp_js_hook(); \
-    }
+}
 #define MICROPY_VM_HOOK_LOOP MICROPY_VM_HOOK_POLL
 #define MICROPY_VM_HOOK_RETURN MICROPY_VM_HOOK_POLL
 
diff --git a/ports/minimal/frozentest.py b/ports/minimal/frozentest.py
index 0f99b74..78cdd60 100644
--- a/ports/minimal/frozentest.py
+++ b/ports/minimal/frozentest.py
@@ -1,7 +1,7 @@
-print('uPy')
-print('a long string that is not interned')
-print('a string that has unicode αβγ chars')
-print(b'bytes 1234\x01')
+print("uPy")
+print("a long string that is not interned")
+print("a string that has unicode αβγ chars")
+print(b"bytes 1234\x01")
 print(123456789)
 for i in range(4):
     print(i)
diff --git a/ports/minimal/main.c b/ports/minimal/main.c
index adc1dad..27ba9ed 100644
--- a/ports/minimal/main.c
+++ b/ports/minimal/main.c
@@ -33,7 +33,7 @@
 
 int main(int argc, char **argv) {
     int stack_dummy;
-    stack_top = (char*)&stack_dummy;
+    stack_top = (char *)&stack_dummy;
 
     #if MICROPY_ENABLE_GC
     gc_init(heap, heap + sizeof(heap));
@@ -84,11 +84,15 @@
 MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
 
 void nlr_jump_fail(void *val) {
-    while (1);
+    while (1) {
+        ;
+    }
 }
 
 void NORETURN __fatal_error(const char *msg) {
-    while (1);
+    while (1) {
+        ;
+    }
 }
 
 #ifndef NDEBUG
@@ -149,7 +153,7 @@
     // when we get here: stack is initialised, bss is clear, data is copied
 
     // SCB->CCR: enable 8-byte stack alignment for IRQ handlers, in accord with EABI
-    *((volatile uint32_t*)0xe000ed14) |= 1 << 9;
+    *((volatile uint32_t *)0xe000ed14) |= 1 << 9;
 
     // initialise the cpu and peripherals
     #if MICROPY_MIN_USE_STM32_MCU
@@ -205,10 +209,10 @@
     volatile uint32_t CR1;
 } periph_uart_t;
 
-#define USART1 ((periph_uart_t*) 0x40011000)
-#define GPIOA  ((periph_gpio_t*) 0x40020000)
-#define GPIOB  ((periph_gpio_t*) 0x40020400)
-#define RCC    ((periph_rcc_t*)  0x40023800)
+#define USART1 ((periph_uart_t *) 0x40011000)
+#define GPIOA  ((periph_gpio_t *) 0x40020000)
+#define GPIOB  ((periph_gpio_t *) 0x40020400)
+#define RCC    ((periph_rcc_t *)  0x40023800)
 
 // simple GPIO interface
 #define GPIO_MODE_IN (0)
diff --git a/ports/minimal/mpconfigport.h b/ports/minimal/mpconfigport.h
index f2a4352..41e22cd 100644
--- a/ports/minimal/mpconfigport.h
+++ b/ports/minimal/mpconfigport.h
@@ -60,7 +60,7 @@
 
 // type definitions for the specific machine
 
-#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1))
+#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1))
 
 // This port is intended to be 32-bit, but unfortunately, int32_t for
 // different targets may be defined in different ways - either as int
diff --git a/ports/minimal/mphalport.h b/ports/minimal/mphalport.h
index 60d68bd..5130d19 100644
--- a/ports/minimal/mphalport.h
+++ b/ports/minimal/mphalport.h
@@ -1,2 +1,5 @@
-static inline mp_uint_t mp_hal_ticks_ms(void) { return 0; }
-static inline void mp_hal_set_interrupt_char(char c) {}
+static inline mp_uint_t mp_hal_ticks_ms(void) {
+    return 0;
+}
+static inline void mp_hal_set_interrupt_char(char c) {
+}
diff --git a/ports/minimal/uart_core.c b/ports/minimal/uart_core.c
index d2d17b4..5b3797d 100644
--- a/ports/minimal/uart_core.c
+++ b/ports/minimal/uart_core.c
@@ -10,35 +10,35 @@
     volatile uint32_t SR;
     volatile uint32_t DR;
 } periph_uart_t;
-#define USART1 ((periph_uart_t*)0x40011000)
+#define USART1 ((periph_uart_t *)0x40011000)
 #endif
 
 // Receive single character
 int mp_hal_stdin_rx_chr(void) {
     unsigned char c = 0;
-#if MICROPY_MIN_USE_STDOUT
+    #if MICROPY_MIN_USE_STDOUT
     int r = read(0, &c, 1);
     (void)r;
-#elif MICROPY_MIN_USE_STM32_MCU
+    #elif MICROPY_MIN_USE_STM32_MCU
     // wait for RXNE
     while ((USART1->SR & (1 << 5)) == 0) {
     }
     c = USART1->DR;
-#endif
+    #endif
     return c;
 }
 
 // Send string of given length
 void mp_hal_stdout_tx_strn(const char *str, mp_uint_t len) {
-#if MICROPY_MIN_USE_STDOUT
+    #if MICROPY_MIN_USE_STDOUT
     int r = write(1, str, len);
     (void)r;
-#elif MICROPY_MIN_USE_STM32_MCU
+    #elif MICROPY_MIN_USE_STM32_MCU
     while (len--) {
         // wait for TXE
         while ((USART1->SR & (1 << 7)) == 0) {
         }
         USART1->DR = *str++;
     }
-#endif
+    #endif
 }
diff --git a/ports/nrf/boards/make-pins.py b/ports/nrf/boards/make-pins.py
index 1844a06..56c56ae 100644
--- a/ports/nrf/boards/make-pins.py
+++ b/ports/nrf/boards/make-pins.py
@@ -7,27 +7,27 @@
 import sys
 import csv
 
-SUPPORTED_FN = {
-    'UART'  : ['RX', 'TX', 'CTS', 'RTS']
-}
+SUPPORTED_FN = {"UART": ["RX", "TX", "CTS", "RTS"]}
+
 
 def parse_pin(name_str):
     """Parses a string and returns a pin-num."""
     if len(name_str) < 1:
         raise ValueError("Expecting pin name to be at least 4 charcters.")
-    if name_str[0] != 'P':
+    if name_str[0] != "P":
         raise ValueError("Expecting pin name to start with P")
-    pin_str = name_str[1:].split('/')[0]
+    pin_str = name_str[1:].split("/")[0]
     if not pin_str.isdigit():
         raise ValueError("Expecting numeric pin number.")
     return int(pin_str)
 
+
 def split_name_num(name_num):
     num = None
     for num_idx in range(len(name_num) - 1, -1, -1):
         if not name_num[num_idx].isdigit():
-            name = name_num[0:num_idx + 1]
-            num_str = name_num[num_idx + 1:]
+            name = name_num[0 : num_idx + 1]
+            num_str = name_num[num_idx + 1 :]
             if len(num_str) > 0:
                 num = int(num_str)
             break
@@ -41,12 +41,12 @@
         self.idx = idx
         self.af_str = af_str
 
-        self.func = ''
+        self.func = ""
         self.fn_num = None
-        self.pin_type = ''
+        self.pin_type = ""
         self.supported = False
 
-        af_words = af_str.split('_', 1)
+        af_words = af_str.split("_", 1)
         self.func, self.fn_num = split_name_num(af_words[0])
         if len(af_words) > 1:
             self.pin_type = af_words[1]
@@ -62,22 +62,25 @@
         """Returns the numbered function (i.e. USART6) for this AF."""
         if self.fn_num is None:
             return self.func
-        return '{:s}{:d}'.format(self.func, self.fn_num)
+        return "{:s}{:d}".format(self.func, self.fn_num)
 
     def mux_name(self):
-        return 'AF{:d}_{:s}'.format(self.idx, self.ptr())
+        return "AF{:d}_{:s}".format(self.idx, self.ptr())
 
     def print(self):
         """Prints the C representation of this AF."""
         if self.supported:
-            print('  AF',  end='')
+            print("  AF", end="")
         else:
-            print('  //', end='')
+            print("  //", end="")
         fn_num = self.fn_num
         if fn_num is None:
             fn_num = 0
-        print('({:2d}, {:8s}, {:2d}, {:10s}, {:8s}), // {:s}'.format(self.idx,
-              self.func, fn_num, self.pin_type, self.ptr(), self.af_str))
+        print(
+            "({:2d}, {:8s}, {:2d}, {:10s}, {:8s}), // {:s}".format(
+                self.idx, self.func, fn_num, self.pin_type, self.ptr(), self.af_str
+            )
+        )
 
     def qstr_list(self):
         return [self.mux_name()]
@@ -96,7 +99,7 @@
         self.board_index = None
 
     def cpu_pin_name(self):
-        return '{:s}{:d}'.format("P", self.pin)
+        return "{:s}{:d}".format("P", self.pin)
 
     def is_board_pin(self):
         return self.board_pin
@@ -108,9 +111,9 @@
         self.board_index = index
 
     def parse_adc(self, adc_str):
-        if (adc_str[:3] != 'ADC'):
+        if adc_str[:3] != "ADC":
             return
-        (adc,channel) = adc_str.split('_')
+        (adc, channel) = adc_str.split("_")
         for idx in range(3, len(adc)):
             self.adc_num = int(adc[idx])
         self.adc_channel = int(channel[2:])
@@ -120,7 +123,7 @@
             return
         # If there is a slash, then the slash separates 2 aliases for the
         # same alternate function.
-        af_strs = af_strs_in.split('/')
+        af_strs = af_strs_in.split("/")
         for af_str in af_strs:
             alt_fn = AlternateFunction(af_idx, af_str)
             self.alt_fn.append(alt_fn)
@@ -129,49 +132,55 @@
 
     def alt_fn_name(self, null_if_0=False):
         if null_if_0 and self.alt_fn_count == 0:
-            return 'NULL'
-        return 'pin_{:s}_af'.format(self.cpu_pin_name())
+            return "NULL"
+        return "pin_{:s}_af".format(self.cpu_pin_name())
 
     def adc_num_str(self):
-        str = ''
-        for adc_num in range(1,4):
+        str = ""
+        for adc_num in range(1, 4):
             if self.adc_num & (1 << (adc_num - 1)):
                 if len(str) > 0:
-                    str += ' | '
-                str += 'PIN_ADC'
-                str += chr(ord('0') + adc_num)
+                    str += " | "
+                str += "PIN_ADC"
+                str += chr(ord("0") + adc_num)
         if len(str) == 0:
-            str = '0'
+            str = "0"
         return str
 
     def print_const_table_entry(self):
-        print('  PIN({:d}, {:s}, {:s}, {:d}),'.format(
-            self.pin,
-            self.alt_fn_name(null_if_0=True),
-            self.adc_num_str(), self.adc_channel))
+        print(
+            "  PIN({:d}, {:s}, {:s}, {:d}),".format(
+                self.pin, self.alt_fn_name(null_if_0=True), self.adc_num_str(), self.adc_channel
+            )
+        )
 
     def print(self):
         if self.alt_fn_count == 0:
-            print("// ",  end='')
-        print('const pin_af_obj_t {:s}[] = {{'.format(self.alt_fn_name()))
+            print("// ", end="")
+        print("const pin_af_obj_t {:s}[] = {{".format(self.alt_fn_name()))
         for alt_fn in self.alt_fn:
             alt_fn.print()
         if self.alt_fn_count == 0:
-            print("// ",  end='')
-        print('};')
-        print('')
-        print('const pin_obj_t pin_{:s} = PIN({:d}, {:s}, {:s}, {:d});'.format(
-            self.cpu_pin_name(), self.pin,
-            self.alt_fn_name(null_if_0=True),
-            self.adc_num_str(), self.adc_channel))
-        print('')
+            print("// ", end="")
+        print("};")
+        print("")
+        print(
+            "const pin_obj_t pin_{:s} = PIN({:d}, {:s}, {:s}, {:d});".format(
+                self.cpu_pin_name(),
+                self.pin,
+                self.alt_fn_name(null_if_0=True),
+                self.adc_num_str(),
+                self.adc_channel,
+            )
+        )
+        print("")
 
     def print_header(self, hdr_file):
-        hdr_file.write('extern const pin_obj_t pin_{:s};\n'.
-                       format(self.cpu_pin_name()))
+        hdr_file.write("extern const pin_obj_t pin_{:s};\n".format(self.cpu_pin_name()))
         if self.alt_fn_count > 0:
-            hdr_file.write('extern const pin_af_obj_t pin_{:s}_af[];\n'.
-                           format(self.cpu_pin_name()))
+            hdr_file.write(
+                "extern const pin_af_obj_t pin_{:s}_af[];\n".format(self.cpu_pin_name())
+            )
 
     def qstr_list(self):
         result = []
@@ -182,7 +191,6 @@
 
 
 class NamedPin(object):
-
     def __init__(self, name, pin):
         self._name = name
         self._pin = pin
@@ -195,10 +203,9 @@
 
 
 class Pins(object):
-
     def __init__(self):
-        self.cpu_pins = []   # list of NamedPin objects
-        self.board_pins = [] # list of NamedPin objects
+        self.cpu_pins = []  # list of NamedPin objects
+        self.board_pins = []  # list of NamedPin objects
 
     def find_pin(self, pin_num):
         for named_pin in self.cpu_pins:
@@ -207,7 +214,7 @@
                 return pin
 
     def parse_af_file(self, filename, pinname_col, af_col, af_col_end):
-        with open(filename, 'r') as csvfile:
+        with open(filename, "r") as csvfile:
             rows = csv.reader(csvfile)
             for row in rows:
                 try:
@@ -223,7 +230,7 @@
                 self.cpu_pins.append(NamedPin(pin.cpu_pin_name(), pin))
 
     def parse_board_file(self, filename):
-        with open(filename, 'r') as csvfile:
+        with open(filename, "r") as csvfile:
             rows = csv.reader(csvfile)
             for row in rows:
                 try:
@@ -236,13 +243,23 @@
                     self.board_pins.append(NamedPin(row[0], pin))
 
     def print_named(self, label, named_pins):
-        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 named_pin in named_pins:
             pin = named_pin.pin()
             if pin.is_board_pin():
-                print('  {{ MP_ROM_QSTR(MP_QSTR_{:s}), MP_ROM_PTR(&machine_board_pin_obj[{:d}]) }},'.format(named_pin.name(), pin.board_index))
-        print('};')
-        print('MP_DEFINE_CONST_DICT(pin_{:s}_pins_locals_dict, pin_{:s}_pins_locals_dict_table);'.format(label, label));
+                print(
+                    "  {{ MP_ROM_QSTR(MP_QSTR_{:s}), MP_ROM_PTR(&machine_board_pin_obj[{:d}]) }},".format(
+                        named_pin.name(), pin.board_index
+                    )
+                )
+        print("};")
+        print(
+            "MP_DEFINE_CONST_DICT(pin_{:s}_pins_locals_dict, pin_{:s}_pins_locals_dict_table);".format(
+                label, label
+            )
+        )
 
     def print_const_table(self):
         num_board_pins = 0
@@ -251,50 +268,52 @@
             if pin.is_board_pin():
                 pin.set_board_index(num_board_pins)
                 num_board_pins += 1
-        print('')
-        print('const uint8_t machine_pin_num_of_board_pins = {:d};'.format(num_board_pins))
-        print('')
-        print('const pin_obj_t machine_board_pin_obj[{:d}] = {{'.format(num_board_pins))
+        print("")
+        print("const uint8_t machine_pin_num_of_board_pins = {:d};".format(num_board_pins))
+        print("")
+        print("const pin_obj_t machine_board_pin_obj[{:d}] = {{".format(num_board_pins))
         for named_pin in self.cpu_pins:
             pin = named_pin.pin()
             if pin.is_board_pin():
                 pin.print_const_table_entry()
-        print('};');
+        print("};")
 
     def print(self):
-        self.print_named('cpu', self.cpu_pins)
-        print('')
-        self.print_named('board', self.board_pins)
+        self.print_named("cpu", self.cpu_pins)
+        print("")
+        self.print_named("board", self.board_pins)
 
     def print_adc(self, adc_num):
-        print('');
-        print('const pin_obj_t * const pin_adc{:d}[] = {{'.format(adc_num))
+        print("")
+        print("const pin_obj_t * const pin_adc{:d}[] = {{".format(adc_num))
         for channel in range(16):
             adc_found = False
             for named_pin in self.cpu_pins:
                 pin = named_pin.pin()
-                if (pin.is_board_pin() and
-                    (pin.adc_num & (1 << (adc_num - 1))) and (pin.adc_channel == channel)):
-                    print('  &pin_{:s}, // {:d}'.format(pin.cpu_pin_name(), channel))
+                if (
+                    pin.is_board_pin()
+                    and (pin.adc_num & (1 << (adc_num - 1)))
+                    and (pin.adc_channel == channel)
+                ):
+                    print("  &pin_{:s}, // {:d}".format(pin.cpu_pin_name(), channel))
                     adc_found = True
                     break
             if not adc_found:
-                print('  NULL,    // {:d}'.format(channel))
-        print('};')
-
+                print("  NULL,    // {:d}".format(channel))
+        print("};")
 
     def print_header(self, hdr_filename):
-        with open(hdr_filename, 'wt') as hdr_file:
+        with open(hdr_filename, "wt") as hdr_file:
             for named_pin in self.cpu_pins:
                 pin = named_pin.pin()
                 if pin.is_board_pin():
                     pin.print_header(hdr_file)
-            hdr_file.write('extern const pin_obj_t * const pin_adc1[];\n')
-            hdr_file.write('extern const pin_obj_t * const pin_adc2[];\n')
-            hdr_file.write('extern const pin_obj_t * const pin_adc3[];\n')
+            hdr_file.write("extern const pin_obj_t * const pin_adc1[];\n")
+            hdr_file.write("extern const pin_obj_t * const pin_adc2[];\n")
+            hdr_file.write("extern const pin_obj_t * const pin_adc3[];\n")
 
     def print_qstr(self, qstr_filename):
-        with open(qstr_filename, 'wt') as qstr_file:
+        with open(qstr_filename, "wt") as qstr_file:
             qstr_set = set([])
             for named_pin in self.cpu_pins:
                 pin = named_pin.pin()
@@ -304,11 +323,10 @@
             for named_pin in self.board_pins:
                 qstr_set |= set([named_pin.name()])
             for qstr in sorted(qstr_set):
-                print('Q({})'.format(qstr), file=qstr_file)
-
+                print("Q({})".format(qstr), file=qstr_file)
 
     def print_af_hdr(self, af_const_filename):
-        with open(af_const_filename,  'wt') as af_const_file:
+        with open(af_const_filename, "wt") as af_const_file:
             af_hdr_set = set([])
             mux_name_width = 0
             for named_pin in self.cpu_pins:
@@ -321,88 +339,89 @@
                             if len(mux_name) > mux_name_width:
                                 mux_name_width = len(mux_name)
             for mux_name in sorted(af_hdr_set):
-                key = 'MP_ROM_QSTR(MP_QSTR_{}),'.format(mux_name)
-                val = 'MP_ROM_INT(GPIO_{})'.format(mux_name)
-                print('    { %-*s %s },' % (mux_name_width + 26, key, val),
-                      file=af_const_file)
+                key = "MP_ROM_QSTR(MP_QSTR_{}),".format(mux_name)
+                val = "MP_ROM_INT(GPIO_{})".format(mux_name)
+                print("    { %-*s %s }," % (mux_name_width + 26, key, val), file=af_const_file)
 
     def print_af_py(self, af_py_filename):
-        with open(af_py_filename,  'wt') as af_py_file:
-            print('PINS_AF = (', file=af_py_file);
+        with open(af_py_filename, "wt") as af_py_file:
+            print("PINS_AF = (", file=af_py_file)
             for named_pin in self.board_pins:
-                print("  ('%s', " % named_pin.name(), end='', file=af_py_file)
+                print("  ('%s', " % named_pin.name(), end="", file=af_py_file)
                 for af in named_pin.pin().alt_fn:
                     if af.is_supported():
-                        print("(%d, '%s'), " % (af.idx, af.af_str), end='', file=af_py_file)
-                print('),', file=af_py_file)
-            print(')',  file=af_py_file)
+                        print("(%d, '%s'), " % (af.idx, af.af_str), end="", file=af_py_file)
+                print("),", file=af_py_file)
+            print(")", file=af_py_file)
 
 
 def main():
     parser = argparse.ArgumentParser(
         prog="make-pins.py",
         usage="%(prog)s [options] [command]",
-        description="Generate board specific pin file"
+        description="Generate board specific pin file",
     )
     parser.add_argument(
-        "-a", "--af",
+        "-a",
+        "--af",
         dest="af_filename",
         help="Specifies the alternate function file for the chip",
-        default="nrf.csv"
+        default="nrf.csv",
     )
     parser.add_argument(
         "--af-const",
         dest="af_const_filename",
         help="Specifies header file for alternate function constants.",
-        default="build/pins_af_const.h"
+        default="build/pins_af_const.h",
     )
     parser.add_argument(
         "--af-py",
         dest="af_py_filename",
         help="Specifies the filename for the python alternate function mappings.",
-        default="build/pins_af.py"
+        default="build/pins_af.py",
     )
     parser.add_argument(
-        "-b", "--board",
-        dest="board_filename",
-        help="Specifies the board file",
+        "-b", "--board", dest="board_filename", help="Specifies the board file",
     )
     parser.add_argument(
-        "-p", "--prefix",
+        "-p",
+        "--prefix",
         dest="prefix_filename",
         help="Specifies beginning portion of generated pins file",
-        default="nrf52_prefix.c"
+        default="nrf52_prefix.c",
     )
     parser.add_argument(
-        "-q", "--qstr",
+        "-q",
+        "--qstr",
         dest="qstr_filename",
         help="Specifies name of generated qstr header file",
-        default="build/pins_qstr.h"
+        default="build/pins_qstr.h",
     )
     parser.add_argument(
-        "-r", "--hdr",
+        "-r",
+        "--hdr",
         dest="hdr_filename",
         help="Specifies name of generated pin header file",
-        default="build/pins.h"
+        default="build/pins.h",
     )
     args = parser.parse_args(sys.argv[1:])
 
     pins = Pins()
 
-    print('// This file was automatically generated by make-pins.py')
-    print('//')
+    print("// This file was automatically generated by make-pins.py")
+    print("//")
     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, 1, 2, 2)
 
     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)
 
     if args.prefix_filename:
-        print('// --prefix {:s}'.format(args.prefix_filename))
-        print('')
-        with open(args.prefix_filename, 'r') as prefix_file:
+        print("// --prefix {:s}".format(args.prefix_filename))
+        print("")
+        with open(args.prefix_filename, "r") as prefix_file:
             print(prefix_file.read())
 
     pins.print_const_table()
diff --git a/ports/nrf/examples/mountsd.py b/ports/nrf/examples/mountsd.py
index 037b325..315205c 100644
--- a/ports/nrf/examples/mountsd.py
+++ b/ports/nrf/examples/mountsd.py
@@ -24,12 +24,13 @@
 from machine import SPI, Pin
 from sdcard import SDCard
 
+
 def mnt():
     cs = Pin("P22", mode=Pin.OUT)
     sd = SDCard(SPI(0), cs)
-    os.mount(sd, '/')
+    os.mount(sd, "/")
+
 
 def list():
     files = os.listdir()
     print(files)
-
diff --git a/ports/nrf/examples/musictest.py b/ports/nrf/examples/musictest.py
index 46276d3..8f45238 100644
--- a/ports/nrf/examples/musictest.py
+++ b/ports/nrf/examples/musictest.py
@@ -1,4 +1,4 @@
-# 
+#
 # Example usage where "P3" is the Buzzer pin.
 #
 #  from musictest import play
@@ -8,6 +8,7 @@
 from machine import Pin
 import music
 
+
 def play(pin_str):
     p = Pin(pin_str, mode=Pin.OUT)
     music.play(music.PRELUDE, pin=p)
diff --git a/ports/nrf/examples/nrf52_pwm.py b/ports/nrf/examples/nrf52_pwm.py
index b242ea9..ce3fa32 100644
--- a/ports/nrf/examples/nrf52_pwm.py
+++ b/ports/nrf/examples/nrf52_pwm.py
@@ -1,6 +1,7 @@
 import time
 from machine import PWM, Pin
 
+
 def pulse():
     for i in range(0, 101):
         p = PWM(0, Pin("P17", mode=Pin.OUT), freq=PWM.FREQ_16MHZ, duty=i, period=16000)
@@ -9,7 +10,7 @@
         p.deinit()
 
     for i in range(0, 101):
-        p = PWM(0, Pin("P17", mode=Pin.OUT), freq=PWM.FREQ_16MHZ, duty=100-i, period=16000)
+        p = PWM(0, Pin("P17", mode=Pin.OUT), freq=PWM.FREQ_16MHZ, duty=100 - i, period=16000)
         p.init()
         time.sleep_ms(10)
         p.deinit()
diff --git a/ports/nrf/examples/nrf52_servo.py b/ports/nrf/examples/nrf52_servo.py
index baa8600..5506303 100644
--- a/ports/nrf/examples/nrf52_servo.py
+++ b/ports/nrf/examples/nrf52_servo.py
@@ -25,26 +25,34 @@
 import time
 from machine import PWM, Pin
 
-class Servo():
+
+class Servo:
     def __init__(self, pin_name=""):
         if pin_name:
             self.pin = Pin(pin_name, mode=Pin.OUT, pull=Pin.PULL_DOWN)
         else:
             self.pin = Pin("P22", mode=Pin.OUT, pull=Pin.PULL_DOWN)
+
     def left(self):
-        p = PWM(0, self.pin, freq=PWM.FREQ_125KHZ, pulse_width=105, period=2500, mode=PWM.MODE_HIGH_LOW)
+        p = PWM(
+            0, self.pin, freq=PWM.FREQ_125KHZ, pulse_width=105, period=2500, mode=PWM.MODE_HIGH_LOW
+        )
         p.init()
         time.sleep_ms(200)
         p.deinit()
-        
+
     def center(self):
-        p = PWM(0, self.pin, freq=PWM.FREQ_125KHZ, pulse_width=188, period=2500, mode=PWM.MODE_HIGH_LOW)
+        p = PWM(
+            0, self.pin, freq=PWM.FREQ_125KHZ, pulse_width=188, period=2500, mode=PWM.MODE_HIGH_LOW
+        )
         p.init()
         time.sleep_ms(200)
         p.deinit()
-        
+
     def right(self):
-        p = PWM(0, self.pin, freq=PWM.FREQ_125KHZ, pulse_width=275, period=2500, mode=PWM.MODE_HIGH_LOW)
+        p = PWM(
+            0, self.pin, freq=PWM.FREQ_125KHZ, pulse_width=275, period=2500, mode=PWM.MODE_HIGH_LOW
+        )
         p.init()
         time.sleep_ms(200)
         p.deinit()
diff --git a/ports/nrf/examples/powerup.py b/ports/nrf/examples/powerup.py
index 6f14309..2ecc639 100644
--- a/ports/nrf/examples/powerup.py
+++ b/ports/nrf/examples/powerup.py
@@ -41,22 +41,25 @@
 from machine import Pin
 from ubluepy import Peripheral, Scanner, constants
 
+
 def bytes_to_str(bytes):
     string = ""
     for b in bytes:
         string += chr(b)
     return string
 
+
 def get_device_names(scan_entries):
     dev_names = []
     for e in scan_entries:
         scan = e.getScanData()
         if scan:
             for s in scan:
-               if s[0] == constants.ad_types.AD_TYPE_COMPLETE_LOCAL_NAME:
-                   dev_names.append((e, bytes_to_str(s[2])))
+                if s[0] == constants.ad_types.AD_TYPE_COMPLETE_LOCAL_NAME:
+                    dev_names.append((e, bytes_to_str(s[2])))
     return dev_names
 
+
 def find_device_by_name(name):
     s = Scanner()
     scan_res = s.scan(500)
@@ -66,6 +69,7 @@
         if name == dev[1]:
             return dev[0]
 
+
 class PowerUp3:
     def __init__(self):
         self.x_adc = ADC(1)
@@ -76,14 +80,14 @@
         self.btn_speed_off = Pin("P16", mode=Pin.IN, pull=Pin.PULL_UP)
 
         self.x_mid = 0
-        
+
         self.calibrate()
         self.connect()
         self.loop()
-        
+
     def read_stick_x(self):
         return self.x_adc.value()
-        
+
     def button_speed_up(self):
         return not bool(self.btn_speed_up.value())
 
@@ -146,7 +150,7 @@
             self.angle(0)
 
     def rudder_left(self, angle):
-        steps = (angle // self.interval_size_left)
+        steps = angle // self.interval_size_left
         new_angle = 60 - steps
 
         if self.old_angle != new_angle:
@@ -154,7 +158,7 @@
             self.old_angle = new_angle
 
     def rudder_right(self, angle):
-        steps = (angle // self.interval_size_right)
+        steps = angle // self.interval_size_right
         new_angle = -steps
 
         if self.old_angle != new_angle:
@@ -162,9 +166,9 @@
             self.old_angle = new_angle
 
     def throttle(self, speed):
-        if (speed > 200):
+        if speed > 200:
             speed = 200
-        elif (speed < 0):
+        elif speed < 0:
             speed = 0
 
         if self.old_speed != speed:
@@ -188,10 +192,10 @@
 
             # read out new angle
             new_angle = self.read_stick_x()
-            if (new_angle < 256):
-                if (new_angle > right_threshold):
+            if new_angle < 256:
+                if new_angle > right_threshold:
                     self.rudder_right(new_angle - self.x_mid)
-                elif (new_angle < left_threshold):
+                elif new_angle < left_threshold:
                     self.rudder_left(new_angle)
                 else:
                     self.rudder_center()
diff --git a/ports/nrf/examples/seeed_tft.py b/ports/nrf/examples/seeed_tft.py
index c5cd4cc..bf246be 100644
--- a/ports/nrf/examples/seeed_tft.py
+++ b/ports/nrf/examples/seeed_tft.py
@@ -51,24 +51,28 @@
 from machine import SPI, Pin
 from sdcard import SDCard
 
+
 def mount_tf(self, mount_point="/"):
     sd = SDCard(SPI(0), Pin("P15", mode=Pin.OUT))
     os.mount(sd, mount_point)
 
+
 class ILI9341:
     def __init__(self, width, height):
         self.width = width
         self.height = height
         self.pages = self.height // 8
         self.buffer = bytearray(self.pages * self.width)
-        self.framebuf = framebuf.FrameBuffer(self.buffer, self.width, self.height, framebuf.MONO_VLSB)
+        self.framebuf = framebuf.FrameBuffer(
+            self.buffer, self.width, self.height, framebuf.MONO_VLSB
+        )
 
         self.spi = SPI(0)
         # chip select
         self.cs = Pin("P16", mode=Pin.OUT, pull=Pin.PULL_UP)
         # command
         self.dc = Pin("P17", mode=Pin.OUT, pull=Pin.PULL_UP)
-        
+
         # initialize all pins high
         self.cs.high()
         self.dc.high()
@@ -76,27 +80,26 @@
         self.spi.init(baudrate=8000000, phase=0, polarity=0)
 
         self.init_display()
-        
 
     def init_display(self):
         time.sleep_ms(500)
-        
+
         self.write_cmd(0x01)
-        
+
         time.sleep_ms(200)
-    
+
         self.write_cmd(0xCF)
         self.write_data(bytearray([0x00, 0x8B, 0x30]))
-    
+
         self.write_cmd(0xED)
         self.write_data(bytearray([0x67, 0x03, 0x12, 0x81]))
 
         self.write_cmd(0xE8)
         self.write_data(bytearray([0x85, 0x10, 0x7A]))
-    
+
         self.write_cmd(0xCB)
         self.write_data(bytearray([0x39, 0x2C, 0x00, 0x34, 0x02]))
-    
+
         self.write_cmd(0xF7)
         self.write_data(bytearray([0x20]))
 
@@ -107,54 +110,94 @@
         self.write_cmd(0xC0)
         # VRH[5:0]
         self.write_data(bytearray([0x1B]))
-        
+
         # Power control
         self.write_cmd(0xC1)
         # SAP[2:0];BT[3:0]
         self.write_data(bytearray([0x10]))
-        
+
         # VCM control
         self.write_cmd(0xC5)
         self.write_data(bytearray([0x3F, 0x3C]))
-    
+
         # VCM control2
         self.write_cmd(0xC7)
         self.write_data(bytearray([0xB7]))
-    
+
         # Memory Access Control
         self.write_cmd(0x36)
         self.write_data(bytearray([0x08]))
-    
+
         self.write_cmd(0x3A)
         self.write_data(bytearray([0x55]))
-    
+
         self.write_cmd(0xB1)
         self.write_data(bytearray([0x00, 0x1B]))
-        
+
         # Display Function Control
         self.write_cmd(0xB6)
         self.write_data(bytearray([0x0A, 0xA2]))
-    
+
         # 3Gamma Function Disable
         self.write_cmd(0xF2)
         self.write_data(bytearray([0x00]))
-        
+
         # Gamma curve selected
         self.write_cmd(0x26)
         self.write_data(bytearray([0x01]))
-    
+
         # Set Gamma
         self.write_cmd(0xE0)
-        self.write_data(bytearray([0x0F, 0x2A, 0x28, 0x08, 0x0E, 0x08, 0x54, 0XA9, 0x43, 0x0A, 0x0F, 0x00, 0x00, 0x00, 0x00]))
-    
+        self.write_data(
+            bytearray(
+                [
+                    0x0F,
+                    0x2A,
+                    0x28,
+                    0x08,
+                    0x0E,
+                    0x08,
+                    0x54,
+                    0xA9,
+                    0x43,
+                    0x0A,
+                    0x0F,
+                    0x00,
+                    0x00,
+                    0x00,
+                    0x00,
+                ]
+            )
+        )
+
         # Set Gamma
-        self.write_cmd(0XE1)
-        self.write_data(bytearray([0x00, 0x15, 0x17, 0x07, 0x11, 0x06, 0x2B, 0x56, 0x3C, 0x05, 0x10, 0x0F, 0x3F, 0x3F, 0x0F]))
-        
+        self.write_cmd(0xE1)
+        self.write_data(
+            bytearray(
+                [
+                    0x00,
+                    0x15,
+                    0x17,
+                    0x07,
+                    0x11,
+                    0x06,
+                    0x2B,
+                    0x56,
+                    0x3C,
+                    0x05,
+                    0x10,
+                    0x0F,
+                    0x3F,
+                    0x3F,
+                    0x0F,
+                ]
+            )
+        )
+
         # Exit Sleep
         self.write_cmd(0x11)
         time.sleep_ms(120)
-        
+
         # Display on
         self.write_cmd(0x29)
         time.sleep_ms(500)
@@ -164,14 +207,14 @@
         # set col
         self.write_cmd(0x2A)
         self.write_data(bytearray([0x00, 0x00]))
-        self.write_data(bytearray([0x00, 0xef]))
-        
-        # set page 
+        self.write_data(bytearray([0x00, 0xEF]))
+
+        # set page
         self.write_cmd(0x2B)
         self.write_data(bytearray([0x00, 0x00]))
-        self.write_data(bytearray([0x01, 0x3f]))
+        self.write_data(bytearray([0x01, 0x3F]))
 
-        self.write_cmd(0x2c);
+        self.write_cmd(0x2C)
 
         num_of_pixels = self.height * self.width
 
@@ -201,10 +244,9 @@
         self.cs.low()
         self.spi.write(bytearray([cmd]))
         self.cs.high()
-        
+
     def write_data(self, buf):
         self.dc.high()
         self.cs.low()
         self.spi.write(buf)
         self.cs.high()
-
diff --git a/ports/nrf/examples/ssd1306_mod.py b/ports/nrf/examples/ssd1306_mod.py
index d9614e5..b083a3a 100644
--- a/ports/nrf/examples/ssd1306_mod.py
+++ b/ports/nrf/examples/ssd1306_mod.py
@@ -20,11 +20,11 @@
 
 from ssd1306 import SSD1306_I2C
 
-SET_COL_ADDR        = const(0x21)
-SET_PAGE_ADDR       = const(0x22)
+SET_COL_ADDR = const(0x21)
+SET_PAGE_ADDR = const(0x22)
+
 
 class SSD1306_I2C_Mod(SSD1306_I2C):
-
     def show(self):
         x0 = 0
         x1 = self.width - 1
@@ -39,16 +39,15 @@
         self.write_cmd(0)
         self.write_cmd(self.pages - 1)
 
-        chunk_size = 254 # 255, excluding opcode.
+        chunk_size = 254  # 255, excluding opcode.
         num_of_chunks = len(self.buffer) // chunk_size
         leftover = len(self.buffer) - (num_of_chunks * chunk_size)
 
         for i in range(0, num_of_chunks):
-            self.write_data(self.buffer[chunk_size*i:chunk_size*(i+1)])
-        if (leftover > 0):
-            self.write_data(self.buffer[chunk_size * num_of_chunks:])
-
+            self.write_data(self.buffer[chunk_size * i : chunk_size * (i + 1)])
+        if leftover > 0:
+            self.write_data(self.buffer[chunk_size * num_of_chunks :])
 
     def write_data(self, buf):
-        buffer = bytearray([0x40]) + buf # Co=0, D/C#=1
+        buffer = bytearray([0x40]) + buf  # Co=0, D/C#=1
         self.i2c.writeto(self.addr, buffer)
diff --git a/ports/nrf/examples/ubluepy_eddystone.py b/ports/nrf/examples/ubluepy_eddystone.py
index c8abd5a..1ebb236 100644
--- a/ports/nrf/examples/ubluepy_eddystone.py
+++ b/ports/nrf/examples/ubluepy_eddystone.py
@@ -1,13 +1,16 @@
 from ubluepy import Peripheral, constants
 
-BLE_GAP_ADV_FLAG_LE_GENERAL_DISC_MODE       = const(0x02)
-BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED       = const(0x04)
+BLE_GAP_ADV_FLAG_LE_GENERAL_DISC_MODE = const(0x02)
+BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED = const(0x04)
 
-BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE = const(BLE_GAP_ADV_FLAG_LE_GENERAL_DISC_MODE | BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED)
+BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE = const(
+    BLE_GAP_ADV_FLAG_LE_GENERAL_DISC_MODE | BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED
+)
 
-EDDYSTONE_FRAME_TYPE_URL                    = const(0x10)
-EDDYSTONE_URL_PREFIX_HTTP_WWW               = const(0x00) # "http://www".
-EDDYSTONE_URL_SUFFIX_DOT_COM                = const(0x01) # ".com"
+EDDYSTONE_FRAME_TYPE_URL = const(0x10)
+EDDYSTONE_URL_PREFIX_HTTP_WWW = const(0x00)  # "http://www".
+EDDYSTONE_URL_SUFFIX_DOT_COM = const(0x01)  # ".com"
+
 
 def string_to_binarray(text):
     b = bytearray([])
@@ -15,6 +18,7 @@
         b.append(ord(c))
     return b
 
+
 def gen_ad_type_content(ad_type, data):
     b = bytearray(1)
     b.append(ad_type)
@@ -22,6 +26,7 @@
     b[0] = len(b) - 1
     return b
 
+
 def generate_eddystone_adv_packet(url):
     # flags
     disc_mode = bytearray([BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE])
@@ -29,10 +34,12 @@
 
     # 16-bit uuid
     uuid = bytearray([0xAA, 0xFE])
-    packet_uuid16 = gen_ad_type_content(constants.ad_types.AD_TYPE_16BIT_SERVICE_UUID_COMPLETE, uuid)
+    packet_uuid16 = gen_ad_type_content(
+        constants.ad_types.AD_TYPE_16BIT_SERVICE_UUID_COMPLETE, uuid
+    )
 
     # eddystone data
-    rssi = 0xEE # -18 dB, approx signal strength at 0m.
+    rssi = 0xEE  # -18 dB, approx signal strength at 0m.
     eddystone_data = bytearray([])
     eddystone_data.append(EDDYSTONE_FRAME_TYPE_URL)
     eddystone_data.append(rssi)
@@ -42,7 +49,9 @@
 
     # service data
     service_data = uuid + eddystone_data
-    packet_service_data = gen_ad_type_content(constants.ad_types.AD_TYPE_SERVICE_DATA, service_data)
+    packet_service_data = gen_ad_type_content(
+        constants.ad_types.AD_TYPE_SERVICE_DATA, service_data
+    )
 
     # generate advertisment packet
     packet = bytearray([])
@@ -52,7 +61,8 @@
 
     return packet
 
+
 def start():
-    adv_packet = generate_eddystone_adv_packet("micropython")  
+    adv_packet = generate_eddystone_adv_packet("micropython")
     p = Peripheral()
-    p.advertise(data=adv_packet, connectable=False)
\ No newline at end of file
+    p.advertise(data=adv_packet, connectable=False)
diff --git a/ports/nrf/examples/ubluepy_scan.py b/ports/nrf/examples/ubluepy_scan.py
index ab11661..37daa6c 100644
--- a/ports/nrf/examples/ubluepy_scan.py
+++ b/ports/nrf/examples/ubluepy_scan.py
@@ -1,38 +1,42 @@
 from ubluepy import Scanner, constants
 
+
 def bytes_to_str(bytes):
     string = ""
     for b in bytes:
         string += chr(b)
     return string
 
+
 def get_device_names(scan_entries):
     dev_names = []
     for e in scan_entries:
         scan = e.getScanData()
         if scan:
             for s in scan:
-               if s[0] == constants.ad_types.AD_TYPE_COMPLETE_LOCAL_NAME:
-                   dev_names.append((e, bytes_to_str(s[2])))
+                if s[0] == constants.ad_types.AD_TYPE_COMPLETE_LOCAL_NAME:
+                    dev_names.append((e, bytes_to_str(s[2])))
     return dev_names
 
+
 def find_device_by_name(name):
     s = Scanner()
     scan_res = s.scan(100)
-    
+
     device_names = get_device_names(scan_res)
     for dev in device_names:
         if name == dev[1]:
             return dev[0]
 
+
 # >>> res = find_device_by_name("micr")
 # >>> if res:
 # ...     print("address:", res.addr())
 # ...     print("address type:", res.addr_type())
 # ...     print("rssi:", res.rssi())
-# ...     
-# ...     
-# ... 
+# ...
+# ...
+# ...
 # address: c2:73:61:89:24:45
 # address type: 1
 # rssi: -26
diff --git a/ports/nrf/examples/ubluepy_temp.py b/ports/nrf/examples/ubluepy_temp.py
index 7df057b..f841849 100644
--- a/ports/nrf/examples/ubluepy_temp.py
+++ b/ports/nrf/examples/ubluepy_temp.py
@@ -26,12 +26,13 @@
 from machine import RTCounter, Temp
 from ubluepy import Service, Characteristic, UUID, Peripheral, constants
 
+
 def event_handler(id, handle, data):
     global rtc
     global periph
     global serv_env_sense
     global notif_enabled
- 
+
     if id == constants.EVT_GAP_CONNECTED:
         # indicated 'connected'
         LED(1).on()
@@ -50,11 +51,12 @@
             notif_enabled = True
             # start low power timer
             rtc.start()
-        else: 
+        else:
             notif_enabled = False
             # stop low power timer
             rtc.stop()
 
+
 def send_temp(timer_id):
     global notif_enabled
     global char_temp
@@ -62,26 +64,27 @@
     if notif_enabled:
         # measure chip temperature
         temp = Temp.read()
-        temp =  temp * 100
+        temp = temp * 100
         char_temp.write(bytearray([temp & 0xFF, temp >> 8]))
 
+
 # start off with LED(1) off
 LED(1).off()
 
-# use RTC1 as RTC0 is used by bluetooth stack 
+# use RTC1 as RTC0 is used by bluetooth stack
 # set up RTC callback every 5 second
 rtc = RTCounter(1, period=50, mode=RTCounter.PERIODIC, callback=send_temp)
 
 notif_enabled = False
 
-uuid_env_sense = UUID("0x181A") # Environmental Sensing service
-uuid_temp = UUID("0x2A6E") # Temperature characteristic
- 
+uuid_env_sense = UUID("0x181A")  # Environmental Sensing service
+uuid_temp = UUID("0x2A6E")  # Temperature characteristic
+
 serv_env_sense = Service(uuid_env_sense)
 
 temp_props = Characteristic.PROP_NOTIFY | Characteristic.PROP_READ
 temp_attrs = Characteristic.ATTR_CCCD
-char_temp = Characteristic(uuid_temp, props = temp_props, attrs = temp_attrs)
+char_temp = Characteristic(uuid_temp, props=temp_props, attrs=temp_attrs)
 
 serv_env_sense.addCharacteristic(char_temp)
 
@@ -89,4 +92,3 @@
 periph.addService(serv_env_sense)
 periph.setConnectionHandler(event_handler)
 periph.advertise(device_name="micr_temp", services=[serv_env_sense])
-
diff --git a/ports/nrf/freeze/test.py b/ports/nrf/freeze/test.py
index e64bbc9..ba05ae1 100644
--- a/ports/nrf/freeze/test.py
+++ b/ports/nrf/freeze/test.py
@@ -1,4 +1,5 @@
 import sys
 
+
 def hello():
     print("Hello %s!" % sys.platform)
diff --git a/ports/nrf/gccollect.c b/ports/nrf/gccollect.c
index 68b8188..167825d 100644
--- a/ports/nrf/gccollect.c
+++ b/ports/nrf/gccollect.c
@@ -45,7 +45,7 @@
     uintptr_t sp = get_sp();
 
     // trace the stack, including the registers (since they live on the stack in this function)
-    gc_collect_root((void**)sp, ((uint32_t)&_ram_end - sp) / sizeof(uint32_t));
+    gc_collect_root((void **)sp, ((uint32_t)&_ram_end - sp) / sizeof(uint32_t));
 
     // end the GC
     gc_collect_end();
diff --git a/ports/nrf/help.c b/ports/nrf/help.c
index 5856ef6..afc9791 100644
--- a/ports/nrf/help.c
+++ b/ports/nrf/help.c
@@ -32,23 +32,23 @@
 #endif
 
 const char nrf5_help_text[] =
-"Welcome to MicroPython!\n"
-"\n"
-"For online help please visit http://micropython.org/help/.\n"
-"\n"
-"Quick overview of commands for the board:\n"
+    "Welcome to MicroPython!\n"
+    "\n"
+    "For online help please visit http://micropython.org/help/.\n"
+    "\n"
+    "Quick overview of commands for the board:\n"
 #if MICROPY_HW_HAS_LED
-"  board.LED(n)    -- create an LED object for LED n (n=" HELP_TEXT_BOARD_LED ")\n"
-"\n"
+    "  board.LED(n)    -- create an LED object for LED n (n=" HELP_TEXT_BOARD_LED ")\n"
+    "\n"
 #endif
 #if BLUETOOTH_SD
-HELP_TEXT_SD
+    HELP_TEXT_SD
 #endif
-"Control commands:\n"
-"  CTRL-A        -- on a blank line, enter raw REPL mode\n"
-"  CTRL-B        -- on a blank line, enter normal REPL mode\n"
-"  CTRL-D        -- on a blank line, do a soft reset of the board\n"
-"  CTRL-E        -- on a blank line, enter paste mode\n"
-"\n"
-"For further help on a specific object, type help(obj)\n"
+    "Control commands:\n"
+    "  CTRL-A        -- on a blank line, enter raw REPL mode\n"
+    "  CTRL-B        -- on a blank line, enter normal REPL mode\n"
+    "  CTRL-D        -- on a blank line, do a soft reset of the board\n"
+    "  CTRL-E        -- on a blank line, enter paste mode\n"
+    "\n"
+    "For further help on a specific object, type help(obj)\n"
 ;
diff --git a/ports/nrf/main.c b/ports/nrf/main.c
index af59912..3c5d0a0 100644
--- a/ports/nrf/main.c
+++ b/ports/nrf/main.c
@@ -110,7 +110,7 @@
 
     // Stack limit should be less than real stack size, so we have a chance
     // to recover from limit hit.  (Limit is measured in bytes.)
-    mp_stack_set_limit((char*)&_ram_end - (char*)&_heap_end - 400);
+    mp_stack_set_limit((char *)&_ram_end - (char *)&_heap_end - 400);
 
     machine_init();
 
@@ -124,35 +124,35 @@
     readline_init0();
 
 
-#if MICROPY_PY_MACHINE_HW_SPI
+    #if MICROPY_PY_MACHINE_HW_SPI
     spi_init0();
-#endif
+    #endif
 
-#if MICROPY_PY_MACHINE_I2C
+    #if MICROPY_PY_MACHINE_I2C
     i2c_init0();
-#endif
+    #endif
 
-#if MICROPY_PY_MACHINE_ADC
+    #if MICROPY_PY_MACHINE_ADC
     adc_init0();
-#endif
+    #endif
 
-#if MICROPY_PY_MACHINE_HW_PWM
+    #if MICROPY_PY_MACHINE_HW_PWM
     pwm_init0();
-#endif
+    #endif
 
-#if MICROPY_PY_MACHINE_RTCOUNTER
+    #if MICROPY_PY_MACHINE_RTCOUNTER
     rtc_init0();
-#endif
+    #endif
 
-#if MICROPY_PY_MACHINE_TIMER
+    #if MICROPY_PY_MACHINE_TIMER
     timer_init0();
-#endif
+    #endif
 
-#if MICROPY_PY_MACHINE_UART
+    #if MICROPY_PY_MACHINE_UART
     uart_init0();
-#endif
+    #endif
 
-#if (MICROPY_PY_BLE_NUS == 0) && (MICROPY_HW_USB_CDC == 0)
+    #if (MICROPY_PY_BLE_NUS == 0) && (MICROPY_HW_USB_CDC == 0)
     {
         mp_obj_t args[2] = {
             MP_OBJ_NEW_SMALL_INT(0),
@@ -160,15 +160,15 @@
         };
         MP_STATE_PORT(board_stdio_uart) = machine_hard_uart_type.make_new((mp_obj_t)&machine_hard_uart_type, MP_ARRAY_SIZE(args), 0, args);
     }
-#endif
+    #endif
 
-pin_init0();
+    pin_init0();
 
-#if MICROPY_MBFS
+    #if MICROPY_MBFS
     microbit_filesystem_init();
-#endif
+    #endif
 
-#if MICROPY_HW_HAS_SDCARD
+    #if MICROPY_HW_HAS_SDCARD
     // if an SD card is present then mount it on /sd/
     if (sdcard_is_present()) {
         // create vfs object
@@ -197,46 +197,46 @@
             // use SD card as current directory
             f_chdrive("/sd");
         }
-        no_mem_for_sd:;
+    no_mem_for_sd:;
     }
-#endif
+    #endif
 
     // Main script is finished, so now go into REPL mode.
     // The REPL mode can change, or it can request a soft reset.
     int ret_code = 0;
 
-#if MICROPY_PY_BLE_NUS
+    #if MICROPY_PY_BLE_NUS
     ble_uart_init0();
-#endif
+    #endif
 
-#if MICROPY_PY_MACHINE_SOFT_PWM
+    #if MICROPY_PY_MACHINE_SOFT_PWM
     ticker_init0();
     softpwm_init0();
-#endif
+    #endif
 
-#if MICROPY_PY_MUSIC
+    #if MICROPY_PY_MUSIC
     microbit_music_init0();
-#endif
-#if BOARD_SPECIFIC_MODULES
+    #endif
+    #if BOARD_SPECIFIC_MODULES
     board_modules_init0();
-#endif
+    #endif
 
-#if MICROPY_PY_MACHINE_SOFT_PWM
+    #if MICROPY_PY_MACHINE_SOFT_PWM
     ticker_start();
     pwm_start();
-#endif
+    #endif
 
-led_state(1, 0);
+    led_state(1, 0);
 
-#if MICROPY_VFS || MICROPY_MBFS || MICROPY_MODULE_FROZEN
+    #if MICROPY_VFS || MICROPY_MBFS || MICROPY_MODULE_FROZEN
     // run boot.py and main.py if they exist.
     pyexec_file_if_exists("boot.py");
     pyexec_file_if_exists("main.py");
-#endif
+    #endif
 
-#if MICROPY_HW_USB_CDC
+    #if MICROPY_HW_USB_CDC
     usb_cdc_init();
-#endif
+    #endif
 
     for (;;) {
         if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
@@ -255,9 +255,9 @@
 
     printf("MPY: soft reboot\n");
 
-#if BLUETOOTH_SD
+    #if BLUETOOTH_SD
     sd_softdevice_disable();
-#endif
+    #endif
 
     goto soft_reset;
 
@@ -298,9 +298,8 @@
 #endif
 
 
-void HardFault_Handler(void)
-{
-#if defined(NRF52_SERIES) || defined(NRF91_SERIES)
+void HardFault_Handler(void) {
+    #if defined(NRF52_SERIES) || defined(NRF91_SERIES)
     static volatile uint32_t reg;
     static volatile uint32_t reg2;
     static volatile uint32_t bfar;
@@ -312,11 +311,13 @@
         (void)reg2;
         (void)bfar;
     }
-#endif
+    #endif
 }
 
 void NORETURN __fatal_error(const char *msg) {
-    while (1);
+    while (1) {
+        ;
+    }
 }
 
 void nlr_jump_fail(void *val) {
@@ -330,4 +331,6 @@
     __fatal_error("Assertion failed");
 }
 
-void _start(void) {main(0, NULL);}
+void _start(void) {
+    main(0, NULL);
+}
diff --git a/ports/nrf/mpconfigport.h b/ports/nrf/mpconfigport.h
index f0cc68a..2807611 100644
--- a/ports/nrf/mpconfigport.h
+++ b/ports/nrf/mpconfigport.h
@@ -195,7 +195,7 @@
 
 #define BYTES_PER_WORD (4)
 
-#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1))
+#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1))
 
 #define MP_SSIZE_MAX (0x7fffffff)
 
diff --git a/ports/nrf/mphalport.c b/ports/nrf/mphalport.c
index 57d61b0..bdedea9 100644
--- a/ports/nrf/mphalport.c
+++ b/ports/nrf/mphalport.c
@@ -93,16 +93,15 @@
     mp_hal_stdout_tx_strn(str, strlen(str));
 }
 
-void mp_hal_delay_us(mp_uint_t us)
-{
+void mp_hal_delay_us(mp_uint_t us) {
     if (us == 0) {
         return;
     }
-    register uint32_t delay __ASM ("r0") = us;
+    register uint32_t delay __ASM("r0") = us;
     __ASM volatile (
-#ifdef NRF51
-            ".syntax unified\n"
-#endif
+        #ifdef NRF51
+        ".syntax unified\n"
+        #endif
         "1:\n"
         " SUBS %0, %0, #1\n"
         " NOP\n"
@@ -117,7 +116,7 @@
         " NOP\n"
         " NOP\n"
         " NOP\n"
-#if defined(NRF52) || defined(NRF9160_XXAA)
+        #if defined(NRF52) || defined(NRF9160_XXAA)
         " NOP\n"
         " NOP\n"
         " NOP\n"
@@ -164,13 +163,12 @@
         " NOP\n"
         " NOP\n"
         " NOP\n"
-#endif
+        #endif
         " BNE 1b\n"
         : "+r" (delay));
 }
 
-void mp_hal_delay_ms(mp_uint_t ms)
-{
+void mp_hal_delay_ms(mp_uint_t ms) {
     for (mp_uint_t i = 0; i < ms; i++)
     {
         mp_hal_delay_us(999);
@@ -181,21 +179,21 @@
 
 static const char nrfx_error_unknown[1] = "";
 
-static const char nrfx_error_success[]            = "NRFX_SUCCESS";
-static const char nrfx_error_internal[]           = "NRFX_ERROR_INTERNAL";
-static const char nrfx_error_no_mem[]             = "NRFX_ERROR_NO_MEM";
-static const char nrfx_error_not_supported[]      = "NRFX_ERROR_NOT_SUPPORTED";
-static const char nrfx_error_invalid_param[]      = "NRFX_ERROR_INVALID_PARAM";
-static const char nrfx_error_invalid_state[]      = "NRFX_ERROR_INVALID_STATE";
-static const char nrfx_error_invalid_length[]     = "NRFX_ERROR_INVALID_LENGTH";
-static const char nrfx_error_timeout[]            = "NRFX_ERROR_TIMEOUT";
-static const char nrfx_error_forbidden[]          = "NRFX_ERROR_FORBIDDEN";
-static const char nrfx_error_null[]               = "NRFX_ERROR_NULL";
-static const char nrfx_error_invalid_addr[]       = "NRFX_ERROR_INVALID_ADDR";
-static const char nrfx_error_busy[]               = "NRFX_ERROR_BUSY";
+static const char nrfx_error_success[] = "NRFX_SUCCESS";
+static const char nrfx_error_internal[] = "NRFX_ERROR_INTERNAL";
+static const char nrfx_error_no_mem[] = "NRFX_ERROR_NO_MEM";
+static const char nrfx_error_not_supported[] = "NRFX_ERROR_NOT_SUPPORTED";
+static const char nrfx_error_invalid_param[] = "NRFX_ERROR_INVALID_PARAM";
+static const char nrfx_error_invalid_state[] = "NRFX_ERROR_INVALID_STATE";
+static const char nrfx_error_invalid_length[] = "NRFX_ERROR_INVALID_LENGTH";
+static const char nrfx_error_timeout[] = "NRFX_ERROR_TIMEOUT";
+static const char nrfx_error_forbidden[] = "NRFX_ERROR_FORBIDDEN";
+static const char nrfx_error_null[] = "NRFX_ERROR_NULL";
+static const char nrfx_error_invalid_addr[] = "NRFX_ERROR_INVALID_ADDR";
+static const char nrfx_error_busy[] = "NRFX_ERROR_BUSY";
 static const char nrfx_error_already_initalized[] = "NRFX_ERROR_ALREADY_INITIALIZED";
 
-static const char * nrfx_error_strings[13] = {
+static const char *nrfx_error_strings[13] = {
     nrfx_error_success,
     nrfx_error_internal,
     nrfx_error_no_mem,
@@ -212,16 +210,16 @@
 };
 
 static const char nrfx_drv_error_twi_err_overrun[] = "NRFX_ERROR_DRV_TWI_ERR_OVERRUN";
-static const char nrfx_drv_error_twi_err_anack[]   = "NRFX_ERROR_DRV_TWI_ERR_ANACK";
-static const char nrfx_drv_error_twi_err_dnack[]   = "NRFX_ERROR_DRV_TWI_ERR_DNACK";
+static const char nrfx_drv_error_twi_err_anack[] = "NRFX_ERROR_DRV_TWI_ERR_ANACK";
+static const char nrfx_drv_error_twi_err_dnack[] = "NRFX_ERROR_DRV_TWI_ERR_DNACK";
 
-static const char * nrfx_drv_error_strings[3] = {
+static const char *nrfx_drv_error_strings[3] = {
     nrfx_drv_error_twi_err_overrun,
     nrfx_drv_error_twi_err_anack,
     nrfx_drv_error_twi_err_dnack
 };
 
-const char * nrfx_error_code_lookup(uint32_t err_code) {
+const char *nrfx_error_code_lookup(uint32_t err_code) {
     if (err_code >= NRFX_ERROR_BASE_NUM && err_code <= NRFX_ERROR_BASE_NUM + 13) {
         return nrfx_error_strings[err_code - NRFX_ERROR_BASE_NUM];
     } else if (err_code >= NRFX_ERROR_DRIVERS_BASE_NUM && err_code <= NRFX_ERROR_DRIVERS_BASE_NUM + 3) {
diff --git a/ports/nrf/mphalport.h b/ports/nrf/mphalport.h
index 23df0c0..5614be2 100644
--- a/ports/nrf/mphalport.h
+++ b/ports/nrf/mphalport.h
@@ -35,10 +35,10 @@
 
 typedef enum
 {
-  HAL_OK       = 0x00,
-  HAL_ERROR    = 0x01,
-  HAL_BUSY     = 0x02,
-  HAL_TIMEOUT  = 0x03
+    HAL_OK       = 0x00,
+    HAL_ERROR    = 0x01,
+    HAL_BUSY     = 0x02,
+    HAL_TIMEOUT  = 0x03
 } HAL_StatusTypeDef;
 
 static inline uint32_t hal_tick_fake(void) {
@@ -58,9 +58,9 @@
 void mp_hal_delay_ms(mp_uint_t ms);
 void mp_hal_delay_us(mp_uint_t us);
 
-const char * nrfx_error_code_lookup(uint32_t err_code);
+const char *nrfx_error_code_lookup(uint32_t err_code);
 
-#define mp_hal_pin_obj_t const pin_obj_t*
+#define mp_hal_pin_obj_t const pin_obj_t *
 #define mp_hal_get_pin_obj(o)    pin_find(o)
 #define mp_hal_pin_high(p)       nrf_gpio_pin_set(p->pin)
 #define mp_hal_pin_low(p)        nrf_gpio_pin_clear(p->pin)
diff --git a/ports/nrf/nrfx_config.h b/ports/nrf/nrfx_config.h
index 65b37e6..6fe5aca 100644
--- a/ports/nrf/nrfx_config.h
+++ b/ports/nrf/nrfx_config.h
@@ -106,9 +106,9 @@
   #define NRFX_SPIM0_ENABLED 1
   #define NRFX_SPIM1_ENABLED 1
 
-  // 0 NRF_GPIO_PIN_NOPULL
-  // 1 NRF_GPIO_PIN_PULLDOWN
-  // 3 NRF_GPIO_PIN_PULLUP
+// 0 NRF_GPIO_PIN_NOPULL
+// 1 NRF_GPIO_PIN_PULLDOWN
+// 3 NRF_GPIO_PIN_PULLUP
   #define NRFX_SPIM_MISO_PULL_CFG 1
 #endif // NRF51
 
diff --git a/ports/nrf/nrfx_glue.h b/ports/nrf/nrfx_glue.h
index ffd2cff..153403f 100644
--- a/ports/nrf/nrfx_glue.h
+++ b/ports/nrf/nrfx_glue.h
@@ -53,7 +53,7 @@
         } else { \
             NVIC_EnableIRQ(irq_number); \
         } \
-    } while(0)
+    } while (0)
 #else
 #define NRFX_IRQ_ENABLE(irq_number) sd_nvic_EnableIRQ(irq_number)
 #endif
@@ -67,7 +67,7 @@
         } else { \
             NVIC_DisableIRQ(irq_number); \
         } \
-    } while(0)
+    } while (0)
 #else
 #define NRFX_IRQ_DISABLE(irq_number) sd_nvic_DisableIRQ(irq_number)
 #endif
@@ -81,7 +81,7 @@
         } else { \
             NVIC_SetPriority(irq_number, priority); \
         } \
-    } while(0)
+    } while (0)
 #else
 #define NRFX_IRQ_PRIORITY_SET(irq_number, priority) sd_nvic_SetPriority(irq_number, priority)
 #endif
@@ -95,7 +95,7 @@
         } else { \
             NVIC_SetPendingIRQ(irq_number); \
         } \
-    } while(0)
+    } while (0)
 #else
 #define NRFX_IRQ_PENDING_SET(irq_number) sd_nvic_SetPendingIRQ(irq_number)
 #endif
@@ -109,7 +109,7 @@
         } else { \
             NVIC_ClearPendingIRQ(irq_number)(irq_number); \
         } \
-    } while(0)
+    } while (0)
 #else
 #define NRFX_IRQ_PENDING_CLEAR(irq_number) sd_nvic_ClearPendingIRQ(irq_number)
 #endif
@@ -120,8 +120,8 @@
         sd_nvic_critical_region_enter(&_is_nested_critical_region);
 
 #define NRFX_CRITICAL_SECTION_EXIT() \
-        sd_nvic_critical_region_exit(_is_nested_critical_region); \
-    }
+    sd_nvic_critical_region_exit(_is_nested_critical_region); \
+}
 
 #else // BLUETOOTH_SD
 
diff --git a/ports/nrf/nrfx_log.h b/ports/nrf/nrfx_log.h
index ca2fd58..8710d3f 100644
--- a/ports/nrf/nrfx_log.h
+++ b/ports/nrf/nrfx_log.h
@@ -33,7 +33,7 @@
 
 #define LOG_TEST_UART 1
 
-#define TEST_MODULE_IMPL(x, y) LOG_TEST_ ## x == LOG_TEST_ ## y
+#define TEST_MODULE_IMPL(x, y) LOG_TEST_##x == LOG_TEST_##y
 #define TEST_MODULE(x, y) TEST_MODULE_IMPL(x, y)
 
 #if (!defined(NRFX_LOG_ENABLED) || (NRFX_LOG_ENABLED == 0)) || \
@@ -56,11 +56,11 @@
     #define VALUE(x) VALUE_TO_STR(x)
 
     #define LOG_PRINTF(fmt, ...) \
-        do { \
-            printf("%s: ", VALUE(NRFX_LOG_MODULE)); \
-            printf(fmt, ##__VA_ARGS__); \
-            printf("\n"); \
-        } while (0)
+    do { \
+        printf("%s: ", VALUE(NRFX_LOG_MODULE)); \
+        printf(fmt,##__VA_ARGS__); \
+        printf("\n"); \
+    } while (0)
 
     #define NRFX_LOG_DEBUG   LOG_PRINTF
     #define NRFX_LOG_ERROR   LOG_PRINTF
@@ -77,7 +77,7 @@
     #define NRFX_LOG_HEXDUMP_DEBUG(p_memory, length)
 
     #define NRFX_LOG_ERROR_STRING_GET(error_code) \
-        nrfx_error_code_lookup(error_code)
+    nrfx_error_code_lookup(error_code)
 
 #endif // NRFX_LOG_ENABLED
 
diff --git a/ports/nrf/pin_defs_nrf5.h b/ports/nrf/pin_defs_nrf5.h
index fb2930d..a884c87 100644
--- a/ports/nrf/pin_defs_nrf5.h
+++ b/ports/nrf/pin_defs_nrf5.h
@@ -31,39 +31,39 @@
 #include "nrf_gpio.h"
 
 enum {
-  PORT_A,
-  PORT_B,
+    PORT_A,
+    PORT_B,
 };
 
 enum {
-  AF_FN_UART,
-  AF_FN_SPI,
+    AF_FN_UART,
+    AF_FN_SPI,
 };
 
 enum {
-  AF_PIN_TYPE_UART_TX = 0,
-  AF_PIN_TYPE_UART_RX,
-  AF_PIN_TYPE_UART_CTS,
-  AF_PIN_TYPE_UART_RTS,
+    AF_PIN_TYPE_UART_TX = 0,
+    AF_PIN_TYPE_UART_RX,
+    AF_PIN_TYPE_UART_CTS,
+    AF_PIN_TYPE_UART_RTS,
 
-  AF_PIN_TYPE_SPI_MOSI = 0,
-  AF_PIN_TYPE_SPI_MISO,
-  AF_PIN_TYPE_SPI_SCK,
-  AF_PIN_TYPE_SPI_NSS,
+    AF_PIN_TYPE_SPI_MOSI = 0,
+    AF_PIN_TYPE_SPI_MISO,
+    AF_PIN_TYPE_SPI_SCK,
+    AF_PIN_TYPE_SPI_NSS,
 };
 
 #if defined(NRF51) || defined(NRF52_SERIES)
 #define PIN_DEFS_PORT_AF_UNION \
-    NRF_UART_Type  *UART;
+    NRF_UART_Type *UART;
 //  NRF_SPI_Type  *SPIM;
 //  NRF_SPIS_Type *SPIS;
 #elif defined(NRF91_SERIES)
 #define PIN_DEFS_PORT_AF_UNION \
-    NRF_UARTE_Type  *UART;
+    NRF_UARTE_Type *UART;
 #endif
 
 enum {
-  PIN_ADC1 = (1 << 0),
+    PIN_ADC1 = (1 << 0),
 };
 
 typedef NRF_GPIO_Type pin_gpio_t;
diff --git a/ports/pic16bit/board.c b/ports/pic16bit/board.c
index 0321b0e..977dd2c 100644
--- a/ports/pic16bit/board.c
+++ b/ports/pic16bit/board.c
@@ -79,17 +79,29 @@
 void led_state(int led, int state) {
     int val = state ? LED_ON : LED_OFF;
     switch (led) {
-        case 1: RED_LED = val; break;
-        case 2: YELLOW_LED = val; break;
-        case 3: GREEN_LED = val; break;
+        case 1:
+            RED_LED = val;
+            break;
+        case 2:
+            YELLOW_LED = val;
+            break;
+        case 3:
+            GREEN_LED = val;
+            break;
     }
 }
 
 void led_toggle(int led) {
     switch (led) {
-        case 1: RED_LED ^= 1; break;
-        case 2: YELLOW_LED ^= 1; break;
-        case 3: GREEN_LED ^= 1; break;
+        case 1:
+            RED_LED ^= 1;
+            break;
+        case 2:
+            YELLOW_LED ^= 1;
+            break;
+        case 3:
+            GREEN_LED ^= 1;
+            break;
     }
 }
 
@@ -111,8 +123,12 @@
 int switch_get(int sw) {
     int val = 1;
     switch (sw) {
-        case 1: val = SWITCH_S1; break;
-        case 2: val = SWITCH_S2; break;
+        case 1:
+            val = SWITCH_S1;
+            break;
+        case 2:
+            val = SWITCH_S2;
+            break;
     }
     return val == 0;
 }
diff --git a/ports/pic16bit/main.c b/ports/pic16bit/main.c
index c96ac54..07db3f5 100644
--- a/ports/pic16bit/main.c
+++ b/ports/pic16bit/main.c
@@ -68,7 +68,7 @@
 
     // init MicroPython runtime
     int stack_dummy;
-    MP_STATE_THREAD(stack_top) = (char*)&stack_dummy;
+    MP_STATE_THREAD(stack_top) = (char *)&stack_dummy;
     gc_init(heap, heap + sizeof(heap));
     mp_init();
     mp_hal_init();
@@ -115,11 +115,15 @@
 MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
 
 void nlr_jump_fail(void *val) {
-    while (1);
+    while (1) {
+        ;
+    }
 }
 
 void NORETURN __fatal_error(const char *msg) {
-    while (1);
+    while (1) {
+        ;
+    }
 }
 
 #ifndef NDEBUG
diff --git a/ports/pic16bit/modpyb.c b/ports/pic16bit/modpyb.c
index 6299146..a18b377 100644
--- a/ports/pic16bit/modpyb.c
+++ b/ports/pic16bit/modpyb.c
@@ -66,5 +66,5 @@
 
 const mp_obj_module_t pyb_module = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&pyb_module_globals,
+    .globals = (mp_obj_dict_t *)&pyb_module_globals,
 };
diff --git a/ports/pic16bit/mpconfigport.h b/ports/pic16bit/mpconfigport.h
index 59880dc..a63ff41 100644
--- a/ports/pic16bit/mpconfigport.h
+++ b/ports/pic16bit/mpconfigport.h
@@ -75,7 +75,7 @@
 // 2-byte aligned pointers (see config setting above).
 //#define MICROPY_OBJ_BASE_ALIGNMENT  __attribute__((aligned(4)))
 
-#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p)))
+#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p)))
 
 #define UINT_FMT "%u"
 #define INT_FMT "%d"
diff --git a/ports/powerpc/frozentest.py b/ports/powerpc/frozentest.py
index 0f99b74..78cdd60 100644
--- a/ports/powerpc/frozentest.py
+++ b/ports/powerpc/frozentest.py
@@ -1,7 +1,7 @@
-print('uPy')
-print('a long string that is not interned')
-print('a string that has unicode αβγ chars')
-print(b'bytes 1234\x01')
+print("uPy")
+print("a long string that is not interned")
+print("a string that has unicode αβγ chars")
+print(b"bytes 1234\x01")
 print(123456789)
 for i in range(4):
     print(i)
diff --git a/ports/powerpc/main.c b/ports/powerpc/main.c
index 9b164ac..421f9be 100644
--- a/ports/powerpc/main.c
+++ b/ports/powerpc/main.c
@@ -50,7 +50,8 @@
 void __assert_fail(const char *__assertion, const char *__file,
     unsigned int __line, const char *__function) {
     printf("Assert at %s:%d:%s() \"%s\" failed\n", __file, __line, __function, __assertion);
-    for (;;) ;
+    for (;;) {;
+    }
 }
 
 static char *stack_top;
@@ -62,7 +63,7 @@
 
 int main(int argc, char **argv) {
     int stack_dummy;
-    stack_top = (char*)&stack_dummy;
+    stack_top = (char *)&stack_dummy;
 
     // microwatt has argc/r3 = 0 whereas QEMU has r3 set in head.S
     uart_init_ppc(argc);
@@ -124,11 +125,15 @@
 MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
 
 void nlr_jump_fail(void *val) {
-    while (1);
+    while (1) {
+        ;
+    }
 }
 
 void NORETURN __fatal_error(const char *msg) {
-    while (1);
+    while (1) {
+        ;
+    }
 }
 
 #ifndef NDEBUG
diff --git a/ports/powerpc/mpconfigport.h b/ports/powerpc/mpconfigport.h
index 93ef699..1800b8c 100644
--- a/ports/powerpc/mpconfigport.h
+++ b/ports/powerpc/mpconfigport.h
@@ -93,7 +93,7 @@
 
 // type definitions for the specific machine
 
-#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1))
+#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1))
 
 // This port is 64-bit
 #define UINT_FMT "%lu"
diff --git a/ports/powerpc/mphalport.h b/ports/powerpc/mphalport.h
index c6bf940..bb7fa34 100644
--- a/ports/powerpc/mphalport.h
+++ b/ports/powerpc/mphalport.h
@@ -25,7 +25,7 @@
  */
 
 #define mftb()  ({unsigned long rval;                                   \
-        __asm__ volatile("mftb %0" : "=r" (rval)); rval;})
+                  __asm__ volatile ("mftb %0" : "=r" (rval)); rval;})
 
 #define TBFREQ 512000000
 
diff --git a/ports/powerpc/uart_lpc_serial.c b/ports/powerpc/uart_lpc_serial.c
index 51a55cb..c15fc04 100644
--- a/ports/powerpc/uart_lpc_serial.c
+++ b/ports/powerpc/uart_lpc_serial.c
@@ -101,11 +101,15 @@
 }
 
 char lpc_uart_read(void) {
-    while (lpc_uart_rx_empty()) ;
+    while (lpc_uart_rx_empty()) {
+        ;
+    }
     return lpc_uart_reg_read(REG_THR);
 }
 
 void lpc_uart_write(char c) {
-    while (lpc_uart_tx_full());
+    while (lpc_uart_tx_full()) {
+        ;
+    }
     lpc_uart_reg_write(REG_RBR, c);
 }
diff --git a/ports/powerpc/uart_potato.c b/ports/powerpc/uart_potato.c
index 18f89d4..4a487f3 100644
--- a/ports/powerpc/uart_potato.c
+++ b/ports/powerpc/uart_potato.c
@@ -105,7 +105,9 @@
 char potato_uart_read(void) {
     uint64_t val;
 
-    while (potato_uart_rx_empty());
+    while (potato_uart_rx_empty()) {
+        ;
+    }
     val = potato_uart_reg_read(POTATO_CONSOLE_RX);
 
     return (char)(val & 0x000000ff);
@@ -116,6 +118,8 @@
 
     val = c;
 
-    while (potato_uart_tx_full());
+    while (potato_uart_tx_full()) {
+        ;
+    }
     potato_uart_reg_write(POTATO_CONSOLE_TX, val);
 }
diff --git a/ports/qemu-arm/main.c b/ports/qemu-arm/main.c
index 41bf945..8c49d0c 100644
--- a/ports/qemu-arm/main.c
+++ b/ports/qemu-arm/main.c
@@ -30,8 +30,8 @@
 int main(int argc, char **argv) {
     mp_stack_ctrl_init();
     mp_stack_set_limit(10240);
-    uint32_t heap[16*1024 / 4];
-    gc_init(heap, (char*)heap + 16 * 1024);
+    uint32_t heap[16 * 1024 / 4];
+    gc_init(heap, (char *)heap + 16 * 1024);
     mp_init();
     do_str("print('hello world!')", MP_PARSE_SINGLE_INPUT);
     mp_deinit();
diff --git a/ports/qemu-arm/modmachine.c b/ports/qemu-arm/modmachine.c
index 0f66349..728fd4f 100644
--- a/ports/qemu-arm/modmachine.c
+++ b/ports/qemu-arm/modmachine.c
@@ -43,5 +43,5 @@
 
 const mp_obj_module_t mp_module_machine = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&machine_module_globals,
+    .globals = (mp_obj_dict_t *)&machine_module_globals,
 };
diff --git a/ports/qemu-arm/moduos.c b/ports/qemu-arm/moduos.c
index a48b51d..23a1241 100644
--- a/ports/qemu-arm/moduos.c
+++ b/ports/qemu-arm/moduos.c
@@ -49,5 +49,5 @@
 
 const mp_obj_module_t mp_module_uos = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&os_module_globals,
+    .globals = (mp_obj_dict_t *)&os_module_globals,
 };
diff --git a/ports/qemu-arm/mpconfigport.h b/ports/qemu-arm/mpconfigport.h
index 3d4abd5..498ab3e 100644
--- a/ports/qemu-arm/mpconfigport.h
+++ b/ports/qemu-arm/mpconfigport.h
@@ -43,7 +43,7 @@
 
 // type definitions for the specific machine
 
-#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1))
+#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1))
 
 #define MP_SSIZE_MAX (0x7fffffff)
 
diff --git a/ports/qemu-arm/startup.c b/ports/qemu-arm/startup.c
index 5198d08..002d5ef 100644
--- a/ports/qemu-arm/startup.c
+++ b/ports/qemu-arm/startup.c
@@ -68,7 +68,7 @@
         ".notclean:\n"
         "movs r0, #0x18\n" // SYS_EXIT
         "bkpt 0xab\n"
-    );
+        );
     for (;;) {
     }
 }
diff --git a/ports/qemu-arm/test-frzmpy/native_frozen_align.py b/ports/qemu-arm/test-frzmpy/native_frozen_align.py
index 5c5c0e8..8675b8e 100644
--- a/ports/qemu-arm/test-frzmpy/native_frozen_align.py
+++ b/ports/qemu-arm/test-frzmpy/native_frozen_align.py
@@ -1,13 +1,16 @@
 import micropython
 
+
 @micropython.native
 def native_x(x):
     print(x + 1)
 
+
 @micropython.native
 def native_y(x):
     print(x + 1)
 
+
 @micropython.native
 def native_z(x):
     print(x + 1)
diff --git a/ports/qemu-arm/test_main.c b/ports/qemu-arm/test_main.c
index 3fd2c01..5fc5d4e 100644
--- a/ports/qemu-arm/test_main.c
+++ b/ports/qemu-arm/test_main.c
@@ -23,7 +23,7 @@
     mp_stack_ctrl_init();
     mp_stack_set_limit(10240);
     static uint32_t heap[HEAP_SIZE / sizeof(uint32_t)];
-    upytest_set_heap(heap, (char*)heap + HEAP_SIZE);
+    upytest_set_heap(heap, (char *)heap + HEAP_SIZE);
     int r = tinytest_main(0, NULL, groups);
     printf("status: %d\n", r);
     return r;
@@ -37,7 +37,7 @@
     uintptr_t sp = gc_helper_get_regs_and_sp(regs);
 
     // trace the stack, including the registers (since they live on the stack in this function)
-    gc_collect_root((void**)sp, ((uint32_t)MP_STATE_THREAD(stack_top) - (uint32_t)sp) / sizeof(uint32_t));
+    gc_collect_root((void **)sp, ((uint32_t)MP_STATE_THREAD(stack_top) - (uint32_t)sp) / sizeof(uint32_t));
 
     gc_collect_end();
 }
diff --git a/ports/qemu-arm/uart.c b/ports/qemu-arm/uart.c
index a0ce737..8710e9e 100644
--- a/ports/qemu-arm/uart.c
+++ b/ports/qemu-arm/uart.c
@@ -10,7 +10,7 @@
     volatile uint32_t DR;
 } UART_t;
 
-#define UART0 ((UART_t*)(0x40011000))
+#define UART0 ((UART_t *)(0x40011000))
 
 void uart_init(void) {
 }
@@ -32,7 +32,7 @@
     volatile uint32_t TXD;      // 0x51c
 } UART_t;
 
-#define UART0 ((UART_t*)(0x40002000))
+#define UART0 ((UART_t *)(0x40002000))
 
 void uart_init(void) {
     UART0->ENABLE = 4;
@@ -60,7 +60,7 @@
     volatile uint32_t BAUDDIV;
 } UART_t;
 
-#define UART0 ((UART_t*)(0x40004000))
+#define UART0 ((UART_t *)(0x40004000))
 
 void uart_init(void) {
     UART0->BAUDDIV = 16;
diff --git a/ports/samd/main.c b/ports/samd/main.c
index a66bdfb..6c6b6f3 100644
--- a/ports/samd/main.c
+++ b/ports/samd/main.c
@@ -67,7 +67,7 @@
     gc_collect_start();
     uintptr_t regs[10];
     uintptr_t sp = gc_helper_get_regs_and_sp(regs);
-    gc_collect_root((void**)sp, ((uintptr_t)MP_STATE_THREAD(stack_top) - sp) / sizeof(uint32_t));
+    gc_collect_root((void **)sp, ((uintptr_t)MP_STATE_THREAD(stack_top) - sp) / sizeof(uint32_t));
     gc_collect_end();
 }
 
@@ -92,7 +92,7 @@
 #ifndef NDEBUG
 void MP_WEAK __assert_func(const char *file, int line, const char *func, const char *expr) {
     mp_printf(MP_PYTHON_PRINTER, "Assertion '%s' failed, at file %s:%d\n", expr, file, line);
-    for(;;) {
+    for (;;) {
     }
 }
 #endif
diff --git a/ports/samd/modmachine.c b/ports/samd/modmachine.c
index 5362ef1..207e4c7 100644
--- a/ports/samd/modmachine.c
+++ b/ports/samd/modmachine.c
@@ -68,5 +68,5 @@
 
 const mp_obj_module_t mp_module_machine = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&machine_module_globals,
+    .globals = (mp_obj_dict_t *)&machine_module_globals,
 };
diff --git a/ports/samd/modutime.c b/ports/samd/modutime.c
index c3c152b..8d6a405 100644
--- a/ports/samd/modutime.c
+++ b/ports/samd/modutime.c
@@ -43,5 +43,5 @@
 
 const mp_obj_module_t mp_module_utime = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&time_module_globals,
+    .globals = (mp_obj_dict_t *)&time_module_globals,
 };
diff --git a/ports/samd/mpconfigport.h b/ports/samd/mpconfigport.h
index d77b9d5..ffb30bf 100644
--- a/ports/samd/mpconfigport.h
+++ b/ports/samd/mpconfigport.h
@@ -97,7 +97,7 @@
         __WFI(); \
     } while (0);
 
-#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1))
+#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1))
 #define MP_PLAT_PRINT_STRN(str, len) mp_hal_stdout_tx_strn_cooked(str, len)
 
 #define MP_SSIZE_MAX (0x7fffffff)
diff --git a/ports/samd/mphalport.c b/ports/samd/mphalport.c
index ebd9dcb..67fc2cb 100644
--- a/ports/samd/mphalport.c
+++ b/ports/samd/mphalport.c
@@ -93,7 +93,8 @@
         }
     }
     while (len--) {
-        while (!(USARTx->USART.INTFLAG.bit.DRE)) { }
+        while (!(USARTx->USART.INTFLAG.bit.DRE)) {
+        }
         USARTx->USART.DATA.bit.DATA = *str++;
     }
 }
diff --git a/ports/samd/mphalport.h b/ports/samd/mphalport.h
index 5256265..fc7dbe9 100644
--- a/ports/samd/mphalport.h
+++ b/ports/samd/mphalport.h
@@ -32,8 +32,14 @@
 
 void mp_hal_set_interrupt_char(int c);
 
-static inline mp_uint_t mp_hal_ticks_ms(void) { return systick_ms; }
-static inline mp_uint_t mp_hal_ticks_us(void) { return systick_ms * 1000; }
-static inline mp_uint_t mp_hal_ticks_cpu(void) { return 0; }
+static inline mp_uint_t mp_hal_ticks_ms(void) {
+    return systick_ms;
+}
+static inline mp_uint_t mp_hal_ticks_us(void) {
+    return systick_ms * 1000;
+}
+static inline mp_uint_t mp_hal_ticks_cpu(void) {
+    return 0;
+}
 
 #endif // MICROPY_INCLUDED_SAMD_MPHALPORT_H
diff --git a/ports/samd/samd_isr.c b/ports/samd/samd_isr.c
index 8341df8..dcf80d2 100644
--- a/ports/samd/samd_isr.c
+++ b/ports/samd/samd_isr.c
@@ -59,10 +59,10 @@
     #endif
 
     // SCB->VTOR
-    *((volatile uint32_t*)0xe000ed08) = (uint32_t)&isr_vector;
+    *((volatile uint32_t *)0xe000ed08) = (uint32_t)&isr_vector;
 
     // SCB->CCR: enable 8-byte stack alignment for IRQ handlers, in accord with EABI
-    *((volatile uint32_t*)0xe000ed14) |= 1 << 9;
+    *((volatile uint32_t *)0xe000ed14) |= 1 << 9;
 
     // Initialise the cpu and peripherals
     samd_init();
diff --git a/ports/samd/samd_soc.c b/ports/samd/samd_soc.c
index 569cd38..a08d0de 100644
--- a/ports/samd/samd_soc.c
+++ b/ports/samd/samd_soc.c
@@ -37,7 +37,8 @@
 
     PM->APBCMASK.bit.SERCOM0_ = 1;
     GCLK->CLKCTRL.reg = GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID_SERCOM0_CORE;
-    while (GCLK->STATUS.bit.SYNCBUSY) { }
+    while (GCLK->STATUS.bit.SYNCBUSY) {
+    }
 
     uint32_t rxpo = 3;
     uint32_t txpo = 1;
@@ -58,18 +59,21 @@
 
     #endif
 
-    while (USARTx->USART.SYNCBUSY.bit.SWRST) { }
+    while (USARTx->USART.SYNCBUSY.bit.SWRST) {
+    }
     USARTx->USART.CTRLA.bit.SWRST = 1;
-    while (USARTx->USART.SYNCBUSY.bit.SWRST) { }
+    while (USARTx->USART.SYNCBUSY.bit.SWRST) {
+    }
 
     USARTx->USART.CTRLA.reg =
         SERCOM_USART_CTRLA_DORD
         | SERCOM_USART_CTRLA_RXPO(rxpo)
         | SERCOM_USART_CTRLA_TXPO(txpo)
         | SERCOM_USART_CTRLA_MODE(1)
-        ;
+    ;
     USARTx->USART.CTRLB.reg = SERCOM_USART_CTRLB_RXEN | SERCOM_USART_CTRLB_TXEN;
-    while (USARTx->USART.SYNCBUSY.bit.CTRLB) { }
+    while (USARTx->USART.SYNCBUSY.bit.CTRLB) {
+    }
     #if CPU_FREQ == 8000000
     uint32_t baud = 50437; // 115200 baud; 65536*(1 - 16 * 115200/8e6)
     #elif CPU_FREQ == 48000000
@@ -79,7 +83,8 @@
     #endif
     USARTx->USART.BAUD.bit.BAUD = baud;
     USARTx->USART.CTRLA.bit.ENABLE = 1;
-    while (USARTx->USART.SYNCBUSY.bit.ENABLE) { }
+    while (USARTx->USART.SYNCBUSY.bit.ENABLE) {
+    }
 }
 
 static void usb_init(void) {
@@ -91,7 +96,8 @@
     uint8_t alt = 6; // alt G, USB
     #elif defined(MCU_SAMD51)
     GCLK->PCHCTRL[USB_GCLK_ID].reg = GCLK_PCHCTRL_CHEN | GCLK_PCHCTRL_GEN_GCLK1;
-    while (GCLK->PCHCTRL[USB_GCLK_ID].bit.CHEN == 0) { }
+    while (GCLK->PCHCTRL[USB_GCLK_ID].bit.CHEN == 0) {
+    }
     MCLK->AHBMASK.bit.USB_ = 1;
     MCLK->APBBMASK.bit.USB_ = 1;
     uint8_t alt = 7; // alt H, USB
@@ -115,10 +121,11 @@
 
     // Enable DFLL48M
     SYSCTRL->DFLLCTRL.reg = SYSCTRL_DFLLCTRL_ENABLE;
-    while (!SYSCTRL->PCLKSR.bit.DFLLRDY) {}
+    while (!SYSCTRL->PCLKSR.bit.DFLLRDY) {
+    }
     SYSCTRL->DFLLMUL.reg = SYSCTRL_DFLLMUL_CSTEP(1) | SYSCTRL_DFLLMUL_FSTEP(1)
         | SYSCTRL_DFLLMUL_MUL(48000);
-    uint32_t coarse = (*((uint32_t*)FUSES_DFLL48M_COARSE_CAL_ADDR) & FUSES_DFLL48M_COARSE_CAL_Msk)
+    uint32_t coarse = (*((uint32_t *)FUSES_DFLL48M_COARSE_CAL_ADDR) & FUSES_DFLL48M_COARSE_CAL_Msk)
         >> FUSES_DFLL48M_COARSE_CAL_Pos;
     if (coarse == 0x3f) {
         coarse = 0x1f;
@@ -127,11 +134,13 @@
     SYSCTRL->DFLLVAL.reg = SYSCTRL_DFLLVAL_COARSE(coarse) | SYSCTRL_DFLLVAL_FINE(fine);
     SYSCTRL->DFLLCTRL.reg = SYSCTRL_DFLLCTRL_CCDIS | SYSCTRL_DFLLCTRL_USBCRM
         | SYSCTRL_DFLLCTRL_MODE | SYSCTRL_DFLLCTRL_ENABLE;
-    while (!SYSCTRL->PCLKSR.bit.DFLLRDY) {}
+    while (!SYSCTRL->PCLKSR.bit.DFLLRDY) {
+    }
 
     GCLK->GENDIV.reg = GCLK_GENDIV_ID(0) | GCLK_GENDIV_DIV(1);
     GCLK->GENCTRL.reg = GCLK_GENCTRL_GENEN | GCLK_GENCTRL_SRC_DFLL48M | GCLK_GENCTRL_ID(0);
-    while (GCLK->STATUS.bit.SYNCBUSY) { }
+    while (GCLK->STATUS.bit.SYNCBUSY) {
+    }
 
     // Configure PA10 as output for LED
     PORT->Group[0].DIRSET.reg = 1 << 10;
@@ -139,7 +148,8 @@
     #elif defined(MCU_SAMD51)
 
     GCLK->GENCTRL[1].reg = 1 << GCLK_GENCTRL_DIV_Pos | GCLK_GENCTRL_GENEN | GCLK_GENCTRL_SRC_DFLL;
-    while (GCLK->SYNCBUSY.bit.GENCTRL1) { }
+    while (GCLK->SYNCBUSY.bit.GENCTRL1) {
+    }
 
     // Configure PA22 as output for LED
     PORT->Group[0].DIRSET.reg = 1 << 22;
diff --git a/ports/samd/tusb_port.c b/ports/samd/tusb_port.c
index 23c242b..8f18e5e 100644
--- a/ports/samd/tusb_port.c
+++ b/ports/samd/tusb_port.c
@@ -50,19 +50,19 @@
 // Note: descriptors returned from callbacks must exist long enough for transfer to complete
 
 static const tusb_desc_device_t usbd_desc_device = {
-    .bLength            = sizeof(tusb_desc_device_t),
-    .bDescriptorType    = TUSB_DESC_DEVICE,
-    .bcdUSB             = 0x0200,
-    .bDeviceClass       = TUSB_CLASS_MISC,
-    .bDeviceSubClass    = MISC_SUBCLASS_COMMON,
-    .bDeviceProtocol    = MISC_PROTOCOL_IAD,
-    .bMaxPacketSize0    = CFG_TUD_ENDOINT0_SIZE,
-    .idVendor           = USBD_VID,
-    .idProduct          = USBD_PID,
-    .bcdDevice          = 0x0100,
-    .iManufacturer      = USBD_STR_MANUF,
-    .iProduct           = USBD_STR_PRODUCT,
-    .iSerialNumber      = USBD_STR_SERIAL,
+    .bLength = sizeof(tusb_desc_device_t),
+    .bDescriptorType = TUSB_DESC_DEVICE,
+    .bcdUSB = 0x0200,
+    .bDeviceClass = TUSB_CLASS_MISC,
+    .bDeviceSubClass = MISC_SUBCLASS_COMMON,
+    .bDeviceProtocol = MISC_PROTOCOL_IAD,
+    .bMaxPacketSize0 = CFG_TUD_ENDOINT0_SIZE,
+    .idVendor = USBD_VID,
+    .idProduct = USBD_PID,
+    .bcdDevice = 0x0100,
+    .iManufacturer = USBD_STR_MANUF,
+    .iProduct = USBD_STR_PRODUCT,
+    .iSerialNumber = USBD_STR_SERIAL,
     .bNumConfigurations = 1,
 };
 
@@ -82,7 +82,7 @@
 };
 
 const uint8_t *tud_descriptor_device_cb(void) {
-    return (const uint8_t*)&usbd_desc_device;
+    return (const uint8_t *)&usbd_desc_device;
 }
 
 const uint8_t *tud_descriptor_configuration_cb(uint8_t index) {
@@ -102,7 +102,7 @@
         if (index >= sizeof(usbd_desc_str) / sizeof(usbd_desc_str[0])) {
             return NULL;
         }
-        const char* str = usbd_desc_str[index];
+        const char *str = usbd_desc_str[index];
         for (len = 0; len < DESC_STR_MAX - 1 && str[len]; ++len) {
             desc_str[1 + len] = str[len];
         }
diff --git a/ports/stm32/accel.c b/ports/stm32/accel.c
index eb55b5d..baf1112 100644
--- a/ports/stm32/accel.c
+++ b/ports/stm32/accel.c
@@ -234,7 +234,8 @@
     const size_t DATA_SIZE = 5;
     const size_t DATA_STRIDE = 2;
     #endif
-    uint8_t data[DATA_SIZE]; data[0] = ACCEL_REG_X;
+    uint8_t data[DATA_SIZE];
+    data[0] = ACCEL_REG_X;
     i2c_writeto(I2C1, ACCEL_ADDR, data, 1, false);
     i2c_readfrom(I2C1, ACCEL_ADDR, data, DATA_SIZE, true);
 
@@ -284,7 +285,7 @@
     { &mp_type_type },
     .name = MP_QSTR_Accel,
     .make_new = pyb_accel_make_new,
-    .locals_dict = (mp_obj_dict_t*)&pyb_accel_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_accel_locals_dict,
 };
 
 #endif // MICROPY_HW_HAS_MMA7660 || MICROPY_HW_HAS_KXTJ3
diff --git a/ports/stm32/adc.c b/ports/stm32/adc.c
index 8abaa3b..8d89e1f 100644
--- a/ports/stm32/adc.c
+++ b/ports/stm32/adc.c
@@ -70,8 +70,8 @@
 #define ADC_LAST_GPIO_CHANNEL   (15)
 #define ADC_SCALE_V             (3.3f)
 #define ADC_CAL_ADDRESS         (0x1ffff7ba)
-#define ADC_CAL1                ((uint16_t*)0x1ffff7b8)
-#define ADC_CAL2                ((uint16_t*)0x1ffff7c2)
+#define ADC_CAL1                ((uint16_t *)0x1ffff7b8)
+#define ADC_CAL2                ((uint16_t *)0x1ffff7c2)
 #define ADC_CAL_BITS            (12)
 
 #elif defined(STM32F4)
@@ -80,8 +80,8 @@
 #define ADC_LAST_GPIO_CHANNEL   (15)
 #define ADC_SCALE_V             (3.3f)
 #define ADC_CAL_ADDRESS         (0x1fff7a2a)
-#define ADC_CAL1                ((uint16_t*)(ADC_CAL_ADDRESS + 2))
-#define ADC_CAL2                ((uint16_t*)(ADC_CAL_ADDRESS + 4))
+#define ADC_CAL1                ((uint16_t *)(ADC_CAL_ADDRESS + 2))
+#define ADC_CAL2                ((uint16_t *)(ADC_CAL_ADDRESS + 4))
 #define ADC_CAL_BITS            (12)
 
 #elif defined(STM32F7)
@@ -96,8 +96,8 @@
 #define ADC_CAL_ADDRESS         (0x1ff0f44a)
 #endif
 
-#define ADC_CAL1                ((uint16_t*)(ADC_CAL_ADDRESS + 2))
-#define ADC_CAL2                ((uint16_t*)(ADC_CAL_ADDRESS + 4))
+#define ADC_CAL1                ((uint16_t *)(ADC_CAL_ADDRESS + 2))
+#define ADC_CAL2                ((uint16_t *)(ADC_CAL_ADDRESS + 4))
 #define ADC_CAL_BITS            (12)
 
 #elif defined(STM32H7)
@@ -106,8 +106,8 @@
 #define ADC_LAST_GPIO_CHANNEL   (16)
 #define ADC_SCALE_V             (3.3f)
 #define ADC_CAL_ADDRESS         (0x1FF1E860)
-#define ADC_CAL1                ((uint16_t*)(0x1FF1E820))
-#define ADC_CAL2                ((uint16_t*)(0x1FF1E840))
+#define ADC_CAL1                ((uint16_t *)(0x1FF1E820))
+#define ADC_CAL2                ((uint16_t *)(0x1FF1E840))
 #define ADC_CAL_BITS            (16)
 
 #elif defined(STM32L4)
@@ -116,8 +116,8 @@
 #define ADC_LAST_GPIO_CHANNEL   (16)
 #define ADC_SCALE_V             (3.0f)
 #define ADC_CAL_ADDRESS         (0x1fff75aa)
-#define ADC_CAL1                ((uint16_t*)(ADC_CAL_ADDRESS - 2))
-#define ADC_CAL2                ((uint16_t*)(ADC_CAL_ADDRESS + 0x20))
+#define ADC_CAL1                ((uint16_t *)(ADC_CAL_ADDRESS - 2))
+#define ADC_CAL2                ((uint16_t *)(ADC_CAL_ADDRESS + 0x20))
 #define ADC_CAL_BITS            (12)
 
 #else
@@ -129,25 +129,25 @@
 #if defined(STM32F091xC)
 #define VBAT_DIV (2)
 #elif defined(STM32F405xx) || defined(STM32F415xx) || \
-      defined(STM32F407xx) || defined(STM32F417xx) || \
-      defined(STM32F401xC) || defined(STM32F401xE)
+    defined(STM32F407xx) || defined(STM32F417xx) || \
+    defined(STM32F401xC) || defined(STM32F401xE)
 #define VBAT_DIV (2)
 #elif defined(STM32F411xE) || defined(STM32F413xx) || \
-      defined(STM32F427xx) || defined(STM32F429xx) || \
-      defined(STM32F437xx) || defined(STM32F439xx) || \
-      defined(STM32F446xx)
+    defined(STM32F427xx) || defined(STM32F429xx) || \
+    defined(STM32F437xx) || defined(STM32F439xx) || \
+    defined(STM32F446xx)
 #define VBAT_DIV (4)
 #elif defined(STM32F722xx) || defined(STM32F723xx) || \
-      defined(STM32F732xx) || defined(STM32F733xx) || \
-      defined(STM32F746xx) || defined(STM32F765xx) || \
-      defined(STM32F767xx) || defined(STM32F769xx)
+    defined(STM32F732xx) || defined(STM32F733xx) || \
+    defined(STM32F746xx) || defined(STM32F765xx) || \
+    defined(STM32F767xx) || defined(STM32F769xx)
 #define VBAT_DIV (4)
 #elif defined(STM32H743xx)
 #define VBAT_DIV (4)
 #elif defined(STM32L432xx) || \
-      defined(STM32L451xx) || defined(STM32L452xx) || \
-      defined(STM32L462xx) || defined(STM32L475xx) || \
-      defined(STM32L476xx) || defined(STM32L496xx)
+    defined(STM32L451xx) || defined(STM32L452xx) || \
+    defined(STM32L462xx) || defined(STM32L475xx) || \
+    defined(STM32L476xx) || defined(STM32L496xx)
 #define VBAT_DIV (3)
 #else
 #error Unsupported processor
@@ -167,8 +167,8 @@
 #ifndef __HAL_ADC_IS_CHANNEL_INTERNAL
 #define __HAL_ADC_IS_CHANNEL_INTERNAL(channel) \
     (channel == ADC_CHANNEL_VBAT \
-     || channel == ADC_CHANNEL_VREFINT \
-     || channel == ADC_CHANNEL_TEMPSENSOR)
+    || channel == ADC_CHANNEL_VREFINT \
+    || channel == ADC_CHANNEL_TEMPSENSOR)
 #endif
 
 typedef struct _pyb_obj_adc_t {
@@ -191,32 +191,32 @@
 }
 
 STATIC bool is_adcx_channel(int channel) {
-#if defined(STM32F411xE)
+    #if defined(STM32F411xE)
     // The HAL has an incorrect IS_ADC_CHANNEL macro for the F411 so we check for temp
     return IS_ADC_CHANNEL(channel) || channel == ADC_CHANNEL_TEMPSENSOR;
-#elif defined(STM32F0) || defined(STM32F4) || defined(STM32F7)
+    #elif defined(STM32F0) || defined(STM32F4) || defined(STM32F7)
     return IS_ADC_CHANNEL(channel);
-#elif defined(STM32H7)
+    #elif defined(STM32H7)
     return __HAL_ADC_IS_CHANNEL_INTERNAL(channel)
-        || IS_ADC_CHANNEL(__HAL_ADC_DECIMAL_NB_TO_CHANNEL(channel));
-#elif defined(STM32L4)
+           || IS_ADC_CHANNEL(__HAL_ADC_DECIMAL_NB_TO_CHANNEL(channel));
+    #elif defined(STM32L4)
     ADC_HandleTypeDef handle;
     handle.Instance = ADCx;
     return IS_ADC_CHANNEL(&handle, channel);
-#else
+    #else
     #error Unsupported processor
-#endif
+    #endif
 }
 
 STATIC void adc_wait_for_eoc_or_timeout(int32_t timeout) {
     uint32_t tickstart = HAL_GetTick();
-#if defined(STM32F4) || defined(STM32F7)
+    #if defined(STM32F4) || defined(STM32F7)
     while ((ADCx->SR & ADC_FLAG_EOC) != ADC_FLAG_EOC) {
-#elif defined(STM32F0) || defined(STM32H7) || defined(STM32L4)
+    #elif defined(STM32F0) || defined(STM32H7) || defined(STM32L4)
     while (READ_BIT(ADCx->ISR, ADC_FLAG_EOC) != ADC_FLAG_EOC) {
-#else
+    #else
     #error Unsupported processor
-#endif
+        #endif
         if (((HAL_GetTick() - tickstart ) > timeout)) {
             break; // timeout
         }
@@ -224,58 +224,58 @@
 }
 
 STATIC void adcx_clock_enable(void) {
-#if defined(STM32F0) || defined(STM32F4) || defined(STM32F7)
+    #if defined(STM32F0) || defined(STM32F4) || defined(STM32F7)
     ADCx_CLK_ENABLE();
-#elif defined(STM32H7)
+    #elif defined(STM32H7)
     __HAL_RCC_ADC3_CLK_ENABLE();
     __HAL_RCC_ADC_CONFIG(RCC_ADCCLKSOURCE_CLKP);
-#elif defined(STM32L4)
+    #elif defined(STM32L4)
     __HAL_RCC_ADC_CLK_ENABLE();
-#else
+    #else
     #error Unsupported processor
-#endif
+    #endif
 }
 
 STATIC void adcx_init_periph(ADC_HandleTypeDef *adch, uint32_t resolution) {
     adcx_clock_enable();
 
-    adch->Instance                   = ADCx;
-    adch->Init.Resolution            = resolution;
-    adch->Init.ContinuousConvMode    = DISABLE;
+    adch->Instance = ADCx;
+    adch->Init.Resolution = resolution;
+    adch->Init.ContinuousConvMode = DISABLE;
     adch->Init.DiscontinuousConvMode = DISABLE;
     #if !defined(STM32F0)
-    adch->Init.NbrOfDiscConversion   = 0;
-    adch->Init.NbrOfConversion       = 1;
+    adch->Init.NbrOfDiscConversion = 0;
+    adch->Init.NbrOfConversion = 1;
     #endif
-    adch->Init.EOCSelection          = ADC_EOC_SINGLE_CONV;
-    adch->Init.ExternalTrigConv      = ADC_SOFTWARE_START;
-    adch->Init.ExternalTrigConvEdge  = ADC_EXTERNALTRIGCONVEDGE_NONE;
+    adch->Init.EOCSelection = ADC_EOC_SINGLE_CONV;
+    adch->Init.ExternalTrigConv = ADC_SOFTWARE_START;
+    adch->Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
     #if defined(STM32F0)
-    adch->Init.ClockPrescaler        = ADC_CLOCK_SYNC_PCLK_DIV4; // 12MHz
-    adch->Init.ScanConvMode          = DISABLE;
-    adch->Init.DataAlign             = ADC_DATAALIGN_RIGHT;
+    adch->Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4;        // 12MHz
+    adch->Init.ScanConvMode = DISABLE;
+    adch->Init.DataAlign = ADC_DATAALIGN_RIGHT;
     adch->Init.DMAContinuousRequests = DISABLE;
-    adch->Init.SamplingTimeCommon    = ADC_SAMPLETIME_55CYCLES_5; // ~4uS
+    adch->Init.SamplingTimeCommon = ADC_SAMPLETIME_55CYCLES_5;    // ~4uS
     #elif defined(STM32F4) || defined(STM32F7)
-    adch->Init.ClockPrescaler        = ADC_CLOCK_SYNC_PCLK_DIV2;
-    adch->Init.ScanConvMode          = DISABLE;
-    adch->Init.DataAlign             = ADC_DATAALIGN_RIGHT;
+    adch->Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
+    adch->Init.ScanConvMode = DISABLE;
+    adch->Init.DataAlign = ADC_DATAALIGN_RIGHT;
     adch->Init.DMAContinuousRequests = DISABLE;
     #elif defined(STM32H7)
-    adch->Init.ClockPrescaler        = ADC_CLOCK_SYNC_PCLK_DIV4;
-    adch->Init.ScanConvMode          = DISABLE;
-    adch->Init.LowPowerAutoWait      = DISABLE;
-    adch->Init.Overrun               = ADC_OVR_DATA_OVERWRITTEN;
-    adch->Init.OversamplingMode      = DISABLE;
-    adch->Init.LeftBitShift          = ADC_LEFTBITSHIFT_NONE;
+    adch->Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4;
+    adch->Init.ScanConvMode = DISABLE;
+    adch->Init.LowPowerAutoWait = DISABLE;
+    adch->Init.Overrun = ADC_OVR_DATA_OVERWRITTEN;
+    adch->Init.OversamplingMode = DISABLE;
+    adch->Init.LeftBitShift = ADC_LEFTBITSHIFT_NONE;
     adch->Init.ConversionDataManagement = ADC_CONVERSIONDATA_DR;
     #elif defined(STM32L4)
-    adch->Init.ClockPrescaler        = ADC_CLOCK_ASYNC_DIV1;
-    adch->Init.ScanConvMode          = ADC_SCAN_DISABLE;
-    adch->Init.LowPowerAutoWait      = DISABLE;
-    adch->Init.Overrun               = ADC_OVR_DATA_PRESERVED;
-    adch->Init.OversamplingMode      = DISABLE;
-    adch->Init.DataAlign             = ADC_DATAALIGN_RIGHT;
+    adch->Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV1;
+    adch->Init.ScanConvMode = ADC_SCAN_DISABLE;
+    adch->Init.LowPowerAutoWait = DISABLE;
+    adch->Init.Overrun = ADC_OVR_DATA_PRESERVED;
+    adch->Init.OversamplingMode = DISABLE;
+    adch->Init.DataAlign = ADC_DATAALIGN_RIGHT;
     adch->Init.DMAContinuousRequests = DISABLE;
     #else
     #error Unsupported processor
@@ -301,14 +301,13 @@
 
     adcx_init_periph(&adc_obj->handle, ADC_RESOLUTION_12B);
 
-#if defined(STM32L4) && defined(ADC_DUALMODE_REGSIMULT_INJECSIMULT)
+    #if defined(STM32L4) && defined(ADC_DUALMODE_REGSIMULT_INJECSIMULT)
     ADC_MultiModeTypeDef multimode;
     multimode.Mode = ADC_MODE_INDEPENDENT;
-    if (HAL_ADCEx_MultiModeConfigChannel(&adc_obj->handle, &multimode) != HAL_OK)
-    {
+    if (HAL_ADCEx_MultiModeConfigChannel(&adc_obj->handle, &multimode) != HAL_OK) {
         mp_raise_msg_varg(&mp_type_ValueError, "Can not set multimode on ADC1 channel: %d", adc_obj->channel);
     }
-#endif
+    #endif
 }
 
 STATIC void adc_config_channel(ADC_HandleTypeDef *adc_handle, uint32_t channel) {
@@ -324,11 +323,11 @@
     #endif
     sConfig.Channel = channel;
 
-#if defined(STM32F0)
+    #if defined(STM32F0)
     sConfig.SamplingTime = ADC_SAMPLETIME_55CYCLES_5;
-#elif defined(STM32F4) || defined(STM32F7)
+    #elif defined(STM32F4) || defined(STM32F7)
     sConfig.SamplingTime = ADC_SAMPLETIME_15CYCLES;
-#elif defined(STM32H7)
+    #elif defined(STM32H7)
     if (__HAL_ADC_IS_CHANNEL_INTERNAL(channel)) {
         sConfig.SamplingTime = ADC_SAMPLETIME_810CYCLES_5;
     } else {
@@ -338,7 +337,7 @@
     sConfig.OffsetNumber = ADC_OFFSET_NONE;
     sConfig.OffsetRightShift = DISABLE;
     sConfig.OffsetSignedSaturation = DISABLE;
-#elif defined(STM32L4)
+    #elif defined(STM32L4)
     if (__HAL_ADC_IS_CHANNEL_INTERNAL(channel)) {
         sConfig.SamplingTime = ADC_SAMPLETIME_247CYCLES_5;
     } else {
@@ -347,9 +346,9 @@
     sConfig.SingleDiff = ADC_SINGLE_ENDED;
     sConfig.OffsetNumber = ADC_OFFSET_NONE;
     sConfig.Offset = 0;
-#else
+    #else
     #error Unsupported processor
-#endif
+    #endif
 
     #if defined(STM32F0)
     // On the STM32F0 we must select only one channel at a time to sample, so clear all
@@ -522,13 +521,13 @@
             HAL_ADC_Start(&self->handle);
         } else {
             // for subsequent samples we can just set the "start sample" bit
-#if defined(STM32F4) || defined(STM32F7)
+            #if defined(STM32F4) || defined(STM32F7)
             ADCx->CR2 |= (uint32_t)ADC_CR2_SWSTART;
-#elif defined(STM32F0) || defined(STM32H7) || defined(STM32L4)
+            #elif defined(STM32F0) || defined(STM32H7) || defined(STM32L4)
             SET_BIT(ADCx->CR, ADC_CR_ADSTART);
-#else
+            #else
             #error Unsupported processor
-#endif
+            #endif
         }
 
         // wait for sample to complete
@@ -675,7 +674,7 @@
     .name = MP_QSTR_ADC,
     .print = adc_print,
     .make_new = adc_make_new,
-    .locals_dict = (mp_obj_dict_t*)&adc_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&adc_locals_dict,
 };
 
 /******************************************************************************/
@@ -690,13 +689,23 @@
 
     switch (resolution) {
         #if !defined(STM32H7)
-        case 6:  resolution = ADC_RESOLUTION_6B;  break;
+        case 6:
+            resolution = ADC_RESOLUTION_6B;
+            break;
         #endif
-        case 8:  resolution = ADC_RESOLUTION_8B;  break;
-        case 10: resolution = ADC_RESOLUTION_10B; break;
-        case 12: resolution = ADC_RESOLUTION_12B; break;
+        case 8:
+            resolution = ADC_RESOLUTION_8B;
+            break;
+        case 10:
+            resolution = ADC_RESOLUTION_10B;
+            break;
+        case 12:
+            resolution = ADC_RESOLUTION_12B;
+            break;
         #if defined(STM32H7)
-        case 16: resolution = ADC_RESOLUTION_16B; break;
+        case 16:
+            resolution = ADC_RESOLUTION_16B;
+            break;
         #endif
         default:
             mp_raise_msg_varg(&mp_type_ValueError, "resolution %d not supported", resolution);
@@ -722,12 +731,16 @@
 
     switch (res_reg) {
         #if !defined(STM32H7)
-        case ADC_RESOLUTION_6B:  return 6;
+        case ADC_RESOLUTION_6B:
+            return 6;
         #endif
-        case ADC_RESOLUTION_8B:  return 8;
-        case ADC_RESOLUTION_10B: return 10;
+        case ADC_RESOLUTION_8B:
+            return 8;
+        case ADC_RESOLUTION_10B:
+            return 10;
         #if defined(STM32H7)
-        case ADC_RESOLUTION_16B: return 16;
+        case ADC_RESOLUTION_16B:
+            return 16;
         #endif
     }
     return 12;
@@ -782,7 +795,7 @@
     mp_int_t res = mp_obj_get_int(args[0]);
     uint32_t en_mask = 0xffffffff;
     if (n_args > 1) {
-        en_mask =  mp_obj_get_int(args[1]);
+        en_mask = mp_obj_get_int(args[1]);
     }
     adc_init_all(o, res, en_mask);
 
@@ -803,7 +816,7 @@
     float data = adc_read_core_temp_float(&self->handle);
     return mp_obj_new_float(data);
     #else
-    int data  = adc_read_core_temp(&self->handle);
+    int data = adc_read_core_temp(&self->handle);
     return mp_obj_new_int(data);
     #endif
 }
@@ -819,7 +832,7 @@
 
 STATIC mp_obj_t adc_all_read_core_vref(mp_obj_t self_in) {
     pyb_adc_all_obj_t *self = MP_OBJ_TO_PTR(self_in);
-    float data  = adc_read_core_vref(&self->handle);
+    float data = adc_read_core_vref(&self->handle);
     return mp_obj_new_float(data);
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_1(adc_all_read_core_vref_obj, adc_all_read_core_vref);
@@ -835,11 +848,11 @@
 STATIC const mp_rom_map_elem_t adc_all_locals_dict_table[] = {
     { MP_ROM_QSTR(MP_QSTR_read_channel), MP_ROM_PTR(&adc_all_read_channel_obj) },
     { MP_ROM_QSTR(MP_QSTR_read_core_temp), MP_ROM_PTR(&adc_all_read_core_temp_obj) },
-#if MICROPY_PY_BUILTINS_FLOAT
+    #if MICROPY_PY_BUILTINS_FLOAT
     { MP_ROM_QSTR(MP_QSTR_read_core_vbat), MP_ROM_PTR(&adc_all_read_core_vbat_obj) },
     { MP_ROM_QSTR(MP_QSTR_read_core_vref), MP_ROM_PTR(&adc_all_read_core_vref_obj) },
     { MP_ROM_QSTR(MP_QSTR_read_vref), MP_ROM_PTR(&adc_all_read_vref_obj) },
-#endif
+    #endif
 };
 
 STATIC MP_DEFINE_CONST_DICT(adc_all_locals_dict, adc_all_locals_dict_table);
@@ -848,7 +861,7 @@
     { &mp_type_type },
     .name = MP_QSTR_ADCAll,
     .make_new = adc_all_make_new,
-    .locals_dict = (mp_obj_dict_t*)&adc_all_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&adc_all_locals_dict,
 };
 
 #endif // MICROPY_HW_ENABLE_ADC
diff --git a/ports/stm32/boards/PYBD_SF2/manifest.py b/ports/stm32/boards/PYBD_SF2/manifest.py
index 48cc2ce..3819aa0 100644
--- a/ports/stm32/boards/PYBD_SF2/manifest.py
+++ b/ports/stm32/boards/PYBD_SF2/manifest.py
@@ -1,2 +1,2 @@
-include('$(PORT_DIR)/boards/manifest.py')
-include('$(MPY_DIR)/extmod/webrepl/manifest.py')
+include("$(PORT_DIR)/boards/manifest.py")
+include("$(MPY_DIR)/extmod/webrepl/manifest.py")
diff --git a/ports/stm32/boards/STM32F4DISC/staccel.py b/ports/stm32/boards/STM32F4DISC/staccel.py
index 2f2561d..af77720 100644
--- a/ports/stm32/boards/STM32F4DISC/staccel.py
+++ b/ports/stm32/boards/STM32F4DISC/staccel.py
@@ -18,29 +18,30 @@
 from pyb import Pin
 from pyb import SPI
 
-READWRITE_CMD = const(0x80) 
+READWRITE_CMD = const(0x80)
 MULTIPLEBYTE_CMD = const(0x40)
-WHO_AM_I_ADDR = const(0x0f)
+WHO_AM_I_ADDR = const(0x0F)
 OUT_X_ADDR = const(0x29)
-OUT_Y_ADDR = const(0x2b)
-OUT_Z_ADDR = const(0x2d)
-OUT_T_ADDR = const(0x0c)
+OUT_Y_ADDR = const(0x2B)
+OUT_Z_ADDR = const(0x2D)
+OUT_T_ADDR = const(0x0C)
 
-LIS302DL_WHO_AM_I_VAL = const(0x3b)
+LIS302DL_WHO_AM_I_VAL = const(0x3B)
 LIS302DL_CTRL_REG1_ADDR = const(0x20)
 # Configuration for 100Hz sampling rate, +-2g range
 LIS302DL_CONF = const(0b01000111)
 
-LIS3DSH_WHO_AM_I_VAL = const(0x3f)
+LIS3DSH_WHO_AM_I_VAL = const(0x3F)
 LIS3DSH_CTRL_REG4_ADDR = const(0x20)
 LIS3DSH_CTRL_REG5_ADDR = const(0x24)
 # Configuration for 100Hz sampling rate, +-2g range
 LIS3DSH_CTRL_REG4_CONF = const(0b01100111)
 LIS3DSH_CTRL_REG5_CONF = const(0b00000000)
 
+
 class STAccel:
     def __init__(self):
-        self.cs_pin = Pin('PE3', Pin.OUT_PP, Pin.PULL_NONE)
+        self.cs_pin = Pin("PE3", Pin.OUT_PP, Pin.PULL_NONE)
         self.cs_pin.high()
         self.spi = SPI(1, SPI.MASTER, baudrate=328125, polarity=0, phase=1, bits=8)
 
@@ -54,7 +55,7 @@
             self.write_bytes(LIS3DSH_CTRL_REG5_ADDR, bytearray([LIS3DSH_CTRL_REG5_CONF]))
             self.sensitivity = 0.06 * 256
         else:
-            raise Exception('LIS302DL or LIS3DSH accelerometer not present')
+            raise Exception("LIS302DL or LIS3DSH accelerometer not present")
 
     def convert_raw_to_g(self, x):
         if x & 0x80:
@@ -68,7 +69,7 @@
             addr |= READWRITE_CMD
         self.cs_pin.low()
         self.spi.send(addr)
-        #buf = self.spi.send_recv(bytearray(nbytes * [0])) # read data, MSB first
+        # buf = self.spi.send_recv(bytearray(nbytes * [0])) # read data, MSB first
         buf = self.spi.recv(nbytes)
         self.cs_pin.high()
         return buf
diff --git a/ports/stm32/boards/make-pins.py b/ports/stm32/boards/make-pins.py
index 3819b47..692387f 100755
--- a/ports/stm32/boards/make-pins.py
+++ b/ports/stm32/boards/make-pins.py
@@ -9,52 +9,54 @@
 
 # Must have matching entries in AF_FN_* enum in ../pin_defs_stm32.h
 SUPPORTED_FN = {
-    'TIM'   : ['CH1',  'CH2',  'CH3',  'CH4',
-               'CH1N', 'CH2N', 'CH3N', 'CH1_ETR', 'ETR', 'BKIN'],
-    'I2C'   : ['SDA', 'SCL'],
-    'I2S'   : ['CK', 'MCK', 'SD', 'WS', 'EXTSD'],
-    'USART' : ['RX', 'TX', 'CTS', 'RTS', 'CK'],
-    'UART'  : ['RX', 'TX', 'CTS', 'RTS'],
-    'SPI'   : ['NSS', 'SCK', 'MISO', 'MOSI'],
-    'SDMMC' : ['CK', 'CMD', 'D0', 'D1', 'D2', 'D3'],
-    'CAN'   : ['TX', 'RX'],
+    "TIM": ["CH1", "CH2", "CH3", "CH4", "CH1N", "CH2N", "CH3N", "CH1_ETR", "ETR", "BKIN"],
+    "I2C": ["SDA", "SCL"],
+    "I2S": ["CK", "MCK", "SD", "WS", "EXTSD"],
+    "USART": ["RX", "TX", "CTS", "RTS", "CK"],
+    "UART": ["RX", "TX", "CTS", "RTS"],
+    "SPI": ["NSS", "SCK", "MISO", "MOSI"],
+    "SDMMC": ["CK", "CMD", "D0", "D1", "D2", "D3"],
+    "CAN": ["TX", "RX"],
 }
 
 CONDITIONAL_VAR = {
-    'I2C'   : 'MICROPY_HW_I2C{num}_SCL',
-    'I2S'   : 'MICROPY_HW_ENABLE_I2S{num}',
-    'SPI'   : 'MICROPY_HW_SPI{num}_SCK',
-    'UART'  : 'MICROPY_HW_UART{num}_TX',
-    'USART' : 'MICROPY_HW_UART{num}_TX',
-    'SDMMC' : 'MICROPY_HW_SDMMC{num}_CK',
-    'CAN'   : 'MICROPY_HW_CAN{num}_TX',
+    "I2C": "MICROPY_HW_I2C{num}_SCL",
+    "I2S": "MICROPY_HW_ENABLE_I2S{num}",
+    "SPI": "MICROPY_HW_SPI{num}_SCK",
+    "UART": "MICROPY_HW_UART{num}_TX",
+    "USART": "MICROPY_HW_UART{num}_TX",
+    "SDMMC": "MICROPY_HW_SDMMC{num}_CK",
+    "CAN": "MICROPY_HW_CAN{num}_TX",
 }
 
+
 def parse_port_pin(name_str):
     """Parses a string and returns a (port-num, pin-num) tuple."""
     if len(name_str) < 3:
         raise ValueError("Expecting pin name to be at least 3 charcters.")
-    if name_str[0] != 'P':
+    if name_str[0] != "P":
         raise ValueError("Expecting pin name to start with P")
-    if name_str[1] < 'A' or name_str[1] > 'K':
+    if name_str[1] < "A" or name_str[1] > "K":
         raise ValueError("Expecting pin port to be between A and K")
-    port = ord(name_str[1]) - ord('A')
+    port = ord(name_str[1]) - ord("A")
     pin_str = name_str[2:]
     if not pin_str.isdigit():
         raise ValueError("Expecting numeric pin number.")
     return (port, int(pin_str))
 
+
 def split_name_num(name_num):
     num = None
     for num_idx in range(len(name_num) - 1, -1, -1):
         if not name_num[num_idx].isdigit():
-            name = name_num[0:num_idx + 1]
-            num_str = name_num[num_idx + 1:]
+            name = name_num[0 : num_idx + 1]
+            num_str = name_num[num_idx + 1 :]
             if len(num_str) > 0:
                 num = int(num_str)
             break
     return name, num
 
+
 def conditional_var(name_num):
     # Try the specific instance first. For example, if name_num is UART4_RX
     # then try UART4 first, and then try UART second.
@@ -66,19 +68,21 @@
         var.append(CONDITIONAL_VAR[name_num])
     return var
 
+
 def print_conditional_if(cond_var, file=None):
     if cond_var:
         cond_str = []
         for var in cond_var:
-            if var.find('ENABLE') >= 0:
-                cond_str.append('(defined({0}) && {0})'.format(var))
+            if var.find("ENABLE") >= 0:
+                cond_str.append("(defined({0}) && {0})".format(var))
             else:
-                cond_str.append('defined({0})'.format(var))
-        print('#if ' + ' || '.join(cond_str), file=file)
+                cond_str.append("defined({0})".format(var))
+        print("#if " + " || ".join(cond_str), file=file)
+
 
 def print_conditional_endif(cond_var, file=None):
     if cond_var:
-        print('#endif', file=file)
+        print("#endif", file=file)
 
 
 class AlternateFunction(object):
@@ -88,16 +92,16 @@
         self.idx = idx
         # Special case. We change I2S2ext_SD into I2S2_EXTSD so that it parses
         # the same way the other peripherals do.
-        af_str = af_str.replace('ext_', '_EXT')
+        af_str = af_str.replace("ext_", "_EXT")
 
         self.af_str = af_str
 
-        self.func = ''
+        self.func = ""
         self.fn_num = None
-        self.pin_type = ''
+        self.pin_type = ""
         self.supported = False
 
-        af_words = af_str.split('_', 1)
+        af_words = af_str.split("_", 1)
         self.func, self.fn_num = split_name_num(af_words[0])
         if len(af_words) > 1:
             self.pin_type = af_words[1]
@@ -113,25 +117,28 @@
         """Returns the numbered function (i.e. USART6) for this AF."""
         if self.fn_num is None:
             return self.func
-        return '{:s}{:d}'.format(self.func, self.fn_num)
+        return "{:s}{:d}".format(self.func, self.fn_num)
 
     def mux_name(self):
-        return 'AF{:d}_{:s}'.format(self.idx, self.ptr())
+        return "AF{:d}_{:s}".format(self.idx, self.ptr())
 
     def print(self):
         """Prints the C representation of this AF."""
         cond_var = None
         if self.supported:
-            cond_var = conditional_var('{}{}'.format(self.func, self.fn_num))
+            cond_var = conditional_var("{}{}".format(self.func, self.fn_num))
             print_conditional_if(cond_var)
-            print('  AF',  end='')
+            print("  AF", end="")
         else:
-            print('  //', end='')
+            print("  //", end="")
         fn_num = self.fn_num
         if fn_num is None:
             fn_num = 0
-        print('({:2d}, {:8s}, {:2d}, {:10s}, {:8s}), // {:s}'.format(self.idx,
-              self.func, fn_num, self.pin_type, self.ptr(), self.af_str))
+        print(
+            "({:2d}, {:8s}, {:2d}, {:10s}, {:8s}), // {:s}".format(
+                self.idx, self.func, fn_num, self.pin_type, self.ptr(), self.af_str
+            )
+        )
         print_conditional_endif(cond_var)
 
     def qstr_list(self):
@@ -151,10 +158,10 @@
         self.board_pin = False
 
     def port_letter(self):
-        return chr(self.port + ord('A'))
+        return chr(self.port + ord("A"))
 
     def cpu_pin_name(self):
-        return '{:s}{:d}'.format(self.port_letter(), self.pin)
+        return "{:s}{:d}".format(self.port_letter(), self.pin)
 
     def is_board_pin(self):
         return self.board_pin
@@ -163,16 +170,16 @@
         self.board_pin = True
 
     def parse_adc(self, adc_str):
-        if (adc_str[:3] != 'ADC'):
+        if adc_str[:3] != "ADC":
             return
 
-        if adc_str.find('_INP') != -1:
+        if adc_str.find("_INP") != -1:
             # STM32H7xx, entries have the form: ADCxx_IN[PN]yy/...
             # for now just pick the entry with the most ADC periphs
             adc, channel = None, None
-            for ss in adc_str.split('/'):
-                if ss.find('_INP') != -1:
-                    a, c = ss.split('_')
+            for ss in adc_str.split("/"):
+                if ss.find("_INP") != -1:
+                    a, c = ss.split("_")
                     if adc is None or len(a) > len(adc):
                         adc, channel = a, c
             if adc is None:
@@ -180,12 +187,12 @@
             channel = channel[3:]
         else:
             # all other MCUs, entries have the form: ADCxx_INyy
-            adc, channel = adc_str.split('_')
+            adc, channel = adc_str.split("_")
             channel = channel[2:]
 
         for idx in range(3, len(adc)):
-            adc_num = int(adc[idx]) # 1, 2, or 3
-            self.adc_num |= (1 << (adc_num - 1))
+            adc_num = int(adc[idx])  # 1, 2, or 3
+            self.adc_num |= 1 << (adc_num - 1)
         self.adc_channel = int(channel)
 
     def parse_af(self, af_idx, af_strs_in):
@@ -193,7 +200,7 @@
             return
         # If there is a slash, then the slash separates 2 aliases for the
         # same alternate function.
-        af_strs = af_strs_in.split('/')
+        af_strs = af_strs_in.split("/")
         for af_str in af_strs:
             alt_fn = AlternateFunction(af_idx, af_str)
             self.alt_fn.append(alt_fn)
@@ -202,43 +209,49 @@
 
     def alt_fn_name(self, null_if_0=False):
         if null_if_0 and self.alt_fn_count == 0:
-            return 'NULL'
-        return 'pin_{:s}_af'.format(self.cpu_pin_name())
+            return "NULL"
+        return "pin_{:s}_af".format(self.cpu_pin_name())
 
     def adc_num_str(self):
-        str = ''
-        for adc_num in range(1,4):
+        str = ""
+        for adc_num in range(1, 4):
             if self.adc_num & (1 << (adc_num - 1)):
                 if len(str) > 0:
-                    str += ' | '
-                str += 'PIN_ADC'
-                str += chr(ord('0') + adc_num)
+                    str += " | "
+                str += "PIN_ADC"
+                str += chr(ord("0") + adc_num)
         if len(str) == 0:
-            str = '0'
+            str = "0"
         return str
 
     def print(self):
         if self.alt_fn_count == 0:
-            print("// ",  end='')
-        print('const pin_af_obj_t {:s}[] = {{'.format(self.alt_fn_name()))
+            print("// ", end="")
+        print("const pin_af_obj_t {:s}[] = {{".format(self.alt_fn_name()))
         for alt_fn in self.alt_fn:
             alt_fn.print()
         if self.alt_fn_count == 0:
-            print("// ",  end='')
-        print('};')
-        print('')
-        print('const pin_obj_t pin_{:s}_obj = PIN({:s}, {:d}, {:s}, {:s}, {:d});'.format(
-            self.cpu_pin_name(), self.port_letter(), self.pin,
-            self.alt_fn_name(null_if_0=True),
-            self.adc_num_str(), self.adc_channel))
-        print('')
+            print("// ", end="")
+        print("};")
+        print("")
+        print(
+            "const pin_obj_t pin_{:s}_obj = PIN({:s}, {:d}, {:s}, {:s}, {:d});".format(
+                self.cpu_pin_name(),
+                self.port_letter(),
+                self.pin,
+                self.alt_fn_name(null_if_0=True),
+                self.adc_num_str(),
+                self.adc_channel,
+            )
+        )
+        print("")
 
     def print_header(self, hdr_file):
         n = self.cpu_pin_name()
-        hdr_file.write('extern const pin_obj_t pin_{:s}_obj;\n'.format(n))
-        hdr_file.write('#define pin_{:s} (&pin_{:s}_obj)\n'.format(n, n))
+        hdr_file.write("extern const pin_obj_t pin_{:s}_obj;\n".format(n))
+        hdr_file.write("#define pin_{:s} (&pin_{:s}_obj)\n".format(n, n))
         if self.alt_fn_count > 0:
-            hdr_file.write('extern const pin_af_obj_t pin_{:s}_af[];\n'.format(n))
+            hdr_file.write("extern const pin_af_obj_t pin_{:s}_af[];\n".format(n))
 
     def qstr_list(self):
         result = []
@@ -249,9 +262,8 @@
 
 
 class NamedPin(object):
-
     def __init__(self, name, pin):
-        if name.startswith('-'):
+        if name.startswith("-"):
             self._is_hidden = True
             self._name = name[1:]
         else:
@@ -270,10 +282,9 @@
 
 
 class Pins(object):
-
     def __init__(self):
-        self.cpu_pins = []   # list of NamedPin objects
-        self.board_pins = [] # list of NamedPin objects
+        self.cpu_pins = []  # list of NamedPin objects
+        self.board_pins = []  # list of NamedPin objects
 
     def find_pin(self, port_num, pin_num):
         for named_pin in self.cpu_pins:
@@ -282,7 +293,7 @@
                 return pin
 
     def parse_af_file(self, filename, pinname_col, af_col):
-        with open(filename, 'r') as csvfile:
+        with open(filename, "r") as csvfile:
             rows = csv.reader(csvfile)
             for row in rows:
                 try:
@@ -298,7 +309,7 @@
                 self.cpu_pins.append(NamedPin(pin.cpu_pin_name(), pin))
 
     def parse_board_file(self, filename):
-        with open(filename, 'r') as csvfile:
+        with open(filename, "r") as csvfile:
             rows = csv.reader(csvfile)
             for row in rows:
                 try:
@@ -308,64 +319,80 @@
                 pin = self.find_pin(port_num, pin_num)
                 if pin:
                     pin.set_is_board_pin()
-                    if row[0]: # Only add board pins that have a name
+                    if row[0]:  # Only add board pins that have a name
                         self.board_pins.append(NamedPin(row[0], pin))
 
     def print_named(self, label, named_pins):
-        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 named_pin in named_pins:
             pin = named_pin.pin()
             if pin.is_board_pin() and not named_pin.is_hidden():
-                print('  {{ MP_ROM_QSTR(MP_QSTR_{:s}), MP_ROM_PTR(&pin_{:s}_obj) }},'.format(named_pin.name(),  pin.cpu_pin_name()))
-        print('};')
-        print('MP_DEFINE_CONST_DICT(pin_{:s}_pins_locals_dict, pin_{:s}_pins_locals_dict_table);'.format(label, label))
+                print(
+                    "  {{ MP_ROM_QSTR(MP_QSTR_{:s}), MP_ROM_PTR(&pin_{:s}_obj) }},".format(
+                        named_pin.name(), pin.cpu_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):
         for named_pin in self.cpu_pins:
             pin = named_pin.pin()
             if pin.is_board_pin():
                 pin.print()
-        self.print_named('cpu', self.cpu_pins)
-        print('')
-        self.print_named('board', self.board_pins)
+        self.print_named("cpu", self.cpu_pins)
+        print("")
+        self.print_named("board", self.board_pins)
 
     def print_adc(self, adc_num):
-        print('')
-        print('const pin_obj_t * const pin_adc{:d}[] = {{'.format(adc_num))
+        print("")
+        print("const pin_obj_t * const pin_adc{:d}[] = {{".format(adc_num))
         for channel in range(17):
             if channel == 16:
-                print('#if defined(STM32L4)')
+                print("#if defined(STM32L4)")
             adc_found = False
             for named_pin in self.cpu_pins:
                 pin = named_pin.pin()
-                if (pin.is_board_pin() and
-                    (pin.adc_num & (1 << (adc_num - 1))) and (pin.adc_channel == channel)):
-                    print('  &pin_{:s}_obj, // {:d}'.format(pin.cpu_pin_name(), channel))
+                if (
+                    pin.is_board_pin()
+                    and (pin.adc_num & (1 << (adc_num - 1)))
+                    and (pin.adc_channel == channel)
+                ):
+                    print("  &pin_{:s}_obj, // {:d}".format(pin.cpu_pin_name(), channel))
                     adc_found = True
                     break
             if not adc_found:
-                print('  NULL,    // {:d}'.format(channel))
+                print("  NULL,    // {:d}".format(channel))
             if channel == 16:
-                print('#endif')
-        print('};')
-
+                print("#endif")
+        print("};")
 
     def print_header(self, hdr_filename, obj_decls):
-        with open(hdr_filename, 'wt') as hdr_file:
+        with open(hdr_filename, "wt") as hdr_file:
             if obj_decls:
                 for named_pin in self.cpu_pins:
                     pin = named_pin.pin()
                     if pin.is_board_pin():
                         pin.print_header(hdr_file)
-                hdr_file.write('extern const pin_obj_t * const pin_adc1[];\n')
-                hdr_file.write('extern const pin_obj_t * const pin_adc2[];\n')
-                hdr_file.write('extern const pin_obj_t * const pin_adc3[];\n')
+                hdr_file.write("extern const pin_obj_t * const pin_adc1[];\n")
+                hdr_file.write("extern const pin_obj_t * const pin_adc2[];\n")
+                hdr_file.write("extern const pin_obj_t * const pin_adc3[];\n")
             # provide #define's mapping board to cpu name
             for named_pin in self.board_pins:
-                hdr_file.write("#define pyb_pin_{:s} pin_{:s}\n".format(named_pin.name(), named_pin.pin().cpu_pin_name()))
+                hdr_file.write(
+                    "#define pyb_pin_{:s} pin_{:s}\n".format(
+                        named_pin.name(), named_pin.pin().cpu_pin_name()
+                    )
+                )
 
     def print_qstr(self, qstr_filename):
-        with open(qstr_filename, 'wt') as qstr_file:
+        with open(qstr_filename, "wt") as qstr_file:
             qstr_set = set([])
             for named_pin in self.cpu_pins:
                 pin = named_pin.pin()
@@ -377,15 +404,15 @@
                     qstr_set |= set([named_pin.name()])
             for qstr in sorted(qstr_set):
                 cond_var = None
-                if qstr.startswith('AF'):
-                    af_words = qstr.split('_')
+                if qstr.startswith("AF"):
+                    af_words = qstr.split("_")
                     cond_var = conditional_var(af_words[1])
                     print_conditional_if(cond_var, file=qstr_file)
-                print('Q({})'.format(qstr), file=qstr_file)
+                print("Q({})".format(qstr), file=qstr_file)
                 print_conditional_endif(cond_var, file=qstr_file)
 
     def print_af_hdr(self, af_const_filename):
-        with open(af_const_filename,  'wt') as af_const_file:
+        with open(af_const_filename, "wt") as af_const_file:
             af_hdr_set = set([])
             mux_name_width = 0
             for named_pin in self.cpu_pins:
@@ -398,36 +425,37 @@
                             if len(mux_name) > mux_name_width:
                                 mux_name_width = len(mux_name)
             for mux_name in sorted(af_hdr_set):
-                af_words = mux_name.split('_')  # ex mux_name: AF9_I2C2
+                af_words = mux_name.split("_")  # ex mux_name: AF9_I2C2
                 cond_var = conditional_var(af_words[1])
                 print_conditional_if(cond_var, file=af_const_file)
-                key = 'MP_ROM_QSTR(MP_QSTR_{}),'.format(mux_name)
-                val = 'MP_ROM_INT(GPIO_{})'.format(mux_name)
-                print('    { %-*s %s },' % (mux_name_width + 26, key, val),
-                      file=af_const_file)
+                key = "MP_ROM_QSTR(MP_QSTR_{}),".format(mux_name)
+                val = "MP_ROM_INT(GPIO_{})".format(mux_name)
+                print("    { %-*s %s }," % (mux_name_width + 26, key, val), file=af_const_file)
                 print_conditional_endif(cond_var, file=af_const_file)
 
     def print_af_defs(self, af_defs_filename, cmp_strings):
-        with open(af_defs_filename,  'wt') as af_defs_file:
+        with open(af_defs_filename, "wt") as af_defs_file:
 
             STATIC_AF_TOKENS = {}
             for named_pin in self.board_pins:
                 for af in named_pin.pin().alt_fn:
                     func = "%s%d" % (af.func, af.fn_num) if af.fn_num else af.func
-                    pin_type = (af.pin_type or "NULL").split('(')[0]
+                    pin_type = (af.pin_type or "NULL").split("(")[0]
                     tok = "#define STATIC_AF_%s_%s(pin_obj) ( \\" % (func, pin_type)
                     if tok not in STATIC_AF_TOKENS:
                         STATIC_AF_TOKENS[tok] = []
                     if cmp_strings:
                         pin_name = named_pin.pin().cpu_pin_name()
-                        cmp_str = '    ((strcmp( #pin_obj , "(&pin_%s_obj)") ' \
-                            ' & strcmp( #pin_obj , "((&pin_%s_obj))")) == 0) ? (%d) : \\' % (
-                                pin_name, pin_name, af.idx
-                            )
+                        cmp_str = (
+                            '    ((strcmp( #pin_obj , "(&pin_%s_obj)") '
+                            ' & strcmp( #pin_obj , "((&pin_%s_obj))")) == 0) ? (%d) : \\'
+                            % (pin_name, pin_name, af.idx)
+                        )
                     else:
-                        cmp_str = '    ((pin_obj) == (pin_%s)) ? (%d) : \\' % (
-                                named_pin.pin().cpu_pin_name(), af.idx
-                            )
+                        cmp_str = "    ((pin_obj) == (pin_%s)) ? (%d) : \\" % (
+                            named_pin.pin().cpu_pin_name(),
+                            af.idx,
+                        )
                     STATIC_AF_TOKENS[tok].append(cmp_str)
 
             for tok, pins in STATIC_AF_TOKENS.items():
@@ -436,48 +464,49 @@
                 print("    (0xffffffffffffffffULL))\n", file=af_defs_file)
 
     def print_af_py(self, af_py_filename):
-        with open(af_py_filename,  'wt') as af_py_file:
-            print('PINS_AF = (', file=af_py_file)
+        with open(af_py_filename, "wt") as af_py_file:
+            print("PINS_AF = (", file=af_py_file)
             for named_pin in self.board_pins:
                 if named_pin.is_hidden():
                     continue
-                print("  ('%s', " % named_pin.name(), end='', file=af_py_file)
+                print("  ('%s', " % named_pin.name(), end="", file=af_py_file)
                 for af in named_pin.pin().alt_fn:
                     if af.is_supported():
-                        print("(%d, '%s'), " % (af.idx, af.af_str), end='', file=af_py_file)
-                print('),', file=af_py_file)
-            print(')',  file=af_py_file)
+                        print("(%d, '%s'), " % (af.idx, af.af_str), end="", file=af_py_file)
+                print("),", file=af_py_file)
+            print(")", file=af_py_file)
 
 
 def main():
     parser = argparse.ArgumentParser(
         prog="make-pins.py",
         usage="%(prog)s [options] [command]",
-        description="Generate board specific pin file"
+        description="Generate board specific pin file",
     )
     parser.add_argument(
-        "-a", "--af",
+        "-a",
+        "--af",
         dest="af_filename",
         help="Specifies the alternate function file for the chip",
-        default="stm32f4xx_af.csv"
+        default="stm32f4xx_af.csv",
     )
     parser.add_argument(
         "--af-const",
         dest="af_const_filename",
         help="Specifies header file for alternate function constants.",
-        default="build/pins_af_const.h"
+        default="build/pins_af_const.h",
     )
     parser.add_argument(
         "--af-py",
         dest="af_py_filename",
         help="Specifies the filename for the python alternate function mappings.",
-        default="build/pins_af.py"
+        default="build/pins_af.py",
     )
     parser.add_argument(
         "--af-defs",
         dest="af_defs_filename",
         help="Specifies the filename for the alternate function defines.",
-        default="build/pins_af_defs.h"
+        default="build/pins_af_defs.h",
     )
     parser.add_argument(
         "--af-defs-cmp-strings",
@@ -486,52 +515,53 @@
         action="store_true",
     )
     parser.add_argument(
-        "-b", "--board",
-        dest="board_filename",
-        help="Specifies the board file",
+        "-b", "--board", dest="board_filename", help="Specifies the board file",
     )
     parser.add_argument(
-        "-p", "--prefix",
+        "-p",
+        "--prefix",
         dest="prefix_filename",
         help="Specifies beginning portion of generated pins file",
-        default="stm32f4xx_prefix.c"
+        default="stm32f4xx_prefix.c",
     )
     parser.add_argument(
-        "-q", "--qstr",
+        "-q",
+        "--qstr",
         dest="qstr_filename",
         help="Specifies name of generated qstr header file",
-        default="build/pins_qstr.h"
+        default="build/pins_qstr.h",
     )
     parser.add_argument(
-        "-r", "--hdr",
+        "-r",
+        "--hdr",
         dest="hdr_filename",
         help="Specifies name of generated pin header file",
-        default="build/pins.h"
+        default="build/pins.h",
     )
     parser.add_argument(
         "--hdr-obj-decls",
         dest="hdr_obj_decls",
         help="Whether to include declarations for pin objects in pin header file",
-        action="store_true"
+        action="store_true",
     )
     args = parser.parse_args(sys.argv[1:])
 
     pins = Pins()
 
-    print('// This file was automatically generated by make-pins.py')
-    print('//')
+    print("// This file was automatically generated by make-pins.py")
+    print("//")
     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, 1, 2)
 
     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)
 
     if args.prefix_filename:
-        print('// --prefix {:s}'.format(args.prefix_filename))
-        print('')
-        with open(args.prefix_filename, 'r') as prefix_file:
+        print("// --prefix {:s}".format(args.prefix_filename))
+        print("")
+        with open(args.prefix_filename, "r") as prefix_file:
             print(prefix_file.read())
     pins.print()
     pins.print_adc(1)
diff --git a/ports/stm32/boards/manifest.py b/ports/stm32/boards/manifest.py
index 41b728f..3390773 100644
--- a/ports/stm32/boards/manifest.py
+++ b/ports/stm32/boards/manifest.py
@@ -1,3 +1,3 @@
-freeze('$(MPY_DIR)/drivers/dht', 'dht.py')
-freeze('$(MPY_DIR)/drivers/display', ('lcd160cr.py', 'lcd160cr_test.py'))
-freeze('$(MPY_DIR)/drivers/onewire', 'onewire.py')
+freeze("$(MPY_DIR)/drivers/dht", "dht.py")
+freeze("$(MPY_DIR)/drivers/display", ("lcd160cr.py", "lcd160cr_test.py"))
+freeze("$(MPY_DIR)/drivers/onewire", "onewire.py")
diff --git a/ports/stm32/boards/pllvalues.py b/ports/stm32/boards/pllvalues.py
index 2d64876..59d6603 100644
--- a/ports/stm32/boards/pllvalues.py
+++ b/ports/stm32/boards/pllvalues.py
@@ -7,8 +7,11 @@
 from __future__ import print_function
 import re
 
+
 class MCU:
-    def __init__(self, range_sysclk, range_m, range_n, range_p, range_q, range_vco_in, range_vco_out):
+    def __init__(
+        self, range_sysclk, range_m, range_n, range_p, range_q, range_vco_in, range_vco_out
+    ):
         self.range_sysclk = range_sysclk
         self.range_m = range_m
         self.range_n = range_n
@@ -17,6 +20,7 @@
         self.range_vco_in = range_vco_in
         self.range_vco_out = range_vco_out
 
+
 mcu_default = MCU(
     range_sysclk=range(2, 216 + 1, 2),
     range_m=range(2, 63 + 1),
@@ -28,21 +32,23 @@
 )
 
 mcu_h7 = MCU(
-    range_sysclk=range(2, 400 + 1, 2), # above 400MHz currently unsupported
+    range_sysclk=range(2, 400 + 1, 2),  # above 400MHz currently unsupported
     range_m=range(1, 63 + 1),
     range_n=range(4, 512 + 1),
     range_p=range(2, 128 + 1, 2),
     range_q=range(1, 128 + 1),
     range_vco_in=range(1, 16 + 1),
-    range_vco_out=range(150, 960 + 1), # 150-420=medium, 192-960=wide
+    range_vco_out=range(150, 960 + 1),  # 150-420=medium, 192-960=wide
 )
 
+
 def close_int(x):
     return abs(x - round(x)) < 0.01
 
+
 # original version that requires N/M to be an integer (for simplicity)
 def compute_pll(hse, sys):
-    for P in (2, 4, 6, 8): # allowed values of P
+    for P in (2, 4, 6, 8):  # allowed values of P
         Q = sys * P / 48
         NbyM = sys * P / hse
         # N/M and Q must be integers
@@ -69,6 +75,7 @@
     # no valid values found
     return None
 
+
 # improved version that doesn't require N/M to be an integer
 def compute_pll2(hse, sys, relax_pll48):
     # Loop over the allowed values of P, looking for a valid PLL configuration
@@ -78,9 +85,9 @@
         # VCO_OUT must be between 192MHz and 432MHz
         if not sys * P in mcu.range_vco_out:
             continue
-        NbyM = float(sys * P) / hse # float for Python 2
+        NbyM = float(sys * P) / hse  # float for Python 2
         # scan M
-        M_min = mcu.range_n[0] // int(round(NbyM)) # starting value
+        M_min = mcu.range_n[0] // int(round(NbyM))  # starting value
         while mcu.range_vco_in[-1] * M_min < hse:
             M_min += 1
         # VCO_IN must be >=1MHz, but higher is better for stability so start high (low M)
@@ -94,7 +101,7 @@
             # N is restricted
             if N not in mcu.range_n:
                 continue
-            Q = float(sys * P) / 48 # float for Python 2
+            Q = float(sys * P) / 48  # float for Python 2
             # Q must be an integer in a set range
             if close_int(Q) and round(Q) in mcu.range_q:
                 # found valid values
@@ -113,8 +120,9 @@
         # no valid values found which give 48MHz on PLL48
         return None
 
+
 def compute_derived(hse, pll):
-    hse = float(hse) # float for Python 2
+    hse = float(hse)  # float for Python 2
     M, N, P, Q = pll
     vco_in = hse / M
     vco_out = hse * N / M
@@ -122,6 +130,7 @@
     pll48ck = hse / M * N / Q
     return (vco_in, vco_out, pllck, pll48ck)
 
+
 def verify_pll(hse, pll):
     M, N, P, Q = pll
     vco_in, vco_out, pllck, pll48ck = compute_derived(hse, pll)
@@ -140,6 +149,7 @@
     assert mcu.range_vco_in[0] <= vco_in <= mcu.range_vco_in[-1]
     assert mcu.range_vco_out[0] <= vco_out <= mcu.range_vco_out[-1]
 
+
 def compute_pll_table(source_clk, relax_pll48):
     valid_plls = []
     for sysclk in mcu.range_sysclk:
@@ -149,22 +159,27 @@
             valid_plls.append((sysclk, pll))
     return valid_plls
 
+
 def generate_c_table(hse, valid_plls):
     valid_plls.sort()
-    if mcu.range_sysclk[-1] <= 0xff and mcu.range_m[-1] <= 0x3f and mcu.range_p[-1] // 2 - 1 <= 0x3:
-        typedef = 'uint16_t'
-        sys_mask = 0xff
+    if (
+        mcu.range_sysclk[-1] <= 0xFF
+        and mcu.range_m[-1] <= 0x3F
+        and mcu.range_p[-1] // 2 - 1 <= 0x3
+    ):
+        typedef = "uint16_t"
+        sys_mask = 0xFF
         m_shift = 10
-        m_mask = 0x3f
+        m_mask = 0x3F
         p_shift = 8
         p_mask = 0x3
     else:
-        typedef = 'uint32_t'
-        sys_mask = 0xffff
+        typedef = "uint32_t"
+        sys_mask = 0xFFFF
         m_shift = 24
-        m_mask = 0xff
+        m_mask = 0xFF
         p_shift = 16
-        p_mask = 0xff
+        p_mask = 0xFF
     print("#define PLL_FREQ_TABLE_SYS(pll) ((pll) & %d)" % (sys_mask,))
     print("#define PLL_FREQ_TABLE_M(pll) (((pll) >> %d) & %d)" % (m_shift, m_mask))
     print("#define PLL_FREQ_TABLE_P(pll) (((((pll) >> %d) & %d) + 1) * 2)" % (p_shift, p_mask))
@@ -172,15 +187,18 @@
     print("// (M, P/2-1, SYS) values for %u MHz source" % hse)
     print("static const pll_freq_table_t pll_freq_table[%u] = {" % (len(valid_plls),))
     for sys, (M, N, P, Q) in valid_plls:
-        print("    (%u << %u) | (%u << %u) | %u," % (M, m_shift, P // 2 - 1, p_shift, sys), end='')
+        print("    (%u << %u) | (%u << %u) | %u," % (M, m_shift, P // 2 - 1, p_shift, sys), end="")
         if M >= 2:
             vco_in, vco_out, pllck, pll48ck = compute_derived(hse, (M, N, P, Q))
-            print(" // M=%u N=%u P=%u Q=%u vco_in=%.2f vco_out=%.2f pll48=%.2f"
-                % (M, N, P, Q, vco_in, vco_out, pll48ck), end=''
+            print(
+                " // M=%u N=%u P=%u Q=%u vco_in=%.2f vco_out=%.2f pll48=%.2f"
+                % (M, N, P, Q, vco_in, vco_out, pll48ck),
+                end="",
             )
         print()
     print("};")
 
+
 def print_table(hse, valid_plls):
     print("HSE =", hse, "MHz")
     print("sys :  M      N     P     Q : VCO_IN VCO_OUT   PLLCK PLL48CK")
@@ -189,9 +207,10 @@
         print(out_format % ((sys,) + pll + compute_derived(hse, pll)))
     print("found %u valid configurations" % len(valid_plls))
 
+
 def search_header_for_hsx_values(filename, vals):
     regex_inc = re.compile(r'#include "(boards/[A-Za-z0-9_./]+)"')
-    regex_def = re.compile(r'#define +(HSE_VALUE|HSI_VALUE) +\((\(uint32_t\))?([0-9]+)\)')
+    regex_def = re.compile(r"#define +(HSE_VALUE|HSI_VALUE) +\((\(uint32_t\))?([0-9]+)\)")
     with open(filename) as f:
         for line in f:
             line = line.strip()
@@ -204,30 +223,32 @@
             if m:
                 # Found HSE_VALUE or HSI_VALUE
                 val = int(m.group(3)) // 1000000
-                if m.group(1) == 'HSE_VALUE':
+                if m.group(1) == "HSE_VALUE":
                     vals[0] = val
                 else:
                     vals[1] = val
     return vals
 
+
 def main():
     global mcu
     global out_format
 
     # parse input args
     import sys
+
     argv = sys.argv[1:]
 
     c_table = False
-    mcu_series = 'f4'
+    mcu_series = "f4"
     hse = None
     hsi = None
 
     while True:
-        if argv[0] == '-c':
+        if argv[0] == "-c":
             c_table = True
             argv.pop(0)
-        elif argv[0] == '-m':
+        elif argv[0] == "-m":
             argv.pop(0)
             mcu_series = argv.pop(0).lower()
         else:
@@ -250,31 +271,32 @@
         hse = int(argv[0])
 
     # Select MCU parameters
-    if mcu_series == 'h7':
+    if mcu_series == "h7":
         mcu = mcu_h7
     else:
         mcu = mcu_default
 
     # Relax constraight on PLLQ being 48MHz on F7 and H7 MCUs, which have separate PLLs for 48MHz
-    relax_pll48 = mcu_series in ('f7', 'h7')
+    relax_pll48 = mcu_series in ("f7", "h7")
 
     hse_valid_plls = compute_pll_table(hse, relax_pll48)
     if hsi is not None:
         hsi_valid_plls = compute_pll_table(hsi, relax_pll48)
 
     if c_table:
-        print('#if MICROPY_HW_CLK_USE_HSI')
+        print("#if MICROPY_HW_CLK_USE_HSI")
         if hsi is not None:
             hsi_valid_plls.append((hsi, (0, 0, 2, 0)))
             generate_c_table(hsi, hsi_valid_plls)
-        print('#else')
+        print("#else")
         if hsi is not None:
             hse_valid_plls.append((hsi, (0, 0, 2, 0)))
         hse_valid_plls.append((hse, (1, 0, 2, 0)))
         generate_c_table(hse, hse_valid_plls)
-        print('#endif')
+        print("#endif")
     else:
         print_table(hse, hse_valid_plls)
 
+
 if __name__ == "__main__":
     main()
diff --git a/ports/stm32/can.c b/ports/stm32/can.c
index 1ee4649..e5fc55e 100644
--- a/ports/stm32/can.c
+++ b/ports/stm32/can.c
@@ -163,16 +163,16 @@
 void can_clearfilter(pyb_can_obj_t *self, uint32_t f, uint8_t bank) {
     CAN_FilterConfTypeDef filter;
 
-    filter.FilterIdHigh         = 0;
-    filter.FilterIdLow          = 0;
-    filter.FilterMaskIdHigh     = 0;
-    filter.FilterMaskIdLow      = 0;
+    filter.FilterIdHigh = 0;
+    filter.FilterIdLow = 0;
+    filter.FilterMaskIdHigh = 0;
+    filter.FilterMaskIdLow = 0;
     filter.FilterFIFOAssignment = CAN_FILTER_FIFO0;
-    filter.FilterNumber         = f;
-    filter.FilterMode           = CAN_FILTERMODE_IDMASK;
-    filter.FilterScale          = CAN_FILTERSCALE_16BIT;
-    filter.FilterActivation     = DISABLE;
-    filter.BankNumber           = bank;
+    filter.FilterNumber = f;
+    filter.FilterMode = CAN_FILTERMODE_IDMASK;
+    filter.FilterScale = CAN_FILTERSCALE_16BIT;
+    filter.FilterActivation = DISABLE;
+    filter.BankNumber = bank;
 
     HAL_CAN_ConfigFilter(NULL, &filter);
 }
@@ -235,15 +235,15 @@
     assert_param(IS_CAN_DLC(hcan->pTxMsg->DLC));
 
     // Select one empty transmit mailbox
-    if ((hcan->Instance->TSR&CAN_TSR_TME0) == CAN_TSR_TME0) {
+    if ((hcan->Instance->TSR & CAN_TSR_TME0) == CAN_TSR_TME0) {
         transmitmailbox = CAN_TXMAILBOX_0;
         rqcpflag = CAN_FLAG_RQCP0;
         txokflag = CAN_FLAG_TXOK0;
-    } else if ((hcan->Instance->TSR&CAN_TSR_TME1) == CAN_TSR_TME1) {
+    } else if ((hcan->Instance->TSR & CAN_TSR_TME1) == CAN_TSR_TME1) {
         transmitmailbox = CAN_TXMAILBOX_1;
         rqcpflag = CAN_FLAG_RQCP1;
         txokflag = CAN_FLAG_TXOK1;
-    } else if ((hcan->Instance->TSR&CAN_TSR_TME2) == CAN_TSR_TME2) {
+    } else if ((hcan->Instance->TSR & CAN_TSR_TME2) == CAN_TSR_TME2) {
         transmitmailbox = CAN_TXMAILBOX_2;
         rqcpflag = CAN_FLAG_RQCP2;
         txokflag = CAN_FLAG_TXOK2;
@@ -257,12 +257,12 @@
         if (hcan->pTxMsg->IDE == CAN_ID_STD) {
             assert_param(IS_CAN_STDID(hcan->pTxMsg->StdId));
             hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->StdId << 21) | \
-                                                        hcan->pTxMsg->RTR);
+                hcan->pTxMsg->RTR);
         } else {
             assert_param(IS_CAN_EXTID(hcan->pTxMsg->ExtId));
             hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->ExtId << 3) | \
-                                                        hcan->pTxMsg->IDE | \
-                                                        hcan->pTxMsg->RTR);
+                hcan->pTxMsg->IDE | \
+                hcan->pTxMsg->RTR);
         }
 
         // Set up the DLC
@@ -272,13 +272,13 @@
 
         // Set up the data field
         hcan->Instance->sTxMailBox[transmitmailbox].TDLR = (((uint32_t)hcan->pTxMsg->Data[3] << 24) |
-                                                ((uint32_t)hcan->pTxMsg->Data[2] << 16) |
-                                                ((uint32_t)hcan->pTxMsg->Data[1] << 8) |
-                                                ((uint32_t)hcan->pTxMsg->Data[0]));
+            ((uint32_t)hcan->pTxMsg->Data[2] << 16) |
+            ((uint32_t)hcan->pTxMsg->Data[1] << 8) |
+            ((uint32_t)hcan->pTxMsg->Data[0]));
         hcan->Instance->sTxMailBox[transmitmailbox].TDHR = (((uint32_t)hcan->pTxMsg->Data[7] << 24) |
-                                                ((uint32_t)hcan->pTxMsg->Data[6] << 16) |
-                                                ((uint32_t)hcan->pTxMsg->Data[5] << 8) |
-                                                ((uint32_t)hcan->pTxMsg->Data[4]));
+            ((uint32_t)hcan->pTxMsg->Data[6] << 16) |
+            ((uint32_t)hcan->pTxMsg->Data[5] << 8) |
+            ((uint32_t)hcan->pTxMsg->Data[4]));
         // Request transmission
         hcan->Instance->sTxMailBox[transmitmailbox].TIR |= CAN_TI0R_TXRQ;
 
diff --git a/ports/stm32/dac.c b/ports/stm32/dac.c
index 29f11db..c5c6172 100644
--- a/ports/stm32/dac.c
+++ b/ports/stm32/dac.c
@@ -153,7 +153,7 @@
         base = (uint32_t)&DAC->DHR12R2;
     #endif
     }
-    *(volatile uint32_t*)(base + align) = value;
+    *(volatile uint32_t *)(base + align) = value;
 }
 
 STATIC void dac_start(uint32_t dac_channel) {
@@ -500,7 +500,7 @@
     .name = MP_QSTR_DAC,
     .print = pyb_dac_print,
     .make_new = pyb_dac_make_new,
-    .locals_dict = (mp_obj_dict_t*)&pyb_dac_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_dac_locals_dict,
 };
 
 #endif // MICROPY_HW_ENABLE_DAC
diff --git a/ports/stm32/dma.c b/ports/stm32/dma.c
index 734cf2e..15919fa 100644
--- a/ports/stm32/dma.c
+++ b/ports/stm32/dma.c
@@ -96,22 +96,22 @@
 // vary depending on the peripheral instance so they get passed separately
 static const DMA_InitTypeDef dma_init_struct_spi_i2c = {
     #if defined(STM32F4) || defined(STM32F7)
-    .Channel             = 0,
+    .Channel = 0,
     #elif defined(STM32H7) || defined(STM32L0) || defined(STM32L4)
-    .Request             = 0,
+    .Request = 0,
     #endif
-    .Direction           = 0,
-    .PeriphInc           = DMA_PINC_DISABLE,
-    .MemInc              = DMA_MINC_ENABLE,
+    .Direction = 0,
+    .PeriphInc = DMA_PINC_DISABLE,
+    .MemInc = DMA_MINC_ENABLE,
     .PeriphDataAlignment = DMA_PDATAALIGN_BYTE,
-    .MemDataAlignment    = DMA_MDATAALIGN_BYTE,
-    .Mode                = DMA_NORMAL,
-    .Priority            = DMA_PRIORITY_LOW,
+    .MemDataAlignment = DMA_MDATAALIGN_BYTE,
+    .Mode = DMA_NORMAL,
+    .Priority = DMA_PRIORITY_LOW,
     #if defined(STM32F4) || defined(STM32F7) || defined(STM32H7)
-    .FIFOMode            = DMA_FIFOMODE_DISABLE,
-    .FIFOThreshold       = DMA_FIFO_THRESHOLD_FULL,
-    .MemBurst            = DMA_MBURST_INC4,
-    .PeriphBurst         = DMA_PBURST_INC4
+    .FIFOMode = DMA_FIFOMODE_DISABLE,
+    .FIFOThreshold = DMA_FIFO_THRESHOLD_FULL,
+    .MemBurst = DMA_MBURST_INC4,
+    .PeriphBurst = DMA_PBURST_INC4
     #endif
 };
 
@@ -119,26 +119,26 @@
 // Parameters to dma_init() for SDIO tx and rx.
 static const DMA_InitTypeDef dma_init_struct_sdio = {
     #if defined(STM32F4) || defined(STM32F7)
-    .Channel             = 0,
+    .Channel = 0,
     #elif defined(STM32L0) || defined(STM32L4)
-    .Request             = 0,
+    .Request = 0,
     #endif
-    .Direction           = 0,
-    .PeriphInc           = DMA_PINC_DISABLE,
-    .MemInc              = DMA_MINC_ENABLE,
+    .Direction = 0,
+    .PeriphInc = DMA_PINC_DISABLE,
+    .MemInc = DMA_MINC_ENABLE,
     .PeriphDataAlignment = DMA_PDATAALIGN_WORD,
-    .MemDataAlignment    = DMA_MDATAALIGN_WORD,
+    .MemDataAlignment = DMA_MDATAALIGN_WORD,
     #if defined(STM32F4) || defined(STM32F7)
-    .Mode                = DMA_PFCTRL,
+    .Mode = DMA_PFCTRL,
     #elif defined(STM32L0) || defined(STM32L4)
-    .Mode                = DMA_NORMAL,
+    .Mode = DMA_NORMAL,
     #endif
-    .Priority            = DMA_PRIORITY_VERY_HIGH,
+    .Priority = DMA_PRIORITY_VERY_HIGH,
     #if defined(STM32F4) || defined(STM32F7)
-    .FIFOMode            = DMA_FIFOMODE_ENABLE,
-    .FIFOThreshold       = DMA_FIFO_THRESHOLD_FULL,
-    .MemBurst            = DMA_MBURST_INC4,
-    .PeriphBurst         = DMA_PBURST_INC4,
+    .FIFOMode = DMA_FIFOMODE_ENABLE,
+    .FIFOThreshold = DMA_FIFO_THRESHOLD_FULL,
+    .MemBurst = DMA_MBURST_INC4,
+    .PeriphBurst = DMA_PBURST_INC4,
     #endif
 };
 #endif
@@ -147,22 +147,22 @@
 // Default parameters to dma_init() for DAC tx
 static const DMA_InitTypeDef dma_init_struct_dac = {
     #if defined(STM32F4) || defined(STM32F7)
-    .Channel             = 0,
+    .Channel = 0,
     #elif defined(STM32H7) || defined(STM32L0) || defined(STM32L4)
-    .Request             = 0,
+    .Request = 0,
     #endif
-    .Direction           = 0,
-    .PeriphInc           = DMA_PINC_DISABLE,
-    .MemInc              = DMA_MINC_ENABLE,
+    .Direction = 0,
+    .PeriphInc = DMA_PINC_DISABLE,
+    .MemInc = DMA_MINC_ENABLE,
     .PeriphDataAlignment = DMA_PDATAALIGN_BYTE,
-    .MemDataAlignment    = DMA_MDATAALIGN_BYTE,
-    .Mode                = DMA_NORMAL,
-    .Priority            = DMA_PRIORITY_HIGH,
+    .MemDataAlignment = DMA_MDATAALIGN_BYTE,
+    .Mode = DMA_NORMAL,
+    .Priority = DMA_PRIORITY_HIGH,
     #if defined(STM32F4) || defined(STM32F7) || defined(STM32H7)
-    .FIFOMode            = DMA_FIFOMODE_DISABLE,
-    .FIFOThreshold       = DMA_FIFO_THRESHOLD_HALFFULL,
-    .MemBurst            = DMA_MBURST_SINGLE,
-    .PeriphBurst         = DMA_PBURST_SINGLE,
+    .FIFOMode = DMA_FIFOMODE_DISABLE,
+    .FIFOThreshold = DMA_FIFO_THRESHOLD_HALFFULL,
+    .MemBurst = DMA_MBURST_SINGLE,
+    .PeriphBurst = DMA_PBURST_SINGLE,
     #endif
 };
 #endif
@@ -170,21 +170,21 @@
 #if MICROPY_HW_ENABLE_DCMI
 static const DMA_InitTypeDef dma_init_struct_dcmi = {
     #if defined(STM32H7)
-    .Request             = DMA_REQUEST_DCMI,
+    .Request = DMA_REQUEST_DCMI,
     #else
-    .Channel             = DMA_CHANNEL_1,
+    .Channel = DMA_CHANNEL_1,
     #endif
-    .Direction           = DMA_PERIPH_TO_MEMORY,
-    .PeriphInc           = DMA_PINC_DISABLE,
-    .MemInc              = DMA_MINC_ENABLE,
+    .Direction = DMA_PERIPH_TO_MEMORY,
+    .PeriphInc = DMA_PINC_DISABLE,
+    .MemInc = DMA_MINC_ENABLE,
     .PeriphDataAlignment = DMA_PDATAALIGN_WORD,
-    .MemDataAlignment    = DMA_MDATAALIGN_WORD,
-    .Mode                = DMA_NORMAL,
-    .Priority            = DMA_PRIORITY_HIGH,
-    .FIFOMode            = DMA_FIFOMODE_ENABLE,
-    .FIFOThreshold       = DMA_FIFO_THRESHOLD_FULL,
-    .MemBurst            = DMA_MBURST_INC4,
-    .PeriphBurst         = DMA_PBURST_SINGLE
+    .MemDataAlignment = DMA_MDATAALIGN_WORD,
+    .Mode = DMA_NORMAL,
+    .Priority = DMA_PRIORITY_HIGH,
+    .FIFOMode = DMA_FIFOMODE_ENABLE,
+    .FIFOThreshold = DMA_FIFO_THRESHOLD_FULL,
+    .MemBurst = DMA_MBURST_INC4,
+    .PeriphBurst = DMA_PBURST_SINGLE
 };
 #endif
 
@@ -566,22 +566,118 @@
 
 #elif defined(STM32F4) || defined(STM32F7) || defined(STM32H7)
 
-void DMA1_Stream0_IRQHandler(void) { IRQ_ENTER(DMA1_Stream0_IRQn); if (dma_handle[dma_id_0] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_0]); } IRQ_EXIT(DMA1_Stream0_IRQn); }
-void DMA1_Stream1_IRQHandler(void) { IRQ_ENTER(DMA1_Stream1_IRQn); if (dma_handle[dma_id_1] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_1]); } IRQ_EXIT(DMA1_Stream1_IRQn); }
-void DMA1_Stream2_IRQHandler(void) { IRQ_ENTER(DMA1_Stream2_IRQn); if (dma_handle[dma_id_2] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_2]); } IRQ_EXIT(DMA1_Stream2_IRQn); }
-void DMA1_Stream3_IRQHandler(void) { IRQ_ENTER(DMA1_Stream3_IRQn); if (dma_handle[dma_id_3] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_3]); } IRQ_EXIT(DMA1_Stream3_IRQn); }
-void DMA1_Stream4_IRQHandler(void) { IRQ_ENTER(DMA1_Stream4_IRQn); if (dma_handle[dma_id_4] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_4]); } IRQ_EXIT(DMA1_Stream4_IRQn); }
-void DMA1_Stream5_IRQHandler(void) { IRQ_ENTER(DMA1_Stream5_IRQn); if (dma_handle[dma_id_5] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_5]); } IRQ_EXIT(DMA1_Stream5_IRQn); }
-void DMA1_Stream6_IRQHandler(void) { IRQ_ENTER(DMA1_Stream6_IRQn); if (dma_handle[dma_id_6] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_6]); } IRQ_EXIT(DMA1_Stream6_IRQn); }
-void DMA1_Stream7_IRQHandler(void) { IRQ_ENTER(DMA1_Stream7_IRQn); if (dma_handle[dma_id_7] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_7]); } IRQ_EXIT(DMA1_Stream7_IRQn); }
-void DMA2_Stream0_IRQHandler(void) { IRQ_ENTER(DMA2_Stream0_IRQn); if (dma_handle[dma_id_8] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_8]); } IRQ_EXIT(DMA2_Stream0_IRQn); }
-void DMA2_Stream1_IRQHandler(void) { IRQ_ENTER(DMA2_Stream1_IRQn); if (dma_handle[dma_id_9] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_9]); } IRQ_EXIT(DMA2_Stream1_IRQn); }
-void DMA2_Stream2_IRQHandler(void) { IRQ_ENTER(DMA2_Stream2_IRQn); if (dma_handle[dma_id_10] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_10]); } IRQ_EXIT(DMA2_Stream2_IRQn); }
-void DMA2_Stream3_IRQHandler(void) { IRQ_ENTER(DMA2_Stream3_IRQn); if (dma_handle[dma_id_11] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_11]); } IRQ_EXIT(DMA2_Stream3_IRQn); }
-void DMA2_Stream4_IRQHandler(void) { IRQ_ENTER(DMA2_Stream4_IRQn); if (dma_handle[dma_id_12] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_12]); } IRQ_EXIT(DMA2_Stream4_IRQn); }
-void DMA2_Stream5_IRQHandler(void) { IRQ_ENTER(DMA2_Stream5_IRQn); if (dma_handle[dma_id_13] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_13]); } IRQ_EXIT(DMA2_Stream5_IRQn); }
-void DMA2_Stream6_IRQHandler(void) { IRQ_ENTER(DMA2_Stream6_IRQn); if (dma_handle[dma_id_14] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_14]); } IRQ_EXIT(DMA2_Stream6_IRQn); }
-void DMA2_Stream7_IRQHandler(void) { IRQ_ENTER(DMA2_Stream7_IRQn); if (dma_handle[dma_id_15] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_15]); } IRQ_EXIT(DMA2_Stream7_IRQn); }
+void DMA1_Stream0_IRQHandler(void) {
+    IRQ_ENTER(DMA1_Stream0_IRQn);
+    if (dma_handle[dma_id_0] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_0]);
+    }
+    IRQ_EXIT(DMA1_Stream0_IRQn);
+}
+void DMA1_Stream1_IRQHandler(void) {
+    IRQ_ENTER(DMA1_Stream1_IRQn);
+    if (dma_handle[dma_id_1] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_1]);
+    }
+    IRQ_EXIT(DMA1_Stream1_IRQn);
+}
+void DMA1_Stream2_IRQHandler(void) {
+    IRQ_ENTER(DMA1_Stream2_IRQn);
+    if (dma_handle[dma_id_2] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_2]);
+    }
+    IRQ_EXIT(DMA1_Stream2_IRQn);
+}
+void DMA1_Stream3_IRQHandler(void) {
+    IRQ_ENTER(DMA1_Stream3_IRQn);
+    if (dma_handle[dma_id_3] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_3]);
+    }
+    IRQ_EXIT(DMA1_Stream3_IRQn);
+}
+void DMA1_Stream4_IRQHandler(void) {
+    IRQ_ENTER(DMA1_Stream4_IRQn);
+    if (dma_handle[dma_id_4] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_4]);
+    }
+    IRQ_EXIT(DMA1_Stream4_IRQn);
+}
+void DMA1_Stream5_IRQHandler(void) {
+    IRQ_ENTER(DMA1_Stream5_IRQn);
+    if (dma_handle[dma_id_5] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_5]);
+    }
+    IRQ_EXIT(DMA1_Stream5_IRQn);
+}
+void DMA1_Stream6_IRQHandler(void) {
+    IRQ_ENTER(DMA1_Stream6_IRQn);
+    if (dma_handle[dma_id_6] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_6]);
+    }
+    IRQ_EXIT(DMA1_Stream6_IRQn);
+}
+void DMA1_Stream7_IRQHandler(void) {
+    IRQ_ENTER(DMA1_Stream7_IRQn);
+    if (dma_handle[dma_id_7] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_7]);
+    }
+    IRQ_EXIT(DMA1_Stream7_IRQn);
+}
+void DMA2_Stream0_IRQHandler(void) {
+    IRQ_ENTER(DMA2_Stream0_IRQn);
+    if (dma_handle[dma_id_8] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_8]);
+    }
+    IRQ_EXIT(DMA2_Stream0_IRQn);
+}
+void DMA2_Stream1_IRQHandler(void) {
+    IRQ_ENTER(DMA2_Stream1_IRQn);
+    if (dma_handle[dma_id_9] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_9]);
+    }
+    IRQ_EXIT(DMA2_Stream1_IRQn);
+}
+void DMA2_Stream2_IRQHandler(void) {
+    IRQ_ENTER(DMA2_Stream2_IRQn);
+    if (dma_handle[dma_id_10] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_10]);
+    }
+    IRQ_EXIT(DMA2_Stream2_IRQn);
+}
+void DMA2_Stream3_IRQHandler(void) {
+    IRQ_ENTER(DMA2_Stream3_IRQn);
+    if (dma_handle[dma_id_11] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_11]);
+    }
+    IRQ_EXIT(DMA2_Stream3_IRQn);
+}
+void DMA2_Stream4_IRQHandler(void) {
+    IRQ_ENTER(DMA2_Stream4_IRQn);
+    if (dma_handle[dma_id_12] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_12]);
+    }
+    IRQ_EXIT(DMA2_Stream4_IRQn);
+}
+void DMA2_Stream5_IRQHandler(void) {
+    IRQ_ENTER(DMA2_Stream5_IRQn);
+    if (dma_handle[dma_id_13] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_13]);
+    }
+    IRQ_EXIT(DMA2_Stream5_IRQn);
+}
+void DMA2_Stream6_IRQHandler(void) {
+    IRQ_ENTER(DMA2_Stream6_IRQn);
+    if (dma_handle[dma_id_14] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_14]);
+    }
+    IRQ_EXIT(DMA2_Stream6_IRQn);
+}
+void DMA2_Stream7_IRQHandler(void) {
+    IRQ_ENTER(DMA2_Stream7_IRQn);
+    if (dma_handle[dma_id_15] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_15]);
+    }
+    IRQ_EXIT(DMA2_Stream7_IRQn);
+}
 
 #elif defined(STM32L0)
 
@@ -623,20 +719,104 @@
 
 #elif defined(STM32L4)
 
-void DMA1_Channel1_IRQHandler(void) { IRQ_ENTER(DMA1_Channel1_IRQn); if (dma_handle[dma_id_0] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_0]); } IRQ_EXIT(DMA1_Channel1_IRQn); }
-void DMA1_Channel2_IRQHandler(void) { IRQ_ENTER(DMA1_Channel2_IRQn); if (dma_handle[dma_id_1] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_1]); } IRQ_EXIT(DMA1_Channel2_IRQn); }
-void DMA1_Channel3_IRQHandler(void) { IRQ_ENTER(DMA1_Channel3_IRQn); if (dma_handle[dma_id_2] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_2]); } IRQ_EXIT(DMA1_Channel3_IRQn); }
-void DMA1_Channel4_IRQHandler(void) { IRQ_ENTER(DMA1_Channel4_IRQn); if (dma_handle[dma_id_3] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_3]); } IRQ_EXIT(DMA1_Channel4_IRQn); }
-void DMA1_Channel5_IRQHandler(void) { IRQ_ENTER(DMA1_Channel5_IRQn); if (dma_handle[dma_id_4] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_4]); } IRQ_EXIT(DMA1_Channel5_IRQn); }
-void DMA1_Channel6_IRQHandler(void) { IRQ_ENTER(DMA1_Channel6_IRQn); if (dma_handle[dma_id_5] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_5]); } IRQ_EXIT(DMA1_Channel6_IRQn); }
-void DMA1_Channel7_IRQHandler(void) { IRQ_ENTER(DMA1_Channel7_IRQn); if (dma_handle[dma_id_6] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_6]); } IRQ_EXIT(DMA1_Channel7_IRQn); }
-void DMA2_Channel1_IRQHandler(void) { IRQ_ENTER(DMA2_Channel1_IRQn); if (dma_handle[dma_id_7] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_7]); } IRQ_EXIT(DMA2_Channel1_IRQn); }
-void DMA2_Channel2_IRQHandler(void) { IRQ_ENTER(DMA2_Channel2_IRQn); if (dma_handle[dma_id_8] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_8]); } IRQ_EXIT(DMA2_Channel2_IRQn); }
-void DMA2_Channel3_IRQHandler(void) { IRQ_ENTER(DMA2_Channel3_IRQn); if (dma_handle[dma_id_9] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_9]); } IRQ_EXIT(DMA2_Channel3_IRQn); }
-void DMA2_Channel4_IRQHandler(void) { IRQ_ENTER(DMA2_Channel4_IRQn); if (dma_handle[dma_id_10] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_10]);} IRQ_EXIT(DMA2_Channel4_IRQn); }
-void DMA2_Channel5_IRQHandler(void) { IRQ_ENTER(DMA2_Channel5_IRQn); if (dma_handle[dma_id_11] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_11]);} IRQ_EXIT(DMA2_Channel5_IRQn); }
-void DMA2_Channel6_IRQHandler(void) { IRQ_ENTER(DMA2_Channel6_IRQn); if (dma_handle[dma_id_12] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_12]);} IRQ_EXIT(DMA2_Channel6_IRQn); }
-void DMA2_Channel7_IRQHandler(void) { IRQ_ENTER(DMA2_Channel7_IRQn); if (dma_handle[dma_id_13] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_13]);} IRQ_EXIT(DMA2_Channel7_IRQn); }
+void DMA1_Channel1_IRQHandler(void) {
+    IRQ_ENTER(DMA1_Channel1_IRQn);
+    if (dma_handle[dma_id_0] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_0]);
+    }
+    IRQ_EXIT(DMA1_Channel1_IRQn);
+}
+void DMA1_Channel2_IRQHandler(void) {
+    IRQ_ENTER(DMA1_Channel2_IRQn);
+    if (dma_handle[dma_id_1] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_1]);
+    }
+    IRQ_EXIT(DMA1_Channel2_IRQn);
+}
+void DMA1_Channel3_IRQHandler(void) {
+    IRQ_ENTER(DMA1_Channel3_IRQn);
+    if (dma_handle[dma_id_2] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_2]);
+    }
+    IRQ_EXIT(DMA1_Channel3_IRQn);
+}
+void DMA1_Channel4_IRQHandler(void) {
+    IRQ_ENTER(DMA1_Channel4_IRQn);
+    if (dma_handle[dma_id_3] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_3]);
+    }
+    IRQ_EXIT(DMA1_Channel4_IRQn);
+}
+void DMA1_Channel5_IRQHandler(void) {
+    IRQ_ENTER(DMA1_Channel5_IRQn);
+    if (dma_handle[dma_id_4] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_4]);
+    }
+    IRQ_EXIT(DMA1_Channel5_IRQn);
+}
+void DMA1_Channel6_IRQHandler(void) {
+    IRQ_ENTER(DMA1_Channel6_IRQn);
+    if (dma_handle[dma_id_5] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_5]);
+    }
+    IRQ_EXIT(DMA1_Channel6_IRQn);
+}
+void DMA1_Channel7_IRQHandler(void) {
+    IRQ_ENTER(DMA1_Channel7_IRQn);
+    if (dma_handle[dma_id_6] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_6]);
+    }
+    IRQ_EXIT(DMA1_Channel7_IRQn);
+}
+void DMA2_Channel1_IRQHandler(void) {
+    IRQ_ENTER(DMA2_Channel1_IRQn);
+    if (dma_handle[dma_id_7] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_7]);
+    }
+    IRQ_EXIT(DMA2_Channel1_IRQn);
+}
+void DMA2_Channel2_IRQHandler(void) {
+    IRQ_ENTER(DMA2_Channel2_IRQn);
+    if (dma_handle[dma_id_8] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_8]);
+    }
+    IRQ_EXIT(DMA2_Channel2_IRQn);
+}
+void DMA2_Channel3_IRQHandler(void) {
+    IRQ_ENTER(DMA2_Channel3_IRQn);
+    if (dma_handle[dma_id_9] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_9]);
+    }
+    IRQ_EXIT(DMA2_Channel3_IRQn);
+}
+void DMA2_Channel4_IRQHandler(void) {
+    IRQ_ENTER(DMA2_Channel4_IRQn);
+    if (dma_handle[dma_id_10] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_10]);
+    }
+    IRQ_EXIT(DMA2_Channel4_IRQn);
+}
+void DMA2_Channel5_IRQHandler(void) {
+    IRQ_ENTER(DMA2_Channel5_IRQn);
+    if (dma_handle[dma_id_11] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_11]);
+    }
+    IRQ_EXIT(DMA2_Channel5_IRQn);
+}
+void DMA2_Channel6_IRQHandler(void) {
+    IRQ_ENTER(DMA2_Channel6_IRQn);
+    if (dma_handle[dma_id_12] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_12]);
+    }
+    IRQ_EXIT(DMA2_Channel6_IRQn);
+}
+void DMA2_Channel7_IRQHandler(void) {
+    IRQ_ENTER(DMA2_Channel7_IRQn);
+    if (dma_handle[dma_id_13] != NULL) {
+        HAL_DMA_IRQHandler(dma_handle[dma_id_13]);
+    }
+    IRQ_EXIT(DMA2_Channel7_IRQn);
+}
 
 #endif
 
@@ -709,14 +889,14 @@
     dma->Parent = data;
 }
 
-void dma_init(DMA_HandleTypeDef *dma, const dma_descr_t *dma_descr, uint32_t dir, void *data){
+void dma_init(DMA_HandleTypeDef *dma, const dma_descr_t *dma_descr, uint32_t dir, void *data) {
     // Some drivers allocate the DMA_HandleTypeDef from the stack
     // (i.e. dac, i2c, spi) and for those cases we need to clear the
     // structure so we don't get random values from the stack)
     memset(dma, 0, sizeof(*dma));
 
     if (dma_descr != NULL) {
-        dma_id_t dma_id  = dma_descr->id;
+        dma_id_t dma_id = dma_descr->id;
 
         dma_init_handle(dma, dma_descr, dir, data);
         // set global pointer for IRQ handler
@@ -802,7 +982,7 @@
         return;
     }
 
-    static const uint32_t   controller_mask[] = {
+    static const uint32_t controller_mask[] = {
         DMA1_ENABLE_MASK,
         #if defined(DMA2)
         DMA2_ENABLE_MASK,
@@ -849,7 +1029,7 @@
         | descr->init->MemInc       // MINC
         | descr->init->PeriphInc    // PINC
         | config                    // MSIZE | PSIZE | CIRC | DIR
-        ;
+    ;
 
     // Select channel that the DMA stream uses
     #if defined(STM32F0)
@@ -859,7 +1039,7 @@
         __HAL_DMA2_REMAP(descr->sub_instance);
     }
     #else
-    DMA_Request_TypeDef *dma_ctrl = (void*)(((uint32_t)dma & ~0xff) + (DMA1_CSELR_BASE - DMA1_BASE)); // DMA1_CSELR or DMA2_CSELR
+    DMA_Request_TypeDef *dma_ctrl = (void *)(((uint32_t)dma & ~0xff) + (DMA1_CSELR_BASE - DMA1_BASE)); // DMA1_CSELR or DMA2_CSELR
     uint32_t channel_number = (((uint32_t)dma & 0xff) - 0x08) / 20; // 0 through 6
     uint32_t channel_pos = channel_number * 4;
     dma_ctrl->CSELR = (dma_ctrl->CSELR & ~(0xf << channel_pos)) | (descr->sub_instance << channel_pos);
@@ -900,13 +1080,13 @@
         | init->MemInc              // MINC
         | init->PeriphInc           // PINC
         | config                    // MSIZE | PSIZE | CIRC | DIR
-        ;
+    ;
 
     // Set FIFO control register
     dma->FCR =
         init->FIFOMode              // DMDIS
         | init->FIFOThreshold       // FTH
-        ;
+    ;
 }
 
 void dma_nohal_deinit(const dma_descr_t *descr) {
diff --git a/ports/stm32/eth.c b/ports/stm32/eth.c
index 756bb6d..33d2070 100644
--- a/ports/stm32/eth.c
+++ b/ports/stm32/eth.c
@@ -256,15 +256,15 @@
     ETH->DMAIER =
         ETH_DMAIER_NISE // enable normal interrupts
         | ETH_DMAIER_RIE // enable RX interrupt
-        ;
+    ;
 
     // Configure RX descriptor lists
     for (size_t i = 0; i < RX_BUF_NUM; ++i) {
         eth_dma.rx_descr[i].rdes0 = 1 << RX_DESCR_0_OWN_Pos;
         eth_dma.rx_descr[i].rdes1 =
             1 << RX_DESCR_1_RCH_Pos // chained
-            | RX_BUF_SIZE << RX_DESCR_1_RBS1_Pos
-            ;
+                | RX_BUF_SIZE << RX_DESCR_1_RBS1_Pos
+        ;
         eth_dma.rx_descr[i].rdes2 = (uint32_t)&eth_dma.rx_buf[i * RX_BUF_SIZE];
         eth_dma.rx_descr[i].rdes3 = (uint32_t)&eth_dma.rx_descr[(i + 1) % RX_BUF_NUM];
     }
@@ -285,13 +285,13 @@
     ETH->DMAOMR =
         ETH_DMAOMR_RSF // read from RX FIFO after a full frame is written
         | ETH_DMAOMR_TSF // transmit when a full frame is in TX FIFO (needed by errata)
-        ;
+    ;
     mp_hal_delay_ms(2);
 
     // Select MAC filtering options
     ETH->MACFFR =
         ETH_MACFFR_RA // pass all frames up
-        ;
+    ;
     mp_hal_delay_ms(2);
 
     // Set MAC address
@@ -307,21 +307,21 @@
         : (phy_scsr & PHY_SCSR_SPEED_Msk) == PHY_SCSR_SPEED_100HALF ? ETH_MACCR_FES
         : (phy_scsr & PHY_SCSR_SPEED_Msk) == PHY_SCSR_SPEED_100FULL ? (ETH_MACCR_FES | ETH_MACCR_DM)
         : 0
-        ;
+    ;
     mp_hal_delay_ms(2);
 
     // Start MAC layer
     ETH->MACCR |=
         ETH_MACCR_TE // enable TX
         | ETH_MACCR_RE // enable RX
-        ;
+    ;
     mp_hal_delay_ms(2);
 
     // Start DMA layer
     ETH->DMAOMR |=
         ETH_DMAOMR_ST // start TX
         | ETH_DMAOMR_SR // start RX
-        ;
+    ;
     mp_hal_delay_ms(2);
 
     // Enable interrupts
@@ -373,11 +373,11 @@
     // Schedule to send next outgoing frame
     tx_descr->tdes0 =
         1 << TX_DESCR_0_OWN_Pos     // owned by DMA
-        | 1 << TX_DESCR_0_LS_Pos    // last segment
-        | 1 << TX_DESCR_0_FS_Pos    // first segment
-        | 3 << TX_DESCR_0_CIC_Pos   // enable all checksums inserted by hardware
-        | 1 << TX_DESCR_0_TCH_Pos   // TX descriptor is chained
-        ;
+            | 1 << TX_DESCR_0_LS_Pos // last segment
+            | 1 << TX_DESCR_0_FS_Pos // first segment
+            | 3 << TX_DESCR_0_CIC_Pos // enable all checksums inserted by hardware
+            | 1 << TX_DESCR_0_TCH_Pos // TX descriptor is chained
+    ;
 
     // Notify ETH DMA that there is a new TX descriptor for sending
     __DMB();
@@ -398,8 +398,8 @@
     // Schedule to get next incoming frame
     rx_descr->rdes1 =
         1 << RX_DESCR_1_RCH_Pos                 // RX descriptor is chained
-        | RX_BUF_SIZE << RX_DESCR_1_RBS1_Pos    // maximum buffer length
-        ;
+            | RX_BUF_SIZE << RX_DESCR_1_RBS1_Pos // maximum buffer length
+    ;
     rx_descr->rdes2 = (uint32_t)buf;
     rx_descr->rdes3 = (uint32_t)&eth_dma.rx_descr[eth_dma.rx_descr_idx];
     rx_descr->rdes0 = 1 << RX_DESCR_0_OWN_Pos;  // owned by DMA
@@ -424,7 +424,7 @@
             // Get RX buffer containing new frame
             size_t len = (rx_descr->rdes0 & RX_DESCR_0_FL_Msk) >> RX_DESCR_0_FL_Pos;
             len -= 4; // discard CRC at end
-            uint8_t *buf = (uint8_t*)rx_descr->rdes2;
+            uint8_t *buf = (uint8_t *)rx_descr->rdes2;
 
             // Process frame
             eth_process_frame(&eth_instance, len, buf);
diff --git a/ports/stm32/extint.c b/ports/stm32/extint.c
index c4841f3..6c186f5 100644
--- a/ports/stm32/extint.c
+++ b/ports/stm32/extint.c
@@ -433,13 +433,13 @@
         return;
     }
     // we need 0 to 1 transition to trigger the interrupt
-#if defined(STM32L4) || defined(STM32H7) || defined(STM32WB)
+    #if defined(STM32L4) || defined(STM32H7) || defined(STM32WB)
     EXTI->SWIER1 &= ~(1 << line);
     EXTI->SWIER1 |= (1 << line);
-#else
+    #else
     EXTI->SWIER &= ~(1 << line);
     EXTI->SWIER |= (1 << line);
-#endif
+    #endif
 }
 
 void extint_trigger_mode(uint line, uint32_t mode) {
@@ -624,7 +624,7 @@
     .name = MP_QSTR_ExtInt,
     .print = extint_obj_print,
     .make_new = extint_make_new,
-    .locals_dict = (mp_obj_dict_t*)&extint_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&extint_locals_dict,
 };
 
 void extint_init0(void) {
@@ -634,7 +634,7 @@
         }
         MP_STATE_PORT(pyb_extint_callback)[i] = mp_const_none;
         pyb_extint_mode[i] = EXTI_Mode_Interrupt;
-   }
+    }
 }
 
 // Interrupt handler
diff --git a/ports/stm32/factoryreset.c b/ports/stm32/factoryreset.c
index 513b521..0459110 100644
--- a/ports/stm32/factoryreset.c
+++ b/ports/stm32/factoryreset.c
@@ -35,21 +35,21 @@
 #if MICROPY_HW_ENABLE_STORAGE
 
 static const char fresh_boot_py[] =
-"# boot.py -- run on boot-up\r\n"
-"# can run arbitrary Python, but best to keep it minimal\r\n"
-"\r\n"
-"import machine\r\n"
-"import pyb\r\n"
-"pyb.country('US') # ISO 3166-1 Alpha-2 code, eg US, GB, DE, AU\r\n"
-"#pyb.main('main.py') # main script to run after this one\r\n"
+    "# boot.py -- run on boot-up\r\n"
+    "# can run arbitrary Python, but best to keep it minimal\r\n"
+    "\r\n"
+    "import machine\r\n"
+    "import pyb\r\n"
+    "pyb.country('US') # ISO 3166-1 Alpha-2 code, eg US, GB, DE, AU\r\n"
+    "#pyb.main('main.py') # main script to run after this one\r\n"
 #if MICROPY_HW_ENABLE_USB
-"#pyb.usb_mode('VCP+MSC') # act as a serial and a storage device\r\n"
-"#pyb.usb_mode('VCP+HID') # act as a serial device and a mouse\r\n"
+    "#pyb.usb_mode('VCP+MSC') # act as a serial and a storage device\r\n"
+    "#pyb.usb_mode('VCP+HID') # act as a serial device and a mouse\r\n"
 #endif
 ;
 
 static const char fresh_main_py[] =
-"# main.py -- put your code here!\r\n"
+    "# main.py -- put your code here!\r\n"
 ;
 
 #if MICROPY_HW_ENABLE_USB
@@ -58,18 +58,18 @@
 ;
 
 static const char fresh_readme_txt[] =
-"This is a MicroPython board\r\n"
-"\r\n"
-"You can get started right away by writing your Python code in 'main.py'.\r\n"
-"\r\n"
-"For a serial prompt:\r\n"
-" - Windows: you need to go to 'Device manager', right click on the unknown device,\r\n"
-"   then update the driver software, using the 'pybcdc.inf' file found on this drive.\r\n"
-"   Then use a terminal program like Hyperterminal or putty.\r\n"
-" - Mac OS X: use the command: screen /dev/tty.usbmodem*\r\n"
-" - Linux: use the command: screen /dev/ttyACM0\r\n"
-"\r\n"
-"Please visit http://micropython.org/help/ for further help.\r\n"
+    "This is a MicroPython board\r\n"
+    "\r\n"
+    "You can get started right away by writing your Python code in 'main.py'.\r\n"
+    "\r\n"
+    "For a serial prompt:\r\n"
+    " - Windows: you need to go to 'Device manager', right click on the unknown device,\r\n"
+    "   then update the driver software, using the 'pybcdc.inf' file found on this drive.\r\n"
+    "   Then use a terminal program like Hyperterminal or putty.\r\n"
+    " - Mac OS X: use the command: screen /dev/tty.usbmodem*\r\n"
+    " - Linux: use the command: screen /dev/ttyACM0\r\n"
+    "\r\n"
+    "Please visit http://micropython.org/help/ for further help.\r\n"
 ;
 #endif
 
diff --git a/ports/stm32/fdcan.c b/ports/stm32/fdcan.c
index 611ebe1..b3b1da9 100644
--- a/ports/stm32/fdcan.c
+++ b/ports/stm32/fdcan.c
@@ -65,13 +65,13 @@
     if (can_obj->can_id == PYB_CAN_1) {
         init->MessageRAMOffset = 0;
     } else {
-        init->MessageRAMOffset = 2560/2;
+        init->MessageRAMOffset = 2560 / 2;
     }
 
     init->StdFiltersNbr = 64; // 128 / 2
     init->ExtFiltersNbr = 0; // Not used
 
-    init->TxEventsNbr  = 16; // 32 / 2
+    init->TxEventsNbr = 16;  // 32 / 2
     init->RxBuffersNbr = 32; // 64 / 2
     init->TxBuffersNbr = 16; // 32 / 2
 
@@ -219,14 +219,14 @@
 
     // Get pointer to incoming message
     uint32_t index = (can->Instance->RXF0S & FDCAN_RXF0S_F0GI) >> 8;
-    uint32_t *address = (uint32_t*)(can->msgRam.RxFIFO0SA + (index * can->Init.RxFifo0ElmtSize * 4));
+    uint32_t *address = (uint32_t *)(can->msgRam.RxFIFO0SA + (index * can->Init.RxFifo0ElmtSize * 4));
 
     // Parse header of message
     hdr->IdType = *address & FDCAN_ELEMENT_MASK_XTD;
-    if(hdr->IdType == FDCAN_STANDARD_ID) {
-      hdr->Identifier = (*address & FDCAN_ELEMENT_MASK_STDID) >> 18;
+    if (hdr->IdType == FDCAN_STANDARD_ID) {
+        hdr->Identifier = (*address & FDCAN_ELEMENT_MASK_STDID) >> 18;
     } else {
-      hdr->Identifier = *address & FDCAN_ELEMENT_MASK_EXTID;
+        hdr->Identifier = *address & FDCAN_ELEMENT_MASK_EXTID;
     }
     hdr->RxFrameType = *address & FDCAN_ELEMENT_MASK_RTR;
     hdr->ErrorStateIndicator = *address++ & FDCAN_ELEMENT_MASK_ESI;
@@ -238,9 +238,9 @@
     hdr->IsFilterMatchingFrame = (*address++ & FDCAN_ELEMENT_MASK_ANMF) >> 31;
 
     // Copy data
-    uint8_t *pdata = (uint8_t*)address;
-    for(uint32_t i = 0; i < 8; ++i) { // TODO use DLCtoBytes[hdr->DataLength] for length > 8
-      *data++ = *pdata++;
+    uint8_t *pdata = (uint8_t *)address;
+    for (uint32_t i = 0; i < 8; ++i) { // TODO use DLCtoBytes[hdr->DataLength] for length > 8
+        *data++ = *pdata++;
     }
 
     // Release (free) message from FIFO
@@ -268,7 +268,7 @@
     switch (*state) {
         case RX_STATE_FIFO_EMPTY:
             __HAL_FDCAN_DISABLE_IT(&self->can,  (fifo_id == FDCAN_RX_FIFO0) ?
-                    FDCAN_IT_RX_FIFO0_NEW_MESSAGE : FDCAN_IT_RX_FIFO1_NEW_MESSAGE);
+                FDCAN_IT_RX_FIFO0_NEW_MESSAGE : FDCAN_IT_RX_FIFO1_NEW_MESSAGE);
             irq_reason = MP_OBJ_NEW_SMALL_INT(0);
             *state = RX_STATE_MESSAGE_PENDING;
             break;
@@ -280,9 +280,9 @@
             break;
         case RX_STATE_FIFO_FULL:
             __HAL_FDCAN_DISABLE_IT(&self->can, (fifo_id == FDCAN_RX_FIFO0) ?
-                    FDCAN_IT_RX_FIFO0_MESSAGE_LOST : FDCAN_IT_RX_FIFO1_MESSAGE_LOST);
+                FDCAN_IT_RX_FIFO0_MESSAGE_LOST : FDCAN_IT_RX_FIFO1_MESSAGE_LOST);
             __HAL_FDCAN_CLEAR_FLAG(&self->can, (fifo_id == FDCAN_RX_FIFO0) ?
-                    FDCAN_FLAG_RX_FIFO0_MESSAGE_LOST : FDCAN_FLAG_RX_FIFO1_MESSAGE_LOST);
+                FDCAN_FLAG_RX_FIFO0_MESSAGE_LOST : FDCAN_FLAG_RX_FIFO1_MESSAGE_LOST);
             irq_reason = MP_OBJ_NEW_SMALL_INT(2);
             *state = RX_STATE_FIFO_OVERFLOW;
             break;
diff --git a/ports/stm32/flash.c b/ports/stm32/flash.c
index 49cbbe0..99c95f7 100644
--- a/ports/stm32/flash.c
+++ b/ports/stm32/flash.c
@@ -100,7 +100,7 @@
     if (READ_BIT(FLASH->OPTCR, FLASH_OPTCR_SWAP_BANK) == 0) {
     #else
     if (READ_BIT(SYSCFG->MEMRMP, SYSCFG_MEMRMP_FB_MODE) == 0) {
-    #endif
+        #endif
         // no bank swap
         if (addr < (FLASH_BASE + FLASH_BANK_SIZE)) {
             return FLASH_BANK_1;
@@ -175,36 +175,37 @@
 
     #if defined(STM32F0)
     __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR);
-    EraseInitStruct.TypeErase   = FLASH_TYPEERASE_PAGES;
+    EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
     EraseInitStruct.PageAddress = flash_dest;
-    EraseInitStruct.NbPages     = (4 * num_word32 + FLASH_PAGE_SIZE - 4) / FLASH_PAGE_SIZE;
+    EraseInitStruct.NbPages = (4 * num_word32 + FLASH_PAGE_SIZE - 4) / FLASH_PAGE_SIZE;
     #elif defined(STM32L0)
     __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR);
-    EraseInitStruct.TypeErase   = FLASH_TYPEERASE_PAGES;
+    EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
     EraseInitStruct.PageAddress = flash_dest;
-    EraseInitStruct.NbPages     = (4 * num_word32 + FLASH_PAGE_SIZE - 4) / FLASH_PAGE_SIZE;
+    EraseInitStruct.NbPages = (4 * num_word32 + FLASH_PAGE_SIZE - 4) / FLASH_PAGE_SIZE;
     #elif (defined(STM32L4) && !defined(SYSCFG_MEMRMP_FB_MODE)) || defined(STM32WB)
     __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_ALL_ERRORS);
-    EraseInitStruct.TypeErase   = FLASH_TYPEERASE_PAGES;
-    EraseInitStruct.Page        = get_page(flash_dest);
-    EraseInitStruct.NbPages     = (4 * num_word32 + FLASH_PAGE_SIZE - 4) / FLASH_PAGE_SIZE;
+    EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
+    EraseInitStruct.Page = get_page(flash_dest);
+    EraseInitStruct.NbPages = (4 * num_word32 + FLASH_PAGE_SIZE - 4) / FLASH_PAGE_SIZE;
     #elif defined(STM32L4)
     __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_ALL_ERRORS);
 
     // erase the sector(s)
     // The sector returned by flash_get_sector_info can not be used
     // as the flash has on each bank 0/1 pages 0..255
-    EraseInitStruct.TypeErase   = FLASH_TYPEERASE_PAGES;
-    EraseInitStruct.Banks       = get_bank(flash_dest);
-    EraseInitStruct.Page        = get_page(flash_dest);
-    EraseInitStruct.NbPages     = get_page(flash_dest + 4 * num_word32 - 1) - EraseInitStruct.Page + 1;;
+    EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
+    EraseInitStruct.Banks = get_bank(flash_dest);
+    EraseInitStruct.Page = get_page(flash_dest);
+    EraseInitStruct.NbPages = get_page(flash_dest + 4 * num_word32 - 1) - EraseInitStruct.Page + 1;
+    ;
     #else
     // Clear pending flags (if any)
     #if defined(STM32H7)
     __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_ALL_ERRORS_BANK1 | FLASH_FLAG_ALL_ERRORS_BANK2);
     #else
     __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |
-                           FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR);
+        FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR);
     #endif
 
     // erase the sector(s)
@@ -259,7 +260,7 @@
 
     // program the flash uint64 by uint64
     for (int i = 0; i < num_word32 / 2; i++) {
-        uint64_t val = *(uint64_t*)src;
+        uint64_t val = *(uint64_t *)src;
         if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, flash_dest, val) != HAL_OK) {
             // error occurred during flash write
             HAL_FLASH_Lock(); // lock the flash
@@ -269,7 +270,7 @@
         src += 2;
     }
     if ((num_word32 & 0x01) == 1) {
-        uint64_t val = *(uint64_t*)flash_dest;
+        uint64_t val = *(uint64_t *)flash_dest;
         val = (val & 0xffffffff00000000uL) | (*src);
         if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, flash_dest, val) != HAL_OK) {
             // error occurred during flash write
diff --git a/ports/stm32/flashbdev.c b/ports/stm32/flashbdev.c
index beb28c4..bc3f6b0 100644
--- a/ports/stm32/flashbdev.c
+++ b/ports/stm32/flashbdev.c
@@ -111,9 +111,9 @@
 #define FLASH_MEM_SEG1_NUM_BLOCKS (256) // Sector 1: 128k / 512b = 256 blocks
 
 #elif defined(STM32L432xx) || \
-      defined(STM32L451xx) || defined(STM32L452xx) || defined(STM32L462xx) || \
-      defined(STM32L475xx) || defined(STM32L476xx) || defined(STM32L496xx) || \
-      defined(STM32WB)
+    defined(STM32L451xx) || defined(STM32L452xx) || defined(STM32L462xx) || \
+    defined(STM32L475xx) || defined(STM32L476xx) || defined(STM32L496xx) || \
+    defined(STM32WB)
 
 // The STM32L4xx doesn't have CCRAM, so we use SRAM2 for this, although
 // actual location and size is defined by the linker script.
@@ -187,7 +187,7 @@
     }
     if (flash_cache_sector_id != flash_sector_id) {
         flash_bdev_ioctl(BDEV_IOCTL_SYNC, 0);
-        memcpy((void*)CACHE_MEM_START_ADDR, (const void*)flash_sector_start, flash_sector_size);
+        memcpy((void *)CACHE_MEM_START_ADDR, (const void *)flash_sector_start, flash_sector_size);
         flash_cache_sector_id = flash_sector_id;
         flash_cache_sector_start = flash_sector_start;
         flash_cache_sector_size = flash_sector_size;
@@ -195,7 +195,7 @@
     flash_flags |= FLASH_FLAG_DIRTY;
     led_state(PYB_LED_RED, 1); // indicate a dirty cache with LED on
     flash_tick_counter_last_write = HAL_GetTick();
-    return (uint8_t*)CACHE_MEM_START_ADDR + flash_addr - flash_sector_start;
+    return (uint8_t *)CACHE_MEM_START_ADDR + flash_addr - flash_sector_start;
 }
 
 static uint8_t *flash_cache_get_addr_for_read(uint32_t flash_addr) {
@@ -204,10 +204,10 @@
     uint32_t flash_sector_id = flash_get_sector_info(flash_addr, &flash_sector_start, &flash_sector_size);
     if (flash_cache_sector_id == flash_sector_id) {
         // in cache, copy from there
-        return (uint8_t*)CACHE_MEM_START_ADDR + flash_addr - flash_sector_start;
+        return (uint8_t *)CACHE_MEM_START_ADDR + flash_addr - flash_sector_start;
     }
     // not in cache, copy straight from flash
-    return (uint8_t*)flash_addr;
+    return (uint8_t *)flash_addr;
 }
 
 static uint32_t convert_block_to_flash_addr(uint32_t block) {
@@ -258,7 +258,7 @@
     // On file close and flash unmount we get a forced write, so we can afford to wait a while
     if ((flash_flags & FLASH_FLAG_FORCE_WRITE) || HAL_GetTick() - flash_tick_counter_last_write >= 5000) {
         // sync the cache RAM buffer by writing it to the flash page
-        flash_write(flash_cache_sector_start, (const uint32_t*)CACHE_MEM_START_ADDR, flash_cache_sector_size / 4);
+        flash_write(flash_cache_sector_start, (const uint32_t *)CACHE_MEM_START_ADDR, flash_cache_sector_size / 4);
         // clear the flash flags now that we have a clean cache
         flash_flags = 0;
         // indicate a clean cache with LED off
diff --git a/ports/stm32/font_petme128_8x8.h b/ports/stm32/font_petme128_8x8.h
index cdc4e73..9963698 100644
--- a/ports/stm32/font_petme128_8x8.h
+++ b/ports/stm32/font_petme128_8x8.h
@@ -27,7 +27,7 @@
 #define MICROPY_INCLUDED_STM32_FONT_PETME128_8X8_H
 
 static const uint8_t font_petme128_8x8[] = {
-    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // 32= 
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // 32=
     0x00,0x00,0x00,0x4f,0x4f,0x00,0x00,0x00, // 33=!
     0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00, // 34="
     0x14,0x7f,0x7f,0x14,0x14,0x7f,0x7f,0x14, // 35=#
diff --git a/ports/stm32/gccollect.c b/ports/stm32/gccollect.c
index f5a49b7..cd7b22c 100644
--- a/ports/stm32/gccollect.c
+++ b/ports/stm32/gccollect.c
@@ -48,7 +48,7 @@
     uintptr_t sp = gc_helper_get_regs_and_sp(regs);
 
     // trace the stack, including the registers (since they live on the stack in this function)
-    gc_collect_root((void**)sp, ((uint32_t)MP_STATE_THREAD(stack_top) - sp) / sizeof(uint32_t));
+    gc_collect_root((void **)sp, ((uint32_t)MP_STATE_THREAD(stack_top) - sp) / sizeof(uint32_t));
 
     // trace root pointers from any threads
     #if MICROPY_PY_THREAD
diff --git a/ports/stm32/help.c b/ports/stm32/help.c
index f9d97b7..fba0a69 100644
--- a/ports/stm32/help.c
+++ b/ports/stm32/help.c
@@ -27,45 +27,45 @@
 #include "py/builtin.h"
 
 const char stm32_help_text[] =
-"Welcome to MicroPython!\n"
-"\n"
-"For online help please visit http://micropython.org/help/.\n"
-"\n"
-"Quick overview of commands for the board:\n"
-"  pyb.info()    -- print some general information\n"
-"  pyb.delay(n)  -- wait for n milliseconds\n"
-"  pyb.millis()  -- get number of milliseconds since hard reset\n"
-"  pyb.Switch()  -- create a switch object\n"
-"                   Switch methods: (), callback(f)\n"
-"  pyb.LED(n)    -- create an LED object for LED n (n=1,2,3,4)\n"
-"                   LED methods: on(), off(), toggle(), intensity(<n>)\n"
-"  pyb.Pin(pin)  -- get a pin, eg pyb.Pin('X1')\n"
-"  pyb.Pin(pin, m, [p]) -- get a pin and configure it for IO mode m, pull mode p\n"
-"                   Pin methods: init(..), value([v]), high(), low()\n"
-"  pyb.ExtInt(pin, m, p, callback) -- create an external interrupt object\n"
-"  pyb.ADC(pin)  -- make an analog object from a pin\n"
-"                   ADC methods: read(), read_timed(buf, freq)\n"
-"  pyb.DAC(port) -- make a DAC object\n"
-"                   DAC methods: triangle(freq), write(n), write_timed(buf, freq)\n"
-"  pyb.RTC()     -- make an RTC object; methods: datetime([val])\n"
-"  pyb.rng()     -- get a 30-bit hardware random number\n"
-"  pyb.Servo(n)  -- create Servo object for servo n (n=1,2,3,4)\n"
-"                   Servo methods: calibration(..), angle([x, [t]]), speed([x, [t]])\n"
-"  pyb.Accel()   -- create an Accelerometer object\n"
-"                   Accelerometer methods: x(), y(), z(), tilt(), filtered_xyz()\n"
-"\n"
-"Pins are numbered X1-X12, X17-X22, Y1-Y12, or by their MCU name\n"
-"Pin IO modes are: pyb.Pin.IN, pyb.Pin.OUT_PP, pyb.Pin.OUT_OD\n"
-"Pin pull modes are: pyb.Pin.PULL_NONE, pyb.Pin.PULL_UP, pyb.Pin.PULL_DOWN\n"
-"Additional serial bus objects: pyb.I2C(n), pyb.SPI(n), pyb.UART(n)\n"
-"\n"
-"Control commands:\n"
-"  CTRL-A        -- on a blank line, enter raw REPL mode\n"
-"  CTRL-B        -- on a blank line, enter normal REPL mode\n"
-"  CTRL-C        -- interrupt a running program\n"
-"  CTRL-D        -- on a blank line, do a soft reset of the board\n"
-"  CTRL-E        -- on a blank line, enter paste mode\n"
-"\n"
-"For further help on a specific object, type help(obj)\n"
-"For a list of available modules, type help('modules')\n"
+    "Welcome to MicroPython!\n"
+    "\n"
+    "For online help please visit http://micropython.org/help/.\n"
+    "\n"
+    "Quick overview of commands for the board:\n"
+    "  pyb.info()    -- print some general information\n"
+    "  pyb.delay(n)  -- wait for n milliseconds\n"
+    "  pyb.millis()  -- get number of milliseconds since hard reset\n"
+    "  pyb.Switch()  -- create a switch object\n"
+    "                   Switch methods: (), callback(f)\n"
+    "  pyb.LED(n)    -- create an LED object for LED n (n=1,2,3,4)\n"
+    "                   LED methods: on(), off(), toggle(), intensity(<n>)\n"
+    "  pyb.Pin(pin)  -- get a pin, eg pyb.Pin('X1')\n"
+    "  pyb.Pin(pin, m, [p]) -- get a pin and configure it for IO mode m, pull mode p\n"
+    "                   Pin methods: init(..), value([v]), high(), low()\n"
+    "  pyb.ExtInt(pin, m, p, callback) -- create an external interrupt object\n"
+    "  pyb.ADC(pin)  -- make an analog object from a pin\n"
+    "                   ADC methods: read(), read_timed(buf, freq)\n"
+    "  pyb.DAC(port) -- make a DAC object\n"
+    "                   DAC methods: triangle(freq), write(n), write_timed(buf, freq)\n"
+    "  pyb.RTC()     -- make an RTC object; methods: datetime([val])\n"
+    "  pyb.rng()     -- get a 30-bit hardware random number\n"
+    "  pyb.Servo(n)  -- create Servo object for servo n (n=1,2,3,4)\n"
+    "                   Servo methods: calibration(..), angle([x, [t]]), speed([x, [t]])\n"
+    "  pyb.Accel()   -- create an Accelerometer object\n"
+    "                   Accelerometer methods: x(), y(), z(), tilt(), filtered_xyz()\n"
+    "\n"
+    "Pins are numbered X1-X12, X17-X22, Y1-Y12, or by their MCU name\n"
+    "Pin IO modes are: pyb.Pin.IN, pyb.Pin.OUT_PP, pyb.Pin.OUT_OD\n"
+    "Pin pull modes are: pyb.Pin.PULL_NONE, pyb.Pin.PULL_UP, pyb.Pin.PULL_DOWN\n"
+    "Additional serial bus objects: pyb.I2C(n), pyb.SPI(n), pyb.UART(n)\n"
+    "\n"
+    "Control commands:\n"
+    "  CTRL-A        -- on a blank line, enter raw REPL mode\n"
+    "  CTRL-B        -- on a blank line, enter normal REPL mode\n"
+    "  CTRL-C        -- interrupt a running program\n"
+    "  CTRL-D        -- on a blank line, do a soft reset of the board\n"
+    "  CTRL-E        -- on a blank line, enter paste mode\n"
+    "\n"
+    "For further help on a specific object, type help(obj)\n"
+    "For a list of available modules, type help('modules')\n"
 ;
diff --git a/ports/stm32/lcd.c b/ports/stm32/lcd.c
index 6dfda62..85bcc28 100644
--- a/ports/stm32/lcd.c
+++ b/ports/stm32/lcd.c
@@ -236,14 +236,23 @@
         spi_clock = HAL_RCC_GetPCLK1Freq();
     }
     uint br_prescale = spi_clock / 16000000; // datasheet says LCD can run at 20MHz, but we go for 16MHz
-    if (br_prescale <= 2) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2; }
-    else if (br_prescale <= 4) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4; }
-    else if (br_prescale <= 8) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8; }
-    else if (br_prescale <= 16) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16; }
-    else if (br_prescale <= 32) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32; }
-    else if (br_prescale <= 64) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64; }
-    else if (br_prescale <= 128) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128; }
-    else { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256; }
+    if (br_prescale <= 2) {
+        init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
+    } else if (br_prescale <= 4) {
+        init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4;
+    } else if (br_prescale <= 8) {
+        init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
+    } else if (br_prescale <= 16) {
+        init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16;
+    } else if (br_prescale <= 32) {
+        init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32;
+    } else if (br_prescale <= 64) {
+        init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64;
+    } else if (br_prescale <= 128) {
+        init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128;
+    } else {
+        init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256;
+    }
 
     // data is sent bigendian, latches on rising clock
     init->CLKPolarity = SPI_POLARITY_HIGH;
@@ -328,7 +337,7 @@
 
     // send the data
     for (uint i = 0; i < bufinfo.len; i++) {
-        lcd_out(self, instr_data, ((byte*)bufinfo.buf)[i]);
+        lcd_out(self, instr_data, ((byte *)bufinfo.buf)[i]);
     }
 
     return mp_const_none;
@@ -452,7 +461,7 @@
     // loop over chars
     for (const char *top = data + len; data < top; data++) {
         // get char and make sure its in range of font
-        uint chr = *(byte*)data;
+        uint chr = *(byte *)data;
         if (chr < 32 || chr > 127) {
             chr = 127;
         }
@@ -521,7 +530,7 @@
     { &mp_type_type },
     .name = MP_QSTR_LCD,
     .make_new = pyb_lcd_make_new,
-    .locals_dict = (mp_obj_dict_t*)&pyb_lcd_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_lcd_locals_dict,
 };
 
 #endif // MICROPY_HW_HAS_LCD
diff --git a/ports/stm32/led.c b/ports/stm32/led.c
index e05849c..d04557f 100644
--- a/ports/stm32/led.c
+++ b/ports/stm32/led.c
@@ -52,15 +52,15 @@
 
 STATIC const pyb_led_obj_t pyb_led_obj[] = {
     {{&pyb_led_type}, 1, MICROPY_HW_LED1},
-#if defined(MICROPY_HW_LED2)
+    #if defined(MICROPY_HW_LED2)
     {{&pyb_led_type}, 2, MICROPY_HW_LED2},
-#if defined(MICROPY_HW_LED3)
+    #if defined(MICROPY_HW_LED3)
     {{&pyb_led_type}, 3, MICROPY_HW_LED3},
-#if defined(MICROPY_HW_LED4)
+    #if defined(MICROPY_HW_LED4)
     {{&pyb_led_type}, 4, MICROPY_HW_LED4},
-#endif
-#endif
-#endif
+    #endif
+    #endif
+    #endif
 };
 #define NUM_LEDS MP_ARRAY_SIZE(pyb_led_obj)
 
@@ -102,7 +102,7 @@
 #define LED_PWM_TIM_PERIOD (10000) // TIM runs at 1MHz and fires every 10ms
 
 // this gives the address of the CCR register for channels 1-4
-#define LED_PWM_CCR(pwm_cfg) ((volatile uint32_t*)&(pwm_cfg)->tim->CCR1 + ((pwm_cfg)->tim_channel >> 2))
+#define LED_PWM_CCR(pwm_cfg) ((volatile uint32_t *)&(pwm_cfg)->tim->CCR1 + ((pwm_cfg)->tim_channel >> 2))
 
 typedef struct _led_pwm_config_t {
     TIM_TypeDef *tim;
@@ -135,10 +135,17 @@
 
     // TIM configuration
     switch (pwm_cfg->tim_id) {
-        case 1: __TIM1_CLK_ENABLE(); break;
-        case 2: __TIM2_CLK_ENABLE(); break;
-        case 3: __TIM3_CLK_ENABLE(); break;
-        default: assert(0);
+        case 1:
+            __TIM1_CLK_ENABLE();
+            break;
+        case 2:
+            __TIM2_CLK_ENABLE();
+            break;
+        case 3:
+            __TIM3_CLK_ENABLE();
+            break;
+        default:
+            assert(0);
     }
     TIM_HandleTypeDef tim = {0};
     tim.Instance = pwm_cfg->tim;
@@ -361,7 +368,7 @@
     .name = MP_QSTR_LED,
     .print = led_obj_print,
     .make_new = led_obj_make_new,
-    .locals_dict = (mp_obj_dict_t*)&led_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&led_locals_dict,
 };
 
 #else
diff --git a/ports/stm32/machine_adc.c b/ports/stm32/machine_adc.c
index 9fe00bd..71ee537 100644
--- a/ports/stm32/machine_adc.c
+++ b/ports/stm32/machine_adc.c
@@ -446,5 +446,5 @@
     .name = MP_QSTR_ADC,
     .print = machine_adc_print,
     .make_new = machine_adc_make_new,
-    .locals_dict = (mp_obj_dict_t*)&machine_adc_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&machine_adc_locals_dict,
 };
diff --git a/ports/stm32/machine_i2c.c b/ports/stm32/machine_i2c.c
index 6e08666..1c703b1 100644
--- a/ports/stm32/machine_i2c.c
+++ b/ports/stm32/machine_i2c.c
@@ -242,7 +242,7 @@
     }
 
     // get static peripheral object
-    machine_hard_i2c_obj_t *self = (machine_hard_i2c_obj_t*)&machine_hard_i2c_obj[i2c_id - 1];
+    machine_hard_i2c_obj_t *self = (machine_hard_i2c_obj_t *)&machine_hard_i2c_obj[i2c_id - 1];
 
     // here we would check the scl/sda pins and configure them, but it's not implemented
     if (args[ARG_scl].u_obj != MP_OBJ_NULL || args[ARG_sda].u_obj != MP_OBJ_NULL) {
@@ -272,7 +272,7 @@
     .print = machine_hard_i2c_print,
     .make_new = machine_hard_i2c_make_new,
     .protocol = &machine_hard_i2c_p,
-    .locals_dict = (mp_obj_dict_t*)&mp_machine_soft_i2c_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&mp_machine_soft_i2c_locals_dict,
 };
 
 #endif // MICROPY_HW_ENABLE_HW_I2C
diff --git a/ports/stm32/machine_spi.c b/ports/stm32/machine_spi.c
index dedcafc..d012d70 100644
--- a/ports/stm32/machine_spi.c
+++ b/ports/stm32/machine_spi.c
@@ -95,7 +95,7 @@
 }
 
 STATIC void machine_hard_spi_init(mp_obj_base_t *self_in, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
-    machine_hard_spi_obj_t *self = (machine_hard_spi_obj_t*)self_in;
+    machine_hard_spi_obj_t *self = (machine_hard_spi_obj_t *)self_in;
 
     enum { ARG_baudrate, ARG_polarity, ARG_phase, ARG_bits, ARG_firstbit };
     static const mp_arg_t allowed_args[] = {
@@ -118,12 +118,12 @@
 }
 
 STATIC void machine_hard_spi_deinit(mp_obj_base_t *self_in) {
-    machine_hard_spi_obj_t *self = (machine_hard_spi_obj_t*)self_in;
+    machine_hard_spi_obj_t *self = (machine_hard_spi_obj_t *)self_in;
     spi_deinit(self->spi);
 }
 
 STATIC void machine_hard_spi_transfer(mp_obj_base_t *self_in, size_t len, const uint8_t *src, uint8_t *dest) {
-    machine_hard_spi_obj_t *self = (machine_hard_spi_obj_t*)self_in;
+    machine_hard_spi_obj_t *self = (machine_hard_spi_obj_t *)self_in;
     spi_transfer(self->spi, len, src, dest, SPI_TRANSFER_TIMEOUT(len));
 }
 
@@ -139,5 +139,5 @@
     .print = machine_hard_spi_print,
     .make_new = mp_machine_spi_make_new, // delegate to master constructor
     .protocol = &machine_hard_spi_p,
-    .locals_dict = (mp_obj_dict_t*)&mp_machine_spi_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&mp_machine_spi_locals_dict,
 };
diff --git a/ports/stm32/machine_timer.c b/ports/stm32/machine_timer.c
index 1e9be42..daaf51b 100644
--- a/ports/stm32/machine_timer.c
+++ b/ports/stm32/machine_timer.c
@@ -128,5 +128,5 @@
     .name = MP_QSTR_Timer,
     .print = machine_timer_print,
     .make_new = machine_timer_make_new,
-    .locals_dict = (mp_obj_dict_t*)&machine_timer_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&machine_timer_locals_dict,
 };
diff --git a/ports/stm32/machine_uart.c b/ports/stm32/machine_uart.c
index 96cab07..f9fa321 100644
--- a/ports/stm32/machine_uart.c
+++ b/ports/stm32/machine_uart.c
@@ -188,7 +188,7 @@
             if (cr3 & USART_CR3_RTSE) {
                 mp_print_str(print, "RTS");
                 if (cr3 & USART_CR3_CTSE) {
-                   mp_print_str(print, "|");
+                    mp_print_str(print, "|");
                 }
             }
             if (cr3 & USART_CR3_CTSE) {
@@ -235,7 +235,7 @@
         mp_arg_val_t baudrate, bits, parity, stop, flow, timeout, timeout_char, rxbuf, read_buf_len;
     } args;
     mp_arg_parse_all(n_args, pos_args, kw_args,
-        MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args);
+        MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args);
 
     // static UARTs are used for internal purposes and shouldn't be reconfigured
     if (self->is_static) {
@@ -272,8 +272,12 @@
     // stop bits
     uint32_t stop;
     switch (args.stop.u_int) {
-        case 1: stop = UART_STOPBITS_1; break;
-        default: stop = UART_STOPBITS_2; break;
+        case 1:
+            stop = UART_STOPBITS_1;
+            break;
+        default:
+            stop = UART_STOPBITS_2;
+            break;
     }
 
     // flow control
@@ -596,7 +600,7 @@
     for (;;) {
         int data = uart_rx_char(self);
         if (self->char_width == CHAR_WIDTH_9BIT) {
-            *(uint16_t*)buf = data;
+            *(uint16_t *)buf = data;
             buf += 2;
         } else {
             *buf++ = data;
@@ -669,5 +673,5 @@
     .getiter = mp_identity_getiter,
     .iternext = mp_stream_unbuffered_iter,
     .protocol = &uart_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&pyb_uart_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_uart_locals_dict,
 };
diff --git a/ports/stm32/main.c b/ports/stm32/main.c
index 45bacbc..e221df0 100644
--- a/ports/stm32/main.c
+++ b/ports/stm32/main.c
@@ -166,7 +166,7 @@
     mp_int_t ret = -MP_EIO;
     if (nlr_push(&nlr) == 0) {
         mp_obj_t args[] = { bdev, mount_point };
-        mp_vfs_mount(2, args, (mp_map_t*)&mp_const_empty_map);
+        mp_vfs_mount(2, args, (mp_map_t *)&mp_const_empty_map);
         mp_vfs_chdir(mount_point);
         ret = 0; // success
         nlr_pop();
@@ -203,7 +203,7 @@
     #if MICROPY_VFS_LFS1
     if (memcmp(&buf[40], "littlefs", 8) == 0) {
         // LFS1
-        lfs1_superblock_t *superblock = (void*)&buf[12];
+        lfs1_superblock_t *superblock = (void *)&buf[12];
         uint32_t block_size = lfs1_fromle32(superblock->d.block_size);
         uint32_t block_count = lfs1_fromle32(superblock->d.block_count);
         len = block_count * block_size;
@@ -213,7 +213,7 @@
     #if MICROPY_VFS_LFS2
     if (memcmp(&buf[8], "littlefs", 8) == 0) {
         // LFS2
-        lfs2_superblock_t *superblock = (void*)&buf[20];
+        lfs2_superblock_t *superblock = (void *)&buf[20];
         uint32_t block_size = lfs2_fromle32(superblock->block_size);
         uint32_t block_count = lfs2_fromle32(superblock->block_count);
         len = block_count * block_size;
@@ -473,20 +473,20 @@
     __HAL_RCC_GPIOD_CLK_ENABLE();
     #endif
 
-    #if defined(STM32F4) ||  defined(STM32F7)
-        #if defined(__HAL_RCC_DTCMRAMEN_CLK_ENABLE)
-        // The STM32F746 doesn't really have CCM memory, but it does have DTCM,
-        // which behaves more or less like normal SRAM.
-        __HAL_RCC_DTCMRAMEN_CLK_ENABLE();
-        #elif defined(CCMDATARAM_BASE)
-        // enable the CCM RAM
-        __HAL_RCC_CCMDATARAMEN_CLK_ENABLE();
-        #endif
+    #if defined(STM32F4) || defined(STM32F7)
+    #if defined(__HAL_RCC_DTCMRAMEN_CLK_ENABLE)
+    // The STM32F746 doesn't really have CCM memory, but it does have DTCM,
+    // which behaves more or less like normal SRAM.
+    __HAL_RCC_DTCMRAMEN_CLK_ENABLE();
+    #elif defined(CCMDATARAM_BASE)
+    // enable the CCM RAM
+    __HAL_RCC_CCMDATARAMEN_CLK_ENABLE();
+    #endif
     #elif defined(STM32H7)
-        // Enable D2 SRAM1/2/3 clocks.
-        __HAL_RCC_D2SRAM1_CLK_ENABLE();
-        __HAL_RCC_D2SRAM2_CLK_ENABLE();
-        __HAL_RCC_D2SRAM3_CLK_ENABLE();
+    // Enable D2 SRAM1/2/3 clocks.
+    __HAL_RCC_D2SRAM1_CLK_ENABLE();
+    __HAL_RCC_D2SRAM2_CLK_ENABLE();
+    __HAL_RCC_D2SRAM3_CLK_ENABLE();
     #endif
 
 
@@ -549,9 +549,9 @@
         cyw43_init(&cyw43_state);
         uint8_t buf[8];
         memcpy(&buf[0], "PYBD", 4);
-        mp_hal_get_mac_ascii(MP_HAL_MAC_WLAN0, 8, 4, (char*)&buf[4]);
+        mp_hal_get_mac_ascii(MP_HAL_MAC_WLAN0, 8, 4, (char *)&buf[4]);
         cyw43_wifi_ap_set_ssid(&cyw43_state, 8, buf);
-        cyw43_wifi_ap_set_password(&cyw43_state, 8, (const uint8_t*)"pybd0123");
+        cyw43_wifi_ap_set_password(&cyw43_state, 8, (const uint8_t *)"pybd0123");
     }
     #endif
 
@@ -594,7 +594,7 @@
     // to recover from limit hit.  (Limit is measured in bytes.)
     // Note: stack control relies on main thread being initialised above
     mp_stack_set_top(&_estack);
-    mp_stack_set_limit((char*)&_estack - (char*)&_sstack - 1024);
+    mp_stack_set_limit((char *)&_estack - (char *)&_sstack - 1024);
 
     // GC init
     gc_init(MICROPY_HEAP_START, MICROPY_HEAP_END);
diff --git a/ports/stm32/make-stmconst.py b/ports/stm32/make-stmconst.py
index 41ec9b5..1b3cc08 100644
--- a/ports/stm32/make-stmconst.py
+++ b/ports/stm32/make-stmconst.py
@@ -11,16 +11,23 @@
 
 # Python 2/3 compatibility
 import platform
-if platform.python_version_tuple()[0] == '2':
+
+if platform.python_version_tuple()[0] == "2":
+
     def convert_bytes_to_str(b):
         return b
-elif platform.python_version_tuple()[0] == '3':
+
+
+elif platform.python_version_tuple()[0] == "3":
+
     def convert_bytes_to_str(b):
         try:
-            return str(b, 'utf8')
+            return str(b, "utf8")
         except ValueError:
             # some files have invalid utf8 bytes, so filter them out
-            return ''.join(chr(l) for l in b if l <= 126)
+            return "".join(chr(l) for l in b if l <= 126)
+
+
 # end compatibility code
 
 # given a list of (name,regex) pairs, find the first one that matches the given line
@@ -31,29 +38,64 @@
             return name, match
     return None, None
 
+
 class LexerError(Exception):
     def __init__(self, line):
         self.line = line
 
+
 class Lexer:
-    re_io_reg = r'__IO uint(?P<bits>8|16|32)_t +(?P<reg>[A-Z0-9]+)'
-    re_comment = r'(?P<comment>[A-Za-z0-9 \-/_()&]+)'
-    re_addr_offset = r'Address offset: (?P<offset>0x[0-9A-Z]{2,3})'
+    re_io_reg = r"__IO uint(?P<bits>8|16|32)_t +(?P<reg>[A-Z0-9]+)"
+    re_comment = r"(?P<comment>[A-Za-z0-9 \-/_()&]+)"
+    re_addr_offset = r"Address offset: (?P<offset>0x[0-9A-Z]{2,3})"
     regexs = (
-        ('#define hex', re.compile(r'#define +(?P<id>[A-Z0-9_]+) +\(?(\(uint32_t\))?(?P<hex>0x[0-9A-F]+)U?L?\)?($| */\*)')),
-        ('#define X', re.compile(r'#define +(?P<id>[A-Z0-9_]+) +(?P<id2>[A-Z0-9_]+)($| +/\*)')),
-        ('#define X+hex', re.compile(r'#define +(?P<id>[A-Za-z0-9_]+) +\(?(?P<id2>[A-Z0-9_]+) \+ (?P<hex>0x[0-9A-F]+)U?L?\)?($| +/\*)')),
-        ('#define typedef', re.compile(r'#define +(?P<id>[A-Z0-9_]+(ext)?) +\(\([A-Za-z0-9_]+_TypeDef \*\) (?P<id2>[A-Za-z0-9_]+)\)($| +/\*)')),
-        ('typedef struct', re.compile(r'typedef struct$')),
-        ('{', re.compile(r'{$')),
-        ('}', re.compile(r'}$')),
-        ('} TypeDef', re.compile(r'} *(?P<id>[A-Z][A-Za-z0-9_]+)_(?P<global>([A-Za-z0-9_]+)?)TypeDef;$')),
-        ('IO reg', re.compile(re_io_reg + r'; */\*!< *' + re_comment + r', +' + re_addr_offset + r' *\*/')),
-        ('IO reg array', re.compile(re_io_reg + r'\[(?P<array>[2-8])\]; */\*!< *' + re_comment + r', +' + re_addr_offset + r'-(0x[0-9A-Z]{2,3}) *\*/')),
+        (
+            "#define hex",
+            re.compile(
+                r"#define +(?P<id>[A-Z0-9_]+) +\(?(\(uint32_t\))?(?P<hex>0x[0-9A-F]+)U?L?\)?($| */\*)"
+            ),
+        ),
+        ("#define X", re.compile(r"#define +(?P<id>[A-Z0-9_]+) +(?P<id2>[A-Z0-9_]+)($| +/\*)")),
+        (
+            "#define X+hex",
+            re.compile(
+                r"#define +(?P<id>[A-Za-z0-9_]+) +\(?(?P<id2>[A-Z0-9_]+) \+ (?P<hex>0x[0-9A-F]+)U?L?\)?($| +/\*)"
+            ),
+        ),
+        (
+            "#define typedef",
+            re.compile(
+                r"#define +(?P<id>[A-Z0-9_]+(ext)?) +\(\([A-Za-z0-9_]+_TypeDef \*\) (?P<id2>[A-Za-z0-9_]+)\)($| +/\*)"
+            ),
+        ),
+        ("typedef struct", re.compile(r"typedef struct$")),
+        ("{", re.compile(r"{$")),
+        ("}", re.compile(r"}$")),
+        (
+            "} TypeDef",
+            re.compile(r"} *(?P<id>[A-Z][A-Za-z0-9_]+)_(?P<global>([A-Za-z0-9_]+)?)TypeDef;$"),
+        ),
+        (
+            "IO reg",
+            re.compile(
+                re_io_reg + r"; */\*!< *" + re_comment + r", +" + re_addr_offset + r" *\*/"
+            ),
+        ),
+        (
+            "IO reg array",
+            re.compile(
+                re_io_reg
+                + r"\[(?P<array>[2-8])\]; */\*!< *"
+                + re_comment
+                + r", +"
+                + re_addr_offset
+                + r"-(0x[0-9A-Z]{2,3}) *\*/"
+            ),
+        ),
     )
 
     def __init__(self, filename):
-        self.file = open(filename, 'rb')
+        self.file = open(filename, "rb")
         self.line_number = 0
 
     def next_match(self, strictly_next=False):
@@ -62,7 +104,7 @@
             line = convert_bytes_to_str(line)
             self.line_number += 1
             if len(line) == 0:
-                return ('EOF', None)
+                return ("EOF", None)
             match = re_match_first(Lexer.regexs, line.strip())
             if strictly_next or match[0] is not None:
                 return match
@@ -73,6 +115,7 @@
             raise LexerError(self.line_number)
         return match
 
+
 def parse_file(filename):
     lexer = Lexer(filename)
 
@@ -81,71 +124,75 @@
     periphs = []
     while True:
         m = lexer.next_match()
-        if m[0] == 'EOF':
+        if m[0] == "EOF":
             break
-        elif m[0] == '#define hex':
+        elif m[0] == "#define hex":
             d = m[1].groupdict()
-            consts[d['id']] = int(d['hex'], base=16)
-        elif m[0] == '#define X':
+            consts[d["id"]] = int(d["hex"], base=16)
+        elif m[0] == "#define X":
             d = m[1].groupdict()
-            if d['id2'] in consts:
-                consts[d['id']] = consts[d['id2']]
-        elif m[0] == '#define X+hex':
+            if d["id2"] in consts:
+                consts[d["id"]] = consts[d["id2"]]
+        elif m[0] == "#define X+hex":
             d = m[1].groupdict()
-            if d['id2'] in consts:
-                consts[d['id']] = consts[d['id2']] + int(d['hex'], base=16)
-        elif m[0] == '#define typedef':
+            if d["id2"] in consts:
+                consts[d["id"]] = consts[d["id2"]] + int(d["hex"], base=16)
+        elif m[0] == "#define typedef":
             d = m[1].groupdict()
-            if d['id2'] in consts:
-                periphs.append((d['id'], consts[d['id2']]))
-        elif m[0] == 'typedef struct':
-            lexer.must_match('{')
+            if d["id2"] in consts:
+                periphs.append((d["id"], consts[d["id2"]]))
+        elif m[0] == "typedef struct":
+            lexer.must_match("{")
             m = lexer.next_match()
             regs = []
-            while m[0] in ('IO reg', 'IO reg array'):
+            while m[0] in ("IO reg", "IO reg array"):
                 d = m[1].groupdict()
-                reg = d['reg']
-                offset = int(d['offset'], base=16)
-                bits = int(d['bits'])
-                comment = d['comment']
-                if m[0] == 'IO reg':
+                reg = d["reg"]
+                offset = int(d["offset"], base=16)
+                bits = int(d["bits"])
+                comment = d["comment"]
+                if m[0] == "IO reg":
                     regs.append((reg, offset, bits, comment))
                 else:
-                    for i in range(int(d['array'])):
+                    for i in range(int(d["array"])):
                         regs.append((reg + str(i), offset + i * bits // 8, bits, comment))
                 m = lexer.next_match()
-            if m[0] == '}':
+            if m[0] == "}":
                 pass
-            elif m[0] == '} TypeDef':
-                reg_defs[m[1].groupdict()['id']] = regs
+            elif m[0] == "} TypeDef":
+                reg_defs[m[1].groupdict()["id"]] = regs
             else:
                 raise LexerError(lexer.line_number)
 
     return periphs, reg_defs
 
+
 def print_int_obj(val, needed_mpzs):
     if -0x40000000 <= val < 0x40000000:
-        print('MP_ROM_INT(%#x)' % val, end='')
+        print("MP_ROM_INT(%#x)" % val, end="")
     else:
-        print('MP_ROM_PTR(&mpz_%08x)' % val, end='')
+        print("MP_ROM_PTR(&mpz_%08x)" % val, end="")
         needed_mpzs.add(val)
 
+
 def print_periph(periph_name, periph_val, needed_qstrs, needed_mpzs):
     qstr = periph_name.upper()
-    print('{ MP_ROM_QSTR(MP_QSTR_%s), ' % qstr, end='')
+    print("{ MP_ROM_QSTR(MP_QSTR_%s), " % qstr, end="")
     print_int_obj(periph_val, needed_mpzs)
-    print(' },')
+    print(" },")
     needed_qstrs.add(qstr)
 
+
 def print_regs(reg_name, reg_defs, needed_qstrs, needed_mpzs):
     reg_name = reg_name.upper()
     for r in reg_defs:
-        qstr = reg_name + '_' + r[0]
-        print('{ MP_ROM_QSTR(MP_QSTR_%s), ' % qstr, end='')
+        qstr = reg_name + "_" + r[0]
+        print("{ MP_ROM_QSTR(MP_QSTR_%s), " % qstr, end="")
         print_int_obj(r[1], needed_mpzs)
-        print(' }, // %s-bits, %s' % (r[2], r[3]))
+        print(" }, // %s-bits, %s" % (r[2], r[3]))
         needed_qstrs.add(qstr)
 
+
 # This version of print regs groups registers together into submodules (eg GPIO submodule).
 # This makes the qstrs shorter, and makes the list of constants more manageable (since
 # they are not all in one big module) but it is then harder to compile the constants, and
@@ -154,21 +201,28 @@
 # And for the number of constants we have, this function seems to use about the same amount
 # of ROM as print_regs.
 def print_regs_as_submodules(reg_name, reg_defs, modules, needed_qstrs):
-    mod_name_lower = reg_name.lower() + '_'
+    mod_name_lower = reg_name.lower() + "_"
     mod_name_upper = mod_name_lower.upper()
     modules.append((mod_name_lower, mod_name_upper))
 
-    print("""
+    print(
+        """
 STATIC const mp_rom_map_elem_t stm_%s_globals_table[] = {
     { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_%s) },
-""" % (mod_name_lower, mod_name_upper))
+"""
+        % (mod_name_lower, mod_name_upper)
+    )
     needed_qstrs.add(mod_name_upper)
 
     for r in reg_defs:
-        print('    { MP_ROM_QSTR(MP_QSTR_%s), MP_ROM_INT(%#x) }, // %s-bits, %s' % (r[0], r[1], r[2], r[3]))
+        print(
+            "    { MP_ROM_QSTR(MP_QSTR_%s), MP_ROM_INT(%#x) }, // %s-bits, %s"
+            % (r[0], r[1], r[2], r[3])
+        )
         needed_qstrs.add(r[0])
 
-    print("""};
+    print(
+        """};
 
 STATIC MP_DEFINE_CONST_DICT(stm_%s_globals, stm_%s_globals_table);
 
@@ -177,23 +231,35 @@
     .name = MP_QSTR_%s,
     .globals = (mp_obj_dict_t*)&stm_%s_globals,
 };
-""" % (mod_name_lower, mod_name_lower, mod_name_lower, mod_name_upper, mod_name_lower))
+"""
+        % (mod_name_lower, mod_name_lower, mod_name_lower, mod_name_upper, mod_name_lower)
+    )
+
 
 def main():
-    cmd_parser = argparse.ArgumentParser(description='Extract ST constants from a C header file.')
-    cmd_parser.add_argument('file', nargs=1, help='input file')
-    cmd_parser.add_argument('-q', '--qstr', dest='qstr_filename', default='build/stmconst_qstr.h',
-                            help='Specified the name of the generated qstr header file')
-    cmd_parser.add_argument('--mpz', dest='mpz_filename', default='build/stmconst_mpz.h',
-                            help='the destination file of the generated mpz header')
+    cmd_parser = argparse.ArgumentParser(description="Extract ST constants from a C header file.")
+    cmd_parser.add_argument("file", nargs=1, help="input file")
+    cmd_parser.add_argument(
+        "-q",
+        "--qstr",
+        dest="qstr_filename",
+        default="build/stmconst_qstr.h",
+        help="Specified the name of the generated qstr header file",
+    )
+    cmd_parser.add_argument(
+        "--mpz",
+        dest="mpz_filename",
+        default="build/stmconst_mpz.h",
+        help="the destination file of the generated mpz header",
+    )
     args = cmd_parser.parse_args()
 
     periphs, reg_defs = parse_file(args.file[0])
 
     # add legacy GPIO constants that were removed when upgrading CMSIS
-    if 'GPIO' in reg_defs and 'stm32f4' in args.file[0]:
-        reg_defs['GPIO'].append(['BSRRL', 0x18, 16, 'legacy register'])
-        reg_defs['GPIO'].append(['BSRRH', 0x1a, 16, 'legacy register'])
+    if "GPIO" in reg_defs and "stm32f4" in args.file[0]:
+        reg_defs["GPIO"].append(["BSRRL", 0x18, 16, "legacy register"])
+        reg_defs["GPIO"].append(["BSRRH", 0x1A, 16, "legacy register"])
 
     modules = []
     needed_qstrs = set()
@@ -206,55 +272,60 @@
         print_periph(periph_name, periph_val, needed_qstrs, needed_mpzs)
 
     for reg in (
-        'ADC',
+        "ADC",
         #'ADC_Common',
         #'CAN_TxMailBox',
         #'CAN_FIFOMailBox',
         #'CAN_FilterRegister',
         #'CAN',
-        'CRC',
-        'DAC',
-        'DBGMCU',
-        'DMA_Stream',
-        'DMA',
-        'EXTI',
-        'FLASH',
-        'GPIO',
-        'SYSCFG',
-        'I2C',
-        'IWDG',
-        'PWR',
-        'RCC',
-        'RTC',
+        "CRC",
+        "DAC",
+        "DBGMCU",
+        "DMA_Stream",
+        "DMA",
+        "EXTI",
+        "FLASH",
+        "GPIO",
+        "SYSCFG",
+        "I2C",
+        "IWDG",
+        "PWR",
+        "RCC",
+        "RTC",
         #'SDIO',
-        'SPI',
-        'TIM',
-        'USART',
-        'WWDG',
-        'RNG',
-        ):
+        "SPI",
+        "TIM",
+        "USART",
+        "WWDG",
+        "RNG",
+    ):
         if reg in reg_defs:
             print_regs(reg, reg_defs[reg], needed_qstrs, needed_mpzs)
-        #print_regs_as_submodules(reg, reg_defs[reg], modules, needed_qstrs)
+        # print_regs_as_submodules(reg, reg_defs[reg], modules, needed_qstrs)
 
-    #print("#define MOD_STM_CONST_MODULES \\")
-    #for mod_lower, mod_upper in modules:
+    # print("#define MOD_STM_CONST_MODULES \\")
+    # for mod_lower, mod_upper in modules:
     #    print("    { MP_ROM_QSTR(MP_QSTR_%s), MP_ROM_PTR(&stm_%s_obj) }, \\" % (mod_upper, mod_lower))
 
     print("")
 
-    with open(args.qstr_filename, 'wt') as qstr_file:
-        print('#if MICROPY_PY_STM', file=qstr_file)
+    with open(args.qstr_filename, "wt") as qstr_file:
+        print("#if MICROPY_PY_STM", file=qstr_file)
         for qstr in sorted(needed_qstrs):
-            print('Q({})'.format(qstr), file=qstr_file)
-        print('#endif // MICROPY_PY_STM', file=qstr_file)
+            print("Q({})".format(qstr), file=qstr_file)
+        print("#endif // MICROPY_PY_STM", file=qstr_file)
 
-    with open(args.mpz_filename, 'wt') as mpz_file:
+    with open(args.mpz_filename, "wt") as mpz_file:
         for mpz in sorted(needed_mpzs):
-            assert 0 <= mpz <= 0xffffffff
-            print('STATIC const mp_obj_int_t mpz_%08x = {{&mp_type_int}, '
-                '{.neg=0, .fixed_dig=1, .alloc=2, .len=2, ' '.dig=(uint16_t*)(const uint16_t[]){%#x, %#x}}};'
-                % (mpz, mpz & 0xffff, (mpz >> 16) & 0xffff), file=mpz_file)
+            assert 0 <= mpz <= 0xFFFFFFFF
+            print(
+                "STATIC const mp_obj_int_t mpz_%08x = {{&mp_type_int}, "
+                "{.neg=0, .fixed_dig=1, .alloc=2, .len=2, "
+                ".dig=(uint16_t*)(const uint16_t[]){%#x, %#x}}};"
+                % (mpz, mpz & 0xFFFF, (mpz >> 16) & 0xFFFF),
+                file=mpz_file,
+            )
+
 
 if __name__ == "__main__":
     main()
diff --git a/ports/stm32/mboot/fwupdate.py b/ports/stm32/mboot/fwupdate.py
index b2690e8..b44ed77 100644
--- a/ports/stm32/mboot/fwupdate.py
+++ b/ports/stm32/mboot/fwupdate.py
@@ -6,7 +6,7 @@
 
 
 FLASH_KEY1 = 0x45670123
-FLASH_KEY2 = 0xcdef89ab
+FLASH_KEY2 = 0xCDEF89AB
 
 
 def check_mem_contains(addr, buf):
@@ -17,99 +17,100 @@
             return False
     return True
 
+
 def check_mem_erased(addr, size):
     mem16 = stm.mem16
     r = range(0, size, 2)
     for off in r:
-        if mem16[addr + off] != 0xffff:
+        if mem16[addr + off] != 0xFFFF:
             return False
     return True
 
+
 def dfu_read(filename):
-    f = open(filename, 'rb')
+    f = open(filename, "rb")
 
     hdr = f.read(3)
     f.seek(0)
-    if hdr == b'Dfu':
+    if hdr == b"Dfu":
         pass
-    elif hdr == b'\x1f\x8b\x08':
+    elif hdr == b"\x1f\x8b\x08":
         f = uzlib.DecompIO(f, 16 + 15)
     else:
-        print('Invalid firmware', filename)
+        print("Invalid firmware", filename)
         return None
 
     elems = []
 
     hdr = f.read(11)
-    sig, ver, size, num_targ = struct.unpack('<5sBIB', hdr)
+    sig, ver, size, num_targ = struct.unpack("<5sBIB", hdr)
 
     file_offset = 11
 
     for i in range(num_targ):
         hdr = f.read(274)
-        sig, alt, has_name, name, t_size, num_elem = struct.unpack('<6sBi255sII', hdr)
+        sig, alt, has_name, name, t_size, num_elem = struct.unpack("<6sBi255sII", hdr)
 
         file_offset += 274
         file_offset_t = file_offset
         for j in range(num_elem):
             hdr = f.read(8)
-            addr, e_size = struct.unpack('<II', hdr)
+            addr, e_size = struct.unpack("<II", hdr)
             data = f.read(e_size)
             elems.append((addr, data))
             file_offset += 8 + e_size
 
         if t_size != file_offset - file_offset_t:
-            print('corrupt DFU', t_size, file_offset - file_offset_t)
+            print("corrupt DFU", t_size, file_offset - file_offset_t)
             return None
 
     if size != file_offset:
-        print('corrupt DFU', size, file_offset)
+        print("corrupt DFU", size, file_offset)
         return None
 
     hdr = f.read(16)
-    hdr = struct.unpack('<HHHH3sBI', hdr)
+    hdr = struct.unpack("<HHHH3sBI", hdr)
 
     return elems
 
+
 def flash_wait_not_busy():
     while stm.mem32[stm.FLASH + stm.FLASH_SR] & 1 << 16:
         machine.idle()
 
+
 def flash_unlock():
     stm.mem32[stm.FLASH + stm.FLASH_KEYR] = FLASH_KEY1
     stm.mem32[stm.FLASH + stm.FLASH_KEYR] = FLASH_KEY2
 
+
 def flash_lock():
-    stm.mem32[stm.FLASH + stm.FLASH_CR] = 1 << 31 # LOCK
+    stm.mem32[stm.FLASH + stm.FLASH_CR] = 1 << 31  # LOCK
+
 
 def flash_erase_sector(sector):
-    assert 0 <= sector <= 7 # for F722
+    assert 0 <= sector <= 7  # for F722
     flash_wait_not_busy()
-    cr = (
-        2 << 8 # PSIZE = 32 bits
-        | sector << 3 # SNB
-        | 1 << 1 # SER
-    )
+    cr = 2 << 8 | sector << 3 | 1 << 1  # PSIZE = 32 bits  # SNB  # SER
     stm.mem32[stm.FLASH + stm.FLASH_CR] = cr
-    stm.mem32[stm.FLASH + stm.FLASH_CR] = cr | 1 << 16 # STRT
+    stm.mem32[stm.FLASH + stm.FLASH_CR] = cr | 1 << 16  # STRT
     flash_wait_not_busy()
     stm.mem32[stm.FLASH + stm.FLASH_CR] = 0
 
+
 def flash_write(addr, buf):
     assert len(buf) % 4 == 0
     flash_wait_not_busy()
-    cr = (
-        2 << 8 # PSIZE = 32 bits
-        | 1 << 0 # PG
-    )
+    cr = 2 << 8 | 1 << 0  # PSIZE = 32 bits  # PG
     stm.mem32[stm.FLASH + stm.FLASH_CR] = cr
     for off in range(0, len(buf), 4):
-        stm.mem32[addr + off] = struct.unpack_from('I', buf, off)[0]
+        stm.mem32[addr + off] = struct.unpack_from("I", buf, off)[0]
         flash_wait_not_busy()
     stm.mem32[stm.FLASH + stm.FLASH_CR] = 0
 
+
 def update_mboot(filename):
-    print('Loading file', filename)
+    print("Loading file", filename)
 
     mboot_fw = dfu_read(filename)
     if mboot_fw is None:
@@ -122,14 +123,14 @@
 
     # TODO: Validate firmware in a simple way
 
-    print('Found Mboot data with size %u.' % len(mboot_fw))
+    print("Found Mboot data with size %u." % len(mboot_fw))
 
     chk = check_mem_contains(mboot_addr, mboot_fw)
     if chk:
-        print('Supplied version of Mboot is already on device.')
+        print("Supplied version of Mboot is already on device.")
         return
 
-    print('Programming Mboot, do not turn off!')
+    print("Programming Mboot, do not turn off!")
     time.sleep_ms(50)
 
     irq = machine.disable_irq()
@@ -141,24 +142,25 @@
     flash_lock()
     machine.enable_irq(irq)
 
-    print('New Mboot programmed.')
+    print("New Mboot programmed.")
 
     if check_mem_contains(mboot_addr, mboot_fw):
-        print('Verification of new Mboot succeeded.')
+        print("Verification of new Mboot succeeded.")
     else:
-        print('Verification of new Mboot FAILED!  Try rerunning.')
+        print("Verification of new Mboot FAILED!  Try rerunning.")
 
-    print('Programming finished, can now reset or turn off.')
+    print("Programming finished, can now reset or turn off.")
+
 
 def update_mpy(filename, fs_base, fs_len):
     # Check firmware is of .dfu.gz type
     try:
-        with open(filename, 'rb') as f:
+        with open(filename, "rb") as f:
             hdr = uzlib.DecompIO(f, 16 + 15).read(6)
     except Exception:
         hdr = None
-    if hdr != b'DfuSe\x01':
-        print('Firmware must be a .dfu.gz file.')
+    if hdr != b"DfuSe\x01":
+        print("Firmware must be a .dfu.gz file.")
         return
 
     ELEM_TYPE_END = 1
@@ -166,7 +168,11 @@
     ELEM_TYPE_FSLOAD = 3
     ELEM_MOUNT_FAT = 1
     mount_point = 1
-    mount = struct.pack('<BBBBLL', ELEM_TYPE_MOUNT, 10, mount_point, ELEM_MOUNT_FAT, fs_base, fs_len)
-    fsup = struct.pack('<BBB', ELEM_TYPE_FSLOAD, 1 + len(filename), mount_point) + bytes(filename, 'ascii')
-    end = struct.pack('<BB', ELEM_TYPE_END, 0)
+    mount = struct.pack(
+        "<BBBBLL", ELEM_TYPE_MOUNT, 10, mount_point, ELEM_MOUNT_FAT, fs_base, fs_len
+    )
+    fsup = struct.pack("<BBB", ELEM_TYPE_FSLOAD, 1 + len(filename), mount_point) + bytes(
+        filename, "ascii"
+    )
+    end = struct.pack("<BB", ELEM_TYPE_END, 0)
     machine.bootloader(mount + fsup + end)
diff --git a/ports/stm32/mboot/mboot.py b/ports/stm32/mboot/mboot.py
index 39ae0f6..e0dab16 100644
--- a/ports/stm32/mboot/mboot.py
+++ b/ports/stm32/mboot/mboot.py
@@ -27,9 +27,9 @@
         self.addr = addr
         self.buf1 = bytearray(1)
         try:
-            self.i2c.writeto(addr, b'')
+            self.i2c.writeto(addr, b"")
         except OSError:
-            raise Exception('no I2C mboot device found')
+            raise Exception("no I2C mboot device found")
 
     def wait_response(self):
         start = time.ticks_ms()
@@ -41,47 +41,47 @@
             except OSError as er:
                 time.sleep_us(500)
             if time.ticks_diff(time.ticks_ms(), start) > 5000:
-                raise Exception('timeout')
+                raise Exception("timeout")
         if n >= 129:
             raise Exception(n)
         if n == 0:
-            return b''
+            return b""
         else:
             return self.i2c.readfrom(self.addr, n)
 
     def wait_empty_response(self):
         ret = self.wait_response()
         if ret:
-            raise Exception('expected empty response got %r' % ret)
+            raise Exception("expected empty response got %r" % ret)
         else:
             return None
 
     def echo(self, data):
-        self.i2c.writeto(self.addr, struct.pack('<B', I2C_CMD_ECHO) + data)
+        self.i2c.writeto(self.addr, struct.pack("<B", I2C_CMD_ECHO) + data)
         return self.wait_response()
 
     def getid(self):
-        self.i2c.writeto(self.addr, struct.pack('<B', I2C_CMD_GETID))
+        self.i2c.writeto(self.addr, struct.pack("<B", I2C_CMD_GETID))
         ret = self.wait_response()
         unique_id = ret[:12]
-        mcu_name, board_name = ret[12:].split(b'\x00')
-        return unique_id, str(mcu_name, 'ascii'), str(board_name, 'ascii')
+        mcu_name, board_name = ret[12:].split(b"\x00")
+        return unique_id, str(mcu_name, "ascii"), str(board_name, "ascii")
 
     def reset(self):
-        self.i2c.writeto(self.addr, struct.pack('<B', I2C_CMD_RESET))
+        self.i2c.writeto(self.addr, struct.pack("<B", I2C_CMD_RESET))
         # we don't expect any response
 
     def getlayout(self):
-        self.i2c.writeto(self.addr, struct.pack('<B', I2C_CMD_GETLAYOUT))
+        self.i2c.writeto(self.addr, struct.pack("<B", I2C_CMD_GETLAYOUT))
         layout = self.wait_response()
-        id, flash_addr, layout = layout.split(b'/')
-        assert id == b'@Internal Flash  '
+        id, flash_addr, layout = layout.split(b"/")
+        assert id == b"@Internal Flash  "
         flash_addr = int(flash_addr, 16)
         pages = []
-        for chunk in layout.split(b','):
-            n, sz = chunk.split(b'*')
+        for chunk in layout.split(b","):
+            n, sz = chunk.split(b"*")
             n = int(n)
-            assert sz.endswith(b'Kg')
+            assert sz.endswith(b"Kg")
             sz = int(sz[:-2]) * 1024
             for i in range(n):
                 pages.append((flash_addr, sz))
@@ -89,43 +89,43 @@
         return pages
 
     def pageerase(self, addr):
-        self.i2c.writeto(self.addr, struct.pack('<BI', I2C_CMD_PAGEERASE, addr))
+        self.i2c.writeto(self.addr, struct.pack("<BI", I2C_CMD_PAGEERASE, addr))
         self.wait_empty_response()
 
     def setrdaddr(self, addr):
-        self.i2c.writeto(self.addr, struct.pack('<BI', I2C_CMD_SETRDADDR, addr))
+        self.i2c.writeto(self.addr, struct.pack("<BI", I2C_CMD_SETRDADDR, addr))
         self.wait_empty_response()
 
     def setwraddr(self, addr):
-        self.i2c.writeto(self.addr, struct.pack('<BI', I2C_CMD_SETWRADDR, addr))
+        self.i2c.writeto(self.addr, struct.pack("<BI", I2C_CMD_SETWRADDR, addr))
         self.wait_empty_response()
 
     def read(self, n):
-        self.i2c.writeto(self.addr, struct.pack('<BB', I2C_CMD_READ, n))
+        self.i2c.writeto(self.addr, struct.pack("<BB", I2C_CMD_READ, n))
         return self.wait_response()
 
     def write(self, buf):
-        self.i2c.writeto(self.addr, struct.pack('<B', I2C_CMD_WRITE) + buf)
+        self.i2c.writeto(self.addr, struct.pack("<B", I2C_CMD_WRITE) + buf)
         self.wait_empty_response()
 
     def calchash(self, n):
-        self.i2c.writeto(self.addr, struct.pack('<BI', I2C_CMD_CALCHASH, n))
+        self.i2c.writeto(self.addr, struct.pack("<BI", I2C_CMD_CALCHASH, n))
         return self.wait_response()
 
     def markvalid(self):
-        self.i2c.writeto(self.addr, struct.pack('<B', I2C_CMD_MARKVALID))
+        self.i2c.writeto(self.addr, struct.pack("<B", I2C_CMD_MARKVALID))
         self.wait_empty_response()
 
     def deployfile(self, filename, addr):
         pages = self.getlayout()
         page_erased = [False] * len(pages)
-        buf = bytearray(128) # maximum payload supported by I2C protocol
+        buf = bytearray(128)  # maximum payload supported by I2C protocol
         start_addr = addr
         self.setwraddr(addr)
         fsize = os.stat(filename)[6]
         local_sha = hashlib.sha256()
-        print('Deploying %s to location 0x%08x' % (filename, addr))
-        with open(filename, 'rb') as f:
+        print("Deploying %s to location 0x%08x" % (filename, addr))
+        with open(filename, "rb") as f:
             t0 = time.ticks_ms()
             while True:
                 n = f.readinto(buf)
@@ -137,12 +137,16 @@
                     if p[0] <= addr < p[0] + p[1]:
                         # found page
                         if not page_erased[i]:
-                            print('\r% 3u%% erase 0x%08x' % (100 * (addr - start_addr) // fsize, addr), end='')
+                            print(
+                                "\r% 3u%% erase 0x%08x"
+                                % (100 * (addr - start_addr) // fsize, addr),
+                                end="",
+                            )
                             self.pageerase(addr)
                             page_erased[i] = True
                         break
                 else:
-                    raise Exception('address 0x%08x not valid' % addr)
+                    raise Exception("address 0x%08x not valid" % addr)
 
                 # write the data
                 self.write(buf)
@@ -158,20 +162,20 @@
                 addr += n
                 ntotal = addr - start_addr
                 if ntotal % 2048 == 0 or ntotal == fsize:
-                    print('\r% 3u%% % 7u bytes   ' % (100 * ntotal // fsize, ntotal), end='')
+                    print("\r% 3u%% % 7u bytes   " % (100 * ntotal // fsize, ntotal), end="")
             t1 = time.ticks_ms()
         print()
-        print('rate: %.2f KiB/sec' % (1024 * ntotal / (t1 - t0) / 1000))
+        print("rate: %.2f KiB/sec" % (1024 * ntotal / (t1 - t0) / 1000))
 
         local_sha = local_sha.digest()
-        print('Local SHA256: ', ''.join('%02x' % x for x in local_sha))
+        print("Local SHA256: ", "".join("%02x" % x for x in local_sha))
 
         self.setrdaddr(start_addr)
         remote_sha = self.calchash(ntotal)
-        print('Remote SHA256:', ''.join('%02x' % x for x in remote_sha))
+        print("Remote SHA256:", "".join("%02x" % x for x in remote_sha))
 
         if local_sha == remote_sha:
-            print('Marking app firmware as valid')
+            print("Marking app firmware as valid")
             self.markvalid()
 
         self.reset()
diff --git a/ports/stm32/modmachine.c b/ports/stm32/modmachine.c
index 8ea136b..02496a0 100644
--- a/ports/stm32/modmachine.c
+++ b/ports/stm32/modmachine.c
@@ -124,10 +124,10 @@
         if (state & RCC_SR_IWDGRSTF || state & RCC_SR_WWDGRSTF) {
             reset_cause = PYB_RESET_WDT;
         } else if (state & RCC_SR_PORRSTF
-            #if !defined(STM32F0)
-            || state & RCC_SR_BORRSTF
-            #endif
-            ) {
+                   #if !defined(STM32F0)
+                   || state & RCC_SR_BORRSTF
+                   #endif
+                   ) {
             reset_cause = PYB_RESET_POWER_ON;
         } else if (state & RCC_SR_PINRSTF) {
             reset_cause = PYB_RESET_HARD;
@@ -150,7 +150,7 @@
 STATIC mp_obj_t machine_info(size_t n_args, const mp_obj_t *args) {
     // get and print unique id; 96 bits
     {
-        byte *id = (byte*)MP_HAL_UNIQUE_ID_ADDRESS;
+        byte *id = (byte *)MP_HAL_UNIQUE_ID_ADDRESS;
         printf("ID=%02x%02x%02x%02x:%02x%02x%02x%02x:%02x%02x%02x%02x\n", id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7], id[8], id[9], id[10], id[11]);
     }
 
@@ -159,15 +159,15 @@
     {
         #if defined(STM32F0)
         printf("S=%u\nH=%u\nP1=%u\n",
-               (unsigned int)HAL_RCC_GetSysClockFreq(),
-               (unsigned int)HAL_RCC_GetHCLKFreq(),
-               (unsigned int)HAL_RCC_GetPCLK1Freq());
+            (unsigned int)HAL_RCC_GetSysClockFreq(),
+            (unsigned int)HAL_RCC_GetHCLKFreq(),
+            (unsigned int)HAL_RCC_GetPCLK1Freq());
         #else
         printf("S=%u\nH=%u\nP1=%u\nP2=%u\n",
-               (unsigned int)HAL_RCC_GetSysClockFreq(),
-               (unsigned int)HAL_RCC_GetHCLKFreq(),
-               (unsigned int)HAL_RCC_GetPCLK1Freq(),
-               (unsigned int)HAL_RCC_GetPCLK2Freq());
+            (unsigned int)HAL_RCC_GetSysClockFreq(),
+            (unsigned int)HAL_RCC_GetHCLKFreq(),
+            (unsigned int)HAL_RCC_GetPCLK1Freq(),
+            (unsigned int)HAL_RCC_GetPCLK2Freq());
         #endif
     }
 
@@ -235,7 +235,7 @@
 
 // Returns a string of 12 bytes (96 bits), which is the unique ID for the MCU.
 STATIC mp_obj_t machine_unique_id(void) {
-    byte *id = (byte*)MP_HAL_UNIQUE_ID_ADDRESS;
+    byte *id = (byte *)MP_HAL_UNIQUE_ID_ADDRESS;
     return mp_obj_new_bytes(id, 12);
 }
 MP_DEFINE_CONST_FUN_OBJ_0(machine_unique_id_obj, machine_unique_id);
@@ -274,7 +274,7 @@
         // With a string/bytes given, pass its data to the custom bootloader
         size_t len;
         const char *data = mp_obj_str_get_data(args[0], &len);
-        void *mboot_region = (void*)*((volatile uint32_t*)0x08000000);
+        void *mboot_region = (void *)*((volatile uint32_t *)0x08000000);
         memmove(mboot_region, data, len);
         powerctrl_enter_bootloader(0x70ad0080, 0x08000000);
     }
@@ -286,7 +286,9 @@
     powerctrl_enter_bootloader(0, 0x00000000);
     #endif
 
-    while (1);
+    while (1) {
+        ;
+    }
 }
 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_bootloader_obj, 0, 1, machine_bootloader);
 
@@ -295,12 +297,12 @@
     if (n_args == 0) {
         // get
         mp_obj_t tuple[] = {
-           mp_obj_new_int(HAL_RCC_GetSysClockFreq()),
-           mp_obj_new_int(HAL_RCC_GetHCLKFreq()),
-           mp_obj_new_int(HAL_RCC_GetPCLK1Freq()),
-           #if !defined(STM32F0)
-           mp_obj_new_int(HAL_RCC_GetPCLK2Freq()),
-           #endif
+            mp_obj_new_int(HAL_RCC_GetSysClockFreq()),
+            mp_obj_new_int(HAL_RCC_GetHCLKFreq()),
+            mp_obj_new_int(HAL_RCC_GetPCLK1Freq()),
+            #if !defined(STM32F0)
+            mp_obj_new_int(HAL_RCC_GetPCLK2Freq()),
+            #endif
         };
         return mp_obj_new_tuple(MP_ARRAY_SIZE(tuple), tuple);
     } else {
@@ -372,17 +374,17 @@
     { MP_ROM_QSTR(MP_QSTR_soft_reset),          MP_ROM_PTR(&machine_soft_reset_obj) },
     { MP_ROM_QSTR(MP_QSTR_bootloader),          MP_ROM_PTR(&machine_bootloader_obj) },
     { MP_ROM_QSTR(MP_QSTR_freq),                MP_ROM_PTR(&machine_freq_obj) },
-#if MICROPY_HW_ENABLE_RNG
+    #if MICROPY_HW_ENABLE_RNG
     { MP_ROM_QSTR(MP_QSTR_rng),                 MP_ROM_PTR(&pyb_rng_get_obj) },
-#endif
+    #endif
     { MP_ROM_QSTR(MP_QSTR_idle),                MP_ROM_PTR(&pyb_wfi_obj) },
     { MP_ROM_QSTR(MP_QSTR_sleep),               MP_ROM_PTR(&machine_lightsleep_obj) },
     { MP_ROM_QSTR(MP_QSTR_lightsleep),          MP_ROM_PTR(&machine_lightsleep_obj) },
     { MP_ROM_QSTR(MP_QSTR_deepsleep),           MP_ROM_PTR(&machine_deepsleep_obj) },
     { MP_ROM_QSTR(MP_QSTR_reset_cause),         MP_ROM_PTR(&machine_reset_cause_obj) },
-#if 0
+    #if 0
     { MP_ROM_QSTR(MP_QSTR_wake_reason),         MP_ROM_PTR(&machine_wake_reason_obj) },
-#endif
+    #endif
 
     { MP_ROM_QSTR(MP_QSTR_disable_irq),         MP_ROM_PTR(&pyb_disable_irq_obj) },
     { MP_ROM_QSTR(MP_QSTR_enable_irq),          MP_ROM_PTR(&pyb_enable_irq_obj) },
@@ -398,14 +400,14 @@
 
     { MP_ROM_QSTR(MP_QSTR_RTC),                 MP_ROM_PTR(&pyb_rtc_type) },
     { MP_ROM_QSTR(MP_QSTR_ADC),                 MP_ROM_PTR(&machine_adc_type) },
-#if MICROPY_PY_MACHINE_I2C
+    #if MICROPY_PY_MACHINE_I2C
     { MP_ROM_QSTR(MP_QSTR_I2C),                 MP_ROM_PTR(&machine_i2c_type) },
-#endif
+    #endif
     { MP_ROM_QSTR(MP_QSTR_SPI),                 MP_ROM_PTR(&machine_hard_spi_type) },
     { MP_ROM_QSTR(MP_QSTR_UART),                MP_ROM_PTR(&pyb_uart_type) },
     { MP_ROM_QSTR(MP_QSTR_WDT),                 MP_ROM_PTR(&pyb_wdt_type) },
     { MP_ROM_QSTR(MP_QSTR_Timer),               MP_ROM_PTR(&machine_timer_type) },
-#if 0
+    #if 0
     { MP_ROM_QSTR(MP_QSTR_HeartBeat),           MP_ROM_PTR(&pyb_heartbeat_type) },
     { MP_ROM_QSTR(MP_QSTR_SD),                  MP_ROM_PTR(&pyb_sd_type) },
 
@@ -413,23 +415,23 @@
     { MP_ROM_QSTR(MP_QSTR_IDLE),                MP_ROM_INT(PYB_PWR_MODE_ACTIVE) },
     { MP_ROM_QSTR(MP_QSTR_SLEEP),               MP_ROM_INT(PYB_PWR_MODE_LPDS) },
     { MP_ROM_QSTR(MP_QSTR_DEEPSLEEP),           MP_ROM_INT(PYB_PWR_MODE_HIBERNATE) },
-#endif
+    #endif
     { MP_ROM_QSTR(MP_QSTR_PWRON_RESET),         MP_ROM_INT(PYB_RESET_POWER_ON) },
     { MP_ROM_QSTR(MP_QSTR_HARD_RESET),          MP_ROM_INT(PYB_RESET_HARD) },
     { MP_ROM_QSTR(MP_QSTR_WDT_RESET),           MP_ROM_INT(PYB_RESET_WDT) },
     { MP_ROM_QSTR(MP_QSTR_DEEPSLEEP_RESET),     MP_ROM_INT(PYB_RESET_DEEPSLEEP) },
     { MP_ROM_QSTR(MP_QSTR_SOFT_RESET),          MP_ROM_INT(PYB_RESET_SOFT) },
-#if 0
+    #if 0
     { MP_ROM_QSTR(MP_QSTR_WLAN_WAKE),           MP_ROM_INT(PYB_SLP_WAKED_BY_WLAN) },
     { MP_ROM_QSTR(MP_QSTR_PIN_WAKE),            MP_ROM_INT(PYB_SLP_WAKED_BY_GPIO) },
     { MP_ROM_QSTR(MP_QSTR_RTC_WAKE),            MP_ROM_INT(PYB_SLP_WAKED_BY_RTC) },
-#endif
+    #endif
 };
 
 STATIC MP_DEFINE_CONST_DICT(machine_module_globals, machine_module_globals_table);
 
 const mp_obj_module_t machine_module = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&machine_module_globals,
+    .globals = (mp_obj_dict_t *)&machine_module_globals,
 };
 
diff --git a/ports/stm32/modnetwork.c b/ports/stm32/modnetwork.c
index 4b0f77f..8f10612 100644
--- a/ports/stm32/modnetwork.c
+++ b/ports/stm32/modnetwork.c
@@ -157,7 +157,7 @@
 
 const mp_obj_module_t mp_module_network = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_network_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_network_globals,
 };
 
 /*******************************************************************************/
@@ -170,10 +170,10 @@
         // Get IP addresses
         const ip_addr_t *dns = dns_getserver(0);
         mp_obj_t tuple[4] = {
-            netutils_format_ipv4_addr((uint8_t*)&netif->ip_addr, NETUTILS_BIG),
-            netutils_format_ipv4_addr((uint8_t*)&netif->netmask, NETUTILS_BIG),
-            netutils_format_ipv4_addr((uint8_t*)&netif->gw, NETUTILS_BIG),
-            netutils_format_ipv4_addr((uint8_t*)dns, NETUTILS_BIG),
+            netutils_format_ipv4_addr((uint8_t *)&netif->ip_addr, NETUTILS_BIG),
+            netutils_format_ipv4_addr((uint8_t *)&netif->netmask, NETUTILS_BIG),
+            netutils_format_ipv4_addr((uint8_t *)&netif->gw, NETUTILS_BIG),
+            netutils_format_ipv4_addr((uint8_t *)dns, NETUTILS_BIG),
         };
         return mp_obj_new_tuple(4, tuple);
     } else if (args[0] == MP_OBJ_NEW_QSTR(MP_QSTR_dhcp)) {
@@ -202,11 +202,11 @@
         // Set static IP addresses
         mp_obj_t *items;
         mp_obj_get_array_fixed_n(args[0], 4, &items);
-        netutils_parse_ipv4_addr(items[0], (uint8_t*)&netif->ip_addr, NETUTILS_BIG);
-        netutils_parse_ipv4_addr(items[1], (uint8_t*)&netif->netmask, NETUTILS_BIG);
-        netutils_parse_ipv4_addr(items[2], (uint8_t*)&netif->gw, NETUTILS_BIG);
+        netutils_parse_ipv4_addr(items[0], (uint8_t *)&netif->ip_addr, NETUTILS_BIG);
+        netutils_parse_ipv4_addr(items[1], (uint8_t *)&netif->netmask, NETUTILS_BIG);
+        netutils_parse_ipv4_addr(items[2], (uint8_t *)&netif->gw, NETUTILS_BIG);
         ip_addr_t dns;
-        netutils_parse_ipv4_addr(items[3], (uint8_t*)&dns, NETUTILS_BIG);
+        netutils_parse_ipv4_addr(items[3], (uint8_t *)&dns, NETUTILS_BIG);
         dns_setserver(0, &dns);
         return mp_const_none;
     }
diff --git a/ports/stm32/modnwcc3k.c b/ports/stm32/modnwcc3k.c
index e5ca52e..92e680e 100644
--- a/ports/stm32/modnwcc3k.c
+++ b/ports/stm32/modnwcc3k.c
@@ -52,8 +52,8 @@
 #include "patch_prog.h"
 
 #define MAX_ADDRSTRLEN      (128)
-#define MAX_RX_PACKET       (CC3000_RX_BUFFER_SIZE-CC3000_MINIMAL_RX_SIZE-1)
-#define MAX_TX_PACKET       (CC3000_TX_BUFFER_SIZE-CC3000_MINIMAL_TX_SIZE-1)
+#define MAX_RX_PACKET       (CC3000_RX_BUFFER_SIZE - CC3000_MINIMAL_RX_SIZE - 1)
+#define MAX_TX_PACKET       (CC3000_TX_BUFFER_SIZE - CC3000_MINIMAL_TX_SIZE - 1)
 
 #define MAKE_SOCKADDR(addr, ip, port) \
     sockaddr addr; \
@@ -115,7 +115,7 @@
 STATIC int cc3k_gethostbyname(mp_obj_t nic, const char *name, mp_uint_t len, uint8_t *out_ip) {
     uint32_t ip;
     // CC3000 gethostbyname is unreliable and usually returns -95 on first call
-    for (int retry = 5; CC3000_EXPORT(gethostbyname)((char*)name, len, &ip) < 0; retry--) {
+    for (int retry = 5; CC3000_EXPORT(gethostbyname)((char *)name, len, &ip) < 0; retry--) {
         if (retry == 0 || CC3000_EXPORT(errno) != -95) {
             return CC3000_EXPORT(errno);
         }
@@ -143,10 +143,18 @@
 
     mp_uint_t type;
     switch (socket->u_param.type) {
-        case MOD_NETWORK_SOCK_STREAM: type = SOCK_STREAM; break;
-        case MOD_NETWORK_SOCK_DGRAM: type = SOCK_DGRAM; break;
-        case MOD_NETWORK_SOCK_RAW: type = SOCK_RAW; break;
-        default: *_errno = MP_EINVAL; return -1;
+        case MOD_NETWORK_SOCK_STREAM:
+            type = SOCK_STREAM;
+            break;
+        case MOD_NETWORK_SOCK_DGRAM:
+            type = SOCK_DGRAM;
+            break;
+        case MOD_NETWORK_SOCK_RAW:
+            type = SOCK_RAW;
+            break;
+        default:
+            *_errno = MP_EINVAL;
+            return -1;
     }
 
     // open socket
@@ -247,7 +255,7 @@
     mp_int_t bytes = 0;
     while (bytes < len) {
         int n = MIN((len - bytes), MAX_TX_PACKET);
-        n = CC3000_EXPORT(send)(socket->u_state, (uint8_t*)buf + bytes, n, 0);
+        n = CC3000_EXPORT(send)(socket->u_state, (uint8_t *)buf + bytes, n, 0);
         if (n <= 0) {
             *_errno = CC3000_EXPORT(errno);
             return -1;
@@ -291,7 +299,7 @@
 
 STATIC mp_uint_t cc3k_socket_sendto(mod_network_socket_obj_t *socket, const byte *buf, mp_uint_t len, byte *ip, mp_uint_t port, int *_errno) {
     MAKE_SOCKADDR(addr, ip, port)
-    int ret = CC3000_EXPORT(sendto)(socket->u_state, (byte*)buf, len, 0, (sockaddr*)&addr, sizeof(addr));
+    int ret = CC3000_EXPORT(sendto)(socket->u_state, (byte *)buf, len, 0, (sockaddr *)&addr, sizeof(addr));
     if (ret < 0) {
         *_errno = CC3000_EXPORT(errno);
         return -1;
@@ -416,7 +424,7 @@
     mp_obj_base_t base;
 } cc3k_obj_t;
 
-STATIC const cc3k_obj_t cc3k_obj = {{(mp_obj_type_t*)&mod_network_nic_type_cc3k}};
+STATIC const cc3k_obj_t cc3k_obj = {{(mp_obj_type_t *)&mod_network_nic_type_cc3k}};
 
 // \classmethod \constructor(spi, pin_cs, pin_en, pin_irq)
 // Initialise the CC3000 using the given SPI bus and pins and return a CC3K object.
@@ -436,11 +444,11 @@
         pin_find(args[1]),
         pin_find(args[2]),
         pin_find(args[3])
-    );
+        );
 
     // initialize and start the module
     wlan_init(cc3k_callback, NULL, NULL, NULL,
-            ReadWlanInterruptPin, SpiResumeSpi, SpiPauseSpi, WriteWlanPin);
+        ReadWlanInterruptPin, SpiResumeSpi, SpiPauseSpi, WriteWlanPin);
 
     if (wlan_start(0) != 0) {
         mp_raise_msg(&mp_type_OSError, "failed to init CC3000 module");
@@ -450,10 +458,10 @@
     // wlan_ioctl_set_connection_policy(0, 0, 0);
 
     // Mask out all non-required events from the CC3000
-    wlan_set_event_mask(HCI_EVNT_WLAN_KEEPALIVE|
-                        HCI_EVNT_WLAN_UNSOL_INIT|
-                        HCI_EVNT_WLAN_ASYNC_PING_REPORT|
-                        HCI_EVNT_WLAN_ASYNC_SIMPLE_CONFIG_DONE);
+    wlan_set_event_mask(HCI_EVNT_WLAN_KEEPALIVE |
+        HCI_EVNT_WLAN_UNSOL_INIT |
+        HCI_EVNT_WLAN_ASYNC_PING_REPORT |
+        HCI_EVNT_WLAN_ASYNC_SIMPLE_CONFIG_DONE);
 
     // register with network module
     mod_network_register_nic((mp_obj_t)&cc3k_obj);
@@ -494,7 +502,7 @@
     }
 
     // connect to AP
-    if (wlan_connect(sec, (char*)ssid, ssid_len, (uint8_t*)bssid, (uint8_t*)key, key_len) != 0) {
+    if (wlan_connect(sec, (char *)ssid, ssid_len, (uint8_t *)bssid, (uint8_t *)key, key_len) != 0) {
         mp_raise_msg_varg(&mp_type_OSError, "could not connect to ssid=%s, sec=%d, key=%s\n", ssid, sec, key);
     }
 
@@ -531,7 +539,7 @@
         netutils_format_ipv4_addr(ipconfig.aucDNSServer, NETUTILS_LITTLE),
         netutils_format_ipv4_addr(ipconfig.aucDHCPServer, NETUTILS_LITTLE),
         mp_obj_new_str(mac_vstr.buf, mac_vstr.len),
-        mp_obj_new_str((const char*)ipconfig.uaSSID, strlen((const char*)ipconfig.uaSSID)),
+        mp_obj_new_str((const char *)ipconfig.uaSSID, strlen((const char *)ipconfig.uaSSID)),
     };
     return mp_obj_new_tuple(MP_ARRAY_SIZE(tuple), tuple);
 }
@@ -581,7 +589,7 @@
         { &mp_type_type },
         .name = MP_QSTR_CC3K,
         .make_new = cc3k_make_new,
-        .locals_dict = (mp_obj_dict_t*)&cc3k_locals_dict,
+        .locals_dict = (mp_obj_dict_t *)&cc3k_locals_dict,
     },
     .gethostbyname = cc3k_gethostbyname,
     .socket = cc3k_socket_socket,
diff --git a/ports/stm32/modnwwiznet5k.c b/ports/stm32/modnwwiznet5k.c
index bf4b72f..db7bc8b 100644
--- a/ports/stm32/modnwwiznet5k.c
+++ b/ports/stm32/modnwwiznet5k.c
@@ -79,7 +79,7 @@
 }
 
 STATIC void wiz_spi_write(const uint8_t *buf, uint32_t len) {
-    HAL_StatusTypeDef status = HAL_SPI_Transmit(wiznet5k_obj.spi->spi, (uint8_t*)buf, len, 5000);
+    HAL_StatusTypeDef status = HAL_SPI_Transmit(wiznet5k_obj.spi->spi, (uint8_t *)buf, len, 5000);
     (void)status;
 }
 
@@ -87,7 +87,7 @@
     uint8_t dns_ip[MOD_NETWORK_IPADDR_BUF_SIZE] = {8, 8, 8, 8};
     uint8_t *buf = m_new(uint8_t, MAX_DNS_BUF_SIZE);
     DNS_init(0, buf);
-    mp_int_t ret = DNS_run(dns_ip, (uint8_t*)name, out_ip);
+    mp_int_t ret = DNS_run(dns_ip, (uint8_t *)name, out_ip);
     m_del(uint8_t, buf, MAX_DNS_BUF_SIZE);
     if (ret == 1) {
         // success
@@ -105,9 +105,15 @@
     }
 
     switch (socket->u_param.type) {
-        case MOD_NETWORK_SOCK_STREAM: socket->u_param.type = Sn_MR_TCP; break;
-        case MOD_NETWORK_SOCK_DGRAM: socket->u_param.type = Sn_MR_UDP; break;
-        default: *_errno = MP_EINVAL; return -1;
+        case MOD_NETWORK_SOCK_STREAM:
+            socket->u_param.type = Sn_MR_TCP;
+            break;
+        case MOD_NETWORK_SOCK_DGRAM:
+            socket->u_param.type = Sn_MR_UDP;
+            break;
+        default:
+            *_errno = MP_EINVAL;
+            return -1;
     }
 
     if (socket->u_param.fileno == -1) {
@@ -226,7 +232,7 @@
 
 STATIC mp_uint_t wiznet5k_socket_send(mod_network_socket_obj_t *socket, const byte *buf, mp_uint_t len, int *_errno) {
     MP_THREAD_GIL_EXIT();
-    mp_int_t ret = WIZCHIP_EXPORT(send)(socket->u_param.fileno, (byte*)buf, len);
+    mp_int_t ret = WIZCHIP_EXPORT(send)(socket->u_param.fileno, (byte *)buf, len);
     MP_THREAD_GIL_ENTER();
 
     // TODO convert Wiz errno's to POSIX ones
@@ -261,7 +267,7 @@
     }
 
     MP_THREAD_GIL_EXIT();
-    mp_int_t ret = WIZCHIP_EXPORT(sendto)(socket->u_param.fileno, (byte*)buf, len, ip, port);
+    mp_int_t ret = WIZCHIP_EXPORT(sendto)(socket->u_param.fileno, (byte *)buf, len, ip, port);
     MP_THREAD_GIL_ENTER();
 
     if (ret < 0) {
@@ -344,7 +350,7 @@
     mp_arg_check_num(n_args, n_kw, 3, 3, false);
 
     // init the wiznet5k object
-    wiznet5k_obj.base.type = (mp_obj_type_t*)&mod_network_nic_type_wiznet5k;
+    wiznet5k_obj.base.type = (mp_obj_type_t *)&mod_network_nic_type_wiznet5k;
     wiznet5k_obj.cris_state = 0;
     wiznet5k_obj.spi = spi_from_mp_obj(args[0]);
     wiznet5k_obj.cs = pin_find(args[1]);
@@ -390,7 +396,7 @@
         .dns = {8, 8, 8, 8}, // Google public DNS
         .dhcp = NETINFO_STATIC,
     };
-    ctlnetwork(CN_SET_NETINFO, (void*)&netinfo);
+    ctlnetwork(CN_SET_NETINFO, (void *)&netinfo);
 
     // seems we need a small delay after init
     mp_hal_delay_ms(250);
@@ -484,7 +490,7 @@
         { &mp_type_type },
         .name = MP_QSTR_WIZNET5K,
         .make_new = wiznet5k_make_new,
-        .locals_dict = (mp_obj_dict_t*)&wiznet5k_locals_dict,
+        .locals_dict = (mp_obj_dict_t *)&wiznet5k_locals_dict,
     },
     .gethostbyname = wiznet5k_gethostbyname,
     .socket = wiznet5k_socket_socket,
diff --git a/ports/stm32/modpyb.c b/ports/stm32/modpyb.c
index 6dbfb1e..dd24798 100644
--- a/ports/stm32/modpyb.c
+++ b/ports/stm32/modpyb.c
@@ -194,74 +194,74 @@
 
     { MP_ROM_QSTR(MP_QSTR_Timer), MP_ROM_PTR(&pyb_timer_type) },
 
-#if MICROPY_HW_ENABLE_RNG
+    #if MICROPY_HW_ENABLE_RNG
     { MP_ROM_QSTR(MP_QSTR_rng), MP_ROM_PTR(&pyb_rng_get_obj) },
-#endif
+    #endif
 
-#if MICROPY_HW_ENABLE_RTC
+    #if MICROPY_HW_ENABLE_RTC
     { MP_ROM_QSTR(MP_QSTR_RTC), MP_ROM_PTR(&pyb_rtc_type) },
-#endif
+    #endif
 
     { MP_ROM_QSTR(MP_QSTR_Pin), MP_ROM_PTR(&pin_type) },
     { MP_ROM_QSTR(MP_QSTR_ExtInt), MP_ROM_PTR(&extint_type) },
 
-#if MICROPY_HW_ENABLE_SERVO
+    #if MICROPY_HW_ENABLE_SERVO
     { MP_ROM_QSTR(MP_QSTR_pwm), MP_ROM_PTR(&pyb_pwm_set_obj) },
     { MP_ROM_QSTR(MP_QSTR_servo), MP_ROM_PTR(&pyb_servo_set_obj) },
     { MP_ROM_QSTR(MP_QSTR_Servo), MP_ROM_PTR(&pyb_servo_type) },
-#endif
+    #endif
 
-#if MICROPY_HW_HAS_SWITCH
+    #if MICROPY_HW_HAS_SWITCH
     { MP_ROM_QSTR(MP_QSTR_Switch), MP_ROM_PTR(&pyb_switch_type) },
-#endif
+    #endif
 
-#if MICROPY_HW_HAS_FLASH
+    #if MICROPY_HW_HAS_FLASH
     { MP_ROM_QSTR(MP_QSTR_Flash), MP_ROM_PTR(&pyb_flash_type) },
-#endif
+    #endif
 
-#if MICROPY_HW_ENABLE_SDCARD
+    #if MICROPY_HW_ENABLE_SDCARD
     #if MICROPY_PY_PYB_LEGACY
     { MP_ROM_QSTR(MP_QSTR_SD), MP_ROM_PTR(&pyb_sdcard_obj) }, // now obsolete
     #endif
     { MP_ROM_QSTR(MP_QSTR_SDCard), MP_ROM_PTR(&pyb_sdcard_type) },
-#endif
+    #endif
     #if MICROPY_HW_ENABLE_MMCARD
     { MP_ROM_QSTR(MP_QSTR_MMCard), MP_ROM_PTR(&pyb_mmcard_type) },
     #endif
 
-#if defined(MICROPY_HW_LED1)
+    #if defined(MICROPY_HW_LED1)
     { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pyb_led_type) },
-#endif
+    #endif
     #if MICROPY_PY_PYB_LEGACY && MICROPY_HW_ENABLE_HW_I2C
     { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&pyb_i2c_type) },
     #endif
     { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&pyb_spi_type) },
     { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&pyb_uart_type) },
-#if MICROPY_HW_ENABLE_CAN
+    #if MICROPY_HW_ENABLE_CAN
     { MP_ROM_QSTR(MP_QSTR_CAN), MP_ROM_PTR(&pyb_can_type) },
-#endif
+    #endif
 
     #if MICROPY_HW_ENABLE_ADC
     { MP_ROM_QSTR(MP_QSTR_ADC), MP_ROM_PTR(&pyb_adc_type) },
     { MP_ROM_QSTR(MP_QSTR_ADCAll), MP_ROM_PTR(&pyb_adc_all_type) },
     #endif
 
-#if MICROPY_HW_ENABLE_DAC
+    #if MICROPY_HW_ENABLE_DAC
     { MP_ROM_QSTR(MP_QSTR_DAC), MP_ROM_PTR(&pyb_dac_type) },
-#endif
+    #endif
 
-#if MICROPY_HW_HAS_MMA7660 || MICROPY_HW_HAS_KXTJ3
+    #if MICROPY_HW_HAS_MMA7660 || MICROPY_HW_HAS_KXTJ3
     { MP_ROM_QSTR(MP_QSTR_Accel), MP_ROM_PTR(&pyb_accel_type) },
-#endif
+    #endif
 
-#if MICROPY_HW_HAS_LCD
+    #if MICROPY_HW_HAS_LCD
     { MP_ROM_QSTR(MP_QSTR_LCD), MP_ROM_PTR(&pyb_lcd_type) },
-#endif
+    #endif
 };
 
 STATIC MP_DEFINE_CONST_DICT(pyb_module_globals, pyb_module_globals_table);
 
 const mp_obj_module_t pyb_module = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&pyb_module_globals,
+    .globals = (mp_obj_dict_t *)&pyb_module_globals,
 };
diff --git a/ports/stm32/modstm.c b/ports/stm32/modstm.c
index 3fae3a5..418b8bd 100644
--- a/ports/stm32/modstm.c
+++ b/ports/stm32/modstm.c
@@ -43,14 +43,14 @@
     { MP_ROM_QSTR(MP_QSTR_mem16), MP_ROM_PTR(&machine_mem16_obj) },
     { MP_ROM_QSTR(MP_QSTR_mem32), MP_ROM_PTR(&machine_mem32_obj) },
 
-#include "genhdr/modstm_const.h"
+    #include "genhdr/modstm_const.h"
 };
 
 STATIC MP_DEFINE_CONST_DICT(stm_module_globals, stm_module_globals_table);
 
 const mp_obj_module_t stm_module = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&stm_module_globals,
+    .globals = (mp_obj_dict_t *)&stm_module_globals,
 };
 
 #endif // MICROPY_PY_STM
diff --git a/ports/stm32/moduos.c b/ports/stm32/moduos.c
index cafe2fe..6f9740c 100644
--- a/ports/stm32/moduos.c
+++ b/ports/stm32/moduos.c
@@ -74,7 +74,7 @@
     MP_ROM_PTR(&os_uname_info_release_obj),
     MP_ROM_PTR(&os_uname_info_version_obj),
     MP_ROM_PTR(&os_uname_info_machine_obj)
-);
+    );
 
 STATIC mp_obj_t os_uname(void) {
     return MP_OBJ_FROM_PTR(&os_uname_info_obj);
@@ -113,10 +113,10 @@
 bool mp_uos_dupterm_is_builtin_stream(mp_const_obj_t stream) {
     const mp_obj_type_t *type = mp_obj_get_type(stream);
     return type == &pyb_uart_type
-        #if MICROPY_HW_ENABLE_USB
-        || type == &pyb_usb_vcp_type
-        #endif
-        ;
+           #if MICROPY_HW_ENABLE_USB
+           || type == &pyb_usb_vcp_type
+           #endif
+    ;
 }
 
 STATIC mp_obj_t uos_dupterm(size_t n_args, const mp_obj_t *args) {
@@ -164,9 +164,9 @@
     /// \constant sep - separation character used in paths
     { MP_ROM_QSTR(MP_QSTR_sep), MP_ROM_QSTR(MP_QSTR__slash_) },
 
-#if MICROPY_HW_ENABLE_RNG
+    #if MICROPY_HW_ENABLE_RNG
     { MP_ROM_QSTR(MP_QSTR_urandom), MP_ROM_PTR(&os_urandom_obj) },
-#endif
+    #endif
 
     // these are MicroPython extensions
     { MP_ROM_QSTR(MP_QSTR_dupterm), MP_ROM_PTR(&uos_dupterm_obj) },
@@ -187,5 +187,5 @@
 
 const mp_obj_module_t mp_module_uos = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&os_module_globals,
+    .globals = (mp_obj_dict_t *)&os_module_globals,
 };
diff --git a/ports/stm32/modusocket.c b/ports/stm32/modusocket.c
index 9af6e37..b7cb337 100644
--- a/ports/stm32/modusocket.c
+++ b/ports/stm32/modusocket.c
@@ -71,7 +71,7 @@
     if (self->nic == MP_OBJ_NULL) {
         // select NIC based on IP
         self->nic = mod_network_find_nic(ip);
-        self->nic_type = (mod_network_nic_type_t*)mp_obj_get_type(self->nic);
+        self->nic_type = (mod_network_nic_type_t *)mp_obj_get_type(self->nic);
 
         // call the NIC to open the socket
         int _errno;
@@ -208,7 +208,7 @@
     vstr_t vstr;
     vstr_init_len(&vstr, len);
     int _errno;
-    mp_uint_t ret = self->nic_type->recv(self, (byte*)vstr.buf, len, &_errno);
+    mp_uint_t ret = self->nic_type->recv(self, (byte *)vstr.buf, len, &_errno);
     if (ret == -1) {
         mp_raise_OSError(_errno);
     }
@@ -258,7 +258,7 @@
     byte ip[4];
     mp_uint_t port;
     int _errno;
-    mp_int_t ret = self->nic_type->recvfrom(self, (byte*)vstr.buf, vstr.len, ip, &port, &_errno);
+    mp_int_t ret = self->nic_type->recvfrom(self, (byte *)vstr.buf, vstr.len, ip, &port, &_errno);
     if (ret == -1) {
         mp_raise_OSError(_errno);
     }
@@ -389,7 +389,7 @@
     .name = MP_QSTR_socket,
     .make_new = socket_make_new,
     .protocol = &socket_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&socket_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&socket_locals_dict,
 };
 
 /******************************************************************************/
@@ -419,7 +419,7 @@
         // find a NIC that can do a name lookup
         for (mp_uint_t i = 0; i < MP_STATE_PORT(mod_network_nic_list).len; i++) {
             mp_obj_t nic = MP_STATE_PORT(mod_network_nic_list).items[i];
-            mod_network_nic_type_t *nic_type = (mod_network_nic_type_t*)mp_obj_get_type(nic);
+            mod_network_nic_type_t *nic_type = (mod_network_nic_type_t *)mp_obj_get_type(nic);
             if (nic_type->gethostbyname != NULL) {
                 int ret = nic_type->gethostbyname(nic, host, hlen, out_ip);
                 if (ret != 0) {
@@ -441,7 +441,7 @@
     tuple->items[2] = MP_OBJ_NEW_SMALL_INT(0);
     tuple->items[3] = MP_OBJ_NEW_QSTR(MP_QSTR_);
     tuple->items[4] = netutils_format_inet_addr(out_ip, port, NETUTILS_BIG);
-    return mp_obj_new_list(1, (mp_obj_t*)&tuple);
+    return mp_obj_new_list(1, (mp_obj_t *)&tuple);
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_usocket_getaddrinfo_obj, mod_usocket_getaddrinfo);
 
@@ -474,7 +474,7 @@
 
 const mp_obj_module_t mp_module_usocket = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_usocket_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_usocket_globals,
 };
 
 #endif // MICROPY_PY_USOCKET && !MICROPY_PY_LWIP
diff --git a/ports/stm32/modutime.c b/ports/stm32/modutime.c
index 695e6cf..54758de 100644
--- a/ports/stm32/modutime.c
+++ b/ports/stm32/modutime.c
@@ -110,8 +110,8 @@
     }
 
     return mp_obj_new_int_from_uint(timeutils_mktime(mp_obj_get_int(elem[0]),
-            mp_obj_get_int(elem[1]), mp_obj_get_int(elem[2]), mp_obj_get_int(elem[3]),
-            mp_obj_get_int(elem[4]), mp_obj_get_int(elem[5])));
+        mp_obj_get_int(elem[1]), mp_obj_get_int(elem[2]), mp_obj_get_int(elem[3]),
+        mp_obj_get_int(elem[4]), mp_obj_get_int(elem[5])));
 }
 MP_DEFINE_CONST_FUN_OBJ_1(time_mktime_obj, time_mktime);
 
@@ -149,5 +149,5 @@
 
 const mp_obj_module_t mp_module_utime = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&time_module_globals,
+    .globals = (mp_obj_dict_t *)&time_module_globals,
 };
diff --git a/ports/stm32/mpconfigboard_common.h b/ports/stm32/mpconfigboard_common.h
index ce5c715..127696b 100644
--- a/ports/stm32/mpconfigboard_common.h
+++ b/ports/stm32/mpconfigboard_common.h
@@ -314,11 +314,11 @@
 // D-cache clean/invalidate helpers
 #if __DCACHE_PRESENT == 1
 #define MP_HAL_CLEANINVALIDATE_DCACHE(addr, size) \
-    (SCB_CleanInvalidateDCache_by_Addr((uint32_t*)((uint32_t)addr & ~0x1f), \
-        ((uint32_t)((uint8_t*)addr + size + 0x1f) & ~0x1f) - ((uint32_t)addr & ~0x1f)))
+    (SCB_CleanInvalidateDCache_by_Addr((uint32_t *)((uint32_t)addr & ~0x1f), \
+    ((uint32_t)((uint8_t *)addr + size + 0x1f) & ~0x1f) - ((uint32_t)addr & ~0x1f)))
 #define MP_HAL_CLEAN_DCACHE(addr, size) \
-    (SCB_CleanDCache_by_Addr((uint32_t*)((uint32_t)addr & ~0x1f), \
-        ((uint32_t)((uint8_t*)addr + size + 0x1f) & ~0x1f) - ((uint32_t)addr & ~0x1f)))
+    (SCB_CleanDCache_by_Addr((uint32_t *)((uint32_t)addr & ~0x1f), \
+    ((uint32_t)((uint8_t *)addr + size + 0x1f) & ~0x1f) - ((uint32_t)addr & ~0x1f)))
 #else
 #define MP_HAL_CLEANINVALIDATE_DCACHE(addr, size)
 #define MP_HAL_CLEAN_DCACHE(addr, size)
diff --git a/ports/stm32/mpconfigport.h b/ports/stm32/mpconfigport.h
index 4e9118e..ada4ce5 100644
--- a/ports/stm32/mpconfigport.h
+++ b/ports/stm32/mpconfigport.h
@@ -301,11 +301,11 @@
     mp_obj_list_t mod_network_nic_list; \
     \
     MICROPY_PORT_ROOT_POINTER_MBEDTLS \
-    MICROPY_PORT_ROOT_POINTER_BLUETOOTH_NIMBLE \
+        MICROPY_PORT_ROOT_POINTER_BLUETOOTH_NIMBLE \
 
 // type definitions for the specific machine
 
-#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((uint32_t)(p) | 1))
+#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((uint32_t)(p) | 1))
 
 #define MP_SSIZE_MAX (0x7fffffff)
 
diff --git a/ports/stm32/mphalport.c b/ports/stm32/mphalport.c
index c8d83be..0e40911 100644
--- a/ports/stm32/mphalport.c
+++ b/ports/stm32/mphalport.c
@@ -33,15 +33,15 @@
 
 MP_WEAK int mp_hal_stdin_rx_chr(void) {
     for (;;) {
-#if 0
-#ifdef USE_HOST_MODE
+        #if 0
+        #ifdef USE_HOST_MODE
         pyb_usb_host_process();
         int c = pyb_usb_host_get_keyboard();
         if (c != 0) {
             return c;
         }
-#endif
-#endif
+        #endif
+        #endif
         if (MP_STATE_PORT(pyb_stdio_uart) != NULL && uart_rx_any(MP_STATE_PORT(pyb_stdio_uart))) {
             return uart_rx_char(MP_STATE_PORT(pyb_stdio_uart));
         }
@@ -61,9 +61,9 @@
     if (MP_STATE_PORT(pyb_stdio_uart) != NULL) {
         uart_tx_strn(MP_STATE_PORT(pyb_stdio_uart), str, len);
     }
-#if 0 && defined(USE_HOST_MODE) && MICROPY_HW_HAS_LCD
+    #if 0 && defined(USE_HOST_MODE) && MICROPY_HW_HAS_LCD
     lcd_print_strn(str, len);
-#endif
+    #endif
     mp_uos_dupterm_tx_strn(str, len);
 }
 
diff --git a/ports/stm32/mphalport.h b/ports/stm32/mphalport.h
index ce3c51f..fe9378a 100644
--- a/ports/stm32/mphalport.h
+++ b/ports/stm32/mphalport.h
@@ -57,7 +57,7 @@
 #define MP_HAL_PIN_SPEED_HIGH           (GPIO_SPEED_FREQ_HIGH)
 #define MP_HAL_PIN_SPEED_VERY_HIGH      (GPIO_SPEED_FREQ_VERY_HIGH)
 
-#define mp_hal_pin_obj_t const pin_obj_t*
+#define mp_hal_pin_obj_t const pin_obj_t *
 #define mp_hal_get_pin_obj(o)   pin_find(o)
 #define mp_hal_pin_name(p)      ((p)->name)
 #define mp_hal_pin_input(p)     mp_hal_pin_config((p), MP_HAL_PIN_MODE_INPUT, MP_HAL_PIN_PULL_NONE, 0)
diff --git a/ports/stm32/mpthreadport.c b/ports/stm32/mpthreadport.c
index 4e1ebf0..48c2c3b 100644
--- a/ports/stm32/mpthreadport.c
+++ b/ports/stm32/mpthreadport.c
@@ -44,7 +44,7 @@
 void mp_thread_gc_others(void) {
     mp_thread_mutex_lock(&thread_mutex, 1);
     for (pyb_thread_t *th = pyb_thread_all; th != NULL; th = th->all_next) {
-        gc_collect_root((void**)&th, 1);
+        gc_collect_root((void **)&th, 1);
         gc_collect_root(&th->arg, 1);
         gc_collect_root(&th->stack, 1);
         if (th != pyb_thread_cur) {
@@ -54,7 +54,7 @@
     mp_thread_mutex_unlock(&thread_mutex);
 }
 
-void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size) {
+void mp_thread_create(void *(*entry)(void *), void *arg, size_t *stack_size) {
     if (*stack_size == 0) {
         *stack_size = 4096; // default stack size
     } else if (*stack_size < 2048) {
diff --git a/ports/stm32/mpu.h b/ports/stm32/mpu.h
index 74ba814..ff51f38 100644
--- a/ports/stm32/mpu.h
+++ b/ports/stm32/mpu.h
@@ -36,39 +36,39 @@
 #define MPU_REGION_SDRAM2   (MPU_REGION_NUMBER5)
 
 #define MPU_CONFIG_DISABLE(srd, size) ( \
-    MPU_INSTRUCTION_ACCESS_DISABLE  << MPU_RASR_XN_Pos \
-    | MPU_REGION_NO_ACCESS          << MPU_RASR_AP_Pos \
-    | MPU_TEX_LEVEL0                << MPU_RASR_TEX_Pos \
-    | MPU_ACCESS_NOT_SHAREABLE      << MPU_RASR_S_Pos \
-    | MPU_ACCESS_NOT_CACHEABLE      << MPU_RASR_C_Pos \
-    | MPU_ACCESS_NOT_BUFFERABLE     << MPU_RASR_B_Pos \
-    | (srd)                         << MPU_RASR_SRD_Pos \
-    | (size)                        << MPU_RASR_SIZE_Pos \
-    | MPU_REGION_ENABLE             << MPU_RASR_ENABLE_Pos \
+    MPU_INSTRUCTION_ACCESS_DISABLE << MPU_RASR_XN_Pos \
+        | MPU_REGION_NO_ACCESS << MPU_RASR_AP_Pos \
+        | MPU_TEX_LEVEL0 << MPU_RASR_TEX_Pos \
+        | MPU_ACCESS_NOT_SHAREABLE << MPU_RASR_S_Pos \
+        | MPU_ACCESS_NOT_CACHEABLE << MPU_RASR_C_Pos \
+        | MPU_ACCESS_NOT_BUFFERABLE << MPU_RASR_B_Pos \
+        | (srd) << MPU_RASR_SRD_Pos \
+        | (size) << MPU_RASR_SIZE_Pos \
+        | MPU_REGION_ENABLE << MPU_RASR_ENABLE_Pos \
     )
 
 #define MPU_CONFIG_ETH(size) ( \
-    MPU_INSTRUCTION_ACCESS_DISABLE  << MPU_RASR_XN_Pos \
-    | MPU_REGION_FULL_ACCESS        << MPU_RASR_AP_Pos \
-    | MPU_TEX_LEVEL1                << MPU_RASR_TEX_Pos \
-    | MPU_ACCESS_SHAREABLE          << MPU_RASR_S_Pos \
-    | MPU_ACCESS_NOT_CACHEABLE      << MPU_RASR_C_Pos \
-    | MPU_ACCESS_NOT_BUFFERABLE     << MPU_RASR_B_Pos \
-    | 0x00                          << MPU_RASR_SRD_Pos \
-    | (size)                        << MPU_RASR_SIZE_Pos \
-    | MPU_REGION_ENABLE             << MPU_RASR_ENABLE_Pos \
+    MPU_INSTRUCTION_ACCESS_DISABLE << MPU_RASR_XN_Pos \
+        | MPU_REGION_FULL_ACCESS << MPU_RASR_AP_Pos \
+        | MPU_TEX_LEVEL1 << MPU_RASR_TEX_Pos \
+        | MPU_ACCESS_SHAREABLE << MPU_RASR_S_Pos \
+        | MPU_ACCESS_NOT_CACHEABLE << MPU_RASR_C_Pos \
+        | MPU_ACCESS_NOT_BUFFERABLE << MPU_RASR_B_Pos \
+        | 0x00 << MPU_RASR_SRD_Pos \
+        | (size) << MPU_RASR_SIZE_Pos \
+        | MPU_REGION_ENABLE << MPU_RASR_ENABLE_Pos \
     )
 
 #define MPU_CONFIG_SDRAM(size) ( \
-    MPU_INSTRUCTION_ACCESS_ENABLE   << MPU_RASR_XN_Pos \
-    | MPU_REGION_FULL_ACCESS        << MPU_RASR_AP_Pos \
-    | MPU_TEX_LEVEL1                << MPU_RASR_TEX_Pos \
-    | MPU_ACCESS_NOT_SHAREABLE      << MPU_RASR_S_Pos \
-    | MPU_ACCESS_CACHEABLE          << MPU_RASR_C_Pos \
-    | MPU_ACCESS_BUFFERABLE         << MPU_RASR_B_Pos \
-    | 0x00                          << MPU_RASR_SRD_Pos \
-    | (size)                        << MPU_RASR_SIZE_Pos \
-    | MPU_REGION_ENABLE             << MPU_RASR_ENABLE_Pos \
+    MPU_INSTRUCTION_ACCESS_ENABLE << MPU_RASR_XN_Pos \
+        | MPU_REGION_FULL_ACCESS << MPU_RASR_AP_Pos \
+        | MPU_TEX_LEVEL1 << MPU_RASR_TEX_Pos \
+        | MPU_ACCESS_NOT_SHAREABLE << MPU_RASR_S_Pos \
+        | MPU_ACCESS_CACHEABLE << MPU_RASR_C_Pos \
+        | MPU_ACCESS_BUFFERABLE << MPU_RASR_B_Pos \
+        | 0x00 << MPU_RASR_SRD_Pos \
+        | (size) << MPU_RASR_SIZE_Pos \
+        | MPU_REGION_ENABLE << MPU_RASR_ENABLE_Pos \
     )
 
 static inline void mpu_init(void) {
diff --git a/ports/stm32/network_lan.c b/ports/stm32/network_lan.c
index d89c237..8b2104a 100644
--- a/ports/stm32/network_lan.c
+++ b/ports/stm32/network_lan.c
@@ -50,7 +50,7 @@
         netif->ip_addr.addr >> 8 & 0xff,
         netif->ip_addr.addr >> 16 & 0xff,
         netif->ip_addr.addr >> 24
-    );
+        );
 }
 
 STATIC mp_obj_t network_lan_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
@@ -159,7 +159,7 @@
     .name = MP_QSTR_LAN,
     .print = network_lan_print,
     .make_new = network_lan_make_new,
-    .locals_dict = (mp_obj_dict_t*)&network_lan_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&network_lan_locals_dict,
 };
 
 #endif // defined(MICROPY_HW_ETH_MDC)
diff --git a/ports/stm32/network_wiznet5k.c b/ports/stm32/network_wiznet5k.c
index 796b555..f57f6a8 100644
--- a/ports/stm32/network_wiznet5k.c
+++ b/ports/stm32/network_wiznet5k.c
@@ -86,7 +86,7 @@
 }
 
 STATIC void wiz_spi_write(const uint8_t *buf, uint32_t len) {
-    HAL_StatusTypeDef status = HAL_SPI_Transmit(wiznet5k_obj.spi->spi, (uint8_t*)buf, len, 5000);
+    HAL_StatusTypeDef status = HAL_SPI_Transmit(wiznet5k_obj.spi->spi, (uint8_t *)buf, len, 5000);
     (void)status;
 }
 
@@ -156,7 +156,7 @@
 
 STATIC void wiznet5k_send_ethernet(wiznet5k_obj_t *self, size_t len, const uint8_t *buf) {
     uint8_t ip[4] = {1, 1, 1, 1}; // dummy
-    int ret = WIZCHIP_EXPORT(sendto)(0, (byte*)buf, len, ip, 11); // dummy port
+    int ret = WIZCHIP_EXPORT(sendto)(0, (byte *)buf, len, ip, 11); // dummy port
     if (ret != len) {
         printf("wiznet5k_send_ethernet: fatal error %d\n", ret);
         netif_set_link_down(&self->netif);
@@ -271,7 +271,7 @@
     // Access the existing object, if it has been constructed with the same hardware interface
     if (wiznet5k_obj.base.type == &mod_network_nic_type_wiznet5k) {
         if (!(wiznet5k_obj.spi == spi && wiznet5k_obj.cs == cs && wiznet5k_obj.rst == rst
-            && wiznet5k_obj.netif.flags != 0)) {
+              && wiznet5k_obj.netif.flags != 0)) {
             wiznet5k_deinit();
         }
     }
@@ -327,7 +327,7 @@
         wizphy_getphylink() == PHY_LINK_ON
         && (self->netif.flags & NETIF_FLAG_UP)
         && self->netif.ip_addr.addr != 0
-    );
+        );
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_1(wiznet5k_isconnected_obj, wiznet5k_isconnected);
 
@@ -459,7 +459,7 @@
     { &mp_type_type },
     .name = MP_QSTR_WIZNET5K,
     .make_new = wiznet5k_make_new,
-    .locals_dict = (mp_obj_dict_t*)&wiznet5k_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&wiznet5k_locals_dict,
 };
 
 #endif // MICROPY_PY_WIZNET5K && MICROPY_PY_LWIP
diff --git a/ports/stm32/nimble_hci_uart.c b/ports/stm32/nimble_hci_uart.c
index e2ba00c..1160855 100644
--- a/ports/stm32/nimble_hci_uart.c
+++ b/ports/stm32/nimble_hci_uart.c
@@ -61,7 +61,7 @@
 
 void nimble_hci_uart_tx_strn(const char *str, uint len) {
     MICROPY_PY_LWIP_ENTER
-    rfcore_ble_hci_cmd(len, (const uint8_t*)str);
+    rfcore_ble_hci_cmd(len, (const uint8_t *)str);
     MICROPY_PY_LWIP_EXIT
 }
 
diff --git a/ports/stm32/pendsv.c b/ports/stm32/pendsv.c
index 2979dc4..60b8709 100644
--- a/ports/stm32/pendsv.c
+++ b/ports/stm32/pendsv.c
@@ -180,5 +180,5 @@
         #endif
         "pendsv_object_ptr: .word pendsv_object\n"
         "nlr_jump_ptr: .word nlr_jump\n"
-    );
+        );
 }
diff --git a/ports/stm32/pin.c b/ports/stm32/pin.c
index 93b5c34..2a2228f 100644
--- a/ports/stm32/pin.c
+++ b/ports/stm32/pin.c
@@ -564,7 +564,7 @@
     { MP_ROM_QSTR(MP_QSTR_AF_OD),     MP_ROM_INT(GPIO_MODE_AF_OD) },
     { MP_ROM_QSTR(MP_QSTR_PULL_NONE), MP_ROM_INT(GPIO_NOPULL) },
 
-#include "genhdr/pins_af_const.h"
+    #include "genhdr/pins_af_const.h"
 };
 
 STATIC MP_DEFINE_CONST_DICT(pin_locals_dict, pin_locals_dict_table);
@@ -596,7 +596,7 @@
     .make_new = mp_pin_make_new,
     .call = pin_call,
     .protocol = &pin_pin_p,
-    .locals_dict = (mp_obj_dict_t*)&pin_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pin_locals_dict,
 };
 
 /// \moduleref pyb
@@ -670,5 +670,5 @@
     { &mp_type_type },
     .name = MP_QSTR_PinAF,
     .print = pin_af_obj_print,
-    .locals_dict = (mp_obj_dict_t*)&pin_af_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pin_af_locals_dict,
 };
diff --git a/ports/stm32/pin.h b/ports/stm32/pin.h
index ea57b0a..969298a 100644
--- a/ports/stm32/pin.h
+++ b/ports/stm32/pin.h
@@ -33,26 +33,26 @@
 #include "py/obj.h"
 
 typedef struct {
-  mp_obj_base_t base;
-  qstr name;
-  uint8_t idx;
-  uint8_t fn;
-  uint8_t unit;
-  uint8_t type;
-  void *reg; // The peripheral associated with this AF
+    mp_obj_base_t base;
+    qstr name;
+    uint8_t idx;
+    uint8_t fn;
+    uint8_t unit;
+    uint8_t type;
+    void *reg; // The peripheral associated with this AF
 } pin_af_obj_t;
 
 typedef struct {
-  mp_obj_base_t base;
-  qstr name;
-  uint32_t port   : 4;
-  uint32_t pin    : 5;      // Some ARM processors use 32 bits/PORT
-  uint32_t num_af : 4;
-  uint32_t adc_channel : 5; // Some ARM processors use 32 bits/PORT
-  uint32_t adc_num  : 3;    // 1 bit per ADC
-  uint32_t pin_mask;
-  pin_gpio_t *gpio;
-  const pin_af_obj_t *af;
+    mp_obj_base_t base;
+    qstr name;
+    uint32_t port   : 4;
+    uint32_t pin    : 5;    // Some ARM processors use 32 bits/PORT
+    uint32_t num_af : 4;
+    uint32_t adc_channel : 5; // Some ARM processors use 32 bits/PORT
+    uint32_t adc_num  : 3;  // 1 bit per ADC
+    uint32_t pin_mask;
+    pin_gpio_t *gpio;
+    const pin_af_obj_t *af;
 } pin_obj_t;
 
 extern const mp_obj_type_t pin_type;
@@ -62,8 +62,8 @@
 #include "genhdr/pins.h"
 
 typedef struct {
-  const char *name;
-  const pin_obj_t *pin;
+    const char *name;
+    const pin_obj_t *pin;
 } pin_named_pin_t;
 
 extern const pin_named_pin_t pin_board_pins[];
diff --git a/ports/stm32/pin_defs_stm32.h b/ports/stm32/pin_defs_stm32.h
index 739083d..33a1790 100644
--- a/ports/stm32/pin_defs_stm32.h
+++ b/ports/stm32/pin_defs_stm32.h
@@ -28,76 +28,76 @@
 // This file should only ever be #included by pin.h and not directly.
 
 enum {
-  PORT_A,
-  PORT_B,
-  PORT_C,
-  PORT_D,
-  PORT_E,
-  PORT_F,
-  PORT_G,
-  PORT_H,
-  PORT_I,
-  PORT_J,
-  PORT_K,
+    PORT_A,
+    PORT_B,
+    PORT_C,
+    PORT_D,
+    PORT_E,
+    PORT_F,
+    PORT_G,
+    PORT_H,
+    PORT_I,
+    PORT_J,
+    PORT_K,
 };
 
 // Must have matching entries in SUPPORTED_FN in boards/make-pins.py
 enum {
-  AF_FN_TIM,
-  AF_FN_I2C,
-  AF_FN_USART,
-  AF_FN_UART = AF_FN_USART,
-  AF_FN_SPI,
-  AF_FN_I2S,
-  AF_FN_SDMMC,
-  AF_FN_CAN,
+    AF_FN_TIM,
+    AF_FN_I2C,
+    AF_FN_USART,
+    AF_FN_UART = AF_FN_USART,
+    AF_FN_SPI,
+    AF_FN_I2S,
+    AF_FN_SDMMC,
+    AF_FN_CAN,
 };
 
 enum {
-  AF_PIN_TYPE_TIM_CH1 = 0,
-  AF_PIN_TYPE_TIM_CH2,
-  AF_PIN_TYPE_TIM_CH3,
-  AF_PIN_TYPE_TIM_CH4,
-  AF_PIN_TYPE_TIM_CH1N,
-  AF_PIN_TYPE_TIM_CH2N,
-  AF_PIN_TYPE_TIM_CH3N,
-  AF_PIN_TYPE_TIM_CH1_ETR,
-  AF_PIN_TYPE_TIM_ETR,
-  AF_PIN_TYPE_TIM_BKIN,
+    AF_PIN_TYPE_TIM_CH1 = 0,
+    AF_PIN_TYPE_TIM_CH2,
+    AF_PIN_TYPE_TIM_CH3,
+    AF_PIN_TYPE_TIM_CH4,
+    AF_PIN_TYPE_TIM_CH1N,
+    AF_PIN_TYPE_TIM_CH2N,
+    AF_PIN_TYPE_TIM_CH3N,
+    AF_PIN_TYPE_TIM_CH1_ETR,
+    AF_PIN_TYPE_TIM_ETR,
+    AF_PIN_TYPE_TIM_BKIN,
 
-  AF_PIN_TYPE_I2C_SDA = 0,
-  AF_PIN_TYPE_I2C_SCL,
+    AF_PIN_TYPE_I2C_SDA = 0,
+    AF_PIN_TYPE_I2C_SCL,
 
-  AF_PIN_TYPE_USART_TX = 0,
-  AF_PIN_TYPE_USART_RX,
-  AF_PIN_TYPE_USART_CTS,
-  AF_PIN_TYPE_USART_RTS,
-  AF_PIN_TYPE_USART_CK,
-  AF_PIN_TYPE_UART_TX  = AF_PIN_TYPE_USART_TX,
-  AF_PIN_TYPE_UART_RX  = AF_PIN_TYPE_USART_RX,
-  AF_PIN_TYPE_UART_CTS = AF_PIN_TYPE_USART_CTS,
-  AF_PIN_TYPE_UART_RTS = AF_PIN_TYPE_USART_RTS,
+    AF_PIN_TYPE_USART_TX = 0,
+    AF_PIN_TYPE_USART_RX,
+    AF_PIN_TYPE_USART_CTS,
+    AF_PIN_TYPE_USART_RTS,
+    AF_PIN_TYPE_USART_CK,
+    AF_PIN_TYPE_UART_TX  = AF_PIN_TYPE_USART_TX,
+    AF_PIN_TYPE_UART_RX  = AF_PIN_TYPE_USART_RX,
+    AF_PIN_TYPE_UART_CTS = AF_PIN_TYPE_USART_CTS,
+    AF_PIN_TYPE_UART_RTS = AF_PIN_TYPE_USART_RTS,
 
-  AF_PIN_TYPE_SPI_MOSI = 0,
-  AF_PIN_TYPE_SPI_MISO,
-  AF_PIN_TYPE_SPI_SCK,
-  AF_PIN_TYPE_SPI_NSS,
+    AF_PIN_TYPE_SPI_MOSI = 0,
+    AF_PIN_TYPE_SPI_MISO,
+    AF_PIN_TYPE_SPI_SCK,
+    AF_PIN_TYPE_SPI_NSS,
 
-  AF_PIN_TYPE_I2S_CK = 0,
-  AF_PIN_TYPE_I2S_MCK,
-  AF_PIN_TYPE_I2S_SD,
-  AF_PIN_TYPE_I2S_WS,
-  AF_PIN_TYPE_I2S_EXTSD,
+    AF_PIN_TYPE_I2S_CK = 0,
+    AF_PIN_TYPE_I2S_MCK,
+    AF_PIN_TYPE_I2S_SD,
+    AF_PIN_TYPE_I2S_WS,
+    AF_PIN_TYPE_I2S_EXTSD,
 
-  AF_PIN_TYPE_SDMMC_CK = 0,
-  AF_PIN_TYPE_SDMMC_CMD,
-  AF_PIN_TYPE_SDMMC_D0,
-  AF_PIN_TYPE_SDMMC_D1,
-  AF_PIN_TYPE_SDMMC_D2,
-  AF_PIN_TYPE_SDMMC_D3,
+    AF_PIN_TYPE_SDMMC_CK = 0,
+    AF_PIN_TYPE_SDMMC_CMD,
+    AF_PIN_TYPE_SDMMC_D0,
+    AF_PIN_TYPE_SDMMC_D1,
+    AF_PIN_TYPE_SDMMC_D2,
+    AF_PIN_TYPE_SDMMC_D3,
 
-  AF_PIN_TYPE_CAN_TX = 0,
-  AF_PIN_TYPE_CAN_RX,
+    AF_PIN_TYPE_CAN_TX = 0,
+    AF_PIN_TYPE_CAN_RX,
 };
 
 // The HAL uses a slightly different naming than we chose, so we provide
@@ -123,9 +123,9 @@
 #endif
 
 enum {
-  PIN_ADC1  = (1 << 0),
-  PIN_ADC2  = (1 << 1),
-  PIN_ADC3  = (1 << 2),
+    PIN_ADC1  = (1 << 0),
+    PIN_ADC2  = (1 << 1),
+    PIN_ADC3  = (1 << 2),
 };
 
 typedef GPIO_TypeDef pin_gpio_t;
diff --git a/ports/stm32/pin_named_pins.c b/ports/stm32/pin_named_pins.c
index 1c7e643..3a8e0f9 100644
--- a/ports/stm32/pin_named_pins.c
+++ b/ports/stm32/pin_named_pins.c
@@ -34,18 +34,18 @@
 const mp_obj_type_t pin_cpu_pins_obj_type = {
     { &mp_type_type },
     .name = MP_QSTR_cpu,
-    .locals_dict = (mp_obj_dict_t*)&pin_cpu_pins_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pin_cpu_pins_locals_dict,
 };
 
 const mp_obj_type_t pin_board_pins_obj_type = {
     { &mp_type_type },
     .name = MP_QSTR_board,
-    .locals_dict = (mp_obj_dict_t*)&pin_board_pins_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pin_board_pins_locals_dict,
 };
 
 const pin_obj_t *pin_find_named_pin(const mp_obj_dict_t *named_pins, mp_obj_t name) {
     const mp_map_t *named_map = &named_pins->map;
-    mp_map_elem_t *named_elem = mp_map_lookup((mp_map_t*)named_map, name, MP_MAP_LOOKUP);
+    mp_map_elem_t *named_elem = mp_map_lookup((mp_map_t *)named_map, name, MP_MAP_LOOKUP);
     if (named_elem != NULL && named_elem->value != MP_OBJ_NULL) {
         return MP_OBJ_TO_PTR(named_elem->value);
     }
diff --git a/ports/stm32/pin_static_af.h b/ports/stm32/pin_static_af.h
index f5f4e6f..49580a2 100644
--- a/ports/stm32/pin_static_af.h
+++ b/ports/stm32/pin_static_af.h
@@ -32,18 +32,18 @@
 
 #if 0 // Enable to test if AF's are statically compiled
 #define mp_hal_pin_config_alt_static(pin_obj, mode, pull, fn_type) \
-        mp_hal_pin_config(pin_obj, mode, pull, fn_type(pin_obj)); \
-        _Static_assert(fn_type(pin_obj) != -1, ""); \
-        _Static_assert(__builtin_constant_p(fn_type(pin_obj)) == 1, "")
+    mp_hal_pin_config(pin_obj, mode, pull, fn_type(pin_obj)); \
+    _Static_assert(fn_type(pin_obj) != -1, ""); \
+    _Static_assert(__builtin_constant_p(fn_type(pin_obj)) == 1, "")
 
 #else
 
 #define mp_hal_pin_config_alt_static(pin_obj, mode, pull, fn_type) \
-        mp_hal_pin_config(pin_obj, mode, pull, fn_type(pin_obj)) /* Overflow Error => alt func not found */
+    mp_hal_pin_config(pin_obj, mode, pull, fn_type(pin_obj))     /* Overflow Error => alt func not found */
 
 #define mp_hal_pin_config_alt_static_speed(pin_obj, mode, pull, speed, fn_type) \
-        mp_hal_pin_config(pin_obj, mode, pull, fn_type(pin_obj)); /* Overflow Error => alt func not found */ \
-        mp_hal_pin_config_speed(pin_obj, speed)
+    mp_hal_pin_config(pin_obj, mode, pull, fn_type(pin_obj));     /* Overflow Error => alt func not found */ \
+    mp_hal_pin_config_speed(pin_obj, speed)
 
 #endif
 
diff --git a/ports/stm32/powerctrl.c b/ports/stm32/powerctrl.c
index 0b26e2a..e11de8b 100644
--- a/ports/stm32/powerctrl.c
+++ b/ports/stm32/powerctrl.c
@@ -42,7 +42,7 @@
 
 // Location in RAM of bootloader state (just after the top of the stack)
 extern uint32_t _estack[];
-#define BL_STATE ((uint32_t*)&_estack)
+#define BL_STATE ((uint32_t *)&_estack)
 
 static inline void powerctrl_disable_hsi_if_unused(void) {
     #if !MICROPY_HW_CLK_USE_HSI && (defined(STM32F4) || defined(STM32F7) || defined(STM32H7))
@@ -74,7 +74,7 @@
         "msr msp, r2\n"         // get stack pointer
         "ldr r2, [r1, #4]\n"    // get address of destination
         "bx r2\n"               // branch to bootloader
-    );
+        );
 }
 
 void powerctrl_check_enter_bootloader(void) {
@@ -205,51 +205,89 @@
 
 STATIC uint32_t calc_ahb_div(uint32_t wanted_div) {
     #if defined(STM32H7)
-    if (wanted_div <= 1) { return RCC_HCLK_DIV1; }
-    else if (wanted_div <= 2) { return RCC_HCLK_DIV2; }
-    else if (wanted_div <= 4) { return RCC_HCLK_DIV4; }
-    else if (wanted_div <= 8) { return RCC_HCLK_DIV8; }
-    else if (wanted_div <= 16) { return RCC_HCLK_DIV16; }
-    else if (wanted_div <= 64) { return RCC_HCLK_DIV64; }
-    else if (wanted_div <= 128) { return RCC_HCLK_DIV128; }
-    else if (wanted_div <= 256) { return RCC_HCLK_DIV256; }
-    else { return RCC_HCLK_DIV512; }
+    if (wanted_div <= 1) {
+        return RCC_HCLK_DIV1;
+    } else if (wanted_div <= 2) {
+        return RCC_HCLK_DIV2;
+    } else if (wanted_div <= 4) {
+        return RCC_HCLK_DIV4;
+    } else if (wanted_div <= 8) {
+        return RCC_HCLK_DIV8;
+    } else if (wanted_div <= 16) {
+        return RCC_HCLK_DIV16;
+    } else if (wanted_div <= 64) {
+        return RCC_HCLK_DIV64;
+    } else if (wanted_div <= 128) {
+        return RCC_HCLK_DIV128;
+    } else if (wanted_div <= 256) {
+        return RCC_HCLK_DIV256;
+    } else {
+        return RCC_HCLK_DIV512;
+    }
     #else
-    if (wanted_div <= 1) { return RCC_SYSCLK_DIV1; }
-    else if (wanted_div <= 2) { return RCC_SYSCLK_DIV2; }
-    else if (wanted_div <= 4) { return RCC_SYSCLK_DIV4; }
-    else if (wanted_div <= 8) { return RCC_SYSCLK_DIV8; }
-    else if (wanted_div <= 16) { return RCC_SYSCLK_DIV16; }
-    else if (wanted_div <= 64) { return RCC_SYSCLK_DIV64; }
-    else if (wanted_div <= 128) { return RCC_SYSCLK_DIV128; }
-    else if (wanted_div <= 256) { return RCC_SYSCLK_DIV256; }
-    else { return RCC_SYSCLK_DIV512; }
+    if (wanted_div <= 1) {
+        return RCC_SYSCLK_DIV1;
+    } else if (wanted_div <= 2) {
+        return RCC_SYSCLK_DIV2;
+    } else if (wanted_div <= 4) {
+        return RCC_SYSCLK_DIV4;
+    } else if (wanted_div <= 8) {
+        return RCC_SYSCLK_DIV8;
+    } else if (wanted_div <= 16) {
+        return RCC_SYSCLK_DIV16;
+    } else if (wanted_div <= 64) {
+        return RCC_SYSCLK_DIV64;
+    } else if (wanted_div <= 128) {
+        return RCC_SYSCLK_DIV128;
+    } else if (wanted_div <= 256) {
+        return RCC_SYSCLK_DIV256;
+    } else {
+        return RCC_SYSCLK_DIV512;
+    }
     #endif
 }
 
 STATIC uint32_t calc_apb1_div(uint32_t wanted_div) {
     #if defined(STM32H7)
-    if (wanted_div <= 1) { return RCC_APB1_DIV1; }
-    else if (wanted_div <= 2) { return RCC_APB1_DIV2; }
-    else if (wanted_div <= 4) { return RCC_APB1_DIV4; }
-    else if (wanted_div <= 8) { return RCC_APB1_DIV8; }
-    else { return RCC_APB1_DIV16; }
+    if (wanted_div <= 1) {
+        return RCC_APB1_DIV1;
+    } else if (wanted_div <= 2) {
+        return RCC_APB1_DIV2;
+    } else if (wanted_div <= 4) {
+        return RCC_APB1_DIV4;
+    } else if (wanted_div <= 8) {
+        return RCC_APB1_DIV8;
+    } else {
+        return RCC_APB1_DIV16;
+    }
     #else
-    if (wanted_div <= 1) { return RCC_HCLK_DIV1; }
-    else if (wanted_div <= 2) { return RCC_HCLK_DIV2; }
-    else if (wanted_div <= 4) { return RCC_HCLK_DIV4; }
-    else if (wanted_div <= 8) { return RCC_HCLK_DIV8; }
-    else { return RCC_HCLK_DIV16; }
+    if (wanted_div <= 1) {
+        return RCC_HCLK_DIV1;
+    } else if (wanted_div <= 2) {
+        return RCC_HCLK_DIV2;
+    } else if (wanted_div <= 4) {
+        return RCC_HCLK_DIV4;
+    } else if (wanted_div <= 8) {
+        return RCC_HCLK_DIV8;
+    } else {
+        return RCC_HCLK_DIV16;
+    }
     #endif
 }
 
 STATIC uint32_t calc_apb2_div(uint32_t wanted_div) {
     #if defined(STM32H7)
-    if (wanted_div <= 1) { return RCC_APB2_DIV1; }
-    else if (wanted_div <= 2) { return RCC_APB2_DIV2; }
-    else if (wanted_div <= 4) { return RCC_APB2_DIV4; }
-    else if (wanted_div <= 8) { return RCC_APB2_DIV8; }
-    else { return RCC_APB2_DIV16; }
+    if (wanted_div <= 1) {
+        return RCC_APB2_DIV1;
+    } else if (wanted_div <= 2) {
+        return RCC_APB2_DIV2;
+    } else if (wanted_div <= 4) {
+        return RCC_APB2_DIV4;
+    } else if (wanted_div <= 8) {
+        return RCC_APB2_DIV8;
+    } else {
+        return RCC_APB2_DIV16;
+    }
     #else
     return calc_apb1_div(wanted_div);
     #endif
@@ -326,7 +364,7 @@
     RCC_ClkInitStruct.APB1CLKDivider = calc_apb1_div(ahb / apb1);
     RCC_ClkInitStruct.APB2CLKDivider = calc_apb2_div(ahb / apb2);
     #if defined(STM32H7)
-    RCC_ClkInitStruct.SYSCLKDivider  = RCC_SYSCLK_DIV1;
+    RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1;
     RCC_ClkInitStruct.APB3CLKDivider = RCC_APB3_DIV2;
     RCC_ClkInitStruct.APB4CLKDivider = RCC_APB4_DIV2;
     #endif
@@ -438,9 +476,9 @@
     HAL_PWREx_EnableFlashPowerDown();
     #endif
 
-    # if defined(STM32F7)
+    #if defined(STM32F7)
     HAL_PWR_EnterSTOPMode((PWR_CR1_LPDS | PWR_CR1_LPUDS | PWR_CR1_FPDS | PWR_CR1_UDEN), PWR_STOPENTRY_WFI);
-    # else
+    #else
     HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI);
     #endif
 
diff --git a/ports/stm32/powerctrlboot.c b/ports/stm32/powerctrlboot.c
index acc33f1..749cb55 100644
--- a/ports/stm32/powerctrlboot.c
+++ b/ports/stm32/powerctrlboot.c
@@ -166,10 +166,10 @@
     #define PLLR (3) // f_R = 64MHz
     RCC->PLLCFGR =
         (PLLR - 1) << RCC_PLLCFGR_PLLR_Pos | RCC_PLLCFGR_PLLREN
-        | (PLLQ - 1) << RCC_PLLCFGR_PLLQ_Pos | RCC_PLLCFGR_PLLQEN
-        | PLLN << RCC_PLLCFGR_PLLN_Pos
-        | (PLLM - 1) << RCC_PLLCFGR_PLLM_Pos
-        | 3 << RCC_PLLCFGR_PLLSRC_Pos;
+            | (PLLQ - 1) << RCC_PLLCFGR_PLLQ_Pos | RCC_PLLCFGR_PLLQEN
+            | PLLN << RCC_PLLCFGR_PLLN_Pos
+            | (PLLM - 1) << RCC_PLLCFGR_PLLM_Pos
+            | 3 << RCC_PLLCFGR_PLLSRC_Pos;
     RCC->CR |= RCC_CR_PLLON;
     while (!(RCC->CR & RCC_CR_PLLRDY)) {
         // Wait for PLL to lock
diff --git a/ports/stm32/pyb_can.c b/ports/stm32/pyb_can.c
index 2faa450..fa577e7 100644
--- a/ports/stm32/pyb_can.c
+++ b/ports/stm32/pyb_can.c
@@ -113,10 +113,19 @@
     } else {
         qstr mode;
         switch (self->can.Init.Mode) {
-            case CAN_MODE_NORMAL: mode = MP_QSTR_NORMAL; break;
-            case CAN_MODE_LOOPBACK: mode = MP_QSTR_LOOPBACK; break;
-            case CAN_MODE_SILENT: mode = MP_QSTR_SILENT; break;
-            case CAN_MODE_SILENT_LOOPBACK: default: mode = MP_QSTR_SILENT_LOOPBACK; break;
+            case CAN_MODE_NORMAL:
+                mode = MP_QSTR_NORMAL;
+                break;
+            case CAN_MODE_LOOPBACK:
+                mode = MP_QSTR_LOOPBACK;
+                break;
+            case CAN_MODE_SILENT:
+                mode = MP_QSTR_SILENT;
+                break;
+            case CAN_MODE_SILENT_LOOPBACK:
+            default:
+                mode = MP_QSTR_SILENT_LOOPBACK;
+                break;
         }
         mp_printf(print, "CAN(%u, CAN.%q, extframe=%q, auto_restart=%q)",
             self->can_id,
@@ -125,9 +134,9 @@
             #if MICROPY_HW_ENABLE_FDCAN
             (self->can.Instance->CCCR & FDCAN_CCCR_DAR) ? MP_QSTR_True : MP_QSTR_False
             #else
-            (self->can.Instance->MCR & CAN_MCR_ABOM) ? MP_QSTR_True : MP_QSTR_False
+                (self->can.Instance->MCR & CAN_MCR_ABOM) ? MP_QSTR_True : MP_QSTR_False
             #endif
-        );
+            );
     }
 }
 
@@ -135,12 +144,12 @@
 STATIC mp_obj_t pyb_can_init_helper(pyb_can_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
     enum { ARG_mode, ARG_extframe, ARG_prescaler, ARG_sjw, ARG_bs1, ARG_bs2, ARG_auto_restart };
     static const mp_arg_t allowed_args[] = {
-        { MP_QSTR_mode,         MP_ARG_REQUIRED | MP_ARG_INT,   {.u_int  = CAN_MODE_NORMAL} },
+        { MP_QSTR_mode,         MP_ARG_REQUIRED | MP_ARG_INT,   {.u_int = CAN_MODE_NORMAL} },
         { MP_QSTR_extframe,     MP_ARG_BOOL,                    {.u_bool = false} },
-        { MP_QSTR_prescaler,    MP_ARG_INT,                     {.u_int  = CAN_DEFAULT_PRESCALER} },
-        { MP_QSTR_sjw,          MP_ARG_KW_ONLY | MP_ARG_INT,    {.u_int  = CAN_DEFAULT_SJW} },
-        { MP_QSTR_bs1,          MP_ARG_KW_ONLY | MP_ARG_INT,    {.u_int  = CAN_DEFAULT_BS1} },
-        { MP_QSTR_bs2,          MP_ARG_KW_ONLY | MP_ARG_INT,    {.u_int  = CAN_DEFAULT_BS2} },
+        { MP_QSTR_prescaler,    MP_ARG_INT,                     {.u_int = CAN_DEFAULT_PRESCALER} },
+        { MP_QSTR_sjw,          MP_ARG_KW_ONLY | MP_ARG_INT,    {.u_int = CAN_DEFAULT_SJW} },
+        { MP_QSTR_bs1,          MP_ARG_KW_ONLY | MP_ARG_INT,    {.u_int = CAN_DEFAULT_BS1} },
+        { MP_QSTR_bs2,          MP_ARG_KW_ONLY | MP_ARG_INT,    {.u_int = CAN_DEFAULT_BS2} },
         { MP_QSTR_auto_restart, MP_ARG_KW_ONLY | MP_ARG_BOOL,   {.u_bool = false} },
     };
 
@@ -396,7 +405,7 @@
     }
     if (args[ARG_rtr].u_bool == false) {
         tx_msg.TxFrameType = FDCAN_DATA_FRAME;
-    } else  {
+    } else {
         tx_msg.TxFrameType = FDCAN_REMOTE_FRAME;
     }
     #else
@@ -412,13 +421,13 @@
     }
     if (args[ARG_rtr].u_bool == false) {
         tx_msg.RTR = CAN_RTR_DATA;
-    } else  {
+    } else {
         tx_msg.RTR = CAN_RTR_REMOTE;
     }
     #endif
 
     for (mp_uint_t i = 0; i < bufinfo.len; i++) {
-        tx_data[i] = ((byte*)bufinfo.buf)[i];
+        tx_data[i] = ((byte *)bufinfo.buf)[i];
     }
 
     HAL_StatusTypeDef status;
@@ -485,24 +494,24 @@
         byte *state = (fifo == CAN_FIFO0) ? &self->rx_state0 : &self->rx_state1;
 
         switch (*state) {
-        case RX_STATE_FIFO_EMPTY:
-            break;
-        case RX_STATE_MESSAGE_PENDING:
-            if (__HAL_CAN_MSG_PENDING(&self->can, fifo) == 0) {
-                // Fifo is empty
-                __HAL_CAN_ENABLE_IT(&self->can, (fifo == CAN_FIFO0) ? CAN_IT_FIFO0_PENDING : CAN_IT_FIFO1_PENDING);
-                *state = RX_STATE_FIFO_EMPTY;
-            }
-            break;
-        case RX_STATE_FIFO_FULL:
-            __HAL_CAN_ENABLE_IT(&self->can, (fifo == CAN_FIFO0) ? CAN_IT_FIFO0_FULL : CAN_IT_FIFO1_FULL);
-            *state = RX_STATE_MESSAGE_PENDING;
-            break;
-        case RX_STATE_FIFO_OVERFLOW:
-            __HAL_CAN_ENABLE_IT(&self->can, (fifo == CAN_FIFO0) ? CAN_IT_FIFO0_OVRF : CAN_IT_FIFO1_OVRF);
-            __HAL_CAN_ENABLE_IT(&self->can, (fifo == CAN_FIFO0) ? CAN_IT_FIFO0_FULL : CAN_IT_FIFO1_FULL);
-            *state = RX_STATE_MESSAGE_PENDING;
-            break;
+            case RX_STATE_FIFO_EMPTY:
+                break;
+            case RX_STATE_MESSAGE_PENDING:
+                if (__HAL_CAN_MSG_PENDING(&self->can, fifo) == 0) {
+                    // Fifo is empty
+                    __HAL_CAN_ENABLE_IT(&self->can, (fifo == CAN_FIFO0) ? CAN_IT_FIFO0_PENDING : CAN_IT_FIFO1_PENDING);
+                    *state = RX_STATE_FIFO_EMPTY;
+                }
+                break;
+            case RX_STATE_FIFO_FULL:
+                __HAL_CAN_ENABLE_IT(&self->can, (fifo == CAN_FIFO0) ? CAN_IT_FIFO0_FULL : CAN_IT_FIFO1_FULL);
+                *state = RX_STATE_MESSAGE_PENDING;
+                break;
+            case RX_STATE_FIFO_OVERFLOW:
+                __HAL_CAN_ENABLE_IT(&self->can, (fifo == CAN_FIFO0) ? CAN_IT_FIFO0_OVRF : CAN_IT_FIFO1_OVRF);
+                __HAL_CAN_ENABLE_IT(&self->can, (fifo == CAN_FIFO0) ? CAN_IT_FIFO0_FULL : CAN_IT_FIFO1_FULL);
+                *state = RX_STATE_MESSAGE_PENDING;
+                break;
         }
     }
 
@@ -512,7 +521,7 @@
     mp_obj_t *items;
     if (ret_obj == mp_const_none) {
         ret_obj = mp_obj_new_tuple(4, NULL);
-        items = ((mp_obj_tuple_t*)MP_OBJ_TO_PTR(ret_obj))->items;
+        items = ((mp_obj_tuple_t *)MP_OBJ_TO_PTR(ret_obj))->items;
         items[3] = mp_obj_new_bytes(rx_data, rx_dlc);
     } else {
         // User should provide a list of length at least 4 to hold the values
@@ -531,7 +540,7 @@
         }
         mp_obj_array_t *mv = MP_OBJ_TO_PTR(items[3]);
         if (!(mv->typecode == (MP_OBJ_ARRAY_TYPECODE_FLAG_RW | BYTEARRAY_TYPECODE)
-            || (mv->typecode | 0x20) == (MP_OBJ_ARRAY_TYPECODE_FLAG_RW | 'b'))) {
+              || (mv->typecode | 0x20) == (MP_OBJ_ARRAY_TYPECODE_FLAG_RW | 'b'))) {
             mp_raise_ValueError(NULL);
         }
         mv->len = rx_dlc;
@@ -590,7 +599,7 @@
         { MP_QSTR_mode,     MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} },
         { MP_QSTR_fifo,     MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = CAN_FILTER_FIFO0} },
         { MP_QSTR_params,   MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
-        { MP_QSTR_rtr,      MP_ARG_KW_ONLY  | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
+        { MP_QSTR_rtr,      MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
     };
 
     // parse args
@@ -606,7 +615,7 @@
 
     // Check filter mode
     if (((args[ARG_mode].u_int != FDCAN_FILTER_RANGE) &&
-         (args[ARG_mode].u_int != FDCAN_FILTER_DUAL)  &&
+         (args[ARG_mode].u_int != FDCAN_FILTER_DUAL) &&
          (args[ARG_mode].u_int != FDCAN_FILTER_MASK))) {
         goto error;
     }
@@ -639,7 +648,7 @@
     mp_obj_t *rtr_flags;
     mp_obj_t *params;
     mp_obj_get_array(args[ARG_params].u_obj, &len, &params);
-    if (args[ARG_rtr].u_obj != MP_OBJ_NULL){
+    if (args[ARG_rtr].u_obj != MP_OBJ_NULL) {
         mp_obj_get_array(args[ARG_rtr].u_obj, &rtr_len, &rtr_flags);
     }
 
@@ -663,9 +672,9 @@
                     rtr_masks[3] = mp_obj_get_int(rtr_flags[3]) ? 0x02 : 0;
                 }
             }
-            filter.FilterIdLow      = EXTENDED_ID_TO_16BIT_FILTER(mp_obj_get_int(params[0])) | rtr_masks[0]; // id1
-            filter.FilterMaskIdLow  = EXTENDED_ID_TO_16BIT_FILTER(mp_obj_get_int(params[1])) | rtr_masks[1]; // mask1
-            filter.FilterIdHigh     = EXTENDED_ID_TO_16BIT_FILTER(mp_obj_get_int(params[2])) | rtr_masks[2]; // id2
+            filter.FilterIdLow = EXTENDED_ID_TO_16BIT_FILTER(mp_obj_get_int(params[0])) | rtr_masks[0];      // id1
+            filter.FilterMaskIdLow = EXTENDED_ID_TO_16BIT_FILTER(mp_obj_get_int(params[1])) | rtr_masks[1];  // mask1
+            filter.FilterIdHigh = EXTENDED_ID_TO_16BIT_FILTER(mp_obj_get_int(params[2])) | rtr_masks[2];     // id2
             filter.FilterMaskIdHigh = EXTENDED_ID_TO_16BIT_FILTER(mp_obj_get_int(params[3])) | rtr_masks[3]; // mask2
         } else { // Basic frames
             if (args[ARG_rtr].u_obj != MP_OBJ_NULL) {
@@ -681,19 +690,18 @@
                     rtr_masks[3] = mp_obj_get_int(rtr_flags[3]) ? 0x10 : 0;
                 }
             }
-            filter.FilterIdLow      = (mp_obj_get_int(params[0]) << 5) | rtr_masks[0]; // id1
-            filter.FilterMaskIdLow  = (mp_obj_get_int(params[1]) << 5) | rtr_masks[1]; // mask1
-            filter.FilterIdHigh     = (mp_obj_get_int(params[2]) << 5) | rtr_masks[2]; // id2
+            filter.FilterIdLow = (mp_obj_get_int(params[0]) << 5) | rtr_masks[0];      // id1
+            filter.FilterMaskIdLow = (mp_obj_get_int(params[1]) << 5) | rtr_masks[1];  // mask1
+            filter.FilterIdHigh = (mp_obj_get_int(params[2]) << 5) | rtr_masks[2];     // id2
             filter.FilterMaskIdHigh = (mp_obj_get_int(params[3]) << 5) | rtr_masks[3]; // mask2
         }
         if (args[ARG_mode].u_int == MASK16) {
-            filter.FilterMode  = CAN_FILTERMODE_IDMASK;
+            filter.FilterMode = CAN_FILTERMODE_IDMASK;
         }
         if (args[ARG_mode].u_int == LIST16) {
-            filter.FilterMode  = CAN_FILTERMODE_IDLIST;
+            filter.FilterMode = CAN_FILTERMODE_IDLIST;
         }
-    }
-    else if (args[ARG_mode].u_int == MASK32 || args[ARG_mode].u_int == LIST32) {
+    } else if (args[ARG_mode].u_int == MASK32 || args[ARG_mode].u_int == LIST32) {
         if (len != 2) {
             goto error;
         }
@@ -707,15 +715,15 @@
                 rtr_masks[1] = mp_obj_get_int(rtr_flags[1]) ? 0x02 : 0;
             }
         }
-        filter.FilterIdHigh     = (mp_obj_get_int(params[0]) & 0x1FFFE000)  >> 13;
-        filter.FilterIdLow      = (((mp_obj_get_int(params[0]) & 0x00001FFF) << 3) | 4) | rtr_masks[0];
+        filter.FilterIdHigh = (mp_obj_get_int(params[0]) & 0x1FFFE000) >> 13;
+        filter.FilterIdLow = (((mp_obj_get_int(params[0]) & 0x00001FFF) << 3) | 4) | rtr_masks[0];
         filter.FilterMaskIdHigh = (mp_obj_get_int(params[1]) & 0x1FFFE000 ) >> 13;
-        filter.FilterMaskIdLow  = (((mp_obj_get_int(params[1]) & 0x00001FFF) << 3) | 4) | rtr_masks[1];
+        filter.FilterMaskIdLow = (((mp_obj_get_int(params[1]) & 0x00001FFF) << 3) | 4) | rtr_masks[1];
         if (args[ARG_mode].u_int == MASK32) {
-            filter.FilterMode  = CAN_FILTERMODE_IDMASK;
+            filter.FilterMode = CAN_FILTERMODE_IDMASK;
         }
         if (args[ARG_mode].u_int == LIST32) {
-            filter.FilterMode  = CAN_FILTERMODE_IDLIST;
+            filter.FilterMode = CAN_FILTERMODE_IDLIST;
         }
     } else {
         goto error;
@@ -895,7 +903,7 @@
     .print = pyb_can_print,
     .make_new = pyb_can_make_new,
     .protocol = &can_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&pyb_can_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_can_locals_dict,
 };
 
 #endif // MICROPY_HW_ENABLE_CAN
diff --git a/ports/stm32/pyb_i2c.c b/ports/stm32/pyb_i2c.c
index 7034897..09e5328 100644
--- a/ports/stm32/pyb_i2c.c
+++ b/ports/stm32/pyb_i2c.c
@@ -145,7 +145,7 @@
         {PYB_I2C_SPEED_STANDARD, 0x40912732}, \
         {PYB_I2C_SPEED_FULL, 0x10911823}, \
         {PYB_I2C_SPEED_FAST, 0x00611116}, \
-    }
+}
 #define MICROPY_HW_I2C_BAUDRATE_DEFAULT (PYB_I2C_SPEED_FULL)
 #define MICROPY_HW_I2C_BAUDRATE_MAX (PYB_I2C_SPEED_FAST)
 
@@ -159,7 +159,7 @@
         {PYB_I2C_SPEED_STANDARD, 0xb0420f13}, \
         {PYB_I2C_SPEED_FULL, 0x70330309}, \
         {PYB_I2C_SPEED_FAST, 0x50100103}, \
-    }
+}
 #define MICROPY_HW_I2C_BAUDRATE_DEFAULT (PYB_I2C_SPEED_FULL)
 #define MICROPY_HW_I2C_BAUDRATE_MAX (PYB_I2C_SPEED_FAST)
 
@@ -170,7 +170,7 @@
         {PYB_I2C_SPEED_STANDARD, 0x40604E73}, \
         {PYB_I2C_SPEED_FULL, 0x00901954}, \
         {PYB_I2C_SPEED_FAST, 0x10810915}, \
-    }
+}
 #define MICROPY_HW_I2C_BAUDRATE_DEFAULT (PYB_I2C_SPEED_FULL)
 #define MICROPY_HW_I2C_BAUDRATE_MAX (PYB_I2C_SPEED_FAST)
 
@@ -187,8 +187,8 @@
 #endif
 
 STATIC const struct {
-    uint32_t    baudrate;
-    uint32_t    timing;
+    uint32_t baudrate;
+    uint32_t timing;
 } pyb_i2c_baudrate_timing[] = MICROPY_HW_I2C_BAUDRATE_TIMING;
 
 #define NUM_BAUDRATE_TIMINGS MP_ARRAY_SIZE(pyb_i2c_baudrate_timing)
@@ -379,12 +379,12 @@
 void pyb_i2c_init_freq(const pyb_i2c_obj_t *self, mp_int_t freq) {
     I2C_InitTypeDef *init = &self->i2c->Init;
 
-    init->AddressingMode    = I2C_ADDRESSINGMODE_7BIT;
-    init->DualAddressMode   = I2C_DUALADDRESS_DISABLED;
-    init->GeneralCallMode   = I2C_GENERALCALL_DISABLED;
-    init->NoStretchMode     = I2C_NOSTRETCH_DISABLE;
-    init->OwnAddress1       = PYB_I2C_MASTER_ADDRESS;
-    init->OwnAddress2       = 0; // unused
+    init->AddressingMode = I2C_ADDRESSINGMODE_7BIT;
+    init->DualAddressMode = I2C_DUALADDRESS_DISABLED;
+    init->GeneralCallMode = I2C_GENERALCALL_DISABLED;
+    init->NoStretchMode = I2C_NOSTRETCH_DISABLE;
+    init->OwnAddress1 = PYB_I2C_MASTER_ADDRESS;
+    init->OwnAddress2 = 0;       // unused
     if (freq != -1) {
         i2c_set_baudrate(init, MIN(freq, MICROPY_HW_I2C_BAUDRATE_MAX));
     }
@@ -543,24 +543,35 @@
 /******************************************************************************/
 /* MicroPython bindings                                                       */
 
-static inline bool in_master_mode(pyb_i2c_obj_t *self) { return self->i2c->Init.OwnAddress1 == PYB_I2C_MASTER_ADDRESS; }
+static inline bool in_master_mode(pyb_i2c_obj_t *self) {
+    return self->i2c->Init.OwnAddress1 == PYB_I2C_MASTER_ADDRESS;
+}
 
 STATIC void pyb_i2c_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
     pyb_i2c_obj_t *self = MP_OBJ_TO_PTR(self_in);
 
     uint i2c_num = 0;
-    if (0) { }
+    if (0) {
+    }
     #if defined(MICROPY_HW_I2C1_SCL)
-    else if (self->i2c->Instance == I2C1) { i2c_num = 1; }
+    else if (self->i2c->Instance == I2C1) {
+        i2c_num = 1;
+    }
     #endif
     #if defined(MICROPY_HW_I2C2_SCL)
-    else if (self->i2c->Instance == I2C2) { i2c_num = 2; }
+    else if (self->i2c->Instance == I2C2) {
+        i2c_num = 2;
+    }
     #endif
     #if defined(MICROPY_HW_I2C3_SCL)
-    else if (self->i2c->Instance == I2C3) { i2c_num = 3; }
+    else if (self->i2c->Instance == I2C3) {
+        i2c_num = 3;
+    }
     #endif
     #if defined(MICROPY_HW_I2C4_SCL)
-    else if (self->i2c->Instance == I2C4) { i2c_num = 4; }
+    else if (self->i2c->Instance == I2C4) {
+        i2c_num = 4;
+    }
     #endif
 
     if (self->i2c->State == HAL_I2C_STATE_RESET) {
@@ -575,7 +586,7 @@
                 #if PYB_I2C_TIMINGR
                 , self->i2c->Init.Timing
                 #endif
-            );
+                );
         } else {
             mp_printf(print, "I2C(%u, I2C.SLAVE, addr=0x%02x)", i2c_num, (self->i2c->Instance->OAR1 >> 1) & 0x7f);
         }
@@ -626,11 +637,11 @@
         i2c_set_baudrate(init, MIN(args[2].u_int, MICROPY_HW_I2C_BAUDRATE_MAX));
     }
 
-    init->AddressingMode  = I2C_ADDRESSINGMODE_7BIT;
+    init->AddressingMode = I2C_ADDRESSINGMODE_7BIT;
     init->DualAddressMode = I2C_DUALADDRESS_DISABLED;
     init->GeneralCallMode = args[3].u_bool ? I2C_GENERALCALL_ENABLED : I2C_GENERALCALL_DISABLED;
-    init->OwnAddress2     = 0; // unused
-    init->NoStretchMode   = I2C_NOSTRETCH_DISABLE;
+    init->OwnAddress2 = 0;     // unused
+    init->NoStretchMode = I2C_NOSTRETCH_DISABLE;
 
     *self->use_dma = args[4].u_bool;
 
@@ -883,17 +894,17 @@
         }
         mp_uint_t i2c_addr = args[1].u_int << 1;
         if (!use_dma) {
-            status = HAL_I2C_Master_Receive(self->i2c, i2c_addr, (uint8_t*)vstr.buf, vstr.len, args[2].u_int);
+            status = HAL_I2C_Master_Receive(self->i2c, i2c_addr, (uint8_t *)vstr.buf, vstr.len, args[2].u_int);
         } else {
             MP_HAL_CLEANINVALIDATE_DCACHE(vstr.buf, vstr.len);
-            status = HAL_I2C_Master_Receive_DMA(self->i2c, i2c_addr, (uint8_t*)vstr.buf, vstr.len);
+            status = HAL_I2C_Master_Receive_DMA(self->i2c, i2c_addr, (uint8_t *)vstr.buf, vstr.len);
         }
     } else {
         if (!use_dma) {
-            status = HAL_I2C_Slave_Receive(self->i2c, (uint8_t*)vstr.buf, vstr.len, args[2].u_int);
+            status = HAL_I2C_Slave_Receive(self->i2c, (uint8_t *)vstr.buf, vstr.len, args[2].u_int);
         } else {
             MP_HAL_CLEANINVALIDATE_DCACHE(vstr.buf, vstr.len);
-            status = HAL_I2C_Slave_Receive_DMA(self->i2c, (uint8_t*)vstr.buf, vstr.len);
+            status = HAL_I2C_Slave_Receive_DMA(self->i2c, (uint8_t *)vstr.buf, vstr.len);
         }
     }
 
@@ -967,14 +978,14 @@
 
     HAL_StatusTypeDef status;
     if (!use_dma) {
-        status = HAL_I2C_Mem_Read(self->i2c, i2c_addr, mem_addr, mem_addr_size, (uint8_t*)vstr.buf, vstr.len, args[3].u_int);
+        status = HAL_I2C_Mem_Read(self->i2c, i2c_addr, mem_addr, mem_addr_size, (uint8_t *)vstr.buf, vstr.len, args[3].u_int);
     } else {
         DMA_HandleTypeDef rx_dma;
         dma_init(&rx_dma, self->rx_dma_descr, DMA_PERIPH_TO_MEMORY, self->i2c);
         self->i2c->hdmatx = NULL;
         self->i2c->hdmarx = &rx_dma;
         MP_HAL_CLEANINVALIDATE_DCACHE(vstr.buf, vstr.len);
-        status = HAL_I2C_Mem_Read_DMA(self->i2c, i2c_addr, mem_addr, mem_addr_size, (uint8_t*)vstr.buf, vstr.len);
+        status = HAL_I2C_Mem_Read_DMA(self->i2c, i2c_addr, mem_addr, mem_addr_size, (uint8_t *)vstr.buf, vstr.len);
         if (status == HAL_OK) {
             status = i2c_wait_dma_finished(self->i2c, args[3].u_int);
         }
@@ -1084,7 +1095,7 @@
     .name = MP_QSTR_I2C,
     .print = pyb_i2c_print,
     .make_new = pyb_i2c_make_new,
-    .locals_dict = (mp_obj_dict_t*)&pyb_i2c_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_i2c_locals_dict,
 };
 
 #endif // MICROPY_PY_PYB_LEGACY && MICROPY_HW_ENABLE_HW_I2C
diff --git a/ports/stm32/pyb_spi.c b/ports/stm32/pyb_spi.c
index a3cacea..4e7a4a6 100644
--- a/ports/stm32/pyb_spi.c
+++ b/ports/stm32/pyb_spi.c
@@ -223,7 +223,7 @@
     mp_obj_t o_ret = pyb_buf_get_for_recv(args[0].u_obj, &vstr);
 
     // receive the data
-    spi_transfer(self->spi, vstr.len, NULL, (uint8_t*)vstr.buf, args[1].u_int);
+    spi_transfer(self->spi, vstr.len, NULL, (uint8_t *)vstr.buf, args[1].u_int);
 
     // return the received data
     if (o_ret != MP_OBJ_NULL) {
@@ -339,7 +339,7 @@
 STATIC MP_DEFINE_CONST_DICT(pyb_spi_locals_dict, pyb_spi_locals_dict_table);
 
 STATIC void spi_transfer_machine(mp_obj_base_t *self_in, size_t len, const uint8_t *src, uint8_t *dest) {
-    pyb_spi_obj_t *self = (pyb_spi_obj_t*)self_in;
+    pyb_spi_obj_t *self = (pyb_spi_obj_t *)self_in;
     spi_transfer(self->spi, len, src, dest, SPI_TRANSFER_TIMEOUT(len));
 }
 
@@ -353,5 +353,5 @@
     .print = pyb_spi_print,
     .make_new = pyb_spi_make_new,
     .protocol = &pyb_spi_p,
-    .locals_dict = (mp_obj_dict_t*)&pyb_spi_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_spi_locals_dict,
 };
diff --git a/ports/stm32/pybthread.c b/ports/stm32/pybthread.c
index d6e9a3f..603bc2e 100644
--- a/ports/stm32/pybthread.c
+++ b/ports/stm32/pybthread.c
@@ -34,15 +34,15 @@
 
 #if MICROPY_PY_THREAD
 
-#define PYB_MUTEX_UNLOCKED ((void*)0)
-#define PYB_MUTEX_LOCKED ((void*)1)
+#define PYB_MUTEX_UNLOCKED ((void *)0)
+#define PYB_MUTEX_LOCKED ((void *)1)
 
 // These macros are used when we only need to protect against a thread
 // switch; other interrupts are still allowed to proceed.
 #define RAISE_IRQ_PRI() raise_irq_pri(IRQ_PRI_PENDSV)
 #define RESTORE_IRQ_PRI(state) restore_irq_pri(state)
 
-extern void __fatal_error(const char*);
+extern void __fatal_error(const char *);
 
 volatile int pyb_thread_enabled;
 pyb_thread_t *volatile pyb_thread_all;
@@ -94,7 +94,7 @@
     // take current thread off the run list
     pyb_thread_remove_from_runable(thread);
     // take current thread off the list of all threads
-    for (pyb_thread_t **n = (pyb_thread_t**)&pyb_thread_all;; n = &(*n)->all_next) {
+    for (pyb_thread_t **n = (pyb_thread_t **)&pyb_thread_all;; n = &(*n)->all_next) {
         if (*n == thread) {
             *n = thread->all_next;
             break;
@@ -116,7 +116,7 @@
 }
 
 uint32_t pyb_thread_new(pyb_thread_t *thread, void *stack, size_t stack_len, void *entry, void *arg) {
-    uint32_t *stack_top = (uint32_t*)stack + stack_len; // stack is full descending
+    uint32_t *stack_top = (uint32_t *)stack + stack_len; // stack is full descending
     *--stack_top = 0x01000000; // xPSR (thumb bit set)
     *--stack_top = (uint32_t)entry & 0xfffffffe; // pc (must have bit 0 cleared, even for thumb code)
     *--stack_top = (uint32_t)pyb_thread_terminate; // lr
diff --git a/ports/stm32/pybthread.h b/ports/stm32/pybthread.h
index 4230050..8e5ce25 100644
--- a/ports/stm32/pybthread.h
+++ b/ports/stm32/pybthread.h
@@ -59,7 +59,7 @@
 }
 
 static inline void *pyb_thread_get_local(void) {
-    return (void*)pyb_thread_cur->local_state;
+    return (void *)pyb_thread_cur->local_state;
 }
 
 static inline void pyb_thread_yield(void) {
diff --git a/ports/stm32/qspi.c b/ports/stm32/qspi.c
index 20cdafb..b82d3d8 100644
--- a/ports/stm32/qspi.c
+++ b/ports/stm32/qspi.c
@@ -101,7 +101,7 @@
 
     QUADSPI->CR =
         (MICROPY_HW_QSPI_PRESCALER - 1) << QUADSPI_CR_PRESCALER_Pos
-        | 3 << QUADSPI_CR_FTHRES_Pos // 4 bytes must be available to read/write
+            | 3 << QUADSPI_CR_FTHRES_Pos // 4 bytes must be available to read/write
         #if defined(QUADSPI_CR_FSEL_Pos)
         | 0 << QUADSPI_CR_FSEL_Pos // FLASH 1 selected
         #endif
@@ -109,15 +109,15 @@
         | 0 << QUADSPI_CR_DFM_Pos // dual-flash mode disabled
         #endif
         | MICROPY_HW_QSPI_SAMPLE_SHIFT << QUADSPI_CR_SSHIFT_Pos
-        | MICROPY_HW_QSPI_TIMEOUT_COUNTER << QUADSPI_CR_TCEN_Pos
-        | 1 << QUADSPI_CR_EN_Pos // enable the peripheral
-        ;
+            | MICROPY_HW_QSPI_TIMEOUT_COUNTER << QUADSPI_CR_TCEN_Pos
+            | 1 << QUADSPI_CR_EN_Pos // enable the peripheral
+    ;
 
     QUADSPI->DCR =
         (MICROPY_HW_QSPIFLASH_SIZE_BITS_LOG2 - 3 - 1) << QUADSPI_DCR_FSIZE_Pos
-        | (MICROPY_HW_QSPI_CS_HIGH_CYCLES - 1) << QUADSPI_DCR_CSHT_Pos
-        | 0 << QUADSPI_DCR_CKMODE_Pos // CLK idles at low state
-        ;
+            | (MICROPY_HW_QSPI_CS_HIGH_CYCLES - 1) << QUADSPI_DCR_CSHT_Pos
+            | 0 << QUADSPI_DCR_CKMODE_Pos // CLK idles at low state
+    ;
 }
 
 void qspi_memory_map(void) {
@@ -127,17 +127,17 @@
 
     QUADSPI->CCR =
         0 << QUADSPI_CCR_DDRM_Pos // DDR mode disabled
-        | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction
-        | 3 << QUADSPI_CCR_FMODE_Pos // memory-mapped mode
-        | 3 << QUADSPI_CCR_DMODE_Pos // data on 4 lines
-        | 4 << QUADSPI_CCR_DCYC_Pos // 4 dummy cycles
-        | 0 << QUADSPI_CCR_ABSIZE_Pos // 8-bit alternate byte
-        | 3 << QUADSPI_CCR_ABMODE_Pos // alternate byte on 4 lines
-        | QSPI_ADSIZE << QUADSPI_CCR_ADSIZE_Pos
-        | 3 << QUADSPI_CCR_ADMODE_Pos // address on 4 lines
-        | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line
-        | QSPI_CMD << QUADSPI_CCR_INSTRUCTION_Pos
-        ;
+            | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction
+            | 3 << QUADSPI_CCR_FMODE_Pos // memory-mapped mode
+            | 3 << QUADSPI_CCR_DMODE_Pos // data on 4 lines
+            | 4 << QUADSPI_CCR_DCYC_Pos // 4 dummy cycles
+            | 0 << QUADSPI_CCR_ABSIZE_Pos // 8-bit alternate byte
+            | 3 << QUADSPI_CCR_ABMODE_Pos // alternate byte on 4 lines
+            | QSPI_ADSIZE << QUADSPI_CCR_ADSIZE_Pos
+            | 3 << QUADSPI_CCR_ADMODE_Pos // address on 4 lines
+            | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line
+            | QSPI_CMD << QUADSPI_CCR_INSTRUCTION_Pos
+    ;
 
     qspi_mpu_enable_mapped();
 }
@@ -174,32 +174,32 @@
     if (len == 0) {
         QUADSPI->CCR =
             0 << QUADSPI_CCR_DDRM_Pos // DDR mode disabled
-            | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction
-            | 0 << QUADSPI_CCR_FMODE_Pos // indirect write mode
-            | 0 << QUADSPI_CCR_DMODE_Pos // no data
-            | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles
-            | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte
-            | 0 << QUADSPI_CCR_ADMODE_Pos // no address
-            | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line
-            | cmd << QUADSPI_CCR_INSTRUCTION_Pos // write opcode
-            ;
+                | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction
+                | 0 << QUADSPI_CCR_FMODE_Pos // indirect write mode
+                | 0 << QUADSPI_CCR_DMODE_Pos // no data
+                | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles
+                | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte
+                | 0 << QUADSPI_CCR_ADMODE_Pos // no address
+                | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line
+                | cmd << QUADSPI_CCR_INSTRUCTION_Pos // write opcode
+        ;
     } else {
         QUADSPI->DLR = len - 1;
 
         QUADSPI->CCR =
             0 << QUADSPI_CCR_DDRM_Pos // DDR mode disabled
-            | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction
-            | 0 << QUADSPI_CCR_FMODE_Pos // indirect write mode
-            | 1 << QUADSPI_CCR_DMODE_Pos // data on 1 line
-            | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles
-            | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte
-            | 0 << QUADSPI_CCR_ADMODE_Pos // no address
-            | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line
-            | cmd << QUADSPI_CCR_INSTRUCTION_Pos // write opcode
-            ;
+                | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction
+                | 0 << QUADSPI_CCR_FMODE_Pos // indirect write mode
+                | 1 << QUADSPI_CCR_DMODE_Pos // data on 1 line
+                | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles
+                | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte
+                | 0 << QUADSPI_CCR_ADMODE_Pos // no address
+                | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line
+                | cmd << QUADSPI_CCR_INSTRUCTION_Pos // write opcode
+        ;
 
         // This assumes len==2
-        *(uint16_t*)&QUADSPI->DR = data;
+        *(uint16_t *)&QUADSPI->DR = data;
     }
 
     // Wait for write to finish
@@ -219,16 +219,16 @@
     if (len == 0) {
         QUADSPI->CCR =
             0 << QUADSPI_CCR_DDRM_Pos // DDR mode disabled
-            | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction
-            | 0 << QUADSPI_CCR_FMODE_Pos // indirect write mode
-            | 0 << QUADSPI_CCR_DMODE_Pos // no data
-            | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles
-            | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte
-            | adsize << QUADSPI_CCR_ADSIZE_Pos // 32/24-bit address size
-            | 1 << QUADSPI_CCR_ADMODE_Pos // address on 1 line
-            | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line
-            | cmd << QUADSPI_CCR_INSTRUCTION_Pos // write opcode
-            ;
+                | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction
+                | 0 << QUADSPI_CCR_FMODE_Pos // indirect write mode
+                | 0 << QUADSPI_CCR_DMODE_Pos // no data
+                | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles
+                | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte
+                | adsize << QUADSPI_CCR_ADSIZE_Pos // 32/24-bit address size
+                | 1 << QUADSPI_CCR_ADMODE_Pos // address on 1 line
+                | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line
+                | cmd << QUADSPI_CCR_INSTRUCTION_Pos // write opcode
+        ;
 
         QUADSPI->AR = addr;
     } else {
@@ -236,16 +236,16 @@
 
         QUADSPI->CCR =
             0 << QUADSPI_CCR_DDRM_Pos // DDR mode disabled
-            | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction
-            | 0 << QUADSPI_CCR_FMODE_Pos // indirect write mode
-            | 1 << QUADSPI_CCR_DMODE_Pos // data on 1 line
-            | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles
-            | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte
-            | adsize << QUADSPI_CCR_ADSIZE_Pos // 32/24-bit address size
-            | 1 << QUADSPI_CCR_ADMODE_Pos // address on 1 line
-            | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line
-            | cmd << QUADSPI_CCR_INSTRUCTION_Pos // write opcode
-            ;
+                | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction
+                | 0 << QUADSPI_CCR_FMODE_Pos // indirect write mode
+                | 1 << QUADSPI_CCR_DMODE_Pos // data on 1 line
+                | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles
+                | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte
+                | adsize << QUADSPI_CCR_ADSIZE_Pos // 32/24-bit address size
+                | 1 << QUADSPI_CCR_ADMODE_Pos // address on 1 line
+                | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line
+                | cmd << QUADSPI_CCR_INSTRUCTION_Pos // write opcode
+        ;
 
         QUADSPI->AR = addr;
 
@@ -253,7 +253,7 @@
         while (len) {
             while (!(QUADSPI->SR & QUADSPI_SR_FTF)) {
             }
-            *(volatile uint8_t*)&QUADSPI->DR = *src++;
+            *(volatile uint8_t *)&QUADSPI->DR = *src++;
             --len;
         }
     }
@@ -274,15 +274,15 @@
 
     QUADSPI->CCR =
         0 << QUADSPI_CCR_DDRM_Pos // DDR mode disabled
-        | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction
-        | 1 << QUADSPI_CCR_FMODE_Pos // indirect read mode
-        | 1 << QUADSPI_CCR_DMODE_Pos // data on 1 line
-        | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles
-        | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte
-        | 0 << QUADSPI_CCR_ADMODE_Pos // no address
-        | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line
-        | cmd << QUADSPI_CCR_INSTRUCTION_Pos // read opcode
-        ;
+            | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction
+            | 1 << QUADSPI_CCR_FMODE_Pos // indirect read mode
+            | 1 << QUADSPI_CCR_DMODE_Pos // data on 1 line
+            | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles
+            | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte
+            | 0 << QUADSPI_CCR_ADMODE_Pos // no address
+            | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line
+            | cmd << QUADSPI_CCR_INSTRUCTION_Pos // read opcode
+    ;
 
     // Wait for read to finish
     while (!(QUADSPI->SR & QUADSPI_SR_TCF)) {
@@ -305,17 +305,17 @@
 
     QUADSPI->CCR =
         0 << QUADSPI_CCR_DDRM_Pos // DDR mode disabled
-        | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction
-        | 1 << QUADSPI_CCR_FMODE_Pos // indirect read mode
-        | 3 << QUADSPI_CCR_DMODE_Pos // data on 4 lines
-        | 4 << QUADSPI_CCR_DCYC_Pos // 4 dummy cycles
-        | 0 << QUADSPI_CCR_ABSIZE_Pos // 8-bit alternate byte
-        | 3 << QUADSPI_CCR_ABMODE_Pos // alternate byte on 4 lines
-        | adsize << QUADSPI_CCR_ADSIZE_Pos // 32 or 24-bit address size
-        | 3 << QUADSPI_CCR_ADMODE_Pos // address on 4 lines
-        | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line
-        | cmd << QUADSPI_CCR_INSTRUCTION_Pos // quad read opcode
-        ;
+            | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction
+            | 1 << QUADSPI_CCR_FMODE_Pos // indirect read mode
+            | 3 << QUADSPI_CCR_DMODE_Pos // data on 4 lines
+            | 4 << QUADSPI_CCR_DCYC_Pos // 4 dummy cycles
+            | 0 << QUADSPI_CCR_ABSIZE_Pos // 8-bit alternate byte
+            | 3 << QUADSPI_CCR_ABMODE_Pos // alternate byte on 4 lines
+            | adsize << QUADSPI_CCR_ADSIZE_Pos // 32 or 24-bit address size
+            | 3 << QUADSPI_CCR_ADMODE_Pos // address on 4 lines
+            | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line
+            | cmd << QUADSPI_CCR_INSTRUCTION_Pos // quad read opcode
+    ;
 
     QUADSPI->ABR = 0; // alternate byte: disable continuous read mode
     QUADSPI->AR = addr; // addres to read from
@@ -325,7 +325,7 @@
         while (len >= 4) {
             while (!(QUADSPI->SR & QUADSPI_SR_FTF)) {
             }
-            *(uint32_t*)dest = QUADSPI->DR;
+            *(uint32_t *)dest = QUADSPI->DR;
             dest += 4;
             len -= 4;
         }
@@ -335,7 +335,7 @@
     while (len) {
         while (!((QUADSPI->SR >> QUADSPI_SR_FLEVEL_Pos) & 0x3f)) {
         }
-        *dest++ = *(volatile uint8_t*)&QUADSPI->DR;
+        *dest++ = *(volatile uint8_t *)&QUADSPI->DR;
         --len;
     }
 
diff --git a/ports/stm32/rfcore.c b/ports/stm32/rfcore.c
index 2b45bb2..8221527 100644
--- a/ports/stm32/rfcore.c
+++ b/ports/stm32/rfcore.c
@@ -56,7 +56,7 @@
 } tl_list_node_t;
 
 typedef struct _parse_hci_info_t {
-    int (*cb_fun)(void*, uint8_t);
+    int (*cb_fun)(void *, uint8_t);
     void *cb_env;
     bool was_hci_reset_evt;
 } parse_hci_info_t;
@@ -106,11 +106,11 @@
 // IPCC interface
 
 STATIC uint32_t get_ipccdba(void) {
-    return *(uint32_t*)(OPTION_BYTE_BASE + 0x68) & 0x3fff;
+    return *(uint32_t *)(OPTION_BYTE_BASE + 0x68) & 0x3fff;
 }
 
 STATIC volatile void **get_buffer_table(void) {
-    return (volatile void**)(SRAM2A_BASE + get_ipccdba());
+    return (volatile void **)(SRAM2A_BASE + get_ipccdba());
 }
 
 void ipcc_init(uint32_t irq_pri) {
@@ -255,10 +255,10 @@
         volatile tl_list_node_t *cur = head->next;
         bool free = false;
         while (cur != head) {
-            tl_parse_hci_msg((uint8_t*)cur->body, parse);
+            tl_parse_hci_msg((uint8_t *)cur->body, parse);
             volatile tl_list_node_t *next = tl_list_unlink(cur);
-            if ((void*)&ipcc_mem_memmgr_evt_pool[0] <= (void*)cur
-                && (void*)cur < (void*)&ipcc_mem_memmgr_evt_pool[MP_ARRAY_SIZE(ipcc_mem_memmgr_evt_pool)]) {
+            if ((void *)&ipcc_mem_memmgr_evt_pool[0] <= (void *)cur
+                && (void *)cur < (void *)&ipcc_mem_memmgr_evt_pool[MP_ARRAY_SIZE(ipcc_mem_memmgr_evt_pool)]) {
                 // Place memory back in free pool
                 tl_list_append(&ipcc_mem_memmgr_free_buf_queue, cur);
                 free = true;
@@ -275,7 +275,7 @@
 }
 
 STATIC void tl_hci_cmd(uint8_t *cmd, unsigned int ch, uint8_t hdr, uint16_t opcode, size_t len, const uint8_t *buf) {
-    tl_list_node_t *n = (tl_list_node_t*)cmd;
+    tl_list_node_t *n = (tl_list_node_t *)cmd;
     n->next = n;
     n->prev = n;
     cmd[8] = hdr;
@@ -294,12 +294,12 @@
 }
 
 STATIC void tl_sys_hci_cmd_resp(uint16_t opcode, size_t len, const uint8_t *buf) {
-    tl_hci_cmd((uint8_t*)&ipcc_mem_sys_cmd_buf, IPCC_CH_SYS, 0x10, opcode, len, buf);
-    tl_sys_wait_resp((uint8_t*)&ipcc_mem_sys_cmd_buf, IPCC_CH_SYS);
+    tl_hci_cmd((uint8_t *)&ipcc_mem_sys_cmd_buf, IPCC_CH_SYS, 0x10, opcode, len, buf);
+    tl_sys_wait_resp((uint8_t *)&ipcc_mem_sys_cmd_buf, IPCC_CH_SYS);
 }
 
 STATIC void tl_ble_hci_cmd_resp(uint16_t opcode, size_t len, const uint8_t *buf) {
-    tl_hci_cmd((uint8_t*)&ipcc_mem_ble_cmd_buf[0], IPCC_CH_BLE, 0x01, opcode, len, buf);
+    tl_hci_cmd((uint8_t *)&ipcc_mem_ble_cmd_buf[0], IPCC_CH_BLE, 0x01, opcode, len, buf);
     ipcc_wait_msg(IPCC_CH_BLE, 250);
     tl_check_msg(&ipcc_mem_ble_evt_queue, IPCC_CH_BLE, NULL);
 }
@@ -324,7 +324,7 @@
 }
 
 static const struct {
-    uint8_t* pBleBufferAddress;     // unused
+    uint8_t *pBleBufferAddress;     // unused
     uint32_t BleBufferSize;         // unused
     uint16_t NumAttrRecord;
     uint16_t NumAttrServ;
@@ -369,7 +369,7 @@
     tl_check_msg(&ipcc_mem_ble_evt_queue, IPCC_CH_BLE, NULL);
 
     // Configure and reset the BLE controller
-    tl_sys_hci_cmd_resp(HCI_OPCODE(OGF_VENDOR, OCF_BLE_INIT), sizeof(ble_init_params), (const uint8_t*)&ble_init_params);
+    tl_sys_hci_cmd_resp(HCI_OPCODE(OGF_VENDOR, OCF_BLE_INIT), sizeof(ble_init_params), (const uint8_t *)&ble_init_params);
     tl_ble_hci_cmd_resp(HCI_OPCODE(0x03, 0x0003), 0, NULL);
 }
 
@@ -385,10 +385,10 @@
     tl_list_node_t *n;
     uint32_t ch;
     if (src[0] == 0x01) {
-        n = (tl_list_node_t*)&ipcc_mem_ble_cmd_buf[0];
+        n = (tl_list_node_t *)&ipcc_mem_ble_cmd_buf[0];
         ch = IPCC_CH_BLE;
     } else if (src[0] == 0x02) {
-        n = (tl_list_node_t*)&ipcc_mem_ble_hci_acl_data_buf[0];
+        n = (tl_list_node_t *)&ipcc_mem_ble_hci_acl_data_buf[0];
         ch = IPCC_CH_HCI_ACL;
     } else {
         printf("** UNEXPECTED HCI HDR: 0x%02x **\n", src[0]);
@@ -403,7 +403,7 @@
     IPCC->C1SCR = ch << 16;
 }
 
-void rfcore_ble_check_msg(int (*cb)(void*, uint8_t), void *env) {
+void rfcore_ble_check_msg(int (*cb)(void *, uint8_t), void *env) {
     parse_hci_info_t parse = { cb, env, false };
     tl_check_msg(&ipcc_mem_ble_evt_queue, IPCC_CH_BLE, &parse);
 
@@ -413,12 +413,13 @@
         buf[0] = 0; // config offset
         buf[1] = 6; // config length
         mp_hal_get_mac(MP_HAL_MAC_BDADDR, &buf[2]);
-        #define SWAP_UINT8(a, b) { uint8_t temp = a; a = b; b = temp; }
+        #define SWAP_UINT8(a, b) { uint8_t temp = a; a = b; b = temp; \
+}
         SWAP_UINT8(buf[2], buf[7]);
         SWAP_UINT8(buf[3], buf[6]);
         SWAP_UINT8(buf[4], buf[5]);
         tl_ble_hci_cmd_resp(HCI_OPCODE(OGF_VENDOR, OCF_WRITE_CONFIG), 8, buf); // set BDADDR
-        tl_ble_hci_cmd_resp(HCI_OPCODE(OGF_VENDOR, OCF_SET_TX_POWER), 2, (const uint8_t*)"\x00\x06"); // 0 dBm
+        tl_ble_hci_cmd_resp(HCI_OPCODE(OGF_VENDOR, OCF_SET_TX_POWER), 2, (const uint8_t *)"\x00\x06"); // 0 dBm
     }
 }
 
diff --git a/ports/stm32/rfcore.h b/ports/stm32/rfcore.h
index ef12707..8a04075 100644
--- a/ports/stm32/rfcore.h
+++ b/ports/stm32/rfcore.h
@@ -32,6 +32,6 @@
 
 void rfcore_ble_init(void);
 void rfcore_ble_hci_cmd(size_t len, const uint8_t *src);
-void rfcore_ble_check_msg(int (*cb)(void*, uint8_t), void *env);
+void rfcore_ble_check_msg(int (*cb)(void *, uint8_t), void *env);
 
 #endif // MICROPY_INCLUDED_STM32_RFCORE_H
diff --git a/ports/stm32/rtc.c b/ports/stm32/rtc.c
index 4019617..92b669d 100644
--- a/ports/stm32/rtc.c
+++ b/ports/stm32/rtc.c
@@ -125,7 +125,7 @@
             rtc_info |= 0x40000 | (RCC->BDCR & 7) | (RCC->CSR & 3) << 8;
             return;
         } else if ((bdcr & (RCC_BDCR_RTCEN | RCC_BDCR_RTCSEL))
-            == (RCC_BDCR_RTCEN | RCC_BDCR_RTCSEL_1)) {
+                   == (RCC_BDCR_RTCEN | RCC_BDCR_RTCSEL_1)) {
             // LSI configured as the RTC clock source --> no need to (re-)init RTC
             // remove Backup Domain write protection
             HAL_PWR_EnableBkUpAccess();
@@ -186,14 +186,14 @@
     // fresh reset; configure RTC Calendar
     RTC_CalendarConfig();
     #if defined(STM32L4) || defined(STM32WB)
-    if(__HAL_RCC_GET_FLAG(RCC_FLAG_BORRST) != RESET) {
+    if (__HAL_RCC_GET_FLAG(RCC_FLAG_BORRST) != RESET) {
     #else
-    if(__HAL_RCC_GET_FLAG(RCC_FLAG_PORRST) != RESET) {
-    #endif
+    if (__HAL_RCC_GET_FLAG(RCC_FLAG_PORRST) != RESET) {
+        #endif
         // power on reset occurred
         rtc_info |= 0x10000;
     }
-    if(__HAL_RCC_GET_FLAG(RCC_FLAG_PINRST) != RESET) {
+    if (__HAL_RCC_GET_FLAG(RCC_FLAG_PINRST) != RESET) {
         // external reset occurred
         rtc_info |= 0x20000;
     }
@@ -202,7 +202,7 @@
     rtc_need_init_finalise = false;
 }
 
-STATIC HAL_StatusTypeDef PYB_RCC_OscConfig(RCC_OscInitTypeDef  *RCC_OscInitStruct) {
+STATIC HAL_StatusTypeDef PYB_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) {
     /*------------------------------ LSI Configuration -------------------------*/
     if ((RCC_OscInitStruct->OscillatorType & RCC_OSCILLATORTYPE_LSI) == RCC_OSCILLATORTYPE_LSI) {
         // Check the LSI State
@@ -295,7 +295,7 @@
         return HAL_ERROR;
     } else {
         // Clear RTC_CR FMT, OSEL and POL Bits
-        hrtc->Instance->CR &= ((uint32_t)~(RTC_CR_FMT | RTC_CR_OSEL | RTC_CR_POL));
+        hrtc->Instance->CR &= ((uint32_t) ~(RTC_CR_FMT | RTC_CR_OSEL | RTC_CR_POL));
         // Set RTC_CR register
         hrtc->Instance->CR |= (uint32_t)(hrtc->Init.HourFormat | hrtc->Init.OutPut | hrtc->Init.OutPutPolarity);
 
@@ -304,16 +304,16 @@
         hrtc->Instance->PRER |= (uint32_t)(hrtc->Init.AsynchPrediv << 16);
 
         // Exit Initialization mode
-        hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT;
+        hrtc->Instance->ISR &= (uint32_t) ~RTC_ISR_INIT;
 
         #if defined(STM32L0) || defined(STM32L4) || defined(STM32H7) || defined(STM32WB)
-        hrtc->Instance->OR &= (uint32_t)~RTC_OR_ALARMOUTTYPE;
+        hrtc->Instance->OR &= (uint32_t) ~RTC_OR_ALARMOUTTYPE;
         hrtc->Instance->OR |= (uint32_t)(hrtc->Init.OutPutType);
         #elif defined(STM32F7)
-        hrtc->Instance->OR &= (uint32_t)~RTC_OR_ALARMTYPE;
+        hrtc->Instance->OR &= (uint32_t) ~RTC_OR_ALARMTYPE;
         hrtc->Instance->OR |= (uint32_t)(hrtc->Init.OutPutType);
         #else
-        hrtc->Instance->TAFCR &= (uint32_t)~RTC_TAFCR_ALARMOUTTYPE;
+        hrtc->Instance->TAFCR &= (uint32_t) ~RTC_TAFCR_ALARMOUTTYPE;
         hrtc->Instance->TAFCR |= (uint32_t)(hrtc->Init.OutPutType);
         #endif
 
@@ -340,7 +340,7 @@
     // configuration variable is set.  Otherwise it uses LSI (internal osc).
 
     RCC_OscInitTypeDef RCC_OscInitStruct;
-    RCC_OscInitStruct.OscillatorType =  RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_LSE;
+    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_LSE;
     RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
     #if MICROPY_HW_RTC_USE_BYPASS
     if (rtc_use_byp) {
@@ -422,7 +422,7 @@
     date.Date = 1;
     date.WeekDay = RTC_WEEKDAY_THURSDAY;
 
-    if(HAL_RTC_SetDate(&RTCHandle, &date, RTC_FORMAT_BIN) != HAL_OK) {
+    if (HAL_RTC_SetDate(&RTCHandle, &date, RTC_FORMAT_BIN) != HAL_OK) {
         // init error
         return;
     }
@@ -714,7 +714,7 @@
         cal = mp_obj_get_int(args[1]);
         mp_uint_t cal_p, cal_m;
         if (cal < -511 || cal > 512) {
-#if defined(MICROPY_HW_RTC_USE_CALOUT) && MICROPY_HW_RTC_USE_CALOUT
+            #if defined(MICROPY_HW_RTC_USE_CALOUT) && MICROPY_HW_RTC_USE_CALOUT
             if ((cal & 0xfffe) == 0x0ffe) {
                 // turn on/off X18 (PC13) 512Hz output
                 // Note:
@@ -728,9 +728,9 @@
             } else {
                 mp_raise_ValueError("calibration value out of range");
             }
-#else
+            #else
             mp_raise_ValueError("calibration value out of range");
-#endif
+            #endif
         }
         if (cal > 0) {
             cal_p = RTC_SMOOTHCALIB_PLUSPULSES_SET;
@@ -767,5 +767,5 @@
     { &mp_type_type },
     .name = MP_QSTR_RTC,
     .make_new = pyb_rtc_make_new,
-    .locals_dict = (mp_obj_dict_t*)&pyb_rtc_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_rtc_locals_dict,
 };
diff --git a/ports/stm32/sdcard.c b/ports/stm32/sdcard.c
index 632ea43..c0d9df8 100644
--- a/ports/stm32/sdcard.c
+++ b/ports/stm32/sdcard.c
@@ -244,14 +244,14 @@
 STATIC HAL_StatusTypeDef sdmmc_init_sd(void) {
     // SD device interface configuration
     sdmmc_handle.sd.Instance = SDIO;
-    sdmmc_handle.sd.Init.ClockEdge           = SDIO_CLOCK_EDGE_RISING;
+    sdmmc_handle.sd.Init.ClockEdge = SDIO_CLOCK_EDGE_RISING;
     #ifndef STM32H7
-    sdmmc_handle.sd.Init.ClockBypass         = SDIO_CLOCK_BYPASS_DISABLE;
+    sdmmc_handle.sd.Init.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE;
     #endif
-    sdmmc_handle.sd.Init.ClockPowerSave      = SDIO_CLOCK_POWER_SAVE_ENABLE;
-    sdmmc_handle.sd.Init.BusWide             = SDIO_BUS_WIDE_1B;
+    sdmmc_handle.sd.Init.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_ENABLE;
+    sdmmc_handle.sd.Init.BusWide = SDIO_BUS_WIDE_1B;
     sdmmc_handle.sd.Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE;
-    sdmmc_handle.sd.Init.ClockDiv            = SDIO_TRANSFER_CLK_DIV;
+    sdmmc_handle.sd.Init.ClockDiv = SDIO_TRANSFER_CLK_DIV;
 
     // init the SD interface, with retry if it's not ready yet
     HAL_StatusTypeDef status;
@@ -279,14 +279,14 @@
 STATIC HAL_StatusTypeDef sdmmc_init_mmc(void) {
     // MMC device interface configuration
     sdmmc_handle.mmc.Instance = SDIO;
-    sdmmc_handle.mmc.Init.ClockEdge           = SDIO_CLOCK_EDGE_RISING;
+    sdmmc_handle.mmc.Init.ClockEdge = SDIO_CLOCK_EDGE_RISING;
     #ifndef STM32H7
-    sdmmc_handle.mmc.Init.ClockBypass         = SDIO_CLOCK_BYPASS_DISABLE;
+    sdmmc_handle.mmc.Init.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE;
     #endif
-    sdmmc_handle.mmc.Init.ClockPowerSave      = SDIO_CLOCK_POWER_SAVE_ENABLE;
-    sdmmc_handle.mmc.Init.BusWide             = SDIO_BUS_WIDE_1B;
+    sdmmc_handle.mmc.Init.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_ENABLE;
+    sdmmc_handle.mmc.Init.BusWide = SDIO_BUS_WIDE_1B;
     sdmmc_handle.mmc.Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE;
-    sdmmc_handle.mmc.Init.ClockDiv            = SDIO_TRANSFER_CLK_DIV;
+    sdmmc_handle.mmc.Init.ClockDiv = SDIO_TRANSFER_CLK_DIV;
 
     // Init the SDIO interface
     HAL_StatusTypeDef status = HAL_MMC_Init(&sdmmc_handle.mmc);
@@ -503,8 +503,8 @@
         // bytes at the aligned location should be able to be changed for the
         // duration of this function call.
         orig_dest = dest;
-        dest = (uint8_t*)((uint32_t)dest & ~3);
-        saved_word = *(uint32_t*)dest;
+        dest = (uint8_t *)((uint32_t)dest & ~3);
+        saved_word = *(uint32_t *)dest;
     }
 
     if (query_irq() == IRQ_STATE_ENABLED) {
@@ -626,11 +626,11 @@
         sdcard_reset_periph();
         #if MICROPY_HW_ENABLE_MMCARD
         if (pyb_sdmmc_flags & PYB_SDMMC_FLAG_MMC) {
-            err = HAL_MMC_WriteBlocks_DMA(&sdmmc_handle.mmc, (uint8_t*)src, block_num, num_blocks);
+            err = HAL_MMC_WriteBlocks_DMA(&sdmmc_handle.mmc, (uint8_t *)src, block_num, num_blocks);
         } else
         #endif
         {
-            err = HAL_SD_WriteBlocks_DMA(&sdmmc_handle.sd, (uint8_t*)src, block_num, num_blocks);
+            err = HAL_SD_WriteBlocks_DMA(&sdmmc_handle.sd, (uint8_t *)src, block_num, num_blocks);
         }
         if (err == HAL_OK) {
             err = sdcard_wait_finished(60000);
@@ -652,11 +652,11 @@
     } else {
         #if MICROPY_HW_ENABLE_MMCARD
         if (pyb_sdmmc_flags & PYB_SDMMC_FLAG_MMC) {
-            err = HAL_MMC_WriteBlocks(&sdmmc_handle.mmc, (uint8_t*)src, block_num, num_blocks, 60000);
+            err = HAL_MMC_WriteBlocks(&sdmmc_handle.mmc, (uint8_t *)src, block_num, num_blocks, 60000);
         } else
         #endif
         {
-            err = HAL_SD_WriteBlocks(&sdmmc_handle.sd, (uint8_t*)src, block_num, num_blocks, 60000);
+            err = HAL_SD_WriteBlocks(&sdmmc_handle.sd, (uint8_t *)src, block_num, num_blocks, 60000);
         }
         if (err == HAL_OK) {
             err = sdcard_wait_finished(60000);
@@ -857,7 +857,7 @@
     { &mp_type_type },
     .name = MP_QSTR_SDCard,
     .make_new = pyb_sdcard_make_new,
-    .locals_dict = (mp_obj_dict_t*)&pyb_sdcard_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_sdcard_locals_dict,
 };
 #endif
 
@@ -866,7 +866,7 @@
     { &mp_type_type },
     .name = MP_QSTR_MMCard,
     .make_new = pyb_mmcard_make_new,
-    .locals_dict = (mp_obj_dict_t*)&pyb_sdcard_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_sdcard_locals_dict,
 };
 #endif
 
diff --git a/ports/stm32/sdio.c b/ports/stm32/sdio.c
index 12d8326..79cc9c9 100644
--- a/ports/stm32/sdio.c
+++ b/ports/stm32/sdio.c
@@ -125,7 +125,7 @@
         #if defined(STM32H7)
         if (!sdmmc_dma) {
             while (sdmmc_buf_cur < sdmmc_buf_top && (SDMMC1->STA & SDMMC_STA_DPSMACT) && !(SDMMC1->STA & SDMMC_STA_RXFIFOE)) {
-                *(uint32_t*)sdmmc_buf_cur = SDMMC1->FIFO;
+                *(uint32_t *)sdmmc_buf_cur = SDMMC1->FIFO;
                 sdmmc_buf_cur += 4;
             }
         }
@@ -145,8 +145,8 @@
                 | (sdmmc_dma << SDMMC_DCTRL_DMAEN_Pos)
                 #endif
                 | (!sdmmc_write) << SDMMC_DCTRL_DTDIR_Pos
-                | SDMMC_DCTRL_DTEN
-                ;
+                    | SDMMC_DCTRL_DTEN
+            ;
             if (!sdmmc_dma) {
                 SDMMC1->MASK |= SDMMC_MASK_TXFIFOHEIE;
             }
@@ -160,7 +160,7 @@
         // check if there is some remaining data in RXFIFO
         if (!sdmmc_dma) {
             while (SDMMC1->STA & SDMMC_STA_RXDAVL) {
-                *(uint32_t*)sdmmc_buf_cur = SDMMC1->FIFO;
+                *(uint32_t *)sdmmc_buf_cur = SDMMC1->FIFO;
                 sdmmc_buf_cur += 4;
             }
         }
@@ -174,7 +174,7 @@
         if (!sdmmc_dma && sdmmc_write) {
             // write up to 8 words to fifo
             for (size_t i = 8; i && sdmmc_buf_cur < sdmmc_buf_top; --i) {
-                SDMMC1->FIFO = *(uint32_t*)sdmmc_buf_cur;
+                SDMMC1->FIFO = *(uint32_t *)sdmmc_buf_cur;
                 sdmmc_buf_cur += 4;
             }
             if (sdmmc_buf_cur >= sdmmc_buf_top) {
@@ -186,7 +186,7 @@
         if (!sdmmc_dma && !sdmmc_write) {
             // read up to 8 words from fifo
             for (size_t i = 8; i && sdmmc_buf_cur < sdmmc_buf_top; --i) {
-                *(uint32_t*)sdmmc_buf_cur = SDMMC1->FIFO;
+                *(uint32_t *)sdmmc_buf_cur = SDMMC1->FIFO;
                 sdmmc_buf_cur += 4;
             }
         }
@@ -336,7 +336,7 @@
             | write << 6 // DIR mem-to-periph
             | 1 << 5 // PFCTRL periph is flow controller
             | 1 << 0 // EN
-            ;
+        ;
         #else
         SDMMC1->IDMABASE0 = (uint32_t)buf;
         SDMMC1->IDMACTRL = SDMMC_IDMA_IDMAEN;
@@ -360,8 +360,8 @@
             | (dma << SDMMC_DCTRL_DMAEN_Pos)
             #endif
             | (!write) << SDMMC_DCTRL_DTDIR_Pos
-            | SDMMC_DCTRL_DTEN
-            ;
+                | SDMMC_DCTRL_DTEN
+        ;
     }
 
     SDMMC1->ARG = arg;
@@ -372,8 +372,8 @@
     sdmmc_write = write;
     sdmmc_dma = dma;
     sdmmc_error = 0;
-    sdmmc_buf_cur = (uint8_t*)buf;
-    sdmmc_buf_top = (uint8_t*)buf + len;
+    sdmmc_buf_cur = (uint8_t *)buf;
+    sdmmc_buf_top = (uint8_t *)buf + len;
     SDMMC1->MASK = (SDMMC1->MASK & SDMMC_MASK_SDIOITIE) | SDMMC_MASK_CMDRENDIE | SDMMC_MASK_DATAENDIE | SDMMC_MASK_RXFIFOHFIE | 0x3f;
 
     // wait to complete transfer
diff --git a/ports/stm32/sdram.c b/ports/stm32/sdram.c
index 5c32c6a..0aae74e 100644
--- a/ports/stm32/sdram.c
+++ b/ports/stm32/sdram.c
@@ -50,7 +50,7 @@
 #ifdef FMC_SDRAM_BANK
 
 static void sdram_init_seq(SDRAM_HandleTypeDef
-        *hsdram, FMC_SDRAM_CommandTypeDef *command);
+    *hsdram, FMC_SDRAM_CommandTypeDef *command);
 extern void __fatal_error(const char *msg);
 
 bool sdram_init(void) {
@@ -135,36 +135,36 @@
     hsdram.Instance = FMC_SDRAM_DEVICE;
     /* Timing configuration for 90 Mhz of SD clock frequency (180Mhz/2) */
     /* TMRD: 2 Clock cycles */
-    SDRAM_Timing.LoadToActiveDelay    = MICROPY_HW_SDRAM_TIMING_TMRD;
+    SDRAM_Timing.LoadToActiveDelay = MICROPY_HW_SDRAM_TIMING_TMRD;
     /* TXSR: min=70ns (6x11.90ns) */
     SDRAM_Timing.ExitSelfRefreshDelay = MICROPY_HW_SDRAM_TIMING_TXSR;
     /* TRAS */
-    SDRAM_Timing.SelfRefreshTime      = MICROPY_HW_SDRAM_TIMING_TRAS;
+    SDRAM_Timing.SelfRefreshTime = MICROPY_HW_SDRAM_TIMING_TRAS;
     /* TRC */
-    SDRAM_Timing.RowCycleDelay        = MICROPY_HW_SDRAM_TIMING_TRC;
+    SDRAM_Timing.RowCycleDelay = MICROPY_HW_SDRAM_TIMING_TRC;
     /* TWR */
-    SDRAM_Timing.WriteRecoveryTime    = MICROPY_HW_SDRAM_TIMING_TWR;
+    SDRAM_Timing.WriteRecoveryTime = MICROPY_HW_SDRAM_TIMING_TWR;
     /* TRP */
-    SDRAM_Timing.RPDelay              = MICROPY_HW_SDRAM_TIMING_TRP;
+    SDRAM_Timing.RPDelay = MICROPY_HW_SDRAM_TIMING_TRP;
     /* TRCD */
-    SDRAM_Timing.RCDDelay             = MICROPY_HW_SDRAM_TIMING_TRCD;
+    SDRAM_Timing.RCDDelay = MICROPY_HW_SDRAM_TIMING_TRCD;
 
-    #define _FMC_INIT(x, n) x ## _ ## n
+    #define _FMC_INIT(x, n) x##_##n
     #define FMC_INIT(x, n) _FMC_INIT(x,  n)
 
-    hsdram.Init.SDBank             = FMC_SDRAM_BANK;
-    hsdram.Init.ColumnBitsNumber   = FMC_INIT(FMC_SDRAM_COLUMN_BITS_NUM, MICROPY_HW_SDRAM_COLUMN_BITS_NUM);
-    hsdram.Init.RowBitsNumber      = FMC_INIT(FMC_SDRAM_ROW_BITS_NUM, MICROPY_HW_SDRAM_ROW_BITS_NUM);
-    hsdram.Init.MemoryDataWidth    = FMC_INIT(FMC_SDRAM_MEM_BUS_WIDTH, MICROPY_HW_SDRAM_MEM_BUS_WIDTH);
+    hsdram.Init.SDBank = FMC_SDRAM_BANK;
+    hsdram.Init.ColumnBitsNumber = FMC_INIT(FMC_SDRAM_COLUMN_BITS_NUM, MICROPY_HW_SDRAM_COLUMN_BITS_NUM);
+    hsdram.Init.RowBitsNumber = FMC_INIT(FMC_SDRAM_ROW_BITS_NUM, MICROPY_HW_SDRAM_ROW_BITS_NUM);
+    hsdram.Init.MemoryDataWidth = FMC_INIT(FMC_SDRAM_MEM_BUS_WIDTH, MICROPY_HW_SDRAM_MEM_BUS_WIDTH);
     hsdram.Init.InternalBankNumber = FMC_INIT(FMC_SDRAM_INTERN_BANKS_NUM, MICROPY_HW_SDRAM_INTERN_BANKS_NUM);
-    hsdram.Init.CASLatency         = FMC_INIT(FMC_SDRAM_CAS_LATENCY, MICROPY_HW_SDRAM_CAS_LATENCY);
-    hsdram.Init.SDClockPeriod      = FMC_INIT(FMC_SDRAM_CLOCK_PERIOD, MICROPY_HW_SDRAM_CLOCK_PERIOD);
-    hsdram.Init.ReadPipeDelay      = FMC_INIT(FMC_SDRAM_RPIPE_DELAY, MICROPY_HW_SDRAM_RPIPE_DELAY);
-    hsdram.Init.ReadBurst          = (MICROPY_HW_SDRAM_RBURST) ? FMC_SDRAM_RBURST_ENABLE : FMC_SDRAM_RBURST_DISABLE;
-    hsdram.Init.WriteProtection    = (MICROPY_HW_SDRAM_WRITE_PROTECTION) ? FMC_SDRAM_WRITE_PROTECTION_ENABLE : FMC_SDRAM_WRITE_PROTECTION_DISABLE;
+    hsdram.Init.CASLatency = FMC_INIT(FMC_SDRAM_CAS_LATENCY, MICROPY_HW_SDRAM_CAS_LATENCY);
+    hsdram.Init.SDClockPeriod = FMC_INIT(FMC_SDRAM_CLOCK_PERIOD, MICROPY_HW_SDRAM_CLOCK_PERIOD);
+    hsdram.Init.ReadPipeDelay = FMC_INIT(FMC_SDRAM_RPIPE_DELAY, MICROPY_HW_SDRAM_RPIPE_DELAY);
+    hsdram.Init.ReadBurst = (MICROPY_HW_SDRAM_RBURST) ? FMC_SDRAM_RBURST_ENABLE : FMC_SDRAM_RBURST_DISABLE;
+    hsdram.Init.WriteProtection = (MICROPY_HW_SDRAM_WRITE_PROTECTION) ? FMC_SDRAM_WRITE_PROTECTION_ENABLE : FMC_SDRAM_WRITE_PROTECTION_DISABLE;
 
     /* Initialize the SDRAM controller */
-    if(HAL_SDRAM_Init(&hsdram, &SDRAM_Timing) != HAL_OK) {
+    if (HAL_SDRAM_Init(&hsdram, &SDRAM_Timing) != HAL_OK) {
         return false;
     }
 
@@ -173,23 +173,22 @@
 }
 
 void *sdram_start(void) {
-    return (void*)SDRAM_START_ADDRESS;
+    return (void *)SDRAM_START_ADDRESS;
 }
 
 void *sdram_end(void) {
-    return (void*)(SDRAM_START_ADDRESS + MICROPY_HW_SDRAM_SIZE);
+    return (void *)(SDRAM_START_ADDRESS + MICROPY_HW_SDRAM_SIZE);
 }
 
 static void sdram_init_seq(SDRAM_HandleTypeDef
-        *hsdram, FMC_SDRAM_CommandTypeDef *command)
-{
+    *hsdram, FMC_SDRAM_CommandTypeDef *command) {
     /* Program the SDRAM external device */
-    __IO uint32_t tmpmrd =0;
+    __IO uint32_t tmpmrd = 0;
 
     /* Step 3:  Configure a clock configuration enable command */
-    command->CommandMode           = FMC_SDRAM_CMD_CLK_ENABLE;
-    command->CommandTarget         = FMC_SDRAM_CMD_TARGET_BANK;
-    command->AutoRefreshNumber     = 1;
+    command->CommandMode = FMC_SDRAM_CMD_CLK_ENABLE;
+    command->CommandTarget = FMC_SDRAM_CMD_TARGET_BANK;
+    command->AutoRefreshNumber = 1;
     command->ModeRegisterDefinition = 0;
 
     /* Send the command */
@@ -199,18 +198,18 @@
     HAL_Delay(100);
 
     /* Step 5: Configure a PALL (precharge all) command */
-    command->CommandMode           = FMC_SDRAM_CMD_PALL;
-    command->CommandTarget         = FMC_SDRAM_CMD_TARGET_BANK;
-    command->AutoRefreshNumber     = 1;
+    command->CommandMode = FMC_SDRAM_CMD_PALL;
+    command->CommandTarget = FMC_SDRAM_CMD_TARGET_BANK;
+    command->AutoRefreshNumber = 1;
     command->ModeRegisterDefinition = 0;
 
     /* Send the command */
     HAL_SDRAM_SendCommand(hsdram, command, 0x1000);
 
     /* Step 6 : Configure a Auto-Refresh command */
-    command->CommandMode           = FMC_SDRAM_CMD_AUTOREFRESH_MODE;
-    command->CommandTarget         = FMC_SDRAM_CMD_TARGET_BANK;
-    command->AutoRefreshNumber     = MICROPY_HW_SDRAM_AUTOREFRESH_NUM;
+    command->CommandMode = FMC_SDRAM_CMD_AUTOREFRESH_MODE;
+    command->CommandTarget = FMC_SDRAM_CMD_TARGET_BANK;
+    command->AutoRefreshNumber = MICROPY_HW_SDRAM_AUTOREFRESH_NUM;
     command->ModeRegisterDefinition = 0;
 
     /* Send the command */
@@ -218,14 +217,14 @@
 
     /* Step 7: Program the external memory mode register */
     tmpmrd = (uint32_t)FMC_INIT(SDRAM_MODEREG_BURST_LENGTH, MICROPY_HW_SDRAM_BURST_LENGTH) |
-        SDRAM_MODEREG_BURST_TYPE_SEQUENTIAL   |
+        SDRAM_MODEREG_BURST_TYPE_SEQUENTIAL |
         FMC_INIT(SDRAM_MODEREG_CAS_LATENCY, MICROPY_HW_SDRAM_CAS_LATENCY) |
         SDRAM_MODEREG_OPERATING_MODE_STANDARD |
         SDRAM_MODEREG_WRITEBURST_MODE_SINGLE;
 
-    command->CommandMode           = FMC_SDRAM_CMD_LOAD_MODE;
-    command->CommandTarget         = FMC_SDRAM_CMD_TARGET_BANK;
-    command->AutoRefreshNumber     = 1;
+    command->CommandMode = FMC_SDRAM_CMD_LOAD_MODE;
+    command->CommandTarget = FMC_SDRAM_CMD_TARGET_BANK;
+    command->AutoRefreshNumber = 1;
     command->ModeRegisterDefinition = tmpmrd;
 
     /* Send the command */
@@ -258,7 +257,7 @@
 bool sdram_test(bool fast) {
     uint8_t const pattern = 0xaa;
     uint8_t const antipattern = 0x55;
-    uint8_t *const mem_base = (uint8_t*)sdram_start();
+    uint8_t *const mem_base = (uint8_t *)sdram_start();
 
     /* test data bus */
     for (uint8_t i = 1; i; i <<= 1) {
diff --git a/ports/stm32/servo.c b/ports/stm32/servo.c
index b239880..a368b57 100644
--- a/ports/stm32/servo.c
+++ b/ports/stm32/servo.c
@@ -125,7 +125,7 @@
 
 STATIC void servo_init_channel(pyb_servo_obj_t *s) {
     static const uint8_t channel_table[4] =
-        {TIM_CHANNEL_1, TIM_CHANNEL_2, TIM_CHANNEL_3, TIM_CHANNEL_4};
+    {TIM_CHANNEL_1, TIM_CHANNEL_2, TIM_CHANNEL_3, TIM_CHANNEL_4};
     uint32_t channel = channel_table[s->pin->pin];
 
     // GPIO configuration
@@ -153,13 +153,25 @@
 STATIC mp_obj_t pyb_servo_set(mp_obj_t port, mp_obj_t value) {
     int p = mp_obj_get_int(port);
     int v = mp_obj_get_int(value);
-    if (v < 50) { v = 50; }
-    if (v > 250) { v = 250; }
+    if (v < 50) {
+        v = 50;
+    }
+    if (v > 250) {
+        v = 250;
+    }
     switch (p) {
-        case 1: TIM5->CCR1 = v; break;
-        case 2: TIM5->CCR2 = v; break;
-        case 3: TIM5->CCR3 = v; break;
-        case 4: TIM5->CCR4 = v; break;
+        case 1:
+            TIM5->CCR1 = v;
+            break;
+        case 2:
+            TIM5->CCR2 = v;
+            break;
+        case 3:
+            TIM5->CCR3 = v;
+            break;
+        case 4:
+            TIM5->CCR4 = v;
+            break;
     }
     return mp_const_none;
 }
@@ -265,11 +277,11 @@
         // get angle
         return mp_obj_new_int((self->pulse_cur - self->pulse_centre) * 90 / self->pulse_angle_90);
     } else {
-#if MICROPY_PY_BUILTINS_FLOAT
+        #if MICROPY_PY_BUILTINS_FLOAT
         self->pulse_dest = self->pulse_centre + self->pulse_angle_90 * mp_obj_get_float(args[1]) / 90.0;
-#else
+        #else
         self->pulse_dest = self->pulse_centre + self->pulse_angle_90 * mp_obj_get_int(args[1]) / 90;
-#endif
+        #endif
         if (n_args == 2) {
             // set angle immediately
             self->time_left = 0;
@@ -295,11 +307,11 @@
         // get speed
         return mp_obj_new_int((self->pulse_cur - self->pulse_centre) * 100 / self->pulse_speed_100);
     } else {
-#if MICROPY_PY_BUILTINS_FLOAT
+        #if MICROPY_PY_BUILTINS_FLOAT
         self->pulse_dest = self->pulse_centre + self->pulse_speed_100 * mp_obj_get_float(args[1]) / 100.0;
-#else
+        #else
         self->pulse_dest = self->pulse_centre + self->pulse_speed_100 * mp_obj_get_int(args[1]) / 100;
-#endif
+        #endif
         if (n_args == 2) {
             // set speed immediately
             self->time_left = 0;
@@ -329,7 +341,7 @@
     .name = MP_QSTR_Servo,
     .print = pyb_servo_print,
     .make_new = pyb_servo_make_new,
-    .locals_dict = (mp_obj_dict_t*)&pyb_servo_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_servo_locals_dict,
 };
 
 #endif // MICROPY_HW_ENABLE_SERVO
diff --git a/ports/stm32/softtimer.c b/ports/stm32/softtimer.c
index 60c2709..ae87e1f 100644
--- a/ports/stm32/softtimer.c
+++ b/ports/stm32/softtimer.c
@@ -41,8 +41,8 @@
 }
 
 STATIC int soft_timer_lt(mp_pairheap_t *n1, mp_pairheap_t *n2) {
-    soft_timer_entry_t *e1 = (soft_timer_entry_t*)n1;
-    soft_timer_entry_t *e2 = (soft_timer_entry_t*)n2;
+    soft_timer_entry_t *e1 = (soft_timer_entry_t *)n1;
+    soft_timer_entry_t *e2 = (soft_timer_entry_t *)n2;
     return TICKS_DIFF(e1->expiry_ms, e2->expiry_ms) < 0;
 }
 
@@ -63,11 +63,11 @@
     soft_timer_entry_t *heap = MP_STATE_PORT(soft_timer_heap);
     while (heap != NULL && TICKS_DIFF(heap->expiry_ms, ticks_ms) <= 0) {
         soft_timer_entry_t *entry = heap;
-        heap = (soft_timer_entry_t*)mp_pairheap_pop(soft_timer_lt, &heap->pairheap);
+        heap = (soft_timer_entry_t *)mp_pairheap_pop(soft_timer_lt, &heap->pairheap);
         mp_sched_schedule(entry->callback, MP_OBJ_FROM_PTR(entry));
         if (entry->mode == SOFT_TIMER_MODE_PERIODIC) {
             entry->expiry_ms += entry->delta_ms;
-            heap = (soft_timer_entry_t*)mp_pairheap_push(soft_timer_lt, &heap->pairheap, &entry->pairheap);
+            heap = (soft_timer_entry_t *)mp_pairheap_push(soft_timer_lt, &heap->pairheap, &entry->pairheap);
         }
     }
     MP_STATE_PORT(soft_timer_heap) = heap;
@@ -82,7 +82,7 @@
 
 void soft_timer_insert(soft_timer_entry_t *entry) {
     uint32_t irq_state = raise_irq_pri(IRQ_PRI_PENDSV);
-    MP_STATE_PORT(soft_timer_heap) = (soft_timer_entry_t*)mp_pairheap_push(soft_timer_lt, &MP_STATE_PORT(soft_timer_heap)->pairheap, &entry->pairheap);
+    MP_STATE_PORT(soft_timer_heap) = (soft_timer_entry_t *)mp_pairheap_push(soft_timer_lt, &MP_STATE_PORT(soft_timer_heap)->pairheap, &entry->pairheap);
     if (entry == MP_STATE_PORT(soft_timer_heap)) {
         // This new timer became the earliest one so set soft_timer_next
         soft_timer_schedule_systick(entry->expiry_ms);
@@ -92,6 +92,6 @@
 
 void soft_timer_remove(soft_timer_entry_t *entry) {
     uint32_t irq_state = raise_irq_pri(IRQ_PRI_PENDSV);
-    MP_STATE_PORT(soft_timer_heap) = (soft_timer_entry_t*)mp_pairheap_delete(soft_timer_lt, &MP_STATE_PORT(soft_timer_heap)->pairheap, &entry->pairheap);
+    MP_STATE_PORT(soft_timer_heap) = (soft_timer_entry_t *)mp_pairheap_delete(soft_timer_lt, &MP_STATE_PORT(soft_timer_heap)->pairheap, &entry->pairheap);
     restore_irq_pri(irq_state);
 }
diff --git a/ports/stm32/spi.c b/ports/stm32/spi.c
index 1095e96..50cebff 100644
--- a/ports/stm32/spi.c
+++ b/ports/stm32/spi.c
@@ -100,22 +100,46 @@
 #if defined(STM32H7)
 // STM32H7 HAL requires SPI IRQs to be enabled and handled.
 #if defined(MICROPY_HW_SPI1_SCK)
-void SPI1_IRQHandler(void) { IRQ_ENTER(SPI1_IRQn); HAL_SPI_IRQHandler(&SPIHandle1); IRQ_EXIT(SPI1_IRQn); }
+void SPI1_IRQHandler(void) {
+    IRQ_ENTER(SPI1_IRQn);
+    HAL_SPI_IRQHandler(&SPIHandle1);
+    IRQ_EXIT(SPI1_IRQn);
+}
 #endif
 #if defined(MICROPY_HW_SPI2_SCK)
-void SPI2_IRQHandler(void) { IRQ_ENTER(SPI2_IRQn); HAL_SPI_IRQHandler(&SPIHandle2); IRQ_EXIT(SPI2_IRQn); }
+void SPI2_IRQHandler(void) {
+    IRQ_ENTER(SPI2_IRQn);
+    HAL_SPI_IRQHandler(&SPIHandle2);
+    IRQ_EXIT(SPI2_IRQn);
+}
 #endif
 #if defined(MICROPY_HW_SPI3_SCK)
-void SPI3_IRQHandler(void) { IRQ_ENTER(SPI3_IRQn); HAL_SPI_IRQHandler(&SPIHandle3); IRQ_EXIT(SPI3_IRQn); }
+void SPI3_IRQHandler(void) {
+    IRQ_ENTER(SPI3_IRQn);
+    HAL_SPI_IRQHandler(&SPIHandle3);
+    IRQ_EXIT(SPI3_IRQn);
+}
 #endif
 #if defined(MICROPY_HW_SPI4_SCK)
-void SPI4_IRQHandler(void) { IRQ_ENTER(SPI4_IRQn); HAL_SPI_IRQHandler(&SPIHandle4); IRQ_EXIT(SPI4_IRQn); }
+void SPI4_IRQHandler(void) {
+    IRQ_ENTER(SPI4_IRQn);
+    HAL_SPI_IRQHandler(&SPIHandle4);
+    IRQ_EXIT(SPI4_IRQn);
+}
 #endif
 #if defined(MICROPY_HW_SPI5_SCK)
-void SPI5_IRQHandler(void) { IRQ_ENTER(SPI5_IRQn); HAL_SPI_IRQHandler(&SPIHandle5); IRQ_EXIT(SPI5_IRQn); }
+void SPI5_IRQHandler(void) {
+    IRQ_ENTER(SPI5_IRQn);
+    HAL_SPI_IRQHandler(&SPIHandle5);
+    IRQ_EXIT(SPI5_IRQn);
+}
 #endif
 #if defined(MICROPY_HW_SPI6_SCK)
-void SPI6_IRQHandler(void) { IRQ_ENTER(SPI6_IRQn); HAL_SPI_IRQHandler(&SPIHandle6); IRQ_EXIT(SPI6_IRQn); }
+void SPI6_IRQHandler(void) {
+    IRQ_ENTER(SPI6_IRQn);
+    HAL_SPI_IRQHandler(&SPIHandle6);
+    IRQ_EXIT(SPI6_IRQn);
+}
 #endif
 #endif
 
@@ -227,14 +251,23 @@
             // prescaler not given, so select one that yields at most the requested baudrate
             prescale = (spi_get_source_freq(spi) + baudrate - 1) / baudrate;
         }
-        if (prescale <= 2) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2; }
-        else if (prescale <= 4) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4; }
-        else if (prescale <= 8) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8; }
-        else if (prescale <= 16) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16; }
-        else if (prescale <= 32) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32; }
-        else if (prescale <= 64) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64; }
-        else if (prescale <= 128) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128; }
-        else { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256; }
+        if (prescale <= 2) {
+            init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
+        } else if (prescale <= 4) {
+            init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4;
+        } else if (prescale <= 8) {
+            init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
+        } else if (prescale <= 16) {
+            init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16;
+        } else if (prescale <= 32) {
+            init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32;
+        } else if (prescale <= 64) {
+            init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64;
+        } else if (prescale <= 128) {
+            init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128;
+        } else {
+            init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256;
+        }
     }
 
     if (polarity != -1) {
@@ -378,9 +411,9 @@
     #if defined(STM32H7)
     NVIC_SetPriority(irqn, IRQ_PRI_SPI);
     HAL_NVIC_EnableIRQ(irqn);
-    #else 
+    #else
     (void)irqn;
-    #endif 
+    #endif
 }
 
 void spi_deinit(const spi_t *spi_obj) {
@@ -462,7 +495,7 @@
     if (dest == NULL) {
         // send only
         if (len == 1 || query_irq() == IRQ_STATE_DISABLED) {
-            status = HAL_SPI_Transmit(self->spi, (uint8_t*)src, len, timeout);
+            status = HAL_SPI_Transmit(self->spi, (uint8_t *)src, len, timeout);
         } else {
             DMA_HandleTypeDef tx_dma;
             dma_init(&tx_dma, self->tx_dma_descr, DMA_MEMORY_TO_PERIPH, self->spi);
@@ -472,7 +505,7 @@
             uint32_t t_start = HAL_GetTick();
             do {
                 uint32_t l = MIN(len, 65535);
-                status = HAL_SPI_Transmit_DMA(self->spi, (uint8_t*)src, l);
+                status = HAL_SPI_Transmit_DMA(self->spi, (uint8_t *)src, l);
                 if (status != HAL_OK) {
                     break;
                 }
@@ -523,7 +556,7 @@
     } else {
         // send and receive
         if (len == 1 || query_irq() == IRQ_STATE_DISABLED) {
-            status = HAL_SPI_TransmitReceive(self->spi, (uint8_t*)src, dest, len, timeout);
+            status = HAL_SPI_TransmitReceive(self->spi, (uint8_t *)src, dest, len, timeout);
         } else {
             DMA_HandleTypeDef tx_dma, rx_dma;
             dma_init(&tx_dma, self->tx_dma_descr, DMA_MEMORY_TO_PERIPH, self->spi);
@@ -535,7 +568,7 @@
             uint32_t t_start = HAL_GetTick();
             do {
                 uint32_t l = MIN(len, 65535);
-                status = HAL_SPI_TransmitReceive_DMA(self->spi, (uint8_t*)src, dest, l);
+                status = HAL_SPI_TransmitReceive_DMA(self->spi, (uint8_t *)src, dest, l);
                 if (status != HAL_OK) {
                     break;
                 }
@@ -561,21 +594,32 @@
     SPI_HandleTypeDef *spi = spi_obj->spi;
 
     uint spi_num = 1; // default to SPI1
-    if (0) { }
+    if (0) {
+    }
     #if defined(SPI2)
-    else if (spi->Instance == SPI2) { spi_num = 2; }
+    else if (spi->Instance == SPI2) {
+        spi_num = 2;
+    }
     #endif
     #if defined(SPI3)
-    else if (spi->Instance == SPI3) { spi_num = 3; }
+    else if (spi->Instance == SPI3) {
+        spi_num = 3;
+    }
     #endif
     #if defined(SPI4)
-    else if (spi->Instance == SPI4) { spi_num = 4; }
+    else if (spi->Instance == SPI4) {
+        spi_num = 4;
+    }
     #endif
     #if defined(SPI5)
-    else if (spi->Instance == SPI5) { spi_num = 5; }
+    else if (spi->Instance == SPI5) {
+        spi_num = 5;
+    }
     #endif
     #if defined(SPI6)
-    else if (spi->Instance == SPI6) { spi_num = 6; }
+    else if (spi->Instance == SPI6) {
+        spi_num = 6;
+    }
     #endif
 
     mp_printf(print, "SPI(%u", spi_num);
@@ -618,7 +662,7 @@
 // Implementation of low-level SPI C protocol
 
 STATIC int spi_proto_ioctl(void *self_in, uint32_t cmd) {
-    spi_proto_cfg_t *self = (spi_proto_cfg_t*)self_in;
+    spi_proto_cfg_t *self = (spi_proto_cfg_t *)self_in;
 
     switch (cmd) {
         case MP_SPI_IOCTL_INIT:
@@ -641,7 +685,7 @@
 }
 
 STATIC void spi_proto_transfer(void *self_in, size_t len, const uint8_t *src, uint8_t *dest) {
-    spi_proto_cfg_t *self = (spi_proto_cfg_t*)self_in;
+    spi_proto_cfg_t *self = (spi_proto_cfg_t *)self_in;
     spi_transfer(self->spi, len, src, dest, SPI_TRANSFER_TIMEOUT(len));
 }
 
diff --git a/ports/stm32/spibdev.c b/ports/stm32/spibdev.c
index 97ce885..05c8819 100644
--- a/ports/stm32/spibdev.c
+++ b/ports/stm32/spibdev.c
@@ -35,7 +35,7 @@
 int32_t spi_bdev_ioctl(spi_bdev_t *bdev, uint32_t op, uint32_t arg) {
     switch (op) {
         case BDEV_IOCTL_INIT:
-            bdev->spiflash.config = (const mp_spiflash_config_t*)arg;
+            bdev->spiflash.config = (const mp_spiflash_config_t *)arg;
             mp_spiflash_init(&bdev->spiflash);
             bdev->flash_tick_counter_last_write = 0;
             return 0;
diff --git a/ports/stm32/stm32_it.c b/ports/stm32/stm32_it.c
index 1a22272..b84f4ad 100644
--- a/ports/stm32/stm32_it.c
+++ b/ports/stm32/stm32_it.c
@@ -83,7 +83,7 @@
 #include "i2c.h"
 #include "usb.h"
 
-extern void __fatal_error(const char*);
+extern void __fatal_error(const char *);
 #if defined(MICROPY_HW_USB_FS)
 extern PCD_HandleTypeDef pcd_fs_handle;
 #endif
@@ -107,9 +107,9 @@
     buf[2] = hexDig[(val >> 20) & 0x0f];
     buf[3] = hexDig[(val >> 16) & 0x0f];
     buf[4] = hexDig[(val >> 12) & 0x0f];
-    buf[5] = hexDig[(val >>  8) & 0x0f];
-    buf[6] = hexDig[(val >>  4) & 0x0f];
-    buf[7] = hexDig[(val >>  0) & 0x0f];
+    buf[5] = hexDig[(val >> 8) & 0x0f];
+    buf[6] = hexDig[(val >> 4) & 0x0f];
+    buf[7] = hexDig[(val >> 0) & 0x0f];
     buf[8] = '\0';
 
     return buf;
@@ -137,7 +137,7 @@
 // // stack: R0, R1, R2, R3, R12, LR, PC, XPSR
 
 typedef struct {
-    uint32_t    r0, r1, r2, r3, r12, lr, pc, xpsr;
+    uint32_t r0, r1, r2, r3, r12, lr, pc, xpsr;
 } ExceptionRegisters_t;
 
 int pyb_hard_fault_debug = 0;
@@ -178,14 +178,14 @@
     }
     #endif
 
-    if ((void*)&_ram_start <= (void*)regs && (void*)regs < (void*)&_ram_end) {
+    if ((void *)&_ram_start <= (void *)regs && (void *)regs < (void *)&_ram_end) {
         mp_hal_stdout_tx_str("Stack:\r\n");
         uint32_t *stack_top = &_estack;
-        if ((void*)regs < (void*)&_sstack) {
+        if ((void *)regs < (void *)&_sstack) {
             // stack not in static stack area so limit the amount we print
-            stack_top = (uint32_t*)regs + 32;
+            stack_top = (uint32_t *)regs + 32;
         }
-        for (uint32_t *sp = (uint32_t*)regs; sp < stack_top; ++sp) {
+        for (uint32_t *sp = (uint32_t *)regs; sp < stack_top; ++sp) {
             print_hex_hex("  ", (uint32_t)sp, *sp);
         }
     }
@@ -210,23 +210,23 @@
     // was stacked up using the process stack pointer (aka PSP).
 
     #if __CORTEX_M == 0
-    __asm volatile(
-    " mov r0, lr    \n"
-    " lsr r0, r0, #3 \n"        // Shift Bit 3 into carry to see which stack pointer we should use.
-    " mrs r0, msp   \n"         // Make R0 point to main stack pointer
-    " bcc .use_msp  \n"         // Keep MSP in R0 if SPSEL (carry) is 0
-    " mrs r0, psp   \n"         // Make R0 point to process stack pointer
-    " .use_msp:     \n"
-    " b HardFault_C_Handler \n" // Off to C land
-    );
+    __asm volatile (
+        " mov r0, lr    \n"
+        " lsr r0, r0, #3 \n"    // Shift Bit 3 into carry to see which stack pointer we should use.
+        " mrs r0, msp   \n"     // Make R0 point to main stack pointer
+        " bcc .use_msp  \n"     // Keep MSP in R0 if SPSEL (carry) is 0
+        " mrs r0, psp   \n"     // Make R0 point to process stack pointer
+        " .use_msp:     \n"
+        " b HardFault_C_Handler \n" // Off to C land
+        );
     #else
-    __asm volatile(
-    " tst lr, #4    \n"         // Test Bit 3 to see which stack pointer we should use.
-    " ite eq        \n"         // Tell the assembler that the nest 2 instructions are if-then-else
-    " mrseq r0, msp \n"         // Make R0 point to main stack pointer
-    " mrsne r0, psp \n"         // Make R0 point to process stack pointer
-    " b HardFault_C_Handler \n" // Off to C land
-    );
+    __asm volatile (
+        " tst lr, #4    \n"     // Test Bit 3 to see which stack pointer we should use.
+        " ite eq        \n"     // Tell the assembler that the nest 2 instructions are if-then-else
+        " mrseq r0, msp \n"     // Make R0 point to main stack pointer
+        " mrsne r0, psp \n"     // Make R0 point to process stack pointer
+        " b HardFault_C_Handler \n" // Off to C land
+        );
     #endif
 }
 
@@ -343,43 +343,43 @@
   */
 STATIC void OTG_CMD_WKUP_Handler(PCD_HandleTypeDef *pcd_handle) {
 
-  if (pcd_handle->Init.low_power_enable) {
-    /* Reset SLEEPDEEP bit of Cortex System Control Register */
-    SCB->SCR &= (uint32_t)~((uint32_t)(SCB_SCR_SLEEPDEEP_Msk | SCB_SCR_SLEEPONEXIT_Msk));
+    if (pcd_handle->Init.low_power_enable) {
+        /* Reset SLEEPDEEP bit of Cortex System Control Register */
+        SCB->SCR &= (uint32_t) ~((uint32_t)(SCB_SCR_SLEEPDEEP_Msk | SCB_SCR_SLEEPONEXIT_Msk));
 
-    /* Configures system clock after wake-up from STOP: enable HSE/HSI, PLL and select
-    PLL as system clock source (HSE/HSI and PLL are disabled in STOP mode) */
+        /* Configures system clock after wake-up from STOP: enable HSE/HSI, PLL and select
+        PLL as system clock source (HSE/HSI and PLL are disabled in STOP mode) */
 
-    __HAL_RCC_HSE_CONFIG(MICROPY_HW_RCC_HSE_STATE);
-    #if MICROPY_HW_CLK_USE_HSI
-    __HAL_RCC_HSI_ENABLE();
-    #endif
+        __HAL_RCC_HSE_CONFIG(MICROPY_HW_RCC_HSE_STATE);
+        #if MICROPY_HW_CLK_USE_HSI
+        __HAL_RCC_HSI_ENABLE();
+        #endif
 
-    /* Wait till HSE/HSI is ready */
-    while(__HAL_RCC_GET_FLAG(MICROPY_HW_RCC_FLAG_HSxRDY) == RESET)
-    {}
+        /* Wait till HSE/HSI is ready */
+        while (__HAL_RCC_GET_FLAG(MICROPY_HW_RCC_FLAG_HSxRDY) == RESET) {
+        }
 
-    /* Enable the main PLL. */
-    __HAL_RCC_PLL_ENABLE();
+        /* Enable the main PLL. */
+        __HAL_RCC_PLL_ENABLE();
 
-    /* Wait till PLL is ready */
-    while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET)
-    {}
+        /* Wait till PLL is ready */
+        while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) {
+        }
 
-    /* Select PLL as SYSCLK */
-    MODIFY_REG(RCC->CFGR, RCC_CFGR_SW, RCC_SYSCLKSOURCE_PLLCLK);
+        /* Select PLL as SYSCLK */
+        MODIFY_REG(RCC->CFGR, RCC_CFGR_SW, RCC_SYSCLKSOURCE_PLLCLK);
 
-    #if defined(STM32H7)
-    while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_PLL1)
-    {}
-    #else
-    while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_PLL)
-    {}
-    #endif
+        #if defined(STM32H7)
+        while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_PLL1) {
+        }
+        #else
+        while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_PLL) {
+        }
+        #endif
 
-    /* ungate PHY clock */
-     __HAL_PCD_UNGATE_PHYCLOCK(pcd_handle);
-  }
+        /* ungate PHY clock */
+        __HAL_PCD_UNGATE_PHYCLOCK(pcd_handle);
+    }
 
 }
 #endif
@@ -393,12 +393,12 @@
 void OTG_FS_WKUP_IRQHandler(void) {
     IRQ_ENTER(OTG_FS_WKUP_IRQn);
 
-  OTG_CMD_WKUP_Handler(&pcd_fs_handle);
+    OTG_CMD_WKUP_Handler(&pcd_fs_handle);
 
-  #if !defined(STM32H7)
-  /* Clear EXTI pending Bit*/
-  __HAL_USB_FS_EXTI_CLEAR_FLAG();
-  #endif
+    #if !defined(STM32H7)
+    /* Clear EXTI pending Bit*/
+    __HAL_USB_FS_EXTI_CLEAR_FLAG();
+    #endif
 
     IRQ_EXIT(OTG_FS_WKUP_IRQn);
 }
@@ -413,12 +413,12 @@
 void OTG_HS_WKUP_IRQHandler(void) {
     IRQ_ENTER(OTG_HS_WKUP_IRQn);
 
-  OTG_CMD_WKUP_Handler(&pcd_hs_handle);
+    OTG_CMD_WKUP_Handler(&pcd_hs_handle);
 
-  #if !defined(STM32H7)
-  /* Clear EXTI pending Bit*/
-  __HAL_USB_HS_EXTI_CLEAR_FLAG();
-  #endif
+    #if !defined(STM32H7)
+    /* Clear EXTI pending Bit*/
+    __HAL_USB_HS_EXTI_CLEAR_FLAG();
+    #endif
 
     IRQ_EXIT(OTG_HS_WKUP_IRQn);
 }
@@ -512,7 +512,7 @@
 }
 
 #if defined(ETH)    // The 407 has ETH, the 405 doesn't
-void ETH_WKUP_IRQHandler(void)  {
+void ETH_WKUP_IRQHandler(void) {
     IRQ_ENTER(ETH_WKUP_IRQn);
     Handle_EXTI_Irq(EXTI_ETH_WAKEUP);
     IRQ_EXIT(ETH_WKUP_IRQn);
diff --git a/ports/stm32/storage.c b/ports/stm32/storage.c
index 7e131f0..0fa3750 100644
--- a/ports/stm32/storage.c
+++ b/ports/stm32/storage.c
@@ -384,8 +384,12 @@
             }
             return MP_OBJ_NEW_SMALL_INT(ret);
         }
-        case MP_BLOCKDEV_IOCTL_DEINIT: storage_flush(); return MP_OBJ_NEW_SMALL_INT(0); // TODO properly
-        case MP_BLOCKDEV_IOCTL_SYNC: storage_flush(); return MP_OBJ_NEW_SMALL_INT(0);
+        case MP_BLOCKDEV_IOCTL_DEINIT:
+            storage_flush();
+            return MP_OBJ_NEW_SMALL_INT(0);                                             // TODO properly
+        case MP_BLOCKDEV_IOCTL_SYNC:
+            storage_flush();
+            return MP_OBJ_NEW_SMALL_INT(0);
 
         case MP_BLOCKDEV_IOCTL_BLOCK_COUNT: {
             mp_int_t n;
@@ -423,7 +427,8 @@
             return MP_OBJ_NEW_SMALL_INT(ret);
         }
 
-        default: return mp_const_none;
+        default:
+            return mp_const_none;
     }
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_3(pyb_flash_ioctl_obj, pyb_flash_ioctl);
@@ -441,7 +446,7 @@
     .name = MP_QSTR_Flash,
     .print = pyb_flash_print,
     .make_new = pyb_flash_make_new,
-    .locals_dict = (mp_obj_dict_t*)&pyb_flash_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_flash_locals_dict,
 };
 
 void pyb_flash_init_vfs(fs_user_mount_t *vfs) {
diff --git a/ports/stm32/system_stm32.c b/ports/stm32/system_stm32.c
index 46dd58b..30c8bfd 100644
--- a/ports/stm32/system_stm32.c
+++ b/ports/stm32/system_stm32.c
@@ -163,8 +163,7 @@
   *
   * Timers run from APBx if APBx_PRESC=1, else 2x APBx
   */
-void SystemClock_Config(void)
-{
+void SystemClock_Config(void) {
     #if defined(STM32F7)
     // The DFU bootloader changes the clocksource register from its default power
     // on reset value, so we set it back here, so the clocksources are the same
@@ -225,7 +224,7 @@
     RCC_OscInitStruct.PLL.PLLR = MICROPY_HW_CLK_PLLR;
     RCC_OscInitStruct.MSIState = RCC_MSI_OFF;
     #else
-    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE|RCC_OSCILLATORTYPE_MSI;
+    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_MSI;
     RCC_OscInitStruct.MSIState = RCC_MSI_ON;
     RCC_OscInitStruct.MSICalibrationValue = RCC_MSICALIBRATION_DEFAULT;
     RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6;
@@ -247,7 +246,7 @@
     RCC_ClkInitStruct.ClockType |= (RCC_CLOCKTYPE_D3PCLK1 | RCC_CLOCKTYPE_D1PCLK1);
     #endif
 
-#if defined(MICROPY_HW_CLK_LAST_FREQ) && MICROPY_HW_CLK_LAST_FREQ
+    #if defined(MICROPY_HW_CLK_LAST_FREQ) && MICROPY_HW_CLK_LAST_FREQ
     #if defined(STM32F7)
     #define FREQ_BKP BKP31R
     #elif defined(STM32L4)
@@ -265,7 +264,7 @@
     uint32_t b1 = (m >> 26) & 0x7;
     uint32_t b2 = (m >> 29) & 0x7;
     q = (m >> 18) & 0xf;
-    p = (((m >> 16) & 0x03)+1)*2;
+    p = (((m >> 16) & 0x03) + 1) * 2;
     n = (m >> 6) & 0x3ff;
     m &= 0x3f;
     if ((q < 2) || (q > 15) || (p > 8) || (p < 2) || (n < 192) || (n >= 433) || (m < 2)) {
@@ -289,7 +288,7 @@
     RCC_ClkInitStruct.AHBCLKDivider = h;  //RCC_SYSCLK_DIV1;
     RCC_ClkInitStruct.APB1CLKDivider = b1; //RCC_HCLK_DIV4;
     RCC_ClkInitStruct.APB2CLKDivider = b2; //RCC_HCLK_DIV2;
-#else // defined(MICROPY_HW_CLK_LAST_FREQ) && MICROPY_HW_CLK_LAST_FREQ
+    #else // defined(MICROPY_HW_CLK_LAST_FREQ) && MICROPY_HW_CLK_LAST_FREQ
     RCC_OscInitStruct.PLL.PLLM = MICROPY_HW_CLK_PLLM;
     RCC_OscInitStruct.PLL.PLLN = MICROPY_HW_CLK_PLLN;
     RCC_OscInitStruct.PLL.PLLP = MICROPY_HW_CLK_PLLP;
@@ -305,28 +304,28 @@
     #endif
 
     #if defined(STM32F4) || defined(STM32F7)
-    RCC_ClkInitStruct.AHBCLKDivider  = RCC_SYSCLK_DIV1;
+    RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
     RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
     RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
     #elif defined(STM32L4)
-    RCC_ClkInitStruct.AHBCLKDivider  = RCC_SYSCLK_DIV1;
+    RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
     RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
     RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
     #elif defined(STM32H7)
-    RCC_ClkInitStruct.SYSCLKDivider  = RCC_SYSCLK_DIV1;
-    RCC_ClkInitStruct.AHBCLKDivider  = RCC_HCLK_DIV2;
+    RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1;
+    RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV2;
     RCC_ClkInitStruct.APB3CLKDivider = RCC_APB3_DIV2;
     RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV2;
     RCC_ClkInitStruct.APB2CLKDivider = RCC_APB2_DIV2;
     RCC_ClkInitStruct.APB4CLKDivider = RCC_APB4_DIV2;
     #endif
-#endif
+    #endif
 
-    if(HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
-      __fatal_error("HAL_RCC_OscConfig");
+    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
+        __fatal_error("HAL_RCC_OscConfig");
     }
 
-#if defined(STM32H7)
+    #if defined(STM32H7)
     /* PLL3 for USB Clock */
     PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USB;
     PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_PLL3;
@@ -341,15 +340,14 @@
     if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) {
         __fatal_error("HAL_RCCEx_PeriphCLKConfig");
     }
-#endif
+    #endif
 
-#if defined(STM32F7)
-  /* Activate the OverDrive to reach the 200 MHz Frequency */
-  if (HAL_PWREx_EnableOverDrive() != HAL_OK)
-  {
-    __fatal_error("HAL_PWREx_EnableOverDrive");
-  }
-#endif
+    #if defined(STM32F7)
+    /* Activate the OverDrive to reach the 200 MHz Frequency */
+    if (HAL_PWREx_EnableOverDrive() != HAL_OK) {
+        __fatal_error("HAL_PWREx_EnableOverDrive");
+    }
+    #endif
 
     uint32_t vco_out = RCC_OscInitStruct.PLL.PLLN * (MICROPY_HW_CLK_VALUE / 1000000) / RCC_OscInitStruct.PLL.PLLM;
     uint32_t sysclk_mhz = vco_out / RCC_OscInitStruct.PLL.PLLP;
@@ -358,28 +356,28 @@
         __fatal_error("HAL_RCC_ClockConfig");
     }
 
-#if defined(STM32H7)
-  /* Activate CSI clock mandatory for I/O Compensation Cell*/
-  __HAL_RCC_CSI_ENABLE() ;
+    #if defined(STM32H7)
+    /* Activate CSI clock mandatory for I/O Compensation Cell*/
+    __HAL_RCC_CSI_ENABLE();
 
-  /* Enable SYSCFG clock mandatory for I/O Compensation Cell */
-  __HAL_RCC_SYSCFG_CLK_ENABLE() ;
+    /* Enable SYSCFG clock mandatory for I/O Compensation Cell */
+    __HAL_RCC_SYSCFG_CLK_ENABLE();
 
-  /* Enable the I/O Compensation Cell */
-  HAL_EnableCompensationCell();
+    /* Enable the I/O Compensation Cell */
+    HAL_EnableCompensationCell();
 
-  /* Enable the USB voltage level detector */
-  HAL_PWREx_EnableUSBVoltageDetector();
-#endif
+    /* Enable the USB voltage level detector */
+    HAL_PWREx_EnableUSBVoltageDetector();
+    #endif
 
-#if defined(STM32L4)
+    #if defined(STM32L4)
     // Enable MSI-Hardware auto calibration mode with LSE
     HAL_RCCEx_EnableMSIPLLMode();
 
     RCC_PeriphCLKInitTypeDef PeriphClkInitStruct;
-    PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_SAI1|RCC_PERIPHCLK_I2C1
-                                              |RCC_PERIPHCLK_USB |RCC_PERIPHCLK_ADC
-                                              |RCC_PERIPHCLK_RNG |RCC_PERIPHCLK_RTC;
+    PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_SAI1 | RCC_PERIPHCLK_I2C1
+        | RCC_PERIPHCLK_USB | RCC_PERIPHCLK_ADC
+        | RCC_PERIPHCLK_RNG | RCC_PERIPHCLK_RTC;
     PeriphClkInitStruct.I2c1ClockSelection = RCC_I2C1CLKSOURCE_PCLK1;
 
     PeriphClkInitStruct.Sai1ClockSelection = RCC_SAI1CLKSOURCE_PLLSAI1;
@@ -412,11 +410,10 @@
     PeriphClkInitStruct.PLLSAI1.PLLSAI1R = RCC_PLLR_DIV2;
     #endif
     PeriphClkInitStruct.PLLSAI1.PLLSAI1ClockOut = RCC_PLLSAI1_SAI1CLK
-                                                 |RCC_PLLSAI1_48M2CLK
-                                                 |RCC_PLLSAI1_ADC1CLK;
+        | RCC_PLLSAI1_48M2CLK
+        | RCC_PLLSAI1_ADC1CLK;
 
-    if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
-    {
+    if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) {
         __fatal_error("HAL_RCCEx_PeriphCLKConfig");
     }
 
@@ -424,10 +421,10 @@
 
     HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);
 
-    HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);
+    HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq() / 1000);
     HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
     NVIC_SetPriority(SysTick_IRQn, NVIC_EncodePriority(NVIC_PRIORITYGROUP_4, TICK_INT_PRIORITY, 0));
-#endif
+    #endif
 }
 
 #endif
diff --git a/ports/stm32/systick.c b/ports/stm32/systick.c
index 85c99b9..d70fc00 100644
--- a/ports/stm32/systick.c
+++ b/ports/stm32/systick.c
@@ -154,7 +154,7 @@
     mp_uint_t irq_state = disable_irq();
     uint32_t counter = SysTick->VAL;
     uint32_t milliseconds = HAL_GetTick();
-    uint32_t status  = SysTick->CTRL;
+    uint32_t status = SysTick->CTRL;
     enable_irq(irq_state);
 
     // It's still possible for the countflag bit to get set if the counter was
diff --git a/ports/stm32/timer.c b/ports/stm32/timer.c
index 0c120e7..1b32d8a 100644
--- a/ports/stm32/timer.c
+++ b/ports/stm32/timer.c
@@ -94,8 +94,8 @@
 } pyb_channel_mode;
 
 STATIC const struct {
-    qstr        name;
-    uint32_t    oc_mode;
+    qstr name;
+    uint32_t oc_mode;
 } channel_mode_info[] = {
     { MP_QSTR_PWM,                TIM_OCMODE_PWM1 },
     { MP_QSTR_PWM_INVERTED,       TIM_OCMODE_PWM2 },
@@ -295,7 +295,7 @@
         mp_int_t freq = mp_obj_get_int(freq_in);
         if (freq <= 0) {
             goto bad_freq;
-            bad_freq:
+        bad_freq:
             mp_raise_ValueError("must have positive freq");
         }
         period = source_freq / freq;
@@ -471,19 +471,19 @@
 
 STATIC void config_deadtime(pyb_timer_obj_t *self, mp_int_t ticks, mp_int_t brk) {
     TIM_BreakDeadTimeConfigTypeDef deadTimeConfig;
-    deadTimeConfig.OffStateRunMode  = TIM_OSSR_DISABLE;
+    deadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE;
     deadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE;
-    deadTimeConfig.LockLevel        = TIM_LOCKLEVEL_OFF;
-    deadTimeConfig.DeadTime         = compute_dtg_from_ticks(ticks);
-    deadTimeConfig.BreakState       = brk == BRK_OFF ? TIM_BREAK_DISABLE : TIM_BREAK_ENABLE;
-    deadTimeConfig.BreakPolarity    = brk == BRK_LOW ? TIM_BREAKPOLARITY_LOW : TIM_BREAKPOLARITY_HIGH;
+    deadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF;
+    deadTimeConfig.DeadTime = compute_dtg_from_ticks(ticks);
+    deadTimeConfig.BreakState = brk == BRK_OFF ? TIM_BREAK_DISABLE : TIM_BREAK_ENABLE;
+    deadTimeConfig.BreakPolarity = brk == BRK_LOW ? TIM_BREAKPOLARITY_LOW : TIM_BREAKPOLARITY_HIGH;
     #if defined(STM32F7) || defined(STM32H7) | defined(STM32L4)
-    deadTimeConfig.BreakFilter      = 0;
-    deadTimeConfig.Break2State      = TIM_BREAK_DISABLE;
-    deadTimeConfig.Break2Polarity   = TIM_BREAKPOLARITY_LOW;
-    deadTimeConfig.Break2Filter     = 0;
+    deadTimeConfig.BreakFilter = 0;
+    deadTimeConfig.Break2State = TIM_BREAK_DISABLE;
+    deadTimeConfig.Break2Polarity = TIM_BREAKPOLARITY_LOW;
+    deadTimeConfig.Break2Filter = 0;
     #endif
-    deadTimeConfig.AutomaticOutput  = TIM_AUTOMATICOUTPUT_DISABLE;
+    deadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE;
     HAL_TIMEx_ConfigBreakDeadTime(&self->tim, &deadTimeConfig);
 }
 
@@ -632,8 +632,8 @@
     }
 
     init->ClockDivision = args[ARG_div].u_int == 2 ? TIM_CLOCKDIVISION_DIV2 :
-                          args[ARG_div].u_int == 4 ? TIM_CLOCKDIVISION_DIV4 :
-                                                     TIM_CLOCKDIVISION_DIV1;
+        args[ARG_div].u_int == 4 ? TIM_CLOCKDIVISION_DIV4 :
+        TIM_CLOCKDIVISION_DIV1;
 
     #if !defined(STM32L0)
     init->RepetitionCounter = 0;
@@ -642,68 +642,112 @@
     // enable TIM clock
     switch (self->tim_id) {
         #if defined(TIM1)
-        case 1: __HAL_RCC_TIM1_CLK_ENABLE(); break;
+        case 1:
+            __HAL_RCC_TIM1_CLK_ENABLE();
+            break;
         #endif
-        case 2: __HAL_RCC_TIM2_CLK_ENABLE(); break;
+        case 2:
+            __HAL_RCC_TIM2_CLK_ENABLE();
+            break;
         #if defined(TIM3)
-        case 3: __HAL_RCC_TIM3_CLK_ENABLE(); break;
+        case 3:
+            __HAL_RCC_TIM3_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM4)
-        case 4: __HAL_RCC_TIM4_CLK_ENABLE(); break;
+        case 4:
+            __HAL_RCC_TIM4_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM5)
-        case 5: __HAL_RCC_TIM5_CLK_ENABLE(); break;
+        case 5:
+            __HAL_RCC_TIM5_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM6)
-        case 6: __HAL_RCC_TIM6_CLK_ENABLE(); break;
+        case 6:
+            __HAL_RCC_TIM6_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM7)
-        case 7: __HAL_RCC_TIM7_CLK_ENABLE(); break;
+        case 7:
+            __HAL_RCC_TIM7_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM8)
-        case 8: __HAL_RCC_TIM8_CLK_ENABLE(); break;
+        case 8:
+            __HAL_RCC_TIM8_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM9)
-        case 9: __HAL_RCC_TIM9_CLK_ENABLE(); break;
+        case 9:
+            __HAL_RCC_TIM9_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM10)
-        case 10: __HAL_RCC_TIM10_CLK_ENABLE(); break;
+        case 10:
+            __HAL_RCC_TIM10_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM11)
-        case 11: __HAL_RCC_TIM11_CLK_ENABLE(); break;
+        case 11:
+            __HAL_RCC_TIM11_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM12)
-        case 12: __HAL_RCC_TIM12_CLK_ENABLE(); break;
+        case 12:
+            __HAL_RCC_TIM12_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM13)
-        case 13: __HAL_RCC_TIM13_CLK_ENABLE(); break;
+        case 13:
+            __HAL_RCC_TIM13_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM14)
-        case 14: __HAL_RCC_TIM14_CLK_ENABLE(); break;
+        case 14:
+            __HAL_RCC_TIM14_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM15)
-        case 15: __HAL_RCC_TIM15_CLK_ENABLE(); break;
+        case 15:
+            __HAL_RCC_TIM15_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM16)
-        case 16: __HAL_RCC_TIM16_CLK_ENABLE(); break;
+        case 16:
+            __HAL_RCC_TIM16_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM17)
-        case 17: __HAL_RCC_TIM17_CLK_ENABLE(); break;
+        case 17:
+            __HAL_RCC_TIM17_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM18)
-        case 18: __HAL_RCC_TIM18_CLK_ENABLE(); break;
+        case 18:
+            __HAL_RCC_TIM18_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM19)
-        case 19: __HAL_RCC_TIM19_CLK_ENABLE(); break;
+        case 19:
+            __HAL_RCC_TIM19_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM20)
-        case 20: __HAL_RCC_TIM20_CLK_ENABLE(); break;
+        case 20:
+            __HAL_RCC_TIM20_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM21)
-        case 21: __HAL_RCC_TIM21_CLK_ENABLE(); break;
+        case 21:
+            __HAL_RCC_TIM21_CLK_ENABLE();
+            break;
         #endif
         #if defined(TIM22)
-        case 22: __HAL_RCC_TIM22_CLK_ENABLE(); break;
+        case 22:
+            __HAL_RCC_TIM22_CLK_ENABLE();
+            break;
         #endif
     }
 
@@ -730,7 +774,7 @@
     if (IS_TIM_BREAK_INSTANCE(self->tim.Instance)) {
     #else
     if (0) {
-    #endif
+        #endif
         config_deadtime(self, args[ARG_deadtime].u_int, args[ARG_brk].u_int);
 
     }
@@ -858,7 +902,7 @@
         tim->is_32bit = tim_id == 2 || tim_id == 5;
         tim->callback = mp_const_none;
         uint32_t ti = tim_instance_table[tim_id - 1];
-        tim->tim.Instance = (TIM_TypeDef*)(ti & 0xffffff00);
+        tim->tim.Instance = (TIM_TypeDef *)(ti & 0xffffff00);
         tim->irqn = ti & 0xff;
         MP_STATE_PORT(pyb_timer_obj_all)[tim_id - 1] = tim;
     } else {
@@ -1085,11 +1129,11 @@
                 // use absolute pulse width value (defaults to 0 if nothing given)
                 oc_config.Pulse = args[3].u_int;
             }
-            oc_config.OCPolarity   = TIM_OCPOLARITY_HIGH;
-            oc_config.OCFastMode   = TIM_OCFAST_DISABLE;
+            oc_config.OCPolarity = TIM_OCPOLARITY_HIGH;
+            oc_config.OCFastMode = TIM_OCFAST_DISABLE;
             #if !defined(STM32L0)
-            oc_config.OCNPolarity  = TIM_OCNPOLARITY_HIGH;
-            oc_config.OCIdleState  = TIM_OCIDLESTATE_SET;
+            oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
+            oc_config.OCIdleState = TIM_OCIDLESTATE_SET;
             oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET;
             #endif
 
@@ -1115,20 +1159,20 @@
         case CHANNEL_MODE_OC_FORCED_ACTIVE:
         case CHANNEL_MODE_OC_FORCED_INACTIVE: {
             TIM_OC_InitTypeDef oc_config;
-            oc_config.OCMode       = channel_mode_info[chan->mode].oc_mode;
-            oc_config.Pulse        = args[5].u_int;
-            oc_config.OCPolarity   = args[6].u_int;
+            oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
+            oc_config.Pulse = args[5].u_int;
+            oc_config.OCPolarity = args[6].u_int;
             if (oc_config.OCPolarity == 0xffffffff) {
                 oc_config.OCPolarity = TIM_OCPOLARITY_HIGH;
             }
-            oc_config.OCFastMode   = TIM_OCFAST_DISABLE;
+            oc_config.OCFastMode = TIM_OCFAST_DISABLE;
             #if !defined(STM32L0)
             if (oc_config.OCPolarity == TIM_OCPOLARITY_HIGH) {
-                oc_config.OCNPolarity  = TIM_OCNPOLARITY_HIGH;
+                oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
             } else {
-                oc_config.OCNPolarity  = TIM_OCNPOLARITY_LOW;
+                oc_config.OCNPolarity = TIM_OCNPOLARITY_LOW;
             }
-            oc_config.OCIdleState  = TIM_OCIDLESTATE_SET;
+            oc_config.OCIdleState = TIM_OCIDLESTATE_SET;
             oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET;
             #endif
 
@@ -1153,13 +1197,13 @@
         case CHANNEL_MODE_IC: {
             TIM_IC_InitTypeDef ic_config;
 
-            ic_config.ICPolarity  = args[6].u_int;
+            ic_config.ICPolarity = args[6].u_int;
             if (ic_config.ICPolarity == 0xffffffff) {
                 ic_config.ICPolarity = TIM_ICPOLARITY_RISING;
             }
             ic_config.ICSelection = TIM_ICSELECTION_DIRECTTI;
             ic_config.ICPrescaler = TIM_ICPSC_DIV1;
-            ic_config.ICFilter    = 0;
+            ic_config.ICFilter = 0;
 
             if (!IS_TIM_IC_POLARITY(ic_config.ICPolarity)) {
                 mp_raise_msg_varg(&mp_type_ValueError, "invalid polarity (%d)", ic_config.ICPolarity);
@@ -1179,41 +1223,41 @@
             TIM_Encoder_InitTypeDef enc_config;
 
             enc_config.EncoderMode = channel_mode_info[chan->mode].oc_mode;
-            enc_config.IC1Polarity  = args[6].u_int;
+            enc_config.IC1Polarity = args[6].u_int;
             if (enc_config.IC1Polarity == 0xffffffff) {
                 enc_config.IC1Polarity = TIM_ICPOLARITY_RISING;
             }
-            enc_config.IC2Polarity  = enc_config.IC1Polarity;
+            enc_config.IC2Polarity = enc_config.IC1Polarity;
             enc_config.IC1Selection = TIM_ICSELECTION_DIRECTTI;
             enc_config.IC2Selection = TIM_ICSELECTION_DIRECTTI;
             enc_config.IC1Prescaler = TIM_ICPSC_DIV1;
             enc_config.IC2Prescaler = TIM_ICPSC_DIV1;
-            enc_config.IC1Filter    = 0;
-            enc_config.IC2Filter    = 0;
+            enc_config.IC1Filter = 0;
+            enc_config.IC2Filter = 0;
 
             if (!IS_TIM_IC_POLARITY(enc_config.IC1Polarity)) {
                 mp_raise_msg_varg(&mp_type_ValueError, "invalid polarity (%d)", enc_config.IC1Polarity);
             }
             // Only Timers 1, 2, 3, 4, 5, and 8 support encoder mode
             if (
-            #if defined(TIM1)
+                #if defined(TIM1)
                 self->tim.Instance != TIM1
-            &&
-            #endif
+                &&
+                #endif
                 self->tim.Instance != TIM2
-            #if defined(TIM3)
-            &&  self->tim.Instance != TIM3
-            #endif
-            #if defined(TIM4)
-            &&  self->tim.Instance != TIM4
-            #endif
-            #if defined(TIM5)
-            &&  self->tim.Instance != TIM5
-            #endif
-            #if defined(TIM8)
-            &&  self->tim.Instance != TIM8
-            #endif
-            ) {
+                #if defined(TIM3)
+                && self->tim.Instance != TIM3
+                #endif
+                #if defined(TIM4)
+                && self->tim.Instance != TIM4
+                #endif
+                #if defined(TIM5)
+                && self->tim.Instance != TIM5
+                #endif
+                #if defined(TIM8)
+                && self->tim.Instance != TIM8
+                #endif
+                ) {
                 mp_raise_msg_varg(&mp_type_ValueError, "encoder not supported on timer %d", self->tim_id);
             }
 
@@ -1394,7 +1438,7 @@
     .name = MP_QSTR_Timer,
     .print = pyb_timer_print,
     .make_new = pyb_timer_make_new,
-    .locals_dict = (mp_obj_dict_t*)&pyb_timer_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_timer_locals_dict,
 };
 
 /// \moduleref pyb
@@ -1407,9 +1451,9 @@
     pyb_timer_channel_obj_t *self = MP_OBJ_TO_PTR(self_in);
 
     mp_printf(print, "TimerChannel(timer=%u, channel=%u, mode=%s)",
-          self->timer->tim_id,
-          self->channel,
-          qstr_str(channel_mode_info[self->mode].name));
+        self->timer->tim_id,
+        self->channel,
+        qstr_str(channel_mode_info[self->mode].name));
 }
 
 /// \method capture([value])
@@ -1529,7 +1573,7 @@
     { &mp_type_type },
     .name = MP_QSTR_TimerChannel,
     .print = pyb_timer_channel_print,
-    .locals_dict = (mp_obj_dict_t*)&pyb_timer_channel_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_timer_channel_locals_dict,
 };
 
 STATIC void timer_handle_irq_channel(pyb_timer_obj_t *tim, uint8_t channel, mp_obj_t callback) {
diff --git a/ports/stm32/uart.c b/ports/stm32/uart.c
index d2d234a..8693813 100644
--- a/ports/stm32/uart.c
+++ b/ports/stm32/uart.c
@@ -130,46 +130,57 @@
     }
     switch (uart_id) {
         #if defined(MICROPY_HW_UART1_TX) && defined(MICROPY_HW_UART1_RX)
-        case PYB_UART_1: return true;
+        case PYB_UART_1:
+            return true;
         #endif
 
         #if defined(MICROPY_HW_UART2_TX) && defined(MICROPY_HW_UART2_RX)
-        case PYB_UART_2: return true;
+        case PYB_UART_2:
+            return true;
         #endif
 
         #if defined(MICROPY_HW_UART3_TX) && defined(MICROPY_HW_UART3_RX)
-        case PYB_UART_3: return true;
+        case PYB_UART_3:
+            return true;
         #endif
 
         #if defined(MICROPY_HW_UART4_TX) && defined(MICROPY_HW_UART4_RX)
-        case PYB_UART_4: return true;
+        case PYB_UART_4:
+            return true;
         #endif
 
         #if defined(MICROPY_HW_UART5_TX) && defined(MICROPY_HW_UART5_RX)
-        case PYB_UART_5: return true;
+        case PYB_UART_5:
+            return true;
         #endif
 
         #if defined(MICROPY_HW_UART6_TX) && defined(MICROPY_HW_UART6_RX)
-        case PYB_UART_6: return true;
+        case PYB_UART_6:
+            return true;
         #endif
 
         #if defined(MICROPY_HW_UART7_TX) && defined(MICROPY_HW_UART7_RX)
-        case PYB_UART_7: return true;
+        case PYB_UART_7:
+            return true;
         #endif
 
         #if defined(MICROPY_HW_UART8_TX) && defined(MICROPY_HW_UART8_RX)
-        case PYB_UART_8: return true;
+        case PYB_UART_8:
+            return true;
         #endif
 
         #if defined(MICROPY_HW_UART9_TX) && defined(MICROPY_HW_UART9_RX)
-        case PYB_UART_9: return true;
+        case PYB_UART_9:
+            return true;
         #endif
 
         #if defined(MICROPY_HW_UART10_TX) && defined(MICROPY_HW_UART10_RX)
-        case PYB_UART_10: return true;
+        case PYB_UART_10:
+            return true;
         #endif
 
-        default: return false;
+        default:
+            return false;
     }
 }
 
@@ -661,7 +672,7 @@
         // buffering via IRQ
         int data;
         if (self->char_width == CHAR_WIDTH_9BIT) {
-            data = ((uint16_t*)self->read_buf)[self->read_buf_tail];
+            data = ((uint16_t *)self->read_buf)[self->read_buf_tail];
         } else {
             data = self->read_buf[self->read_buf_tail];
         }
@@ -744,7 +755,7 @@
         timeout = 2 * self->timeout_char;
     }
 
-    const uint8_t *src = (const uint8_t*)src_in;
+    const uint8_t *src = (const uint8_t *)src_in;
     size_t num_tx = 0;
     USART_TypeDef *uart = self->uartx;
 
@@ -755,7 +766,7 @@
         }
         uint32_t data;
         if (self->char_width == CHAR_WIDTH_9BIT) {
-            data = *((uint16_t*)src) & 0x1ff;
+            data = *((uint16_t *)src) & 0x1ff;
             src += 2;
         } else {
             data = *src++;
@@ -811,7 +822,7 @@
                     pendsv_kbd_intr();
                 } else {
                     if (self->char_width == CHAR_WIDTH_9BIT) {
-                        ((uint16_t*)self->read_buf)[self->read_buf_head] = data;
+                        ((uint16_t *)self->read_buf)[self->read_buf_head] = data;
                     } else {
                         self->read_buf[self->read_buf_head] = data;
                     }
diff --git a/ports/stm32/usb.c b/ports/stm32/usb.c
index 432d55a..5c8b105 100644
--- a/ports/stm32/usb.c
+++ b/ports/stm32/usb.c
@@ -238,8 +238,8 @@
         // set up the USBD state
         USBD_HandleTypeDef *usbd = &usb_dev->hUSBDDevice;
         usbd->id = dev_id;
-        usbd->dev_state  = USBD_STATE_DEFAULT;
-        usbd->pDesc = (USBD_DescriptorsTypeDef*)&USBD_Descriptors;
+        usbd->dev_state = USBD_STATE_DEFAULT;
+        usbd->pDesc = (USBD_DescriptorsTypeDef *)&USBD_Descriptors;
         usbd->pClass = &USBD_CDC_MSC_HID;
         usb_dev->usbd_cdc_msc_hid_state.pdev = usbd;
         for (int i = 0; i < MICROPY_HW_USB_CDC_NUM; ++i) {
@@ -275,7 +275,7 @@
             }
         }
         usbd_msc_init_lu(msc_n, msc_unit);
-        USBD_MSC_RegisterStorage(&usb_dev->usbd_cdc_msc_hid_state, (USBD_StorageTypeDef*)&usbd_msc_fops);
+        USBD_MSC_RegisterStorage(&usb_dev->usbd_cdc_msc_hid_state, (USBD_StorageTypeDef *)&usbd_msc_fops);
         #endif
 
         const uint8_t *fifo_size = usbd_fifo_size_cdc1;
@@ -331,7 +331,7 @@
 
 void usb_vcp_send_strn(const char *str, int len) {
     if (usb_device.enabled) {
-        usbd_cdc_tx_always(&usb_device.usbd_cdc_itf[0], (const uint8_t*)str, len);
+        usbd_cdc_tx_always(&usb_device.usbd_cdc_itf[0], (const uint8_t *)str, len);
     }
 }
 
@@ -399,9 +399,9 @@
 
     // fetch the current usb mode -> pyb.usb_mode()
     if (n_args == 0) {
-    #if defined(USE_HOST_MODE)
+        #if defined(USE_HOST_MODE)
         return MP_OBJ_NEW_QSTR(MP_QSTR_host);
-    #else
+        #else
         uint8_t mode = USBD_GetMode(&usb_device.usbd_cdc_msc_hid_state);
         switch (mode & USBD_MODE_IFACE_MASK) {
             case USBD_MODE_CDC:
@@ -419,7 +419,7 @@
             default:
                 return mp_const_none;
         }
-    #endif
+        #endif
     }
 
     // parse args
@@ -439,7 +439,7 @@
     // get mode string
     const char *mode_str = mp_obj_str_get_str(args[ARG_mode].u_obj);
 
-#if defined(USE_HOST_MODE)
+    #if defined(USE_HOST_MODE)
 
     // hardware configured for USB host mode
 
@@ -449,7 +449,7 @@
         goto bad_mode;
     }
 
-#else
+    #else
 
     // hardware configured for USB device mode
 
@@ -587,7 +587,7 @@
         goto bad_mode;
     }
 
-#endif
+    #endif
 
     return mp_const_none;
 
@@ -628,7 +628,7 @@
 }
 
 STATIC void pyb_usb_vcp_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
-    int id = ((pyb_usb_vcp_obj_t*)MP_OBJ_TO_PTR(self_in))->cdc_itf - &usb_device.usbd_cdc_itf[0];
+    int id = ((pyb_usb_vcp_obj_t *)MP_OBJ_TO_PTR(self_in))->cdc_itf - &usb_device.usbd_cdc_itf[0];
     mp_printf(print, "USB_VCP(%u)", id);
 }
 
@@ -761,7 +761,7 @@
     mp_obj_t o_ret = pyb_buf_get_for_recv(vals[0].u_obj, &vstr);
 
     // receive the data
-    int ret = usbd_cdc_rx(self->cdc_itf, (uint8_t*)vstr.buf, vstr.len, vals[1].u_int);
+    int ret = usbd_cdc_rx(self->cdc_itf, (uint8_t *)vstr.buf, vstr.len, vals[1].u_int);
 
     // return the received data
     if (o_ret != MP_OBJ_NULL) {
@@ -804,7 +804,7 @@
 
 STATIC mp_uint_t pyb_usb_vcp_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) {
     pyb_usb_vcp_obj_t *self = MP_OBJ_TO_PTR(self_in);
-    int ret = usbd_cdc_rx(self->cdc_itf, (byte*)buf, size, 0);
+    int ret = usbd_cdc_rx(self->cdc_itf, (byte *)buf, size, 0);
     if (ret == 0) {
         // return EAGAIN error to indicate non-blocking
         *errcode = MP_EAGAIN;
@@ -815,7 +815,7 @@
 
 STATIC mp_uint_t pyb_usb_vcp_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) {
     pyb_usb_vcp_obj_t *self = MP_OBJ_TO_PTR(self_in);
-    int ret = usbd_cdc_tx_flow(self->cdc_itf, (const byte*)buf, size);
+    int ret = usbd_cdc_tx_flow(self->cdc_itf, (const byte *)buf, size);
     if (ret == 0) {
         // return EAGAIN error to indicate non-blocking
         *errcode = MP_EAGAIN;
@@ -857,7 +857,7 @@
     .getiter = mp_identity_getiter,
     .iternext = mp_stream_unbuffered_iter,
     .protocol = &pyb_usb_vcp_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&pyb_usb_vcp_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_usb_vcp_locals_dict,
 };
 
 /******************************************************************************/
@@ -908,7 +908,7 @@
     mp_obj_t o_ret = pyb_buf_get_for_recv(vals[0].u_obj, &vstr);
 
     // receive the data
-    int ret = usbd_hid_rx(&self->usb_dev->usbd_hid_itf, vstr.len, (uint8_t*)vstr.buf, vals[1].u_int);
+    int ret = usbd_hid_rx(&self->usb_dev->usbd_hid_itf, vstr.len, (uint8_t *)vstr.buf, vals[1].u_int);
 
     if (ret < 0) {
         // error, just return 0/empty bytes
@@ -995,7 +995,7 @@
     .name = MP_QSTR_USB_HID,
     .make_new = pyb_usb_hid_make_new,
     .protocol = &pyb_usb_hid_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&pyb_usb_hid_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_usb_hid_locals_dict,
 };
 
 #endif // MICROPY_HW_USB_HID
@@ -1012,7 +1012,7 @@
 #include "usbh_hid_keybd.h"
 #include "usbh_hid_mouse.h"
 
-__ALIGN_BEGIN USBH_HOST USB_Host __ALIGN_END ;
+__ALIGN_BEGIN USBH_HOST USB_Host __ALIGN_END;
 
 static int host_is_enabled = 0;
 
diff --git a/ports/stm32/usb.h b/ports/stm32/usb.h
index 457c731..f69af86 100644
--- a/ports/stm32/usb.h
+++ b/ports/stm32/usb.h
@@ -74,7 +74,7 @@
 void pyb_usb_dev_deinit(void);
 bool usb_vcp_is_enabled(void);
 int usb_vcp_recv_byte(uint8_t *c); // if a byte is available, return 1 and put the byte in *c, else return 0
-void usb_vcp_send_strn(const char* str, int len);
+void usb_vcp_send_strn(const char *str, int len);
 void usb_vcp_attach_to_repl(const pyb_usb_vcp_obj_t *self, bool attached);
 
 void pyb_usb_host_init(void);
diff --git a/ports/stm32/usbd_cdc_interface.c b/ports/stm32/usbd_cdc_interface.c
index bdd7a4e..1fc7af1 100644
--- a/ports/stm32/usbd_cdc_interface.c
+++ b/ports/stm32/usbd_cdc_interface.c
@@ -62,7 +62,7 @@
 static uint8_t usbd_cdc_connect_tx_timer;
 
 uint8_t *usbd_cdc_init(usbd_cdc_state_t *cdc_in) {
-    usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t*)cdc_in;
+    usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t *)cdc_in;
 
     // Reset the CDC state due to a new USB host connection
     // Note: we don't reset tx_buf_ptr_* in order to allow the output buffer to
@@ -86,7 +86,7 @@
 }
 
 void usbd_cdc_deinit(usbd_cdc_state_t *cdc_in) {
-    usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t*)cdc_in;
+    usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t *)cdc_in;
     cdc->connect_state = USBD_CDC_CONNECT_STATE_DISCONNECTED;
 }
 
@@ -95,8 +95,8 @@
 // pbuf: buffer containing command data (request parameters)
 // length: number of data to be sent (in bytes)
 // Returns USBD_OK if all operations are OK else USBD_FAIL
-int8_t usbd_cdc_control(usbd_cdc_state_t *cdc_in, uint8_t cmd, uint8_t* pbuf, uint16_t length) {
-    usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t*)cdc_in;
+int8_t usbd_cdc_control(usbd_cdc_state_t *cdc_in, uint8_t cmd, uint8_t *pbuf, uint16_t length) {
+    usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t *)cdc_in;
 
     switch (cmd) {
         case CDC_SEND_ENCAPSULATED_COMMAND:
@@ -121,11 +121,11 @@
 
         case CDC_SET_LINE_CODING:
             #if 0
-            LineCoding.bitrate    = (uint32_t)(pbuf[0] | (pbuf[1] << 8) |\
-                                    (pbuf[2] << 16) | (pbuf[3] << 24));
-            LineCoding.format     = pbuf[4];
+            LineCoding.bitrate = (uint32_t)(pbuf[0] | (pbuf[1] << 8) | \
+                (pbuf[2] << 16) | (pbuf[3] << 24));
+            LineCoding.format = pbuf[4];
             LineCoding.paritytype = pbuf[5];
-            LineCoding.datatype   = pbuf[6];
+            LineCoding.datatype = pbuf[6];
             /* Set the new configuration */
             #endif
             break;
@@ -175,7 +175,7 @@
 // (cdc.base.tx_in_progress must be 0)
 void usbd_cdc_tx_ready(usbd_cdc_state_t *cdc_in) {
 
-    usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t*)cdc_in;
+    usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t *)cdc_in;
     cdc->tx_buf_ptr_out = cdc->tx_buf_ptr_out_shadow;
 
     if (cdc->tx_buf_ptr_out == cdc->tx_buf_ptr_in && !cdc->tx_need_empty_packet) {
@@ -224,14 +224,14 @@
     if (usbd_cdc_connect_tx_timer > 0) {
         --usbd_cdc_connect_tx_timer;
     } else {
-        usbd_cdc_msc_hid_state_t *usbd = ((USBD_HandleTypeDef*)hpcd->pData)->pClassData;
+        usbd_cdc_msc_hid_state_t *usbd = ((USBD_HandleTypeDef *)hpcd->pData)->pClassData;
         #if !MICROPY_HW_USB_IS_MULTI_OTG
         USB->CNTR &= ~USB_CNTR_SOFM;
         #else
         hpcd->Instance->GINTMSK &= ~USB_OTG_GINTMSK_SOFM;
         #endif
         for (int i = 0; i < MICROPY_HW_USB_CDC_NUM; ++i) {
-            usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t*)usbd->cdc[i];
+            usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t *)usbd->cdc[i];
             if (cdc->connect_state == USBD_CDC_CONNECT_STATE_CONNECTING) {
                 cdc->connect_state = USBD_CDC_CONNECT_STATE_CONNECTED;
                 usbd_cdc_try_tx(cdc);
@@ -263,7 +263,7 @@
 // len: number of bytes received into the buffer we passed to USBD_CDC_ReceivePacket
 // Returns USBD_OK if all operations are OK else USBD_FAIL
 int8_t usbd_cdc_receive(usbd_cdc_state_t *cdc_in, size_t len) {
-    usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t*)cdc_in;
+    usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t *)cdc_in;
 
     // copy the incoming data into the circular buffer
     for (const uint8_t *src = cdc->rx_packet_buf, *top = cdc->rx_packet_buf + len; src < top; ++src) {
@@ -318,7 +318,7 @@
         // Wait until the device is connected and the buffer has space, with a given timeout
         uint32_t start = HAL_GetTick();
         while (cdc->connect_state == USBD_CDC_CONNECT_STATE_DISCONNECTED
-            || ((cdc->tx_buf_ptr_in + 1) & (USBD_CDC_TX_DATA_SIZE - 1)) == cdc->tx_buf_ptr_out) {
+               || ((cdc->tx_buf_ptr_in + 1) & (USBD_CDC_TX_DATA_SIZE - 1)) == cdc->tx_buf_ptr_out) {
             usbd_cdc_try_tx(cdc);
             // Wraparound of tick is taken care of by 2's complement arithmetic.
             if (HAL_GetTick() - start >= timeout) {
diff --git a/ports/stm32/usbd_conf.c b/ports/stm32/usbd_conf.c
index c2edbb7..d24881d 100644
--- a/ports/stm32/usbd_conf.c
+++ b/ports/stm32/usbd_conf.c
@@ -363,7 +363,7 @@
   */
 USBD_StatusTypeDef USBD_LL_Init(USBD_HandleTypeDef *pdev, int high_speed, const uint8_t *fifo_size) {
     #if MICROPY_HW_USB_FS
-    if (pdev->id ==  USB_PHY_FS_ID) {
+    if (pdev->id == USB_PHY_FS_ID) {
         #if defined(STM32WB)
         PWR->CR2 |= PWR_CR2_USV; // USB supply is valid
         #endif
@@ -631,7 +631,7 @@
   * @param  ep_addr: Endpoint Number
   * @retval Recived Data Size
   */
-uint32_t USBD_LL_GetRxDataSize(USBD_HandleTypeDef *pdev, uint8_t  ep_addr) {
+uint32_t USBD_LL_GetRxDataSize(USBD_HandleTypeDef *pdev, uint8_t ep_addr) {
     return HAL_PCD_EP_GetRxCount(pdev->pData, ep_addr);
 }
 
diff --git a/ports/stm32/usbd_desc.c b/ports/stm32/usbd_desc.c
index d28f9ae..aa68371 100644
--- a/ports/stm32/usbd_desc.c
+++ b/ports/stm32/usbd_desc.c
@@ -119,7 +119,7 @@
   * @retval Pointer to descriptor buffer
   */
 STATIC uint8_t *USBD_DeviceDescriptor(USBD_HandleTypeDef *pdev, uint16_t *length) {
-    uint8_t *dev_desc = ((usbd_cdc_msc_hid_state_t*)pdev->pClassData)->usbd_device_desc;
+    uint8_t *dev_desc = ((usbd_cdc_msc_hid_state_t *)pdev->pClassData)->usbd_device_desc;
     *length = USB_LEN_DEV_DESC;
     return dev_desc;
 }
@@ -137,7 +137,7 @@
     switch (idx) {
         case USBD_IDX_LANGID_STR:
             *length = sizeof(USBD_LangIDDesc);
-            return (uint8_t*)USBD_LangIDDesc; // the data should only be read from this buf
+            return (uint8_t *)USBD_LangIDDesc; // the data should only be read from this buf
 
         case USBD_IDX_MFC_STR:
             str = USBD_MANUFACTURER_STRING;
@@ -193,8 +193,8 @@
             return NULL;
     }
 
-    uint8_t *str_desc = ((usbd_cdc_msc_hid_state_t*)pdev->pClassData)->usbd_str_desc;
-    USBD_GetString((uint8_t*)str, str_desc, length);
+    uint8_t *str_desc = ((usbd_cdc_msc_hid_state_t *)pdev->pClassData)->usbd_str_desc;
+    USBD_GetString((uint8_t *)str, str_desc, length);
     return str_desc;
 }
 
diff --git a/ports/stm32/usbd_hid_interface.c b/ports/stm32/usbd_hid_interface.c
index 8dc39f5..c167fb3 100644
--- a/ports/stm32/usbd_hid_interface.c
+++ b/ports/stm32/usbd_hid_interface.c
@@ -34,14 +34,14 @@
 #if MICROPY_HW_USB_HID
 
 uint8_t *usbd_hid_init(usbd_hid_state_t *hid_in) {
-    usbd_hid_itf_t *hid = (usbd_hid_itf_t*)hid_in;
+    usbd_hid_itf_t *hid = (usbd_hid_itf_t *)hid_in;
     hid->report_in_len = USBD_HID_REPORT_INVALID;
     return &hid->report_in_buf[0]; // location to place first incoming report
 }
 
 int8_t usbd_hid_receive(usbd_hid_state_t *hid_in, size_t len) {
     // Incoming report: save the length but don't schedule next report until user reads this one
-    usbd_hid_itf_t *hid = (usbd_hid_itf_t*)hid_in;
+    usbd_hid_itf_t *hid = (usbd_hid_itf_t *)hid_in;
     hid->report_in_len = len;
     return USBD_OK;
 }
diff --git a/ports/stm32/usbd_msc_interface.c b/ports/stm32/usbd_msc_interface.c
index 2f5e7aa..62fe32b 100644
--- a/ports/stm32/usbd_msc_interface.c
+++ b/ports/stm32/usbd_msc_interface.c
@@ -102,13 +102,13 @@
     'M', 'i', 'c', 'r', 'o', 'P', 'y', ' ', // Manufacturer : 8 bytes
     'p', 'y', 'b', 'o', 'a', 'r', 'd', ' ', // Product      : 16 Bytes
     'F', 'l', 'a', 's', 'h', ' ', ' ', ' ',
-    '1', '.', '0' ,'0',                     // Version      : 4 Bytes
+    '1', '.', '0','0',                      // Version      : 4 Bytes
 };
 
 // Set the logical units that will be exposed over MSC
 void usbd_msc_init_lu(size_t lu_n, const void *lu_data) {
     usbd_msc_lu_num = MIN(lu_n, USBD_MSC_MAX_LUN);
-    memcpy(usbd_msc_lu_data, lu_data, sizeof(void*) * usbd_msc_lu_num);
+    memcpy(usbd_msc_lu_data, lu_data, sizeof(void *) * usbd_msc_lu_num);
     usbd_msc_lu_flags = 0;
 }
 
@@ -139,10 +139,10 @@
         }
     #if MICROPY_HW_ENABLE_SDCARD
     } else if (lu == &pyb_sdcard_type
-        #if MICROPY_HW_ENABLE_MMCARD
-        || lu == &pyb_mmcard_type
-        #endif
-        ) {
+               #if MICROPY_HW_ENABLE_MMCARD
+               || lu == &pyb_mmcard_type
+               #endif
+               ) {
         switch (op) {
             case MP_BLOCKDEV_IOCTL_INIT:
                 if (!sdcard_power_on()) {
@@ -290,10 +290,10 @@
         return 0;
     #if MICROPY_HW_ENABLE_SDCARD
     } else if (lu == &pyb_sdcard_type
-        #if MICROPY_HW_ENABLE_MMCARD
-        || lu == &pyb_mmcard_type
-        #endif
-        ) {
+               #if MICROPY_HW_ENABLE_MMCARD
+               || lu == &pyb_mmcard_type
+               #endif
+               ) {
         if (sdcard_read_blocks(buf, blk_addr, blk_len) == 0) {
             return 0;
         }
@@ -314,10 +314,10 @@
         return 0;
     #if MICROPY_HW_ENABLE_SDCARD
     } else if (lu == &pyb_sdcard_type
-        #if MICROPY_HW_ENABLE_MMCARD
-        || lu == &pyb_mmcard_type
-        #endif
-        ) {
+               #if MICROPY_HW_ENABLE_MMCARD
+               || lu == &pyb_mmcard_type
+               #endif
+               ) {
         if (sdcard_write_blocks(buf, blk_addr, blk_len) == 0) {
             return 0;
         }
diff --git a/ports/stm32/usrsw.c b/ports/stm32/usrsw.c
index 4519f80..596efba 100644
--- a/ports/stm32/usrsw.c
+++ b/ports/stm32/usrsw.c
@@ -119,10 +119,10 @@
     // may have been disabled by an exception in the interrupt, or the
     // user disabling the line explicitly.
     extint_register(MP_OBJ_FROM_PTR(MICROPY_HW_USRSW_PIN),
-                    MICROPY_HW_USRSW_EXTI_MODE,
-                    MICROPY_HW_USRSW_PULL,
-                    callback == mp_const_none ? mp_const_none : MP_OBJ_FROM_PTR(&switch_callback_obj),
-                    true);
+        MICROPY_HW_USRSW_EXTI_MODE,
+        MICROPY_HW_USRSW_PULL,
+        callback == mp_const_none ? mp_const_none : MP_OBJ_FROM_PTR(&switch_callback_obj),
+        true);
     return mp_const_none;
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_switch_callback_obj, pyb_switch_callback);
@@ -140,7 +140,7 @@
     .print = pyb_switch_print,
     .make_new = pyb_switch_make_new,
     .call = pyb_switch_call,
-    .locals_dict = (mp_obj_dict_t*)&pyb_switch_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_switch_locals_dict,
 };
 
 #endif // MICROPY_HW_HAS_SWITCH
diff --git a/ports/stm32/wdt.c b/ports/stm32/wdt.c
index d2aa811..1452fd6 100644
--- a/ports/stm32/wdt.c
+++ b/ports/stm32/wdt.c
@@ -106,5 +106,5 @@
     { &mp_type_type },
     .name = MP_QSTR_WDT,
     .make_new = pyb_wdt_make_new,
-    .locals_dict = (mp_obj_dict_t*)&pyb_wdt_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&pyb_wdt_locals_dict,
 };
diff --git a/ports/teensy/hal_ftm.c b/ports/teensy/hal_ftm.c
index 3c031bf..47dc3e8 100644
--- a/ports/teensy/hal_ftm.c
+++ b/ports/teensy/hal_ftm.c
@@ -43,7 +43,7 @@
     FTMx->MOD = hftm->Init.Period;
     uint32_t sc = FTM_SC_PS(hftm->Init.PrescalerShift);
     if (hftm->Init.CounterMode == FTM_COUNTERMODE_CENTER) {
-      sc |= FTM_SC_CPWMS;
+        sc |= FTM_SC_CPWMS;
     }
     FTMx->SC = sc;
 
@@ -89,7 +89,7 @@
     HAL_FTM_Base_Init(hftm);
 }
 
-void HAL_FTM_OC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef* sConfig, uint32_t channel) {
+void HAL_FTM_OC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef *sConfig, uint32_t channel) {
     FTM_TypeDef *FTMx = hftm->Instance;
     assert_param(IS_FTM_INSTANCE(FTMx));
     assert_param(IS_FTM_CHANNEL(channel));
@@ -100,11 +100,11 @@
     hftm->State = HAL_FTM_STATE_BUSY;
 
     FTMx->channel[channel].CSC = sConfig->OCMode;
-    FTMx->channel[channel].CV  = sConfig->Pulse;
+    FTMx->channel[channel].CV = sConfig->Pulse;
     if (sConfig->OCPolarity & 1) {
-      FTMx->POL |= (1 << channel); 
+        FTMx->POL |= (1 << channel);
     } else {
-      FTMx->POL &= ~(1 << channel); 
+        FTMx->POL &= ~(1 << channel);
     }
 
     hftm->State = HAL_FTM_STATE_READY;
@@ -129,7 +129,7 @@
     HAL_FTM_Base_Init(hftm);
 }
 
-void HAL_FTM_PWM_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef* sConfig, uint32_t channel) {
+void HAL_FTM_PWM_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef *sConfig, uint32_t channel) {
     FTM_TypeDef *FTMx = hftm->Instance;
     assert_param(IS_FTM_INSTANCE(FTMx));
     assert_param(IS_FTM_CHANNEL(channel));
@@ -140,11 +140,11 @@
     hftm->State = HAL_FTM_STATE_BUSY;
 
     FTMx->channel[channel].CSC = sConfig->OCMode;
-    FTMx->channel[channel].CV  = sConfig->Pulse;
+    FTMx->channel[channel].CV = sConfig->Pulse;
     if (sConfig->OCPolarity & 1) {
-      FTMx->POL |= (1 << channel); 
+        FTMx->POL |= (1 << channel);
     } else {
-      FTMx->POL &= ~(1 << channel); 
+        FTMx->POL &= ~(1 << channel);
     }
 
     hftm->State = HAL_FTM_STATE_READY;
@@ -169,7 +169,7 @@
     HAL_FTM_Base_Init(hftm);
 }
 
-void HAL_FTM_IC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_IC_InitTypeDef* sConfig, uint32_t channel) {
+void HAL_FTM_IC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_IC_InitTypeDef *sConfig, uint32_t channel) {
     FTM_TypeDef *FTMx = hftm->Instance;
     assert_param(IS_FTM_INSTANCE(FTMx));
     assert_param(IS_FTM_CHANNEL(channel));
diff --git a/ports/teensy/hal_ftm.h b/ports/teensy/hal_ftm.h
index 84fae83..2ddcd02 100644
--- a/ports/teensy/hal_ftm.h
+++ b/ports/teensy/hal_ftm.h
@@ -31,64 +31,64 @@
 #define FTM2    ((FTM_TypeDef *)&FTM2_SC)
 
 typedef struct {
-    volatile uint32_t CSC;	// Channel x Status And Control
-    volatile uint32_t CV;		// Channel x Value
+    volatile uint32_t CSC;      // Channel x Status And Control
+    volatile uint32_t CV;               // Channel x Value
 } FTM_ChannelTypeDef;
 
 typedef struct {
-    volatile uint32_t SC;		// Status And Control
-    volatile uint32_t CNT;		// Counter
-    volatile uint32_t MOD;		// Modulo
+    volatile uint32_t SC;               // Status And Control
+    volatile uint32_t CNT;              // Counter
+    volatile uint32_t MOD;              // Modulo
     FTM_ChannelTypeDef channel[8];
-    volatile uint32_t CNTIN;	// Counter Initial Value
-    volatile uint32_t STATUS;	// Capture And Compare Status
-    volatile uint32_t MODE;		// Features Mode Selection
-    volatile uint32_t SYNC;		// Synchronization
+    volatile uint32_t CNTIN;    // Counter Initial Value
+    volatile uint32_t STATUS;   // Capture And Compare Status
+    volatile uint32_t MODE;             // Features Mode Selection
+    volatile uint32_t SYNC;             // Synchronization
     volatile uint32_t OUTINIT;  // Initial State For Channels Output
-    volatile uint32_t OUTMASK;	// Output Mask
-    volatile uint32_t COMBINE;	// Function For Linked Channels
+    volatile uint32_t OUTMASK;  // Output Mask
+    volatile uint32_t COMBINE;  // Function For Linked Channels
     volatile uint32_t DEADTIME; // Deadtime Insertion Control
-    volatile uint32_t EXTTRIG;	// FTM External Trigger
-    volatile uint32_t POL;		// Channels Polarity
-    volatile uint32_t FMS;		// Fault Mode Status
-    volatile uint32_t FILTER;	// Input Capture Filter Control
-    volatile uint32_t FLTCTRL;	// Fault Control
-    volatile uint32_t QDCTRL;	// Quadrature Decoder Control And Status
-    volatile uint32_t CONF;		// Configuration
-    volatile uint32_t FLTPOL;	// FTM Fault Input Polarity
-    volatile uint32_t SYNCONF;	// Synchronization Configuration
-    volatile uint32_t INVCTRL;	// FTM Inverting Control
-    volatile uint32_t SWOCTRL;	// FTM Software Output Control
+    volatile uint32_t EXTTRIG;  // FTM External Trigger
+    volatile uint32_t POL;              // Channels Polarity
+    volatile uint32_t FMS;              // Fault Mode Status
+    volatile uint32_t FILTER;   // Input Capture Filter Control
+    volatile uint32_t FLTCTRL;  // Fault Control
+    volatile uint32_t QDCTRL;   // Quadrature Decoder Control And Status
+    volatile uint32_t CONF;             // Configuration
+    volatile uint32_t FLTPOL;   // FTM Fault Input Polarity
+    volatile uint32_t SYNCONF;  // Synchronization Configuration
+    volatile uint32_t INVCTRL;  // FTM Inverting Control
+    volatile uint32_t SWOCTRL;  // FTM Software Output Control
     volatile uint32_t PWMLOAD;  // FTM PWM Load
 } FTM_TypeDef;
 
 typedef struct {
-    uint32_t    PrescalerShift; // Sets the prescaler to 1 << PrescalerShift
-    uint32_t    CounterMode;    // One of FTM_COUNTERMODE_xxx
-    uint32_t    Period;         // Specifies the Period for determining timer overflow
+    uint32_t PrescalerShift;    // Sets the prescaler to 1 << PrescalerShift
+    uint32_t CounterMode;       // One of FTM_COUNTERMODE_xxx
+    uint32_t Period;            // Specifies the Period for determining timer overflow
 } FTM_Base_InitTypeDef;
 
 typedef struct {
-    uint32_t    OCMode;         // One of FTM_OCMODE_xxx
-    uint32_t    Pulse;          // Specifies initial pulse width (0-0xffff)
-    uint32_t    OCPolarity;     // One of FTM_OCPOLRITY_xxx
+    uint32_t OCMode;            // One of FTM_OCMODE_xxx
+    uint32_t Pulse;             // Specifies initial pulse width (0-0xffff)
+    uint32_t OCPolarity;        // One of FTM_OCPOLRITY_xxx
 } FTM_OC_InitTypeDef;
 
 typedef struct {
-    uint32_t    ICPolarity;     // Specifies Rising/Falling/Both
+    uint32_t ICPolarity;        // Specifies Rising/Falling/Both
 } FTM_IC_InitTypeDef;
 
-#define IS_FTM_INSTANCE(INSTANCE)   (((INSTANCE) == FTM0)   || \
-                                     ((INSTANCE) == FTM1)   || \
-                                     ((INSTANCE) == FTM2))
+#define IS_FTM_INSTANCE(INSTANCE)   (((INSTANCE) == FTM0) || \
+    ((INSTANCE) == FTM1) || \
+    ((INSTANCE) == FTM2))
 
-#define IS_FTM_PRESCALERSHIFT(PRESCALERSHIFT) (((PRESCALERSHIFT) & ~7) == 0)
+#define IS_FTM_PRESCALERSHIFT(PRESCALERSHIFT) (((PRESCALERSHIFT) &~7) == 0)
 
 #define FTM_COUNTERMODE_UP      (0)
 #define FTM_COUNTERMODE_CENTER  (FTM_SC_CPWMS)
 
-#define IS_FTM_COUNTERMODE(MODE) (((MODE) == FTM_COUNTERMODE_UP)        ||\
-                                  ((MODE) == FTM_COUNTERMODE_CENTER))
+#define IS_FTM_COUNTERMODE(MODE) (((MODE) == FTM_COUNTERMODE_UP) || \
+    ((MODE) == FTM_COUNTERMODE_CENTER))
 
 #define IS_FTM_PERIOD(PERIOD)   (((PERIOD) & 0xFFFF0000) == 0)
 
@@ -108,12 +108,12 @@
 #define FTM_OCMODE_PWM2     (FTM_CSC_MSB | FTM_CSC_ELSA)
 
 #define IS_FTM_OC_MODE(mode)        ((mode) == FTM_OCMODE_TIMING || \
-                                     (mode) == FTM_OCMODE_ACTIVE || \
-                                     (mode) == FTM_OCMODE_INACTIVE || \
-                                     (mode) == FTM_OCMODE_TOGGLE )
+    (mode) == FTM_OCMODE_ACTIVE || \
+    (mode) == FTM_OCMODE_INACTIVE || \
+    (mode) == FTM_OCMODE_TOGGLE )
 
 #define IS_FTM_PWM_MODE(mode)       ((mode) == FTM_OCMODE_PWM1 || \
-                                     (mode) == FTM_OCMODE_PWM2)
+    (mode) == FTM_OCMODE_PWM2)
 
 #define IS_FTM_CHANNEL(channel)     (((channel) & ~7) == 0)
 
@@ -122,16 +122,16 @@
 #define FTM_OCPOLARITY_HIGH     (0)
 #define FTM_OCPOLARITY_LOW      (1)
 
-#define IS_FTM_OC_POLARITY(polarity) ((polarity) == FTM_OCPOLARITY_HIGH    || \
-                                      (polarity) == FTM_OCPOLARITY_LOW)
+#define IS_FTM_OC_POLARITY(polarity) ((polarity) == FTM_OCPOLARITY_HIGH || \
+    (polarity) == FTM_OCPOLARITY_LOW)
 
 #define FTM_ICPOLARITY_RISING   (FTM_CSC_ELSA)
 #define FTM_ICPOLARITY_FALLING  (FTM_CSC_ELSB)
 #define FTM_ICPOLARITY_BOTH     (FTM_CSC_ELSA | FTM_CSC_ELSB)
 
-#define IS_FTM_IC_POLARITY(polarity) ((polarity) == FTM_ICPOLARITY_RISING    || \
-                                      (polarity) == FTM_ICPOLARITY_FALLING   || \
-                                      (polarity) == FTM_ICPOLARITY_BOTH)
+#define IS_FTM_IC_POLARITY(polarity) ((polarity) == FTM_ICPOLARITY_RISING || \
+    (polarity) == FTM_ICPOLARITY_FALLING || \
+    (polarity) == FTM_ICPOLARITY_BOTH)
 
 typedef enum {
     HAL_FTM_STATE_RESET     = 0x00,
@@ -140,9 +140,9 @@
 } HAL_FTM_State;
 
 typedef struct {
-    FTM_TypeDef            *Instance;
-    FTM_Base_InitTypeDef    Init;
-    HAL_FTM_State           State;
+    FTM_TypeDef *Instance;
+    FTM_Base_InitTypeDef Init;
+    HAL_FTM_State State;
 
 } FTM_HandleTypeDef;
 
@@ -166,19 +166,19 @@
 void HAL_FTM_Base_DeInit(FTM_HandleTypeDef *hftm);
 
 void HAL_FTM_OC_Init(FTM_HandleTypeDef *hftm);
-void HAL_FTM_OC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef* sConfig, uint32_t channel);
+void HAL_FTM_OC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef *sConfig, uint32_t channel);
 void HAL_FTM_OC_Start(FTM_HandleTypeDef *hftm, uint32_t channel);
 void HAL_FTM_OC_Start_IT(FTM_HandleTypeDef *hftm, uint32_t channel);
 void HAL_FTM_OC_DeInit(FTM_HandleTypeDef *hftm);
 
 void HAL_FTM_PWM_Init(FTM_HandleTypeDef *hftm);
-void HAL_FTM_PWM_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef* sConfig, uint32_t channel);
+void HAL_FTM_PWM_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef *sConfig, uint32_t channel);
 void HAL_FTM_PWM_Start(FTM_HandleTypeDef *hftm, uint32_t channel);
 void HAL_FTM_PWM_Start_IT(FTM_HandleTypeDef *hftm, uint32_t channel);
 void HAL_FTM_PWM_DeInit(FTM_HandleTypeDef *hftm);
 
 void HAL_FTM_IC_Init(FTM_HandleTypeDef *hftm);
-void HAL_FTM_IC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_IC_InitTypeDef* sConfig, uint32_t channel);
+void HAL_FTM_IC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_IC_InitTypeDef *sConfig, uint32_t channel);
 void HAL_FTM_IC_Start(FTM_HandleTypeDef *hftm, uint32_t channel);
 void HAL_FTM_IC_Start_IT(FTM_HandleTypeDef *hftm, uint32_t channel);
 void HAL_FTM_IC_DeInit(FTM_HandleTypeDef *hftm);
diff --git a/ports/teensy/hal_gpio.c b/ports/teensy/hal_gpio.c
index f9e1376..e8bc1eb 100644
--- a/ports/teensy/hal_gpio.c
+++ b/ports/teensy/hal_gpio.c
@@ -4,8 +4,7 @@
 
 #define GPIO_NUMBER 32
 
-void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init)
-{
+void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init) {
     /* Check the parameters */
     assert_param(IS_GPIO_PIN(GPIO_Init->Pin));
     assert_param(IS_GPIO_MODE(GPIO_Init->Mode));
@@ -24,11 +23,9 @@
         if ((GPIO_Init->Mode == GPIO_MODE_AF_PP) || (GPIO_Init->Mode == GPIO_MODE_AF_OD)) {
             /* Check the Alternate function parameter */
             assert_param(IS_GPIO_AF(GPIO_Init->Alternate));
-        }
-        else if (GPIO_Init->Mode == GPIO_MODE_ANALOG) {
+        } else if (GPIO_Init->Mode == GPIO_MODE_ANALOG) {
             GPIO_Init->Alternate = 0;
-        }
-        else {
+        } else {
             GPIO_Init->Alternate = 1;
         }
 
@@ -80,44 +77,39 @@
             }
         }
 
-#if 0
+        #if 0
         /*--------------------- EXTI Mode Configuration ------------------------*/
         /* Configure the External Interrupt or event for the current IO */
-        if((GPIO_Init->Mode & EXTI_MODE) == EXTI_MODE)
-        {
-          /* Enable SYSCFG Clock */
-          __SYSCFG_CLK_ENABLE();
+        if ((GPIO_Init->Mode & EXTI_MODE) == EXTI_MODE) {
+            /* Enable SYSCFG Clock */
+            __SYSCFG_CLK_ENABLE();
 
-          temp = ((uint32_t)0x0F) << (4 * (position & 0x03));
-          SYSCFG->EXTICR[position >> 2] &= ~temp;
-          SYSCFG->EXTICR[position >> 2] |= ((uint32_t)(__HAL_GET_GPIO_SOURCE(GPIOx)) << (4 * (position & 0x03)));
+            temp = ((uint32_t)0x0F) << (4 * (position & 0x03));
+            SYSCFG->EXTICR[position >> 2] &= ~temp;
+            SYSCFG->EXTICR[position >> 2] |= ((uint32_t)(__HAL_GET_GPIO_SOURCE(GPIOx)) << (4 * (position & 0x03)));
 
-          /* Clear EXTI line configuration */
-          EXTI->IMR &= ~((uint32_t)iocurrent);
-          EXTI->EMR &= ~((uint32_t)iocurrent);
+            /* Clear EXTI line configuration */
+            EXTI->IMR &= ~((uint32_t)iocurrent);
+            EXTI->EMR &= ~((uint32_t)iocurrent);
 
-          if((GPIO_Init->Mode & GPIO_MODE_IT) == GPIO_MODE_IT)
-          {
-            EXTI->IMR |= iocurrent;
-          }
-          if((GPIO_Init->Mode & GPIO_MODE_EVT) == GPIO_MODE_EVT)
-          {
-            EXTI->EMR |= iocurrent;
-          }
+            if ((GPIO_Init->Mode & GPIO_MODE_IT) == GPIO_MODE_IT) {
+                EXTI->IMR |= iocurrent;
+            }
+            if ((GPIO_Init->Mode & GPIO_MODE_EVT) == GPIO_MODE_EVT) {
+                EXTI->EMR |= iocurrent;
+            }
 
-          /* Clear Rising Falling edge configuration */
-          EXTI->RTSR &= ~((uint32_t)iocurrent);
-          EXTI->FTSR &= ~((uint32_t)iocurrent);
+            /* Clear Rising Falling edge configuration */
+            EXTI->RTSR &= ~((uint32_t)iocurrent);
+            EXTI->FTSR &= ~((uint32_t)iocurrent);
 
-          if((GPIO_Init->Mode & RISING_EDGE) == RISING_EDGE)
-          {
-            EXTI->RTSR |= iocurrent;
-          }
-          if((GPIO_Init->Mode & FALLING_EDGE) == FALLING_EDGE)
-          {
-            EXTI->FTSR |= iocurrent;
-          }
+            if ((GPIO_Init->Mode & RISING_EDGE) == RISING_EDGE) {
+                EXTI->RTSR |= iocurrent;
+            }
+            if ((GPIO_Init->Mode & FALLING_EDGE) == FALLING_EDGE) {
+                EXTI->FTSR |= iocurrent;
+            }
         }
-#endif
+        #endif
     }
 }
diff --git a/ports/teensy/help.c b/ports/teensy/help.c
index a2370c0..11625af 100644
--- a/ports/teensy/help.c
+++ b/ports/teensy/help.c
@@ -27,43 +27,43 @@
 #include "py/builtin.h"
 
 const char teensy_help_text[] =
-"Welcome to MicroPython!\n"
-"\n"
-"For online help please visit http://micropython.org/help/.\n"
-"\n"
-"Quick overview of commands for the board:\n"
-"  pyb.info()    -- print some general information\n"
-"  pyb.gc()      -- run the garbage collector\n"
-"  pyb.delay(n)  -- wait for n milliseconds\n"
-"  pyb.Switch()  -- create a switch object\n"
-"                   Switch methods: (), callback(f)\n"
-"  pyb.LED(n)    -- create an LED object for LED n (n=1,2,3,4)\n"
-"                   LED methods: on(), off(), toggle(), intensity(<n>)\n"
-"  pyb.Pin(pin)  -- get a pin, eg pyb.Pin('X1')\n"
-"  pyb.Pin(pin, m, [p]) -- get a pin and configure it for IO mode m, pull mode p\n"
-"                   Pin methods: init(..), value([v]), high(), low()\n"
-"  pyb.ExtInt(pin, m, p, callback) -- create an external interrupt object\n"
-"  pyb.ADC(pin)  -- make an analog object from a pin\n"
-"                   ADC methods: read(), read_timed(buf, freq)\n"
-"  pyb.DAC(port) -- make a DAC object\n"
-"                   DAC methods: triangle(freq), write(n), write_timed(buf, freq)\n"
-"  pyb.RTC()     -- make an RTC object; methods: datetime([val])\n"
-"  pyb.rng()     -- get a 30-bit hardware random number\n"
-"  pyb.Servo(n)  -- create Servo object for servo n (n=1,2,3,4)\n"
-"                   Servo methods: calibration(..), angle([x, [t]]), speed([x, [t]])\n"
-"  pyb.Accel()   -- create an Accelerometer object\n"
-"                   Accelerometer methods: x(), y(), z(), tilt(), filtered_xyz()\n"
-"\n"
-"Pins are numbered X1-X12, X17-X22, Y1-Y12, or by their MCU name\n"
-"Pin IO modes are: pyb.Pin.IN, pyb.Pin.OUT_PP, pyb.Pin.OUT_OD\n"
-"Pin pull modes are: pyb.Pin.PULL_NONE, pyb.Pin.PULL_UP, pyb.Pin.PULL_DOWN\n"
-"Additional serial bus objects: pyb.I2C(n), pyb.SPI(n), pyb.UART(n)\n"
-"\n"
-"Control commands:\n"
-"  CTRL-A        -- on a blank line, enter raw REPL mode\n"
-"  CTRL-B        -- on a blank line, enter normal REPL mode\n"
-"  CTRL-C        -- interrupt a running program\n"
-"  CTRL-D        -- on a blank line, do a soft reset of the board\n"
-"\n"
-"For further help on a specific object, type help(obj)\n"
+    "Welcome to MicroPython!\n"
+    "\n"
+    "For online help please visit http://micropython.org/help/.\n"
+    "\n"
+    "Quick overview of commands for the board:\n"
+    "  pyb.info()    -- print some general information\n"
+    "  pyb.gc()      -- run the garbage collector\n"
+    "  pyb.delay(n)  -- wait for n milliseconds\n"
+    "  pyb.Switch()  -- create a switch object\n"
+    "                   Switch methods: (), callback(f)\n"
+    "  pyb.LED(n)    -- create an LED object for LED n (n=1,2,3,4)\n"
+    "                   LED methods: on(), off(), toggle(), intensity(<n>)\n"
+    "  pyb.Pin(pin)  -- get a pin, eg pyb.Pin('X1')\n"
+    "  pyb.Pin(pin, m, [p]) -- get a pin and configure it for IO mode m, pull mode p\n"
+    "                   Pin methods: init(..), value([v]), high(), low()\n"
+    "  pyb.ExtInt(pin, m, p, callback) -- create an external interrupt object\n"
+    "  pyb.ADC(pin)  -- make an analog object from a pin\n"
+    "                   ADC methods: read(), read_timed(buf, freq)\n"
+    "  pyb.DAC(port) -- make a DAC object\n"
+    "                   DAC methods: triangle(freq), write(n), write_timed(buf, freq)\n"
+    "  pyb.RTC()     -- make an RTC object; methods: datetime([val])\n"
+    "  pyb.rng()     -- get a 30-bit hardware random number\n"
+    "  pyb.Servo(n)  -- create Servo object for servo n (n=1,2,3,4)\n"
+    "                   Servo methods: calibration(..), angle([x, [t]]), speed([x, [t]])\n"
+    "  pyb.Accel()   -- create an Accelerometer object\n"
+    "                   Accelerometer methods: x(), y(), z(), tilt(), filtered_xyz()\n"
+    "\n"
+    "Pins are numbered X1-X12, X17-X22, Y1-Y12, or by their MCU name\n"
+    "Pin IO modes are: pyb.Pin.IN, pyb.Pin.OUT_PP, pyb.Pin.OUT_OD\n"
+    "Pin pull modes are: pyb.Pin.PULL_NONE, pyb.Pin.PULL_UP, pyb.Pin.PULL_DOWN\n"
+    "Additional serial bus objects: pyb.I2C(n), pyb.SPI(n), pyb.UART(n)\n"
+    "\n"
+    "Control commands:\n"
+    "  CTRL-A        -- on a blank line, enter raw REPL mode\n"
+    "  CTRL-B        -- on a blank line, enter normal REPL mode\n"
+    "  CTRL-C        -- interrupt a running program\n"
+    "  CTRL-D        -- on a blank line, do a soft reset of the board\n"
+    "\n"
+    "For further help on a specific object, type help(obj)\n"
 ;
diff --git a/ports/teensy/led.c b/ports/teensy/led.c
index f1a7b32..7c2f3d2 100644
--- a/ports/teensy/led.c
+++ b/ports/teensy/led.c
@@ -16,15 +16,15 @@
 
 STATIC const pyb_led_obj_t pyb_led_obj[] = {
     {{&pyb_led_type}, 1, &MICROPY_HW_LED1},
-#if defined(MICROPY_HW_LED2)
+    #if defined(MICROPY_HW_LED2)
     {{&pyb_led_type}, 2, &MICROPY_HW_LED2},
-#if defined(MICROPY_HW_LED3)
+    #if defined(MICROPY_HW_LED3)
     {{&pyb_led_type}, 3, &MICROPY_HW_LED3},
-#if defined(MICROPY_HW_LED4)
+    #if defined(MICROPY_HW_LED4)
     {{&pyb_led_type}, 4, &MICROPY_HW_LED4},
-#endif
-#endif
-#endif
+    #endif
+    #endif
+    #endif
 };
 #define NUM_LEDS MP_ARRAY_SIZE(pyb_led_obj)
 
diff --git a/ports/teensy/main.c b/ports/teensy/main.c
index 021ca54..142f710 100644
--- a/ports/teensy/main.c
+++ b/ports/teensy/main.c
@@ -93,7 +93,7 @@
 static mp_obj_t pyb_info(void) {
     // get and print unique id; 96 bits
     {
-        byte *id = (byte*)0x40048058;
+        byte *id = (byte *)0x40048058;
         printf("ID=%02x%02x%02x%02x:%02x%02x%02x%02x:%02x%02x%02x%02x\n", id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7], id[8], id[9], id[10], id[11]);
     }
 
@@ -121,7 +121,7 @@
         printf("  1=%u 2=%u m=%u\n", info.num_1block, info.num_2block, info.max_block);
     }
 
-#if 0
+    #if 0
     // free space on flash
     {
         DWORD nclst;
@@ -129,7 +129,7 @@
         f_getfree("0:", &nclst, &fatfs);
         printf("LFS free: %u bytes\n", (uint)(nclst * fatfs->csize * 512));
     }
-#endif
+    #endif
 
     return mp_const_none;
 }
@@ -162,7 +162,7 @@
         pinMode(pin, INPUT);
         return MP_OBJ_NEW_SMALL_INT(digitalRead(pin));
     }
-    
+
     // set pin
     pinMode(pin, OUTPUT);
     digitalWrite(pin, mp_obj_is_true(args[1]));
@@ -264,7 +264,7 @@
     led_state(PYB_LED_BUILTIN, 1);
 
     // GC init
-    gc_init(&_heap_start, (void*)HEAP_END);
+    gc_init(&_heap_start, (void *)HEAP_END);
 
     // MicroPython init
     mp_init();
@@ -276,7 +276,7 @@
 
     pin_init0();
 
-#if 0
+    #if 0
     // add some functions to the python namespace
     {
         mp_store_name(MP_QSTR_help, mp_make_function_n(0, pyb_help));
@@ -297,23 +297,23 @@
         mp_store_attr(m, MP_QSTR_Servo, mp_make_function_n(0, pyb_Servo));
         mp_store_name(MP_QSTR_pyb, m);
     }
-#endif
+    #endif
 
-#if MICROPY_MODULE_FROZEN
+    #if MICROPY_MODULE_FROZEN
     pyexec_frozen_module("boot.py");
-#else
+    #else
     if (!pyexec_file_if_exists("/boot.py")) {
         flash_error(4);
     }
-#endif
+    #endif
 
     // Turn bootup LED off
     led_state(PYB_LED_BUILTIN, 0);
 
     // run main script
-#if MICROPY_MODULE_FROZEN
+    #if MICROPY_MODULE_FROZEN
     pyexec_frozen_module("main.py");
-#else
+    #else
     {
         vstr_t *vstr = vstr_new(16);
         vstr_add_str(vstr, "/");
@@ -327,7 +327,7 @@
         }
         vstr_free(vstr);
     }
-#endif
+    #endif
 
     // enter REPL
     // REPL mode can change, or it can request a soft reset
@@ -358,24 +358,25 @@
 // ultoa is used by usb_init_serialnumber. Normally ultoa would be provided
 // by nonstd.c from the teensy core, but it conflicts with some of the
 // MicroPython functions in string0.c, so we provide ultoa here.
-char * ultoa(unsigned long val, char *buf, int radix) 	
-{
-	unsigned digit;
-	int i=0, j;
-	char t;
+char *ultoa(unsigned long val, char *buf, int radix) {
+    unsigned digit;
+    int i = 0, j;
+    char t;
 
-	while (1) {
-		digit = val % radix;
-		buf[i] = ((digit < 10) ? '0' + digit : 'A' + digit - 10);
-		val /= radix;
-		if (val == 0) break;
-		i++;
-	}
-	buf[i + 1] = 0;
-	for (j=0; j < i; j++, i--) {
-		t = buf[j];
-		buf[j] = buf[i];
-		buf[i] = t;
-	}
-	return buf;
+    while (1) {
+        digit = val % radix;
+        buf[i] = ((digit < 10) ? '0' + digit : 'A' + digit - 10);
+        val /= radix;
+        if (val == 0) {
+            break;
+        }
+        i++;
+    }
+    buf[i + 1] = 0;
+    for (j = 0; j < i; j++, i--) {
+        t = buf[j];
+        buf[j] = buf[i];
+        buf[i] = t;
+    }
+    return buf;
 }
diff --git a/ports/teensy/make-pins.py b/ports/teensy/make-pins.py
index 0f6c5f2..ddefae8 100755
--- a/ports/teensy/make-pins.py
+++ b/ports/teensy/make-pins.py
@@ -8,33 +8,34 @@
 import csv
 
 SUPPORTED_FN = {
-    'FTM'   : ['CH0',  'CH1',  'CH2',  'CH3', 'CH4', 'CH5', 'CH6', 'CH7',
-               'QD_PHA', 'QD_PHB'],
-    'I2C'   : ['SDA', 'SCL'],
-    'UART'  : ['RX', 'TX', 'CTS', 'RTS'],
-    'SPI'   : ['NSS', 'SCK', 'MISO', 'MOSI']
+    "FTM": ["CH0", "CH1", "CH2", "CH3", "CH4", "CH5", "CH6", "CH7", "QD_PHA", "QD_PHB"],
+    "I2C": ["SDA", "SCL"],
+    "UART": ["RX", "TX", "CTS", "RTS"],
+    "SPI": ["NSS", "SCK", "MISO", "MOSI"],
 }
 
+
 def parse_port_pin(name_str):
     """Parses a string and returns a (port-num, pin-num) tuple."""
     if len(name_str) < 4:
         raise ValueError("Expecting pin name to be at least 4 charcters.")
-    if name_str[0:2] != 'PT':
+    if name_str[0:2] != "PT":
         raise ValueError("Expecting pin name to start with PT")
-    if name_str[2] not in ('A', 'B', 'C', 'D', 'E', 'Z'):
+    if name_str[2] not in ("A", "B", "C", "D", "E", "Z"):
         raise ValueError("Expecting pin port to be between A and E or Z")
-    port = ord(name_str[2]) - ord('A')
-    pin_str = name_str[3:].split('/')[0]
+    port = ord(name_str[2]) - ord("A")
+    pin_str = name_str[3:].split("/")[0]
     if not pin_str.isdigit():
         raise ValueError("Expecting numeric pin number.")
     return (port, int(pin_str))
 
+
 def split_name_num(name_num):
     num = None
     for num_idx in range(len(name_num) - 1, -1, -1):
         if not name_num[num_idx].isdigit():
-            name = name_num[0:num_idx + 1]
-            num_str = name_num[num_idx + 1:]
+            name = name_num[0 : num_idx + 1]
+            num_str = name_num[num_idx + 1 :]
             if len(num_str) > 0:
                 num = int(num_str)
             break
@@ -48,12 +49,12 @@
         self.idx = idx
         self.af_str = af_str
 
-        self.func = ''
+        self.func = ""
         self.fn_num = None
-        self.pin_type = ''
+        self.pin_type = ""
         self.supported = False
 
-        af_words = af_str.split('_', 1)
+        af_words = af_str.split("_", 1)
         self.func, self.fn_num = split_name_num(af_words[0])
         if len(af_words) > 1:
             self.pin_type = af_words[1]
@@ -69,22 +70,25 @@
         """Returns the numbered function (i.e. USART6) for this AF."""
         if self.fn_num is None:
             return self.func
-        return '{:s}{:d}'.format(self.func, self.fn_num)
+        return "{:s}{:d}".format(self.func, self.fn_num)
 
     def mux_name(self):
-        return 'AF{:d}_{:s}'.format(self.idx, self.ptr())
+        return "AF{:d}_{:s}".format(self.idx, self.ptr())
 
     def print(self):
         """Prints the C representation of this AF."""
         if self.supported:
-            print('  AF',  end='')
+            print("  AF", end="")
         else:
-            print('  //', end='')
+            print("  //", end="")
         fn_num = self.fn_num
         if fn_num is None:
             fn_num = 0
-        print('({:2d}, {:8s}, {:2d}, {:10s}, {:8s}), // {:s}'.format(self.idx,
-              self.func, fn_num, self.pin_type, self.ptr(), self.af_str))
+        print(
+            "({:2d}, {:8s}, {:2d}, {:10s}, {:8s}), // {:s}".format(
+                self.idx, self.func, fn_num, self.pin_type, self.ptr(), self.af_str
+            )
+        )
 
     def qstr_list(self):
         return [self.mux_name()]
@@ -103,10 +107,10 @@
         self.board_pin = False
 
     def port_letter(self):
-        return chr(self.port + ord('A'))
+        return chr(self.port + ord("A"))
 
     def cpu_pin_name(self):
-        return '{:s}{:d}'.format(self.port_letter(), self.pin)
+        return "{:s}{:d}".format(self.port_letter(), self.pin)
 
     def is_board_pin(self):
         return self.board_pin
@@ -115,12 +119,12 @@
         self.board_pin = True
 
     def parse_adc(self, adc_str):
-        if (adc_str[:3] != 'ADC'):
+        if adc_str[:3] != "ADC":
             return
-        (adc,channel) = adc_str.split('_')
+        (adc, channel) = adc_str.split("_")
         for idx in range(3, len(adc)):
-            adc_num = int(adc[idx]) # 1, 2, or 3
-            self.adc_num |= (1 << (adc_num - 1))
+            adc_num = int(adc[idx])  # 1, 2, or 3
+            self.adc_num |= 1 << (adc_num - 1)
         self.adc_channel = int(channel[2:])
 
     def parse_af(self, af_idx, af_strs_in):
@@ -128,7 +132,7 @@
             return
         # If there is a slash, then the slash separates 2 aliases for the
         # same alternate function.
-        af_strs = af_strs_in.split('/')
+        af_strs = af_strs_in.split("/")
         for af_str in af_strs:
             alt_fn = AlternateFunction(af_idx, af_str)
             self.alt_fn.append(alt_fn)
@@ -137,43 +141,50 @@
 
     def alt_fn_name(self, null_if_0=False):
         if null_if_0 and self.alt_fn_count == 0:
-            return 'NULL'
-        return 'pin_{:s}_af'.format(self.cpu_pin_name())
+            return "NULL"
+        return "pin_{:s}_af".format(self.cpu_pin_name())
 
     def adc_num_str(self):
-        str = ''
-        for adc_num in range(1,4):
+        str = ""
+        for adc_num in range(1, 4):
             if self.adc_num & (1 << (adc_num - 1)):
                 if len(str) > 0:
-                    str += ' | '
-                str += 'PIN_ADC'
-                str += chr(ord('0') + adc_num)
+                    str += " | "
+                str += "PIN_ADC"
+                str += chr(ord("0") + adc_num)
         if len(str) == 0:
-            str = '0'
+            str = "0"
         return str
 
     def print(self):
         if self.alt_fn_count == 0:
-            print("// ",  end='')
-        print('const pin_af_obj_t {:s}[] = {{'.format(self.alt_fn_name()))
+            print("// ", end="")
+        print("const pin_af_obj_t {:s}[] = {{".format(self.alt_fn_name()))
         for alt_fn in self.alt_fn:
             alt_fn.print()
         if self.alt_fn_count == 0:
-            print("// ",  end='')
-        print('};')
-        print('')
-        print('const pin_obj_t pin_{:s} = PIN({:s}, {:d}, {:d}, {:s}, {:s}, {:d});'.format(
-            self.cpu_pin_name(), self.port_letter(), self.pin,
-            self.alt_fn_count, self.alt_fn_name(null_if_0=True),
-            self.adc_num_str(), self.adc_channel))
-        print('')
+            print("// ", end="")
+        print("};")
+        print("")
+        print(
+            "const pin_obj_t pin_{:s} = PIN({:s}, {:d}, {:d}, {:s}, {:s}, {:d});".format(
+                self.cpu_pin_name(),
+                self.port_letter(),
+                self.pin,
+                self.alt_fn_count,
+                self.alt_fn_name(null_if_0=True),
+                self.adc_num_str(),
+                self.adc_channel,
+            )
+        )
+        print("")
 
     def print_header(self, hdr_file):
-        hdr_file.write('extern const pin_obj_t pin_{:s};\n'.
-                       format(self.cpu_pin_name()))
+        hdr_file.write("extern const pin_obj_t pin_{:s};\n".format(self.cpu_pin_name()))
         if self.alt_fn_count > 0:
-            hdr_file.write('extern const pin_af_obj_t pin_{:s}_af[];\n'.
-                           format(self.cpu_pin_name()))
+            hdr_file.write(
+                "extern const pin_af_obj_t pin_{:s}_af[];\n".format(self.cpu_pin_name())
+            )
 
     def qstr_list(self):
         result = []
@@ -184,7 +195,6 @@
 
 
 class NamedPin(object):
-
     def __init__(self, name, pin):
         self._name = name
         self._pin = pin
@@ -197,10 +207,9 @@
 
 
 class Pins(object):
-
     def __init__(self):
-        self.cpu_pins = []   # list of NamedPin objects
-        self.board_pins = [] # list of NamedPin objects
+        self.cpu_pins = []  # list of NamedPin objects
+        self.board_pins = []  # list of NamedPin objects
 
     def find_pin(self, port_num, pin_num):
         for named_pin in self.cpu_pins:
@@ -209,7 +218,7 @@
                 return pin
 
     def parse_af_file(self, filename, pinname_col, af_col):
-        with open(filename, 'r') as csvfile:
+        with open(filename, "r") as csvfile:
             rows = csv.reader(csvfile)
             for row in rows:
                 try:
@@ -223,7 +232,7 @@
                 self.cpu_pins.append(NamedPin(pin.cpu_pin_name(), pin))
 
     def parse_board_file(self, filename):
-        with open(filename, 'r') as csvfile:
+        with open(filename, "r") as csvfile:
             rows = csv.reader(csvfile)
             for row in rows:
                 try:
@@ -236,52 +245,64 @@
                     self.board_pins.append(NamedPin(row[0], pin))
 
     def print_named(self, label, named_pins):
-        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 named_pin in named_pins:
             pin = named_pin.pin()
             if pin.is_board_pin():
-                print('  {{ MP_ROM_QSTR(MP_QSTR_{:s}), MP_ROM_PTR(&pin_{:s}) }},'.format(named_pin.name(),  pin.cpu_pin_name()))
-        print('};')
-        print('MP_DEFINE_CONST_DICT(pin_{:s}_pins_locals_dict, pin_{:s}_pins_locals_dict_table);'.format(label, label));
+                print(
+                    "  {{ MP_ROM_QSTR(MP_QSTR_{:s}), MP_ROM_PTR(&pin_{:s}) }},".format(
+                        named_pin.name(), pin.cpu_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):
         for named_pin in self.cpu_pins:
             pin = named_pin.pin()
             if pin.is_board_pin():
                 pin.print()
-        self.print_named('cpu', self.cpu_pins)
-        print('')
-        self.print_named('board', self.board_pins)
+        self.print_named("cpu", self.cpu_pins)
+        print("")
+        self.print_named("board", self.board_pins)
 
     def print_adc(self, adc_num):
-        print('');
-        print('const pin_obj_t * const pin_adc{:d}[] = {{'.format(adc_num))
+        print("")
+        print("const pin_obj_t * const pin_adc{:d}[] = {{".format(adc_num))
         for channel in range(16):
             adc_found = False
             for named_pin in self.cpu_pins:
                 pin = named_pin.pin()
-                if (pin.is_board_pin() and
-                    (pin.adc_num & (1 << (adc_num - 1))) and (pin.adc_channel == channel)):
-                    print('  &pin_{:s}, // {:d}'.format(pin.cpu_pin_name(), channel))
+                if (
+                    pin.is_board_pin()
+                    and (pin.adc_num & (1 << (adc_num - 1)))
+                    and (pin.adc_channel == channel)
+                ):
+                    print("  &pin_{:s}, // {:d}".format(pin.cpu_pin_name(), channel))
                     adc_found = True
                     break
             if not adc_found:
-                print('  NULL,    // {:d}'.format(channel))
-        print('};')
-
+                print("  NULL,    // {:d}".format(channel))
+        print("};")
 
     def print_header(self, hdr_filename):
-        with open(hdr_filename, 'wt') as hdr_file:
+        with open(hdr_filename, "wt") as hdr_file:
             for named_pin in self.cpu_pins:
                 pin = named_pin.pin()
                 if pin.is_board_pin():
                     pin.print_header(hdr_file)
-            hdr_file.write('extern const pin_obj_t * const pin_adc1[];\n')
-            hdr_file.write('extern const pin_obj_t * const pin_adc2[];\n')
-            hdr_file.write('extern const pin_obj_t * const pin_adc3[];\n')
+            hdr_file.write("extern const pin_obj_t * const pin_adc1[];\n")
+            hdr_file.write("extern const pin_obj_t * const pin_adc2[];\n")
+            hdr_file.write("extern const pin_obj_t * const pin_adc3[];\n")
 
     def print_qstr(self, qstr_filename):
-        with open(qstr_filename, 'wt') as qstr_file:
+        with open(qstr_filename, "wt") as qstr_file:
             qstr_set = set([])
             for named_pin in self.cpu_pins:
                 pin = named_pin.pin()
@@ -291,11 +312,10 @@
             for named_pin in self.board_pins:
                 qstr_set |= set([named_pin.name()])
             for qstr in sorted(qstr_set):
-                print('Q({})'.format(qstr), file=qstr_file)
-
+                print("Q({})".format(qstr), file=qstr_file)
 
     def print_af_hdr(self, af_const_filename):
-        with open(af_const_filename,  'wt') as af_const_file:
+        with open(af_const_filename, "wt") as af_const_file:
             af_hdr_set = set([])
             mux_name_width = 0
             for named_pin in self.cpu_pins:
@@ -308,88 +328,89 @@
                             if len(mux_name) > mux_name_width:
                                 mux_name_width = len(mux_name)
             for mux_name in sorted(af_hdr_set):
-                key = 'MP_OBJ_NEW_QSTR(MP_QSTR_{}),'.format(mux_name)
-                val = 'MP_OBJ_NEW_SMALL_INT(GPIO_{})'.format(mux_name)
-                print('    { %-*s %s },' % (mux_name_width + 26, key, val),
-                      file=af_const_file)
+                key = "MP_OBJ_NEW_QSTR(MP_QSTR_{}),".format(mux_name)
+                val = "MP_OBJ_NEW_SMALL_INT(GPIO_{})".format(mux_name)
+                print("    { %-*s %s }," % (mux_name_width + 26, key, val), file=af_const_file)
 
     def print_af_py(self, af_py_filename):
-        with open(af_py_filename,  'wt') as af_py_file:
-            print('PINS_AF = (', file=af_py_file);
+        with open(af_py_filename, "wt") as af_py_file:
+            print("PINS_AF = (", file=af_py_file)
             for named_pin in self.board_pins:
-                print("  ('%s', " % named_pin.name(), end='', file=af_py_file)
+                print("  ('%s', " % named_pin.name(), end="", file=af_py_file)
                 for af in named_pin.pin().alt_fn:
                     if af.is_supported():
-                        print("(%d, '%s'), " % (af.idx, af.af_str), end='', file=af_py_file)
-                print('),', file=af_py_file)
-            print(')',  file=af_py_file)
+                        print("(%d, '%s'), " % (af.idx, af.af_str), end="", file=af_py_file)
+                print("),", file=af_py_file)
+            print(")", file=af_py_file)
 
 
 def main():
     parser = argparse.ArgumentParser(
         prog="make-pins.py",
         usage="%(prog)s [options] [command]",
-        description="Generate board specific pin file"
+        description="Generate board specific pin file",
     )
     parser.add_argument(
-        "-a", "--af",
+        "-a",
+        "--af",
         dest="af_filename",
         help="Specifies the alternate function file for the chip",
-        default="mk20dx256_af.csv"
+        default="mk20dx256_af.csv",
     )
     parser.add_argument(
         "--af-const",
         dest="af_const_filename",
         help="Specifies header file for alternate function constants.",
-        default="build/pins_af_const.h"
+        default="build/pins_af_const.h",
     )
     parser.add_argument(
         "--af-py",
         dest="af_py_filename",
         help="Specifies the filename for the python alternate function mappings.",
-        default="build/pins_af.py"
+        default="build/pins_af.py",
     )
     parser.add_argument(
-        "-b", "--board",
-        dest="board_filename",
-        help="Specifies the board file",
+        "-b", "--board", dest="board_filename", help="Specifies the board file",
     )
     parser.add_argument(
-        "-p", "--prefix",
+        "-p",
+        "--prefix",
         dest="prefix_filename",
         help="Specifies beginning portion of generated pins file",
-        default="mk20dx256_prefix.c"
+        default="mk20dx256_prefix.c",
     )
     parser.add_argument(
-        "-q", "--qstr",
+        "-q",
+        "--qstr",
         dest="qstr_filename",
         help="Specifies name of generated qstr header file",
-        default="build/pins_qstr.h"
+        default="build/pins_qstr.h",
     )
     parser.add_argument(
-        "-r", "--hdr",
+        "-r",
+        "--hdr",
         dest="hdr_filename",
         help="Specifies name of generated pin header file",
-        default="build/pins.h"
+        default="build/pins.h",
     )
     args = parser.parse_args(sys.argv[1:])
 
     pins = Pins()
 
-    print('// This file was automatically generated by make-pins.py')
-    print('//')
+    print("// This file was automatically generated by make-pins.py")
+    print("//")
     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, 4, 3)
 
     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)
 
     if args.prefix_filename:
-        print('// --prefix {:s}'.format(args.prefix_filename))
-        print('')
-        with open(args.prefix_filename, 'r') as prefix_file:
+        print("// --prefix {:s}".format(args.prefix_filename))
+        print("")
+        with open(args.prefix_filename, "r") as prefix_file:
             print(prefix_file.read())
     pins.print()
     pins.print_adc(1)
diff --git a/ports/teensy/memzip_files/boot.py b/ports/teensy/memzip_files/boot.py
index 6dd5516..e227989 100644
--- a/ports/teensy/memzip_files/boot.py
+++ b/ports/teensy/memzip_files/boot.py
@@ -1,12 +1,15 @@
 import pyb
+
 print("Executing boot.py")
 
+
 def pins():
     for pin_name in dir(pyb.Pin.board):
         pin = pyb.Pin(pin_name)
-        print('{:10s} {:s}'.format(pin_name, str(pin)))
+        print("{:10s} {:s}".format(pin_name, str(pin)))
+
 
 def af():
     for pin_name in dir(pyb.Pin.board):
         pin = pyb.Pin(pin_name)
-        print('{:10s} {:s}'.format(pin_name, str(pin.af_list())))
+        print("{:10s} {:s}".format(pin_name, str(pin.af_list())))
diff --git a/ports/teensy/memzip_files/main.py b/ports/teensy/memzip_files/main.py
index b652377..a3b3904 100644
--- a/ports/teensy/memzip_files/main.py
+++ b/ports/teensy/memzip_files/main.py
@@ -11,5 +11,3 @@
 led.on()
 pyb.delay(100)
 led.off()
-
-
diff --git a/ports/teensy/mk20dx256_prefix.c b/ports/teensy/mk20dx256_prefix.c
index 58ab07d..4790bb8 100644
--- a/ports/teensy/mk20dx256_prefix.c
+++ b/ports/teensy/mk20dx256_prefix.c
@@ -8,26 +8,26 @@
 #include "pin.h"
 
 #define AF(af_idx, af_fn, af_unit, af_type, af_ptr) \
-{ \
-    { &pin_af_type }, \
-    .name = MP_QSTR_AF ## af_idx ## _ ## af_fn ## af_unit, \
-    .idx = (af_idx), \
-    .fn = AF_FN_ ## af_fn, \
-    .unit = (af_unit), \
-    .type = AF_PIN_TYPE_ ## af_fn ## _ ## af_type, \
-    .reg = (af_ptr) \
-}
+    { \
+        { &pin_af_type }, \
+        .name = MP_QSTR_AF##af_idx##_##af_fn##af_unit, \
+        .idx = (af_idx), \
+        .fn = AF_FN_##af_fn, \
+        .unit = (af_unit), \
+        .type = AF_PIN_TYPE_##af_fn##_##af_type, \
+        .reg = (af_ptr) \
+    }
 
 #define PIN(p_port, p_pin, p_num_af, p_af, p_adc_num, p_adc_channel) \
-{ \
-    { &pin_type }, \
-    .name = MP_QSTR_ ## p_port ## p_pin, \
-    .port = PORT_ ## p_port, \
-    .pin = (p_pin), \
-    .num_af = (p_num_af), \
-    .pin_mask = (1 << (p_pin)), \
-    .gpio = GPIO ## p_port, \
-    .af = p_af, \
-    .adc_num = p_adc_num, \
-    .adc_channel = p_adc_channel, \
-}
+    { \
+        { &pin_type }, \
+        .name = MP_QSTR_##p_port##p_pin, \
+        .port = PORT_##p_port, \
+        .pin = (p_pin), \
+        .num_af = (p_num_af), \
+        .pin_mask = (1 << (p_pin)), \
+        .gpio = GPIO##p_port, \
+        .af = p_af, \
+        .adc_num = p_adc_num, \
+        .adc_channel = p_adc_channel, \
+    }
diff --git a/ports/teensy/modpyb.c b/ports/teensy/modpyb.c
index 6d637a7..d1970d7 100644
--- a/ports/teensy/modpyb.c
+++ b/ports/teensy/modpyb.c
@@ -74,7 +74,7 @@
 STATIC mp_obj_t pyb_info(uint n_args, const mp_obj_t *args) {
     // get and print unique id; 96 bits
     {
-        byte *id = (byte*)0x40048058;
+        byte *id = (byte *)0x40048058;
         printf("ID=%02x%02x%02x%02x:%02x%02x%02x%02x:%02x%02x%02x%02x\n", id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7], id[8], id[9], id[10], id[11]);
     }
 
@@ -125,7 +125,7 @@
 /// \function unique_id()
 /// Returns a string of 12 bytes (96 bits), which is the unique ID for the MCU.
 STATIC mp_obj_t pyb_unique_id(void) {
-    byte *id = (byte*)0x40048058;
+    byte *id = (byte *)0x40048058;
     return mp_obj_new_bytes(id, 12);
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_0(pyb_unique_id_obj, pyb_unique_id);
@@ -135,9 +135,9 @@
 // TODO should also be able to set frequency via this function
 STATIC mp_obj_t pyb_freq(void) {
     mp_obj_t tuple[3] = {
-       mp_obj_new_int(F_CPU),
-       mp_obj_new_int(F_BUS),
-       mp_obj_new_int(F_MEM),
+        mp_obj_new_int(F_CPU),
+        mp_obj_new_int(F_BUS),
+        mp_obj_new_int(F_MEM),
     };
     return mp_obj_new_tuple(3, tuple);
 }
@@ -256,9 +256,9 @@
 /// Takes a 4-tuple (or list) and sends it to the USB host (the PC) to
 /// signal a HID mouse-motion event.
 STATIC mp_obj_t pyb_hid_send_report(mp_obj_t arg) {
-#if 1
+    #if 1
     printf("hid_send_report not currently implemented\n");
-#else
+    #else
     mp_obj_t *items;
     mp_obj_get_array_fixed_n(arg, 4, &items);
     uint8_t data[4];
@@ -267,7 +267,7 @@
     data[2] = mp_obj_get_int(items[2]);
     data[3] = mp_obj_get_int(items[3]);
     usb_hid_send_report(data);
-#endif
+    #endif
     return mp_const_none;
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_hid_send_report_obj, pyb_hid_send_report);
@@ -321,15 +321,15 @@
     { MP_ROM_QSTR(MP_QSTR_Pin), MP_ROM_PTR(&pin_type) },
 //    { MP_ROM_QSTR(MP_QSTR_ExtInt), MP_ROM_PTR(&extint_type) },
 
-#if MICROPY_HW_ENABLE_SERVO
+    #if MICROPY_HW_ENABLE_SERVO
     { MP_ROM_QSTR(MP_QSTR_pwm), MP_ROM_PTR(&pyb_pwm_set_obj) },
     { MP_ROM_QSTR(MP_QSTR_servo), MP_ROM_PTR(&pyb_servo_set_obj) },
     { MP_ROM_QSTR(MP_QSTR_Servo), MP_ROM_PTR(&pyb_servo_type) },
-#endif
+    #endif
 
-#if MICROPY_HW_HAS_SWITCH
+    #if MICROPY_HW_HAS_SWITCH
     { MP_ROM_QSTR(MP_QSTR_Switch), MP_ROM_PTR(&pyb_switch_type) },
-#endif
+    #endif
 
 //#if MICROPY_HW_HAS_SDCARD
 //    { MP_ROM_QSTR(MP_QSTR_SD), MP_ROM_PTR(&pyb_sdcard_obj) },
@@ -356,5 +356,5 @@
 
 const mp_obj_module_t pyb_module = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&pyb_module_globals,
+    .globals = (mp_obj_dict_t *)&pyb_module_globals,
 };
diff --git a/ports/teensy/mpconfigport.h b/ports/teensy/mpconfigport.h
index a75bd68..661941f 100644
--- a/ports/teensy/mpconfigport.h
+++ b/ports/teensy/mpconfigport.h
@@ -73,13 +73,13 @@
 // to know the machine-specific values, see irq.h.
 
 #ifndef __disable_irq
-#define __disable_irq() __asm__ volatile("CPSID i");
+#define __disable_irq() __asm__ volatile ("CPSID i");
 #endif
 
 __attribute__(( always_inline )) static inline uint32_t __get_PRIMASK(void) {
     uint32_t result;
     __asm volatile ("MRS %0, primask" : "=r" (result));
-    return(result);
+    return result;
 }
 
 __attribute__(( always_inline )) static inline void __set_PRIMASK(uint32_t priMask) {
diff --git a/ports/teensy/pin_defs_teensy.c b/ports/teensy/pin_defs_teensy.c
index e7af1e9..9041a37 100644
--- a/ports/teensy/pin_defs_teensy.c
+++ b/ports/teensy/pin_defs_teensy.c
@@ -43,7 +43,7 @@
         // Analog only pin
         return GPIO_NOPULL;
     }
-    volatile uint32_t *port_pcr = GPIO_PIN_TO_PORT_PCR(pin->gpio, pin->pin); 
+    volatile uint32_t *port_pcr = GPIO_PIN_TO_PORT_PCR(pin->gpio, pin->pin);
 
     uint32_t pcr = *port_pcr;
     uint32_t af = (pcr & PORT_PCR_MUX_MASK) >> 8;
diff --git a/ports/teensy/pin_defs_teensy.h b/ports/teensy/pin_defs_teensy.h
index d3a700b..fa24848 100644
--- a/ports/teensy/pin_defs_teensy.h
+++ b/ports/teensy/pin_defs_teensy.h
@@ -1,10 +1,10 @@
 enum {
-  PORT_A,
-  PORT_B,
-  PORT_C,
-  PORT_D,
-  PORT_E,
-  PORT_Z,
+    PORT_A,
+    PORT_B,
+    PORT_C,
+    PORT_D,
+    PORT_E,
+    PORT_Z,
 };
 
 enum {
diff --git a/ports/teensy/reg.c b/ports/teensy/reg.c
index 4f1fd52..97a9e60 100644
--- a/ports/teensy/reg.c
+++ b/ports/teensy/reg.c
@@ -11,7 +11,7 @@
 
         for (mp_uint_t reg_idx = 0; reg_idx < num_regs; reg_idx++, reg++) {
             printf("  %-8s @0x%08x = 0x%08lx\n",
-                   reg->name, (mp_uint_t)base + reg->offset, *(uint32_t *)((uint8_t *)base + reg->offset));
+                reg->name, (mp_uint_t)base + reg->offset, *(uint32_t *)((uint8_t *)base + reg->offset));
         }
         return mp_const_none;
     }
diff --git a/ports/teensy/reg.h b/ports/teensy/reg.h
index 0da6378..8202b53 100644
--- a/ports/teensy/reg.h
+++ b/ports/teensy/reg.h
@@ -3,7 +3,7 @@
 
 typedef struct {
     const char *name;
-    mp_uint_t   offset;
+    mp_uint_t offset;
 } reg_t;
 
 #define REG_ENTRY(st, name) { #name, offsetof(st, name) }
diff --git a/ports/teensy/servo.c b/ports/teensy/servo.c
index 09155f9..33fb0c0 100644
--- a/ports/teensy/servo.c
+++ b/ports/teensy/servo.c
@@ -17,7 +17,7 @@
 #define REFRESH_INTERVAL    20000     // minumim time to refresh servos in microseconds
 
 #define PDB_CONFIG (PDB_SC_TRGSEL(15) | PDB_SC_PDBEN | PDB_SC_PDBIE \
-	| PDB_SC_CONT | PDB_SC_PRESCALER(2) | PDB_SC_MULT(0))
+    | PDB_SC_CONT | PDB_SC_PRESCALER(2) | PDB_SC_MULT(0))
 #define PDB_PRESCALE 4
 #define usToTicks(us)    ((us) * (F_BUS / 1000) / PDB_PRESCALE / 1000)
 #define ticksToUs(ticks) ((ticks) * PDB_PRESCALE * 1000 / (F_BUS / 1000))
@@ -36,14 +36,12 @@
 
 #define clamp(v, min_val, max_val) ((v) < (min_val) ? (min_val) : (v) > (max_val) ? (max_val) : (v))
 
-static float map_uint_to_float(uint x, uint in_min, uint in_max, float out_min, float out_max)
-{
-	return (float)(x - in_min) * (out_max - out_min) / (float)(in_max - in_min) + (float)out_min;
+static float map_uint_to_float(uint x, uint in_min, uint in_max, float out_min, float out_max) {
+    return (float)(x - in_min) * (out_max - out_min) / (float)(in_max - in_min) + (float)out_min;
 }
 
-static uint map_float_to_uint(float x, float in_min, float in_max, uint out_min, uint out_max)
-{
-	return (int)((x - in_min) * (float)(out_max - out_min) / (in_max - in_min) + (float)out_min);
+static uint map_float_to_uint(float x, float in_min, float in_max, uint out_min, uint out_max) {
+    return (int)((x - in_min) * (float)(out_max - out_min) / (in_max - in_min) + (float)out_min);
 }
 
 static mp_obj_t servo_obj_attach(mp_obj_t self_in, mp_obj_t pin_obj) {
@@ -110,9 +108,9 @@
     if (n_args == 1) {
         // get
         float angle = map_uint_to_float(servo_ticks[self->servo_id],
-                                        usToTicks(self->min_usecs),
-                                        usToTicks(self->max_usecs),
-                                        0.0, 180.0);
+            usToTicks(self->min_usecs),
+            usToTicks(self->max_usecs),
+            0.0, 180.0);
         return mp_obj_new_float(angle);
     }
     // Set
@@ -124,9 +122,9 @@
         angle = 180.0F;
     }
     servo_ticks[self->servo_id] = map_float_to_uint(angle,
-                                                    0.0F, 180.0F,
-                                                    usToTicks(self->min_usecs),
-                                                    usToTicks(self->max_usecs));
+        0.0F, 180.0F,
+        usToTicks(self->min_usecs),
+        usToTicks(self->max_usecs));
     return mp_const_none;
 }
 
@@ -207,7 +205,7 @@
     /* Find an unallocated servo id */
 
     self->servo_id = 0;
-    for (mask=1; mask < (1<<MAX_SERVOS); mask <<= 1) {
+    for (mask = 1; mask < (1 << MAX_SERVOS); mask <<= 1) {
         if (!(servo_allocated_mask & mask)) {
             servo_allocated_mask |= mask;
             servo_active_mask &= ~mask;
@@ -221,45 +219,47 @@
     return mp_const_none;
 }
 
-void pdb_isr(void)
-{
-	static int8_t channel = 0, channel_high = MAX_SERVOS;
-	static uint32_t tick_accum = 0;
-	uint32_t ticks;
-	int32_t wait_ticks;
+void pdb_isr(void) {
+    static int8_t channel = 0, channel_high = MAX_SERVOS;
+    static uint32_t tick_accum = 0;
+    uint32_t ticks;
+    int32_t wait_ticks;
 
-	// first, if any channel was left high from the previous
-	// run, now is the time to shut it off
-	if (servo_active_mask & (1 << channel_high)) {
-		digitalWrite(servo_pin[channel_high], LOW);
-		channel_high = MAX_SERVOS;
-	}
-	// search for the next channel to turn on
-	while (channel < MAX_SERVOS) {
-		if (servo_active_mask & (1 << channel)) {
-			digitalWrite(servo_pin[channel], HIGH);
-			channel_high = channel;
-			ticks = servo_ticks[channel];
-			tick_accum += ticks;
-			PDB0_IDLY += ticks;
-			PDB0_SC = PDB_CONFIG | PDB_SC_LDOK;
-			channel++;
-			return;
-		}
-		channel++;
-	}
-	// when all channels have output, wait for the
-	// minimum refresh interval
-	wait_ticks = usToTicks(REFRESH_INTERVAL) - tick_accum;
-	if (wait_ticks < usToTicks(100)) wait_ticks = usToTicks(100);
-	else if (wait_ticks > 60000) wait_ticks = 60000;
-	tick_accum += wait_ticks;
-	PDB0_IDLY += wait_ticks;
-	PDB0_SC = PDB_CONFIG | PDB_SC_LDOK;
-	// if this wait is enough to satisfy the refresh
-	// interval, next time begin again at channel zero
-	if (tick_accum >= usToTicks(REFRESH_INTERVAL)) {
-		tick_accum = 0;
-		channel = 0;
-	}
+    // first, if any channel was left high from the previous
+    // run, now is the time to shut it off
+    if (servo_active_mask & (1 << channel_high)) {
+        digitalWrite(servo_pin[channel_high], LOW);
+        channel_high = MAX_SERVOS;
+    }
+    // search for the next channel to turn on
+    while (channel < MAX_SERVOS) {
+        if (servo_active_mask & (1 << channel)) {
+            digitalWrite(servo_pin[channel], HIGH);
+            channel_high = channel;
+            ticks = servo_ticks[channel];
+            tick_accum += ticks;
+            PDB0_IDLY += ticks;
+            PDB0_SC = PDB_CONFIG | PDB_SC_LDOK;
+            channel++;
+            return;
+        }
+        channel++;
+    }
+    // when all channels have output, wait for the
+    // minimum refresh interval
+    wait_ticks = usToTicks(REFRESH_INTERVAL) - tick_accum;
+    if (wait_ticks < usToTicks(100)) {
+        wait_ticks = usToTicks(100);
+    } else if (wait_ticks > 60000) {
+        wait_ticks = 60000;
+    }
+    tick_accum += wait_ticks;
+    PDB0_IDLY += wait_ticks;
+    PDB0_SC = PDB_CONFIG | PDB_SC_LDOK;
+    // if this wait is enough to satisfy the refresh
+    // interval, next time begin again at channel zero
+    if (tick_accum >= usToTicks(REFRESH_INTERVAL)) {
+        tick_accum = 0;
+        channel = 0;
+    }
 }
diff --git a/ports/teensy/teensy_hal.c b/ports/teensy/teensy_hal.c
index e9cc677..342e7c6 100644
--- a/ports/teensy/teensy_hal.c
+++ b/ports/teensy/teensy_hal.c
@@ -9,17 +9,17 @@
 #include "Arduino.h"
 
 mp_uint_t mp_hal_ticks_ms(void) {
-  return millis();
+    return millis();
 }
 
 void mp_hal_delay_ms(mp_uint_t ms) {
-  delay(ms);
+    delay(ms);
 }
 
 void mp_hal_set_interrupt_char(int c) {
-  // The teensy 3.1 usb stack doesn't currently have the notion of generating
-  // an exception when a certain character is received. That just means that
-  // you can't press Control-C and get your python script to stop.
+    // The teensy 3.1 usb stack doesn't currently have the notion of generating
+    // an exception when a certain character is received. That just means that
+    // you can't press Control-C and get your python script to stop.
 }
 
 uintptr_t mp_hal_stdio_poll(uintptr_t poll_flags) {
diff --git a/ports/teensy/teensy_hal.h b/ports/teensy/teensy_hal.h
index f2e6682..c4cdcc1 100644
--- a/ports/teensy/teensy_hal.h
+++ b/ports/teensy/teensy_hal.h
@@ -3,7 +3,7 @@
 
 #ifdef  USE_FULL_ASSERT
   #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__))
-  void assert_failed(uint8_t* file, uint32_t line);
+void assert_failed(uint8_t *file, uint32_t line);
 #else
   #define assert_param(expr) ((void)0)
 #endif /* USE_FULL_ASSERT */
@@ -41,12 +41,12 @@
 } SPI_TypeDef;
 
 typedef struct {
-    volatile    uint32_t    PDOR;   // Output register
-    volatile    uint32_t    PSOR;   // Set output register
-    volatile    uint32_t    PCOR;   // Clear output register
-    volatile    uint32_t    PTOR;   // Toggle output register
-    volatile    uint32_t    PDIR;   // Data Input register
-    volatile    uint32_t    PDDR;   // Data Direction register
+    volatile uint32_t PDOR;         // Output register
+    volatile uint32_t PSOR;         // Set output register
+    volatile uint32_t PCOR;         // Clear output register
+    volatile uint32_t PTOR;         // Toggle output register
+    volatile uint32_t PDIR;         // Data Input register
+    volatile uint32_t PDDR;         // Data Direction register
 } GPIO_TypeDef;
 
 #define GPIO_OUTPUT_TYPE    ((uint32_t)0x00000010)  // Indicates OD
@@ -60,19 +60,19 @@
 #define GPIO_MODE_IT_RISING ((uint32_t)1)
 #define GPIO_MODE_IT_FALLING ((uint32_t)2)
 
-#define IS_GPIO_MODE(MODE) (((MODE) == GPIO_MODE_INPUT)              ||\
-                            ((MODE) == GPIO_MODE_OUTPUT_PP)          ||\
-                            ((MODE) == GPIO_MODE_OUTPUT_OD)          ||\
-                            ((MODE) == GPIO_MODE_AF_PP)              ||\
-                            ((MODE) == GPIO_MODE_AF_OD)              ||\
-                            ((MODE) == GPIO_MODE_ANALOG))
+#define IS_GPIO_MODE(MODE) (((MODE) == GPIO_MODE_INPUT) || \
+    ((MODE) == GPIO_MODE_OUTPUT_PP) || \
+    ((MODE) == GPIO_MODE_OUTPUT_OD) || \
+    ((MODE) == GPIO_MODE_AF_PP) || \
+    ((MODE) == GPIO_MODE_AF_OD) || \
+    ((MODE) == GPIO_MODE_ANALOG))
 
 #define GPIO_NOPULL         ((uint32_t)0)
 #define GPIO_PULLUP         ((uint32_t)1)
 #define GPIO_PULLDOWN       ((uint32_t)2)
 
 #define IS_GPIO_PULL(PULL) (((PULL) == GPIO_NOPULL) || ((PULL) == GPIO_PULLUP) || \
-                            ((PULL) == GPIO_PULLDOWN))
+    ((PULL) == GPIO_PULLDOWN))
 
 #define GPIO_SPEED_FREQ_LOW       ((uint32_t)0)
 #define GPIO_SPEED_FREQ_MEDIUM    ((uint32_t)1)
@@ -82,11 +82,11 @@
 #define IS_GPIO_AF(af)      ((af) >= 0 && (af) <= 7)
 
 typedef struct {
-    uint32_t    Pin;
-    uint32_t    Mode;
-    uint32_t    Pull;
-    uint32_t    Speed;
-    uint32_t    Alternate;
+    uint32_t Pin;
+    uint32_t Mode;
+    uint32_t Pull;
+    uint32_t Speed;
+    uint32_t Alternate;
 } GPIO_InitTypeDef;
 
 #define GPIO_PORT_TO_PORT_NUM(GPIOx) \
@@ -111,7 +111,7 @@
 #define GPIO_AF7_FTM1   7
 
 __attribute__(( always_inline )) static inline void __WFI(void) {
-  __asm volatile ("wfi");
+    __asm volatile ("wfi");
 }
 
 void mp_hal_set_interrupt_char(int c);
@@ -121,7 +121,7 @@
 void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *init);
 
 struct _pin_obj_t;
-#define mp_hal_pin_obj_t const struct _pin_obj_t*
+#define mp_hal_pin_obj_t const struct _pin_obj_t *
 #define mp_hal_pin_high(p) (((p)->gpio->PSOR) = (p)->pin_mask)
 #define mp_hal_pin_low(p)  (((p)->gpio->PCOR) = (p)->pin_mask)
 #define mp_hal_pin_read(p) (((p)->gpio->PDIR >> (p)->pin) & 1)
diff --git a/ports/teensy/timer.c b/ports/teensy/timer.c
index 88e960c..08dc13f 100644
--- a/ports/teensy/timer.c
+++ b/ports/teensy/timer.c
@@ -49,8 +49,8 @@
 } pyb_channel_mode;
 
 STATIC const struct {
-    qstr        name;
-    uint32_t    oc_mode;
+    qstr name;
+    uint32_t oc_mode;
 } channel_mode_info[] = {
     { MP_QSTR_PWM,                FTM_OCMODE_PWM1 },
     { MP_QSTR_PWM_INVERTED,       FTM_OCMODE_PWM2 },
@@ -195,8 +195,8 @@
         mp_printf(print, "Timer(%u, prescaler=%u, period=%u, mode=%s)",
             self->tim_id,
             1 << (self->ftm.Instance->SC & 7),
-            self->ftm.Instance->MOD & 0xffff,
-            self->ftm.Init.CounterMode == FTM_COUNTERMODE_UP ? "UP" : "CENTER");
+                self->ftm.Instance->MOD & 0xffff,
+                self->ftm.Init.CounterMode == FTM_COUNTERMODE_UP ? "UP" : "CENTER");
     }
 }
 
@@ -319,10 +319,20 @@
     tim->tim_id = mp_obj_get_int(args[0]);
 
     switch (tim->tim_id) {
-        case 0: tim->ftm.Instance = FTM0; tim->irqn = IRQ_FTM0; break;
-        case 1: tim->ftm.Instance = FTM1; tim->irqn = IRQ_FTM1; break;
-        case 2: tim->ftm.Instance = FTM2; tim->irqn = IRQ_FTM2; break;
-        default: mp_raise_msg_varg(&mp_type_ValueError, "Timer %d does not exist", tim->tim_id);
+        case 0:
+            tim->ftm.Instance = FTM0;
+            tim->irqn = IRQ_FTM0;
+            break;
+        case 1:
+            tim->ftm.Instance = FTM1;
+            tim->irqn = IRQ_FTM1;
+            break;
+        case 2:
+            tim->ftm.Instance = FTM2;
+            tim->irqn = IRQ_FTM2;
+            break;
+        default:
+            mp_raise_msg_varg(&mp_type_ValueError, "Timer %d does not exist", tim->tim_id);
     }
 
     if (n_args > 1 || n_kw > 0) {
@@ -551,9 +561,9 @@
         case CHANNEL_MODE_OC_INACTIVE:
         case CHANNEL_MODE_OC_TOGGLE: {
             FTM_OC_InitTypeDef oc_config;
-            oc_config.OCMode       = channel_mode_info[chan->mode].oc_mode;
-            oc_config.Pulse        = vals[4].u_int;
-            oc_config.OCPolarity   = vals[5].u_int;
+            oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
+            oc_config.Pulse = vals[4].u_int;
+            oc_config.OCPolarity = vals[5].u_int;
             if (oc_config.OCPolarity == 0xffffffff) {
                 oc_config.OCPolarity = FTM_OCPOLARITY_HIGH;
             }
@@ -573,7 +583,7 @@
         case CHANNEL_MODE_IC: {
             FTM_IC_InitTypeDef ic_config;
 
-            ic_config.ICPolarity  = vals[5].u_int;
+            ic_config.ICPolarity = vals[5].u_int;
             if (ic_config.ICPolarity == 0xffffffff) {
                 ic_config.ICPolarity = FTM_ICPOLARITY_RISING;
             }
@@ -716,9 +726,9 @@
     { MP_ROM_QSTR(MP_QSTR_prescaler), MP_ROM_PTR(&pyb_timer_prescaler_obj) },
     { MP_ROM_QSTR(MP_QSTR_period), MP_ROM_PTR(&pyb_timer_period_obj) },
     { MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&pyb_timer_callback_obj) },
-#if MICROPY_TIMER_REG
+    #if MICROPY_TIMER_REG
     { MP_ROM_QSTR(MP_QSTR_reg), MP_ROM_PTR(&pyb_timer_reg_obj) },
-#endif
+    #endif
     { MP_ROM_QSTR(MP_QSTR_UP),              MP_ROM_INT(FTM_COUNTERMODE_UP) },
     { MP_ROM_QSTR(MP_QSTR_CENTER),          MP_ROM_INT(FTM_COUNTERMODE_CENTER) },
     { MP_ROM_QSTR(MP_QSTR_PWM),             MP_ROM_INT(CHANNEL_MODE_PWM_NORMAL) },
@@ -754,9 +764,9 @@
     pyb_timer_channel_obj_t *self = self_in;
 
     mp_printf(print, "TimerChannel(timer=%u, channel=%u, mode=%s)",
-          self->timer->tim_id,
-          self->channel,
-          qstr_str(channel_mode_info[self->mode].name));
+        self->timer->tim_id,
+        self->channel,
+        qstr_str(channel_mode_info[self->mode].name));
 }
 
 /// \method capture([value])
@@ -773,7 +783,7 @@
 /// Get or set the pulse width value associated with a channel.
 /// capture, compare, and pulse_width are all aliases for the same function.
 /// pulse_width is the logical name to use when the channel is in PWM mode.
-/// 
+///
 /// In edge aligned mode, a pulse_width of `period + 1` corresponds to a duty cycle of 100%
 /// In center aligned mode, a pulse width of `period` corresponds to a duty cycle of 100%
 STATIC mp_obj_t pyb_timer_channel_capture_compare(size_t n_args, const mp_obj_t *args) {
@@ -860,8 +870,8 @@
 mp_obj_t pyb_timer_channel_reg(uint n_args, const mp_obj_t *args) {
     pyb_timer_channel_obj_t *self = args[0];
     return reg_cmd(&self->timer->ftm.Instance->channel[self->channel],
-                   timer_channel_reg, MP_ARRAY_SIZE(timer_channel_reg),
-                   n_args - 1, args + 1);
+        timer_channel_reg, MP_ARRAY_SIZE(timer_channel_reg),
+        n_args - 1, args + 1);
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_reg_obj, 1, 3, pyb_timer_channel_reg);
 #endif
@@ -873,9 +883,9 @@
     { MP_ROM_QSTR(MP_QSTR_pulse_width_percent), MP_ROM_PTR(&pyb_timer_channel_pulse_width_percent_obj) },
     { MP_ROM_QSTR(MP_QSTR_capture), MP_ROM_PTR(&pyb_timer_channel_capture_compare_obj) },
     { MP_ROM_QSTR(MP_QSTR_compare), MP_ROM_PTR(&pyb_timer_channel_capture_compare_obj) },
-#if MICROPY_TIMER_REG
+    #if MICROPY_TIMER_REG
     { MP_ROM_QSTR(MP_QSTR_reg), MP_ROM_PTR(&pyb_timer_channel_reg_obj) },
-#endif
+    #endif
 };
 STATIC MP_DEFINE_CONST_DICT(pyb_timer_channel_locals_dict, pyb_timer_channel_locals_dict_table);
 
@@ -906,10 +916,10 @@
         self->callback = mp_const_none;
         if (channel == 0xffffffff) {
             printf("Uncaught exception in Timer(" UINT_FMT
-                   ") interrupt handler\n", self->tim_id);
+                ") interrupt handler\n", self->tim_id);
         } else {
             printf("Uncaught exception in Timer(" UINT_FMT ") channel "
-                   UINT_FMT " interrupt handler\n", self->tim_id, channel);
+                UINT_FMT " interrupt handler\n", self->tim_id, channel);
         }
         mp_obj_print_exception(&mp_plat_print, (mp_obj_t)nlr.ret_val);
     }
@@ -956,7 +966,7 @@
             } else {
                 __HAL_FTM_DISABLE_CH_IT(&self->ftm, chan->channel);
                 printf("No callback for Timer %d channel %u (now disabled)\n",
-                       self->tim_id, chan->channel);
+                    self->tim_id, chan->channel);
             }
         }
         chan = chan->next;
@@ -971,7 +981,7 @@
                     __HAL_FTM_CLEAR_CH_FLAG(&self->ftm, channel);
                     __HAL_FTM_DISABLE_CH_IT(&self->ftm, channel);
                     printf("Unhandled interrupt Timer %d channel %u (now disabled)\n",
-                           tim_id, channel);
+                        tim_id, channel);
                 }
             }
         }
diff --git a/ports/teensy/uart.c b/ports/teensy/uart.c
index 95ed073..1d27359 100644
--- a/ports/teensy/uart.c
+++ b/ports/teensy/uart.c
@@ -62,12 +62,12 @@
 
 // assumes Init parameters have been set up correctly
 bool uart_init2(pyb_uart_obj_t *uart_obj) {
-#if 0
+    #if 0
     USART_TypeDef *UARTx = NULL;
 
     uint32_t GPIO_Pin = 0;
-    uint8_t  GPIO_AF_UARTx = 0;
-    GPIO_TypeDef* GPIO_Port = NULL;
+    uint8_t GPIO_AF_UARTx = 0;
+    GPIO_TypeDef *GPIO_Port = NULL;
 
     switch (uart_obj->uart_id) {
         // USART1 is on PA9/PA10 (CK on PA8), PB6/PB7
@@ -75,13 +75,13 @@
             UARTx = USART1;
             GPIO_AF_UARTx = GPIO_AF7_USART1;
 
-#if defined (PYBV4) || defined(PYBV10)
+            #if defined (PYBV4) || defined(PYBV10)
             GPIO_Port = GPIOB;
             GPIO_Pin = GPIO_PIN_6 | GPIO_PIN_7;
-#else
+            #else
             GPIO_Port = GPIOA;
             GPIO_Pin = GPIO_PIN_9 | GPIO_PIN_10;
-#endif
+            #endif
 
             __USART1_CLK_ENABLE();
             break;
@@ -102,13 +102,13 @@
             UARTx = USART3;
             GPIO_AF_UARTx = GPIO_AF7_USART3;
 
-#if defined(PYBV3) || defined(PYBV4) | defined(PYBV10)
+            #if defined(PYBV3) || defined(PYBV4) | defined(PYBV10)
             GPIO_Port = GPIOB;
             GPIO_Pin = GPIO_PIN_10 | GPIO_PIN_11;
-#else
+            #else
             GPIO_Port = GPIOD;
             GPIO_Pin = GPIO_PIN_8 | GPIO_PIN_9;
-#endif
+            #endif
             __USART3_CLK_ENABLE();
             break;
 
@@ -152,12 +152,12 @@
     HAL_UART_Init(&uart_obj->uart);
 
     uart_obj->is_enabled = true;
-#endif
+    #endif
     return true;
 }
 
 bool uart_init(pyb_uart_obj_t *uart_obj, uint32_t baudrate) {
-#if 0
+    #if 0
     UART_HandleTypeDef *uh = &uart_obj->uart;
     memset(uh, 0, sizeof(*uh));
     uh->Init.BaudRate = baudrate;
@@ -167,47 +167,47 @@
     uh->Init.Mode = UART_MODE_TX_RX;
     uh->Init.HwFlowCtl = UART_HWCONTROL_NONE;
     uh->Init.OverSampling = UART_OVERSAMPLING_16;
-#endif
+    #endif
     return uart_init2(uart_obj);
 }
 
 mp_uint_t uart_rx_any(pyb_uart_obj_t *uart_obj) {
-#if 0
+    #if 0
     return __HAL_UART_GET_FLAG(&uart_obj->uart, UART_FLAG_RXNE);
-#else
+    #else
     return 0;
-#endif
+    #endif
 }
 
 int uart_rx_char(pyb_uart_obj_t *uart_obj) {
     uint8_t ch;
-#if 0
+    #if 0
     if (HAL_UART_Receive(&uart_obj->uart, &ch, 1, 0) != HAL_OK) {
         ch = 0;
     }
-#else
+    #else
     ch = 'A';
-#endif
+    #endif
     return ch;
 }
 
 void uart_tx_char(pyb_uart_obj_t *uart_obj, int c) {
-#if 0
+    #if 0
     uint8_t ch = c;
     HAL_UART_Transmit(&uart_obj->uart, &ch, 1, 100000);
-#endif
+    #endif
 }
 
 void uart_tx_str(pyb_uart_obj_t *uart_obj, const char *str) {
-#if 0
-    HAL_UART_Transmit(&uart_obj->uart, (uint8_t*)str, strlen(str), 100000);
-#endif
+    #if 0
+    HAL_UART_Transmit(&uart_obj->uart, (uint8_t *)str, strlen(str), 100000);
+    #endif
 }
 
 void uart_tx_strn(pyb_uart_obj_t *uart_obj, const char *str, uint len) {
-#if 0
-    HAL_UART_Transmit(&uart_obj->uart, (uint8_t*)str, len, 100000);
-#endif
+    #if 0
+    HAL_UART_Transmit(&uart_obj->uart, (uint8_t *)str, len, 100000);
+    #endif
 }
 
 void uart_tx_strn_cooked(pyb_uart_obj_t *uart_obj, const char *str, uint len) {
@@ -227,7 +227,7 @@
     if (!self->is_enabled) {
         mp_printf(print, "UART(%lu)", self->uart_id);
     } else {
-#if 0
+        #if 0
         mp_printf(print, "UART(%lu, baudrate=%u, bits=%u, stop=%u",
             self->uart_id, self->uart.Init.BaudRate,
             self->uart.Init.WordLength == UART_WORDLENGTH_8B ? 8 : 9,
@@ -237,7 +237,7 @@
         } else {
             mp_printf(print, ", parity=%u)", self->uart.Init.Parity == UART_PARITY_EVEN ? 0 : 1);
         }
-#endif
+        #endif
     }
 }
 
@@ -261,15 +261,19 @@
     // parse args
     mp_arg_val_t vals[PYB_UART_INIT_NUM_ARGS];
     mp_arg_parse_all(n_args, args, kw_args, PYB_UART_INIT_NUM_ARGS, pyb_uart_init_args, vals);
-#if 0
+    #if 0
     // set the UART configuration values
     memset(&self->uart, 0, sizeof(self->uart));
     UART_InitTypeDef *init = &self->uart.Init;
     init->BaudRate = vals[0].u_int;
     init->WordLength = vals[1].u_int == 8 ? UART_WORDLENGTH_8B : UART_WORDLENGTH_9B;
     switch (vals[2].u_int) {
-        case 1: init->StopBits = UART_STOPBITS_1; break;
-        default: init->StopBits = UART_STOPBITS_2; break;
+        case 1:
+            init->StopBits = UART_STOPBITS_1;
+            break;
+        default:
+            init->StopBits = UART_STOPBITS_2;
+            break;
     }
     if (vals[3].u_obj == mp_const_none) {
         init->Parity = UART_PARITY_NONE;
@@ -285,7 +289,7 @@
     if (!uart_init2(self)) {
         mp_raise_msg_varg(&mp_type_ValueError, "UART port %d does not exist", self->uart_id);
     }
-#endif
+    #endif
 
     return mp_const_none;
 }
@@ -315,11 +319,11 @@
 
     // work out port
     o->uart_id = 0;
-#if 0
+    #if 0
     if (mp_obj_is_str(args[0])) {
         const char *port = mp_obj_str_get_str(args[0]);
         if (0) {
-#if defined(PYBV10)
+        #if defined(PYBV10)
         } else if (strcmp(port, "XA") == 0) {
             o->uart_id = PYB_UART_XA;
         } else if (strcmp(port, "XB") == 0) {
@@ -328,14 +332,14 @@
             o->uart_id = PYB_UART_YA;
         } else if (strcmp(port, "YB") == 0) {
             o->uart_id = PYB_UART_YB;
-#endif
+        #endif
         } else {
             mp_raise_msg_varg(&mp_type_ValueError, "UART port %s does not exist", port);
         }
     } else {
         o->uart_id = mp_obj_get_int(args[0]);
     }
-#endif
+    #endif
 
     if (n_args > 1 || n_kw > 0) {
         // start the peripheral
@@ -395,7 +399,7 @@
     mp_arg_val_t vals[PYB_UART_SEND_NUM_ARGS];
     mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_UART_SEND_NUM_ARGS, pyb_uart_send_args, vals);
 
-#if 0
+    #if 0
     // get the buffer to send from
     mp_buffer_info_t bufinfo;
     uint8_t data[1];
@@ -408,9 +412,9 @@
         // TODO really need a HardwareError object, or something
         mp_raise_msg_varg(&mp_type_Exception, "HAL_UART_Transmit failed with code %d", status);
     }
-#else
+    #else
     (void)self;
-#endif
+    #endif
 
     return mp_const_none;
 }
@@ -439,7 +443,7 @@
 
     pyb_uart_obj_t *self = args[0];
 
-#if 0
+    #if 0
     // parse args
     mp_arg_val_t vals[PYB_UART_RECV_NUM_ARGS];
     mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_UART_RECV_NUM_ARGS, pyb_uart_recv_args, vals);
@@ -462,10 +466,10 @@
     } else {
         return mp_obj_str_builder_end(o_ret);
     }
-#else
+    #else
     (void)self;
     return mp_const_none;
-#endif
+    #endif
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_recv_obj, 1, pyb_uart_recv);
 
diff --git a/ports/teensy/usb.c b/ports/teensy/usb.c
index ed96826..a906f912 100644
--- a/ports/teensy/usb.c
+++ b/ports/teensy/usb.c
@@ -7,46 +7,40 @@
 #include "usb.h"
 #include "usb_serial.h"
 
-bool usb_vcp_is_connected(void)
-{
-  return usb_configuration && (usb_cdc_line_rtsdtr & (USB_SERIAL_DTR | USB_SERIAL_RTS));
+bool usb_vcp_is_connected(void) {
+    return usb_configuration && (usb_cdc_line_rtsdtr & (USB_SERIAL_DTR | USB_SERIAL_RTS));
 }
 
-bool usb_vcp_is_enabled(void)
-{
-  return true;
+bool usb_vcp_is_enabled(void) {
+    return true;
 }
 
 int usb_vcp_rx_num(void) {
-  return usb_serial_available();
+    return usb_serial_available();
 }
 
-int usb_vcp_recv_byte(uint8_t *ptr)
-{
-  int ch = usb_serial_getchar();
-  if (ch < 0) {
-    return 0;
-  }
-  *ptr = ch;
-  return 1;
-}
-
-void usb_vcp_send_str(const char* str)
-{
-  usb_vcp_send_strn(str, strlen(str));
-}
-
-void usb_vcp_send_strn(const char* str, int len)
-{
-  usb_serial_write(str, len);
-}
-
-void usb_vcp_send_strn_cooked(const char *str, int len)
-{
-  for (const char *top = str + len; str < top; str++) {
-    if (*str == '\n') {
-      usb_serial_putchar('\r');
+int usb_vcp_recv_byte(uint8_t *ptr) {
+    int ch = usb_serial_getchar();
+    if (ch < 0) {
+        return 0;
     }
-    usb_serial_putchar(*str);
-  }
+    *ptr = ch;
+    return 1;
+}
+
+void usb_vcp_send_str(const char *str) {
+    usb_vcp_send_strn(str, strlen(str));
+}
+
+void usb_vcp_send_strn(const char *str, int len) {
+    usb_serial_write(str, len);
+}
+
+void usb_vcp_send_strn_cooked(const char *str, int len) {
+    for (const char *top = str + len; str < top; str++) {
+        if (*str == '\n') {
+            usb_serial_putchar('\r');
+        }
+        usb_serial_putchar(*str);
+    }
 }
diff --git a/ports/teensy/usb.h b/ports/teensy/usb.h
index 50fb3ff..7ca0eac 100644
--- a/ports/teensy/usb.h
+++ b/ports/teensy/usb.h
@@ -5,8 +5,8 @@
 bool usb_vcp_is_enabled(void);
 int usb_vcp_rx_num(void);
 int usb_vcp_recv_byte(uint8_t *ptr);
-void usb_vcp_send_str(const char* str);
-void usb_vcp_send_strn(const char* str, int len);
+void usb_vcp_send_str(const char *str);
+void usb_vcp_send_strn(const char *str, int len);
 void usb_vcp_send_strn_cooked(const char *str, int len);
 
 #endif // MICROPY_INCLUDED_TEENSY_USB_H
diff --git a/ports/unix/alloc.c b/ports/unix/alloc.c
index ca12d02..7fe7b4d 100644
--- a/ports/unix/alloc.c
+++ b/ports/unix/alloc.c
@@ -69,7 +69,7 @@
     munmap(ptr, size);
 
     // unlink the mmap'd region from the list
-    for (mmap_region_t **rg = (mmap_region_t**)&MP_STATE_VM(mmap_region_head); *rg != NULL; *rg = (*rg)->next) {
+    for (mmap_region_t **rg = (mmap_region_t **)&MP_STATE_VM(mmap_region_head); *rg != NULL; *rg = (*rg)->next) {
         if ((*rg)->ptr == ptr) {
             mmap_region_t *next = (*rg)->next;
             m_del_obj(mmap_region_t, *rg);
diff --git a/ports/unix/coverage.c b/ports/unix/coverage.c
index 8978931..59fcf55 100644
--- a/ports/unix/coverage.c
+++ b/ports/unix/coverage.c
@@ -108,7 +108,7 @@
 STATIC const mp_obj_type_t mp_type_stest_fileio = {
     { &mp_type_type },
     .protocol = &fileio_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict,
 };
 
 // stream read returns non-blocking error
@@ -135,12 +135,12 @@
 STATIC const mp_obj_type_t mp_type_stest_textio2 = {
     { &mp_type_type },
     .protocol = &textio_stream_p2,
-    .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict2,
+    .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict2,
 };
 
 // str/bytes objects without a valid hash
-STATIC const mp_obj_str_t str_no_hash_obj = {{&mp_type_str}, 0, 10, (const byte*)"0123456789"};
-STATIC const mp_obj_str_t bytes_no_hash_obj = {{&mp_type_bytes}, 0, 10, (const byte*)"0123456789"};
+STATIC const mp_obj_str_t str_no_hash_obj = {{&mp_type_str}, 0, 10, (const byte *)"0123456789"};
+STATIC const mp_obj_str_t bytes_no_hash_obj = {{&mp_type_bytes}, 0, 10, (const byte *)"0123456789"};
 
 STATIC int pairheap_lt(mp_pairheap_t *a, mp_pairheap_t *b) {
     return (uintptr_t)a < (uintptr_t)b;
@@ -160,12 +160,14 @@
         if (mp_pairheap_is_empty(pairheap_lt, heap)) {
             mp_printf(&mp_plat_print, " -");
         } else {
-            mp_printf(&mp_plat_print, " %d", mp_pairheap_peek(pairheap_lt, heap) - &node[0]);;
+            mp_printf(&mp_plat_print, " %d", mp_pairheap_peek(pairheap_lt, heap) - &node[0]);
+            ;
         }
     }
     printf("\npop all:");
     while (!mp_pairheap_is_empty(pairheap_lt, heap)) {
-        mp_printf(&mp_plat_print, " %d", mp_pairheap_peek(pairheap_lt, heap) - &node[0]);;
+        mp_printf(&mp_plat_print, " %d", mp_pairheap_peek(pairheap_lt, heap) - &node[0]);
+        ;
         heap = mp_pairheap_pop(pairheap_lt, heap);
     }
     printf("\n");
@@ -438,10 +440,10 @@
 
         // call mp_execute_bytecode with invalide bytecode (should raise NotImplementedError)
         mp_obj_fun_bc_t fun_bc;
-        fun_bc.bytecode = (const byte*)"\x01"; // just needed for n_state
+        fun_bc.bytecode = (const byte *)"\x01"; // just needed for n_state
         mp_code_state_t *code_state = m_new_obj_var(mp_code_state_t, mp_obj_t, 1);
         code_state->fun_bc = &fun_bc;
-        code_state->ip = (const byte*)"\x00"; // just needed for an invalid opcode
+        code_state->ip = (const byte *)"\x00"; // just needed for an invalid opcode
         code_state->sp = &code_state->state[0];
         code_state->exc_sp_idx = 0;
         code_state->old_globals = NULL;
diff --git a/ports/unix/file.c b/ports/unix/file.c
index 8a16528..0fe4f98 100644
--- a/ports/unix/file.c
+++ b/ports/unix/file.c
@@ -110,7 +110,7 @@
     check_fd_is_open(o);
     switch (request) {
         case MP_STREAM_SEEK: {
-            struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)arg;
+            struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)arg;
             MP_THREAD_GIL_EXIT();
             off_t off = lseek(o->fd, s->offset, s->whence);
             MP_THREAD_GIL_ENTER();
@@ -190,7 +190,7 @@
             case '+':
                 mode_rw = O_RDWR;
                 break;
-            #if MICROPY_PY_IO_FILEIO
+                #if MICROPY_PY_IO_FILEIO
             // If we don't have io.FileIO, then files are in text mode implicitly
             case 'b':
                 type = &mp_type_fileio;
@@ -198,7 +198,7 @@
             case 't':
                 type = &mp_type_textio;
                 break;
-            #endif
+                #endif
         }
     }
 
@@ -260,7 +260,7 @@
     .getiter = mp_identity_getiter,
     .iternext = mp_stream_unbuffered_iter,
     .protocol = &fileio_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict,
 };
 #endif
 
@@ -279,7 +279,7 @@
     .getiter = mp_identity_getiter,
     .iternext = mp_stream_unbuffered_iter,
     .protocol = &textio_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict,
 };
 
 // Factory function for I/O stream classes
@@ -291,7 +291,7 @@
 }
 MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
 
-const mp_obj_fdfile_t mp_sys_stdin_obj  = { .base = {&mp_type_textio}, .fd = STDIN_FILENO };
+const mp_obj_fdfile_t mp_sys_stdin_obj = { .base = {&mp_type_textio}, .fd = STDIN_FILENO };
 const mp_obj_fdfile_t mp_sys_stdout_obj = { .base = {&mp_type_textio}, .fd = STDOUT_FILENO };
 const mp_obj_fdfile_t mp_sys_stderr_obj = { .base = {&mp_type_textio}, .fd = STDERR_FILENO };
 
diff --git a/ports/unix/gccollect.c b/ports/unix/gccollect.c
index ddc2d92..7a92f5f 100644
--- a/ports/unix/gccollect.c
+++ b/ports/unix/gccollect.c
@@ -49,20 +49,20 @@
     register long r13 asm ("r13");
     register long r14 asm ("r14");
     register long r15 asm ("r15");
-#ifdef __clang__
+    #ifdef __clang__
     // TODO:
     // This is dirty workaround for Clang. It tries to get around
     // uncompliant (wrt to GCC) behavior of handling register variables.
     // Application of this patch here is random, and done only to unbreak
     // MacOS build. Better, cross-arch ways to deal with Clang issues should
     // be found.
-    asm("" : "=r"(rbx));
-    asm("" : "=r"(rbp));
-    asm("" : "=r"(r12));
-    asm("" : "=r"(r13));
-    asm("" : "=r"(r14));
-    asm("" : "=r"(r15));
-#endif
+    asm ("" : "=r" (rbx));
+    asm ("" : "=r" (rbp));
+    asm ("" : "=r" (r12));
+    asm ("" : "=r" (r13));
+    asm ("" : "=r" (r14));
+    asm ("" : "=r" (r15));
+    #endif
     arr[0] = rbx;
     arr[1] = rbp;
     arr[2] = r12;
@@ -80,18 +80,18 @@
     register long esi asm ("esi");
     register long edi asm ("edi");
     register long ebp asm ("ebp");
-#ifdef __clang__
+    #ifdef __clang__
     // TODO:
     // This is dirty workaround for Clang. It tries to get around
     // uncompliant (wrt to GCC) behavior of handling register variables.
     // Application of this patch here is random, and done only to unbreak
     // MacOS build. Better, cross-arch ways to deal with Clang issues should
     // be found.
-    asm("" : "=r"(ebx));
-    asm("" : "=r"(esi));
-    asm("" : "=r"(edi));
-    asm("" : "=r"(ebp));
-#endif
+    asm ("" : "=r" (ebx));
+    asm ("" : "=r" (esi));
+    asm ("" : "=r" (edi));
+    asm ("" : "=r" (ebp));
+    #endif
     arr[0] = ebx;
     arr[1] = esi;
     arr[2] = edi;
@@ -160,7 +160,7 @@
     regs_t regs;
     gc_helper_get_regs(regs);
     // GC stack (and regs because we captured them)
-    void **regs_ptr = (void**)(void*)&regs;
+    void **regs_ptr = (void **)(void *)&regs;
     gc_collect_root(regs_ptr, ((uintptr_t)MP_STATE_THREAD(stack_top) - (uintptr_t)&regs) / sizeof(uintptr_t));
 }
 
diff --git a/ports/unix/input.c b/ports/unix/input.c
index 7d60b46..a33c020 100644
--- a/ports/unix/input.c
+++ b/ports/unix/input.c
@@ -59,7 +59,7 @@
 #endif
 
 void prompt_read_history(void) {
-#if MICROPY_USE_READLINE_HISTORY
+    #if MICROPY_USE_READLINE_HISTORY
     #if MICROPY_USE_READLINE == 1
     readline_init0(); // will clear history pointers
     char *home = getenv("HOME");
@@ -91,11 +91,11 @@
         vstr_clear(&vstr);
     }
     #endif
-#endif
+    #endif
 }
 
 void prompt_write_history(void) {
-#if MICROPY_USE_READLINE_HISTORY
+    #if MICROPY_USE_READLINE_HISTORY
     #if MICROPY_USE_READLINE == 1
     char *home = getenv("HOME");
     if (home != NULL) {
@@ -117,5 +117,5 @@
         }
     }
     #endif
-#endif
+    #endif
 }
diff --git a/ports/unix/main.c b/ports/unix/main.c
index 3f464d5..cab3f38 100644
--- a/ports/unix/main.c
+++ b/ports/unix/main.c
@@ -59,7 +59,7 @@
 #if MICROPY_ENABLE_GC
 // Heap size of GC heap (if enabled)
 // Make it larger on a 64 bit machine, because pointers are larger.
-long heap_size = 1024*1024 * (sizeof(mp_uint_t) / 4);
+long heap_size = 1024 * 1024 * (sizeof(mp_uint_t) / 4);
 #endif
 
 STATIC void stderr_print_strn(void *env, const char *str, size_t len) {
@@ -116,7 +116,7 @@
             const vstr_t *vstr = source;
             lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, vstr->buf, vstr->len, false);
         } else if (source_kind == LEX_SRC_FILENAME) {
-            lex = mp_lexer_new_from_file((const char*)source);
+            lex = mp_lexer_new_from_file((const char *)source);
         } else { // LEX_SRC_STDIN
             lex = mp_lexer_new_from_fd(MP_QSTR__lt_stdin_gt_, 0, false);
         }
@@ -301,33 +301,33 @@
 
 STATIC void print_help(char **argv) {
     printf(
-"usage: %s [<opts>] [-X <implopt>] [-c <command> | -m <module> | <filename>]\n"
-"Options:\n"
-"-h : print this help message\n"
-"-i : enable inspection via REPL after running command/module/file\n"
-#if MICROPY_DEBUG_PRINTERS
-"-v : verbose (trace various operations); can be multiple\n"
-#endif
-"-O[N] : apply bytecode optimizations of level N\n"
-"\n"
-"Implementation specific options (-X):\n", argv[0]
-);
+        "usage: %s [<opts>] [-X <implopt>] [-c <command> | -m <module> | <filename>]\n"
+        "Options:\n"
+        "-h : print this help message\n"
+        "-i : enable inspection via REPL after running command/module/file\n"
+        #if MICROPY_DEBUG_PRINTERS
+        "-v : verbose (trace various operations); can be multiple\n"
+        #endif
+        "-O[N] : apply bytecode optimizations of level N\n"
+        "\n"
+        "Implementation specific options (-X):\n", argv[0]
+        );
     int impl_opts_cnt = 0;
     printf(
-"  compile-only                 -- parse and compile only\n"
-#if MICROPY_EMIT_NATIVE
-"  emit={bytecode,native,viper} -- set the default code emitter\n"
-#else
-"  emit=bytecode                -- set the default code emitter\n"
-#endif
-);
+        "  compile-only                 -- parse and compile only\n"
+        #if MICROPY_EMIT_NATIVE
+        "  emit={bytecode,native,viper} -- set the default code emitter\n"
+        #else
+        "  emit=bytecode                -- set the default code emitter\n"
+        #endif
+        );
     impl_opts_cnt++;
-#if MICROPY_ENABLE_GC
+    #if MICROPY_ENABLE_GC
     printf(
-"  heapsize=<n>[w][K|M] -- set the heap size for the GC (default %ld)\n"
-, heap_size);
+        "  heapsize=<n>[w][K|M] -- set the heap size for the GC (default %ld)\n"
+        , heap_size);
     impl_opts_cnt++;
-#endif
+    #endif
 
     if (impl_opts_cnt == 0) {
         printf("  (none)\n");
@@ -362,7 +362,7 @@
                 } else if (strcmp(argv[a + 1], "emit=viper") == 0) {
                     emit_opt = MP_EMIT_OPT_VIPER;
                 #endif
-#if MICROPY_ENABLE_GC
+                #if MICROPY_ENABLE_GC
                 } else if (strncmp(argv[a + 1], "heapsize=", sizeof("heapsize=") - 1) == 0) {
                     char *end;
                     heap_size = strtol(argv[a + 1] + sizeof("heapsize=") - 1, &end, 0);
@@ -395,9 +395,9 @@
                     if (heap_size < 700) {
                         goto invalid_arg;
                     }
-#endif
+                #endif
                 } else {
-invalid_arg:
+                invalid_arg:
                     exit(invalid_args());
                 }
                 a++;
@@ -452,10 +452,10 @@
 
     pre_process_options(argc, argv);
 
-#if MICROPY_ENABLE_GC
+    #if MICROPY_ENABLE_GC
     char *heap = malloc(heap_size);
     gc_init(heap, heap + heap_size);
-#endif
+    #endif
 
     #if MICROPY_ENABLE_PYSTACK
     static mp_obj_t pystack[1024];
@@ -478,7 +478,7 @@
             mp_type_vfs_posix.make_new(&mp_type_vfs_posix, 0, 0, NULL),
             MP_OBJ_NEW_QSTR(MP_QSTR__slash_),
         };
-        mp_vfs_mount(2, args, (mp_map_t*)&mp_const_empty_map);
+        mp_vfs_mount(2, args, (mp_map_t *)&mp_const_empty_map);
         MP_STATE_VM(vfs_cur) = MP_STATE_VM(vfs_mount_table);
     }
     #endif
@@ -507,25 +507,25 @@
     mp_obj_list_get(mp_sys_path, &path_num, &path_items);
     path_items[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
     {
-    char *p = path;
-    for (mp_uint_t i = 1; i < path_num; i++) {
-        char *p1 = strchr(p, PATHLIST_SEP_CHAR);
-        if (p1 == NULL) {
-            p1 = p + strlen(p);
+        char *p = path;
+        for (mp_uint_t i = 1; i < path_num; i++) {
+            char *p1 = strchr(p, PATHLIST_SEP_CHAR);
+            if (p1 == NULL) {
+                p1 = p + strlen(p);
+            }
+            if (p[0] == '~' && p[1] == '/' && home != NULL) {
+                // Expand standalone ~ to $HOME
+                int home_l = strlen(home);
+                vstr_t vstr;
+                vstr_init(&vstr, home_l + (p1 - p - 1) + 1);
+                vstr_add_strn(&vstr, home, home_l);
+                vstr_add_strn(&vstr, p + 1, p1 - p - 1);
+                path_items[i] = mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
+            } else {
+                path_items[i] = mp_obj_new_str_via_qstr(p, p1 - p);
+            }
+            p = p1 + 1;
         }
-        if (p[0] == '~' && p[1] == '/' && home != NULL) {
-            // Expand standalone ~ to $HOME
-            int home_l = strlen(home);
-            vstr_t vstr;
-            vstr_init(&vstr, home_l + (p1 - p - 1) + 1);
-            vstr_add_strn(&vstr, home, home_l);
-            vstr_add_strn(&vstr, p + 1, p1 - p - 1);
-            path_items[i] = mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
-        } else {
-            path_items[i] = mp_obj_new_str_via_qstr(p, p1 - p);
-        }
-        p = p1 + 1;
-    }
     }
 
     mp_obj_list_init(MP_OBJ_TO_PTR(mp_sys_argv), 0);
@@ -627,7 +627,8 @@
                     MP_STATE_VM(mp_optimise_value) = argv[a][2] & 0xf;
                 } else {
                     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 {
                 return invalid_args();
@@ -694,11 +695,11 @@
 
     mp_deinit();
 
-#if MICROPY_ENABLE_GC && !defined(NDEBUG)
+    #if MICROPY_ENABLE_GC && !defined(NDEBUG)
     // We don't really need to free memory since we are about to exit the
     // process, but doing so helps to find memory leaks.
     free(heap);
-#endif
+    #endif
 
     //printf("total bytes = %d\n", m_get_total_bytes_allocated());
     return ret & 0xff;
diff --git a/ports/unix/modffi.c b/ports/unix/modffi.c
index 75d70e2..1cc10bd 100644
--- a/ports/unix/modffi.c
+++ b/ports/unix/modffi.c
@@ -97,35 +97,48 @@
 STATIC const mp_obj_type_t fficallback_type;
 STATIC const mp_obj_type_t ffivar_type;
 
-STATIC ffi_type *char2ffi_type(char c)
-{
+STATIC ffi_type *char2ffi_type(char c) {
     switch (c) {
-        case 'b': return &ffi_type_schar;
-        case 'B': return &ffi_type_uchar;
-        case 'h': return &ffi_type_sshort;
-        case 'H': return &ffi_type_ushort;
-        case 'i': return &ffi_type_sint;
-        case 'I': return &ffi_type_uint;
-        case 'l': return &ffi_type_slong;
-        case 'L': return &ffi_type_ulong;
-        case 'q': return &ffi_type_sint64;
-        case 'Q': return &ffi_type_uint64;
+        case 'b':
+            return &ffi_type_schar;
+        case 'B':
+            return &ffi_type_uchar;
+        case 'h':
+            return &ffi_type_sshort;
+        case 'H':
+            return &ffi_type_ushort;
+        case 'i':
+            return &ffi_type_sint;
+        case 'I':
+            return &ffi_type_uint;
+        case 'l':
+            return &ffi_type_slong;
+        case 'L':
+            return &ffi_type_ulong;
+        case 'q':
+            return &ffi_type_sint64;
+        case 'Q':
+            return &ffi_type_uint64;
         #if MICROPY_PY_BUILTINS_FLOAT
-        case 'f': return &ffi_type_float;
-        case 'd': return &ffi_type_double;
+        case 'f':
+            return &ffi_type_float;
+        case 'd':
+            return &ffi_type_double;
         #endif
         case 'O': // mp_obj_t
         case 'C': // (*)()
         case 'P': // const void*
         case 'p': // void*
-        case 's': return &ffi_type_pointer;
-        case 'v': return &ffi_type_void;
-        default: return NULL;
+        case 's':
+            return &ffi_type_pointer;
+        case 'v':
+            return &ffi_type_void;
+        default:
+            return NULL;
     }
 }
 
-STATIC ffi_type *get_ffi_type(mp_obj_t o_in)
-{
+STATIC ffi_type *get_ffi_type(mp_obj_t o_in) {
     if (mp_obj_is_str(o_in)) {
         const char *s = mp_obj_str_get_str(o_in);
         ffi_type *t = char2ffi_type(*s);
@@ -138,8 +151,7 @@
     mp_raise_TypeError("Unknown type");
 }
 
-STATIC mp_obj_t return_ffi_value(ffi_arg val, char type)
-{
+STATIC mp_obj_t return_ffi_value(ffi_arg val, char type) {
     switch (type) {
         case 's': {
             const char *s = (const char *)(intptr_t)val;
@@ -152,11 +164,13 @@
             return mp_const_none;
         #if MICROPY_PY_BUILTINS_FLOAT
         case 'f': {
-            union { ffi_arg ffi; float flt; } val_union = { .ffi = val };
+            union { ffi_arg ffi;
+                    float flt;
+            } val_union = { .ffi = val };
             return mp_obj_new_float(val_union.flt);
         }
         case 'd': {
-            double *p = (double*)&val;
+            double *p = (double *)&val;
             return mp_obj_new_float(*p);
         }
         #endif
@@ -187,7 +201,7 @@
     const char *argtypes = mp_obj_str_get_str(argtypes_in);
 
     mp_int_t nparams = MP_OBJ_SMALL_INT_VALUE(mp_obj_len_maybe(argtypes_in));
-    mp_obj_ffifunc_t *o = m_new_obj_var(mp_obj_ffifunc_t, ffi_type*, nparams);
+    mp_obj_ffifunc_t *o = m_new_obj_var(mp_obj_ffifunc_t, ffi_type *, nparams);
     o->base.type = &ffifunc_type;
 
     o->func = func;
@@ -224,20 +238,20 @@
 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ffimod_func_obj, 4, 4, ffimod_func);
 
 STATIC mp_obj_t mod_ffi_func(mp_obj_t rettype, mp_obj_t addr_in, mp_obj_t argtypes) {
-    void *addr = (void*)MP_OBJ_TO_PTR(mp_obj_int_get_truncated(addr_in));
+    void *addr = (void *)MP_OBJ_TO_PTR(mp_obj_int_get_truncated(addr_in));
     return make_func(rettype, addr, argtypes);
 }
 MP_DEFINE_CONST_FUN_OBJ_3(mod_ffi_func_obj, mod_ffi_func);
 
-STATIC void call_py_func(ffi_cif *cif, void *ret, void** args, void *func) {
+STATIC void call_py_func(ffi_cif *cif, void *ret, void **args, void *func) {
     mp_obj_t pyargs[cif->nargs];
     for (uint i = 0; i < cif->nargs; i++) {
-        pyargs[i] = mp_obj_new_int(*(mp_int_t*)args[i]);
+        pyargs[i] = mp_obj_new_int(*(mp_int_t *)args[i]);
     }
     mp_obj_t res = mp_call_function_n_kw(MP_OBJ_FROM_PTR(func), cif->nargs, 0, pyargs);
 
     if (res != mp_const_none) {
-        *(ffi_arg*)ret = mp_obj_int_get_truncated(res);
+        *(ffi_arg *)ret = mp_obj_int_get_truncated(res);
     }
 }
 
@@ -245,7 +259,7 @@
     const char *rettype = mp_obj_str_get_str(rettype_in);
 
     mp_int_t nparams = MP_OBJ_SMALL_INT_VALUE(mp_obj_len_maybe(paramtypes_in));
-    mp_obj_fficallback_t *o = m_new_obj_var(mp_obj_fficallback_t, ffi_type*, nparams);
+    mp_obj_fficallback_t *o = m_new_obj_var(mp_obj_fficallback_t, ffi_type *, nparams);
     o->base.type = &fficallback_type;
 
     o->clo = ffi_closure_alloc(sizeof(ffi_closure), &o->func);
@@ -337,7 +351,7 @@
     .name = MP_QSTR_ffimod,
     .print = ffimod_print,
     .make_new = ffimod_make_new,
-    .locals_dict = (mp_obj_dict_t*)&ffimod_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&ffimod_locals_dict,
 };
 
 // FFI function
@@ -363,10 +377,10 @@
             values[i] = (ffi_arg)(intptr_t)a;
         #if MICROPY_PY_BUILTINS_FLOAT
         } else if (*argtype == 'f') {
-            float *p = (float*)&values[i];
+            float *p = (float *)&values[i];
             *p = mp_obj_get_float(a);
         } else if (*argtype == 'd') {
-            double *p = (double*)&values[i];
+            double *p = (double *)&values[i];
             *p = mp_obj_get_float(a);
         #endif
         } else if (a == mp_const_none) {
@@ -376,8 +390,8 @@
         } else if (mp_obj_is_str(a)) {
             const char *s = mp_obj_str_get_str(a);
             values[i] = (ffi_arg)(intptr_t)s;
-        } else if (((mp_obj_base_t*)MP_OBJ_TO_PTR(a))->type->buffer_p.get_buffer != NULL) {
-            mp_obj_base_t *o = (mp_obj_base_t*)MP_OBJ_TO_PTR(a);
+        } else if (((mp_obj_base_t *)MP_OBJ_TO_PTR(a))->type->buffer_p.get_buffer != NULL) {
+            mp_obj_base_t *o = (mp_obj_base_t *)MP_OBJ_TO_PTR(a);
             mp_buffer_info_t bufinfo;
             int ret = o->type->buffer_p.get_buffer(MP_OBJ_FROM_PTR(o), &bufinfo, MP_BUFFER_READ); // TODO: MP_BUFFER_READ?
             if (ret != 0) {
@@ -441,7 +455,7 @@
     (void)kind;
     mp_obj_ffivar_t *self = MP_OBJ_TO_PTR(self_in);
     // Variable value printed as cast to int
-    mp_printf(print, "<ffivar @%p: 0x%x>", self->var, *(int*)self->var);
+    mp_printf(print, "<ffivar @%p: 0x%x>", self->var, *(int *)self->var);
 }
 
 STATIC mp_obj_t ffivar_get(mp_obj_t self_in) {
@@ -468,7 +482,7 @@
     { &mp_type_type },
     .name = MP_QSTR_ffivar,
     .print = ffivar_print,
-    .locals_dict = (mp_obj_dict_t*)&ffivar_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&ffivar_locals_dict,
 };
 
 // Generic opaque storage object (unused)
@@ -487,7 +501,7 @@
 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_ffi_open_obj, 1, 2, mod_ffi_open);
 
 STATIC mp_obj_t mod_ffi_as_bytearray(mp_obj_t ptr, mp_obj_t size) {
-    return mp_obj_new_bytearray_by_ref(mp_obj_int_get_truncated(size), (void*)(uintptr_t)mp_obj_int_get_truncated(ptr));
+    return mp_obj_new_bytearray_by_ref(mp_obj_int_get_truncated(size), (void *)(uintptr_t)mp_obj_int_get_truncated(ptr));
 }
 MP_DEFINE_CONST_FUN_OBJ_2(mod_ffi_as_bytearray_obj, mod_ffi_as_bytearray);
 
@@ -503,5 +517,5 @@
 
 const mp_obj_module_t mp_module_ffi = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_ffi_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_ffi_globals,
 };
diff --git a/ports/unix/modjni.c b/ports/unix/modjni.c
index 902c34f..f5dbd9c 100644
--- a/ports/unix/modjni.c
+++ b/ports/unix/modjni.c
@@ -179,7 +179,7 @@
     .print = jclass_print,
     .attr = jclass_attr,
     .call = jclass_call,
-    .locals_dict = (mp_obj_dict_t*)&jclass_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&jclass_locals_dict,
 };
 
 STATIC mp_obj_t new_jclass(jclass jc) {
@@ -288,7 +288,7 @@
     }
 
 
-return MP_OBJ_NULL;
+    return MP_OBJ_NULL;
 }
 
 STATIC mp_obj_t jobject_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
@@ -364,10 +364,10 @@
 #define IMATCH(s, static) ((!strncmp(s, static, sizeof(static) - 1)) && (s += sizeof(static) - 1))
 
 #define CHECK_TYPE(java_type_name) \
-                if (strncmp(arg_type, java_type_name, sizeof(java_type_name) - 1) != 0) { \
-                    return false; \
-                } \
-                arg_type += sizeof(java_type_name) - 1;
+    if (strncmp(arg_type, java_type_name, sizeof(java_type_name) - 1) != 0) { \
+        return false; \
+    } \
+    arg_type += sizeof(java_type_name) - 1;
 
 STATIC const char *strprev(const char *s, char c) {
     while (*s != c) {
@@ -481,7 +481,7 @@
             ret_type = strprev(ret_type, ' ') + 1;
 
             int name_len = strlen(name);
-            if (strncmp(name, meth_name, name_len/*arg_types - meth_name - 1*/) || meth_name[name_len] != '('/*(*/) {
+            if (strncmp(name, meth_name, name_len /*arg_types - meth_name - 1*/) || meth_name[name_len] != '(' /*(*/) {
                 goto next_method;
             }
         }
@@ -541,7 +541,7 @@
             }
         }
 
-next_method:
+    next_method:
         JJ(ReleaseStringUTFChars, name_o, decl);
         JJ(DeleteLocalRef, name_o);
         JJ(DeleteLocalRef, meth);
@@ -601,9 +601,9 @@
     if (!libjvm) {
         mp_raise_msg(&mp_type_OSError, "unable to load libjvm.so, use LD_LIBRARY_PATH");
     }
-    int (*_JNI_CreateJavaVM)(void*, void**, void*) = dlsym(libjvm, "JNI_CreateJavaVM");
+    int (*_JNI_CreateJavaVM)(void *, void **, void *) = dlsym(libjvm, "JNI_CreateJavaVM");
 
-    int st = _JNI_CreateJavaVM(&jvm, (void**)&env, &args);
+    int st = _JNI_CreateJavaVM(&jvm, (void **)&env, &args);
     if (st < 0 || !env) {
         mp_raise_msg(&mp_type_OSError, "unable to create JVM");
     }
@@ -614,26 +614,26 @@
 
     jclass Object_class = JJ(FindClass, "java/lang/Object");
     Object_toString_mid = JJ(GetMethodID, Object_class, "toString",
-                                     "()Ljava/lang/String;");
+        "()Ljava/lang/String;");
 
     Class_getName_mid = (*env)->GetMethodID(env, Class_class, "getName",
-                                     "()Ljava/lang/String;");
+        "()Ljava/lang/String;");
     Class_getField_mid = (*env)->GetMethodID(env, Class_class, "getField",
-                                     "(Ljava/lang/String;)Ljava/lang/reflect/Field;");
+        "(Ljava/lang/String;)Ljava/lang/reflect/Field;");
     Class_getMethods_mid = (*env)->GetMethodID(env, Class_class, "getMethods",
-                                     "()[Ljava/lang/reflect/Method;");
+        "()[Ljava/lang/reflect/Method;");
     Class_getConstructors_mid = (*env)->GetMethodID(env, Class_class, "getConstructors",
-                                     "()[Ljava/lang/reflect/Constructor;");
+        "()[Ljava/lang/reflect/Constructor;");
     Method_getName_mid = (*env)->GetMethodID(env, method_class, "getName",
-                                     "()Ljava/lang/String;");
+        "()Ljava/lang/String;");
 
     List_class = JJ(FindClass, "java/util/List");
     List_get_mid = JJ(GetMethodID, List_class, "get",
-                                     "(I)Ljava/lang/Object;");
+        "(I)Ljava/lang/Object;");
     List_set_mid = JJ(GetMethodID, List_class, "set",
-                                     "(ILjava/lang/Object;)Ljava/lang/Object;");
+        "(ILjava/lang/Object;)Ljava/lang/Object;");
     List_size_mid = JJ(GetMethodID, List_class, "size",
-                                     "()I");
+        "()I");
     IndexException_class = JJ(FindClass, "java/lang/IndexOutOfBoundsException");
 }
 
@@ -715,5 +715,5 @@
 
 const mp_obj_module_t mp_module_jni = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_jni_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_jni_globals,
 };
diff --git a/ports/unix/modmachine.c b/ports/unix/modmachine.c
index a3e5751..492b49c 100644
--- a/ports/unix/modmachine.c
+++ b/ports/unix/modmachine.c
@@ -95,7 +95,7 @@
 
 const mp_obj_module_t mp_module_machine = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&machine_module_globals,
+    .globals = (mp_obj_dict_t *)&machine_module_globals,
 };
 
 #endif // MICROPY_PY_MACHINE
diff --git a/ports/unix/modos.c b/ports/unix/modos.c
index 5b70aee..1414f87 100644
--- a/ports/unix/modos.c
+++ b/ports/unix/modos.c
@@ -331,5 +331,5 @@
 
 const mp_obj_module_t mp_module_os = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_os_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_os_globals,
 };
diff --git a/ports/unix/modtermios.c b/ports/unix/modtermios.c
index 85eabf3..7a578be 100644
--- a/ports/unix/modtermios.c
+++ b/ports/unix/modtermios.c
@@ -58,7 +58,7 @@
             // but no way unicode chars could be there, if c_cc is defined to be a
             // a "char". But it's type is actually cc_t, which can be anything.
             // TODO: For now, we still deal with it like that.
-            cc->items[i] = mp_obj_new_bytes((byte*)&term.c_cc[i], 1);
+            cc->items[i] = mp_obj_new_bytes((byte *)&term.c_cc[i], 1);
         }
     }
     return MP_OBJ_FROM_PTR(r);
@@ -129,7 +129,7 @@
     { MP_ROM_QSTR(MP_QSTR_tcsetattr), MP_ROM_PTR(&mod_termios_tcsetattr_obj) },
     { MP_ROM_QSTR(MP_QSTR_setraw), MP_ROM_PTR(&mod_termios_setraw_obj) },
 
-#define C(name) { MP_ROM_QSTR(MP_QSTR_ ## name), MP_ROM_INT(name) }
+#define C(name) { MP_ROM_QSTR(MP_QSTR_##name), MP_ROM_INT(name) }
     C(TCSANOW),
 
     C(B9600),
@@ -146,5 +146,5 @@
 
 const mp_obj_module_t mp_module_termios = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_termios_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_termios_globals,
 };
diff --git a/ports/unix/modtime.c b/ports/unix/modtime.c
index 4ea8cb6..78068b3 100644
--- a/ports/unix/modtime.c
+++ b/ports/unix/modtime.c
@@ -67,32 +67,32 @@
 #endif
 
 STATIC mp_obj_t mod_time_time(void) {
-#if MICROPY_PY_BUILTINS_FLOAT
+    #if MICROPY_PY_BUILTINS_FLOAT
     struct timeval tv;
     gettimeofday(&tv, NULL);
     mp_float_t val = tv.tv_sec + (mp_float_t)tv.tv_usec / 1000000;
     return mp_obj_new_float(val);
-#else
+    #else
     return mp_obj_new_int((mp_int_t)time(NULL));
-#endif
+    #endif
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_time_time_obj, mod_time_time);
 
 // Note: this is deprecated since CPy3.3, but pystone still uses it.
 STATIC mp_obj_t mod_time_clock(void) {
-#if MICROPY_PY_BUILTINS_FLOAT
+    #if MICROPY_PY_BUILTINS_FLOAT
     // float cannot represent full range of int32 precisely, so we pre-divide
     // int to reduce resolution, and then actually do float division hoping
     // to preserve integer part resolution.
     return mp_obj_new_float((float)(clock() / 1000) / CLOCK_DIV);
-#else
+    #else
     return mp_obj_new_int((mp_int_t)clock());
-#endif
+    #endif
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_time_clock_obj, mod_time_clock);
 
 STATIC mp_obj_t mod_time_sleep(mp_obj_t arg) {
-#if MICROPY_PY_BUILTINS_FLOAT
+    #if MICROPY_PY_BUILTINS_FLOAT
     struct timeval tv;
     mp_float_t val = mp_obj_get_float(arg);
     double ipart;
@@ -116,12 +116,12 @@
         #endif
     }
     RAISE_ERRNO(res, errno);
-#else
+    #else
     // TODO: Handle EINTR
     MP_THREAD_GIL_EXIT();
     sleep(mp_obj_get_int(arg));
     MP_THREAD_GIL_ENTER();
-#endif
+    #endif
     return mp_const_none;
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_time_sleep_obj, mod_time_sleep);
@@ -212,7 +212,7 @@
 
 const mp_obj_module_t mp_module_time = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_time_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_time_globals,
 };
 
 #endif // MICROPY_PY_UTIME
diff --git a/ports/unix/moduos_vfs.c b/ports/unix/moduos_vfs.c
index d4171d0..6e4f352 100644
--- a/ports/unix/moduos_vfs.c
+++ b/ports/unix/moduos_vfs.c
@@ -88,7 +88,7 @@
 
 const mp_obj_module_t mp_module_uos_vfs = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&uos_vfs_module_globals,
+    .globals = (mp_obj_dict_t *)&uos_vfs_module_globals,
 };
 
 #endif // MICROPY_VFS
diff --git a/ports/unix/moduselect.c b/ports/unix/moduselect.c
index 4a095ec..a48e904 100644
--- a/ports/unix/moduselect.c
+++ b/ports/unix/moduselect.c
@@ -315,7 +315,7 @@
     .name = MP_QSTR_poll,
     .getiter = mp_identity_getiter,
     .iternext = poll_iternext,
-    .locals_dict = (void*)&poll_locals_dict,
+    .locals_dict = (void *)&poll_locals_dict,
 };
 
 STATIC mp_obj_t select_poll(size_t n_args, const mp_obj_t *args) {
@@ -348,7 +348,7 @@
 
 const mp_obj_module_t mp_module_uselect = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_select_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_select_globals,
 };
 
 #endif // MICROPY_PY_USELECT_POSIX
diff --git a/ports/unix/modusocket.c b/ports/unix/modusocket.c
index 85e4628..4c5d5d2 100644
--- a/ports/unix/modusocket.c
+++ b/ports/unix/modusocket.c
@@ -208,7 +208,7 @@
     byte addr[32];
     socklen_t addr_len = sizeof(addr);
     MP_THREAD_GIL_EXIT();
-    int fd = accept(self->fd, (struct sockaddr*)&addr, &addr_len);
+    int fd = accept(self->fd, (struct sockaddr *)&addr, &addr_len);
     MP_THREAD_GIL_ENTER();
     int err = errno;
     if (fd == -1 && self->blocking && err == EAGAIN) {
@@ -263,7 +263,7 @@
 
     byte *buf = m_new(byte, sz);
     MP_THREAD_GIL_EXIT();
-    int out_sz = recvfrom(self->fd, buf, sz, flags, (struct sockaddr*)&addr, &addr_len);
+    int out_sz = recvfrom(self->fd, buf, sz, flags, (struct sockaddr *)&addr, &addr_len);
     MP_THREAD_GIL_ENTER();
     RAISE_ERRNO(out_sz, errno);
 
@@ -272,7 +272,7 @@
 
     mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL));
     t->items[0] = buf_o;
-    t->items[1] = mp_obj_from_sockaddr((struct sockaddr*)&addr, addr_len);
+    t->items[1] = mp_obj_from_sockaddr((struct sockaddr *)&addr, addr_len);
 
     return MP_OBJ_FROM_PTR(t);
 }
@@ -315,7 +315,7 @@
     mp_get_buffer_raise(dst_addr, &addr_bi, MP_BUFFER_READ);
     MP_THREAD_GIL_EXIT();
     int out_sz = sendto(self->fd, bufinfo.buf, bufinfo.len, flags,
-                        (struct sockaddr *)addr_bi.buf, addr_bi.len);
+        (struct sockaddr *)addr_bi.buf, addr_bi.len);
     MP_THREAD_GIL_ENTER();
     RAISE_ERRNO(out_sz, errno);
 
@@ -425,7 +425,7 @@
     mp_obj_t *new_args = alloca(n_args * sizeof(mp_obj_t));
     memcpy(new_args + 1, args + 1, (n_args - 1) * sizeof(mp_obj_t));
     new_args[0] = MP_OBJ_NEW_SMALL_INT(self->fd);
-    return mp_builtin_open(n_args, new_args, (mp_map_t*)&mp_const_empty_map);
+    return mp_builtin_open(n_args, new_args, (mp_map_t *)&mp_const_empty_map);
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_makefile_obj, 1, 3, socket_makefile);
 
@@ -494,7 +494,7 @@
     .getiter = NULL,
     .iternext = NULL,
     .protocol = &usocket_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&usocket_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&usocket_locals_dict,
 };
 
 #define BINADDR_MAX_LEN sizeof(struct in6_addr)
@@ -548,8 +548,8 @@
         snprintf(buf, sizeof(buf), "%u", port);
         serv = buf;
         hints.ai_flags = AI_NUMERICSERV;
-#ifdef __UCLIBC_MAJOR__
-#if __UCLIBC_MAJOR__ == 0 && (__UCLIBC_MINOR__ < 9 || (__UCLIBC_MINOR__ == 9 && __UCLIBC_SUBLEVEL__ <= 32))
+        #ifdef __UCLIBC_MAJOR__
+        #if __UCLIBC_MAJOR__ == 0 && (__UCLIBC_MINOR__ < 9 || (__UCLIBC_MINOR__ == 9 && __UCLIBC_SUBLEVEL__ <= 32))
 // "warning" requires -Wno-cpp which is a relatively new gcc option, so we choose not to use it.
 //#warning Working around uClibc bug with numeric service name
         // Older versions og uClibc have bugs when numeric ports in service
@@ -560,8 +560,8 @@
         // Note that this is crude workaround, precluding UDP socket addresses
         // to be returned. TODO: set only if not set by Python args.
         hints.ai_socktype = SOCK_STREAM;
-#endif
-#endif
+        #endif
+        #endif
     } else {
         serv = mp_obj_str_get_str(args[1]);
     }
@@ -608,30 +608,30 @@
 STATIC mp_obj_t mod_socket_sockaddr(mp_obj_t sockaddr_in) {
     mp_buffer_info_t bufinfo;
     mp_get_buffer_raise(sockaddr_in, &bufinfo, MP_BUFFER_READ);
-    switch (((struct sockaddr*)bufinfo.buf)->sa_family) {
+    switch (((struct sockaddr *)bufinfo.buf)->sa_family) {
         case AF_INET: {
-            struct sockaddr_in *sa = (struct sockaddr_in*)bufinfo.buf;
+            struct sockaddr_in *sa = (struct sockaddr_in *)bufinfo.buf;
             mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(3, NULL));
             t->items[0] = MP_OBJ_NEW_SMALL_INT(AF_INET);
-            t->items[1] = mp_obj_new_bytes((byte*)&sa->sin_addr, sizeof(sa->sin_addr));
+            t->items[1] = mp_obj_new_bytes((byte *)&sa->sin_addr, sizeof(sa->sin_addr));
             t->items[2] = MP_OBJ_NEW_SMALL_INT(ntohs(sa->sin_port));
             return MP_OBJ_FROM_PTR(t);
         }
         case AF_INET6: {
-            struct sockaddr_in6 *sa = (struct sockaddr_in6*)bufinfo.buf;
+            struct sockaddr_in6 *sa = (struct sockaddr_in6 *)bufinfo.buf;
             mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(5, NULL));
             t->items[0] = MP_OBJ_NEW_SMALL_INT(AF_INET6);
-            t->items[1] = mp_obj_new_bytes((byte*)&sa->sin6_addr, sizeof(sa->sin6_addr));
+            t->items[1] = mp_obj_new_bytes((byte *)&sa->sin6_addr, sizeof(sa->sin6_addr));
             t->items[2] = MP_OBJ_NEW_SMALL_INT(ntohs(sa->sin6_port));
             t->items[3] = MP_OBJ_NEW_SMALL_INT(ntohl(sa->sin6_flowinfo));
             t->items[4] = MP_OBJ_NEW_SMALL_INT(ntohl(sa->sin6_scope_id));
             return MP_OBJ_FROM_PTR(t);
         }
         default: {
-            struct sockaddr *sa = (struct sockaddr*)bufinfo.buf;
+            struct sockaddr *sa = (struct sockaddr *)bufinfo.buf;
             mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL));
             t->items[0] = MP_OBJ_NEW_SMALL_INT(sa->sa_family);
-            t->items[1] = mp_obj_new_bytes((byte*)sa->sa_data, bufinfo.len - offsetof(struct sockaddr, sa_data));
+            t->items[1] = mp_obj_new_bytes((byte *)sa->sa_data, bufinfo.len - offsetof(struct sockaddr, sa_data));
             return MP_OBJ_FROM_PTR(t);
         }
     }
@@ -647,7 +647,7 @@
     { MP_ROM_QSTR(MP_QSTR_inet_ntop), MP_ROM_PTR(&mod_socket_inet_ntop_obj) },
     { MP_ROM_QSTR(MP_QSTR_sockaddr), MP_ROM_PTR(&mod_socket_sockaddr_obj) },
 
-#define C(name) { MP_ROM_QSTR(MP_QSTR_ ## name), MP_ROM_INT(name) }
+#define C(name) { MP_ROM_QSTR(MP_QSTR_##name), MP_ROM_INT(name) }
     C(AF_UNIX),
     C(AF_INET),
     C(AF_INET6),
@@ -671,5 +671,5 @@
 
 const mp_obj_module_t mp_module_socket = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_socket_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_socket_globals,
 };
diff --git a/ports/unix/mpconfigport.h b/ports/unix/mpconfigport.h
index 2f01aff..fc2e231 100644
--- a/ports/unix/mpconfigport.h
+++ b/ports/unix/mpconfigport.h
@@ -44,7 +44,7 @@
 #endif
 #if !defined(MICROPY_EMIT_THUMB) && defined(__thumb2__)
     #define MICROPY_EMIT_THUMB      (1)
-    #define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1))
+    #define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1))
 #endif
 // Some compilers define __thumb2__ and __arm__ at the same time, let
 // autodetected thumb2 emitter have priority.
@@ -271,7 +271,7 @@
 typedef long mp_off_t;
 #endif
 
-void mp_unix_alloc_exec(size_t min_size, void** ptr, size_t *size);
+void mp_unix_alloc_exec(size_t min_size, void **ptr, size_t *size);
 void mp_unix_free_exec(void *ptr, size_t size);
 void mp_unix_mark_exec(void);
 #define MP_PLAT_ALLOC_EXEC(min_size, ptr, size) mp_unix_alloc_exec(min_size, ptr, size)
@@ -286,10 +286,10 @@
 #define MP_PLAT_PRINT_STRN(str, len) mp_hal_stdout_tx_strn_cooked(str, len)
 #else
 #define MP_PLAT_PRINT_STRN(str, len) do { \
-    MP_THREAD_GIL_EXIT(); \
-    ssize_t ret = write(1, str, len); \
-    MP_THREAD_GIL_ENTER(); \
-    (void)ret; \
+        MP_THREAD_GIL_EXIT(); \
+        ssize_t ret = write(1, str, len); \
+        MP_THREAD_GIL_ENTER(); \
+        (void)ret; \
 } while (0)
 #endif
 
diff --git a/ports/unix/mphalport.h b/ports/unix/mphalport.h
index cb86e70..daa9c73 100644
--- a/ports/unix/mphalport.h
+++ b/ports/unix/mphalport.h
@@ -42,7 +42,7 @@
 #include "input.h"
 #define mp_hal_readline mp_hal_readline
 static inline int mp_hal_readline(vstr_t *vstr, const char *p) {
-    char *line = prompt((char*)p);
+    char *line = prompt((char *)p);
     vstr_add_str(vstr, line);
     free(line);
     return 0;
@@ -65,10 +65,14 @@
 
 // TODO: POSIX et al. define usleep() as guaranteedly capable only of 1s sleep:
 // "The useconds argument shall be less than one million."
-static inline void mp_hal_delay_ms(mp_uint_t ms) { usleep((ms) * 1000); }
-static inline void mp_hal_delay_us(mp_uint_t us) { usleep(us); }
+static inline void mp_hal_delay_ms(mp_uint_t ms) {
+    usleep((ms) * 1000);
+}
+static inline void mp_hal_delay_us(mp_uint_t us) {
+    usleep(us);
+}
 #define mp_hal_ticks_cpu() 0
 
 #define RAISE_ERRNO(err_flag, error_val) \
     { if (err_flag == -1) \
-        { mp_raise_OSError(error_val); } }
+      { mp_raise_OSError(error_val); } }
diff --git a/ports/unix/mpthreadport.c b/ports/unix/mpthreadport.c
index 4ee6923..c604c5d 100644
--- a/ports/unix/mpthreadport.c
+++ b/ports/unix/mpthreadport.c
@@ -82,8 +82,8 @@
         // gc_collect_regs_and_stack function above
         //gc_collect_root((void**)context, sizeof(ucontext_t) / sizeof(uintptr_t));
         #if MICROPY_ENABLE_PYSTACK
-        void **ptrs = (void**)(void*)MP_STATE_THREAD(pystack_start);
-        gc_collect_root(ptrs, (MP_STATE_THREAD(pystack_cur) - MP_STATE_THREAD(pystack_start)) / sizeof(void*));
+        void **ptrs = (void **)(void *)MP_STATE_THREAD(pystack_start);
+        gc_collect_root(ptrs, (MP_STATE_THREAD(pystack_cur) - MP_STATE_THREAD(pystack_start)) / sizeof(void *));
         #endif
         #if defined (__APPLE__)
         sem_post(thread_signal_done_p);
@@ -163,7 +163,7 @@
 }
 
 mp_state_thread_t *mp_thread_get_state(void) {
-    return (mp_state_thread_t*)pthread_getspecific(tls_key);
+    return (mp_state_thread_t *)pthread_getspecific(tls_key);
 }
 
 void mp_thread_set_state(mp_state_thread_t *state) {
@@ -182,7 +182,7 @@
     pthread_mutex_unlock(&thread_mutex);
 }
 
-void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size) {
+void mp_thread_create(void *(*entry)(void *), void *arg, size_t *stack_size) {
     // default stack size is 8k machine-words
     if (*stack_size == 0) {
         *stack_size = 8192 * BYTES_PER_WORD;
diff --git a/ports/unix/unix_mphal.c b/ports/unix/unix_mphal.c
index f7570a3..0d7638f 100644
--- a/ports/unix/unix_mphal.c
+++ b/ports/unix/unix_mphal.c
@@ -132,7 +132,7 @@
             return -1;
         }
         nlr_pop();
-        return *(byte*)bufinfo.buf;
+        return *(byte *)bufinfo.buf;
     } else {
         // Temporarily disable dupterm to avoid infinite recursion
         mp_obj_t save_term = MP_STATE_VM(dupterm_objs[idx]);
@@ -147,12 +147,12 @@
 #endif
 
 int mp_hal_stdin_rx_chr(void) {
-#if MICROPY_PY_OS_DUPTERM
+    #if MICROPY_PY_OS_DUPTERM
     // TODO only support dupterm one slot at the moment
     if (MP_STATE_VM(dupterm_objs[0]) != MP_OBJ_NULL) {
         int c;
         do {
-             c = call_dupterm_read(0);
+            c = call_dupterm_read(0);
         } while (c == -2);
         if (c == -1) {
             goto main_term;
@@ -163,7 +163,7 @@
         return c;
     }
 main_term:;
-#endif
+    #endif
 
     MP_THREAD_GIL_EXIT();
     unsigned char c;
diff --git a/ports/windows/fmode.c b/ports/windows/fmode.c
index 33ba24e..a7976b8 100644
--- a/ports/windows/fmode.c
+++ b/ports/windows/fmode.c
@@ -32,12 +32,12 @@
 // Workaround for setting file translation mode: we must distinguish toolsets
 // since mingw has no _set_fmode, and altering msvc's _fmode directly has no effect
 STATIC int set_fmode_impl(int mode) {
-#ifndef _MSC_VER
+    #ifndef _MSC_VER
     _fmode = mode;
     return 0;
-#else
+    #else
     return _set_fmode(mode);
-#endif
+    #endif
 }
 
 void set_fmode_binary(void) {
diff --git a/ports/windows/init.c b/ports/windows/init.c
index 73ab713..930400f 100644
--- a/ports/windows/init.c
+++ b/ports/windows/init.c
@@ -41,7 +41,7 @@
 #endif
 
 void init() {
-#ifdef _MSC_VER
+    #ifdef _MSC_VER
     // Disable the 'Debug Error!' dialog for assertions failures and the likes,
     // instead write messages to the debugger output and terminate.
     _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
@@ -52,16 +52,16 @@
     // passing invalid file descriptors to functions like lseek() and make the
     // functions called behave properly by setting errno to EBADF/EINVAL/..
     _set_invalid_parameter_handler(invalid_param_handler);
-#endif
+    #endif
     SetConsoleCtrlHandler(console_sighandler, TRUE);
     init_sleep();
-#ifdef __MINGW32__
+    #ifdef __MINGW32__
     putenv("PRINTF_EXPONENT_DIGITS=2");
-#elif _MSC_VER < 1900
+    #elif _MSC_VER < 1900
     // This is only necessary for Visual Studio versions 2013 and below:
     // https://msdn.microsoft.com/en-us/library/bb531344(v=vs.140).aspx
     _set_output_format(_TWO_DIGIT_EXPONENT);
-#endif
+    #endif
     set_fmode_binary();
 }
 
diff --git a/ports/windows/mpconfigport.h b/ports/windows/mpconfigport.h
index 2d852a8..0018b4f 100644
--- a/ports/windows/mpconfigport.h
+++ b/ports/windows/mpconfigport.h
@@ -243,12 +243,12 @@
 #define S_ISDIR(m)                  (((m) & S_IFMT) == S_IFDIR)
 #ifdef _WIN64
 #define SSIZE_MAX                   _I64_MAX
-typedef __int64                     ssize_t;
+typedef __int64 ssize_t;
 #else
 #define SSIZE_MAX                   _I32_MAX
-typedef int                         ssize_t;
+typedef int ssize_t;
 #endif
-typedef mp_off_t                    off_t;
+typedef mp_off_t off_t;
 
 
 // Put static/global variables in sections with a known name
diff --git a/ports/windows/realpath.c b/ports/windows/realpath.c
index ac9adf8..5e429ef 100644
--- a/ports/windows/realpath.c
+++ b/ports/windows/realpath.c
@@ -33,8 +33,9 @@
     if (p != NULL) {
         char *pp = p;
         while (*pp != 0) {
-            if (*pp == '\\')
+            if (*pp == '\\') {
                 *pp = '/';
+            }
             ++pp;
         }
     }
@@ -50,14 +51,16 @@
         errno = EINVAL;
     } else if (access(path, R_OK) == 0) {
         ret = resolved_path;
-        if (ret == NULL)
+        if (ret == NULL) {
             ret = malloc(_MAX_PATH);
+        }
         if (ret == NULL) {
             errno = ENOMEM;
         } else {
             ret = _fullpath(ret, path, _MAX_PATH);
-            if (ret == NULL)
+            if (ret == NULL) {
                 errno = EIO;
+            }
         }
     }
     return to_unix_path(ret);
diff --git a/ports/windows/windows_mphal.c b/ports/windows/windows_mphal.c
index e0c1255..7835c61 100644
--- a/ports/windows/windows_mphal.c
+++ b/ports/windows/windows_mphal.c
@@ -47,8 +47,8 @@
 STATIC void assure_conout_handle() {
     if (!con_out) {
         con_out = CreateFile("CONOUT$", GENERIC_READ | GENERIC_WRITE,
-                      FILE_SHARE_READ | FILE_SHARE_WRITE,
-                      NULL, OPEN_EXISTING, 0, 0);
+            FILE_SHARE_READ | FILE_SHARE_WRITE,
+            NULL, OPEN_EXISTING, 0, 0);
         assert(con_out != INVALID_HANDLE_VALUE);
     }
 }
@@ -198,25 +198,25 @@
     DWORD num_read;
     INPUT_RECORD rec;
     for (;;) {
-      MP_THREAD_GIL_EXIT();
-      status = ReadConsoleInput(std_in, &rec, 1, &num_read)
-      MP_THREAD_GIL_ENTER();
-      if (!status || !num_read) {
-          return CHAR_CTRL_C; // EOF, ctrl-D
-      }
-      if (rec.EventType != KEY_EVENT || !rec.Event.KeyEvent.bKeyDown) { // only want key down events
-          continue;
-      }
-      const bool ctrl_key_down = (rec.Event.KeyEvent.dwControlKeyState & LEFT_CTRL_PRESSED) ||
-                                 (rec.Event.KeyEvent.dwControlKeyState & RIGHT_CTRL_PRESSED);
-      const int ret = esc_seq_process_vk(rec.Event.KeyEvent.wVirtualKeyCode, ctrl_key_down);
-      if (ret) {
-          return ret;
-      }
-      const char c = rec.Event.KeyEvent.uChar.AsciiChar;
-      if (c) { // plain ascii char, return it
-          return c;
-      }
+        MP_THREAD_GIL_EXIT();
+        status = ReadConsoleInput(std_in, &rec, 1, &num_read)
+            MP_THREAD_GIL_ENTER();
+        if (!status || !num_read) {
+            return CHAR_CTRL_C; // EOF, ctrl-D
+        }
+        if (rec.EventType != KEY_EVENT || !rec.Event.KeyEvent.bKeyDown) { // only want key down events
+            continue;
+        }
+        const bool ctrl_key_down = (rec.Event.KeyEvent.dwControlKeyState & LEFT_CTRL_PRESSED) ||
+            (rec.Event.KeyEvent.dwControlKeyState & RIGHT_CTRL_PRESSED);
+        const int ret = esc_seq_process_vk(rec.Event.KeyEvent.wVirtualKeyCode, ctrl_key_down);
+        if (ret) {
+            return ret;
+        }
+        const char c = rec.Event.KeyEvent.uChar.AsciiChar;
+        if (c) { // plain ascii char, return it
+            return c;
+        }
     }
 }
 
@@ -249,9 +249,9 @@
 mp_uint_t mp_hal_ticks_cpu(void) {
     LARGE_INTEGER value;
     QueryPerformanceCounter(&value);
-#ifdef _WIN64
+    #ifdef _WIN64
     return value.QuadPart;
-#else
+    #else
     return value.LowPart;
-#endif
+    #endif
 }
diff --git a/ports/zephyr/help.c b/ports/zephyr/help.c
index becc203..4ee674b 100644
--- a/ports/zephyr/help.c
+++ b/ports/zephyr/help.c
@@ -27,14 +27,14 @@
 #include "py/builtin.h"
 
 const char zephyr_help_text[] =
-"Welcome to MicroPython!\n"
-"\n"
-"Control commands:\n"
-"  CTRL-A        -- on a blank line, enter raw REPL mode\n"
-"  CTRL-B        -- on a blank line, enter normal REPL mode\n"
-"  CTRL-C        -- interrupt a running program\n"
-"  CTRL-D        -- on a blank line, do a soft reset of the board\n"
-"  CTRL-E        -- on a blank line, enter paste mode\n"
-"\n"
-"For further help on a specific object, type help(obj)\n"
+    "Welcome to MicroPython!\n"
+    "\n"
+    "Control commands:\n"
+    "  CTRL-A        -- on a blank line, enter raw REPL mode\n"
+    "  CTRL-B        -- on a blank line, enter normal REPL mode\n"
+    "  CTRL-C        -- interrupt a running program\n"
+    "  CTRL-D        -- on a blank line, do a soft reset of the board\n"
+    "  CTRL-E        -- on a blank line, enter paste mode\n"
+    "\n"
+    "For further help on a specific object, type help(obj)\n"
 ;
diff --git a/ports/zephyr/machine_i2c.c b/ports/zephyr/machine_i2c.c
index 087cf4b..0f16095 100644
--- a/ports/zephyr/machine_i2c.c
+++ b/ports/zephyr/machine_i2c.c
@@ -97,7 +97,7 @@
     struct i2c_msg msg;
     int ret;
 
-    msg.buf = (u8_t*)buf;
+    msg.buf = (u8_t *)buf;
     msg.len = len;
     msg.flags = 0;
 
@@ -133,5 +133,5 @@
     .print = machine_hard_i2c_print,
     .make_new = machine_hard_i2c_make_new,
     .protocol = &machine_hard_i2c_p,
-    .locals_dict = (mp_obj_dict_t*)&mp_machine_soft_i2c_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&mp_machine_soft_i2c_locals_dict,
 };
diff --git a/ports/zephyr/main.c b/ports/zephyr/main.c
index 7c64589..6ed8c51 100644
--- a/ports/zephyr/main.c
+++ b/ports/zephyr/main.c
@@ -57,7 +57,7 @@
 void init_zephyr(void) {
     // We now rely on CONFIG_NET_APP_SETTINGS to set up bootstrap
     // network addresses.
-#if 0
+    #if 0
     #ifdef CONFIG_NETWORKING
     if (net_if_get_default() == NULL) {
         // If there's no default networking interface,
@@ -78,7 +78,7 @@
     static struct in6_addr in6addr_my = {{{0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
     net_if_ipv6_addr_add(net_if_get_default(), &in6addr_my, NET_ADDR_MANUAL, 0);
     #endif
-#endif
+    #endif
 }
 
 int real_main(void) {
@@ -160,7 +160,9 @@
 MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
 
 NORETURN void nlr_jump_fail(void *val) {
-    while (1);
+    while (1) {
+        ;
+    }
 }
 
 #ifndef NDEBUG
diff --git a/ports/zephyr/modmachine.c b/ports/zephyr/modmachine.c
index dd79774..72078cf 100644
--- a/ports/zephyr/modmachine.c
+++ b/ports/zephyr/modmachine.c
@@ -72,7 +72,7 @@
 
 const mp_obj_module_t mp_module_machine = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&machine_module_globals,
+    .globals = (mp_obj_dict_t *)&machine_module_globals,
 };
 
 #endif // MICROPY_PY_MACHINE
diff --git a/ports/zephyr/moduos.c b/ports/zephyr/moduos.c
index 46745e6..49d5744 100644
--- a/ports/zephyr/moduos.c
+++ b/ports/zephyr/moduos.c
@@ -69,7 +69,7 @@
 
 const mp_obj_module_t mp_module_uos = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&uos_module_globals,
+    .globals = (mp_obj_dict_t *)&uos_module_globals,
 };
 
 #endif // MICROPY_PY_UOS
diff --git a/ports/zephyr/modusocket.c b/ports/zephyr/modusocket.c
index 0830837..09d8754 100644
--- a/ports/zephyr/modusocket.c
+++ b/ports/zephyr/modusocket.c
@@ -75,18 +75,18 @@
 
 STATIC void parse_inet_addr(socket_obj_t *socket, mp_obj_t addr_in, struct sockaddr *sockaddr) {
     // We employ the fact that port and address offsets are the same for IPv4 & IPv6
-    struct sockaddr_in *sockaddr_in = (struct sockaddr_in*)sockaddr;
+    struct sockaddr_in *sockaddr_in = (struct sockaddr_in *)sockaddr;
 
     mp_obj_t *addr_items;
     mp_obj_get_array_fixed_n(addr_in, 2, &addr_items);
-    sockaddr_in->sin_family = net_context_get_family((void*)socket->ctx);
+    sockaddr_in->sin_family = net_context_get_family((void *)socket->ctx);
     RAISE_ERRNO(net_addr_pton(sockaddr_in->sin_family, mp_obj_str_get_str(addr_items[0]), &sockaddr_in->sin_addr));
     sockaddr_in->sin_port = htons(mp_obj_get_int(addr_items[1]));
 }
 
 STATIC mp_obj_t format_inet_addr(struct sockaddr *addr, mp_obj_t port) {
     // We employ the fact that port and address offsets are the same for IPv4 & IPv6
-    struct sockaddr_in6 *sockaddr_in6 = (struct sockaddr_in6*)addr;
+    struct sockaddr_in6 *sockaddr_in6 = (struct sockaddr_in6 *)addr;
     char buf[40];
     net_addr_ntop(addr->sa_family, &sockaddr_in6->sin6_addr, buf, sizeof(buf));
     mp_obj_tuple_t *tuple = mp_obj_new_tuple(addr->sa_family == AF_INET ? 2 : 4, NULL);
@@ -119,7 +119,7 @@
     if (self->ctx == -1) {
         mp_printf(print, "<socket NULL>");
     } else {
-        struct net_context *ctx = (void*)self->ctx;
+        struct net_context *ctx = (void *)self->ctx;
         mp_printf(print, "<socket %p type=%d>", ctx, net_context_get_type(ctx));
     }
 }
@@ -462,7 +462,7 @@
 
 const mp_obj_module_t mp_module_usocket = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_usocket_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_usocket_globals,
 };
 
 #endif // MICROPY_PY_USOCKET
diff --git a/ports/zephyr/modutime.c b/ports/zephyr/modutime.c
index a5d32fe..ba9e1d8 100644
--- a/ports/zephyr/modutime.c
+++ b/ports/zephyr/modutime.c
@@ -61,7 +61,7 @@
 
 const mp_obj_module_t mp_module_time = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_time_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_time_globals,
 };
 
 #endif // MICROPY_PY_UTIME
diff --git a/ports/zephyr/modzephyr.c b/ports/zephyr/modzephyr.c
index 02ad356..2d03ac2 100644
--- a/ports/zephyr/modzephyr.c
+++ b/ports/zephyr/modzephyr.c
@@ -49,8 +49,7 @@
 extern k_tid_t const _main_thread;
 extern k_tid_t const _idle_thread;
 
-static void thread_stack_dump(const struct k_thread *thread, void *user_data)
-{
+static void thread_stack_dump(const struct k_thread *thread, void *user_data) {
     const char *th_name = k_thread_name_get((k_tid_t)thread);
 
     if (th_name == NULL) {
@@ -59,7 +58,7 @@
         th_name = tid;
     }
 
-    stack_analyze(th_name, (char*)thread->stack_info.start, thread->stack_info.size);
+    stack_analyze(th_name, (char *)thread->stack_info.start, thread->stack_info.size);
 }
 
 STATIC mp_obj_t mod_stacks_analyze(void) {
@@ -104,7 +103,7 @@
 
 const mp_obj_module_t mp_module_zephyr = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_time_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_time_globals,
 };
 
 #endif // MICROPY_PY_ZEPHYR
diff --git a/ports/zephyr/modzsensor.c b/ports/zephyr/modzsensor.c
index 570017b..736cd22 100644
--- a/ports/zephyr/modzsensor.c
+++ b/ports/zephyr/modzsensor.c
@@ -110,14 +110,14 @@
     { &mp_type_type },
     .name = MP_QSTR_Sensor,
     .make_new = sensor_make_new,
-    .locals_dict = (void*)&sensor_locals_dict,
+    .locals_dict = (void *)&sensor_locals_dict,
 };
 
 STATIC const mp_rom_map_elem_t mp_module_zsensor_globals_table[] = {
     { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_zsensor) },
     { MP_ROM_QSTR(MP_QSTR_Sensor), MP_ROM_PTR(&sensor_type) },
 
-#define C(name) { MP_ROM_QSTR(MP_QSTR_ ## name), MP_ROM_INT(SENSOR_CHAN_ ## name) }
+#define C(name) { MP_ROM_QSTR(MP_QSTR_##name), MP_ROM_INT(SENSOR_CHAN_##name) }
     C(ACCEL_X),
     C(ACCEL_Y),
     C(ACCEL_Z),
@@ -140,7 +140,7 @@
 
 const mp_obj_module_t mp_module_zsensor = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_zsensor_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_zsensor_globals,
 };
 
 #endif //MICROPY_PY_UHASHLIB
diff --git a/ports/zephyr/uart_core.c b/ports/zephyr/uart_core.c
index 1c92650..fef9f00 100644
--- a/ports/zephyr/uart_core.c
+++ b/ports/zephyr/uart_core.c
@@ -36,23 +36,23 @@
 
 // Receive single character
 int mp_hal_stdin_rx_chr(void) {
-#ifdef CONFIG_CONSOLE_SUBSYS
+    #ifdef CONFIG_CONSOLE_SUBSYS
     return console_getchar();
-#else
+    #else
     return zephyr_getchar();
-#endif
+    #endif
 }
 
 // Send string of given length
 void mp_hal_stdout_tx_strn(const char *str, mp_uint_t len) {
-#ifdef CONFIG_CONSOLE_SUBSYS
+    #ifdef CONFIG_CONSOLE_SUBSYS
     while (len--) {
         char c = *str++;
         while (console_putchar(c) == -1) {
             k_sleep(1);
         }
     }
-#else
+    #else
     static struct device *uart_console_dev;
     if (uart_console_dev == NULL) {
         uart_console_dev = device_get_binding(CONFIG_UART_CONSOLE_ON_DEV_NAME);
@@ -61,5 +61,5 @@
     while (len--) {
         uart_poll_out(uart_console_dev, *str++);
     }
-#endif
+    #endif
 }
diff --git a/ports/zephyr/zephyr_storage.c b/ports/zephyr/zephyr_storage.c
index ccbd06c..c592881 100644
--- a/ports/zephyr/zephyr_storage.c
+++ b/ports/zephyr/zephyr_storage.c
@@ -134,7 +134,7 @@
     .name = MP_QSTR_DiskAccess,
     .print = zephyr_disk_access_print,
     .make_new = zephyr_disk_access_make_new,
-    .locals_dict = (mp_obj_dict_t*)&zephyr_disk_access_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&zephyr_disk_access_locals_dict,
 };
 #endif // CONFIG_DISK_ACCESS
 
@@ -256,6 +256,6 @@
     .name = MP_QSTR_FlashArea,
     .print = zephyr_flash_area_print,
     .make_new = zephyr_flash_area_make_new,
-    .locals_dict = (mp_obj_dict_t*)&zephyr_flash_area_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&zephyr_flash_area_locals_dict,
 };
 #endif // CONFIG_FLASH_MAP
diff --git a/py/argcheck.c b/py/argcheck.c
index 3b3f9ee..87e13bc 100644
--- a/py/argcheck.c
+++ b/py/argcheck.c
@@ -113,7 +113,7 @@
         }
     }
     if (pos_found < n_pos) {
-        extra_positional:
+    extra_positional:
         if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
             mp_arg_error_terse_mismatch();
         } else {
diff --git a/py/asmarm.c b/py/asmarm.c
index 59c661c..72b37f7 100644
--- a/py/asmarm.c
+++ b/py/asmarm.c
@@ -40,20 +40,20 @@
 
 void asm_arm_end_pass(asm_arm_t *as) {
     if (as->base.pass == MP_ASM_PASS_EMIT) {
-#if defined(__linux__) && defined(__GNUC__)
+        #if defined(__linux__) && defined(__GNUC__)
         char *start = mp_asm_base_get_code(&as->base);
         char *end = start + mp_asm_base_get_code_size(&as->base);
         __builtin___clear_cache(start, end);
-#elif defined(__arm__)
+        #elif defined(__arm__)
         // flush I- and D-cache
-        asm volatile(
-                "0:"
-                "mrc p15, 0, r15, c7, c10, 3\n"
-                "bne 0b\n"
-                "mov r0, #0\n"
-                "mcr p15, 0, r0, c7, c7, 0\n"
-                : : : "r0", "cc");
-#endif
+        asm volatile (
+            "0:"
+            "mrc p15, 0, r15, c7, c10, 3\n"
+            "bne 0b\n"
+            "mov r0, #0\n"
+            "mcr p15, 0, r0, c7, c7, 0\n"
+            : : : "r0", "cc");
+        #endif
     }
 }
 
@@ -61,7 +61,7 @@
 STATIC void emit(asm_arm_t *as, uint op) {
     uint8_t *c = mp_asm_base_get_cur_to_write_bytes(&as->base, 4);
     if (c != NULL) {
-        *(uint32_t*)c = op;
+        *(uint32_t *)c = op;
     }
 }
 
diff --git a/py/asmbase.c b/py/asmbase.c
index ab861da..344e03e 100644
--- a/py/asmbase.c
+++ b/py/asmbase.c
@@ -51,7 +51,7 @@
         memset(as->label_offsets, -1, as->max_num_labels * sizeof(size_t));
     } else {
         // allocating executable RAM is platform specific
-        MP_PLAT_ALLOC_EXEC(as->code_offset, (void**)&as->code_base, &as->code_size);
+        MP_PLAT_ALLOC_EXEC(as->code_offset, (void **)&as->code_base, &as->code_size);
         assert(as->code_base != NULL);
     }
     as->pass = pass;
@@ -84,12 +84,12 @@
 }
 
 // align must be a multiple of 2
-void mp_asm_base_align(mp_asm_base_t* as, unsigned int align) {
+void mp_asm_base_align(mp_asm_base_t *as, unsigned int align) {
     as->code_offset = (as->code_offset + align - 1) & (~(align - 1));
 }
 
 // this function assumes a little endian machine
-void mp_asm_base_data(mp_asm_base_t* as, unsigned int bytesize, uintptr_t val) {
+void mp_asm_base_data(mp_asm_base_t *as, unsigned int bytesize, uintptr_t val) {
     uint8_t *c = mp_asm_base_get_cur_to_write_bytes(as, bytesize);
     if (c != NULL) {
         for (unsigned int i = 0; i < bytesize; i++) {
diff --git a/py/asmbase.h b/py/asmbase.h
index b5e2593..24c3af8 100644
--- a/py/asmbase.h
+++ b/py/asmbase.h
@@ -47,8 +47,8 @@
 void mp_asm_base_start_pass(mp_asm_base_t *as, int pass);
 uint8_t *mp_asm_base_get_cur_to_write_bytes(mp_asm_base_t *as, size_t num_bytes_to_write);
 void mp_asm_base_label_assign(mp_asm_base_t *as, size_t label);
-void mp_asm_base_align(mp_asm_base_t* as, unsigned int align);
-void mp_asm_base_data(mp_asm_base_t* as, unsigned int bytesize, uintptr_t val);
+void mp_asm_base_align(mp_asm_base_t *as, unsigned int align);
+void mp_asm_base_data(mp_asm_base_t *as, unsigned int bytesize, uintptr_t val);
 
 static inline size_t mp_asm_base_get_code_pos(mp_asm_base_t *as) {
     return as->code_offset;
diff --git a/py/asmthumb.c b/py/asmthumb.c
index 68fb8f2..bb10935 100644
--- a/py/asmthumb.c
+++ b/py/asmthumb.c
@@ -377,7 +377,7 @@
         }
     } else {
         // is a forwards jump, so need to assume it's large
-        large_jump:
+    large_jump:
         asm_thumb_op32(as, OP_BW_HI(rel), OP_BW_LO(rel));
     }
 }
@@ -396,7 +396,7 @@
         }
     } else {
         // is a forwards jump, so need to assume it's large
-        large_jump:
+    large_jump:
         asm_thumb_op32(as, OP_BCC_W_HI(cond, rel), OP_BCC_W_LO(rel));
     }
 }
diff --git a/py/asmthumb.h b/py/asmthumb.h
index c21c23f..6d0ee4b 100644
--- a/py/asmthumb.h
+++ b/py/asmthumb.h
@@ -95,8 +95,9 @@
 void asm_thumb_op16(asm_thumb_t *as, uint op);
 void asm_thumb_op32(asm_thumb_t *as, uint op1, uint op2);
 
-static inline void asm_thumb_it_cc(asm_thumb_t *as, uint cc, uint mask)
-    { asm_thumb_op16(as, ASM_THUMB_OP_IT | (cc << 4) | mask); }
+static inline void asm_thumb_it_cc(asm_thumb_t *as, uint cc, uint mask) {
+    asm_thumb_op16(as, ASM_THUMB_OP_IT | (cc << 4) | mask);
+}
 
 // FORMAT 1: move shifted register
 
@@ -129,14 +130,18 @@
     asm_thumb_op16(as, ASM_THUMB_FORMAT_2_ENCODE(op, rlo_dest, rlo_src, src_b));
 }
 
-static inline void asm_thumb_add_rlo_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, uint rlo_src_b)
-    { asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_ADD | ASM_THUMB_FORMAT_2_REG_OPERAND, rlo_dest, rlo_src_a, rlo_src_b); }
-static inline void asm_thumb_add_rlo_rlo_i3(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, int i3_src)
-    { asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_ADD | ASM_THUMB_FORMAT_2_IMM_OPERAND, rlo_dest, rlo_src_a, i3_src); }
-static inline void asm_thumb_sub_rlo_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, uint rlo_src_b)
-    { asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_SUB | ASM_THUMB_FORMAT_2_REG_OPERAND, rlo_dest, rlo_src_a, rlo_src_b); }
-static inline void asm_thumb_sub_rlo_rlo_i3(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, int i3_src)
-    { asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_SUB | ASM_THUMB_FORMAT_2_IMM_OPERAND, rlo_dest, rlo_src_a, i3_src); }
+static inline void asm_thumb_add_rlo_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, uint rlo_src_b) {
+    asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_ADD | ASM_THUMB_FORMAT_2_REG_OPERAND, rlo_dest, rlo_src_a, rlo_src_b);
+}
+static inline void asm_thumb_add_rlo_rlo_i3(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, int i3_src) {
+    asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_ADD | ASM_THUMB_FORMAT_2_IMM_OPERAND, rlo_dest, rlo_src_a, i3_src);
+}
+static inline void asm_thumb_sub_rlo_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, uint rlo_src_b) {
+    asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_SUB | ASM_THUMB_FORMAT_2_REG_OPERAND, rlo_dest, rlo_src_a, rlo_src_b);
+}
+static inline void asm_thumb_sub_rlo_rlo_i3(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, int i3_src) {
+    asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_SUB | ASM_THUMB_FORMAT_2_IMM_OPERAND, rlo_dest, rlo_src_a, i3_src);
+}
 
 // FORMAT 3: move/compare/add/subtract immediate
 // These instructions all do zero extension of the i8 value
@@ -153,10 +158,18 @@
     asm_thumb_op16(as, ASM_THUMB_FORMAT_3_ENCODE(op, rlo, i8));
 }
 
-static inline void asm_thumb_mov_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_MOV, rlo, i8); }
-static inline void asm_thumb_cmp_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_CMP, rlo, i8); }
-static inline void asm_thumb_add_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_ADD, rlo, i8); }
-static inline void asm_thumb_sub_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_SUB, rlo, i8); }
+static inline void asm_thumb_mov_rlo_i8(asm_thumb_t *as, uint rlo, int i8) {
+    asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_MOV, rlo, i8);
+}
+static inline void asm_thumb_cmp_rlo_i8(asm_thumb_t *as, uint rlo, int i8) {
+    asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_CMP, rlo, i8);
+}
+static inline void asm_thumb_add_rlo_i8(asm_thumb_t *as, uint rlo, int i8) {
+    asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_ADD, rlo, i8);
+}
+static inline void asm_thumb_sub_rlo_i8(asm_thumb_t *as, uint rlo, int i8) {
+    asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_SUB, rlo, i8);
+}
 
 // FORMAT 4: ALU operations
 
@@ -179,7 +192,9 @@
 
 void asm_thumb_format_4(asm_thumb_t *as, uint op, uint rlo_dest, uint rlo_src);
 
-static inline void asm_thumb_cmp_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_src) { asm_thumb_format_4(as, ASM_THUMB_FORMAT_4_CMP, rlo_dest, rlo_src); }
+static inline void asm_thumb_cmp_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_src) {
+    asm_thumb_format_4(as, ASM_THUMB_FORMAT_4_CMP, rlo_dest, rlo_src);
+}
 
 // FORMAT 5: hi register operations (add, cmp, mov, bx)
 // For add/cmp/mov, at least one of the args must be a high register
@@ -219,21 +234,28 @@
 #define ASM_THUMB_FORMAT_9_10_ENCODE(op, rlo_dest, rlo_base, offset) \
     ((op) | (((offset) << 6) & 0x07c0) | ((rlo_base) << 3) | (rlo_dest))
 
-static inline void asm_thumb_format_9_10(asm_thumb_t *as, uint op, uint rlo_dest, uint rlo_base, uint offset)
-    { asm_thumb_op16(as, ASM_THUMB_FORMAT_9_10_ENCODE(op, rlo_dest, rlo_base, offset)); }
+static inline void asm_thumb_format_9_10(asm_thumb_t *as, uint op, uint rlo_dest, uint rlo_base, uint offset) {
+    asm_thumb_op16(as, ASM_THUMB_FORMAT_9_10_ENCODE(op, rlo_dest, rlo_base, offset));
+}
 
-static inline void asm_thumb_str_rlo_rlo_i5(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint word_offset)
-    { asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_STR | ASM_THUMB_FORMAT_9_WORD_TRANSFER, rlo_src, rlo_base, word_offset); }
-static inline void asm_thumb_strb_rlo_rlo_i5(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint byte_offset)
-    { asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_STR | ASM_THUMB_FORMAT_9_BYTE_TRANSFER, rlo_src, rlo_base, byte_offset); }
-static inline void asm_thumb_strh_rlo_rlo_i5(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint byte_offset)
-    { asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_10_STRH, rlo_src, rlo_base, byte_offset); }
-static inline void asm_thumb_ldr_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint word_offset)
-    { asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_LDR | ASM_THUMB_FORMAT_9_WORD_TRANSFER, rlo_dest, rlo_base, word_offset); }
-static inline void asm_thumb_ldrb_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint byte_offset)
-    { asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_LDR | ASM_THUMB_FORMAT_9_BYTE_TRANSFER , rlo_dest, rlo_base, byte_offset); }
-static inline void asm_thumb_ldrh_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint byte_offset)
-    { asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_10_LDRH, rlo_dest, rlo_base, byte_offset); }
+static inline void asm_thumb_str_rlo_rlo_i5(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint word_offset) {
+    asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_STR | ASM_THUMB_FORMAT_9_WORD_TRANSFER, rlo_src, rlo_base, word_offset);
+}
+static inline void asm_thumb_strb_rlo_rlo_i5(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint byte_offset) {
+    asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_STR | ASM_THUMB_FORMAT_9_BYTE_TRANSFER, rlo_src, rlo_base, byte_offset);
+}
+static inline void asm_thumb_strh_rlo_rlo_i5(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint byte_offset) {
+    asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_10_STRH, rlo_src, rlo_base, byte_offset);
+}
+static inline void asm_thumb_ldr_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint word_offset) {
+    asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_LDR | ASM_THUMB_FORMAT_9_WORD_TRANSFER, rlo_dest, rlo_base, word_offset);
+}
+static inline void asm_thumb_ldrb_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint byte_offset) {
+    asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_LDR | ASM_THUMB_FORMAT_9_BYTE_TRANSFER, rlo_dest, rlo_base, byte_offset);
+}
+static inline void asm_thumb_ldrh_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint byte_offset) {
+    asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_10_LDRH, rlo_dest, rlo_base, byte_offset);
+}
 
 // TODO convert these to above format style
 
diff --git a/py/asmx64.c b/py/asmx64.c
index b18703a..f52b028 100644
--- a/py/asmx64.c
+++ b/py/asmx64.c
@@ -123,14 +123,14 @@
 }
 
 STATIC void asm_x64_write_byte_1(asm_x64_t *as, byte b1) {
-    byte* c = asm_x64_get_cur_to_write_bytes(as, 1);
+    byte *c = asm_x64_get_cur_to_write_bytes(as, 1);
     if (c != NULL) {
         c[0] = b1;
     }
 }
 
 STATIC void asm_x64_write_byte_2(asm_x64_t *as, byte b1, byte b2) {
-    byte* c = asm_x64_get_cur_to_write_bytes(as, 2);
+    byte *c = asm_x64_get_cur_to_write_bytes(as, 2);
     if (c != NULL) {
         c[0] = b1;
         c[1] = b2;
@@ -138,7 +138,7 @@
 }
 
 STATIC void asm_x64_write_byte_3(asm_x64_t *as, byte b1, byte b2, byte b3) {
-    byte* c = asm_x64_get_cur_to_write_bytes(as, 3);
+    byte *c = asm_x64_get_cur_to_write_bytes(as, 3);
     if (c != NULL) {
         c[0] = b1;
         c[1] = b2;
@@ -147,7 +147,7 @@
 }
 
 STATIC void asm_x64_write_word32(asm_x64_t *as, int w32) {
-    byte* c = asm_x64_get_cur_to_write_bytes(as, 4);
+    byte *c = asm_x64_get_cur_to_write_bytes(as, 4);
     if (c != NULL) {
         c[0] = IMM32_L0(w32);
         c[1] = IMM32_L1(w32);
@@ -157,7 +157,7 @@
 }
 
 STATIC void asm_x64_write_word64(asm_x64_t *as, int64_t w64) {
-    byte* c = asm_x64_get_cur_to_write_bytes(as, 8);
+    byte *c = asm_x64_get_cur_to_write_bytes(as, 8);
     if (c != NULL) {
         c[0] = IMM32_L0(w64);
         c[1] = IMM32_L1(w64);
@@ -378,11 +378,11 @@
     asm_x64_generic_r64_r64(as, dest_r64, src_r64, OPCODE_XOR_R64_TO_RM64);
 }
 
-void asm_x64_shl_r64_cl(asm_x64_t* as, int dest_r64) {
+void asm_x64_shl_r64_cl(asm_x64_t *as, int dest_r64) {
     asm_x64_generic_r64_r64(as, dest_r64, 4, OPCODE_SHL_RM64_CL);
 }
 
-void asm_x64_sar_r64_cl(asm_x64_t* as, int dest_r64) {
+void asm_x64_sar_r64_cl(asm_x64_t *as, int dest_r64) {
     asm_x64_generic_r64_r64(as, dest_r64, 7, OPCODE_SAR_RM64_CL);
 }
 
@@ -500,7 +500,7 @@
         }
     } else {
         // is a forwards jump, so need to assume it's large
-        large_jump:
+    large_jump:
         rel -= 5;
         asm_x64_write_byte_1(as, OPCODE_JMP_REL32);
         asm_x64_write_word32(as, rel);
@@ -522,7 +522,7 @@
         }
     } else {
         // is a forwards jump, so need to assume it's large
-        large_jump:
+    large_jump:
         rel -= 6;
         asm_x64_write_byte_2(as, OPCODE_JCC_REL32_A, OPCODE_JCC_REL32_B | jcc_type);
         asm_x64_write_word32(as, rel);
diff --git a/py/asmx64.h b/py/asmx64.h
index d3761b7..28b1bd2 100644
--- a/py/asmx64.h
+++ b/py/asmx64.h
@@ -79,12 +79,12 @@
     (void)as;
 }
 
-void asm_x64_nop(asm_x64_t* as);
-void asm_x64_push_r64(asm_x64_t* as, int src_r64);
-void asm_x64_pop_r64(asm_x64_t* as, int dest_r64);
-void asm_x64_mov_r64_r64(asm_x64_t* as, int dest_r64, int src_r64);
+void asm_x64_nop(asm_x64_t *as);
+void asm_x64_push_r64(asm_x64_t *as, int src_r64);
+void asm_x64_pop_r64(asm_x64_t *as, int dest_r64);
+void asm_x64_mov_r64_r64(asm_x64_t *as, int dest_r64, int src_r64);
 size_t asm_x64_mov_i32_to_r64(asm_x64_t *as, int src_i32, int dest_r64);
-void asm_x64_mov_i64_to_r64(asm_x64_t* as, int64_t src_i64, int dest_r64);
+void asm_x64_mov_i64_to_r64(asm_x64_t *as, int64_t src_i64, int dest_r64);
 void asm_x64_mov_i64_to_r64_optimised(asm_x64_t *as, int64_t src_i64, int dest_r64);
 void asm_x64_mov_r8_to_mem8(asm_x64_t *as, int src_r64, int dest_r64, int dest_disp);
 void asm_x64_mov_r16_to_mem16(asm_x64_t *as, int src_r64, int dest_r64, int dest_disp);
@@ -97,25 +97,25 @@
 void asm_x64_and_r64_r64(asm_x64_t *as, int dest_r64, int src_r64);
 void asm_x64_or_r64_r64(asm_x64_t *as, int dest_r64, int src_r64);
 void asm_x64_xor_r64_r64(asm_x64_t *as, int dest_r64, int src_r64);
-void asm_x64_shl_r64_cl(asm_x64_t* as, int dest_r64);
-void asm_x64_sar_r64_cl(asm_x64_t* as, int dest_r64);
-void asm_x64_add_r64_r64(asm_x64_t* as, int dest_r64, int src_r64);
-void asm_x64_sub_r64_r64(asm_x64_t* as, int dest_r64, int src_r64);
-void asm_x64_mul_r64_r64(asm_x64_t* as, int dest_r64, int src_r64);
-void asm_x64_cmp_r64_with_r64(asm_x64_t* as, int src_r64_a, int src_r64_b);
-void asm_x64_test_r8_with_r8(asm_x64_t* as, int src_r64_a, int src_r64_b);
+void asm_x64_shl_r64_cl(asm_x64_t *as, int dest_r64);
+void asm_x64_sar_r64_cl(asm_x64_t *as, int dest_r64);
+void asm_x64_add_r64_r64(asm_x64_t *as, int dest_r64, int src_r64);
+void asm_x64_sub_r64_r64(asm_x64_t *as, int dest_r64, int src_r64);
+void asm_x64_mul_r64_r64(asm_x64_t *as, int dest_r64, int src_r64);
+void asm_x64_cmp_r64_with_r64(asm_x64_t *as, int src_r64_a, int src_r64_b);
+void asm_x64_test_r8_with_r8(asm_x64_t *as, int src_r64_a, int src_r64_b);
 void asm_x64_test_r64_with_r64(asm_x64_t *as, int src_r64_a, int src_r64_b);
-void asm_x64_setcc_r8(asm_x64_t* as, int jcc_type, int dest_r8);
+void asm_x64_setcc_r8(asm_x64_t *as, int jcc_type, int dest_r8);
 void asm_x64_jmp_reg(asm_x64_t *as, int src_r64);
-void asm_x64_jmp_label(asm_x64_t* as, mp_uint_t label);
-void asm_x64_jcc_label(asm_x64_t* as, int jcc_type, mp_uint_t label);
-void asm_x64_entry(asm_x64_t* as, int num_locals);
-void asm_x64_exit(asm_x64_t* as);
-void asm_x64_mov_local_to_r64(asm_x64_t* as, int src_local_num, int dest_r64);
-void asm_x64_mov_r64_to_local(asm_x64_t* as, int src_r64, int dest_local_num);
-void asm_x64_mov_local_addr_to_r64(asm_x64_t* as, int local_num, int dest_r64);
+void asm_x64_jmp_label(asm_x64_t *as, mp_uint_t label);
+void asm_x64_jcc_label(asm_x64_t *as, int jcc_type, mp_uint_t label);
+void asm_x64_entry(asm_x64_t *as, int num_locals);
+void asm_x64_exit(asm_x64_t *as);
+void asm_x64_mov_local_to_r64(asm_x64_t *as, int src_local_num, int dest_r64);
+void asm_x64_mov_r64_to_local(asm_x64_t *as, int src_r64, int dest_local_num);
+void asm_x64_mov_local_addr_to_r64(asm_x64_t *as, int local_num, int dest_r64);
 void asm_x64_mov_reg_pcrel(asm_x64_t *as, int dest_r64, mp_uint_t label);
-void asm_x64_call_ind(asm_x64_t* as, size_t fun_id, int temp_r32);
+void asm_x64_call_ind(asm_x64_t *as, size_t fun_id, int temp_r32);
 
 // Holds a pointer to mp_fun_table
 #define ASM_X64_REG_FUN_TABLE ASM_X64_REG_RBP
diff --git a/py/asmx86.c b/py/asmx86.c
index e69d06d..4a8be3f 100644
--- a/py/asmx86.c
+++ b/py/asmx86.c
@@ -103,14 +103,14 @@
 #define SIGNED_FIT8(x) (((x) & 0xffffff80) == 0) || (((x) & 0xffffff80) == 0xffffff80)
 
 STATIC void asm_x86_write_byte_1(asm_x86_t *as, byte b1) {
-    byte* c = mp_asm_base_get_cur_to_write_bytes(&as->base, 1);
+    byte *c = mp_asm_base_get_cur_to_write_bytes(&as->base, 1);
     if (c != NULL) {
         c[0] = b1;
     }
 }
 
 STATIC void asm_x86_write_byte_2(asm_x86_t *as, byte b1, byte b2) {
-    byte* c = mp_asm_base_get_cur_to_write_bytes(&as->base, 2);
+    byte *c = mp_asm_base_get_cur_to_write_bytes(&as->base, 2);
     if (c != NULL) {
         c[0] = b1;
         c[1] = b2;
@@ -118,7 +118,7 @@
 }
 
 STATIC void asm_x86_write_byte_3(asm_x86_t *as, byte b1, byte b2, byte b3) {
-    byte* c = mp_asm_base_get_cur_to_write_bytes(&as->base, 3);
+    byte *c = mp_asm_base_get_cur_to_write_bytes(&as->base, 3);
     if (c != NULL) {
         c[0] = b1;
         c[1] = b2;
@@ -127,7 +127,7 @@
 }
 
 STATIC void asm_x86_write_word32(asm_x86_t *as, int w32) {
-    byte* c = mp_asm_base_get_cur_to_write_bytes(&as->base, 4);
+    byte *c = mp_asm_base_get_cur_to_write_bytes(&as->base, 4);
     if (c != NULL) {
         c[0] = IMM32_L0(w32);
         c[1] = IMM32_L1(w32);
@@ -255,11 +255,11 @@
     asm_x86_generic_r32_r32(as, dest_r32, src_r32, OPCODE_XOR_R32_TO_RM32);
 }
 
-void asm_x86_shl_r32_cl(asm_x86_t* as, int dest_r32) {
+void asm_x86_shl_r32_cl(asm_x86_t *as, int dest_r32) {
     asm_x86_generic_r32_r32(as, dest_r32, 4, OPCODE_SHL_RM32_CL);
 }
 
-void asm_x86_sar_r32_cl(asm_x86_t* as, int dest_r32) {
+void asm_x86_sar_r32_cl(asm_x86_t *as, int dest_r32) {
     asm_x86_generic_r32_r32(as, dest_r32, 7, OPCODE_SAR_RM32_CL);
 }
 
@@ -368,7 +368,7 @@
         }
     } else {
         // is a forwards jump, so need to assume it's large
-        large_jump:
+    large_jump:
         rel -= 5;
         asm_x86_write_byte_1(as, OPCODE_JMP_REL32);
         asm_x86_write_word32(as, rel);
@@ -390,7 +390,7 @@
         }
     } else {
         // is a forwards jump, so need to assume it's large
-        large_jump:
+    large_jump:
         rel -= 6;
         asm_x86_write_byte_2(as, OPCODE_JCC_REL32_A, OPCODE_JCC_REL32_B | jcc_type);
         asm_x86_write_word32(as, rel);
@@ -488,8 +488,7 @@
     asm_x86_push_disp(as, ASM_X86_REG_ESP, asm_x86_local_offset_from_esp(as, local_num));
 }
 
-void asm_x86_push_local_addr(asm_x86_t *as, int local_num, int temp_r32)
-{
+void asm_x86_push_local_addr(asm_x86_t *as, int local_num, int temp_r32) {
     asm_x86_mov_r32_r32(as, temp_r32, ASM_X86_REG_ESP);
     asm_x86_add_i32_to_r32(as, asm_x86_local_offset_from_esp(as, local_num), temp_r32);
     asm_x86_push_r32(as, temp_r32);
diff --git a/py/asmx86.h b/py/asmx86.h
index abcea18..4855cd7 100644
--- a/py/asmx86.h
+++ b/py/asmx86.h
@@ -81,7 +81,7 @@
     (void)as;
 }
 
-void asm_x86_mov_r32_r32(asm_x86_t* as, int dest_r32, int src_r32);
+void asm_x86_mov_r32_r32(asm_x86_t *as, int dest_r32, int src_r32);
 size_t asm_x86_mov_i32_to_r32(asm_x86_t *as, int32_t src_i32, int dest_r32);
 void asm_x86_mov_r8_to_mem8(asm_x86_t *as, int src_r32, int dest_r32, int dest_disp);
 void asm_x86_mov_r16_to_mem16(asm_x86_t *as, int src_r32, int dest_r32, int dest_disp);
@@ -92,26 +92,26 @@
 void asm_x86_and_r32_r32(asm_x86_t *as, int dest_r32, int src_r32);
 void asm_x86_or_r32_r32(asm_x86_t *as, int dest_r32, int src_r32);
 void asm_x86_xor_r32_r32(asm_x86_t *as, int dest_r32, int src_r32);
-void asm_x86_shl_r32_cl(asm_x86_t* as, int dest_r32);
-void asm_x86_sar_r32_cl(asm_x86_t* as, int dest_r32);
-void asm_x86_add_r32_r32(asm_x86_t* as, int dest_r32, int src_r32);
-void asm_x86_sub_r32_r32(asm_x86_t* as, int dest_r32, int src_r32);
-void asm_x86_mul_r32_r32(asm_x86_t* as, int dest_r32, int src_r32);
-void asm_x86_cmp_r32_with_r32(asm_x86_t* as, int src_r32_a, int src_r32_b);
-void asm_x86_test_r8_with_r8(asm_x86_t* as, int src_r32_a, int src_r32_b);
-void asm_x86_test_r32_with_r32(asm_x86_t* as, int src_r32_a, int src_r32_b);
-void asm_x86_setcc_r8(asm_x86_t* as, mp_uint_t jcc_type, int dest_r8);
+void asm_x86_shl_r32_cl(asm_x86_t *as, int dest_r32);
+void asm_x86_sar_r32_cl(asm_x86_t *as, int dest_r32);
+void asm_x86_add_r32_r32(asm_x86_t *as, int dest_r32, int src_r32);
+void asm_x86_sub_r32_r32(asm_x86_t *as, int dest_r32, int src_r32);
+void asm_x86_mul_r32_r32(asm_x86_t *as, int dest_r32, int src_r32);
+void asm_x86_cmp_r32_with_r32(asm_x86_t *as, int src_r32_a, int src_r32_b);
+void asm_x86_test_r8_with_r8(asm_x86_t *as, int src_r32_a, int src_r32_b);
+void asm_x86_test_r32_with_r32(asm_x86_t *as, int src_r32_a, int src_r32_b);
+void asm_x86_setcc_r8(asm_x86_t *as, mp_uint_t jcc_type, int dest_r8);
 void asm_x86_jmp_reg(asm_x86_t *as, int src_r86);
-void asm_x86_jmp_label(asm_x86_t* as, mp_uint_t label);
-void asm_x86_jcc_label(asm_x86_t* as, mp_uint_t jcc_type, mp_uint_t label);
-void asm_x86_entry(asm_x86_t* as, int num_locals);
-void asm_x86_exit(asm_x86_t* as);
+void asm_x86_jmp_label(asm_x86_t *as, mp_uint_t label);
+void asm_x86_jcc_label(asm_x86_t *as, mp_uint_t jcc_type, mp_uint_t label);
+void asm_x86_entry(asm_x86_t *as, int num_locals);
+void asm_x86_exit(asm_x86_t *as);
 void asm_x86_mov_arg_to_r32(asm_x86_t *as, int src_arg_num, int dest_r32);
-void asm_x86_mov_local_to_r32(asm_x86_t* as, int src_local_num, int dest_r32);
-void asm_x86_mov_r32_to_local(asm_x86_t* as, int src_r32, int dest_local_num);
-void asm_x86_mov_local_addr_to_r32(asm_x86_t* as, int local_num, int dest_r32);
+void asm_x86_mov_local_to_r32(asm_x86_t *as, int src_local_num, int dest_r32);
+void asm_x86_mov_r32_to_local(asm_x86_t *as, int src_r32, int dest_local_num);
+void asm_x86_mov_local_addr_to_r32(asm_x86_t *as, int local_num, int dest_r32);
 void asm_x86_mov_reg_pcrel(asm_x86_t *as, int dest_r64, mp_uint_t label);
-void asm_x86_call_ind(asm_x86_t* as, size_t fun_id, mp_uint_t n_args, int temp_r32);
+void asm_x86_call_ind(asm_x86_t *as, size_t fun_id, mp_uint_t n_args, int temp_r32);
 
 // Holds a pointer to mp_fun_table
 #define ASM_X86_REG_FUN_TABLE ASM_X86_REG_EBP
diff --git a/py/asmxtensa.c b/py/asmxtensa.c
index 32e5e95..0956d50 100644
--- a/py/asmxtensa.c
+++ b/py/asmxtensa.c
@@ -65,7 +65,7 @@
     // jump over the constants
     asm_xtensa_op_j(as, as->num_const * WORD_SIZE + 4 - 4);
     mp_asm_base_get_cur_to_write_bytes(&as->base, 1); // padding/alignment byte
-    as->const_table = (uint32_t*)mp_asm_base_get_cur_to_write_bytes(&as->base, as->num_const * 4);
+    as->const_table = (uint32_t *)mp_asm_base_get_cur_to_write_bytes(&as->base, as->num_const * 4);
 
     // adjust the stack-pointer to store a0, a12, a13, a14, a15 and locals, 16-byte aligned
     as->stack_adjust = (((ASM_XTENSA_NUM_REGS_SAVED + num_locals) * WORD_SIZE) + 15) & ~15;
@@ -105,7 +105,7 @@
     // jump over the constants
     asm_xtensa_op_j(as, as->num_const * WORD_SIZE + 4 - 4);
     mp_asm_base_get_cur_to_write_bytes(&as->base, 1); // padding/alignment byte
-    as->const_table = (uint32_t*)mp_asm_base_get_cur_to_write_bytes(&as->base, as->num_const * 4);
+    as->const_table = (uint32_t *)mp_asm_base_get_cur_to_write_bytes(&as->base, as->num_const * 4);
 
     as->stack_adjust = 32 + ((((ASM_XTENSA_NUM_REGS_SAVED_WIN + num_locals) * WORD_SIZE) + 15) & ~15);
     asm_xtensa_op_entry(as, ASM_XTENSA_REG_A1, as->stack_adjust);
@@ -173,7 +173,7 @@
 
 size_t asm_xtensa_mov_reg_i32(asm_xtensa_t *as, uint reg_dest, uint32_t i32) {
     // load the constant
-    uint32_t const_table_offset = (uint8_t*)as->const_table - as->base.code_base;
+    uint32_t const_table_offset = (uint8_t *)as->const_table - as->base.code_base;
     size_t loc = const_table_offset + as->cur_const * WORD_SIZE;
     asm_xtensa_op_l32r(as, reg_dest, as->base.code_offset, loc);
     // store the constant in the table
diff --git a/py/bc.c b/py/bc.c
index 417ac3c..34b9284 100644
--- a/py/bc.c
+++ b/py/bc.c
@@ -75,21 +75,21 @@
 #endif
 
 STATIC NORETURN void fun_pos_args_mismatch(mp_obj_fun_bc_t *f, size_t expected, size_t given) {
-#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE
+    #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE
     // generic message, used also for other argument issues
     (void)f;
     (void)expected;
     (void)given;
     mp_arg_error_terse_mismatch();
-#elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL
+    #elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL
     (void)f;
     mp_raise_msg_varg(&mp_type_TypeError,
         "function takes %d positional arguments but %d were given", expected, given);
-#elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED
+    #elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED
     mp_raise_msg_varg(&mp_type_TypeError,
         "%q() takes %d positional arguments but %d were given",
         mp_obj_fun_get_name(MP_OBJ_FROM_PTR(f)), expected, given);
-#endif
+    #endif
 }
 
 #if DEBUG_PRINT
@@ -195,7 +195,7 @@
         }
 
         // get pointer to arg_names array
-        const mp_obj_t *arg_names = (const mp_obj_t*)self->const_table;
+        const mp_obj_t *arg_names = (const mp_obj_t *)self->const_table;
 
         for (size_t i = 0; i < n_kw; i++) {
             // the keys in kwargs are expected to be qstr objects
@@ -220,7 +220,7 @@
                 }
             }
             mp_obj_dict_store(dict, kwargs[2 * i], kwargs[2 * i + 1]);
-continue2:;
+        continue2:;
         }
 
         DEBUG_printf("Args with kws flattened: ");
@@ -252,7 +252,7 @@
             if (code_state->state[n_state - 1 - n_pos_args - i] == MP_OBJ_NULL) {
                 mp_map_elem_t *elem = NULL;
                 if ((scope_flags & MP_SCOPE_FLAG_DEFKWARGS) != 0) {
-                    elem = mp_map_lookup(&((mp_obj_dict_t*)MP_OBJ_TO_PTR(self->extra_args[n_def_pos_args]))->map, arg_names[n_pos_args + i], MP_MAP_LOOKUP);
+                    elem = mp_map_lookup(&((mp_obj_dict_t *)MP_OBJ_TO_PTR(self->extra_args[n_def_pos_args]))->map, arg_names[n_pos_args + i], MP_MAP_LOOKUP);
                 }
                 if (elem != NULL) {
                     code_state->state[n_state - 1 - n_pos_args - i] = elem->value;
diff --git a/py/bc.h b/py/bc.h
index a96d17a..65af407 100644
--- a/py/bc.h
+++ b/py/bc.h
@@ -72,94 +72,94 @@
 //  constN          : obj
 
 #define MP_BC_PRELUDE_SIG_ENCODE(S, E, scope, out_byte, out_env) \
-do {                                                            \
-    /*// Get values to store in prelude */                      \
-    size_t F = scope->scope_flags & MP_SCOPE_FLAG_ALL_SIG;      \
-    size_t A = scope->num_pos_args;                             \
-    size_t K = scope->num_kwonly_args;                          \
-    size_t D = scope->num_def_pos_args;                         \
+    do {                                                            \
+        /*// Get values to store in prelude */                      \
+        size_t F = scope->scope_flags & MP_SCOPE_FLAG_ALL_SIG;      \
+        size_t A = scope->num_pos_args;                             \
+        size_t K = scope->num_kwonly_args;                          \
+        size_t D = scope->num_def_pos_args;                         \
                                                                 \
-    /* Adjust S to shrink range, to compress better */          \
-    S -= 1;                                                     \
+        /* Adjust S to shrink range, to compress better */          \
+        S -= 1;                                                     \
                                                                 \
-    /* Encode prelude */                                        \
-    /* xSSSSEAA */                                              \
-    uint8_t z = (S & 0xf) << 3 | (E & 1) << 2 | (A & 3);        \
-    S >>= 4;                                                    \
-    E >>= 1;                                                    \
-    A >>= 2;                                                    \
-    while (S | E | F | A | K | D) {                             \
-        out_byte(out_env, 0x80 | z);                            \
-        /* xFSSKAED */                                          \
-        z = (F & 1) << 6 | (S & 3) << 4 | (K & 1) << 3          \
-            | (A & 1) << 2 | (E & 1) << 1 | (D & 1);            \
-        S >>= 2;                                                \
-        E >>= 1;                                                \
-        F >>= 1;                                                \
-        A >>= 1;                                                \
-        K >>= 1;                                                \
-        D >>= 1;                                                \
-    }                                                           \
-    out_byte(out_env, z);                                       \
-} while (0)
+        /* Encode prelude */                                        \
+        /* xSSSSEAA */                                              \
+        uint8_t z = (S & 0xf) << 3 | (E & 1) << 2 | (A & 3);        \
+        S >>= 4;                                                    \
+        E >>= 1;                                                    \
+        A >>= 2;                                                    \
+        while (S | E | F | A | K | D) {                             \
+            out_byte(out_env, 0x80 | z);                            \
+            /* xFSSKAED */                                          \
+            z = (F & 1) << 6 | (S & 3) << 4 | (K & 1) << 3          \
+                | (A & 1) << 2 | (E & 1) << 1 | (D & 1);            \
+            S >>= 2;                                                \
+            E >>= 1;                                                \
+            F >>= 1;                                                \
+            A >>= 1;                                                \
+            K >>= 1;                                                \
+            D >>= 1;                                                \
+        }                                                           \
+        out_byte(out_env, z);                                       \
+    } while (0)
 
 #define MP_BC_PRELUDE_SIG_DECODE_INTO(ip, S, E, F, A, K, D)     \
-do {                                                            \
-    uint8_t z = *(ip)++;                                        \
-    /* xSSSSEAA */                                              \
-    S = (z >> 3) & 0xf;                                         \
-    E = (z >> 2) & 0x1;                                         \
-    F = 0;                                                      \
-    A = z & 0x3;                                                \
-    K = 0;                                                      \
-    D = 0;                                                      \
-    for (unsigned n = 0; z & 0x80; ++n) {                       \
-        z = *(ip)++;                                            \
-        /* xFSSKAED */                                          \
-        S |= (z & 0x30) << (2 * n);                             \
-        E |= (z & 0x02) << n;                                   \
-        F |= ((z & 0x40) >> 6) << n;                            \
-        A |= (z & 0x4) << n;                                    \
-        K |= ((z & 0x08) >> 3) << n;                            \
-        D |= (z & 0x1) << n;                                    \
-    }                                                           \
-    S += 1;                                                     \
-} while (0)
+    do {                                                            \
+        uint8_t z = *(ip)++;                                        \
+        /* xSSSSEAA */                                              \
+        S = (z >> 3) & 0xf;                                         \
+        E = (z >> 2) & 0x1;                                         \
+        F = 0;                                                      \
+        A = z & 0x3;                                                \
+        K = 0;                                                      \
+        D = 0;                                                      \
+        for (unsigned n = 0; z & 0x80; ++n) {                       \
+            z = *(ip)++;                                            \
+            /* xFSSKAED */                                          \
+            S |= (z & 0x30) << (2 * n);                             \
+            E |= (z & 0x02) << n;                                   \
+            F |= ((z & 0x40) >> 6) << n;                            \
+            A |= (z & 0x4) << n;                                    \
+            K |= ((z & 0x08) >> 3) << n;                            \
+            D |= (z & 0x1) << n;                                    \
+        }                                                           \
+        S += 1;                                                     \
+    } while (0)
 
 #define MP_BC_PRELUDE_SIG_DECODE(ip) \
     size_t n_state, n_exc_stack, scope_flags, n_pos_args, n_kwonly_args, n_def_pos_args; \
     MP_BC_PRELUDE_SIG_DECODE_INTO(ip, n_state, n_exc_stack, scope_flags, n_pos_args, n_kwonly_args, n_def_pos_args)
 
 #define MP_BC_PRELUDE_SIZE_ENCODE(I, C, out_byte, out_env)      \
-do {                                                            \
-    /* Encode bit-wise as: xIIIIIIC */                          \
-    uint8_t z = 0;                                              \
-    do {                                                        \
-        z = (I & 0x3f) << 1 | (C & 1);                          \
-        C >>= 1;                                                \
-        I >>= 6;                                                \
-        if (C | I) {                                            \
-            z |= 0x80;                                          \
-        }                                                       \
-        out_byte(out_env, z);                                   \
-    } while (C | I);                                            \
-} while (0)
+    do {                                                            \
+        /* Encode bit-wise as: xIIIIIIC */                          \
+        uint8_t z = 0;                                              \
+        do {                                                        \
+            z = (I & 0x3f) << 1 | (C & 1);                          \
+            C >>= 1;                                                \
+            I >>= 6;                                                \
+            if (C | I) {                                            \
+                z |= 0x80;                                          \
+            }                                                       \
+            out_byte(out_env, z);                                   \
+        } while (C | I);                                            \
+    } while (0)
 
 #define MP_BC_PRELUDE_SIZE_DECODE_INTO(ip, I, C)                \
-do {                                                            \
-    uint8_t z;                                                  \
-    C = 0;                                                      \
-    I = 0;                                                      \
-    for (unsigned n = 0;; ++n) {                                \
-        z = *(ip)++;                                            \
-        /* xIIIIIIC */                                          \
-        C |= (z & 1) << n;                                      \
-        I |= ((z & 0x7e) >> 1) << (6 * n);                      \
-        if (!(z & 0x80)) {                                      \
-            break;                                              \
-        }                                                       \
-    }                                                           \
-} while (0)
+    do {                                                            \
+        uint8_t z;                                                  \
+        C = 0;                                                      \
+        I = 0;                                                      \
+        for (unsigned n = 0;; ++n) {                                \
+            z = *(ip)++;                                            \
+            /* xIIIIIIC */                                          \
+            C |= (z & 1) << n;                                      \
+            I |= ((z & 0x7e) >> 1) << (6 * n);                      \
+            if (!(z & 0x80)) {                                      \
+                break;                                              \
+            }                                                       \
+        }                                                           \
+    } while (0)
 
 #define MP_BC_PRELUDE_SIZE_DECODE(ip) \
     size_t n_info, n_cell; \
@@ -232,10 +232,10 @@
 #define mp_bytecode_print_inst(code, const_table) mp_bytecode_print2(code, 1, const_table)
 
 // Helper macros to access pointer with least significant bits holding flags
-#define MP_TAGPTR_PTR(x) ((void*)((uintptr_t)(x) & ~((uintptr_t)3)))
+#define MP_TAGPTR_PTR(x) ((void *)((uintptr_t)(x) & ~((uintptr_t)3)))
 #define MP_TAGPTR_TAG0(x) ((uintptr_t)(x) & 1)
 #define MP_TAGPTR_TAG1(x) ((uintptr_t)(x) & 2)
-#define MP_TAGPTR_MAKE(ptr, tag) ((void*)((uintptr_t)(ptr) | (tag)))
+#define MP_TAGPTR_MAKE(ptr, tag) ((void *)((uintptr_t)(ptr) | (tag)))
 
 #if MICROPY_PERSISTENT_CODE_LOAD || MICROPY_PERSISTENT_CODE_SAVE
 
diff --git a/py/binary.c b/py/binary.c
index a8907bf..faa4135 100644
--- a/py/binary.c
+++ b/py/binary.c
@@ -46,24 +46,40 @@
     size_t size = 0;
     int align = 1;
     switch (struct_type) {
-        case '<': case '>':
+        case '<':
+        case '>':
             switch (val_type) {
-                case 'b': case 'B':
-                    size = 1; break;
-                case 'h': case 'H':
-                    size = 2; break;
-                case 'i': case 'I':
-                    size = 4; break;
-                case 'l': case 'L':
-                    size = 4; break;
-                case 'q': case 'Q':
-                    size = 8; break;
-                case 'P': case 'O': case 'S':
-                    size = sizeof(void*); break;
+                case 'b':
+                case 'B':
+                    size = 1;
+                    break;
+                case 'h':
+                case 'H':
+                    size = 2;
+                    break;
+                case 'i':
+                case 'I':
+                    size = 4;
+                    break;
+                case 'l':
+                case 'L':
+                    size = 4;
+                    break;
+                case 'q':
+                case 'Q':
+                    size = 8;
+                    break;
+                case 'P':
+                case 'O':
+                case 'S':
+                    size = sizeof(void *);
+                    break;
                 case 'f':
-                    size = sizeof(float); break;
+                    size = sizeof(float);
+                    break;
                 case 'd':
-                    size = sizeof(double); break;
+                    size = sizeof(double);
+                    break;
             }
             break;
         case '@': {
@@ -76,29 +92,44 @@
             // particular (or any) ABI.
             switch (val_type) {
                 case BYTEARRAY_TYPECODE:
-                case 'b': case 'B':
-                    align = size = 1; break;
-                case 'h': case 'H':
+                case 'b':
+                case 'B':
+                    align = size = 1;
+                    break;
+                case 'h':
+                case 'H':
                     align = alignof(short);
-                    size = sizeof(short); break;
-                case 'i': case 'I':
+                    size = sizeof(short);
+                    break;
+                case 'i':
+                case 'I':
                     align = alignof(int);
-                    size = sizeof(int); break;
-                case 'l': case 'L':
+                    size = sizeof(int);
+                    break;
+                case 'l':
+                case 'L':
                     align = alignof(long);
-                    size = sizeof(long); break;
-                case 'q': case 'Q':
+                    size = sizeof(long);
+                    break;
+                case 'q':
+                case 'Q':
                     align = alignof(long long);
-                    size = sizeof(long long); break;
-                case 'P': case 'O': case 'S':
-                    align = alignof(void*);
-                    size = sizeof(void*); break;
+                    size = sizeof(long long);
+                    break;
+                case 'P':
+                case 'O':
+                case 'S':
+                    align = alignof(void *);
+                    size = sizeof(void *);
+                    break;
                 case 'f':
                     align = alignof(float);
-                    size = sizeof(float); break;
+                    size = sizeof(float);
+                    break;
                 case 'd':
                     align = alignof(double);
-                    size = sizeof(double); break;
+                    size = sizeof(double);
+                    break;
             }
         }
     }
@@ -117,44 +148,44 @@
     mp_int_t val = 0;
     switch (typecode) {
         case 'b':
-            val = ((signed char*)p)[index];
+            val = ((signed char *)p)[index];
             break;
         case BYTEARRAY_TYPECODE:
         case 'B':
-            val = ((unsigned char*)p)[index];
+            val = ((unsigned char *)p)[index];
             break;
         case 'h':
-            val = ((short*)p)[index];
+            val = ((short *)p)[index];
             break;
         case 'H':
-            val = ((unsigned short*)p)[index];
+            val = ((unsigned short *)p)[index];
             break;
         case 'i':
-            return mp_obj_new_int(((int*)p)[index]);
+            return mp_obj_new_int(((int *)p)[index]);
         case 'I':
-            return mp_obj_new_int_from_uint(((unsigned int*)p)[index]);
+            return mp_obj_new_int_from_uint(((unsigned int *)p)[index]);
         case 'l':
-            return mp_obj_new_int(((long*)p)[index]);
+            return mp_obj_new_int(((long *)p)[index]);
         case 'L':
-            return mp_obj_new_int_from_uint(((unsigned long*)p)[index]);
+            return mp_obj_new_int_from_uint(((unsigned long *)p)[index]);
         #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE
         case 'q':
-            return mp_obj_new_int_from_ll(((long long*)p)[index]);
+            return mp_obj_new_int_from_ll(((long long *)p)[index]);
         case 'Q':
-            return mp_obj_new_int_from_ull(((unsigned long long*)p)[index]);
+            return mp_obj_new_int_from_ull(((unsigned long long *)p)[index]);
         #endif
-#if MICROPY_PY_BUILTINS_FLOAT
+        #if MICROPY_PY_BUILTINS_FLOAT
         case 'f':
-            return mp_obj_new_float(((float*)p)[index]);
+            return mp_obj_new_float(((float *)p)[index]);
         case 'd':
-            return mp_obj_new_float(((double*)p)[index]);
-#endif
+            return mp_obj_new_float(((double *)p)[index]);
+        #endif
         // Extension to CPython: array of objects
         case 'O':
-            return ((mp_obj_t*)p)[index];
+            return ((mp_obj_t *)p)[index];
         // Extension to CPython: array of pointers
         case 'P':
-            return mp_obj_new_int((mp_int_t)(uintptr_t)((void**)p)[index]);
+            return mp_obj_new_int((mp_int_t)(uintptr_t)((void **)p)[index]);
     }
     return MP_OBJ_NEW_SMALL_INT(val);
 }
@@ -206,16 +237,20 @@
     if (val_type == 'O') {
         return (mp_obj_t)(mp_uint_t)val;
     } else if (val_type == 'S') {
-        const char *s_val = (const char*)(uintptr_t)(mp_uint_t)val;
+        const char *s_val = (const char *)(uintptr_t)(mp_uint_t)val;
         return mp_obj_new_str(s_val, strlen(s_val));
-#if MICROPY_PY_BUILTINS_FLOAT
+    #if MICROPY_PY_BUILTINS_FLOAT
     } else if (val_type == 'f') {
-        union { uint32_t i; float f; } fpu = {val};
+        union { uint32_t i;
+                float f;
+        } fpu = {val};
         return mp_obj_new_float(fpu.f);
     } else if (val_type == 'd') {
-        union { uint64_t i; double f; } fpu = {val};
+        union { uint64_t i;
+                double f;
+        } fpu = {val};
         return mp_obj_new_float(fpu.f);
-#endif
+    #endif
     } else if (is_signed(val_type)) {
         if ((long long)MP_SMALL_INT_MIN <= val && val <= (long long)MP_SMALL_INT_MAX) {
             return mp_obj_new_int((mp_int_t)val);
@@ -236,13 +271,13 @@
         memcpy(dest, &val, val_sz);
     } else if (MP_ENDIANNESS_BIG && big_endian) {
         // only copy the least-significant val_sz bytes
-        memcpy(dest, (byte*)&val + sizeof(mp_uint_t) - val_sz, val_sz);
+        memcpy(dest, (byte *)&val + sizeof(mp_uint_t) - val_sz, val_sz);
     } else {
         const byte *src;
         if (MP_ENDIANNESS_LITTLE) {
-            src = (const byte*)&val + val_sz;
+            src = (const byte *)&val + val_sz;
         } else {
-            src = (const byte*)&val + sizeof(mp_uint_t);
+            src = (const byte *)&val + sizeof(mp_uint_t);
         }
         while (val_sz--) {
             *dest++ = *--src;
@@ -271,15 +306,20 @@
         case 'O':
             val = (mp_uint_t)val_in;
             break;
-#if MICROPY_PY_BUILTINS_FLOAT
+        #if MICROPY_PY_BUILTINS_FLOAT
         case 'f': {
-            union { uint32_t i; float f; } fp_sp;
+            union { uint32_t i;
+                    float f;
+            } fp_sp;
             fp_sp.f = mp_obj_get_float(val_in);
             val = fp_sp.i;
             break;
         }
         case 'd': {
-            union { uint64_t i64; uint32_t i32[2]; double f; } fp_dp;
+            union { uint64_t i64;
+                    uint32_t i32[2];
+                    double f;
+            } fp_dp;
             fp_dp.f = mp_obj_get_float(val_in);
             if (BYTES_PER_WORD == 8) {
                 val = fp_dp.i64;
@@ -291,7 +331,7 @@
             }
             break;
         }
-#endif
+        #endif
         default:
             #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE
             if (mp_obj_is_type(val_in, &mp_type_int)) {
@@ -317,24 +357,24 @@
 
 void mp_binary_set_val_array(char typecode, void *p, size_t index, mp_obj_t val_in) {
     switch (typecode) {
-#if MICROPY_PY_BUILTINS_FLOAT
+        #if MICROPY_PY_BUILTINS_FLOAT
         case 'f':
-            ((float*)p)[index] = mp_obj_get_float(val_in);
+            ((float *)p)[index] = mp_obj_get_float(val_in);
             break;
         case 'd':
-            ((double*)p)[index] = mp_obj_get_float(val_in);
+            ((double *)p)[index] = mp_obj_get_float(val_in);
             break;
-#endif
+        #endif
         // Extension to CPython: array of objects
         case 'O':
-            ((mp_obj_t*)p)[index] = val_in;
+            ((mp_obj_t *)p)[index] = val_in;
             break;
         default:
             #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE
             if (mp_obj_is_type(val_in, &mp_type_int)) {
                 size_t size = mp_binary_get_size('@', typecode, NULL);
                 mp_obj_int_to_bytes_impl(val_in, MP_ENDIANNESS_BIG,
-                    size, (uint8_t*)p + index * size);
+                    size, (uint8_t *)p + index * size);
                 return;
             }
             #endif
@@ -345,49 +385,49 @@
 void mp_binary_set_val_array_from_int(char typecode, void *p, size_t index, mp_int_t val) {
     switch (typecode) {
         case 'b':
-            ((signed char*)p)[index] = val;
+            ((signed char *)p)[index] = val;
             break;
         case BYTEARRAY_TYPECODE:
         case 'B':
-            ((unsigned char*)p)[index] = val;
+            ((unsigned char *)p)[index] = val;
             break;
         case 'h':
-            ((short*)p)[index] = val;
+            ((short *)p)[index] = val;
             break;
         case 'H':
-            ((unsigned short*)p)[index] = val;
+            ((unsigned short *)p)[index] = val;
             break;
         case 'i':
-            ((int*)p)[index] = val;
+            ((int *)p)[index] = val;
             break;
         case 'I':
-            ((unsigned int*)p)[index] = val;
+            ((unsigned int *)p)[index] = val;
             break;
         case 'l':
-            ((long*)p)[index] = val;
+            ((long *)p)[index] = val;
             break;
         case 'L':
-            ((unsigned long*)p)[index] = val;
+            ((unsigned long *)p)[index] = val;
             break;
         #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE
         case 'q':
-            ((long long*)p)[index] = val;
+            ((long long *)p)[index] = val;
             break;
         case 'Q':
-            ((unsigned long long*)p)[index] = val;
+            ((unsigned long long *)p)[index] = val;
             break;
         #endif
-#if MICROPY_PY_BUILTINS_FLOAT
+        #if MICROPY_PY_BUILTINS_FLOAT
         case 'f':
-            ((float*)p)[index] = val;
+            ((float *)p)[index] = val;
             break;
         case 'd':
-            ((double*)p)[index] = val;
+            ((double *)p)[index] = val;
             break;
-#endif
+        #endif
         // Extension to CPython: array of pointers
         case 'P':
-            ((void**)p)[index] = (void*)(uintptr_t)val;
+            ((void **)p)[index] = (void *)(uintptr_t)val;
             break;
     }
 }
diff --git a/py/builtinevex.c b/py/builtinevex.c
index 819e3e1..a4bf7d9 100644
--- a/py/builtinevex.c
+++ b/py/builtinevex.c
@@ -90,9 +90,15 @@
     qstr mode = mp_obj_str_get_qstr(args[2]);
     mp_parse_input_kind_t parse_input_kind;
     switch (mode) {
-        case MP_QSTR_single: parse_input_kind = MP_PARSE_SINGLE_INPUT; break;
-        case MP_QSTR_exec: parse_input_kind = MP_PARSE_FILE_INPUT; break;
-        case MP_QSTR_eval: parse_input_kind = MP_PARSE_EVAL_INPUT; break;
+        case MP_QSTR_single:
+            parse_input_kind = MP_PARSE_SINGLE_INPUT;
+            break;
+        case MP_QSTR_exec:
+            parse_input_kind = MP_PARSE_FILE_INPUT;
+            break;
+        case MP_QSTR_eval:
+            parse_input_kind = MP_PARSE_EVAL_INPUT;
+            break;
         default:
             mp_raise_ValueError("bad compile mode");
     }
diff --git a/py/builtinhelp.c b/py/builtinhelp.c
index 033242b..1373563 100644
--- a/py/builtinhelp.c
+++ b/py/builtinhelp.c
@@ -33,18 +33,18 @@
 #if MICROPY_PY_BUILTINS_HELP
 
 const char mp_help_default_text[] =
-"Welcome to MicroPython!\n"
-"\n"
-"For online docs please visit http://docs.micropython.org/\n"
-"\n"
-"Control commands:\n"
-"  CTRL-A        -- on a blank line, enter raw REPL mode\n"
-"  CTRL-B        -- on a blank line, enter normal REPL mode\n"
-"  CTRL-C        -- interrupt a running program\n"
-"  CTRL-D        -- on a blank line, exit or do a soft reset\n"
-"  CTRL-E        -- on a blank line, enter paste mode\n"
-"\n"
-"For further help on a specific object, type help(obj)\n"
+    "Welcome to MicroPython!\n"
+    "\n"
+    "For online docs please visit http://docs.micropython.org/\n"
+    "\n"
+    "Control commands:\n"
+    "  CTRL-A        -- on a blank line, enter raw REPL mode\n"
+    "  CTRL-B        -- on a blank line, enter normal REPL mode\n"
+    "  CTRL-C        -- interrupt a running program\n"
+    "  CTRL-D        -- on a blank line, exit or do a soft reset\n"
+    "  CTRL-E        -- on a blank line, enter paste mode\n"
+    "\n"
+    "For further help on a specific object, type help(obj)\n"
 ;
 
 STATIC void mp_help_print_info_about_object(mp_obj_t name_o, mp_obj_t value) {
@@ -91,7 +91,7 @@
     #endif
 
     // sort the list so it's printed in alphabetical order
-    mp_obj_list_sort(1, &list, (mp_map_t*)&mp_const_empty_map);
+    mp_obj_list_sort(1, &list, (mp_map_t *)&mp_const_empty_map);
 
     // print the list of modules in a column-first order
     #define NUM_COLUMNS (4)
diff --git a/py/builtinimport.c b/py/builtinimport.c
index 23ab166..b188f3c 100644
--- a/py/builtinimport.c
+++ b/py/builtinimport.c
@@ -96,7 +96,7 @@
 }
 
 STATIC mp_import_stat_t find_file(const char *file_str, uint file_len, vstr_t *dest) {
-#if MICROPY_PY_SYS
+    #if MICROPY_PY_SYS
     // extract the list of paths
     size_t path_num;
     mp_obj_t *path_items;
@@ -122,7 +122,7 @@
         // could not find a directory or file
         return MP_IMPORT_STAT_NO_EXIST;
     }
-#endif
+    #endif
 
     // mp_sys_path is empty, so just use the given file name
     vstr_add_strn(dest, file_str, file_len);
@@ -143,7 +143,7 @@
 #endif
 
 #if MICROPY_PERSISTENT_CODE_LOAD || MICROPY_MODULE_FROZEN_MPY
-STATIC void do_execute_raw_code(mp_obj_t module_obj, mp_raw_code_t *raw_code, const char* source_name) {
+STATIC void do_execute_raw_code(mp_obj_t module_obj, mp_raw_code_t *raw_code, const char *source_name) {
     (void)source_name;
 
     #if MICROPY_PY___FILE__
@@ -244,14 +244,14 @@
 }
 
 mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) {
-#if DEBUG_PRINT
+    #if DEBUG_PRINT
     DEBUG_printf("__import__:\n");
     for (size_t i = 0; i < n_args; i++) {
         DEBUG_printf("  ");
         mp_obj_print(args[i], PRINT_REPR);
         DEBUG_printf("\n");
     }
-#endif
+    #endif
 
     mp_obj_t module_name = args[0];
     mp_obj_t fromtuple = mp_const_none;
@@ -290,12 +290,12 @@
         mp_map_elem_t *elem = mp_map_lookup(globals_map, MP_OBJ_NEW_QSTR(MP_QSTR___path__), MP_MAP_LOOKUP);
         bool is_pkg = (elem != NULL);
 
-#if DEBUG_PRINT
+        #if DEBUG_PRINT
         DEBUG_printf("Current module/package: ");
         mp_obj_print(this_name_q, PRINT_REPR);
         DEBUG_printf(", is_package: %d", is_pkg);
         DEBUG_printf("\n");
-#endif
+        #endif
 
         size_t this_name_l;
         const char *this_name = mp_obj_str_get_data(this_name_q, &this_name_l);
diff --git a/py/compile.c b/py/compile.c
index 885e318..225f207 100644
--- a/py/compile.c
+++ b/py/compile.c
@@ -47,14 +47,14 @@
 // define rules with a compile function
 #define DEF_RULE(rule, comp, kind, ...) PN_##rule,
 #define DEF_RULE_NC(rule, kind, ...)
-#include "py/grammar.h"
+    #include "py/grammar.h"
 #undef DEF_RULE
 #undef DEF_RULE_NC
     PN_const_object, // special node for a constant, generic Python object
 // define rules without a compile function
 #define DEF_RULE(rule, comp, kind, ...)
 #define DEF_RULE_NC(rule, kind, ...) PN_##rule,
-#include "py/grammar.h"
+    #include "py/grammar.h"
 #undef DEF_RULE
 #undef DEF_RULE_NC
 } pn_kind_t;
@@ -193,7 +193,7 @@
 STATIC void compile_error_set_line(compiler_t *comp, mp_parse_node_t pn) {
     // if the line of the error is unknown then try to update it from the pn
     if (comp->compile_error_line == 0 && MP_PARSE_NODE_IS_STRUCT(pn)) {
-        comp->compile_error_line = ((mp_parse_node_struct_t*)pn)->source_line;
+        comp->compile_error_line = ((mp_parse_node_struct_t *)pn)->source_line;
     }
 }
 
@@ -259,7 +259,7 @@
 
 STATIC void apply_to_single_or_list(compiler_t *comp, mp_parse_node_t pn, pn_kind_t pn_list_kind, apply_list_fun_t f) {
     if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, pn_list_kind)) {
-        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
+        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
         int num_nodes = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
         for (int i = 0; i < num_nodes; i++) {
             f(comp, pns->nodes[i]);
@@ -350,7 +350,7 @@
         }
         return;
     } else if (MP_PARSE_NODE_IS_STRUCT(pn)) {
-        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
+        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
         int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
         if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_or_test) {
             if (jump_if == false) {
@@ -409,7 +409,7 @@
     }
 
     if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) {
-        mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1];
+        mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1];
         if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_atom_expr_trailers) {
             int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns1);
             if (assign_kind != ASSIGN_AUG_STORE) {
@@ -418,7 +418,7 @@
                 }
             }
             assert(MP_PARSE_NODE_IS_STRUCT(pns1->nodes[n - 1]));
-            pns1 = (mp_parse_node_struct_t*)pns1->nodes[n - 1];
+            pns1 = (mp_parse_node_struct_t *)pns1->nodes[n - 1];
         }
         if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_trailer_bracket) {
             if (assign_kind == ASSIGN_AUG_STORE) {
@@ -478,14 +478,14 @@
     }
     if (num_head != 0) {
         if (0 == have_star_index) {
-            c_assign(comp, ((mp_parse_node_struct_t*)node_head)->nodes[0], ASSIGN_STORE);
+            c_assign(comp, ((mp_parse_node_struct_t *)node_head)->nodes[0], ASSIGN_STORE);
         } else {
             c_assign(comp, node_head, ASSIGN_STORE);
         }
     }
     for (uint i = 0; i < num_tail; i++) {
         if (num_head + i == have_star_index) {
-            c_assign(comp, ((mp_parse_node_struct_t*)nodes_tail[i])->nodes[0], ASSIGN_STORE);
+            c_assign(comp, ((mp_parse_node_struct_t *)nodes_tail[i])->nodes[0], ASSIGN_STORE);
         } else {
             c_assign(comp, nodes_tail[i], ASSIGN_STORE);
         }
@@ -513,7 +513,7 @@
         }
     } else {
         // pn must be a struct
-        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
+        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
         switch (MP_PARSE_NODE_STRUCT_KIND(pns)) {
             case PN_atom_expr_normal:
                 // lhs is an index or attribute
@@ -539,7 +539,7 @@
                     if (assign_kind != ASSIGN_STORE) {
                         goto cannot_assign;
                     }
-                    pns = (mp_parse_node_struct_t*)pns->nodes[0];
+                    pns = (mp_parse_node_struct_t *)pns->nodes[0];
                     goto testlist_comp;
                 }
                 break;
@@ -553,7 +553,7 @@
                     // empty list, assignment allowed
                     c_assign_tuple(comp, MP_PARSE_NODE_NULL, 0, NULL);
                 } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp)) {
-                    pns = (mp_parse_node_struct_t*)pns->nodes[0];
+                    pns = (mp_parse_node_struct_t *)pns->nodes[0];
                     goto testlist_comp;
                 } else {
                     // brackets around 1 item
@@ -566,10 +566,10 @@
         }
         return;
 
-        testlist_comp:
+    testlist_comp:
         // lhs is a sequence
         if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) {
-            mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)pns->nodes[1];
+            mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[1];
             if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_testlist_comp_3b) {
                 // sequence of one item, with trailing comma
                 assert(MP_PARSE_NODE_IS_NULL(pns2->nodes[0]));
@@ -586,14 +586,14 @@
             }
         } else {
             // sequence with 2 items
-            sequence_with_2_items:
+        sequence_with_2_items:
             c_assign_tuple(comp, MP_PARSE_NODE_NULL, 2, pns->nodes);
         }
         return;
     }
     return;
 
-    cannot_assign:
+cannot_assign:
     compile_syntax_error(comp, pn, "can't assign to expression");
 }
 
@@ -650,7 +650,7 @@
         pn_kind = -1;
     } else {
         assert(MP_PARSE_NODE_IS_STRUCT(pn));
-        pn_kind = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pn);
+        pn_kind = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn);
     }
 
     if (pn_kind == PN_typedargslist_star || pn_kind == PN_varargslist_star) {
@@ -680,7 +680,7 @@
         } else if (pn_kind == PN_typedargslist_name) {
             // this parameter has a colon and/or equal specifier
 
-            mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
+            mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
             pn_id = pns->nodes[0];
             //pn_colon = pns->nodes[1]; // unused
             pn_equal = pns->nodes[2];
@@ -689,7 +689,7 @@
             assert(pn_kind == PN_varargslist_name); // should be
             // this parameter has an equal specifier
 
-            mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
+            mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
             pn_id = pns->nodes[0];
             pn_equal = pns->nodes[1];
         }
@@ -779,7 +779,7 @@
     }
 
     // get the scope for this function
-    scope_t *fscope = (scope_t*)pns->nodes[4];
+    scope_t *fscope = (scope_t *)pns->nodes[4];
 
     // compile the function definition
     compile_funcdef_lambdef(comp, fscope, pns->nodes[1], PN_typedargslist);
@@ -801,7 +801,7 @@
     EMIT(load_build_class);
 
     // scope for this class
-    scope_t *cscope = (scope_t*)pns->nodes[3];
+    scope_t *cscope = (scope_t *)pns->nodes[3];
 
     // compile the class
     close_over_variables_etc(comp, cscope, 0, 0);
@@ -835,13 +835,13 @@
     qstr attr = MP_PARSE_NODE_LEAF_ARG(name_nodes[1]);
     if (attr == MP_QSTR_bytecode) {
         *emit_options = MP_EMIT_OPT_BYTECODE;
-#if MICROPY_EMIT_NATIVE
+    #if MICROPY_EMIT_NATIVE
     } else if (attr == MP_QSTR_native) {
         *emit_options = MP_EMIT_OPT_NATIVE_PYTHON;
     } else if (attr == MP_QSTR_viper) {
         *emit_options = MP_EMIT_OPT_VIPER;
-#endif
-    #if MICROPY_EMIT_INLINE_ASM
+    #endif
+        #if MICROPY_EMIT_INLINE_ASM
     #if MICROPY_DYNAMIC_COMPILER
     } else if (attr == MP_QSTR_asm_thumb) {
         *emit_options = MP_EMIT_OPT_ASM;
@@ -851,7 +851,7 @@
     } else if (attr == ASM_DECORATOR_QSTR) {
         *emit_options = MP_EMIT_OPT_ASM;
     #endif
-    #endif
+        #endif
     } else {
         compile_syntax_error(comp, name_nodes[1], "invalid micropython decorator");
     }
@@ -883,7 +883,7 @@
     int num_built_in_decorators = 0;
     for (int i = 0; i < n; i++) {
         assert(MP_PARSE_NODE_IS_STRUCT_KIND(nodes[i], PN_decorator)); // should be
-        mp_parse_node_struct_t *pns_decorator = (mp_parse_node_struct_t*)nodes[i];
+        mp_parse_node_struct_t *pns_decorator = (mp_parse_node_struct_t *)nodes[i];
 
         // nodes[0] contains the decorator function, which is a dotted name
         mp_parse_node_t *name_nodes;
@@ -913,16 +913,16 @@
     }
 
     // compile the body (funcdef, async funcdef or classdef) and get its name
-    mp_parse_node_struct_t *pns_body = (mp_parse_node_struct_t*)pns->nodes[1];
+    mp_parse_node_struct_t *pns_body = (mp_parse_node_struct_t *)pns->nodes[1];
     qstr body_name = 0;
     if (MP_PARSE_NODE_STRUCT_KIND(pns_body) == PN_funcdef) {
         body_name = compile_funcdef_helper(comp, pns_body, emit_options);
     #if MICROPY_PY_ASYNC_AWAIT
     } else if (MP_PARSE_NODE_STRUCT_KIND(pns_body) == PN_async_funcdef) {
         assert(MP_PARSE_NODE_IS_STRUCT(pns_body->nodes[0]));
-        mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t*)pns_body->nodes[0];
+        mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t *)pns_body->nodes[0];
         body_name = compile_funcdef_helper(comp, pns0, emit_options);
-        scope_t *fscope = (scope_t*)pns0->nodes[4];
+        scope_t *fscope = (scope_t *)pns0->nodes[4];
         fscope->scope_flags |= MP_SCOPE_FLAG_GENERATOR;
     #endif
     } else {
@@ -949,19 +949,19 @@
     if (MP_PARSE_NODE_IS_ID(pn)) {
         compile_delete_id(comp, MP_PARSE_NODE_LEAF_ARG(pn));
     } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_atom_expr_normal)) {
-        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
+        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
 
         compile_node(comp, pns->nodes[0]); // base of the atom_expr_normal node
 
         if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) {
-            mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1];
+            mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1];
             if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_atom_expr_trailers) {
                 int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns1);
                 for (int i = 0; i < n - 1; i++) {
                     compile_node(comp, pns1->nodes[i]);
                 }
                 assert(MP_PARSE_NODE_IS_STRUCT(pns1->nodes[n - 1]));
-                pns1 = (mp_parse_node_struct_t*)pns1->nodes[n - 1];
+                pns1 = (mp_parse_node_struct_t *)pns1->nodes[n - 1];
             }
             if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_trailer_bracket) {
                 compile_node(comp, pns1->nodes[0]);
@@ -977,16 +977,16 @@
         }
 
     } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_atom_paren)) {
-        pn = ((mp_parse_node_struct_t*)pn)->nodes[0];
+        pn = ((mp_parse_node_struct_t *)pn)->nodes[0];
         if (MP_PARSE_NODE_IS_NULL(pn)) {
             goto cannot_delete;
         } else {
             assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_testlist_comp));
-            mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
+            mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
             // TODO perhaps factorise testlist_comp code with other uses of PN_testlist_comp
 
             if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) {
-                mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1];
+                mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1];
                 if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_testlist_comp_3b) {
                     // sequence of one item, with trailing comma
                     assert(MP_PARSE_NODE_IS_NULL(pns1->nodes[0]));
@@ -1006,7 +1006,7 @@
                 }
             } else {
                 // sequence with 2 items
-                sequence_with_2_items:
+            sequence_with_2_items:
                 c_del_stmt(comp, pns->nodes[0]);
                 c_del_stmt(comp, pns->nodes[1]);
             }
@@ -1051,10 +1051,10 @@
         // no argument to 'return', so return None
         EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
     } else if (MICROPY_COMP_RETURN_IF_EXPR
-        && MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_test_if_expr)) {
+               && MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_test_if_expr)) {
         // special case when returning an if-expression; to match CPython optimisation
-        mp_parse_node_struct_t *pns_test_if_expr = (mp_parse_node_struct_t*)pns->nodes[0];
-        mp_parse_node_struct_t *pns_test_if_else = (mp_parse_node_struct_t*)pns_test_if_expr->nodes[1];
+        mp_parse_node_struct_t *pns_test_if_expr = (mp_parse_node_struct_t *)pns->nodes[0];
+        mp_parse_node_struct_t *pns_test_if_else = (mp_parse_node_struct_t *)pns_test_if_expr->nodes[1];
 
         uint l_fail = comp_next_label(comp);
         c_if_cond(comp, pns_test_if_else->nodes[0], false, l_fail); // condition
@@ -1079,7 +1079,7 @@
         EMIT_ARG(raise_varargs, 0);
     } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_raise_stmt_arg)) {
         // raise x from y
-        pns = (mp_parse_node_struct_t*)pns->nodes[0];
+        pns = (mp_parse_node_struct_t *)pns->nodes[0];
         compile_node(comp, pns->nodes[0]);
         compile_node(comp, pns->nodes[1]);
         EMIT_ARG(raise_varargs, 2);
@@ -1096,7 +1096,7 @@
 STATIC void do_import_name(compiler_t *comp, mp_parse_node_t pn, qstr *q_base) {
     bool is_as = false;
     if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_dotted_as_name)) {
-        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
+        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
         // a name of the form x as y; unwrap it
         *q_base = MP_PARSE_NODE_LEAF_ARG(pns->nodes[1]);
         pn = pns->nodes[0];
@@ -1115,7 +1115,7 @@
         EMIT_ARG(import, q_full, MP_EMIT_IMPORT_NAME);
     } else {
         assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_dotted_name)); // should be
-        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
+        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
         {
             // a name of the form a.b.c
             if (!is_as) {
@@ -1174,7 +1174,7 @@
             pn_import_source = MP_PARSE_NODE_NULL;
         } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn_import_source, PN_import_from_2b)) {
             // This covers relative imports starting with dot(s) like "from .foo import"
-            mp_parse_node_struct_t *pns_2b = (mp_parse_node_struct_t*)pn_import_source;
+            mp_parse_node_struct_t *pns_2b = (mp_parse_node_struct_t *)pn_import_source;
             pn_rel = pns_2b->nodes[0];
             pn_import_source = pns_2b->nodes[1];
             assert(!MP_PARSE_NODE_IS_NULL(pn_import_source)); // should not be
@@ -1225,7 +1225,7 @@
         int n = mp_parse_node_extract_list(&pns->nodes[1], PN_import_as_names, &pn_nodes);
         for (int i = 0; i < n; i++) {
             assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn_nodes[i], PN_import_as_name));
-            mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t*)pn_nodes[i];
+            mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t *)pn_nodes[i];
             qstr id2 = MP_PARSE_NODE_LEAF_ARG(pns3->nodes[0]); // should be id
             EMIT_ARG(load_const_str, id2);
         }
@@ -1236,7 +1236,7 @@
         do_import_name(comp, pn_import_source, &dummy_q);
         for (int i = 0; i < n; i++) {
             assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn_nodes[i], PN_import_as_name));
-            mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t*)pn_nodes[i];
+            mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t *)pn_nodes[i];
             qstr id2 = MP_PARSE_NODE_LEAF_ARG(pns3->nodes[0]); // should be id
             EMIT_ARG(import, id2, MP_EMIT_IMPORT_FROM);
             if (MP_PARSE_NODE_IS_NULL(pns3->nodes[1])) {
@@ -1349,7 +1349,7 @@
     int n_elif = mp_parse_node_extract_list(&pns->nodes[2], PN_if_stmt_elif_list, &pn_elif);
     for (int i = 0; i < n_elif; i++) {
         assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn_elif[i], PN_if_stmt_elif)); // should be
-        mp_parse_node_struct_t *pns_elif = (mp_parse_node_struct_t*)pn_elif[i];
+        mp_parse_node_struct_t *pns_elif = (mp_parse_node_struct_t *)pn_elif[i];
 
         // optimisation: don't emit anything when "if False"
         if (!mp_parse_node_is_const_false(pns_elif->nodes[0])) {
@@ -1518,11 +1518,11 @@
     // this is actually slower, but uses no heap memory
     // for viper it will be much, much faster
     if (/*comp->scope_cur->emit_options == MP_EMIT_OPT_VIPER &&*/ MP_PARSE_NODE_IS_ID(pns->nodes[0]) && MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_atom_expr_normal)) {
-        mp_parse_node_struct_t *pns_it = (mp_parse_node_struct_t*)pns->nodes[1];
+        mp_parse_node_struct_t *pns_it = (mp_parse_node_struct_t *)pns->nodes[1];
         if (MP_PARSE_NODE_IS_ID(pns_it->nodes[0])
             && MP_PARSE_NODE_LEAF_ARG(pns_it->nodes[0]) == MP_QSTR_range
-            && MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pns_it->nodes[1]) == PN_trailer_paren) {
-            mp_parse_node_t pn_range_args = ((mp_parse_node_struct_t*)pns_it->nodes[1])->nodes[0];
+            && MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pns_it->nodes[1]) == PN_trailer_paren) {
+            mp_parse_node_t pn_range_args = ((mp_parse_node_struct_t *)pns_it->nodes[1])->nodes[0];
             mp_parse_node_t *args;
             int n_args = mp_parse_node_extract_list(&pn_range_args, PN_arglist, &args);
             mp_parse_node_t pn_range_start;
@@ -1551,13 +1551,13 @@
                 }
                 // arguments must be able to be compiled as standard expressions
                 if (optimize && MP_PARSE_NODE_IS_STRUCT(pn_range_start)) {
-                    int k = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pn_range_start);
+                    int k = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn_range_start);
                     if (k == PN_arglist_star || k == PN_arglist_dbl_star || k == PN_argument) {
                         optimize = false;
                     }
                 }
                 if (optimize && MP_PARSE_NODE_IS_STRUCT(pn_range_end)) {
-                    int k = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pn_range_end);
+                    int k = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn_range_end);
                     if (k == PN_arglist_star || k == PN_arglist_dbl_star || k == PN_argument) {
                         optimize = false;
                     }
@@ -1614,7 +1614,7 @@
 
     for (int i = 0; i < n_except; i++) {
         assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn_excepts[i], PN_try_stmt_except)); // should be
-        mp_parse_node_struct_t *pns_except = (mp_parse_node_struct_t*)pn_excepts[i];
+        mp_parse_node_struct_t *pns_except = (mp_parse_node_struct_t *)pn_excepts[i];
 
         qstr qstr_exception_local = 0;
         uint end_finally_label = comp_next_label(comp);
@@ -1633,7 +1633,7 @@
             // this exception handler requires a match to a certain type of exception
             mp_parse_node_t pns_exception_expr = pns_except->nodes[0];
             if (MP_PARSE_NODE_IS_STRUCT(pns_exception_expr)) {
-                mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t*)pns_exception_expr;
+                mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t *)pns_exception_expr;
                 if (MP_PARSE_NODE_STRUCT_KIND(pns3) == PN_try_stmt_as_name) {
                     // handler binds the exception to a local
                     pns_exception_expr = pns3->nodes[0];
@@ -1713,7 +1713,7 @@
 STATIC void compile_try_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
     assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should be
     {
-        mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)pns->nodes[1];
+        mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[1];
         if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_try_stmt_finally) {
             // just try-finally
             compile_try_finally(comp, pns->nodes[0], 0, NULL, MP_PARSE_NODE_NULL, pns2->nodes[0]);
@@ -1726,7 +1726,7 @@
                 compile_try_except(comp, pns->nodes[0], n_except, pn_excepts, pns2->nodes[1]);
             } else {
                 // have finally
-                compile_try_finally(comp, pns->nodes[0], n_except, pn_excepts, pns2->nodes[1], ((mp_parse_node_struct_t*)pns2->nodes[2])->nodes[0]);
+                compile_try_finally(comp, pns->nodes[0], n_except, pn_excepts, pns2->nodes[1], ((mp_parse_node_struct_t *)pns2->nodes[2])->nodes[0]);
             }
         } else {
             // just try-except
@@ -1745,7 +1745,7 @@
         uint l_end = comp_next_label(comp);
         if (MP_PARSE_NODE_IS_STRUCT_KIND(nodes[0], PN_with_item)) {
             // this pre-bit is of the form "a as b"
-            mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)nodes[0];
+            mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)nodes[0];
             compile_node(comp, pns->nodes[0]);
             compile_increase_except_level(comp, l_end, MP_EMIT_SETUP_BLOCK_WITH);
             c_assign(comp, pns->nodes[1], ASSIGN_STORE);
@@ -1851,7 +1851,7 @@
 
         if (MP_PARSE_NODE_IS_STRUCT_KIND(nodes[0], PN_with_item)) {
             // this pre-bit is of the form "a as b"
-            mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)nodes[0];
+            mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)nodes[0];
             compile_node(comp, pns->nodes[0]);
             EMIT(dup_top);
             compile_await_object_method(comp, MP_QSTR___aenter__);
@@ -1963,11 +1963,11 @@
 
 STATIC void compile_async_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
     assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[0]));
-    mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t*)pns->nodes[0];
+    mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t *)pns->nodes[0];
     if (MP_PARSE_NODE_STRUCT_KIND(pns0) == PN_funcdef) {
         // async def
         compile_funcdef(comp, pns0);
-        scope_t *fscope = (scope_t*)pns0->nodes[4];
+        scope_t *fscope = (scope_t *)pns0->nodes[4];
         fscope->scope_flags |= MP_SCOPE_FLAG_GENERATOR;
     } else if (MP_PARSE_NODE_STRUCT_KIND(pns0) == PN_for_stmt) {
         // async for
@@ -2000,7 +2000,7 @@
             }
         }
     } else if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) {
-        mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1];
+        mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1];
         int kind = MP_PARSE_NODE_STRUCT_KIND(pns1);
         if (kind == PN_expr_stmt_augassign) {
             c_assign(comp, pns->nodes[0], ASSIGN_AUG_LOAD); // lhs load for aug assign
@@ -2029,8 +2029,8 @@
             #if MICROPY_COMP_DOUBLE_TUPLE_ASSIGN
             if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_testlist_star_expr)
                 && MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_star_expr)) {
-                mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t*)pns->nodes[0];
-                pns1 = (mp_parse_node_struct_t*)pns->nodes[1];
+                mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t *)pns->nodes[0];
+                pns1 = (mp_parse_node_struct_t *)pns->nodes[1];
                 uint32_t n_pns0 = MP_PARSE_NODE_STRUCT_NUM_NODES(pns0);
                 // Can only optimise a tuple-to-tuple assignment when all of the following hold:
                 //  - equal number of items in LHS and RHS tuples
@@ -2080,7 +2080,7 @@
 
 STATIC void compile_test_if_expr(compiler_t *comp, mp_parse_node_struct_t *pns) {
     assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_test_if_else));
-    mp_parse_node_struct_t *pns_test_if_else = (mp_parse_node_struct_t*)pns->nodes[1];
+    mp_parse_node_struct_t *pns_test_if_else = (mp_parse_node_struct_t *)pns->nodes[1];
 
     uint l_fail = comp_next_label(comp);
     uint l_end = comp_next_label(comp);
@@ -2102,7 +2102,7 @@
     }
 
     // get the scope for this lambda
-    scope_t *this_scope = (scope_t*)pns->nodes[2];
+    scope_t *this_scope = (scope_t *)pns->nodes[2];
 
     // compile the lambda definition
     compile_funcdef_lambdef(comp, this_scope, pns->nodes[0], PN_varargslist);
@@ -2151,7 +2151,7 @@
             EMIT_ARG(binary_op, op);
         } else {
             assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[i])); // should be
-            mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)pns->nodes[i];
+            mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[i];
             int kind = MP_PARSE_NODE_STRUCT_KIND(pns2);
             if (kind == PN_comp_op_not_in) {
                 EMIT_ARG(binary_op, MP_BINARY_OP_NOT_IN);
@@ -2230,10 +2230,10 @@
 
     // get the array of trailers (known to be an array of PARSE_NODE_STRUCT)
     size_t num_trail = 1;
-    mp_parse_node_struct_t **pns_trail = (mp_parse_node_struct_t**)&pns->nodes[1];
+    mp_parse_node_struct_t **pns_trail = (mp_parse_node_struct_t **)&pns->nodes[1];
     if (MP_PARSE_NODE_STRUCT_KIND(pns_trail[0]) == PN_atom_expr_trailers) {
         num_trail = MP_PARSE_NODE_STRUCT_NUM_NODES(pns_trail[0]);
-        pns_trail = (mp_parse_node_struct_t**)&pns_trail[0]->nodes[0];
+        pns_trail = (mp_parse_node_struct_t **)&pns_trail[0]->nodes[0];
     }
 
     // the current index into the array of trailers
@@ -2282,19 +2282,19 @@
             i = 1;
         }
 
-    #if MICROPY_COMP_CONST_LITERAL && MICROPY_PY_COLLECTIONS_ORDEREDDICT
-    // handle special OrderedDict constructor
+        #if MICROPY_COMP_CONST_LITERAL && MICROPY_PY_COLLECTIONS_ORDEREDDICT
+        // handle special OrderedDict constructor
     } else if (MP_PARSE_NODE_IS_ID(pns->nodes[0])
-        && MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]) == MP_QSTR_OrderedDict
-        && MP_PARSE_NODE_STRUCT_KIND(pns_trail[0]) == PN_trailer_paren
-        && MP_PARSE_NODE_IS_STRUCT_KIND(pns_trail[0]->nodes[0], PN_atom_brace)) {
+               && MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]) == MP_QSTR_OrderedDict
+               && MP_PARSE_NODE_STRUCT_KIND(pns_trail[0]) == PN_trailer_paren
+               && MP_PARSE_NODE_IS_STRUCT_KIND(pns_trail[0]->nodes[0], PN_atom_brace)) {
         // at this point we have matched "OrderedDict({...})"
 
         EMIT_ARG(call_function, 0, 0, 0);
-        mp_parse_node_struct_t *pns_dict = (mp_parse_node_struct_t*)pns_trail[0]->nodes[0];
+        mp_parse_node_struct_t *pns_dict = (mp_parse_node_struct_t *)pns_trail[0]->nodes[0];
         compile_atom_brace_helper(comp, pns_dict, false);
         i = 1;
-    #endif
+        #endif
     }
 
     // compile the remaining trailers
@@ -2337,7 +2337,7 @@
     mp_parse_node_struct_t *star_args_node = NULL, *dblstar_args_node = NULL;
     for (int i = 0; i < n_args; i++) {
         if (MP_PARSE_NODE_IS_STRUCT(args[i])) {
-            mp_parse_node_struct_t *pns_arg = (mp_parse_node_struct_t*)args[i];
+            mp_parse_node_struct_t *pns_arg = (mp_parse_node_struct_t *)args[i];
             if (MP_PARSE_NODE_STRUCT_KIND(pns_arg) == PN_arglist_star) {
                 if (star_flags & MP_EMIT_STAR_FLAG_SINGLE) {
                     compile_syntax_error(comp, (mp_parse_node_t)pns_arg, "can't have multiple *x");
@@ -2369,7 +2369,7 @@
                 goto normal_argument;
             }
         } else {
-            normal_argument:
+        normal_argument:
             if (star_flags) {
                 compile_syntax_error(comp, args[i], "non-keyword arg after */**");
                 return;
@@ -2410,7 +2410,7 @@
 STATIC void compile_comprehension(compiler_t *comp, mp_parse_node_struct_t *pns, scope_kind_t kind) {
     assert(MP_PARSE_NODE_STRUCT_NUM_NODES(pns) == 2);
     assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_comp_for));
-    mp_parse_node_struct_t *pns_comp_for = (mp_parse_node_struct_t*)pns->nodes[1];
+    mp_parse_node_struct_t *pns_comp_for = (mp_parse_node_struct_t *)pns->nodes[1];
 
     if (comp->pass == MP_PASS_SCOPE) {
         // create a new scope for this comprehension
@@ -2420,7 +2420,7 @@
     }
 
     // get the scope for this comprehension
-    scope_t *this_scope = (scope_t*)pns_comp_for->nodes[3];
+    scope_t *this_scope = (scope_t *)pns_comp_for->nodes[3];
 
     // compile the comprehension
     close_over_variables_etc(comp, this_scope, 0, 0);
@@ -2438,10 +2438,10 @@
         c_tuple(comp, MP_PARSE_NODE_NULL, NULL);
     } else {
         assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp));
-        pns = (mp_parse_node_struct_t*)pns->nodes[0];
+        pns = (mp_parse_node_struct_t *)pns->nodes[0];
         assert(!MP_PARSE_NODE_IS_NULL(pns->nodes[1]));
         if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) {
-            mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)pns->nodes[1];
+            mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[1];
             if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_testlist_comp_3b) {
                 // tuple of one item, with trailing comma
                 assert(MP_PARSE_NODE_IS_NULL(pns2->nodes[0]));
@@ -2458,7 +2458,7 @@
             }
         } else {
             // tuple with 2 items
-            tuple_with_2_items:
+        tuple_with_2_items:
             c_tuple(comp, MP_PARSE_NODE_NULL, pns);
         }
     }
@@ -2469,9 +2469,9 @@
         // empty list
         EMIT_ARG(build, 0, MP_EMIT_BUILD_LIST);
     } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp)) {
-        mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)pns->nodes[0];
+        mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[0];
         if (MP_PARSE_NODE_IS_STRUCT(pns2->nodes[1])) {
-            mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t*)pns2->nodes[1];
+            mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t *)pns2->nodes[1];
             if (MP_PARSE_NODE_STRUCT_KIND(pns3) == PN_testlist_comp_3b) {
                 // list of one item, with trailing comma
                 assert(MP_PARSE_NODE_IS_NULL(pns3->nodes[0]));
@@ -2491,7 +2491,7 @@
             }
         } else {
             // list with 2 items
-            list_with_2_items:
+        list_with_2_items:
             compile_node(comp, pns2->nodes[0]);
             compile_node(comp, pns2->nodes[1]);
             EMIT_ARG(build, 2, MP_EMIT_BUILD_LIST);
@@ -2511,7 +2511,7 @@
             EMIT_ARG(build, 0, MP_EMIT_BUILD_MAP);
         }
     } else if (MP_PARSE_NODE_IS_STRUCT(pn)) {
-        pns = (mp_parse_node_struct_t*)pn;
+        pns = (mp_parse_node_struct_t *)pn;
         if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_dictorsetmaker_item) {
             // dict with one element
             if (create_map) {
@@ -2521,7 +2521,7 @@
             EMIT(store_map);
         } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_dictorsetmaker) {
             assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should succeed
-            mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1];
+            mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1];
             if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_dictorsetmaker_list) {
                 // dict/set with multiple elements
 
@@ -2595,7 +2595,7 @@
         }
     } else {
         // set with one element
-        set_with_one_element:
+    set_with_one_element:
         #if MICROPY_PY_BUILTINS_SET
         compile_node(comp, pn);
         EMIT_ARG(build, 1, MP_EMIT_BUILD_SET);
@@ -2629,7 +2629,7 @@
     if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_subscript_2) {
         compile_node(comp, pns->nodes[0]); // start of slice
         assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should always be
-        pns = (mp_parse_node_struct_t*)pns->nodes[1];
+        pns = (mp_parse_node_struct_t *)pns->nodes[1];
     } else {
         // pns is a PN_subscript_3, load None for start of slice
         EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
@@ -2642,7 +2642,7 @@
         EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
         EMIT_ARG(build, 2, MP_EMIT_BUILD_SLICE);
     } else if (MP_PARSE_NODE_IS_STRUCT(pn)) {
-        pns = (mp_parse_node_struct_t*)pn;
+        pns = (mp_parse_node_struct_t *)pn;
         if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_subscript_3c) {
             EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
             pn = pns->nodes[0];
@@ -2657,7 +2657,7 @@
         } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_subscript_3d) {
             compile_node(comp, pns->nodes[0]);
             assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should always be
-            pns = (mp_parse_node_struct_t*)pns->nodes[1];
+            pns = (mp_parse_node_struct_t *)pns->nodes[1];
             assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_sliceop); // should always be
             if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) {
                 // [?:x:]
@@ -2702,7 +2702,7 @@
         EMIT_ARG(yield, MP_EMIT_YIELD_VALUE);
         reserve_labels_for_native(comp, 1);
     } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_yield_arg_from)) {
-        pns = (mp_parse_node_struct_t*)pns->nodes[0];
+        pns = (mp_parse_node_struct_t *)pns->nodes[0];
         compile_node(comp, pns->nodes[0]);
         compile_yield_from(comp);
     } else {
@@ -2736,13 +2736,13 @@
     EMIT_ARG(load_const_obj, get_const_object(pns));
 }
 
-typedef void (*compile_function_t)(compiler_t*, mp_parse_node_struct_t*);
+typedef void (*compile_function_t)(compiler_t *, mp_parse_node_struct_t *);
 STATIC const compile_function_t compile_function[] = {
 // only define rules with a compile function
 #define c(f) compile_##f
 #define DEF_RULE(rule, comp, kind, ...) comp,
 #define DEF_RULE_NC(rule, kind, ...)
-#include "py/grammar.h"
+    #include "py/grammar.h"
 #undef c
 #undef DEF_RULE
 #undef DEF_RULE_NC
@@ -2774,8 +2774,12 @@
     } else if (MP_PARSE_NODE_IS_LEAF(pn)) {
         uintptr_t arg = MP_PARSE_NODE_LEAF_ARG(pn);
         switch (MP_PARSE_NODE_LEAF_KIND(pn)) {
-            case MP_PARSE_NODE_ID: compile_load_id(comp, arg); break;
-            case MP_PARSE_NODE_STRING: EMIT_ARG(load_const_str, arg); break;
+            case MP_PARSE_NODE_ID:
+                compile_load_id(comp, arg);
+                break;
+            case MP_PARSE_NODE_STRING:
+                EMIT_ARG(load_const_str, arg);
+                break;
             case MP_PARSE_NODE_BYTES:
                 // only create and load the actual bytes object on the last pass
                 if (comp->pass != MP_PASS_EMIT) {
@@ -2786,18 +2790,19 @@
                     EMIT_ARG(load_const_obj, mp_obj_new_bytes(data, len));
                 }
                 break;
-            case MP_PARSE_NODE_TOKEN: default:
+            case MP_PARSE_NODE_TOKEN:
+            default:
                 if (arg == MP_TOKEN_NEWLINE) {
                     // this can occur when file_input lets through a NEWLINE (eg if file starts with a newline)
                     // or when single_input lets through a NEWLINE (user enters a blank line)
                     // do nothing
                 } else {
-                  EMIT_ARG(load_const_tok, arg);
+                    EMIT_ARG(load_const_tok, arg);
                 }
                 break;
         }
     } else {
-        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
+        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
         EMIT_ARG(set_source_line, pns->source_line);
         assert(MP_PARSE_NODE_STRUCT_KIND(pns) <= PN_const_object);
         compile_function_t f = compile_function[MP_PARSE_NODE_STRUCT_KIND(pns)];
@@ -2847,7 +2852,7 @@
         }
     } else {
         assert(MP_PARSE_NODE_IS_STRUCT(pn));
-        pns = (mp_parse_node_struct_t*)pn;
+        pns = (mp_parse_node_struct_t *)pn;
         if (MP_PARSE_NODE_STRUCT_KIND(pns) == pn_name) {
             // named parameter with possible annotation
             param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]);
@@ -2880,7 +2885,7 @@
                 assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_tfpdef)); // should be
                 // named star with possible annotation
                 comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_VARARGS;
-                pns = (mp_parse_node_struct_t*)pns->nodes[0];
+                pns = (mp_parse_node_struct_t *)pns->nodes[0];
                 param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]);
             }
         } else {
@@ -2927,7 +2932,7 @@
     c_assign(comp, pns_comp_for->nodes[0], ASSIGN_STORE);
     mp_parse_node_t pn_iter = pns_comp_for->nodes[2];
 
-    tail_recursion:
+tail_recursion:
     if (MP_PARSE_NODE_IS_NULL(pn_iter)) {
         // no more nested if/for; compile inner expression
         compile_node(comp, pn_inner_expr);
@@ -2938,16 +2943,16 @@
         } else {
             EMIT_ARG(store_comp, comp->scope_cur->kind, 4 * for_depth + 5);
         }
-    } else if (MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pn_iter) == PN_comp_if) {
+    } else if (MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn_iter) == PN_comp_if) {
         // if condition
-        mp_parse_node_struct_t *pns_comp_if = (mp_parse_node_struct_t*)pn_iter;
+        mp_parse_node_struct_t *pns_comp_if = (mp_parse_node_struct_t *)pn_iter;
         c_if_cond(comp, pns_comp_if->nodes[0], false, l_top);
         pn_iter = pns_comp_if->nodes[1];
         goto tail_recursion;
     } else {
-        assert(MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pn_iter) == PN_comp_for); // should be
+        assert(MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn_iter) == PN_comp_for); // should be
         // for loop
-        mp_parse_node_struct_t *pns_comp_for2 = (mp_parse_node_struct_t*)pn_iter;
+        mp_parse_node_struct_t *pns_comp_for2 = (mp_parse_node_struct_t *)pn_iter;
         compile_node(comp, pns_comp_for2->nodes[1]);
         EMIT_ARG(get_iter, true);
         compile_scope_comp_iter(comp, pns_comp_for2, pn_inner_expr, for_depth + 1);
@@ -2959,7 +2964,7 @@
 }
 
 STATIC void check_for_doc_string(compiler_t *comp, mp_parse_node_t pn) {
-#if MICROPY_ENABLE_DOC_STRING
+    #if MICROPY_ENABLE_DOC_STRING
     // see http://www.python.org/dev/peps/pep-0257/
 
     // look for the first statement
@@ -2967,7 +2972,7 @@
         // a statement; fall through
     } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_file_input_2)) {
         // file input; find the first non-newline node
-        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
+        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
         int num_nodes = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
         for (int i = 0; i < num_nodes; i++) {
             pn = pns->nodes[i];
@@ -2979,28 +2984,28 @@
         // if we didn't find a non-newline then it's okay to fall through; pn will be a newline and so doc-string test below will fail gracefully
     } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_suite_block_stmts)) {
         // a list of statements; get the first one
-        pn = ((mp_parse_node_struct_t*)pn)->nodes[0];
+        pn = ((mp_parse_node_struct_t *)pn)->nodes[0];
     } else {
         return;
     }
 
     // check the first statement for a doc string
     if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_expr_stmt)) {
-        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
+        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
         if ((MP_PARSE_NODE_IS_LEAF(pns->nodes[0])
-                && MP_PARSE_NODE_LEAF_KIND(pns->nodes[0]) == MP_PARSE_NODE_STRING)
+             && MP_PARSE_NODE_LEAF_KIND(pns->nodes[0]) == MP_PARSE_NODE_STRING)
             || (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_const_object)
-                && mp_obj_is_str(get_const_object((mp_parse_node_struct_t*)pns->nodes[0])))) {
-                // compile the doc string
-                compile_node(comp, pns->nodes[0]);
-                // store the doc string
-                compile_store_id(comp, MP_QSTR___doc__);
+                && mp_obj_is_str(get_const_object((mp_parse_node_struct_t *)pns->nodes[0])))) {
+            // compile the doc string
+            compile_node(comp, pns->nodes[0]);
+            // store the doc string
+            compile_store_id(comp, MP_QSTR___doc__);
         }
     }
-#else
+    #else
     (void)comp;
     (void)pn;
-#endif
+    #endif
 }
 
 STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) {
@@ -3020,7 +3025,7 @@
     // compile
     if (MP_PARSE_NODE_IS_STRUCT_KIND(scope->pn, PN_eval_input)) {
         assert(scope->kind == SCOPE_MODULE);
-        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)scope->pn;
+        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn;
         compile_node(comp, pns->nodes[0]); // compile the expression
         EMIT(return_value);
     } else if (scope->kind == SCOPE_MODULE) {
@@ -3032,7 +3037,7 @@
         EMIT(return_value);
     } else if (scope->kind == SCOPE_FUNCTION) {
         assert(MP_PARSE_NODE_IS_STRUCT(scope->pn));
-        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)scope->pn;
+        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn;
         assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_funcdef);
 
         // work out number of parameters, keywords and default parameters, and add them to the id_info array
@@ -3057,7 +3062,7 @@
         }
     } else if (scope->kind == SCOPE_LAMBDA) {
         assert(MP_PARSE_NODE_IS_STRUCT(scope->pn));
-        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)scope->pn;
+        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn;
         assert(MP_PARSE_NODE_STRUCT_NUM_NODES(pns) == 3);
 
         // Set the source line number for the start of the lambda
@@ -3082,10 +3087,10 @@
         // a bit of a hack at the moment
 
         assert(MP_PARSE_NODE_IS_STRUCT(scope->pn));
-        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)scope->pn;
+        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn;
         assert(MP_PARSE_NODE_STRUCT_NUM_NODES(pns) == 2);
         assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_comp_for));
-        mp_parse_node_struct_t *pns_comp_for = (mp_parse_node_struct_t*)pns->nodes[1];
+        mp_parse_node_struct_t *pns_comp_for = (mp_parse_node_struct_t *)pns->nodes[1];
 
         // We need a unique name for the comprehension argument (the iterator).
         // CPython uses .0, but we should be able to use anything that won't
@@ -3132,7 +3137,7 @@
     } else {
         assert(scope->kind == SCOPE_CLASS);
         assert(MP_PARSE_NODE_IS_STRUCT(scope->pn));
-        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)scope->pn;
+        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn;
         assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_classdef);
 
         if (comp->pass == MP_PASS_SCOPE) {
@@ -3184,7 +3189,7 @@
 
     // get the function definition parse node
     assert(MP_PARSE_NODE_IS_STRUCT(scope->pn));
-    mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)scope->pn;
+    mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn;
     assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_funcdef);
 
     //qstr f_id = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); // function name
@@ -3207,11 +3212,21 @@
         if (MP_PARSE_NODE_IS_ID(pn_annotation)) {
             qstr ret_type = MP_PARSE_NODE_LEAF_ARG(pn_annotation);
             switch (ret_type) {
-                case MP_QSTR_object: type_sig = MP_NATIVE_TYPE_OBJ; break;
-                case MP_QSTR_bool: type_sig = MP_NATIVE_TYPE_BOOL; break;
-                case MP_QSTR_int: type_sig = MP_NATIVE_TYPE_INT; break;
-                case MP_QSTR_uint: type_sig = MP_NATIVE_TYPE_UINT; break;
-                default: compile_syntax_error(comp, pn_annotation, "unknown type"); return;
+                case MP_QSTR_object:
+                    type_sig = MP_NATIVE_TYPE_OBJ;
+                    break;
+                case MP_QSTR_bool:
+                    type_sig = MP_NATIVE_TYPE_BOOL;
+                    break;
+                case MP_QSTR_int:
+                    type_sig = MP_NATIVE_TYPE_INT;
+                    break;
+                case MP_QSTR_uint:
+                    type_sig = MP_NATIVE_TYPE_UINT;
+                    break;
+                default:
+                    compile_syntax_error(comp, pn_annotation, "unknown type");
+                    return;
             }
         } else {
             compile_syntax_error(comp, pn_annotation, "return annotation must be an identifier");
@@ -3224,7 +3239,7 @@
 
     for (int i = 0; i < num; i++) {
         assert(MP_PARSE_NODE_IS_STRUCT(nodes[i]));
-        mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)nodes[i];
+        mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)nodes[i];
         if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_pass_stmt) {
             // no instructions
             continue;
@@ -3240,7 +3255,7 @@
         if (!MP_PARSE_NODE_IS_NULL(pns2->nodes[1])) {
             goto not_an_instruction;
         }
-        pns2 = (mp_parse_node_struct_t*)pns2->nodes[0];
+        pns2 = (mp_parse_node_struct_t *)pns2->nodes[0];
         if (MP_PARSE_NODE_STRUCT_KIND(pns2) != PN_atom_expr_normal) {
             goto not_an_instruction;
         }
@@ -3254,7 +3269,7 @@
         // parse node looks like an instruction
         // get instruction name and args
         qstr op = MP_PARSE_NODE_LEAF_ARG(pns2->nodes[0]);
-        pns2 = (mp_parse_node_struct_t*)pns2->nodes[1]; // PN_trailer_paren
+        pns2 = (mp_parse_node_struct_t *)pns2->nodes[1]; // PN_trailer_paren
         mp_parse_node_t *pn_arg;
         int n_args = mp_parse_node_extract_list(&pns2->nodes[0], PN_arglist, &pn_arg);
 
@@ -3277,7 +3292,7 @@
                 return;
             }
             if (pass > MP_PASS_SCOPE) {
-                mp_asm_base_align((mp_asm_base_t*)comp->emit_inline_asm,
+                mp_asm_base_align((mp_asm_base_t *)comp->emit_inline_asm,
                     MP_PARSE_NODE_LEAF_SMALL_INT(pn_arg[0]));
             }
         } else if (op == MP_QSTR_data) {
@@ -3292,7 +3307,7 @@
                         compile_syntax_error(comp, nodes[i], "'data' requires integer arguments");
                         return;
                     }
-                    mp_asm_base_data((mp_asm_base_t*)comp->emit_inline_asm,
+                    mp_asm_base_data((mp_asm_base_t *)comp->emit_inline_asm,
                         bytesize, MP_PARSE_NODE_LEAF_SMALL_INT(pn_arg[j]));
                 }
             }
@@ -3312,9 +3327,9 @@
         EMIT_INLINE_ASM_ARG(end_pass, type_sig);
 
         if (comp->pass == MP_PASS_EMIT) {
-            void *f = mp_asm_base_get_code((mp_asm_base_t*)comp->emit_inline_asm);
+            void *f = mp_asm_base_get_code((mp_asm_base_t *)comp->emit_inline_asm);
             mp_emit_glue_assign_native(comp->scope_cur->raw_code, MP_CODE_NATIVE_ASM,
-                f, mp_asm_base_get_code_size((mp_asm_base_t*)comp->emit_inline_asm),
+                f, mp_asm_base_get_code_size((mp_asm_base_t *)comp->emit_inline_asm),
                 NULL,
                 #if MICROPY_PERSISTENT_CODE_SAVE
                 0, 0, 0, 0, NULL,
@@ -3340,7 +3355,9 @@
             if (id->flags & ID_FLAG_IS_STAR_PARAM) {
                 if (id_param != NULL) {
                     // swap star param with last param
-                    id_info_t temp = *id_param; *id_param = *id; *id = temp;
+                    id_info_t temp = *id_param;
+                    *id_param = *id;
+                    *id = temp;
                 }
                 break;
             } else if (id_param == NULL && id->flags == ID_FLAG_IS_PARAM) {
@@ -3485,9 +3502,9 @@
     emit_bc_set_max_num_labels(emit_bc, max_num_labels);
 
     // compile pass 2 and 3
-#if MICROPY_EMIT_NATIVE
+    #if MICROPY_EMIT_NATIVE
     emit_t *emit_native = NULL;
-#endif
+    #endif
     for (scope_t *s = comp->scope_head; s != NULL && comp->compile_error == MP_OBJ_NULL; s = s->next) {
         #if MICROPY_EMIT_INLINE_ASM
         if (s->emit_options == MP_EMIT_OPT_ASM) {
@@ -3520,7 +3537,7 @@
 
             switch (s->emit_options) {
 
-#if MICROPY_EMIT_NATIVE
+                #if MICROPY_EMIT_NATIVE
                 case MP_EMIT_OPT_NATIVE_PYTHON:
                 case MP_EMIT_OPT_VIPER:
                     if (emit_native == NULL) {
@@ -3529,7 +3546,7 @@
                     comp->emit_method_table = NATIVE_EMITTER_TABLE;
                     comp->emit = emit_native;
                     break;
-#endif // MICROPY_EMIT_NATIVE
+                #endif // MICROPY_EMIT_NATIVE
 
                 default:
                     comp->emit = emit_bc;
@@ -3566,11 +3583,11 @@
     // free the emitters
 
     emit_bc_free(emit_bc);
-#if MICROPY_EMIT_NATIVE
+    #if MICROPY_EMIT_NATIVE
     if (emit_native != NULL) {
         NATIVE_EMITTER(free)(emit_native);
     }
-#endif
+    #endif
     #if MICROPY_EMIT_INLINE_ASM
     if (comp->emit_inline_asm != NULL) {
         ASM_EMITTER(free)(comp->emit_inline_asm);
diff --git a/py/dynruntime.h b/py/dynruntime.h
index bbe093a..494ad77 100644
--- a/py/dynruntime.h
+++ b/py/dynruntime.h
@@ -73,18 +73,18 @@
 /******************************************************************************/
 // Types and objects
 
-#define MP_OBJ_NEW_QSTR(x) MP_OBJ_NEW_QSTR_ ## x
+#define MP_OBJ_NEW_QSTR(x) MP_OBJ_NEW_QSTR_##x
 
 #define mp_type_type                        (*mp_fun_table.type_type)
 #define mp_type_str                         (*mp_fun_table.type_str)
 #define mp_type_list                        (*mp_fun_table.type_list)
-#define mp_type_EOFError                    (*(mp_obj_type_t*)(mp_load_global(MP_QSTR_EOFError)))
-#define mp_type_IndexError                  (*(mp_obj_type_t*)(mp_load_global(MP_QSTR_IndexError)))
-#define mp_type_KeyError                    (*(mp_obj_type_t*)(mp_load_global(MP_QSTR_KeyError)))
-#define mp_type_NotImplementedError         (*(mp_obj_type_t*)(mp_load_global(MP_QSTR_NotImplementedError)))
-#define mp_type_RuntimeError                (*(mp_obj_type_t*)(mp_load_global(MP_QSTR_RuntimeError)))
-#define mp_type_TypeError                   (*(mp_obj_type_t*)(mp_load_global(MP_QSTR_TypeError)))
-#define mp_type_ValueError                  (*(mp_obj_type_t*)(mp_load_global(MP_QSTR_ValueError)))
+#define mp_type_EOFError                    (*(mp_obj_type_t *)(mp_load_global(MP_QSTR_EOFError)))
+#define mp_type_IndexError                  (*(mp_obj_type_t *)(mp_load_global(MP_QSTR_IndexError)))
+#define mp_type_KeyError                    (*(mp_obj_type_t *)(mp_load_global(MP_QSTR_KeyError)))
+#define mp_type_NotImplementedError         (*(mp_obj_type_t *)(mp_load_global(MP_QSTR_NotImplementedError)))
+#define mp_type_RuntimeError                (*(mp_obj_type_t *)(mp_load_global(MP_QSTR_RuntimeError)))
+#define mp_type_TypeError                   (*(mp_obj_type_t *)(mp_load_global(MP_QSTR_TypeError)))
+#define mp_type_ValueError                  (*(mp_obj_type_t *)(mp_load_global(MP_QSTR_ValueError)))
 
 #define mp_stream_read_obj                  (*mp_fun_table.stream_read_obj)
 #define mp_stream_readinto_obj              (*mp_fun_table.stream_readinto_obj)
@@ -110,7 +110,7 @@
 #define mp_obj_cast_to_native_base(o, t)    (mp_obj_cast_to_native_base_dyn((o), (t)))
 #define mp_obj_get_int(o)                   (mp_fun_table.native_from_obj(o, MP_NATIVE_TYPE_INT))
 #define mp_obj_get_int_truncated(o)         (mp_fun_table.native_from_obj(o, MP_NATIVE_TYPE_UINT))
-#define mp_obj_str_get_str(s)               ((void*)mp_fun_table.native_from_obj(s, MP_NATIVE_TYPE_PTR))
+#define mp_obj_str_get_str(s)               ((void *)mp_fun_table.native_from_obj(s, MP_NATIVE_TYPE_PTR))
 #define mp_obj_str_get_data(o, len)         (mp_obj_str_get_data_dyn((o), (len)))
 #define mp_get_buffer_raise(o, bufinfo, fl) (mp_fun_table.get_buffer_raise((o), (bufinfo), (fl)))
 #define mp_get_stream_raise(s, flags)       (mp_fun_table.get_stream_raise((s), (flags)))
@@ -119,9 +119,9 @@
 #define mp_obj_subscr(base, index, val)     (mp_fun_table.obj_subscr((base), (index), (val)))
 #define mp_obj_list_append(list, item)      (mp_fun_table.list_append((list), (item)))
 
-static inline mp_obj_t mp_obj_new_str_of_type_dyn(const mp_obj_type_t *type, const byte* data, size_t len) {
+static inline mp_obj_t mp_obj_new_str_of_type_dyn(const mp_obj_type_t *type, const byte *data, size_t len) {
     if (type == &mp_type_str) {
-        return mp_obj_new_str((const char*)data, len);
+        return mp_obj_new_str((const char *)data, len);
     } else {
         return mp_obj_new_bytes(data, len);
     }
@@ -137,7 +137,7 @@
         // This is a very simple version of mp_obj_is_subclass_fast that could be improved.
         return MP_OBJ_NULL;
     } else {
-        mp_obj_instance_t *self = (mp_obj_instance_t*)MP_OBJ_TO_PTR(self_in);
+        mp_obj_instance_t *self = (mp_obj_instance_t *)MP_OBJ_TO_PTR(self_in);
         return self->subobj[0];
     }
 }
@@ -177,7 +177,7 @@
     mp_raw_code_t rc; \
     rc.kind = MP_CODE_NATIVE_VIPER; \
     rc.scope_flags = 0; \
-    rc.const_table = (void*)self->const_table; \
+    rc.const_table = (void *)self->const_table; \
     (void)rc;
 
 #define MP_DYNRUNTIME_INIT_EXIT \
diff --git a/py/emit.h b/py/emit.h
index 26d027a..13bd3e9 100644
--- a/py/emit.h
+++ b/py/emit.h
@@ -99,7 +99,7 @@
 
 typedef struct _emit_method_table_t {
     #if MICROPY_DYNAMIC_COMPILER
-    emit_t *(*emit_new)(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels);
+    emit_t *(*emit_new)(mp_obj_t * error_slot, uint *label_slot, mp_uint_t max_num_labels);
     void (*emit_free)(emit_t *emit);
     #endif
 
@@ -188,7 +188,7 @@
 emit_t *emit_native_xtensa_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels);
 emit_t *emit_native_xtensawin_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels);
 
-void emit_bc_set_max_num_labels(emit_t* emit, mp_uint_t max_num_labels);
+void emit_bc_set_max_num_labels(emit_t *emit, mp_uint_t max_num_labels);
 
 void emit_bc_free(emit_t *emit);
 void emit_native_x64_free(emit_t *emit);
diff --git a/py/emitbc.c b/py/emitbc.c
index ee4a7d5..e90c28c 100644
--- a/py/emitbc.c
+++ b/py/emitbc.c
@@ -121,7 +121,7 @@
     }
 }
 
-STATIC void emit_write_code_info_byte(emit_t* emit, byte val) {
+STATIC void emit_write_code_info_byte(emit_t *emit, byte val) {
     *emit_get_cur_to_write_code_info(emit, 1) = val;
 }
 
@@ -230,7 +230,7 @@
 }
 #endif
 
-STATIC void emit_write_bytecode_byte_qstr(emit_t* emit, int stack_adj, byte b, qstr qst) {
+STATIC void emit_write_bytecode_byte_qstr(emit_t *emit, int stack_adj, byte b, qstr qst) {
     #if MICROPY_PERSISTENT_CODE
     assert((qst >> 16) == 0);
     mp_emit_bc_adjust_stack_size(emit, stack_adj);
@@ -252,7 +252,7 @@
     // aligns the pointer so it is friendly to GC
     emit_write_bytecode_byte(emit, stack_adj, b);
     emit->bytecode_offset = (size_t)MP_ALIGN(emit->bytecode_offset, sizeof(mp_obj_t));
-    mp_obj_t *c = (mp_obj_t*)emit_get_cur_to_write_bytecode(emit, sizeof(mp_obj_t));
+    mp_obj_t *c = (mp_obj_t *)emit_get_cur_to_write_bytecode(emit, sizeof(mp_obj_t));
     // Verify thar c is already uint-aligned
     assert(c == MP_ALIGN(c, sizeof(mp_obj_t)));
     *c = obj;
@@ -267,10 +267,10 @@
     #else
     // aligns the pointer so it is friendly to GC
     emit_write_bytecode_byte(emit, stack_adj, b);
-    emit->bytecode_offset = (size_t)MP_ALIGN(emit->bytecode_offset, sizeof(void*));
-    void **c = (void**)emit_get_cur_to_write_bytecode(emit, sizeof(void*));
+    emit->bytecode_offset = (size_t)MP_ALIGN(emit->bytecode_offset, sizeof(void *));
+    void **c = (void **)emit_get_cur_to_write_bytecode(emit, sizeof(void *));
     // Verify thar c is already uint-aligned
-    assert(c == MP_ALIGN(c, sizeof(void*)));
+    assert(c == MP_ALIGN(c, sizeof(void *)));
     *c = rc;
     #endif
     #if MICROPY_PY_SYS_SETTRACE
@@ -467,7 +467,7 @@
 }
 
 void mp_emit_bc_set_source_line(emit_t *emit, mp_uint_t source_line) {
-#if MICROPY_ENABLE_SOURCE_LINE
+    #if MICROPY_ENABLE_SOURCE_LINE
     if (MP_STATE_VM(mp_optimise_value) >= 3) {
         // If we compile with -O3, don't store line numbers.
         return;
@@ -479,10 +479,10 @@
         emit->last_source_line_offset = emit->bytecode_offset;
         emit->last_source_line = source_line;
     }
-#else
+    #else
     (void)emit;
     (void)source_line;
-#endif
+    #endif
 }
 
 void mp_emit_bc_label_assign(emit_t *emit, mp_uint_t l) {
diff --git a/py/emitglue.c b/py/emitglue.c
index d30a1e6..98320c4 100644
--- a/py/emitglue.c
+++ b/py/emitglue.c
@@ -84,17 +84,17 @@
     mp_prof_extract_prelude(code, prelude);
     #endif
 
-#ifdef DEBUG_PRINT
+    #ifdef DEBUG_PRINT
     #if !MICROPY_DEBUG_PRINTERS
     const size_t len = 0;
     #endif
     DEBUG_printf("assign byte code: code=%p len=" UINT_FMT " flags=%x\n", code, len, (uint)scope_flags);
-#endif
-#if MICROPY_DEBUG_PRINTERS
+    #endif
+    #if MICROPY_DEBUG_PRINTERS
     if (mp_verbose_flag >= 2) {
         mp_bytecode_print(rc, code, len, const_table);
     }
-#endif
+    #endif
 }
 
 #if MICROPY_EMIT_MACHINE_CODE
@@ -120,28 +120,28 @@
     rc->prelude_offset = prelude_offset;
     rc->n_obj = n_obj;
     rc->n_raw_code = n_raw_code;
-    rc->n_qstr= n_qstr;
+    rc->n_qstr = n_qstr;
     rc->qstr_link = qstr_link;
     #endif
 
-#ifdef DEBUG_PRINT
+    #ifdef DEBUG_PRINT
     DEBUG_printf("assign native: kind=%d fun=%p len=" UINT_FMT " n_pos_args=" UINT_FMT " flags=%x\n", kind, fun_data, fun_len, n_pos_args, (uint)scope_flags);
     for (mp_uint_t i = 0; i < fun_len; i++) {
         if (i > 0 && i % 16 == 0) {
             DEBUG_printf("\n");
         }
-        DEBUG_printf(" %02x", ((byte*)fun_data)[i]);
+        DEBUG_printf(" %02x", ((byte *)fun_data)[i]);
     }
     DEBUG_printf("\n");
 
-#ifdef WRITE_CODE
+    #ifdef WRITE_CODE
     FILE *fp_write_code = fopen("out-code", "wb");
     fwrite(fun_data, fun_len, 1, fp_write_code);
     fclose(fp_write_code);
-#endif
-#else
+    #endif
+    #else
     (void)fun_len;
-#endif
+    #endif
 }
 #endif
 
@@ -164,7 +164,7 @@
             fun = mp_obj_new_fun_native(def_args, def_kw_args, rc->fun_data, rc->const_table);
             // Check for a generator function, and if so change the type of the object
             if ((rc->scope_flags & MP_SCOPE_FLAG_GENERATOR) != 0) {
-                ((mp_obj_base_t*)MP_OBJ_TO_PTR(fun))->type = &mp_type_native_gen_wrap;
+                ((mp_obj_base_t *)MP_OBJ_TO_PTR(fun))->type = &mp_type_native_gen_wrap;
             }
             break;
         #endif
@@ -179,7 +179,7 @@
             fun = mp_obj_new_fun_bc(def_args, def_kw_args, rc->fun_data, rc->const_table);
             // check for generator functions and if so change the type of the object
             if ((rc->scope_flags & MP_SCOPE_FLAG_GENERATOR) != 0) {
-                ((mp_obj_base_t*)MP_OBJ_TO_PTR(fun))->type = &mp_type_gen_wrap;
+                ((mp_obj_base_t *)MP_OBJ_TO_PTR(fun))->type = &mp_type_gen_wrap;
             }
 
             #if MICROPY_PY_SYS_SETTRACE
diff --git a/py/emitinlinethumb.c b/py/emitinlinethumb.c
index 0f58976..358ccac 100644
--- a/py/emitinlinethumb.c
+++ b/py/emitinlinethumb.c
@@ -39,14 +39,14 @@
 // define rules with a compile function
 #define DEF_RULE(rule, comp, kind, ...) PN_##rule,
 #define DEF_RULE_NC(rule, kind, ...)
-#include "py/grammar.h"
+    #include "py/grammar.h"
 #undef DEF_RULE
 #undef DEF_RULE_NC
     PN_const_object, // special node for a constant, generic Python object
 // define rules without a compile function
 #define DEF_RULE(rule, comp, kind, ...)
 #define DEF_RULE_NC(rule, kind, ...) PN_##rule,
-#include "py/grammar.h"
+    #include "py/grammar.h"
 #undef DEF_RULE
 #undef DEF_RULE_NC
 } pn_kind_t;
@@ -131,7 +131,9 @@
     return true;
 }
 
-typedef struct _reg_name_t { byte reg; byte name[3]; } reg_name_t;
+typedef struct _reg_name_t { byte reg;
+                             byte name[3];
+} reg_name_t;
 STATIC const reg_name_t reg_name_table[] = {
     {0, "r0\0"},
     {1, "r1\0"},
@@ -157,7 +159,9 @@
 };
 
 #define MAX_SPECIAL_REGISTER_NAME_LENGTH 7
-typedef struct _special_reg_name_t { byte reg; char name[MAX_SPECIAL_REGISTER_NAME_LENGTH + 1]; } special_reg_name_t;
+typedef struct _special_reg_name_t { byte reg;
+                                     char name[MAX_SPECIAL_REGISTER_NAME_LENGTH + 1];
+} special_reg_name_t;
 STATIC const special_reg_name_t special_reg_name_table[] = {
     {5, "IPSR"},
     {17, "BASEPRI"},
@@ -226,8 +230,8 @@
         }
         if (regno > 31) {
             emit_inline_thumb_error_exc(emit,
-                 mp_obj_new_exception_msg_varg(&mp_type_SyntaxError,
-                       "'%s' expects at most r%d", op, 31));
+                mp_obj_new_exception_msg_varg(&mp_type_SyntaxError,
+                    "'%s' expects at most r%d", op, 31));
             return 0;
         } else {
             return regno;
@@ -235,7 +239,7 @@
     }
 malformed:
     emit_inline_thumb_error_exc(emit,
-         mp_obj_new_exception_msg_varg(&mp_type_SyntaxError,
+        mp_obj_new_exception_msg_varg(&mp_type_SyntaxError,
             "'%s' expects an FPU register", op));
     return 0;
 }
@@ -248,7 +252,7 @@
         goto bad_arg;
     }
 
-    mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
+    mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
     assert(MP_PARSE_NODE_STRUCT_NUM_NODES(pns) == 1); // should always be
     pn = pns->nodes[0];
 
@@ -258,10 +262,10 @@
         // set with one element
         reglist |= 1 << get_arg_reg(emit, op, pn, 15);
     } else if (MP_PARSE_NODE_IS_STRUCT(pn)) {
-        pns = (mp_parse_node_struct_t*)pn;
+        pns = (mp_parse_node_struct_t *)pn;
         if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_dictorsetmaker) {
             assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should succeed
-            mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1];
+            mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1];
             if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_dictorsetmaker_list) {
                 // set with multiple elements
 
@@ -311,11 +315,11 @@
     if (!MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_atom_bracket)) {
         goto bad_arg;
     }
-    mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
+    mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
     if (!MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp)) {
         goto bad_arg;
     }
-    pns = (mp_parse_node_struct_t*)pns->nodes[0];
+    pns = (mp_parse_node_struct_t *)pns->nodes[0];
     if (MP_PARSE_NODE_STRUCT_NUM_NODES(pns) != 2) {
         goto bad_arg;
     }
@@ -347,7 +351,9 @@
     return 0;
 }
 
-typedef struct _cc_name_t { byte cc; byte name[2]; } cc_name_t;
+typedef struct _cc_name_t { byte cc;
+                            byte name[2];
+} cc_name_t;
 STATIC const cc_name_t cc_name_table[] = {
     { ASM_THUMB_CC_EQ, "eq" },
     { ASM_THUMB_CC_NE, "ne" },
@@ -365,7 +371,9 @@
     { ASM_THUMB_CC_LE, "le" },
 };
 
-typedef struct _format_4_op_t { byte op; char name[3]; } format_4_op_t;
+typedef struct _format_4_op_t { byte op;
+                                char name[3];
+} format_4_op_t;
 #define X(x) (((x) >> 4) & 0xff) // only need 1 byte to distinguish these ops
 STATIC const format_4_op_t format_4_op_table[] = {
     { X(ASM_THUMB_FORMAT_4_EOR), "eor" },
@@ -387,7 +395,9 @@
 #undef X
 
 // name is actually a qstr, which should fit in 16 bits
-typedef struct _format_9_10_op_t { uint16_t op; uint16_t name; } format_9_10_op_t;
+typedef struct _format_9_10_op_t { uint16_t op;
+                                   uint16_t name;
+} format_9_10_op_t;
 #define X(x) (x)
 STATIC const format_9_10_op_t format_9_10_op_table[] = {
     { X(ASM_THUMB_FORMAT_9_LDR | ASM_THUMB_FORMAT_9_WORD_TRANSFER), MP_QSTR_ldr },
@@ -401,7 +411,9 @@
 
 #if MICROPY_EMIT_INLINE_THUMB_FLOAT
 // actual opcodes are: 0xee00 | op.hi_nibble, 0x0a00 | op.lo_nibble
-typedef struct _format_vfp_op_t { byte op; char name[3]; } format_vfp_op_t;
+typedef struct _format_vfp_op_t { byte op;
+                                  char name[3];
+} format_vfp_op_t;
 STATIC const format_vfp_op_t format_vfp_op_table[] = {
     { 0x30, "add" },
     { 0x34, "sub" },
@@ -425,7 +437,7 @@
     // "subs", RLO, RLO, I3, asm_thumb_subs_reg_reg_i3
 
     size_t op_len;
-    const char *op_str = (const char*)qstr_data(op, &op_len);
+    const char *op_str = (const char *)qstr_data(op, &op_len);
 
     #if MICROPY_EMIT_INLINE_THUMB_FLOAT
     if (op_str[0] == 'v') {
@@ -434,7 +446,7 @@
             mp_uint_t op_code = 0x0ac0, op_code_hi;
             if (op == MP_QSTR_vcmp) {
                 op_code_hi = 0xeeb4;
-                op_vfp_twoargs:;
+            op_vfp_twoargs:;
                 mp_uint_t vd = get_arg_vfpreg(emit, op_str, pn_args[0]);
                 mp_uint_t vm = get_arg_vfpreg(emit, op_str, pn_args[1]);
                 asm_thumb_op32(&emit->as,
@@ -485,7 +497,7 @@
                     0x0a10 | (r_arm << 12) | ((vm & 1) << 7));
             } else if (op == MP_QSTR_vldr) {
                 op_code_hi = 0xed90;
-                op_vldr_vstr:;
+            op_vldr_vstr:;
                 mp_uint_t vd = get_arg_vfpreg(emit, op_str, pn_args[0]);
                 mp_parse_node_t pn_base, pn_offset;
                 if (get_arg_addr(emit, op_str, pn_args[1], &pn_base, &pn_offset)) {
@@ -549,8 +561,8 @@
             mp_uint_t r = get_arg_reg(emit, op_str, pn_args[0], 15);
             asm_thumb_op16(&emit->as, 0x4700 | (r << 3));
         } else if (op_str[0] == 'b' && (op_len == 3
-                    || (op_len == 5 && op_str[3] == '_'
-                        && (op_str[4] == 'n' || (ARMV7M && op_str[4] == 'w'))))) {
+                                        || (op_len == 5 && op_str[3] == '_'
+                                            && (op_str[4] == 'n' || (ARMV7M && op_str[4] == 'w'))))) {
             mp_uint_t cc = -1;
             for (mp_uint_t i = 0; i < MP_ARRAY_SIZE(cc_name_table); i++) {
                 if (op_str[1] == cc_name_table[i].name[0] && op_str[2] == cc_name_table[i].name[1]) {
@@ -639,7 +651,7 @@
                 op_code_hi = 0xfab0;
                 op_code = 0xf080;
                 mp_uint_t rd, rm;
-                op_clz_rbit:
+            op_clz_rbit:
                 rd = get_arg_reg(emit, op_str, pn_args[0], 15);
                 rm = get_arg_reg(emit, op_str, pn_args[1], 15);
                 asm_thumb_op32(&emit->as, op_code_hi | rm, op_code | (rd << 8) | rm);
@@ -647,7 +659,7 @@
                 op_code_hi = 0xfa90;
                 op_code = 0xf0a0;
                 goto op_clz_rbit;
-            } else if (ARMV7M && op == MP_QSTR_mrs){
+            } else if (ARMV7M && op == MP_QSTR_mrs) {
                 mp_uint_t reg_dest = get_arg_reg(emit, op_str, pn_args[0], 12);
                 mp_uint_t reg_src = get_arg_special_reg(emit, op_str, pn_args[1]);
                 asm_thumb_op32(&emit->as, 0xf3ef, 0x8000 | (reg_dest << 8) | reg_src);
@@ -655,7 +667,7 @@
                 if (op == MP_QSTR_and_) {
                     op_code = ASM_THUMB_FORMAT_4_AND;
                     mp_uint_t reg_dest, reg_src;
-                    op_format_4:
+                op_format_4:
                     reg_dest = get_arg_reg(emit, op_str, pn_args[0], 7);
                     reg_src = get_arg_reg(emit, op_str, pn_args[1], 7);
                     asm_thumb_format_4(&emit->as, op_code, reg_dest, reg_src);
@@ -676,7 +688,7 @@
             if (op == MP_QSTR_mov) {
                 op_code = ASM_THUMB_FORMAT_3_MOV;
                 mp_uint_t rlo_dest, i8_src;
-                op_format_3:
+            op_format_3:
                 rlo_dest = get_arg_reg(emit, op_str, pn_args[0], 7);
                 i8_src = get_arg_i(emit, op_str, pn_args[1], 0xff);
                 asm_thumb_format_3(&emit->as, op_code, rlo_dest, i8_src);
@@ -692,7 +704,7 @@
             } else if (ARMV7M && op == MP_QSTR_movw) {
                 op_code = ASM_THUMB_OP_MOVW;
                 mp_uint_t reg_dest;
-                op_movw_movt:
+            op_movw_movt:
                 reg_dest = get_arg_reg(emit, op_str, pn_args[0], 15);
                 int i_src = get_arg_i(emit, op_str, pn_args[1], 0xffff);
                 asm_thumb_mov_reg_i16(&emit->as, op_code, reg_dest, i_src);
@@ -745,7 +757,7 @@
         if (op == MP_QSTR_lsl) {
             op_code = ASM_THUMB_FORMAT_1_LSL;
             mp_uint_t rlo_dest, rlo_src, i5;
-            op_format_1:
+        op_format_1:
             rlo_dest = get_arg_reg(emit, op_str, pn_args[0], 7);
             rlo_src = get_arg_reg(emit, op_str, pn_args[1], 7);
             i5 = get_arg_i(emit, op_str, pn_args[2], 0x1f);
@@ -759,7 +771,7 @@
         } else if (op == MP_QSTR_add) {
             op_code = ASM_THUMB_FORMAT_2_ADD;
             mp_uint_t rlo_dest, rlo_src;
-            op_format_2:
+        op_format_2:
             rlo_dest = get_arg_reg(emit, op_str, pn_args[0], 7);
             rlo_src = get_arg_reg(emit, op_str, pn_args[1], 7);
             int src_b;
@@ -774,7 +786,7 @@
         } else if (ARMV7M && op == MP_QSTR_sdiv) {
             op_code = 0xfb90; // sdiv high part
             mp_uint_t rd, rn, rm;
-            op_sdiv_udiv:
+        op_sdiv_udiv:
             rd = get_arg_reg(emit, op_str, pn_args[0], 15);
             rn = get_arg_reg(emit, op_str, pn_args[1], 15);
             rm = get_arg_reg(emit, op_str, pn_args[2], 15);
diff --git a/py/emitinlinextensa.c b/py/emitinlinextensa.c
index d101791..6776382 100644
--- a/py/emitinlinextensa.c
+++ b/py/emitinlinextensa.c
@@ -115,7 +115,9 @@
     return true;
 }
 
-typedef struct _reg_name_t { byte reg; byte name[3]; } reg_name_t;
+typedef struct _reg_name_t { byte reg;
+                             byte name[3];
+} reg_name_t;
 STATIC const reg_name_t reg_name_table[] = {
     {0, "a0\0"},
     {1, "a1\0"},
@@ -242,7 +244,7 @@
 
 STATIC void emit_inline_xtensa_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_args, mp_parse_node_t *pn_args) {
     size_t op_len;
-    const char *op_str = (const char*)qstr_data(op, &op_len);
+    const char *op_str = (const char *)qstr_data(op, &op_len);
 
     if (n_args == 0) {
         if (op == MP_QSTR_ret_n) {
diff --git a/py/emitnative.c b/py/emitnative.c
index da60c11..7deabe3 100644
--- a/py/emitnative.c
+++ b/py/emitnative.c
@@ -135,7 +135,7 @@
 
 #define EMIT_NATIVE_VIPER_TYPE_ERROR(emit, ...) do { \
         *emit->error_slot = mp_obj_new_exception_msg_varg(&mp_type_ViperTypeError, __VA_ARGS__); \
-    } while (0)
+} while (0)
 
 typedef enum {
     STACK_VALUE,
@@ -163,15 +163,25 @@
 
 STATIC qstr vtype_to_qstr(vtype_kind_t vtype) {
     switch (vtype) {
-        case VTYPE_PYOBJ: return MP_QSTR_object;
-        case VTYPE_BOOL: return MP_QSTR_bool;
-        case VTYPE_INT: return MP_QSTR_int;
-        case VTYPE_UINT: return MP_QSTR_uint;
-        case VTYPE_PTR: return MP_QSTR_ptr;
-        case VTYPE_PTR8: return MP_QSTR_ptr8;
-        case VTYPE_PTR16: return MP_QSTR_ptr16;
-        case VTYPE_PTR32: return MP_QSTR_ptr32;
-        case VTYPE_PTR_NONE: default: return MP_QSTR_None;
+        case VTYPE_PYOBJ:
+            return MP_QSTR_object;
+        case VTYPE_BOOL:
+            return MP_QSTR_bool;
+        case VTYPE_INT:
+            return MP_QSTR_int;
+        case VTYPE_UINT:
+            return MP_QSTR_uint;
+        case VTYPE_PTR:
+            return MP_QSTR_ptr;
+        case VTYPE_PTR8:
+            return MP_QSTR_ptr8;
+        case VTYPE_PTR16:
+            return MP_QSTR_ptr16;
+        case VTYPE_PTR32:
+            return MP_QSTR_ptr32;
+        case VTYPE_PTR_NONE:
+        default:
+            return MP_QSTR_None;
     }
 }
 
@@ -244,7 +254,7 @@
 STATIC void emit_native_global_exc_exit(emit_t *emit);
 STATIC void emit_native_load_const_obj(emit_t *emit, mp_obj_t obj);
 
-emit_t *EXPORT_FUN(new)(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels) {
+emit_t *EXPORT_FUN(new)(mp_obj_t * error_slot, uint *label_slot, mp_uint_t max_num_labels) {
     emit_t *emit = m_new0(emit_t, 1);
     emit->error_slot = error_slot;
     emit->label_slot = label_slot;
@@ -257,7 +267,7 @@
     return emit;
 }
 
-void EXPORT_FUN(free)(emit_t *emit) {
+void EXPORT_FUN(free)(emit_t * emit) {
     mp_asm_base_deinit(&emit->as->base, false);
     m_del_obj(ASM_T, emit->as);
     m_del(exc_stack_entry_t, emit->exc_stack, emit->exc_stack_alloc);
@@ -733,14 +743,14 @@
     if (emit->pass > MP_PASS_SCOPE && emit->stack_size > emit->scope->stack_size) {
         emit->scope->stack_size = emit->stack_size;
     }
-#ifdef DEBUG_PRINT
+    #ifdef DEBUG_PRINT
     DEBUG_printf("  adjust_stack; stack_size=%d+%d; stack now:", emit->stack_size - stack_size_delta, stack_size_delta);
     for (int i = 0; i < emit->stack_size; i++) {
         stack_info_t *si = &emit->stack_info[i];
         DEBUG_printf(" (v=%d k=%d %d)", si->vtype, si->kind, si->data.u_reg);
     }
     DEBUG_printf("\n");
-#endif
+    #endif
 }
 
 STATIC void emit_native_adjust_stack_size(emit_t *emit, mp_int_t delta) {
@@ -1132,8 +1142,8 @@
 
     bool is_finally = false;
     if (emit->exc_stack_size > 0) {
-       exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size - 1];
-       is_finally = e->is_finally && e->label == l;
+        exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size - 1];
+        is_finally = e->is_finally && e->label == l;
     }
 
     if (is_finally) {
@@ -2423,7 +2433,7 @@
                 asm_xtensa_setcc_reg_reg_reg(emit->as, cc & ~0x80, REG_RET, reg_rhs, REG_ARG_2);
             }
             #else
-                #error not implemented
+            #error not implemented
             #endif
             emit_post_push_reg(emit, VTYPE_BOOL, REG_RET);
         } else {
diff --git a/py/formatfloat.c b/py/formatfloat.c
index dc7fc1d..50fc0da 100644
--- a/py/formatfloat.c
+++ b/py/formatfloat.c
@@ -68,11 +68,20 @@
     float f;
     uint32_t u;
 };
-static inline int fp_signbit(float x) { union floatbits fb = {x}; return fb.u & FLT_SIGN_MASK; }
+static inline int fp_signbit(float x) {
+    union floatbits fb = {x};
+    return fb.u & FLT_SIGN_MASK;
+}
 #define fp_isnan(x) isnan(x)
 #define fp_isinf(x) isinf(x)
-static inline int fp_iszero(float x) { union floatbits fb = {x}; return fb.u == 0; }
-static inline int fp_isless1(float x) { union floatbits fb = {x}; return fb.u < 0x3f800000; }
+static inline int fp_iszero(float x) {
+    union floatbits fb = {x};
+    return fb.u == 0;
+}
+static inline int fp_isless1(float x) {
+    union floatbits fb = {x};
+    return fb.u < 0x3f800000;
+}
 
 #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
 
@@ -282,7 +291,7 @@
         if (fmt == 'e' && prec > (buf_remaining - FPMIN_BUF_SIZE)) {
             prec = buf_remaining - FPMIN_BUF_SIZE;
         }
-        if (fmt == 'g'){
+        if (fmt == 'g') {
             // Truncate precision to prevent buffer overflow
             if (prec + (FPMIN_BUF_SIZE - 1) > buf_remaining) {
                 prec = buf_remaining - (FPMIN_BUF_SIZE - 1);
diff --git a/py/frozenmod.c b/py/frozenmod.c
index 06d4f84..a250c02 100644
--- a/py/frozenmod.c
+++ b/py/frozenmod.c
@@ -146,7 +146,7 @@
     #if MICROPY_MODULE_FROZEN_MPY
     const mp_raw_code_t *rc = mp_find_frozen_mpy(str, len);
     if (rc != NULL) {
-        *data = (void*)rc;
+        *data = (void *)rc;
         return MP_FROZEN_MPY;
     }
     #endif
diff --git a/py/gc.c b/py/gc.c
index 092dbc7..7d159ad 100644
--- a/py/gc.c
+++ b/py/gc.c
@@ -82,7 +82,7 @@
 #define ATB_HEAD_TO_MARK(block) do { MP_STATE_MEM(gc_alloc_table_start)[(block) / BLOCKS_PER_ATB] |= (AT_MARK << BLOCK_SHIFT(block)); } while (0)
 #define ATB_MARK_TO_HEAD(block) do { MP_STATE_MEM(gc_alloc_table_start)[(block) / BLOCKS_PER_ATB] &= (~(AT_TAIL << BLOCK_SHIFT(block))); } while (0)
 
-#define BLOCK_FROM_PTR(ptr) (((byte*)(ptr) - MP_STATE_MEM(gc_pool_start)) / BYTES_PER_BLOCK)
+#define BLOCK_FROM_PTR(ptr) (((byte *)(ptr) - MP_STATE_MEM(gc_pool_start)) / BYTES_PER_BLOCK)
 #define PTR_FROM_BLOCK(block) (((block) * BYTES_PER_BLOCK + (uintptr_t)MP_STATE_MEM(gc_pool_start)))
 #define ATB_FROM_BLOCK(bl) ((bl) / BLOCKS_PER_ATB)
 
@@ -108,43 +108,43 @@
 // TODO waste less memory; currently requires that all entries in alloc_table have a corresponding block in pool
 void gc_init(void *start, void *end) {
     // align end pointer on block boundary
-    end = (void*)((uintptr_t)end & (~(BYTES_PER_BLOCK - 1)));
-    DEBUG_printf("Initializing GC heap: %p..%p = " UINT_FMT " bytes\n", start, end, (byte*)end - (byte*)start);
+    end = (void *)((uintptr_t)end & (~(BYTES_PER_BLOCK - 1)));
+    DEBUG_printf("Initializing GC heap: %p..%p = " UINT_FMT " bytes\n", start, end, (byte *)end - (byte *)start);
 
     // calculate parameters for GC (T=total, A=alloc table, F=finaliser table, P=pool; all in bytes):
     // T = A + F + P
     //     F = A * BLOCKS_PER_ATB / BLOCKS_PER_FTB
     //     P = A * BLOCKS_PER_ATB * BYTES_PER_BLOCK
     // => T = A * (1 + BLOCKS_PER_ATB / BLOCKS_PER_FTB + BLOCKS_PER_ATB * BYTES_PER_BLOCK)
-    size_t total_byte_len = (byte*)end - (byte*)start;
-#if MICROPY_ENABLE_FINALISER
+    size_t total_byte_len = (byte *)end - (byte *)start;
+    #if MICROPY_ENABLE_FINALISER
     MP_STATE_MEM(gc_alloc_table_byte_len) = total_byte_len * BITS_PER_BYTE / (BITS_PER_BYTE + BITS_PER_BYTE * BLOCKS_PER_ATB / BLOCKS_PER_FTB + BITS_PER_BYTE * BLOCKS_PER_ATB * BYTES_PER_BLOCK);
-#else
+    #else
     MP_STATE_MEM(gc_alloc_table_byte_len) = total_byte_len / (1 + BITS_PER_BYTE / 2 * BYTES_PER_BLOCK);
-#endif
+    #endif
 
-    MP_STATE_MEM(gc_alloc_table_start) = (byte*)start;
+    MP_STATE_MEM(gc_alloc_table_start) = (byte *)start;
 
-#if MICROPY_ENABLE_FINALISER
+    #if MICROPY_ENABLE_FINALISER
     size_t gc_finaliser_table_byte_len = (MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB + BLOCKS_PER_FTB - 1) / BLOCKS_PER_FTB;
     MP_STATE_MEM(gc_finaliser_table_start) = MP_STATE_MEM(gc_alloc_table_start) + MP_STATE_MEM(gc_alloc_table_byte_len);
-#endif
+    #endif
 
     size_t gc_pool_block_len = MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB;
-    MP_STATE_MEM(gc_pool_start) = (byte*)end - gc_pool_block_len * BYTES_PER_BLOCK;
+    MP_STATE_MEM(gc_pool_start) = (byte *)end - gc_pool_block_len * BYTES_PER_BLOCK;
     MP_STATE_MEM(gc_pool_end) = end;
 
-#if MICROPY_ENABLE_FINALISER
+    #if MICROPY_ENABLE_FINALISER
     assert(MP_STATE_MEM(gc_pool_start) >= MP_STATE_MEM(gc_finaliser_table_start) + gc_finaliser_table_byte_len);
-#endif
+    #endif
 
     // clear ATBs
     memset(MP_STATE_MEM(gc_alloc_table_start), 0, MP_STATE_MEM(gc_alloc_table_byte_len));
 
-#if MICROPY_ENABLE_FINALISER
+    #if MICROPY_ENABLE_FINALISER
     // clear FTBs
     memset(MP_STATE_MEM(gc_finaliser_table_start), 0, gc_finaliser_table_byte_len);
-#endif
+    #endif
 
     // set last free ATB index to start of heap
     MP_STATE_MEM(gc_last_free_atb_index) = 0;
@@ -167,9 +167,9 @@
 
     DEBUG_printf("GC layout:\n");
     DEBUG_printf("  alloc table at %p, length " UINT_FMT " bytes, " UINT_FMT " blocks\n", MP_STATE_MEM(gc_alloc_table_start), MP_STATE_MEM(gc_alloc_table_byte_len), MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB);
-#if MICROPY_ENABLE_FINALISER
+    #if MICROPY_ENABLE_FINALISER
     DEBUG_printf("  finaliser table at %p, length " UINT_FMT " bytes, " UINT_FMT " blocks\n", MP_STATE_MEM(gc_finaliser_table_start), gc_finaliser_table_byte_len, gc_finaliser_table_byte_len * BLOCKS_PER_FTB);
-#endif
+    #endif
     DEBUG_printf("  pool at %p, length " UINT_FMT " bytes, " UINT_FMT " blocks\n", MP_STATE_MEM(gc_pool_start), gc_pool_block_len * BYTES_PER_BLOCK, gc_pool_block_len);
 }
 
@@ -191,9 +191,9 @@
 
 // ptr should be of type void*
 #define VERIFY_PTR(ptr) ( \
-        ((uintptr_t)(ptr) & (BYTES_PER_BLOCK - 1)) == 0      /* must be aligned on a block */ \
-        && ptr >= (void*)MP_STATE_MEM(gc_pool_start)     /* must be above start of pool */ \
-        && ptr < (void*)MP_STATE_MEM(gc_pool_end)        /* must be below end of pool */ \
+    ((uintptr_t)(ptr) & (BYTES_PER_BLOCK - 1)) == 0          /* must be aligned on a block */ \
+    && ptr >= (void *)MP_STATE_MEM(gc_pool_start)        /* must be above start of pool */ \
+    && ptr < (void *)MP_STATE_MEM(gc_pool_end)           /* must be below end of pool */ \
     )
 
 #ifndef TRACE_MARK
@@ -219,8 +219,8 @@
         } while (ATB_GET_KIND(block + n_blocks) == AT_TAIL);
 
         // check this block's children
-        void **ptrs = (void**)PTR_FROM_BLOCK(block);
-        for (size_t i = n_blocks * BYTES_PER_BLOCK / sizeof(void*); i > 0; i--, ptrs++) {
+        void **ptrs = (void **)PTR_FROM_BLOCK(block);
+        for (size_t i = n_blocks * BYTES_PER_BLOCK / sizeof(void *); i > 0; i--, ptrs++) {
             void *ptr = *ptrs;
             if (VERIFY_PTR(ptr)) {
                 // Mark and push this pointer
@@ -271,9 +271,9 @@
     for (size_t block = 0; block < MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB; block++) {
         switch (ATB_GET_KIND(block)) {
             case AT_HEAD:
-#if MICROPY_ENABLE_FINALISER
+                #if MICROPY_ENABLE_FINALISER
                 if (FTB_GET(block)) {
-                    mp_obj_base_t *obj = (mp_obj_base_t*)PTR_FROM_BLOCK(block);
+                    mp_obj_base_t *obj = (mp_obj_base_t *)PTR_FROM_BLOCK(block);
                     if (obj->type != NULL) {
                         // if the object has a type then see if it has a __del__ method
                         mp_obj_t dest[2];
@@ -292,19 +292,19 @@
                     // clear finaliser flag
                     FTB_CLEAR(block);
                 }
-#endif
+                #endif
                 free_tail = 1;
                 DEBUG_printf("gc_sweep(%p)\n", PTR_FROM_BLOCK(block));
                 #if MICROPY_PY_GC_COLLECT_RETVAL
                 MP_STATE_MEM(gc_collected)++;
                 #endif
-                // fall through to free the head
+            // fall through to free the head
 
             case AT_TAIL:
                 if (free_tail) {
                     ATB_ANY_TO_FREE(block);
                     #if CLEAR_ON_SWEEP
-                    memset((void*)PTR_FROM_BLOCK(block), 0, BYTES_PER_BLOCK);
+                    memset((void *)PTR_FROM_BLOCK(block), 0, BYTES_PER_BLOCK);
                     #endif
                 }
                 break;
@@ -328,15 +328,15 @@
     // Trace root pointers.  This relies on the root pointers being organised
     // correctly in the mp_state_ctx structure.  We scan nlr_top, dict_locals,
     // dict_globals, then the root pointer section of mp_state_vm.
-    void **ptrs = (void**)(void*)&mp_state_ctx;
+    void **ptrs = (void **)(void *)&mp_state_ctx;
     size_t root_start = offsetof(mp_state_ctx_t, thread.dict_locals);
     size_t root_end = offsetof(mp_state_ctx_t, vm.qstr_last_chunk);
-    gc_collect_root(ptrs + root_start / sizeof(void*), (root_end - root_start) / sizeof(void*));
+    gc_collect_root(ptrs + root_start / sizeof(void *), (root_end - root_start) / sizeof(void *));
 
     #if MICROPY_ENABLE_PYSTACK
     // Trace root pointers from the Python stack.
-    ptrs = (void**)(void*)MP_STATE_THREAD(pystack_start);
-    gc_collect_root(ptrs, (MP_STATE_THREAD(pystack_cur) - MP_STATE_THREAD(pystack_start)) / sizeof(void*));
+    ptrs = (void **)(void *)MP_STATE_THREAD(pystack_start);
+    gc_collect_root(ptrs, (MP_STATE_THREAD(pystack_cur) - MP_STATE_THREAD(pystack_start)) / sizeof(void *));
     #endif
 }
 
@@ -518,7 +518,7 @@
 
     // get pointer to first block
     // we must create this pointer before unlocking the GC so a collection can find it
-    void *ret_ptr = (void*)(MP_STATE_MEM(gc_pool_start) + start_block * BYTES_PER_BLOCK);
+    void *ret_ptr = (void *)(MP_STATE_MEM(gc_pool_start) + start_block * BYTES_PER_BLOCK);
     DEBUG_printf("gc_alloc(%p)\n", ret_ptr);
 
     #if MICROPY_GC_ALLOC_THRESHOLD
@@ -529,20 +529,20 @@
 
     #if MICROPY_GC_CONSERVATIVE_CLEAR
     // be conservative and zero out all the newly allocated blocks
-    memset((byte*)ret_ptr, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK);
+    memset((byte *)ret_ptr, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK);
     #else
     // zero out the additional bytes of the newly allocated blocks
     // This is needed because the blocks may have previously held pointers
     // to the heap and will not be set to something else if the caller
     // doesn't actually use the entire block.  As such they will continue
     // to point to the heap and may prevent other blocks from being reclaimed.
-    memset((byte*)ret_ptr + n_bytes, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK - n_bytes);
+    memset((byte *)ret_ptr + n_bytes, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK - n_bytes);
     #endif
 
     #if MICROPY_ENABLE_FINALISER
     if (has_finaliser) {
         // clear type pointer in case it is never set
-        ((mp_obj_base_t*)ret_ptr)->type = NULL;
+        ((mp_obj_base_t *)ret_ptr)->type = NULL;
         // set mp_obj flag only if it has a finaliser
         GC_ENTER();
         FTB_SET(start_block);
@@ -643,11 +643,11 @@
         if (ptr == NULL) {
             has_finaliser = false;
         } else {
-#if MICROPY_ENABLE_FINALISER
+            #if MICROPY_ENABLE_FINALISER
             has_finaliser = FTB_GET(BLOCK_FROM_PTR((mp_uint_t)ptr));
-#else
+            #else
             has_finaliser = false;
-#endif
+            #endif
         }
         void *ptr2 = gc_alloc(n_bytes, has_finaliser);
         if (ptr2 == NULL) {
@@ -696,7 +696,7 @@
     // free blocks to satisfy the realloc.  Note that we need to compute the
     // total size of the existing memory chunk so we can correctly and
     // efficiently shrink it (see below for shrinking code).
-    size_t n_free   = 0;
+    size_t n_free = 0;
     size_t n_blocks = 1; // counting HEAD block
     size_t max_block = MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB;
     for (size_t bl = block + n_blocks; bl < max_block; bl++) {
@@ -755,10 +755,10 @@
 
         #if MICROPY_GC_CONSERVATIVE_CLEAR
         // be conservative and zero out all the newly allocated blocks
-        memset((byte*)ptr_in + n_blocks * BYTES_PER_BLOCK, 0, (new_blocks - n_blocks) * BYTES_PER_BLOCK);
+        memset((byte *)ptr_in + n_blocks * BYTES_PER_BLOCK, 0, (new_blocks - n_blocks) * BYTES_PER_BLOCK);
         #else
         // zero out the additional bytes of the newly allocated blocks (see comment above in gc_alloc)
-        memset((byte*)ptr_in + n_bytes, 0, new_blocks * BYTES_PER_BLOCK - n_bytes);
+        memset((byte *)ptr_in + n_bytes, 0, new_blocks * BYTES_PER_BLOCK - n_bytes);
         #endif
 
         #if EXTENSIVE_HEAP_PROFILING
@@ -802,7 +802,7 @@
     mp_printf(&mp_plat_print, "GC: total: %u, used: %u, free: %u\n",
         (uint)info.total, (uint)info.used, (uint)info.free);
     mp_printf(&mp_plat_print, " No. of 1-blocks: %u, 2-blocks: %u, max blk sz: %u, max free sz: %u\n",
-           (uint)info.num_1block, (uint)info.num_2block, (uint)info.max_block, (uint)info.max_free);
+        (uint)info.num_1block, (uint)info.num_2block, (uint)info.max_block, (uint)info.max_free);
 }
 
 void gc_dump_alloc_table(void) {
@@ -839,7 +839,9 @@
         }
         int c = ' ';
         switch (ATB_GET_KIND(bl)) {
-            case AT_FREE: c = '.'; break;
+            case AT_FREE:
+                c = '.';
+                break;
             /* this prints out if the object is reachable from BSS or STACK (for unix only)
             case AT_HEAD: {
                 c = 'h';
@@ -868,35 +870,48 @@
             */
             /* this prints the uPy object type of the head block */
             case AT_HEAD: {
-                void **ptr = (void**)(MP_STATE_MEM(gc_pool_start) + bl * BYTES_PER_BLOCK);
-                if (*ptr == &mp_type_tuple) { c = 'T'; }
-                else if (*ptr == &mp_type_list) { c = 'L'; }
-                else if (*ptr == &mp_type_dict) { c = 'D'; }
-                else if (*ptr == &mp_type_str || *ptr == &mp_type_bytes) { c = 'S'; }
+                void **ptr = (void **)(MP_STATE_MEM(gc_pool_start) + bl * BYTES_PER_BLOCK);
+                if (*ptr == &mp_type_tuple) {
+                    c = 'T';
+                } else if (*ptr == &mp_type_list) {
+                    c = 'L';
+                } else if (*ptr == &mp_type_dict) {
+                    c = 'D';
+                } else if (*ptr == &mp_type_str || *ptr == &mp_type_bytes) {
+                    c = 'S';
+                }
                 #if MICROPY_PY_BUILTINS_BYTEARRAY
-                else if (*ptr == &mp_type_bytearray) { c = 'A'; }
+                else if (*ptr == &mp_type_bytearray) {
+                    c = 'A';
+                }
                 #endif
                 #if MICROPY_PY_ARRAY
-                else if (*ptr == &mp_type_array) { c = 'A'; }
+                else if (*ptr == &mp_type_array) {
+                    c = 'A';
+                }
                 #endif
                 #if MICROPY_PY_BUILTINS_FLOAT
-                else if (*ptr == &mp_type_float) { c = 'F'; }
+                else if (*ptr == &mp_type_float) {
+                    c = 'F';
+                }
                 #endif
-                else if (*ptr == &mp_type_fun_bc) { c = 'B'; }
-                else if (*ptr == &mp_type_module) { c = 'M'; }
-                else {
+                else if (*ptr == &mp_type_fun_bc) {
+                    c = 'B';
+                } else if (*ptr == &mp_type_module) {
+                    c = 'M';
+                } else {
                     c = 'h';
                     #if 0
                     // This code prints "Q" for qstr-pool data, and "q" for qstr-str
                     // data.  It can be useful to see how qstrs are being allocated,
                     // but is disabled by default because it is very slow.
                     for (qstr_pool_t *pool = MP_STATE_VM(last_pool); c == 'h' && pool != NULL; pool = pool->prev) {
-                        if ((qstr_pool_t*)ptr == pool) {
+                        if ((qstr_pool_t *)ptr == pool) {
                             c = 'Q';
                             break;
                         }
                         for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) {
-                            if ((const byte*)ptr == *q) {
+                            if ((const byte *)ptr == *q) {
                                 c = 'q';
                                 break;
                             }
@@ -906,8 +921,12 @@
                 }
                 break;
             }
-            case AT_TAIL: c = '='; break;
-            case AT_MARK: c = 'm'; break;
+            case AT_TAIL:
+                c = '=';
+                break;
+            case AT_MARK:
+                c = 'm';
+                break;
         }
         mp_printf(&mp_plat_print, "%c", c);
     }
@@ -933,7 +952,7 @@
         p2[1] = p;
         ptrs[0] = p2;
     }
-    for (int i = 0; i < 25; i+=2) {
+    for (int i = 0; i < 25; i += 2) {
         mp_uint_t *p = gc_alloc(i, false);
         printf("p=%p\n", p);
         if (i & 3) {
@@ -945,7 +964,7 @@
     gc_dump_alloc_table();
     printf("Starting GC...\n");
     gc_collect_start();
-    gc_collect_root(ptrs, sizeof(ptrs) / sizeof(void*));
+    gc_collect_root(ptrs, sizeof(ptrs) / sizeof(void *));
     gc_collect_end();
     printf("After GC:\n");
     gc_dump_alloc_table();
diff --git a/py/lexer.c b/py/lexer.c
index 5f8adda..73ff5ec 100644
--- a/py/lexer.c
+++ b/py/lexer.c
@@ -105,9 +105,9 @@
 
 STATIC bool is_string_or_bytes(mp_lexer_t *lex) {
     return is_char_or(lex, '\'', '\"')
-        || (is_char_or3(lex, 'r', 'u', 'b') && is_char_following_or(lex, '\'', '\"'))
-        || ((is_char_and(lex, 'r', 'b') || is_char_and(lex, 'b', 'r'))
-            && is_char_following_following_or(lex, '\'', '\"'));
+           || (is_char_or3(lex, 'r', 'u', 'b') && is_char_following_or(lex, '\'', '\"'))
+           || ((is_char_and(lex, 'r', 'b') || is_char_and(lex, 'b', 'r'))
+               && is_char_following_following_or(lex, '\'', '\"'));
 }
 
 // to easily parse utf-8 identifiers we allow any raw byte with high bit set
@@ -307,17 +307,36 @@
                     switch (c) {
                         // note: "c" can never be MP_LEXER_EOF because next_char
                         // always inserts a newline at the end of the input stream
-                        case '\n': c = MP_LEXER_EOF; break; // backslash escape the newline, just ignore it
-                        case '\\': break;
-                        case '\'': break;
-                        case '"': break;
-                        case 'a': c = 0x07; break;
-                        case 'b': c = 0x08; break;
-                        case 't': c = 0x09; break;
-                        case 'n': c = 0x0a; break;
-                        case 'v': c = 0x0b; break;
-                        case 'f': c = 0x0c; break;
-                        case 'r': c = 0x0d; break;
+                        case '\n':
+                            c = MP_LEXER_EOF;
+                            break;                          // backslash escape the newline, just ignore it
+                        case '\\':
+                            break;
+                        case '\'':
+                            break;
+                        case '"':
+                            break;
+                        case 'a':
+                            c = 0x07;
+                            break;
+                        case 'b':
+                            c = 0x08;
+                            break;
+                        case 't':
+                            c = 0x09;
+                            break;
+                        case 'n':
+                            c = 0x0a;
+                            break;
+                        case 'v':
+                            c = 0x0b;
+                            break;
+                        case 'f':
+                            c = 0x0c;
+                            break;
+                        case 'r':
+                            c = 0x0d;
+                            break;
                         case 'u':
                         case 'U':
                             if (lex->tok_kind == MP_TOKEN_BYTES) {
@@ -325,9 +344,8 @@
                                 vstr_add_char(&lex->vstr, '\\');
                                 break;
                             }
-                            // Otherwise fall through.
-                        case 'x':
-                        {
+                        // Otherwise fall through.
+                        case 'x': {
                             mp_uint_t num = 0;
                             if (!get_hex(lex, (c == 'x' ? 2 : c == 'u' ? 4 : 8), &num)) {
                                 // not enough hex chars for escape sequence
@@ -707,7 +725,7 @@
 
 mp_lexer_t *mp_lexer_new_from_str_len(qstr src_name, const char *str, size_t len, size_t free_len) {
     mp_reader_t reader;
-    mp_reader_new_mem(&reader, (const byte*)str, len, free_len);
+    mp_reader_new_mem(&reader, (const byte *)str, len, free_len);
     return mp_lexer_new(src_name, reader);
 }
 
diff --git a/py/makemoduledefs.py b/py/makemoduledefs.py
index f17b0e3..d718da6 100644
--- a/py/makemoduledefs.py
+++ b/py/makemoduledefs.py
@@ -13,10 +13,7 @@
 import argparse
 
 
-pattern = re.compile(
-    r"[\n;]\s*MP_REGISTER_MODULE\((.*?),\s*(.*?),\s*(.*?)\);",
-    flags=re.DOTALL
-)
+pattern = re.compile(r"[\n;]\s*MP_REGISTER_MODULE\((.*?),\s*(.*?),\s*(.*?)\);", flags=re.DOTALL)
 
 
 def find_c_file(obj_file, vpath):
@@ -28,7 +25,7 @@
     """
     c_file = None
     relative_c_file = os.path.splitext(obj_file)[0] + ".c"
-    relative_c_file = relative_c_file.lstrip('/\\')
+    relative_c_file = relative_c_file.lstrip("/\\")
     for p in vpath:
         possible_c_file = os.path.join(p, relative_c_file)
         if os.path.exists(possible_c_file):
@@ -50,7 +47,7 @@
         # No c file to match the object file, skip
         return set()
 
-    with io.open(c_file, encoding='utf-8') as c_file_obj:
+    with io.open(c_file, encoding="utf-8") as c_file_obj:
         return set(re.findall(pattern, c_file_obj.read()))
 
 
@@ -67,15 +64,20 @@
     for module_name, obj_module, enabled_define in modules:
         mod_def = "MODULE_DEF_{}".format(module_name.upper())
         mod_defs.append(mod_def)
-        print((
-            "#if ({enabled_define})\n"
-            "    extern const struct _mp_obj_module_t {obj_module};\n"
-            "    #define {mod_def} {{ MP_ROM_QSTR({module_name}), MP_ROM_PTR(&{obj_module}) }},\n"
-            "#else\n"
-            "    #define {mod_def}\n"
-            "#endif\n"
-            ).format(module_name=module_name, obj_module=obj_module,
-                     enabled_define=enabled_define, mod_def=mod_def)
+        print(
+            (
+                "#if ({enabled_define})\n"
+                "    extern const struct _mp_obj_module_t {obj_module};\n"
+                "    #define {mod_def} {{ MP_ROM_QSTR({module_name}), MP_ROM_PTR(&{obj_module}) }},\n"
+                "#else\n"
+                "    #define {mod_def}\n"
+                "#endif\n"
+            ).format(
+                module_name=module_name,
+                obj_module=obj_module,
+                enabled_define=enabled_define,
+                mod_def=mod_def,
+            )
         )
 
     print("\n#define MICROPY_REGISTERED_MODULES \\")
@@ -88,13 +90,13 @@
 
 def main():
     parser = argparse.ArgumentParser()
-    parser.add_argument("--vpath", default=".",
-                        help="comma separated list of folders to search for c files in")
-    parser.add_argument("files", nargs="*",
-                        help="list of c files to search")
+    parser.add_argument(
+        "--vpath", default=".", help="comma separated list of folders to search for c files in"
+    )
+    parser.add_argument("files", nargs="*", help="list of c files to search")
     args = parser.parse_args()
 
-    vpath = [p.strip() for p in args.vpath.split(',')]
+    vpath = [p.strip() for p in args.vpath.split(",")]
 
     modules = set()
     for obj_file in args.files:
@@ -104,5 +106,5 @@
     generate_module_table_header(sorted(modules))
 
 
-if __name__ == '__main__':
+if __name__ == "__main__":
     main()
diff --git a/py/makeqstrdata.py b/py/makeqstrdata.py
index 7799be0..403c406 100644
--- a/py/makeqstrdata.py
+++ b/py/makeqstrdata.py
@@ -13,49 +13,50 @@
 #   - iterating through bytes is different
 #   - codepoint2name lives in a different module
 import platform
-if platform.python_version_tuple()[0] == '2':
+
+if platform.python_version_tuple()[0] == "2":
     bytes_cons = lambda val, enc=None: bytearray(val)
     from htmlentitydefs import codepoint2name
-elif platform.python_version_tuple()[0] == '3':
+elif platform.python_version_tuple()[0] == "3":
     bytes_cons = bytes
     from html.entities import codepoint2name
 # end compatibility code
 
-codepoint2name[ord('-')] = 'hyphen';
+codepoint2name[ord("-")] = "hyphen"
 
 # add some custom names to map characters that aren't in HTML
-codepoint2name[ord(' ')] = 'space'
-codepoint2name[ord('\'')] = 'squot'
-codepoint2name[ord(',')] = 'comma'
-codepoint2name[ord('.')] = 'dot'
-codepoint2name[ord(':')] = 'colon'
-codepoint2name[ord(';')] = 'semicolon'
-codepoint2name[ord('/')] = 'slash'
-codepoint2name[ord('%')] = 'percent'
-codepoint2name[ord('#')] = 'hash'
-codepoint2name[ord('(')] = 'paren_open'
-codepoint2name[ord(')')] = 'paren_close'
-codepoint2name[ord('[')] = 'bracket_open'
-codepoint2name[ord(']')] = 'bracket_close'
-codepoint2name[ord('{')] = 'brace_open'
-codepoint2name[ord('}')] = 'brace_close'
-codepoint2name[ord('*')] = 'star'
-codepoint2name[ord('!')] = 'bang'
-codepoint2name[ord('\\')] = 'backslash'
-codepoint2name[ord('+')] = 'plus'
-codepoint2name[ord('$')] = 'dollar'
-codepoint2name[ord('=')] = 'equals'
-codepoint2name[ord('?')] = 'question'
-codepoint2name[ord('@')] = 'at_sign'
-codepoint2name[ord('^')] = 'caret'
-codepoint2name[ord('|')] = 'pipe'
-codepoint2name[ord('~')] = 'tilde'
+codepoint2name[ord(" ")] = "space"
+codepoint2name[ord("'")] = "squot"
+codepoint2name[ord(",")] = "comma"
+codepoint2name[ord(".")] = "dot"
+codepoint2name[ord(":")] = "colon"
+codepoint2name[ord(";")] = "semicolon"
+codepoint2name[ord("/")] = "slash"
+codepoint2name[ord("%")] = "percent"
+codepoint2name[ord("#")] = "hash"
+codepoint2name[ord("(")] = "paren_open"
+codepoint2name[ord(")")] = "paren_close"
+codepoint2name[ord("[")] = "bracket_open"
+codepoint2name[ord("]")] = "bracket_close"
+codepoint2name[ord("{")] = "brace_open"
+codepoint2name[ord("}")] = "brace_close"
+codepoint2name[ord("*")] = "star"
+codepoint2name[ord("!")] = "bang"
+codepoint2name[ord("\\")] = "backslash"
+codepoint2name[ord("+")] = "plus"
+codepoint2name[ord("$")] = "dollar"
+codepoint2name[ord("=")] = "equals"
+codepoint2name[ord("?")] = "question"
+codepoint2name[ord("@")] = "at_sign"
+codepoint2name[ord("^")] = "caret"
+codepoint2name[ord("|")] = "pipe"
+codepoint2name[ord("~")] = "tilde"
 
 # static qstrs, should be sorted
 
 static_qstr_list = [
     "",
-    "__dir__", # Put __dir__ after empty qstr for builtin dir() to work
+    "__dir__",  # Put __dir__ after empty qstr for builtin dir() to work
     "\n",
     " ",
     "*",
@@ -229,15 +230,18 @@
     # Make sure that valid hash is never zero, zero means "hash not computed"
     return (hash & ((1 << (8 * bytes_hash)) - 1)) or 1
 
+
 def qstr_escape(qst):
     def esc_char(m):
         c = ord(m.group(0))
         try:
             name = codepoint2name[c]
         except KeyError:
-            name = '0x%02x' % c
-        return "_" + name + '_'
-    return re.sub(r'[^A-Za-z0-9_]', esc_char, qst)
+            name = "0x%02x" % c
+        return "_" + name + "_"
+
+    return re.sub(r"[^A-Za-z0-9_]", esc_char, qst)
+
 
 def parse_input_headers(infiles):
     qcfgs = {}
@@ -257,22 +261,22 @@
 
     # read the qstrs in from the input files
     for infile in infiles:
-        with open(infile, 'rt') as f:
+        with open(infile, "rt") as f:
             for line in f:
                 line = line.strip()
 
                 # is this a config line?
-                match = re.match(r'^QCFG\((.+), (.+)\)', line)
+                match = re.match(r"^QCFG\((.+), (.+)\)", line)
                 if match:
                     value = match.group(2)
-                    if value[0] == '(' and value[-1] == ')':
+                    if value[0] == "(" and value[-1] == ")":
                         # strip parenthesis from config value
                         value = value[1:-1]
                     qcfgs[match.group(1)] = value
                     continue
 
                 # is this a QSTR line?
-                match = re.match(r'^Q\((.*)\)$', line)
+                match = re.match(r"^Q\((.*)\)$", line)
                 if not match:
                     continue
 
@@ -280,10 +284,10 @@
                 qstr = match.group(1)
 
                 # special cases to specify control characters
-                if qstr == '\\n':
-                    qstr = '\n'
-                elif qstr == '\\r\\n':
-                    qstr = '\r\n'
+                if qstr == "\\n":
+                    qstr = "\n"
+                elif qstr == "\\r\\n":
+                    qstr = "\r\n"
 
                 # work out the corresponding qstr name
                 ident = qstr_escape(qstr)
@@ -312,43 +316,54 @@
 
     return qcfgs, qstrs
 
+
 def make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr):
-    qbytes = bytes_cons(qstr, 'utf8')
+    qbytes = bytes_cons(qstr, "utf8")
     qlen = len(qbytes)
     qhash = compute_hash(qbytes, cfg_bytes_hash)
-    if all(32 <= ord(c) <= 126 and c != '\\' and c != '"' for c in qstr):
+    if all(32 <= ord(c) <= 126 and c != "\\" and c != '"' for c in qstr):
         # qstr is all printable ASCII so render it as-is (for easier debugging)
         qdata = qstr
     else:
         # qstr contains non-printable codes so render entire thing as hex pairs
-        qdata = ''.join(('\\x%02x' % b) for b in qbytes)
+        qdata = "".join(("\\x%02x" % b) for b in qbytes)
     if qlen >= (1 << (8 * cfg_bytes_len)):
-        print('qstr is too long:', qstr)
+        print("qstr is too long:", qstr)
         assert False
-    qlen_str = ('\\x%02x' * cfg_bytes_len) % tuple(((qlen >> (8 * i)) & 0xff) for i in range(cfg_bytes_len))
-    qhash_str = ('\\x%02x' * cfg_bytes_hash) % tuple(((qhash >> (8 * i)) & 0xff) for i in range(cfg_bytes_hash))
+    qlen_str = ("\\x%02x" * cfg_bytes_len) % tuple(
+        ((qlen >> (8 * i)) & 0xFF) for i in range(cfg_bytes_len)
+    )
+    qhash_str = ("\\x%02x" * cfg_bytes_hash) % tuple(
+        ((qhash >> (8 * i)) & 0xFF) for i in range(cfg_bytes_hash)
+    )
     return '(const byte*)"%s%s" "%s"' % (qhash_str, qlen_str, qdata)
 
+
 def print_qstr_data(qcfgs, qstrs):
     # get config variables
-    cfg_bytes_len = int(qcfgs['BYTES_IN_LEN'])
-    cfg_bytes_hash = int(qcfgs['BYTES_IN_HASH'])
+    cfg_bytes_len = int(qcfgs["BYTES_IN_LEN"])
+    cfg_bytes_hash = int(qcfgs["BYTES_IN_HASH"])
 
     # print out the starter of the generated C header file
-    print('// This file was automatically generated by makeqstrdata.py')
-    print('')
+    print("// This file was automatically generated by makeqstrdata.py")
+    print("")
 
     # add NULL qstr with no hash or data
-    print('QDEF(MP_QSTRnull, (const byte*)"%s%s" "")' % ('\\x00' * cfg_bytes_hash, '\\x00' * cfg_bytes_len))
+    print(
+        'QDEF(MP_QSTRnull, (const byte*)"%s%s" "")'
+        % ("\\x00" * cfg_bytes_hash, "\\x00" * cfg_bytes_len)
+    )
 
     # go through each qstr and print it out
     for order, ident, qstr in sorted(qstrs.values(), key=lambda x: x[0]):
         qbytes = make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr)
-        print('QDEF(MP_QSTR_%s, %s)' % (ident, qbytes))
+        print("QDEF(MP_QSTR_%s, %s)" % (ident, qbytes))
+
 
 def do_work(infiles):
     qcfgs, qstrs = parse_input_headers(infiles)
     print_qstr_data(qcfgs, qstrs)
 
+
 if __name__ == "__main__":
     do_work(sys.argv[1:])
diff --git a/py/makeqstrdefs.py b/py/makeqstrdefs.py
index 209e7a1..03ea1af 100644
--- a/py/makeqstrdefs.py
+++ b/py/makeqstrdefs.py
@@ -20,16 +20,17 @@
         with open(args.output_dir + "/" + fname + ".qstr", "w") as f:
             f.write("\n".join(output) + "\n")
 
+
 def process_file(f):
     re_line = re.compile(r"#[line]*\s\d+\s\"([^\"]+)\"")
-    re_qstr = re.compile(r'MP_QSTR_[_a-zA-Z0-9]+')
+    re_qstr = re.compile(r"MP_QSTR_[_a-zA-Z0-9]+")
     output = []
     last_fname = None
     for line in f:
         if line.isspace():
             continue
         # match gcc-like output (# n "file") and msvc-like output (#line n "file")
-        if line.startswith(('# ', '#line')):
+        if line.startswith(("# ", "#line")):
             m = re_line.match(line)
             assert m is not None
             fname = m.group(1)
@@ -41,8 +42,8 @@
                 last_fname = fname
             continue
         for match in re_qstr.findall(line):
-            name = match.replace('MP_QSTR_', '')
-            output.append('Q(' + name + ')')
+            name = match.replace("MP_QSTR_", "")
+            output.append("Q(" + name + ")")
 
     write_out(last_fname, output)
     return ""
@@ -51,6 +52,7 @@
 def cat_together():
     import glob
     import hashlib
+
     hasher = hashlib.md5()
     all_lines = []
     outf = open(args.output_dir + "/out", "wb")
@@ -64,7 +66,7 @@
     outf.close()
     hasher.update(all_lines)
     new_hash = hasher.hexdigest()
-    #print(new_hash)
+    # print(new_hash)
     old_hash = None
     try:
         with open(args.output_file + ".hash") as f:
@@ -87,11 +89,12 @@
 
 if __name__ == "__main__":
     if len(sys.argv) != 5:
-        print('usage: %s command input_filename output_dir output_file' % sys.argv[0])
+        print("usage: %s command input_filename output_dir output_file" % sys.argv[0])
         sys.exit(2)
 
     class Args:
         pass
+
     args = Args()
     args.command = sys.argv[1]
     args.input_filename = sys.argv[2]
@@ -104,7 +107,7 @@
         pass
 
     if args.command == "split":
-        with io.open(args.input_filename, encoding='utf-8') as infile:
+        with io.open(args.input_filename, encoding="utf-8") as infile:
             process_file(infile)
 
     if args.command == "cat":
diff --git a/py/makeversionhdr.py b/py/makeversionhdr.py
index 2ab99d8..567b3b8 100644
--- a/py/makeversionhdr.py
+++ b/py/makeversionhdr.py
@@ -11,6 +11,7 @@
 import datetime
 import subprocess
 
+
 def get_version_info_from_git():
     # Python 2.6 doesn't have check_output, so check for that
     try:
@@ -21,7 +22,11 @@
 
     # Note: git describe doesn't work if no tag is available
     try:
-        git_tag = subprocess.check_output(["git", "describe", "--dirty", "--always"], stderr=subprocess.STDOUT, universal_newlines=True).strip()
+        git_tag = subprocess.check_output(
+            ["git", "describe", "--dirty", "--always"],
+            stderr=subprocess.STDOUT,
+            universal_newlines=True,
+        ).strip()
     except subprocess.CalledProcessError as er:
         if er.returncode == 128:
             # git exit code of 128 means no repository found
@@ -30,7 +35,11 @@
     except OSError:
         return None
     try:
-        git_hash = subprocess.check_output(["git", "rev-parse", "--short", "HEAD"], stderr=subprocess.STDOUT, universal_newlines=True).strip()
+        git_hash = subprocess.check_output(
+            ["git", "rev-parse", "--short", "HEAD"],
+            stderr=subprocess.STDOUT,
+            universal_newlines=True,
+        ).strip()
     except subprocess.CalledProcessError:
         git_hash = "unknown"
     except OSError:
@@ -38,9 +47,13 @@
 
     try:
         # Check if there are any modified files.
-        subprocess.check_call(["git", "diff", "--no-ext-diff", "--quiet", "--exit-code"], stderr=subprocess.STDOUT)
+        subprocess.check_call(
+            ["git", "diff", "--no-ext-diff", "--quiet", "--exit-code"], stderr=subprocess.STDOUT
+        )
         # Check if there are any staged files.
-        subprocess.check_call(["git", "diff-index", "--cached", "--quiet", "HEAD", "--"], stderr=subprocess.STDOUT)
+        subprocess.check_call(
+            ["git", "diff-index", "--cached", "--quiet", "HEAD", "--"], stderr=subprocess.STDOUT
+        )
     except subprocess.CalledProcessError:
         git_hash += "-dirty"
     except OSError:
@@ -48,6 +61,7 @@
 
     return git_tag, git_hash
 
+
 def get_version_info_from_docs_conf():
     with open(os.path.join(os.path.dirname(sys.argv[0]), "..", "docs", "conf.py")) as f:
         for line in f:
@@ -57,6 +71,7 @@
                 return git_tag, "<no hash>"
     return None
 
+
 def make_version_header(filename):
     # Get version info using git, with fallback to docs/conf.py
     info = get_version_info_from_git()
@@ -71,12 +86,16 @@
 #define MICROPY_GIT_TAG "%s"
 #define MICROPY_GIT_HASH "%s"
 #define MICROPY_BUILD_DATE "%s"
-""" % (git_tag, git_hash, datetime.date.today().strftime("%Y-%m-%d"))
+""" % (
+        git_tag,
+        git_hash,
+        datetime.date.today().strftime("%Y-%m-%d"),
+    )
 
     # Check if the file contents changed from last time
     write_file = True
     if os.path.isfile(filename):
-        with open(filename, 'r') as f:
+        with open(filename, "r") as f:
             existing_data = f.read()
         if existing_data == file_data:
             write_file = False
@@ -84,8 +103,9 @@
     # Only write the file if we need to
     if write_file:
         print("GEN %s" % filename)
-        with open(filename, 'w') as f:
+        with open(filename, "w") as f:
             f.write(file_data)
 
+
 if __name__ == "__main__":
     make_version_header(sys.argv[1])
diff --git a/py/malloc.c b/py/malloc.c
index f5d82b4..c775d5b 100644
--- a/py/malloc.c
+++ b/py/malloc.c
@@ -87,22 +87,22 @@
     if (ptr == NULL && num_bytes != 0) {
         m_malloc_fail(num_bytes);
     }
-#if MICROPY_MEM_STATS
+    #if MICROPY_MEM_STATS
     MP_STATE_MEM(total_bytes_allocated) += num_bytes;
     MP_STATE_MEM(current_bytes_allocated) += num_bytes;
     UPDATE_PEAK();
-#endif
+    #endif
     DEBUG_printf("malloc %d : %p\n", num_bytes, ptr);
     return ptr;
 }
 
 void *m_malloc_maybe(size_t num_bytes) {
     void *ptr = malloc(num_bytes);
-#if MICROPY_MEM_STATS
+    #if MICROPY_MEM_STATS
     MP_STATE_MEM(total_bytes_allocated) += num_bytes;
     MP_STATE_MEM(current_bytes_allocated) += num_bytes;
     UPDATE_PEAK();
-#endif
+    #endif
     DEBUG_printf("malloc %d : %p\n", num_bytes, ptr);
     return ptr;
 }
@@ -113,11 +113,11 @@
     if (ptr == NULL && num_bytes != 0) {
         m_malloc_fail(num_bytes);
     }
-#if MICROPY_MEM_STATS
+    #if MICROPY_MEM_STATS
     MP_STATE_MEM(total_bytes_allocated) += num_bytes;
     MP_STATE_MEM(current_bytes_allocated) += num_bytes;
     UPDATE_PEAK();
-#endif
+    #endif
     DEBUG_printf("malloc %d : %p\n", num_bytes, ptr);
     return ptr;
 }
@@ -142,7 +142,7 @@
     if (new_ptr == NULL && new_num_bytes != 0) {
         m_malloc_fail(new_num_bytes);
     }
-#if MICROPY_MEM_STATS
+    #if MICROPY_MEM_STATS
     // At first thought, "Total bytes allocated" should only grow,
     // after all, it's *total*. But consider for example 2K block
     // shrunk to 1K and then grown to 2K again. It's still 2K
@@ -152,7 +152,7 @@
     MP_STATE_MEM(total_bytes_allocated) += diff;
     MP_STATE_MEM(current_bytes_allocated) += diff;
     UPDATE_PEAK();
-#endif
+    #endif
     #if MICROPY_MALLOC_USES_ALLOCATED_SIZE
     DEBUG_printf("realloc %p, %d, %d : %p\n", ptr, old_num_bytes, new_num_bytes, new_ptr);
     #else
@@ -168,7 +168,7 @@
 #endif
 {
     void *new_ptr = realloc_ext(ptr, new_num_bytes, allow_move);
-#if MICROPY_MEM_STATS
+    #if MICROPY_MEM_STATS
     // At first thought, "Total bytes allocated" should only grow,
     // after all, it's *total*. But consider for example 2K block
     // shrunk to 1K and then grown to 2K again. It's still 2K
@@ -181,7 +181,7 @@
         MP_STATE_MEM(current_bytes_allocated) += diff;
         UPDATE_PEAK();
     }
-#endif
+    #endif
     #if MICROPY_MALLOC_USES_ALLOCATED_SIZE
     DEBUG_printf("realloc %p, %d, %d : %p\n", ptr, old_num_bytes, new_num_bytes, new_ptr);
     #else
@@ -197,9 +197,9 @@
 #endif
 {
     free(ptr);
-#if MICROPY_MEM_STATS
+    #if MICROPY_MEM_STATS
     MP_STATE_MEM(current_bytes_allocated) -= num_bytes;
-#endif
+    #endif
     #if MICROPY_MALLOC_USES_ALLOCATED_SIZE
     DEBUG_printf("free %p, %d\n", ptr, num_bytes);
     #else
diff --git a/py/map.c b/py/map.c
index 5f3c6e5..2570941 100644
--- a/py/map.c
+++ b/py/map.c
@@ -96,7 +96,7 @@
     map->all_keys_are_qstrs = 1;
     map->is_fixed = 1;
     map->is_ordered = 1;
-    map->table = (mp_map_elem_t*)table;
+    map->table = (mp_map_elem_t *)table;
 }
 
 // Differentiate from mp_map_clear() - semantics is different
diff --git a/py/misc.h b/py/misc.h
index 50feaf7..eafcef9 100644
--- a/py/misc.h
+++ b/py/misc.h
@@ -57,28 +57,28 @@
 
 // TODO make a lazy m_renew that can increase by a smaller amount than requested (but by at least 1 more element)
 
-#define m_new(type, num) ((type*)(m_malloc(sizeof(type) * (num))))
-#define m_new_maybe(type, num) ((type*)(m_malloc_maybe(sizeof(type) * (num))))
-#define m_new0(type, num) ((type*)(m_malloc0(sizeof(type) * (num))))
+#define m_new(type, num) ((type *)(m_malloc(sizeof(type) * (num))))
+#define m_new_maybe(type, num) ((type *)(m_malloc_maybe(sizeof(type) * (num))))
+#define m_new0(type, num) ((type *)(m_malloc0(sizeof(type) * (num))))
 #define m_new_obj(type) (m_new(type, 1))
 #define m_new_obj_maybe(type) (m_new_maybe(type, 1))
-#define m_new_obj_var(obj_type, var_type, var_num) ((obj_type*)m_malloc(sizeof(obj_type) + sizeof(var_type) * (var_num)))
-#define m_new_obj_var_maybe(obj_type, var_type, var_num) ((obj_type*)m_malloc_maybe(sizeof(obj_type) + sizeof(var_type) * (var_num)))
+#define m_new_obj_var(obj_type, var_type, var_num) ((obj_type *)m_malloc(sizeof(obj_type) + sizeof(var_type) * (var_num)))
+#define m_new_obj_var_maybe(obj_type, var_type, var_num) ((obj_type *)m_malloc_maybe(sizeof(obj_type) + sizeof(var_type) * (var_num)))
 #if MICROPY_ENABLE_FINALISER
-#define m_new_obj_with_finaliser(type) ((type*)(m_malloc_with_finaliser(sizeof(type))))
-#define m_new_obj_var_with_finaliser(type, var_type, var_num) ((type*)m_malloc_with_finaliser(sizeof(type) + sizeof(var_type) * (var_num)))
+#define m_new_obj_with_finaliser(type) ((type *)(m_malloc_with_finaliser(sizeof(type))))
+#define m_new_obj_var_with_finaliser(type, var_type, var_num) ((type *)m_malloc_with_finaliser(sizeof(type) + sizeof(var_type) * (var_num)))
 #else
 #define m_new_obj_with_finaliser(type) m_new_obj(type)
 #define m_new_obj_var_with_finaliser(type, var_type, var_num) m_new_obj_var(type, var_type, var_num)
 #endif
 #if MICROPY_MALLOC_USES_ALLOCATED_SIZE
-#define m_renew(type, ptr, old_num, new_num) ((type*)(m_realloc((ptr), sizeof(type) * (old_num), sizeof(type) * (new_num))))
-#define m_renew_maybe(type, ptr, old_num, new_num, allow_move) ((type*)(m_realloc_maybe((ptr), sizeof(type) * (old_num), sizeof(type) * (new_num), (allow_move))))
+#define m_renew(type, ptr, old_num, new_num) ((type *)(m_realloc((ptr), sizeof(type) * (old_num), sizeof(type) * (new_num))))
+#define m_renew_maybe(type, ptr, old_num, new_num, allow_move) ((type *)(m_realloc_maybe((ptr), sizeof(type) * (old_num), sizeof(type) * (new_num), (allow_move))))
 #define m_del(type, ptr, num) m_free(ptr, sizeof(type) * (num))
 #define m_del_var(obj_type, var_type, var_num, ptr) (m_free(ptr, sizeof(obj_type) + sizeof(var_type) * (var_num)))
 #else
-#define m_renew(type, ptr, old_num, new_num) ((type*)(m_realloc((ptr), sizeof(type) * (new_num))))
-#define m_renew_maybe(type, ptr, old_num, new_num, allow_move) ((type*)(m_realloc_maybe((ptr), sizeof(type) * (new_num), (allow_move))))
+#define m_renew(type, ptr, old_num, new_num) ((type *)(m_realloc((ptr), sizeof(type) * (new_num))))
+#define m_renew_maybe(type, ptr, old_num, new_num, allow_move) ((type *)(m_realloc_maybe((ptr), sizeof(type) * (new_num), (allow_move))))
 #define m_del(type, ptr, num) ((void)(num), m_free(ptr))
 #define m_del_var(obj_type, var_type, var_num, ptr) ((void)(var_num), m_free(ptr))
 #endif
@@ -111,7 +111,7 @@
 #define MP_ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
 
 // align ptr to the nearest multiple of "alignment"
-#define MP_ALIGN(ptr, alignment) (void*)(((uintptr_t)(ptr) + ((alignment) - 1)) & ~((alignment) - 1))
+#define MP_ALIGN(ptr, alignment) (void *)(((uintptr_t)(ptr) + ((alignment) - 1)) & ~((alignment) - 1))
 
 /** unichar / UTF-8 *********************************************/
 
@@ -129,9 +129,16 @@
 const byte *utf8_next_char(const byte *s);
 size_t utf8_charlen(const byte *str, size_t len);
 #else
-static inline unichar utf8_get_char(const byte *s) { return *s; }
-static inline const byte *utf8_next_char(const byte *s) { return s + 1; }
-static inline size_t utf8_charlen(const byte *str, size_t len) { (void)str; return len; }
+static inline unichar utf8_get_char(const byte *s) {
+    return *s;
+}
+static inline const byte *utf8_next_char(const byte *s) {
+    return s + 1;
+}
+static inline size_t utf8_charlen(const byte *str, size_t len) {
+    (void)str;
+    return len;
+}
 #endif
 
 bool unichar_isspace(unichar c);
@@ -169,9 +176,15 @@
 void vstr_clear(vstr_t *vstr);
 vstr_t *vstr_new(size_t alloc);
 void vstr_free(vstr_t *vstr);
-static inline void vstr_reset(vstr_t *vstr) { vstr->len = 0; }
-static inline char *vstr_str(vstr_t *vstr) { return vstr->buf; }
-static inline size_t vstr_len(vstr_t *vstr) { return vstr->len; }
+static inline void vstr_reset(vstr_t *vstr) {
+    vstr->len = 0;
+}
+static inline char *vstr_str(vstr_t *vstr) {
+    return vstr->buf;
+}
+static inline size_t vstr_len(vstr_t *vstr) {
+    return vstr->len;
+}
 void vstr_hint_size(vstr_t *vstr, size_t size);
 char *vstr_extend(vstr_t *vstr, size_t size);
 char *vstr_add_len(vstr_t *vstr, size_t len);
@@ -192,10 +205,10 @@
 #define CHECKBUF(buf, max_size) char buf[max_size + 1]; size_t buf##_len = max_size; char *buf##_p = buf;
 #define CHECKBUF_RESET(buf, max_size) buf##_len = max_size; buf##_p = buf;
 #define CHECKBUF_APPEND(buf, src, src_len) \
-        { size_t l = MIN(src_len, buf##_len); \
-        memcpy(buf##_p, src, l); \
-        buf##_len -= l; \
-        buf##_p += l; }
+    { size_t l = MIN(src_len, buf##_len); \
+      memcpy(buf##_p, src, l); \
+      buf##_len -= l; \
+      buf##_p += l; }
 #define CHECKBUF_APPEND_0(buf) { *buf##_p = 0; }
 #define CHECKBUF_LEN(buf) (buf##_p - buf)
 
diff --git a/py/modarray.c b/py/modarray.c
index b459a83..9ab1795 100644
--- a/py/modarray.c
+++ b/py/modarray.c
@@ -37,7 +37,7 @@
 
 const mp_obj_module_t mp_module_uarray = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_array_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_array_globals,
 };
 
 MP_REGISTER_MODULE(MP_QSTR_uarray, mp_module_uarray, MICROPY_PY_ARRAY);
diff --git a/py/modbuiltins.c b/py/modbuiltins.c
index 6065bfd..299ec2d 100644
--- a/py/modbuiltins.c
+++ b/py/modbuiltins.c
@@ -140,7 +140,8 @@
     uint8_t str[4];
     int len = 0;
     if (c < 0x80) {
-        *str = c; len = 1;
+        *str = c;
+        len = 1;
     } else if (c < 0x800) {
         str[0] = (c >> 6) | 0xC0;
         str[1] = (c & 0x3F) | 0x80;
@@ -159,12 +160,12 @@
     } else {
         mp_raise_ValueError("chr() arg not in range(0x110000)");
     }
-    return mp_obj_new_str_via_qstr((char*)str, len);
+    return mp_obj_new_str_via_qstr((char *)str, len);
     #else
     mp_int_t ord = mp_obj_get_int(o_in);
     if (0 <= ord && ord <= 0xff) {
         uint8_t str[1] = {ord};
-        return mp_obj_new_str_via_qstr((char*)str, 1);
+        return mp_obj_new_str_via_qstr((char *)str, 1);
     } else {
         mp_raise_ValueError("chr() arg not in range(256)");
     }
@@ -355,7 +356,7 @@
 
 STATIC mp_obj_t mp_builtin_ord(mp_obj_t o_in) {
     size_t len;
-    const byte *str = (const byte*)mp_obj_str_get_data(o_in, &len);
+    const byte *str = (const byte *)mp_obj_str_get_data(o_in, &len);
     #if MICROPY_PY_BUILTINS_STR_UNICODE
     if (mp_obj_is_str(o_in)) {
         len = utf8_charlen(str, len);
@@ -382,15 +383,16 @@
 
 STATIC mp_obj_t mp_builtin_pow(size_t n_args, const mp_obj_t *args) {
     switch (n_args) {
-        case 2: return mp_binary_op(MP_BINARY_OP_POWER, args[0], args[1]);
+        case 2:
+            return mp_binary_op(MP_BINARY_OP_POWER, args[0], args[1]);
         default:
-#if !MICROPY_PY_BUILTINS_POW3
+            #if !MICROPY_PY_BUILTINS_POW3
             mp_raise_msg(&mp_type_NotImplementedError, "3-arg pow() not supported");
-#elif MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_MPZ
+            #elif MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_MPZ
             return mp_binary_op(MP_BINARY_OP_MODULO, mp_binary_op(MP_BINARY_OP_POWER, args[0], args[1]), args[2]);
-#else
+            #else
             return mp_obj_int_pow3(args[0], args[1], args[2]);
-#endif
+            #endif
     }
 }
 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_pow_obj, 2, 3, mp_builtin_pow);
@@ -485,7 +487,7 @@
         }
 
         mp_obj_t mult = mp_binary_op(MP_BINARY_OP_POWER, MP_OBJ_NEW_SMALL_INT(10), MP_OBJ_NEW_SMALL_INT(-num_dig));
-        mp_obj_t half_mult =  mp_binary_op(MP_BINARY_OP_FLOOR_DIVIDE, mult, MP_OBJ_NEW_SMALL_INT(2));
+        mp_obj_t half_mult = mp_binary_op(MP_BINARY_OP_FLOOR_DIVIDE, mult, MP_OBJ_NEW_SMALL_INT(2));
         mp_obj_t modulo = mp_binary_op(MP_BINARY_OP_MODULO, o_in, mult);
         mp_obj_t rounded = mp_binary_op(MP_BINARY_OP_SUBTRACT, o_in, modulo);
         if (mp_obj_is_true(mp_binary_op(MP_BINARY_OP_MORE, half_mult, modulo))) {
@@ -503,7 +505,7 @@
         }
         #endif
     }
-#if MICROPY_PY_BUILTINS_FLOAT
+    #if MICROPY_PY_BUILTINS_FLOAT
     mp_float_t val = mp_obj_get_float(o_in);
     if (n_args > 1) {
         mp_int_t num_dig = mp_obj_get_int(args[1]);
@@ -514,18 +516,22 @@
     }
     mp_float_t rounded = MICROPY_FLOAT_C_FUN(nearbyint)(val);
     return mp_obj_new_int_from_float(rounded);
-#else
+    #else
     mp_int_t r = mp_obj_get_int(o_in);
     return mp_obj_new_int(r);
-#endif
+    #endif
 }
 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_round_obj, 1, 2, mp_builtin_round);
 
 STATIC mp_obj_t mp_builtin_sum(size_t n_args, const mp_obj_t *args) {
     mp_obj_t value;
     switch (n_args) {
-        case 1: value = MP_OBJ_NEW_SMALL_INT(0); break;
-        default: value = args[1]; break;
+        case 1:
+            value = MP_OBJ_NEW_SMALL_INT(0);
+            break;
+        default:
+            value = args[1];
+            break;
     }
     mp_obj_iter_buf_t iter_buf;
     mp_obj_t iterable = mp_getiter(args[0], &iter_buf);
@@ -771,5 +777,5 @@
 
 const mp_obj_module_t mp_module_builtins = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_builtins_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_builtins_globals,
 };
diff --git a/py/modcmath.c b/py/modcmath.c
index 70fd542..ce1f474 100644
--- a/py/modcmath.c
+++ b/py/modcmath.c
@@ -43,7 +43,7 @@
     mp_float_t real, imag;
     mp_obj_get_complex(z_obj, &real, &imag);
     mp_obj_t tuple[2] = {
-        mp_obj_new_float(MICROPY_FLOAT_C_FUN(sqrt)(real*real + imag*imag)),
+        mp_obj_new_float(MICROPY_FLOAT_C_FUN(sqrt)(real * real + imag * imag)),
         mp_obj_new_float(MICROPY_FLOAT_C_FUN(atan2)(imag, real)),
     };
     return mp_obj_new_tuple(2, tuple);
@@ -72,7 +72,7 @@
 STATIC mp_obj_t mp_cmath_log(mp_obj_t z_obj) {
     mp_float_t real, imag;
     mp_obj_get_complex(z_obj, &real, &imag);
-    return mp_obj_new_complex(0.5 * MICROPY_FLOAT_C_FUN(log)(real*real + imag*imag), MICROPY_FLOAT_C_FUN(atan2)(imag, real));
+    return mp_obj_new_complex(0.5 * MICROPY_FLOAT_C_FUN(log)(real * real + imag * imag), MICROPY_FLOAT_C_FUN(atan2)(imag, real));
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_cmath_log_obj, mp_cmath_log);
 
@@ -81,7 +81,7 @@
 STATIC mp_obj_t mp_cmath_log10(mp_obj_t z_obj) {
     mp_float_t real, imag;
     mp_obj_get_complex(z_obj, &real, &imag);
-    return mp_obj_new_complex(0.5 * MICROPY_FLOAT_C_FUN(log10)(real*real + imag*imag), 0.4342944819032518 * MICROPY_FLOAT_C_FUN(atan2)(imag, real));
+    return mp_obj_new_complex(0.5 * MICROPY_FLOAT_C_FUN(log10)(real * real + imag * imag), 0.4342944819032518 * MICROPY_FLOAT_C_FUN(atan2)(imag, real));
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_cmath_log10_obj, mp_cmath_log10);
 #endif
@@ -90,7 +90,7 @@
 STATIC mp_obj_t mp_cmath_sqrt(mp_obj_t z_obj) {
     mp_float_t real, imag;
     mp_obj_get_complex(z_obj, &real, &imag);
-    mp_float_t sqrt_abs = MICROPY_FLOAT_C_FUN(pow)(real*real + imag*imag, 0.25);
+    mp_float_t sqrt_abs = MICROPY_FLOAT_C_FUN(pow)(real * real + imag * imag, 0.25);
     mp_float_t theta = 0.5 * MICROPY_FLOAT_C_FUN(atan2)(imag, real);
     return mp_obj_new_complex(sqrt_abs * MICROPY_FLOAT_C_FUN(cos)(theta), sqrt_abs * MICROPY_FLOAT_C_FUN(sin)(theta));
 }
@@ -146,7 +146,7 @@
 
 const mp_obj_module_t mp_module_cmath = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_cmath_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_cmath_globals,
 };
 
 #endif // MICROPY_PY_BUILTINS_FLOAT && MICROPY_PY_CMATH
diff --git a/py/modcollections.c b/py/modcollections.c
index bb64884..c145f12 100644
--- a/py/modcollections.c
+++ b/py/modcollections.c
@@ -43,7 +43,7 @@
 
 const mp_obj_module_t mp_module_collections = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_collections_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_collections_globals,
 };
 
 #endif // MICROPY_PY_COLLECTIONS
diff --git a/py/modgc.c b/py/modgc.c
index 55e73de..534a711 100644
--- a/py/modgc.c
+++ b/py/modgc.c
@@ -33,11 +33,11 @@
 // collect(): run a garbage collection
 STATIC mp_obj_t py_gc_collect(void) {
     gc_collect();
-#if MICROPY_PY_GC_COLLECT_RETVAL
+    #if MICROPY_PY_GC_COLLECT_RETVAL
     return MP_OBJ_NEW_SMALL_INT(MP_STATE_MEM(gc_collected));
-#else
+    #else
     return mp_const_none;
-#endif
+    #endif
 }
 MP_DEFINE_CONST_FUN_OBJ_0(gc_collect_obj, py_gc_collect);
 
@@ -112,7 +112,7 @@
 
 const mp_obj_module_t mp_module_gc = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_gc_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_gc_globals,
 };
 
 #endif
diff --git a/py/modio.c b/py/modio.c
index 94ef5d4..14f5f21 100644
--- a/py/modio.c
+++ b/py/modio.c
@@ -72,7 +72,7 @@
 }
 
 STATIC mp_uint_t iobase_write(mp_obj_t obj, const void *buf, mp_uint_t size, int *errcode) {
-    return iobase_read_write(obj, (void*)buf, size, errcode, MP_QSTR_write);
+    return iobase_read_write(obj, (void *)buf, size, errcode, MP_QSTR_write);
 }
 
 STATIC mp_uint_t iobase_ioctl(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode) {
@@ -144,7 +144,7 @@
         // is word-aligned, to guard against obscure cases when it matters, e.g.
         // https://github.com/micropython/micropython/issues/1863
         memcpy(self->buf + self->len, buf, rem);
-        buf = (byte*)buf + rem;
+        buf = (byte *)buf + rem;
         size -= rem;
         mp_uint_t out_sz = mp_stream_write_exactly(self->stream, self->buf, self->alloc, errcode);
         (void)out_sz;
@@ -195,7 +195,7 @@
     .name = MP_QSTR_BufferedWriter,
     .make_new = bufwriter_make_new,
     .protocol = &bufwriter_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&bufwriter_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&bufwriter_locals_dict,
 };
 #endif // MICROPY_PY_IO_BUFFEREDWRITER
 
@@ -231,14 +231,14 @@
         mp_obj_stringio_t *o = m_new_obj(mp_obj_stringio_t);
         o->base.type = &mp_type_bytesio;
         o->vstr = m_new_obj(vstr_t);
-        vstr_init_fixed_buf(o->vstr, len + 1, (char*)data);
+        vstr_init_fixed_buf(o->vstr, len + 1, (char *)data);
         o->vstr->len = len;
         o->pos = 0;
         return MP_OBJ_FROM_PTR(o);
     }
 
     mp_obj_t path_out = mp_obj_new_str(path_buf.buf, path_buf.len);
-    return mp_builtin_open(1, &path_out, (mp_map_t*)&mp_const_empty_map);
+    return mp_builtin_open(1, &path_out, (mp_map_t *)&mp_const_empty_map);
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_2(resource_stream_obj, resource_stream);
 #endif
@@ -273,7 +273,7 @@
 
 const mp_obj_module_t mp_module_io = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_io_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_io_globals,
 };
 
 #endif
diff --git a/py/modmath.c b/py/modmath.c
index 35bb44b..5fe8e49 100644
--- a/py/modmath.c
+++ b/py/modmath.c
@@ -59,30 +59,30 @@
 }
 
 #define MATH_FUN_1(py_name, c_name) \
-    STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj) { \
+    STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj) { \
         return math_generic_1(x_obj, MICROPY_FLOAT_C_FUN(c_name)); \
     } \
-    STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_## py_name ## _obj, mp_math_ ## py_name);
+    STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_##py_name##_obj, mp_math_##py_name);
 
 #define MATH_FUN_1_TO_BOOL(py_name, c_name) \
-    STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj) { return mp_obj_new_bool(c_name(mp_obj_get_float(x_obj))); } \
-    STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_## py_name ## _obj, mp_math_ ## py_name);
+    STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj) { return mp_obj_new_bool(c_name(mp_obj_get_float(x_obj))); } \
+    STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_##py_name##_obj, mp_math_##py_name);
 
 #define MATH_FUN_1_TO_INT(py_name, c_name) \
-    STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj) { return mp_obj_new_int_from_float(MICROPY_FLOAT_C_FUN(c_name)(mp_obj_get_float(x_obj))); } \
-    STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_## py_name ## _obj, mp_math_ ## py_name);
+    STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj) { return mp_obj_new_int_from_float(MICROPY_FLOAT_C_FUN(c_name)(mp_obj_get_float(x_obj))); } \
+    STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_##py_name##_obj, mp_math_##py_name);
 
 #define MATH_FUN_2(py_name, c_name) \
-    STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj, mp_obj_t y_obj) { \
+    STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj, mp_obj_t y_obj) { \
         return math_generic_2(x_obj, y_obj, MICROPY_FLOAT_C_FUN(c_name)); \
     } \
-    STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_math_## py_name ## _obj, mp_math_ ## py_name);
+    STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_math_##py_name##_obj, mp_math_##py_name);
 
 #define MATH_FUN_2_FLT_INT(py_name, c_name) \
-    STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj, mp_obj_t y_obj) { \
+    STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj, mp_obj_t y_obj) { \
         return mp_obj_new_float(MICROPY_FLOAT_C_FUN(c_name)(mp_obj_get_float(x_obj), mp_obj_get_int(y_obj))); \
     } \
-    STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_math_## py_name ## _obj, mp_math_ ## py_name);
+    STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_math_##py_name##_obj, mp_math_##py_name);
 
 #if MP_NEED_LOG2
 #undef log2
@@ -392,7 +392,7 @@
 
 const mp_obj_module_t mp_module_math = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_math_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_math_globals,
 };
 
 #endif // MICROPY_PY_BUILTINS_FLOAT && MICROPY_PY_MATH
diff --git a/py/modmicropython.c b/py/modmicropython.c
index 8d36697..d73d2bd 100644
--- a/py/modmicropython.c
+++ b/py/modmicropython.c
@@ -68,25 +68,25 @@
 
 mp_obj_t mp_micropython_mem_info(size_t n_args, const mp_obj_t *args) {
     (void)args;
-#if MICROPY_MEM_STATS
+    #if MICROPY_MEM_STATS
     mp_printf(&mp_plat_print, "mem: total=" UINT_FMT ", current=" UINT_FMT ", peak=" UINT_FMT "\n",
         (mp_uint_t)m_get_total_bytes_allocated(), (mp_uint_t)m_get_current_bytes_allocated(), (mp_uint_t)m_get_peak_bytes_allocated());
-#endif
-#if MICROPY_STACK_CHECK
+    #endif
+    #if MICROPY_STACK_CHECK
     mp_printf(&mp_plat_print, "stack: " UINT_FMT " out of " UINT_FMT "\n",
         mp_stack_usage(), (mp_uint_t)MP_STATE_THREAD(stack_limit));
-#else
+    #else
     mp_printf(&mp_plat_print, "stack: " UINT_FMT "\n", mp_stack_usage());
-#endif
-#if MICROPY_ENABLE_GC
+    #endif
+    #if MICROPY_ENABLE_GC
     gc_dump_info();
     if (n_args == 1) {
         // arg given means dump gc allocation table
         gc_dump_alloc_table();
     }
-#else
+    #else
     (void)n_args;
-#endif
+    #endif
     return mp_const_none;
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_micropython_mem_info_obj, 0, 1, mp_micropython_mem_info);
@@ -163,21 +163,21 @@
     #if MICROPY_ENABLE_COMPILER
     { MP_ROM_QSTR(MP_QSTR_opt_level), MP_ROM_PTR(&mp_micropython_opt_level_obj) },
     #endif
-#if MICROPY_PY_MICROPYTHON_MEM_INFO
-#if MICROPY_MEM_STATS
+    #if MICROPY_PY_MICROPYTHON_MEM_INFO
+    #if MICROPY_MEM_STATS
     { MP_ROM_QSTR(MP_QSTR_mem_total), MP_ROM_PTR(&mp_micropython_mem_total_obj) },
     { MP_ROM_QSTR(MP_QSTR_mem_current), MP_ROM_PTR(&mp_micropython_mem_current_obj) },
     { MP_ROM_QSTR(MP_QSTR_mem_peak), MP_ROM_PTR(&mp_micropython_mem_peak_obj) },
-#endif
+    #endif
     { MP_ROM_QSTR(MP_QSTR_mem_info), MP_ROM_PTR(&mp_micropython_mem_info_obj) },
     { MP_ROM_QSTR(MP_QSTR_qstr_info), MP_ROM_PTR(&mp_micropython_qstr_info_obj) },
-#endif
+    #endif
     #if MICROPY_PY_MICROPYTHON_STACK_USE
     { MP_ROM_QSTR(MP_QSTR_stack_use), MP_ROM_PTR(&mp_micropython_stack_use_obj) },
     #endif
-#if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF && (MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE == 0)
+    #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF && (MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE == 0)
     { MP_ROM_QSTR(MP_QSTR_alloc_emergency_exception_buf), MP_ROM_PTR(&mp_alloc_emergency_exception_buf_obj) },
-#endif
+    #endif
     #if MICROPY_ENABLE_PYSTACK
     { MP_ROM_QSTR(MP_QSTR_pystack_use), MP_ROM_PTR(&mp_micropython_pystack_use_obj) },
     #endif
@@ -197,5 +197,5 @@
 
 const mp_obj_module_t mp_module_micropython = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_micropython_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_micropython_globals,
 };
diff --git a/py/modstruct.c b/py/modstruct.c
index 36af426..caf0ad9 100644
--- a/py/modstruct.c
+++ b/py/modstruct.c
@@ -217,7 +217,7 @@
     mp_int_t size = MP_OBJ_SMALL_INT_VALUE(struct_calcsize(args[0]));
     vstr_t vstr;
     vstr_init_len(&vstr, size);
-    byte *p = (byte*)vstr.buf;
+    byte *p = (byte *)vstr.buf;
     memset(p, 0, size);
     struct_pack_into_internal(args[0], p, n_args - 1, &args[1]);
     return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
@@ -263,7 +263,7 @@
 
 const mp_obj_module_t mp_module_ustruct = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_struct_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_struct_globals,
 };
 
 #endif
diff --git a/py/modsys.c b/py/modsys.c
index 29fac7c..8092d97 100644
--- a/py/modsys.c
+++ b/py/modsys.c
@@ -89,8 +89,8 @@
     mp_sys_implementation_obj,
     impl_fields,
     2 + MICROPY_PERSISTENT_CODE_LOAD,
-        SYS_IMPLEMENTATION_ELEMS
-);
+    SYS_IMPLEMENTATION_ELEMS
+    );
 #else
 STATIC const mp_rom_obj_tuple_t mp_sys_implementation_obj = {
     {&mp_type_tuple},
@@ -252,7 +252,7 @@
 
 const mp_obj_module_t mp_module_sys = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_sys_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_sys_globals,
 };
 
 #endif
diff --git a/py/modthread.c b/py/modthread.c
index f54bf83..35e7d50 100644
--- a/py/modthread.c
+++ b/py/modthread.c
@@ -120,7 +120,7 @@
 STATIC const mp_obj_type_t mp_type_thread_lock = {
     { &mp_type_type },
     .name = MP_QSTR_lock,
-    .locals_dict = (mp_obj_dict_t*)&thread_lock_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&thread_lock_locals_dict,
 };
 
 /****************************************************************/
@@ -157,7 +157,7 @@
 STATIC void *thread_entry(void *args_in) {
     // Execution begins here for a new thread.  We do not have the GIL.
 
-    thread_entry_args_t *args = (thread_entry_args_t*)args_in;
+    thread_entry_args_t *args = (thread_entry_args_t *)args_in;
 
     mp_state_thread_t ts;
     mp_thread_set_state(&ts);
@@ -193,7 +193,7 @@
     } else {
         // uncaught exception
         // check for SystemExit
-        mp_obj_base_t *exc = (mp_obj_base_t*)nlr.ret_val;
+        mp_obj_base_t *exc = (mp_obj_base_t *)nlr.ret_val;
         if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(exc->type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) {
             // swallow exception silently
         } else {
@@ -237,7 +237,7 @@
         if (mp_obj_get_type(args[2]) != &mp_type_dict) {
             mp_raise_TypeError("expecting a dict for keyword args");
         }
-        mp_map_t *map = &((mp_obj_dict_t*)MP_OBJ_TO_PTR(args[2]))->map;
+        mp_map_t *map = &((mp_obj_dict_t *)MP_OBJ_TO_PTR(args[2]))->map;
         th_args = m_new_obj_var(thread_entry_args_t, mp_obj_t, pos_args_len + 2 * map->used);
         th_args->n_kw = map->used;
         // copy across the keyword arguments
@@ -294,7 +294,7 @@
 
 const mp_obj_module_t mp_module_thread = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_thread_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_thread_globals,
 };
 
 #endif // MICROPY_PY_THREAD
diff --git a/py/moduerrno.c b/py/moduerrno.c
index 0e0a3f0..93a08d8 100644
--- a/py/moduerrno.c
+++ b/py/moduerrno.c
@@ -63,9 +63,9 @@
 
 #if MICROPY_PY_UERRNO_ERRORCODE
 STATIC const mp_rom_map_elem_t errorcode_table[] = {
-    #define X(e) { MP_ROM_INT(MP_ ## e), MP_ROM_QSTR(MP_QSTR_## e) },
+    #define X(e) { MP_ROM_INT(MP_##e), MP_ROM_QSTR(MP_QSTR_##e) },
     MICROPY_PY_UERRNO_LIST
-    #undef X
+#undef X
 };
 
 STATIC const mp_obj_dict_t errorcode_dict = {
@@ -76,7 +76,7 @@
         .is_ordered = 1,
         .used = MP_ARRAY_SIZE(errorcode_table),
         .alloc = MP_ARRAY_SIZE(errorcode_table),
-        .table = (mp_map_elem_t*)(mp_rom_map_elem_t*)errorcode_table,
+        .table = (mp_map_elem_t *)(mp_rom_map_elem_t *)errorcode_table,
     },
 };
 #endif
@@ -87,22 +87,22 @@
     { MP_ROM_QSTR(MP_QSTR_errorcode), MP_ROM_PTR(&errorcode_dict) },
     #endif
 
-    #define X(e) { MP_ROM_QSTR(MP_QSTR_## e), MP_ROM_INT(MP_ ## e) },
+    #define X(e) { MP_ROM_QSTR(MP_QSTR_##e), MP_ROM_INT(MP_##e) },
     MICROPY_PY_UERRNO_LIST
-    #undef X
+#undef X
 };
 
 STATIC MP_DEFINE_CONST_DICT(mp_module_uerrno_globals, mp_module_uerrno_globals_table);
 
 const mp_obj_module_t mp_module_uerrno = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&mp_module_uerrno_globals,
+    .globals = (mp_obj_dict_t *)&mp_module_uerrno_globals,
 };
 
 qstr mp_errno_to_str(mp_obj_t errno_val) {
     #if MICROPY_PY_UERRNO_ERRORCODE
     // We have the errorcode dict so can do a lookup using the hash map
-    mp_map_elem_t *elem = mp_map_lookup((mp_map_t*)&errorcode_dict.map, errno_val, MP_MAP_LOOKUP);
+    mp_map_elem_t *elem = mp_map_lookup((mp_map_t *)&errorcode_dict.map, errno_val, MP_MAP_LOOKUP);
     if (elem == NULL) {
         return MP_QSTRnull;
     } else {
diff --git a/py/mpconfig.h b/py/mpconfig.h
index f2754dd..4cefdf3 100644
--- a/py/mpconfig.h
+++ b/py/mpconfig.h
@@ -34,8 +34,8 @@
 // Combined version as a 32-bit number for convenience
 #define MICROPY_VERSION ( \
     MICROPY_VERSION_MAJOR << 16 \
-    | MICROPY_VERSION_MINOR << 8 \
-    | MICROPY_VERSION_MICRO)
+        | MICROPY_VERSION_MINOR << 8 \
+        | MICROPY_VERSION_MICRO)
 
 // String version
 #define MICROPY_VERSION_STRING \
@@ -550,9 +550,9 @@
 #define MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF (0)
 #endif
 #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
-#   ifndef MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE
-#   define MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE (0)   // 0 - implies dynamic allocation
-#   endif
+#ifndef MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE
+#define MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE (0)      // 0 - implies dynamic allocation
+#endif
 #endif
 
 // Whether to provide the mp_kbd_exception object, and micropython.kbd_intr function
@@ -1489,7 +1489,7 @@
 #elif defined(MP_ENDIANNESS_BIG)
 #define MP_ENDIANNESS_LITTLE (!MP_ENDIANNESS_BIG)
 #else
-  // Endianness not defined by port so try to autodetect it.
+// Endianness not defined by port so try to autodetect it.
   #if defined(__BYTE_ORDER__)
     #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
       #define MP_ENDIANNESS_LITTLE (1)
@@ -1595,33 +1595,33 @@
 
 #ifndef MP_HTOBE16
 #if MP_ENDIANNESS_LITTLE
-# define MP_HTOBE16(x) ((uint16_t)( (((x) & 0xff) << 8) | (((x) >> 8) & 0xff) ))
-# define MP_BE16TOH(x) MP_HTOBE16(x)
+#define MP_HTOBE16(x) ((uint16_t)( (((x) & 0xff) << 8) | (((x) >> 8) & 0xff) ))
+#define MP_BE16TOH(x) MP_HTOBE16(x)
 #else
-# define MP_HTOBE16(x) (x)
-# define MP_BE16TOH(x) (x)
+#define MP_HTOBE16(x) (x)
+#define MP_BE16TOH(x) (x)
 #endif
 #endif
 
 #ifndef MP_HTOBE32
 #if MP_ENDIANNESS_LITTLE
-# define MP_HTOBE32(x) ((uint32_t)( (((x) & 0xff) << 24) | (((x) & 0xff00) << 8) | (((x) >> 8)  & 0xff00) | (((x) >> 24) & 0xff) ))
-# define MP_BE32TOH(x) MP_HTOBE32(x)
+#define MP_HTOBE32(x) ((uint32_t)( (((x) & 0xff) << 24) | (((x) & 0xff00) << 8) | (((x) >> 8) & 0xff00) | (((x) >> 24) & 0xff) ))
+#define MP_BE32TOH(x) MP_HTOBE32(x)
 #else
-# define MP_HTOBE32(x) (x)
-# define MP_BE32TOH(x) (x)
+#define MP_HTOBE32(x) (x)
+#define MP_BE32TOH(x) (x)
 #endif
 #endif
 
 // Warning categories are by default implemented as strings, though
 // hook is left for a port to define them as something else.
 #if MICROPY_WARNINGS_CATEGORY
-# ifndef MP_WARN_CAT
-# define MP_WARN_CAT(x) #x
-# endif
+#ifndef MP_WARN_CAT
+#define MP_WARN_CAT(x) #x
+#endif
 #else
-# undef MP_WARN_CAT
-# define MP_WARN_CAT(x) (NULL)
+#undef MP_WARN_CAT
+#define MP_WARN_CAT(x) (NULL)
 #endif
 
 // Feature dependency check.
diff --git a/py/mpprint.c b/py/mpprint.c
index cf09f7b..49653a0 100644
--- a/py/mpprint.c
+++ b/py/mpprint.c
@@ -269,14 +269,14 @@
         // We add the pad in this function, so since the pad goes after
         // the sign & prefix, we format without a prefix
         str = mp_obj_int_formatted(&buf, &buf_size, &fmt_size,
-                                   x, base, NULL, base_char, comma);
+            x, base, NULL, base_char, comma);
         if (*str == '-') {
             sign = *str++;
             fmt_size--;
         }
     } else {
         str = mp_obj_int_formatted(&buf, &buf_size, &fmt_size,
-                                   x, base, prefix, base_char, comma);
+            x, base, prefix, base_char, comma);
     }
 
     int spaces_before = 0;
@@ -347,8 +347,7 @@
 
     if (flags & PF_FLAG_SHOW_SIGN) {
         sign = '+';
-    }
-    else
+    } else
     if (flags & PF_FLAG_SPACE_SIGN) {
         sign = ' ';
     }
@@ -411,14 +410,20 @@
         int flags = 0;
         char fill = ' ';
         while (*fmt != '\0') {
-            if (*fmt == '-') flags |= PF_FLAG_LEFT_ADJUST;
-            else if (*fmt == '+') flags |= PF_FLAG_SHOW_SIGN;
-            else if (*fmt == ' ') flags |= PF_FLAG_SPACE_SIGN;
-            else if (*fmt == '!') flags |= PF_FLAG_NO_TRAILZ;
-            else if (*fmt == '0') {
+            if (*fmt == '-') {
+                flags |= PF_FLAG_LEFT_ADJUST;
+            } else if (*fmt == '+') {
+                flags |= PF_FLAG_SHOW_SIGN;
+            } else if (*fmt == ' ') {
+                flags |= PF_FLAG_SPACE_SIGN;
+            } else if (*fmt == '!') {
+                flags |= PF_FLAG_NO_TRAILZ;
+            } else if (*fmt == '0') {
                 flags |= PF_FLAG_PAD_AFTER_SIGN;
                 fill = '0';
-            } else break;
+            } else {
+                break;
+            }
             ++fmt;
         }
 
@@ -470,26 +475,23 @@
                     chrs += mp_print_strn(print, "false", 5, flags, fill, width);
                 }
                 break;
-            case 'c':
-            {
+            case 'c': {
                 char str = va_arg(args, int);
                 chrs += mp_print_strn(print, &str, 1, flags, fill, width);
                 break;
             }
-            case 'q':
-            {
+            case 'q': {
                 qstr qst = va_arg(args, qstr);
                 size_t len;
-                const char *str = (const char*)qstr_data(qst, &len);
+                const char *str = (const char *)qstr_data(qst, &len);
                 if (prec < 0) {
                     prec = len;
                 }
                 chrs += mp_print_strn(print, str, prec, flags, fill, width);
                 break;
             }
-            case 's':
-            {
-                const char *str = va_arg(args, const char*);
+            case 's': {
+                const char *str = va_arg(args, const char *);
                 #ifndef NDEBUG
                 // With debugging enabled, catch printing of null string pointers
                 if (prec != 0 && str == NULL) {
@@ -532,26 +534,25 @@
                 // Use unsigned long int to work on both ILP32 and LP64 systems
                 chrs += mp_print_int(print, va_arg(args, unsigned long int), 0, 16, 'a', flags, fill, width);
                 break;
-#if MICROPY_PY_BUILTINS_FLOAT
+            #if MICROPY_PY_BUILTINS_FLOAT
             case 'e':
             case 'E':
             case 'f':
             case 'F':
             case 'g':
-            case 'G':
-            {
-#if ((MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT) || (MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE))
+            case 'G': {
+                #if ((MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT) || (MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE))
                 mp_float_t f = va_arg(args, double);
                 chrs += mp_print_float(print, f, *fmt, flags, fill, width, prec);
-#else
-#error Unknown MICROPY FLOAT IMPL
-#endif
+                #else
+                #error Unknown MICROPY FLOAT IMPL
+                #endif
                 break;
             }
-#endif
-            // Because 'l' is eaten above, another 'l' means %ll.  We need to support
-            // this length specifier for OBJ_REPR_D (64-bit NaN boxing).
-            // TODO Either enable this unconditionally, or provide a specific config var.
+            #endif
+                // Because 'l' is eaten above, another 'l' means %ll.  We need to support
+                // this length specifier for OBJ_REPR_D (64-bit NaN boxing).
+                // TODO Either enable this unconditionally, or provide a specific config var.
             #if (MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D) || defined(_WIN64)
             case 'l': {
                 unsigned long long int arg_value = va_arg(args, unsigned long long int);
diff --git a/py/mpprint.h b/py/mpprint.h
index 07462bd..aef9015 100644
--- a/py/mpprint.h
+++ b/py/mpprint.h
@@ -40,9 +40,9 @@
 #define PF_FLAG_SHOW_OCTAL_LETTER (0x200)
 
 #if MICROPY_PY_IO && MICROPY_PY_SYS_STDFILES
-#    define MP_PYTHON_PRINTER &mp_sys_stdout_print
+#define MP_PYTHON_PRINTER &mp_sys_stdout_print
 #else
-#    define MP_PYTHON_PRINTER &mp_plat_print
+#define MP_PYTHON_PRINTER &mp_plat_print
 #endif
 
 typedef void (*mp_print_strn_t)(void *data, const char *str, size_t len);
diff --git a/py/mpthread.h b/py/mpthread.h
index f2ab081..e611ef4 100644
--- a/py/mpthread.h
+++ b/py/mpthread.h
@@ -40,7 +40,7 @@
 
 struct _mp_state_thread_t *mp_thread_get_state(void);
 void mp_thread_set_state(struct _mp_state_thread_t *state);
-void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size);
+void mp_thread_create(void *(*entry)(void *), void *arg, size_t *stack_size);
 void mp_thread_start(void);
 void mp_thread_finish(void);
 void mp_thread_mutex_init(mp_thread_mutex_t *mutex);
diff --git a/py/mpz.c b/py/mpz.c
index d79d16d..fb9ac6e 100644
--- a/py/mpz.c
+++ b/py/mpz.c
@@ -60,13 +60,21 @@
    assumes i, j are normalised
 */
 STATIC int mpn_cmp(const mpz_dig_t *idig, size_t ilen, const mpz_dig_t *jdig, size_t jlen) {
-    if (ilen < jlen) { return -1; }
-    if (ilen > jlen) { return 1; }
+    if (ilen < jlen) {
+        return -1;
+    }
+    if (ilen > jlen) {
+        return 1;
+    }
 
     for (idig += ilen, jdig += ilen; ilen > 0; --ilen) {
         mpz_dbl_dig_signed_t cmp = (mpz_dbl_dig_t)*(--idig) - (mpz_dbl_dig_t)*(--jdig);
-        if (cmp < 0) { return -1; }
-        if (cmp > 0) { return 1; }
+        if (cmp < 0) {
+            return -1;
+        }
+        if (cmp > 0) {
+            return 1;
+        }
     }
 
     return 0;
@@ -228,7 +236,7 @@
    can have i, j, k pointing to same memory
 */
 STATIC size_t mpn_and_neg(mpz_dig_t *idig, const mpz_dig_t *jdig, size_t jlen, const mpz_dig_t *kdig, size_t klen,
-                            mpz_dbl_dig_t carryi, mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) {
+    mpz_dbl_dig_t carryi, mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) {
     mpz_dig_t *oidig = idig;
     mpz_dig_t imask = (0 == carryi) ? 0 : DIG_MASK;
     mpz_dig_t jmask = (0 == carryj) ? 0 : DIG_MASK;
@@ -289,7 +297,7 @@
 #if MICROPY_OPT_MPZ_BITWISE
 
 STATIC size_t mpn_or_neg(mpz_dig_t *idig, const mpz_dig_t *jdig, size_t jlen, const mpz_dig_t *kdig, size_t klen,
-                            mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) {
+    mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) {
     mpz_dig_t *oidig = idig;
     mpz_dbl_dig_t carryi = 1;
     mpz_dig_t jmask = (0 == carryj) ? 0 : DIG_MASK;
@@ -319,7 +327,7 @@
 #else
 
 STATIC size_t mpn_or_neg(mpz_dig_t *idig, const mpz_dig_t *jdig, size_t jlen, const mpz_dig_t *kdig, size_t klen,
-                            mpz_dbl_dig_t carryi, mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) {
+    mpz_dbl_dig_t carryi, mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) {
     mpz_dig_t *oidig = idig;
     mpz_dig_t imask = (0 == carryi) ? 0 : DIG_MASK;
     mpz_dig_t jmask = (0 == carryj) ? 0 : DIG_MASK;
@@ -378,7 +386,7 @@
    can have i, j, k pointing to same memory
 */
 STATIC size_t mpn_xor_neg(mpz_dig_t *idig, const mpz_dig_t *jdig, size_t jlen, const mpz_dig_t *kdig, size_t klen,
-                              mpz_dbl_dig_t carryi, mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) {
+    mpz_dbl_dig_t carryi, mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) {
     mpz_dig_t *oidig = idig;
 
     for (; jlen > 0; ++idig, ++jdig) {
@@ -812,16 +820,16 @@
                 z->dig[dig_ind++] = (frc << shft) & DIG_MASK;
                 frc >>= DIG_SIZE - shft;
             }
-#if DIG_SIZE < (MP_FLOAT_FRAC_BITS + 1)
+            #if DIG_SIZE < (MP_FLOAT_FRAC_BITS + 1)
             while (dig_ind != dig_cnt) {
                 z->dig[dig_ind++] = frc & DIG_MASK;
                 frc >>= DIG_SIZE;
             }
-#else
+            #else
             if (dig_ind != dig_cnt) {
                 z->dig[dig_ind] = frc;
             }
-#endif
+            #endif
         }
     }
 }
@@ -935,28 +943,48 @@
 mp_int_t mpz_cmp_sml_int(const mpz_t *z, mp_int_t sml_int) {
     mp_int_t cmp;
     if (z->neg == 0) {
-        if (sml_int < 0) return 1;
-        if (sml_int == 0) {
-            if (z->len == 0) return 0;
+        if (sml_int < 0) {
             return 1;
         }
-        if (z->len == 0) return -1;
-        assert(sml_int < (1 << DIG_SIZE));
-        if (z->len != 1) return 1;
-        cmp = z->dig[0] - sml_int;
-    } else {
-        if (sml_int > 0) return -1;
         if (sml_int == 0) {
-            if (z->len == 0) return 0;
+            if (z->len == 0) {
+                return 0;
+            }
+            return 1;
+        }
+        if (z->len == 0) {
             return -1;
         }
-        if (z->len == 0) return 1;
+        assert(sml_int < (1 << DIG_SIZE));
+        if (z->len != 1) {
+            return 1;
+        }
+        cmp = z->dig[0] - sml_int;
+    } else {
+        if (sml_int > 0) {
+            return -1;
+        }
+        if (sml_int == 0) {
+            if (z->len == 0) {
+                return 0;
+            }
+            return -1;
+        }
+        if (z->len == 0) {
+            return 1;
+        }
         assert(sml_int > -(1 << DIG_SIZE));
-        if (z->len != 1) return -1;
+        if (z->len != 1) {
+            return -1;
+        }
         cmp = -z->dig[0] - sml_int;
     }
-    if (cmp < 0) return -1;
-    if (cmp > 0) return 1;
+    if (cmp < 0) {
+        return -1;
+    }
+    if (cmp > 0) {
+        return 1;
+    }
     return 0;
 }
 #endif
@@ -1194,7 +1222,7 @@
     } else {
         mpz_need_dig(dest, lhs->len + 1);
         dest->len = mpn_and_neg(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len,
-                                 lhs->neg == rhs->neg, 0 != lhs->neg, 0 != rhs->neg);
+            lhs->neg == rhs->neg, 0 != lhs->neg, 0 != rhs->neg);
         dest->neg = lhs->neg & rhs->neg;
     }
 
@@ -1202,7 +1230,7 @@
 
     mpz_need_dig(dest, lhs->len + (lhs->neg || rhs->neg));
     dest->len = mpn_and_neg(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len,
-                             (lhs->neg == rhs->neg) ? lhs->neg : 0, lhs->neg, rhs->neg);
+        (lhs->neg == rhs->neg) ? lhs->neg : 0, lhs->neg, rhs->neg);
     dest->neg = lhs->neg & rhs->neg;
 
     #endif
@@ -1228,7 +1256,7 @@
     } else {
         mpz_need_dig(dest, lhs->len + 1);
         dest->len = mpn_or_neg(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len,
-                                 0 != lhs->neg, 0 != rhs->neg);
+            0 != lhs->neg, 0 != rhs->neg);
         dest->neg = 1;
     }
 
@@ -1236,7 +1264,7 @@
 
     mpz_need_dig(dest, lhs->len + (lhs->neg || rhs->neg));
     dest->len = mpn_or_neg(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len,
-                             (lhs->neg || rhs->neg), lhs->neg, rhs->neg);
+        (lhs->neg || rhs->neg), lhs->neg, rhs->neg);
     dest->neg = lhs->neg | rhs->neg;
 
     #endif
@@ -1266,7 +1294,7 @@
     } else {
         mpz_need_dig(dest, lhs->len + 1);
         dest->len = mpn_xor_neg(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len, 1,
-                                0 == lhs->neg, 0 == rhs->neg);
+            0 == lhs->neg, 0 == rhs->neg);
         dest->neg = 1;
     }
 
@@ -1274,7 +1302,7 @@
 
     mpz_need_dig(dest, lhs->len + (lhs->neg || rhs->neg));
     dest->len = mpn_xor_neg(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len,
-                             (lhs->neg != rhs->neg), 0 == lhs->neg, 0 == rhs->neg);
+        (lhs->neg != rhs->neg), 0 == lhs->neg, 0 == rhs->neg);
     dest->neg = lhs->neg ^ rhs->neg;
 
     #endif
@@ -1363,7 +1391,8 @@
 
     mpz_t *x = mpz_clone(lhs);
     mpz_t *n = mpz_clone(rhs);
-    mpz_t quo; mpz_init_zero(&quo);
+    mpz_t quo;
+    mpz_init_zero(&quo);
 
     while (n->len > 0) {
         if ((n->dig[0] & 1) != 0) {
@@ -1406,7 +1435,8 @@
 
     mpz_t *a = mpz_clone(z1);
     mpz_t *b = mpz_clone(z2);
-    mpz_t c; mpz_init_zero(&c);
+    mpz_t c;
+    mpz_init_zero(&c);
     a->neg = 0;
     b->neg = 0;
 
@@ -1417,7 +1447,9 @@
                 mpz_deinit(&c);
                 return b;
             }
-            mpz_t *t = a; a = b; b = t;
+            mpz_t *t = a;
+            a = b;
+            b = t;
         }
         if (!(b->len >= 2 || (b->len == 1 && b->dig[0] > 1))) { // compute b > 0; could be mpz_cmp_small_int(b, 1) > 0
             break;
@@ -1484,7 +1516,8 @@
     if (lhs->neg != rhs->neg) {
         dest_quo->neg = 1;
         if (!mpz_is_zero(dest_rem)) {
-            mpz_t mpzone; mpz_init_from_int(&mpzone, -1);
+            mpz_t mpzone;
+            mpz_init_from_int(&mpzone, -1);
             mpz_add_inpl(dest_quo, dest_quo, &mpzone);
             mpz_add_inpl(dest_rem, dest_rem, rhs);
         }
@@ -1499,7 +1532,8 @@
 */
 mpz_t *mpz_div(const mpz_t *lhs, const mpz_t *rhs) {
     mpz_t *quo = mpz_zero();
-    mpz_t rem; mpz_init_zero(&rem);
+    mpz_t rem;
+    mpz_init_zero(&rem);
     mpz_divmod_inpl(quo, &rem, lhs, rhs);
     mpz_deinit(&rem);
     return quo;
@@ -1509,7 +1543,8 @@
    can have lhs, rhs the same
 */
 mpz_t *mpz_mod(const mpz_t *lhs, const mpz_t *rhs) {
-    mpz_t quo; mpz_init_zero(&quo);
+    mpz_t quo;
+    mpz_init_zero(&quo);
     mpz_t *rem = mpz_zero();
     mpz_divmod_inpl(&quo, rem, lhs, rhs);
     mpz_deinit(&quo);
@@ -1646,8 +1681,9 @@
     char *s = str;
     if (ilen == 0) {
         if (prefix) {
-            while (*prefix)
+            while (*prefix) {
                 *s++ = *prefix++;
+            }
         }
         *s++ = '0';
         *s = '\0';
diff --git a/py/mpz.h b/py/mpz.h
index 3c36cac..cc15049 100644
--- a/py/mpz.h
+++ b/py/mpz.h
@@ -46,10 +46,10 @@
 
 #ifndef MPZ_DIG_SIZE
   #if defined(__x86_64__) || defined(_WIN64)
-    // 64-bit machine, using 32-bit storage for digits
+// 64-bit machine, using 32-bit storage for digits
     #define MPZ_DIG_SIZE (32)
   #else
-    // default: 32-bit machine, using 16-bit storage for digits
+// default: 32-bit machine, using 16-bit storage for digits
     #define MPZ_DIG_SIZE (16)
   #endif
 #endif
@@ -99,7 +99,7 @@
 } mpz_t;
 
 // convenience macro to declare an mpz with a digit array from the stack, initialised by an integer
-#define MPZ_CONST_INT(z, val) mpz_t z; mpz_dig_t z ## _digits[MPZ_NUM_DIG_FOR_INT]; mpz_init_fixed_from_int(&z, z_digits, MPZ_NUM_DIG_FOR_INT, val);
+#define MPZ_CONST_INT(z, val) mpz_t z; mpz_dig_t z##_digits[MPZ_NUM_DIG_FOR_INT]; mpz_init_fixed_from_int(&z, z_digits, MPZ_NUM_DIG_FOR_INT, val);
 
 void mpz_init_zero(mpz_t *z);
 void mpz_init_from_int(mpz_t *z, mp_int_t val);
@@ -115,8 +115,12 @@
 size_t mpz_set_from_str(mpz_t *z, const char *str, size_t len, bool neg, unsigned int base);
 void mpz_set_from_bytes(mpz_t *z, bool big_endian, size_t len, const byte *buf);
 
-static inline bool mpz_is_zero(const mpz_t *z) { return z->len == 0; }
-static inline bool mpz_is_neg(const mpz_t *z) { return z->len != 0 && z->neg != 0; }
+static inline bool mpz_is_zero(const mpz_t *z) {
+    return z->len == 0;
+}
+static inline bool mpz_is_neg(const mpz_t *z) {
+    return z->len != 0 && z->neg != 0;
+}
 int mpz_cmp(const mpz_t *lhs, const mpz_t *rhs);
 
 void mpz_abs_inpl(mpz_t *dest, const mpz_t *z);
@@ -134,7 +138,9 @@
 void mpz_xor_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs);
 void mpz_divmod_inpl(mpz_t *dest_quo, mpz_t *dest_rem, const mpz_t *lhs, const mpz_t *rhs);
 
-static inline size_t mpz_max_num_bits(const mpz_t *z) { return z->len * MPZ_DIG_SIZE; }
+static inline size_t mpz_max_num_bits(const mpz_t *z) {
+    return z->len * MPZ_DIG_SIZE;
+}
 mp_int_t mpz_hash(const mpz_t *z);
 bool mpz_as_int_checked(const mpz_t *z, mp_int_t *value);
 bool mpz_as_uint_checked(const mpz_t *z, mp_uint_t *value);
diff --git a/py/nativeglue.c b/py/nativeglue.c
index 2e0ac56..ee38e4d 100644
--- a/py/nativeglue.c
+++ b/py/nativeglue.c
@@ -44,15 +44,24 @@
 
 int mp_native_type_from_qstr(qstr qst) {
     switch (qst) {
-        case MP_QSTR_object: return MP_NATIVE_TYPE_OBJ;
-        case MP_QSTR_bool: return MP_NATIVE_TYPE_BOOL;
-        case MP_QSTR_int: return MP_NATIVE_TYPE_INT;
-        case MP_QSTR_uint: return MP_NATIVE_TYPE_UINT;
-        case MP_QSTR_ptr: return MP_NATIVE_TYPE_PTR;
-        case MP_QSTR_ptr8: return MP_NATIVE_TYPE_PTR8;
-        case MP_QSTR_ptr16: return MP_NATIVE_TYPE_PTR16;
-        case MP_QSTR_ptr32: return MP_NATIVE_TYPE_PTR32;
-        default: return -1;
+        case MP_QSTR_object:
+            return MP_NATIVE_TYPE_OBJ;
+        case MP_QSTR_bool:
+            return MP_NATIVE_TYPE_BOOL;
+        case MP_QSTR_int:
+            return MP_NATIVE_TYPE_INT;
+        case MP_QSTR_uint:
+            return MP_NATIVE_TYPE_UINT;
+        case MP_QSTR_ptr:
+            return MP_NATIVE_TYPE_PTR;
+        case MP_QSTR_ptr8:
+            return MP_NATIVE_TYPE_PTR8;
+        case MP_QSTR_ptr16:
+            return MP_NATIVE_TYPE_PTR16;
+        case MP_QSTR_ptr32:
+            return MP_NATIVE_TYPE_PTR32;
+        default:
+            return -1;
     }
 }
 
@@ -60,10 +69,13 @@
 mp_uint_t mp_native_from_obj(mp_obj_t obj, mp_uint_t type) {
     DEBUG_printf("mp_native_from_obj(%p, " UINT_FMT ")\n", obj, type);
     switch (type & 0xf) {
-        case MP_NATIVE_TYPE_OBJ: return (mp_uint_t)obj;
-        case MP_NATIVE_TYPE_BOOL: return mp_obj_is_true(obj);
+        case MP_NATIVE_TYPE_OBJ:
+            return (mp_uint_t)obj;
+        case MP_NATIVE_TYPE_BOOL:
+            return mp_obj_is_true(obj);
         case MP_NATIVE_TYPE_INT:
-        case MP_NATIVE_TYPE_UINT: return mp_obj_get_int_truncated(obj);
+        case MP_NATIVE_TYPE_UINT:
+            return mp_obj_get_int_truncated(obj);
         default: { // cast obj to a pointer
             mp_buffer_info_t bufinfo;
             if (mp_get_buffer(obj, &bufinfo, MP_BUFFER_READ)) {
@@ -84,10 +96,14 @@
 mp_obj_t mp_native_to_obj(mp_uint_t val, mp_uint_t type) {
     DEBUG_printf("mp_native_to_obj(" UINT_FMT ", " UINT_FMT ")\n", val, type);
     switch (type & 0xf) {
-        case MP_NATIVE_TYPE_OBJ: return (mp_obj_t)val;
-        case MP_NATIVE_TYPE_BOOL: return mp_obj_new_bool(val);
-        case MP_NATIVE_TYPE_INT: return mp_obj_new_int(val);
-        case MP_NATIVE_TYPE_UINT: return mp_obj_new_int_from_uint(val);
+        case MP_NATIVE_TYPE_OBJ:
+            return (mp_obj_t)val;
+        case MP_NATIVE_TYPE_BOOL:
+            return mp_obj_new_bool(val);
+        case MP_NATIVE_TYPE_INT:
+            return mp_obj_new_int(val);
+        case MP_NATIVE_TYPE_UINT:
+            return mp_obj_new_int_from_uint(val);
         default: // a pointer
             // we return just the value of the pointer as an integer
             return mp_obj_new_int_from_uint(val);
diff --git a/py/nativeglue.h b/py/nativeglue.h
index 1b6d9cc..9e320ef 100644
--- a/py/nativeglue.h
+++ b/py/nativeglue.h
@@ -91,7 +91,7 @@
     mp_const_obj_t const_true;
     mp_uint_t (*native_from_obj)(mp_obj_t obj, mp_uint_t type);
     mp_obj_t (*native_to_obj)(mp_uint_t val, mp_uint_t type);
-    mp_obj_dict_t *(*swap_globals)(mp_obj_dict_t *new_globals);
+    mp_obj_dict_t *(*swap_globals)(mp_obj_dict_t * new_globals);
     mp_obj_t (*load_name)(qstr qst);
     mp_obj_t (*load_global)(qstr qst);
     mp_obj_t (*load_build_class)(void);
@@ -147,8 +147,8 @@
     #endif
     void (*raise_msg)(const mp_obj_type_t *exc_type, const char *msg);
     const mp_obj_type_t *(*obj_get_type)(mp_const_obj_t o_in);
-    mp_obj_t (*obj_new_str)(const char* data, size_t len);
-    mp_obj_t (*obj_new_bytes)(const byte* data, size_t len);
+    mp_obj_t (*obj_new_str)(const char *data, size_t len);
+    mp_obj_t (*obj_new_bytes)(const byte *data, size_t len);
     mp_obj_t (*obj_new_bytearray_by_ref)(size_t n, void *items);
     mp_obj_t (*obj_new_float_from_f)(float f);
     mp_obj_t (*obj_new_float_from_d)(double d);
diff --git a/py/nlr.c b/py/nlr.c
index 03d0157..a35e7d2 100644
--- a/py/nlr.c
+++ b/py/nlr.c
@@ -30,7 +30,7 @@
 // When not using setjmp, nlr_push_tail is called from inline asm so needs special care
 #if MICROPY_NLR_X86 && MICROPY_NLR_OS_WINDOWS
 // On these 32-bit platforms make sure nlr_push_tail doesn't have a leading underscore
-unsigned int nlr_push_tail(nlr_buf_t *nlr) asm("nlr_push_tail");
+unsigned int nlr_push_tail(nlr_buf_t *nlr) asm ("nlr_push_tail");
 #else
 // LTO can't see inside inline asm functions so explicitly mark nlr_push_tail as used
 __attribute__((used)) unsigned int nlr_push_tail(nlr_buf_t *nlr);
diff --git a/py/nlrpowerpc.c b/py/nlrpowerpc.c
index b403823..940d856 100644
--- a/py/nlrpowerpc.c
+++ b/py/nlrpowerpc.c
@@ -34,44 +34,44 @@
 
 unsigned int nlr_push(nlr_buf_t *nlr) {
 
-    __asm__ volatile(
-    "li     4, 0x4eed ; "      // Store canary
-    "std    4,  0x00(%0) ;"
-    "std    0,  0x08(%0) ;"
-    "std    1,  0x10(%0) ;"
-    "std    2,  0x18(%0) ;"
-    "std    14, 0x20(%0) ;"
-    "std    15, 0x28(%0) ;"
-    "std    16, 0x30(%0) ;"
-    "std    17, 0x38(%0) ;"
-    "std    18, 0x40(%0) ;"
-    "std    19, 0x48(%0) ;"
-    "std    20, 0x50(%0) ;"
-    "std    21, 0x58(%0) ;"
-    "std    22, 0x60(%0) ;"
-    "std    23, 0x68(%0) ;"
-    "std    24, 0x70(%0) ;"
-    "std    25, 0x78(%0) ;"
-    "std    26, 0x80(%0) ;"
-    "std    27, 0x88(%0) ;"
-    "std    28, 0x90(%0) ;"
-    "std    29, 0x98(%0) ;"
-    "std    30, 0xA0(%0) ;"
-    "std    31, 0xA8(%0) ;"
+    __asm__ volatile (
+        "li     4, 0x4eed ; "  // Store canary
+        "std    4,  0x00(%0) ;"
+        "std    0,  0x08(%0) ;"
+        "std    1,  0x10(%0) ;"
+        "std    2,  0x18(%0) ;"
+        "std    14, 0x20(%0) ;"
+        "std    15, 0x28(%0) ;"
+        "std    16, 0x30(%0) ;"
+        "std    17, 0x38(%0) ;"
+        "std    18, 0x40(%0) ;"
+        "std    19, 0x48(%0) ;"
+        "std    20, 0x50(%0) ;"
+        "std    21, 0x58(%0) ;"
+        "std    22, 0x60(%0) ;"
+        "std    23, 0x68(%0) ;"
+        "std    24, 0x70(%0) ;"
+        "std    25, 0x78(%0) ;"
+        "std    26, 0x80(%0) ;"
+        "std    27, 0x88(%0) ;"
+        "std    28, 0x90(%0) ;"
+        "std    29, 0x98(%0) ;"
+        "std    30, 0xA0(%0) ;"
+        "std    31, 0xA8(%0) ;"
 
-    "mfcr   4 ; "
-    "std    4, 0xB0(%0) ;"
-    "mflr   4 ;"
-    "std    4, 0xB8(%0) ;"
-    "li     4, nlr_push_tail@l ;"
-    "oris   4, 4, nlr_push_tail@h ;"
-    "mtctr  4 ;"
-    "mr    3, %1 ; "
-    "bctr  ;"
-    :
-    : "r"(&nlr->regs), "r"(nlr)
-    :
-    );
+        "mfcr   4 ; "
+        "std    4, 0xB0(%0) ;"
+        "mflr   4 ;"
+        "std    4, 0xB8(%0) ;"
+        "li     4, nlr_push_tail@l ;"
+        "oris   4, 4, nlr_push_tail@h ;"
+        "mtctr  4 ;"
+        "mr    3, %1 ; "
+        "bctr  ;"
+        :
+        : "r" (&nlr->regs), "r" (nlr)
+        :
+        );
 
     return 0;
 }
@@ -79,41 +79,41 @@
 NORETURN void nlr_jump(void *val) {
     MP_NLR_JUMP_HEAD(val, top)
 
-    __asm__ volatile(
-    "ld    3, 0x0(%0) ;"
-    "cmpdi 3, 0x4eed ; " // Check canary
-    "bne   . ; "
-    "ld    0,  0x08(%0) ;"
-    "ld    1,  0x10(%0) ;"
-    "ld    2,  0x18(%0) ;"
-    "ld    14, 0x20(%0) ;"
-    "ld    15, 0x28(%0) ;"
-    "ld    16, 0x30(%0) ;"
-    "ld    17, 0x38(%0) ;"
-    "ld    18, 0x40(%0) ;"
-    "ld    19, 0x48(%0) ;"
-    "ld    20, 0x50(%0) ;"
-    "ld    21, 0x58(%0) ;"
-    "ld    22, 0x60(%0) ;"
-    "ld    23, 0x68(%0) ;"
-    "ld    24, 0x70(%0) ;"
-    "ld    25, 0x78(%0) ;"
-    "ld    26, 0x80(%0) ;"
-    "ld    27, 0x88(%0) ;"
-    "ld    28, 0x90(%0) ;"
-    "ld    29, 0x98(%0) ;"
-    "ld    30, 0xA0(%0) ;"
-    "ld    31, 0xA8(%0) ;"
-    "ld    3,  0xB0(%0) ;"
-    "mtcr  3 ;"
-    "ld    3, 0xB8(%0) ;"
-    "mtlr  3 ; "
-    "li    3, 1;"
-    "blr ;"
-    :
-    : "r"(&top->regs)
-    :
-    );
+    __asm__ volatile (
+        "ld    3, 0x0(%0) ;"
+        "cmpdi 3, 0x4eed ; " // Check canary
+        "bne   . ; "
+        "ld    0,  0x08(%0) ;"
+        "ld    1,  0x10(%0) ;"
+        "ld    2,  0x18(%0) ;"
+        "ld    14, 0x20(%0) ;"
+        "ld    15, 0x28(%0) ;"
+        "ld    16, 0x30(%0) ;"
+        "ld    17, 0x38(%0) ;"
+        "ld    18, 0x40(%0) ;"
+        "ld    19, 0x48(%0) ;"
+        "ld    20, 0x50(%0) ;"
+        "ld    21, 0x58(%0) ;"
+        "ld    22, 0x60(%0) ;"
+        "ld    23, 0x68(%0) ;"
+        "ld    24, 0x70(%0) ;"
+        "ld    25, 0x78(%0) ;"
+        "ld    26, 0x80(%0) ;"
+        "ld    27, 0x88(%0) ;"
+        "ld    28, 0x90(%0) ;"
+        "ld    29, 0x98(%0) ;"
+        "ld    30, 0xA0(%0) ;"
+        "ld    31, 0xA8(%0) ;"
+        "ld    3,  0xB0(%0) ;"
+        "mtcr  3 ;"
+        "ld    3, 0xB8(%0) ;"
+        "mtlr  3 ; "
+        "li    3, 1;"
+        "blr ;"
+        :
+        : "r" (&top->regs)
+        :
+        );
 
     MP_UNREACHABLE;
 }
diff --git a/py/nlrthumb.c b/py/nlrthumb.c
index bc30388..a8ffecc 100644
--- a/py/nlrthumb.c
+++ b/py/nlrthumb.c
@@ -39,51 +39,51 @@
 __attribute__((naked)) unsigned int nlr_push(nlr_buf_t *nlr) {
 
     __asm volatile (
-    "str    r4, [r0, #12]       \n" // store r4 into nlr_buf
-    "str    r5, [r0, #16]       \n" // store r5 into nlr_buf
-    "str    r6, [r0, #20]       \n" // store r6 into nlr_buf
-    "str    r7, [r0, #24]       \n" // store r7 into nlr_buf
+        "str    r4, [r0, #12]       \n" // store r4 into nlr_buf
+        "str    r5, [r0, #16]       \n" // store r5 into nlr_buf
+        "str    r6, [r0, #20]       \n" // store r6 into nlr_buf
+        "str    r7, [r0, #24]       \n" // store r7 into nlr_buf
 
-#if !defined(__thumb2__)
-    "mov    r1, r8              \n"
-    "str    r1, [r0, #28]       \n" // store r8 into nlr_buf
-    "mov    r1, r9              \n"
-    "str    r1, [r0, #32]       \n" // store r9 into nlr_buf
-    "mov    r1, r10             \n"
-    "str    r1, [r0, #36]       \n" // store r10 into nlr_buf
-    "mov    r1, r11             \n"
-    "str    r1, [r0, #40]       \n" // store r11 into nlr_buf
-    "mov    r1, r13             \n"
-    "str    r1, [r0, #44]       \n" // store r13=sp into nlr_buf
-    "mov    r1, lr              \n"
-    "str    r1, [r0, #8]        \n" // store lr into nlr_buf
-#else
-    "str    r8, [r0, #28]       \n" // store r8 into nlr_buf
-    "str    r9, [r0, #32]       \n" // store r9 into nlr_buf
-    "str    r10, [r0, #36]      \n" // store r10 into nlr_buf
-    "str    r11, [r0, #40]      \n" // store r11 into nlr_buf
-    "str    r13, [r0, #44]      \n" // store r13=sp into nlr_buf
-    #if MICROPY_NLR_NUM_REGS == 16
-    "vstr   d8, [r0, #48]       \n" // store s16-s17 into nlr_buf
-    "vstr   d9, [r0, #56]       \n" // store s18-s19 into nlr_buf
-    "vstr   d10, [r0, #64]      \n" // store s20-s21 into nlr_buf
-    #endif
-    "str    lr, [r0, #8]        \n" // store lr into nlr_buf
-#endif
+        #if !defined(__thumb2__)
+        "mov    r1, r8              \n"
+        "str    r1, [r0, #28]       \n" // store r8 into nlr_buf
+        "mov    r1, r9              \n"
+        "str    r1, [r0, #32]       \n" // store r9 into nlr_buf
+        "mov    r1, r10             \n"
+        "str    r1, [r0, #36]       \n" // store r10 into nlr_buf
+        "mov    r1, r11             \n"
+        "str    r1, [r0, #40]       \n" // store r11 into nlr_buf
+        "mov    r1, r13             \n"
+        "str    r1, [r0, #44]       \n" // store r13=sp into nlr_buf
+        "mov    r1, lr              \n"
+        "str    r1, [r0, #8]        \n" // store lr into nlr_buf
+        #else
+        "str    r8, [r0, #28]       \n" // store r8 into nlr_buf
+        "str    r9, [r0, #32]       \n" // store r9 into nlr_buf
+        "str    r10, [r0, #36]      \n" // store r10 into nlr_buf
+        "str    r11, [r0, #40]      \n" // store r11 into nlr_buf
+        "str    r13, [r0, #44]      \n" // store r13=sp into nlr_buf
+        #if MICROPY_NLR_NUM_REGS == 16
+        "vstr   d8, [r0, #48]       \n" // store s16-s17 into nlr_buf
+        "vstr   d9, [r0, #56]       \n" // store s18-s19 into nlr_buf
+        "vstr   d10, [r0, #64]      \n" // store s20-s21 into nlr_buf
+        #endif
+        "str    lr, [r0, #8]        \n" // store lr into nlr_buf
+        #endif
 
-#if !defined(__thumb2__)
-    "ldr    r1, nlr_push_tail_var \n"
-    "bx     r1                  \n" // do the rest in C
-    ".align 2                   \n"
-    "nlr_push_tail_var: .word nlr_push_tail \n"
-#else
-    #if defined(__APPLE__) || defined(__MACH__)
-    "b      _nlr_push_tail      \n" // do the rest in C
-    #else
-    "b      nlr_push_tail       \n" // do the rest in C
-    #endif
-#endif
-    );
+        #if !defined(__thumb2__)
+        "ldr    r1, nlr_push_tail_var \n"
+        "bx     r1                  \n" // do the rest in C
+        ".align 2                   \n"
+        "nlr_push_tail_var: .word nlr_push_tail \n"
+        #else
+        #if defined(__APPLE__) || defined(__MACH__)
+        "b      _nlr_push_tail      \n" // do the rest in C
+        #else
+        "b      nlr_push_tail       \n" // do the rest in C
+        #endif
+        #endif
+        );
 
     #if !defined(__clang__) && defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8))
     // Older versions of gcc give an error when naked functions don't return a value
@@ -96,44 +96,44 @@
     MP_NLR_JUMP_HEAD(val, top)
 
     __asm volatile (
-    "mov    r0, %0              \n" // r0 points to nlr_buf
-    "ldr    r4, [r0, #12]       \n" // load r4 from nlr_buf
-    "ldr    r5, [r0, #16]       \n" // load r5 from nlr_buf
-    "ldr    r6, [r0, #20]       \n" // load r6 from nlr_buf
-    "ldr    r7, [r0, #24]       \n" // load r7 from nlr_buf
+        "mov    r0, %0              \n" // r0 points to nlr_buf
+        "ldr    r4, [r0, #12]       \n" // load r4 from nlr_buf
+        "ldr    r5, [r0, #16]       \n" // load r5 from nlr_buf
+        "ldr    r6, [r0, #20]       \n" // load r6 from nlr_buf
+        "ldr    r7, [r0, #24]       \n" // load r7 from nlr_buf
 
-#if !defined(__thumb2__)
-    "ldr    r1, [r0, #28]       \n" // load r8 from nlr_buf
-    "mov    r8, r1              \n"
-    "ldr    r1, [r0, #32]       \n" // load r9 from nlr_buf
-    "mov    r9, r1              \n"
-    "ldr    r1, [r0, #36]       \n" // load r10 from nlr_buf
-    "mov    r10, r1             \n"
-    "ldr    r1, [r0, #40]       \n" // load r11 from nlr_buf
-    "mov    r11, r1             \n"
-    "ldr    r1, [r0, #44]       \n" // load r13=sp from nlr_buf
-    "mov    r13, r1             \n"
-    "ldr    r1, [r0, #8]        \n" // load lr from nlr_buf
-    "mov    lr, r1              \n"
-#else
-    "ldr    r8, [r0, #28]       \n" // load r8 from nlr_buf
-    "ldr    r9, [r0, #32]       \n" // load r9 from nlr_buf
-    "ldr    r10, [r0, #36]      \n" // load r10 from nlr_buf
-    "ldr    r11, [r0, #40]      \n" // load r11 from nlr_buf
-    "ldr    r13, [r0, #44]      \n" // load r13=sp from nlr_buf
-    #if MICROPY_NLR_NUM_REGS == 16
-    "vldr   d8, [r0, #48]       \n" // load s16-s17 from nlr_buf
-    "vldr   d9, [r0, #56]       \n" // load s18-s19 from nlr_buf
-    "vldr   d10, [r0, #64]      \n" // load s20-s21 from nlr_buf
-    #endif
-    "ldr    lr, [r0, #8]        \n" // load lr from nlr_buf
-#endif
-    "movs   r0, #1              \n" // return 1, non-local return
-    "bx     lr                  \n" // return
-    :                               // output operands
-    : "r"(top)                      // input operands
-    :                               // clobbered registers
-    );
+        #if !defined(__thumb2__)
+        "ldr    r1, [r0, #28]       \n" // load r8 from nlr_buf
+        "mov    r8, r1              \n"
+        "ldr    r1, [r0, #32]       \n" // load r9 from nlr_buf
+        "mov    r9, r1              \n"
+        "ldr    r1, [r0, #36]       \n" // load r10 from nlr_buf
+        "mov    r10, r1             \n"
+        "ldr    r1, [r0, #40]       \n" // load r11 from nlr_buf
+        "mov    r11, r1             \n"
+        "ldr    r1, [r0, #44]       \n" // load r13=sp from nlr_buf
+        "mov    r13, r1             \n"
+        "ldr    r1, [r0, #8]        \n" // load lr from nlr_buf
+        "mov    lr, r1              \n"
+        #else
+        "ldr    r8, [r0, #28]       \n" // load r8 from nlr_buf
+        "ldr    r9, [r0, #32]       \n" // load r9 from nlr_buf
+        "ldr    r10, [r0, #36]      \n" // load r10 from nlr_buf
+        "ldr    r11, [r0, #40]      \n" // load r11 from nlr_buf
+        "ldr    r13, [r0, #44]      \n" // load r13=sp from nlr_buf
+        #if MICROPY_NLR_NUM_REGS == 16
+        "vldr   d8, [r0, #48]       \n" // load s16-s17 from nlr_buf
+        "vldr   d9, [r0, #56]       \n" // load s18-s19 from nlr_buf
+        "vldr   d10, [r0, #64]      \n" // load s20-s21 from nlr_buf
+        #endif
+        "ldr    lr, [r0, #8]        \n" // load lr from nlr_buf
+        #endif
+        "movs   r0, #1              \n" // return 1, non-local return
+        "bx     lr                  \n" // return
+        :                           // output operands
+        : "r" (top)                 // input operands
+        :                           // clobbered registers
+        );
 
     MP_UNREACHABLE
 }
diff --git a/py/nlrx64.c b/py/nlrx64.c
index 95496b3..eb39dad 100644
--- a/py/nlrx64.c
+++ b/py/nlrx64.c
@@ -41,41 +41,41 @@
     #if MICROPY_NLR_OS_WINDOWS
 
     __asm volatile (
-    "movq   (%rsp), %rax        \n" // load return %rip
-    "movq   %rax, 16(%rcx)      \n" // store %rip into nlr_buf
-    "movq   %rbp, 24(%rcx)      \n" // store %rbp into nlr_buf
-    "movq   %rsp, 32(%rcx)      \n" // store %rsp into nlr_buf
-    "movq   %rbx, 40(%rcx)      \n" // store %rbx into nlr_buf
-    "movq   %r12, 48(%rcx)      \n" // store %r12 into nlr_buf
-    "movq   %r13, 56(%rcx)      \n" // store %r13 into nlr_buf
-    "movq   %r14, 64(%rcx)      \n" // store %r14 into nlr_buf
-    "movq   %r15, 72(%rcx)      \n" // store %r15 into nlr_buf
-    "movq   %rdi, 80(%rcx)      \n" // store %rdr into nlr_buf
-    "movq   %rsi, 88(%rcx)      \n" // store %rsi into nlr_buf
-    "jmp    nlr_push_tail       \n" // do the rest in C
-    );
+        "movq   (%rsp), %rax        \n" // load return %rip
+        "movq   %rax, 16(%rcx)      \n" // store %rip into nlr_buf
+        "movq   %rbp, 24(%rcx)      \n" // store %rbp into nlr_buf
+        "movq   %rsp, 32(%rcx)      \n" // store %rsp into nlr_buf
+        "movq   %rbx, 40(%rcx)      \n" // store %rbx into nlr_buf
+        "movq   %r12, 48(%rcx)      \n" // store %r12 into nlr_buf
+        "movq   %r13, 56(%rcx)      \n" // store %r13 into nlr_buf
+        "movq   %r14, 64(%rcx)      \n" // store %r14 into nlr_buf
+        "movq   %r15, 72(%rcx)      \n" // store %r15 into nlr_buf
+        "movq   %rdi, 80(%rcx)      \n" // store %rdr into nlr_buf
+        "movq   %rsi, 88(%rcx)      \n" // store %rsi into nlr_buf
+        "jmp    nlr_push_tail       \n" // do the rest in C
+        );
 
     #else
 
     __asm volatile (
-    #if defined(__APPLE__) || defined(__MACH__)
-    "pop    %rbp                \n" // undo function's prelude
-    #endif
-    "movq   (%rsp), %rax        \n" // load return %rip
-    "movq   %rax, 16(%rdi)      \n" // store %rip into nlr_buf
-    "movq   %rbp, 24(%rdi)      \n" // store %rbp into nlr_buf
-    "movq   %rsp, 32(%rdi)      \n" // store %rsp into nlr_buf
-    "movq   %rbx, 40(%rdi)      \n" // store %rbx into nlr_buf
-    "movq   %r12, 48(%rdi)      \n" // store %r12 into nlr_buf
-    "movq   %r13, 56(%rdi)      \n" // store %r13 into nlr_buf
-    "movq   %r14, 64(%rdi)      \n" // store %r14 into nlr_buf
-    "movq   %r15, 72(%rdi)      \n" // store %r15 into nlr_buf
-    #if defined(__APPLE__) || defined(__MACH__)
-    "jmp    _nlr_push_tail      \n" // do the rest in C
-    #else
-    "jmp    nlr_push_tail       \n" // do the rest in C
-    #endif
-    );
+        #if defined(__APPLE__) || defined(__MACH__)
+        "pop    %rbp                \n" // undo function's prelude
+        #endif
+        "movq   (%rsp), %rax        \n" // load return %rip
+        "movq   %rax, 16(%rdi)      \n" // store %rip into nlr_buf
+        "movq   %rbp, 24(%rdi)      \n" // store %rbp into nlr_buf
+        "movq   %rsp, 32(%rdi)      \n" // store %rsp into nlr_buf
+        "movq   %rbx, 40(%rdi)      \n" // store %rbx into nlr_buf
+        "movq   %r12, 48(%rdi)      \n" // store %r12 into nlr_buf
+        "movq   %r13, 56(%rdi)      \n" // store %r13 into nlr_buf
+        "movq   %r14, 64(%rdi)      \n" // store %r14 into nlr_buf
+        "movq   %r15, 72(%rdi)      \n" // store %r15 into nlr_buf
+        #if defined(__APPLE__) || defined(__MACH__)
+        "jmp    _nlr_push_tail      \n" // do the rest in C
+        #else
+        "jmp    nlr_push_tail       \n" // do the rest in C
+        #endif
+        );
 
     #endif
 
@@ -86,27 +86,27 @@
     MP_NLR_JUMP_HEAD(val, top)
 
     __asm volatile (
-    "movq   %0, %%rcx           \n" // %rcx points to nlr_buf
-    #if MICROPY_NLR_OS_WINDOWS
-    "movq   88(%%rcx), %%rsi    \n" // load saved %rsi
-    "movq   80(%%rcx), %%rdi    \n" // load saved %rdr
-    #endif
-    "movq   72(%%rcx), %%r15    \n" // load saved %r15
-    "movq   64(%%rcx), %%r14    \n" // load saved %r14
-    "movq   56(%%rcx), %%r13    \n" // load saved %r13
-    "movq   48(%%rcx), %%r12    \n" // load saved %r12
-    "movq   40(%%rcx), %%rbx    \n" // load saved %rbx
-    "movq   32(%%rcx), %%rsp    \n" // load saved %rsp
-    "movq   24(%%rcx), %%rbp    \n" // load saved %rbp
-    "movq   16(%%rcx), %%rax    \n" // load saved %rip
-    "movq   %%rax, (%%rsp)      \n" // store saved %rip to stack
-    "xorq   %%rax, %%rax        \n" // clear return register
-    "inc    %%al                \n" // increase to make 1, non-local return
-    "ret                        \n" // return
-    :                               // output operands
-    : "r"(top)                      // input operands
-    :                               // clobbered registers
-    );
+        "movq   %0, %%rcx           \n" // %rcx points to nlr_buf
+        #if MICROPY_NLR_OS_WINDOWS
+        "movq   88(%%rcx), %%rsi    \n" // load saved %rsi
+        "movq   80(%%rcx), %%rdi    \n" // load saved %rdr
+        #endif
+        "movq   72(%%rcx), %%r15    \n" // load saved %r15
+        "movq   64(%%rcx), %%r14    \n" // load saved %r14
+        "movq   56(%%rcx), %%r13    \n" // load saved %r13
+        "movq   48(%%rcx), %%r12    \n" // load saved %r12
+        "movq   40(%%rcx), %%rbx    \n" // load saved %rbx
+        "movq   32(%%rcx), %%rsp    \n" // load saved %rsp
+        "movq   24(%%rcx), %%rbp    \n" // load saved %rbp
+        "movq   16(%%rcx), %%rax    \n" // load saved %rip
+        "movq   %%rax, (%%rsp)      \n" // store saved %rip to stack
+        "xorq   %%rax, %%rax        \n" // clear return register
+        "inc    %%al                \n" // increase to make 1, non-local return
+        "ret                        \n" // return
+        :                           // output operands
+        : "r" (top)                 // input operands
+        :                           // clobbered registers
+        );
 
     MP_UNREACHABLE
 }
diff --git a/py/nlrx86.c b/py/nlrx86.c
index 461b459..f658d41 100644
--- a/py/nlrx86.c
+++ b/py/nlrx86.c
@@ -34,7 +34,7 @@
 //  ebx, esi, edi, ebp, esp, eip
 
 #if MICROPY_NLR_OS_WINDOWS
-unsigned int nlr_push_tail(nlr_buf_t *nlr) asm("nlr_push_tail");
+unsigned int nlr_push_tail(nlr_buf_t *nlr) asm ("nlr_push_tail");
 #else
 __attribute__((used)) unsigned int nlr_push_tail(nlr_buf_t *nlr);
 #endif
@@ -59,19 +59,19 @@
     (void)nlr;
 
     __asm volatile (
-    #if UNDO_PRELUDE
-    "pop    %ebp                \n" // undo function's prelude
-    #endif
-    "mov    4(%esp), %edx       \n" // load nlr_buf
-    "mov    (%esp), %eax        \n" // load return %eip
-    "mov    %eax, 8(%edx)       \n" // store %eip into nlr_buf
-    "mov    %ebp, 12(%edx)      \n" // store %ebp into nlr_buf
-    "mov    %esp, 16(%edx)      \n" // store %esp into nlr_buf
-    "mov    %ebx, 20(%edx)      \n" // store %ebx into nlr_buf
-    "mov    %edi, 24(%edx)      \n" // store %edi into nlr_buf
-    "mov    %esi, 28(%edx)      \n" // store %esi into nlr_buf
-    "jmp    nlr_push_tail       \n" // do the rest in C
-    );
+        #if UNDO_PRELUDE
+        "pop    %ebp                \n" // undo function's prelude
+        #endif
+        "mov    4(%esp), %edx       \n" // load nlr_buf
+        "mov    (%esp), %eax        \n" // load return %eip
+        "mov    %eax, 8(%edx)       \n" // store %eip into nlr_buf
+        "mov    %ebp, 12(%edx)      \n" // store %ebp into nlr_buf
+        "mov    %esp, 16(%edx)      \n" // store %esp into nlr_buf
+        "mov    %ebx, 20(%edx)      \n" // store %ebx into nlr_buf
+        "mov    %edi, 24(%edx)      \n" // store %edi into nlr_buf
+        "mov    %esi, 28(%edx)      \n" // store %esi into nlr_buf
+        "jmp    nlr_push_tail       \n" // do the rest in C
+        );
 
     #if !USE_NAKED
     return 0; // needed to silence compiler warning
@@ -82,21 +82,21 @@
     MP_NLR_JUMP_HEAD(val, top)
 
     __asm volatile (
-    "mov    %0, %%edx           \n" // %edx points to nlr_buf
-    "mov    28(%%edx), %%esi    \n" // load saved %esi
-    "mov    24(%%edx), %%edi    \n" // load saved %edi
-    "mov    20(%%edx), %%ebx    \n" // load saved %ebx
-    "mov    16(%%edx), %%esp    \n" // load saved %esp
-    "mov    12(%%edx), %%ebp    \n" // load saved %ebp
-    "mov    8(%%edx), %%eax     \n" // load saved %eip
-    "mov    %%eax, (%%esp)      \n" // store saved %eip to stack
-    "xor    %%eax, %%eax        \n" // clear return register
-    "inc    %%al                \n" // increase to make 1, non-local return
-    "ret                        \n" // return
-    :                               // output operands
-    : "r"(top)                      // input operands
-    :                               // clobbered registers
-    );
+        "mov    %0, %%edx           \n" // %edx points to nlr_buf
+        "mov    28(%%edx), %%esi    \n" // load saved %esi
+        "mov    24(%%edx), %%edi    \n" // load saved %edi
+        "mov    20(%%edx), %%ebx    \n" // load saved %ebx
+        "mov    16(%%edx), %%esp    \n" // load saved %esp
+        "mov    12(%%edx), %%ebp    \n" // load saved %ebp
+        "mov    8(%%edx), %%eax     \n" // load saved %eip
+        "mov    %%eax, (%%esp)      \n" // store saved %eip to stack
+        "xor    %%eax, %%eax        \n" // clear return register
+        "inc    %%al                \n" // increase to make 1, non-local return
+        "ret                        \n" // return
+        :                           // output operands
+        : "r" (top)                 // input operands
+        :                           // clobbered registers
+        );
 
     MP_UNREACHABLE
 }
diff --git a/py/nlrxtensa.c b/py/nlrxtensa.c
index 895b202..abe9042 100644
--- a/py/nlrxtensa.c
+++ b/py/nlrxtensa.c
@@ -39,18 +39,18 @@
 unsigned int nlr_push(nlr_buf_t *nlr) {
 
     __asm volatile (
-    "s32i.n  a0, a2, 8          \n" // save regs...
-    "s32i.n  a1, a2, 12         \n"
-    "s32i.n  a8, a2, 16         \n"
-    "s32i.n  a9, a2, 20         \n"
-    "s32i.n  a10, a2, 24        \n"
-    "s32i.n  a11, a2, 28        \n"
-    "s32i.n  a12, a2, 32        \n"
-    "s32i.n  a13, a2, 36        \n"
-    "s32i.n  a14, a2, 40        \n"
-    "s32i.n  a15, a2, 44        \n"
-    "j      nlr_push_tail       \n" // do the rest in C
-    );
+        "s32i.n  a0, a2, 8          \n" // save regs...
+        "s32i.n  a1, a2, 12         \n"
+        "s32i.n  a8, a2, 16         \n"
+        "s32i.n  a9, a2, 20         \n"
+        "s32i.n  a10, a2, 24        \n"
+        "s32i.n  a11, a2, 28        \n"
+        "s32i.n  a12, a2, 32        \n"
+        "s32i.n  a13, a2, 36        \n"
+        "s32i.n  a14, a2, 40        \n"
+        "s32i.n  a15, a2, 44        \n"
+        "j      nlr_push_tail       \n" // do the rest in C
+        );
 
     return 0; // needed to silence compiler warning
 }
@@ -59,23 +59,23 @@
     MP_NLR_JUMP_HEAD(val, top)
 
     __asm volatile (
-    "mov.n   a2, %0             \n" // a2 points to nlr_buf
-    "l32i.n  a0, a2, 8          \n" // restore regs...
-    "l32i.n  a1, a2, 12         \n"
-    "l32i.n  a8, a2, 16         \n"
-    "l32i.n  a9, a2, 20         \n"
-    "l32i.n  a10, a2, 24        \n"
-    "l32i.n  a11, a2, 28        \n"
-    "l32i.n  a12, a2, 32        \n"
-    "l32i.n  a13, a2, 36        \n"
-    "l32i.n  a14, a2, 40        \n"
-    "l32i.n  a15, a2, 44        \n"
-    "movi.n a2, 1               \n" // return 1, non-local return
-    "ret.n                      \n" // return
-    :                               // output operands
-    : "r"(top)                      // input operands
-    :                               // clobbered registers
-    );
+        "mov.n   a2, %0             \n" // a2 points to nlr_buf
+        "l32i.n  a0, a2, 8          \n" // restore regs...
+        "l32i.n  a1, a2, 12         \n"
+        "l32i.n  a8, a2, 16         \n"
+        "l32i.n  a9, a2, 20         \n"
+        "l32i.n  a10, a2, 24        \n"
+        "l32i.n  a11, a2, 28        \n"
+        "l32i.n  a12, a2, 32        \n"
+        "l32i.n  a13, a2, 36        \n"
+        "l32i.n  a14, a2, 40        \n"
+        "l32i.n  a15, a2, 44        \n"
+        "movi.n a2, 1               \n" // return 1, non-local return
+        "ret.n                      \n" // return
+        :                           // output operands
+        : "r" (top)                 // input operands
+        :                           // clobbered registers
+        );
 
     MP_UNREACHABLE
 }
diff --git a/py/obj.c b/py/obj.c
index eef24a9..6e68180 100644
--- a/py/obj.c
+++ b/py/obj.c
@@ -77,11 +77,11 @@
         return &mp_type_int;
     } else if (mp_obj_is_qstr(o_in)) {
         return &mp_type_str;
-    #if MICROPY_PY_BUILTINS_FLOAT && ( \
-        MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D)
+        #if MICROPY_PY_BUILTINS_FLOAT && ( \
+            MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D)
     } else if (mp_obj_is_float(o_in)) {
         return &mp_type_float;
-    #endif
+        #endif
     #if MICROPY_OBJ_IMMEDIATE_OBJS
     } else if (mp_obj_is_immediate_obj(o_in)) {
         static const mp_obj_type_t *const types[2] = {&mp_type_NoneType, &mp_type_bool};
@@ -102,15 +102,15 @@
 void mp_obj_print_helper(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) {
     // There can be data structures nested too deep, or just recursive
     MP_STACK_CHECK();
-#ifndef NDEBUG
+    #ifndef NDEBUG
     if (o_in == MP_OBJ_NULL) {
         mp_print_str(print, "(nil)");
         return;
     }
-#endif
+    #endif
     const mp_obj_type_t *type = mp_obj_get_type(o_in);
     if (type->print != NULL) {
-        type->print((mp_print_t*)print, o_in, kind);
+        type->print((mp_print_t *)print, o_in, kind);
     } else {
         mp_printf(print, "<%q>", type->name);
     }
@@ -129,11 +129,11 @@
             assert(n % 3 == 0);
             mp_print_str(print, "Traceback (most recent call last):\n");
             for (int i = n - 3; i >= 0; i -= 3) {
-#if MICROPY_ENABLE_SOURCE_LINE
+                #if MICROPY_ENABLE_SOURCE_LINE
                 mp_printf(print, "  File \"%q\", line %d", values[i], (int)values[i + 1]);
-#else
+                #else
                 mp_printf(print, "  File \"%q\"", values[i]);
-#endif
+                #endif
                 // the block name can be NULL if it's unknown
                 qstr block = values[i + 2];
                 if (block == MP_QSTRnull) {
@@ -507,10 +507,10 @@
 // may return MP_OBJ_NULL
 mp_obj_t mp_obj_len_maybe(mp_obj_t o_in) {
     if (
-#if !MICROPY_PY_BUILTINS_STR_UNICODE
+        #if !MICROPY_PY_BUILTINS_STR_UNICODE
         // It's simple - unicode is slow, non-unicode is fast
         mp_obj_is_str(o_in) ||
-#endif
+        #endif
         mp_obj_is_type(o_in, &mp_type_bytes)) {
         GET_STR_LEN(o_in, l);
         return MP_OBJ_NEW_SMALL_INT(l);
@@ -589,7 +589,9 @@
 
 mp_obj_t mp_generic_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
     switch (op) {
-        case MP_UNARY_OP_HASH: return MP_OBJ_NEW_SMALL_INT((mp_uint_t)o_in);
-        default: return MP_OBJ_NULL; // op not supported
+        case MP_UNARY_OP_HASH:
+            return MP_OBJ_NEW_SMALL_INT((mp_uint_t)o_in);
+        default:
+            return MP_OBJ_NULL;      // op not supported
     }
 }
diff --git a/py/obj.h b/py/obj.h
index 3e910eb..e3299cb 100644
--- a/py/obj.h
+++ b/py/obj.h
@@ -66,13 +66,13 @@
 // as many as we can to MP_OBJ_NULL because it's cheaper to load/compare 0.
 
 #if MICROPY_DEBUG_MP_OBJ_SENTINELS
-#define MP_OBJ_NULL             (MP_OBJ_FROM_PTR((void*)0))
-#define MP_OBJ_STOP_ITERATION   (MP_OBJ_FROM_PTR((void*)4))
-#define MP_OBJ_SENTINEL         (MP_OBJ_FROM_PTR((void*)8))
+#define MP_OBJ_NULL             (MP_OBJ_FROM_PTR((void *)0))
+#define MP_OBJ_STOP_ITERATION   (MP_OBJ_FROM_PTR((void *)4))
+#define MP_OBJ_SENTINEL         (MP_OBJ_FROM_PTR((void *)8))
 #else
-#define MP_OBJ_NULL             (MP_OBJ_FROM_PTR((void*)0))
-#define MP_OBJ_STOP_ITERATION   (MP_OBJ_FROM_PTR((void*)0))
-#define MP_OBJ_SENTINEL         (MP_OBJ_FROM_PTR((void*)4))
+#define MP_OBJ_NULL             (MP_OBJ_FROM_PTR((void *)0))
+#define MP_OBJ_STOP_ITERATION   (MP_OBJ_FROM_PTR((void *)0))
+#define MP_OBJ_SENTINEL         (MP_OBJ_FROM_PTR((void *)4))
 #endif
 
 // These macros/inline functions operate on objects and depend on the
@@ -81,18 +81,21 @@
 
 #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A
 
-static inline bool mp_obj_is_small_int(mp_const_obj_t o)
-    { return ((((mp_int_t)(o)) & 1) != 0); }
+static inline bool mp_obj_is_small_int(mp_const_obj_t o) {
+    return (((mp_int_t)(o)) & 1) != 0;
+}
 #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)(o)) >> 1)
 #define MP_OBJ_NEW_SMALL_INT(small_int) ((mp_obj_t)((((mp_uint_t)(small_int)) << 1) | 1))
 
-static inline bool mp_obj_is_qstr(mp_const_obj_t o)
-    { return ((((mp_int_t)(o)) & 7) == 2); }
+static inline bool mp_obj_is_qstr(mp_const_obj_t o) {
+    return (((mp_int_t)(o)) & 7) == 2;
+}
 #define MP_OBJ_QSTR_VALUE(o) (((mp_uint_t)(o)) >> 3)
 #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 3) | 2))
 
-static inline bool mp_obj_is_immediate_obj(mp_const_obj_t o)
-    { return ((((mp_int_t)(o)) & 7) == 6); }
+static inline bool mp_obj_is_immediate_obj(mp_const_obj_t o) {
+    return (((mp_int_t)(o)) & 7) == 6;
+}
 #define MP_OBJ_IMMEDIATE_OBJ_VALUE(o) (((mp_uint_t)(o)) >> 3)
 #define MP_OBJ_NEW_IMMEDIATE_OBJ(val) ((mp_obj_t)(((val) << 3) | 6))
 
@@ -107,23 +110,27 @@
 mp_obj_t mp_obj_new_float(mp_float_t value);
 #endif
 
-static inline bool mp_obj_is_obj(mp_const_obj_t o)
-    { return ((((mp_int_t)(o)) & 3) == 0); }
+static inline bool mp_obj_is_obj(mp_const_obj_t o) {
+    return (((mp_int_t)(o)) & 3) == 0;
+}
 
 #elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B
 
-static inline bool mp_obj_is_small_int(mp_const_obj_t o)
-    { return ((((mp_int_t)(o)) & 3) == 1); }
+static inline bool mp_obj_is_small_int(mp_const_obj_t o) {
+    return (((mp_int_t)(o)) & 3) == 1;
+}
 #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)(o)) >> 2)
 #define MP_OBJ_NEW_SMALL_INT(small_int) ((mp_obj_t)((((mp_uint_t)(small_int)) << 2) | 1))
 
-static inline bool mp_obj_is_qstr(mp_const_obj_t o)
-    { return ((((mp_int_t)(o)) & 7) == 3); }
+static inline bool mp_obj_is_qstr(mp_const_obj_t o) {
+    return (((mp_int_t)(o)) & 7) == 3;
+}
 #define MP_OBJ_QSTR_VALUE(o) (((mp_uint_t)(o)) >> 3)
 #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 3) | 3))
 
-static inline bool mp_obj_is_immediate_obj(mp_const_obj_t o)
-    { return ((((mp_int_t)(o)) & 7) == 7); }
+static inline bool mp_obj_is_immediate_obj(mp_const_obj_t o) {
+    return (((mp_int_t)(o)) & 7) == 7;
+}
 #define MP_OBJ_IMMEDIATE_OBJ_VALUE(o) (((mp_uint_t)(o)) >> 3)
 #define MP_OBJ_NEW_IMMEDIATE_OBJ(val) ((mp_obj_t)(((val) << 3) | 7))
 
@@ -138,13 +145,15 @@
 mp_obj_t mp_obj_new_float(mp_float_t value);
 #endif
 
-static inline bool mp_obj_is_obj(mp_const_obj_t o)
-    { return ((((mp_int_t)(o)) & 1) == 0); }
+static inline bool mp_obj_is_obj(mp_const_obj_t o) {
+    return (((mp_int_t)(o)) & 1) == 0;
+}
 
 #elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C
 
-static inline bool mp_obj_is_small_int(mp_const_obj_t o)
-    { return ((((mp_int_t)(o)) & 1) != 0); }
+static inline bool mp_obj_is_small_int(mp_const_obj_t o) {
+    return (((mp_int_t)(o)) & 1) != 0;
+}
 #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)(o)) >> 1)
 #define MP_OBJ_NEW_SMALL_INT(small_int) ((mp_obj_t)((((mp_uint_t)(small_int)) << 1) | 1))
 
@@ -152,8 +161,9 @@
 #define mp_const_float_e MP_ROM_PTR((mp_obj_t)(((0x402df854 & ~3) | 2) + 0x80800000))
 #define mp_const_float_pi MP_ROM_PTR((mp_obj_t)(((0x40490fdb & ~3) | 2) + 0x80800000))
 
-static inline bool mp_obj_is_float(mp_const_obj_t o)
-    { return (((mp_uint_t)(o)) & 3) == 2 && (((mp_uint_t)(o)) & 0xff800007) != 0x00000006; }
+static inline bool mp_obj_is_float(mp_const_obj_t o) {
+    return (((mp_uint_t)(o)) & 3) == 2 && (((mp_uint_t)(o)) & 0xff800007) != 0x00000006;
+}
 static inline mp_float_t mp_obj_float_get(mp_const_obj_t o) {
     union {
         mp_float_t f;
@@ -170,33 +180,39 @@
 }
 #endif
 
-static inline bool mp_obj_is_qstr(mp_const_obj_t o)
-    { return (((mp_uint_t)(o)) & 0xff80000f) == 0x00000006; }
+static inline bool mp_obj_is_qstr(mp_const_obj_t o) {
+    return (((mp_uint_t)(o)) & 0xff80000f) == 0x00000006;
+}
 #define MP_OBJ_QSTR_VALUE(o) (((mp_uint_t)(o)) >> 4)
 #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 4) | 0x00000006))
 
-static inline bool mp_obj_is_immediate_obj(mp_const_obj_t o)
-    { return (((mp_uint_t)(o)) & 0xff80000f) == 0x0000000e; }
+static inline bool mp_obj_is_immediate_obj(mp_const_obj_t o) {
+    return (((mp_uint_t)(o)) & 0xff80000f) == 0x0000000e;
+}
 #define MP_OBJ_IMMEDIATE_OBJ_VALUE(o) (((mp_uint_t)(o)) >> 4)
 #define MP_OBJ_NEW_IMMEDIATE_OBJ(val) ((mp_obj_t)(((val) << 4) | 0xe))
 
-static inline bool mp_obj_is_obj(mp_const_obj_t o)
-    { return ((((mp_int_t)(o)) & 3) == 0); }
+static inline bool mp_obj_is_obj(mp_const_obj_t o) {
+    return (((mp_int_t)(o)) & 3) == 0;
+}
 
 #elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
 
-static inline bool mp_obj_is_small_int(mp_const_obj_t o)
-    { return ((((uint64_t)(o)) & 0xffff000000000000) == 0x0001000000000000); }
+static inline bool mp_obj_is_small_int(mp_const_obj_t o) {
+    return (((uint64_t)(o)) & 0xffff000000000000) == 0x0001000000000000;
+}
 #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)((o) << 16)) >> 17)
 #define MP_OBJ_NEW_SMALL_INT(small_int) (((((uint64_t)(small_int)) & 0x7fffffffffff) << 1) | 0x0001000000000001)
 
-static inline bool mp_obj_is_qstr(mp_const_obj_t o)
-    { return ((((uint64_t)(o)) & 0xffff000000000000) == 0x0002000000000000); }
+static inline bool mp_obj_is_qstr(mp_const_obj_t o) {
+    return (((uint64_t)(o)) & 0xffff000000000000) == 0x0002000000000000;
+}
 #define MP_OBJ_QSTR_VALUE(o) ((((uint32_t)(o)) >> 1) & 0xffffffff)
 #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)(((uint64_t)(((uint32_t)(qst)) << 1)) | 0x0002000000000001))
 
-static inline bool mp_obj_is_immediate_obj(mp_const_obj_t o)
-    { return ((((uint64_t)(o)) & 0xffff000000000000) == 0x0003000000000000); }
+static inline bool mp_obj_is_immediate_obj(mp_const_obj_t o) {
+    return (((uint64_t)(o)) & 0xffff000000000000) == 0x0003000000000000;
+}
 #define MP_OBJ_IMMEDIATE_OBJ_VALUE(o) ((((uint32_t)(o)) >> 46) & 3)
 #define MP_OBJ_NEW_IMMEDIATE_OBJ(val) (((uint64_t)(val) << 46) | 0x0003000000000000)
 
@@ -228,13 +244,17 @@
 }
 #endif
 
-static inline bool mp_obj_is_obj(mp_const_obj_t o)
-    { return ((((uint64_t)(o)) & 0xffff000000000000) == 0x0000000000000000); }
-#define MP_OBJ_TO_PTR(o) ((void*)(uintptr_t)(o))
+static inline bool mp_obj_is_obj(mp_const_obj_t o) {
+    return (((uint64_t)(o)) & 0xffff000000000000) == 0x0000000000000000;
+}
+#define MP_OBJ_TO_PTR(o) ((void *)(uintptr_t)(o))
 #define MP_OBJ_FROM_PTR(p) ((mp_obj_t)((uintptr_t)(p)))
 
 // rom object storage needs special handling to widen 32-bit pointer to 64-bits
-typedef union _mp_rom_obj_t { uint64_t u64; struct { const void *lo, *hi; } u32; } mp_rom_obj_t;
+typedef union _mp_rom_obj_t { uint64_t u64;
+                              struct { const void *lo, *hi;
+                              } u32;
+} mp_rom_obj_t;
 #define MP_ROM_INT(i) {MP_OBJ_NEW_SMALL_INT(i)}
 #define MP_ROM_QSTR(q) {MP_OBJ_NEW_QSTR(q)}
 #if MP_ENDIANNESS_LITTLE
@@ -252,7 +272,7 @@
 
 // Cast mp_obj_t to object pointer
 #ifndef MP_OBJ_TO_PTR
-#define MP_OBJ_TO_PTR(o) ((void*)o)
+#define MP_OBJ_TO_PTR(o) ((void *)o)
 #endif
 
 // Cast object pointer to mp_obj_t
@@ -309,25 +329,25 @@
 
 #define MP_DEFINE_CONST_FUN_OBJ_0(obj_name, fun_name) \
     const mp_obj_fun_builtin_fixed_t obj_name = \
-        {{&mp_type_fun_builtin_0}, .fun._0 = fun_name}
+    {{&mp_type_fun_builtin_0}, .fun._0 = fun_name}
 #define MP_DEFINE_CONST_FUN_OBJ_1(obj_name, fun_name) \
     const mp_obj_fun_builtin_fixed_t obj_name = \
-        {{&mp_type_fun_builtin_1}, .fun._1 = fun_name}
+    {{&mp_type_fun_builtin_1}, .fun._1 = fun_name}
 #define MP_DEFINE_CONST_FUN_OBJ_2(obj_name, fun_name) \
     const mp_obj_fun_builtin_fixed_t obj_name = \
-        {{&mp_type_fun_builtin_2}, .fun._2 = fun_name}
+    {{&mp_type_fun_builtin_2}, .fun._2 = fun_name}
 #define MP_DEFINE_CONST_FUN_OBJ_3(obj_name, fun_name) \
     const mp_obj_fun_builtin_fixed_t obj_name = \
-        {{&mp_type_fun_builtin_3}, .fun._3 = fun_name}
+    {{&mp_type_fun_builtin_3}, .fun._3 = fun_name}
 #define MP_DEFINE_CONST_FUN_OBJ_VAR(obj_name, n_args_min, fun_name) \
     const mp_obj_fun_builtin_var_t obj_name = \
-        {{&mp_type_fun_builtin_var}, MP_OBJ_FUN_MAKE_SIG(n_args_min, MP_OBJ_FUN_ARGS_MAX, false), .fun.var = fun_name}
+    {{&mp_type_fun_builtin_var}, MP_OBJ_FUN_MAKE_SIG(n_args_min, MP_OBJ_FUN_ARGS_MAX, false), .fun.var = fun_name}
 #define MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(obj_name, n_args_min, n_args_max, fun_name) \
     const mp_obj_fun_builtin_var_t obj_name = \
-        {{&mp_type_fun_builtin_var}, MP_OBJ_FUN_MAKE_SIG(n_args_min, n_args_max, false), .fun.var = fun_name}
+    {{&mp_type_fun_builtin_var}, MP_OBJ_FUN_MAKE_SIG(n_args_min, n_args_max, false), .fun.var = fun_name}
 #define MP_DEFINE_CONST_FUN_OBJ_KW(obj_name, n_args_min, fun_name) \
     const mp_obj_fun_builtin_var_t obj_name = \
-        {{&mp_type_fun_builtin_var}, MP_OBJ_FUN_MAKE_SIG(n_args_min, MP_OBJ_FUN_ARGS_MAX, true), .fun.kw = fun_name}
+    {{&mp_type_fun_builtin_var}, MP_OBJ_FUN_MAKE_SIG(n_args_min, MP_OBJ_FUN_ARGS_MAX, true), .fun.kw = fun_name}
 
 // These macros are used to define constant map/dict objects
 // You can put "static" in front of the definition to make it local
@@ -339,7 +359,7 @@
         .is_ordered = 1, \
         .used = MP_ARRAY_SIZE(table_name), \
         .alloc = MP_ARRAY_SIZE(table_name), \
-        .table = (mp_map_elem_t*)(mp_rom_map_elem_t*)table_name, \
+        .table = (mp_map_elem_t *)(mp_rom_map_elem_t *)table_name, \
     }
 
 #define MP_DEFINE_CONST_DICT(dict_name, table_name) \
@@ -351,7 +371,7 @@
             .is_ordered = 1, \
             .used = MP_ARRAY_SIZE(table_name), \
             .alloc = MP_ARRAY_SIZE(table_name), \
-            .table = (mp_map_elem_t*)(mp_rom_map_elem_t*)table_name, \
+            .table = (mp_map_elem_t *)(mp_rom_map_elem_t *)table_name, \
         }, \
     }
 
@@ -402,7 +422,9 @@
 
 extern const mp_map_t mp_const_empty_map;
 
-static inline bool mp_map_slot_is_filled(const mp_map_t *map, size_t pos) { return ((map)->table[pos].key != MP_OBJ_NULL && (map)->table[pos].key != MP_OBJ_SENTINEL); }
+static inline bool mp_map_slot_is_filled(const mp_map_t *map, size_t pos) {
+    return (map)->table[pos].key != MP_OBJ_NULL && (map)->table[pos].key != MP_OBJ_SENTINEL;
+}
 
 void mp_map_init(mp_map_t *map, size_t n);
 void mp_map_init_fixed_table(mp_map_t *map, size_t n, const mp_obj_t *table);
@@ -421,7 +443,9 @@
     mp_obj_t *table;
 } mp_set_t;
 
-static inline bool mp_set_slot_is_filled(const mp_set_t *set, size_t pos) { return ((set)->table[pos] != MP_OBJ_NULL && (set)->table[pos] != MP_OBJ_SENTINEL); }
+static inline bool mp_set_slot_is_filled(const mp_set_t *set, size_t pos) {
+    return (set)->table[pos] != MP_OBJ_NULL && (set)->table[pos] != MP_OBJ_SENTINEL;
+}
 
 void mp_set_init(mp_set_t *set, size_t n);
 mp_obj_t mp_set_lookup(mp_set_t *set, mp_obj_t index, mp_map_lookup_kind_t lookup_kind);
@@ -672,7 +696,7 @@
 // check for more specific object types.
 // Note: these are kept as macros because inline functions sometimes use much
 // more code space than the equivalent macros, depending on the compiler.
-#define mp_obj_is_type(o, t) (mp_obj_is_obj(o) && (((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type == (t))) // this does not work for checking int, str or fun; use below macros for that
+#define mp_obj_is_type(o, t) (mp_obj_is_obj(o) && (((mp_obj_base_t *)MP_OBJ_TO_PTR(o))->type == (t))) // this does not work for checking int, str or fun; use below macros for that
 #if MICROPY_OBJ_IMMEDIATE_OBJS
 // bool's are immediates, not real objects, so test for the 2 possible values.
 #define mp_obj_is_bool(o) ((o) == mp_const_false || (o) == mp_const_true)
@@ -681,21 +705,23 @@
 #endif
 #define mp_obj_is_int(o) (mp_obj_is_small_int(o) || mp_obj_is_type(o, &mp_type_int))
 #define mp_obj_is_str(o) (mp_obj_is_qstr(o) || mp_obj_is_type(o, &mp_type_str))
-#define mp_obj_is_str_or_bytes(o) (mp_obj_is_qstr(o) || (mp_obj_is_obj(o) && ((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type->binary_op == mp_obj_str_binary_op))
-#define mp_obj_is_fun(o) (mp_obj_is_obj(o) && (((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type->name == MP_QSTR_function))
+#define mp_obj_is_str_or_bytes(o) (mp_obj_is_qstr(o) || (mp_obj_is_obj(o) && ((mp_obj_base_t *)MP_OBJ_TO_PTR(o))->type->binary_op == mp_obj_str_binary_op))
+#define mp_obj_is_fun(o) (mp_obj_is_obj(o) && (((mp_obj_base_t *)MP_OBJ_TO_PTR(o))->type->name == MP_QSTR_function))
 
 mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict);
-static inline mp_obj_t mp_obj_new_bool(mp_int_t x) { return x ? mp_const_true : mp_const_false; }
+static inline mp_obj_t mp_obj_new_bool(mp_int_t x) {
+    return x ? mp_const_true : mp_const_false;
+}
 mp_obj_t mp_obj_new_cell(mp_obj_t obj);
 mp_obj_t mp_obj_new_int(mp_int_t value);
 mp_obj_t mp_obj_new_int_from_uint(mp_uint_t value);
 mp_obj_t mp_obj_new_int_from_str_len(const char **str, size_t len, bool neg, unsigned int base);
 mp_obj_t mp_obj_new_int_from_ll(long long val); // this must return a multi-precision integer object (or raise an overflow exception)
 mp_obj_t mp_obj_new_int_from_ull(unsigned long long val); // this must return a multi-precision integer object (or raise an overflow exception)
-mp_obj_t mp_obj_new_str(const char* data, size_t len);
-mp_obj_t mp_obj_new_str_via_qstr(const char* data, size_t len);
+mp_obj_t mp_obj_new_str(const char *data, size_t len);
+mp_obj_t mp_obj_new_str_via_qstr(const char *data, size_t len);
 mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr);
-mp_obj_t mp_obj_new_bytes(const byte* data, size_t len);
+mp_obj_t mp_obj_new_bytes(const byte *data, size_t len);
 mp_obj_t mp_obj_new_bytearray(size_t n, void *items);
 mp_obj_t mp_obj_new_bytearray_by_ref(size_t n, void *items);
 #if MICROPY_PY_BUILTINS_FLOAT
@@ -739,7 +765,9 @@
 mp_obj_t mp_obj_equal_not_equal(mp_binary_op_t op, mp_obj_t o1, mp_obj_t o2);
 bool mp_obj_equal(mp_obj_t o1, mp_obj_t o2);
 
-static inline bool mp_obj_is_integer(mp_const_obj_t o) { return mp_obj_is_int(o) || mp_obj_is_bool(o); } // returns true if o is bool, small int or long int
+static inline bool mp_obj_is_integer(mp_const_obj_t o) {
+    return mp_obj_is_int(o) || mp_obj_is_bool(o);
+}                                                                                                        // returns true if o is bool, small int or long int
 mp_int_t mp_obj_get_int(mp_const_obj_t arg);
 mp_int_t mp_obj_get_int_truncated(mp_const_obj_t arg);
 bool mp_obj_get_int_maybe(mp_const_obj_t arg, mp_int_t *value);
@@ -796,7 +824,9 @@
 #if MICROPY_FLOAT_HIGH_QUALITY_HASH
 mp_int_t mp_float_hash(mp_float_t val);
 #else
-static inline mp_int_t mp_float_hash(mp_float_t val) { return (mp_int_t)val; }
+static inline mp_int_t mp_float_hash(mp_float_t val) {
+    return (mp_int_t)val;
+}
 #endif
 mp_obj_t mp_obj_float_binary_op(mp_binary_op_t op, mp_float_t lhs_val, mp_obj_t rhs); // can return MP_OBJ_NULL if op not supported
 
@@ -831,7 +861,7 @@
 mp_obj_t mp_obj_dict_store(mp_obj_t self_in, mp_obj_t key, mp_obj_t value);
 mp_obj_t mp_obj_dict_delete(mp_obj_t self_in, mp_obj_t key);
 static inline mp_map_t *mp_obj_dict_get_map(mp_obj_t dict) {
-    return &((mp_obj_dict_t*)MP_OBJ_TO_PTR(dict))->map;
+    return &((mp_obj_dict_t *)MP_OBJ_TO_PTR(dict))->map;
 }
 
 // set
@@ -887,7 +917,7 @@
     mp_obj_dict_t *globals;
 } mp_obj_module_t;
 static inline mp_obj_dict_t *mp_obj_module_get_globals(mp_obj_t module) {
-    return ((mp_obj_module_t*)MP_OBJ_TO_PTR(module))->globals;
+    return ((mp_obj_module_t *)MP_OBJ_TO_PTR(module))->globals;
 }
 // check if given module object is a package
 bool mp_obj_is_package(mp_obj_t module);
@@ -920,18 +950,18 @@
 mp_obj_t mp_seq_count_obj(const mp_obj_t *items, size_t len, mp_obj_t value);
 mp_obj_t mp_seq_extract_slice(size_t len, const mp_obj_t *seq, mp_bound_slice_t *indexes);
 // Helper to clear stale pointers from allocated, but unused memory, to preclude GC problems
-#define mp_seq_clear(start, len, alloc_len, item_sz) memset((byte*)(start) + (len) * (item_sz), 0, ((alloc_len) - (len)) * (item_sz))
+#define mp_seq_clear(start, len, alloc_len, item_sz) memset((byte *)(start) + (len) * (item_sz), 0, ((alloc_len) - (len)) * (item_sz))
 #define mp_seq_replace_slice_no_grow(dest, dest_len, beg, end, slice, slice_len, item_sz) \
     /*printf("memcpy(%p, %p, %d)\n", dest + beg, slice, slice_len * (item_sz));*/ \
-    memcpy(((char*)dest) + (beg) * (item_sz), slice, slice_len * (item_sz)); \
+    memcpy(((char *)dest) + (beg) * (item_sz), slice, slice_len * (item_sz)); \
     /*printf("memmove(%p, %p, %d)\n", dest + (beg + slice_len), dest + end, (dest_len - end) * (item_sz));*/ \
-    memmove(((char*)dest) + (beg + slice_len) * (item_sz), ((char*)dest) + (end) * (item_sz), (dest_len - end) * (item_sz));
+    memmove(((char *)dest) + (beg + slice_len) * (item_sz), ((char *)dest) + (end) * (item_sz), (dest_len - end) * (item_sz));
 
 // Note: dest and slice regions may overlap
 #define mp_seq_replace_slice_grow_inplace(dest, dest_len, beg, end, slice, slice_len, len_adj, item_sz) \
     /*printf("memmove(%p, %p, %d)\n", dest + beg + len_adj, dest + beg, (dest_len - beg) * (item_sz));*/ \
-    memmove(((char*)dest) + (beg + slice_len) * (item_sz), ((char*)dest) + (end) * (item_sz), ((dest_len) + (len_adj) - ((beg) + (slice_len))) * (item_sz)); \
-    memmove(((char*)dest) + (beg) * (item_sz), slice, slice_len * (item_sz));
+    memmove(((char *)dest) + (beg + slice_len) * (item_sz), ((char *)dest) + (end) * (item_sz), ((dest_len) + (len_adj) - ((beg) + (slice_len))) * (item_sz)); \
+    memmove(((char *)dest) + (beg) * (item_sz), slice, slice_len * (item_sz));
 
 // Provide translation for legacy API
 #define MP_OBJ_IS_SMALL_INT mp_obj_is_small_int
diff --git a/py/objarray.c b/py/objarray.c
index 760eff8..7f5cbf0 100644
--- a/py/objarray.c
+++ b/py/objarray.c
@@ -117,10 +117,10 @@
     // other arrays can only be raw-initialised from bytes and bytearray objects
     mp_buffer_info_t bufinfo;
     if (((MICROPY_PY_BUILTINS_BYTEARRAY
-            && typecode == BYTEARRAY_TYPECODE)
-        || (MICROPY_PY_ARRAY
-            && (mp_obj_is_type(initializer, &mp_type_bytes)
-                || (MICROPY_PY_BUILTINS_BYTEARRAY && mp_obj_is_type(initializer, &mp_type_bytearray)))))
+          && typecode == BYTEARRAY_TYPECODE)
+         || (MICROPY_PY_ARRAY
+             && (mp_obj_is_type(initializer, &mp_type_bytes)
+                 || (MICROPY_PY_BUILTINS_BYTEARRAY && mp_obj_is_type(initializer, &mp_type_bytearray)))))
         && mp_get_buffer(initializer, &bufinfo, MP_BUFFER_READ)) {
         // construct array from raw bytes
         // we round-down the len to make it a multiple of sz (CPython raises error)
@@ -249,9 +249,12 @@
 STATIC mp_obj_t array_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
     mp_obj_array_t *o = MP_OBJ_TO_PTR(o_in);
     switch (op) {
-        case MP_UNARY_OP_BOOL: return mp_obj_new_bool(o->len != 0);
-        case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(o->len);
-        default: return MP_OBJ_NULL; // op not supported
+        case MP_UNARY_OP_BOOL:
+            return mp_obj_new_bool(o->len != 0);
+        case MP_UNARY_OP_LEN:
+            return MP_OBJ_NEW_SMALL_INT(o->len);
+        default:
+            return MP_OBJ_NULL;      // op not supported
     }
 }
 
@@ -272,7 +275,7 @@
 
             // note: lhs->len is element count of lhs, lhs_bufinfo.len is byte count
             mp_obj_array_t *res = array_new(lhs_bufinfo.typecode, lhs->len + rhs_len);
-            mp_seq_cat((byte*)res->items, lhs_bufinfo.buf, lhs_bufinfo.len, rhs_bufinfo.buf, rhs_len * sz, byte);
+            mp_seq_cat((byte *)res->items, lhs_bufinfo.buf, lhs_bufinfo.len, rhs_bufinfo.buf, rhs_len * sz, byte);
             return MP_OBJ_FROM_PTR(res);
         }
 
@@ -371,7 +374,7 @@
     }
 
     // extend
-    mp_seq_copy((byte*)self->items + self->len * sz, arg_bufinfo.buf, len * sz, byte);
+    mp_seq_copy((byte *)self->items + self->len * sz, arg_bufinfo.buf, len * sz, byte);
     self->len += len;
 
     return mp_const_none;
@@ -388,7 +391,7 @@
         return MP_OBJ_NULL; // op not supported
     } else {
         mp_obj_array_t *o = MP_OBJ_TO_PTR(self_in);
-#if MICROPY_PY_BUILTINS_SLICE
+        #if MICROPY_PY_BUILTINS_SLICE
         if (mp_obj_is_type(index_in, &mp_type_slice)) {
             mp_bound_slice_t slice;
             if (!mp_seq_get_fast_slice_indexes(o->len, index_in, &slice)) {
@@ -400,7 +403,7 @@
                 size_t src_len;
                 void *src_items;
                 size_t item_sz = mp_binary_get_size('@', o->typecode & TYPECODE_MASK, NULL);
-                if (mp_obj_is_obj(value) && ((mp_obj_base_t*)MP_OBJ_TO_PTR(value))->type->subscr == array_subscr) {
+                if (mp_obj_is_obj(value) && ((mp_obj_base_t *)MP_OBJ_TO_PTR(value))->type->subscr == array_subscr) {
                     // value is array, bytearray or memoryview
                     mp_obj_array_t *src_slice = MP_OBJ_TO_PTR(value);
                     if (item_sz != mp_binary_get_size('@', src_slice->typecode & TYPECODE_MASK, NULL)) {
@@ -411,7 +414,7 @@
                     src_items = src_slice->items;
                     #if MICROPY_PY_BUILTINS_MEMORYVIEW
                     if (mp_obj_is_type(value, &mp_type_memoryview)) {
-                        src_items = (uint8_t*)src_items + (src_slice->memview_offset * item_sz);
+                        src_items = (uint8_t *)src_items + (src_slice->memview_offset * item_sz);
                     }
                     #endif
                 } else if (mp_obj_is_type(value, &mp_type_bytes)) {
@@ -428,7 +431,7 @@
 
                 // TODO: check src/dst compat
                 mp_int_t len_adj = src_len - (slice.stop - slice.start);
-                uint8_t* dest_items = o->items;
+                uint8_t *dest_items = o->items;
                 #if MICROPY_PY_BUILTINS_MEMORYVIEW
                 if (o->base.type == &mp_type_memoryview) {
                     if (!(o->typecode & MP_OBJ_ARRAY_TYPECODE_FLAG_RW)) {
@@ -479,11 +482,11 @@
             #endif
             {
                 res = array_new(o->typecode, slice.stop - slice.start);
-                memcpy(res->items, (uint8_t*)o->items + slice.start * sz, (slice.stop - slice.start) * sz);
+                memcpy(res->items, (uint8_t *)o->items + slice.start * sz, (slice.stop - slice.start) * sz);
             }
             return MP_OBJ_FROM_PTR(res);
         } else
-#endif
+        #endif
         {
             size_t index = mp_get_index(o->base.type, o->len, index_in, false);
             #if MICROPY_PY_BUILTINS_MEMORYVIEW
@@ -519,7 +522,7 @@
             // read-only memoryview
             return 1;
         }
-        bufinfo->buf = (uint8_t*)bufinfo->buf + (size_t)o->memview_offset * sz;
+        bufinfo->buf = (uint8_t *)bufinfo->buf + (size_t)o->memview_offset * sz;
     }
     #else
     (void)flags;
@@ -550,7 +553,7 @@
     .binary_op = array_binary_op,
     .subscr = array_subscr,
     .buffer_p = { .get_buffer = array_get_buffer },
-    .locals_dict = (mp_obj_dict_t*)&array_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&array_locals_dict,
 };
 #endif
 
@@ -566,7 +569,7 @@
     .binary_op = array_binary_op,
     .subscr = array_subscr,
     .buffer_p = { .get_buffer = array_get_buffer },
-    .locals_dict = (mp_obj_dict_t*)&array_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&array_locals_dict,
 };
 #endif
 
@@ -641,7 +644,7 @@
 STATIC mp_obj_t array_iterator_new(mp_obj_t array_in, mp_obj_iter_buf_t *iter_buf) {
     assert(sizeof(mp_obj_array_t) <= sizeof(mp_obj_iter_buf_t));
     mp_obj_array_t *array = MP_OBJ_TO_PTR(array_in);
-    mp_obj_array_it_t *o = (mp_obj_array_it_t*)iter_buf;
+    mp_obj_array_it_t *o = (mp_obj_array_it_t *)iter_buf;
     o->base.type = &array_it_type;
     o->array = array;
     o->offset = 0;
diff --git a/py/objattrtuple.c b/py/objattrtuple.c
index 3cc298d..3422d01 100644
--- a/py/objattrtuple.c
+++ b/py/objattrtuple.c
@@ -51,7 +51,7 @@
 STATIC void mp_obj_attrtuple_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) {
     (void)kind;
     mp_obj_tuple_t *o = MP_OBJ_TO_PTR(o_in);
-    const qstr *fields = (const qstr*)MP_OBJ_TO_PTR(o->items[o->len]);
+    const qstr *fields = (const qstr *)MP_OBJ_TO_PTR(o->items[o->len]);
     mp_obj_attrtuple_print_helper(print, fields, o);
 }
 
@@ -60,7 +60,7 @@
         // load attribute
         mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in);
         size_t len = self->len;
-        const qstr *fields = (const qstr*)MP_OBJ_TO_PTR(self->items[len]);
+        const qstr *fields = (const qstr *)MP_OBJ_TO_PTR(self->items[len]);
         for (size_t i = 0; i < len; i++) {
             if (fields[i] == attr) {
                 dest[0] = self->items[i];
diff --git a/py/objbool.c b/py/objbool.c
index 1183a7e..23e023d 100644
--- a/py/objbool.c
+++ b/py/objbool.c
@@ -34,7 +34,7 @@
 
 #else
 
-#define BOOL_VALUE(o) (((mp_obj_bool_t*)MP_OBJ_TO_PTR(o))->value)
+#define BOOL_VALUE(o) (((mp_obj_bool_t *)MP_OBJ_TO_PTR(o))->value)
 
 typedef struct _mp_obj_bool_t {
     mp_obj_base_t base;
diff --git a/py/objboundmeth.c b/py/objboundmeth.c
index 8fc44f1..a3e1d30 100644
--- a/py/objboundmeth.c
+++ b/py/objboundmeth.c
@@ -98,13 +98,13 @@
 STATIC const mp_obj_type_t mp_type_bound_meth = {
     { &mp_type_type },
     .name = MP_QSTR_bound_method,
-#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED
+    #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED
     .print = bound_meth_print,
-#endif
+    #endif
     .call = bound_meth_call,
-#if MICROPY_PY_FUNCTION_ATTRS
+    #if MICROPY_PY_FUNCTION_ATTRS
     .attr = bound_meth_attr,
-#endif
+    #endif
 };
 
 mp_obj_t mp_obj_new_bound_meth(mp_obj_t meth, mp_obj_t self) {
diff --git a/py/objcell.c b/py/objcell.c
index 1119064..be2ae8c 100644
--- a/py/objcell.c
+++ b/py/objcell.c
@@ -58,9 +58,9 @@
 STATIC const mp_obj_type_t mp_type_cell = {
     { &mp_type_type },
     .name = MP_QSTR_, // cell representation is just value in < >
-#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED
+    #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED
     .print = cell_print,
-#endif
+    #endif
 };
 
 mp_obj_t mp_obj_new_cell(mp_obj_t obj) {
diff --git a/py/objclosure.c b/py/objclosure.c
index 4eb9eb8..f5038ff 100644
--- a/py/objclosure.c
+++ b/py/objclosure.c
@@ -81,9 +81,9 @@
 const mp_obj_type_t closure_type = {
     { &mp_type_type },
     .name = MP_QSTR_closure,
-#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED
+    #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED
     .print = closure_print,
-#endif
+    #endif
     .call = closure_call,
 };
 
diff --git a/py/objcomplex.c b/py/objcomplex.c
index 2031c1c..b7af1b1 100644
--- a/py/objcomplex.c
+++ b/py/objcomplex.c
@@ -45,17 +45,17 @@
 STATIC void complex_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) {
     (void)kind;
     mp_obj_complex_t *o = MP_OBJ_TO_PTR(o_in);
-#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
+    #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
     char buf[16];
     #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C
     const int precision = 6;
     #else
     const int precision = 7;
     #endif
-#else
+    #else
     char buf[32];
     const int precision = 16;
-#endif
+    #endif
     if (o->real == 0) {
         mp_format_float(o->imag, buf, sizeof(buf), 'g', precision, '\0');
         mp_printf(print, "%sj", buf);
@@ -117,13 +117,18 @@
 STATIC mp_obj_t complex_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
     mp_obj_complex_t *o = MP_OBJ_TO_PTR(o_in);
     switch (op) {
-        case MP_UNARY_OP_BOOL: return mp_obj_new_bool(o->real != 0 || o->imag != 0);
-        case MP_UNARY_OP_HASH: return MP_OBJ_NEW_SMALL_INT(mp_float_hash(o->real) ^ mp_float_hash(o->imag));
-        case MP_UNARY_OP_POSITIVE: return o_in;
-        case MP_UNARY_OP_NEGATIVE: return mp_obj_new_complex(-o->real, -o->imag);
+        case MP_UNARY_OP_BOOL:
+            return mp_obj_new_bool(o->real != 0 || o->imag != 0);
+        case MP_UNARY_OP_HASH:
+            return MP_OBJ_NEW_SMALL_INT(mp_float_hash(o->real) ^ mp_float_hash(o->imag));
+        case MP_UNARY_OP_POSITIVE:
+            return o_in;
+        case MP_UNARY_OP_NEGATIVE:
+            return mp_obj_new_complex(-o->real, -o->imag);
         case MP_UNARY_OP_ABS:
-            return mp_obj_new_float(MICROPY_FLOAT_C_FUN(sqrt)(o->real*o->real + o->imag*o->imag));
-        default: return MP_OBJ_NULL; // op not supported
+            return mp_obj_new_float(MICROPY_FLOAT_C_FUN(sqrt)(o->real * o->real + o->imag * o->imag));
+        default:
+            return MP_OBJ_NULL;      // op not supported
     }
 }
 
@@ -188,7 +193,7 @@
         case MP_BINARY_OP_MULTIPLY:
         case MP_BINARY_OP_INPLACE_MULTIPLY: {
             mp_float_t real;
-            multiply:
+        multiply:
             real = lhs_real * rhs_real - lhs_imag * rhs_imag;
             lhs_imag = lhs_real * rhs_imag + lhs_imag * rhs_real;
             lhs_real = real;
@@ -211,7 +216,7 @@
                 lhs_imag = -lhs_real / rhs_imag;
                 lhs_real = real;
             } else {
-                mp_float_t rhs_len_sq = rhs_real*rhs_real + rhs_imag*rhs_imag;
+                mp_float_t rhs_len_sq = rhs_real * rhs_real + rhs_imag * rhs_imag;
                 rhs_real /= rhs_len_sq;
                 rhs_imag /= -rhs_len_sq;
                 goto multiply;
@@ -225,7 +230,7 @@
             //        = exp( (x2*ln1 - y2*arg1) + i*(y2*ln1 + x2*arg1) )
             //        = exp(x3 + i*y3)
             //        = exp(x3)*(cos(y3) + i*sin(y3))
-            mp_float_t abs1 = MICROPY_FLOAT_C_FUN(sqrt)(lhs_real*lhs_real + lhs_imag*lhs_imag);
+            mp_float_t abs1 = MICROPY_FLOAT_C_FUN(sqrt)(lhs_real * lhs_real + lhs_imag * lhs_imag);
             if (abs1 == 0) {
                 if (rhs_imag == 0 && rhs_real >= 0) {
                     lhs_real = (rhs_real == 0);
@@ -244,7 +249,8 @@
             break;
         }
 
-        case MP_BINARY_OP_EQUAL: return mp_obj_new_bool(lhs_real == rhs_real && lhs_imag == rhs_imag);
+        case MP_BINARY_OP_EQUAL:
+            return mp_obj_new_bool(lhs_real == rhs_real && lhs_imag == rhs_imag);
 
         default:
             return MP_OBJ_NULL; // op not supported
diff --git a/py/objdeque.c b/py/objdeque.c
index 1cff1f8..0eb6665 100644
--- a/py/objdeque.c
+++ b/py/objdeque.c
@@ -161,7 +161,7 @@
     .name = MP_QSTR_deque,
     .make_new = deque_make_new,
     .unary_op = deque_unary_op,
-    .locals_dict = (mp_obj_dict_t*)&deque_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&deque_locals_dict,
 };
 
 #endif // MICROPY_PY_COLLECTIONS_DEQUE
diff --git a/py/objdict.c b/py/objdict.c
index f831a04..5447826 100644
--- a/py/objdict.c
+++ b/py/objdict.c
@@ -33,7 +33,7 @@
 #include "py/objtype.h"
 #include "py/objstr.h"
 
-#define mp_obj_is_dict_type(o) (mp_obj_is_obj(o) && ((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type->make_new == dict_make_new)
+#define mp_obj_is_dict_type(o) (mp_obj_is_obj(o) && ((mp_obj_base_t *)MP_OBJ_TO_PTR(o))->type->make_new == dict_make_new)
 
 STATIC mp_obj_t dict_update(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs);
 
@@ -109,15 +109,18 @@
 STATIC mp_obj_t dict_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
     mp_obj_dict_t *self = MP_OBJ_TO_PTR(self_in);
     switch (op) {
-        case MP_UNARY_OP_BOOL: return mp_obj_new_bool(self->map.used != 0);
-        case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(self->map.used);
+        case MP_UNARY_OP_BOOL:
+            return mp_obj_new_bool(self->map.used != 0);
+        case MP_UNARY_OP_LEN:
+            return MP_OBJ_NEW_SMALL_INT(self->map.used);
         #if MICROPY_PY_SYS_GETSIZEOF
         case MP_UNARY_OP_SIZEOF: {
             size_t sz = sizeof(*self) + sizeof(*self->map.table) * self->map.alloc;
             return MP_OBJ_NEW_SMALL_INT(sz);
         }
         #endif
-        default: return MP_OBJ_NULL; // op not supported
+        default:
+            return MP_OBJ_NULL;      // op not supported
     }
 }
 
@@ -348,7 +351,7 @@
             if (args[1] != args[0]) {
                 size_t cur = 0;
                 mp_map_elem_t *elem = NULL;
-                while ((elem = dict_iter_next((mp_obj_dict_t*)MP_OBJ_TO_PTR(args[1]), &cur)) != NULL) {
+                while ((elem = dict_iter_next((mp_obj_dict_t *)MP_OBJ_TO_PTR(args[1]), &cur)) != NULL) {
                     mp_map_lookup(&self->map, elem->key, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND)->value = elem->value;
                 }
             }
@@ -444,7 +447,7 @@
     assert(sizeof(mp_obj_dict_view_it_t) <= sizeof(mp_obj_iter_buf_t));
     mp_check_self(mp_obj_is_type(view_in, &dict_view_type));
     mp_obj_dict_view_t *view = MP_OBJ_TO_PTR(view_in);
-    mp_obj_dict_view_it_t *o = (mp_obj_dict_view_it_t*)iter_buf;
+    mp_obj_dict_view_it_t *o = (mp_obj_dict_view_it_t *)iter_buf;
     o->base.type = &dict_view_it_type;
     o->kind = view->kind;
     o->dict = view->dict;
@@ -526,7 +529,7 @@
 STATIC mp_obj_t dict_getiter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf) {
     assert(sizeof(mp_obj_dict_view_it_t) <= sizeof(mp_obj_iter_buf_t));
     mp_check_self(mp_obj_is_dict_type(self_in));
-    mp_obj_dict_view_it_t *o = (mp_obj_dict_view_it_t*)iter_buf;
+    mp_obj_dict_view_it_t *o = (mp_obj_dict_view_it_t *)iter_buf;
     o->base.type = &dict_view_it_type;
     o->kind = MP_DICT_VIEW_KEYS;
     o->dict = self_in;
@@ -567,7 +570,7 @@
     .binary_op = dict_binary_op,
     .subscr = dict_subscr,
     .getiter = dict_getiter,
-    .locals_dict = (mp_obj_dict_t*)&dict_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&dict_locals_dict,
 };
 
 #if MICROPY_PY_COLLECTIONS_ORDEREDDICT
@@ -581,7 +584,7 @@
     .subscr = dict_subscr,
     .getiter = dict_getiter,
     .parent = &mp_type_dict,
-    .locals_dict = (mp_obj_dict_t*)&dict_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&dict_locals_dict,
 };
 #endif
 
diff --git a/py/objenumerate.c b/py/objenumerate.c
index 243c9f8..d1de4ad 100644
--- a/py/objenumerate.c
+++ b/py/objenumerate.c
@@ -40,7 +40,7 @@
 STATIC mp_obj_t enumerate_iternext(mp_obj_t self_in);
 
 STATIC mp_obj_t enumerate_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
-#if MICROPY_CPYTHON_COMPAT
+    #if MICROPY_CPYTHON_COMPAT
     static const mp_arg_t allowed_args[] = {
         { MP_QSTR_iterable, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
         { MP_QSTR_start, MP_ARG_INT, {.u_int = 0} },
@@ -51,20 +51,20 @@
         mp_arg_val_t iterable, start;
     } arg_vals;
     mp_arg_parse_all_kw_array(n_args, n_kw, args,
-        MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&arg_vals);
+        MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&arg_vals);
 
     // create enumerate object
     mp_obj_enumerate_t *o = m_new_obj(mp_obj_enumerate_t);
     o->base.type = type;
     o->iter = mp_getiter(arg_vals.iterable.u_obj, NULL);
     o->cur = arg_vals.start.u_int;
-#else
+    #else
     mp_arg_check_num(n_args, n_kw, 1, 2, false);
     mp_obj_enumerate_t *o = m_new_obj(mp_obj_enumerate_t);
     o->base.type = type;
     o->iter = mp_getiter(args[0], NULL);
     o->cur = n_args > 1 ? mp_obj_get_int(args[1]) : 0;
-#endif
+    #endif
 
     return MP_OBJ_FROM_PTR(o);
 }
diff --git a/py/objexcept.c b/py/objexcept.c
index b5c1693..ef99019 100644
--- a/py/objexcept.c
+++ b/py/objexcept.c
@@ -58,7 +58,7 @@
 #define EMG_BUF_TUPLE_SIZE(n_args)  (sizeof(mp_obj_tuple_t) + n_args * sizeof(mp_obj_t))
 #define EMG_BUF_STR_OFFSET          (EMG_BUF_TUPLE_OFFSET + EMG_BUF_TUPLE_SIZE(1))
 
-#   if MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE > 0
+#if MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE > 0
 #define mp_emergency_exception_buf_size MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE
 
 void mp_init_emergency_exception_buf(void) {
@@ -150,7 +150,7 @@
     mp_obj_tuple_t *o_tuple;
     if (n_args == 0) {
         // No args, can use the empty tuple straightaway
-        o_tuple = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj;
+        o_tuple = (mp_obj_tuple_t *)&mp_const_empty_tuple_obj;
     } else {
         // Try to allocate memory for the tuple containing the args
         o_tuple = m_new_obj_var_maybe(mp_obj_tuple_t, mp_obj_t, n_args);
@@ -161,14 +161,14 @@
         // Otherwise we are free to use the whole buffer after the traceback data.
         if (o_tuple == NULL && mp_emergency_exception_buf_size >=
             EMG_BUF_TUPLE_OFFSET + EMG_BUF_TUPLE_SIZE(n_args)) {
-            o_tuple = (mp_obj_tuple_t*)
-                ((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf) + EMG_BUF_TUPLE_OFFSET);
+            o_tuple = (mp_obj_tuple_t *)
+                ((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + EMG_BUF_TUPLE_OFFSET);
         }
         #endif
 
         if (o_tuple == NULL) {
             // No memory for a tuple, fallback to an empty tuple
-            o_tuple = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj;
+            o_tuple = (mp_obj_tuple_t *)&mp_const_empty_tuple_obj;
         } else {
             // Have memory for a tuple so populate it
             o_tuple->base.type = &mp_type_tuple;
@@ -336,7 +336,7 @@
     // traceback and 1-tuple.
     if (o_str == NULL
         && mp_emergency_exception_buf_size >= EMG_BUF_STR_OFFSET + sizeof(mp_obj_str_t)) {
-        o_str = (mp_obj_str_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
+        o_str = (mp_obj_str_t *)((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf)
             + EMG_BUF_STR_OFFSET);
     }
     #endif
@@ -349,7 +349,7 @@
     // Create the string object and call mp_obj_exception_make_new to create the exception
     o_str->base.type = &mp_type_str;
     o_str->len = strlen(msg);
-    o_str->data = (const byte*)msg;
+    o_str->data = (const byte *)msg;
     o_str->hash = qstr_compute_hash(o_str->data, o_str->len);
     mp_obj_t arg = MP_OBJ_FROM_PTR(o_str);
     return mp_obj_exception_make_new(exc_type, 1, 0, &arg);
@@ -415,10 +415,10 @@
     if ((o_str == NULL || o_str_buf == NULL)
         && mp_emergency_exception_buf_size >= EMG_BUF_STR_OFFSET + sizeof(mp_obj_str_t) + 16) {
         used_emg_buf = true;
-        o_str = (mp_obj_str_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
+        o_str = (mp_obj_str_t *)((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf)
             + EMG_BUF_STR_OFFSET);
-        o_str_buf = (byte*)&o_str[1];
-        o_str_alloc = (uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
+        o_str_buf = (byte *)&o_str[1];
+        o_str_alloc = (uint8_t *)MP_STATE_VM(mp_emergency_exception_buf)
             + mp_emergency_exception_buf_size - o_str_buf;
     }
     #endif
@@ -432,7 +432,7 @@
         // No memory for the string buffer: assume that the fmt string is in ROM
         // and use that data as the data of the string
         o_str->len = o_str_alloc - 1; // will be equal to strlen(fmt)
-        o_str->data = (const byte*)fmt;
+        o_str->data = (const byte *)fmt;
     } else {
         // We have some memory to format the string
         struct _exc_printer_t exc_pr = {!used_emg_buf, o_str_alloc, 0, o_str_buf};
@@ -487,7 +487,7 @@
     if (mp_obj_is_native_exception_instance(self_in)) { \
         self = MP_OBJ_TO_PTR(self_in); \
     } else { \
-        self = MP_OBJ_TO_PTR(((mp_obj_instance_t*)MP_OBJ_TO_PTR(self_in))->subobj[0]); \
+        self = MP_OBJ_TO_PTR(((mp_obj_instance_t *)MP_OBJ_TO_PTR(self_in))->subobj[0]); \
     }
 
 void mp_obj_exception_clear_traceback(mp_obj_t self_in) {
@@ -509,7 +509,7 @@
             #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
             if (mp_emergency_exception_buf_size >= EMG_BUF_TRACEBACK_OFFSET + EMG_BUF_TRACEBACK_SIZE) {
                 // There is room in the emergency buffer for traceback data
-                size_t *tb = (size_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
+                size_t *tb = (size_t *)((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf)
                     + EMG_BUF_TRACEBACK_OFFSET);
                 self->traceback_data = tb;
                 self->traceback_alloc = EMG_BUF_TRACEBACK_SIZE / sizeof(size_t);
@@ -528,7 +528,7 @@
         self->traceback_len = 0;
     } else if (self->traceback_len + TRACEBACK_ENTRY_LEN > self->traceback_alloc) {
         #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
-        if (self->traceback_data == (size_t*)MP_STATE_VM(mp_emergency_exception_buf)) {
+        if (self->traceback_data == (size_t *)MP_STATE_VM(mp_emergency_exception_buf)) {
             // Can't resize the emergency buffer
             return;
         }
diff --git a/py/objexcept.h b/py/objexcept.h
index 7c30762..384456b 100644
--- a/py/objexcept.h
+++ b/py/objexcept.h
@@ -41,13 +41,13 @@
 void mp_obj_exception_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest);
 
 #define MP_DEFINE_EXCEPTION(exc_name, base_name) \
-const mp_obj_type_t mp_type_ ## exc_name = { \
-    { &mp_type_type }, \
-    .name = MP_QSTR_ ## exc_name, \
-    .print = mp_obj_exception_print, \
-    .make_new = mp_obj_exception_make_new, \
-    .attr = mp_obj_exception_attr, \
-    .parent = &mp_type_ ## base_name, \
-};
+    const mp_obj_type_t mp_type_##exc_name = { \
+        { &mp_type_type }, \
+        .name = MP_QSTR_##exc_name, \
+        .print = mp_obj_exception_print, \
+        .make_new = mp_obj_exception_make_new, \
+        .attr = mp_obj_exception_attr, \
+        .parent = &mp_type_##base_name, \
+    };
 
 #endif // MICROPY_INCLUDED_PY_OBJEXCEPT_H
diff --git a/py/objfloat.c b/py/objfloat.c
index 0554307..40619d7 100644
--- a/py/objfloat.c
+++ b/py/objfloat.c
@@ -95,17 +95,17 @@
 STATIC void float_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) {
     (void)kind;
     mp_float_t o_val = mp_obj_float_get(o_in);
-#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
+    #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
     char buf[16];
     #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C
     const int precision = 6;
     #else
     const int precision = 7;
     #endif
-#else
+    #else
     char buf[32];
     const int precision = 16;
-#endif
+    #endif
     mp_format_float(o_val, buf, sizeof(buf), 'g', precision, '\0');
     mp_print_str(print, buf);
     if (strchr(buf, '.') == NULL && strchr(buf, 'e') == NULL && strchr(buf, 'n') == NULL) {
@@ -142,10 +142,14 @@
 STATIC mp_obj_t float_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
     mp_float_t val = mp_obj_float_get(o_in);
     switch (op) {
-        case MP_UNARY_OP_BOOL: return mp_obj_new_bool(val != 0);
-        case MP_UNARY_OP_HASH: return MP_OBJ_NEW_SMALL_INT(mp_float_hash(val));
-        case MP_UNARY_OP_POSITIVE: return o_in;
-        case MP_UNARY_OP_NEGATIVE: return mp_obj_new_float(-val);
+        case MP_UNARY_OP_BOOL:
+            return mp_obj_new_bool(val != 0);
+        case MP_UNARY_OP_HASH:
+            return MP_OBJ_NEW_SMALL_INT(mp_float_hash(val));
+        case MP_UNARY_OP_POSITIVE:
+            return o_in;
+        case MP_UNARY_OP_NEGATIVE:
+            return mp_obj_new_float(-val);
         case MP_UNARY_OP_ABS: {
             if (signbit(val)) {
                 return mp_obj_new_float(-val);
@@ -153,7 +157,8 @@
                 return o_in;
             }
         }
-        default: return MP_OBJ_NULL; // op not supported
+        default:
+            return MP_OBJ_NULL;      // op not supported
     }
 }
 
@@ -237,15 +242,21 @@
 
     switch (op) {
         case MP_BINARY_OP_ADD:
-        case MP_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break;
+        case MP_BINARY_OP_INPLACE_ADD:
+            lhs_val += rhs_val;
+            break;
         case MP_BINARY_OP_SUBTRACT:
-        case MP_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break;
+        case MP_BINARY_OP_INPLACE_SUBTRACT:
+            lhs_val -= rhs_val;
+            break;
         case MP_BINARY_OP_MULTIPLY:
-        case MP_BINARY_OP_INPLACE_MULTIPLY: lhs_val *= rhs_val; break;
+        case MP_BINARY_OP_INPLACE_MULTIPLY:
+            lhs_val *= rhs_val;
+            break;
         case MP_BINARY_OP_FLOOR_DIVIDE:
         case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE:
             if (rhs_val == 0) {
-                zero_division_error:
+            zero_division_error:
                 mp_raise_msg(&mp_type_ZeroDivisionError, "divide by zero");
             }
             // Python specs require that x == (x//y)*y + (x%y) so we must
@@ -300,11 +311,16 @@
             };
             return mp_obj_new_tuple(2, tuple);
         }
-        case MP_BINARY_OP_LESS: return mp_obj_new_bool(lhs_val < rhs_val);
-        case MP_BINARY_OP_MORE: return mp_obj_new_bool(lhs_val > rhs_val);
-        case MP_BINARY_OP_EQUAL: return mp_obj_new_bool(lhs_val == rhs_val);
-        case MP_BINARY_OP_LESS_EQUAL: return mp_obj_new_bool(lhs_val <= rhs_val);
-        case MP_BINARY_OP_MORE_EQUAL: return mp_obj_new_bool(lhs_val >= rhs_val);
+        case MP_BINARY_OP_LESS:
+            return mp_obj_new_bool(lhs_val < rhs_val);
+        case MP_BINARY_OP_MORE:
+            return mp_obj_new_bool(lhs_val > rhs_val);
+        case MP_BINARY_OP_EQUAL:
+            return mp_obj_new_bool(lhs_val == rhs_val);
+        case MP_BINARY_OP_LESS_EQUAL:
+            return mp_obj_new_bool(lhs_val <= rhs_val);
+        case MP_BINARY_OP_MORE_EQUAL:
+            return mp_obj_new_bool(lhs_val >= rhs_val);
 
         default:
             return MP_OBJ_NULL; // op not supported
diff --git a/py/objfun.c b/py/objfun.c
index dbff2fa..1afb0f8 100644
--- a/py/objfun.c
+++ b/py/objfun.c
@@ -197,8 +197,8 @@
         MP_BC_PRELUDE_SIG_DECODE_INTO(ip, n_state_out_var, n_exc_stack, scope_flags, n_pos_args, n_kwonly_args, n_def_args); \
                                     \
         /* state size in bytes */                                                 \
-        state_size_out_var = n_state_out_var * sizeof(mp_obj_t)                   \
-                           + n_exc_stack * sizeof(mp_exc_stack_t);                \
+        state_size_out_var = n_state_out_var *sizeof(mp_obj_t)                   \
+            + n_exc_stack *sizeof(mp_exc_stack_t);                \
     }
 
 #define INIT_CODESTATE(code_state, _fun_bc, _n_state, n_args, n_kw, args) \
@@ -356,14 +356,14 @@
 const mp_obj_type_t mp_type_fun_bc = {
     { &mp_type_type },
     .name = MP_QSTR_function,
-#if MICROPY_CPYTHON_COMPAT
+    #if MICROPY_CPYTHON_COMPAT
     .print = fun_bc_print,
-#endif
+    #endif
     .call = fun_bc_call,
     .unary_op = mp_generic_unary_op,
-#if MICROPY_PY_FUNCTION_ATTRS
+    #if MICROPY_PY_FUNCTION_ATTRS
     .attr = mp_obj_fun_bc_attr,
-#endif
+    #endif
 };
 
 mp_obj_t mp_obj_new_fun_bc(mp_obj_t def_args_in, mp_obj_t def_kw_args, const byte *code, const mp_uint_t *const_table) {
@@ -400,7 +400,7 @@
 STATIC mp_obj_t fun_native_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
     MP_STACK_CHECK();
     mp_obj_fun_bc_t *self = self_in;
-    mp_call_fun_t fun = MICROPY_MAKE_POINTER_CALLABLE((void*)self->bytecode);
+    mp_call_fun_t fun = MICROPY_MAKE_POINTER_CALLABLE((void *)self->bytecode);
     return fun(self_in, n_args, n_kw, args);
 }
 
@@ -412,7 +412,7 @@
 };
 
 mp_obj_t mp_obj_new_fun_native(mp_obj_t def_args_in, mp_obj_t def_kw_args, const void *fun_data, const mp_uint_t *const_table) {
-    mp_obj_fun_bc_t *o = mp_obj_new_fun_bc(def_args_in, def_kw_args, (const byte*)fun_data, const_table);
+    mp_obj_fun_bc_t *o = mp_obj_new_fun_bc(def_args_in, def_kw_args, (const byte *)fun_data, const_table);
     o->base.type = &mp_type_fun_native;
     return o;
 }
@@ -505,7 +505,7 @@
             convert_obj_for_inline_asm(args[1]),
             convert_obj_for_inline_asm(args[2]),
             convert_obj_for_inline_asm(args[3])
-        );
+            );
     }
 
     return mp_native_to_obj(ret, self->type_sig);
diff --git a/py/objgenerator.c b/py/objgenerator.c
index 2bb96bc..cd88e96 100644
--- a/py/objgenerator.c
+++ b/py/objgenerator.c
@@ -36,7 +36,7 @@
 #include "py/stackctrl.h"
 
 // Instance of GeneratorExit exception - needed by generator.close()
-const mp_obj_exception_t mp_const_GeneratorExit_obj = {{&mp_type_GeneratorExit}, 0, 0, NULL, (mp_obj_tuple_t*)&mp_const_empty_tuple_obj};
+const mp_obj_exception_t mp_const_GeneratorExit_obj = {{&mp_type_GeneratorExit}, 0, 0, NULL, (mp_obj_tuple_t *)&mp_const_empty_tuple_obj};
 
 /******************************************************************************/
 /* generator wrapper                                                          */
@@ -91,11 +91,11 @@
     mp_obj_fun_bc_t *self_fun = MP_OBJ_TO_PTR(self_in);
 
     // Determine start of prelude, and extract n_state from it
-    uintptr_t prelude_offset = ((uintptr_t*)self_fun->bytecode)[0];
+    uintptr_t prelude_offset = ((uintptr_t *)self_fun->bytecode)[0];
     #if MICROPY_EMIT_NATIVE_PRELUDE_AS_BYTES_OBJ
     // Prelude is in bytes object in const_table, at index prelude_offset
     mp_obj_str_t *prelude_bytes = MP_OBJ_TO_PTR(self_fun->const_table[prelude_offset]);
-    prelude_offset = (const byte*)prelude_bytes->data - self_fun->bytecode;
+    prelude_offset = (const byte *)prelude_bytes->data - self_fun->bytecode;
     #endif
     const uint8_t *ip = self_fun->bytecode + prelude_offset;
     size_t n_state, n_exc_stack_unused, scope_flags, n_pos_args, n_kwonly_args, n_def_args;
@@ -110,7 +110,7 @@
     // Parse the input arguments and set up the code state
     o->pend_exc = mp_const_none;
     o->code_state.fun_bc = self_fun;
-    o->code_state.ip = (const byte*)prelude_offset;
+    o->code_state.ip = (const byte *)prelude_offset;
     o->code_state.n_state = n_state;
     mp_setup_code_state(&o->code_state, n_args, n_kw, args);
 
@@ -118,8 +118,8 @@
     o->code_state.exc_sp_idx = MP_CODE_STATE_EXC_SP_IDX_SENTINEL;
 
     // Prepare the generator instance for execution
-    uintptr_t start_offset = ((uintptr_t*)self_fun->bytecode)[1];
-    o->code_state.ip = MICROPY_MAKE_POINTER_CALLABLE((void*)(self_fun->bytecode + start_offset));
+    uintptr_t start_offset = ((uintptr_t *)self_fun->bytecode)[1];
+    o->code_state.ip = MICROPY_MAKE_POINTER_CALLABLE((void *)(self_fun->bytecode + start_offset));
 
     return MP_OBJ_FROM_PTR(o);
 }
@@ -188,9 +188,9 @@
     #if MICROPY_EMIT_NATIVE
     if (self->code_state.exc_sp_idx == MP_CODE_STATE_EXC_SP_IDX_SENTINEL) {
         // A native generator, with entry point 2 words into the "bytecode" pointer
-        typedef uintptr_t (*mp_fun_native_gen_t)(void*, mp_obj_t);
-        mp_fun_native_gen_t fun = MICROPY_MAKE_POINTER_CALLABLE((const void*)(self->code_state.fun_bc->bytecode + 2 * sizeof(uintptr_t)));
-        ret_kind = fun((void*)&self->code_state, throw_value);
+        typedef uintptr_t (*mp_fun_native_gen_t)(void *, mp_obj_t);
+        mp_fun_native_gen_t fun = MICROPY_MAKE_POINTER_CALLABLE((const void *)(self->code_state.fun_bc->bytecode + 2 * sizeof(uintptr_t)));
+        ret_kind = fun((void *)&self->code_state, throw_value);
     } else
     #endif
     {
@@ -347,5 +347,5 @@
     .unary_op = mp_generic_unary_op,
     .getiter = mp_identity_getiter,
     .iternext = gen_instance_iternext,
-    .locals_dict = (mp_obj_dict_t*)&gen_instance_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&gen_instance_locals_dict,
 };
diff --git a/py/objgetitemiter.c b/py/objgetitemiter.c
index ec41c2c..54e27b8 100644
--- a/py/objgetitemiter.c
+++ b/py/objgetitemiter.c
@@ -46,7 +46,7 @@
         return value;
     } else {
         // an exception was raised
-        mp_obj_type_t *t = (mp_obj_type_t*)((mp_obj_base_t*)nlr.ret_val)->type;
+        mp_obj_type_t *t = (mp_obj_type_t *)((mp_obj_base_t *)nlr.ret_val)->type;
         if (t == &mp_type_StopIteration || t == &mp_type_IndexError) {
             // return MP_OBJ_STOP_ITERATION instead of raising
             return MP_OBJ_STOP_ITERATION;
@@ -67,7 +67,7 @@
 // args are those returned from mp_load_method_maybe (ie either an attribute or a method)
 mp_obj_t mp_obj_new_getitem_iter(mp_obj_t *args, mp_obj_iter_buf_t *iter_buf) {
     assert(sizeof(mp_obj_getitem_iter_t) <= sizeof(mp_obj_iter_buf_t));
-    mp_obj_getitem_iter_t *o = (mp_obj_getitem_iter_t*)iter_buf;
+    mp_obj_getitem_iter_t *o = (mp_obj_getitem_iter_t *)iter_buf;
     o->base.type = &it_type;
     o->args[0] = args[0];
     o->args[1] = args[1];
diff --git a/py/objint.c b/py/objint.c
index 2fdcf58..da51e5a 100644
--- a/py/objint.c
+++ b/py/objint.c
@@ -57,10 +57,10 @@
                 size_t l;
                 const char *s = mp_obj_str_get_data(args[0], &l);
                 return mp_parse_num_integer(s, l, 0, NULL);
-#if MICROPY_PY_BUILTINS_FLOAT
+            #if MICROPY_PY_BUILTINS_FLOAT
             } else if (mp_obj_is_float(args[0])) {
                 return mp_obj_new_int_from_float(mp_obj_float_get(args[0]));
-#endif
+            #endif
             } else {
                 return mp_unary_op(MP_UNARY_OP_INT, args[0]);
             }
@@ -86,26 +86,26 @@
 STATIC mp_fp_as_int_class_t mp_classify_fp_as_int(mp_float_t val) {
     union {
         mp_float_t f;
-#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
+        #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
         uint32_t i;
-#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
+        #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
         uint32_t i[2];
-#endif
+        #endif
     } u = {val};
 
     uint32_t e;
-#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
+    #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
     e = u.i;
-#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
+    #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
     e = u.i[MP_ENDIANNESS_LITTLE];
-#endif
+    #endif
 #define MP_FLOAT_SIGN_SHIFT_I32 ((MP_FLOAT_FRAC_BITS + MP_FLOAT_EXP_BITS) % 32)
 #define MP_FLOAT_EXP_SHIFT_I32 (MP_FLOAT_FRAC_BITS % 32)
 
     if (e & (1U << MP_FLOAT_SIGN_SHIFT_I32)) {
-#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
+        #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
         e |= u.i[MP_ENDIANNESS_BIG] != 0;
-#endif
+        #endif
         if ((e & ~(1 << MP_FLOAT_SIGN_SHIFT_I32)) == 0) {
             // handle case of -0 (when sign is set but rest of bits are zero)
             e = 0;
@@ -120,16 +120,16 @@
     if (e <= ((8 * sizeof(uintptr_t) + MP_FLOAT_EXP_BIAS - 3) << MP_FLOAT_EXP_SHIFT_I32)) {
         return MP_FP_CLASS_FIT_SMALLINT;
     }
-#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
+    #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
     if (e <= (((sizeof(long long) * BITS_PER_BYTE) + MP_FLOAT_EXP_BIAS - 2) << MP_FLOAT_EXP_SHIFT_I32)) {
         return MP_FP_CLASS_FIT_LONGINT;
     }
-#endif
-#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ
+    #endif
+    #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ
     return MP_FP_CLASS_FIT_LONGINT;
-#else
+    #else
     return MP_FP_CLASS_OVERFLOW;
-#endif
+    #endif
 }
 #undef MP_FLOAT_SIGN_SHIFT_I32
 #undef MP_FLOAT_EXP_SHIFT_I32
@@ -218,7 +218,7 @@
 // The resulting formatted string will be returned from this function and the
 // formatted size will be in *fmt_size.
 char *mp_obj_int_formatted(char **buf, size_t *buf_size, size_t *fmt_size, mp_const_obj_t self_in,
-                           int base, const char *prefix, char base_char, char comma) {
+    int base, const char *prefix, char base_char, char comma) {
     fmt_int_t num;
     #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE
     // Only have small ints; get the integer value to format.
@@ -392,7 +392,7 @@
     mp_buffer_info_t bufinfo;
     mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ);
 
-    const byte* buf = (const byte*)bufinfo.buf;
+    const byte *buf = (const byte *)bufinfo.buf;
     int delta = 1;
     if (args[2] == MP_OBJ_NEW_QSTR(MP_QSTR_little)) {
         buf += bufinfo.len - 1;
@@ -428,7 +428,7 @@
 
     vstr_t vstr;
     vstr_init_len(&vstr, len);
-    byte *data = (byte*)vstr.buf;
+    byte *data = (byte *)vstr.buf;
     memset(data, 0, len);
 
     #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE
@@ -460,5 +460,5 @@
     .make_new = mp_obj_int_make_new,
     .unary_op = mp_obj_int_unary_op,
     .binary_op = mp_obj_int_binary_op,
-    .locals_dict = (mp_obj_dict_t*)&int_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&int_locals_dict,
 };
diff --git a/py/objint.h b/py/objint.h
index 4b95acd..c475238 100644
--- a/py/objint.h
+++ b/py/objint.h
@@ -31,11 +31,11 @@
 
 typedef struct _mp_obj_int_t {
     mp_obj_base_t base;
-#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
+    #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
     mp_longint_impl_t val;
-#elif MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ
+    #elif MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ
     mpz_t mpz;
-#endif
+    #endif
 } mp_obj_int_t;
 
 extern const mp_obj_int_t mp_maxsize_obj;
@@ -50,9 +50,9 @@
 
 void mp_obj_int_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind);
 char *mp_obj_int_formatted(char **buf, size_t *buf_size, size_t *fmt_size, mp_const_obj_t self_in,
-                           int base, const char *prefix, char base_char, char comma);
+    int base, const char *prefix, char base_char, char comma);
 char *mp_obj_int_formatted_impl(char **buf, size_t *buf_size, size_t *fmt_size, mp_const_obj_t self_in,
-                                int base, const char *prefix, char base_char, char comma);
+    int base, const char *prefix, char base_char, char comma);
 mp_int_t mp_obj_int_hash(mp_obj_t self_in);
 mp_obj_t mp_obj_int_from_bytes_impl(bool big_endian, size_t len, const byte *buf);
 void mp_obj_int_to_bytes_impl(mp_obj_t self_in, bool big_endian, size_t len, byte *buf);
diff --git a/py/objint_longlong.c b/py/objint_longlong.c
index 37e2d6b..c34415a 100644
--- a/py/objint_longlong.c
+++ b/py/objint_longlong.c
@@ -95,15 +95,20 @@
 mp_obj_t mp_obj_int_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
     mp_obj_int_t *o = o_in;
     switch (op) {
-        case MP_UNARY_OP_BOOL: return mp_obj_new_bool(o->val != 0);
+        case MP_UNARY_OP_BOOL:
+            return mp_obj_new_bool(o->val != 0);
 
         // truncate value to fit in mp_int_t, which gives the same hash as
         // small int if the value fits without truncation
-        case MP_UNARY_OP_HASH: return MP_OBJ_NEW_SMALL_INT((mp_int_t)o->val);
+        case MP_UNARY_OP_HASH:
+            return MP_OBJ_NEW_SMALL_INT((mp_int_t)o->val);
 
-        case MP_UNARY_OP_POSITIVE: return o_in;
-        case MP_UNARY_OP_NEGATIVE: return mp_obj_new_int_from_ll(-o->val);
-        case MP_UNARY_OP_INVERT: return mp_obj_new_int_from_ll(~o->val);
+        case MP_UNARY_OP_POSITIVE:
+            return o_in;
+        case MP_UNARY_OP_NEGATIVE:
+            return mp_obj_new_int_from_ll(-o->val);
+        case MP_UNARY_OP_INVERT:
+            return mp_obj_new_int_from_ll(~o->val);
         case MP_UNARY_OP_ABS: {
             mp_obj_int_t *self = MP_OBJ_TO_PTR(o_in);
             if (self->val >= 0) {
@@ -114,7 +119,8 @@
             self->val = -self->val;
             return MP_OBJ_FROM_PTR(self);
         }
-        default: return MP_OBJ_NULL; // op not supported
+        default:
+            return MP_OBJ_NULL;      // op not supported
     }
 }
 
@@ -126,13 +132,13 @@
         lhs_val = MP_OBJ_SMALL_INT_VALUE(lhs_in);
     } else {
         assert(mp_obj_is_type(lhs_in, &mp_type_int));
-        lhs_val = ((mp_obj_int_t*)lhs_in)->val;
+        lhs_val = ((mp_obj_int_t *)lhs_in)->val;
     }
 
     if (mp_obj_is_small_int(rhs_in)) {
         rhs_val = MP_OBJ_SMALL_INT_VALUE(rhs_in);
     } else if (mp_obj_is_type(rhs_in, &mp_type_int)) {
-        rhs_val = ((mp_obj_int_t*)rhs_in)->val;
+        rhs_val = ((mp_obj_int_t *)rhs_in)->val;
     } else {
         // delegate to generic function to check for extra cases
         return mp_obj_int_binary_op_extra_cases(op, lhs_in, rhs_in);
diff --git a/py/objint_mpz.c b/py/objint_mpz.c
index 7b2bcc9..5fd558f 100644
--- a/py/objint_mpz.c
+++ b/py/objint_mpz.c
@@ -68,7 +68,7 @@
 // *FORMAT-ON*
 const mp_obj_int_t mp_maxsize_obj = {
     {&mp_type_int},
-    {.fixed_dig = 1, .len = NUM_DIG, .alloc = NUM_DIG, .dig = (mpz_dig_t*)maxsize_dig}
+    {.fixed_dig = 1, .len = NUM_DIG, .alloc = NUM_DIG, .dig = (mpz_dig_t *)maxsize_dig}
 };
 #undef DIG_MASK
 #undef NUM_DIG
@@ -91,7 +91,7 @@
 //
 // This particular routine should only be called for the mpz representation of the int.
 char *mp_obj_int_formatted_impl(char **buf, size_t *buf_size, size_t *fmt_size, mp_const_obj_t self_in,
-                                int base, const char *prefix, char base_char, char comma) {
+    int base, const char *prefix, char base_char, char comma) {
     assert(mp_obj_is_type(self_in, &mp_type_int));
     const mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in);
 
@@ -144,11 +144,20 @@
 mp_obj_t mp_obj_int_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
     mp_obj_int_t *o = MP_OBJ_TO_PTR(o_in);
     switch (op) {
-        case MP_UNARY_OP_BOOL: return mp_obj_new_bool(!mpz_is_zero(&o->mpz));
-        case MP_UNARY_OP_HASH: return MP_OBJ_NEW_SMALL_INT(mpz_hash(&o->mpz));
-        case MP_UNARY_OP_POSITIVE: return o_in;
-        case MP_UNARY_OP_NEGATIVE: { mp_obj_int_t *o2 = mp_obj_int_new_mpz(); mpz_neg_inpl(&o2->mpz, &o->mpz); return MP_OBJ_FROM_PTR(o2); }
-        case MP_UNARY_OP_INVERT: { mp_obj_int_t *o2 = mp_obj_int_new_mpz(); mpz_not_inpl(&o2->mpz, &o->mpz); return MP_OBJ_FROM_PTR(o2); }
+        case MP_UNARY_OP_BOOL:
+            return mp_obj_new_bool(!mpz_is_zero(&o->mpz));
+        case MP_UNARY_OP_HASH:
+            return MP_OBJ_NEW_SMALL_INT(mpz_hash(&o->mpz));
+        case MP_UNARY_OP_POSITIVE:
+            return o_in;
+        case MP_UNARY_OP_NEGATIVE: { mp_obj_int_t *o2 = mp_obj_int_new_mpz();
+                                     mpz_neg_inpl(&o2->mpz, &o->mpz);
+                                     return MP_OBJ_FROM_PTR(o2);
+        }
+        case MP_UNARY_OP_INVERT: { mp_obj_int_t *o2 = mp_obj_int_new_mpz();
+                                   mpz_not_inpl(&o2->mpz, &o->mpz);
+                                   return MP_OBJ_FROM_PTR(o2);
+        }
         case MP_UNARY_OP_ABS: {
             mp_obj_int_t *self = MP_OBJ_TO_PTR(o_in);
             if (self->mpz.neg == 0) {
@@ -158,7 +167,8 @@
             mpz_abs_inpl(&self2->mpz, &self->mpz);
             return MP_OBJ_FROM_PTR(self2);
         }
-        default: return MP_OBJ_NULL; // op not supported
+        default:
+            return MP_OBJ_NULL;      // op not supported
     }
 }
 
@@ -174,7 +184,7 @@
         zlhs = &z_int;
     } else {
         assert(mp_obj_is_type(lhs_in, &mp_type_int));
-        zlhs = &((mp_obj_int_t*)MP_OBJ_TO_PTR(lhs_in))->mpz;
+        zlhs = &((mp_obj_int_t *)MP_OBJ_TO_PTR(lhs_in))->mpz;
     }
 
     // if rhs is small int, then lhs was not (otherwise mp_binary_op handles it)
@@ -182,15 +192,15 @@
         mpz_init_fixed_from_int(&z_int, z_int_dig, MPZ_NUM_DIG_FOR_INT, MP_OBJ_SMALL_INT_VALUE(rhs_in));
         zrhs = &z_int;
     } else if (mp_obj_is_type(rhs_in, &mp_type_int)) {
-        zrhs = &((mp_obj_int_t*)MP_OBJ_TO_PTR(rhs_in))->mpz;
-#if MICROPY_PY_BUILTINS_FLOAT
+        zrhs = &((mp_obj_int_t *)MP_OBJ_TO_PTR(rhs_in))->mpz;
+    #if MICROPY_PY_BUILTINS_FLOAT
     } else if (mp_obj_is_float(rhs_in)) {
         return mp_obj_float_binary_op(op, mpz_as_float(zlhs), rhs_in);
-#endif
-#if MICROPY_PY_BUILTINS_COMPLEX
+    #endif
+    #if MICROPY_PY_BUILTINS_COMPLEX
     } else if (mp_obj_is_type(rhs_in, &mp_type_complex)) {
         return mp_obj_complex_binary_op(op, mpz_as_float(zlhs), 0, rhs_in);
-#endif
+    #endif
     } else {
         // delegate to generic function to check for extra cases
         return mp_obj_int_binary_op_extra_cases(op, lhs_in, rhs_in);
@@ -226,10 +236,11 @@
             case MP_BINARY_OP_FLOOR_DIVIDE:
             case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE: {
                 if (mpz_is_zero(zrhs)) {
-                    zero_division_error:
+                zero_division_error:
                     mp_raise_msg(&mp_type_ZeroDivisionError, "divide by zero");
                 }
-                mpz_t rem; mpz_init_zero(&rem);
+                mpz_t rem;
+                mpz_init_zero(&rem);
                 mpz_divmod_inpl(&res->mpz, &rem, zlhs, zrhs);
                 mpz_deinit(&rem);
                 break;
@@ -239,7 +250,8 @@
                 if (mpz_is_zero(zrhs)) {
                     goto zero_division_error;
                 }
-                mpz_t quo; mpz_init_zero(&quo);
+                mpz_t quo;
+                mpz_init_zero(&quo);
                 mpz_divmod_inpl(&quo, &res->mpz, zlhs, zrhs);
                 mpz_deinit(&quo);
                 break;
@@ -345,9 +357,15 @@
 
         mpz_pow3_inpl(&(res_p->mpz), lhs, rhs, mod);
 
-        if (lhs == &l_temp) { mpz_deinit(lhs); }
-        if (rhs == &r_temp) { mpz_deinit(rhs); }
-        if (mod == &m_temp) { mpz_deinit(mod); }
+        if (lhs == &l_temp) {
+            mpz_deinit(lhs);
+        }
+        if (rhs == &r_temp) {
+            mpz_deinit(rhs);
+        }
+        if (mod == &m_temp) {
+            mpz_deinit(mod);
+        }
         return result;
     }
 }
diff --git a/py/objlist.c b/py/objlist.c
index 00afcd5..38329e0 100644
--- a/py/objlist.c
+++ b/py/objlist.c
@@ -88,15 +88,18 @@
 STATIC mp_obj_t list_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
     mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
     switch (op) {
-        case MP_UNARY_OP_BOOL: return mp_obj_new_bool(self->len != 0);
-        case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(self->len);
+        case MP_UNARY_OP_BOOL:
+            return mp_obj_new_bool(self->len != 0);
+        case MP_UNARY_OP_LEN:
+            return MP_OBJ_NEW_SMALL_INT(self->len);
         #if MICROPY_PY_SYS_GETSIZEOF
         case MP_UNARY_OP_SIZEOF: {
             size_t sz = sizeof(*self) + sizeof(mp_obj_t) * self->alloc;
             return MP_OBJ_NEW_SMALL_INT(sz);
         }
         #endif
-        default: return MP_OBJ_NULL; // op not supported
+        default:
+            return MP_OBJ_NULL;      // op not supported
     }
 }
 
@@ -153,7 +156,7 @@
 STATIC mp_obj_t list_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
     if (value == MP_OBJ_NULL) {
         // delete
-#if MICROPY_PY_BUILTINS_SLICE
+        #if MICROPY_PY_BUILTINS_SLICE
         if (mp_obj_is_type(index, &mp_type_slice)) {
             mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
             mp_bound_slice_t slice;
@@ -163,20 +166,20 @@
 
             mp_int_t len_adj = slice.start - slice.stop;
             assert(len_adj <= 0);
-            mp_seq_replace_slice_no_grow(self->items, self->len, slice.start, slice.stop, self->items/*NULL*/, 0, sizeof(*self->items));
+            mp_seq_replace_slice_no_grow(self->items, self->len, slice.start, slice.stop, self->items /*NULL*/, 0, sizeof(*self->items));
             // Clear "freed" elements at the end of list
             mp_seq_clear(self->items, self->len + len_adj, self->len, sizeof(*self->items));
             self->len += len_adj;
             return mp_const_none;
         }
-#endif
+        #endif
         mp_obj_t args[2] = {self_in, index};
         list_pop(2, args);
         return mp_const_none;
     } else if (value == MP_OBJ_SENTINEL) {
         // load
         mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
-#if MICROPY_PY_BUILTINS_SLICE
+        #if MICROPY_PY_BUILTINS_SLICE
         if (mp_obj_is_type(index, &mp_type_slice)) {
             mp_bound_slice_t slice;
             if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice)) {
@@ -186,14 +189,15 @@
             mp_seq_copy(res->items, self->items + slice.start, res->len, mp_obj_t);
             return MP_OBJ_FROM_PTR(res);
         }
-#endif
+        #endif
         size_t index_val = mp_get_index(self->base.type, self->len, index, false);
         return self->items[index_val];
     } else {
-#if MICROPY_PY_BUILTINS_SLICE
+        #if MICROPY_PY_BUILTINS_SLICE
         if (mp_obj_is_type(index, &mp_type_slice)) {
             mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
-            size_t value_len; mp_obj_t *value_items;
+            size_t value_len;
+            mp_obj_t *value_items;
             mp_obj_get_array(value, &value_len, &value_items);
             mp_bound_slice_t slice_out;
             if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice_out)) {
@@ -219,7 +223,7 @@
             self->len += len_adj;
             return mp_const_none;
         }
-#endif
+        #endif
         mp_obj_list_store(self_in, index, value);
         return mp_const_none;
     }
@@ -275,7 +279,7 @@
     // Clear stale pointer from slot which just got freed to prevent GC issues
     self->items[self->len] = MP_OBJ_NULL;
     if (self->alloc > LIST_MIN_ALLOC && self->alloc > 2 * self->len) {
-        self->items = m_renew(mp_obj_t, self->items, self->alloc, self->alloc/2);
+        self->items = m_renew(mp_obj_t, self->items, self->alloc, self->alloc / 2);
         self->alloc /= 2;
     }
     return ret;
@@ -288,9 +292,13 @@
         mp_obj_t *t = tail;
         mp_obj_t v = key_fn == MP_OBJ_NULL ? tail[0] : mp_call_function_1(key_fn, tail[0]); // get pivot using key_fn
         for (;;) {
-            do ++h; while (h < t && mp_binary_op(MP_BINARY_OP_LESS, key_fn == MP_OBJ_NULL ? h[0] : mp_call_function_1(key_fn, h[0]), v) == binop_less_result);
-            do --t; while (h < t && mp_binary_op(MP_BINARY_OP_LESS, v, key_fn == MP_OBJ_NULL ? t[0] : mp_call_function_1(key_fn, t[0])) == binop_less_result);
-            if (h >= t) break;
+            do {++h;
+            } while (h < t && mp_binary_op(MP_BINARY_OP_LESS, key_fn == MP_OBJ_NULL ? h[0] : mp_call_function_1(key_fn, h[0]), v) == binop_less_result);
+            do {--t;
+            } while (h < t && mp_binary_op(MP_BINARY_OP_LESS, v, key_fn == MP_OBJ_NULL ? t[0] : mp_call_function_1(key_fn, t[0])) == binop_less_result);
+            if (h >= t) {
+                break;
+            }
             mp_obj_t x = h[0];
             h[0] = t[0];
             t[0] = x;
@@ -321,15 +329,15 @@
         mp_arg_val_t key, reverse;
     } args;
     mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
-        MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args);
+        MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args);
 
     mp_check_self(mp_obj_is_type(pos_args[0], &mp_type_list));
     mp_obj_list_t *self = MP_OBJ_TO_PTR(pos_args[0]);
 
     if (self->len > 1) {
         mp_quicksort(self->items, self->items + self->len - 1,
-                     args.key.u_obj == mp_const_none ? MP_OBJ_NULL : args.key.u_obj,
-                     args.reverse.u_bool ? mp_const_false : mp_const_true);
+            args.key.u_obj == mp_const_none ? MP_OBJ_NULL : args.key.u_obj,
+            args.reverse.u_bool ? mp_const_false : mp_const_true);
     }
 
     return mp_const_none;
@@ -369,19 +377,19 @@
     // insert has its own strange index logic
     mp_int_t index = MP_OBJ_SMALL_INT_VALUE(idx);
     if (index < 0) {
-         index += self->len;
+        index += self->len;
     }
     if (index < 0) {
-         index = 0;
+        index = 0;
     }
     if ((size_t)index > self->len) {
-         index = self->len;
+        index = self->len;
     }
 
     mp_obj_list_append(self_in, mp_const_none);
 
-    for (mp_int_t i = self->len-1; i > index; i--) {
-         self->items[i] = self->items[i-1];
+    for (mp_int_t i = self->len - 1; i > index; i--) {
+        self->items[i] = self->items[i - 1];
     }
     self->items[index] = obj;
 
@@ -402,10 +410,10 @@
     mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
 
     mp_int_t len = self->len;
-    for (mp_int_t i = 0; i < len/2; i++) {
-         mp_obj_t a = self->items[i];
-         self->items[i] = self->items[len-i-1];
-         self->items[len-i-1] = a;
+    for (mp_int_t i = 0; i < len / 2; i++) {
+        mp_obj_t a = self->items[i];
+        self->items[i] = self->items[len - i - 1];
+        self->items[len - i - 1] = a;
     }
 
     return mp_const_none;
@@ -448,7 +456,7 @@
     .binary_op = list_binary_op,
     .subscr = list_subscr,
     .getiter = list_getiter,
-    .locals_dict = (mp_obj_dict_t*)&list_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&list_locals_dict,
 };
 
 void mp_obj_list_init(mp_obj_list_t *o, size_t n) {
@@ -518,7 +526,7 @@
 
 mp_obj_t mp_obj_new_list_iterator(mp_obj_t list, size_t cur, mp_obj_iter_buf_t *iter_buf) {
     assert(sizeof(mp_obj_list_it_t) <= sizeof(mp_obj_iter_buf_t));
-    mp_obj_list_it_t *o = (mp_obj_list_it_t*)iter_buf;
+    mp_obj_list_it_t *o = (mp_obj_list_it_t *)iter_buf;
     o->base.type = &mp_type_polymorph_iter;
     o->iternext = list_it_iternext;
     o->list = list;
diff --git a/py/objmodule.c b/py/objmodule.c
index 81558a0..7904700 100644
--- a/py/objmodule.c
+++ b/py/objmodule.c
@@ -45,7 +45,7 @@
         module_name = mp_obj_str_get_str(elem->value);
     }
 
-#if MICROPY_PY___FILE__
+    #if MICROPY_PY___FILE__
     // If we store __file__ to imported modules then try to lookup this
     // symbol to give more information about the module.
     elem = mp_map_lookup(&self->globals->map, MP_OBJ_NEW_QSTR(MP_QSTR___file__), MP_MAP_LOOKUP);
@@ -53,7 +53,7 @@
         mp_printf(print, "<module '%s' from '%s'>", module_name, mp_obj_str_get_str(elem->value));
         return;
     }
-#endif
+    #endif
 
     mp_printf(print, "<module '%s'>", module_name);
 }
@@ -140,93 +140,93 @@
     { MP_ROM_QSTR(MP_QSTR_builtins), MP_ROM_PTR(&mp_module_builtins) },
     { MP_ROM_QSTR(MP_QSTR_micropython), MP_ROM_PTR(&mp_module_micropython) },
 
-#if MICROPY_PY_IO
+    #if MICROPY_PY_IO
     { MP_ROM_QSTR(MP_QSTR_uio), MP_ROM_PTR(&mp_module_io) },
-#endif
-#if MICROPY_PY_COLLECTIONS
+    #endif
+    #if MICROPY_PY_COLLECTIONS
     { MP_ROM_QSTR(MP_QSTR_ucollections), MP_ROM_PTR(&mp_module_collections) },
-#endif
-#if MICROPY_PY_STRUCT
+    #endif
+    #if MICROPY_PY_STRUCT
     { MP_ROM_QSTR(MP_QSTR_ustruct), MP_ROM_PTR(&mp_module_ustruct) },
-#endif
+    #endif
 
-#if MICROPY_PY_BUILTINS_FLOAT
-#if MICROPY_PY_MATH
+    #if MICROPY_PY_BUILTINS_FLOAT
+    #if MICROPY_PY_MATH
     { MP_ROM_QSTR(MP_QSTR_math), MP_ROM_PTR(&mp_module_math) },
-#endif
-#if MICROPY_PY_BUILTINS_COMPLEX && MICROPY_PY_CMATH
+    #endif
+    #if MICROPY_PY_BUILTINS_COMPLEX && MICROPY_PY_CMATH
     { MP_ROM_QSTR(MP_QSTR_cmath), MP_ROM_PTR(&mp_module_cmath) },
-#endif
-#endif
-#if MICROPY_PY_SYS
+    #endif
+    #endif
+    #if MICROPY_PY_SYS
     { MP_ROM_QSTR(MP_QSTR_sys), MP_ROM_PTR(&mp_module_sys) },
-#endif
-#if MICROPY_PY_GC && MICROPY_ENABLE_GC
+    #endif
+    #if MICROPY_PY_GC && MICROPY_ENABLE_GC
     { MP_ROM_QSTR(MP_QSTR_gc), MP_ROM_PTR(&mp_module_gc) },
-#endif
-#if MICROPY_PY_THREAD
+    #endif
+    #if MICROPY_PY_THREAD
     { MP_ROM_QSTR(MP_QSTR__thread), MP_ROM_PTR(&mp_module_thread) },
-#endif
+    #endif
 
     // extmod modules
 
-#if MICROPY_PY_UERRNO
+    #if MICROPY_PY_UERRNO
     { MP_ROM_QSTR(MP_QSTR_uerrno), MP_ROM_PTR(&mp_module_uerrno) },
-#endif
-#if MICROPY_PY_UCTYPES
+    #endif
+    #if MICROPY_PY_UCTYPES
     { MP_ROM_QSTR(MP_QSTR_uctypes), MP_ROM_PTR(&mp_module_uctypes) },
-#endif
-#if MICROPY_PY_UZLIB
+    #endif
+    #if MICROPY_PY_UZLIB
     { MP_ROM_QSTR(MP_QSTR_uzlib), MP_ROM_PTR(&mp_module_uzlib) },
-#endif
-#if MICROPY_PY_UJSON
+    #endif
+    #if MICROPY_PY_UJSON
     { MP_ROM_QSTR(MP_QSTR_ujson), MP_ROM_PTR(&mp_module_ujson) },
-#endif
-#if MICROPY_PY_URE
+    #endif
+    #if MICROPY_PY_URE
     { MP_ROM_QSTR(MP_QSTR_ure), MP_ROM_PTR(&mp_module_ure) },
-#endif
-#if MICROPY_PY_UHEAPQ
+    #endif
+    #if MICROPY_PY_UHEAPQ
     { MP_ROM_QSTR(MP_QSTR_uheapq), MP_ROM_PTR(&mp_module_uheapq) },
-#endif
-#if MICROPY_PY_UTIMEQ
+    #endif
+    #if MICROPY_PY_UTIMEQ
     { MP_ROM_QSTR(MP_QSTR_utimeq), MP_ROM_PTR(&mp_module_utimeq) },
-#endif
-#if MICROPY_PY_UHASHLIB
+    #endif
+    #if MICROPY_PY_UHASHLIB
     { MP_ROM_QSTR(MP_QSTR_uhashlib), MP_ROM_PTR(&mp_module_uhashlib) },
-#endif
-#if MICROPY_PY_UCRYPTOLIB
+    #endif
+    #if MICROPY_PY_UCRYPTOLIB
     { MP_ROM_QSTR(MP_QSTR_ucryptolib), MP_ROM_PTR(&mp_module_ucryptolib) },
-#endif
-#if MICROPY_PY_UBINASCII
+    #endif
+    #if MICROPY_PY_UBINASCII
     { MP_ROM_QSTR(MP_QSTR_ubinascii), MP_ROM_PTR(&mp_module_ubinascii) },
-#endif
-#if MICROPY_PY_URANDOM
+    #endif
+    #if MICROPY_PY_URANDOM
     { MP_ROM_QSTR(MP_QSTR_urandom), MP_ROM_PTR(&mp_module_urandom) },
-#endif
-#if MICROPY_PY_USELECT
+    #endif
+    #if MICROPY_PY_USELECT
     { MP_ROM_QSTR(MP_QSTR_uselect), MP_ROM_PTR(&mp_module_uselect) },
-#endif
-#if MICROPY_PY_USSL
+    #endif
+    #if MICROPY_PY_USSL
     { MP_ROM_QSTR(MP_QSTR_ussl), MP_ROM_PTR(&mp_module_ussl) },
-#endif
-#if MICROPY_PY_LWIP
+    #endif
+    #if MICROPY_PY_LWIP
     { MP_ROM_QSTR(MP_QSTR_lwip), MP_ROM_PTR(&mp_module_lwip) },
-#endif
-#if MICROPY_PY_UWEBSOCKET
+    #endif
+    #if MICROPY_PY_UWEBSOCKET
     { MP_ROM_QSTR(MP_QSTR_uwebsocket), MP_ROM_PTR(&mp_module_uwebsocket) },
-#endif
-#if MICROPY_PY_WEBREPL
+    #endif
+    #if MICROPY_PY_WEBREPL
     { MP_ROM_QSTR(MP_QSTR__webrepl), MP_ROM_PTR(&mp_module_webrepl) },
-#endif
-#if MICROPY_PY_FRAMEBUF
+    #endif
+    #if MICROPY_PY_FRAMEBUF
     { MP_ROM_QSTR(MP_QSTR_framebuf), MP_ROM_PTR(&mp_module_framebuf) },
-#endif
-#if MICROPY_PY_BTREE
+    #endif
+    #if MICROPY_PY_BTREE
     { MP_ROM_QSTR(MP_QSTR_btree), MP_ROM_PTR(&mp_module_btree) },
-#endif
-#if MICROPY_PY_BLUETOOTH
+    #endif
+    #if MICROPY_PY_BLUETOOTH
     { MP_ROM_QSTR(MP_QSTR_ubluetooth), MP_ROM_PTR(&mp_module_ubluetooth) },
-#endif
+    #endif
 
     // extra builtin modules as defined by a port
     MICROPY_PORT_BUILTIN_MODULES
@@ -247,7 +247,7 @@
 
     if (el == NULL) {
         // module not found, look for builtin module names
-        el = mp_map_lookup((mp_map_t*)&mp_builtin_module_map, MP_OBJ_NEW_QSTR(module_name), MP_MAP_LOOKUP);
+        el = mp_map_lookup((mp_map_t *)&mp_builtin_module_map, MP_OBJ_NEW_QSTR(module_name), MP_MAP_LOOKUP);
         if (el == NULL) {
             return MP_OBJ_NULL;
         }
@@ -267,7 +267,7 @@
 // Search for u"foo" in built-in modules, return MP_OBJ_NULL if not found
 mp_obj_t mp_module_search_umodule(const char *module_str) {
     for (size_t i = 0; i < MP_ARRAY_SIZE(mp_builtin_module_table); ++i) {
-        const mp_map_elem_t *entry = (const mp_map_elem_t*)&mp_builtin_module_table[i];
+        const mp_map_elem_t *entry = (const mp_map_elem_t *)&mp_builtin_module_table[i];
         const char *key = qstr_str(MP_OBJ_QSTR_VALUE(entry->key));
         if (key[0] == 'u' && strcmp(&key[1], module_str) == 0) {
             return (mp_obj_t)entry->value;
diff --git a/py/objnamedtuple.c b/py/objnamedtuple.c
index 8e714aa..a4ac19f 100644
--- a/py/objnamedtuple.c
+++ b/py/objnamedtuple.c
@@ -46,7 +46,7 @@
 #if MICROPY_PY_COLLECTIONS_NAMEDTUPLE__ASDICT
 STATIC mp_obj_t namedtuple_asdict(mp_obj_t self_in) {
     mp_obj_namedtuple_t *self = MP_OBJ_TO_PTR(self_in);
-    const qstr *fields = ((mp_obj_namedtuple_type_t*)self->tuple.base.type)->fields;
+    const qstr *fields = ((mp_obj_namedtuple_type_t *)self->tuple.base.type)->fields;
     mp_obj_t dict = mp_obj_new_dict(self->tuple.len);
     //make it an OrderedDict
     mp_obj_dict_t *dictObj = MP_OBJ_TO_PTR(dict);
@@ -64,7 +64,7 @@
     (void)kind;
     mp_obj_namedtuple_t *o = MP_OBJ_TO_PTR(o_in);
     mp_printf(print, "%q", o->tuple.base.type->name);
-    const qstr *fields = ((mp_obj_namedtuple_type_t*)o->tuple.base.type)->fields;
+    const qstr *fields = ((mp_obj_namedtuple_type_t *)o->tuple.base.type)->fields;
     mp_obj_attrtuple_print_helper(print, fields, &o->tuple);
 }
 
@@ -79,7 +79,7 @@
             return;
         }
         #endif
-        size_t id = mp_obj_namedtuple_find_field((mp_obj_namedtuple_type_t*)self->tuple.base.type, attr);
+        size_t id = mp_obj_namedtuple_find_field((mp_obj_namedtuple_type_t *)self->tuple.base.type, attr);
         if (id == (size_t)-1) {
             return;
         }
@@ -92,7 +92,7 @@
 }
 
 STATIC mp_obj_t namedtuple_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
-    const mp_obj_namedtuple_type_t *type = (const mp_obj_namedtuple_type_t*)type_in;
+    const mp_obj_namedtuple_type_t *type = (const mp_obj_namedtuple_type_t *)type_in;
     size_t num_fields = type->n_fields;
     if (n_args + n_kw != num_fields) {
         if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
diff --git a/py/objobject.c b/py/objobject.c
index 71301dc..62a3366 100644
--- a/py/objobject.c
+++ b/py/objobject.c
@@ -49,7 +49,7 @@
 STATIC MP_DEFINE_CONST_FUN_OBJ_1(object___init___obj, object___init__);
 
 STATIC mp_obj_t object___new__(mp_obj_t cls) {
-    if (!mp_obj_is_type(cls, &mp_type_type) || !mp_obj_is_instance_type((mp_obj_type_t*)MP_OBJ_TO_PTR(cls))) {
+    if (!mp_obj_is_type(cls, &mp_type_type) || !mp_obj_is_instance_type((mp_obj_type_t *)MP_OBJ_TO_PTR(cls))) {
         mp_raise_TypeError("arg must be user-type");
     }
     // This executes only "__new__" part of instance creation.
@@ -117,6 +117,6 @@
     .name = MP_QSTR_object,
     .make_new = object_make_new,
     #if MICROPY_CPYTHON_COMPAT
-    .locals_dict = (mp_obj_dict_t*)&object_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&object_locals_dict,
     #endif
 };
diff --git a/py/objproperty.c b/py/objproperty.c
index 2a7844b..8d2c292 100644
--- a/py/objproperty.c
+++ b/py/objproperty.c
@@ -58,7 +58,7 @@
 
 STATIC mp_obj_t property_getter(mp_obj_t self_in, mp_obj_t getter) {
     mp_obj_property_t *p2 = m_new_obj(mp_obj_property_t);
-    *p2 = *(mp_obj_property_t*)MP_OBJ_TO_PTR(self_in);
+    *p2 = *(mp_obj_property_t *)MP_OBJ_TO_PTR(self_in);
     p2->proxy[0] = getter;
     return MP_OBJ_FROM_PTR(p2);
 }
@@ -67,7 +67,7 @@
 
 STATIC mp_obj_t property_setter(mp_obj_t self_in, mp_obj_t setter) {
     mp_obj_property_t *p2 = m_new_obj(mp_obj_property_t);
-    *p2 = *(mp_obj_property_t*)MP_OBJ_TO_PTR(self_in);
+    *p2 = *(mp_obj_property_t *)MP_OBJ_TO_PTR(self_in);
     p2->proxy[1] = setter;
     return MP_OBJ_FROM_PTR(p2);
 }
@@ -76,7 +76,7 @@
 
 STATIC mp_obj_t property_deleter(mp_obj_t self_in, mp_obj_t deleter) {
     mp_obj_property_t *p2 = m_new_obj(mp_obj_property_t);
-    *p2 = *(mp_obj_property_t*)MP_OBJ_TO_PTR(self_in);
+    *p2 = *(mp_obj_property_t *)MP_OBJ_TO_PTR(self_in);
     p2->proxy[2] = deleter;
     return MP_OBJ_FROM_PTR(p2);
 }
@@ -95,7 +95,7 @@
     { &mp_type_type },
     .name = MP_QSTR_property,
     .make_new = property_make_new,
-    .locals_dict = (mp_obj_dict_t*)&property_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&property_locals_dict,
 };
 
 const mp_obj_t *mp_obj_property_get(mp_obj_t self_in) {
diff --git a/py/objrange.c b/py/objrange.c
index 6c3097a..9727d48 100644
--- a/py/objrange.c
+++ b/py/objrange.c
@@ -59,7 +59,7 @@
 
 STATIC mp_obj_t mp_obj_new_range_iterator(mp_int_t cur, mp_int_t stop, mp_int_t step, mp_obj_iter_buf_t *iter_buf) {
     assert(sizeof(mp_obj_range_it_t) <= sizeof(mp_obj_iter_buf_t));
-    mp_obj_range_it_t *o = (mp_obj_range_it_t*)iter_buf;
+    mp_obj_range_it_t *o = (mp_obj_range_it_t *)iter_buf;
     o->base.type = &range_it_type;
     o->cur = cur;
     o->stop = stop;
@@ -132,9 +132,12 @@
     mp_obj_range_t *self = MP_OBJ_TO_PTR(self_in);
     mp_int_t len = range_len(self);
     switch (op) {
-        case MP_UNARY_OP_BOOL: return mp_obj_new_bool(len > 0);
-        case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(len);
-        default: return MP_OBJ_NULL; // op not supported
+        case MP_UNARY_OP_BOOL:
+            return mp_obj_new_bool(len > 0);
+        case MP_UNARY_OP_LEN:
+            return MP_OBJ_NEW_SMALL_INT(len);
+        default:
+            return MP_OBJ_NULL;      // op not supported
     }
 }
 
@@ -152,7 +155,7 @@
         && (lhs_len == 0
             || (lhs->start == rhs->start
                 && (lhs_len == 1 || lhs->step == rhs->step)))
-    );
+        );
 }
 #endif
 
@@ -161,7 +164,7 @@
         // load
         mp_obj_range_t *self = MP_OBJ_TO_PTR(self_in);
         mp_int_t len = range_len(self);
-#if MICROPY_PY_BUILTINS_SLICE
+        #if MICROPY_PY_BUILTINS_SLICE
         if (mp_obj_is_type(index, &mp_type_slice)) {
             mp_bound_slice_t slice;
             mp_seq_get_fast_slice_indexes(len, index, &slice);
@@ -176,7 +179,7 @@
             }
             return MP_OBJ_FROM_PTR(o);
         }
-#endif
+        #endif
         size_t index_val = mp_get_index(self->base.type, len, index, false);
         return MP_OBJ_NEW_SMALL_INT(self->start + index_val * self->step);
     } else {
@@ -218,7 +221,7 @@
     #endif
     .subscr = range_subscr,
     .getiter = range_getiter,
-#if MICROPY_PY_BUILTINS_RANGE_ATTRS
+    #if MICROPY_PY_BUILTINS_RANGE_ATTRS
     .attr = range_attr,
-#endif
+    #endif
 };
diff --git a/py/objset.c b/py/objset.c
index 48d6caf..da56f9a 100644
--- a/py/objset.c
+++ b/py/objset.c
@@ -47,9 +47,9 @@
 
 STATIC bool is_set_or_frozenset(mp_obj_t o) {
     return mp_obj_is_type(o, &mp_type_set)
-#if MICROPY_PY_BUILTINS_FROZENSET
-        || mp_obj_is_type(o, &mp_type_frozenset)
-#endif
+           #if MICROPY_PY_BUILTINS_FROZENSET
+           || mp_obj_is_type(o, &mp_type_frozenset)
+           #endif
     ;
 }
 
@@ -121,7 +121,7 @@
                 mp_obj_set_store(set, item);
             }
             // Set actual set/frozenset type
-            ((mp_obj_set_t*)MP_OBJ_TO_PTR(set))->base.type = type;
+            ((mp_obj_set_t *)MP_OBJ_TO_PTR(set))->base.type = type;
             return set;
         }
     }
@@ -144,7 +144,7 @@
 
 STATIC mp_obj_t set_getiter(mp_obj_t set_in, mp_obj_iter_buf_t *iter_buf) {
     assert(sizeof(mp_obj_set_it_t) <= sizeof(mp_obj_iter_buf_t));
-    mp_obj_set_it_t *o = (mp_obj_set_it_t*)iter_buf;
+    mp_obj_set_it_t *o = (mp_obj_set_it_t *)iter_buf;
     o->base.type = &mp_type_polymorph_iter;
     o->iternext = set_it_iternext;
     o->set = (mp_obj_set_t *)MP_OBJ_TO_PTR(set_in);
@@ -205,7 +205,7 @@
         if (self == other) {
             set_clear(self);
         } else {
-            mp_set_t *self_set = &((mp_obj_set_t*)MP_OBJ_TO_PTR(self))->set;
+            mp_set_t *self_set = &((mp_obj_set_t *)MP_OBJ_TO_PTR(self))->set;
             mp_obj_t iter = mp_getiter(other, NULL);
             mp_obj_t next;
             while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
@@ -426,9 +426,11 @@
 STATIC mp_obj_t set_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
     mp_obj_set_t *self = MP_OBJ_TO_PTR(self_in);
     switch (op) {
-        case MP_UNARY_OP_BOOL: return mp_obj_new_bool(self->set.used != 0);
-        case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(self->set.used);
-#if MICROPY_PY_BUILTINS_FROZENSET
+        case MP_UNARY_OP_BOOL:
+            return mp_obj_new_bool(self->set.used != 0);
+        case MP_UNARY_OP_LEN:
+            return MP_OBJ_NEW_SMALL_INT(self->set.used);
+        #if MICROPY_PY_BUILTINS_FROZENSET
         case MP_UNARY_OP_HASH:
             if (mp_obj_is_type(self_in, &mp_type_frozenset)) {
                 // start hash with unique value
@@ -443,8 +445,9 @@
                 }
                 return MP_OBJ_NEW_SMALL_INT(hash);
             }
-#endif
-        default: return MP_OBJ_NULL; // op not supported
+        #endif
+        default:
+            return MP_OBJ_NULL;      // op not supported
     }
 }
 
@@ -544,7 +547,7 @@
     .unary_op = set_unary_op,
     .binary_op = set_binary_op,
     .getiter = set_getiter,
-    .locals_dict = (mp_obj_dict_t*)&set_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&set_locals_dict,
 };
 
 #if MICROPY_PY_BUILTINS_FROZENSET
@@ -570,7 +573,7 @@
     .unary_op = set_unary_op,
     .binary_op = set_binary_op,
     .getiter = set_getiter,
-    .locals_dict = (mp_obj_dict_t*)&frozenset_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&frozenset_locals_dict,
 };
 #endif
 
diff --git a/py/objslice.c b/py/objslice.c
index 86ee03e..d1c23cb 100644
--- a/py/objslice.c
+++ b/py/objslice.c
@@ -96,11 +96,11 @@
     { &mp_type_type },
     .name = MP_QSTR_slice,
     .print = slice_print,
-#if MICROPY_PY_BUILTINS_SLICE_ATTRS
+    #if MICROPY_PY_BUILTINS_SLICE_ATTRS
     .attr = slice_attr,
-#elif MICROPY_PY_BUILTINS_SLICE_INDICES
-    .locals_dict = (mp_obj_dict_t*)&slice_locals_dict,
-#endif
+    #elif MICROPY_PY_BUILTINS_SLICE_INDICES
+    .locals_dict = (mp_obj_dict_t *)&slice_locals_dict,
+    #endif
 };
 
 mp_obj_t mp_obj_new_slice(mp_obj_t ostart, mp_obj_t ostop, mp_obj_t ostep) {
diff --git a/py/objstr.c b/py/objstr.c
index 7919a4d..aba0349 100644
--- a/py/objstr.c
+++ b/py/objstr.c
@@ -133,11 +133,11 @@
 }
 
 mp_obj_t mp_obj_str_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
-#if MICROPY_CPYTHON_COMPAT
+    #if MICROPY_CPYTHON_COMPAT
     if (n_kw != 0) {
         mp_arg_error_unimpl_kw();
     }
-#endif
+    #endif
 
     mp_arg_check_num(n_args, n_kw, 0, 3, false);
 
@@ -168,7 +168,7 @@
                 #endif
 
                 // Check if a qstr with this data already exists
-                qstr q = qstr_find_strn((const char*)str_data, str_len);
+                qstr q = qstr_find_strn((const char *)str_data, str_len);
                 if (q != MP_QSTRnull) {
                     return MP_OBJ_NEW_QSTR(q);
                 }
@@ -412,7 +412,7 @@
 #if !MICROPY_PY_BUILTINS_STR_UNICODE
 // objstrunicode defines own version
 const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, size_t self_len,
-                             mp_obj_t index, bool is_slice) {
+    mp_obj_t index, bool is_slice) {
     size_t index_val = mp_get_index(type, self_len, index, is_slice);
     return self_data + index_val;
 }
@@ -424,7 +424,7 @@
     GET_STR_DATA_LEN(self_in, self_data, self_len);
     if (value == MP_OBJ_SENTINEL) {
         // load
-#if MICROPY_PY_BUILTINS_SLICE
+        #if MICROPY_PY_BUILTINS_SLICE
         if (mp_obj_is_type(index, &mp_type_slice)) {
             mp_bound_slice_t slice;
             if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
@@ -432,13 +432,13 @@
             }
             return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
         }
-#endif
+        #endif
         size_t index_val = mp_get_index(type, self_len, index, false);
         // If we have unicode enabled the type will always be bytes, so take the short cut.
         if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
             return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
         } else {
-            return mp_obj_new_str_via_qstr((char*)&self_data[index_val], 1);
+            return mp_obj_new_str_via_qstr((char *)&self_data[index_val], 1);
         }
     } else {
         return MP_OBJ_NULL; // op not supported
@@ -480,7 +480,7 @@
     // make joined string
     vstr_t vstr;
     vstr_init_len(&vstr, required_len);
-    byte *data = (byte*)vstr.buf;
+    byte *data = (byte *)vstr.buf;
     for (size_t i = 0; i < seq_len; i++) {
         if (i > 0) {
             memcpy(data, sep_str, sep_len);
@@ -515,15 +515,21 @@
         // sep not given, so separate on whitespace
 
         // Initial whitespace is not counted as split, so we pre-do it
-        while (s < top && unichar_isspace(*s)) s++;
+        while (s < top && unichar_isspace(*s)) {
+            s++;
+        }
         while (s < top && splits != 0) {
             const byte *start = s;
-            while (s < top && !unichar_isspace(*s)) s++;
+            while (s < top && !unichar_isspace(*s)) {
+                s++;
+            }
             mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
             if (s >= top) {
                 break;
             }
-            while (s < top && unichar_isspace(*s)) s++;
+            while (s < top && unichar_isspace(*s)) {
+                s++;
+            }
             if (splits > 0) {
                 splits--;
             }
@@ -915,19 +921,19 @@
 
 STATIC bool arg_looks_numeric(mp_obj_t arg) {
     return arg_looks_integer(arg)
-#if MICROPY_PY_BUILTINS_FLOAT
-        || mp_obj_is_float(arg)
-#endif
+           #if MICROPY_PY_BUILTINS_FLOAT
+           || mp_obj_is_float(arg)
+           #endif
     ;
 }
 
 #if MICROPY_PY_BUILTINS_STR_OP_MODULO
 STATIC mp_obj_t arg_as_int(mp_obj_t arg) {
-#if MICROPY_PY_BUILTINS_FLOAT
+    #if MICROPY_PY_BUILTINS_FLOAT
     if (mp_obj_is_float(arg)) {
         return mp_obj_new_int_from_float(mp_obj_float_get(arg));
     }
-#endif
+    #endif
     return arg;
 }
 #endif
@@ -1065,7 +1071,8 @@
                 *arg_i = -1;
             } else {
                 const char *lookup;
-                for (lookup = field_name; lookup < field_name_top && *lookup != '.' && *lookup != '['; lookup++);
+                for (lookup = field_name; lookup < field_name_top && *lookup != '.' && *lookup != '['; lookup++) {;
+                }
                 mp_obj_t field_q = mp_obj_new_str_via_qstr(field_name, lookup - field_name); // should it be via qstr?
                 field_name = lookup;
                 mp_map_elem_t *key_elem = mp_map_lookup(kwargs, field_q, MP_MAP_LOOKUP);
@@ -1210,9 +1217,15 @@
         }
 
         switch (align) {
-            case '<': flags |= PF_FLAG_LEFT_ADJUST;     break;
-            case '=': flags |= PF_FLAG_PAD_AFTER_SIGN;  break;
-            case '^': flags |= PF_FLAG_CENTER_ADJUST;   break;
+            case '<':
+                flags |= PF_FLAG_LEFT_ADJUST;
+                break;
+            case '=':
+                flags |= PF_FLAG_PAD_AFTER_SIGN;
+                break;
+            case '^':
+                flags |= PF_FLAG_CENTER_ADJUST;
+                break;
         }
 
         if (arg_looks_integer(arg)) {
@@ -1221,8 +1234,7 @@
                     mp_print_mp_int(&print, arg, 2, 'a', flags, fill, width, 0);
                     continue;
 
-                case 'c':
-                {
+                case 'c': {
                     char ch = mp_obj_get_int(arg);
                     mp_print_strn(&print, &ch, 1, flags, fill, width);
                     continue;
@@ -1308,7 +1320,7 @@
             }
 
             switch (type) {
-#if MICROPY_PY_BUILTINS_FLOAT
+                #if MICROPY_PY_BUILTINS_FLOAT
                 case 'e':
                 case 'E':
                 case 'f':
@@ -1326,9 +1338,9 @@
                     #define F100 100.0
                     #endif
                     mp_print_float(&print, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision);
-                    #undef F100
+#undef F100
                     break;
-#endif
+                #endif
 
                 default:
                     if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
@@ -1386,7 +1398,7 @@
 
     GET_STR_DATA_LEN(args[0], str, len);
     int arg_i = 0;
-    vstr_t vstr = mp_obj_str_format_helper((const char*)str, (const char*)str + len, &arg_i, n_args, args, kwargs);
+    vstr_t vstr = mp_obj_str_format_helper((const char *)str, (const char *)str + len, &arg_i, n_args, args, kwargs);
     return mp_obj_new_str_from_vstr(mp_obj_get_type(args[0]), &vstr);
 }
 MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format);
@@ -1434,7 +1446,7 @@
                 }
                 ++str;
             }
-            mp_obj_t k_obj = mp_obj_new_str_via_qstr((const char*)key, str - key);
+            mp_obj_t k_obj = mp_obj_new_str_via_qstr((const char *)key, str - key);
             arg = mp_obj_dict_get(dict, k_obj);
             str++;
         }
@@ -1443,14 +1455,20 @@
         char fill = ' ';
         int alt = 0;
         while (str < top) {
-            if (*str == '-')      flags |= PF_FLAG_LEFT_ADJUST;
-            else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
-            else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
-            else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
-            else if (*str == '0') {
+            if (*str == '-') {
+                flags |= PF_FLAG_LEFT_ADJUST;
+            } else if (*str == '+') {
+                flags |= PF_FLAG_SHOW_SIGN;
+            } else if (*str == ' ') {
+                flags |= PF_FLAG_SPACE_SIGN;
+            } else if (*str == '#') {
+                alt = PF_FLAG_SHOW_PREFIX;
+            } else if (*str == '0') {
                 flags |= PF_FLAG_PAD_AFTER_SIGN;
                 fill = '0';
-            } else break;
+            } else {
+                break;
+            }
             str++;
         }
         // parse width, if it exists
@@ -1463,7 +1481,7 @@
                 width = mp_obj_get_int(args[arg_i++]);
                 str++;
             } else {
-                str = (const byte*)str_to_int((const char*)str, (const char*)top, &width);
+                str = (const byte *)str_to_int((const char *)str, (const char *)top, &width);
             }
         }
         int prec = -1;
@@ -1477,13 +1495,13 @@
                     str++;
                 } else {
                     prec = 0;
-                    str = (const byte*)str_to_int((const char*)str, (const char*)top, &prec);
+                    str = (const byte *)str_to_int((const char *)str, (const char *)top, &prec);
                 }
             }
         }
 
         if (str >= top) {
-incomplete_format:
+        incomplete_format:
             if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
                 terse_str_format_value_error();
             } else {
@@ -1494,7 +1512,7 @@
         // Tuple value lookup
         if (arg == MP_OBJ_NULL) {
             if (arg_i >= n_args) {
-not_enough_args:
+            not_enough_args:
                 mp_raise_TypeError("format string needs more arguments");
             }
             arg = args[arg_i++];
@@ -1522,7 +1540,7 @@
                 mp_print_mp_int(&print, arg_as_int(arg), 10, 'a', flags, fill, width, prec);
                 break;
 
-#if MICROPY_PY_BUILTINS_FLOAT
+            #if MICROPY_PY_BUILTINS_FLOAT
             case 'e':
             case 'E':
             case 'f':
@@ -1531,7 +1549,7 @@
             case 'G':
                 mp_print_float(&print, mp_obj_get_float(arg), *str, flags, fill, width, prec);
                 break;
-#endif
+            #endif
 
             case 'o':
                 if (alt) {
@@ -1541,8 +1559,7 @@
                 break;
 
             case 'r':
-            case 's':
-            {
+            case 's': {
                 vstr_t arg_vstr;
                 mp_print_t arg_print;
                 vstr_init_print(&arg_vstr, 16, &arg_print);
@@ -1684,7 +1701,7 @@
             } else {
                 // substr found, allocate new string
                 vstr_init_len(&vstr, replaced_str_index);
-                data = (byte*)vstr.buf;
+                data = (byte *)vstr.buf;
                 assert(data != NULL);
             }
         } else {
@@ -1799,7 +1816,7 @@
     GET_STR_DATA_LEN(self_in, self_data, self_len);
     vstr_t vstr;
     vstr_init_len(&vstr, self_len);
-    byte *data = (byte*)vstr.buf;
+    byte *data = (byte *)vstr.buf;
     for (size_t i = 0; i < self_len; i++) {
         *data++ = op(*self_data++);
     }
@@ -1907,7 +1924,7 @@
 mp_int_t mp_obj_str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) {
     if (flags == MP_BUFFER_READ) {
         GET_STR_DATA_LEN(self_in, str_data, str_len);
-        bufinfo->buf = (void*)str_data;
+        bufinfo->buf = (void *)str_data;
         bufinfo->len = str_len;
         bufinfo->typecode = 'B'; // bytes should be unsigned, so should unicode byte-access
         return 0;
@@ -1918,7 +1935,7 @@
 }
 
 STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = {
-#if MICROPY_CPYTHON_COMPAT
+    #if MICROPY_CPYTHON_COMPAT
     { MP_ROM_QSTR(MP_QSTR_decode), MP_ROM_PTR(&bytes_decode_obj) },
     #if !MICROPY_PY_BUILTINS_STR_UNICODE
     // If we have separate unicode type, then here we have methods only
@@ -1928,7 +1945,7 @@
     // methods (which should do type checking at runtime).
     { MP_ROM_QSTR(MP_QSTR_encode), MP_ROM_PTR(&str_encode_obj) },
     #endif
-#endif
+    #endif
     { MP_ROM_QSTR(MP_QSTR_find), MP_ROM_PTR(&str_find_obj) },
     { MP_ROM_QSTR(MP_QSTR_rfind), MP_ROM_PTR(&str_rfind_obj) },
     { MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&str_index_obj) },
@@ -1979,7 +1996,7 @@
     .subscr = bytes_subscr,
     .getiter = mp_obj_new_str_iterator,
     .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
-    .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&str8_locals_dict,
 };
 #endif
 
@@ -1993,16 +2010,16 @@
     .subscr = bytes_subscr,
     .getiter = mp_obj_new_bytes_iterator,
     .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
-    .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&str8_locals_dict,
 };
 
 // The zero-length bytes object, with data that includes a null-terminating byte
-const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, (const byte*)""};
+const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, (const byte *)""};
 
 // Create a str/bytes object using the given data.  New memory is allocated and
 // the data is copied across.  This function should only be used if the type is bytes,
 // or if the type is str and the string data is known to be not interned.
-mp_obj_t mp_obj_new_str_copy(const mp_obj_type_t *type, const byte* data, size_t len) {
+mp_obj_t mp_obj_new_str_copy(const mp_obj_type_t *type, const byte *data, size_t len) {
     mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
     o->base.type = type;
     o->len = len;
@@ -2019,16 +2036,16 @@
 // Create a str/bytes object using the given data.  If the type is str and the string
 // data is already interned, then a qstr object is returned.  Otherwise new memory is
 // allocated for the object and the data is copied across.
-mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte* data, size_t len) {
+mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte *data, size_t len) {
     if (type == &mp_type_str) {
-        return mp_obj_new_str((const char*)data, len);
+        return mp_obj_new_str((const char *)data, len);
     } else {
         return mp_obj_new_bytes(data, len);
     }
 }
 
 // Create a str using a qstr to store the data; may use existing or new qstr.
-mp_obj_t mp_obj_new_str_via_qstr(const char* data, size_t len) {
+mp_obj_t mp_obj_new_str_via_qstr(const char *data, size_t len) {
     return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
 }
 
@@ -2050,41 +2067,41 @@
     mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
     o->base.type = type;
     o->len = vstr->len;
-    o->hash = qstr_compute_hash((byte*)vstr->buf, vstr->len);
+    o->hash = qstr_compute_hash((byte *)vstr->buf, vstr->len);
     if (vstr->len + 1 == vstr->alloc) {
-        o->data = (byte*)vstr->buf;
+        o->data = (byte *)vstr->buf;
     } else {
-        o->data = (byte*)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1);
+        o->data = (byte *)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1);
     }
-    ((byte*)o->data)[o->len] = '\0'; // add null byte
+    ((byte *)o->data)[o->len] = '\0'; // add null byte
     vstr->buf = NULL;
     vstr->alloc = 0;
     return MP_OBJ_FROM_PTR(o);
 }
 
-mp_obj_t mp_obj_new_str(const char* data, size_t len) {
+mp_obj_t mp_obj_new_str(const char *data, size_t len) {
     qstr q = qstr_find_strn(data, len);
     if (q != MP_QSTRnull) {
         // qstr with this data already exists
         return MP_OBJ_NEW_QSTR(q);
     } else {
         // no existing qstr, don't make one
-        return mp_obj_new_str_copy(&mp_type_str, (const byte*)data, len);
+        return mp_obj_new_str_copy(&mp_type_str, (const byte *)data, len);
     }
 }
 
 mp_obj_t mp_obj_str_intern(mp_obj_t str) {
     GET_STR_DATA_LEN(str, data, len);
-    return mp_obj_new_str_via_qstr((const char*)data, len);
+    return mp_obj_new_str_via_qstr((const char *)data, len);
 }
 
 mp_obj_t mp_obj_str_intern_checked(mp_obj_t obj) {
     size_t len;
     const char *data = mp_obj_str_get_data(obj, &len);
-    return mp_obj_new_str_via_qstr((const char*)data, len);
+    return mp_obj_new_str_via_qstr((const char *)data, len);
 }
 
-mp_obj_t mp_obj_new_bytes(const byte* data, size_t len) {
+mp_obj_t mp_obj_new_bytes(const byte *data, size_t len) {
     return mp_obj_new_str_copy(&mp_type_bytes, data, len);
 }
 
@@ -2125,7 +2142,7 @@
         return MP_OBJ_QSTR_VALUE(self_in);
     } else if (mp_obj_is_type(self_in, &mp_type_str)) {
         mp_obj_str_t *self = MP_OBJ_TO_PTR(self_in);
-        return qstr_from_strn((char*)self->data, self->len);
+        return qstr_from_strn((char *)self->data, self->len);
     } else {
         bad_implicit_conversion(self_in);
     }
@@ -2137,7 +2154,7 @@
     if (mp_obj_is_str_or_bytes(self_in)) {
         GET_STR_DATA_LEN(self_in, s, l);
         (void)l; // len unused
-        return (const char*)s;
+        return (const char *)s;
     } else {
         bad_implicit_conversion(self_in);
     }
@@ -2147,7 +2164,7 @@
     if (mp_obj_is_str_or_bytes(self_in)) {
         GET_STR_DATA_LEN(self_in, s, l);
         *len = l;
-        return (const char*)s;
+        return (const char *)s;
     } else {
         bad_implicit_conversion(self_in);
     }
@@ -2158,8 +2175,8 @@
     if (mp_obj_is_qstr(self_in)) {
         return qstr_data(MP_OBJ_QSTR_VALUE(self_in), len);
     } else {
-        *len = ((mp_obj_str_t*)MP_OBJ_TO_PTR(self_in))->len;
-        return ((mp_obj_str_t*)MP_OBJ_TO_PTR(self_in))->data;
+        *len = ((mp_obj_str_t *)MP_OBJ_TO_PTR(self_in))->len;
+        return ((mp_obj_str_t *)MP_OBJ_TO_PTR(self_in))->data;
     }
 }
 #endif
@@ -2179,7 +2196,7 @@
     mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
     GET_STR_DATA_LEN(self->str, str, len);
     if (self->cur < len) {
-        mp_obj_t o_out = mp_obj_new_str_via_qstr((const char*)str + self->cur, 1);
+        mp_obj_t o_out = mp_obj_new_str_via_qstr((const char *)str + self->cur, 1);
         self->cur += 1;
         return o_out;
     } else {
@@ -2189,7 +2206,7 @@
 
 STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) {
     assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t));
-    mp_obj_str8_it_t *o = (mp_obj_str8_it_t*)iter_buf;
+    mp_obj_str8_it_t *o = (mp_obj_str8_it_t *)iter_buf;
     o->base.type = &mp_type_polymorph_iter;
     o->iternext = str_it_iternext;
     o->str = str;
@@ -2212,7 +2229,7 @@
 
 mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) {
     assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t));
-    mp_obj_str8_it_t *o = (mp_obj_str8_it_t*)iter_buf;
+    mp_obj_str8_it_t *o = (mp_obj_str8_it_t *)iter_buf;
     o->base.type = &mp_type_polymorph_iter;
     o->iternext = bytes_it_iternext;
     o->str = str;
diff --git a/py/objstr.h b/py/objstr.h
index ba300cc..8c450ba 100644
--- a/py/objstr.h
+++ b/py/objstr.h
@@ -36,18 +36,18 @@
     const byte *data;
 } mp_obj_str_t;
 
-#define MP_DEFINE_STR_OBJ(obj_name, str) mp_obj_str_t obj_name = {{&mp_type_str}, 0, sizeof(str) - 1, (const byte*)str}
+#define MP_DEFINE_STR_OBJ(obj_name, str) mp_obj_str_t obj_name = {{&mp_type_str}, 0, sizeof(str) - 1, (const byte *)str}
 
 // use this macro to extract the string hash
 // warning: the hash can be 0, meaning invalid, and must then be explicitly computed from the data
 #define GET_STR_HASH(str_obj_in, str_hash) \
     mp_uint_t str_hash; if (mp_obj_is_qstr(str_obj_in)) \
-    { str_hash = qstr_hash(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_hash = ((mp_obj_str_t*)MP_OBJ_TO_PTR(str_obj_in))->hash; }
+    { str_hash = qstr_hash(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_hash = ((mp_obj_str_t *)MP_OBJ_TO_PTR(str_obj_in))->hash; }
 
 // use this macro to extract the string length
 #define GET_STR_LEN(str_obj_in, str_len) \
     size_t str_len; if (mp_obj_is_qstr(str_obj_in)) \
-    { str_len = qstr_len(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_len = ((mp_obj_str_t*)MP_OBJ_TO_PTR(str_obj_in))->len; }
+    { str_len = qstr_len(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_len = ((mp_obj_str_t *)MP_OBJ_TO_PTR(str_obj_in))->len; }
 
 // use this macro to extract the string data and length
 #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
@@ -58,21 +58,21 @@
 #define GET_STR_DATA_LEN(str_obj_in, str_data, str_len) \
     const byte *str_data; size_t str_len; if (mp_obj_is_qstr(str_obj_in)) \
     { str_data = qstr_data(MP_OBJ_QSTR_VALUE(str_obj_in), &str_len); } \
-    else { str_len = ((mp_obj_str_t*)MP_OBJ_TO_PTR(str_obj_in))->len; str_data = ((mp_obj_str_t*)MP_OBJ_TO_PTR(str_obj_in))->data; }
+    else { str_len = ((mp_obj_str_t *)MP_OBJ_TO_PTR(str_obj_in))->len; str_data = ((mp_obj_str_t *)MP_OBJ_TO_PTR(str_obj_in))->data; }
 #endif
 
 mp_obj_t mp_obj_str_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args);
 void mp_str_print_json(const mp_print_t *print, const byte *str_data, size_t str_len);
 mp_obj_t mp_obj_str_format(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs);
 mp_obj_t mp_obj_str_split(size_t n_args, const mp_obj_t *args);
-mp_obj_t mp_obj_new_str_copy(const mp_obj_type_t *type, const byte* data, size_t len);
-mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte* data, size_t len);
+mp_obj_t mp_obj_new_str_copy(const mp_obj_type_t *type, const byte *data, size_t len);
+mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte *data, size_t len);
 
 mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in);
 mp_int_t mp_obj_str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags);
 
 const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, size_t self_len,
-                             mp_obj_t index, bool is_slice);
+    mp_obj_t index, bool is_slice);
 const byte *find_subbytes(const byte *haystack, size_t hlen, const byte *needle, size_t nlen, int direction);
 
 MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj);
diff --git a/py/objstringio.c b/py/objstringio.c
index cca4a81..98808e3 100644
--- a/py/objstringio.c
+++ b/py/objstringio.c
@@ -114,7 +114,7 @@
     mp_obj_stringio_t *o = MP_OBJ_TO_PTR(o_in);
     switch (request) {
         case MP_STREAM_SEEK: {
-            struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)arg;
+            struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)arg;
             mp_uint_t ref = 0;
             switch (s->whence) {
                 case MP_SEEK_CUR:
@@ -166,7 +166,7 @@
     mp_obj_stringio_t *self = MP_OBJ_TO_PTR(self_in);
     check_stringio_is_open(self);
     // TODO: Try to avoid copying string
-    return mp_obj_new_str_of_type(STREAM_TO_CONTENT_TYPE(self), (byte*)self->vstr->buf, self->vstr->len);
+    return mp_obj_new_str_of_type(STREAM_TO_CONTENT_TYPE(self), (byte *)self->vstr->buf, self->vstr->len);
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_1(stringio_getvalue_obj, stringio_getvalue);
 
@@ -252,7 +252,7 @@
     .getiter = mp_identity_getiter,
     .iternext = mp_stream_unbuffered_iter,
     .protocol = &stringio_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&stringio_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&stringio_locals_dict,
 };
 
 #if MICROPY_PY_IO_BYTESIO
@@ -270,7 +270,7 @@
     .getiter = mp_identity_getiter,
     .iternext = mp_stream_unbuffered_iter,
     .protocol = &bytesio_stream_p,
-    .locals_dict = (mp_obj_dict_t*)&stringio_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&stringio_locals_dict,
 };
 #endif
 
diff --git a/py/objstrunicode.c b/py/objstrunicode.c
index c9bd6ee..defcbe4 100644
--- a/py/objstrunicode.c
+++ b/py/objstrunicode.c
@@ -113,7 +113,7 @@
 // Convert an index into a pointer to its lead byte. Out of bounds indexing will raise IndexError or
 // be capped to the first/last character of the string, depending on is_slice.
 const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, size_t self_len,
-                             mp_obj_t index, bool is_slice) {
+    mp_obj_t index, bool is_slice) {
     // All str functions also handle bytes objects, and they call str_index_to_ptr(),
     // so it must handle bytes.
     if (type == &mp_type_bytes) {
@@ -132,8 +132,7 @@
         mp_raise_msg_varg(&mp_type_TypeError, "string indices must be integers, not %s", mp_obj_get_type_str(index));
     }
     const byte *s, *top = self_data + self_len;
-    if (i < 0)
-    {
+    if (i < 0) {
         // Negative indexing is performed by counting from the end of the string.
         for (s = top - 1; i; --s) {
             if (s < self_data) {
@@ -181,7 +180,7 @@
     GET_STR_DATA_LEN(self_in, self_data, self_len);
     if (value == MP_OBJ_SENTINEL) {
         // load
-#if MICROPY_PY_BUILTINS_SLICE
+        #if MICROPY_PY_BUILTINS_SLICE
         if (mp_obj_is_type(index, &mp_type_slice)) {
             mp_obj_t ostart, ostop, ostep;
             mp_obj_slice_t *slice = MP_OBJ_TO_PTR(index);
@@ -211,7 +210,7 @@
             }
             return mp_obj_new_str_of_type(type, (const byte *)pstart, pstop - pstart);
         }
-#endif
+        #endif
         const byte *s = str_index_to_ptr(type, self_data, self_len, index, false);
         int len = 1;
         if (UTF8_IS_NONASCII(*s)) {
@@ -220,16 +219,16 @@
                 ++len;
             }
         }
-        return mp_obj_new_str_via_qstr((const char*)s, len); // This will create a one-character string
+        return mp_obj_new_str_via_qstr((const char *)s, len); // This will create a one-character string
     } else {
         return MP_OBJ_NULL; // op not supported
     }
 }
 
 STATIC const mp_rom_map_elem_t struni_locals_dict_table[] = {
-#if MICROPY_CPYTHON_COMPAT
+    #if MICROPY_CPYTHON_COMPAT
     { MP_ROM_QSTR(MP_QSTR_encode), MP_ROM_PTR(&str_encode_obj) },
-#endif
+    #endif
     { MP_ROM_QSTR(MP_QSTR_find), MP_ROM_PTR(&str_find_obj) },
     { MP_ROM_QSTR(MP_QSTR_rfind), MP_ROM_PTR(&str_rfind_obj) },
     { MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&str_index_obj) },
@@ -278,7 +277,7 @@
     .subscr = str_subscr,
     .getiter = mp_obj_new_str_iterator,
     .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
-    .locals_dict = (mp_obj_dict_t*)&struni_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&struni_locals_dict,
 };
 
 /******************************************************************************/
@@ -297,7 +296,7 @@
     if (self->cur < len) {
         const byte *cur = str + self->cur;
         const byte *end = utf8_next_char(str + self->cur);
-        mp_obj_t o_out = mp_obj_new_str_via_qstr((const char*)cur, end - cur);
+        mp_obj_t o_out = mp_obj_new_str_via_qstr((const char *)cur, end - cur);
         self->cur += end - cur;
         return o_out;
     } else {
@@ -307,7 +306,7 @@
 
 STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) {
     assert(sizeof(mp_obj_str_it_t) <= sizeof(mp_obj_iter_buf_t));
-    mp_obj_str_it_t *o = (mp_obj_str_it_t*)iter_buf;
+    mp_obj_str_it_t *o = (mp_obj_str_it_t *)iter_buf;
     o->base.type = &mp_type_polymorph_iter;
     o->iternext = str_it_iternext;
     o->str = str;
diff --git a/py/objtuple.c b/py/objtuple.c
index e3f37eb..77e70a1 100644
--- a/py/objtuple.c
+++ b/py/objtuple.c
@@ -122,7 +122,8 @@
 mp_obj_t mp_obj_tuple_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
     mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in);
     switch (op) {
-        case MP_UNARY_OP_BOOL: return mp_obj_new_bool(self->len != 0);
+        case MP_UNARY_OP_BOOL:
+            return mp_obj_new_bool(self->len != 0);
         case MP_UNARY_OP_HASH: {
             // start hash with pointer to empty tuple, to make it fairly unique
             mp_int_t hash = (mp_int_t)mp_const_empty_tuple;
@@ -131,8 +132,10 @@
             }
             return MP_OBJ_NEW_SMALL_INT(hash);
         }
-        case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(self->len);
-        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
     }
 }
 
@@ -178,7 +181,7 @@
     if (value == MP_OBJ_SENTINEL) {
         // load
         mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in);
-#if MICROPY_PY_BUILTINS_SLICE
+        #if MICROPY_PY_BUILTINS_SLICE
         if (mp_obj_is_type(index, &mp_type_slice)) {
             mp_bound_slice_t slice;
             if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice)) {
@@ -188,7 +191,7 @@
             mp_seq_copy(res->items, self->items + slice.start, res->len, mp_obj_t);
             return MP_OBJ_FROM_PTR(res);
         }
-#endif
+        #endif
         size_t index_value = mp_get_index(self->base.type, self->len, index, false);
         return self->items[index_value];
     } else {
@@ -226,7 +229,7 @@
     .binary_op = mp_obj_tuple_binary_op,
     .subscr = mp_obj_tuple_subscr,
     .getiter = mp_obj_tuple_getiter,
-    .locals_dict = (mp_obj_dict_t*)&tuple_locals_dict,
+    .locals_dict = (mp_obj_dict_t *)&tuple_locals_dict,
 };
 
 // the zero-length tuple
@@ -283,7 +286,7 @@
 
 mp_obj_t mp_obj_tuple_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf) {
     assert(sizeof(mp_obj_tuple_it_t) <= sizeof(mp_obj_iter_buf_t));
-    mp_obj_tuple_it_t *o = (mp_obj_tuple_it_t*)iter_buf;
+    mp_obj_tuple_it_t *o = (mp_obj_tuple_it_t *)iter_buf;
     o->base.type = &mp_type_polymorph_iter;
     o->iternext = tuple_it_iternext;
     o->tuple = MP_OBJ_TO_PTR(o_in);
diff --git a/py/objtuple.h b/py/objtuple.h
index 74cde88..cc42aa6 100644
--- a/py/objtuple.h
+++ b/py/objtuple.h
@@ -52,7 +52,7 @@
     const mp_rom_obj_tuple_t tuple_obj_name = { \
         .base = {&mp_type_attrtuple}, \
         .len = nitems, \
-        .items = { __VA_ARGS__ , MP_ROM_PTR((void*)fields) } \
+        .items = { __VA_ARGS__, MP_ROM_PTR((void *)fields) } \
     }
 
 #if MICROPY_PY_COLLECTIONS
diff --git a/py/objtype.c b/py/objtype.c
index 206e80f..0f49ad2 100644
--- a/py/objtype.c
+++ b/py/objtype.c
@@ -42,7 +42,7 @@
 #endif
 
 #define ENABLE_SPECIAL_ACCESSORS \
-    (MICROPY_PY_DESCRIPTORS  || MICROPY_PY_DELATTR_SETATTR || MICROPY_PY_BUILTINS_PROPERTY)
+    (MICROPY_PY_DESCRIPTORS || MICROPY_PY_DELATTR_SETATTR || MICROPY_PY_BUILTINS_PROPERTY)
 
 STATIC mp_obj_t static_class_method_make_new(const mp_obj_type_t *self_in, size_t n_args, size_t n_kw, const mp_obj_t *args);
 
@@ -63,7 +63,7 @@
             // No parents so end search here.
             return count;
         #if MICROPY_MULTIPLE_INHERITANCE
-        } else if (((mp_obj_base_t*)type->parent)->type == &mp_type_tuple) {
+        } else if (((mp_obj_base_t *)type->parent)->type == &mp_type_tuple) {
             // Multiple parents, search through them all recursively.
             const mp_obj_tuple_t *parent_tuple = type->parent;
             const mp_obj_t *item = parent_tuple->items;
@@ -133,7 +133,7 @@
     bool is_type;
 };
 
-STATIC void mp_obj_class_lookup(struct class_lookup_data  *lookup, const mp_obj_type_t *type) {
+STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_type_t *type) {
     assert(lookup->dest[0] == MP_OBJ_NULL);
     assert(lookup->dest[1] == MP_OBJ_NULL);
     for (;;) {
@@ -143,7 +143,7 @@
         // this should not be applied to class types, as will result in extra
         // lookup either.
         if (lookup->meth_offset != 0 && mp_obj_is_native_type(type)) {
-            if (*(void**)((char*)type + lookup->meth_offset) != NULL) {
+            if (*(void **)((char *)type + lookup->meth_offset) != NULL) {
                 DEBUG_printf("mp_obj_class_lookup: Matched special meth slot (off=%d) for %s\n",
                     lookup->meth_offset, qstr_str(lookup->attr));
                 lookup->dest[0] = MP_OBJ_SENTINEL;
@@ -160,7 +160,7 @@
                 if (lookup->is_type) {
                     // If we look up a class method, we need to return original type for which we
                     // do a lookup, not a (base) type in which we found the class method.
-                    const mp_obj_type_t *org_type = (const mp_obj_type_t*)lookup->obj;
+                    const mp_obj_type_t *org_type = (const mp_obj_type_t *)lookup->obj;
                     mp_convert_member_lookup(MP_OBJ_NULL, org_type, elem->value, lookup->dest);
                 } else {
                     mp_obj_instance_t *obj = lookup->obj;
@@ -173,7 +173,7 @@
                     }
                     mp_convert_member_lookup(obj_obj, type, elem->value, lookup->dest);
                 }
-#if DEBUG_PRINT
+                #if DEBUG_PRINT
                 DEBUG_printf("mp_obj_class_lookup: Returning: ");
                 mp_obj_print_helper(MICROPY_DEBUG_PRINTER, lookup->dest[0], PRINT_REPR);
                 if (lookup->dest[1] != MP_OBJ_NULL) {
@@ -181,7 +181,7 @@
                     DEBUG_printf(" <%s @%p>", mp_obj_get_type_str(lookup->dest[1]), MP_OBJ_TO_PTR(lookup->dest[1]));
                 }
                 DEBUG_printf("\n");
-#endif
+                #endif
                 return;
             }
         }
@@ -202,13 +202,13 @@
             DEBUG_printf("mp_obj_class_lookup: No more parents\n");
             return;
         #if MICROPY_MULTIPLE_INHERITANCE
-        } else if (((mp_obj_base_t*)type->parent)->type == &mp_type_tuple) {
+        } else if (((mp_obj_base_t *)type->parent)->type == &mp_type_tuple) {
             const mp_obj_tuple_t *parent_tuple = type->parent;
             const mp_obj_t *item = parent_tuple->items;
             const mp_obj_t *top = item + parent_tuple->len - 1;
             for (; item < top; ++item) {
                 assert(mp_obj_is_type(*item, &mp_type_type));
-                mp_obj_type_t *bt = (mp_obj_type_t*)MP_OBJ_TO_PTR(*item);
+                mp_obj_type_t *bt = (mp_obj_type_t *)MP_OBJ_TO_PTR(*item);
                 if (bt == &mp_type_object) {
                     // Not a "real" type
                     continue;
@@ -221,7 +221,7 @@
 
             // search last base (simple tail recursion elimination)
             assert(mp_obj_is_type(*item, &mp_type_type));
-            type = (mp_obj_type_t*)MP_OBJ_TO_PTR(*item);
+            type = (mp_obj_type_t *)MP_OBJ_TO_PTR(*item);
         #endif
         } else {
             type = type->parent;
@@ -586,7 +586,7 @@
         dest[0] = elem->value;
         return;
     }
-#if MICROPY_CPYTHON_COMPAT
+    #if MICROPY_CPYTHON_COMPAT
     if (attr == MP_QSTR___dict__) {
         // Create a new dict with a copy of the instance's map items.
         // This creates, unlike CPython, a 'read-only' __dict__: modifying
@@ -601,7 +601,7 @@
         dest[0] = attr_dict;
         return;
     }
-#endif
+    #endif
     struct class_lookup_data lookup = {
         .obj = self,
         .attr = attr,
@@ -1031,7 +1031,7 @@
         }
         #endif
         struct class_lookup_data lookup = {
-            .obj = (mp_obj_instance_t*)self,
+            .obj = (mp_obj_instance_t *)self,
             .attr = attr,
             .meth_offset = 0,
             .dest = dest,
@@ -1146,7 +1146,7 @@
         // abstract base class which would translate C-level protocol to
         // Python method calls, and any subclass inheriting from it will
         // support this feature.
-        o->protocol = ((mp_obj_type_t*)MP_OBJ_TO_PTR(bases_items[0]))->protocol;
+        o->protocol = ((mp_obj_type_t *)MP_OBJ_TO_PTR(bases_items[0]))->protocol;
 
         if (bases_len >= 2) {
             #if MICROPY_MULTIPLE_INHERITANCE
@@ -1223,7 +1223,7 @@
         mp_raise_TypeError(NULL);
     }
     mp_obj_super_t *o = m_new_obj(mp_obj_super_t);
-    *o = (mp_obj_super_t){{type_in}, args[0], args[1]};
+    *o = (mp_obj_super_t) {{type_in}, args[0], args[1]};
     return MP_OBJ_FROM_PTR(o);
 }
 
@@ -1256,7 +1256,7 @@
     if (type->parent == NULL) {
         // no parents, do nothing
     #if MICROPY_MULTIPLE_INHERITANCE
-    } else if (((mp_obj_base_t*)type->parent)->type == &mp_type_tuple) {
+    } else if (((mp_obj_base_t *)type->parent)->type == &mp_type_tuple) {
         const mp_obj_tuple_t *parent_tuple = type->parent;
         size_t len = parent_tuple->len;
         const mp_obj_t *items = parent_tuple->items;
@@ -1267,7 +1267,7 @@
                 // and we don't want to lookup native methods in object.
                 continue;
             }
-            mp_obj_class_lookup(&lookup, (mp_obj_type_t*)MP_OBJ_TO_PTR(items[i]));
+            mp_obj_class_lookup(&lookup, (mp_obj_type_t *)MP_OBJ_TO_PTR(items[i]));
             if (dest[0] != MP_OBJ_NULL) {
                 break;
             }
@@ -1330,7 +1330,7 @@
             // type has no parents
             return false;
         #if MICROPY_MULTIPLE_INHERITANCE
-        } else if (((mp_obj_base_t*)self->parent)->type == &mp_type_tuple) {
+        } else if (((mp_obj_base_t *)self->parent)->type == &mp_type_tuple) {
             // get the base objects (they should be type objects)
             const mp_obj_tuple_t *parent_tuple = self->parent;
             const mp_obj_t *item = parent_tuple->items;
@@ -1397,7 +1397,7 @@
     } else if (!mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(self_type), native_type)) {
         return MP_OBJ_NULL;
     } else {
-        mp_obj_instance_t *self = (mp_obj_instance_t*)MP_OBJ_TO_PTR(self_in);
+        mp_obj_instance_t *self = (mp_obj_instance_t *)MP_OBJ_TO_PTR(self_in);
         return self->subobj[0];
     }
 }
@@ -1411,7 +1411,7 @@
     mp_arg_check_num(n_args, n_kw, 1, 1, false);
 
     mp_obj_static_class_method_t *o = m_new_obj(mp_obj_static_class_method_t);
-    *o = (mp_obj_static_class_method_t){{self}, args[0]};
+    *o = (mp_obj_static_class_method_t) {{self}, args[0]};
     return MP_OBJ_FROM_PTR(o);
 }
 
diff --git a/py/pairheap.c b/py/pairheap.c
index caa51bf..a1eecec 100644
--- a/py/pairheap.c
+++ b/py/pairheap.c
@@ -31,9 +31,9 @@
 //   - LSB set: the node is the last of the children and points to its parent node
 //   - other: the node is a child and not the last child
 // The macros below help manage this pointer.
-#define NEXT_MAKE_RIGHTMOST_PARENT(parent) ((void*)((uintptr_t)(parent) | 1))
+#define NEXT_MAKE_RIGHTMOST_PARENT(parent) ((void *)((uintptr_t)(parent) | 1))
 #define NEXT_IS_RIGHTMOST_PARENT(next) ((uintptr_t)(next) & 1)
-#define NEXT_GET_RIGHTMOST_PARENT(next) ((void*)((uintptr_t)(next) & ~1))
+#define NEXT_GET_RIGHTMOST_PARENT(next) ((void *)((uintptr_t)(next) & ~1))
 
 // O(1), stable
 mp_pairheap_t *mp_pairheap_meld(mp_pairheap_lt_t lt, mp_pairheap_t *heap1, mp_pairheap_t *heap2) {
diff --git a/py/pairheap.h b/py/pairheap.h
index f9517f2..8a9138b 100644
--- a/py/pairheap.h
+++ b/py/pairheap.h
@@ -50,7 +50,7 @@
 } mp_pairheap_t;
 
 // This is the function for the less-than operation on nodes/elements.
-typedef int (*mp_pairheap_lt_t)(mp_pairheap_t*, mp_pairheap_t*);
+typedef int (*mp_pairheap_lt_t)(mp_pairheap_t *, mp_pairheap_t *);
 
 // Core functions.
 mp_pairheap_t *mp_pairheap_meld(mp_pairheap_lt_t lt, mp_pairheap_t *heap1, mp_pairheap_t *heap2);
diff --git a/py/parse.c b/py/parse.c
index 1174f5d..8b68fd3 100644
--- a/py/parse.c
+++ b/py/parse.c
@@ -260,7 +260,7 @@
 
     if (chunk != NULL && chunk->union_.used + num_bytes > chunk->alloc) {
         // not enough room at end of previously allocated chunk so try to grow
-        mp_parse_chunk_t *new_data = (mp_parse_chunk_t*)m_renew_maybe(byte, chunk,
+        mp_parse_chunk_t *new_data = (mp_parse_chunk_t *)m_renew_maybe(byte, chunk,
             sizeof(mp_parse_chunk_t) + chunk->alloc,
             sizeof(mp_parse_chunk_t) + chunk->alloc + num_bytes, false);
         if (new_data == NULL) {
@@ -283,7 +283,7 @@
         if (alloc < num_bytes) {
             alloc = num_bytes;
         }
-        chunk = (mp_parse_chunk_t*)m_new(byte, sizeof(mp_parse_chunk_t) + alloc);
+        chunk = (mp_parse_chunk_t *)m_new(byte, sizeof(mp_parse_chunk_t) + alloc);
         chunk->alloc = alloc;
         chunk->union_.used = 0;
         parser->cur_chunk = chunk;
@@ -322,12 +322,12 @@
 
 bool mp_parse_node_is_const_false(mp_parse_node_t pn) {
     return MP_PARSE_NODE_IS_TOKEN_KIND(pn, MP_TOKEN_KW_FALSE)
-        || (MP_PARSE_NODE_IS_SMALL_INT(pn) && MP_PARSE_NODE_LEAF_SMALL_INT(pn) == 0);
+           || (MP_PARSE_NODE_IS_SMALL_INT(pn) && MP_PARSE_NODE_LEAF_SMALL_INT(pn) == 0);
 }
 
 bool mp_parse_node_is_const_true(mp_parse_node_t pn) {
     return MP_PARSE_NODE_IS_TOKEN_KIND(pn, MP_TOKEN_KW_TRUE)
-        || (MP_PARSE_NODE_IS_SMALL_INT(pn) && MP_PARSE_NODE_LEAF_SMALL_INT(pn) != 0);
+           || (MP_PARSE_NODE_IS_SMALL_INT(pn) && MP_PARSE_NODE_LEAF_SMALL_INT(pn) != 0);
 }
 
 bool mp_parse_node_get_int_maybe(mp_parse_node_t pn, mp_obj_t *o) {
@@ -335,7 +335,7 @@
         *o = MP_OBJ_NEW_SMALL_INT(MP_PARSE_NODE_LEAF_SMALL_INT(pn));
         return true;
     } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, RULE_const_object)) {
-        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
+        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
         #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
         // nodes are 32-bit pointers, but need to extract 64-bit object
         *o = (uint64_t)pns->nodes[0] | ((uint64_t)pns->nodes[1] << 32);
@@ -356,7 +356,7 @@
         *nodes = pn;
         return 1;
     } else {
-        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)(*pn);
+        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)(*pn);
         if (MP_PARSE_NODE_STRUCT_KIND(pns) != pn_kind) {
             *nodes = pn;
             return 1;
@@ -370,7 +370,7 @@
 #if MICROPY_DEBUG_PRINTERS
 void mp_parse_node_print(mp_parse_node_t pn, size_t indent) {
     if (MP_PARSE_NODE_IS_STRUCT(pn)) {
-        printf("[% 4d] ", (int)((mp_parse_node_struct_t*)pn)->source_line);
+        printf("[% 4d] ", (int)((mp_parse_node_struct_t *)pn)->source_line);
     } else {
         printf("       ");
     }
@@ -385,16 +385,23 @@
     } else if (MP_PARSE_NODE_IS_LEAF(pn)) {
         uintptr_t arg = MP_PARSE_NODE_LEAF_ARG(pn);
         switch (MP_PARSE_NODE_LEAF_KIND(pn)) {
-            case MP_PARSE_NODE_ID: printf("id(%s)\n", qstr_str(arg)); break;
-            case MP_PARSE_NODE_STRING: printf("str(%s)\n", qstr_str(arg)); break;
-            case MP_PARSE_NODE_BYTES: printf("bytes(%s)\n", qstr_str(arg)); break;
+            case MP_PARSE_NODE_ID:
+                printf("id(%s)\n", qstr_str(arg));
+                break;
+            case MP_PARSE_NODE_STRING:
+                printf("str(%s)\n", qstr_str(arg));
+                break;
+            case MP_PARSE_NODE_BYTES:
+                printf("bytes(%s)\n", qstr_str(arg));
+                break;
             default:
                 assert(MP_PARSE_NODE_LEAF_KIND(pn) == MP_PARSE_NODE_TOKEN);
-                printf("tok(%u)\n", (uint)arg); break;
+                printf("tok(%u)\n", (uint)arg);
+                break;
         }
     } else {
         // node must be a mp_parse_node_struct_t
-        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
+        mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
         if (MP_PARSE_NODE_STRUCT_KIND(pns) == RULE_const_object) {
             #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
             printf("literal const(%016llx)\n", (uint64_t)pns->nodes[0] | ((uint64_t)pns->nodes[1] << 32));
@@ -521,7 +528,7 @@
             // not interned, make a node holding a pointer to the string/bytes object
             mp_obj_t o = mp_obj_new_str_copy(
                 lex->tok_kind == MP_TOKEN_STRING ? &mp_type_str : &mp_type_bytes,
-                (const byte*)lex->vstr.buf, lex->vstr.len);
+                (const byte *)lex->vstr.buf, lex->vstr.len);
             pn = make_node_const_object(parser, lex->tok_line, o);
         }
     } else {
@@ -634,8 +641,8 @@
             arg0 = mp_binary_op(op, arg0, arg1);
         }
     } else if (rule_id == RULE_shift_expr
-        || rule_id == RULE_arith_expr
-        || rule_id == RULE_term) {
+               || rule_id == RULE_arith_expr
+               || rule_id == RULE_term) {
         // folding for binary ops: << >> + - * @ / % //
         mp_parse_node_t pn = peek_result(parser, num_args - 1);
         if (!mp_parse_node_get_int_maybe(pn, &arg0)) {
@@ -688,14 +695,14 @@
         mp_parse_node_t pn1 = peek_result(parser, 0);
         if (!MP_PARSE_NODE_IS_NULL(pn1)
             && !(MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_expr_stmt_augassign)
-            || MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_expr_stmt_assign_list))) {
+                 || MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_expr_stmt_assign_list))) {
             // this node is of the form <x> = <y>
             mp_parse_node_t pn0 = peek_result(parser, 1);
             if (MP_PARSE_NODE_IS_ID(pn0)
                 && MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_atom_expr_normal)
-                && MP_PARSE_NODE_IS_ID(((mp_parse_node_struct_t*)pn1)->nodes[0])
-                && MP_PARSE_NODE_LEAF_ARG(((mp_parse_node_struct_t*)pn1)->nodes[0]) == MP_QSTR_const
-                && MP_PARSE_NODE_IS_STRUCT_KIND(((mp_parse_node_struct_t*)pn1)->nodes[1], RULE_trailer_paren)
+                && MP_PARSE_NODE_IS_ID(((mp_parse_node_struct_t *)pn1)->nodes[0])
+                && MP_PARSE_NODE_LEAF_ARG(((mp_parse_node_struct_t *)pn1)->nodes[0]) == MP_QSTR_const
+                && MP_PARSE_NODE_IS_STRUCT_KIND(((mp_parse_node_struct_t *)pn1)->nodes[1], RULE_trailer_paren)
                 ) {
                 // code to assign dynamic constants: id = const(value)
 
@@ -703,13 +710,13 @@
                 qstr id = MP_PARSE_NODE_LEAF_ARG(pn0);
 
                 // get the value
-                mp_parse_node_t pn_value = ((mp_parse_node_struct_t*)((mp_parse_node_struct_t*)pn1)->nodes[1])->nodes[0];
+                mp_parse_node_t pn_value = ((mp_parse_node_struct_t *)((mp_parse_node_struct_t *)pn1)->nodes[1])->nodes[0];
                 mp_obj_t value;
                 if (!mp_parse_node_get_int_maybe(pn_value, &value)) {
                     mp_obj_t exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
                         "constant must be an integer");
                     mp_obj_exception_add_traceback(exc, parser->lexer->source_name,
-                        ((mp_parse_node_struct_t*)pn1)->source_line, MP_QSTRnull);
+                        ((mp_parse_node_struct_t *)pn1)->source_line, MP_QSTRnull);
                     nlr_raise(exc);
                 }
 
@@ -743,16 +750,16 @@
         mp_parse_node_t pn0 = peek_result(parser, 1);
         mp_parse_node_t pn1 = peek_result(parser, 0);
         if (!(MP_PARSE_NODE_IS_ID(pn0)
-            && MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_trailer_period))) {
+              && MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_trailer_period))) {
             return false;
         }
         // id1.id2
         // look it up in constant table, see if it can be replaced with an integer
-        mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pn1;
+        mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pn1;
         assert(MP_PARSE_NODE_IS_ID(pns1->nodes[0]));
         qstr q_base = MP_PARSE_NODE_LEAF_ARG(pn0);
         qstr q_attr = MP_PARSE_NODE_LEAF_ARG(pns1->nodes[0]);
-        mp_map_elem_t *elem = mp_map_lookup((mp_map_t*)&mp_constants_map, MP_OBJ_NEW_QSTR(q_base), MP_MAP_LOOKUP);
+        mp_map_elem_t *elem = mp_map_lookup((mp_map_t *)&mp_constants_map, MP_OBJ_NEW_QSTR(q_base), MP_MAP_LOOKUP);
         if (elem == NULL) {
             return false;
         }
@@ -845,9 +852,14 @@
     // work out the top-level rule to use, and push it on the stack
     size_t top_level_rule;
     switch (input_kind) {
-        case MP_PARSE_SINGLE_INPUT: top_level_rule = RULE_single_input; break;
-        case MP_PARSE_EVAL_INPUT: top_level_rule = RULE_eval_input; break;
-        default: top_level_rule = RULE_file_input;
+        case MP_PARSE_SINGLE_INPUT:
+            top_level_rule = RULE_single_input;
+            break;
+        case MP_PARSE_EVAL_INPUT:
+            top_level_rule = RULE_eval_input;
+            break;
+        default:
+            top_level_rule = RULE_file_input;
     }
     push_rule(&parser, lex->tok_line, top_level_rule, 0);
 
@@ -856,7 +868,7 @@
     bool backtrack = false;
 
     for (;;) {
-        next_rule:
+    next_rule:
         if (parser.rule_stack_top == 0) {
             break;
         }
@@ -1028,7 +1040,7 @@
                 // n=3 is: item (sep item)* [sep]
                 bool had_trailing_sep;
                 if (backtrack) {
-                    list_backtrack:
+                list_backtrack:
                     had_trailing_sep = false;
                     if (n == 2) {
                         if (i == 1) {
diff --git a/py/parse.h b/py/parse.h
index 9a1a2b4..0963862 100644
--- a/py/parse.h
+++ b/py/parse.h
@@ -63,7 +63,7 @@
 #define MP_PARSE_NODE_IS_NULL(pn) ((pn) == MP_PARSE_NODE_NULL)
 #define MP_PARSE_NODE_IS_LEAF(pn) ((pn) & 3)
 #define MP_PARSE_NODE_IS_STRUCT(pn) ((pn) != MP_PARSE_NODE_NULL && ((pn) & 3) == 0)
-#define MP_PARSE_NODE_IS_STRUCT_KIND(pn, k) ((pn) != MP_PARSE_NODE_NULL && ((pn) & 3) == 0 && MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)(pn)) == (k))
+#define MP_PARSE_NODE_IS_STRUCT_KIND(pn, k) ((pn) != MP_PARSE_NODE_NULL && ((pn) & 3) == 0 && MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)(pn)) == (k))
 
 #define MP_PARSE_NODE_IS_SMALL_INT(pn) (((pn) & 0x1) == MP_PARSE_NODE_SMALL_INT)
 #define MP_PARSE_NODE_IS_ID(pn) (((pn) & 0x0f) == MP_PARSE_NODE_ID)
diff --git a/py/parsenum.c b/py/parsenum.c
index 2b01b72..cdcae80 100644
--- a/py/parsenum.c
+++ b/py/parsenum.c
@@ -40,7 +40,7 @@
     // if lex!=NULL then the parser called us and we need to convert the
     // exception's type from ValueError to SyntaxError and add traceback info
     if (lex != NULL) {
-        ((mp_obj_base_t*)MP_OBJ_TO_PTR(exc))->type = &mp_type_SyntaxError;
+        ((mp_obj_base_t *)MP_OBJ_TO_PTR(exc))->type = &mp_type_SyntaxError;
         mp_obj_exception_add_traceback(exc, lex->source_name, lex->tok_line, MP_QSTRnull);
     }
     nlr_raise(exc);
@@ -73,7 +73,7 @@
     }
 
     // parse optional base prefix
-    str += mp_parse_num_base((const char*)str, top - str, &base);
+    str += mp_parse_num_base((const char *)str, top - str, &base);
 
     // string should be an integer number
     mp_int_t int_val = 0;
@@ -137,9 +137,9 @@
 overflow:
     // reparse using long int
     {
-        const char *s2 = (const char*)str_val_start;
+        const char *s2 = (const char *)str_val_start;
         ret_val = mp_obj_new_int_from_str_len(&s2, top - str_val_start, neg, base);
-        str = (const byte*)s2;
+        str = (const byte *)s2;
         goto have_ret_val;
     }
 
@@ -171,7 +171,7 @@
 } parse_dec_in_t;
 
 mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool force_complex, mp_lexer_t *lex) {
-#if MICROPY_PY_BUILTINS_FLOAT
+    #if MICROPY_PY_BUILTINS_FLOAT
 
 // DEC_VAL_MAX only needs to be rough and is used to retain precision while not overflowing
 // SMALL_NORMAL_VAL is the smallest power of 10 that is still a normal float
@@ -179,17 +179,17 @@
 //   Note: EXACT_POWER_OF_10 is at least floor(log_5(2^mantissa_length)). Indeed, 10^n = 2^n * 5^n
 //   so we only have to store the 5^n part in the mantissa (the 2^n part will go into the float's
 //   exponent).
-#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
+    #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
 #define DEC_VAL_MAX 1e20F
 #define SMALL_NORMAL_VAL (1e-37F)
 #define SMALL_NORMAL_EXP (-37)
 #define EXACT_POWER_OF_10 (9)
-#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
+    #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
 #define DEC_VAL_MAX 1e200
 #define SMALL_NORMAL_VAL (1e-307)
 #define SMALL_NORMAL_EXP (-307)
 #define EXACT_POWER_OF_10 (22)
-#endif
+    #endif
 
     const char *top = str + len;
     mp_float_t dec_val = 0;
@@ -334,17 +334,17 @@
     }
 
     // return the object
-#if MICROPY_PY_BUILTINS_COMPLEX
+    #if MICROPY_PY_BUILTINS_COMPLEX
     if (imag) {
         return mp_obj_new_complex(0, dec_val);
     } else if (force_complex) {
         return mp_obj_new_complex(dec_val, 0);
     }
-#else
+    #else
     if (imag || force_complex) {
         raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, "complex values not supported"), lex);
     }
-#endif
+    #endif
     else {
         return mp_obj_new_float(dec_val);
     }
@@ -352,7 +352,7 @@
 value_error:
     raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, "invalid syntax for number"), lex);
 
-#else
+    #else
     raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, "decimal numbers not supported"), lex);
-#endif
+    #endif
 }
diff --git a/py/parsenumbase.c b/py/parsenumbase.c
index ba10591..94523a6 100644
--- a/py/parsenumbase.c
+++ b/py/parsenumbase.c
@@ -31,7 +31,7 @@
 // find real radix base, and strip preceding '0x', '0o' and '0b'
 // puts base in *base, and returns number of bytes to skip the prefix
 size_t mp_parse_num_base(const char *str, size_t len, int *base) {
-    const byte *p = (const byte*)str;
+    const byte *p = (const byte *)str;
     if (len <= 1) {
         goto no_prefix;
     }
@@ -67,5 +67,5 @@
             *base = 10;
         }
     }
-    return p - (const byte*)str;
+    return p - (const byte *)str;
 }
diff --git a/py/persistentcode.c b/py/persistentcode.c
index 7039f9f..19cfb02 100644
--- a/py/persistentcode.c
+++ b/py/persistentcode.c
@@ -135,7 +135,7 @@
     prelude->n_kwonly_args = n_kwonly_args;
     prelude->n_def_pos_args = n_def_pos_args;
     MP_BC_PRELUDE_SIZE_DECODE(*ip);
-    byte *ip_info = (byte*)*ip;
+    byte *ip_info = (byte *)*ip;
     *ip += n_info;
     *ip += n_cell;
     return ip_info;
@@ -160,9 +160,9 @@
 #if MICROPY_EMIT_THUMB
 STATIC void asm_thumb_rewrite_mov(uint8_t *pc, uint16_t val) {
     // high part
-    *(uint16_t*)pc = (*(uint16_t*)pc & 0xfbf0) | (val >> 1 & 0x0400) | (val >> 12);
+    *(uint16_t *)pc = (*(uint16_t *)pc & 0xfbf0) | (val >> 1 & 0x0400) | (val >> 12);
     // low part
-    *(uint16_t*)(pc + 2) = (*(uint16_t*)(pc + 2) & 0x0f00) | (val << 4 & 0x7000) | (val & 0x00ff);
+    *(uint16_t *)(pc + 2) = (*(uint16_t *)(pc + 2) & 0x0f00) | (val << 4 & 0x7000) | (val & 0x00ff);
 
 }
 #endif
@@ -200,10 +200,10 @@
             size_t addr = read_uint(ri->reader, NULL);
             if ((addr & 1) == 0) {
                 // Point to somewhere in text
-                addr_to_adjust = &((uintptr_t*)text)[addr >> 1];
+                addr_to_adjust = &((uintptr_t *)text)[addr >> 1];
             } else {
                 // Point to somewhere in rodata
-                addr_to_adjust = &((uintptr_t*)ri->const_table[1])[addr >> 1];
+                addr_to_adjust = &((uintptr_t *)ri->const_table[1])[addr >> 1];
             }
         }
         op >>= 1;
@@ -227,7 +227,7 @@
             dest = (uintptr_t)&mp_fun_table;
         } else {
             // Destination is an entry in mp_fun_table
-            dest = ((uintptr_t*)&mp_fun_table)[op - 7];
+            dest = ((uintptr_t *)&mp_fun_table)[op - 7];
         }
         while (n--) {
             *addr_to_adjust++ += dest;
@@ -275,7 +275,7 @@
     }
     len >>= 1;
     char *str = m_new(char, len);
-    read_bytes(reader, (byte*)str, len);
+    read_bytes(reader, (byte *)str, len);
     qstr qst = qstr_from_strn(str, len);
     m_del(char, str, len);
     qstr_window_push(qw, qst);
@@ -290,7 +290,7 @@
         size_t len = read_uint(reader, NULL);
         vstr_t vstr;
         vstr_init_len(&vstr, len);
-        read_bytes(reader, (byte*)vstr.buf, len);
+        read_bytes(reader, (byte *)vstr.buf, len);
         if (obj_type == 's' || obj_type == 'b') {
             return mp_obj_new_str_from_vstr(obj_type == 's' ? &mp_type_str : &mp_type_bytes, &vstr);
         } else if (obj_type == 'i') {
@@ -304,9 +304,11 @@
 
 STATIC void load_prelude_qstrs(mp_reader_t *reader, qstr_window_t *qw, byte *ip) {
     qstr simple_name = load_qstr(reader, qw);
-    ip[0] = simple_name; ip[1] = simple_name >> 8;
+    ip[0] = simple_name;
+    ip[1] = simple_name >> 8;
     qstr source_file = load_qstr(reader, qw);
-    ip[2] = source_file; ip[3] = source_file >> 8;
+    ip[2] = source_file;
+    ip[3] = source_file >> 8;
 }
 
 STATIC void load_prelude(mp_reader_t *reader, qstr_window_t *qw, byte **ip, bytecode_prelude_t *prelude) {
@@ -316,7 +318,7 @@
     read_uint(reader, &ip_read);                    // read in n_info/n_cell (is effectively a var-uint)
 
     // Prelude header has been read into *ip, now decode and extract values from it
-    extract_prelude((const byte**)ip, prelude);
+    extract_prelude((const byte **)ip, prelude);
 
     // Load qstrs in prelude
     load_prelude_qstrs(reader, qw, ip_read);
@@ -382,7 +384,7 @@
     } else {
         // Allocate memory for native data and load it
         size_t fun_alloc;
-        MP_PLAT_ALLOC_EXEC(fun_data_len, (void**)&fun_data, &fun_alloc);
+        MP_PLAT_ALLOC_EXEC(fun_data_len, (void **)&fun_data, &fun_alloc);
         read_bytes(reader, fun_data, fun_data_len);
 
         if (kind == MP_CODE_NATIVE_PY || kind == MP_CODE_NATIVE_VIPER) {
@@ -398,7 +400,7 @@
                     dest[1] = (qst >> 8) & 0xff;
                 } else if ((off & 3) == 3) {
                     // Generic, aligned qstr-object link
-                    *(mp_obj_t*)dest = MP_OBJ_NEW_QSTR(qst);
+                    *(mp_obj_t *)dest = MP_OBJ_NEW_QSTR(qst);
                 } else {
                     // Architecture-specific link
                     arch_link_qstr(dest, (off & 3) == 2, qst);
@@ -578,7 +580,7 @@
 #include "py/objstr.h"
 
 STATIC void mp_print_bytes(mp_print_t *print, const byte *data, size_t len) {
-    print->print_strn(print->data, (const char*)data, len);
+    print->print_strn(print->data, (const char *)data, len);
 }
 
 #define BYTES_FOR_INT ((BYTES_PER_WORD * 8 + 6) / 7)
@@ -590,7 +592,7 @@
     for (; n != 0; n >>= 7) {
         *--p = 0x80 | (n & 0x7f);
     }
-    print->print_strn(print->data, (char*)p, buf + sizeof(buf) - p);
+    print->print_strn(print->data, (char *)p, buf + sizeof(buf) - p);
 }
 
 STATIC void save_qstr(mp_print_t *print, qstr_window_t *qw, qstr qst) {
@@ -624,7 +626,7 @@
         const char *str = mp_obj_str_get_data(o, &len);
         mp_print_bytes(print, &obj_type, 1);
         mp_print_uint(print, len);
-        mp_print_bytes(print, (const byte*)str, len);
+        mp_print_bytes(print, (const byte *)str, len);
     } else if (MP_OBJ_TO_PTR(o) == &mp_const_ellipsis_obj) {
         byte obj_type = 'e';
         mp_print_bytes(print, &obj_type, 1);
@@ -648,7 +650,7 @@
         mp_obj_print_helper(&pr, o, PRINT_REPR);
         mp_print_bytes(print, &obj_type, 1);
         mp_print_uint(print, vstr.len);
-        mp_print_bytes(print, (const byte*)vstr.buf, vstr.len);
+        mp_print_bytes(print, (const byte *)vstr.buf, vstr.len);
         vstr_clear(&vstr);
     }
 }
@@ -686,13 +688,13 @@
         const byte *ip_info = extract_prelude(&ip, &prelude);
 
         // Save prelude
-        mp_print_bytes(print, rc->fun_data, ip_info - (const byte*)rc->fun_data);
+        mp_print_bytes(print, rc->fun_data, ip_info - (const byte *)rc->fun_data);
         save_prelude_qstrs(print, qstr_window, ip_info);
         ip_info += 4;
         mp_print_bytes(print, ip_info, ip - ip_info);
 
         // Save bytecode
-        const byte *ip_top = (const byte*)rc->fun_data + rc->fun_data_len;
+        const byte *ip_top = (const byte *)rc->fun_data + rc->fun_data_len;
         save_bytecode(print, qstr_window, ip, ip_top);
     #if MICROPY_EMIT_MACHINE_CODE
     } else {
@@ -713,7 +715,7 @@
             mp_print_uint(print, rc->prelude_offset);
 
             // Extract prelude and save qstrs in prelude
-            const byte *ip = (const byte*)rc->fun_data + rc->prelude_offset;
+            const byte *ip = (const byte *)rc->fun_data + rc->prelude_offset;
             const byte *ip_info = extract_prelude(&ip, &prelude);
             save_prelude_qstrs(print, qstr_window, ip_info);
         } else {
@@ -755,7 +757,7 @@
             save_obj(print, (mp_obj_t)*const_table++);
         }
         for (size_t i = 0; i < rc->n_raw_code; ++i) {
-            save_raw_code(print, (mp_raw_code_t*)(uintptr_t)*const_table++, qstr_window);
+            save_raw_code(print, (mp_raw_code_t *)(uintptr_t)*const_table++, qstr_window);
         }
     }
 }
@@ -774,7 +776,7 @@
         + rc->n_obj;
 
     for (size_t i = 0; i < rc->n_raw_code; ++i) {
-        if (mp_raw_code_has_native((mp_raw_code_t*)(uintptr_t)*const_table++)) {
+        if (mp_raw_code_has_native((mp_raw_code_t *)(uintptr_t)*const_table++)) {
             return true;
         }
     }
@@ -832,7 +834,7 @@
     MP_THREAD_GIL_EXIT();
     int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
     MP_THREAD_GIL_ENTER();
-    mp_print_t fd_print = {(void*)(intptr_t)fd, fd_print_strn};
+    mp_print_t fd_print = {(void *)(intptr_t)fd, fd_print_strn};
     mp_raw_code_save(rc, &fd_print);
     MP_THREAD_GIL_EXIT();
     close(fd);
diff --git a/py/profile.c b/py/profile.c
index 72726cd..863b006 100644
--- a/py/profile.c
+++ b/py/profile.c
@@ -73,18 +73,18 @@
         o,
         prelude->qstr_source_file,
         rc->line_of_definition
-    );
+        );
 }
 
-STATIC mp_obj_tuple_t* code_consts(const mp_raw_code_t *rc) {
+STATIC mp_obj_tuple_t *code_consts(const mp_raw_code_t *rc) {
     const mp_bytecode_prelude_t *prelude = &rc->prelude;
     int start = prelude->n_pos_args + prelude->n_kwonly_args + rc->n_obj;
-    int stop  = prelude->n_pos_args + prelude->n_kwonly_args + rc->n_obj + rc->n_raw_code;
+    int stop = prelude->n_pos_args + prelude->n_kwonly_args + rc->n_obj + rc->n_raw_code;
     mp_obj_tuple_t *consts = MP_OBJ_TO_PTR(mp_obj_new_tuple(stop - start + 1, NULL));
 
     size_t const_no = 0;
     for (int i = start; i < stop; ++i) {
-        mp_obj_t code = mp_obj_new_code((const mp_raw_code_t*)MP_OBJ_TO_PTR(rc->const_table[i]));
+        mp_obj_t code = mp_obj_new_code((const mp_raw_code_t *)MP_OBJ_TO_PTR(rc->const_table[i]));
         if (code == MP_OBJ_NULL) {
             m_malloc_fail(sizeof(mp_obj_code_t));
         }
@@ -103,7 +103,7 @@
     uint last_lineno = mp_prof_bytecode_lineno(rc, start);
     uint lasti = 0;
 
-    const uint buffer_chunk_size = (stop-start) >> 2; // heuristic magic
+    const uint buffer_chunk_size = (stop - start) >> 2; // heuristic magic
     uint buffer_size = buffer_chunk_size;
     byte *buffer = m_new(byte, buffer_size);
     uint buffer_index = 0;
@@ -141,12 +141,12 @@
     mp_obj_code_t *o = MP_OBJ_TO_PTR(self_in);
     const mp_raw_code_t *rc = o->rc;
     const mp_bytecode_prelude_t *prelude = &rc->prelude;
-    switch(attr) {
+    switch (attr) {
         case MP_QSTR_co_code:
             dest[0] = mp_obj_new_bytes(
-                (void*)prelude->opcodes,
-                rc->fun_data_len - (prelude->opcodes - (const byte*)rc->fun_data)
-            );
+                (void *)prelude->opcodes,
+                rc->fun_data_len - (prelude->opcodes - (const byte *)rc->fun_data)
+                );
             break;
         case MP_QSTR_co_consts:
             dest[0] = MP_OBJ_FROM_PTR(code_consts(rc));
@@ -165,7 +165,7 @@
             break;
         case MP_QSTR_co_lnotab:
             if (!o->lnotab) {
-                 o->lnotab = raw_code_lnotab(rc);
+                o->lnotab = raw_code_lnotab(rc);
             }
             dest[0] = o->lnotab;
             break;
@@ -207,7 +207,7 @@
         prelude->qstr_source_file,
         frame->lineno,
         prelude->qstr_block_name
-    );
+        );
 }
 
 STATIC void frame_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
@@ -218,7 +218,7 @@
 
     mp_obj_frame_t *o = MP_OBJ_TO_PTR(self_in);
 
-    switch(attr) {
+    switch (attr) {
         case MP_QSTR_f_back:
             dest[0] = mp_const_none;
             if (o->code_state->prev_state) {
@@ -282,7 +282,7 @@
 // Trace logic
 
 typedef struct {
-    struct _mp_obj_frame_t * frame;
+    struct _mp_obj_frame_t *frame;
     mp_obj_t event;
     mp_obj_t arg;
 } prof_callback_args_t;
@@ -340,7 +340,7 @@
     }
 
     mp_obj_t top;
-    prof_callback_args_t _args, *args=&_args;
+    prof_callback_args_t _args, *args = &_args;
     args->frame = code_state->frame;
 
     // SETTRACE event CALL
@@ -388,7 +388,7 @@
     mp_obj_t top = mp_const_none;
     mp_obj_t callback = code_state->frame->callback;
 
-    prof_callback_args_t _args, *args=&_args;
+    prof_callback_args_t _args, *args = &_args;
     args->frame = code_state->frame;
     args->event = mp_const_none;
     args->arg = mp_const_none;
@@ -444,10 +444,10 @@
 #include "runtime0.h"
 
 #define DECODE_UINT { \
-    unum = 0; \
-    do { \
-        unum = (unum << 7) + (*ip & 0x7f); \
-    } while ((*ip++ & 0x80) != 0); \
+        unum = 0; \
+        do { \
+            unum = (unum << 7) + (*ip & 0x7f); \
+        } while ((*ip++ & 0x80) != 0); \
 }
 #define DECODE_ULABEL do { unum = (ip[0] | (ip[1] << 8)); ip += 2; } while (0)
 #define DECODE_SLABEL do { unum = (ip[0] | (ip[1] << 8)) - 0x8000; ip += 2; } while (0)
@@ -457,7 +457,7 @@
     ip += 2;
 #define DECODE_PTR \
     DECODE_UINT; \
-    ptr = (const byte*)const_table[unum]
+    ptr = (const byte *)const_table[unum]
 #define DECODE_OBJ \
     DECODE_UINT; \
     obj = (mp_obj_t)const_table[unum]
@@ -471,13 +471,13 @@
 
 STATIC const byte *mp_prof_opcode_decode(const byte *ip, const mp_uint_t *const_table, mp_dis_instruction_t *instruction) {
     mp_uint_t unum;
-    const byte* ptr;
+    const byte *ptr;
     mp_obj_t obj;
     qstr qst;
 
     instruction->qstr_opname = MP_QSTR_;
     instruction->arg = 0;
-    instruction->argobj= mp_const_none;
+    instruction->argobj = mp_const_none;
     instruction->argobjex_cache = mp_const_none;
 
     switch (*ip++) {
@@ -511,14 +511,14 @@
             DECODE_QSTR;
             instruction->qstr_opname = MP_QSTR_LOAD_CONST_STRING;
             instruction->arg = qst;
-            instruction->argobj= MP_OBJ_NEW_QSTR(qst);
+            instruction->argobj = MP_OBJ_NEW_QSTR(qst);
             break;
 
         case MP_BC_LOAD_CONST_OBJ:
             DECODE_OBJ;
             instruction->qstr_opname = MP_QSTR_LOAD_CONST_OBJ;
             instruction->arg = unum;
-            instruction->argobj= obj;
+            instruction->argobj = obj;
             break;
 
         case MP_BC_LOAD_NULL:
@@ -541,7 +541,7 @@
             DECODE_QSTR;
             instruction->qstr_opname = MP_QSTR_LOAD_NAME;
             instruction->arg = qst;
-            instruction->argobj= MP_OBJ_NEW_QSTR(qst);
+            instruction->argobj = MP_OBJ_NEW_QSTR(qst);
             if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) {
                 instruction->argobjex_cache = MP_OBJ_NEW_SMALL_INT(*ip++);
             }
@@ -551,7 +551,7 @@
             DECODE_QSTR;
             instruction->qstr_opname = MP_QSTR_LOAD_GLOBAL;
             instruction->arg = qst;
-            instruction->argobj= MP_OBJ_NEW_QSTR(qst);
+            instruction->argobj = MP_OBJ_NEW_QSTR(qst);
             if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) {
                 instruction->argobjex_cache = MP_OBJ_NEW_SMALL_INT(*ip++);
             }
@@ -561,7 +561,7 @@
             DECODE_QSTR;
             instruction->qstr_opname = MP_QSTR_LOAD_ATTR;
             instruction->arg = qst;
-            instruction->argobj= MP_OBJ_NEW_QSTR(qst);
+            instruction->argobj = MP_OBJ_NEW_QSTR(qst);
             if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) {
                 instruction->argobjex_cache = MP_OBJ_NEW_SMALL_INT(*ip++);
             }
@@ -571,14 +571,14 @@
             DECODE_QSTR;
             instruction->qstr_opname = MP_QSTR_LOAD_METHOD;
             instruction->arg = qst;
-            instruction->argobj= MP_OBJ_NEW_QSTR(qst);
+            instruction->argobj = MP_OBJ_NEW_QSTR(qst);
             break;
 
         case MP_BC_LOAD_SUPER_METHOD:
             DECODE_QSTR;
             instruction->qstr_opname = MP_QSTR_LOAD_SUPER_METHOD;
             instruction->arg = qst;
-            instruction->argobj= MP_OBJ_NEW_QSTR(qst);
+            instruction->argobj = MP_OBJ_NEW_QSTR(qst);
             break;
 
         case MP_BC_LOAD_BUILD_CLASS:
@@ -605,21 +605,21 @@
             DECODE_QSTR;
             instruction->qstr_opname = MP_QSTR_STORE_NAME;
             instruction->arg = qst;
-            instruction->argobj= MP_OBJ_NEW_QSTR(qst);
+            instruction->argobj = MP_OBJ_NEW_QSTR(qst);
             break;
 
         case MP_BC_STORE_GLOBAL:
             DECODE_QSTR;
             instruction->qstr_opname = MP_QSTR_STORE_GLOBAL;
             instruction->arg = qst;
-            instruction->argobj= MP_OBJ_NEW_QSTR(qst);
+            instruction->argobj = MP_OBJ_NEW_QSTR(qst);
             break;
 
         case MP_BC_STORE_ATTR:
             DECODE_QSTR;
             instruction->qstr_opname = MP_QSTR_STORE_ATTR;
             instruction->arg = qst;
-            instruction->argobj= MP_OBJ_NEW_QSTR(qst);
+            instruction->argobj = MP_OBJ_NEW_QSTR(qst);
             if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) {
                 instruction->argobjex_cache = MP_OBJ_NEW_SMALL_INT(*ip++);
             }
@@ -645,14 +645,14 @@
             DECODE_QSTR;
             instruction->qstr_opname = MP_QSTR_DELETE_NAME;
             instruction->arg = qst;
-            instruction->argobj= MP_OBJ_NEW_QSTR(qst);
+            instruction->argobj = MP_OBJ_NEW_QSTR(qst);
             break;
 
         case MP_BC_DELETE_GLOBAL:
             DECODE_QSTR;
             instruction->qstr_opname = MP_QSTR_DELETE_GLOBAL;
             instruction->arg = qst;
-            instruction->argobj= MP_OBJ_NEW_QSTR(qst);
+            instruction->argobj = MP_OBJ_NEW_QSTR(qst);
             break;
 
         case MP_BC_DUP_TOP:
@@ -813,14 +813,14 @@
             DECODE_PTR;
             instruction->qstr_opname = MP_QSTR_MAKE_FUNCTION;
             instruction->arg = unum;
-            instruction->argobj= mp_obj_new_int_from_ull((uint64_t)ptr);
+            instruction->argobj = mp_obj_new_int_from_ull((uint64_t)ptr);
             break;
 
         case MP_BC_MAKE_FUNCTION_DEFARGS:
             DECODE_PTR;
             instruction->qstr_opname = MP_QSTR_MAKE_FUNCTION_DEFARGS;
             instruction->arg = unum;
-            instruction->argobj= mp_obj_new_int_from_ull((uint64_t)ptr);
+            instruction->argobj = mp_obj_new_int_from_ull((uint64_t)ptr);
             break;
 
         case MP_BC_MAKE_CLOSURE: {
@@ -828,7 +828,7 @@
             mp_uint_t n_closed_over = *ip++;
             instruction->qstr_opname = MP_QSTR_MAKE_CLOSURE;
             instruction->arg = unum;
-            instruction->argobj= mp_obj_new_int_from_ull((uint64_t)ptr);
+            instruction->argobj = mp_obj_new_int_from_ull((uint64_t)ptr);
             instruction->argobjex_cache = MP_OBJ_NEW_SMALL_INT(n_closed_over);
             break;
         }
@@ -838,7 +838,7 @@
             mp_uint_t n_closed_over = *ip++;
             instruction->qstr_opname = MP_QSTR_MAKE_CLOSURE_DEFARGS;
             instruction->arg = unum;
-            instruction->argobj= mp_obj_new_int_from_ull((uint64_t)ptr);
+            instruction->argobj = mp_obj_new_int_from_ull((uint64_t)ptr);
             instruction->argobjex_cache = MP_OBJ_NEW_SMALL_INT(n_closed_over);
             break;
         }
@@ -899,14 +899,14 @@
             DECODE_QSTR;
             instruction->qstr_opname = MP_QSTR_IMPORT_NAME;
             instruction->arg = qst;
-            instruction->argobj= MP_OBJ_NEW_QSTR(qst);
+            instruction->argobj = MP_OBJ_NEW_QSTR(qst);
             break;
 
         case MP_BC_IMPORT_FROM:
             DECODE_QSTR;
             instruction->qstr_opname = MP_QSTR_IMPORT_FROM;
             instruction->arg = qst;
-            instruction->argobj= MP_OBJ_NEW_QSTR(qst);
+            instruction->argobj = MP_OBJ_NEW_QSTR(qst);
             break;
 
         case MP_BC_IMPORT_STAR:
@@ -931,7 +931,7 @@
                 instruction->qstr_opname = MP_QSTR_BINARY_OP;
                 instruction->arg = op;
             } else {
-                mp_printf(&mp_plat_print, "code %p, opcode 0x%02x not implemented\n", ip-1, ip[-1]);
+                mp_printf(&mp_plat_print, "code %p, opcode 0x%02x not implemented\n", ip - 1, ip[-1]);
                 assert(0);
                 return ip;
             }
@@ -941,7 +941,7 @@
     return ip;
 }
 
-void mp_prof_print_instr(const byte* ip, mp_code_state_t *code_state) {
+void mp_prof_print_instr(const byte *ip, mp_code_state_t *code_state) {
     mp_dis_instruction_t _instruction, *instruction = &_instruction;
     mp_prof_opcode_decode(ip, code_state->fun_bc->rc->const_table, instruction);
     const mp_raw_code_t *rc = code_state->fun_bc->rc;
@@ -958,7 +958,7 @@
             prelude->qstr_block_name,
             offset,
             mp_prof_bytecode_lineno(rc, offset)
-        );
+            );
     }
 
     /* bytecode */ if (0) {
diff --git a/py/profile.h b/py/profile.h
index 0293e26..64e207d 100644
--- a/py/profile.h
+++ b/py/profile.h
@@ -69,7 +69,7 @@
 // to be included in production/release builds.
 #define MICROPY_PROF_INSTR_DEBUG_PRINT_ENABLE 0
 #if MICROPY_PROF_INSTR_DEBUG_PRINT_ENABLE
-void mp_prof_print_instr(const byte* ip, mp_code_state_t *code_state);
+void mp_prof_print_instr(const byte *ip, mp_code_state_t *code_state);
 #define MP_PROF_INSTR_DEBUG_PRINT(current_ip) mp_prof_print_instr((current_ip), code_state)
 #else
 #define MP_PROF_INSTR_DEBUG_PRINT(current_ip)
diff --git a/py/pystack.c b/py/pystack.c
index 552e59d..f7323fd 100644
--- a/py/pystack.c
+++ b/py/pystack.c
@@ -49,7 +49,7 @@
     void *ptr = MP_STATE_THREAD(pystack_cur);
     MP_STATE_THREAD(pystack_cur) += n_bytes;
     #if MP_PYSTACK_DEBUG
-    *(size_t*)(MP_STATE_THREAD(pystack_cur) - MICROPY_PYSTACK_ALIGN) = n_bytes;
+    *(size_t *)(MP_STATE_THREAD(pystack_cur) - MICROPY_PYSTACK_ALIGN) = n_bytes;
     #endif
     return ptr;
 }
diff --git a/py/pystack.h b/py/pystack.h
index 82ac374..ea8fddc 100644
--- a/py/pystack.h
+++ b/py/pystack.h
@@ -41,21 +41,21 @@
 // pointer to the block that was allocated first and it and all subsequently
 // allocated blocks will be freed.
 static inline void mp_pystack_free(void *ptr) {
-    assert((uint8_t*)ptr >= MP_STATE_THREAD(pystack_start));
-    assert((uint8_t*)ptr <= MP_STATE_THREAD(pystack_cur));
+    assert((uint8_t *)ptr >= MP_STATE_THREAD(pystack_start));
+    assert((uint8_t *)ptr <= MP_STATE_THREAD(pystack_cur));
     #if MP_PYSTACK_DEBUG
-    size_t n_bytes_to_free = MP_STATE_THREAD(pystack_cur) - (uint8_t*)ptr;
-    size_t n_bytes = *(size_t*)(MP_STATE_THREAD(pystack_cur) - MICROPY_PYSTACK_ALIGN);
+    size_t n_bytes_to_free = MP_STATE_THREAD(pystack_cur) - (uint8_t *)ptr;
+    size_t n_bytes = *(size_t *)(MP_STATE_THREAD(pystack_cur) - MICROPY_PYSTACK_ALIGN);
     while (n_bytes < n_bytes_to_free) {
-        n_bytes += *(size_t*)(MP_STATE_THREAD(pystack_cur) - n_bytes - MICROPY_PYSTACK_ALIGN);
+        n_bytes += *(size_t *)(MP_STATE_THREAD(pystack_cur) - n_bytes - MICROPY_PYSTACK_ALIGN);
     }
     if (n_bytes != n_bytes_to_free) {
         mp_printf(&mp_plat_print, "mp_pystack_free() failed: %u != %u\n", (uint)n_bytes_to_free,
-            (uint)*(size_t*)(MP_STATE_THREAD(pystack_cur) - MICROPY_PYSTACK_ALIGN));
+            (uint)*(size_t *)(MP_STATE_THREAD(pystack_cur) - MICROPY_PYSTACK_ALIGN));
         assert(0);
     }
     #endif
-    MP_STATE_THREAD(pystack_cur) = (uint8_t*)ptr;
+    MP_STATE_THREAD(pystack_cur) = (uint8_t *)ptr;
 }
 
 static inline void mp_pystack_realloc(void *ptr, size_t n_bytes) {
diff --git a/py/qstr.c b/py/qstr.c
index 940d09e..c3d78bf 100644
--- a/py/qstr.c
+++ b/py/qstr.c
@@ -106,11 +106,11 @@
     MICROPY_ALLOC_QSTR_ENTRIES_INIT,
     MP_QSTRnumber_of,   // corresponds to number of strings in array just below
     {
-#ifndef NO_QSTR
+        #ifndef NO_QSTR
 #define QDEF(id, str) str,
-#include "genhdr/qstrdefs.generated.h"
+        #include "genhdr/qstrdefs.generated.h"
 #undef QDEF
-#endif
+        #endif
     },
 };
 
@@ -122,7 +122,7 @@
 #endif
 
 void qstr_init(void) {
-    MP_STATE_VM(last_pool) = (qstr_pool_t*)&CONST_POOL; // we won't modify the const_pool since it has no allocated room left
+    MP_STATE_VM(last_pool) = (qstr_pool_t *)&CONST_POOL; // we won't modify the const_pool since it has no allocated room left
     MP_STATE_VM(qstr_last_chunk) = NULL;
 
     #if MICROPY_PY_THREAD && !MICROPY_PY_THREAD_GIL
@@ -151,7 +151,7 @@
         // Put a lower bound on the allocation size in case the extra qstr pool has few entries
         new_alloc = MAX(MICROPY_ALLOC_QSTR_ENTRIES_INIT, new_alloc);
         #endif
-        qstr_pool_t *pool = m_new_obj_var_maybe(qstr_pool_t, const char*, new_alloc);
+        qstr_pool_t *pool = m_new_obj_var_maybe(qstr_pool_t, const char *, new_alloc);
         if (pool == NULL) {
             QSTR_EXIT();
             m_malloc_fail(new_alloc);
@@ -173,7 +173,7 @@
 
 qstr qstr_find_strn(const char *str, size_t str_len) {
     // work out hash of str
-    mp_uint_t str_hash = qstr_compute_hash((const byte*)str, str_len);
+    mp_uint_t str_hash = qstr_compute_hash((const byte *)str, str_len);
 
     // search pools for the data
     for (qstr_pool_t *pool = MP_STATE_VM(last_pool); pool != NULL; pool = pool->prev) {
@@ -245,7 +245,7 @@
         MP_STATE_VM(qstr_last_used) += n_bytes;
 
         // store the interned strings' data
-        mp_uint_t hash = qstr_compute_hash((const byte*)str, len);
+        mp_uint_t hash = qstr_compute_hash((const byte *)str, len);
         Q_SET_HASH(q_ptr, hash);
         Q_SET_LENGTH(q_ptr, len);
         memcpy(q_ptr + MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN, str, len);
@@ -268,7 +268,7 @@
 
 const char *qstr_str(qstr q) {
     const byte *qd = find_qstr(q);
-    return (const char*)Q_GET_DATA(qd);
+    return (const char *)Q_GET_DATA(qd);
 }
 
 const byte *qstr_data(qstr q, size_t *len) {
diff --git a/py/qstr.h b/py/qstr.h
index 8153ef2..7dd3024 100644
--- a/py/qstr.h
+++ b/py/qstr.h
@@ -37,11 +37,11 @@
 
 // first entry in enum will be MP_QSTRnull=0, which indicates invalid/no qstr
 enum {
-#ifndef NO_QSTR
+    #ifndef NO_QSTR
 #define QDEF(id, str) id,
-#include "genhdr/qstrdefs.generated.h"
+    #include "genhdr/qstrdefs.generated.h"
 #undef QDEF
-#endif
+    #endif
     MP_QSTRnumber_of, // no underscore so it can't clash with any of the above
 };
 
diff --git a/py/reader.c b/py/reader.c
index d99dfc5..d68406b 100644
--- a/py/reader.c
+++ b/py/reader.c
@@ -40,7 +40,7 @@
 } mp_reader_mem_t;
 
 STATIC mp_uint_t mp_reader_mem_readbyte(void *data) {
-    mp_reader_mem_t *reader = (mp_reader_mem_t*)data;
+    mp_reader_mem_t *reader = (mp_reader_mem_t *)data;
     if (reader->cur < reader->end) {
         return *reader->cur++;
     } else {
@@ -49,9 +49,9 @@
 }
 
 STATIC void mp_reader_mem_close(void *data) {
-    mp_reader_mem_t *reader = (mp_reader_mem_t*)data;
+    mp_reader_mem_t *reader = (mp_reader_mem_t *)data;
     if (reader->free_len > 0) {
-        m_del(char, (char*)reader->beg, reader->free_len);
+        m_del(char, (char *)reader->beg, reader->free_len);
     }
     m_del_obj(mp_reader_mem_t, reader);
 }
@@ -82,7 +82,7 @@
 } mp_reader_posix_t;
 
 STATIC mp_uint_t mp_reader_posix_readbyte(void *data) {
-    mp_reader_posix_t *reader = (mp_reader_posix_t*)data;
+    mp_reader_posix_t *reader = (mp_reader_posix_t *)data;
     if (reader->pos >= reader->len) {
         if (reader->len == 0) {
             return MP_READER_EOF;
@@ -102,7 +102,7 @@
 }
 
 STATIC void mp_reader_posix_close(void *data) {
-    mp_reader_posix_t *reader = (mp_reader_posix_t*)data;
+    mp_reader_posix_t *reader = (mp_reader_posix_t *)data;
     if (reader->close_fd) {
         MP_THREAD_GIL_EXIT();
         close(reader->fd);
diff --git a/py/repl.c b/py/repl.c
index 9389b34..c758fc0 100644
--- a/py/repl.c
+++ b/py/repl.c
@@ -50,7 +50,7 @@
 
     // check if input starts with a certain keyword
     bool starts_with_compound_keyword =
-           input[0] == '@'
+        input[0] == '@'
         || str_startswith_word(input, "if")
         || str_startswith_word(input, "while")
         || str_startswith_word(input, "for")
@@ -61,7 +61,7 @@
         #if MICROPY_PY_ASYNC_AWAIT
         || str_startswith_word(input, "async")
         #endif
-        ;
+    ;
 
     // check for unmatched open bracket, quote or escape quote
     #define Q_NONE (0)
@@ -95,13 +95,26 @@
             }
         } else if (in_quote == Q_NONE) {
             switch (*i) {
-                case '(': n_paren += 1; break;
-                case ')': n_paren -= 1; break;
-                case '[': n_brack += 1; break;
-                case ']': n_brack -= 1; break;
-                case '{': n_brace += 1; break;
-                case '}': n_brace -= 1; break;
-                default: break;
+                case '(':
+                    n_paren += 1;
+                    break;
+                case ')':
+                    n_paren -= 1;
+                    break;
+                case '[':
+                    n_brack += 1;
+                    break;
+                case ']':
+                    n_brack -= 1;
+                    break;
+                case '{':
+                    n_brace += 1;
+                    break;
+                case '}':
+                    n_brace -= 1;
+                    break;
+                default:
+                    break;
             }
         }
     }
@@ -183,7 +196,7 @@
             qstr q_first = 0, q_last = 0;
             for (qstr q = MP_QSTR_ + 1; q < nqstr; ++q) {
                 size_t d_len;
-                const char *d_str = (const char*)qstr_data(q, &d_len);
+                const char *d_str = (const char *)qstr_data(q, &d_len);
                 if (s_len <= d_len && strncmp(s_start, d_str, s_len) == 0) {
                     mp_load_method_protected(obj, q, dest, true);
                     if (dest[0] != MP_OBJ_NULL) {
@@ -237,7 +250,7 @@
             int line_len = MAX_LINE_LEN; // force a newline for first word
             for (qstr q = q_first; q <= q_last; ++q) {
                 size_t d_len;
-                const char *d_str = (const char*)qstr_data(q, &d_len);
+                const char *d_str = (const char *)qstr_data(q, &d_len);
                 if (s_len <= d_len && strncmp(s_start, d_str, s_len) == 0) {
                     mp_load_method_protected(obj, q, dest, true);
                     if (dest[0] != MP_OBJ_NULL) {
diff --git a/py/ringbuf.h b/py/ringbuf.h
index 8d4ed16..4d316d9 100644
--- a/py/ringbuf.h
+++ b/py/ringbuf.h
@@ -42,11 +42,11 @@
 
 // Dynamic initialization. This needs to become findable as a root pointer!
 #define ringbuf_alloc(r, sz) \
-{ \
-    (r)->buf = m_new(uint8_t, sz); \
-    (r)->size = sz; \
-    (r)->iget = (r)->iput = 0; \
-}
+    { \
+        (r)->buf = m_new(uint8_t, sz); \
+        (r)->size = sz; \
+        (r)->iget = (r)->iput = 0; \
+    }
 
 static inline int ringbuf_get(ringbuf_t *r) {
     if (r->iget == r->iput) {
diff --git a/py/runtime.c b/py/runtime.c
index 906d07b..88b89c6 100644
--- a/py/runtime.c
+++ b/py/runtime.c
@@ -55,7 +55,7 @@
 
 const mp_obj_module_t mp_module___main__ = {
     .base = { &mp_type_module },
-    .globals = (mp_obj_dict_t*)&MP_STATE_VM(dict_main),
+    .globals = (mp_obj_dict_t *)&MP_STATE_VM(dict_main),
 };
 
 void mp_init(void) {
@@ -69,9 +69,9 @@
     MP_STATE_VM(sched_len) = 0;
     #endif
 
-#if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
+    #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
     mp_init_emergency_exception_buf();
-#endif
+    #endif
 
     #if MICROPY_KBD_EXCEPTION
     // initialise the exception object for raising KeyboardInterrupt
@@ -79,7 +79,7 @@
     MP_STATE_VM(mp_kbd_exception).traceback_alloc = 0;
     MP_STATE_VM(mp_kbd_exception).traceback_len = 0;
     MP_STATE_VM(mp_kbd_exception).traceback_data = NULL;
-    MP_STATE_VM(mp_kbd_exception).args = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj;
+    MP_STATE_VM(mp_kbd_exception).args = (mp_obj_tuple_t *)&mp_const_empty_tuple_obj;
     #endif
 
     #if MICROPY_ENABLE_COMPILER
@@ -183,7 +183,7 @@
             }
         }
         #endif
-        elem = mp_map_lookup((mp_map_t*)&mp_module_builtins_globals.map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
+        elem = mp_map_lookup((mp_map_t *)&mp_module_builtins_globals.map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
         if (elem == NULL) {
             if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
                 mp_raise_msg(&mp_type_NameError, "name not defined");
@@ -367,11 +367,17 @@
             //      <<      checked explicitly
             switch (op) {
                 case MP_BINARY_OP_OR:
-                case MP_BINARY_OP_INPLACE_OR: lhs_val |= rhs_val; break;
+                case MP_BINARY_OP_INPLACE_OR:
+                    lhs_val |= rhs_val;
+                    break;
                 case MP_BINARY_OP_XOR:
-                case MP_BINARY_OP_INPLACE_XOR: lhs_val ^= rhs_val; break;
+                case MP_BINARY_OP_INPLACE_XOR:
+                    lhs_val ^= rhs_val;
+                    break;
                 case MP_BINARY_OP_AND:
-                case MP_BINARY_OP_INPLACE_AND: lhs_val &= rhs_val; break;
+                case MP_BINARY_OP_INPLACE_AND:
+                    lhs_val &= rhs_val;
+                    break;
                 case MP_BINARY_OP_LSHIFT:
                 case MP_BINARY_OP_INPLACE_LSHIFT: {
                     if (rhs_val < 0) {
@@ -403,9 +409,13 @@
                     }
                     break;
                 case MP_BINARY_OP_ADD:
-                case MP_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break;
+                case MP_BINARY_OP_INPLACE_ADD:
+                    lhs_val += rhs_val;
+                    break;
                 case MP_BINARY_OP_SUBTRACT:
-                case MP_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break;
+                case MP_BINARY_OP_INPLACE_SUBTRACT:
+                    lhs_val -= rhs_val;
+                    break;
                 case MP_BINARY_OP_MULTIPLY:
                 case MP_BINARY_OP_INPLACE_MULTIPLY: {
 
@@ -505,10 +515,14 @@
                     return MP_OBJ_FROM_PTR(tuple);
                 }
 
-                case MP_BINARY_OP_LESS: return mp_obj_new_bool(lhs_val < rhs_val);
-                case MP_BINARY_OP_MORE: return mp_obj_new_bool(lhs_val > rhs_val);
-                case MP_BINARY_OP_LESS_EQUAL: return mp_obj_new_bool(lhs_val <= rhs_val);
-                case MP_BINARY_OP_MORE_EQUAL: return mp_obj_new_bool(lhs_val >= rhs_val);
+                case MP_BINARY_OP_LESS:
+                    return mp_obj_new_bool(lhs_val < rhs_val);
+                case MP_BINARY_OP_MORE:
+                    return mp_obj_new_bool(lhs_val > rhs_val);
+                case MP_BINARY_OP_LESS_EQUAL:
+                    return mp_obj_new_bool(lhs_val <= rhs_val);
+                case MP_BINARY_OP_MORE_EQUAL:
+                    return mp_obj_new_bool(lhs_val >= rhs_val);
 
                 default:
                     goto unsupported_op;
@@ -519,7 +533,7 @@
             } else {
                 return mp_obj_new_int_from_ll(lhs_val);
             }
-#if MICROPY_PY_BUILTINS_FLOAT
+        #if MICROPY_PY_BUILTINS_FLOAT
         } else if (mp_obj_is_float(rhs)) {
             mp_obj_t res = mp_obj_float_binary_op(op, lhs_val, rhs);
             if (res == MP_OBJ_NULL) {
@@ -527,8 +541,8 @@
             } else {
                 return res;
             }
-#endif
-#if MICROPY_PY_BUILTINS_COMPLEX
+        #endif
+        #if MICROPY_PY_BUILTINS_COMPLEX
         } else if (mp_obj_is_type(rhs, &mp_type_complex)) {
             mp_obj_t res = mp_obj_complex_binary_op(op, lhs_val, 0, rhs);
             if (res == MP_OBJ_NULL) {
@@ -536,7 +550,7 @@
             } else {
                 return res;
             }
-#endif
+        #endif
         }
     }
 
@@ -559,7 +573,7 @@
         }
     }
 
-#if MICROPY_PY_REVERSE_SPECIAL_METHODS
+    #if MICROPY_PY_REVERSE_SPECIAL_METHODS
     if (op >= MP_BINARY_OP_OR && op <= MP_BINARY_OP_POWER) {
         mp_obj_t t = rhs;
         rhs = lhs;
@@ -573,7 +587,7 @@
         lhs = t;
         op -= MP_BINARY_OP_REVERSE_OR - MP_BINARY_OP_OR;
     }
-#endif
+    #endif
 
     if (op == MP_BINARY_OP_CONTAINS) {
         // If type didn't support containment then explicitly walk the iterator.
@@ -1000,7 +1014,7 @@
 void mp_convert_member_lookup(mp_obj_t self, const mp_obj_type_t *type, mp_obj_t member, mp_obj_t *dest) {
     if (mp_obj_is_type(member, &mp_type_staticmethod)) {
         // return just the function
-        dest[0] = ((mp_obj_static_class_method_t*)MP_OBJ_TO_PTR(member))->fun;
+        dest[0] = ((mp_obj_static_class_method_t *)MP_OBJ_TO_PTR(member))->fun;
     } else if (mp_obj_is_type(member, &mp_type_classmethod)) {
         // return a bound method, with self being the type of this object
         // this type should be the type of the original instance, not the base
@@ -1008,18 +1022,18 @@
         if (self != MP_OBJ_NULL) {
             type = mp_obj_get_type(self);
         }
-        dest[0] = ((mp_obj_static_class_method_t*)MP_OBJ_TO_PTR(member))->fun;
+        dest[0] = ((mp_obj_static_class_method_t *)MP_OBJ_TO_PTR(member))->fun;
         dest[1] = MP_OBJ_FROM_PTR(type);
     } else if (mp_obj_is_type(member, &mp_type_type)) {
         // Don't try to bind types (even though they're callable)
         dest[0] = member;
     } else if (mp_obj_is_fun(member)
-        || (mp_obj_is_obj(member)
-            && (((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_closure
-                || ((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_generator))) {
+               || (mp_obj_is_obj(member)
+                   && (((mp_obj_base_t *)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_closure
+                       || ((mp_obj_base_t *)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_generator))) {
         // only functions, closures and generators objects can be bound to self
         #if MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
-        const mp_obj_type_t *m_type = ((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type;
+        const mp_obj_type_t *m_type = ((mp_obj_base_t *)MP_OBJ_TO_PTR(member))->type;
         if (self == MP_OBJ_NULL
             && (m_type == &mp_type_fun_builtin_0
                 || m_type == &mp_type_fun_builtin_1
@@ -1098,7 +1112,7 @@
             if (mp_obj_is_type(base, &mp_type_type)) {
                 mp_raise_msg_varg(&mp_type_AttributeError,
                     "type object '%q' has no attribute '%q'",
-                    ((mp_obj_type_t*)MP_OBJ_TO_PTR(base))->name, attr);
+                    ((mp_obj_type_t *)MP_OBJ_TO_PTR(base))->name, attr);
             } else {
                 mp_raise_msg_varg(&mp_type_AttributeError,
                     "'%s' object has no attribute '%q'",
@@ -1116,7 +1130,7 @@
         nlr_pop();
     } else {
         if (!catch_all_exc
-            && !mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t*)nlr.ret_val)->type),
+            && !mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type),
                 MP_OBJ_FROM_PTR(&mp_type_AttributeError))) {
             // Re-raise the exception
             nlr_raise(MP_OBJ_FROM_PTR(nlr.ret_val));
@@ -1231,7 +1245,7 @@
                 nlr_pop();
                 return ret;
             } else {
-                if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t*)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) {
+                if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) {
                     return MP_OBJ_STOP_ITERATION;
                 } else {
                     nlr_jump(nlr.ret_val);
@@ -1376,7 +1390,7 @@
 
     if (dest[1] != MP_OBJ_NULL) {
         // Hopefully we can't import bound method from an object
-import_error:
+    import_error:
         mp_raise_msg_varg(&mp_type_ImportError, "cannot import name %q", name);
     }
 
diff --git a/py/runtime.h b/py/runtime.h
index 46e0887..85c377f 100644
--- a/py/runtime.h
+++ b/py/runtime.h
@@ -71,7 +71,9 @@
 #if MICROPY_ENABLE_SCHEDULER
 void mp_sched_lock(void);
 void mp_sched_unlock(void);
-static inline unsigned int mp_sched_num_pending(void) { return MP_STATE_VM(sched_len); }
+static inline unsigned int mp_sched_num_pending(void) {
+    return MP_STATE_VM(sched_len);
+}
 bool mp_sched_schedule(mp_obj_t function, mp_obj_t arg);
 #endif
 
@@ -87,10 +89,18 @@
 NORETURN void mp_arg_error_terse_mismatch(void);
 NORETURN void mp_arg_error_unimpl_kw(void);
 
-static inline mp_obj_dict_t *mp_locals_get(void) { return MP_STATE_THREAD(dict_locals); }
-static inline void mp_locals_set(mp_obj_dict_t *d) { MP_STATE_THREAD(dict_locals) = d; }
-static inline mp_obj_dict_t *mp_globals_get(void) { return MP_STATE_THREAD(dict_globals); }
-static inline void mp_globals_set(mp_obj_dict_t *d) { MP_STATE_THREAD(dict_globals) = d; }
+static inline mp_obj_dict_t *mp_locals_get(void) {
+    return MP_STATE_THREAD(dict_locals);
+}
+static inline void mp_locals_set(mp_obj_dict_t *d) {
+    MP_STATE_THREAD(dict_locals) = d;
+}
+static inline mp_obj_dict_t *mp_globals_get(void) {
+    return MP_STATE_THREAD(dict_globals);
+}
+static inline void mp_globals_set(mp_obj_dict_t *d) {
+    MP_STATE_THREAD(dict_globals) = d;
+}
 
 mp_obj_t mp_load_name(qstr qst);
 mp_obj_t mp_load_global(qstr qst);
diff --git a/py/scope.c b/py/scope.c
index d996731..1e45139 100644
--- a/py/scope.c
+++ b/py/scope.c
@@ -47,7 +47,7 @@
     scope->source_file = source_file;
     if (kind == SCOPE_FUNCTION || kind == SCOPE_CLASS) {
         assert(MP_PARSE_NODE_IS_STRUCT(pn));
-        scope->simple_name = MP_PARSE_NODE_LEAF_ARG(((mp_parse_node_struct_t*)pn)->nodes[0]);
+        scope->simple_name = MP_PARSE_NODE_LEAF_ARG(((mp_parse_node_struct_t *)pn)->nodes[0]);
     } else {
         scope->simple_name = scope_simple_name_table[kind];
     }
diff --git a/py/sequence.c b/py/sequence.c
index 94a9bb9..c9cb041 100644
--- a/py/sequence.c
+++ b/py/sequence.c
@@ -39,7 +39,7 @@
     for (size_t i = 0; i < times; i++) {
         size_t copy_sz = item_sz * len;
         memcpy(dest, items, copy_sz);
-        dest = (char*)dest + copy_sz;
+        dest = (char *)dest + copy_sz;
     }
 }
 
@@ -96,7 +96,7 @@
 
     // Let's deal only with > & >=
     if (op == MP_BINARY_OP_LESS || op == MP_BINARY_OP_LESS_EQUAL) {
-        SWAP(const byte*, data1, data2);
+        SWAP(const byte *, data1, data2);
         SWAP(size_t, len1, len2);
         if (op == MP_BINARY_OP_LESS) {
             op = MP_BINARY_OP_MORE;
@@ -163,7 +163,7 @@
         }
 
         // Otherwise, application of relation op gives the answer
-        return (mp_binary_op(op, items1[i], items2[i]) == mp_const_true);
+        return mp_binary_op(op, items1[i], items2[i]) == mp_const_true;
     }
 
     // If we had tie in the last element...
@@ -208,9 +208,9 @@
 mp_obj_t mp_seq_count_obj(const mp_obj_t *items, size_t len, mp_obj_t value) {
     size_t count = 0;
     for (size_t i = 0; i < len; i++) {
-         if (mp_obj_equal(items[i], value)) {
-              count++;
-         }
+        if (mp_obj_equal(items[i], value)) {
+            count++;
+        }
     }
 
     // Common sense says this cannot overflow small int
diff --git a/py/showbc.c b/py/showbc.c
index d154511..4d6527f 100644
--- a/py/showbc.c
+++ b/py/showbc.c
@@ -36,10 +36,10 @@
 #define printf(...) mp_printf(&mp_plat_print, __VA_ARGS__)
 
 #define DECODE_UINT { \
-    unum = 0; \
-    do { \
-        unum = (unum << 7) + (*ip & 0x7f); \
-    } while ((*ip++ & 0x80) != 0); \
+        unum = 0; \
+        do { \
+            unum = (unum << 7) + (*ip & 0x7f); \
+        } while ((*ip++ & 0x80) != 0); \
 }
 #define DECODE_ULABEL do { unum = (ip[0] | (ip[1] << 8)); ip += 2; } while (0)
 #define DECODE_SLABEL do { unum = (ip[0] | (ip[1] << 8)) - 0x8000; ip += 2; } while (0)
@@ -59,20 +59,20 @@
 #else
 
 #define DECODE_QSTR { \
-    qst = 0; \
-    do { \
-        qst = (qst << 7) + (*ip & 0x7f); \
-    } while ((*ip++ & 0x80) != 0); \
+        qst = 0; \
+        do { \
+            qst = (qst << 7) + (*ip & 0x7f); \
+        } while ((*ip++ & 0x80) != 0); \
 }
 #define DECODE_PTR do { \
-    ip = (byte*)MP_ALIGN(ip, sizeof(void*)); \
-    unum = (uintptr_t)*(void**)ip; \
-    ip += sizeof(void*); \
+        ip = (byte *)MP_ALIGN(ip, sizeof(void *)); \
+        unum = (uintptr_t)*(void **)ip; \
+        ip += sizeof(void *); \
 } while (0)
 #define DECODE_OBJ do { \
-    ip = (byte*)MP_ALIGN(ip, sizeof(mp_obj_t)); \
-    unum = (mp_uint_t)*(mp_obj_t*)ip; \
-    ip += sizeof(mp_obj_t); \
+        ip = (byte *)MP_ALIGN(ip, sizeof(mp_obj_t)); \
+        unum = (mp_uint_t)*(mp_obj_t *)ip; \
+        ip += sizeof(mp_obj_t); \
 } while (0)
 
 #endif
@@ -135,7 +135,7 @@
         mp_int_t bc = 0;
         mp_uint_t source_line = 1;
         printf("  bc=" INT_FMT " line=" UINT_FMT "\n", bc, source_line);
-        for (const byte* ci = code_info; *ci;) {
+        for (const byte *ci = code_info; *ci;) {
             if ((ci[0] & 0x80) == 0) {
                 // 0b0LLBBBBB encoding
                 bc += ci[0] & 0x1f;
@@ -422,12 +422,12 @@
             printf("BUILD_SET " UINT_FMT, unum);
             break;
 
-#if MICROPY_PY_BUILTINS_SLICE
+        #if MICROPY_PY_BUILTINS_SLICE
         case MP_BC_BUILD_SLICE:
             DECODE_UINT;
             printf("BUILD_SLICE " UINT_FMT, unum);
             break;
-#endif
+        #endif
 
         case MP_BC_STORE_COMP:
             DECODE_UINT;
@@ -446,25 +446,25 @@
 
         case MP_BC_MAKE_FUNCTION:
             DECODE_PTR;
-            printf("MAKE_FUNCTION %p", (void*)(uintptr_t)unum);
+            printf("MAKE_FUNCTION %p", (void *)(uintptr_t)unum);
             break;
 
         case MP_BC_MAKE_FUNCTION_DEFARGS:
             DECODE_PTR;
-            printf("MAKE_FUNCTION_DEFARGS %p", (void*)(uintptr_t)unum);
+            printf("MAKE_FUNCTION_DEFARGS %p", (void *)(uintptr_t)unum);
             break;
 
         case MP_BC_MAKE_CLOSURE: {
             DECODE_PTR;
             mp_uint_t n_closed_over = *ip++;
-            printf("MAKE_CLOSURE %p " UINT_FMT, (void*)(uintptr_t)unum, n_closed_over);
+            printf("MAKE_CLOSURE %p " UINT_FMT, (void *)(uintptr_t)unum, n_closed_over);
             break;
         }
 
         case MP_BC_MAKE_CLOSURE_DEFARGS: {
             DECODE_PTR;
             mp_uint_t n_closed_over = *ip++;
-            printf("MAKE_CLOSURE_DEFARGS %p " UINT_FMT, (void*)(uintptr_t)unum, n_closed_over);
+            printf("MAKE_CLOSURE_DEFARGS %p " UINT_FMT, (void *)(uintptr_t)unum, n_closed_over);
             break;
         }
 
diff --git a/py/stackctrl.c b/py/stackctrl.c
index 5c07796..c2f3adb 100644
--- a/py/stackctrl.c
+++ b/py/stackctrl.c
@@ -29,7 +29,7 @@
 
 void mp_stack_ctrl_init(void) {
     volatile int stack_dummy;
-    MP_STATE_THREAD(stack_top) = (char*)&stack_dummy;
+    MP_STATE_THREAD(stack_top) = (char *)&stack_dummy;
 }
 
 void mp_stack_set_top(void *top) {
@@ -39,7 +39,7 @@
 mp_uint_t mp_stack_usage(void) {
     // Assumes descending stack
     volatile int stack_dummy;
-    return MP_STATE_THREAD(stack_top) - (char*)&stack_dummy;
+    return MP_STATE_THREAD(stack_top) - (char *)&stack_dummy;
 }
 
 #if MICROPY_STACK_CHECK
diff --git a/py/stream.c b/py/stream.c
index d795681..9d87eb1 100644
--- a/py/stream.c
+++ b/py/stream.c
@@ -227,7 +227,7 @@
 
 mp_obj_t mp_stream_write(mp_obj_t self_in, const void *buf, size_t len, byte flags) {
     int error;
-    mp_uint_t out_sz = mp_stream_rw(self_in, (void*)buf, len, &error, flags);
+    mp_uint_t out_sz = mp_stream_rw(self_in, (void *)buf, len, &error, flags);
     if (error != 0) {
         if (mp_is_nonblocking_error(error)) {
             // http://docs.python.org/3/library/io.html#io.RawIOBase.write
@@ -261,7 +261,7 @@
         }
     }
     bufinfo.len -= off;
-    return mp_stream_write(args[0], (byte*)bufinfo.buf + off, MIN(bufinfo.len, max_len), MP_STREAM_RW_WRITE);
+    return mp_stream_write(args[0], (byte *)bufinfo.buf + off, MIN(bufinfo.len, max_len), MP_STREAM_RW_WRITE);
 }
 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_write_obj, 2, 4, stream_write_method);
 
@@ -378,7 +378,7 @@
             mp_raise_OSError(error);
         }
         if (out_sz == 0) {
-done:
+        done:
             // Back out previously added byte
             // Consider, what's better - read a char and get OutOfMemory (so read
             // char is lost), or allocate first as we do.
@@ -508,7 +508,7 @@
 int mp_stream_errno;
 
 ssize_t mp_stream_posix_write(void *stream, const void *buf, size_t len) {
-    mp_obj_base_t* o = stream;
+    mp_obj_base_t *o = stream;
     const mp_stream_p_t *stream_p = o->type->protocol;
     mp_uint_t out_sz = stream_p->write(MP_OBJ_FROM_PTR(stream), buf, len, &mp_stream_errno);
     if (out_sz == MP_STREAM_ERROR) {
@@ -519,7 +519,7 @@
 }
 
 ssize_t mp_stream_posix_read(void *stream, void *buf, size_t len) {
-    mp_obj_base_t* o = stream;
+    mp_obj_base_t *o = stream;
     const mp_stream_p_t *stream_p = o->type->protocol;
     mp_uint_t out_sz = stream_p->read(MP_OBJ_FROM_PTR(stream), buf, len, &mp_stream_errno);
     if (out_sz == MP_STREAM_ERROR) {
@@ -530,7 +530,7 @@
 }
 
 off_t mp_stream_posix_lseek(void *stream, off_t offset, int whence) {
-    const mp_obj_base_t* o = stream;
+    const mp_obj_base_t *o = stream;
     const mp_stream_p_t *stream_p = o->type->protocol;
     struct mp_stream_seek_t seek_s;
     seek_s.offset = offset;
@@ -543,7 +543,7 @@
 }
 
 int mp_stream_posix_fsync(void *stream) {
-    mp_obj_base_t* o = stream;
+    mp_obj_base_t *o = stream;
     const mp_stream_p_t *stream_p = o->type->protocol;
     mp_uint_t res = stream_p->ioctl(MP_OBJ_FROM_PTR(stream), MP_STREAM_FLUSH, 0, &mp_stream_errno);
     if (res == MP_STREAM_ERROR) {
diff --git a/py/stream.h b/py/stream.h
index 3ebd4e0..96f439c 100644
--- a/py/stream.h
+++ b/py/stream.h
@@ -95,7 +95,7 @@
 
 // Object is assumed to have a non-NULL stream protocol with valid r/w/ioctl methods
 static inline const mp_stream_p_t *mp_get_stream(mp_const_obj_t self) {
-    return (const mp_stream_p_t*)((const mp_obj_base_t*)MP_OBJ_TO_PTR(self))->type->protocol;
+    return (const mp_stream_p_t *)((const mp_obj_base_t *)MP_OBJ_TO_PTR(self))->type->protocol;
 }
 
 const mp_stream_p_t *mp_get_stream_raise(mp_obj_t self_in, int flags);
@@ -111,7 +111,7 @@
 #define MP_STREAM_RW_WRITE 2
 #define MP_STREAM_RW_ONCE  1
 mp_uint_t mp_stream_rw(mp_obj_t stream, void *buf, mp_uint_t size, int *errcode, byte flags);
-#define mp_stream_write_exactly(stream, buf, size, err) mp_stream_rw(stream, (byte*)buf, size, err, MP_STREAM_RW_WRITE)
+#define mp_stream_write_exactly(stream, buf, size, err) mp_stream_rw(stream, (byte *)buf, size, err, MP_STREAM_RW_WRITE)
 #define mp_stream_read_exactly(stream, buf, size, err) mp_stream_rw(stream, buf, size, err, MP_STREAM_RW_READ)
 
 void mp_stream_write_adaptor(void *self, const char *buf, size_t len);
diff --git a/py/unicode.c b/py/unicode.c
index 369240e..5acaad3 100644
--- a/py/unicode.c
+++ b/py/unicode.c
@@ -71,7 +71,9 @@
 
 unichar utf8_get_char(const byte *s) {
     unichar ord = *s++;
-    if (!UTF8_IS_NONASCII(ord)) return ord;
+    if (!UTF8_IS_NONASCII(ord)) {
+        return ord;
+    }
     ord &= 0x7F;
     for (unichar mask = 0x40; ord & mask; mask >>= 1) {
         ord &= ~mask;
diff --git a/py/vstr.c b/py/vstr.c
index 6f48018..56327b5 100644
--- a/py/vstr.c
+++ b/py/vstr.c
@@ -140,37 +140,37 @@
 }
 
 void vstr_add_byte(vstr_t *vstr, byte b) {
-    byte *buf = (byte*)vstr_add_len(vstr, 1);
+    byte *buf = (byte *)vstr_add_len(vstr, 1);
     buf[0] = b;
 }
 
 void vstr_add_char(vstr_t *vstr, unichar c) {
-#if MICROPY_PY_BUILTINS_STR_UNICODE
+    #if MICROPY_PY_BUILTINS_STR_UNICODE
     // TODO: Can this be simplified and deduplicated?
     // Is it worth just calling vstr_add_len(vstr, 4)?
     if (c < 0x80) {
-        byte *buf = (byte*)vstr_add_len(vstr, 1);
+        byte *buf = (byte *)vstr_add_len(vstr, 1);
         *buf = (byte)c;
     } else if (c < 0x800) {
-        byte *buf = (byte*)vstr_add_len(vstr, 2);
+        byte *buf = (byte *)vstr_add_len(vstr, 2);
         buf[0] = (c >> 6) | 0xC0;
         buf[1] = (c & 0x3F) | 0x80;
     } else if (c < 0x10000) {
-        byte *buf = (byte*)vstr_add_len(vstr, 3);
+        byte *buf = (byte *)vstr_add_len(vstr, 3);
         buf[0] = (c >> 12) | 0xE0;
         buf[1] = ((c >> 6) & 0x3F) | 0x80;
         buf[2] = (c & 0x3F) | 0x80;
     } else {
         assert(c < 0x110000);
-        byte *buf = (byte*)vstr_add_len(vstr, 4);
+        byte *buf = (byte *)vstr_add_len(vstr, 4);
         buf[0] = (c >> 18) | 0xF0;
         buf[1] = ((c >> 12) & 0x3F) | 0x80;
         buf[2] = ((c >> 6) & 0x3F) | 0x80;
         buf[3] = (c & 0x3F) | 0x80;
     }
-#else
+    #else
     vstr_add_byte(vstr, c);
-#endif
+    #endif
 }
 
 void vstr_add_str(vstr_t *vstr, const char *str) {
diff --git a/tools/dfu.py b/tools/dfu.py
index ee89c75..6591436 100755
--- a/tools/dfu.py
+++ b/tools/dfu.py
@@ -4,122 +4,160 @@
 # Distributed under Gnu LGPL 3.0
 # see http://www.gnu.org/licenses/lgpl-3.0.txt
 
-import sys,struct,zlib,os
+import sys, struct, zlib, os
 from optparse import OptionParser
 
-DEFAULT_DEVICE="0x0483:0xdf11"
+DEFAULT_DEVICE = "0x0483:0xdf11"
 
-def named(tuple,names):
-  return dict(zip(names.split(),tuple))
-def consume(fmt,data,names):
-  n = struct.calcsize(fmt)
-  return named(struct.unpack(fmt,data[:n]),names),data[n:]
+
+def named(tuple, names):
+    return dict(zip(names.split(), tuple))
+
+
+def consume(fmt, data, names):
+    n = struct.calcsize(fmt)
+    return named(struct.unpack(fmt, data[:n]), names), data[n:]
+
+
 def cstring(string):
-  return string.split('\0',1)[0]
+    return string.split("\0", 1)[0]
+
+
 def compute_crc(data):
-  return 0xFFFFFFFF & -zlib.crc32(data) -1
+    return 0xFFFFFFFF & -zlib.crc32(data) - 1
 
-def parse(file,dump_images=False):
-  print ('File: "%s"' % file)
-  data = open(file,'rb').read()
-  crc = compute_crc(data[:-4])
-  prefix, data = consume('<5sBIB',data,'signature version size targets')
-  print ('%(signature)s v%(version)d, image size: %(size)d, targets: %(targets)d' % prefix)
-  for t in range(prefix['targets']):
-    tprefix, data  = consume('<6sBI255s2I',data,'signature altsetting named name size elements')
-    tprefix['num'] = t
-    if tprefix['named']:
-      tprefix['name'] = cstring(tprefix['name'])
-    else:
-      tprefix['name'] = ''
-    print ('%(signature)s %(num)d, alt setting: %(altsetting)s, name: "%(name)s", size: %(size)d, elements: %(elements)d' % tprefix)
-    tsize = tprefix['size']
-    target, data = data[:tsize], data[tsize:]
-    for e in range(tprefix['elements']):
-      eprefix, target = consume('<2I',target,'address size')
-      eprefix['num'] = e
-      print ('  %(num)d, address: 0x%(address)08x, size: %(size)d' % eprefix)
-      esize = eprefix['size']
-      image, target = target[:esize], target[esize:]
-      if dump_images:
-        out = '%s.target%d.image%d.bin' % (file,t,e)
-        open(out,'wb').write(image)
-        print ('    DUMPED IMAGE TO "%s"' % out)
-    if len(target):
-      print ("target %d: PARSE ERROR" % t)
-  suffix = named(struct.unpack('<4H3sBI',data[:16]),'device product vendor dfu ufd len crc')
-  print ('usb: %(vendor)04x:%(product)04x, device: 0x%(device)04x, dfu: 0x%(dfu)04x, %(ufd)s, %(len)d, 0x%(crc)08x' % suffix)
-  if crc != suffix['crc']:
-    print ("CRC ERROR: computed crc32 is 0x%08x" % crc)
-  data = data[16:]
-  if data:
-    print ("PARSE ERROR")
 
-def build(file,targets,device=DEFAULT_DEVICE):
-  data = b''
-  for t,target in enumerate(targets):
-    tdata = b''
-    for image in target:
-      # pad image to 8 bytes (needed at least for L476)
-      pad = (8 - len(image['data']) % 8 ) % 8
-      image['data'] = image['data'] + bytes(bytearray(8)[0:pad])
-      #
-      tdata += struct.pack('<2I',image['address'],len(image['data']))+image['data']
-    tdata = struct.pack('<6sBI255s2I',b'Target',0,1, b'ST...',len(tdata),len(target)) + tdata
-    data += tdata
-  data  = struct.pack('<5sBIB',b'DfuSe',1,len(data)+11,len(targets)) + data
-  v,d=map(lambda x: int(x,0) & 0xFFFF, device.split(':',1))
-  data += struct.pack('<4H3sB',0,d,v,0x011a,b'UFD',16)
-  crc   = compute_crc(data)
-  data += struct.pack('<I',crc)
-  open(file,'wb').write(data)
+def parse(file, dump_images=False):
+    print('File: "%s"' % file)
+    data = open(file, "rb").read()
+    crc = compute_crc(data[:-4])
+    prefix, data = consume("<5sBIB", data, "signature version size targets")
+    print("%(signature)s v%(version)d, image size: %(size)d, targets: %(targets)d" % prefix)
+    for t in range(prefix["targets"]):
+        tprefix, data = consume(
+            "<6sBI255s2I", data, "signature altsetting named name size elements"
+        )
+        tprefix["num"] = t
+        if tprefix["named"]:
+            tprefix["name"] = cstring(tprefix["name"])
+        else:
+            tprefix["name"] = ""
+        print(
+            '%(signature)s %(num)d, alt setting: %(altsetting)s, name: "%(name)s", size: %(size)d, elements: %(elements)d'
+            % tprefix
+        )
+        tsize = tprefix["size"]
+        target, data = data[:tsize], data[tsize:]
+        for e in range(tprefix["elements"]):
+            eprefix, target = consume("<2I", target, "address size")
+            eprefix["num"] = e
+            print("  %(num)d, address: 0x%(address)08x, size: %(size)d" % eprefix)
+            esize = eprefix["size"]
+            image, target = target[:esize], target[esize:]
+            if dump_images:
+                out = "%s.target%d.image%d.bin" % (file, t, e)
+                open(out, "wb").write(image)
+                print('    DUMPED IMAGE TO "%s"' % out)
+        if len(target):
+            print("target %d: PARSE ERROR" % t)
+    suffix = named(struct.unpack("<4H3sBI", data[:16]), "device product vendor dfu ufd len crc")
+    print(
+        "usb: %(vendor)04x:%(product)04x, device: 0x%(device)04x, dfu: 0x%(dfu)04x, %(ufd)s, %(len)d, 0x%(crc)08x"
+        % suffix
+    )
+    if crc != suffix["crc"]:
+        print("CRC ERROR: computed crc32 is 0x%08x" % crc)
+    data = data[16:]
+    if data:
+        print("PARSE ERROR")
 
-if __name__=="__main__":
-  usage = """
+
+def build(file, targets, device=DEFAULT_DEVICE):
+    data = b""
+    for t, target in enumerate(targets):
+        tdata = b""
+        for image in target:
+            # pad image to 8 bytes (needed at least for L476)
+            pad = (8 - len(image["data"]) % 8) % 8
+            image["data"] = image["data"] + bytes(bytearray(8)[0:pad])
+            #
+            tdata += struct.pack("<2I", image["address"], len(image["data"])) + image["data"]
+        tdata = (
+            struct.pack("<6sBI255s2I", b"Target", 0, 1, b"ST...", len(tdata), len(target)) + tdata
+        )
+        data += tdata
+    data = struct.pack("<5sBIB", b"DfuSe", 1, len(data) + 11, len(targets)) + data
+    v, d = map(lambda x: int(x, 0) & 0xFFFF, device.split(":", 1))
+    data += struct.pack("<4H3sB", 0, d, v, 0x011A, b"UFD", 16)
+    crc = compute_crc(data)
+    data += struct.pack("<I", crc)
+    open(file, "wb").write(data)
+
+
+if __name__ == "__main__":
+    usage = """
 %prog [-d|--dump] infile.dfu
 %prog {-b|--build} address:file.bin [-b address:file.bin ...] [{-D|--device}=vendor:device] outfile.dfu"""
-  parser = OptionParser(usage=usage)
-  parser.add_option("-b", "--build", action="append", dest="binfiles",
-    help="build a DFU file from given BINFILES", metavar="BINFILES")
-  parser.add_option("-D", "--device", action="store", dest="device",
-    help="build for DEVICE, defaults to %s" % DEFAULT_DEVICE, metavar="DEVICE")
-  parser.add_option("-d", "--dump", action="store_true", dest="dump_images",
-    default=False, help="dump contained images to current directory")
-  (options, args) = parser.parse_args()
+    parser = OptionParser(usage=usage)
+    parser.add_option(
+        "-b",
+        "--build",
+        action="append",
+        dest="binfiles",
+        help="build a DFU file from given BINFILES",
+        metavar="BINFILES",
+    )
+    parser.add_option(
+        "-D",
+        "--device",
+        action="store",
+        dest="device",
+        help="build for DEVICE, defaults to %s" % DEFAULT_DEVICE,
+        metavar="DEVICE",
+    )
+    parser.add_option(
+        "-d",
+        "--dump",
+        action="store_true",
+        dest="dump_images",
+        default=False,
+        help="dump contained images to current directory",
+    )
+    (options, args) = parser.parse_args()
 
-  if options.binfiles and len(args)==1:
-    target = []
-    for arg in options.binfiles:
-      try:
-        address,binfile = arg.split(':',1)
-      except ValueError:
-        print ("Address:file couple '%s' invalid." % arg)
+    if options.binfiles and len(args) == 1:
+        target = []
+        for arg in options.binfiles:
+            try:
+                address, binfile = arg.split(":", 1)
+            except ValueError:
+                print("Address:file couple '%s' invalid." % arg)
+                sys.exit(1)
+            try:
+                address = int(address, 0) & 0xFFFFFFFF
+            except ValueError:
+                print("Address %s invalid." % address)
+                sys.exit(1)
+            if not os.path.isfile(binfile):
+                print("Unreadable file '%s'." % binfile)
+                sys.exit(1)
+            target.append({"address": address, "data": open(binfile, "rb").read()})
+        outfile = args[0]
+        device = DEFAULT_DEVICE
+        if options.device:
+            device = options.device
+        try:
+            v, d = map(lambda x: int(x, 0) & 0xFFFF, device.split(":", 1))
+        except:
+            print("Invalid device '%s'." % device)
+            sys.exit(1)
+        build(outfile, [target], device)
+    elif len(args) == 1:
+        infile = args[0]
+        if not os.path.isfile(infile):
+            print("Unreadable file '%s'." % infile)
+            sys.exit(1)
+        parse(infile, dump_images=options.dump_images)
+    else:
+        parser.print_help()
         sys.exit(1)
-      try:
-        address = int(address,0) & 0xFFFFFFFF
-      except ValueError:
-        print ("Address %s invalid." % address)
-        sys.exit(1)
-      if not os.path.isfile(binfile):
-        print ("Unreadable file '%s'." % binfile)
-        sys.exit(1)
-      target.append({ 'address': address, 'data': open(binfile,'rb').read() })
-    outfile = args[0]
-    device = DEFAULT_DEVICE
-    if options.device:
-      device=options.device
-    try:
-      v,d=map(lambda x: int(x,0) & 0xFFFF, device.split(':',1))
-    except:
-      print ("Invalid device '%s'." % device)
-      sys.exit(1)
-    build(outfile,[target],device)
-  elif len(args)==1:
-    infile = args[0]
-    if not os.path.isfile(infile):
-      print ("Unreadable file '%s'." % infile)
-      sys.exit(1)
-    parse(infile, dump_images=options.dump_images)
-  else:
-    parser.print_help()
-    sys.exit(1)
diff --git a/tools/file2h.py b/tools/file2h.py
index 2a04ae2..4607ab9 100644
--- a/tools/file2h.py
+++ b/tools/file2h.py
@@ -12,19 +12,19 @@
 # Can either be set explicitly, or left blank to auto-detect
 # Except auto-detect doesn't work because the file has been passed
 # through Python text processing, which makes all EOL a \n
-line_end = '\\r\\n'
+line_end = "\\r\\n"
 
 if __name__ == "__main__":
     filename = sys.argv[1]
-    for line in open(filename, 'r').readlines():
+    for line in open(filename, "r").readlines():
         if not line_end:
-            for ending in ('\r\n', '\r', '\n'):
+            for ending in ("\r\n", "\r", "\n"):
                 if line.endswith(ending):
-                    line_end = ending.replace('\r', '\\r').replace('\n', '\\n')
+                    line_end = ending.replace("\r", "\\r").replace("\n", "\\n")
                     break
             if not line_end:
                 raise Exception("Couldn't auto-detect line-ending of %s" % filename)
-        line = line.rstrip('\r\n')
-        line = line.replace('\\', '\\\\')
+        line = line.rstrip("\r\n")
+        line = line.replace("\\", "\\\\")
         line = line.replace('"', '\\"')
         print('"%s%s"' % (line, line_end))
diff --git a/tools/gen-cpydiff.py b/tools/gen-cpydiff.py
index 356ade8..c45bad1 100644
--- a/tools/gen-cpydiff.py
+++ b/tools/gen-cpydiff.py
@@ -37,89 +37,128 @@
 # such version should be used to test for differences. If your default python3
 # executable is of lower version, you can point MICROPY_CPYTHON3 environment var
 # to the correct executable.
-if os.name == 'nt':
-    CPYTHON3 = os.getenv('MICROPY_CPYTHON3', 'python3.exe')
-    MICROPYTHON = os.getenv('MICROPY_MICROPYTHON', '../ports/windows/micropython.exe')
+if os.name == "nt":
+    CPYTHON3 = os.getenv("MICROPY_CPYTHON3", "python3.exe")
+    MICROPYTHON = os.getenv("MICROPY_MICROPYTHON", "../ports/windows/micropython.exe")
 else:
-    CPYTHON3 = os.getenv('MICROPY_CPYTHON3', 'python3')
-    MICROPYTHON = os.getenv('MICROPY_MICROPYTHON', '../ports/unix/micropython')
+    CPYTHON3 = os.getenv("MICROPY_CPYTHON3", "python3")
+    MICROPYTHON = os.getenv("MICROPY_MICROPYTHON", "../ports/unix/micropython")
 
-TESTPATH = '../tests/cpydiff/'
-DOCPATH = '../docs/genrst/'
-INDEXTEMPLATE = '../docs/differences/index_template.txt'
-INDEX = 'index.rst'
+TESTPATH = "../tests/cpydiff/"
+DOCPATH = "../docs/genrst/"
+INDEXTEMPLATE = "../docs/differences/index_template.txt"
+INDEX = "index.rst"
 
-HEADER = '.. This document was generated by tools/gen-cpydiff.py\n\n'
-UIMPORTLIST = {'struct', 'collections', 'json'}
-CLASSMAP = {'Core': 'Core language', 'Types': 'Builtin types'}
-INDEXPRIORITY = ['syntax', 'core_language', 'builtin_types', 'modules']
-RSTCHARS = ['=', '-', '~', '`', ':']
+HEADER = ".. This document was generated by tools/gen-cpydiff.py\n\n"
+UIMPORTLIST = {"struct", "collections", "json"}
+CLASSMAP = {"Core": "Core language", "Types": "Builtin types"}
+INDEXPRIORITY = ["syntax", "core_language", "builtin_types", "modules"]
+RSTCHARS = ["=", "-", "~", "`", ":"]
 SPLIT = '"""\n|categories: |description: |cause: |workaround: '
-TAB = '    '
+TAB = "    "
 
-Output = namedtuple('output', ['name', 'class_', 'desc', 'cause', 'workaround', 'code',
-                               'output_cpy', 'output_upy', 'status'])
+Output = namedtuple(
+    "output",
+    [
+        "name",
+        "class_",
+        "desc",
+        "cause",
+        "workaround",
+        "code",
+        "output_cpy",
+        "output_upy",
+        "status",
+    ],
+)
+
 
 def readfiles():
     """ Reads test files """
-    tests = list(filter(lambda x: x.endswith('.py'), os.listdir(TESTPATH)))
+    tests = list(filter(lambda x: x.endswith(".py"), os.listdir(TESTPATH)))
     tests.sort()
     files = []
 
     for test in tests:
-        text = open(TESTPATH + test, 'r').read()
+        text = open(TESTPATH + test, "r").read()
 
         try:
-            class_, desc, cause, workaround, code = [x.rstrip() for x in \
-                                                    list(filter(None, re.split(SPLIT, text)))]
-            output = Output(test, class_, desc, cause, workaround, code, '', '', '')
+            class_, desc, cause, workaround, code = [
+                x.rstrip() for x in list(filter(None, re.split(SPLIT, text)))
+            ]
+            output = Output(test, class_, desc, cause, workaround, code, "", "", "")
             files.append(output)
         except IndexError:
-            print('Incorrect format in file ' + TESTPATH + test)
+            print("Incorrect format in file " + TESTPATH + test)
 
     return files
 
+
 def uimports(code):
     """ converts CPython module names into MicroPython equivalents """
     for uimport in UIMPORTLIST:
-        uimport = bytes(uimport, 'utf8')
-        code = code.replace(uimport, b'u' + uimport)
+        uimport = bytes(uimport, "utf8")
+        code = code.replace(uimport, b"u" + uimport)
     return code
 
+
 def run_tests(tests):
     """ executes all tests """
     results = []
     for test in tests:
-        with open(TESTPATH + test.name, 'rb') as f:
+        with open(TESTPATH + test.name, "rb") as f:
             input_cpy = f.read()
         input_upy = uimports(input_cpy)
 
-        process = subprocess.Popen(CPYTHON3, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
-        output_cpy = [com.decode('utf8') for com in process.communicate(input_cpy)]
+        process = subprocess.Popen(
+            CPYTHON3,
+            shell=True,
+            stdout=subprocess.PIPE,
+            stdin=subprocess.PIPE,
+            stderr=subprocess.PIPE,
+        )
+        output_cpy = [com.decode("utf8") for com in process.communicate(input_cpy)]
 
-        process = subprocess.Popen(MICROPYTHON, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
-        output_upy = [com.decode('utf8') for com in process.communicate(input_upy)]
+        process = subprocess.Popen(
+            MICROPYTHON,
+            shell=True,
+            stdout=subprocess.PIPE,
+            stdin=subprocess.PIPE,
+            stderr=subprocess.PIPE,
+        )
+        output_upy = [com.decode("utf8") for com in process.communicate(input_upy)]
 
         if output_cpy[0] == output_upy[0] and output_cpy[1] == output_upy[1]:
-            status = 'Supported'
-            print('Supported operation!\nFile: ' + TESTPATH + test.name)
+            status = "Supported"
+            print("Supported operation!\nFile: " + TESTPATH + test.name)
         else:
-            status = 'Unsupported'
+            status = "Unsupported"
 
-        output = Output(test.name, test.class_, test.desc, test.cause,
-                        test.workaround, test.code, output_cpy, output_upy, status)
+        output = Output(
+            test.name,
+            test.class_,
+            test.desc,
+            test.cause,
+            test.workaround,
+            test.code,
+            output_cpy,
+            output_upy,
+            status,
+        )
         results.append(output)
 
     results.sort(key=lambda x: x.class_)
     return results
 
+
 def indent(block, spaces):
     """ indents paragraphs of text for rst formatting """
-    new_block = ''
-    for line in block.split('\n'):
-        new_block += spaces + line + '\n'
+    new_block = ""
+    for line in block.split("\n"):
+        new_block += spaces + line + "\n"
     return new_block
 
+
 def gen_table(contents):
     """ creates a table given any set of columns """
     xlengths = []
@@ -127,31 +166,32 @@
     for column in contents:
         col_len = 0
         for entry in column:
-            lines = entry.split('\n')
+            lines = entry.split("\n")
             for line in lines:
                 col_len = max(len(line) + 2, col_len)
         xlengths.append(col_len)
     for i in range(len(contents[0])):
         ymax = 0
         for j in range(len(contents)):
-            ymax = max(ymax, len(contents[j][i].split('\n')))
+            ymax = max(ymax, len(contents[j][i].split("\n")))
         ylengths.append(ymax)
 
-    table_divider = '+' + ''.join(['-' * i + '+' for i in xlengths]) + '\n'
+    table_divider = "+" + "".join(["-" * i + "+" for i in xlengths]) + "\n"
     table = table_divider
     for i in range(len(ylengths)):
         row = [column[i] for column in contents]
-        row = [entry + '\n' * (ylengths[i]-len(entry.split('\n'))) for entry in row]
-        row = [entry.split('\n') for entry in row]
+        row = [entry + "\n" * (ylengths[i] - len(entry.split("\n"))) for entry in row]
+        row = [entry.split("\n") for entry in row]
         for j in range(ylengths[i]):
             k = 0
             for entry in row:
                 width = xlengths[k]
-                table += ''.join(['| {:{}}'.format(entry[j], width - 1)])
+                table += "".join(["| {:{}}".format(entry[j], width - 1)])
                 k += 1
-            table += '|\n'
+            table += "|\n"
         table += table_divider
-    return table + '\n'
+    return table + "\n"
+
 
 def gen_rst(results):
     """ creates restructured text documents to display tests """
@@ -166,61 +206,63 @@
     toctree = []
     class_ = []
     for output in results:
-        section = output.class_.split(',')
+        section = output.class_.split(",")
         for i in range(len(section)):
             section[i] = section[i].rstrip()
             if section[i] in CLASSMAP:
                 section[i] = CLASSMAP[section[i]]
             if i >= len(class_) or section[i] != class_[i]:
                 if i == 0:
-                    filename = section[i].replace(' ', '_').lower()
-                    rst = open(DOCPATH + filename + '.rst', 'w')
+                    filename = section[i].replace(" ", "_").lower()
+                    rst = open(DOCPATH + filename + ".rst", "w")
                     rst.write(HEADER)
-                    rst.write(section[i] + '\n')
+                    rst.write(section[i] + "\n")
                     rst.write(RSTCHARS[0] * len(section[i]))
                     rst.write(time.strftime("\nGenerated %a %d %b %Y %X UTC\n\n", time.gmtime()))
                     toctree.append(filename)
                 else:
-                    rst.write(section[i] + '\n')
-                    rst.write(RSTCHARS[min(i, len(RSTCHARS)-1)] * len(section[i]))
-                    rst.write('\n\n')
+                    rst.write(section[i] + "\n")
+                    rst.write(RSTCHARS[min(i, len(RSTCHARS) - 1)] * len(section[i]))
+                    rst.write("\n\n")
         class_ = section
-        rst.write('.. _cpydiff_%s:\n\n' % output.name.rsplit('.', 1)[0])
-        rst.write(output.desc + '\n')
-        rst.write('~' * len(output.desc) + '\n\n')
-        if output.cause != 'Unknown':
-            rst.write('**Cause:** ' + output.cause + '\n\n')
-        if output.workaround != 'Unknown':
-            rst.write('**Workaround:** ' + output.workaround + '\n\n')
+        rst.write(".. _cpydiff_%s:\n\n" % output.name.rsplit(".", 1)[0])
+        rst.write(output.desc + "\n")
+        rst.write("~" * len(output.desc) + "\n\n")
+        if output.cause != "Unknown":
+            rst.write("**Cause:** " + output.cause + "\n\n")
+        if output.workaround != "Unknown":
+            rst.write("**Workaround:** " + output.workaround + "\n\n")
 
-        rst.write('Sample code::\n\n' + indent(output.code, TAB) + '\n')
-        output_cpy = indent(''.join(output.output_cpy[0:2]), TAB).rstrip()
-        output_cpy = ('::\n\n' if output_cpy != '' else '') + output_cpy
-        output_upy = indent(''.join(output.output_upy[0:2]), TAB).rstrip()
-        output_upy = ('::\n\n' if output_upy != '' else '') + output_upy
-        table = gen_table([['CPy output:', output_cpy], ['uPy output:', output_upy]])
+        rst.write("Sample code::\n\n" + indent(output.code, TAB) + "\n")
+        output_cpy = indent("".join(output.output_cpy[0:2]), TAB).rstrip()
+        output_cpy = ("::\n\n" if output_cpy != "" else "") + output_cpy
+        output_upy = indent("".join(output.output_upy[0:2]), TAB).rstrip()
+        output_upy = ("::\n\n" if output_upy != "" else "") + output_upy
+        table = gen_table([["CPy output:", output_cpy], ["uPy output:", output_upy]])
         rst.write(table)
 
-    template = open(INDEXTEMPLATE, 'r')
-    index = open(DOCPATH + INDEX, 'w')
+    template = open(INDEXTEMPLATE, "r")
+    index = open(DOCPATH + INDEX, "w")
     index.write(HEADER)
     index.write(template.read())
     for section in INDEXPRIORITY:
         if section in toctree:
-            index.write(indent(section + '.rst', TAB))
+            index.write(indent(section + ".rst", TAB))
             toctree.remove(section)
     for section in toctree:
-        index.write(indent(section + '.rst', TAB))
+        index.write(indent(section + ".rst", TAB))
+
 
 def main():
     """ Main function """
 
     # set search path so that test scripts find the test modules (and no other ones)
-    os.environ['PYTHONPATH'] = TESTPATH
-    os.environ['MICROPYPATH'] = TESTPATH
+    os.environ["PYTHONPATH"] = TESTPATH
+    os.environ["MICROPYPATH"] = TESTPATH
 
     files = readfiles()
     results = run_tests(files)
     gen_rst(results)
 
+
 main()
diff --git a/tools/gendoc.py b/tools/gendoc.py
index 61844d2..0f13056 100644
--- a/tools/gendoc.py
+++ b/tools/gendoc.py
@@ -15,10 +15,12 @@
             return name, match
     return None, None
 
+
 def makedirs(d):
     if not os.path.isdir(d):
         os.makedirs(d)
 
+
 class Lexer:
     class LexerError(Exception):
         pass
@@ -31,15 +33,15 @@
 
     def __init__(self, file):
         self.filename = file
-        with open(file, 'rt') as f:
+        with open(file, "rt") as f:
             line_num = 0
             lines = []
             for line in f:
                 line_num += 1
                 line = line.strip()
-                if line == '///':
-                    lines.append((line_num, ''))
-                elif line.startswith('/// '):
+                if line == "///":
+                    lines.append((line_num, ""))
+                elif line.startswith("/// "):
                     lines.append((line_num, line[4:]))
                 elif len(lines) > 0 and lines[-1][1] is not None:
                     lines.append((line_num, None))
@@ -64,9 +66,10 @@
                 return l[1]
 
     def error(self, msg):
-        print('({}:{}) {}'.format(self.filename, self.cur_line, msg))
+        print("({}:{}) {}".format(self.filename, self.cur_line, msg))
         raise Lexer.LexerError
 
+
 class MarkdownWriter:
     def __init__(self):
         pass
@@ -75,52 +78,53 @@
         self.lines = []
 
     def end(self):
-        return '\n'.join(self.lines)
+        return "\n".join(self.lines)
 
     def heading(self, level, text):
         if len(self.lines) > 0:
-            self.lines.append('')
-        self.lines.append(level * '#' + ' ' + text)
-        self.lines.append('')
+            self.lines.append("")
+        self.lines.append(level * "#" + " " + text)
+        self.lines.append("")
 
     def para(self, text):
-        if len(self.lines) > 0 and self.lines[-1] != '':
-            self.lines.append('')
+        if len(self.lines) > 0 and self.lines[-1] != "":
+            self.lines.append("")
         if isinstance(text, list):
             self.lines.extend(text)
         elif isinstance(text, str):
             self.lines.append(text)
         else:
             assert False
-        self.lines.append('')
+        self.lines.append("")
 
     def single_line(self, text):
         self.lines.append(text)
 
     def module(self, name, short_descr, descr):
-        self.heading(1, 'module {}'.format(name))
+        self.heading(1, "module {}".format(name))
         self.para(descr)
 
     def function(self, ctx, name, args, descr):
-        proto = '{}.{}{}'.format(ctx, self.name, self.args)
-        self.heading(3, '`' + proto + '`')
+        proto = "{}.{}{}".format(ctx, self.name, self.args)
+        self.heading(3, "`" + proto + "`")
         self.para(descr)
 
     def method(self, ctx, name, args, descr):
-        if name == '\\constructor':
-            proto = '{}{}'.format(ctx, args)
-        elif name == '\\call':
-            proto = '{}{}'.format(ctx, args)
+        if name == "\\constructor":
+            proto = "{}{}".format(ctx, args)
+        elif name == "\\call":
+            proto = "{}{}".format(ctx, args)
         else:
-            proto = '{}.{}{}'.format(ctx, name, args)
-        self.heading(3, '`' + proto + '`')
+            proto = "{}.{}{}".format(ctx, name, args)
+        self.heading(3, "`" + proto + "`")
         self.para(descr)
 
     def constant(self, ctx, name, descr):
-        self.single_line('`{}.{}` - {}'.format(ctx, name, descr))
+        self.single_line("`{}.{}` - {}".format(ctx, name, descr))
+
 
 class ReStructuredTextWriter:
-    head_chars = {1:'=', 2:'-', 3:'.'}
+    head_chars = {1: "=", 2: "-", 3: "."}
 
     def __init__(self):
         pass
@@ -129,23 +133,23 @@
         self.lines = []
 
     def end(self):
-        return '\n'.join(self.lines)
+        return "\n".join(self.lines)
 
     def _convert(self, text):
-        return text.replace('`', '``').replace('*', '\\*')
+        return text.replace("`", "``").replace("*", "\\*")
 
     def heading(self, level, text, convert=True):
         if len(self.lines) > 0:
-            self.lines.append('')
+            self.lines.append("")
         if convert:
             text = self._convert(text)
         self.lines.append(text)
         self.lines.append(len(text) * self.head_chars[level])
-        self.lines.append('')
+        self.lines.append("")
 
-    def para(self, text, indent=''):
-        if len(self.lines) > 0 and self.lines[-1] != '':
-            self.lines.append('')
+    def para(self, text, indent=""):
+        if len(self.lines) > 0 and self.lines[-1] != "":
+            self.lines.append("")
         if isinstance(text, list):
             for t in text:
                 self.lines.append(indent + self._convert(t))
@@ -153,39 +157,41 @@
             self.lines.append(indent + self._convert(text))
         else:
             assert False
-        self.lines.append('')
+        self.lines.append("")
 
     def single_line(self, text):
         self.lines.append(self._convert(text))
 
     def module(self, name, short_descr, descr):
-        self.heading(1, ':mod:`{}` --- {}'.format(name, self._convert(short_descr)), convert=False)
-        self.lines.append('.. module:: {}'.format(name))
-        self.lines.append('   :synopsis: {}'.format(short_descr))
+        self.heading(1, ":mod:`{}` --- {}".format(name, self._convert(short_descr)), convert=False)
+        self.lines.append(".. module:: {}".format(name))
+        self.lines.append("   :synopsis: {}".format(short_descr))
         self.para(descr)
 
     def function(self, ctx, name, args, descr):
         args = self._convert(args)
-        self.lines.append('.. function:: ' + name + args)
-        self.para(descr, indent='   ')
+        self.lines.append(".. function:: " + name + args)
+        self.para(descr, indent="   ")
 
     def method(self, ctx, name, args, descr):
         args = self._convert(args)
-        if name == '\\constructor':
-            self.lines.append('.. class:: ' + ctx + args)
-        elif name == '\\call':
-            self.lines.append('.. method:: ' + ctx + args)
+        if name == "\\constructor":
+            self.lines.append(".. class:: " + ctx + args)
+        elif name == "\\call":
+            self.lines.append(".. method:: " + ctx + args)
         else:
-            self.lines.append('.. method:: ' + ctx + '.' + name + args)
-        self.para(descr, indent='   ')
+            self.lines.append(".. method:: " + ctx + "." + name + args)
+        self.para(descr, indent="   ")
 
     def constant(self, ctx, name, descr):
-        self.lines.append('.. data:: ' + name)
-        self.para(descr, indent='   ')
+        self.lines.append(".. data:: " + name)
+        self.para(descr, indent="   ")
+
 
 class DocValidateError(Exception):
     pass
 
+
 class DocItem:
     def __init__(self):
         self.doc = []
@@ -202,6 +208,7 @@
     def dump(self, writer):
         writer.para(self.doc)
 
+
 class DocConstant(DocItem):
     def __init__(self, name, descr):
         super().__init__()
@@ -211,6 +218,7 @@
     def dump(self, ctx, writer):
         writer.constant(ctx, self.name, self.descr)
 
+
 class DocFunction(DocItem):
     def __init__(self, name, args):
         super().__init__()
@@ -220,6 +228,7 @@
     def dump(self, ctx, writer):
         writer.function(ctx, self.name, self.args, self.doc)
 
+
 class DocMethod(DocItem):
     def __init__(self, name, args):
         super().__init__()
@@ -229,6 +238,7 @@
     def dump(self, ctx, writer):
         writer.method(ctx, self.name, self.args, self.doc)
 
+
 class DocClass(DocItem):
     def __init__(self, name, descr):
         super().__init__()
@@ -240,51 +250,52 @@
         self.constants = {}
 
     def process_classmethod(self, lex, d):
-        name = d['id']
-        if name == '\\constructor':
+        name = d["id"]
+        if name == "\\constructor":
             dict_ = self.constructors
         else:
             dict_ = self.classmethods
         if name in dict_:
             lex.error("multiple definition of method '{}'".format(name))
-        method = dict_[name] = DocMethod(name, d['args'])
+        method = dict_[name] = DocMethod(name, d["args"])
         method.add_doc(lex)
 
     def process_method(self, lex, d):
-        name = d['id']
+        name = d["id"]
         dict_ = self.methods
         if name in dict_:
             lex.error("multiple definition of method '{}'".format(name))
-        method = dict_[name] = DocMethod(name, d['args'])
+        method = dict_[name] = DocMethod(name, d["args"])
         method.add_doc(lex)
 
     def process_constant(self, lex, d):
-        name = d['id']
+        name = d["id"]
         if name in self.constants:
             lex.error("multiple definition of constant '{}'".format(name))
-        self.constants[name] = DocConstant(name, d['descr'])
+        self.constants[name] = DocConstant(name, d["descr"])
         lex.opt_break()
 
     def dump(self, writer):
-        writer.heading(1, 'class {}'.format(self.name))
+        writer.heading(1, "class {}".format(self.name))
         super().dump(writer)
         if len(self.constructors) > 0:
-            writer.heading(2, 'Constructors')
-            for f in sorted(self.constructors.values(), key=lambda x:x.name):
+            writer.heading(2, "Constructors")
+            for f in sorted(self.constructors.values(), key=lambda x: x.name):
                 f.dump(self.name, writer)
         if len(self.classmethods) > 0:
-            writer.heading(2, 'Class methods')
-            for f in sorted(self.classmethods.values(), key=lambda x:x.name):
+            writer.heading(2, "Class methods")
+            for f in sorted(self.classmethods.values(), key=lambda x: x.name):
                 f.dump(self.name, writer)
         if len(self.methods) > 0:
-            writer.heading(2, 'Methods')
-            for f in sorted(self.methods.values(), key=lambda x:x.name):
+            writer.heading(2, "Methods")
+            for f in sorted(self.methods.values(), key=lambda x: x.name):
                 f.dump(self.name.lower(), writer)
         if len(self.constants) > 0:
-            writer.heading(2, 'Constants')
-            for c in sorted(self.constants.values(), key=lambda x:x.name):
+            writer.heading(2, "Constants")
+            for c in sorted(self.constants.values(), key=lambda x: x.name):
                 c.dump(self.name, writer)
 
+
 class DocModule(DocItem):
     def __init__(self, name, descr):
         super().__init__()
@@ -299,22 +310,22 @@
         self.cur_class = None
 
     def process_function(self, lex, d):
-        name = d['id']
+        name = d["id"]
         if name in self.functions:
             lex.error("multiple definition of function '{}'".format(name))
-        function = self.functions[name] = DocFunction(name, d['args'])
+        function = self.functions[name] = DocFunction(name, d["args"])
         function.add_doc(lex)
 
-    #def process_classref(self, lex, d):
+    # def process_classref(self, lex, d):
     #    name = d['id']
     #    self.classes[name] = name
     #    lex.opt_break()
 
     def process_class(self, lex, d):
-        name = d['id']
+        name = d["id"]
         if name in self.classes:
             lex.error("multiple definition of class '{}'".format(name))
-        self.cur_class = self.classes[name] = DocClass(name, d['descr'])
+        self.cur_class = self.classes[name] = DocClass(name, d["descr"])
         self.cur_class.add_doc(lex)
 
     def process_classmethod(self, lex, d):
@@ -326,10 +337,10 @@
     def process_constant(self, lex, d):
         if self.cur_class is None:
             # a module-level constant
-            name = d['id']
+            name = d["id"]
             if name in self.constants:
                 lex.error("multiple definition of constant '{}'".format(name))
-            self.constants[name] = DocConstant(name, d['descr'])
+            self.constants[name] = DocConstant(name, d["descr"])
             lex.opt_break()
         else:
             # a class-level constant
@@ -337,50 +348,51 @@
 
     def validate(self):
         if self.descr is None:
-            raise DocValidateError('module {} referenced but never defined'.format(self.name))
+            raise DocValidateError("module {} referenced but never defined".format(self.name))
 
     def dump(self, writer):
         writer.module(self.name, self.descr, self.doc)
         if self.functions:
-            writer.heading(2, 'Functions')
-            for f in sorted(self.functions.values(), key=lambda x:x.name):
+            writer.heading(2, "Functions")
+            for f in sorted(self.functions.values(), key=lambda x: x.name):
                 f.dump(self.name, writer)
         if self.constants:
-            writer.heading(2, 'Constants')
-            for c in sorted(self.constants.values(), key=lambda x:x.name):
+            writer.heading(2, "Constants")
+            for c in sorted(self.constants.values(), key=lambda x: x.name):
                 c.dump(self.name, writer)
         if self.classes:
-            writer.heading(2, 'Classes')
-            for c in sorted(self.classes.values(), key=lambda x:x.name):
-                writer.para('[`{}.{}`]({}) - {}'.format(self.name, c.name, c.name, c.descr))
+            writer.heading(2, "Classes")
+            for c in sorted(self.classes.values(), key=lambda x: x.name):
+                writer.para("[`{}.{}`]({}) - {}".format(self.name, c.name, c.name, c.descr))
 
     def write_html(self, dir):
         md_writer = MarkdownWriter()
         md_writer.start()
         self.dump(md_writer)
-        with open(os.path.join(dir, 'index.html'), 'wt') as f:
+        with open(os.path.join(dir, "index.html"), "wt") as f:
             f.write(markdown.markdown(md_writer.end()))
         for c in self.classes.values():
             class_dir = os.path.join(dir, c.name)
             makedirs(class_dir)
             md_writer.start()
-            md_writer.para('part of the [{} module](./)'.format(self.name))
+            md_writer.para("part of the [{} module](./)".format(self.name))
             c.dump(md_writer)
-            with open(os.path.join(class_dir, 'index.html'), 'wt') as f:
+            with open(os.path.join(class_dir, "index.html"), "wt") as f:
                 f.write(markdown.markdown(md_writer.end()))
 
     def write_rst(self, dir):
         rst_writer = ReStructuredTextWriter()
         rst_writer.start()
         self.dump(rst_writer)
-        with open(dir + '/' + self.name + '.rst', 'wt') as f:
+        with open(dir + "/" + self.name + ".rst", "wt") as f:
             f.write(rst_writer.end())
         for c in self.classes.values():
             rst_writer.start()
             c.dump(rst_writer)
-            with open(dir + '/' + self.name + '.' + c.name + '.rst', 'wt') as f:
+            with open(dir + "/" + self.name + "." + c.name + ".rst", "wt") as f:
                 f.write(rst_writer.end())
 
+
 class Doc:
     def __init__(self):
         self.modules = {}
@@ -393,20 +405,20 @@
 
     def check_module(self, lex):
         if self.cur_module is None:
-            lex.error('module not defined')
+            lex.error("module not defined")
 
     def process_module(self, lex, d):
-        name = d['id']
+        name = d["id"]
         if name not in self.modules:
             self.modules[name] = DocModule(name, None)
         self.cur_module = self.modules[name]
         if self.cur_module.descr is not None:
             lex.error("multiple definition of module '{}'".format(name))
-        self.cur_module.descr = d['descr']
+        self.cur_module.descr = d["descr"]
         self.cur_module.add_doc(lex)
 
     def process_moduleref(self, lex, d):
-        name = d['id']
+        name = d["id"]
         if name not in self.modules:
             self.modules[name] = DocModule(name, None)
         self.cur_module = self.modules[name]
@@ -437,41 +449,46 @@
             m.validate()
 
     def dump(self, writer):
-        writer.heading(1, 'Modules')
-        writer.para('These are the Python modules that are implemented.')
-        for m in sorted(self.modules.values(), key=lambda x:x.name):
-            writer.para('[`{}`]({}/) - {}'.format(m.name, m.name, m.descr))
+        writer.heading(1, "Modules")
+        writer.para("These are the Python modules that are implemented.")
+        for m in sorted(self.modules.values(), key=lambda x: x.name):
+            writer.para("[`{}`]({}/) - {}".format(m.name, m.name, m.descr))
 
     def write_html(self, dir):
         md_writer = MarkdownWriter()
-        with open(os.path.join(dir, 'module', 'index.html'), 'wt') as f:
+        with open(os.path.join(dir, "module", "index.html"), "wt") as f:
             md_writer.start()
             self.dump(md_writer)
             f.write(markdown.markdown(md_writer.end()))
         for m in self.modules.values():
-            mod_dir = os.path.join(dir, 'module', m.name)
+            mod_dir = os.path.join(dir, "module", m.name)
             makedirs(mod_dir)
             m.write_html(mod_dir)
 
     def write_rst(self, dir):
-        #with open(os.path.join(dir, 'module', 'index.html'), 'wt') as f:
+        # with open(os.path.join(dir, 'module', 'index.html'), 'wt') as f:
         #    f.write(markdown.markdown(self.dump()))
         for m in self.modules.values():
             m.write_rst(dir)
 
-regex_descr = r'(?P<descr>.*)'
+
+regex_descr = r"(?P<descr>.*)"
 
 doc_regexs = (
-    (Doc.process_module, re.compile(r'\\module (?P<id>[a-z][a-z0-9]*) - ' + regex_descr + r'$')),
-    (Doc.process_moduleref, re.compile(r'\\moduleref (?P<id>[a-z]+)$')),
-    (Doc.process_function, re.compile(r'\\function (?P<id>[a-z0-9_]+)(?P<args>\(.*\))$')),
-    (Doc.process_classmethod, re.compile(r'\\classmethod (?P<id>\\?[a-z0-9_]+)(?P<args>\(.*\))$')),
-    (Doc.process_method, re.compile(r'\\method (?P<id>\\?[a-z0-9_]+)(?P<args>\(.*\))$')),
-    (Doc.process_constant, re.compile(r'\\constant (?P<id>[A-Za-z0-9_]+) - ' + regex_descr + r'$')),
-    #(Doc.process_classref, re.compile(r'\\classref (?P<id>[A-Za-z0-9_]+)$')),
-    (Doc.process_class, re.compile(r'\\class (?P<id>[A-Za-z0-9_]+) - ' + regex_descr + r'$')),
+    (Doc.process_module, re.compile(r"\\module (?P<id>[a-z][a-z0-9]*) - " + regex_descr + r"$")),
+    (Doc.process_moduleref, re.compile(r"\\moduleref (?P<id>[a-z]+)$")),
+    (Doc.process_function, re.compile(r"\\function (?P<id>[a-z0-9_]+)(?P<args>\(.*\))$")),
+    (Doc.process_classmethod, re.compile(r"\\classmethod (?P<id>\\?[a-z0-9_]+)(?P<args>\(.*\))$")),
+    (Doc.process_method, re.compile(r"\\method (?P<id>\\?[a-z0-9_]+)(?P<args>\(.*\))$")),
+    (
+        Doc.process_constant,
+        re.compile(r"\\constant (?P<id>[A-Za-z0-9_]+) - " + regex_descr + r"$"),
+    ),
+    # (Doc.process_classref, re.compile(r'\\classref (?P<id>[A-Za-z0-9_]+)$')),
+    (Doc.process_class, re.compile(r"\\class (?P<id>[A-Za-z0-9_]+) - " + regex_descr + r"$")),
 )
 
+
 def process_file(file, doc):
     lex = Lexer(file)
     doc.new_file()
@@ -481,11 +498,11 @@
                 line = lex.next()
                 fun, match = re_match_first(doc_regexs, line)
                 if fun == None:
-                    lex.error('unknown line format: {}'.format(line))
+                    lex.error("unknown line format: {}".format(line))
                 fun(doc, lex, match.groupdict())
 
         except Lexer.Break:
-            lex.error('unexpected break')
+            lex.error("unexpected break")
 
         except Lexer.EOF:
             pass
@@ -495,16 +512,21 @@
 
     return True
 
+
 def main():
-    cmd_parser = argparse.ArgumentParser(description='Generate documentation for pyboard API from C files.')
-    cmd_parser.add_argument('--outdir', metavar='<output dir>', default='gendoc-out', help='ouput directory')
-    cmd_parser.add_argument('--format', default='html', help='output format: html or rst')
-    cmd_parser.add_argument('files', nargs='+', help='input files')
+    cmd_parser = argparse.ArgumentParser(
+        description="Generate documentation for pyboard API from C files."
+    )
+    cmd_parser.add_argument(
+        "--outdir", metavar="<output dir>", default="gendoc-out", help="ouput directory"
+    )
+    cmd_parser.add_argument("--format", default="html", help="output format: html or rst")
+    cmd_parser.add_argument("files", nargs="+", help="input files")
     args = cmd_parser.parse_args()
 
     doc = Doc()
     for file in args.files:
-        print('processing', file)
+        print("processing", file)
         if not process_file(file, doc):
             return
     try:
@@ -514,15 +536,16 @@
 
     makedirs(args.outdir)
 
-    if args.format == 'html':
+    if args.format == "html":
         doc.write_html(args.outdir)
-    elif args.format == 'rst':
+    elif args.format == "rst":
         doc.write_rst(args.outdir)
     else:
-        print('unknown format:', args.format)
+        print("unknown format:", args.format)
         return
 
-    print('written to', args.outdir)
+    print("written to", args.outdir)
+
 
 if __name__ == "__main__":
     main()
diff --git a/tools/insert-usb-ids.py b/tools/insert-usb-ids.py
index cdccd3b..b1d848a 100644
--- a/tools/insert-usb-ids.py
+++ b/tools/insert-usb-ids.py
@@ -8,15 +8,16 @@
 import re
 import string
 
-needed_keys = ('USB_PID_CDC_MSC', 'USB_PID_CDC_HID', 'USB_PID_CDC', 'USB_VID')
+needed_keys = ("USB_PID_CDC_MSC", "USB_PID_CDC_HID", "USB_PID_CDC", "USB_VID")
+
 
 def parse_usb_ids(filename):
     rv = dict()
     for line in open(filename).readlines():
-        line = line.rstrip('\r\n')
-        match = re.match('^#define\s+(\w+)\s+\(0x([0-9A-Fa-f]+)\)$', line)
-        if match and match.group(1).startswith('USBD_'):
-            key = match.group(1).replace('USBD', 'USB')
+        line = line.rstrip("\r\n")
+        match = re.match("^#define\s+(\w+)\s+\(0x([0-9A-Fa-f]+)\)$", line)
+        if match and match.group(1).startswith("USBD_"):
+            key = match.group(1).replace("USBD", "USB")
             val = match.group(2)
             print("key =", key, "val =", val)
             if key in needed_keys:
@@ -26,9 +27,10 @@
             raise Exception("Unable to parse %s from %s" % (k, filename))
     return rv
 
+
 if __name__ == "__main__":
     usb_ids_file = sys.argv[1]
     template_file = sys.argv[2]
     replacements = parse_usb_ids(usb_ids_file)
-    for line in open(template_file, 'r').readlines():
-        print(string.Template(line).safe_substitute(replacements), end='')
+    for line in open(template_file, "r").readlines():
+        print(string.Template(line).safe_substitute(replacements), end="")
diff --git a/tools/make-frozen.py b/tools/make-frozen.py
index 8809fd0..a8706bf 100755
--- a/tools/make-frozen.py
+++ b/tools/make-frozen.py
@@ -25,6 +25,7 @@
 def module_name(f):
     return f
 
+
 modules = []
 
 if len(sys.argv) > 1:
@@ -35,7 +36,7 @@
         for f in filenames:
             fullpath = dirpath + "/" + f
             st = os.stat(fullpath)
-            modules.append((fullpath[root_len + 1:], st))
+            modules.append((fullpath[root_len + 1 :], st))
 
 print("#include <stdint.h>")
 print("const char mp_frozen_str_names[] = {")
@@ -62,8 +63,8 @@
     # data.  We could just encode all characters as hex digits but it's nice
     # to be able to read the resulting C code as ASCII when possible.
 
-    data = bytearray(data) # so Python2 extracts each byte as an integer
-    esc_dict = {ord('\n'): '\\n', ord('\r'): '\\r', ord('"'): '\\"', ord('\\'): '\\\\'}
+    data = bytearray(data)  # so Python2 extracts each byte as an integer
+    esc_dict = {ord("\n"): "\\n", ord("\r"): "\\r", ord('"'): '\\"', ord("\\"): "\\\\"}
     chrs = ['"']
     break_str = False
     for c in data:
@@ -76,9 +77,9 @@
                     break_str = False
                 chrs.append(chr(c))
             else:
-                chrs.append('\\x%02x' % c)
+                chrs.append("\\x%02x" % c)
                 break_str = True
     chrs.append('\\0"')
-    print(''.join(chrs))
+    print("".join(chrs))
 
 print("};")
diff --git a/tools/makemanifest.py b/tools/makemanifest.py
index 2caf7b0..a8b310a 100644
--- a/tools/makemanifest.py
+++ b/tools/makemanifest.py
@@ -33,6 +33,7 @@
 ###########################################################################
 # Public functions to be used in the manifest
 
+
 def include(manifest):
     """Include another manifest.
 
@@ -55,6 +56,7 @@
             exec(f.read())
             os.chdir(prev_cwd)
 
+
 def freeze(path, script=None, opt=0):
     """Freeze the input, automatically determining its type.  A .py script
     will be compiled to a .mpy first then frozen, and a .mpy file will be
@@ -84,6 +86,7 @@
 
     freeze_internal(KIND_AUTO, path, script, opt)
 
+
 def freeze_as_str(path):
     """Freeze the given `path` and all .py scripts within it as a string,
     which will be compiled upon import.
@@ -91,6 +94,7 @@
 
     freeze_internal(KIND_AS_STR, path, None, 0)
 
+
 def freeze_as_mpy(path, script=None, opt=0):
     """Freeze the input (see above) by first compiling the .py scripts to
     .mpy files, then freezing the resulting .mpy files.
@@ -98,6 +102,7 @@
 
     freeze_internal(KIND_AS_MPY, path, script, opt)
 
+
 def freeze_mpy(path, script=None, opt=0):
     """Freeze the input (see above), which must be .mpy files that are
     frozen directly.
@@ -118,9 +123,11 @@
 
 manifest_list = []
 
+
 class FreezeError(Exception):
     pass
 
+
 def system(cmd):
     try:
         output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
@@ -128,23 +135,26 @@
     except subprocess.CalledProcessError as er:
         return -1, er.output
 
+
 def convert_path(path):
     # Perform variable substituion.
     for name, value in VARS.items():
-        path = path.replace('$({})'.format(name), value)
+        path = path.replace("$({})".format(name), value)
     # Convert to absolute path (so that future operations don't rely on
     # still being chdir'ed).
     return os.path.abspath(path)
 
+
 def get_timestamp(path, default=None):
     try:
         stat = os.stat(path)
         return stat.st_mtime
     except OSError:
         if default is None:
-            raise FreezeError('cannot stat {}'.format(path))
+            raise FreezeError("cannot stat {}".format(path))
         return default
 
+
 def get_timestamp_newest(path):
     ts_newest = 0
     for dirpath, dirnames, filenames in os.walk(path, followlinks=True):
@@ -152,82 +162,90 @@
             ts_newest = max(ts_newest, get_timestamp(os.path.join(dirpath, f)))
     return ts_newest
 
+
 def mkdir(path):
-    cur_path = ''
-    for p in path.split('/')[:-1]:
-        cur_path += p + '/'
+    cur_path = ""
+    for p in path.split("/")[:-1]:
+        cur_path += p + "/"
         try:
             os.mkdir(cur_path)
         except OSError as er:
-            if er.args[0] == 17: # file exists
+            if er.args[0] == 17:  # file exists
                 pass
             else:
                 raise er
 
+
 def freeze_internal(kind, path, script, opt):
     path = convert_path(path)
     if script is None and kind == KIND_AS_STR:
         if any(f[0] == KIND_AS_STR for f in manifest_list):
-            raise FreezeError('can only freeze one str directory')
+            raise FreezeError("can only freeze one str directory")
         manifest_list.append((KIND_AS_STR, path, script, opt))
     elif script is None:
         for dirpath, dirnames, filenames in os.walk(path, followlinks=True):
             for f in filenames:
-                freeze_internal(kind, path, (dirpath + '/' + f)[len(path) + 1:], opt)
+                freeze_internal(kind, path, (dirpath + "/" + f)[len(path) + 1 :], opt)
     elif not isinstance(script, str):
         for s in script:
             freeze_internal(kind, path, s, opt)
     else:
-        extension_kind = {KIND_AS_MPY: '.py', KIND_MPY: '.mpy'}
+        extension_kind = {KIND_AS_MPY: ".py", KIND_MPY: ".mpy"}
         if kind == KIND_AUTO:
             for k, ext in extension_kind.items():
                 if script.endswith(ext):
                     kind = k
                     break
             else:
-                print('warn: unsupported file type, skipped freeze: {}'.format(script))
+                print("warn: unsupported file type, skipped freeze: {}".format(script))
                 return
         wanted_extension = extension_kind[kind]
         if not script.endswith(wanted_extension):
-            raise FreezeError('expecting a {} file, got {}'.format(wanted_extension, script))
+            raise FreezeError("expecting a {} file, got {}".format(wanted_extension, script))
         manifest_list.append((kind, path, script, opt))
 
+
 def main():
     # Parse arguments
     import argparse
-    cmd_parser = argparse.ArgumentParser(description='A tool to generate frozen content in MicroPython firmware images.')
-    cmd_parser.add_argument('-o', '--output', help='output path')
-    cmd_parser.add_argument('-b', '--build-dir', help='output path')
-    cmd_parser.add_argument('-f', '--mpy-cross-flags', default='', help='flags to pass to mpy-cross')
-    cmd_parser.add_argument('-v', '--var', action='append', help='variables to substitute')
-    cmd_parser.add_argument('files', nargs='+', help='input manifest list')
+
+    cmd_parser = argparse.ArgumentParser(
+        description="A tool to generate frozen content in MicroPython firmware images."
+    )
+    cmd_parser.add_argument("-o", "--output", help="output path")
+    cmd_parser.add_argument("-b", "--build-dir", help="output path")
+    cmd_parser.add_argument(
+        "-f", "--mpy-cross-flags", default="", help="flags to pass to mpy-cross"
+    )
+    cmd_parser.add_argument("-v", "--var", action="append", help="variables to substitute")
+    cmd_parser.add_argument("files", nargs="+", help="input manifest list")
     args = cmd_parser.parse_args()
 
     # Extract variables for substitution.
     for var in args.var:
-        name, value = var.split('=', 1)
+        name, value = var.split("=", 1)
         if os.path.exists(value):
             value = os.path.abspath(value)
         VARS[name] = value
 
-    if 'MPY_DIR' not in VARS or 'PORT_DIR' not in VARS:
-        print('MPY_DIR and PORT_DIR variables must be specified')
+    if "MPY_DIR" not in VARS or "PORT_DIR" not in VARS:
+        print("MPY_DIR and PORT_DIR variables must be specified")
         sys.exit(1)
 
     # Get paths to tools
-    MAKE_FROZEN = VARS['MPY_DIR'] + '/tools/make-frozen.py'
-    MPY_CROSS = VARS['MPY_DIR'] + '/mpy-cross/mpy-cross'
-    MPY_TOOL = VARS['MPY_DIR'] + '/tools/mpy-tool.py'
+    MAKE_FROZEN = VARS["MPY_DIR"] + "/tools/make-frozen.py"
+    MPY_CROSS = VARS["MPY_DIR"] + "/mpy-cross/mpy-cross"
+    MPY_TOOL = VARS["MPY_DIR"] + "/tools/mpy-tool.py"
 
     # Ensure mpy-cross is built
     if not os.path.exists(MPY_CROSS):
-        print('mpy-cross not found at {}, please build it first'.format(MPY_CROSS))
+        print("mpy-cross not found at {}, please build it first".format(MPY_CROSS))
         sys.exit(1)
 
     # Include top-level inputs, to generate the manifest
     for input_manifest in args.files:
         try:
-            if input_manifest.endswith('.py'):
+            if input_manifest.endswith(".py"):
                 include(input_manifest)
             else:
                 exec(input_manifest)
@@ -244,22 +262,26 @@
             str_paths.append(path)
             ts_outfile = get_timestamp_newest(path)
         elif kind == KIND_AS_MPY:
-            infile = '{}/{}'.format(path, script)
-            outfile = '{}/frozen_mpy/{}.mpy'.format(args.build_dir, script[:-3])
+            infile = "{}/{}".format(path, script)
+            outfile = "{}/frozen_mpy/{}.mpy".format(args.build_dir, script[:-3])
             ts_infile = get_timestamp(infile)
             ts_outfile = get_timestamp(outfile, 0)
             if ts_infile >= ts_outfile:
-                print('MPY', script)
+                print("MPY", script)
                 mkdir(outfile)
-                res, out = system([MPY_CROSS] + args.mpy_cross_flags.split() + ['-o', outfile, '-s', script, '-O{}'.format(opt), infile])
+                res, out = system(
+                    [MPY_CROSS]
+                    + args.mpy_cross_flags.split()
+                    + ["-o", outfile, "-s", script, "-O{}".format(opt), infile]
+                )
                 if res != 0:
-                    print('error compiling {}: {}'.format(infile, out))
+                    print("error compiling {}: {}".format(infile, out))
                     raise SystemExit(1)
                 ts_outfile = get_timestamp(outfile)
             mpy_files.append(outfile)
         else:
             assert kind == KIND_MPY
-            infile = '{}/{}'.format(path, script)
+            infile = "{}/{}".format(path, script)
             mpy_files.append(infile)
             ts_outfile = get_timestamp(infile)
         ts_newest = max(ts_newest, ts_outfile)
@@ -272,35 +294,45 @@
     # Freeze paths as strings
     res, output_str = system([sys.executable, MAKE_FROZEN] + str_paths)
     if res != 0:
-        print('error freezing strings {}: {}'.format(str_paths, output_str))
+        print("error freezing strings {}: {}".format(str_paths, output_str))
         sys.exit(1)
 
     # Freeze .mpy files
     if mpy_files:
-        res, output_mpy = system([sys.executable, MPY_TOOL, '-f', '-q', args.build_dir + '/genhdr/qstrdefs.preprocessed.h'] + mpy_files)
+        res, output_mpy = system(
+            [
+                sys.executable,
+                MPY_TOOL,
+                "-f",
+                "-q",
+                args.build_dir + "/genhdr/qstrdefs.preprocessed.h",
+            ]
+            + mpy_files
+        )
         if res != 0:
-            print('error freezing mpy {}:'.format(mpy_files))
-            print(str(output_mpy, 'utf8'))
+            print("error freezing mpy {}:".format(mpy_files))
+            print(str(output_mpy, "utf8"))
             sys.exit(1)
     else:
         output_mpy = (
             b'#include "py/emitglue.h"\n'
-            b'extern const qstr_pool_t mp_qstr_const_pool;\n'
-            b'const qstr_pool_t mp_qstr_frozen_const_pool = {\n'
-            b'    (qstr_pool_t*)&mp_qstr_const_pool, MP_QSTRnumber_of, 0, 0\n'
-            b'};\n'
+            b"extern const qstr_pool_t mp_qstr_const_pool;\n"
+            b"const qstr_pool_t mp_qstr_frozen_const_pool = {\n"
+            b"    (qstr_pool_t*)&mp_qstr_const_pool, MP_QSTRnumber_of, 0, 0\n"
+            b"};\n"
             b'const char mp_frozen_mpy_names[1] = {"\\0"};\n'
-            b'const mp_raw_code_t *const mp_frozen_mpy_content[0] = {};\n'
+            b"const mp_raw_code_t *const mp_frozen_mpy_content[0] = {};\n"
         )
 
     # Generate output
-    print('GEN', args.output)
+    print("GEN", args.output)
     mkdir(args.output)
-    with open(args.output, 'wb') as f:
-        f.write(b'//\n// Content for MICROPY_MODULE_FROZEN_STR\n//\n')
+    with open(args.output, "wb") as f:
+        f.write(b"//\n// Content for MICROPY_MODULE_FROZEN_STR\n//\n")
         f.write(output_str)
-        f.write(b'//\n// Content for MICROPY_MODULE_FROZEN_MPY\n//\n')
+        f.write(b"//\n// Content for MICROPY_MODULE_FROZEN_MPY\n//\n")
         f.write(output_mpy)
 
-if __name__ == '__main__':
+
+if __name__ == "__main__":
     main()
diff --git a/tools/metrics.py b/tools/metrics.py
index 0cc6db5..5f15602 100755
--- a/tools/metrics.py
+++ b/tools/metrics.py
@@ -45,7 +45,8 @@
 
 import sys, re, subprocess
 
-MAKE_FLAGS = ['-j3', 'CFLAGS_EXTRA=-DNDEBUG']
+MAKE_FLAGS = ["-j3", "CFLAGS_EXTRA=-DNDEBUG"]
+
 
 class PortData:
     def __init__(self, name, dir, output, make_flags=None):
@@ -54,19 +55,21 @@
         self.output = output
         self.make_flags = make_flags
 
+
 port_data = {
-    'b': PortData('bare-arm', 'bare-arm', 'build/firmware.elf'),
-    'm': PortData('minimal x86', 'minimal', 'build/firmware.elf'),
-    'u': PortData('unix x64', 'unix', 'micropython'),
-    'n': PortData('unix nanbox', 'unix', 'micropython-nanbox', 'VARIANT=nanbox'),
-    's': PortData('stm32', 'stm32', 'build-PYBV10/firmware.elf', 'BOARD=PYBV10'),
-    'c': PortData('cc3200', 'cc3200', 'build/WIPY/release/application.axf', 'BTARGET=application'),
-    '8': PortData('esp8266', 'esp8266', 'build-GENERIC/firmware.elf'),
-    '3': PortData('esp32', 'esp32', 'build-GENERIC/application.elf'),
-    'r': PortData('nrf', 'nrf', 'build-pca10040/firmware.elf'),
-    'd': PortData('samd', 'samd', 'build-ADAFRUIT_ITSYBITSY_M4_EXPRESS/firmware.elf'),
+    "b": PortData("bare-arm", "bare-arm", "build/firmware.elf"),
+    "m": PortData("minimal x86", "minimal", "build/firmware.elf"),
+    "u": PortData("unix x64", "unix", "micropython"),
+    "n": PortData("unix nanbox", "unix", "micropython-nanbox", "VARIANT=nanbox"),
+    "s": PortData("stm32", "stm32", "build-PYBV10/firmware.elf", "BOARD=PYBV10"),
+    "c": PortData("cc3200", "cc3200", "build/WIPY/release/application.axf", "BTARGET=application"),
+    "8": PortData("esp8266", "esp8266", "build-GENERIC/firmware.elf"),
+    "3": PortData("esp32", "esp32", "build-GENERIC/application.elf"),
+    "r": PortData("nrf", "nrf", "build-pca10040/firmware.elf"),
+    "d": PortData("samd", "samd", "build-ADAFRUIT_ITSYBITSY_M4_EXPRESS/firmware.elf"),
 }
 
+
 def syscmd(*args):
     sys.stdout.flush()
     a2 = []
@@ -77,6 +80,7 @@
             a2.extend(a)
     subprocess.run(a2)
 
+
 def parse_port_list(args):
     if not args:
         return list(port_data.values())
@@ -87,10 +91,11 @@
                 try:
                     ports.append(port_data[port_char])
                 except KeyError:
-                    print('unknown port:', port_char)
+                    print("unknown port:", port_char)
                     sys.exit(1)
         return ports
 
+
 def read_build_log(filename):
     data = dict()
     lines = []
@@ -98,7 +103,7 @@
     with open(filename) as f:
         for line in f:
             line = line.strip()
-            if line.strip() == 'COMPUTING SIZES':
+            if line.strip() == "COMPUTING SIZES":
                 found_sizes = True
             elif found_sizes:
                 lines.append(line)
@@ -109,14 +114,15 @@
             data[fields[-1]] = [int(f) for f in fields[:-2]]
             is_size_line = False
         else:
-            is_size_line = line.startswith('text\t ')
+            is_size_line = line.startswith("text\t ")
     return data
 
+
 def do_diff(args):
     """Compute the difference between firmware sizes."""
 
     if len(args) != 2:
-        print('usage: %s diff <out1> <out2>' % sys.argv[0])
+        print("usage: %s diff <out1> <out2>" % sys.argv[0])
         sys.exit(1)
 
     data1 = read_build_log(args[0])
@@ -125,81 +131,86 @@
     for key, value1 in data1.items():
         value2 = data2[key]
         for port in port_data.values():
-            if key == 'ports/{}/{}'.format(port.dir, port.output):
+            if key == "ports/{}/{}".format(port.dir, port.output):
                 name = port.name
                 break
         data = [v2 - v1 for v1, v2 in zip(value1, value2)]
-        warn = ''
-        board = re.search(r'/build-([A-Za-z0-9_]+)/', key)
+        warn = ""
+        board = re.search(r"/build-([A-Za-z0-9_]+)/", key)
         if board:
             board = board.group(1)
         else:
-            board = ''
-        if name == 'cc3200':
+            board = ""
+        if name == "cc3200":
             delta = data[0]
             percent = 100 * delta / value1[0]
             if data[1] != 0:
-                warn += ' %+u(data)' % data[1]
+                warn += " %+u(data)" % data[1]
         else:
             delta = data[3]
             percent = 100 * delta / value1[3]
             if data[1] != 0:
-                warn += ' %+u(data)' % data[1]
+                warn += " %+u(data)" % data[1]
             if data[2] != 0:
-                warn += ' %+u(bss)' % data[2]
+                warn += " %+u(bss)" % data[2]
         if warn:
-            warn = '[incl%s]' % warn
-        print('%11s: %+5u %+.3f%% %s%s' % (name, delta, percent, board, warn))
+            warn = "[incl%s]" % warn
+        print("%11s: %+5u %+.3f%% %s%s" % (name, delta, percent, board, warn))
+
 
 def do_clean(args):
     """Clean ports."""
 
     ports = parse_port_list(args)
 
-    print('CLEANING')
+    print("CLEANING")
     for port in ports:
-        syscmd('make', '-C', 'ports/{}'.format(port.dir), port.make_flags, 'clean')
+        syscmd("make", "-C", "ports/{}".format(port.dir), port.make_flags, "clean")
+
 
 def do_build(args):
     """Build ports and print firmware sizes."""
 
     ports = parse_port_list(args)
 
-    print('BUILDING MPY-CROSS')
-    syscmd('make', '-C', 'mpy-cross', MAKE_FLAGS)
+    print("BUILDING MPY-CROSS")
+    syscmd("make", "-C", "mpy-cross", MAKE_FLAGS)
 
-    print('BUILDING PORTS')
+    print("BUILDING PORTS")
     for port in ports:
-        syscmd('make', '-C', 'ports/{}'.format(port.dir), MAKE_FLAGS, port.make_flags)
+        syscmd("make", "-C", "ports/{}".format(port.dir), MAKE_FLAGS, port.make_flags)
 
     do_sizes(args)
 
+
 def do_sizes(args):
     """Compute and print sizes of firmware."""
 
     ports = parse_port_list(args)
 
-    print('COMPUTING SIZES')
+    print("COMPUTING SIZES")
     for port in ports:
-        syscmd('size', 'ports/{}/{}'.format(port.dir, port.output))
+        syscmd("size", "ports/{}/{}".format(port.dir, port.output))
+
 
 def main():
     # Get command to execute
     if len(sys.argv) == 1:
-        print('Available commands:')
+        print("Available commands:")
         for cmd in globals():
-            if cmd.startswith('do_'):
-                print('   {:9} {}'.format(cmd[3:], globals()[cmd].__doc__))
+            if cmd.startswith("do_"):
+                print("   {:9} {}".format(cmd[3:], globals()[cmd].__doc__))
         sys.exit(1)
     cmd = sys.argv.pop(1)
 
     # Dispatch to desired command
     try:
-        cmd = globals()['do_{}'.format(cmd)]
+        cmd = globals()["do_{}".format(cmd)]
     except KeyError:
         print("{}: unknown command '{}'".format(sys.argv[0], cmd))
         sys.exit(1)
     cmd(sys.argv[1:])
 
-if __name__ == '__main__':
+
+if __name__ == "__main__":
     main()
diff --git a/tools/mpy-tool.py b/tools/mpy-tool.py
index 77a1299..0a92465 100755
--- a/tools/mpy-tool.py
+++ b/tools/mpy-tool.py
@@ -27,7 +27,8 @@
 # Python 2/3 compatibility code
 from __future__ import print_function
 import platform
-if platform.python_version_tuple()[0] == '2':
+
+if platform.python_version_tuple()[0] == "2":
     str_cons = lambda val, enc=None: val
     bytes_cons = lambda val, enc=None: bytearray(val)
     is_str_type = lambda o: type(o) is str
@@ -45,48 +46,56 @@
 import struct
 from collections import namedtuple
 
-sys.path.append(sys.path[0] + '/../py')
+sys.path.append(sys.path[0] + "/../py")
 import makeqstrdata as qstrutil
 
+
 class FreezeError(Exception):
     def __init__(self, rawcode, msg):
         self.rawcode = rawcode
         self.msg = msg
 
     def __str__(self):
-        return 'error while freezing %s: %s' % (self.rawcode.source_file, self.msg)
+        return "error while freezing %s: %s" % (self.rawcode.source_file, self.msg)
+
 
 class Config:
     MPY_VERSION = 5
     MICROPY_LONGINT_IMPL_NONE = 0
     MICROPY_LONGINT_IMPL_LONGLONG = 1
     MICROPY_LONGINT_IMPL_MPZ = 2
+
+
 config = Config()
 
+
 class QStrType:
     def __init__(self, str):
         self.str = str
         self.qstr_esc = qstrutil.qstr_escape(self.str)
-        self.qstr_id = 'MP_QSTR_' + self.qstr_esc
+        self.qstr_id = "MP_QSTR_" + self.qstr_esc
+
 
 # Initialise global list of qstrs with static qstrs
-global_qstrs = [None] # MP_QSTRnull should never be referenced
+global_qstrs = [None]  # MP_QSTRnull should never be referenced
 for n in qstrutil.static_qstr_list:
     global_qstrs.append(QStrType(n))
 
+
 class QStrWindow:
     def __init__(self, size):
         self.window = []
         self.size = size
 
     def push(self, val):
-        self.window = [val] + self.window[:self.size - 1]
+        self.window = [val] + self.window[: self.size - 1]
 
     def access(self, idx):
         val = self.window[idx]
-        self.window = [val] + self.window[:idx] + self.window[idx + 1:]
+        self.window = [val] + self.window[:idx] + self.window[idx + 1 :]
         return val
 
+
 MP_CODE_BYTECODE = 2
 MP_CODE_NATIVE_PY = 3
 MP_CODE_NATIVE_VIPER = 4
@@ -104,7 +113,7 @@
 MP_NATIVE_ARCH_XTENSA = 9
 MP_NATIVE_ARCH_XTENSAWIN = 10
 
-MP_BC_MASK_EXTRA_BYTE = 0x9e
+MP_BC_MASK_EXTRA_BYTE = 0x9E
 
 MP_BC_FORMAT_BYTE = 0
 MP_BC_FORMAT_QSTR = 1
@@ -121,13 +130,15 @@
 def mp_opcode_format(bytecode, ip, count_var_uint):
     opcode = bytecode[ip]
     ip_start = ip
-    f = ((0x000003a4 >> (2 * ((opcode) >> 4))) & 3)
+    f = (0x000003A4 >> (2 * ((opcode) >> 4))) & 3
     if f == MP_BC_FORMAT_QSTR:
         if config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE:
-            if (opcode == MP_BC_LOAD_NAME
+            if (
+                opcode == MP_BC_LOAD_NAME
                 or opcode == MP_BC_LOAD_GLOBAL
                 or opcode == MP_BC_LOAD_ATTR
-                or opcode == MP_BC_STORE_ATTR):
+                or opcode == MP_BC_STORE_ATTR
+            ):
                 ip += 1
         ip += 3
     else:
@@ -143,10 +154,11 @@
         ip += extra_byte
     return f, ip - ip_start
 
+
 def read_prelude_sig(read_byte):
     z = read_byte()
     # xSSSSEAA
-    S = (z >> 3) & 0xf
+    S = (z >> 3) & 0xF
     E = (z >> 2) & 0x1
     F = 0
     A = z & 0x3
@@ -166,6 +178,7 @@
     S += 1
     return S, E, F, A, K, D
 
+
 def read_prelude_size(read_byte):
     I = 0
     C = 0
@@ -173,20 +186,29 @@
     while True:
         z = read_byte()
         # xIIIIIIC
-        I |= ((z & 0x7e) >> 1) << (6 * n)
+        I |= ((z & 0x7E) >> 1) << (6 * n)
         C |= (z & 1) << n
         if not (z & 0x80):
             break
         n += 1
     return I, C
 
+
 def extract_prelude(bytecode, ip):
     def local_read_byte():
         b = bytecode[ip_ref[0]]
         ip_ref[0] += 1
         return b
-    ip_ref = [ip] # to close over ip in Python 2 and 3
-    n_state, n_exc_stack, scope_flags, n_pos_args, n_kwonly_args, n_def_pos_args = read_prelude_sig(local_read_byte)
+
+    ip_ref = [ip]  # to close over ip in Python 2 and 3
+    (
+        n_state,
+        n_exc_stack,
+        scope_flags,
+        n_pos_args,
+        n_kwonly_args,
+        n_def_pos_args,
+    ) = read_prelude_sig(local_read_byte)
     n_info, n_cell = read_prelude_size(local_read_byte)
     ip = ip_ref[0]
 
@@ -196,19 +218,21 @@
     # ip2 points to simple_name qstr
     return ip, ip2, (n_state, n_exc_stack, scope_flags, n_pos_args, n_kwonly_args, n_def_pos_args)
 
+
 class MPFunTable:
     pass
 
+
 class RawCode(object):
     # a set of all escaped names, to make sure they are unique
     escaped_names = set()
 
     # convert code kind number to string
     code_kind_str = {
-       MP_CODE_BYTECODE: 'MP_CODE_BYTECODE',
-       MP_CODE_NATIVE_PY: 'MP_CODE_NATIVE_PY',
-       MP_CODE_NATIVE_VIPER: 'MP_CODE_NATIVE_VIPER',
-       MP_CODE_NATIVE_ASM: 'MP_CODE_NATIVE_ASM',
+        MP_CODE_BYTECODE: "MP_CODE_BYTECODE",
+        MP_CODE_NATIVE_PY: "MP_CODE_NATIVE_PY",
+        MP_CODE_NATIVE_VIPER: "MP_CODE_NATIVE_VIPER",
+        MP_CODE_NATIVE_ASM: "MP_CODE_NATIVE_ASM",
     }
 
     def __init__(self, code_kind, bytecode, prelude_offset, qstrs, objs, raw_codes):
@@ -237,7 +261,7 @@
     def dump(self):
         # dump children first
         for rc in self.raw_codes:
-            rc.freeze('')
+            rc.freeze("")
         # TODO
 
     def freeze_children(self, parent_name):
@@ -252,32 +276,39 @@
 
         # emit children first
         for rc in self.raw_codes:
-            rc.freeze(self.escaped_name + '_')
+            rc.freeze(self.escaped_name + "_")
 
     def freeze_constants(self):
         # generate constant objects
         for i, obj in enumerate(self.objs):
-            obj_name = 'const_obj_%s_%u' % (self.escaped_name, i)
+            obj_name = "const_obj_%s_%u" % (self.escaped_name, i)
             if obj is MPFunTable:
                 pass
             elif obj is Ellipsis:
-                print('#define %s mp_const_ellipsis_obj' % obj_name)
+                print("#define %s mp_const_ellipsis_obj" % obj_name)
             elif is_str_type(obj) or is_bytes_type(obj):
                 if is_str_type(obj):
-                    obj = bytes_cons(obj, 'utf8')
-                    obj_type = 'mp_type_str'
+                    obj = bytes_cons(obj, "utf8")
+                    obj_type = "mp_type_str"
                 else:
-                    obj_type = 'mp_type_bytes'
-                print('STATIC const mp_obj_str_t %s = {{&%s}, %u, %u, (const byte*)"%s"};'
-                    % (obj_name, obj_type, qstrutil.compute_hash(obj, config.MICROPY_QSTR_BYTES_IN_HASH),
-                        len(obj), ''.join(('\\x%02x' % b) for b in obj)))
+                    obj_type = "mp_type_bytes"
+                print(
+                    'STATIC const mp_obj_str_t %s = {{&%s}, %u, %u, (const byte*)"%s"};'
+                    % (
+                        obj_name,
+                        obj_type,
+                        qstrutil.compute_hash(obj, config.MICROPY_QSTR_BYTES_IN_HASH),
+                        len(obj),
+                        "".join(("\\x%02x" % b) for b in obj),
+                    )
+                )
             elif is_int_type(obj):
                 if config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_NONE:
                     # TODO check if we can actually fit this long-int into a small-int
-                    raise FreezeError(self, 'target does not support long int')
+                    raise FreezeError(self, "target does not support long int")
                 elif config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_LONGLONG:
                     # TODO
-                    raise FreezeError(self, 'freezing int to long-long is not implemented')
+                    raise FreezeError(self, "freezing int to long-long is not implemented")
                 elif config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_MPZ:
                     neg = 0
                     if obj < 0:
@@ -290,140 +321,175 @@
                         digs.append(z & ((1 << bits_per_dig) - 1))
                         z >>= bits_per_dig
                     ndigs = len(digs)
-                    digs = ','.join(('%#x' % d) for d in digs)
-                    print('STATIC const mp_obj_int_t %s = {{&mp_type_int}, '
-                        '{.neg=%u, .fixed_dig=1, .alloc=%u, .len=%u, .dig=(uint%u_t*)(const uint%u_t[]){%s}}};'
-                        % (obj_name, neg, ndigs, ndigs, bits_per_dig, bits_per_dig, digs))
+                    digs = ",".join(("%#x" % d) for d in digs)
+                    print(
+                        "STATIC const mp_obj_int_t %s = {{&mp_type_int}, "
+                        "{.neg=%u, .fixed_dig=1, .alloc=%u, .len=%u, .dig=(uint%u_t*)(const uint%u_t[]){%s}}};"
+                        % (obj_name, neg, ndigs, ndigs, bits_per_dig, bits_per_dig, digs)
+                    )
             elif type(obj) is float:
-                print('#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B')
-                print('STATIC const mp_obj_float_t %s = {{&mp_type_float}, %.16g};'
-                    % (obj_name, obj))
-                print('#endif')
+                print(
+                    "#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B"
+                )
+                print(
+                    "STATIC const mp_obj_float_t %s = {{&mp_type_float}, %.16g};" % (obj_name, obj)
+                )
+                print("#endif")
             elif type(obj) is complex:
-                print('STATIC const mp_obj_complex_t %s = {{&mp_type_complex}, %.16g, %.16g};'
-                    % (obj_name, obj.real, obj.imag))
+                print(
+                    "STATIC const mp_obj_complex_t %s = {{&mp_type_complex}, %.16g, %.16g};"
+                    % (obj_name, obj.real, obj.imag)
+                )
             else:
-                raise FreezeError(self, 'freezing of object %r is not implemented' % (obj,))
+                raise FreezeError(self, "freezing of object %r is not implemented" % (obj,))
 
         # generate constant table, if it has any entries
         const_table_len = len(self.qstrs) + len(self.objs) + len(self.raw_codes)
         if const_table_len:
-            print('STATIC const mp_rom_obj_t const_table_data_%s[%u] = {'
-                % (self.escaped_name, const_table_len))
+            print(
+                "STATIC const mp_rom_obj_t const_table_data_%s[%u] = {"
+                % (self.escaped_name, const_table_len)
+            )
             for qst in self.qstrs:
-                print('    MP_ROM_QSTR(%s),' % global_qstrs[qst].qstr_id)
+                print("    MP_ROM_QSTR(%s)," % global_qstrs[qst].qstr_id)
             for i in range(len(self.objs)):
                 if self.objs[i] is MPFunTable:
-                    print('    &mp_fun_table,')
+                    print("    &mp_fun_table,")
                 elif type(self.objs[i]) is float:
-                    print('#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B')
-                    print('    MP_ROM_PTR(&const_obj_%s_%u),' % (self.escaped_name, i))
-                    print('#elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C')
-                    n = struct.unpack('<I', struct.pack('<f', self.objs[i]))[0]
+                    print(
+                        "#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B"
+                    )
+                    print("    MP_ROM_PTR(&const_obj_%s_%u)," % (self.escaped_name, i))
+                    print("#elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C")
+                    n = struct.unpack("<I", struct.pack("<f", self.objs[i]))[0]
                     n = ((n & ~0x3) | 2) + 0x80800000
-                    print('    (mp_rom_obj_t)(0x%08x),' % (n,))
-                    print('#elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D')
-                    n = struct.unpack('<Q', struct.pack('<d', self.objs[i]))[0]
+                    print("    (mp_rom_obj_t)(0x%08x)," % (n,))
+                    print("#elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D")
+                    n = struct.unpack("<Q", struct.pack("<d", self.objs[i]))[0]
                     n += 0x8004000000000000
-                    print('    (mp_rom_obj_t)(0x%016x),' % (n,))
-                    print('#endif')
+                    print("    (mp_rom_obj_t)(0x%016x)," % (n,))
+                    print("#endif")
                 else:
-                    print('    MP_ROM_PTR(&const_obj_%s_%u),' % (self.escaped_name, i))
+                    print("    MP_ROM_PTR(&const_obj_%s_%u)," % (self.escaped_name, i))
             for rc in self.raw_codes:
-                print('    MP_ROM_PTR(&raw_code_%s),' % rc.escaped_name)
-            print('};')
+                print("    MP_ROM_PTR(&raw_code_%s)," % rc.escaped_name)
+            print("};")
 
     def freeze_module(self, qstr_links=(), type_sig=0):
         # generate module
-        if self.simple_name.str != '<module>':
-            print('STATIC ', end='')
-        print('const mp_raw_code_t raw_code_%s = {' % self.escaped_name)
-        print('    .kind = %s,' % RawCode.code_kind_str[self.code_kind])
-        print('    .scope_flags = 0x%02x,' % self.prelude[2])
-        print('    .n_pos_args = %u,' % self.prelude[3])
-        print('    .fun_data = fun_data_%s,' % self.escaped_name)
+        if self.simple_name.str != "<module>":
+            print("STATIC ", end="")
+        print("const mp_raw_code_t raw_code_%s = {" % self.escaped_name)
+        print("    .kind = %s," % RawCode.code_kind_str[self.code_kind])
+        print("    .scope_flags = 0x%02x," % self.prelude[2])
+        print("    .n_pos_args = %u," % self.prelude[3])
+        print("    .fun_data = fun_data_%s," % self.escaped_name)
         if len(self.qstrs) + len(self.objs) + len(self.raw_codes):
-            print('    .const_table = (mp_uint_t*)const_table_data_%s,' % self.escaped_name)
+            print("    .const_table = (mp_uint_t*)const_table_data_%s," % self.escaped_name)
         else:
-            print('    .const_table = NULL,')
-        print('    #if MICROPY_PERSISTENT_CODE_SAVE')
-        print('    .fun_data_len = %u,' % len(self.bytecode))
-        print('    .n_obj = %u,' % len(self.objs))
-        print('    .n_raw_code = %u,' % len(self.raw_codes))
+            print("    .const_table = NULL,")
+        print("    #if MICROPY_PERSISTENT_CODE_SAVE")
+        print("    .fun_data_len = %u," % len(self.bytecode))
+        print("    .n_obj = %u," % len(self.objs))
+        print("    .n_raw_code = %u," % len(self.raw_codes))
         if self.code_kind == MP_CODE_BYTECODE:
-            print('    #if MICROPY_PY_SYS_SETTRACE')
-            print('    .prelude = {')
-            print('        .n_state = %u,' % self.prelude[0])
-            print('        .n_exc_stack = %u,' % self.prelude[1])
-            print('        .scope_flags = %u,' % self.prelude[2])
-            print('        .n_pos_args = %u,' % self.prelude[3])
-            print('        .n_kwonly_args = %u,' % self.prelude[4])
-            print('        .n_def_pos_args = %u,' % self.prelude[5])
-            print('        .qstr_block_name = %s,' % self.simple_name.qstr_id)
-            print('        .qstr_source_file = %s,' % self.source_file.qstr_id)
-            print('        .line_info = fun_data_%s + %u,' % (self.escaped_name, 0)) # TODO
-            print('        .opcodes = fun_data_%s + %u,' % (self.escaped_name, self.ip))
-            print('    },')
-            print('    .line_of_definition = %u,' % 0) # TODO
-            print('    #endif')
-        print('    #if MICROPY_EMIT_MACHINE_CODE')
-        print('    .prelude_offset = %u,' % self.prelude_offset)
-        print('    .n_qstr = %u,' % len(qstr_links))
-        print('    .qstr_link = NULL,') # TODO
-        print('    #endif')
-        print('    #endif')
-        print('    #if MICROPY_EMIT_MACHINE_CODE')
-        print('    .type_sig = %u,' % type_sig)
-        print('    #endif')
-        print('};')
+            print("    #if MICROPY_PY_SYS_SETTRACE")
+            print("    .prelude = {")
+            print("        .n_state = %u," % self.prelude[0])
+            print("        .n_exc_stack = %u," % self.prelude[1])
+            print("        .scope_flags = %u," % self.prelude[2])
+            print("        .n_pos_args = %u," % self.prelude[3])
+            print("        .n_kwonly_args = %u," % self.prelude[4])
+            print("        .n_def_pos_args = %u," % self.prelude[5])
+            print("        .qstr_block_name = %s," % self.simple_name.qstr_id)
+            print("        .qstr_source_file = %s," % self.source_file.qstr_id)
+            print("        .line_info = fun_data_%s + %u," % (self.escaped_name, 0))  # TODO
+            print("        .opcodes = fun_data_%s + %u," % (self.escaped_name, self.ip))
+            print("    },")
+            print("    .line_of_definition = %u," % 0)  # TODO
+            print("    #endif")
+        print("    #if MICROPY_EMIT_MACHINE_CODE")
+        print("    .prelude_offset = %u," % self.prelude_offset)
+        print("    .n_qstr = %u," % len(qstr_links))
+        print("    .qstr_link = NULL,")  # TODO
+        print("    #endif")
+        print("    #endif")
+        print("    #if MICROPY_EMIT_MACHINE_CODE")
+        print("    .type_sig = %u," % type_sig)
+        print("    #endif")
+        print("};")
+
 
 class RawCodeBytecode(RawCode):
     def __init__(self, bytecode, qstrs, objs, raw_codes):
-        super(RawCodeBytecode, self).__init__(MP_CODE_BYTECODE, bytecode, 0, qstrs, objs, raw_codes)
+        super(RawCodeBytecode, self).__init__(
+            MP_CODE_BYTECODE, bytecode, 0, qstrs, objs, raw_codes
+        )
 
     def freeze(self, parent_name):
         self.freeze_children(parent_name)
 
         # generate bytecode data
         print()
-        print('// frozen bytecode for file %s, scope %s%s' % (self.source_file.str, parent_name, self.simple_name.str))
-        print('STATIC ', end='')
+        print(
+            "// frozen bytecode for file %s, scope %s%s"
+            % (self.source_file.str, parent_name, self.simple_name.str)
+        )
+        print("STATIC ", end="")
         if not config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE:
-            print('const ', end='')
-        print('byte fun_data_%s[%u] = {' % (self.escaped_name, len(self.bytecode)))
-        print('   ', end='')
+            print("const ", end="")
+        print("byte fun_data_%s[%u] = {" % (self.escaped_name, len(self.bytecode)))
+        print("   ", end="")
         for i in range(self.ip2):
-            print(' 0x%02x,' % self.bytecode[i], end='')
+            print(" 0x%02x," % self.bytecode[i], end="")
         print()
-        print('   ', self.simple_name.qstr_id, '& 0xff,', self.simple_name.qstr_id, '>> 8,')
-        print('   ', self.source_file.qstr_id, '& 0xff,', self.source_file.qstr_id, '>> 8,')
-        print('   ', end='')
+        print("   ", self.simple_name.qstr_id, "& 0xff,", self.simple_name.qstr_id, ">> 8,")
+        print("   ", self.source_file.qstr_id, "& 0xff,", self.source_file.qstr_id, ">> 8,")
+        print("   ", end="")
         for i in range(self.ip2 + 4, self.ip):
-            print(' 0x%02x,' % self.bytecode[i], end='')
+            print(" 0x%02x," % self.bytecode[i], end="")
         print()
         ip = self.ip
         while ip < len(self.bytecode):
             f, sz = mp_opcode_format(self.bytecode, ip, True)
             if f == 1:
                 qst = self._unpack_qstr(ip + 1).qstr_id
-                extra = '' if sz == 3 else ' 0x%02x,' % self.bytecode[ip + 3]
-                print('   ', '0x%02x,' % self.bytecode[ip], qst, '& 0xff,', qst, '>> 8,', extra)
+                extra = "" if sz == 3 else " 0x%02x," % self.bytecode[ip + 3]
+                print("   ", "0x%02x," % self.bytecode[ip], qst, "& 0xff,", qst, ">> 8,", extra)
             else:
-                print('   ', ''.join('0x%02x, ' % self.bytecode[ip + i] for i in range(sz)))
+                print("   ", "".join("0x%02x, " % self.bytecode[ip + i] for i in range(sz)))
             ip += sz
-        print('};')
+        print("};")
 
         self.freeze_constants()
         self.freeze_module()
 
+
 class RawCodeNative(RawCode):
-    def __init__(self, code_kind, fun_data, prelude_offset, prelude, qstr_links, qstrs, objs, raw_codes, type_sig):
-        super(RawCodeNative, self).__init__(code_kind, fun_data, prelude_offset, qstrs, objs, raw_codes)
+    def __init__(
+        self,
+        code_kind,
+        fun_data,
+        prelude_offset,
+        prelude,
+        qstr_links,
+        qstrs,
+        objs,
+        raw_codes,
+        type_sig,
+    ):
+        super(RawCodeNative, self).__init__(
+            code_kind, fun_data, prelude_offset, qstrs, objs, raw_codes
+        )
         self.prelude = prelude
         self.qstr_links = qstr_links
         self.type_sig = type_sig
-        if config.native_arch in (MP_NATIVE_ARCH_X86, MP_NATIVE_ARCH_X64,
-            MP_NATIVE_ARCH_XTENSA, MP_NATIVE_ARCH_XTENSAWIN):
+        if config.native_arch in (
+            MP_NATIVE_ARCH_X86,
+            MP_NATIVE_ARCH_X64,
+            MP_NATIVE_ARCH_XTENSA,
+            MP_NATIVE_ARCH_XTENSAWIN,
+        ):
             self.fun_data_attributes = '__attribute__((section(".text,\\"ax\\",@progbits # ")))'
         else:
             self.fun_data_attributes = '__attribute__((section(".text,\\"ax\\",%progbits @ ")))'
@@ -431,40 +497,49 @@
         # Allow single-byte alignment by default for x86/x64.
         # ARM needs word alignment, ARM Thumb needs halfword, due to instruction size.
         # Xtensa needs word alignment due to the 32-bit constant table embedded in the code.
-        if config.native_arch in (MP_NATIVE_ARCH_ARMV6, MP_NATIVE_ARCH_XTENSA, MP_NATIVE_ARCH_XTENSAWIN):
+        if config.native_arch in (
+            MP_NATIVE_ARCH_ARMV6,
+            MP_NATIVE_ARCH_XTENSA,
+            MP_NATIVE_ARCH_XTENSAWIN,
+        ):
             # ARMV6 or Xtensa -- four byte align.
-            self.fun_data_attributes += ' __attribute__ ((aligned (4)))'
+            self.fun_data_attributes += " __attribute__ ((aligned (4)))"
         elif MP_NATIVE_ARCH_ARMV6M <= config.native_arch <= MP_NATIVE_ARCH_ARMV7EMDP:
             # ARMVxxM -- two byte align.
-            self.fun_data_attributes += ' __attribute__ ((aligned (2)))'
+            self.fun_data_attributes += " __attribute__ ((aligned (2)))"
 
     def _asm_thumb_rewrite_mov(self, pc, val):
-        print('    (%u & 0xf0) | (%s >> 12),' % (self.bytecode[pc], val), end='')
-        print(' (%u & 0xfb) | (%s >> 9 & 0x04),' % (self.bytecode[pc + 1], val), end='')
-        print(' (%s & 0xff),' % (val,), end='')
-        print(' (%u & 0x07) | (%s >> 4 & 0x70),' % (self.bytecode[pc + 3], val))
+        print("    (%u & 0xf0) | (%s >> 12)," % (self.bytecode[pc], val), end="")
+        print(" (%u & 0xfb) | (%s >> 9 & 0x04)," % (self.bytecode[pc + 1], val), end="")
+        print(" (%s & 0xff)," % (val,), end="")
+        print(" (%u & 0x07) | (%s >> 4 & 0x70)," % (self.bytecode[pc + 3], val))
 
     def _link_qstr(self, pc, kind, qst):
         if kind == 0:
             # Generic 16-bit link
-            print('    %s & 0xff, %s >> 8,' % (qst, qst))
+            print("    %s & 0xff, %s >> 8," % (qst, qst))
             return 2
         else:
             # Architecture-specific link
             is_obj = kind == 2
             if is_obj:
-                qst = '((uintptr_t)MP_OBJ_NEW_QSTR(%s))' % qst
+                qst = "((uintptr_t)MP_OBJ_NEW_QSTR(%s))" % qst
             if config.native_arch in (
-                MP_NATIVE_ARCH_X86, MP_NATIVE_ARCH_X64,
-                MP_NATIVE_ARCH_XTENSA, MP_NATIVE_ARCH_XTENSAWIN
-                ):
-                print('    %s & 0xff, (%s >> 8) & 0xff, (%s >> 16) & 0xff, %s >> 24,' % (qst, qst, qst, qst))
+                MP_NATIVE_ARCH_X86,
+                MP_NATIVE_ARCH_X64,
+                MP_NATIVE_ARCH_XTENSA,
+                MP_NATIVE_ARCH_XTENSAWIN,
+            ):
+                print(
+                    "    %s & 0xff, (%s >> 8) & 0xff, (%s >> 16) & 0xff, %s >> 24,"
+                    % (qst, qst, qst, qst)
+                )
                 return 4
             elif MP_NATIVE_ARCH_ARMV6M <= config.native_arch <= MP_NATIVE_ARCH_ARMV7EMDP:
                 if is_obj:
                     # qstr object, movw and movt
                     self._asm_thumb_rewrite_mov(pc, qst)
-                    self._asm_thumb_rewrite_mov(pc + 4, '(%s >> 16)' % qst)
+                    self._asm_thumb_rewrite_mov(pc + 4, "(%s >> 16)" % qst)
                     return 8
                 else:
                     # qstr number, movw instruction
@@ -474,20 +549,26 @@
                 assert 0
 
     def freeze(self, parent_name):
-        if self.prelude[2] & ~0x0f:
-            raise FreezeError('unable to freeze code with relocations')
+        if self.prelude[2] & ~0x0F:
+            raise FreezeError("unable to freeze code with relocations")
 
         self.freeze_children(parent_name)
 
         # generate native code data
         print()
         if self.code_kind == MP_CODE_NATIVE_PY:
-            print('// frozen native code for file %s, scope %s%s' % (self.source_file.str, parent_name, self.simple_name.str))
+            print(
+                "// frozen native code for file %s, scope %s%s"
+                % (self.source_file.str, parent_name, self.simple_name.str)
+            )
         elif self.code_kind == MP_CODE_NATIVE_VIPER:
-            print('// frozen viper code for scope %s' % (parent_name,))
+            print("// frozen viper code for scope %s" % (parent_name,))
         else:
-            print('// frozen assembler code for scope %s' % (parent_name,))
-        print('STATIC const byte fun_data_%s[%u] %s = {' % (self.escaped_name, len(self.bytecode), self.fun_data_attributes))
+            print("// frozen assembler code for scope %s" % (parent_name,))
+        print(
+            "STATIC const byte fun_data_%s[%u] %s = {"
+            % (self.escaped_name, len(self.bytecode), self.fun_data_attributes)
+        )
 
         if self.code_kind == MP_CODE_NATIVE_PY:
             i_top = self.prelude_offset
@@ -507,31 +588,32 @@
                 i16 = min(i + 16, i_top)
                 if qi < len(self.qstr_links):
                     i16 = min(i16, self.qstr_links[qi][0])
-                print('   ', end='')
+                print("   ", end="")
                 for ii in range(i, i16):
-                    print(' 0x%02x,' % self.bytecode[ii], end='')
+                    print(" 0x%02x," % self.bytecode[ii], end="")
                 print()
                 i = i16
 
         if self.code_kind == MP_CODE_NATIVE_PY:
-            print('   ', end='')
+            print("   ", end="")
             for i in range(self.prelude_offset, self.ip2):
-                print(' 0x%02x,' % self.bytecode[i], end='')
+                print(" 0x%02x," % self.bytecode[i], end="")
             print()
 
-            print('   ', self.simple_name.qstr_id, '& 0xff,', self.simple_name.qstr_id, '>> 8,')
-            print('   ', self.source_file.qstr_id, '& 0xff,', self.source_file.qstr_id, '>> 8,')
+            print("   ", self.simple_name.qstr_id, "& 0xff,", self.simple_name.qstr_id, ">> 8,")
+            print("   ", self.source_file.qstr_id, "& 0xff,", self.source_file.qstr_id, ">> 8,")
 
-            print('   ', end='')
+            print("   ", end="")
             for i in range(self.ip2 + 4, self.ip):
-                print(' 0x%02x,' % self.bytecode[i], end='')
+                print(" 0x%02x," % self.bytecode[i], end="")
             print()
 
-        print('};')
+        print("};")
 
         self.freeze_constants()
         self.freeze_module(self.qstr_links, self.type_sig)
 
+
 class BytecodeBuffer:
     def __init__(self, size):
         self.buf = bytearray(size)
@@ -544,21 +626,24 @@
         self.buf[self.idx] = b
         self.idx += 1
 
+
 def read_byte(f, out=None):
     b = bytes_cons(f.read(1))[0]
     if out is not None:
         out.append(b)
     return b
 
+
 def read_uint(f, out=None):
     i = 0
     while True:
         b = read_byte(f, out)
-        i = (i << 7) | (b & 0x7f)
+        i = (i << 7) | (b & 0x7F)
         if b & 0x80 == 0:
             break
     return i
 
+
 def read_qstr(f, qstr_win):
     ln = read_uint(f)
     if ln == 0:
@@ -568,44 +653,55 @@
         # qstr in table
         return qstr_win.access(ln >> 1)
     ln >>= 1
-    data = str_cons(f.read(ln), 'utf8')
+    data = str_cons(f.read(ln), "utf8")
     global_qstrs.append(QStrType(data))
     qstr_win.push(len(global_qstrs) - 1)
     return len(global_qstrs) - 1
 
+
 def read_obj(f):
     obj_type = f.read(1)
-    if obj_type == b'e':
+    if obj_type == b"e":
         return Ellipsis
     else:
         buf = f.read(read_uint(f))
-        if obj_type == b's':
-            return str_cons(buf, 'utf8')
-        elif obj_type == b'b':
+        if obj_type == b"s":
+            return str_cons(buf, "utf8")
+        elif obj_type == b"b":
             return bytes_cons(buf)
-        elif obj_type == b'i':
-            return int(str_cons(buf, 'ascii'), 10)
-        elif obj_type == b'f':
-            return float(str_cons(buf, 'ascii'))
-        elif obj_type == b'c':
-            return complex(str_cons(buf, 'ascii'))
+        elif obj_type == b"i":
+            return int(str_cons(buf, "ascii"), 10)
+        elif obj_type == b"f":
+            return float(str_cons(buf, "ascii"))
+        elif obj_type == b"c":
+            return complex(str_cons(buf, "ascii"))
         else:
             assert 0
 
+
 def read_prelude(f, bytecode, qstr_win):
-    n_state, n_exc_stack, scope_flags, n_pos_args, n_kwonly_args, n_def_pos_args = read_prelude_sig(lambda: read_byte(f, bytecode))
+    (
+        n_state,
+        n_exc_stack,
+        scope_flags,
+        n_pos_args,
+        n_kwonly_args,
+        n_def_pos_args,
+    ) = read_prelude_sig(lambda: read_byte(f, bytecode))
     n_info, n_cell = read_prelude_size(lambda: read_byte(f, bytecode))
-    read_qstr_and_pack(f, bytecode, qstr_win) # simple_name
-    read_qstr_and_pack(f, bytecode, qstr_win) # source_file
+    read_qstr_and_pack(f, bytecode, qstr_win)  # simple_name
+    read_qstr_and_pack(f, bytecode, qstr_win)  # source_file
     for _ in range(n_info - 4 + n_cell):
         read_byte(f, bytecode)
     return n_state, n_exc_stack, scope_flags, n_pos_args, n_kwonly_args, n_def_pos_args
 
+
 def read_qstr_and_pack(f, bytecode, qstr_win):
     qst = read_qstr(f, qstr_win)
-    bytecode.append(qst & 0xff)
+    bytecode.append(qst & 0xFF)
     bytecode.append(qst >> 8)
 
+
 def read_bytecode(file, bytecode, qstr_win):
     while not bytecode.is_full():
         op = read_byte(file, bytecode)
@@ -620,6 +716,7 @@
         for _ in range(sz):
             read_byte(file, bytecode)
 
+
 def read_raw_code(f, qstr_win):
     kind_len = read_uint(f)
     kind = (kind_len & 3) + MP_CODE_BYTECODE
@@ -645,9 +742,9 @@
         if kind == MP_CODE_NATIVE_PY:
             prelude_offset = read_uint(f)
             _, name_idx, prelude = extract_prelude(fun_data.buf, prelude_offset)
-            fun_data.idx = name_idx # rewind to where qstrs are in prelude
-            read_qstr_and_pack(f, fun_data, qstr_win) # simple_name
-            read_qstr_and_pack(f, fun_data, qstr_win) # source_file
+            fun_data.idx = name_idx  # rewind to where qstrs are in prelude
+            read_qstr_and_pack(f, fun_data, qstr_win)  # simple_name
+            read_qstr_and_pack(f, fun_data, qstr_win)  # source_file
         else:
             prelude_offset = None
             scope_flags = read_uint(f)
@@ -673,15 +770,26 @@
     if kind == MP_CODE_BYTECODE:
         return RawCodeBytecode(fun_data.buf, qstrs, objs, raw_codes)
     else:
-        return RawCodeNative(kind, fun_data.buf, prelude_offset, prelude, qstr_links, qstrs, objs, raw_codes, type_sig)
+        return RawCodeNative(
+            kind,
+            fun_data.buf,
+            prelude_offset,
+            prelude,
+            qstr_links,
+            qstrs,
+            objs,
+            raw_codes,
+            type_sig,
+        )
+
 
 def read_mpy(filename):
-    with open(filename, 'rb') as f:
+    with open(filename, "rb") as f:
         header = bytes_cons(f.read(4))
-        if header[0] != ord('M'):
-            raise Exception('not a valid .mpy file')
+        if header[0] != ord("M"):
+            raise Exception("not a valid .mpy file")
         if header[1] != config.MPY_VERSION:
-            raise Exception('incompatible .mpy version')
+            raise Exception("incompatible .mpy version")
         feature_byte = header[2]
         qw_size = read_uint(f)
         config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE = (feature_byte & 1) != 0
@@ -691,7 +799,7 @@
             if config.native_arch == MP_NATIVE_ARCH_NONE:
                 config.native_arch = mpy_native_arch
             elif config.native_arch != mpy_native_arch:
-                raise Exception('native architecture mismatch')
+                raise Exception("native architecture mismatch")
         config.mp_small_int_bits = header[3]
         qstr_win = QStrWindow(qw_size)
         rc = read_raw_code(f, qstr_win)
@@ -699,10 +807,12 @@
         rc.qstr_win_size = qw_size
         return rc
 
+
 def dump_mpy(raw_codes):
     for rc in raw_codes:
         rc.dump()
 
+
 def freeze_mpy(base_qstrs, raw_codes):
     # add to qstrs
     new = {}
@@ -720,156 +830,172 @@
     print('#include "py/nativeglue.h"')
     print()
 
-    print('#if MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE != %u' % config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE)
+    print(
+        "#if MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE != %u"
+        % config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE
+    )
     print('#error "incompatible MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE"')
-    print('#endif')
+    print("#endif")
     print()
 
-    print('#if MICROPY_LONGINT_IMPL != %u' % config.MICROPY_LONGINT_IMPL)
+    print("#if MICROPY_LONGINT_IMPL != %u" % config.MICROPY_LONGINT_IMPL)
     print('#error "incompatible MICROPY_LONGINT_IMPL"')
-    print('#endif')
+    print("#endif")
     print()
 
     if config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_MPZ:
-        print('#if MPZ_DIG_SIZE != %u' % config.MPZ_DIG_SIZE)
+        print("#if MPZ_DIG_SIZE != %u" % config.MPZ_DIG_SIZE)
         print('#error "incompatible MPZ_DIG_SIZE"')
-        print('#endif')
+        print("#endif")
         print()
 
-
-    print('#if MICROPY_PY_BUILTINS_FLOAT')
-    print('typedef struct _mp_obj_float_t {')
-    print('    mp_obj_base_t base;')
-    print('    mp_float_t value;')
-    print('} mp_obj_float_t;')
-    print('#endif')
+    print("#if MICROPY_PY_BUILTINS_FLOAT")
+    print("typedef struct _mp_obj_float_t {")
+    print("    mp_obj_base_t base;")
+    print("    mp_float_t value;")
+    print("} mp_obj_float_t;")
+    print("#endif")
     print()
 
-    print('#if MICROPY_PY_BUILTINS_COMPLEX')
-    print('typedef struct _mp_obj_complex_t {')
-    print('    mp_obj_base_t base;')
-    print('    mp_float_t real;')
-    print('    mp_float_t imag;')
-    print('} mp_obj_complex_t;')
-    print('#endif')
+    print("#if MICROPY_PY_BUILTINS_COMPLEX")
+    print("typedef struct _mp_obj_complex_t {")
+    print("    mp_obj_base_t base;")
+    print("    mp_float_t real;")
+    print("    mp_float_t imag;")
+    print("} mp_obj_complex_t;")
+    print("#endif")
     print()
 
     if len(new) > 0:
-        print('enum {')
+        print("enum {")
         for i in range(len(new)):
             if i == 0:
-                print('    MP_QSTR_%s = MP_QSTRnumber_of,' % new[i][1])
+                print("    MP_QSTR_%s = MP_QSTRnumber_of," % new[i][1])
             else:
-                print('    MP_QSTR_%s,' % new[i][1])
-        print('};')
+                print("    MP_QSTR_%s," % new[i][1])
+        print("};")
 
     # As in qstr.c, set so that the first dynamically allocated pool is twice this size; must be <= the len
     qstr_pool_alloc = min(len(new), 10)
 
     print()
-    print('extern const qstr_pool_t mp_qstr_const_pool;');
-    print('const qstr_pool_t mp_qstr_frozen_const_pool = {')
-    print('    (qstr_pool_t*)&mp_qstr_const_pool, // previous pool')
-    print('    MP_QSTRnumber_of, // previous pool size')
-    print('    %u, // allocated entries' % qstr_pool_alloc)
-    print('    %u, // used entries' % len(new))
-    print('    {')
+    print("extern const qstr_pool_t mp_qstr_const_pool;")
+    print("const qstr_pool_t mp_qstr_frozen_const_pool = {")
+    print("    (qstr_pool_t*)&mp_qstr_const_pool, // previous pool")
+    print("    MP_QSTRnumber_of, // previous pool size")
+    print("    %u, // allocated entries" % qstr_pool_alloc)
+    print("    %u, // used entries" % len(new))
+    print("    {")
     for _, _, qstr in new:
-        print('        %s,'
-            % qstrutil.make_bytes(config.MICROPY_QSTR_BYTES_IN_LEN, config.MICROPY_QSTR_BYTES_IN_HASH, qstr))
-    print('    },')
-    print('};')
+        print(
+            "        %s,"
+            % qstrutil.make_bytes(
+                config.MICROPY_QSTR_BYTES_IN_LEN, config.MICROPY_QSTR_BYTES_IN_HASH, qstr
+            )
+        )
+    print("    },")
+    print("};")
 
     for rc in raw_codes:
-        rc.freeze(rc.source_file.str.replace('/', '_')[:-3] + '_')
+        rc.freeze(rc.source_file.str.replace("/", "_")[:-3] + "_")
 
     print()
-    print('const char mp_frozen_mpy_names[] = {')
+    print("const char mp_frozen_mpy_names[] = {")
     for rc in raw_codes:
         module_name = rc.source_file.str
         print('"%s\\0"' % module_name)
     print('"\\0"};')
 
-    print('const mp_raw_code_t *const mp_frozen_mpy_content[] = {')
+    print("const mp_raw_code_t *const mp_frozen_mpy_content[] = {")
     for rc in raw_codes:
-        print('    &raw_code_%s,' % rc.escaped_name)
-    print('};')
+        print("    &raw_code_%s," % rc.escaped_name)
+    print("};")
+
 
 def merge_mpy(raw_codes, output_file):
-    assert len(raw_codes) <= 31 # so var-uints all fit in 1 byte
+    assert len(raw_codes) <= 31  # so var-uints all fit in 1 byte
     merged_mpy = bytearray()
 
     if len(raw_codes) == 1:
-        with open(raw_codes[0].mpy_source_file, 'rb') as f:
+        with open(raw_codes[0].mpy_source_file, "rb") as f:
             merged_mpy.extend(f.read())
     else:
         header = bytearray(5)
-        header[0] = ord('M')
+        header[0] = ord("M")
         header[1] = config.MPY_VERSION
-        header[2] = (config.native_arch << 2
+        header[2] = (
+            config.native_arch << 2
             | config.MICROPY_PY_BUILTINS_STR_UNICODE << 1
-            | config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE)
+            | config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE
+        )
         header[3] = config.mp_small_int_bits
-        header[4] = 32 # qstr_win_size
+        header[4] = 32  # qstr_win_size
         merged_mpy.extend(header)
 
         bytecode = bytearray()
         bytecode_len = 6 + len(raw_codes) * 4 + 2
-        bytecode.append(bytecode_len << 2) # kind and length
-        bytecode.append(0b00000000) # signature prelude
-        bytecode.append(0b00001000) # size prelude
-        bytecode.extend(b'\x00\x01') # MP_QSTR_
-        bytecode.extend(b'\x00\x01') # MP_QSTR_
+        bytecode.append(bytecode_len << 2)  # kind and length
+        bytecode.append(0b00000000)  # signature prelude
+        bytecode.append(0b00001000)  # size prelude
+        bytecode.extend(b"\x00\x01")  # MP_QSTR_
+        bytecode.extend(b"\x00\x01")  # MP_QSTR_
         for idx in range(len(raw_codes)):
-            bytecode.append(0x32) # MP_BC_MAKE_FUNCTION
-            bytecode.append(idx) # index raw code
-            bytecode.extend(b'\x34\x00') # MP_BC_CALL_FUNCTION, 0 args
-        bytecode.extend(b'\x51\x63') # MP_BC_LOAD_NONE, MP_BC_RETURN_VALUE
+            bytecode.append(0x32)  # MP_BC_MAKE_FUNCTION
+            bytecode.append(idx)  # index raw code
+            bytecode.extend(b"\x34\x00")  # MP_BC_CALL_FUNCTION, 0 args
+        bytecode.extend(b"\x51\x63")  # MP_BC_LOAD_NONE, MP_BC_RETURN_VALUE
 
-        bytecode.append(0) # n_obj
-        bytecode.append(len(raw_codes)) # n_raw_code
+        bytecode.append(0)  # n_obj
+        bytecode.append(len(raw_codes))  # n_raw_code
 
         merged_mpy.extend(bytecode)
 
         for rc in raw_codes:
-            with open(rc.mpy_source_file, 'rb') as f:
-                f.read(4) # skip header
-                read_uint(f) # skip qstr_win_size
-                data = f.read() # read rest of mpy file
+            with open(rc.mpy_source_file, "rb") as f:
+                f.read(4)  # skip header
+                read_uint(f)  # skip qstr_win_size
+                data = f.read()  # read rest of mpy file
                 merged_mpy.extend(data)
 
     if output_file is None:
         sys.stdout.buffer.write(merged_mpy)
     else:
-        with open(output_file, 'wb') as f:
+        with open(output_file, "wb") as f:
             f.write(merged_mpy)
 
+
 def main():
     import argparse
-    cmd_parser = argparse.ArgumentParser(description='A tool to work with MicroPython .mpy files.')
-    cmd_parser.add_argument('-d', '--dump', action='store_true',
-        help='dump contents of files')
-    cmd_parser.add_argument('-f', '--freeze', action='store_true',
-        help='freeze files')
-    cmd_parser.add_argument('--merge', action='store_true',
-        help='merge multiple .mpy files into one')
-    cmd_parser.add_argument('-q', '--qstr-header',
-        help='qstr header file to freeze against')
-    cmd_parser.add_argument('-mlongint-impl', choices=['none', 'longlong', 'mpz'], default='mpz',
-        help='long-int implementation used by target (default mpz)')
-    cmd_parser.add_argument('-mmpz-dig-size', metavar='N', type=int, default=16,
-        help='mpz digit size used by target (default 16)')
-    cmd_parser.add_argument('-o', '--output', default=None,
-        help='output file')
-    cmd_parser.add_argument('files', nargs='+',
-        help='input .mpy files')
+
+    cmd_parser = argparse.ArgumentParser(description="A tool to work with MicroPython .mpy files.")
+    cmd_parser.add_argument("-d", "--dump", action="store_true", help="dump contents of files")
+    cmd_parser.add_argument("-f", "--freeze", action="store_true", help="freeze files")
+    cmd_parser.add_argument(
+        "--merge", action="store_true", help="merge multiple .mpy files into one"
+    )
+    cmd_parser.add_argument("-q", "--qstr-header", help="qstr header file to freeze against")
+    cmd_parser.add_argument(
+        "-mlongint-impl",
+        choices=["none", "longlong", "mpz"],
+        default="mpz",
+        help="long-int implementation used by target (default mpz)",
+    )
+    cmd_parser.add_argument(
+        "-mmpz-dig-size",
+        metavar="N",
+        type=int,
+        default=16,
+        help="mpz digit size used by target (default 16)",
+    )
+    cmd_parser.add_argument("-o", "--output", default=None, help="output file")
+    cmd_parser.add_argument("files", nargs="+", help="input .mpy files")
     args = cmd_parser.parse_args()
 
     # set config values relevant to target machine
     config.MICROPY_LONGINT_IMPL = {
-        'none':config.MICROPY_LONGINT_IMPL_NONE,
-        'longlong':config.MICROPY_LONGINT_IMPL_LONGLONG,
-        'mpz':config.MICROPY_LONGINT_IMPL_MPZ,
+        "none": config.MICROPY_LONGINT_IMPL_NONE,
+        "longlong": config.MICROPY_LONGINT_IMPL_LONGLONG,
+        "mpz": config.MICROPY_LONGINT_IMPL_MPZ,
     }[args.mlongint_impl]
     config.MPZ_DIG_SIZE = args.mmpz_dig_size
     config.native_arch = MP_NATIVE_ARCH_NONE
@@ -877,8 +1003,8 @@
     # set config values for qstrs, and get the existing base set of qstrs
     if args.qstr_header:
         qcfgs, base_qstrs = qstrutil.parse_input_headers([args.qstr_header])
-        config.MICROPY_QSTR_BYTES_IN_LEN = int(qcfgs['BYTES_IN_LEN'])
-        config.MICROPY_QSTR_BYTES_IN_HASH = int(qcfgs['BYTES_IN_HASH'])
+        config.MICROPY_QSTR_BYTES_IN_LEN = int(qcfgs["BYTES_IN_LEN"])
+        config.MICROPY_QSTR_BYTES_IN_HASH = int(qcfgs["BYTES_IN_HASH"])
     else:
         config.MICROPY_QSTR_BYTES_IN_LEN = 1
         config.MICROPY_QSTR_BYTES_IN_HASH = 1
@@ -897,5 +1023,6 @@
     elif args.merge:
         merged_mpy = merge_mpy(raw_codes, args.output)
 
-if __name__ == '__main__':
+
+if __name__ == "__main__":
     main()
diff --git a/tools/mpy_cross_all.py b/tools/mpy_cross_all.py
index 2bda71e..d542bde 100755
--- a/tools/mpy_cross_all.py
+++ b/tools/mpy_cross_all.py
@@ -6,7 +6,9 @@
 argparser = argparse.ArgumentParser(description="Compile all .py files to .mpy recursively")
 argparser.add_argument("-o", "--out", help="output directory (default: input dir)")
 argparser.add_argument("--target", help="select MicroPython target config")
-argparser.add_argument("-mcache-lookup-bc", action="store_true", help="cache map lookups in the bytecode")
+argparser.add_argument(
+    "-mcache-lookup-bc", action="store_true", help="cache map lookups in the bytecode"
+)
 argparser.add_argument("dir", help="input directory")
 args = argparser.parse_args()
 
@@ -26,13 +28,17 @@
     for f in files:
         if f.endswith(".py"):
             fpath = path + "/" + f
-            #print(fpath)
+            # print(fpath)
             out_fpath = args.out + "/" + fpath[path_prefix_len:-3] + ".mpy"
             out_dir = os.path.dirname(out_fpath)
             if not os.path.isdir(out_dir):
                 os.makedirs(out_dir)
-            cmd = "mpy-cross -v -v %s -s %s %s -o %s" % (TARGET_OPTS.get(args.target, ""),
-                fpath[path_prefix_len:], fpath, out_fpath)
-            #print(cmd)
+            cmd = "mpy-cross -v -v %s -s %s %s -o %s" % (
+                TARGET_OPTS.get(args.target, ""),
+                fpath[path_prefix_len:],
+                fpath,
+                out_fpath,
+            )
+            # print(cmd)
             res = os.system(cmd)
             assert res == 0
diff --git a/tools/mpy_ld.py b/tools/mpy_ld.py
index 31c3912..32bc176 100755
--- a/tools/mpy_ld.py
+++ b/tools/mpy_ld.py
@@ -31,7 +31,7 @@
 import sys, os, struct, re
 from elftools.elf import elffile
 
-sys.path.append(os.path.dirname(__file__) + '/../py')
+sys.path.append(os.path.dirname(__file__) + "/../py")
 import makeqstrdata as qstrutil
 
 # MicroPython constants
@@ -70,8 +70,8 @@
 R_ARM_THM_CALL = 10
 R_XTENSA_DIFF32 = 19
 R_XTENSA_SLOT0_OP = 20
-R_ARM_BASE_PREL = 25 # aka R_ARM_GOTPC
-R_ARM_GOT_BREL = 26 # aka R_ARM_GOT32
+R_ARM_BASE_PREL = 25  # aka R_ARM_GOTPC
+R_ARM_GOT_BREL = 26  # aka R_ARM_GOT32
 R_ARM_THM_JUMP24 = 30
 R_X86_64_REX_GOTPCRELX = 42
 R_386_GOT32X = 43
@@ -79,25 +79,29 @@
 ################################################################################
 # Architecture configuration
 
+
 def asm_jump_x86(entry):
-    return struct.pack('<BI', 0xe9, entry - 5)
+    return struct.pack("<BI", 0xE9, entry - 5)
+
 
 def asm_jump_arm(entry):
     b_off = entry - 4
     if b_off >> 11 == 0 or b_off >> 11 == -1:
         # Signed value fits in 12 bits
-        b0 = 0xe000 | (b_off >> 1 & 0x07ff)
+        b0 = 0xE000 | (b_off >> 1 & 0x07FF)
         b1 = 0
     else:
         # Use large jump
-        b0 = 0xf000 | (b_off >> 12 & 0x07ff)
-        b1 = 0xb800 | (b_off >> 1 & 0x7ff)
-    return struct.pack('<HH', b0, b1)
+        b0 = 0xF000 | (b_off >> 12 & 0x07FF)
+        b1 = 0xB800 | (b_off >> 1 & 0x7FF)
+    return struct.pack("<HH", b0, b1)
+
 
 def asm_jump_xtensa(entry):
     jump_offset = entry - 4
     jump_op = jump_offset << 6 | 6
-    return struct.pack('<BH', jump_op & 0xff, jump_op >> 8)
+    return struct.pack("<BH", jump_op & 0xFF, jump_op >> 8)
+
 
 class ArchData:
     def __init__(self, name, mpy_feature, qstr_entry_size, word_size, arch_got, asm_jump):
@@ -107,83 +111,117 @@
         self.word_size = word_size
         self.arch_got = arch_got
         self.asm_jump = asm_jump
-        self.separate_rodata = name == 'EM_XTENSA' and qstr_entry_size == 4
+        self.separate_rodata = name == "EM_XTENSA" and qstr_entry_size == 4
+
 
 ARCH_DATA = {
-    'x86': ArchData(
-        'EM_386',
-        MP_NATIVE_ARCH_X86 << 2 | MICROPY_PY_BUILTINS_STR_UNICODE | MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE,
-        2, 4, (R_386_PC32, R_386_GOT32, R_386_GOT32X), asm_jump_x86,
+    "x86": ArchData(
+        "EM_386",
+        MP_NATIVE_ARCH_X86 << 2
+        | MICROPY_PY_BUILTINS_STR_UNICODE
+        | MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE,
+        2,
+        4,
+        (R_386_PC32, R_386_GOT32, R_386_GOT32X),
+        asm_jump_x86,
     ),
-    'x64': ArchData(
-        'EM_X86_64',
-        MP_NATIVE_ARCH_X64 << 2 | MICROPY_PY_BUILTINS_STR_UNICODE | MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE,
-        2, 8, (R_X86_64_REX_GOTPCRELX,), asm_jump_x86,
+    "x64": ArchData(
+        "EM_X86_64",
+        MP_NATIVE_ARCH_X64 << 2
+        | MICROPY_PY_BUILTINS_STR_UNICODE
+        | MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE,
+        2,
+        8,
+        (R_X86_64_REX_GOTPCRELX,),
+        asm_jump_x86,
     ),
-    'armv7m': ArchData(
-        'EM_ARM',
+    "armv7m": ArchData(
+        "EM_ARM",
         MP_NATIVE_ARCH_ARMV7M << 2 | MICROPY_PY_BUILTINS_STR_UNICODE,
-        2, 4, (R_ARM_GOT_BREL,), asm_jump_arm,
+        2,
+        4,
+        (R_ARM_GOT_BREL,),
+        asm_jump_arm,
     ),
-    'armv7emsp': ArchData(
-        'EM_ARM',
+    "armv7emsp": ArchData(
+        "EM_ARM",
         MP_NATIVE_ARCH_ARMV7EMSP << 2 | MICROPY_PY_BUILTINS_STR_UNICODE,
-        2, 4, (R_ARM_GOT_BREL,), asm_jump_arm,
+        2,
+        4,
+        (R_ARM_GOT_BREL,),
+        asm_jump_arm,
     ),
-    'armv7emdp': ArchData(
-        'EM_ARM',
+    "armv7emdp": ArchData(
+        "EM_ARM",
         MP_NATIVE_ARCH_ARMV7EMDP << 2 | MICROPY_PY_BUILTINS_STR_UNICODE,
-        2, 4, (R_ARM_GOT_BREL,), asm_jump_arm,
+        2,
+        4,
+        (R_ARM_GOT_BREL,),
+        asm_jump_arm,
     ),
-    'xtensa': ArchData(
-        'EM_XTENSA',
+    "xtensa": ArchData(
+        "EM_XTENSA",
         MP_NATIVE_ARCH_XTENSA << 2 | MICROPY_PY_BUILTINS_STR_UNICODE,
-        2, 4, (R_XTENSA_32, R_XTENSA_PLT), asm_jump_xtensa,
+        2,
+        4,
+        (R_XTENSA_32, R_XTENSA_PLT),
+        asm_jump_xtensa,
     ),
-    'xtensawin': ArchData(
-        'EM_XTENSA',
+    "xtensawin": ArchData(
+        "EM_XTENSA",
         MP_NATIVE_ARCH_XTENSAWIN << 2 | MICROPY_PY_BUILTINS_STR_UNICODE,
-        4, 4, (R_XTENSA_32, R_XTENSA_PLT), asm_jump_xtensa,
+        4,
+        4,
+        (R_XTENSA_32, R_XTENSA_PLT),
+        asm_jump_xtensa,
     ),
 }
 
 ################################################################################
 # Helper functions
 
+
 def align_to(value, align):
     return (value + align - 1) & ~(align - 1)
 
+
 def unpack_u24le(data, offset):
     return data[offset] | data[offset + 1] << 8 | data[offset + 2] << 16
 
+
 def pack_u24le(data, offset, value):
-    data[offset] = value & 0xff
-    data[offset + 1] = value >> 8 & 0xff
-    data[offset + 2] = value >> 16 & 0xff
+    data[offset] = value & 0xFF
+    data[offset + 1] = value >> 8 & 0xFF
+    data[offset + 2] = value >> 16 & 0xFF
+
 
 def xxd(text):
     for i in range(0, len(text), 16):
-        print('{:08x}:'.format(i), end='')
+        print("{:08x}:".format(i), end="")
         for j in range(4):
             off = i + j * 4
             if off < len(text):
-                d = int.from_bytes(text[off:off + 4], 'little')
-                print(' {:08x}'.format(d), end='')
+                d = int.from_bytes(text[off : off + 4], "little")
+                print(" {:08x}".format(d), end="")
         print()
 
+
 # Smaller numbers are enabled first
 LOG_LEVEL_1 = 1
 LOG_LEVEL_2 = 2
 LOG_LEVEL_3 = 3
 log_level = LOG_LEVEL_1
 
+
 def log(level, msg):
     if level <= log_level:
         print(msg)
 
+
 ################################################################################
 # Qstr extraction
 
+
 def extract_qstrs(source_files):
     def read_qstrs(f):
         with open(f) as f:
@@ -191,21 +229,21 @@
             objs = set()
             for line in f:
                 while line:
-                    m = re.search(r'MP_OBJ_NEW_QSTR\((MP_QSTR_[A-Za-z0-9_]*)\)', line)
+                    m = re.search(r"MP_OBJ_NEW_QSTR\((MP_QSTR_[A-Za-z0-9_]*)\)", line)
                     if m:
                         objs.add(m.group(1))
                     else:
-                        m = re.search(r'MP_QSTR_[A-Za-z0-9_]*', line)
+                        m = re.search(r"MP_QSTR_[A-Za-z0-9_]*", line)
                         if m:
                             vals.add(m.group())
                     if m:
                         s = m.span()
-                        line = line[:s[0]] + line[s[1]:]
+                        line = line[: s[0]] + line[s[1] :]
                     else:
-                        line = ''
+                        line = ""
             return vals, objs
 
-    static_qstrs = ['MP_QSTR_' + qstrutil.qstr_escape(q) for q in qstrutil.static_qstr_list]
+    static_qstrs = ["MP_QSTR_" + qstrutil.qstr_escape(q) for q in qstrutil.static_qstr_list]
 
     qstr_vals = set()
     qstr_objs = set()
@@ -217,12 +255,15 @@
 
     return static_qstrs, qstr_vals, qstr_objs
 
+
 ################################################################################
 # Linker
 
+
 class LinkError(Exception):
     pass
 
+
 class Section:
     def __init__(self, name, data, alignment, filename=None):
         self.filename = filename
@@ -237,6 +278,7 @@
         assert elfsec.header.sh_addr == 0
         return Section(elfsec.name, elfsec.data(), elfsec.data_alignment, filename)
 
+
 class GOTEntry:
     def __init__(self, name, sym, link_addr=0):
         self.name = name
@@ -245,60 +287,67 @@
         self.link_addr = link_addr
 
     def isexternal(self):
-        return self.sec_name.startswith('.external')
+        return self.sec_name.startswith(".external")
 
     def istext(self):
-        return self.sec_name.startswith('.text')
+        return self.sec_name.startswith(".text")
 
     def isrodata(self):
-        return self.sec_name.startswith(('.rodata', '.data.rel.ro'))
+        return self.sec_name.startswith((".rodata", ".data.rel.ro"))
 
     def isbss(self):
-        return self.sec_name.startswith('.bss')
+        return self.sec_name.startswith(".bss")
+
 
 class LiteralEntry:
     def __init__(self, value, offset):
         self.value = value
         self.offset = offset
 
+
 class LinkEnv:
     def __init__(self, arch):
         self.arch = ARCH_DATA[arch]
-        self.sections = []          # list of sections in order of output
+        self.sections = []  # list of sections in order of output
         self.literal_sections = []  # list of literal sections (xtensa only)
-        self.known_syms = {}        # dict of symbols that are defined
-        self.unresolved_syms = []   # list of unresolved symbols
-        self.mpy_relocs = []        # list of relocations needed in the output .mpy file
+        self.known_syms = {}  # dict of symbols that are defined
+        self.unresolved_syms = []  # list of unresolved symbols
+        self.mpy_relocs = []  # list of relocations needed in the output .mpy file
 
     def check_arch(self, arch_name):
         if arch_name != self.arch.name:
-            raise LinkError('incompatible arch')
+            raise LinkError("incompatible arch")
 
     def print_sections(self):
-        log(LOG_LEVEL_2, 'sections:')
+        log(LOG_LEVEL_2, "sections:")
         for sec in self.sections:
-            log(LOG_LEVEL_2, '  {:08x} {} size={}'.format(sec.addr, sec.name, len(sec.data)))
+            log(LOG_LEVEL_2, "  {:08x} {} size={}".format(sec.addr, sec.name, len(sec.data)))
 
     def find_addr(self, name):
         if name in self.known_syms:
             s = self.known_syms[name]
-            return s.section.addr + s['st_value']
-        raise LinkError('unknown symbol: {}'.format(name))
+            return s.section.addr + s["st_value"]
+        raise LinkError("unknown symbol: {}".format(name))
+
 
 def build_got_generic(env):
     env.got_entries = {}
     for sec in env.sections:
         for r in sec.reloc:
             s = r.sym
-            if not (s.entry['st_info']['bind'] == 'STB_GLOBAL' and r['r_info_type'] in env.arch.arch_got):
+            if not (
+                s.entry["st_info"]["bind"] == "STB_GLOBAL"
+                and r["r_info_type"] in env.arch.arch_got
+            ):
                 continue
-            s_type = s.entry['st_info']['type']
-            assert s_type in ('STT_NOTYPE', 'STT_FUNC', 'STT_OBJECT'), s_type
+            s_type = s.entry["st_info"]["type"]
+            assert s_type in ("STT_NOTYPE", "STT_FUNC", "STT_OBJECT"), s_type
             assert s.name
             if s.name in env.got_entries:
                 continue
             env.got_entries[s.name] = GOTEntry(s.name, s)
 
+
 def build_got_xtensa(env):
     env.got_entries = {}
     env.lit_entries = {}
@@ -311,21 +360,21 @@
         # Look through literal relocations to find any global pointers that should be GOT entries
         for r in sec.reloc:
             s = r.sym
-            s_type = s.entry['st_info']['type']
-            assert s_type in ('STT_NOTYPE', 'STT_FUNC', 'STT_OBJECT', 'STT_SECTION'), s_type
-            assert r['r_info_type'] in env.arch.arch_got
-            assert r['r_offset'] % env.arch.word_size == 0
+            s_type = s.entry["st_info"]["type"]
+            assert s_type in ("STT_NOTYPE", "STT_FUNC", "STT_OBJECT", "STT_SECTION"), s_type
+            assert r["r_info_type"] in env.arch.arch_got
+            assert r["r_offset"] % env.arch.word_size == 0
             # This entry is a global pointer
-            existing = struct.unpack_from('<I', sec.data, r['r_offset'])[0]
-            if s_type == 'STT_SECTION':
-                assert r['r_addend'] == 0
+            existing = struct.unpack_from("<I", sec.data, r["r_offset"])[0]
+            if s_type == "STT_SECTION":
+                assert r["r_addend"] == 0
                 name = "{}+0x{:x}".format(s.section.name, existing)
             else:
                 assert existing == 0
                 name = s.name
-                if r['r_addend'] != 0:
-                    name = "{}+0x{:x}".format(name, r['r_addend'])
-            idx = '{}+0x{:x}'.format(sec.filename, r['r_offset'])
+                if r["r_addend"] != 0:
+                    name = "{}+0x{:x}".format(name, r["r_addend"])
+            idx = "{}+0x{:x}".format(sec.filename, r["r_offset"])
             env.xt_literals[idx] = name
             if name in env.got_entries:
                 # Deduplicate GOT entries
@@ -334,30 +383,35 @@
 
         # Go through all literal entries finding those that aren't global pointers so must be actual literals
         for i in range(0, len(sec.data), env.arch.word_size):
-            idx = '{}+0x{:x}'.format(sec.filename, i)
+            idx = "{}+0x{:x}".format(sec.filename, i)
             if idx not in env.xt_literals:
                 # This entry is an actual literal
-                value = struct.unpack_from('<I', sec.data, i)[0]
+                value = struct.unpack_from("<I", sec.data, i)[0]
                 env.xt_literals[idx] = value
                 if value in env.lit_entries:
                     # Deduplicate literals
                     continue
-                env.lit_entries[value] = LiteralEntry(value, len(env.lit_entries) * env.arch.word_size)
+                env.lit_entries[value] = LiteralEntry(
+                    value, len(env.lit_entries) * env.arch.word_size
+                )
+
 
 def populate_got(env):
     # Compute GOT destination addresses
     for got_entry in env.got_entries.values():
         sym = got_entry.sym
-        if hasattr(sym, 'resolved'):
+        if hasattr(sym, "resolved"):
             sym = sym.resolved
         sec = sym.section
-        addr = sym['st_value']
+        addr = sym["st_value"]
         got_entry.sec_name = sec.name
         got_entry.link_addr += sec.addr + addr
 
     # Get sorted GOT, sorted by external, text, rodata, bss so relocations can be combined
-    got_list = sorted(env.got_entries.values(),
-        key=lambda g: g.isexternal() + 2 * g.istext() + 3 * g.isrodata() + 4 * g.isbss())
+    got_list = sorted(
+        env.got_entries.values(),
+        key=lambda g: g.isexternal() + 2 * g.istext() + 3 * g.isrodata() + 4 * g.isbss(),
+    )
 
     # Layout and populate the GOT
     offset = 0
@@ -365,131 +419,154 @@
         got_entry.offset = offset
         offset += env.arch.word_size
         o = env.got_section.addr + got_entry.offset
-        env.full_text[o:o + env.arch.word_size] = got_entry.link_addr.to_bytes(env.arch.word_size, 'little')
+        env.full_text[o : o + env.arch.word_size] = got_entry.link_addr.to_bytes(
+            env.arch.word_size, "little"
+        )
 
     # Create a relocation for each GOT entry
     for got_entry in got_list:
-        if got_entry.name == 'mp_fun_table':
-            dest = 'mp_fun_table'
-        elif got_entry.name.startswith('mp_fun_table+0x'):
-            dest = int(got_entry.name.split('+')[1], 16) // env.arch.word_size
-        elif got_entry.sec_name.startswith('.text'):
-            dest = '.text'
-        elif got_entry.sec_name.startswith('.rodata'):
-            dest = '.rodata'
-        elif got_entry.sec_name.startswith('.data.rel.ro'):
-            dest = '.data.rel.ro'
-        elif got_entry.sec_name.startswith('.bss'):
-            dest = '.bss'
+        if got_entry.name == "mp_fun_table":
+            dest = "mp_fun_table"
+        elif got_entry.name.startswith("mp_fun_table+0x"):
+            dest = int(got_entry.name.split("+")[1], 16) // env.arch.word_size
+        elif got_entry.sec_name.startswith(".text"):
+            dest = ".text"
+        elif got_entry.sec_name.startswith(".rodata"):
+            dest = ".rodata"
+        elif got_entry.sec_name.startswith(".data.rel.ro"):
+            dest = ".data.rel.ro"
+        elif got_entry.sec_name.startswith(".bss"):
+            dest = ".bss"
         else:
             assert 0, (got_entry.name, got_entry.sec_name)
-        env.mpy_relocs.append(('.text', env.got_section.addr + got_entry.offset, dest))
+        env.mpy_relocs.append((".text", env.got_section.addr + got_entry.offset, dest))
 
     # Print out the final GOT
-    log(LOG_LEVEL_2, 'GOT: {:08x}'.format(env.got_section.addr))
+    log(LOG_LEVEL_2, "GOT: {:08x}".format(env.got_section.addr))
     for g in got_list:
-        log(LOG_LEVEL_2, '  {:08x} {} -> {}+{:08x}'.format(g.offset, g.name, g.sec_name, g.link_addr))
+        log(
+            LOG_LEVEL_2,
+            "  {:08x} {} -> {}+{:08x}".format(g.offset, g.name, g.sec_name, g.link_addr),
+        )
+
 
 def populate_lit(env):
-    log(LOG_LEVEL_2, 'LIT: {:08x}'.format(env.lit_section.addr))
+    log(LOG_LEVEL_2, "LIT: {:08x}".format(env.lit_section.addr))
     for lit_entry in env.lit_entries.values():
         value = lit_entry.value
-        log(LOG_LEVEL_2, '  {:08x} = {:08x}'.format(lit_entry.offset, value))
+        log(LOG_LEVEL_2, "  {:08x} = {:08x}".format(lit_entry.offset, value))
         o = env.lit_section.addr + lit_entry.offset
-        env.full_text[o:o + env.arch.word_size] = value.to_bytes(env.arch.word_size, 'little')
+        env.full_text[o : o + env.arch.word_size] = value.to_bytes(env.arch.word_size, "little")
+
 
 def do_relocation_text(env, text_addr, r):
     # Extract relevant info about symbol that's being relocated
     s = r.sym
-    s_bind = s.entry['st_info']['bind']
-    s_shndx = s.entry['st_shndx']
-    s_type = s.entry['st_info']['type']
-    r_offset = r['r_offset'] + text_addr
-    r_info_type = r['r_info_type']
+    s_bind = s.entry["st_info"]["bind"]
+    s_shndx = s.entry["st_shndx"]
+    s_type = s.entry["st_info"]["type"]
+    r_offset = r["r_offset"] + text_addr
+    r_info_type = r["r_info_type"]
     try:
         # only for RELA sections
-        r_addend = r['r_addend']
+        r_addend = r["r_addend"]
     except KeyError:
         r_addend = 0
 
     # Default relocation type and name for logging
-    reloc_type = 'le32'
+    reloc_type = "le32"
     log_name = None
 
-    if (env.arch.name == 'EM_386' and r_info_type in (R_386_PC32, R_386_PLT32)
-        or env.arch.name == 'EM_X86_64' and r_info_type in (R_X86_64_PC32, R_X86_64_PLT32)
-        or env.arch.name == 'EM_ARM' and r_info_type in (R_ARM_REL32, R_ARM_THM_CALL, R_ARM_THM_JUMP24)
-        or s_bind == 'STB_LOCAL' and env.arch.name == 'EM_XTENSA' and r_info_type == R_XTENSA_32 # not GOT
-        ):
+    if (
+        env.arch.name == "EM_386"
+        and r_info_type in (R_386_PC32, R_386_PLT32)
+        or env.arch.name == "EM_X86_64"
+        and r_info_type in (R_X86_64_PC32, R_X86_64_PLT32)
+        or env.arch.name == "EM_ARM"
+        and r_info_type in (R_ARM_REL32, R_ARM_THM_CALL, R_ARM_THM_JUMP24)
+        or s_bind == "STB_LOCAL"
+        and env.arch.name == "EM_XTENSA"
+        and r_info_type == R_XTENSA_32  # not GOT
+    ):
         # Standard relocation to fixed location within text/rodata
-        if hasattr(s, 'resolved'):
+        if hasattr(s, "resolved"):
             s = s.resolved
 
         sec = s.section
 
-        if env.arch.separate_rodata and sec.name.startswith('.rodata'):
-            raise LinkError('fixed relocation to rodata with rodata referenced via GOT')
+        if env.arch.separate_rodata and sec.name.startswith(".rodata"):
+            raise LinkError("fixed relocation to rodata with rodata referenced via GOT")
 
-        if sec.name.startswith('.bss'):
-            raise LinkError('{}: fixed relocation to bss (bss variables can\'t be static)'.format(s.filename))
+        if sec.name.startswith(".bss"):
+            raise LinkError(
+                "{}: fixed relocation to bss (bss variables can't be static)".format(s.filename)
+            )
 
-        if sec.name.startswith('.external'):
-            raise LinkError('{}: fixed relocation to external symbol: {}'.format(s.filename, s.name))
+        if sec.name.startswith(".external"):
+            raise LinkError(
+                "{}: fixed relocation to external symbol: {}".format(s.filename, s.name)
+            )
 
-        addr = sec.addr + s['st_value']
+        addr = sec.addr + s["st_value"]
         reloc = addr - r_offset + r_addend
 
         if r_info_type in (R_ARM_THM_CALL, R_ARM_THM_JUMP24):
             # Both relocations have the same bit pattern to rewrite:
             #   R_ARM_THM_CALL: bl
             #   R_ARM_THM_JUMP24: b.w
-            reloc_type = 'thumb_b'
+            reloc_type = "thumb_b"
 
-    elif (env.arch.name == 'EM_386' and r_info_type == R_386_GOTPC
-        or env.arch.name == 'EM_ARM' and r_info_type == R_ARM_BASE_PREL
-        ):
+    elif (
+        env.arch.name == "EM_386"
+        and r_info_type == R_386_GOTPC
+        or env.arch.name == "EM_ARM"
+        and r_info_type == R_ARM_BASE_PREL
+    ):
         # Relocation to GOT address itself
-        assert s.name == '_GLOBAL_OFFSET_TABLE_'
+        assert s.name == "_GLOBAL_OFFSET_TABLE_"
         addr = env.got_section.addr
         reloc = addr - r_offset + r_addend
 
-    elif (env.arch.name == 'EM_386' and r_info_type in (R_386_GOT32, R_386_GOT32X)
-        or env.arch.name == 'EM_ARM' and r_info_type == R_ARM_GOT_BREL
-        ):
+    elif (
+        env.arch.name == "EM_386"
+        and r_info_type in (R_386_GOT32, R_386_GOT32X)
+        or env.arch.name == "EM_ARM"
+        and r_info_type == R_ARM_GOT_BREL
+    ):
         # Relcation pointing to GOT
         reloc = addr = env.got_entries[s.name].offset
 
-    elif env.arch.name == 'EM_X86_64' and r_info_type == R_X86_64_REX_GOTPCRELX:
+    elif env.arch.name == "EM_X86_64" and r_info_type == R_X86_64_REX_GOTPCRELX:
         # Relcation pointing to GOT
         got_entry = env.got_entries[s.name]
         addr = env.got_section.addr + got_entry.offset
         reloc = addr - r_offset + r_addend
 
-    elif env.arch.name == 'EM_386' and r_info_type == R_386_GOTOFF:
+    elif env.arch.name == "EM_386" and r_info_type == R_386_GOTOFF:
         # Relocation relative to GOT
-        addr = s.section.addr + s['st_value']
+        addr = s.section.addr + s["st_value"]
         reloc = addr - env.got_section.addr + r_addend
 
-    elif env.arch.name == 'EM_XTENSA' and r_info_type == R_XTENSA_SLOT0_OP:
+    elif env.arch.name == "EM_XTENSA" and r_info_type == R_XTENSA_SLOT0_OP:
         # Relocation pointing to GOT, xtensa specific
         sec = s.section
-        if sec.name.startswith('.text'):
+        if sec.name.startswith(".text"):
             # it looks like R_XTENSA_SLOT0_OP into .text is already correctly relocated
             return
-        assert sec.name.startswith('.literal'), sec.name
-        lit_idx = '{}+0x{:x}'.format(sec.filename, r_addend)
+        assert sec.name.startswith(".literal"), sec.name
+        lit_idx = "{}+0x{:x}".format(sec.filename, r_addend)
         lit_ptr = env.xt_literals[lit_idx]
         if isinstance(lit_ptr, str):
             addr = env.got_section.addr + env.got_entries[lit_ptr].offset
-            log_name = 'GOT {}'.format(lit_ptr)
+            log_name = "GOT {}".format(lit_ptr)
         else:
             addr = env.lit_section.addr + env.lit_entries[lit_ptr].offset
-            log_name = 'LIT'
+            log_name = "LIT"
         reloc = addr - r_offset
-        reloc_type = 'xtensa_l32r'
+        reloc_type = "xtensa_l32r"
 
-    elif env.arch.name == 'EM_XTENSA' and r_info_type == R_XTENSA_DIFF32:
-        if s.section.name.startswith('.text'):
+    elif env.arch.name == "EM_XTENSA" and r_info_type == R_XTENSA_DIFF32:
+        if s.section.name.startswith(".text"):
             # it looks like R_XTENSA_DIFF32 into .text is already correctly relocated
             return
         assert 0
@@ -499,196 +576,216 @@
         assert 0, r_info_type
 
     # Write relocation
-    if reloc_type == 'le32':
-        existing, = struct.unpack_from('<I', env.full_text, r_offset)
-        struct.pack_into('<I', env.full_text, r_offset, (existing + reloc) & 0xffffffff)
-    elif reloc_type == 'thumb_b':
-        b_h, b_l = struct.unpack_from('<HH', env.full_text, r_offset)
-        existing = (b_h & 0x7ff) << 12 | (b_l & 0x7ff) << 1
-        if existing >= 0x400000: # 2's complement
+    if reloc_type == "le32":
+        (existing,) = struct.unpack_from("<I", env.full_text, r_offset)
+        struct.pack_into("<I", env.full_text, r_offset, (existing + reloc) & 0xFFFFFFFF)
+    elif reloc_type == "thumb_b":
+        b_h, b_l = struct.unpack_from("<HH", env.full_text, r_offset)
+        existing = (b_h & 0x7FF) << 12 | (b_l & 0x7FF) << 1
+        if existing >= 0x400000:  # 2's complement
             existing -= 0x800000
         new = existing + reloc
-        b_h = (b_h & 0xf800) | (new >> 12) & 0x7ff
-        b_l = (b_l & 0xf800) | (new >> 1) & 0x7ff
-        struct.pack_into('<HH', env.full_text, r_offset, b_h, b_l)
-    elif reloc_type == 'xtensa_l32r':
+        b_h = (b_h & 0xF800) | (new >> 12) & 0x7FF
+        b_l = (b_l & 0xF800) | (new >> 1) & 0x7FF
+        struct.pack_into("<HH", env.full_text, r_offset, b_h, b_l)
+    elif reloc_type == "xtensa_l32r":
         l32r = unpack_u24le(env.full_text, r_offset)
-        assert l32r & 0xf == 1 # RI16 encoded l32r
+        assert l32r & 0xF == 1  # RI16 encoded l32r
         l32r_imm16 = l32r >> 8
-        l32r_imm16 = (l32r_imm16 + reloc >> 2) & 0xffff
-        l32r = l32r & 0xff | l32r_imm16 << 8
+        l32r_imm16 = (l32r_imm16 + reloc >> 2) & 0xFFFF
+        l32r = l32r & 0xFF | l32r_imm16 << 8
         pack_u24le(env.full_text, r_offset, l32r)
     else:
         assert 0, reloc_type
 
     # Log information about relocation
     if log_name is None:
-        if s_type == 'STT_SECTION':
+        if s_type == "STT_SECTION":
             log_name = s.section.name
         else:
             log_name = s.name
-    log(LOG_LEVEL_3, '  {:08x} {} -> {:08x}'.format(r_offset, log_name, addr))
+    log(LOG_LEVEL_3, "  {:08x} {} -> {:08x}".format(r_offset, log_name, addr))
+
 
 def do_relocation_data(env, text_addr, r):
     s = r.sym
-    s_type = s.entry['st_info']['type']
-    r_offset = r['r_offset'] + text_addr
-    r_info_type = r['r_info_type']
+    s_type = s.entry["st_info"]["type"]
+    r_offset = r["r_offset"] + text_addr
+    r_info_type = r["r_info_type"]
     try:
         # only for RELA sections
-        r_addend = r['r_addend']
+        r_addend = r["r_addend"]
     except KeyError:
         r_addend = 0
 
-    if (env.arch.name == 'EM_386' and r_info_type == R_386_32
-        or env.arch.name == 'EM_X86_64' and r_info_type == R_X86_64_64
-        or env.arch.name == 'EM_ARM' and r_info_type == R_ARM_ABS32
-        or env.arch.name == 'EM_XTENSA' and r_info_type == R_XTENSA_32):
+    if (
+        env.arch.name == "EM_386"
+        and r_info_type == R_386_32
+        or env.arch.name == "EM_X86_64"
+        and r_info_type == R_X86_64_64
+        or env.arch.name == "EM_ARM"
+        and r_info_type == R_ARM_ABS32
+        or env.arch.name == "EM_XTENSA"
+        and r_info_type == R_XTENSA_32
+    ):
         # Relocation in data.rel.ro to internal/external symbol
         if env.arch.word_size == 4:
-            struct_type = '<I'
+            struct_type = "<I"
         elif env.arch.word_size == 8:
-            struct_type = '<Q'
+            struct_type = "<Q"
         sec = s.section
         assert r_offset % env.arch.word_size == 0
-        addr = sec.addr + s['st_value'] + r_addend
-        if s_type == 'STT_SECTION':
+        addr = sec.addr + s["st_value"] + r_addend
+        if s_type == "STT_SECTION":
             log_name = sec.name
         else:
             log_name = s.name
-        log(LOG_LEVEL_3, '  {:08x} -> {} {:08x}'.format(r_offset, log_name, addr))
+        log(LOG_LEVEL_3, "  {:08x} -> {} {:08x}".format(r_offset, log_name, addr))
         if env.arch.separate_rodata:
             data = env.full_rodata
         else:
             data = env.full_text
-        existing, = struct.unpack_from(struct_type, data, r_offset)
-        if sec.name.startswith(('.text', '.rodata', '.data.rel.ro', '.bss')):
+        (existing,) = struct.unpack_from(struct_type, data, r_offset)
+        if sec.name.startswith((".text", ".rodata", ".data.rel.ro", ".bss")):
             struct.pack_into(struct_type, data, r_offset, existing + addr)
             kind = sec.name
-        elif sec.name == '.external.mp_fun_table':
+        elif sec.name == ".external.mp_fun_table":
             assert addr == 0
             kind = s.mp_fun_table_offset
         else:
             assert 0, sec.name
         if env.arch.separate_rodata:
-            base = '.rodata'
+            base = ".rodata"
         else:
-            base = '.text'
+            base = ".text"
         env.mpy_relocs.append((base, r_offset, kind))
 
     else:
         # Unknown/unsupported relocation
         assert 0, r_info_type
 
+
 def load_object_file(env, felf):
-    with open(felf, 'rb') as f:
+    with open(felf, "rb") as f:
         elf = elffile.ELFFile(f)
-        env.check_arch(elf['e_machine'])
+        env.check_arch(elf["e_machine"])
 
         # Get symbol table
-        symtab = list(elf.get_section_by_name('.symtab').iter_symbols())
+        symtab = list(elf.get_section_by_name(".symtab").iter_symbols())
 
         # Load needed sections from ELF file
-        sections_shndx = {} # maps elf shndx to Section object
+        sections_shndx = {}  # maps elf shndx to Section object
         for idx, s in enumerate(elf.iter_sections()):
-            if s.header.sh_type in ('SHT_PROGBITS', 'SHT_NOBITS'):
+            if s.header.sh_type in ("SHT_PROGBITS", "SHT_NOBITS"):
                 if s.data_size == 0:
                     # Ignore empty sections
                     pass
-                elif s.name.startswith(('.literal', '.text', '.rodata', '.data.rel.ro', '.bss')):
+                elif s.name.startswith((".literal", ".text", ".rodata", ".data.rel.ro", ".bss")):
                     sec = Section.from_elfsec(s, felf)
                     sections_shndx[idx] = sec
-                    if s.name.startswith('.literal'):
+                    if s.name.startswith(".literal"):
                         env.literal_sections.append(sec)
                     else:
                         env.sections.append(sec)
-                elif s.name.startswith('.data'):
-                    raise LinkError('{}: {} non-empty'.format(felf, s.name))
+                elif s.name.startswith(".data"):
+                    raise LinkError("{}: {} non-empty".format(felf, s.name))
                 else:
                     # Ignore section
                     pass
-            elif s.header.sh_type in ('SHT_REL', 'SHT_RELA'):
+            elif s.header.sh_type in ("SHT_REL", "SHT_RELA"):
                 shndx = s.header.sh_info
                 if shndx in sections_shndx:
                     sec = sections_shndx[shndx]
                     sec.reloc_name = s.name
                     sec.reloc = list(s.iter_relocations())
                     for r in sec.reloc:
-                        r.sym = symtab[r['r_info_sym']]
+                        r.sym = symtab[r["r_info_sym"]]
 
         # Link symbols to their sections, and update known and unresolved symbols
         for sym in symtab:
             sym.filename = felf
-            shndx = sym.entry['st_shndx']
+            shndx = sym.entry["st_shndx"]
             if shndx in sections_shndx:
                 # Symbol with associated section
                 sym.section = sections_shndx[shndx]
-                if sym['st_info']['bind'] == 'STB_GLOBAL':
+                if sym["st_info"]["bind"] == "STB_GLOBAL":
                     # Defined global symbol
-                    if sym.name in env.known_syms and not sym.name.startswith('__x86.get_pc_thunk.'):
-                        raise LinkError('duplicate symbol: {}'.format(sym.name))
+                    if sym.name in env.known_syms and not sym.name.startswith(
+                        "__x86.get_pc_thunk."
+                    ):
+                        raise LinkError("duplicate symbol: {}".format(sym.name))
                     env.known_syms[sym.name] = sym
-            elif sym.entry['st_shndx'] == 'SHN_UNDEF' and sym['st_info']['bind'] == 'STB_GLOBAL':
+            elif sym.entry["st_shndx"] == "SHN_UNDEF" and sym["st_info"]["bind"] == "STB_GLOBAL":
                 # Undefined global symbol, needs resolving
                 env.unresolved_syms.append(sym)
 
+
 def link_objects(env, native_qstr_vals_len, native_qstr_objs_len):
     # Build GOT information
-    if env.arch.name == 'EM_XTENSA':
+    if env.arch.name == "EM_XTENSA":
         build_got_xtensa(env)
     else:
         build_got_generic(env)
 
     # Creat GOT section
     got_size = len(env.got_entries) * env.arch.word_size
-    env.got_section = Section('GOT', bytearray(got_size), env.arch.word_size)
-    if env.arch.name == 'EM_XTENSA':
+    env.got_section = Section("GOT", bytearray(got_size), env.arch.word_size)
+    if env.arch.name == "EM_XTENSA":
         env.sections.insert(0, env.got_section)
     else:
         env.sections.append(env.got_section)
 
     # Create optional literal section
-    if env.arch.name == 'EM_XTENSA':
+    if env.arch.name == "EM_XTENSA":
         lit_size = len(env.lit_entries) * env.arch.word_size
-        env.lit_section = Section('LIT', bytearray(lit_size), env.arch.word_size)
+        env.lit_section = Section("LIT", bytearray(lit_size), env.arch.word_size)
         env.sections.insert(1, env.lit_section)
 
     # Create section to contain mp_native_qstr_val_table
-    env.qstr_val_section = Section('.text.QSTR_VAL', bytearray(native_qstr_vals_len * env.arch.qstr_entry_size), env.arch.qstr_entry_size)
+    env.qstr_val_section = Section(
+        ".text.QSTR_VAL",
+        bytearray(native_qstr_vals_len * env.arch.qstr_entry_size),
+        env.arch.qstr_entry_size,
+    )
     env.sections.append(env.qstr_val_section)
 
     # Create section to contain mp_native_qstr_obj_table
-    env.qstr_obj_section = Section('.text.QSTR_OBJ', bytearray(native_qstr_objs_len * env.arch.word_size), env.arch.word_size)
+    env.qstr_obj_section = Section(
+        ".text.QSTR_OBJ", bytearray(native_qstr_objs_len * env.arch.word_size), env.arch.word_size
+    )
     env.sections.append(env.qstr_obj_section)
 
     # Resolve unknown symbols
-    mp_fun_table_sec = Section('.external.mp_fun_table', b'', 0)
-    fun_table = {key: 67 + idx
-        for idx, key in enumerate([
-            'mp_type_type',
-            'mp_type_str',
-            'mp_type_list',
-            'mp_type_dict',
-            'mp_type_fun_builtin_0',
-            'mp_type_fun_builtin_1',
-            'mp_type_fun_builtin_2',
-            'mp_type_fun_builtin_3',
-            'mp_type_fun_builtin_var',
-            'mp_stream_read_obj',
-            'mp_stream_readinto_obj',
-            'mp_stream_unbuffered_readline_obj',
-            'mp_stream_write_obj',
-        ])
+    mp_fun_table_sec = Section(".external.mp_fun_table", b"", 0)
+    fun_table = {
+        key: 67 + idx
+        for idx, key in enumerate(
+            [
+                "mp_type_type",
+                "mp_type_str",
+                "mp_type_list",
+                "mp_type_dict",
+                "mp_type_fun_builtin_0",
+                "mp_type_fun_builtin_1",
+                "mp_type_fun_builtin_2",
+                "mp_type_fun_builtin_3",
+                "mp_type_fun_builtin_var",
+                "mp_stream_read_obj",
+                "mp_stream_readinto_obj",
+                "mp_stream_unbuffered_readline_obj",
+                "mp_stream_write_obj",
+            ]
+        )
     }
     for sym in env.unresolved_syms:
-        assert sym['st_value'] == 0
-        if sym.name == '_GLOBAL_OFFSET_TABLE_':
+        assert sym["st_value"] == 0
+        if sym.name == "_GLOBAL_OFFSET_TABLE_":
             pass
-        elif sym.name == 'mp_fun_table':
-            sym.section = Section('.external', b'', 0)
-        elif sym.name == 'mp_native_qstr_val_table':
+        elif sym.name == "mp_fun_table":
+            sym.section = Section(".external", b"", 0)
+        elif sym.name == "mp_native_qstr_val_table":
             sym.section = env.qstr_val_section
-        elif sym.name == 'mp_native_qstr_obj_table':
+        elif sym.name == "mp_native_qstr_obj_table":
             sym.section = env.qstr_obj_section
         elif sym.name in env.known_syms:
             sym.resolved = env.known_syms[sym.name]
@@ -697,48 +794,53 @@
                 sym.section = mp_fun_table_sec
                 sym.mp_fun_table_offset = fun_table[sym.name]
             else:
-                raise LinkError('{}: undefined symbol: {}'.format(sym.filename, sym.name))
+                raise LinkError("{}: undefined symbol: {}".format(sym.filename, sym.name))
 
     # Align sections, assign their addresses, and create full_text
-    env.full_text = bytearray(env.arch.asm_jump(8)) # dummy, to be filled in later
+    env.full_text = bytearray(env.arch.asm_jump(8))  # dummy, to be filled in later
     env.full_rodata = bytearray(0)
     env.full_bss = bytearray(0)
     for sec in env.sections:
-        if env.arch.separate_rodata and sec.name.startswith(('.rodata', '.data.rel.ro')):
+        if env.arch.separate_rodata and sec.name.startswith((".rodata", ".data.rel.ro")):
             data = env.full_rodata
-        elif sec.name.startswith('.bss'):
+        elif sec.name.startswith(".bss"):
             data = env.full_bss
         else:
             data = env.full_text
         sec.addr = align_to(len(data), sec.alignment)
-        data.extend(b'\x00' * (sec.addr - len(data)))
+        data.extend(b"\x00" * (sec.addr - len(data)))
         data.extend(sec.data)
 
     env.print_sections()
 
     populate_got(env)
-    if env.arch.name == 'EM_XTENSA':
+    if env.arch.name == "EM_XTENSA":
         populate_lit(env)
 
     # Fill in relocations
     for sec in env.sections:
         if not sec.reloc:
             continue
-        log(LOG_LEVEL_3, '{}: {} relocations via {}:'.format(sec.filename, sec.name, sec.reloc_name))
+        log(
+            LOG_LEVEL_3,
+            "{}: {} relocations via {}:".format(sec.filename, sec.name, sec.reloc_name),
+        )
         for r in sec.reloc:
-            if sec.name.startswith(('.text', '.rodata')):
+            if sec.name.startswith((".text", ".rodata")):
                 do_relocation_text(env, sec.addr, r)
-            elif sec.name.startswith('.data.rel.ro'):
+            elif sec.name.startswith(".data.rel.ro"):
                 do_relocation_data(env, sec.addr, r)
             else:
                 assert 0, sec.name
 
+
 ################################################################################
 # .mpy output
 
+
 class MPYOutput:
     def open(self, fname):
-        self.f = open(fname, 'wb')
+        self.f = open(fname, "wb")
         self.prev_base = -1
         self.prev_offset = -1
 
@@ -750,10 +852,10 @@
 
     def write_uint(self, val):
         b = bytearray()
-        b.insert(0, val & 0x7f)
+        b.insert(0, val & 0x7F)
         val >>= 7
         while val:
-            b.insert(0, 0x80 | (val & 0x7f))
+            b.insert(0, 0x80 | (val & 0x7F))
             val >>= 7
         self.write_bytes(b)
 
@@ -761,7 +863,7 @@
         if s in qstrutil.static_qstr_list:
             self.write_bytes(bytes([0, qstrutil.static_qstr_list.index(s) + 1]))
         else:
-            s = bytes(s, 'ascii')
+            s = bytes(s, "ascii")
             self.write_uint(len(s) << 1)
             self.write_bytes(s)
 
@@ -774,42 +876,41 @@
             assert 6 <= dest <= 127
             assert n == 1
         dest = dest << 1 | need_offset
-        assert 0 <= dest <= 0xfe, dest
+        assert 0 <= dest <= 0xFE, dest
         self.write_bytes(bytes([dest]))
         if need_offset:
-            if base == '.text':
+            if base == ".text":
                 base = 0
-            elif base == '.rodata':
+            elif base == ".rodata":
                 base = 1
             self.write_uint(offset << 1 | base)
         if n > 1:
             self.write_uint(n)
 
+
 def build_mpy(env, entry_offset, fmpy, native_qstr_vals, native_qstr_objs):
     # Write jump instruction to start of text
     jump = env.arch.asm_jump(entry_offset)
-    env.full_text[:len(jump)] = jump
+    env.full_text[: len(jump)] = jump
 
-    log(LOG_LEVEL_1, 'arch:         {}'.format(env.arch.name))
-    log(LOG_LEVEL_1, 'text size:    {}'.format(len(env.full_text)))
+    log(LOG_LEVEL_1, "arch:         {}".format(env.arch.name))
+    log(LOG_LEVEL_1, "text size:    {}".format(len(env.full_text)))
     if len(env.full_rodata):
-        log(LOG_LEVEL_1, 'rodata size:  {}'.format(len(env.full_rodata)))
-    log(LOG_LEVEL_1, 'bss size:     {}'.format(len(env.full_bss)))
-    log(LOG_LEVEL_1, 'GOT entries:  {}'.format(len(env.got_entries)))
+        log(LOG_LEVEL_1, "rodata size:  {}".format(len(env.full_rodata)))
+    log(LOG_LEVEL_1, "bss size:     {}".format(len(env.full_bss)))
+    log(LOG_LEVEL_1, "GOT entries:  {}".format(len(env.got_entries)))
 
-    #xxd(env.full_text)
+    # xxd(env.full_text)
 
     out = MPYOutput()
     out.open(fmpy)
 
     # MPY: header
-    out.write_bytes(bytearray([
-        ord('M'),
-        MPY_VERSION,
-        env.arch.mpy_feature,
-        MP_SMALL_INT_BITS,
-        QSTR_WINDOW_SIZE,
-    ]))
+    out.write_bytes(
+        bytearray(
+            [ord("M"), MPY_VERSION, env.arch.mpy_feature, MP_SMALL_INT_BITS, QSTR_WINDOW_SIZE,]
+        )
+    )
 
     # MPY: kind/len
     out.write_uint(len(env.full_text) << 2 | (MP_CODE_NATIVE_VIPER - MP_CODE_BYTECODE))
@@ -854,16 +955,16 @@
     # MPY: relocation information
     prev_kind = None
     for base, addr, kind in env.mpy_relocs:
-        if isinstance(kind, str) and kind.startswith('.text'):
+        if isinstance(kind, str) and kind.startswith(".text"):
             kind = 0
-        elif kind in ('.rodata', '.data.rel.ro'):
+        elif kind in (".rodata", ".data.rel.ro"):
             if env.arch.separate_rodata:
                 kind = rodata_const_table_idx
             else:
                 kind = 0
-        elif isinstance(kind, str) and kind.startswith('.bss'):
+        elif isinstance(kind, str) and kind.startswith(".bss"):
             kind = bss_const_table_idx
-        elif kind == 'mp_fun_table':
+        elif kind == "mp_fun_table":
             kind = 6
         else:
             kind = 7 + kind
@@ -883,73 +984,88 @@
         out.write_reloc(prev_base, prev_offset - prev_n + 1, prev_kind, prev_n)
 
     # MPY: sentinel for end of relocations
-    out.write_bytes(b'\xff')
+    out.write_bytes(b"\xff")
 
     out.close()
 
+
 ################################################################################
 # main
 
+
 def do_preprocess(args):
     if args.output is None:
-        assert args.files[0].endswith('.c')
-        args.output = args.files[0][:-1] + 'config.h'
+        assert args.files[0].endswith(".c")
+        args.output = args.files[0][:-1] + "config.h"
     static_qstrs, qstr_vals, qstr_objs = extract_qstrs(args.files)
-    with open(args.output, 'w') as f:
-        print('#include <stdint.h>\n'
-            'typedef uintptr_t mp_uint_t;\n'
-            'typedef intptr_t mp_int_t;\n'
-            'typedef uintptr_t mp_off_t;', file=f)
+    with open(args.output, "w") as f:
+        print(
+            "#include <stdint.h>\n"
+            "typedef uintptr_t mp_uint_t;\n"
+            "typedef intptr_t mp_int_t;\n"
+            "typedef uintptr_t mp_off_t;",
+            file=f,
+        )
         for i, q in enumerate(static_qstrs):
-            print('#define %s (%u)' % (q, i + 1), file=f)
+            print("#define %s (%u)" % (q, i + 1), file=f)
         for i, q in enumerate(sorted(qstr_vals)):
-            print('#define %s (mp_native_qstr_val_table[%d])' % (q, i), file=f)
+            print("#define %s (mp_native_qstr_val_table[%d])" % (q, i), file=f)
         for i, q in enumerate(sorted(qstr_objs)):
-            print('#define MP_OBJ_NEW_QSTR_%s ((mp_obj_t)mp_native_qstr_obj_table[%d])' % (q, i), file=f)
-        if args.arch == 'xtensawin':
-            qstr_type = 'uint32_t' # esp32 can only read 32-bit values from IRAM
+            print(
+                "#define MP_OBJ_NEW_QSTR_%s ((mp_obj_t)mp_native_qstr_obj_table[%d])" % (q, i),
+                file=f,
+            )
+        if args.arch == "xtensawin":
+            qstr_type = "uint32_t"  # esp32 can only read 32-bit values from IRAM
         else:
-            qstr_type = 'uint16_t'
-        print('extern const {} mp_native_qstr_val_table[];'.format(qstr_type), file=f)
-        print('extern const mp_uint_t mp_native_qstr_obj_table[];', file=f)
+            qstr_type = "uint16_t"
+        print("extern const {} mp_native_qstr_val_table[];".format(qstr_type), file=f)
+        print("extern const mp_uint_t mp_native_qstr_obj_table[];", file=f)
+
 
 def do_link(args):
     if args.output is None:
-        assert args.files[0].endswith('.o')
-        args.output = args.files[0][:-1] + 'mpy'
+        assert args.files[0].endswith(".o")
+        args.output = args.files[0][:-1] + "mpy"
     native_qstr_vals = []
     native_qstr_objs = []
     if args.qstrs is not None:
         with open(args.qstrs) as f:
             for l in f:
-                m = re.match(r'#define MP_QSTR_([A-Za-z0-9_]*) \(mp_native_', l)
+                m = re.match(r"#define MP_QSTR_([A-Za-z0-9_]*) \(mp_native_", l)
                 if m:
                     native_qstr_vals.append(m.group(1))
                 else:
-                    m = re.match(r'#define MP_OBJ_NEW_QSTR_MP_QSTR_([A-Za-z0-9_]*)', l)
+                    m = re.match(r"#define MP_OBJ_NEW_QSTR_MP_QSTR_([A-Za-z0-9_]*)", l)
                     if m:
                         native_qstr_objs.append(m.group(1))
-    log(LOG_LEVEL_2, 'qstr vals: ' + ', '.join(native_qstr_vals))
-    log(LOG_LEVEL_2, 'qstr objs: ' + ', '.join(native_qstr_objs))
+    log(LOG_LEVEL_2, "qstr vals: " + ", ".join(native_qstr_vals))
+    log(LOG_LEVEL_2, "qstr objs: " + ", ".join(native_qstr_objs))
     env = LinkEnv(args.arch)
     try:
         for file in args.files:
             load_object_file(env, file)
         link_objects(env, len(native_qstr_vals), len(native_qstr_objs))
-        build_mpy(env, env.find_addr('mpy_init'), args.output, native_qstr_vals, native_qstr_objs)
+        build_mpy(env, env.find_addr("mpy_init"), args.output, native_qstr_vals, native_qstr_objs)
     except LinkError as er:
-        print('LinkError:', er.args[0])
+        print("LinkError:", er.args[0])
         sys.exit(1)
 
+
 def main():
     import argparse
-    cmd_parser = argparse.ArgumentParser(description='Run scripts on the pyboard.')
-    cmd_parser.add_argument('--verbose', '-v', action='count', default=1, help='increase verbosity')
-    cmd_parser.add_argument('--arch', default='x64', help='architecture')
-    cmd_parser.add_argument('--preprocess', action='store_true', help='preprocess source files')
-    cmd_parser.add_argument('--qstrs', default=None, help='file defining additional qstrs')
-    cmd_parser.add_argument('--output', '-o', default=None, help='output .mpy file (default to input with .o->.mpy)')
-    cmd_parser.add_argument('files', nargs='+', help='input files')
+
+    cmd_parser = argparse.ArgumentParser(description="Run scripts on the pyboard.")
+    cmd_parser.add_argument(
+        "--verbose", "-v", action="count", default=1, help="increase verbosity"
+    )
+    cmd_parser.add_argument("--arch", default="x64", help="architecture")
+    cmd_parser.add_argument("--preprocess", action="store_true", help="preprocess source files")
+    cmd_parser.add_argument("--qstrs", default=None, help="file defining additional qstrs")
+    cmd_parser.add_argument(
+        "--output", "-o", default=None, help="output .mpy file (default to input with .o->.mpy)"
+    )
+    cmd_parser.add_argument("files", nargs="+", help="input files")
     args = cmd_parser.parse_args()
 
     global log_level
@@ -960,5 +1076,6 @@
     else:
         do_link(args)
 
-if __name__ == '__main__':
+
+if __name__ == "__main__":
     main()
diff --git a/tools/pyboard.py b/tools/pyboard.py
index a0b4ac3..de8b488 100755
--- a/tools/pyboard.py
+++ b/tools/pyboard.py
@@ -77,35 +77,42 @@
     # Python2 doesn't have buffer attr
     stdout = sys.stdout
 
+
 def stdout_write_bytes(b):
     b = b.replace(b"\x04", b"")
     stdout.write(b)
     stdout.flush()
 
+
 class PyboardError(Exception):
     pass
 
+
 class TelnetToSerial:
     def __init__(self, ip, user, password, read_timeout=None):
         self.tn = None
         import telnetlib
+
         self.tn = telnetlib.Telnet(ip, timeout=15)
         self.read_timeout = read_timeout
-        if b'Login as:' in self.tn.read_until(b'Login as:', timeout=read_timeout):
-            self.tn.write(bytes(user, 'ascii') + b"\r\n")
+        if b"Login as:" in self.tn.read_until(b"Login as:", timeout=read_timeout):
+            self.tn.write(bytes(user, "ascii") + b"\r\n")
 
-            if b'Password:' in self.tn.read_until(b'Password:', timeout=read_timeout):
+            if b"Password:" in self.tn.read_until(b"Password:", timeout=read_timeout):
                 # needed because of internal implementation details of the telnet server
                 time.sleep(0.2)
-                self.tn.write(bytes(password, 'ascii') + b"\r\n")
+                self.tn.write(bytes(password, "ascii") + b"\r\n")
 
-                if b'for more information.' in self.tn.read_until(b'Type "help()" for more information.', timeout=read_timeout):
+                if b"for more information." in self.tn.read_until(
+                    b'Type "help()" for more information.', timeout=read_timeout
+                ):
                     # login successful
                     from collections import deque
+
                     self.fifo = deque()
                     return
 
-        raise PyboardError('Failed to establish a telnet connection with the board')
+        raise PyboardError("Failed to establish a telnet connection with the board")
 
     def __del__(self):
         self.close()
@@ -127,7 +134,7 @@
                     break
                 timeout_count += 1
 
-        data = b''
+        data = b""
         while len(data) < size and len(self.fifo) > 0:
             data += bytes([self.fifo.popleft()])
         return data
@@ -151,24 +158,33 @@
 
     def __init__(self, cmd):
         import subprocess
-        self.subp = subprocess.Popen(cmd, bufsize=0, shell=True, preexec_fn=os.setsid,
-            stdin=subprocess.PIPE, stdout=subprocess.PIPE)
+
+        self.subp = subprocess.Popen(
+            cmd,
+            bufsize=0,
+            shell=True,
+            preexec_fn=os.setsid,
+            stdin=subprocess.PIPE,
+            stdout=subprocess.PIPE,
+        )
 
         # Initially was implemented with selectors, but that adds Python3
         # dependency. However, there can be race conditions communicating
         # with a particular child process (like QEMU), and selectors may
         # still work better in that case, so left inplace for now.
         #
-        #import selectors
-        #self.sel = selectors.DefaultSelector()
-        #self.sel.register(self.subp.stdout, selectors.EVENT_READ)
+        # import selectors
+        # self.sel = selectors.DefaultSelector()
+        # self.sel.register(self.subp.stdout, selectors.EVENT_READ)
 
         import select
+
         self.poll = select.poll()
         self.poll.register(self.subp.stdout.fileno())
 
     def close(self):
         import signal
+
         os.killpg(os.getpgid(self.subp.pid), signal.SIGTERM)
 
     def read(self, size=1):
@@ -182,7 +198,7 @@
         return len(data)
 
     def inWaiting(self):
-        #res = self.sel.select(0)
+        # res = self.sel.select(0)
         res = self.poll.poll(0)
         if res:
             return 1
@@ -198,8 +214,16 @@
         import subprocess
         import re
         import serial
-        self.subp = subprocess.Popen(cmd.split(), bufsize=0, shell=False, preexec_fn=os.setsid,
-            stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+
+        self.subp = subprocess.Popen(
+            cmd.split(),
+            bufsize=0,
+            shell=False,
+            preexec_fn=os.setsid,
+            stdin=subprocess.PIPE,
+            stdout=subprocess.PIPE,
+            stderr=subprocess.PIPE,
+        )
         pty_line = self.subp.stderr.readline().decode("utf-8")
         m = re.search(r"/dev/pts/[0-9]+", pty_line)
         if not m:
@@ -213,6 +237,7 @@
 
     def close(self):
         import signal
+
         os.killpg(os.getpgid(self.subp.pid), signal.SIGTERM)
 
     def read(self, size=1):
@@ -226,36 +251,37 @@
 
 
 class Pyboard:
-    def __init__(self, device, baudrate=115200, user='micro', password='python', wait=0):
+    def __init__(self, device, baudrate=115200, user="micro", password="python", wait=0):
         if device.startswith("exec:"):
-            self.serial = ProcessToSerial(device[len("exec:"):])
+            self.serial = ProcessToSerial(device[len("exec:") :])
         elif device.startswith("execpty:"):
-            self.serial = ProcessPtyToTerminal(device[len("qemupty:"):])
-        elif device and device[0].isdigit() and device[-1].isdigit() and device.count('.') == 3:
+            self.serial = ProcessPtyToTerminal(device[len("qemupty:") :])
+        elif device and device[0].isdigit() and device[-1].isdigit() and device.count(".") == 3:
             # device looks like an IP address
             self.serial = TelnetToSerial(device, user, password, read_timeout=10)
         else:
             import serial
+
             delayed = False
             for attempt in range(wait + 1):
                 try:
                     self.serial = serial.Serial(device, baudrate=baudrate, interCharTimeout=1)
                     break
-                except (OSError, IOError): # Py2 and Py3 have different errors
+                except (OSError, IOError):  # Py2 and Py3 have different errors
                     if wait == 0:
                         continue
                     if attempt == 0:
-                        sys.stdout.write('Waiting {} seconds for pyboard '.format(wait))
+                        sys.stdout.write("Waiting {} seconds for pyboard ".format(wait))
                         delayed = True
                 time.sleep(1)
-                sys.stdout.write('.')
+                sys.stdout.write(".")
                 sys.stdout.flush()
             else:
                 if delayed:
-                    print('')
-                raise PyboardError('failed to access ' + device)
+                    print("")
+                raise PyboardError("failed to access " + device)
             if delayed:
-                print('')
+                print("")
 
     def close(self):
         self.serial.close()
@@ -287,7 +313,7 @@
         return data
 
     def enter_raw_repl(self):
-        self.serial.write(b'\r\x03\x03') # ctrl-C twice: interrupt any running program
+        self.serial.write(b"\r\x03\x03")  # ctrl-C twice: interrupt any running program
 
         # flush input (without relying on serial.flushInput())
         n = self.serial.inWaiting()
@@ -295,38 +321,38 @@
             self.serial.read(n)
             n = self.serial.inWaiting()
 
-        self.serial.write(b'\r\x01') # ctrl-A: enter raw REPL
-        data = self.read_until(1, b'raw REPL; CTRL-B to exit\r\n>')
-        if not data.endswith(b'raw REPL; CTRL-B to exit\r\n>'):
+        self.serial.write(b"\r\x01")  # ctrl-A: enter raw REPL
+        data = self.read_until(1, b"raw REPL; CTRL-B to exit\r\n>")
+        if not data.endswith(b"raw REPL; CTRL-B to exit\r\n>"):
             print(data)
-            raise PyboardError('could not enter raw repl')
+            raise PyboardError("could not enter raw repl")
 
-        self.serial.write(b'\x04') # ctrl-D: soft reset
-        data = self.read_until(1, b'soft reboot\r\n')
-        if not data.endswith(b'soft reboot\r\n'):
+        self.serial.write(b"\x04")  # ctrl-D: soft reset
+        data = self.read_until(1, b"soft reboot\r\n")
+        if not data.endswith(b"soft reboot\r\n"):
             print(data)
-            raise PyboardError('could not enter raw repl')
+            raise PyboardError("could not enter raw repl")
         # By splitting this into 2 reads, it allows boot.py to print stuff,
         # which will show up after the soft reboot and before the raw REPL.
-        data = self.read_until(1, b'raw REPL; CTRL-B to exit\r\n')
-        if not data.endswith(b'raw REPL; CTRL-B to exit\r\n'):
+        data = self.read_until(1, b"raw REPL; CTRL-B to exit\r\n")
+        if not data.endswith(b"raw REPL; CTRL-B to exit\r\n"):
             print(data)
-            raise PyboardError('could not enter raw repl')
+            raise PyboardError("could not enter raw repl")
 
     def exit_raw_repl(self):
-        self.serial.write(b'\r\x02') # ctrl-B: enter friendly REPL
+        self.serial.write(b"\r\x02")  # ctrl-B: enter friendly REPL
 
     def follow(self, timeout, data_consumer=None):
         # wait for normal output
-        data = self.read_until(1, b'\x04', timeout=timeout, data_consumer=data_consumer)
-        if not data.endswith(b'\x04'):
-            raise PyboardError('timeout waiting for first EOF reception')
+        data = self.read_until(1, b"\x04", timeout=timeout, data_consumer=data_consumer)
+        if not data.endswith(b"\x04"):
+            raise PyboardError("timeout waiting for first EOF reception")
         data = data[:-1]
 
         # wait for error output
-        data_err = self.read_until(1, b'\x04', timeout=timeout)
-        if not data_err.endswith(b'\x04'):
-            raise PyboardError('timeout waiting for second EOF reception')
+        data_err = self.read_until(1, b"\x04", timeout=timeout)
+        if not data_err.endswith(b"\x04"):
+            raise PyboardError("timeout waiting for second EOF reception")
         data_err = data_err[:-1]
 
         # return normal and error output
@@ -336,67 +362,71 @@
         if isinstance(command, bytes):
             command_bytes = command
         else:
-            command_bytes = bytes(command, encoding='utf8')
+            command_bytes = bytes(command, encoding="utf8")
 
         # check we have a prompt
-        data = self.read_until(1, b'>')
-        if not data.endswith(b'>'):
-            raise PyboardError('could not enter raw repl')
+        data = self.read_until(1, b">")
+        if not data.endswith(b">"):
+            raise PyboardError("could not enter raw repl")
 
         # write command
         for i in range(0, len(command_bytes), 256):
-            self.serial.write(command_bytes[i:min(i + 256, len(command_bytes))])
+            self.serial.write(command_bytes[i : min(i + 256, len(command_bytes))])
             time.sleep(0.01)
-        self.serial.write(b'\x04')
+        self.serial.write(b"\x04")
 
         # check if we could exec command
         data = self.serial.read(2)
-        if data != b'OK':
-            raise PyboardError('could not exec command (response: %r)' % data)
+        if data != b"OK":
+            raise PyboardError("could not exec command (response: %r)" % data)
 
     def exec_raw(self, command, timeout=10, data_consumer=None):
-        self.exec_raw_no_follow(command);
+        self.exec_raw_no_follow(command)
         return self.follow(timeout, data_consumer)
 
     def eval(self, expression):
-        ret = self.exec_('print({})'.format(expression))
+        ret = self.exec_("print({})".format(expression))
         ret = ret.strip()
         return ret
 
     def exec_(self, command, data_consumer=None):
         ret, ret_err = self.exec_raw(command, data_consumer=data_consumer)
         if ret_err:
-            raise PyboardError('exception', ret, ret_err)
+            raise PyboardError("exception", ret, ret_err)
         return ret
 
     def execfile(self, filename):
-        with open(filename, 'rb') as f:
+        with open(filename, "rb") as f:
             pyfile = f.read()
         return self.exec_(pyfile)
 
     def get_time(self):
-        t = str(self.eval('pyb.RTC().datetime()'), encoding='utf8')[1:-1].split(', ')
+        t = str(self.eval("pyb.RTC().datetime()"), encoding="utf8")[1:-1].split(", ")
         return int(t[4]) * 3600 + int(t[5]) * 60 + int(t[6])
 
     def fs_ls(self, src):
-        cmd = "import uos\nfor f in uos.ilistdir(%s):\n" \
-            " print('{:12} {}{}'.format(f[3]if len(f)>3 else 0,f[0],'/'if f[1]&0x4000 else ''))" % \
-            (("'%s'" % src) if src else '')
+        cmd = (
+            "import uos\nfor f in uos.ilistdir(%s):\n"
+            " print('{:12} {}{}'.format(f[3]if len(f)>3 else 0,f[0],'/'if f[1]&0x4000 else ''))"
+            % (("'%s'" % src) if src else "")
+        )
         self.exec_(cmd, data_consumer=stdout_write_bytes)
 
     def fs_cat(self, src, chunk_size=256):
-        cmd = "with open('%s') as f:\n while 1:\n" \
+        cmd = (
+            "with open('%s') as f:\n while 1:\n"
             "  b=f.read(%u)\n  if not b:break\n  print(b,end='')" % (src, chunk_size)
+        )
         self.exec_(cmd, data_consumer=stdout_write_bytes)
 
     def fs_get(self, src, dest, chunk_size=256):
         self.exec_("f=open('%s','rb')\nr=f.read" % src)
-        with open(dest, 'wb') as f:
+        with open(dest, "wb") as f:
             while True:
                 data = bytearray()
-                self.exec_("print(r(%u))" % chunk_size, data_consumer=lambda d:data.extend(d))
-                assert data.endswith(b'\r\n\x04')
-                data = eval(str(data[:-3], 'ascii'))
+                self.exec_("print(r(%u))" % chunk_size, data_consumer=lambda d: data.extend(d))
+                assert data.endswith(b"\r\n\x04")
+                data = eval(str(data[:-3], "ascii"))
                 if not data:
                     break
                 f.write(data)
@@ -404,15 +434,15 @@
 
     def fs_put(self, src, dest, chunk_size=256):
         self.exec_("f=open('%s','wb')\nw=f.write" % dest)
-        with open(src, 'rb') as f:
+        with open(src, "rb") as f:
             while True:
                 data = f.read(chunk_size)
                 if not data:
                     break
                 if sys.version_info < (3,):
-                    self.exec_('w(b' + repr(data) + ')')
+                    self.exec_("w(b" + repr(data) + ")")
                 else:
-                    self.exec_('w(' + repr(data) + ')')
+                    self.exec_("w(" + repr(data) + ")")
         self.exec_("f.close()")
 
     def fs_mkdir(self, dir):
@@ -424,11 +454,13 @@
     def fs_rm(self, src):
         self.exec_("import uos\nuos.remove('%s')" % src)
 
+
 # in Python2 exec is a keyword so one must use "exec_"
 # but for Python3 we want to provide the nicer version "exec"
 setattr(Pyboard, "exec", Pyboard.exec_)
 
-def execfile(filename, device='/dev/ttyACM0', baudrate=115200, user='micro', password='python'):
+
+def execfile(filename, device="/dev/ttyACM0", baudrate=115200, user="micro", password="python"):
     pyb = Pyboard(device, baudrate, user, password)
     pyb.enter_raw_repl()
     output = pyb.execfile(filename)
@@ -436,54 +468,62 @@
     pyb.exit_raw_repl()
     pyb.close()
 
+
 def filesystem_command(pyb, args):
     def fname_remote(src):
-        if src.startswith(':'):
+        if src.startswith(":"):
             src = src[1:]
         return src
+
     def fname_cp_dest(src, dest):
-        src = src.rsplit('/', 1)[-1]
-        if dest is None or dest == '':
+        src = src.rsplit("/", 1)[-1]
+        if dest is None or dest == "":
             dest = src
-        elif dest == '.':
-            dest = './' + src
-        elif dest.endswith('/'):
+        elif dest == ".":
+            dest = "./" + src
+        elif dest.endswith("/"):
             dest += src
         return dest
 
     cmd = args[0]
     args = args[1:]
     try:
-        if cmd == 'cp':
+        if cmd == "cp":
             srcs = args[:-1]
             dest = args[-1]
-            if srcs[0].startswith('./') or dest.startswith(':'):
+            if srcs[0].startswith("./") or dest.startswith(":"):
                 op = pyb.fs_put
-                fmt = 'cp %s :%s'
+                fmt = "cp %s :%s"
                 dest = fname_remote(dest)
             else:
                 op = pyb.fs_get
-                fmt = 'cp :%s %s'
+                fmt = "cp :%s %s"
             for src in srcs:
                 src = fname_remote(src)
                 dest2 = fname_cp_dest(src, dest)
                 print(fmt % (src, dest2))
                 op(src, dest2)
         else:
-            op = {'ls': pyb.fs_ls, 'cat': pyb.fs_cat, 'mkdir': pyb.fs_mkdir,
-                'rmdir': pyb.fs_rmdir, 'rm': pyb.fs_rm}[cmd]
-            if cmd == 'ls' and not args:
-                args = ['']
+            op = {
+                "ls": pyb.fs_ls,
+                "cat": pyb.fs_cat,
+                "mkdir": pyb.fs_mkdir,
+                "rmdir": pyb.fs_rmdir,
+                "rm": pyb.fs_rm,
+            }[cmd]
+            if cmd == "ls" and not args:
+                args = [""]
             for src in args:
                 src = fname_remote(src)
-                print('%s :%s' % (cmd, src))
+                print("%s :%s" % (cmd, src))
                 op(src)
     except PyboardError as er:
-        print(str(er.args[2], 'ascii'))
+        print(str(er.args[2], "ascii"))
         pyb.exit_raw_repl()
         pyb.close()
         sys.exit(1)
 
+
 _injected_import_hook_code = """\
 import uos, uio
 class _FS:
@@ -511,20 +551,44 @@
 del _injected_buf, _FS
 """
 
+
 def main():
     import argparse
-    cmd_parser = argparse.ArgumentParser(description='Run scripts on the pyboard.')
-    cmd_parser.add_argument('--device', default='/dev/ttyACM0', help='the serial device or the IP address of the pyboard')
-    cmd_parser.add_argument('-b', '--baudrate', default=115200, help='the baud rate of the serial device')
-    cmd_parser.add_argument('-u', '--user', default='micro', help='the telnet login username')
-    cmd_parser.add_argument('-p', '--password', default='python', help='the telnet login password')
-    cmd_parser.add_argument('-c', '--command', help='program passed in as string')
-    cmd_parser.add_argument('-w', '--wait', default=0, type=int, help='seconds to wait for USB connected board to become available')
+
+    cmd_parser = argparse.ArgumentParser(description="Run scripts on the pyboard.")
+    cmd_parser.add_argument(
+        "--device",
+        default="/dev/ttyACM0",
+        help="the serial device or the IP address of the pyboard",
+    )
+    cmd_parser.add_argument(
+        "-b", "--baudrate", default=115200, help="the baud rate of the serial device"
+    )
+    cmd_parser.add_argument("-u", "--user", default="micro", help="the telnet login username")
+    cmd_parser.add_argument("-p", "--password", default="python", help="the telnet login password")
+    cmd_parser.add_argument("-c", "--command", help="program passed in as string")
+    cmd_parser.add_argument(
+        "-w",
+        "--wait",
+        default=0,
+        type=int,
+        help="seconds to wait for USB connected board to become available",
+    )
     group = cmd_parser.add_mutually_exclusive_group()
-    group.add_argument('--follow', action='store_true', help='follow the output after running the scripts [default if no scripts given]')
-    group.add_argument('--no-follow', action='store_true', help='Do not follow the output after running the scripts.')
-    cmd_parser.add_argument('-f', '--filesystem', action='store_true', help='perform a filesystem action')
-    cmd_parser.add_argument('files', nargs='*', help='input files')
+    group.add_argument(
+        "--follow",
+        action="store_true",
+        help="follow the output after running the scripts [default if no scripts given]",
+    )
+    group.add_argument(
+        "--no-follow",
+        action="store_true",
+        help="Do not follow the output after running the scripts.",
+    )
+    cmd_parser.add_argument(
+        "-f", "--filesystem", action="store_true", help="perform a filesystem action"
+    )
+    cmd_parser.add_argument("files", nargs="*", help="input files")
     args = cmd_parser.parse_args()
 
     # open the connection to the pyboard
@@ -551,7 +615,9 @@
                     pyb.exec_raw_no_follow(buf)
                     ret_err = None
                 else:
-                    ret, ret_err = pyb.exec_raw(buf, timeout=None, data_consumer=stdout_write_bytes)
+                    ret, ret_err = pyb.exec_raw(
+                        buf, timeout=None, data_consumer=stdout_write_bytes
+                    )
             except PyboardError as er:
                 print(er)
                 pyb.close()
@@ -571,14 +637,14 @@
 
         # run the command, if given
         if args.command is not None:
-            execbuffer(args.command.encode('utf-8'))
+            execbuffer(args.command.encode("utf-8"))
 
         # run any files
         for filename in args.files:
-            with open(filename, 'rb') as f:
+            with open(filename, "rb") as f:
                 pyfile = f.read()
-                if filename.endswith('.mpy') and pyfile[0] == ord('M'):
-                    pyb.exec_('_injected_buf=' + repr(pyfile))
+                if filename.endswith(".mpy") and pyfile[0] == ord("M"):
+                    pyb.exec_("_injected_buf=" + repr(pyfile))
                     pyfile = _injected_import_hook_code
                 execbuffer(pyfile)
 
@@ -602,5 +668,6 @@
     # close the connection to the pyboard
     pyb.close()
 
+
 if __name__ == "__main__":
     main()
diff --git a/tools/pydfu.py b/tools/pydfu.py
index 962ba2b..9f345d0 100755
--- a/tools/pydfu.py
+++ b/tools/pydfu.py
@@ -25,34 +25,34 @@
 
 # VID/PID
 __VID = 0x0483
-__PID = 0xdf11
+__PID = 0xDF11
 
 # USB request __TIMEOUT
 __TIMEOUT = 4000
 
 # DFU commands
-__DFU_DETACH    = 0
-__DFU_DNLOAD    = 1
-__DFU_UPLOAD    = 2
+__DFU_DETACH = 0
+__DFU_DNLOAD = 1
+__DFU_UPLOAD = 2
 __DFU_GETSTATUS = 3
 __DFU_CLRSTATUS = 4
-__DFU_GETSTATE  = 5
-__DFU_ABORT     = 6
+__DFU_GETSTATE = 5
+__DFU_ABORT = 6
 
 # DFU status
-__DFU_STATE_APP_IDLE                 = 0x00
-__DFU_STATE_APP_DETACH               = 0x01
-__DFU_STATE_DFU_IDLE                 = 0x02
-__DFU_STATE_DFU_DOWNLOAD_SYNC        = 0x03
-__DFU_STATE_DFU_DOWNLOAD_BUSY        = 0x04
-__DFU_STATE_DFU_DOWNLOAD_IDLE        = 0x05
-__DFU_STATE_DFU_MANIFEST_SYNC        = 0x06
-__DFU_STATE_DFU_MANIFEST             = 0x07
-__DFU_STATE_DFU_MANIFEST_WAIT_RESET  = 0x08
-__DFU_STATE_DFU_UPLOAD_IDLE          = 0x09
-__DFU_STATE_DFU_ERROR                = 0x0a
+__DFU_STATE_APP_IDLE = 0x00
+__DFU_STATE_APP_DETACH = 0x01
+__DFU_STATE_DFU_IDLE = 0x02
+__DFU_STATE_DFU_DOWNLOAD_SYNC = 0x03
+__DFU_STATE_DFU_DOWNLOAD_BUSY = 0x04
+__DFU_STATE_DFU_DOWNLOAD_IDLE = 0x05
+__DFU_STATE_DFU_MANIFEST_SYNC = 0x06
+__DFU_STATE_DFU_MANIFEST = 0x07
+__DFU_STATE_DFU_MANIFEST_WAIT_RESET = 0x08
+__DFU_STATE_DFU_UPLOAD_IDLE = 0x09
+__DFU_STATE_DFU_ERROR = 0x0A
 
-_DFU_DESCRIPTOR_TYPE                 = 0x21
+_DFU_DESCRIPTOR_TYPE = 0x21
 
 
 # USB device handle
@@ -68,12 +68,14 @@
 
 # Python 3 deprecated getargspec in favour of getfullargspec, but
 # Python 2 doesn't have the latter, so detect which one to use
-getargspec = getattr(inspect, 'getfullargspec', inspect.getargspec)
+getargspec = getattr(inspect, "getfullargspec", inspect.getargspec)
 
-if 'length' in getargspec(usb.util.get_string).args:
+if "length" in getargspec(usb.util.get_string).args:
     # PyUSB 1.0.0.b1 has the length argument
     def get_string(dev, index):
         return usb.util.get_string(dev, 255, index)
+
+
 else:
     # PyUSB 1.0.0.b2 dropped the length argument
     def get_string(dev, index):
@@ -83,17 +85,17 @@
 def find_dfu_cfg_descr(descr):
     if len(descr) == 9 and descr[0] == 9 and descr[1] == _DFU_DESCRIPTOR_TYPE:
         nt = collections.namedtuple(
-            'CfgDescr',
+            "CfgDescr",
             [
-                'bLength',
-                'bDescriptorType',
-                'bmAttributes',
-                'wDetachTimeOut',
-                'wTransferSize',
-                'bcdDFUVersion'
-            ]
+                "bLength",
+                "bDescriptorType",
+                "bmAttributes",
+                "wDetachTimeOut",
+                "wTransferSize",
+                "bcdDFUVersion",
+            ],
         )
-        return nt(*struct.unpack('<BBBHHH', bytearray(descr)))
+        return nt(*struct.unpack("<BBBHHH", bytearray(descr)))
     return None
 
 
@@ -102,9 +104,9 @@
     global __dev, __cfg_descr
     devices = get_dfu_devices(idVendor=__VID, idProduct=__PID)
     if not devices:
-        raise ValueError('No DFU device found')
+        raise ValueError("No DFU device found")
     if len(devices) > 1:
-        raise ValueError('Multiple DFU devices found')
+        raise ValueError("Multiple DFU devices found")
     __dev = devices[0]
     __dev.set_configuration()
 
@@ -127,8 +129,7 @@
         status = get_status()
         if status == __DFU_STATE_DFU_IDLE:
             break
-        elif (status == __DFU_STATE_DFU_DOWNLOAD_IDLE
-            or status == __DFU_STATE_DFU_UPLOAD_IDLE):
+        elif status == __DFU_STATE_DFU_DOWNLOAD_IDLE or status == __DFU_STATE_DFU_UPLOAD_IDLE:
             abort_request()
         else:
             clr_status()
@@ -141,64 +142,61 @@
 
 def clr_status():
     """Clears any error status (perhaps left over from a previous session)."""
-    __dev.ctrl_transfer(0x21, __DFU_CLRSTATUS, 0, __DFU_INTERFACE,
-                        None, __TIMEOUT)
+    __dev.ctrl_transfer(0x21, __DFU_CLRSTATUS, 0, __DFU_INTERFACE, None, __TIMEOUT)
 
 
 def get_status():
     """Get the status of the last operation."""
-    stat = __dev.ctrl_transfer(0xA1, __DFU_GETSTATUS, 0, __DFU_INTERFACE,
-                               6, 20000)
+    stat = __dev.ctrl_transfer(0xA1, __DFU_GETSTATUS, 0, __DFU_INTERFACE, 6, 20000)
     return stat[4]
 
 
 def mass_erase():
     """Performs a MASS erase (i.e. erases the entire device)."""
     # Send DNLOAD with first byte=0x41
-    __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE,
-                        '\x41', __TIMEOUT)
+    __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, "\x41", __TIMEOUT)
 
     # Execute last command
     if get_status() != __DFU_STATE_DFU_DOWNLOAD_BUSY:
-        raise Exception('DFU: erase failed')
+        raise Exception("DFU: erase failed")
 
     # Check command state
     if get_status() != __DFU_STATE_DFU_DOWNLOAD_IDLE:
-        raise Exception('DFU: erase failed')
+        raise Exception("DFU: erase failed")
 
 
 def page_erase(addr):
     """Erases a single page."""
     if __verbose:
-        print('Erasing page: 0x%x...' % (addr))
+        print("Erasing page: 0x%x..." % (addr))
 
     # Send DNLOAD with first byte=0x41 and page address
-    buf = struct.pack('<BI', 0x41, addr)
+    buf = struct.pack("<BI", 0x41, addr)
     __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, buf, __TIMEOUT)
 
     # Execute last command
     if get_status() != __DFU_STATE_DFU_DOWNLOAD_BUSY:
-        raise Exception('DFU: erase failed')
+        raise Exception("DFU: erase failed")
 
     # Check command state
     if get_status() != __DFU_STATE_DFU_DOWNLOAD_IDLE:
 
-        raise Exception('DFU: erase failed')
+        raise Exception("DFU: erase failed")
 
 
 def set_address(addr):
     """Sets the address for the next operation."""
     # Send DNLOAD with first byte=0x21 and page address
-    buf = struct.pack('<BI', 0x21, addr)
+    buf = struct.pack("<BI", 0x21, addr)
     __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, buf, __TIMEOUT)
 
     # Execute last command
     if get_status() != __DFU_STATE_DFU_DOWNLOAD_BUSY:
-        raise Exception('DFU: set address failed')
+        raise Exception("DFU: set address failed")
 
     # Check command state
     if get_status() != __DFU_STATE_DFU_DOWNLOAD_IDLE:
-        raise Exception('DFU: set address failed')
+        raise Exception("DFU: set address failed")
 
 
 def write_memory(addr, buf, progress=None, progress_addr=0, progress_size=0):
@@ -213,28 +211,29 @@
 
     while xfer_bytes < xfer_total:
         if __verbose and xfer_count % 512 == 0:
-            print('Addr 0x%x %dKBs/%dKBs...' % (xfer_base + xfer_bytes,
-                                                xfer_bytes // 1024,
-                                                xfer_total // 1024))
+            print(
+                "Addr 0x%x %dKBs/%dKBs..."
+                % (xfer_base + xfer_bytes, xfer_bytes // 1024, xfer_total // 1024)
+            )
         if progress and xfer_count % 2 == 0:
-            progress(progress_addr, xfer_base + xfer_bytes - progress_addr,
-                     progress_size)
+            progress(progress_addr, xfer_base + xfer_bytes - progress_addr, progress_size)
 
         # Set mem write address
         set_address(xfer_base + xfer_bytes)
 
         # Send DNLOAD with fw data
         chunk = min(__cfg_descr.wTransferSize, xfer_total - xfer_bytes)
-        __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 2, __DFU_INTERFACE,
-                            buf[xfer_bytes:xfer_bytes + chunk], __TIMEOUT)
+        __dev.ctrl_transfer(
+            0x21, __DFU_DNLOAD, 2, __DFU_INTERFACE, buf[xfer_bytes : xfer_bytes + chunk], __TIMEOUT
+        )
 
         # Execute last command
         if get_status() != __DFU_STATE_DFU_DOWNLOAD_BUSY:
-            raise Exception('DFU: write memory failed')
+            raise Exception("DFU: write memory failed")
 
         # Check command state
         if get_status() != __DFU_STATE_DFU_DOWNLOAD_IDLE:
-            raise Exception('DFU: write memory failed')
+            raise Exception("DFU: write memory failed")
 
         xfer_count += 1
         xfer_bytes += chunk
@@ -255,14 +254,14 @@
 
     # Execute last command
     if get_status() != __DFU_STATE_DFU_DOWNLOAD_BUSY:
-        raise Exception('DFU: write memory failed')
+        raise Exception("DFU: write memory failed")
 
     # Check command state
     if get_status() != __DFU_STATE_DFU_DOWNLOAD_IDLE:
-        raise Exception('DFU: write memory failed')
+        raise Exception("DFU: write memory failed")
 
     if __verbose:
-        print('Write: 0x%x ' % (xfer_base + xfer_offset))
+        print("Write: 0x%x " % (xfer_base + xfer_offset))
 
 
 def exit_dfu():
@@ -271,13 +270,12 @@
     set_address(0x08000000)
 
     # Send DNLOAD with 0 length to exit DFU
-    __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE,
-                        None, __TIMEOUT)
+    __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, None, __TIMEOUT)
 
     try:
         # Execute last command
         if get_status() != __DFU_STATE_DFU_MANIFEST:
-            print('Failed to reset device')
+            print("Failed to reset device")
 
         # Release device
         usb.util.dispose_resources(__dev)
@@ -301,7 +299,7 @@
 
 def cstring(string):
     """Extracts a null-terminated string from a byte array."""
-    return string.decode('utf-8').split('\0', 1)[0]
+    return string.decode("utf-8").split("\0", 1)[0]
 
 
 def compute_crc(data):
@@ -320,8 +318,8 @@
     If an error occurs while parsing the file, then None is returned.
     """
 
-    print('File: {}'.format(filename))
-    with open(filename, 'rb') as fin:
+    print("File: {}".format(filename))
+    with open(filename, "rb") as fin:
         data = fin.read()
     crc = compute_crc(data[:-4])
     elements = []
@@ -334,11 +332,12 @@
     #   B   uint8_t     version     1
     #   I   uint32_t    size        Size of the DFU file (without suffix)
     #   B   uint8_t     targets     Number of targets
-    dfu_prefix, data = consume('<5sBIB', data,
-                               'signature version size targets')
-    print('    %(signature)s v%(version)d, image size: %(size)d, '
-          'targets: %(targets)d' % dfu_prefix)
-    for target_idx in range(dfu_prefix['targets']):
+    dfu_prefix, data = consume("<5sBIB", data, "signature version size targets")
+    print(
+        "    %(signature)s v%(version)d, image size: %(size)d, "
+        "targets: %(targets)d" % dfu_prefix
+    )
+    for target_idx in range(dfu_prefix["targets"]):
         # Decode the Image Prefix
         #
         # <6sBI255s2I
@@ -349,40 +348,40 @@
         #   255s    char[255]   name        Name of the target
         #   I       uint32_t    size        Size of image (without prefix)
         #   I       uint32_t    elements    Number of elements in the image
-        img_prefix, data = consume('<6sBI255s2I', data,
-                                   'signature altsetting named name '
-                                   'size elements')
-        img_prefix['num'] = target_idx
-        if img_prefix['named']:
-            img_prefix['name'] = cstring(img_prefix['name'])
+        img_prefix, data = consume(
+            "<6sBI255s2I", data, "signature altsetting named name " "size elements"
+        )
+        img_prefix["num"] = target_idx
+        if img_prefix["named"]:
+            img_prefix["name"] = cstring(img_prefix["name"])
         else:
-            img_prefix['name'] = ''
-        print('    %(signature)s %(num)d, alt setting: %(altsetting)s, '
-              'name: "%(name)s", size: %(size)d, elements: %(elements)d'
-              % img_prefix)
+            img_prefix["name"] = ""
+        print(
+            "    %(signature)s %(num)d, alt setting: %(altsetting)s, "
+            'name: "%(name)s", size: %(size)d, elements: %(elements)d' % img_prefix
+        )
 
-        target_size = img_prefix['size']
+        target_size = img_prefix["size"]
         target_data = data[:target_size]
         data = data[target_size:]
-        for elem_idx in range(img_prefix['elements']):
+        for elem_idx in range(img_prefix["elements"]):
             # Decode target prefix
             #
             # <2I
             #   <   little endian           Endianness
             #   I   uint32_t    element     Address
             #   I   uint32_t    element     Size
-            elem_prefix, target_data = consume('<2I', target_data, 'addr size')
-            elem_prefix['num'] = elem_idx
-            print('      %(num)d, address: 0x%(addr)08x, size: %(size)d'
-                  % elem_prefix)
-            elem_size = elem_prefix['size']
+            elem_prefix, target_data = consume("<2I", target_data, "addr size")
+            elem_prefix["num"] = elem_idx
+            print("      %(num)d, address: 0x%(addr)08x, size: %(size)d" % elem_prefix)
+            elem_size = elem_prefix["size"]
             elem_data = target_data[:elem_size]
             target_data = target_data[elem_size:]
-            elem_prefix['data'] = elem_data
+            elem_prefix["data"] = elem_data
             elements.append(elem_prefix)
 
         if len(target_data):
-            print('target %d PARSE ERROR' % target_idx)
+            print("target %d PARSE ERROR" % target_idx)
 
     # Decode DFU Suffix
     #
@@ -395,16 +394,19 @@
     #   3s  char[3]     ufd         "UFD"
     #   B   uint8_t     len         16
     #   I   uint32_t    crc32       Checksum
-    dfu_suffix = named(struct.unpack('<4H3sBI', data[:16]),
-                       'device product vendor dfu ufd len crc')
-    print('    usb: %(vendor)04x:%(product)04x, device: 0x%(device)04x, '
-          'dfu: 0x%(dfu)04x, %(ufd)s, %(len)d, 0x%(crc)08x' % dfu_suffix)
-    if crc != dfu_suffix['crc']:
-        print('CRC ERROR: computed crc32 is 0x%08x' % crc)
+    dfu_suffix = named(
+        struct.unpack("<4H3sBI", data[:16]), "device product vendor dfu ufd len crc"
+    )
+    print(
+        "    usb: %(vendor)04x:%(product)04x, device: 0x%(device)04x, "
+        "dfu: 0x%(dfu)04x, %(ufd)s, %(len)d, 0x%(crc)08x" % dfu_suffix
+    )
+    if crc != dfu_suffix["crc"]:
+        print("CRC ERROR: computed crc32 is 0x%08x" % crc)
         return
     data = data[16:]
     if data:
-        print('PARSE ERROR')
+        print("PARSE ERROR")
         return
 
     return elements
@@ -418,8 +420,7 @@
     def __call__(self, device):
         for cfg in device:
             for intf in cfg:
-                return (intf.bInterfaceClass == 0xFE and
-                        intf.bInterfaceSubClass == 1)
+                return intf.bInterfaceClass == 0xFE and intf.bInterfaceSubClass == 1
 
 
 def get_dfu_devices(*args, **kwargs):
@@ -429,8 +430,7 @@
     """
 
     # Convert to list for compatibility with newer PyUSB
-    return list(usb.core.find(*args, find_all=True,
-                              custom_match=FilterDFU(), **kwargs))
+    return list(usb.core.find(*args, find_all=True, custom_match=FilterDFU(), **kwargs))
 
 
 def get_memory_layout(device):
@@ -446,25 +446,29 @@
     cfg = device[0]
     intf = cfg[(0, 0)]
     mem_layout_str = get_string(device, intf.iInterface)
-    mem_layout = mem_layout_str.split('/')
+    mem_layout = mem_layout_str.split("/")
     result = []
     for mem_layout_index in range(1, len(mem_layout), 2):
         addr = int(mem_layout[mem_layout_index], 0)
-        segments = mem_layout[mem_layout_index + 1].split(',')
-        seg_re = re.compile(r'(\d+)\*(\d+)(.)(.)')
+        segments = mem_layout[mem_layout_index + 1].split(",")
+        seg_re = re.compile(r"(\d+)\*(\d+)(.)(.)")
         for segment in segments:
             seg_match = seg_re.match(segment)
             num_pages = int(seg_match.groups()[0], 10)
             page_size = int(seg_match.groups()[1], 10)
             multiplier = seg_match.groups()[2]
-            if multiplier == 'K':
+            if multiplier == "K":
                 page_size *= 1024
-            if multiplier == 'M':
+            if multiplier == "M":
                 page_size *= 1024 * 1024
             size = num_pages * page_size
             last_addr = addr + size - 1
-            result.append(named((addr, last_addr, size, num_pages, page_size),
-                          'addr last_addr size num_pages page_size'))
+            result.append(
+                named(
+                    (addr, last_addr, size, num_pages, page_size),
+                    "addr last_addr size num_pages page_size",
+                )
+            )
             addr += size
     return result
 
@@ -473,18 +477,22 @@
     """Prints a lits of devices detected in DFU mode."""
     devices = get_dfu_devices(*args, **kwargs)
     if not devices:
-        print('No DFU capable devices found')
+        print("No DFU capable devices found")
         return
     for device in devices:
-        print('Bus {} Device {:03d}: ID {:04x}:{:04x}'
-              .format(device.bus, device.address,
-                      device.idVendor, device.idProduct))
+        print(
+            "Bus {} Device {:03d}: ID {:04x}:{:04x}".format(
+                device.bus, device.address, device.idVendor, device.idProduct
+            )
+        )
         layout = get_memory_layout(device)
-        print('Memory Layout')
+        print("Memory Layout")
         for entry in layout:
-            print('    0x{:x} {:2d} pages of {:3d}K bytes'
-                  .format(entry['addr'], entry['num_pages'],
-                          entry['page_size'] // 1024))
+            print(
+                "    0x{:x} {:2d} pages of {:3d}K bytes".format(
+                    entry["addr"], entry["num_pages"], entry["page_size"] // 1024
+                )
+            )
 
 
 def write_elements(elements, mass_erase_used, progress=None):
@@ -494,9 +502,9 @@
 
     mem_layout = get_memory_layout(__dev)
     for elem in elements:
-        addr = elem['addr']
-        size = elem['size']
-        data = elem['data']
+        addr = elem["addr"]
+        size = elem["size"]
+        data = elem["data"]
         elem_size = size
         elem_addr = addr
         if progress:
@@ -505,18 +513,16 @@
             write_size = size
             if not mass_erase_used:
                 for segment in mem_layout:
-                    if addr >= segment['addr'] and \
-                       addr <= segment['last_addr']:
+                    if addr >= segment["addr"] and addr <= segment["last_addr"]:
                         # We found the page containing the address we want to
                         # write, erase it
-                        page_size = segment['page_size']
+                        page_size = segment["page_size"]
                         page_addr = addr & ~(page_size - 1)
                         if addr + write_size > page_addr + page_size:
                             write_size = page_addr + page_size - addr
                         page_erase(page_addr)
                         break
-            write_memory(addr, data[:write_size], progress,
-                         elem_addr, elem_size)
+            write_memory(addr, data[:write_size], progress, elem_addr, elem_size)
             data = data[write_size:]
             addr += write_size
             size -= write_size
@@ -528,45 +534,36 @@
     """Prints a progress report suitable for use on the command line."""
     width = 25
     done = offset * width // size
-    print('\r0x{:08x} {:7d} [{}{}] {:3d}% '
-          .format(addr, size, '=' * done, ' ' * (width - done),
-                  offset * 100 // size), end='')
+    print(
+        "\r0x{:08x} {:7d} [{}{}] {:3d}% ".format(
+            addr, size, "=" * done, " " * (width - done), offset * 100 // size
+        ),
+        end="",
+    )
     try:
         sys.stdout.flush()
     except OSError:
-        pass    # Ignore Windows CLI "WinError 87" on Python 3.6
+        pass  # Ignore Windows CLI "WinError 87" on Python 3.6
     if offset == size:
-        print('')
+        print("")
 
 
 def main():
     """Test program for verifying this files functionality."""
     global __verbose
     # Parse CMD args
-    parser = argparse.ArgumentParser(description='DFU Python Util')
+    parser = argparse.ArgumentParser(description="DFU Python Util")
     parser.add_argument(
-        '-l', '--list',
-        help='list available DFU devices',
-        action='store_true',
-        default=False
+        "-l", "--list", help="list available DFU devices", action="store_true", default=False
     )
     parser.add_argument(
-        '-m', '--mass-erase',
-        help='mass erase device',
-        action='store_true',
-        default=False
+        "-m", "--mass-erase", help="mass erase device", action="store_true", default=False
     )
     parser.add_argument(
-        '-u', '--upload',
-        help='read file from DFU device',
-        dest='path',
-        default=False
+        "-u", "--upload", help="read file from DFU device", dest="path", default=False
     )
     parser.add_argument(
-        '-v', '--verbose',
-        help='increase output verbosity',
-        action='store_true',
-        default=False
+        "-v", "--verbose", help="increase output verbosity", action="store_true", default=False
     )
     args = parser.parse_args()
 
@@ -579,21 +576,22 @@
     init()
 
     if args.mass_erase:
-        print('Mass erase...')
+        print("Mass erase...")
         mass_erase()
 
     if args.path:
         elements = read_dfu_file(args.path)
         if not elements:
             return
-        print('Writing memory...')
+        print("Writing memory...")
         write_elements(elements, args.mass_erase, progress=cli_progress)
 
-        print('Exiting DFU...')
+        print("Exiting DFU...")
         exit_dfu()
         return
 
-    print('No command specified')
+    print("No command specified")
 
-if __name__ == '__main__':
+
+if __name__ == "__main__":
     main()
diff --git a/tools/tinytest-codegen.py b/tools/tinytest-codegen.py
index 424f70a..64f88ed 100755
--- a/tools/tinytest-codegen.py
+++ b/tools/tinytest-codegen.py
@@ -9,17 +9,19 @@
 def escape(s):
     s = s.decode()
     lookup = {
-        '\0': '\\0',
-        '\t': '\\t',
-        '\n': '\\n\"\n\"',
-        '\r': '\\r',
-        '\\': '\\\\',
-        '\"': '\\\"',
+        "\0": "\\0",
+        "\t": "\\t",
+        "\n": '\\n"\n"',
+        "\r": "\\r",
+        "\\": "\\\\",
+        '"': '\\"',
     }
-    return "\"\"\n\"{}\"".format(''.join([lookup[x] if x in lookup else x for x in s]))
+    return '""\n"{}"'.format("".join([lookup[x] if x in lookup else x for x in s]))
+
 
 def chew_filename(t):
-    return { 'func': "test_{}_fn".format(sub(r'/|\.|-', '_', t)), 'desc': t }
+    return {"func": "test_{}_fn".format(sub(r"/|\.|-", "_", t)), "desc": t}
+
 
 def script_to_map(test_file):
     r = {"name": chew_filename(test_file)["func"]}
@@ -29,6 +31,7 @@
         r["output"] = escape(f.read())
     return r
 
+
 test_function = (
     "void {name}(void* data) {{\n"
     "  static const char pystr[] = {script};\n"
@@ -40,79 +43,86 @@
     "}}"
 )
 
-testcase_struct = (
-    "struct testcase_t {name}_tests[] = {{\n{body}\n  END_OF_TESTCASES\n}};"
-)
-testcase_member = (
-    "  {{ \"{desc}\", {func}, TT_ENABLED_, 0, 0 }},"
-)
+testcase_struct = "struct testcase_t {name}_tests[] = {{\n{body}\n  END_OF_TESTCASES\n}};"
+testcase_member = '  {{ "{desc}", {func}, TT_ENABLED_, 0, 0 }},'
 
-testgroup_struct = (
-    "struct testgroup_t groups[] = {{\n{body}\n  END_OF_GROUPS\n}};"
-)
-testgroup_member = (
-    "  {{ \"{name}\", {name}_tests }},"
-)
+testgroup_struct = "struct testgroup_t groups[] = {{\n{body}\n  END_OF_GROUPS\n}};"
+testgroup_member = '  {{ "{name}", {name}_tests }},'
 
 ## XXX: may be we could have `--without <groups>` argument...
 # currently these tests are selected because they pass on qemu-arm
-test_dirs = ('basics', 'micropython', 'misc', 'extmod', 'float', 'inlineasm', 'qemu-arm',) # 'import', 'io',)
+test_dirs = (
+    "basics",
+    "micropython",
+    "misc",
+    "extmod",
+    "float",
+    "inlineasm",
+    "qemu-arm",
+)  # 'import', 'io',)
 exclude_tests = (
     # pattern matching in .exp
-    'basics/bytes_compare3.py',
-    'extmod/ticks_diff.py',
-    'extmod/time_ms_us.py',
-    'extmod/uheapq_timeq.py',
+    "basics/bytes_compare3.py",
+    "extmod/ticks_diff.py",
+    "extmod/time_ms_us.py",
+    "extmod/uheapq_timeq.py",
     # unicode char issue
-    'extmod/ujson_loads.py',
+    "extmod/ujson_loads.py",
     # doesn't output to python stdout
-    'extmod/ure_debug.py',
-    'extmod/vfs_basic.py',
-    'extmod/vfs_fat_ramdisk.py', 'extmod/vfs_fat_fileio.py',
-    'extmod/vfs_fat_fsusermount.py', 'extmod/vfs_fat_oldproto.py',
+    "extmod/ure_debug.py",
+    "extmod/vfs_basic.py",
+    "extmod/vfs_fat_ramdisk.py",
+    "extmod/vfs_fat_fileio.py",
+    "extmod/vfs_fat_fsusermount.py",
+    "extmod/vfs_fat_oldproto.py",
     # rounding issues
-    'float/float_divmod.py',
+    "float/float_divmod.py",
     # requires double precision floating point to work
-    'float/float2int_doubleprec_intbig.py',
-    'float/float_parse_doubleprec.py',
+    "float/float2int_doubleprec_intbig.py",
+    "float/float_parse_doubleprec.py",
     # inline asm FP tests (require Cortex-M4)
-    'inlineasm/asmfpaddsub.py', 'inlineasm/asmfpcmp.py', 'inlineasm/asmfpldrstr.py',
-    'inlineasm/asmfpmuldiv.py','inlineasm/asmfpsqrt.py',
+    "inlineasm/asmfpaddsub.py",
+    "inlineasm/asmfpcmp.py",
+    "inlineasm/asmfpldrstr.py",
+    "inlineasm/asmfpmuldiv.py",
+    "inlineasm/asmfpsqrt.py",
     # different filename in output
-    'micropython/emg_exc.py',
-    'micropython/heapalloc_traceback.py',
+    "micropython/emg_exc.py",
+    "micropython/heapalloc_traceback.py",
     # pattern matching in .exp
-    'micropython/meminfo.py',
+    "micropython/meminfo.py",
     # needs sys stdfiles
-    'misc/print_exception.py',
+    "misc/print_exception.py",
     # settrace .exp files are too large
-    'misc/sys_settrace_loop.py',
-    'misc/sys_settrace_generator.py',
-    'misc/sys_settrace_features.py',
+    "misc/sys_settrace_loop.py",
+    "misc/sys_settrace_generator.py",
+    "misc/sys_settrace_features.py",
 )
 
 output = []
 tests = []
 
-argparser = argparse.ArgumentParser(description='Convert native MicroPython tests to tinytest/upytesthelper C code')
-argparser.add_argument('--stdin', action="store_true", help='read list of tests from stdin')
+argparser = argparse.ArgumentParser(
+    description="Convert native MicroPython tests to tinytest/upytesthelper C code"
+)
+argparser.add_argument("--stdin", action="store_true", help="read list of tests from stdin")
 args = argparser.parse_args()
 
 if not args.stdin:
     for group in test_dirs:
-        tests += [test for test in glob('{}/*.py'.format(group)) if test not in exclude_tests]
+        tests += [test for test in glob("{}/*.py".format(group)) if test not in exclude_tests]
 else:
     for l in sys.stdin:
         tests.append(l.rstrip())
 
 output.extend([test_function.format(**script_to_map(test)) for test in tests])
 testcase_members = [testcase_member.format(**chew_filename(test)) for test in tests]
-output.append(testcase_struct.format(name="", body='\n'.join(testcase_members)))
+output.append(testcase_struct.format(name="", body="\n".join(testcase_members)))
 
 testgroup_members = [testgroup_member.format(name=group) for group in [""]]
 
-output.append(testgroup_struct.format(body='\n'.join(testgroup_members)))
+output.append(testgroup_struct.format(body="\n".join(testgroup_members)))
 
 ## XXX: may be we could have `--output <filename>` argument...
 # Don't depend on what system locale is set, use utf8 encoding.
-sys.stdout.buffer.write('\n\n'.join(output).encode('utf8'))
+sys.stdout.buffer.write("\n\n".join(output).encode("utf8"))
diff --git a/tools/uf2conv.py b/tools/uf2conv.py
index 2f2812a..d67a552 100755
--- a/tools/uf2conv.py
+++ b/tools/uf2conv.py
@@ -1,23 +1,23 @@
 #!/usr/bin/env python3
 
 # Microsoft UF2
-# 
+#
 # The MIT License (MIT)
-# 
+#
 # Copyright (c) Microsoft Corporation
-# 
+#
 # All rights reserved.
-# 
+#
 # Permission is hereby granted, free of charge, to any person obtaining a copy
 # of this software and associated documentation files (the "Software"), to deal
 # in the Software without restriction, including without limitation the rights
 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 # copies of the Software, and to permit persons to whom the Software is
 # furnished to do so, subject to the following conditions:
-# 
+#
 # The above copyright notice and this permission notice shall be included in all
 # copies or substantial portions of the Software.
-# 
+#
 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -35,17 +35,17 @@
 import argparse
 
 
-UF2_MAGIC_START0 = 0x0A324655 # "UF2\n"
-UF2_MAGIC_START1 = 0x9E5D5157 # Randomly selected
-UF2_MAGIC_END    = 0x0AB16F30 # Ditto
+UF2_MAGIC_START0 = 0x0A324655  # "UF2\n"
+UF2_MAGIC_START1 = 0x9E5D5157  # Randomly selected
+UF2_MAGIC_END = 0x0AB16F30  # Ditto
 
 families = {
-    'SAMD21': 0x68ed2b88,
-    'SAMD51': 0x55114460,
-    'NRF52': 0x1b57745f,
-    'STM32F1': 0x5ee21072,
-    'STM32F4': 0x57755a57,
-    'ATMEGA32': 0x16573617,
+    "SAMD21": 0x68ED2B88,
+    "SAMD51": 0x55114460,
+    "NRF52": 0x1B57745F,
+    "STM32F1": 0x5EE21072,
+    "STM32F4": 0x57755A57,
+    "ATMEGA32": 0x16573617,
 }
 
 INFO_FILE = "/INFO_UF2.TXT"
@@ -58,15 +58,17 @@
     w = struct.unpack("<II", buf[0:8])
     return w[0] == UF2_MAGIC_START0 and w[1] == UF2_MAGIC_START1
 
+
 def is_hex(buf):
     try:
         w = buf[0:30].decode("utf-8")
     except UnicodeDecodeError:
         return False
-    if w[0] == ':' and re.match(b"^[:0-9a-fA-F\r\n]+$", buf):
+    if w[0] == ":" and re.match(b"^[:0-9a-fA-F\r\n]+$", buf):
         return True
     return False
 
+
 def convert_from_uf2(buf):
     global appstartaddr
     numblocks = len(buf) // 512
@@ -74,7 +76,7 @@
     outp = b""
     for blockno in range(numblocks):
         ptr = blockno * 512
-        block = buf[ptr:ptr + 512]
+        block = buf[ptr : ptr + 512]
         hd = struct.unpack(b"<IIIIIIII", block[0:32])
         if hd[0] != UF2_MAGIC_START0 or hd[1] != UF2_MAGIC_START1:
             print("Skipping block at " + ptr + "; bad magic")
@@ -92,7 +94,7 @@
         padding = newaddr - curraddr
         if padding < 0:
             assert False, "Block out of order at " + ptr
-        if padding > 10*1024*1024:
+        if padding > 10 * 1024 * 1024:
             assert False, "More than 10M of padding needed at " + ptr
         if padding % 4 != 0:
             assert False, "Non-word padding size at " + ptr
@@ -103,6 +105,7 @@
         curraddr = newaddr + datalen
     return outp
 
+
 def convert_to_carray(file_content):
     outp = "const unsigned char bindata[] __attribute__((aligned(16))) = {"
     for i in range(len(file_content)):
@@ -112,6 +115,7 @@
     outp += "\n};\n"
     return outp
 
+
 def convert_to_uf2(file_content):
     global familyid
     datapadding = b""
@@ -121,13 +125,21 @@
     outp = b""
     for blockno in range(numblocks):
         ptr = 256 * blockno
-        chunk = file_content[ptr:ptr + 256]
+        chunk = file_content[ptr : ptr + 256]
         flags = 0x0
         if familyid:
             flags |= 0x2000
-        hd = struct.pack(b"<IIIIIIII",
-            UF2_MAGIC_START0, UF2_MAGIC_START1,
-            flags, ptr + appstartaddr, 256, blockno, numblocks, familyid)
+        hd = struct.pack(
+            b"<IIIIIIII",
+            UF2_MAGIC_START0,
+            UF2_MAGIC_START1,
+            flags,
+            ptr + appstartaddr,
+            256,
+            blockno,
+            numblocks,
+            familyid,
+        )
         while len(chunk) < 256:
             chunk += b"\x00"
         block = hd + chunk + datapadding + struct.pack(b"<I", UF2_MAGIC_END)
@@ -135,6 +147,7 @@
         outp += block
     return outp
 
+
 class Block:
     def __init__(self, addr):
         self.addr = addr
@@ -145,35 +158,44 @@
         flags = 0x0
         if familyid:
             flags |= 0x2000
-        hd = struct.pack("<IIIIIIII",
-            UF2_MAGIC_START0, UF2_MAGIC_START1,
-            flags, self.addr, 256, blockno, numblocks, familyid)
+        hd = struct.pack(
+            "<IIIIIIII",
+            UF2_MAGIC_START0,
+            UF2_MAGIC_START1,
+            flags,
+            self.addr,
+            256,
+            blockno,
+            numblocks,
+            familyid,
+        )
         hd += self.bytes[0:256]
         while len(hd) < 512 - 4:
             hd += b"\x00"
         hd += struct.pack("<I", UF2_MAGIC_END)
         return hd
 
+
 def convert_from_hex_to_uf2(buf):
     global appstartaddr
     appstartaddr = None
     upper = 0
     currblock = None
     blocks = []
-    for line in buf.split('\n'):
+    for line in buf.split("\n"):
         if line[0] != ":":
             continue
         i = 1
         rec = []
         while i < len(line) - 1:
-            rec.append(int(line[i:i+2], 16))
+            rec.append(int(line[i : i + 2], 16))
             i += 2
         tp = rec[3]
         if tp == 4:
             upper = ((rec[4] << 8) | rec[5]) << 16
         elif tp == 2:
             upper = ((rec[4] << 8) | rec[5]) << 4
-            assert (upper & 0xffff) == 0
+            assert (upper & 0xFFFF) == 0
         elif tp == 1:
             break
         elif tp == 0:
@@ -182,10 +204,10 @@
                 appstartaddr = addr
             i = 4
             while i < len(rec) - 1:
-                if not currblock or currblock.addr & ~0xff != addr & ~0xff:
-                    currblock = Block(addr & ~0xff)
+                if not currblock or currblock.addr & ~0xFF != addr & ~0xFF:
+                    currblock = Block(addr & ~0xFF)
                     blocks.append(currblock)
-                currblock.bytes[addr & 0xff] = rec[i]
+                currblock.bytes[addr & 0xFF] = rec[i]
                 addr += 1
                 i += 1
     numblocks = len(blocks)
@@ -194,14 +216,24 @@
         resfile += blocks[i].encode(i, numblocks)
     return resfile
 
+
 def get_drives():
     drives = []
     if sys.platform == "win32":
-        r = subprocess.check_output(["wmic", "PATH", "Win32_LogicalDisk",
-                                     "get", "DeviceID,", "VolumeName,",
-                                     "FileSystem,", "DriveType"])
-        for line in r.split('\n'):
-            words = re.split('\s+', line)
+        r = subprocess.check_output(
+            [
+                "wmic",
+                "PATH",
+                "Win32_LogicalDisk",
+                "get",
+                "DeviceID,",
+                "VolumeName,",
+                "FileSystem,",
+                "DriveType",
+            ]
+        )
+        for line in r.split("\n"):
+            words = re.split("\s+", line)
             if len(words) >= 3 and words[1] == "2" and words[2] == "FAT":
                 drives.append(words[0])
     else:
@@ -215,7 +247,6 @@
         for d in os.listdir(rootpath):
             drives.append(os.path.join(rootpath, d))
 
-
     def has_info(d):
         try:
             return os.path.isfile(d + INFO_FILE)
@@ -226,7 +257,7 @@
 
 
 def board_id(path):
-    with open(path + INFO_FILE, mode='r') as file:
+    with open(path + INFO_FILE, mode="r") as file:
         file_content = file.read()
     return re.search("Board-ID: ([^\r\n]*)", file_content).group(1)
 
@@ -244,28 +275,45 @@
 
 def main():
     global appstartaddr, familyid
+
     def error(msg):
         print(msg)
         sys.exit(1)
-    parser = argparse.ArgumentParser(description='Convert to UF2 or flash directly.')
-    parser.add_argument('input', metavar='INPUT', type=str, nargs='?',
-                        help='input file (HEX, BIN or UF2)')
-    parser.add_argument('-b' , '--base', dest='base', type=str,
-                        default="0x2000",
-                        help='set base address of application for BIN format (default: 0x2000)')
-    parser.add_argument('-o' , '--output', metavar="FILE", dest='output', type=str,
-                        help='write output to named file; defaults to "flash.uf2" or "flash.bin" where sensible')
-    parser.add_argument('-d' , '--device', dest="device_path",
-                        help='select a device path to flash')
-    parser.add_argument('-l' , '--list', action='store_true',
-                        help='list connected devices')
-    parser.add_argument('-c' , '--convert', action='store_true',
-                        help='do not flash, just convert')
-    parser.add_argument('-f' , '--family', dest='family', type=str,
-                        default="0x0",
-                        help='specify familyID - number or name (default: 0x0)')
-    parser.add_argument('-C' , '--carray', action='store_true',
-                        help='convert binary file to a C array, not UF2')
+
+    parser = argparse.ArgumentParser(description="Convert to UF2 or flash directly.")
+    parser.add_argument(
+        "input", metavar="INPUT", type=str, nargs="?", help="input file (HEX, BIN or UF2)"
+    )
+    parser.add_argument(
+        "-b",
+        "--base",
+        dest="base",
+        type=str,
+        default="0x2000",
+        help="set base address of application for BIN format (default: 0x2000)",
+    )
+    parser.add_argument(
+        "-o",
+        "--output",
+        metavar="FILE",
+        dest="output",
+        type=str,
+        help='write output to named file; defaults to "flash.uf2" or "flash.bin" where sensible',
+    )
+    parser.add_argument("-d", "--device", dest="device_path", help="select a device path to flash")
+    parser.add_argument("-l", "--list", action="store_true", help="list connected devices")
+    parser.add_argument("-c", "--convert", action="store_true", help="do not flash, just convert")
+    parser.add_argument(
+        "-f",
+        "--family",
+        dest="family",
+        type=str,
+        default="0x0",
+        help="specify familyID - number or name (default: 0x0)",
+    )
+    parser.add_argument(
+        "-C", "--carray", action="store_true", help="convert binary file to a C array, not UF2"
+    )
     args = parser.parse_args()
     appstartaddr = int(args.base, 0)
 
@@ -282,7 +330,7 @@
     else:
         if not args.input:
             error("Need input file")
-        with open(args.input, mode='rb') as f:
+        with open(args.input, mode="rb") as f:
             inpbuf = f.read()
         from_uf2 = is_uf2(inpbuf)
         ext = "uf2"
@@ -296,8 +344,10 @@
             ext = "h"
         else:
             outbuf = convert_to_uf2(inpbuf)
-        print("Converting to %s, output size: %d, start address: 0x%x" %
-              (ext, len(outbuf), appstartaddr))
+        print(
+            "Converting to %s, output size: %d, start address: 0x%x"
+            % (ext, len(outbuf), appstartaddr)
+        )
         if args.convert:
             drives = []
             if args.output == None:
diff --git a/tools/upip.py b/tools/upip.py
index e3b8885..0036eac 100644
--- a/tools/upip.py
+++ b/tools/upip.py
@@ -12,6 +12,7 @@
 import ujson as json
 import uzlib
 import upip_utarfile as tarfile
+
 gc.collect()
 
 
@@ -23,9 +24,11 @@
 
 file_buf = bytearray(512)
 
+
 class NotFoundError(Exception):
     pass
 
+
 def op_split(path):
     if path == "":
         return ("", "")
@@ -37,9 +40,11 @@
         head = "/"
     return (head, r[1])
 
+
 def op_basename(path):
     return op_split(path)[1]
 
+
 # Expects *file* name
 def _makedirs(name, mode=0o777):
     ret = False
@@ -70,26 +75,27 @@
                 break
             outf.write(file_buf, sz)
 
+
 def install_tar(f, prefix):
     meta = {}
     for info in f:
-        #print(info)
+        # print(info)
         fname = info.name
         try:
-            fname = fname[fname.index("/") + 1:]
+            fname = fname[fname.index("/") + 1 :]
         except ValueError:
             fname = ""
 
         save = True
         for p in ("setup.", "PKG-INFO", "README"):
-                #print(fname, p)
-                if fname.startswith(p) or ".egg-info" in fname:
-                    if fname.endswith("/requires.txt"):
-                        meta["deps"] = f.extractfile(info).read()
-                    save = False
-                    if debug:
-                        print("Skipping", fname)
-                    break
+            # print(fname, p)
+            if fname.startswith(p) or ".egg-info" in fname:
+                if fname.endswith("/requires.txt"):
+                    meta["deps"] = f.extractfile(info).read()
+                save = False
+                if debug:
+                    print("Skipping", fname)
+                break
 
         if save:
             outfname = prefix + fname
@@ -101,32 +107,37 @@
                 save_file(outfname, subf)
     return meta
 
+
 def expandhome(s):
     if "~/" in s:
         h = os.getenv("HOME")
         s = s.replace("~/", h + "/")
     return s
 
+
 import ussl
 import usocket
+
 warn_ussl = True
+
+
 def url_open(url):
     global warn_ussl
 
     if debug:
         print(url)
 
-    proto, _, host, urlpath = url.split('/', 3)
+    proto, _, host, urlpath = url.split("/", 3)
     try:
         ai = usocket.getaddrinfo(host, 443, 0, usocket.SOCK_STREAM)
     except OSError as e:
         fatal("Unable to resolve %s (no Internet?)" % host, e)
-    #print("Address infos:", ai)
+    # print("Address infos:", ai)
     ai = ai[0]
 
     s = usocket.socket(ai[0], ai[1], ai[2])
     try:
-        #print("Connect address:", addr)
+        # print("Connect address:", addr)
         s.connect(ai[-1])
 
         if proto == "https:":
@@ -147,7 +158,7 @@
             l = s.readline()
             if not l:
                 raise ValueError("Unexpected EOF in HTTP headers")
-            if l == b'\r\n':
+            if l == b"\r\n":
                 break
     except Exception as e:
         s.close()
@@ -175,6 +186,7 @@
         raise exc
     sys.exit(1)
 
+
 def install_pkg(pkg_spec, install_path):
     data = get_pkg_metadata(pkg_spec)
 
@@ -198,6 +210,7 @@
     gc.collect()
     return meta
 
+
 def install(to_install, install_path=None):
     # Calculate gzip dictionary size to use
     global gzdict_sz
@@ -230,9 +243,11 @@
                 deps = deps.decode("utf-8").split("\n")
                 to_install.extend(deps)
     except Exception as e:
-        print("Error installing '{}': {}, packages may be partially installed".format(
-                pkg_spec, e),
-            file=sys.stderr)
+        print(
+            "Error installing '{}': {}, packages may be partially installed".format(pkg_spec, e),
+            file=sys.stderr,
+        )
+
 
 def get_install_path():
     global install_path
@@ -242,6 +257,7 @@
     install_path = expandhome(install_path)
     return install_path
 
+
 def cleanup():
     for fname in cleanup_files:
         try:
@@ -249,21 +265,27 @@
         except OSError:
             print("Warning: Cannot delete " + fname)
 
+
 def help():
-    print("""\
+    print(
+        """\
 upip - Simple PyPI package manager for MicroPython
 Usage: micropython -m upip install [-p <path>] <package>... | -r <requirements.txt>
 import upip; upip.install(package_or_list, [<path>])
 
 If <path> is not given, packages will be installed into sys.path[1]
 (can be set from MICROPYPATH environment variable, if current system
-supports that).""")
+supports that)."""
+    )
     print("Current value of sys.path[1]:", sys.path[1])
-    print("""\
+    print(
+        """\
 
 Note: only MicroPython packages (usually, named micropython-*) are supported
 for installation, upip does not support arbitrary code in setup.py.
-""")
+"""
+    )
+
 
 def main():
     global debug
diff --git a/tools/upip_utarfile.py b/tools/upip_utarfile.py
index 460ca2c..21b899f 100644
--- a/tools/upip_utarfile.py
+++ b/tools/upip_utarfile.py
@@ -9,11 +9,12 @@
 DIRTYPE = "dir"
 REGTYPE = "file"
 
+
 def roundup(val, align):
     return (val + align - 1) & ~(align - 1)
 
-class FileSection:
 
+class FileSection:
     def __init__(self, f, content_len, aligned_len):
         self.f = f
         self.content_len = content_len
@@ -33,7 +34,7 @@
         if self.content_len == 0:
             return 0
         if len(buf) > self.content_len:
-            buf = memoryview(buf)[:self.content_len]
+            buf = memoryview(buf)[: self.content_len]
         sz = self.f.readinto(buf)
         self.content_len -= sz
         return sz
@@ -47,13 +48,13 @@
                 self.f.readinto(buf, s)
                 sz -= s
 
-class TarInfo:
 
+class TarInfo:
     def __str__(self):
         return "TarInfo(%r, %s, %d)" % (self.name, self.type, self.size)
 
-class TarFile:
 
+class TarFile:
     def __init__(self, name=None, fileobj=None):
         if fileobj:
             self.f = fileobj
@@ -62,24 +63,24 @@
         self.subf = None
 
     def next(self):
-            if self.subf:
-                self.subf.skip()
-            buf = self.f.read(512)
-            if not buf:
-                return None
+        if self.subf:
+            self.subf.skip()
+        buf = self.f.read(512)
+        if not buf:
+            return None
 
-            h = uctypes.struct(uctypes.addressof(buf), TAR_HEADER, uctypes.LITTLE_ENDIAN)
+        h = uctypes.struct(uctypes.addressof(buf), TAR_HEADER, uctypes.LITTLE_ENDIAN)
 
-            # Empty block means end of archive
-            if h.name[0] == 0:
-                return None
+        # Empty block means end of archive
+        if h.name[0] == 0:
+            return None
 
-            d = TarInfo()
-            d.name = str(h.name, "utf-8").rstrip("\0")
-            d.size = int(bytes(h.size), 8)
-            d.type = [REGTYPE, DIRTYPE][d.name[-1] == "/"]
-            self.subf = d.subf = FileSection(self.f, d.size, roundup(d.size, 512))
-            return d
+        d = TarInfo()
+        d.name = str(h.name, "utf-8").rstrip("\0")
+        d.size = int(bytes(h.size), 8)
+        d.type = [REGTYPE, DIRTYPE][d.name[-1] == "/"]
+        self.subf = d.subf = FileSection(self.f, d.size, roundup(d.size, 512))
+        return d
 
     def __iter__(self):
         return self