aboutsummaryrefslogtreecommitdiff
path: root/ports/stm32/boards
diff options
context:
space:
mode:
authorDamien George2020-02-27 15:36:53 +1100
committerDamien George2020-02-28 10:33:03 +1100
commit69661f3343bedf86e514337cff63d96cc42f8859 (patch)
treeaf5dfb380ffdb75dda84828f63cf9d840d992f0f /ports/stm32/boards
parent3f39d18c2b884d32f0443e2e8114ff9d7a14d718 (diff)
all: Reformat C and Python source code with tools/codeformat.py.
This is run with uncrustify 0.70.1, and black 19.10b0.
Diffstat (limited to 'ports/stm32/boards')
-rw-r--r--ports/stm32/boards/PYBD_SF2/manifest.py4
-rw-r--r--ports/stm32/boards/STM32F4DISC/staccel.py21
-rwxr-xr-xports/stm32/boards/make-pins.py324
-rw-r--r--ports/stm32/boards/manifest.py6
-rw-r--r--ports/stm32/boards/pllvalues.py80
5 files changed, 244 insertions, 191 deletions
diff --git a/ports/stm32/boards/PYBD_SF2/manifest.py b/ports/stm32/boards/PYBD_SF2/manifest.py
index 48cc2ce93..3819aa01b 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 2f2561d1c..af7772041 100644
--- a/ports/stm32/boards/STM32F4DISC/staccel.py
+++ b/ports/stm32/boards/STM32F4DISC/staccel.py
@@ -18,29 +18,30 @@ from micropython import const
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 @@ class STAccel:
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 @@ class STAccel:
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 3819b4724..692387f40 100755
--- a/ports/stm32/boards/make-pins.py
+++ b/ports/stm32/boards/make-pins.py
@@ -9,52 +9,54 @@ import csv
# 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 @@ def conditional_var(name_num):
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 @@ class AlternateFunction(object):
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 @@ class AlternateFunction(object):
"""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 @@ class Pin(object):
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 @@ class Pin(object):
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 @@ class Pin(object):
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 @@ class Pin(object):
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 @@ class Pin(object):
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 Pin(object):
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 NamedPin(object):
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 @@ class Pins(object):
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 @@ class Pins(object):
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 @@ class Pins(object):
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 @@ class Pins(object):
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 @@ class Pins(object):
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 @@ class Pins(object):
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 @@ def main():
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 41b728fa2..339077323 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 2d64876b4..59d660364 100644
--- a/ports/stm32/boards/pllvalues.py
+++ b/ports/stm32/boards/pllvalues.py
@@ -7,8 +7,11 @@ for the machine.freq() function.
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 @@ class MCU:
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_default = MCU(
)
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 @@ def compute_pll(hse, sys):
# 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 @@ def compute_pll2(hse, sys, relax_pll48):
# 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 @@ def compute_pll2(hse, sys, relax_pll48):
# 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 @@ def compute_pll2(hse, sys, relax_pll48):
# 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 @@ def compute_derived(hse, pll):
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 @@ def verify_pll(hse, pll):
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 @@ def compute_pll_table(source_clk, relax_pll48):
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 @@ def generate_c_table(hse, valid_plls):
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 @@ def print_table(hse, valid_plls):
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 @@ def search_header_for_hsx_values(filename, vals):
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 @@ def main():
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()