Compare commits

..

619 Commits

Author SHA1 Message Date
Damien George
9b486340da all: Bump version to 1.19.1.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-17 12:57:59 +10:00
Damien George
5233fb3a3d extmod/machine_i2c: Only use WRITE1 option if transfer supports it.
When MICROPY_PY_MACHINE_I2C_TRANSFER_WRITE1 is enabled the port's hardware
I2C transfer functions should support the MP_MACHINE_I2C_FLAG_WRITE1
option, but software I2C will not.  So add a flag to the I2C protocol
struct so each individual protocol can indicate whether it supports this
option or not.

Fixes issue #8765.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-17 11:57:57 +10:00
Damien George
d7919ea71e all: Bump version to 1.19.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-16 15:11:02 +10:00
Damien George
096954337f stm32/mboot: Only include UI code if at least one board LED is defined.
Otherwise the board must provide dummy definitions of MBOOT_LED1.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-16 14:31:09 +10:00
Damien George
d75892c0b0 zephyr/modusocket: Fix function object wrapper for listen method.
This was missed by 919f696ad2

Signed-off-by: Damien George <damien@micropython.org>
2022-06-15 11:38:09 +10:00
Phil Howard
37d5114cec py/makemoduledefs.py: Emit useful error for legacy MP_REGISTER_MODULE.
Catch calls to legacy:

MP_REGISTER_MODULE(name, module, enable)

Emit a friendly error suggesting they be rewritten to:

MP_REGISTER_MODULE(name, module).

Signed-off-by: Phil Howard <phil@pimoroni.com>
2022-06-14 15:05:37 +01:00
Andrew Scheller
cedb93c179 docs: Update Raspberry Pi URLs from .org to .com. 2022-06-14 11:41:13 +10:00
iabdalkader
99d3a73d59 nrf/modules/uos/microbitfs: Fix MICROPY_MBFS build to use mp_obj_malloc.
Changes introduced in 0e7bfc88c6 missed
changing this call to mp_obj_malloc.
2022-06-11 21:09:58 +10:00
iabdalkader
58b35c9abd extmod/extmod.cmake: Fix hard-coded mbedtls config file path.
* The mbedtls config file path is hard-coded to the config file in
the stm32 port. Any port using this cmake fragment is not actually
using its own config file.
2022-06-11 21:00:13 +10:00
Damien George
cf7d962cf3 docs/reference/mpyfiles: Update .mpy description to match latest format.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-10 16:42:43 +10:00
Damien George
1f1afae622 examples/natmod/features3: Add example to test more natmod features.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-10 16:42:43 +10:00
Damien George
0e556f22a2 py/dynruntime: Add macros to access more types and mp_const_empty_bytes.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-10 16:42:43 +10:00
Jeremy Herbert
148d12252b py/dynruntime: Add macros to create a new dict and store to dicts. 2022-06-10 16:42:43 +10:00
Damien George
17a0d65ee4 tools/mpy_ld.py: Support GOT entries that reference inside mp_fun_table.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-10 16:42:43 +10:00
Damien George
ee9feacc00 drivers/sdcard: Fix address calculation on v2 SDSC cards.
For v2 cards that are standard capacity the read/write/erase commands take
byte address values.  Use the result of CMD58 to distinguish SDSC from
SDHC/SDXC.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-10 12:56:31 +10:00
Damien George
203b98c42b drivers/sdcard: Make ioctl(4), ioctl(5) return num blocks, block size.
For CSD v1.0 the computed size is in bytes, so convert it to number of
512-byte blocks, and then ioctl(4) will return the correct value.

Also implement ioctl(5) to return the block size, which is always 512.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-10 12:56:30 +10:00
Yukai Li
ab6ad86793 drivers/sdcard: Fix CSD version 1.0 device size calculation.
Signed-off-by: Yukai Li <yukaili.geek@gmail.com>
2022-06-10 12:56:15 +10:00
Damien George
f63b4f85aa py/parse: Work around xtensa esp-2020r3 compiler bug.
This commit works around a bug in xtensa-esp32-elf-gcc version esp-2020r3.

The bug is in generation of loop constructs.  The below code is generated
by the xtensa-esp32 compiler.  The first extract is the buggy machine code
and the second extract is the corrected machine code.  The test
`basics/logic_constfolding.py` fails with the first code and succeeds with
the second.

Disassembly of section .text.push_result_rule:

00000000 <push_result_rule>:
  ...
  d6:   209770       or      a9, a7, a7
  d9:   178976       loop    a9, f4 <push_result_rule+0xf4>
                     d9: R_XTENSA_SLOT0_OP   .text.push_result_rule+0xf4
  dc:   030190       rsr.lend        a9
  df:   130090       wsr.lbeg        a9
  e2:   a8c992       addi    a9, a9, -88
  e5:   06d992       addmi   a9, a9, 0x600
  e8:   130190       wsr.lend        a9
  eb:   002000       isync
  ee:   030290       rsr.lcount      a9
  f1:   01c992       addi    a9, a9, 1
  f4:   1494e7       bne     a4, a14, 10c <push_result_rule+0x10c>
                     f4: R_XTENSA_SLOT0_OP   .text.push_result_rule+0x10c

Disassembly of section .text.push_result_rule:

00000000 <push_result_rule>:
  ...
  d6:   209770       or      a9, a7, a7
  d9:   178976       loop    a9, f4 <push_result_rule+0xf4>
                     d9: R_XTENSA_SLOT0_OP   .text.push_result_rule+0xf4
  dc:   030190       rsr.lend        a9
  df:   130090       wsr.lbeg        a9
  e2:   000091       l32r    a9, fffc00e4 <push_result_rule+0xfffc00e4>
                     e2: R_XTENSA_SLOT0_OP   .literal.push_result_rule+0x18
  e5:   0020f0       nop
  e8:   130190       wsr.lend        a9
  eb:   002000       isync
  ee:   030290       rsr.lcount      a9
  f1:   01c992       addi    a9, a9, 1
  f4:   1494e7       bne     a4, a14, 10c <push_result_rule+0x10c>
                     f4: R_XTENSA_SLOT0_OP   .text.push_result_rule+0x10c

Work done in collaboration with @jimmo.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-09 13:56:30 +10:00
Damien George
3452ee58d3 stm32/boards/LEGO_HUB_NO6: Add comment to readme about powering off.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-09 13:24:08 +10:00
Damien George
45a0c6da5b stm32/mboot: Remove MP_WEAK on led funcs and make some of them static.
Both led_init and led_state are configurable via MBOOT_BOARD_LED_INIT and
MBOOT_BOARD_LED_STATE respectively, so don't need to be MP_WEAK.

Furthermore, led_state and led0_state are private to ui.c so can be made
static.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-09 13:24:08 +10:00
Damien George
bd5152c928 stm32/mboot: Add board-configurable SysTick hook.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-09 13:24:08 +10:00
Damien George
313f082896 tools/ci.sh: Build native .mpy examples for armv7emsp, xtensawin in CI.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-09 13:24:08 +10:00
Damien George
abb3850398 tools/mpy_ld.py: Support R_XTENSA_PDIFF32 relocation.
Newer versions of the ESP-IDF's toolchain use this relocation.

Fixes issue #8436.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-09 11:57:22 +10:00
Damien George
85597aa68e esp32/machine_pin: Only expose IO20 on esp32 for IDF 4.3.2 and above.
This IO was enabled in IDF commit 68f8b999bb69563f2f3d1d897bc073968f41f3bf,
which is available in IDF release v4.3.2 and above.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-08 18:29:01 +10:00
Damien George
6a1dbaad1c tools/ci.sh: Build NUCLEO_H743ZI with -O2 optimisation level.
This tests the build when -O2 is used, which can lead to additional
compiler analysis and warnings.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-08 15:00:59 +10:00
Damien George
182256dc13 tests/stress: Adjust bytecode_limit test so it can SKIP if no memory.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-08 15:00:59 +10:00
Damien George
c7271a86ca py/makemoduledefs.py: Remove shebang line and adjust style of comment.
This file is not executable so shouldn't have the shebang line.  This line
can cause issues when building on Windows msvc when the PyPython variable
is set to something other than "python", because it reverts back to using
the shebang line.

The top comment is also changed to """ style which matches all other
preprocessing scripts in the py/ directory.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-08 15:00:59 +10:00
Damien George
cbad559366 py/compile: Give the compiler a hint about num nodes being non-zero.
Without this, newer versions of gcc (eg 11.2.0) used with -O2 can warn
about `q_ptr` being maybe uninitialized, because it doesn't know that there
is at least one qstr being written in to this (alloca'd) memory.

As part of this, change the type of `n` to `size_t` so the compiler knows
it's unsigned and can generate better code.

Code size change for this commit:

       bare-arm:   -28 -0.049%
    minimal x86:    -4 -0.002%
       unix x64:    +0 +0.000%
    unix nanbox:   -16 -0.003%
          stm32:   -24 -0.006% PYBV10
         cc3200:   -32 -0.017%
        esp8266:    +8 +0.001% GENERIC
          esp32:   -52 -0.003% GENERIC
            nrf:   -24 -0.013% pca10040
            rp2:   -32 -0.006% PICO
           samd:   -28 -0.020% ADAFRUIT_ITSYBITSY_M4_EXPRESS

Signed-off-by: Damien George <damien@micropython.org>
2022-06-08 14:59:43 +10:00
iabdalkader
a4eef90b22 extmod/modusocket: Fix polling of closed sockets.
Unbound sockets in NEW state should return HUP|WR when polled, and return
NVAL when in CLOSED state.
2022-06-08 14:15:01 +10:00
iabdalkader
70bf6ab6fb extmod/modusocket: Add socket state to track new/listening/conn/closed. 2022-06-08 14:13:59 +10:00
Damien George
bd375df02c extmod/extmod.cmake: Require components to be explicitly enabled.
Otherwise include directories are added unconditionally to the build
variables if the component (submodule) is checked out.  This can lead to,
eg, the esp32 build using lib/lwip header files, instead of lwip header
files from the IDF.

Fixes issue #8727.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-08 13:03:34 +10:00
Damien George
e8e8c7c354 extmod/modurandom: Fix missing void in empty argument list.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 23:41:49 +10:00
Damien George
ac3fb974bc unix/variants: Enable seeding random module on import in dev, coverage.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 23:41:49 +10:00
Damien George
d2f018bff1 unix,windows: Factor out code that generates random bytes to a new func.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 23:41:30 +10:00
stijn
5bb2a85d74 windows: Use BCryptGenRandom to implement os.urandom.
Fix urandom not working on windows (there's no /dev/urandom) by using
a proper cryptographic random function (same one as CPython >= 3.11).
2022-06-07 23:32:30 +10:00
Damien George
5290bfaefe tools/mpremote: Bump version to 0.3.0.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 23:23:14 +10:00
Damien George
646fcdadbf tools/mpremote: Add command to print the version.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 23:22:04 +10:00
robert-hh
5cc2dd4f5d mimxrt/machine_uart: Fix an inconsistency for UART.init() arg handling.
With keyword arguments only or just a single non-keyword argument,
UART.init() did not perform the settings.
2022-06-07 18:21:46 +10:00
Clayton Mills
767f2ce9a7 stm32/usbd_conf: Remove disable of SYSCFG clock.
System config block contains hardware unrelated to USB.  So calling
`__SYSCFG_CLK_DISABLE()` during `HAL_PCD_MspDeInit()` has an adverse effect
on other system functionality.

Removing call to `__SYSCFG_CLK_DISABLE()` to rectify this issue.

This call was there since the beginning of the USB CDC code, added in
b30c02afa0.
2022-06-07 18:09:58 +10:00
Clayton Mills
0d8d911950 stm32/powerctrl: Disable sys tick interrupt in stop mode on some STM32s.
According to ST Errata ES0206 Rev 18, Section 2.2.1, on STM32F427x,
STM32F437x, STM32F429x and STM32F439x.

If the system tick interrupt is enabled during stop mode while certain
bits are set in the DBGMCU_CR, then the system will immediately wake
from stop mode.

Suggested workaround is to disable system tick timer interrupt when
entering stop mode.

According to ST Errate ES0394 Rev 11, Section 2.2.17, on STM32WB55Cx and
STM32WB35Cx.

If the system tick interrupt is enabled during stop 0, stop 1 or stop 2
while certain bits are set in DBGMCU_CR, then system will immediately
wake from stop mode but the system remains in low power state. The CPU
therefore fetches incorrect data from inactive Flash, which can cause a
hard fault.

Suggested workaround is to disable system tick timer interrupt when
entering stop mode.
2022-06-07 18:08:02 +10:00
Damien George
14105ff5b1 stm32/machine_i2c: Enable timingr constructor keyword on H7 MCUs.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 17:05:05 +10:00
Damien George
a0dae1dda2 stm32/flash: Remove FLASH_OPTR_DBANK condition in L4, H7 get_bank func.
This was added by mistake in 8f68e26f79 when
adding support for G4 MCUs, which does not using this get_bank() function.

FLASH_OPTR_DBANK is only defined on G4 and L4 MCUs, so on H7 this
FLASH_BANK_2 code was being wrongly excluded.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 16:55:18 +10:00
Damien George
2fb413b265 tools/mpy-tool.py: Improve generated frozen identifiers.
Frozen identifiers now include their full name hierarchy, eg their class
name.  This makes it easier to understand the generated code.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 16:55:18 +10:00
Damien George
1d143cec63 tests/basics: Add .exp file for sys.tracebacklimit test.
The sys.tracebacklimit feature has changed semantics a bit from CPython 3.7
(in the way it modifies the output), so provide a .exp file for the test so
it doesn't rely on CPython.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 16:55:18 +10:00
Damien George
9670a156da all: Rename MICROPY_PY_WIZNET5K to MICROPY_PY_NETWORK_WIZNET5K.
To match MICROPY_PY_NETWORK_CYW43 and MICROPY_PY_NETWORK_NINAW10.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 16:55:18 +10:00
Damien George
66dfe17b18 rp2/CMakeLists: Simplify qstr sources when enabling extmod components.
Also remove redundant modusocket.c and modnetwork.c sources, they are
already added by extmod/extmod.cmake.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 16:55:18 +10:00
Damien George
a446a7bdef rp2/mpnetworkport: Fix lwip alarm callback timing to use microseconds.
The callback passed to add_alarm_in_ms must return microseconds, even
though the initial delay is in milliseconds.  Fix this use, and to avoid
further confusion use the add_alarm_in_us function instead.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 16:55:18 +10:00
Damien George
c58dc7f091 pic16bit: Use 1 byte for qstr hash len and include header to fix build.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 16:55:18 +10:00
Damien George
bf92b0cbf2 tools/ci.sh: Add test for mpy-tool's merging feature.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 13:51:45 +10:00
Damien George
599a22e569 tools/mpy-tool.py: Rework .mpy merging feature.
Now that the native qstr link table is gone, merging a native .mpy file
with a bytecode .mpy file is not as simple as concatenating the .mpy data.
The qstr_table and obj_table tables from all merged .mpy files must now be
joined together, because they are global to the .mpy file (and hence global
to the merged .mpy file).  This means the bytecode needs to be be decoded,
qstr_table and obj_table indices updated to point to the correct entries in
the new tables, and then the bytecode re-encoded.

This commit makes this change to the merging feature in mpy-tool.py.  This
can now merge an arbitrary number of bytecode .mpy files, and up to one
native .mpy file.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 13:51:45 +10:00
Damien George
f506bf342a py/bc: Remove unused mp_opcode_format function.
This was made redundant by f2040bfc7e, which
also did not update this function for the change to qstr-opcode encoding,
so it does not work correctly anyway.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 13:32:38 +10:00
Damien George
b37b578214 py/persistentcode: Remove remaining native qstr linking support.
Support for architecture-specific qstr linking was removed in
d4d53e9e11, where native code was changed to
access qstr values via qstr_table.  The only remaining use for the special
qstr link table in persistentcode.c is to support native module written in
C, linked via mpy_ld.py.  But native modules can also use the standard
module-level qstr_table (and obj_table) which was introduced in the .mpy
file reworking in f2040bfc7e.

This commit removes the remaining native qstr liking support in
persistentcode.c's load_raw_code function, and adds two new relocation
options for constants.qstr_table and constants.obj_table.  mpy_ld.py is
updated to use these relocations options instead of the native qstr link
table.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 13:19:55 +10:00
iabdalkader
2111ca0b8f rp2/boards/ARDUINO_NANO_RP2040_CONNECT: Update USB PID.
This PID is allocated for the Arduino Nano RP2040 running MicroPython.
2022-06-03 16:12:44 +10:00
Andrew Leech
b92e51efe7 tools/ci.sh: Add build of W5100S_EVB_PICO board to rp2 CI.
This exercises the inclusion of a number of libraries in the rp2 port
including mbedtls and lwip.

Signed-off-by: Andrew Leech <andrew@alelec.net>
2022-06-03 14:35:52 +10:00
Andrew Leech
b7a39ad2d1 tests/run-multitests.py: Read IP address from boot nic if available.
This works if your network is pre-configured in boot.py as an object called
"nic".  Without this, multitests expects to access the WLAN/LAN class which
isn't always correct.

Signed-off-by: Andrew Leech <andrew@alelec.net>
2022-06-03 14:35:37 +10:00
Andrew Leech
73a1ea8812 tests/net_inet: Remove broken api.telegram.org from tests.
Signed-off-by: Andrew Leech <andrew@alelec.net>
2022-06-03 14:34:29 +10:00
Andrew Leech
4188bbd3d3 extmod/modussl_mbedtls: Poll EVENT_POLL_HOOK in ssl handshake loop.
Otherwise this is essentially an infinite loop on ports that do not use
interrupts to service network interfaces.

Signed-off-by: Andrew Leech <andrew@alelec.net>
2022-06-03 14:34:29 +10:00
Andrew Leech
ffe5f2efe2 rp2/Makefile: Build in debug mode with "make DEBUG=1".
Signed-off-by: Andrew Leech <andrew@alelec.net>
2022-06-03 14:34:29 +10:00
Andrew Leech
1b80aa9ce3 rp2/boards/W5100S_EVB_PICO: Add Wiznet W5100S-EVB-Pico board.
Signed-off-by: Andrew Leech <andrew@alelec.net>
2022-06-03 14:34:29 +10:00
Andrew Leech
bca816f5ac rp2: Add support for using Wiznet hardware as an Ethernet NIC.
Uses the extmod/network_wiznet5k driver to provide network connectivity.

Signed-off-by: Andrew Leech <andrew@alelec.net>
2022-06-03 14:34:29 +10:00
Andrew Leech
15fea3a1ff rp2: Integrate lwIP network stack.
Signed-off-by: Andrew Leech <andrew@alelec.net>
2022-06-03 14:34:18 +10:00
Andrew Leech
7d9cc69645 rp2/Makefile: Use cmake for "make submodules" task when needed.
Because the submodule list can be updated by cmake files.

Signed-off-by: Andrew Leech <andrew@alelec.net>
2022-06-03 14:29:11 +10:00
Andrew Leech
21b3a396de extmod/network_wiznet5k: Add Wiznet Ethernet network interface.
Originally based on both stm32/network_wiznet5k and stm32/modnwwiznet5k.

If MICROPY_PY_LWIP is enabled it uses the lwIP TCP stack in MicroPython,
communicating with the Wiznet controller in MACRAW mode.  In this mode it
supports using the INTN pin from Wiznet controller to receive data from an
interrupt trigger.

If lwIP is not enabled, it runs in modnetwork/socket mode providing an
interface to the TCP stack running on the Wiznet controller chip.  In this
mode it includes some updates by @irinakim12 from #8021, most notably
bringing in DHCP support.

Supports defining hardware pins in board config or dynamically set at
runtime.  Sets a default MAC address in the random namespace from board
unique-id.

Signed-off-by: Andrew Leech <andrew@alelec.net>
2022-06-03 14:29:11 +10:00
Andrew Leech
cb436e357f lib/wiznet5k: Add submodule for Wiznet Ethernet drivers.
Signed-off-by: Andrew Leech <andrew@alelec.net>
2022-06-03 14:29:11 +10:00
Andrew Leech
05f927b624 rp2/machine_pin: Add mp_hal_pin_interrupt C interface.
So C can can easily configure a pin interrupt and callback.

Signed-off-by: Andrew Leech <andrew@alelec.net>
2022-06-03 14:29:11 +10:00
Andrew Leech
9bd6169b72 rp2/mbedtls: Add support for ssl module with MICROPY_SSL_MBEDTLS.
Signed-off-by: Andrew Leech <andrew@alelec.net>
2022-06-03 14:29:06 +10:00
Andrew Leech
494e8ba722 nrf/mpconfigport: Fix MICROPY_VFS IO build support. 2022-06-03 12:39:43 +10:00
Andrew Leech
c5878dd1f9 nrf/mpconfigport: Enable extra features as defined by ROM levels.
This commit enables extra features from the ROM levels and further
simplifies mpconfigport.h.  The changes are:

- NRF51822 & BLUETOOTH_SD -> MICROPY_CONFIG_ROM_LEVEL_MINIMUM
    - no changes

- NRF51822 -> MICROPY_CONFIG_ROM_LEVEL_CORE_FEATURES
    - MICROPY_PY_IO = 1

- NRF52832 -> MICROPY_CONFIG_ROM_LEVEL_BASIC_FEATURES
    - MICROPY_PY_IO = 1

- NRF52840, NRF9160 -> MICROPY_CONFIG_ROM_LEVEL_EXTRA_FEATURES
    - MICROPY_COMP_MODULE_CONST = 1
    - MICROPY_COMP_TRIPLE_TUPLE_ASSIGN = 1
    - MICROPY_OPT_MPZ_BITWISE = 1
    - MICROPY_PY_ALL_SPECIAL_METHODS = 1
    - MICROPY_PY_BUILTINS_EXECFILE = 1
    - MICROPY_PY_BUILTINS_SLICE_ATTRS = 1
    - MICROPY_PY_BUILTINS_STR_CENTER = 1
    - MICROPY_PY_BUILTINS_STR_PARTITION = 1
    - MICROPY_PY_BUILTINS_STR_SPLITLINES = 1
    - MICROPY_PY_CMATH = 1
    - MICROPY_PY_COLLECTIONS_ORDEREDDICT = 1
    - MICROPY_PY_FRAMEBUF = 1
    - MICROPY_PY_IO = 1
    - MICROPY_PY_MATH_SPECIAL_FUNCTIONS = 1
    - MICROPY_PY_SYS_STDIO_BUFFER = 1
    - MICROPY_PY_UCTYPES = 1
    - MICROPY_PY_UHEAPQ = 1
    - MICROPY_PY_UJSON = 1
    - MICROPY_PY_URE = 1
    - MICROPY_PY_UZLIB = 1
    - MICROPY_REPL_EMACS_KEYS = 1
2022-06-03 12:37:12 +10:00
Andrew Leech
13f5d38f2e nrf/mpconfigport: Set MICROPY_CONFIG_ROM_LEVEL defines for each MCU.
This commit is a no-op change to simplify existing config.
2022-06-03 12:36:40 +10:00
Andrew Leech
8fb01be6cf stm32/rfcore: Remove extra layer of buffering on BLE IPCC.
Whole packets are now pushed up to the higher layer of the BLE stack,
instead of buffering the packets so individual bytes can be requested.
2022-06-03 11:58:43 +10:00
Andrew Leech
91fb9e7888 extmod/nimble: Add support for reading whole HCI UART packets.
This can improve efficiency for Bluetooth systems that already process
whole packets at the lower layers.
2022-06-03 11:53:28 +10:00
Takeo Takahashi
19c680ff57 test/renesas-ra: Remove unsupported feature test of Pin.
Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-06-03 10:58:16 +10:00
Takeo Takahashi
dd83f48fb2 renesas-ra/machine_pin: Remove code for unsupported Pin features.
Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-06-03 10:57:48 +10:00
robert-hh
a0432ed9cb mimxrt: Update port to work with new nxp_driver v2.10.
The nxp_driver v2.10 allows for/requires some changes to the code:

- Remove some part of pwm_backlog.*, which is provided by the lib now.
- Change eth.c: the newer versions have additional parameters of the
  library versions.
- Change sdcard.c: use TransferBlocking instead of TransferNonblocking.
- Add some support for the MIMXRT1176 device.
- Set the clocks for UART, I2C, Timer.
- Integrate the I2S module and fix a rebase error.
- Use blocking transfer only for SPI.  It's faster and interferes less with
  other modules.
- Use the clock_config.c files of library v2.8.5.  The mimxrt files keeps
  the clock_config.c files from Verson 2.8.5.  With clock_config.c from
  v2.10, the boards do not work.  Refactoring of the clock set-up is on the
  to-do list.
- Enable expiry timers for UART, I2C and SPI, avoiding a stall in library
  code.
- The clock_config.* files are moved from the board-specific directories to
  the boards directory and given a MCU related name.
2022-06-03 10:48:49 +10:00
robert-hh
dbe8b0c0ca lib/nxp_driver: Update nxp_driver to v2.10. 2022-06-03 10:48:04 +10:00
iabdalkader
364569d25f drivers/lsm6dsox: Add support for SPI mode. 2022-06-03 01:24:51 +10:00
Damien George
a1afb337d2 extmod/uasyncio: Fix edge case for cancellation of wait_for.
This fixes the cases where the task being waited on finishes just before or
just after the wait_for itself is cancelled.

Fixes issue #8717.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-02 17:14:20 +10:00
Damien George
efe23aca71 all: Remove third argument to MP_REGISTER_MODULE.
It's no longer needed because this macro is now processed after
preprocessing the source code via cpp (in the qstr extraction stage), which
means unused MP_REGISTER_MODULE's are filtered out by the preprocessor.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-02 16:31:37 +10:00
Damien George
47f634300c py: Change makemoduledefs process so it uses output of qstr extraction.
This cleans up the parsing of MP_REGISTER_MODULE() and generation of
genhdr/moduledefs.h so that it uses the same process as compressed error
string messages, using the output of qstr extraction.

This makes sure all MP_REGISTER_MODULE()'s that are part of the build are
correctly picked up.  Previously the extraction would miss some (eg if you
had a mod.c file in the board directory for an stm32 board).

Build speed is more or less unchanged.

Thanks to @stinos for the ports/windows/msvc/genhdr.targets changes.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-02 16:29:53 +10:00
Damien George
340872cfdd stm32/boards/LEGO_HUB_NO6: Add helper scripts to update app firmware.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-02 15:22:16 +10:00
Damien George
87ca431f3f stm32/boards/LEGO_HUB_NO6: Implement robust filesystem-load updates.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-02 14:30:51 +10:00
Damien George
d84ebc31f7 stm32/boards/LEGO_HUB_NO6: Use multi-colour LED for mboot status.
This gives more information to the user when doing updates from SPI flash.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-02 14:30:51 +10:00
Damien George
fae9205594 stm32/boards/LEGO_HUB_NO6: Add support for mboot to access SPI flash.
The following changes are made:
- Use software SPI for external SPI flash access when building mboot.
- Enable the mboot filesystem-loading feature, with FAT FS support.
- Increase the frequency of the CPU when in mboot to 96MHz, to increase the
  speed of SPI flash accesses and programming.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-02 14:30:51 +10:00
Damien George
36211baf0e stm32/boards/LEGO_HUB_NO6: Make all SPI flash transfers use 32-bit addr.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-02 14:30:51 +10:00
Damien George
87fbceef26 stm32/mboot: Pass initial_r0 to early-init and get-reset-mode funcs.
This allows a board to modify initial_r0 if needed.

Also make default board behaviour functions always available, named as
mboot_get_reset_mode_default and mboot_state_change_default.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-02 14:30:51 +10:00
Damien George
e64947dc90 stm32/mboot: Make 0x70ad0000 values named constants with macros.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-02 14:30:51 +10:00
Damien George
9246099935 stm32/mboot: Add update_app_elements to return mboot fsload elements.
In case the elements should not be passed directly to machine.bootloader.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-02 14:30:51 +10:00
Damien George
1296a01f4c stm32/mboot: Move remaining led_state_all call into mboot_state_change.
This was missed in b2deea6762

Signed-off-by: Damien George <damien@micropython.org>
2022-06-02 14:30:51 +10:00
Damien George
54f1694ab6 drivers/bus: Rename MP_SPI_ADDR_IS_32B to MICROPY_HW_SPI_ADDR_IS_32BIT.
And allow it to be configured externally, if needed.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-02 14:30:51 +10:00
Jared Hancock
2f4aca0381 mimxrt/mphalport: Fix strict aliasing error with unique id. 2022-06-02 12:50:14 +10:00
Damien George
6bda80d811 esp32/machine_i2c: Implement write-then-read I2C transfers.
I2C transfers are much more efficient if they are combined, instead of
doing separate writes and reads.

Fixes issue #7134.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-01 13:20:30 +10:00
Damien George
4a1ae99ac3 extmod/machine_i2c: Add optional support for write-then-read transfers.
This option is useful for ports where it's more efficient to do a full I2C
transfer in one go.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-01 13:20:27 +10:00
Andrew Leech
ea9a904b72 docs/reference/manifest: Add link to details about opt-level for freeze. 2022-05-27 14:45:46 +10:00
robert-hh
1df7678674 mimxrt/boards: Extend the deploy_teensy.md instructions. 2022-05-27 13:23:46 +10:00
robert-hh
c7accf7666 mimxrt/boards/OLIMEX_RT1010: Document the initial deploy procedure.
The procedure given here will work whether or not the DevKit motherboard is
used and is equipped with the support MCU.  It is laborious but works.
2022-05-27 13:23:46 +10:00
robert-hh
f795d5bc38 docs/mimxrt: Move the pinout tables to a separate document.
This shortens the quickref.  Also change the note about the hardware SPI
frequeny limits.
2022-05-27 12:48:16 +10:00
robert-hh
eda52e4d73 docs/mimxrt: Add i.MX RT1015 to general.rst, and a few clarifications. 2022-05-27 12:47:54 +10:00
Damien George
065df5568c tests: Move native while test from pybnative to micropython.
And make it so this test can run on any target.

LED and time testing has been removed from this test, that can now be
tested using: ./run-tests.py --via-mpy --emit native.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-26 12:54:43 +10:00
Damien George
20d9f3409a tests/run-tests.py: Add rp2 test target.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-26 12:54:43 +10:00
Damien George
80a86c48e3 tests/micropython: Make import_mpy_native test run on all architectures.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-26 12:54:43 +10:00
Damien George
3180113aef tests/micropython: Make import_mpy_native_gc run on ARMv6-M and above.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-26 12:23:49 +10:00
Damien George
4290d51320 py/emitinlinethumb: Make float instruction use dynamically selectable.
This allows mpy-cross to dynamically select whether ARMv7-M float
instructions are supported in @micropython.asm_thumb functions.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-26 12:22:07 +10:00
Damien George
cca08922d9 py/emitinlinethumb: Make ARMv7-M instruction use dynamically selectable.
This follows on from a5324a1074 and allows
mpy-cross to dynamically select whether ARMv7-M instructions are supported
in @micropython.asm_thumb functions.

The config option MICROPY_EMIT_INLINE_THUMB_ARMV7M is no longer needed, it
is now controlled by MICROPY_EMIT_THUMB_ARMV7M.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-26 11:54:48 +10:00
Damien George
1d047617bb tools/mpy-tool.py: Remove obsolete unicode flag in .mpy header.
This was removed in c49d5207e9

Signed-off-by: Damien George <damien@micropython.org>
2022-05-26 11:43:46 +10:00
iabdalkader
4946dc5f8c teensy/mpconfigport.h: Remove obsolete macros. 2022-05-26 11:17:46 +10:00
iabdalkader
0bdfceacbe extmod/network_ninaw10: Add support for socket events callback. 2022-05-26 11:15:07 +10:00
iabdalkader
be83bdf9ec drivers/ninaw10: Update driver to support firmware 1.5.0.
* Firmware 1.5.0 introduces a new BSD-like sockets ABI,
which improves the integration with MicroPython.
2022-05-25 16:05:50 +02:00
iabdalkader
875caca504 rp2/boards/ARDUINO_NANO_RP2040_CONNECT: Enable webrepl. 2022-05-25 16:05:50 +02:00
iabdalkader
a22d0bda52 rp2/boards/ARDUINO_NANO_RP2040_CONNECT: Disable internal errno.
* Internal errno can't be used with Nina module due to an issue
with esp-idf config.
2022-05-25 16:05:50 +02:00
iabdalkader
4bcffbd1c6 rp2/mpconfigport.h: Allow boards to override internal errno config. 2022-05-25 16:05:50 +02:00
iabdalkader
d037e75991 rp2/mpconfigport.h: Enable static scheduler nodes. 2022-05-25 16:05:50 +02:00
Damien George
6e71cde6aa ports: Use default VFS config for import_stat and builtin_open.
For ports with MICROPY_VFS and MICROPY_PY_IO enabled their configuration
can now be simplified to use the defaults for mp_import_stat and
mp_builtin_open.

This commit makes no functional change, except for the following minor
points:
- the built-in "open" is removed from the minimal port (it previously did
  nothing)
- the duplicate built-in "input" is removed from the esp32 port
- qemu-arm now delegates to VFS import/open

Signed-off-by: Damien George <damien@micropython.org>
2022-05-25 13:04:45 +10:00
Damien George
5956466c0e py/builtin: Clean up and simplify import_stat and builtin_open config.
The following changes are made:

- If MICROPY_VFS is enabled then mp_vfs_import_stat and mp_vfs_open are
  automatically used for mp_import_stat and mp_builtin_open respectively.

- If MICROPY_PY_IO is enabled then "open" is automatically included in the
  set of builtins, and points to mp_builtin_open_obj.

This helps to clean up and simplify the most common port configuration.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-25 13:04:45 +10:00
Damien George
26b1d31eda Revert "stm32/rfcore: Intercept addr-resolution HCI cmd to work arou..."
This reverts commit 2668337f36.

The issue with potential breaking of the BLE RX path in the radio is fixed
since WS v1.12.0.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-25 11:02:35 +10:00
iabdalkader
edf41d2bf8 extmod/modusocket: Add sendall function. 2022-05-25 00:19:41 +10:00
iabdalkader
b9d2f1e844 extmod/modusocket: Add timeout and callback to socket object. 2022-05-25 00:19:41 +10:00
iabdalkader
6841fecbb2 extmod/modusocket: Fix socket_make_new argument parsing. 2022-05-25 00:19:40 +10:00
iabdalkader
3438e80060 extmod/modusocket: Add support for socket events callback.
Add support for the special sockopt 20.
2022-05-25 00:18:33 +10:00
iabdalkader
fc1f876175 extmod/modusocket: Add socket type print function. 2022-05-25 00:18:28 +10:00
iabdalkader
eb957b0c95 extmod/modusocket: Fix errcode returned from socket read/write.
Drivers should ensure a positive errcode is returned from read/write.
2022-05-25 00:18:18 +10:00
iabdalkader
6136c7644a extmod/modusocket: Bind unconnected socket to default NIC in setsockopt.
Bind socket to default NIC if setsockopt is called before the socket is
bound, to allow setting SO_REUSEADDR before calling socket_bind().

Fixes issue #8653.
2022-05-25 00:16:32 +10:00
iabdalkader
7b4147dd0b extmod/modusocket: Fix polling of a new socket.
New sockets should return HUP and WR when polled, following modlwip.
2022-05-25 00:12:42 +10:00
Takeo Takahashi
79f3b8731b renesas-ra/modmachine: Add missing MP_REGISTER_MODULE for umachine.
Fix the issue that umachine is not available.

Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-05-25 00:05:30 +10:00
Damien George
aa53d2f84a py/asmthumb: Provide implementations of clz/ctz for msvc.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-24 22:27:18 +10:00
robert-hh
dd35f76db3 tests/run-multitests.py: Use LAN for IP address if WLAN doesn't exist.
This allows running the test on boards with just a LAN interface.

Fixes issue #8681.
2022-05-24 13:21:05 +10:00
iabdalkader
beeb250d58 tests/multi_net: Fix TCP accept test when using system error numbers.
If a port is not using internal error numbers, which match both lwIP and
Linux error numbers, ENTOCONN from standard libraries errno.h equals 128,
not 107.
2022-05-24 13:15:22 +10:00
iabdalkader
6b6ceafe1a extmod/webrepl: Fix setting password in foreground mode and factor code.
The password was not being set when running in foreground mode.  Duplicate
code has been removed.
2022-05-24 13:12:40 +10:00
Damien George
5fa8ea1b8b tests/extmod: Change expected errno code from 36 to 30 in VfsLfs2 test.
Errno 30 is EROFS, which is now the correct value reported by littlefs 2.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-24 12:52:00 +10:00
Damien George
9269835226 lib/littlefs: Remove assignment of variables to themselves.
To prevent compiler warnings (eg on clang).

Signed-off-by: Damien George <damien@micropython.org>
2022-05-24 12:51:49 +10:00
Damien George
3a544b832b lib/littlefs: Guard lfs2_file_rawopen with LFS2_NO_MALLOC.
To prevent warnings about this function being unused when malloc is
disabled.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-24 12:51:17 +10:00
Damien George
115a23da24 lib/littlefs: Update littlefs2 to v2.5.0.
At commit 40dba4a556e0d81dfbe64301a6aa4e18ceca896c

Signed-off-by: Damien George <damien@micropython.org>
2022-05-24 12:51:17 +10:00
David Lechner
d42d35f56d tests/run-tests.py: Enable -X realtime option for macOS tests.
This enables the new `-X realtime` runtime option when running tests on
macOS.  This causes MicroPython to configure all threads to be high
priority so that they are allowed to use high precision timers.  This
makes tests that depend on the passage of time more likely to succeed.

CI tests that were disabled because of this are now enabled again.

Signed-off-by: David Lechner <david@pybricks.com>
2022-05-24 00:52:44 +10:00
David Lechner
c012318d74 unix: Implement -X realtime command-line option on macOS.
This adds a new command line option to the unix port `-X realtime` to
enable realtime priority on threads.  This enables high precision timers
for applications that need more accurate timers.

Related docs:
https://developer.apple.com/library/archive/technotes/tn2169/_index.html

Fixes issue #8621.

Signed-off-by: David Lechner <david@pybricks.com>
2022-05-24 00:51:47 +10:00
David Lechner
be5657b64f ports: Rename thread_t to mp_thread_t.
This adds the `mp_` prefix to the `thread_t` type.  The name `thread_t`
conflicts with the same in `mach/mach_types.h` on macOS.

Signed-off-by: David Lechner <david@lechnology.com>
2022-05-24 00:51:23 +10:00
Jim Mussared
75efb3267c extmod: Revert accidental usocket->socket rename.
The registration of the usocket module was accidentally changed to socket
in moving to MP_REGISTER_MODULE in bb794f05b7
2022-05-24 00:43:44 +10:00
Damien George
c1b9d2259e py/dynruntime.mk: Add basic support for armv6m architecture.
The examples/natmod features0 and features1 examples now build and run on
ARMv6-M platforms.  More complicated examples are not yet supported because
the compiler emits references to built-in functions like __aeabi_uidiv.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-23 23:01:25 +10:00
Damien George
0e28a1f0e5 mpy-cross: Add armv6m architecture option.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-23 23:01:25 +10:00
Damien George
17ac68770c py/persistentcode: Select ARMV6M as maximum when __thumb2__ not defined.
If __thumb2__ is defined by the compiler then .mpy files marked as ARMV6M
and above (up to ARMV7EMDP) are supported.  If it's not defined then only
ARMV6M .mpy files are supported.  This makes sure that on CPUs like
Cortex-M0+ (where __thumb2__ is not defined) only .mpy files marked as
ARMV6M can be imported.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-23 23:01:25 +10:00
Damien George
a5324a1074 py/asmthumb: Make ARMv7-M instruction use dynamically selectable.
This commit adjusts the asm_thumb_xxx functions so they can be dynamically
configured to use ARMv7-M instructions or not.  This is available when
MICROPY_DYNAMIC_COMPILER is enabled, and then controlled by the value of
mp_dynamic_compiler.native_arch.

If MICROPY_DYNAMIC_COMPILER is disabled the previous behaviour is retained:
the functions emit ARMv7-M instructions only if MICROPY_EMIT_THUMB_ARMV7M
is enabled.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-23 23:01:12 +10:00
Damien George
7d3204783a tests/run-tests.py: Handle case where mpy-cross fails to compile script.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-23 15:45:21 +10:00
Damien George
a8492253c1 tests/basics: Unlock heap if skipping nanbox small-int test.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-23 15:45:16 +10:00
Damien George
d4d53e9e11 py/emitnative: Access qstr values using indirection table qstr_table.
This changes the native emitter to access qstr values using the qstr
indirection table qstr_table, but only when generating native code that
will be saved to a .mpy file.  This makes the resulting native code fully
static, ie it does not require any fix-ups or rewriting when it is
imported.

The performance of native code is more or less unchanged.  Benchmark
results on PYBv1.0 (using --via-mpy and --emit native) are:

N=100 M=100          baseline -> this-commit     diff      diff% (error%)
bm_chaos.py            407.16 ->     411.85 :   +4.69 =  +1.152% (+/-0.01%)
bm_fannkuch.py         100.89 ->     101.20 :   +0.31 =  +0.307% (+/-0.01%)
bm_fft.py             3521.17 ->    3441.72 :  -79.45 =  -2.256% (+/-0.00%)
bm_float.py           6707.29 ->    6644.83 :  -62.46 =  -0.931% (+/-0.00%)
bm_hexiom.py            55.91 ->      55.41 :   -0.50 =  -0.894% (+/-0.00%)
bm_nqueens.py         5343.54 ->    5326.17 :  -17.37 =  -0.325% (+/-0.00%)
bm_pidigits.py         603.89 ->     632.79 :  +28.90 =  +4.786% (+/-0.33%)
core_qstr.py            64.18 ->      64.09 :   -0.09 =  -0.140% (+/-0.01%)
core_yield_from.py     313.61 ->     311.11 :   -2.50 =  -0.797% (+/-0.03%)
misc_aes.py            654.29 ->     659.75 :   +5.46 =  +0.834% (+/-0.02%)
misc_mandel.py        4205.10 ->    4272.08 :  +66.98 =  +1.593% (+/-0.01%)
misc_pystone.py       3077.79 ->    3128.39 :  +50.60 =  +1.644% (+/-0.01%)
misc_raytrace.py       388.45 ->     393.71 :   +5.26 =  +1.354% (+/-0.01%)
viper_call0.py         576.83 ->     566.76 :  -10.07 =  -1.746% (+/-0.05%)
viper_call1a.py        550.39 ->     540.12 :  -10.27 =  -1.866% (+/-0.11%)
viper_call1b.py        438.32 ->     432.09 :   -6.23 =  -1.421% (+/-0.11%)
viper_call1c.py        442.96 ->     436.11 :   -6.85 =  -1.546% (+/-0.08%)
viper_call2a.py        536.31 ->     527.37 :   -8.94 =  -1.667% (+/-0.04%)
viper_call2b.py        378.99 ->     377.50 :   -1.49 =  -0.393% (+/-0.08%)

Signed-off-by: Damien George <damien@micropython.org>
2022-05-23 15:43:06 +10:00
Damien George
94955e8e3d py/asm: Add ASM_LOAD16_REG_REG_OFFSET macro for load-u16 with offset.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-23 14:21:16 +10:00
Damien George
8af5e2551f py/asmarm: Add asm_arm_ldrh_reg_reg_offset() helper func.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-23 14:21:16 +10:00
Damien George
94ae023136 py/asmthumb: Add asm_thumb_ldrh_reg_reg_i12_optimised() helper func.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-23 14:21:14 +10:00
Damien George
689138d484 py/asmthumb: Fix offset variable name in ldr, ldrh and strh functions.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-23 14:20:10 +10:00
Damien George
7883ae413d py/emitnative: Provide dedicated local for exception unwind handler ptr.
This eliminates the need to save and restore the exception unwind handler
pointer when calling nlr_push.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-19 17:31:56 +10:00
Damien George
b608964804 py/emitnative: Simplify generation of code that loads prelude pointer.
It's possible to use REG_PARENT_ARG_1 instead of REG_LOCAL_3.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-19 17:31:56 +10:00
Damien George
56f2d3c2e5 py/asmthumb: Fix PC relative load by sign extending the constant.
PC relative offsets can be negative, in which case the movw result must be
sign extended.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-19 17:31:56 +10:00
Damien George
c70f96f1c5 esp32: Track allocated iRAM and free it on soft reset.
This makes sure all iRAM allocated for native code is freed on soft reset.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-19 17:31:56 +10:00
Damien George
54ab9d23e9 tests/run-perfbench.py: Allow running tests via mpy and native emitter.
The performance benchmark tests now support `--via-mpy` and `--emit native`
on remote targets.  For example:

    $ ./run-perfbench.py -p --via-mpy --emit native 100 100

Signed-off-by: Damien George <damien@micropython.org>
2022-05-19 17:31:56 +10:00
Damien George
1786dacc83 tests/run-tests.py: Allow running tests via mpy-cross on remote targets.
This adds support for the `--via-mpy` and `--emit native` options when
running tests on remote targets (via pyboard.py).  It's now possible to do:

    $ ./run-tests.py --target pyboard --via-mpy
    $ ./run-tests.py --target pyboard --via-mpy --emit native

Signed-off-by: Damien George <damien@micropython.org>
2022-05-19 17:31:56 +10:00
Daniël van de Giessen
ef16796f49 esp32/machine_pin: Fix ESP32C3 IDFv4.4.1 build.
Use new constants as seen in ESP-IDF commit b25fb1.

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2022-05-19 16:47:13 +10:00
Algy Tynan
5dac142a1a esp32/boards/LILYGO_TTGO_LORA32: Remove ID from TTGO Lora32 board json.
Generic ID creates an incorrect link on the MicroPython download page.
Remove the ID to fix the link.

Signed-off-by: Algy Tynan <algy@tynan.io>
2022-05-19 16:45:18 +10:00
Michael Himing
a1abf51a9d esp32/boards/UM_FEATHERS3: Use correct sdkconfig.board. 2022-05-19 16:43:59 +10:00
Christian Zietz
e92c22a839 esp8266/etshal.h: Remove unneeded function declaration. 2022-05-19 16:40:39 +10:00
Christian Zietz
ea1c0557e5 esp8266/machine_wdt: Remove deinit method for watchdog.
Reasons for removal:
- It did not work properly because it stopped the hardware watchdog
  timer while keeping the software watchdog running (issue #8597).
- There isn't a deinit method for the WDT in any other port.
- "The watchdog is not intended to be stopped. That is a feature."
  (See #8600.)
2022-05-19 16:40:39 +10:00
Jim Mussared
8b201dc4c3 py: Remove support for MICROPY_PORT_BUILTIN_MODULES.
This functionality is now replaced with MP_REGISTER_MODULE.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:57:09 +10:00
Jim Mussared
c2d889fc1e renesas-ra: Make port-specific modules use MP_REGISTER_MODULE.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:57:09 +10:00
Jim Mussared
1d33ceb0d0 cc3200: Make port-specific modules use MP_REGISTER_MODULE.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:57:09 +10:00
Jim Mussared
9e4da2320a javascript: Make port-specific modules use MP_REGISTER_MODULE.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:57:09 +10:00
Jim Mussared
ec2fe5d6ca zephyr: Make port-specific modules use MP_REGISTER_MODULE.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:57:09 +10:00
Jim Mussared
63431a5536 unix: Make port-specific modules use MP_REGISTER_MODULE.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:57:09 +10:00
Jim Mussared
d0307e79bb teensy: Make port-specific modules use MP_REGISTER_MODULE.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:57:09 +10:00
Jim Mussared
c3f7424a57 samd: Make port-specific modules use MP_REGISTER_MODULE.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:57:09 +10:00
Jim Mussared
62f00a43d5 rp2: Make port-specific modules use MP_REGISTER_MODULE.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:57:09 +10:00
Jim Mussared
60c5968f99 pic16bit: Make port-specific modules use MP_REGISTER_MODULE.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:57:09 +10:00
Jim Mussared
f67ac90fa9 nrf: Make port-specific modules use MP_REGISTER_MODULE.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:57:09 +10:00
Jim Mussared
7d79fd7e8b mimxrt: Make port-specific modules use MP_REGISTER_MODULE.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:56:30 +10:00
Jim Mussared
4274b34d6b esp8266: Make port-specific modules use MP_REGISTER_MODULE.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:56:30 +10:00
Jim Mussared
24127a4ac4 esp32: Make port-specific modules use MP_REGISTER_MODULE.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:56:30 +10:00
Jim Mussared
0a92469c10 stm32: Make port-specific modules use MP_REGISTER_MODULE.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:56:30 +10:00
Jim Mussared
bb794f05b7 extmod: Make port-included extmod modules use MP_REGISTER_MODULES.
_onewire, socket, and network were previously added by the port rather
than objmodule.c.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:49:12 +10:00
Jim Mussared
d8d3e6ae78 py: Make builtin modules use MP_REGISTER_MODULE.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:49:12 +10:00
Jim Mussared
4eab44a1ec extmod: Make extmod modules use MP_REGISTER_MODULE.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:49:12 +10:00
Jim Mussared
469450171f py/makemoduledefs.py: Allow multiple ways to register a module.
For example, ussl can come from axtls or mbedtls. If neither are enabled
then don't try and set an empty definition twice, and only include it
once in MICROPY_REGISTERED_MODULES.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-18 20:49:12 +10:00
Jim Mussared
bc42db4496 github/ISSUE_TEMPLATE: Add GitHub issue templates and external links.
When opening a new issue the following selection is now shown:
- Bug reports
- Feature requests
- Security issue
- Documentation issue
- Link to forum
- Link to docs
- Link to downloads
2022-05-18 16:49:11 +10:00
Damien George
079f3e5e5b py/parse: Allow all constant objects to be used in "X = const(o)".
Now that constant tuples are supported in the parser, eg (1, True, "str"),
it's a small step to allow anything that is a constant to be used with the
pattern:

    from micropython import const

    X = const(obj)

This commit makes the required changes to allow the following types of
constants:

    from micropython import const

    _INT = const(123)
    _FLOAT = const(1.2)
    _COMPLEX = const(3.4j)
    _STR = const("str")
    _BYTES = const(b"bytes")
    _TUPLE = const((_INT, _STR, _BYTES))
    _TUPLE2 = const((None, False, True, ..., (), _TUPLE))

Prior to this, only integers could be used in const(...).

Signed-off-by: Damien George <damien@micropython.org>
2022-05-18 16:18:35 +10:00
Damien George
761d2f6741 tests/micropython: Add more test cases for native generators.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-18 15:23:11 +10:00
Damien George
80938839c1 tests/extmod: Use bytearray instead of bytes for uctypes test.
Because the test modifies the (now) bytearray object, and if it's a bytes
object it's not guaranteed that it can be modified, or that this constant
object isn't used elsewhere.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-18 15:23:11 +10:00
Damien George
8588525868 py/compile: De-duplicate constant objects in module's constant table.
The recent rework of bytecode made all constants global with respect to the
module (previously, each function had its own constant table).  That means
the constant table for a module is shared among all functions/methods/etc
within the module.

This commit add support to the compiler to de-duplicate constants in this
module constant table.  So if a constant is used more than once -- eg 1.0
or (None, None) -- then the same object is reused for all instances.

For example, if there is code like `print(1.0, 1.0)` then the parser will
create two independent constants 1.0 and 1.0.  The compiler will then (with
this commit) notice they are the same and only put one of them in the
constant table.  The bytecode will then reuse that constant twice in the
print expression.  That allows the second 1.0 to be reclaimed by the GC,
also means the constant table has one less entry so saves a word.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-18 15:23:11 +10:00
Damien George
b3d0f5f67c tests/micropython: Fully unlink nested list in extreme exc test.
To make sure there are no dangling references to the lists, and the GC can
reclaim heap memory.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-18 09:16:33 +10:00
Damien George
90682f43af py/compile: Allow new qstrs to be allocated at all compiler passes.
Prior to this commit, all qstrs were required to be allocated (by calling
mp_emit_common_use_qstr) in the MP_PASS_SCOPE pass (the first one).  But
this is an unnecessary restriction, which is lifted by this commit.
Lifting the restriction simplifies the compiler because it can allocate
qstrs in later passes.

This also generates better code, because in some cases (eg when a variable
is closed over) the scope of an identifier is not known until a bit later
and then the identifier no longer needs its qstr allocated in the global
table.

Code size is reduced for all ports with this commit.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 23:39:22 +10:00
Damien George
1fb01bd6c5 py/emitnative: Put a pointer to the native prelude in child_table array.
Some architectures (like esp32 xtensa) cannot read byte-wise from
executable memory.  This means the prelude for native functions -- which is
usually located after the machine code for the native function -- must be
placed in separate memory that can be read byte-wise.  Prior to this commit
this was achieved by enabling N_PRELUDE_AS_BYTES_OBJ for the emitter and
MICROPY_EMIT_NATIVE_PRELUDE_AS_BYTES_OBJ for the runtime.  The prelude was
then placed in a bytes object, pointed to by the module's constant table.

This behaviour is changed by this commit so that a pointer to the prelude
is stored either in mp_obj_fun_bc_t.child_table, or in
mp_obj_fun_bc_t.child_table[num_children] if num_children > 0.  The reasons
for doing this are:

1. It decouples the native emitter from runtime requirements, the emitted
   code no longer needs to know if the system it runs on can/can't read
   byte-wise from executable memory.

2. It makes all ports have the same emitter behaviour, there is no longer
   the N_PRELUDE_AS_BYTES_OBJ option.

3. The module's constant table is now used only for actual constants in the
   Python code.  This allows further optimisations to be done with the
   constants (eg constant deduplication).

Code size change for those ports that enable the native emitter:
   unix x64:   +80 +0.015%
      stm32:   +24 +0.004% PYBV10
    esp8266:   +88 +0.013% GENERIC
      esp32:   -20 -0.002% GENERIC[incl -112(data)]
        rp2:   +32 +0.005% PICO

Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 16:44:49 +10:00
Damien George
8725a32f41 tools/ci.sh: For esp8266 CI install esptool 3.3.1.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 16:01:56 +10:00
Damien George
f8d3956c63 tools/ci.sh: Run full test suite on stackless and settrace builds.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 14:25:51 +10:00
Damien George
acfc3bbdf8 tests/multi_net: Skip SSL test if relevant modules aren't available.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 14:25:51 +10:00
Damien George
ab0a8f3086 tests/run-tests.py: Exclude settrace tests when using native emitter.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 14:25:51 +10:00
Damien George
5f650b7b7a tests/thread: Use less resources for stress_aes if settrace enabled.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 14:25:51 +10:00
Damien George
1762990579 py/bc: Provide separate code-state setup funcs for bytecode and native.
mpy-cross will now generate native code based on the size of
mp_code_state_native_t, and the runtime will use this struct to calculate
the offset of the .state field.  This makes native code generation and
execution (which rely on this struct) independent to the settings
MICROPY_STACKLESS and MICROPY_PY_SYS_SETTRACE, both of which change the
size of the mp_code_state_t struct.

Fixes issue #5059.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 14:25:51 +10:00
Damien George
8e1db993cd py/asmx64: Support full range of regs in asm_x64_lea_disp_to_r64.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 14:25:51 +10:00
Damien George
6f68a8c240 tests/run-perfbench.py: Return error code if any test fails on target.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 14:06:41 +10:00
Damien George
d7cf8a3b9d tests/perf_bench: Update .mpy file header to remove old unicode flag.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 14:06:41 +10:00
Damien George
2a366e183e docs/reference/mpyfiles: Remove docs about mpy flags and qstr win size.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 12:51:54 +10:00
Damien George
c49d5207e9 py/persistentcode: Remove unicode feature flag from .mpy file.
Prior to this commit, even with unicode disabled .py and .mpy files could
contain unicode characters, eg by entering them directly in a string as
utf-8 encoded.

The only thing the compiler disallowed (with unicode disabled) was using
\uxxxx and \Uxxxxxxxx notation to specify a character within a string with
value >= 0x100; that would give a SyntaxError.

With this change mpy-cross will now accept \u and \U notation to insert a
character with value >= 0x100 into a string (because the -mno-unicode
option is now gone, there's no way to forbid this).  The runtime will
happily work with strings with such characters, just like it already works
with strings with characters that were utf-8 encoded directly.

This change simplifies things because there are no longer any feature
flags in .mpy files, and any bytecode .mpy will now run on any target.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 12:51:54 +10:00
Damien George
b295b6f1f3 py/persistentcode: Remove obsolete comment about qstr window size.
This was made obsolete in f2040bfc7e

Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 12:51:54 +10:00
Damien George
2ed4f7a130 tools/mpy_ld.py: Remove obsolete QSTR_WINDOW_SIZE constant.
This was made obsolete in f2040bfc7e

Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 12:51:54 +10:00
Damien George
8aa254c369 tests: Fix tests to use sys.implementation._mpy.
The field was renamed to _mpy in 59c5d41611

Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 09:46:40 +10:00
Takeo Takahashi
e3c880a569 tools/autobuild: Update for ports/renesas-ra.
* Add build_renesas_ra_boards call in autobuild.sh
* Add build_renesas_ra_boards function to generate firmware.hex.

Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-05-06 17:15:21 +09:00
Damien George
1e72580fd8 top: Update .git-blame-ignore-revs for latest formatting commit.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-05 13:31:04 +10:00
Damien George
5b700b0af9 all: Reformat remaining C code that doesn't have a space after a comma.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-05 13:30:40 +10:00
Damien George
aec8db3cd1 tools/uncrustify: Make sure a space exists after a comma.
This will add a space after a comma if it doesn't have one, but will allow
more than one space if the spaces are already there.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-05 13:30:40 +10:00
Damien George
b0a1b60a9b extmod: Move font_petme128_8x8.h from ports/stm32 to extmod.
And add spaces after commas so it is consistently formatted.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-05 13:30:40 +10:00
Damien George
1216c9fffa py/objmodule: Move stray #include to top of file.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-05 11:02:38 +10:00
Damien George
da31ad7aad mimxrt/mbedtls: Use core-provided tracked alloc instead of custom funcs.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-05 10:31:50 +10:00
Damien George
39c96b543f stm32/mbedtls: Use core-provided tracked alloc instead of custom funcs.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-05 10:31:50 +10:00
Damien George
fca5701f74 py/malloc: Introduce m_tracked_calloc, m_tracked_free functions.
Enabled by MICROPY_TRACKED_ALLOC.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-05 10:31:50 +10:00
Takeo Takahashi
965747bd97 renesas-ra: Rename pyb_rtc_ to machine_rtc_.
Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-05-04 19:45:16 +09:00
Takeo Takahashi
5f57ec464a renesas-ra: Rename pyb_uart_ to machine_uart_.
Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-05-04 19:45:16 +09:00
stijn
20028c7c80 windows: Avoid busy loop when using scheduler. 2022-05-04 10:22:29 +10:00
stijn
8aa79c95bd windows: Consolidate all sleep-related functions into windows_mphal.c.
Replace the timer-based sleep with the standard win32 call since the former
has no benefits: even though it allows specifying the time in 100uSec
chunks, the actual resolution is still limited by the OS and is never
better than 1mSec.

For clarity move all of this next to the mp_hal_delay_ms definition so all
related functions are in one place.
2022-05-04 10:22:09 +10:00
Damien George
c90f097519 tests/extmod: Increase timing on uasyncio tests to make more reliable.
Non-real-time systems like Windows, Linux and macOS do not have reliable
timing, so increase the sleep intervals to make these tests more likely to
pass.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-03 22:53:12 +10:00
Jim Mussared
0e7bfc88c6 all: Use mp_obj_malloc everywhere it's applicable.
This replaces occurences of

    foo_t *foo = m_new_obj(foo_t);
    foo->base.type = &foo_type;

with

    foo_t *foo = mp_obj_malloc(foo_t, &foo_type);

Excludes any places where base is a sub-field or when new0/memset is used.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-03 22:28:14 +10:00
Jim Mussared
6a3bc0e1a1 py/objfloat: Explain why mp_obj_malloc isn't used.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-03 22:25:40 +10:00
Jim Mussared
709e8328d9 py/obj: Introduce mp_obj_malloc macro to allocate, and set object type.
This is to replace the following:

    mp_foo_obj_t *self = m_new_obj(mp_foo_obj_t);
    self->base.type = &mp_type_foo;

with:

    mp_foo_obj_t *self = mp_obj_malloc(mp_foo_obj_t, &mp_type_foo);

Calling the function is less code than inlining setting the type
everywhere, adds up to ~100 bytes on PYBV11.

It also helps to avoid an easy mistake of forgetting to set the type.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-05-03 22:23:46 +10:00
Damien George
590de399f0 py/emitcommon: Don't implicitly close class vars that are assigned to.
When in a class body or at the module level don't implicitly close over
variables that have been assigned to.

Fixes issue #8603.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-03 16:38:43 +10:00
Takeo Takahashi
a21fd7cc21 docs/renesas-ra: Remove unused image files.
Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-05-03 13:22:01 +10:00
Takeo Takahashi
a204365df1 renesas-ra/boards: Change device name information to show properly.
* Change device name table to list style to show properly.
* Change the link of cable connection information to the latest.

Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-05-02 12:02:32 +09:00
Takeo Takahashi
52add7b45c docs: Update files for renesas-ra port.
Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-04-29 12:29:08 +09:00
Takeo Takahashi
1b61800530 docs/renesas-ra: Add renesas-ra docs files.
Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-04-29 12:29:08 +09:00
Takeo Takahashi
3717d599e2 tests/run-tests.py: Update for renesas-ra port.
Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-04-29 12:29:08 +09:00
Takeo Takahashi
4753913253 tests/renesas-ra: Add tests for renesas-ra port.
Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-04-29 12:29:07 +09:00
Takeo Takahashi
3a941cce51 tools/ci.sh: Update for ports/renesas-ra.
Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-04-29 12:29:07 +09:00
Takeo Takahashi
e214ae0e64 github/workflows: Add workflow for renesas-ra port.
Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-04-29 12:29:07 +09:00
Takeo Takahashi
86e35178e6 drivers/dht/dht.py: Change default import module as machine.
Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-04-29 12:29:07 +09:00
Takeo Takahashi
0f57ccf7f2 renesas-ra: Add new port to Renesas RA.
Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-04-29 12:29:06 +09:00
TakeoTakahashi2020
4c9b00b425 lib/fsp: Add renesas fsp git repository as submodule.
Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-04-29 10:55:58 +09:00
Damien George
44186ef59b qemu-arm/mpconfigport: Define MICROPY_PY_SYS_PLATFORM.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-28 17:23:03 +10:00
Damien George
402df833fe py/modsys: Introduce sys.implementation._machine constant.
This contains a string useful for identifying the underlying machine.  This
string is kept consistent with the second part of the REPL banner via the
new config option MICROPY_BANNER_MACHINE.

This makes os.uname() more or less redundant, as all the information in
os.uname() is now available in the sys module.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-28 17:23:03 +10:00
Damien George
59c5d41611 py/modsys: Rename sys.implementation.mpy to sys.implementation._mpy.
Per CPython docs, non-standard attributes must begin with an underscore.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-28 17:23:03 +10:00
Damien George
40047823bc py/modsys: Append MicroPython git version and build date to sys.version.
This commit adds the git hash and build date to sys.version.  This is
allowed according to CPython docs, and is what PyPy does.  The docs state:

    A string containing the version number of the Python interpreter plus
    additional information on the build number and compiler used.

Eg on CPython:

    Python 3.10.4 (main, Mar 23 2022, 23:05:40) [GCC 11.2.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import sys
    >>> sys.version
    '3.10.4 (main, Mar 23 2022, 23:05:40) [GCC 11.2.0]'

and PyPy:

    Python 2.7.12 (5.6.0+dfsg-4, Nov 20 2016, 10:43:30)
    [PyPy 5.6.0 with GCC 6.2.0 20161109] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>>> import sys
    >>>> sys.version
    '2.7.12 (5.6.0+dfsg-4, Nov 20 2016, 10:43:30)\n[PyPy 5.6.0 with GCC ...

With this commit on MicroPython we now have:

    MicroPython v1.18-371-g9d08eb024 on 2022-04-28; linux [GCC 11.2.0] v...
    Use Ctrl-D to exit, Ctrl-E for paste mode
    >>> import sys
    >>> sys.version
    '3.4.0; MicroPython v1.18-371-g9d08eb024 on 2022-04-28'

Note that the start of the banner is the same as the end of sys.version.
This helps to keep code size under control because the string can be reused
by the compiler.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-28 15:23:17 +10:00
Asensio Lorenzo Sempere
9d08eb0247 stm32/boards/NUCLEO_G0B1RE: Add NUCLEO_G0B1RE board definition.
This commit adds a board definition for NUCLEO_G0B1RE. This board has the
REPL on UART2 which is connected to the on-board ST-link USB-UART.

Signed-off-by: Asensio Lorenzo Sempere <asensio.aerospace@gmail.com>
2022-04-28 11:56:15 +10:00
Asensio Lorenzo Sempere
010012c7c3 stm32: Add support for G0 MCUs.
This commit adds support for the STM32G0 series of MCUs.

Signed-off-by: Asensio Lorenzo Sempere <asensio.aerospace@gmail.com>
2022-04-28 11:56:15 +10:00
Asensio Lorenzo Sempere
3587d8e808 stm32/storage: Add support for internal storage on Cortex-M0 MCUs.
This implements self-triggering of the Flash NVIC interrupt on Cortex-M0
devices, which allows enabling internal storage on those MCUs.

Signed-off-by: Asensio Lorenzo Sempere <asensio.aerospace@gmail.com>
2022-04-28 11:56:15 +10:00
Damien George
7f445e3d39 lib/stm32lib: Update library for G0 v1.5.1.
Changes in this new library version are:
- Add G0 HAL at v1.5.1.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-28 11:56:15 +10:00
iabdalkader
96ad86ed2b stm32/boards/ARDUINO_PORTENTA_H7: Add support for Arduino Portenta H7. 2022-04-28 10:42:47 +10:00
iabdalkader
1f33ec140a stm32/ulpi: Include missing py/mperrno.h header. 2022-04-28 10:34:56 +10:00
iabdalkader
014912daae stm32/ulpi: Add USB3320 ULPI low-power functions.
This driver allows switching USB3320 ULPI to low-power mode.  It is ported/
adapted from ST code, stm32f7xx_lp_modes.c, which is BSD-3 licensed code.
2022-04-26 23:11:50 +10:00
iabdalkader
32914c53ef stm32/qspi: Workaround for SR set immediately after setting AR.
See issue #5441.  This issue is now reproducible on the Arduino Portenta
H747, QSPI flash PN MX25L12833F.
2022-04-26 22:33:05 +10:00
iabdalkader
5974ac256b stm32/qspi: Wait for a free FIFO location before writing to DR.
Must always check the FIFO before writing to DR.  Without this, this
function hangs on the H747.
2022-04-26 22:32:48 +10:00
iabdalkader
b28839420d stm32/qspi: Support common flash sizes in MPU configuration.
Add MPU configuration for common flash sizes up to 256MiB.
2022-04-26 22:32:29 +10:00
Damien George
0e6873840b rp2/mpconfigport: Enable execfile, NotImplemented and REPL EMACS keys.
To bring this port in line with other ports that use
MICROPY_CONFIG_ROM_LEVEL_EXTRA_FEATURES.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-26 22:15:07 +10:00
Damien George
eb9674822b esp32/modnetwork: Fix build when MICROPY_PY_NETWORK_WLAN is disabled.
Fixes issue #8541.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-22 21:56:31 +10:00
wemos
ff28d2e3b3 esp32/network_wlan: Support setting/getting txpower in WLAN.config(). 2022-04-22 21:52:28 +10:00
Damien George
2a08e38c60 docs/library/network.WLAN: Add "txpower" to list of known WLAN configs.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-22 21:51:29 +10:00
Damien George
6bec5c4da5 tests/cmdline: Add test for REPL auto-indent.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-22 17:00:16 +10:00
Damien George
6d401be4dd shared/readline: Disable auto-indent if space/tab follows added indent.
Auto-indent still works as the default behaviour, but it is now undone and
disabled if there is a space/tab immediately after an automatically-added
indent.  This makes the REPL behaviour closer to CPython, and in particular
allows text to be pasted at the normal REPL.

Addresses issue #7925.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-22 17:00:16 +10:00
Damien George
a8f23f6366 shared/readline: Make tab insert an indent when it follows whitespace.
Entering tab at the REPL will now make it insert an indent (4 spaces) in
the following cases:
- after any whitespace on a line
- at the start of a line that is not the first line

This changes the existing behaviour where a tab would insert an indent only
if there were no matches in the auto-complete search, and it was the start
of the line.  This means, if there were any symbols in the global
namespace, tab could never be used to indent.

Note that entering tab at the start of the first line will still do
auto-completion, but will now do nothing if there are no symbols in the
global namespace, which is more consistent than before.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-22 17:00:16 +10:00
Damien George
caaff940a2 extmod/uasyncio: Rename and merge TaskQueue push/pop methods.
These are internal names and can be safely renamed without affecting user
code.  push_sorted() and push_head() are merged into a single push()
method, which is already how the C version is implemented.  pop_head() is
simply renamed to pop().

The changes are:
- q.push_sorted(task, t) -> q.push(task, t)
- q.push_head(task) -> q.push(task)
- q.pop_head() -> q.pop()

The shorter names and removal of push_head() leads to a code size reduction
of between 40 and 64 bytes on bare-metal targets.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-22 16:37:02 +10:00
Damien George
28e7e15c0a extmod/uasyncio: Fix bug with task ending just after gather is cancel'd.
This fixes a bug where the gather is cancelled externally and then one of
its sub-tasks (that the gather was waiting on) finishes right between the
cancellation being queued and being executed.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-21 14:25:17 +10:00
Damien George
f7454f850f extmod/uasyncio: Make Python Task match C version with use of asserts.
This helps to catch bugs when a Task is put on more than one pairing heap.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-21 14:25:17 +10:00
Damien George
8631753ff4 tests/run-tests.py: Add timeout for running PC-based MicroPython test.
So the test suite runs to completion, even if the interpreter locks up.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-21 14:25:17 +10:00
Damien George
81c9219375 tools/ci.sh: Don't run uasyncio_gather test on macOS.
The timing on macOS makes this test unreliable.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-21 14:25:17 +10:00
Damien George
ef1c2cdab0 tests/extmod/uasyncio_gather: Make double-raise gather test reliable.
This double-raise test could fail when task[0] raises and stops the gather
before task[1] raises, then task[1] is left to raise later on and spoil the
test.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-20 19:32:49 +10:00
Damien George
c8a687a8fa top: Update .git-blame-ignore-revs for latest formatting commit.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-20 16:17:48 +10:00
Damien George
5c32111fa0 ports: Reformat more C and Python source code.
These files that are reformatted only now fall under the list of files to
apply uncrustify/black formatting to.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-20 16:17:35 +10:00
Damien George
fb10d15d47 tools/codeformat.py: Include more ports .c/.h files in formatting.
This adds a rule to cover all ports/**/*.[ch] file to the code formatting
list.  Explicit exclusions are also added for code in ports/ which is third
party, or which requires a lot of reformatting.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-20 16:02:11 +10:00
Damien George
71a64545a8 tools/codeformat.py: Remove ports/unix/*.py from exclusion list.
These .py files were removed from the .gitignore in commit
3c2aa5ff93

Signed-off-by: Damien George <damien@micropython.org>
2022-04-20 16:01:11 +10:00
Damien George
707aaa350a stm32/boards/LEGO_HUB_NO6: Exclude BTstack code from formatting.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-20 15:54:26 +10:00
Jon Bjarni Bjarnason
1ded8a2977 py/objtype: Convert result of user __contains__ method to bool.
Per https://docs.python.org/3/reference/expressions.html#membership-test-operations

    For user-defined classes which define the contains() method, x in y
    returns True if y.contains(x) returns a true value, and False
    otherwise.

Fixes issue #7884.
2022-04-20 15:44:46 +10:00
iabdalkader
52c2580a40 drivers/ninaw10: Fix isconnected to return False when inactive.
If isconnected is called before active, it returns -1, which causes
mp_obj_new_bool return True, indicating the module is connected.
2022-04-20 15:40:52 +10:00
iabdalkader
03c61916bc stm32/boards/ADAFRUIT_F405_EXPRESS: Use external SPI flash for storage.
Fixes issue #8553.
2022-04-20 15:37:14 +10:00
iabdalkader
71afed1a70 stm32/mphalport: Fix I/O glitches when switching GPIO mode to alt-func.
To avoid any I/O glitches in mp_hal_pin_config, make sure a valid alternate
function is set in AFR first before switching the pin mode.  When switching
from AF to INPUT or OUTPUT, the AF in AFR will remain valid up until the
pin mode is switched.
2022-04-20 15:31:14 +10:00
Chris Wilson
b50fe9a6da stm32/boards/SPARKFUN_MICROMOD_STM32: Fix incorrect UART and I2C config.
Based on testing with real hardware.
2022-04-19 10:42:37 +10:00
Damien George
9ab66b50cb docs/reference: Update constrained docs now that tuples can be const.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-15 00:17:08 +10:00
Damien George
865b61dac2 tests/micropython: Add tests that const tuples don't use the heap.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-15 00:17:02 +10:00
Damien George
07f526067e tools/mpy-tool.py: Intern more strings when freezing.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 23:52:14 +10:00
Damien George
40d431d1bb tools/mpy-tool.py: Optimise freezing of str when str data is a qstr.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 23:52:14 +10:00
Damien George
e647966fc9 tools/mpy-tool.py: Make global qstr list a dedicated class.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 23:52:14 +10:00
Damien George
dfc6c6299c tools/mpy-tool.py: Optimise freezing of empty str and bytes objects.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 23:52:14 +10:00
Damien George
9c8a56343f tools/mpy-tool.py: Optimise freezing of ints that can fit a small int.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 23:52:14 +10:00
Damien George
abdc4ec08d qemu-arm/test-frzmpy: Add test for freezing constant tuples.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 23:52:14 +10:00
Damien George
999abbb8b5 tests/perf_bench: Update import tests for changes to .mpy consts.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 23:52:14 +10:00
Damien George
24894f9065 ports: Recompile bytecode tests now that .mpy format changed.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 23:52:14 +10:00
Damien George
68b3aeeb57 tools/mpy-tool.py: Support freezing tuples and other consts.
This also simplifies how constants are frozen.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 23:52:14 +10:00
Damien George
2a075cc8a9 tools/mpy-tool.py: Support loading tuples from .mpy files.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 23:52:14 +10:00
Damien George
4ca96983ff py/persistentcode: Support loading and saving tuples in .mpy files.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 23:52:14 +10:00
Damien George
35c0cff92b py/parse: Add MICROPY_COMP_CONST_TUPLE option to build const tuples.
This commit adds support to the parser so that tuples which contain only
constant elements (bool, int, str, bytes, etc) are immediately converted to
a tuple object.  This makes it more efficient to use tuples containing
constant data because they no longer need to be created at runtime by the
bytecode (or native code).

Furthermore, with this improvement constant tuples that are part of frozen
code are now able to be stored fully in ROM (this will be implemented in
later commits).

Code size is increased by about 400 bytes on Cortex-M4 platforms.

See related issue #722.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 23:52:12 +10:00
Damien George
24bc1f61f9 py/parse: Print const object value in mp_parse_node_print.
To give more information when printing the parse tree.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 22:45:42 +10:00
Damien George
e52f14d057 py/parse: Factor obj extract code to mp_parse_node_extract_const_object.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 22:44:56 +10:00
Damien George
42d0bd2c17 py/persistentcode: Define enum values for obj types instead of letters.
To keep the separate parts of the code that use these values in sync.  And
make it easier to add new object types.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 22:44:04 +10:00
Stephane Smith
988827b85a esp32/modesp32: Properly define RTC_VALID_EXT_PINS on S2/S3 variants.
On ESP32 S2/S3 variants, GPIO0 through GPIO21 are valid RTC pins.  This
commit defines the valid RTC_VALID_EXT_PINS for the S2/S3 variants,
otherwise, it keeps functionality the same.
2022-04-14 16:17:52 +10:00
Stephane Smith
7005354099 esp32/machine_pin: Don't expose pins 33-37 when octal SPIRAM is enabled.
For ESP32-S3 configurations, CONFIG_SPIRAM_MODE_OCT requires pins 33-37 for
PSRAM.  So exclude them from the machine_pin_type and machine_pin_irq_type
object tables.
2022-04-14 16:14:13 +10:00
Stephane Smith
ae3d5289a5 esp32/boards: Compile GENERIC_SPIRAM and UM_TINYPICO with -Os.
These boards do not build with IDF v4.4 because the section .iram0.text
does not fit in region iram0_0_seg.  Enabling SPIRAM increases the code
size so use -Os instead of -O2 to build these boards.

Fixes issue #8260.
2022-04-14 16:06:41 +10:00
Damien George
fe9eaf12f3 esp32: Add MICROPY_HW_ENABLE_UART_REPL and enable on generic S2/S3.
Some S2/S3 modules don't use the native USB interface but instead have an
external USB-UART.  To make the GENERIC_S3/S3 firmware work on these boards
the UART REPL is enabled in addition to the native USB CDC REPL.

Fixes issues #8418 and #8524.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 14:39:20 +10:00
Damien George
be25e333df esp32/boards: Add test manifest to test freezing during build.
Includes tests for freezing @micropython.native and @micropython.viper
code.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 14:06:38 +10:00
Damien George
b8d959d6cf Revert "py/emitnative: Don't store prelude at end of machine code if..."
This reverts commit 7e8222ae06.

The prelude data must exist somewhere in the native code so load_raw_code
and mpy-tool.py can access and parse it.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 14:06:38 +10:00
Damien George
8045ac07f5 stm32/mpbthciport: Switch scheduling callback to use node scheduler.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 12:33:31 +10:00
Damien George
75506e496f py/scheduler: Add support for scheduling static C-based callbacks.
If MICROPY_SCHEDULER_STATIC_NODES is enabled then C code can declare a
static mp_sched_node_t and schedule a callback using
mp_sched_schedule_node().  In contrast to using mp_sched_schedule(), the
node version will have at most one pending callback outstanding, and will
always be able to schedule if there is nothing already scheduled on this
node.  This guarantees that the the callback will be called exactly once
after it is scheduled.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 12:31:53 +10:00
Peter Hinch
d242a9b7f7 rp2/machine_uart: Use read/write mutex to prevent char duplication.
Duplication of characters is caused by re-entrant calls from separate cores
of uart_fill_tx_fifo().  This patch uses a mutex to ensure that a
re-entrant execution of the function returns without affecting the UART
FIFO.

Fixes issues #8344 and #8360.
2022-04-12 11:39:00 +10:00
Dave Hylands
9d7c168bf5 stm32/boards/PYBD_SFx: Allow FROZEN_MANIFEST to be overridden.
Because mpconfigboard.mk used = rather then ?= it doesn't allow
FROZEN_MANIFEST to be overridden using a GNUmakefile or the manifest.
2022-04-11 16:19:45 +10:00
iabdalkader
a82fad7d8e stm32/system_stm32: Improve H7 PLL and OSC configuration.
- Allow boards to configure CSI, HSI48 and PLL2.
- Allow peripheral clock source configuration.
- Set H7 SYSCLKSource.
2022-04-11 16:12:53 +10:00
iabdalkader
36cac5e154 stm32/system_stm32: Allow boards to configure PLL VCI, VCO and FRACN.
This removes hard-coded PLL1/3 VCI, VCO and FRACN.
2022-04-11 16:12:53 +10:00
iabdalkader
a3e5a68c46 stm32/system_stm32: Set voltage scaling level 0 for H7 Rev-V devices.
This enables voltage scaling level 0 for H7 Rev-V devices, which allows the
CPU to run at the maximum supported operating frequency (480MHz).
2022-04-11 16:12:53 +10:00
iabdalkader
bdbc9b395f stm32/system_stm32: Add H7 switched-mode-power-supply support.
- Add board-level configuration option to set the SMPS supply mode.
- Wait for valid voltage levels after configuring the SMPS mode.
- Wait for external supply ready flag if SMPS supplies external circuitry.
2022-04-11 16:12:53 +10:00
iabdalkader
7b3adb5ce5 stm32/Makefile: Add H747 to Makefile's MCU flags. 2022-04-11 16:12:50 +10:00
iabdalkader
2a19c3cfe1 stm32/sdram: Add function to enable SDRAM power-down mode.
Add power-down mode for maximum power saving while in standby mode, to be
used by a board if needed.  Also fix a typo in a comment.
2022-04-11 16:00:40 +10:00
Damien George
cb0372b5bf stm32/mboot: Add macros for use in led_state_all().
Signed-off-by: Damien George <damien@micropython.org>
2022-04-11 15:52:41 +10:00
Damien George
b2deea6762 stm32/mboot: Consolidate all UI and add general state change hooks.
All user interface (LED, button) code has been moved to ui.c, and the
interface to this code with the rest of the system now goes through calls
to mboot_state_change().  This state-change function can be overridden by a
board to fully customise the user interface behaviour.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-11 15:52:41 +10:00
Christian Zietz
d6c59c9d72 tests/inlineasm: Add test for PUSH LR and POP PC. 2022-04-11 15:35:42 +10:00
Christian Zietz
b0bcb3862b py/emitinlinethumb: Use 16 bit encodings for PUSH LR and POP PC.
The Thumb instruction set has special 16 bit encodings for PUSH involving
LR and POP involving PC, which are commonly used in nested functions.

Using this encoding is particularly important for ARMv6-M, where the more
general 32 bit encoding of PUSH and POP is unavailable.
2022-04-11 15:35:39 +10:00
Damien George
1daeeb2430 docs/differences: Update Python 3.5 diff, with optional listen backlog.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-11 15:28:56 +10:00
Damien George
aab005c75b extmod/modusocket: Provide config macro for socket.listen backlog deflt.
To make it possible to change this value for any given port or board.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-11 15:28:56 +10:00
Jon Bjarni Bjarnason
919f696ad2 extmod/modusocket: Implement optional socket.listen backlog argument.
This follows the CPython change: https://bugs.python.org/issue21455

Socket listen backlog defaults to 2 if not given, based on most bare metal
targets not having many resources for a large backlog.  On UNIX it defaults
to SOMAXCONN or 128, whichever is less.
2022-04-11 15:26:47 +10:00
Rob Knegjens
d3d862769a tools/mpremote: Add option to mount cmd to allow "unsafe" symlinks.
Specifying the option `--unsafe-links` (or `-l`) to `mpremote mount` will
allow symlinks to be followed in the local directory that point outside of
the base directory path.

For the unsafe case the `path_check()` method of `PyboardCommand` still
checks for a common path but without expanding symlinks.  While this check
is currently redundant, it makes the purpose of the method clearer for
possible future uses or extensions.
2022-04-11 15:15:04 +10:00
Rob Knegjens
56978c3dde tools/mpremote: Show progress indicator when copying large files.
When copying large files (> 2048 bytes) to or from a device with
`mpremote cp` a progress bar and percentage counter are temporarily shown.
2022-04-11 15:04:20 +10:00
Damien George
b59989f40e rp2/Makefile: Add mbedtls to GIT_SUBMODULES list and use it in CI func.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-11 13:05:25 +10:00
robert-hh
ca41eda281 mimxrt/mphalport: Fix USB CDC RX handling to not block when unprocessed.
Changes in this commit:
- Fix USB CDC RX handling to not block when unprocessed.  The fix follows
  5873390226.
- Fix dupterm rx.
- Remove some obsolete lines.
2022-04-11 12:30:59 +10:00
robert-hh
752fe75910 mimxrt/machine_spi: Improve handling of busy SPI peripheral.
This commit changes the method of waiting for SPI being not busy.  Instead
of the FIFO size, the TransferBusyFlag is probed.

Also, raise an error if the transfer failed.
2022-04-11 12:27:49 +10:00
robert-hh
b70b8ce3e4 mimxrt/machine_rtc: Start RTC at boot and set datetime if not set.
Changes in this commit:
- Start the RTC Timer at system boot.  Otherwise time.time() will advance
  only if an RTC() object was created.
- Set the time to a more recent date than Jan 1, 1970, if not set.  That is
  2013/10/14, 19:53:11, MicroPython's first commit.
- Compensate an underflow in in timeutils_seconds_since_2000(), called by
  time.time(), if the time is set to a pre-2000 date.
2022-04-11 12:25:23 +10:00
robert-hh
e3030f7436 mimxrt/modules: Append /flash/lib to the default sys.path. 2022-04-11 12:25:15 +10:00
robert-hh
798a29f629 mimxrt/boards: Add board.json file for OLIMEX RT1010Py. 2022-04-11 12:24:43 +10:00
Damien George
66b5c4c770 stm32/machine_bitstream: Include all clobbered regs in Cortex-M0 impl.
These additional registers are used by the assembly code.

Thanks to Jim Mussared for the fix.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-07 21:17:51 +10:00
Damien George
43d50f006d stm32/mpconfigport.h: Let MICROPY_PY_IO_FILEIO take its default value.
This is enabled at MICROPY_CONFIG_ROM_LEVEL_EXTRA_FEATURES, which is the
default for stm32.  Not setting the value in mpconfigboard.h allows boards
to optionally configure it.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-07 13:25:48 +10:00
Martin Fischer
5873390226 rp2/mphalport: Fix USB CDC RX handling to not block when unprocessed.
Prior to this commit, the USB CDC OUT endpoint got NACK'd if a character
was received but not consumed by the application, e.g. via
sys.stdin.read().  This meant that USB CDC was blocked and no additional
characters could be sent from the host.  In particular a ctrl-C could not
interrupt the application if another character was pending.

To fix the issue, the approach in this commit uses a callback tud_cdc_rx_cb
which is called by the TinyUSB stack on reception of new CDC data.  By
consuming the data immediately, the endpoint does not stall anymore.  The
previous handler tud_cdc_rx_wanted_cb was made obsolete and removed.

In addition some cleanup was done along the way: by adding interrupt_char.c
and removing the existing code mp_hal_set_interrupt_char().  Also, there is
now only one (stdin) ringbuffer.

Fixes issue #7996.
2022-04-05 10:47:19 +10:00
iabdalkader
5682595d75 esp32: Allow overriding cmake frozen manifest from the command line.
If MICROPY_FROZEN_MANIFEST is set from the cmake command line, then it will
override the default and any manifest set by the board.
2022-04-04 23:49:10 +10:00
Damien George
86e6744ff5 rp2: Enable ucryptolib, using mbedtls for backend functions.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-04 23:15:01 +10:00
Damien George
11ab90391d extmod/extmod.cmake: Add micropy_lib_mbedtls component.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-04 23:15:01 +10:00
Andrew Leech
8db93dc016 stm32/Makefile: Allow overriding COPT in Makefile.
It can now be set in mpconfigboard.mk (as well as the make command line).
2022-04-04 23:12:15 +10:00
Andrew Leech
3b99b4d675 docs/reference/mpremote: Add details about mount usage over soft reboot. 2022-04-04 16:50:07 +10:00
Andrew Leech
79c05bd522 tools/mpremote: Improve reliability of mount after soft reboot.
With the existing code problems can occur with remounting, the "if t -
t_last_activity > QUIET_TIMEOUT:" check can be triggered early before the
REPL string comes through, meaning that the remount doesn't happen.

On certain boards the "MPY: soft reboot" line comes through immediately
(getting the routine past initial timeout) but then there's a slightly
longer delay while the board restarts before it prints out the startup
header and the REPL prompt.

This commit adds some extra pattern monitoring during the timeout loop to
track the state if a soft restart is actually started.
2022-04-04 16:49:38 +10:00
robert-hh
56b331ace6 drivers/codec: Add driver for the WM8960 codec.
This codec is assembled for the MIMXRT1xxx_DEV boards and available for
WM8960 breakout boards as well.

The driver itself has been tested as working with the MIMXRT boards and a
Sparkfun WM6890 breakout board.  It implements the initialization, basic
methods and some enhanced methods like 3D, ALC, soft-mute and deemphasis.
2022-04-04 16:31:17 +10:00
robert-hh
7a447e08b2 docs: Add quickref and docs for mimxrt, including network.LAN docs. 2022-04-04 14:11:31 +10:00
Damien George
71344c15f4 tests/pyb: Update CAN tests to match revised CAN API.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-02 22:46:31 +11:00
iabdalkader
5cdf964571 docs/library/pyb.CAN: Update CAN docs to match revised API. 2022-04-02 22:46:07 +11:00
iabdalkader
5562ed3f43 stm32/pyb_can: Replace CAN.initfilterbanks with CAN.init keyword arg.
The CAN.initfilterbanks() class method is removed, and its functionality is
replaced with the "num_filter_banks" keyword argument to the CAN
constructor and CAN.init().  This configures the filter bank split.

This new approach provides more flexibility configuring the resources used
by a given CAN instance, allowing other MCUs like H7 to fit the API.  It
also brings CAN closer to how other machine peripherals are configured,
where everything is done in the constructor/init method.

This is a breaking change to the CAN API.
2022-04-02 22:42:00 +11:00
iabdalkader
a79706fb39 stm32/pyb_can: Define the maximum bit timing parameters.
Define the maximum parameters for CAN/FDCAN nominal bit timing, and for
FDCAN data bit timing, for bit timing calculations.
2022-04-02 22:41:37 +11:00
iabdalkader
95104c9f6e stm32/pyb_can: Return the filter ID and type of received messages.
CAN.recv() now returns a 5-tuple, with the new element in the second
position being a boolean, True if the ID is extended.

This is a breaking change of the API for CAN.recv().
2022-04-02 22:40:09 +11:00
iabdalkader
e7264e9532 stm32/pyb_can: Add support for bus with mixed Classic/FD nodes.
A CAN bus can have mixed classic/FD nodes.  Prior to this patch the CAN API
could be configured for either standard or extended ID, but not both/mixed
operation.

This patch allows extended IDs to be filtered and enabled on a per-message
basis, in send(), setfilter() and clearfilter().

This is a breaking change to the API: init() no longer accepts the extframe
keyword argument.
2022-04-02 22:37:52 +11:00
iabdalkader
3320ec44ed stm32/pyb_can: Add support for CAN FD extended frame ID. 2022-04-02 22:37:45 +11:00
iabdalkader
ff287d085f stm32/pyb_can: Enable CAN FD frame support and BRS.
- Enable CAN FD frame support and BRS.
- Optimize the message RAM usage per FDCAN instance.
- Document the usage and different sections of the Message RAM.
2022-04-02 22:37:27 +11:00
Daniel Jour
8baf05af8c py/makeqstrdefs: Cleanup and extend source file classification.
- The classification of source files in makeqstrdefs.py has been moved into
  functions to consolidate the logic for that classification into a single
  place.
- Classification of source files (into C or C++ or "other" files) is based
  on the filename extension.
- For C++ there are many more common filename extensions than just ".cpp";
  see "Options Controlling the Kind of Output" in man gcc for example.  All
  common extensions for C++ source files which need preprocessing have been
  added.
2022-04-01 15:03:21 +11:00
Damien George
1dbf393962 tests/basics/fun_callstardblstar: Add test for large arg allocation.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-01 09:20:42 +11:00
Damien George
40f5c743db py/runtime: Remove unnecessary check for kw_value == MP_OBJ_NULL.
The values are always real objects, only the key can be MP_OBJ_NULL to
indicate a **kwargs entry.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-01 09:20:42 +11:00
Damien George
bd556b6996 py: Fix compiling and decoding of *args at large arg positions.
There were two issues with the existing code:

1. "1 << i" is computed as a 32-bit number so would overflow when
   executed on 64-bit machines (when mp_uint_t is 64-bit).  This meant that
   *args beyond 32 positions would not be handled correctly.

2. star_args must fit as a positive small int so that it is encoded
   correctly in the emitted code.  MP_SMALL_INT_BITS is too big because it
   overflows a small int by 1 bit.  MP_SMALL_INT_BITS - 1 does not work
   because it produces a signed small int which is then sign extended when
   extracted (even by mp_obj_get_int_truncated), and this sign extension
   means that any position arg after *args is also treated as a star-arg.
   So the maximum bit position is MP_SMALL_INT_BITS - 2.  This means that
   MP_OBJ_SMALL_INT_VALUE() can be used instead of
   mp_obj_get_int_truncated() to get the value of star_args.

These issues are fixed by this commit, and a test added.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-01 09:20:42 +11:00
Damien George
e3de723e2d py/emitbc: Assert that a small int fits its encoding when emitting one.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-31 23:59:10 +11:00
David Lechner
2e3f2045f9 py/runtime: Use size_t/ssize_t instead of uint/int.
This replaces instances of uint with size_t and int with ssize_t in
the mp_call_prepare_args_n_kw_var() function since all of the variables
are used as array offsets.

Also sort headers while we are touching this.

Signed-off-by: David Lechner <david@pybricks.com>
2022-03-31 17:01:25 +11:00
David Lechner
47685180f0 tests/basics/fun_callstardblstar: Add coverage test.
This fixes code coverage for the case where a *arg without __len__ is
unpacked and uses exactly the amount of memory that was allocated for
kw args. This triggers the code branch where the memory for the kw args
gets reallocated since it was used already by the *arg unpacking.

Signed-off-by: David Lechner <david@pybricks.com>
2022-03-31 17:01:15 +11:00
David Lechner
9b74d71aa7 py/runtime: Drop new_alloc < 4 check.
To reach this check, n_kw has to be >= 1 and therefore args2_alloc has
to be >= 2. Therefore new_alloc will always be >= 4. So this check will
never be true and can be removed.

Signed-off-by: David Lechner <david@pybricks.com>
2022-03-31 17:01:03 +11:00
David Lechner
3679a47eb0 py/runtime: Do not overallocate when len is known.
This fixes overallocating an extra mp_obj_t when the length of *args and
**args is known. Previously we were allocating 1 mp_obj_t for each
n_args and n_kw plus the length of each *arg and **arg (if they are
known). Since n_args includes *args and n_kw includes **args, this was
allocating an extra mp_obj_t in addition to the length of these args
when unpacked.

To fix this, we just subtract 1 from the length to account for the 1
already implicitly allocated by n_args and n_kw.

Signed-off-by: David Lechner <david@pybricks.com>
2022-03-31 17:00:50 +11:00
David Lechner
783b1a868f py/runtime: Allow multiple *args in a function call.
This is a partial implementation of PEP 448 to allow unpacking multiple
star args in a function or method call.

This is implemented by changing the emitted bytecodes so that both
positional args and star args are stored as positional args.  A bitmap is
added to indicate if an argument at a given position is a positional
argument or a star arg.

In the generated code, this new bitmap takes the place of the old star arg.
It is stored as a small int, so this means only the first N arguments can
be star args where N is the number of bits in a small int.

The runtime is modified to interpret this new bytecode format while still
trying to perform as few memory reallocations as possible.

Signed-off-by: David Lechner <david@pybricks.com>
2022-03-31 16:59:30 +11:00
David Lechner
1e99d29f36 py/runtime: Allow multiple **args in a function call.
This is a partial implementation of PEP 448 to allow multiple ** unpackings
when calling a function or method.

The compiler is modified to encode the argument as a None: obj key-value
pair (similar to how regular keyword arguments are encoded as str: obj
pairs).  The extra object that was pushed on the stack to hold a single **
unpacking object is no longer used and is removed.

The runtime is modified to decode this new format.

Signed-off-by: David Lechner <david@pybricks.com>
2022-03-31 16:54:00 +11:00
Damien George
bb70874111 py/vm: Prevent array bound warning when using -MP_OBJ_ITER_BUF_NSLOTS.
This warning can happen on clang 13.0.1 building mpy-cross:

../py/vm.c:748:25: error: array index -3 refers past the last possible
  element for an array in 64-bit address space containing 64-bit (8-byte)
  elements (max possible 2305843009213693952 elements)
  [-Werror,-Warray-bounds]
                        sp[-MP_OBJ_ITER_BUF_NSLOTS + 1] = MP_OBJ_NULL;
                        ^  ~~~~~~~~~~~~~~~~~~~~~~~~~~~

Using pointer access instead of array access works around this warning.

Fixes issue #8467.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-31 10:59:55 +11:00
Damien George
7e8222ae06 py/emitnative: Don't store prelude at end of machine code if not needed.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-30 16:32:17 +11:00
Damien George
bf3585b33c py/asmxtensa: Fix use of l32i/s32i when offset won't fit in encoding.
This commit adds optimised l32i/s32i functions that select the best load/
store encoding based on the size of the offset, and uses the function when
necessary in code generation.

Without this, ASM_LOAD_REG_REG_OFFSET() could overflow the word offset
(using a narrow encoding), for example when loading the prelude from the
constant table when there are many (>16) constants.

Fixes issue #8458.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-30 16:32:17 +11:00
Damien George
df9a412206 py/compile: Only show raw code that is bytecode.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-30 16:31:53 +11:00
stijn
594c753c27 py/bc.h: Fix C++20 compilation with "volatile".
C++20 is deprecating several usages of the volatile keyword so remove this
one affected case in the codebase which causes such warning.
2022-03-30 16:29:25 +11:00
Damien George
90aaf2dbef extmod/uasyncio: Fix gather cancelling and handling of exceptions.
The following fixes are made:
- cancelling a gather now cancels all sub-tasks of the gather (previously
  it would only cancel the first)
- if any sub-task of a gather raises an exception then the gather finishes
  (previously it would only finish if the first sub-task raised)

Fixes issues #5798, #7807, #7901.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-30 16:07:44 +11:00
Damien George
335002a4c0 extmod/uasyncio: Allow task state to be a callable.
This implements a form of CPython's "add_done_callback()", but at this
stage it is a hidden feature and only intended to be used internally.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-30 16:07:44 +11:00
Andrew Leech
a41bc5a7ca stm32/modmachine: Add deepsleep support to reset_cause() for WB55. 2022-03-30 15:56:26 +11:00
Meriç SARIIŞIK
6b23f7d301 stm32/sdio: Use runtime calculation for clock divider of sdio on H7.
STM32H7 family has a different calculation compared to the current one for
the SDMMC clock divider configuration.
2022-03-30 15:40:59 +11:00
Andrew Leech
303e222f70 nrf/modules: Include uasyncio in default board manifest. 2022-03-30 15:37:49 +11:00
Andrew Leech
f92da1adc4 nrf/drivers/usb: Fix MP_STREAM_POLL_RD support on USB CDC.
This gets ipoll working on USB CDC stdin.
2022-03-30 15:34:25 +11:00
Andrew Leech
dc8b43adc7 nrf/drivers/usb: Fix background events/scheduling while at USB REPL. 2022-03-30 15:33:29 +11:00
Waterlens
4c252ae067 tools/mpremote: Allow running mpremote with python -m.
This is helpful because some scripts are likely to use mpremote with a
specific python path.
2022-03-30 15:29:26 +11:00
Damien George
3e70be8ee9 tests/extmod: Update I2S rate test to work on mimxrt.
Tested on Teensy 4.0.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-30 14:14:57 +11:00
MikeTeachman
1f6cb8f047 mixmrt/machine_i2s: Add I2S protocol support.
This commit adds support for machine.I2S on the mimxrt port.  The I2S API
is consistent with the existing stm32, esp32, and rp2 implementations.

I2S features:
- controller transmit and controller receive
- 16-bit and 32-bit sample sizes
- mono and stereo formats
- sampling frequencies from 8kHz to 48kHz
- 3 modes of operation:
  - blocking
  - non-blocking with callback
  - uasyncio
- configurable internal buffer
- optional MCK

Tested with the following development boards:
- MIMXRT1010_EVK, MIMXRT1015_EVK, MIMXRT1020_EVK, MIMXRT1050_EVK
- Teensy 4.0, Teensy 4.1
- Olimex RT1010
- Seeed ARCH MIX

Tested with the following I2S hardware peripherals:
- UDA1334
- GY-SPH0645LM4H
- WM8960 codec on board the MIMXRT boards and separate breakout board
- INMP441
- PCM5102
- SGTL5000 on the Teensy audio shield

Signed-off-by: Mike Teachman <mike.teachman@gmail.com>
2022-03-30 14:12:40 +11:00
Damien George
5e685a9c6f docs/library/machine.I2S: Clarify what rate refers to.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-29 11:44:08 +11:00
Damien George
7266285845 tests/extmod: Add test for machine.I2S data rate.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-29 11:44:08 +11:00
Damien George
6804a8a891 stm32/machine_i2s: Fix 16-bit stereo i2s_frame_map.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-29 11:44:08 +11:00
Damien George
2a91c8a888 stm32/machine_i2s: Allow I2S.deinit to be called multiple times.
In particular, it is called by the constructor if the instance already
exists.  So if the previous instance was deinit'd then it will be deinit'd
a second time.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-29 11:44:08 +11:00
Damien George
c90dfba04c stm32/machine_i2s: Set FullDuplexMode to disabled on F4.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-29 11:44:08 +11:00
Damien George
35dbde163a tools/mpremote: Support any prompt string when detecting soft reset.
The prompt may be changed by sys.ps1.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-28 16:47:50 +11:00
Damien George
b312a7abf5 py/builtinimport: Alias sys to usys if import weak links aren't enabled.
The sys module should always be available (if it's compiled in), eg to
change sys.path for importing.  So provide an explicit alias from "sys" to
"usys" so that "import sys" can always work.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-28 16:09:58 +11:00
Damien George
6d11c69983 py: Change jump-if-x-or-pop opcodes to have unsigned offset argument.
These jumps are always forwards, and it's more efficient in the VM to
decode an unsigned argument.  These opcodes are already optimised versions
of the sequence "dup-top pop-jump-if-x pop" so it doesn't hurt generality
to optimise them further.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-28 15:43:09 +11:00
Damien George
acd2c5c834 py/emitbc: Add check for bytecode jump offset overflow.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-28 15:41:51 +11:00
Damien George
538c3c0a55 py: Change jump opcodes to emit 1-byte jump offset when possible.
This commit introduces changes:

- All jump opcodes are changed to have variable length arguments, of either
  1 or 2 bytes (previously they were fixed at 2 bytes).  In most cases only
  1 byte is needed to encode the short jump offset, saving bytecode size.

- The bytecode emitter now selects 1 byte jump arguments when the jump
  offset is guaranteed to fit in 1 byte.  This is achieved by checking if
  the code size changed during the last pass and, if it did (if it shrank),
  then requesting that the compiler make another pass to get the correct
  offsets of the now-smaller code.  This can continue multiple times until
  the code stabilises.  The code can only ever shrink so this iteration is
  guaranteed to complete.  In most cases no extra passes are needed, the
  original 4 passes are enough to get it right by the 4th pass (because the
  2nd pass computes roughly the correct labels and the 3rd pass computes
  the correct size for the jump argument).

This change to the jump opcode encoding reduces .mpy files and RAM usage
(when bytecode is in RAM) by about 2% on average.

The performance of the VM is not impacted, at least within measurment of
the performance benchmark suite.

Code size is reduced for builds that include a decent amount of frozen
bytecode.  ARM Cortex-M builds without any frozen code increase by about
350 bytes.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-28 15:41:38 +11:00
Damien George
9e3e67b1d8 py/objgenerator: Fix unused variables when native gen extracts prelude.
Some compilers will warn about unused variables like scope_flags.  So use
MP_BC_PRELUDE_SIG_DECODE() which will silence these warnings.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-25 12:35:49 +11:00
David Lechner
768879f999 py/smallint: Introduce MP_SMALL_INT_BITS macro.
This adds a new MP_SMALL_INT_BITS macro that is a compile-time constant
that contains the number of bits available in an MP_SMALL_INT.

We can use this in place of the runtime function mp_small_int_bits().

Signed-off-by: David Lechner <david@pybricks.com>
2022-03-25 12:23:43 +11:00
David Lechner
e7f6b9f4f7 tools/gen-cpydiff: Skip Black fmt comments.
Since cpydiff is code used as documentation, there are cases where we may
want to use Black's `fmt: on/off/skip` comments to avoid automatic
formatting.  However, we don't want these comments to be distracting in the
generated documentation.

This rewrites the code to omit these comments when generating the docs.

Signed-off-by: David Lechner <david@pybricks.com>
2022-03-25 12:13:00 +11:00
David Lechner
e7a92c0e69 tests/cmdline/cmd_showbc: Fix spelling of sequence. 2022-03-25 12:11:17 +11:00
Damien George
b083cdba2b examples/embedding: Fix build with updated sys and os modules.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-25 11:47:30 +11:00
Damien George
73623d04d5 github/workflows: Add new workflow to test embedding example.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-25 11:39:00 +11:00
iabdalkader
df86cef59a rp2: Allow Overriding cmake frozen manifest from the command line.
If MICROPY_FROZEN_MANIFEST is set from the cmake command line, then it will
override the default and any manifest set by the board.
2022-03-24 22:10:01 +11:00
iabdalkader
fe8b47e29f ports: Allow boards to define additional network interfaces. 2022-03-24 17:23:28 +11:00
Damien George
66fe3d5cb5 stm32: Support building for STM32F745.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-22 16:01:09 +11:00
Andrew Leech
bb0ca00b77 stm32/mboot: Verify CRC32 of fsload DFU files before writing. 2022-03-22 15:04:41 +11:00
Andrew Leech
bc856a1e29 stm32/mboot: Verify signature of fsload packed DFU files before writing.
When verifying the DFU contents, the signature of signed/encrypted files is
also now checked in this initial, dry-run stage.
2022-03-22 15:04:37 +11:00
Damien George
80055c2cdc stm32/mboot/fwupdate.py: Simplify calculation of CRC32.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-22 14:14:31 +11:00
Damien George
bf89e336b9 stm32/boards/PYBD_SF2: Turn on SD card in mboot init if SD enabled.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-22 13:33:43 +11:00
Damien George
e316306546 stm32/mboot: Add support for reading from SD card.
Tested on PYBV10 and PYBD_SF6, with MBOOT_FSLOAD enabled and programming
new firmware from a .dfu.gz file stored on the SD card.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-22 13:33:43 +11:00
Damien George
9b07d38c7e stm32/mboot: Add support for 64-bit mboot address space for reads.
If enabled via MBOOT_ADDRESS_SPACE_64BIT (it's disabled by default) then
read addresses will be 64-bit.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-22 13:33:43 +11:00
Damien George
a92d45c3df stm32/mboot: Always check the magic number to enter filesystem loading.
Even if MBOOT_FSLOAD is disabled, mboot should still check for 0x70ad0080
so it can immediately return to the application if this feature is not
enabled.  Otherwise mboot will get stuck in DFU mode.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-22 12:49:00 +11:00
Damien George
dc91024a73 stm32/mboot: Add pragma for GCC to ignore array bounds warning.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-22 12:44:10 +11:00
Damien George
f0be0de341 stm32/dma: Add option to disable auto-DMA-turn-off.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-22 12:43:53 +11:00
Damien George
63c7593df6 stm32/main: Support SD cards without a partition table.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-22 12:41:15 +11:00
Damien George
75d2bfcccf stm32/sdcard: Add sdcard_select_sd/mmc functions.
So that C code can select which of SD or MMC to use.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-22 12:38:45 +11:00
Damien George
7a9cf1f0fb stm32/sdcard: Use mp_hal_pin_input instead of HAL function.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-22 12:15:36 +11:00
Damien George
eef7eae6b2 esp8266/modesp: Remove esp.info() function.
The main functionality of this info function is available via the existing
micropython.mem_info() and micropython.qstr_info() functions.  The printing
of the address space layout doesn't add much and removing esp.info() saves
about 600 bytes.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-22 11:03:29 +11:00
Damien George
65be5e072f esp8266/mpconfigport.h: Remove config values that are the defaults.
This commit is a no-op in terms of functionality.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-22 11:03:15 +11:00
Kattni Rembor
61c02e6500 esp32/machine_pin: Expose pin 20 for ESP32.
This pin is available on some ESP32 packages.

Signed-off-by: Kattni Rembor <kattni@adafruit.com>
2022-03-22 10:40:00 +11:00
Algy Tynan
afceb56ee2 esp32/boards: Add support for LilyGO LoRa32 boards.
Boards use ESP32-PICO-D4.

Added pins for hardware versions v1.0, v1.2, v1.6 and v2.0.

Signed-off-by: Algy Tynan <algy@tynan.io>
2022-03-22 00:19:36 +11:00
robert-hh
09b55dc297 esp32/machine_hw_spi: Use automatic DMA channel selection for SPI on C3.
Addresses issue #8204.
2022-03-22 00:13:25 +11:00
wemos
1a0bd352d3 esp32/boards: Add LOLIN C3 MINI ESP32-C3 based board. 2022-03-22 00:11:02 +11:00
Jonathan Hogg
3b9de192be esp32/boards/UM_TINYPICO: Remove use of PULL_HOLD.
Change APA102 power handling to not use the (now removed) PULL_HOLD
constant.
2022-03-21 23:59:48 +11:00
Jonathan Hogg
21d0599bd1 esp32/modesp32: Add new gpio_deep_sleep_hold function.
Add a new function to control whether held pins will retain their function
through deep-sleep.

Also document this function and explain how to use this in quickref to
retain pin configuration during deep-sleep.
2022-03-21 23:59:07 +11:00
Jonathan Hogg
7684c996bc esp32/machine_pin: Add new hold keyword argument and remove PULL_HOLD.
The current pull=Pin.PULL_HOLD argument doesn't make a lot of sense in the
context of what it actually does vs what the ESP32 quickref document says
it does.

This commit removes PULL_HOLD and adds a new hold=True|False keyword
argument to Pin()/Pin.init().  Setting this to True will cause the ESP32 to
lock the configuration of the pin – including direction, output value,
drive strength, pull-up/-down – such that it can't be accidentally changed
and will be retained through a watchdog or internal reset.

Fixes issue #8283, and see also #8284.
2022-03-21 23:55:02 +11:00
Jonathan Hogg
5887dfeea6 docs/esp32/quickref: Refine deep-sleep power-saving notes.
This attempts to better explain how pull-ups and pull-downs operate in
deep-sleep mode.
2022-03-21 23:54:41 +11:00
Peter Züger
94a9b50668 mimxrt/mbedtls: Add NULL pointer check in m_free_mbedtls.
Signed-off-by: Peter Züger <zueger.peter@icloud.com>
2022-03-17 13:11:39 +11:00
Peter Züger
95ee29f4f4 stm32/mbedtls: Add NULL pointer check in m_free_mbedtls.
According to the C standard the free(void *ptr) function: if ptr is a null
pointer, no action occurs.

Signed-off-by: Peter Züger <zueger.peter@icloud.com>
2022-03-17 13:11:22 +11:00
iabdalkader
a16dcc8136 stm32/boards: Convert F4xx and F7xx to new flash FS config.
Following on from 35e70c1698.

Fixes issue #8390.
2022-03-17 13:06:45 +11:00
Damien George
63f0e700f4 extmod/modure: Set subject begin_line so ^ doesn't match interior.
Fixes issue #8402.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-16 12:21:00 +11:00
Damien George
adfd57c5fe lib/re1.5: Distinguish between subject start-of-line and start-of-srch.
Otherwise a repeated sub/split will continue to match ^ to the start of
that search.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-16 12:21:00 +11:00
Damien George
1692cad673 py/showbc: Remove global variables and make DECODE_PTR work correctly.
The bytecode state variables mp_showbc_code_start and mp_showbc_constants
have been removed and made local variables passed into the various
functions.

As part of this, the DECODE_PTR macro is fixed so it extracts the relevant
pointer from the child_table (a regression introduced in
f2040bfc7e).

Signed-off-by: Damien George <damien@micropython.org>
2022-03-16 11:59:46 +11:00
Damien George
962ad8622e py/parse: Handle check for target small-int size in parser.
This means that all constants for EMIT_ARG(load_const_obj, obj) are created
in the parser (rather than some in the compiler).

Signed-off-by: Damien George <damien@micropython.org>
2022-03-16 00:41:10 +11:00
Damien George
3c7cab4e98 py/parse: Put const bytes objects in parse tree as const object.
Instead of as an intermediate qstr, which may unnecessarily intern the data
of the bytes object.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-16 00:41:10 +11:00
Damien George
65851ebb51 py/parse: Simplify handling of const int parse nodes.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-16 00:00:25 +11:00
Damien George
eec07332b1 unix/variants: Enable a few optimisations and features on dev, coverage.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-10 13:34:43 +11:00
Damien George
3c20ddb41a unix/variants: Use rom feature config for standard, dev, coverage.
This change is a no-op in terms of functionality.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-10 13:32:25 +11:00
Damien George
0ac3191d8c unix/mpconfigport.h: Collect together config options from extra level.
This change is a no-op in terms of functionality.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-10 13:29:13 +11:00
Damien George
ac2293161e py/modsys: Add optional mutable attributes sys.ps1/ps2 and use them.
This allows customising the REPL prompt strings.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-10 10:58:33 +11:00
Damien George
cac939ddc3 py/modsys: Add optional sys.tracebacklimit attribute.
With behaviour as per CPython.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-10 10:43:21 +11:00
Damien George
bc181550a4 py/modsys: Add optional attribute delegation.
To be enabled when needed by specific sys attributes.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-10 10:43:21 +11:00
Damien George
3356b5ef8d py/objmodule: Support delegating failed attr lookups.
This commit adds generic support for mutable module attributes on built in
modules, by adding support for an optional hook function for module
attribute lookup.  If a module wants to support additional attribute load/
store/delete (beyond what is in the constant, globals dict) then it should
add at the very end of its globals dict MP_MODULE_ATTR_DELEGATION_ENTRY().
This should point to a custom function which will handle any additional
attributes.

The mp_module_generic_attr() function is provided as a helper function for
additional attributes: it requires an array of qstrs (terminated in
MP_QSTRnull) and a corresponding array of objects (with a 1-1 mapping
between qstrs and objects).  If the qstr is found in the array then the
corresponding object is loaded/stored/deleted.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-10 10:35:44 +11:00
Damien George
d470c5a5ba tests/extmod/vfs_posix.py: Only test statvfs if it exists.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-10 00:41:03 +11:00
Damien George
0149cd6b8b windows: Switch to VFS subsystem and use VfsPosix.
Following the unix port.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-10 00:26:36 +11:00
Damien George
2b409ef8a4 unix/moduos: Convert module to use extmod version.
All variants now use extmod/moduos.c as their uos module implementation.
In particular this means they all have MICROPY_VFS enabled and use VfsPosix
for their filesystem.

As part of this, the available functions in uos become more consistent with
other ports:
- coverage variant gets uos.urandom
- minimal and standard variant get: unlink, chdir, getcwd, listdir

Signed-off-by: Damien George <damien@micropython.org>
2022-03-09 21:13:57 +11:00
Damien George
ade2720e55 esp8266/moduos: Convert module to use extmod version.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-09 10:03:23 +11:00
Damien George
11b77263ef stm32/moduos: Convert module to use extmod version.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-09 10:03:23 +11:00
Damien George
9a3e1a1808 mimxrt/moduos: Convert module to use extmod version.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-09 10:03:23 +11:00
Damien George
20bfae1471 qemu-arm/moduos: Convert module to use extmod version.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-09 10:03:23 +11:00
Damien George
94077c6402 samd/moduos: Convert module to use extmod version.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-09 10:03:23 +11:00
Damien George
818be10bb5 zephyr/moduos: Convert module to use extmod version.
This also adds uos.unlink(), for all ports that use extmod/moduos.c.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-09 10:03:23 +11:00
Damien George
1c53d85162 esp32/moduos: Convert module to use extmod version.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-09 10:03:23 +11:00
Damien George
926b554daf extmod/moduos: Create general uos module to be used by all ports.
Based on the rp2 port version, with the rp2 port converted to use this
module.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-09 10:03:23 +11:00
iabdalkader
507ad03329 rp2: Add USB MSC support.
It is currently not enabled by default on any board.
2022-03-09 00:38:07 +11:00
Daniël van de Giessen
e2513bfe8d extmod/moduzlib: Fix parsing zlib header dict size.
From RFC 1950 section 2.2: "CINFO is the base-2 logarithm of the LZ77
window size, minus eight (CINFO=7 indicates a 32K window size)"

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2022-03-08 23:16:14 +11:00
robert-hh
e0b97013d0 mimxrt/hal/pwm_backport: Make PWM symmetric, and round division calcs.
Ensure the symmetry of PWM: the duty rate of X and Q channels was not 50%,
when it should have been.  That is evident at high frequencies, like 15Mhz
or 37.5 MHz.  At low frequencies the deviation mattered less.  The A/B
channels were fine.

Also round up or down non-integer division factors. Before, always the
floor value was used.
2022-03-08 23:11:17 +11:00
robert-hh
4774501cab mimxrt/eth: Avoid a race condition for Ethernet.
That caused Ethernet to lock up at high data rates after ~200MByte data
average in a row.  Tested now with data bursts up to 10 GByte and overall
data rates of ~8MByte/s at the Eth100 port.
2022-03-08 23:11:01 +11:00
robert-hh
04f92a2825 mimxrt/boards: Support using an optional board-specific manifest.py.
If the board directory contains a manifest.py file, it will be included.
File not found errors will be ignored.
2022-03-08 23:10:41 +11:00
robert-hh
c72dfbcef9 mimxrt/boards/TEENSY41: Use the same SPI1 pins for Teensy 4.0 and 4.1.
Teensy 4.1 used different pins for SPI1 than Teensy 4.0, which made the
boards unnecessarily different.
2022-03-08 23:09:47 +11:00
robert-hh
b0d460cd7d mimxrt/eth: Fix an Ethernet transmit error.
Sometimes frames could not be sent immediately because the controller was
still busy with previous frames.  Then, an error was returned to lwip.
This fix adds a limited number of retries for this busy state, waiting
100µs before the next attempt.  Typically the transmit succeeds now at the
second attempt.

Second change: Reset the controller for a clean state after soft reset.
2022-03-08 23:09:17 +11:00
robert-hh
5ea85b7a85 mimxrt/boards: Add board files for MIMXRT1015 and MIMXRT1015_EVK.
OCOTP_Init() has been removed from mphalport.c.  The library files are
missing for the MIMXRT1015, and for just reading the OCOTP the Init is not
required.
2022-03-08 23:08:44 +11:00
robert-hh
5cc50b9f1c mimxrt/machine_spi: Add omitted GPIO config.
The method was changed, but not for the CSx pins.  No functional change.
2022-03-08 23:08:30 +11:00
Philipp Ebensberger
62cb2069bb mimxrt/machine_pin: Change pin drive constants to DRIVE_x naming.
Updated DRIVE_x constants representing pin drive strength.

Signed-off-by: Philipp Ebensberger
2022-03-08 22:30:33 +11:00
Jonathan Hogg
3ebc370344 docs/library/machine.Pin: Update to use preferred DRIVE_x constants.
Update documents with new common names for the drive strength constants.
2022-03-07 23:47:45 +11:00
Jonathan Hogg
4c7c80d626 docs/esp32/quickref: Document GPIO drive strength.
Add brief documentation of the new `drive` keyword argument.
2022-03-07 23:41:29 +11:00
Jonathan Hogg
33083bf527 esp32/machine_pin: Add support for pin drive strength.
Add support for configuring drive strength of output pins with `drive` 
keyword argument and `DRIVE_*` constants.
2022-03-07 23:41:29 +11:00
Damien George
3440201e2e tests/micropython: Switch from set.pop to raise-0 to test exc strings.
To not rely on sets, which are an optional feature.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-07 16:48:35 +11:00
Damien George
9a8ee6a5df tests/run-tests.py: Include test files ending in _set as set tests.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-07 16:48:35 +11:00
Damien George
cced9a0128 zephyr/prj.conf: Enable CONFIG_BUILD_OUTPUT_HEX to generate .hex output.
The .hex file contains more information than .bin, useful for flashing.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-07 16:48:35 +11:00
Maureen Helm
474d288e55 zephyr: Upgrade to Zephyr v3.0.0.
Updates the Zephyr port build instructions and CI to use the latest
Zephyr release tag.

Signed-off-by: Maureen Helm <maureen.helm@intel.com>
2022-03-07 16:48:35 +11:00
Maureen Helm
86a4a52670 zephyr: Update include path to disk_access.h.
The disk_access header was moved to a different path in Zephyr v2.6.0.
The old path was deprecated for two releases (v2.6.0 and v2.7.0) and
will no longer be supported after Zephyr v2.7.0.

Signed-off-by: Maureen Helm <maureen.helm@intel.com>
2022-03-07 16:48:35 +11:00
Damien George
bf01671a96 tools/mpremote: Bump version to 0.2.0.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-07 16:02:55 +11:00
Damien George
7cd166ff92 tests/basics: Add test for creating small-ints in nan-box builds.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-07 15:25:11 +11:00
Damien George
bb2bd071f7 docs/library/esp32.rst: Mark esp32.Partition as not taking kw args.
Fixes issue #8380.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-07 15:15:45 +11:00
David Lechner
eadc927baf docs/differences/python_35: Mark PEP 486 as not applicable.
This adds the "Not relevant" designation to PEP 486 since it has to do with
the Python Launcher for Windows and not the Python language itself.

Also fix a typo while we are touching this line.

Signed-off-by: David Lechner <david@pybricks.com>
2022-03-07 14:15:21 +11:00
Jan
5d9171b5cc docs/library/machine.UART.rst: Add details for invert parameter. 2022-03-07 14:12:50 +11:00
robert-hh
d696d9141e esp32/machine_uart: Make UART.init preserve unspecified parameters.
Most of the settings behaved that way, except for baudate, timeout,
timout_char, invert and flow.
2022-03-07 13:45:50 +11:00
robert-hh
55a0125a15 esp32/machine_pwm: Always set the duty cycle when setting the frequency.
If setting the frequency to a value used already by an existing timer, this
timer will be used.  But still, the duty cycle for that channel may have to
be changed.

Fixes issues #8306 and #8345.
2022-03-07 13:37:23 +11:00
Daniël van de Giessen
665f0e2a68 esp32: Sleep one tick in MICROPY_EVENT_POLL_HOOK.
If MicroPython threads are enabled, loops waiting for an incoming event
should release the GIL and suspend, allowing other tasks to run while they
wait.

Prior to this commit, the problem can easily be observed by running a
thread that is both busy and regularly releases the GIL (for example a loop
doing something then sleeping a few ms after each iteration).  When the
main task is at the REPL, the thread is significantly stalled.  If the main
task is manually made to release the GIL (for example, by calling
utime.sleep_ms(500)) the other thread can be seen immediately working at
the expected speed again.

Additionally, there are various instances in where blocking functions run
MICROPY_EVENT_POLL_HOOK in a loop while they wait for a certain event/
condition.  For example the uselect methods poll objects to determine
whether data is available, but uses 100% of CPU while it does, constantly
calling MICROPY_EVENT_POLL_HOOK in the process.

The MICROPY_EVENT_POLL_HOOK macro is only ever used in waiting loops, where
(if threads are enabled) it makes sense to yield for a single tick so that
these loops do not consume all CPU cycles but instead other threads may
execute.  (In fact, the thing these loops wait for may even indirectly or
directly depend on another task being able to run.)

This change moves the sleep that was inside the REPL input function to
inside the MICROPY_EVENT_POLL_HOOK macro, where the GIL is already being
released, solving both the blocking REPL issue and the 100% CPU use issue
at the same time.

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2022-03-02 12:57:43 +11:00
Andrew Leech
919e586e46 esp32/machine_uart: Allow limited configuration of REPL UART.
Some applications may want to adjust the hard coded 115200 REPL buadrate,
and this commit allows it to be changed dynamically via machine.UART(0).
2022-03-01 18:16:50 +11:00
Andrew Leech
2cc9232781 esp32/uart: Correctly init low-level UART driver for REPL.
uart_driver_install() needs to be called to set up the UART correctly.
2022-03-01 17:33:36 +11:00
YoungJoon Chun
2d47020e15 rp2/mpthreadport: Fix memory corruption when thread is created in core1.
The stack (and arg) of core1 is itself a root pointer, not just the entries
in it.  Without this fix the GC could reclaim the entire stack (and
argument object).

Fixes issues #7124 and #7981.
2022-03-01 17:03:57 +11:00
stijn
795370ca23 py/bc.h: Fix C++ compilation of public API.
Casts between unrelated types must be explicit.  Regression in
f2040bfc7e
2022-03-01 16:17:30 +11:00
Damien George
3c2aa5ff93 unix/.gitignore: Remove *.py from ignore list.
.py files are valid source files and shouldn't be ignored.  This line was
from the early days when .py files in the unix directory were used for
testing.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-28 19:02:58 +11:00
Damien George
8626dcd623 tools/ci.sh: Run performance benchmark as part of all unix test runs.
This tests that the performance benchmarks run without error.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-28 19:02:58 +11:00
Damien George
c4b8dae438 tests/unix: Add coverage test for freezing various objects.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-28 19:02:58 +11:00
robert-hh
5c46721a1c tools/mpy-tool.py: Fix frozen comment generation to escape chars.
That caused the compile of frozen_content.c to fail if characters like
backslash were in a short string.  Thanks to @hippy for identifying the
spot to change.
2022-02-28 18:47:24 +11:00
Damien George
0a217624e1 tools/upip.py: Remove unused op_basename() function.
It seems this was never used, at least not since its inclusion in this
repository.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-25 18:24:03 +11:00
Damien George
546e213265 esp32/boards: Add specific deploy instructions for S3 variant.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-25 16:52:58 +11:00
stijn
c2e8a5acd2 windows: Unify project file headers.
The xmlns attribute is required for older msbuild version (e.g. for
VS2015).  Add it where needed, and reorder the attributes so all
files look the same.
2022-02-25 16:41:11 +11:00
Damien George
d6564a3159 tools/mpremote: Add "umount" command.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-25 13:10:45 +11:00
Damien George
ad1f523e7e tools/mpremote: Add "resume" and "soft-reset" commands.
This makes the auto soft-reset behaviour of mpremote more logical, and now
configurable via these new commands.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-25 13:09:28 +11:00
Damien George
414b59d39c qemu-arm: Add tests for freezing viper and asm_thumb code.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-24 18:29:02 +11:00
Damien George
0a2895b099 tests/perf_bench: Skip bm_chaos test if random.randrange is unavailable.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-24 18:29:02 +11:00
Damien George
66fc0f45c1 tools/ci.sh: Run urandom test scripts as part of native module tests.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-24 18:29:02 +11:00
Damien George
73a1927fce github/workflows: Add new workflow to test .mpy file format and tools.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-24 18:29:02 +11:00
Damien George
c0f2af4e86 ports: Recompile bytecode tests now that .mpy format changed.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-24 18:29:02 +11:00
Damien George
f2040bfc7e py: Rework bytecode and .mpy file format to be mostly static data.
Background: .mpy files are precompiled .py files, built using mpy-cross,
that contain compiled bytecode functions (and can also contain machine
code). The benefit of using an .mpy file over a .py file is that they are
faster to import and take less memory when importing.  They are also
smaller on disk.

But the real benefit of .mpy files comes when they are frozen into the
firmware.  This is done by loading the .mpy file during compilation of the
firmware and turning it into a set of big C data structures (the job of
mpy-tool.py), which are then compiled and downloaded into the ROM of a
device.  These C data structures can be executed in-place, ie directly from
ROM.  This makes importing even faster because there is very little to do,
and also means such frozen modules take up much less RAM (because their
bytecode stays in ROM).

The downside of frozen code is that it requires recompiling and reflashing
the entire firmware.  This can be a big barrier to entry, slows down
development time, and makes it harder to do OTA updates of frozen code
(because the whole firmware must be updated).

This commit attempts to solve this problem by providing a solution that
sits between loading .mpy files into RAM and freezing them into the
firmware.  The .mpy file format has been reworked so that it consists of
data and bytecode which is mostly static and ready to run in-place.  If
these new .mpy files are located in flash/ROM which is memory addressable,
the .mpy file can be executed (mostly) in-place.

With this approach there is still a small amount of unpacking and linking
of the .mpy file that needs to be done when it's imported, but it's still
much better than loading an .mpy from disk into RAM (although not as good
as freezing .mpy files into the firmware).

The main trick to make static .mpy files is to adjust the bytecode so any
qstrs that it references now go through a lookup table to convert from
local qstr number in the module to global qstr number in the firmware.
That means the bytecode does not need linking/rewriting of qstrs when it's
loaded.  Instead only a small qstr table needs to be built (and put in RAM)
at import time.  This means the bytecode itself is static/constant and can
be used directly if it's in addressable memory.  Also the qstr string data
in the .mpy file, and some constant object data, can be used directly.
Note that the qstr table is global to the module (ie not per function).

In more detail, in the VM what used to be (schematically):

    qst = DECODE_QSTR_VALUE;

is now (schematically):

    idx = DECODE_QSTR_INDEX;
    qst = qstr_table[idx];

That allows the bytecode to be fixed at compile time and not need
relinking/rewriting of the qstr values.  Only qstr_table needs to be linked
when the .mpy is loaded.

Incidentally, this helps to reduce the size of bytecode because what used
to be 2-byte qstr values in the bytecode are now (mostly) 1-byte indices.
If the module uses the same qstr more than two times then the bytecode is
smaller than before.

The following changes are measured for this commit compared to the
previous (the baseline):
- average 7%-9% reduction in size of .mpy files
- frozen code size is reduced by about 5%-7%
- importing .py files uses about 5% less RAM in total
- importing .mpy files uses about 4% less RAM in total
- importing .py and .mpy files takes about the same time as before

The qstr indirection in the bytecode has only a small impact on VM
performance.  For stm32 on PYBv1.0 the performance change of this commit
is:

diff of scores (higher is better)
N=100 M=100             baseline -> this-commit  diff      diff% (error%)
bm_chaos.py               371.07 ->  357.39 :  -13.68 =  -3.687% (+/-0.02%)
bm_fannkuch.py             78.72 ->   77.49 :   -1.23 =  -1.563% (+/-0.01%)
bm_fft.py                2591.73 -> 2539.28 :  -52.45 =  -2.024% (+/-0.00%)
bm_float.py              6034.93 -> 5908.30 : -126.63 =  -2.098% (+/-0.01%)
bm_hexiom.py               48.96 ->   47.93 :   -1.03 =  -2.104% (+/-0.00%)
bm_nqueens.py            4510.63 -> 4459.94 :  -50.69 =  -1.124% (+/-0.00%)
bm_pidigits.py            650.28 ->  644.96 :   -5.32 =  -0.818% (+/-0.23%)
core_import_mpy_multi.py  564.77 ->  581.49 :  +16.72 =  +2.960% (+/-0.01%)
core_import_mpy_single.py  68.67 ->   67.16 :   -1.51 =  -2.199% (+/-0.01%)
core_qstr.py               64.16 ->   64.12 :   -0.04 =  -0.062% (+/-0.00%)
core_yield_from.py        362.58 ->  354.50 :   -8.08 =  -2.228% (+/-0.00%)
misc_aes.py               429.69 ->  405.59 :  -24.10 =  -5.609% (+/-0.01%)
misc_mandel.py           3485.13 -> 3416.51 :  -68.62 =  -1.969% (+/-0.00%)
misc_pystone.py          2496.53 -> 2405.56 :  -90.97 =  -3.644% (+/-0.01%)
misc_raytrace.py          381.47 ->  374.01 :   -7.46 =  -1.956% (+/-0.01%)
viper_call0.py            576.73 ->  572.49 :   -4.24 =  -0.735% (+/-0.04%)
viper_call1a.py           550.37 ->  546.21 :   -4.16 =  -0.756% (+/-0.09%)
viper_call1b.py           438.23 ->  435.68 :   -2.55 =  -0.582% (+/-0.06%)
viper_call1c.py           442.84 ->  440.04 :   -2.80 =  -0.632% (+/-0.08%)
viper_call2a.py           536.31 ->  532.35 :   -3.96 =  -0.738% (+/-0.06%)
viper_call2b.py           382.34 ->  377.07 :   -5.27 =  -1.378% (+/-0.03%)

And for unix on x64:

diff of scores (higher is better)
N=2000 M=2000        baseline -> this-commit     diff      diff% (error%)
bm_chaos.py          13594.20 ->  13073.84 :  -520.36 =  -3.828% (+/-5.44%)
bm_fannkuch.py          60.63 ->     59.58 :    -1.05 =  -1.732% (+/-3.01%)
bm_fft.py           112009.15 -> 111603.32 :  -405.83 =  -0.362% (+/-4.03%)
bm_float.py         246202.55 -> 247923.81 : +1721.26 =  +0.699% (+/-2.79%)
bm_hexiom.py           615.65 ->    617.21 :    +1.56 =  +0.253% (+/-1.64%)
bm_nqueens.py       215807.95 -> 215600.96 :  -206.99 =  -0.096% (+/-3.52%)
bm_pidigits.py        8246.74 ->   8422.82 :  +176.08 =  +2.135% (+/-3.64%)
misc_aes.py          16133.00 ->  16452.74 :  +319.74 =  +1.982% (+/-1.50%)
misc_mandel.py      128146.69 -> 130796.43 : +2649.74 =  +2.068% (+/-3.18%)
misc_pystone.py      83811.49 ->  83124.85 :  -686.64 =  -0.819% (+/-1.03%)
misc_raytrace.py     21688.02 ->  21385.10 :  -302.92 =  -1.397% (+/-3.20%)

The code size change is (firmware with a lot of frozen code benefits the
most):

       bare-arm:  +396 +0.697%
    minimal x86: +1595 +0.979% [incl +32(data)]
       unix x64: +2408 +0.470% [incl +800(data)]
    unix nanbox: +1396 +0.309% [incl -96(data)]
          stm32: -1256 -0.318% PYBV10
         cc3200:  +288 +0.157%
        esp8266:  -260 -0.037% GENERIC
          esp32:  -216 -0.014% GENERIC[incl -1072(data)]
            nrf:  +116 +0.067% pca10040
            rp2:  -664 -0.135% PICO
           samd:  +844 +0.607% ADAFRUIT_ITSYBITSY_M4_EXPRESS

As part of this change the .mpy file format version is bumped to version 6.
And mpy-tool.py has been improved to provide a good visualisation of the
contents of .mpy files.

In summary: this commit changes the bytecode to use qstr indirection, and
reworks the .mpy file format to be simpler and allow .mpy files to be
executed in-place.  Performance is not impacted too much.  Eventually it
will be possible to store such .mpy files in a linear, read-only, memory-
mappable filesystem so they can be executed from flash/ROM.  This will
essentially be able to replace frozen code for most applications.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-24 18:08:43 +11:00
Damien George
64bfaae7ab esp32/README.md: Update list of supported IDF versions.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-24 15:23:50 +11:00
Damien George
b1afbe3336 tools/ci.sh: Update IDF v4.4 build to use v4.4 tag.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-24 15:23:32 +11:00
stijn
5f50f4a130 unix: Show compiler info in REPL banner.
The unix port's main.c gets used by unix and windows ports, and with a
variety of compilers, so it's convenient to see which version is actually
being used immediately when starting micropython.  This is similar to what
CPython does.
2022-02-22 00:59:31 +11:00
stijn
49934fcf8b extmod/moduplatform: Move platform PP definitions into a header.
These are more generally useful than just for the module so make them
globally available, prefixed consistently with MICROPY_PLATFORM_.
2022-02-22 00:59:14 +11:00
Damien George
f30b32e084 esp32/modules: Create ffat partition object with block_size=512.
Because these are formatted with a 512 sector size.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-22 00:37:55 +11:00
Damien George
106a83de22 esp32/esp32_partition: Add support for specifying block_size.
To support filesystems that use a block size different from the native
erase-page size.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-22 00:37:25 +11:00
Damien George
5935fa229c esp32/mpconfigport.h: Enable remaining features to get to "extra" level.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-18 16:01:18 +11:00
Damien George
c8cd5a9960 esp32/mpconfigport.h: Use the "extra" feature level.
This commit is a no-op change to simplify existing config.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-18 15:50:01 +11:00
stijn
ff9c708507 tests/run-tests.py: Skip repl tests when running windows underneath.
Some versions of Python (for instance: the mingw-w64 version which can be
installed on MSYS2) do include a pty module and claim to be posix-like
(os.name == 'posix'), yet the select.select call used in run-tests.py hangs
forever.  To be on the safe side just exclude anything which might be
running on windows.
2022-02-18 15:14:47 +11:00
Damien George
5995fb5261 stm32/mboot: Allow a board more control over entry initialisation.
If MBOOT_BOARD_ENTRY_INIT is defined by a board then that function must now
make sure system clocks are configured, eg by calling mboot_entry_init().

Signed-off-by: Damien George <damien@micropython.org>
2022-02-18 14:59:35 +11:00
Damien George
2b62f12103 stm32/mboot: Allow a board to fully configure system clocks.
If a board wants to customise the clocks it can define the following:

    MBOOT_CLK_PLLM
    MBOOT_CLK_PLLN
    MBOOT_CLK_PLLP
    MBOOT_CLK_PLLQ
    MBOOT_CLK_PLLR (only needed on STM32H7)
    MBOOT_FLASH_LATENCY
    MBOOT_CLK_AHB_DIV
    MBOOT_CLK_APB1_DIV
    MBOOT_CLK_APB2_DIV
    MBOOT_CLK_APB3_DIV (only needed on STM32H7)
    MBOOT_CLK_APB4_DIV (only needed on STM32H7)

Signed-off-by: Damien George <damien@micropython.org>
2022-02-18 14:51:01 +11:00
Christophe Priouzeau
130f7db1fc stm32/boards/NUCLEO_WB55: Add Arduino pin alias definitions.
Fixes issue #8295.

Signed-off-by: Christophe Priouzeau <christophe.priouzeau@foss.st.com>
2022-02-18 14:45:49 +11:00
stijn
c14f47faa3 windows/Makefile: Specify CXXFLAGS in the Makefile.
Enables building user modules which use C++ code, like the unix port.
2022-02-18 14:40:36 +11:00
stijn
8bb50c6301 unix/Makefile: Remove explicit addition of -std=c++ flag.
This was added merely for building the C++ user module example, so it's a
better fit to add it in the corresponding micropython.mk.
2022-02-18 14:40:16 +11:00
robert-hh
9c05f3aa1d drivers/sdcard: Allow setting the final SPI baudrate.
This baudrate is supplied in the constructor. The default is 1320000 as
before.

Example:

    sd = sdcard.SDCard(spi, cs, baudrate=20_000_000)
2022-02-18 14:37:44 +11:00
iabdalkader
465b74e78d drivers/ninaw10: Add NIC-level ioctl function.
This commit adds support in the driver for irregular commands.  It
currently supports setting GPIO pin mode, and GPIO pin read/write value.
2022-02-18 14:35:26 +11:00
David Lechner
5d6408f8f9 tools/verifygitlog.py: Ignore line length in body if it's a URL.
This changes the git commit message line length check to ignore lines that
contain URLs, since these cannot be wrapped without breaking tools that
detect URLs and create a link.

Signed-off-by: David Lechner <david@pybricks.com>
2022-02-18 14:33:33 +11:00
David Lechner
28cb573b89 windows/appveyor: Fix printing of test failures.
In the `after_test` section, the current directory is `ports/windows` when
tests are run, so running `run-tests.py` without changing the directory or
specifying a path causes a file not found error.

This commit fixes the problem by changing the directory before calling
`run-tests.py`.

Signed-off-by: David Lechner <david@pybricks.com>
2022-02-18 14:31:52 +11:00
Bradley Wogsland
0dfd0447fa README: Update link for ARM embedded toolchain to developer.arm.com. 2022-02-18 14:28:29 +11:00
YoungJoon Chun
767058f328 rp2/Makefile: Add FROZEN_MANIFEST Makefile option, to override default. 2022-02-18 14:26:57 +11:00
Damien George
18acd0318f py/gc: Update debug code to compile with changes to qstr pool types.
Following on from 18b1ba086c and
f46a7140f5.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-17 11:17:21 +11:00
Damien George
2ea21abae0 tests/extmod/vfs_fat_finaliser.py: Make finalisation more robust.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-12 09:45:32 +11:00
Artyom Skrobov
f46a7140f5 py/qstr: Use const consistently to avoid a cast.
Originally at adafruit#4707

Signed-off-by: Artyom Skrobov <tyomitch@gmail.com>
2022-02-11 22:55:02 +11:00
Artyom Skrobov
18b1ba086c py/qstr: Separate hash and len from string data.
This allows the compiler to merge strings: e.g. "update",
"difference_update" and "symmetric_difference_update" will all point to the
same memory.

No functional change.

The size reduction depends on the number of qstrs in the build.  The change
this commit brings is:

   bare-arm:    -4 -0.007%
minimal x86:  +150 +0.092% [incl +48(data)]
   unix x64:  -608 -0.118%
unix nanbox:  -572 -0.126% [incl +32(data)]
      stm32: -1392 -0.352% PYBV10
     cc3200:  -448 -0.244%
    esp8266: -1208 -0.173% GENERIC
      esp32: -1028 -0.068% GENERIC[incl -1020(data)]
        nrf:  -440 -0.252% pca10040
        rp2: -1072 -0.217% PICO
       samd:  -368 -0.264% ADAFRUIT_ITSYBITSY_M4_EXPRESS

Performance is also improved (on bare metal at least) for the
core_import_mpy_multi.py, core_import_mpy_single.py and core_qstr.py
performance benchmarks.

Originally at adafruit#4583

Signed-off-by: Artyom Skrobov <tyomitch@gmail.com>
2022-02-11 22:52:32 +11:00
Damien George
e8bc4a3a5b tests/run-perfbench.py: Use SKIP consistently, and increase print width.
A script will print "SKIP" if it wants to be skipped, so the test runner
must also use uppercase SKIP.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-11 22:19:38 +11:00
Damien George
a434705700 tests/perf_bench: Add perf test for yield-from execution.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-11 13:42:00 +11:00
Damien George
75da124cf8 tests/perf_bench: Add perf tests for qstr interning and importing .mpy.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-10 15:25:33 +11:00
Damien George
b33fdbe535 tests/run-perfbench.py: Allow a test to SKIP, and to have a .exp file.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-10 15:25:33 +11:00
YoungJoon Chun
d8a7bf83cc rp2/machine_uart: Fix UART RTS behaviour so RTS is deasserted.
The UART hardware flow control was not working correctly, the receive FIFO
was always fetched and RTS was never deasserted.  This is not a problem
when hardware flow control is not used: normally, if the receive FIFO is
full, the UART receiver won't receive data into the FIFO anymore, but the
current implementation fetches from the FIFO and discards it instead.
The problem is that data is discarded even when RTS is enabled.

This commit fixes the issue by only taking from the FIFO if there is room
in the ring buffer to put the character.

Signed-off-by: YoungJoon Chun <yjchun@mac.com>
2022-02-09 16:29:53 +11:00
Lars Kellogg-Stedman
8f6924c9fb docs/library/uasyncio.rst: Fix description of ThreadSafeFlag.wait.
When a task waits on a ThreadSafeFlag (and the wait method returns), the
flag is immediately reset.  This was not clear in the documentation, which
appeared to copy the description of the wait method from the Event class.

Signed-off-by: Lars Kellogg-Stedman <lars@oddbit.com>
2022-02-09 16:09:48 +11:00
Jos Verlinde
6653856b87 docs/library/machine.Pin.rst: Document defaults for Pin.init. 2022-02-09 15:55:10 +11:00
Jos Verlinde
7f67524031 docs/library/pyb.SPI.rst: Document default for prescaler argument.
To prevent "non-default argument follows default argument" errors.
2022-02-09 15:06:34 +11:00
Jos Verlinde
58cd2a8b0a docs/library/esp.rst: Document the osdebug function. 2022-02-09 15:06:19 +11:00
Jos Verlinde
f99b679916 docs/library/machine.WDT.rst: Use correct case for WDT.feed. 2022-02-09 15:05:49 +11:00
Jos Verlinde
7621b17636 docs/library/machine.SPI.rst: Add class constant SoftSPI.MSB and .LSB. 2022-02-09 15:05:38 +11:00
Jos Verlinde
8715ad9ccf docs/library/pyb.DAC.rst: Add DAC class constants. 2022-02-09 15:05:26 +11:00
Jos Verlinde
ba4f6f5fdf docs/library/pyb.rst: Add pyb.hid_mouse and pyb.hid_keyboard constants. 2022-02-09 15:04:57 +11:00
Jos Verlinde
50b172023f docs/library/pyb.Timer.rst: Add pyb.Timer class constants. 2022-02-09 15:04:24 +11:00
Jos Verlinde
2c30ac7aeb docs/library/socket.rst: Document socket as a class.
Following CPython: https://bugs.python.org/issue45772
2022-02-09 15:03:26 +11:00
Jos Verlinde
cd0531c533 docs: Use the correct * keyword-only notation. 2022-02-09 15:01:00 +11:00
Jos Verlinde
a41abd94dc docs/library/collections.rst: Use class for deque and OrderedDict. 2022-02-09 15:00:00 +11:00
iabdalkader
30a022548f tests/multi_net/udp_data.py: Make UDP test more reliable.
The current test depends on a specific number and order of packets to pass,
which can't be reproduced every run due to the unreliable UDP protocol.
This patch adds simple packets sequencing, retransmits with timeouts, and a
packet loss threshold, to make the test more tolerant to UDP protocol
packet drops and reordering.
2022-02-09 14:05:01 +11:00
Seon Rozenblum
aca40127bf esp32/boards: Add three UM ESP32-S3 based boards. 2022-02-09 00:13:10 +11:00
Damien George
468d1979ba esp32/machine_adc: Fix configuration of default ADC atten value.
Prior to this fix, if the ADC atten value was not explicitly given then
adc1_config_channel_atten() would never be called.

Fixes issue #8275.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-08 23:45:41 +11:00
Seon Rozenblum
ada836b834 esp32/machine_adcblock: Fix ADC bit width for ESP32-S3. 2022-02-08 12:35:47 +11:00
Damien George
6fe3856c4f esp32/partitions-16MiB.csv: Increase 14MiB filesystem to maximum size.
The original value was 14000000, it's now changed to 14 * 1024 * 1024.

Fixes issue #8266.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-08 12:25:10 +11:00
Andrew Leech
6f7d6c567f windows/uasyncio: Add support for uasyncio to windows dev variant. 2022-02-07 14:39:15 +11:00
Andrew Leech
c708262c12 windows/uselect: Enable micropython select in dev variant. 2022-02-07 14:39:15 +11:00
Andrew Leech
69c9a76786 windows/mingw: Include extmod/shared/lib sources properly. 2022-02-07 14:39:15 +11:00
Damien George
fecfd52696 tools/mpremote: Fix special handling of ctrl-D when host FS is mounted.
Changes are:
- decision to remount local filesystem on remote device is made only if
  "MPY: soft reboot" is seen in the output after sending a ctrl-D
- a nice message is printed to the user when the remount occurs
- soft reset during raw REPL is now handled correctly

Fixes issue #7731.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-07 13:21:29 +11:00
Andrew Leech
203ec8ca7f tools/mpremote: Correctly manage mounted flag during soft-reset. 2022-02-04 16:19:25 +11:00
Andrew Leech
b1519845f5 tools/mpremote: Accept both --help and help to show usage. 2022-02-04 15:11:04 +11:00
Andrew Leech
5a86d8dc42 tools/mpremote: During soft reboot wait long enough for 115200 data. 2022-02-04 15:09:01 +11:00
Andrew Leech
d865ca53b5 tools/mpremote: Make ConsolePosix work without .raw attribute.
When running mpremote in the vscode terminal on OSX the sys.stdout.buffer
does not have the raw attribute.  It works fine without it.
2022-02-04 15:04:02 +11:00
Andrew Leech
1f84440538 tools/mpremote: Fix "fs cp -r" on Windows.
A backslash in the directory name will end up being passed through to the
device and becoming a backslash in a filename, rather than being
interpreted as directories.  This makes "cp -r" problematic on Windows.
Changing to simply "/",join() fixes this.
2022-02-04 14:58:29 +11:00
Damien George
a7530cbc03 stm32/boards/NUCLEO_L432KC: Disable MICROPY_OPT_COMPUTED_GOTO.
To save space, after recent fixes to L4 ADC made it overflow flash.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-04 14:28:21 +11:00
Peter Hinch
80b81acea5 docs/reference/isr_rules.rst: Describe uasyncio-IRQ interface. 2022-02-04 12:27:16 +11:00
Jonathan Hogg
a43764e654 docs/esp32/quickref: Update ADC documentation.
Update ADC documentation now that the new API is described in the main
docs.
2022-02-04 12:05:15 +11:00
Luiz Brandao
ddda959e57 docs/reference/isr_rules.rst: Fix inconsistent variable name in example.
Fixed to be conistent with the code example above it.
2022-02-04 11:20:15 +11:00
Cem Eliguzel
5943a2ec79 docs/develop/porting.rst: Fix build and import problems in the example. 2022-02-04 11:15:46 +11:00
Damien George
5679fe6aee rp2/modutime: Fix time.localtime day-of-week value.
The correct day-of-week is stored in the RTC (0=Monday, 6=Sunday) so there
is no need to adjust it for the return value of time.localtime().

Fixes issue #7889.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-04 10:48:59 +11:00
iabdalkader
31f2440388 stm32/adc: Remove obsolete FIRST/LAST GPIO channel macros. 2022-02-04 10:45:11 +11:00
iabdalkader
e5df4a96fa stm32/adc: Fix L4 ADC channel numbers.
Use HAL macro to map decimal numbers to channel numbers.  This is needed
since updating L4 HAL v1.17.0 in a0f5b3148a.

Fixes issue #8233.
2022-02-04 10:42:38 +11:00
Peter D. Gray
ae5f647a2d stm32/system_stm32: Make SystemClock_Config() a weak symbol.
This allows boards to override as needed.
2022-02-04 10:29:53 +11:00
Damien George
e306f2285b stm32/boards/NUCLEO_WL55: Add new board definition.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-04 09:43:43 +11:00
Damien George
e0a0719416 stm32: Add initial support for STM32WL MCUs.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-04 09:43:43 +11:00
Damien George
9127e63708 stm32/Makefile: Make stm32lib configurable.
The default stm32lib remains lib/stm32lib, but it can now be easily
overriden at build time by specifying STM32LIB_DIR, or STM32LIB_CMSIS_DIR
and STM32LIB_HAL_DIR.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-04 09:43:43 +11:00
Damien George
e4f59a0020 stm32/rtc: Use LL_RTC functions to simplify some MCU-specific code.
This also fixes a possible race condition when exiting initialisation mode:
reading then writing to ISR (via ISR &= ~RTC_ISR_INIT) will clear any flags
that were set by the hardware between the read and the write.  The correct
way to clear just the INIT bit is to just do a single write via ISR =
~RTC_ISR_INIT, which will not clear any other flags (they must be written
to 0 to clear), and that is exactly what LL_RTC_DisableInitMode does.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-04 08:35:14 +11:00
Damien George
26faf74d52 stm32/mboot: Add support for F469/479 MCUs in fwupdate.py.
And don't assert on the sector number in sector_erase, so it can support
erasing arbitrary sectors.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-03 13:21:57 +11:00
Damien George
4f918f4b26 stm32/mboot: Add MBOOT_BOARD_ENTRY_INIT for a board to add entry code.
Also change the signature of stm32_main to uint32_t, which is what it
should be.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-03 13:20:51 +11:00
Damien George
b8d55d4c52 stm32/mboot: Allow HSI to be used as the main clock source.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-03 13:20:22 +11:00
Damien George
fbd47fc46c ports: Consolidate inclusion of umachine module in built-ins.
The inclusion of `umachine` in the list of built-in modules is now done
centrally in py/objmodule.c.  Enabling MICROPY_PY_MACHINE will include this
module.

As part of this, all ports now have `umachine` as the core module name
(previously some had only `machine` as the name).

Signed-off-by: Damien George <damien@micropython.org>
2022-02-03 10:08:54 +11:00
Damien George
102cc12dbb tools/autobuild: Provide .uf2 images for esp32 builds when available.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-02 23:47:49 +11:00
Damien George
71b3ce3ace esp32: Create .uf2 binaries for S2 and S3 chips.
The name of the filesystem partition is updated to support "ffat", as used
by TinyUF2.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-02 23:47:49 +11:00
Damien George
59b6099508 tools/uf2conv.py: Update to latest version.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-02 23:43:58 +11:00
Damien George
feeeb5ea3a top: Update .git-blame-ignore-revs for latest Black formatting commits.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-02 16:50:14 +11:00
Damien George
ab2923dfa1 all: Update Python formatting to latest Black version 22.1.0.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-02 16:49:55 +11:00
Damien George
326b2c79df docs: Remove reference to obsolete neopixel_write function.
It has been replaced by machine.bitstream.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-02 16:27:10 +11:00
Damien George
872bab6b3c esp32: Remove unneeded modesp.h.
Made redundant by 71f4faac27

Signed-off-by: Damien George <damien@micropython.org>
2022-02-02 16:20:41 +11:00
Emil Kondayan
b18d4392b4 esp32/adc: Fix wrong mapping between ADC2 channel and GPIO number.
According to the IO_MUX table in the ESP32 datasheet, the ADC2 channels are
mapped to different GPIO numbers.
2022-02-02 15:29:02 +11:00
Michael O'Cleirigh
eae2e3516c esp32/main: Automatically size SPIRAM heap when allocated using malloc.
This change allows the same heap allocation rules to be used when using
malloc regardless if the board has SPRAM or normal RAM.

Integrating with the esp32-camera for example requires that ESP32 SPRAM be
allocatable using the esp-idf capabilities aware allocation functions.  In
the case of esp32-camera it's for the framebuffer.

Detect when CONFIG_SPIRAM_USE_MALLOC is in use and use the standard
automatic configuration of leaving 1/2 of the SPRAM available to other
FreeRTOS tasks.
2022-02-02 15:24:02 +11:00
Damien George
1f04a9a1fc esp32/esp32_rmt: Select correct last RMT channel on S2, S3, C3 variants.
For example the ESP32-C3 has 2 TX channels and 2 RX channels in total, and
in this case channel 1 must be the default for bitstream.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-01 16:58:56 +11:00
IhorNehrutsa
15e65b77eb esp32/machine_pwm: Clean up macro names and their use.
- Remove UI_RES_SHIFT macro.
- Rename PWFREQ to PWM_FREQ.
- Rename PWRES to PWM_RES_10_BIT.
- Use UI_RES_16_BIT flag instead of HIGHEST_PWM_RES.
2022-02-01 16:47:29 +11:00
IhorNehrutsa
a5e64c209f esp32/machine_pwm: Fix PWM not allowing frequencies < 611 Hz.
Fixes issue #8189.
2022-02-01 16:46:55 +11:00
Damien George
a5003ba407 gitmodules: Update branch for stm32lib submodule.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-01 16:21:01 +11:00
Herwin Grobben
8f68e26f79 stm32: Add support for G4 MCUs, and add NUCLEO_G474RE board defn.
This commit adds support for the STM32G4 series of MCUs, and a board
definition for NUCLEO_G474RE.  This board has the REPL on LPUART1 which is
connected to the on-board ST-link USB-UART.
2022-02-01 16:21:01 +11:00
Damien George
60e05ae84e stm32/mboot: Compute and check CRC32 of dfu file in fwupdate.py.
Signed-off-by: Damien George <damien@micropython.org>
2022-01-31 18:49:08 +11:00
Damien George
ca1914fb47 stm32/mboot: Support H7 MCUs in fwupdate.py.
And optimise the speed of flash writing.

Signed-off-by: Damien George <damien@micropython.org>
2022-01-31 18:26:55 +11:00
Damien George
29867a2439 stm32/mboot: Include hal_rcc_ex.c in source file list.
It's needed at least on F4 because this file overrides the weak function
HAL_RCC_DeInit() from hal_rcc.c.

Signed-off-by: Damien George <damien@micropython.org>
2022-01-31 18:26:55 +11:00
Damien George
c8c229b96c stm32/mboot: Use PLL3 for USB clock source on H7 MCUs.
PLL3-Q is more reliable than PLL1-Q for the USB clock source when entering
mboot from various reset states (eg power on vs MCU reset).  (It was found
that if the main application used PLL3-Q then sometimes the USB clock
source would stay stuck on PLL3-Q and not switch to PLL1-Q after a reset.)

Other related changes:
- SystemCoreClockUpdate() should be called on H7 because the calculation
  can be involved in some cases.
- __set_PRIMASK(0) should be called because on H7 the built-in ST DFU
  bootloader exits with IRQs disabled.

Signed-off-by: Damien George <damien@micropython.org>
2022-01-31 18:26:55 +11:00
Damien George
c99ed8d6fa stm32/powerctrl: Write bootloader-state as 64-bit word to work on H7.
H7 MCUs have ECC and writes do not go through to SRAM until 64-bits have
been written (on another location is written).  So use 64-bit writes for
the bootloader-state variable so it is committed before the system reset.

As part of this change, the lower byte of the bootloader address in
BL_STATE must now be the magic number 0x5a5 for the state to be valid
(previously this was 0x000 which is not as robust).

Signed-off-by: Damien George <damien@micropython.org>
2022-01-31 18:26:55 +11:00
Damien George
4a4f269a1a stm32/powerctrlboot: Set HAL uwTickPrio variable when needed.
Signed-off-by: Damien George <damien@micropython.org>
2022-01-31 18:26:55 +11:00
Damien George
14becd80c9 stm32/usbd_conf: Set lpm_enable and battery_charging_enable on all MCUs.
Signed-off-by: Damien George <damien@micropython.org>
2022-01-31 16:38:32 +11:00
Herwin Grobben
517e82eb6b stm32/fdcan: Fix naming with regards to G4 series. 2022-01-27 23:06:13 +11:00
Herwin Grobben
160e4d9a6d stm32/fdcan: Fix FIFO1 usage and handling of error interrupts.
The original code used a independent state with regards to the interrupt.
During heavy bus error conditions the internal state could become
out-of-sync with the interrupts.

Further explanation: during the development of an application using CAN
communication, a interrupt-run-away was found in some situations.  It was
found that the error interrupt triggered (Warning, Passive or Bus-Off, all
triggered it) the run-away.  The only recovery was a reset.

Two problems were found:
- the error interrupt is enabled but not cleared in the interrupt routine;
- an internal variable 'State' that was used to track the message received
  state (empty, new, full, overflow) that was not directly related to
  interrupt that indicated the state.

In this commit these issues are fixed by adding more values for the
interrupt reason (warning, passive, bus off) and clearing the error
interrupts, and making the internal state directly dependent on the
interrupt state for received messages.

Furthermore, introducing the FIFO1 in the CAN receive stage, another issue
existed.  Even if the messages are received into the FIFO1 (by selecting
message filtering for FIFO0 and FIFO1), the interrupt firing was indicating
FIFO0 Rx.  The configuration of the interrupts for this is now also fixed.
The CAN peripheral has 2 interrupt lines going into the NVIC controller.
The assignment of the interrupt reasons to these 2 interrupt lines was
missing.  Now the reception of FIFO1 messages triggers the second interrupt
line.  Other interrupts (Rx FIFO0 and bus error) are assigned to the first
interrupt line.

Tested on a Nucleo-G474, and also checked the HAL function to work with the
H7 family.
2022-01-27 23:01:08 +11:00
iabdalkader
a00e1e5735 stm32/dac: Deinit all DACs on soft reset.
DAC timed functions continue to run after a soft reset cycle, using
collected memory in the case of write_timed.
2022-01-27 17:10:39 +11:00
robert-hh
c1841c2d45 mimxrt: Simplify Makefile in selection of flash type.
Simplify it a little bit by combining two sections regarding the
flash type. Thanks to @alphaFred for suggesting it.
2022-01-27 17:05:45 +11:00
robert-hh
da9c3607a5 mimxrt: Add support for the Olimex RT1010 board.
The board.json file is intentionally excluded, until the board will be
sold. But including it into the mimxrt series make it easier to keep
the build up-to-date.
2022-01-27 17:05:45 +11:00
robert-hh
b73073d246 mimxrt: Add USB ID elements.
- Manufacturer, set by MICROPY_HW_USB_STR_MANUF; default "MicroPython"
- Board name, as set by MICROPY_HW_BOARD_NAME
- Unique-ID, same as returned by machine.unique_id()
- USB Vendor ID, as set by MICROPY_HW_USB_VID; default 0xf055
- USB Product ID, as set by MICROPY_HW_USB_PID; default 0x9802
2022-01-27 17:05:34 +11:00
robert-hh
30380962cf mimxrt: Allow to select cs0 or cs1 for SPI.
Using the keyword argument cs=nnn in the constructor. The cs1
pin has to be defined in mpconfigboard.h.
Note: Only a few boards have the CS1 pin exposed to the connectors.
2022-01-27 16:53:30 +11:00
robert-hh
1dc366f901 mimxrt: Replace Pin-config constants by a function call.
The Pin config setting by IOMUXC_SetPinConfig() is supplied by a
bit pattern. That pattern is specific for a MCU family. In preparation
for supporting the MIMXRT117x family, the constant bit pattern is
replaced by a function call, such that the bit pattern is created
at a single place. The code for this functions was taken from
machine_pin.c.

Note: A working port for the MIMXRT1176 exists already.
2022-01-27 16:53:30 +11:00
robert-hh
5bda84aed5 mimxrt: Remove two files from the Seeed Arch Mix directory.
These were leftovers from a previous refactoring in the Seeed Arch Mix
directory.
2022-01-27 16:53:30 +11:00
robert-hh
b8a0358c34 mimxrt: Compensate for a bug in the fsl_lpspi.c file.
This library file has a bug, in that TransferBlocking returns before the
transfer has finished. That is a problem if a write follows immediately
a read.
2022-01-27 16:53:30 +11:00
robert-hh
84b76e4fbf mimxrt: Allow for board-specific flash driver files.
If in a board's mkconfigboard.mk the following symbol is set:

MICROPY_HW_BOARD_FLASH_FILES = 1

then the files:

($BOARD)_flexspi_flash_config.h  and
qspi_nor_flash_config.c  and/or
qspi_hyper_flash_config.c

are expected in the board directory. Otherwise the common files from
the hal directory are used.
2022-01-27 16:53:30 +11:00
robert-hh
2dd3d88409 mimxrt: Support gaps in the SPI an I2C device numbers.
That allows also to use e.g. SPI1 and SPI2 instead SPI0 and SPI1.
2022-01-27 16:53:30 +11:00
Damien George
e1a84a0c6f esp32/partitions: Increase size of app-part from 0x180000 to 0x1F0000.
To fill out all of the available flash up to the start of the filesystem
partition.

Signed-off-by: Damien George <damien@micropython.org>
2022-01-27 16:44:13 +11:00
Damien George
79a3158de6 stm32/pin: Change remaining uses of "af" to "alt".
The keyword "af" has been deprecated for some time and "alt" should be used
instead (but "af" still works).

Signed-off-by: Damien George <damien@micropython.org>
2022-01-27 16:44:13 +11:00
Andrew Leech
30b6ce86be windows: Add micropython.schedule support. 2022-01-23 10:55:08 +11:00
Damien George
c153bfd311 docs/differences: Update python_36 now that b2a_base64 accepts newline.
Signed-off-by: Damien George <damien@micropython.org>
2022-01-23 10:23:30 +11:00
Christian Decker
2e3a2785cd extmod/modubinascii: Add newline keyword to b2a_base64 function.
This allows encoding things (eg a Basic-Auth header for a request) without
slicing the \n from the string, which allocates additional memory.

Co-authored-by: David Lechner <david@lechnology.com>
2022-01-23 10:18:01 +11:00
Damien George
aafd8859e9 docs/differences: Update differences now that math.tau/inf/nan exist.
Signed-off-by: Damien George <damien@micropython.org>
2022-01-23 09:33:19 +11:00
stijn
f3229590a9 tools/ci: Test math constants with MICROPY_OBJ_REPR_D. 2022-01-23 09:28:33 +11:00
stijn
dd6967202a py/modmath: Add math.tau, math.nan and math.inf constants.
Configurable by the new MICROPY_PY_MATH_CONSTANTS option.
2022-01-23 09:28:33 +11:00
stijn
e0b8d69827 github/workflows: Show context for qemu-arm test failures.
Make it easier to see what went wrong in CI builds.
2022-01-23 09:25:19 +11:00
stijn
a9448c0a86 all: Fix MICROPY_OBJ_REPR_D compilation with msvc. 2022-01-23 09:25:01 +11:00
Jos Verlinde
5f8eef4521 windows/README.md: Fix broken mingw link. 2022-01-23 09:19:47 +11:00
ubi de feo
ea5744fd8d esp32/boards: Provide custom deploy_c3.md for ESP32-C3 boards.
This fixes the flash address for installation on ESP32-C3.
2022-01-22 11:18:50 +11:00
Damien George
bb9d688454 esp32/main: Use heap_caps_get_info on IDF <4.1 to compute total heap.
heap_caps_get_total_size() is only available in IDF 4.1 and above.

Signed-off-by: Damien George <damien@micropython.org>
2022-01-22 10:46:31 +11:00
marcidy
ac39960aa1 esp32/modnetwork: Fix test for WIFI_AUTH_MAX for IDF v4.3.0.
Signed-off-by: marcidy <marcidy@gmail.com>
2022-01-22 00:55:07 +11:00
Sean Coates
6a10d3ed99 esp32/README.md: Fix URL for esp-idf installation.
The current URL points to a pinned version of the document (v4.0.2) and is
currently not found (404).
2022-01-22 00:53:26 +11:00
Damien George
23b1a4e0b6 esp32/main: Allocate at most 1/2 of available IDF heap for MP heap.
So that there is some memory left for the OS, eg for ssl buffers.

See issue #7214.

Signed-off-by: Damien George <damien@micropython.org>
2022-01-22 00:46:12 +11:00
Damien George
648656dbbd esp32/esp32_rmt: Call rmt_driver_install directly if running on core 1.
Signed-off-by: Damien George <damien@micropython.org>
2022-01-22 00:11:14 +11:00
jason
357078504d esp32: Pin MicroPython to core 1 again.
This follows up on #5489, where we changed the esp32 core pinning to core 0
in order to work around an issue with IDF < 4.2.0.  Now that IDF > 4.2.0 is
available, we allow pinning back to core 1, which eliminates some
problematic callback latency with WiFi enabled.

NimBLE is also pinned to core 1 - the same core as MicroPython - when using
IDF >=4.2.
2022-01-22 00:10:16 +11:00
Jonathan Hogg
63438a31bb esp32/machine_adcblock: Add new machine.ADCBlock class and update ADC.
Rework the ADC implementation to follow the improved ADC/ADCBlock API.
This adds support for calibrated voltage readings and the ADC2 block.  The
ADC API is backwards compatible with what it was before this change.

Resolves #6219.
2022-01-21 22:55:24 +11:00
Jonathan Hogg
3300d6d337 docs/esp32: Document expanded ADC API in quickref.
Document read_u16(), read_uv() and ADCBlock(). Mark old read(), atten() 
and width() methods as legacy.
2022-01-21 22:40:37 +11:00
Damien George
4d2f487ee1 docs/library: Specify additional ADC methods and new ADCBlock class.
The new ADC methods are: init(), read_uv() and block().

The new ADCBlock class has methods: init() and connect().

See related discussions in #3943, #4213.

Signed-off-by: Damien George <damien@micropython.org>
2022-01-21 22:35:23 +11:00
Damien George
7d71ae25ed extmod/machine_i2c: Increase default SoftI2C timeout to 50ms.
Some devices, eg BNO055, can stretch SCL for a long time, so make the
default large to accommodate them.  50ms matches the current default for
stm32 hardware I2C .

Signed-off-by: Damien George <damien@micropython.org>
2022-01-21 15:10:30 +11:00
Damien George
a707fe50b0 rp2/machine_i2c: Use soft I2C only for len=0, and increase timeout.
The RP2040 I2C hardware can do writes of length 1 and 2, just not of length
0.  So only use software I2C for writes of length 0, to improve
performance.

Also increase the software I2C timeout for zero-length writes to
accommodate the behaviour of a wider range of I2C devices.

Fixes issue #8167.

Signed-off-by: Damien George <damien@micropython.org>
2022-01-21 15:10:29 +11:00
iabdalkader
bef26d4e3f rp2/machine_uart: Add machine.UART init/deinit methods.
Without these methods a lot of existing "portable" scripts are broken.
This change improves portability by making rp2 machine.UART more compliant
with the documented machine UART interface.
2022-01-21 15:08:47 +11:00
Damien George
9438fb7321 extmod/modusocket: Support additional args to getaddrinfo.
Signed-off-by: Damien George <damien@micropython.org>
2022-01-21 13:40:06 +11:00
iabdalkader
1aac151d68 drivers/ninaw10: Return standard error numbers. 2022-01-21 13:35:05 +11:00
iabdalkader
a63875d5ad extmod/modusocket: Create new sockets in blocking mode.
To conform with CPython and other MicroPython ports.
2022-01-21 13:34:56 +11:00
iabdalkader
6e8f4eaa52 tests/multi_net/udp_data.py: Allow reusing port before bind. 2022-01-21 13:34:33 +11:00
iabdalkader
e6ddda29ca tests/multi_net: Close accepted sockets when tests are done.
gc_sweep_all() cleans up sockets via the finaliser, but tests should
cleanly free resources they use.
2022-01-21 13:34:20 +11:00
iabdalkader
155eb1361e extmod/modusocket: Add makefile() method and common socket options. 2022-01-21 13:34:06 +11:00
iabdalkader
b23178a9c0 extmod/modusocket: Make setsockopt return if NIC is not connected. 2022-01-21 13:32:09 +11:00
iabdalkader
e401ff8935 drivers/ninaw10: Fix timeout handling to match modusocket. 2022-01-21 13:31:41 +11:00
iabdalkader
9a61bc3aa7 extmod/network_ninaw10: Implement MP_STREAM_POLL in ioctl.
There is currently no function to query if the socket is writable.
2022-01-21 13:30:48 +11:00
iabdalkader
981664fd07 drivers/ninaw10: Add function to check socket state/data availability. 2022-01-21 13:30:13 +11:00
iabdalkader
5db278f1dd rp2/mphalport: Add optional dupterm support. 2022-01-20 16:57:03 +11:00
iabdalkader
f44fb76055 rp2/mpconfigport.h: Use internal error numbers. 2022-01-20 16:46:14 +11:00
Damien George
7b0a42374e rp2/machine_i2c: Provide more specific error codes from I2C transfer.
Signed-off-by: Damien George <damien@micropython.org>
2022-01-20 16:43:55 +11:00
Damien George
ce4f8b49ce tools/mpremote: Use machine instead of umachine in commands.
Because bare-metal boards will have machine but not always umachine.

Signed-off-by: Damien George <damien@micropython.org>
2022-01-20 16:35:49 +11:00
Damien George
608d421752 stm32/mboot: Remove custom HAL_RCC_GetHCLKFreq and use HAL provided one.
So that a board can access other HAL_RCC functions if it needs them (this
was not possible previously by just adding hal_rcc.c to the src list for a
board because it would clash with the custom HAL_RCC_GetHCLKFreq function).

Signed-off-by: Damien George <damien@micropython.org>
2022-01-20 16:08:17 +11:00
Jeff Epler
037b2c72a1 py/objstr: Support '{:08}'.format("Jan") like Python 3.10.
The new test has an .exp file, because it is not compatible with Python 3.9
and lower.

See CPython version of the issue at https://bugs.python.org/issue27772

Signed-off-by: Jeff Epler <jepler@gmail.com>
2022-01-19 15:34:32 +11:00
Damien George
5e506567a3 stm32/mbedtls: Enable MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE.
This adds MBEDTLS_MD_SHA1 to the list of default hashes for TLS 1.2
handshake signatures.  Although SHA-1 is weak, this option is turned on in
the default mbedtls configuration file, and allows better compatibility
with older servers.  In particular it allows an stm32-mbedtls-based client
to connect to an axtls-based client (eg default unix port and esp8266).

Signed-off-by: Damien George <damien@micropython.org>
2022-01-17 17:35:04 +11:00
Damien George
2c9dc5742a tests/multi_net: Add testing key/cert to SSL server/client test.
So that this tests works with mbedtls.

Signed-off-by: Damien George <damien@micropython.org>
2022-01-17 17:35:04 +11:00
Damien George
c54717a78f tests/run-multitests.py: Set HOST_IP so tests work between PC and board.
Signed-off-by: Damien George <damien@micropython.org>
2022-01-17 17:35:04 +11:00
Damien George
5df1d8be6c tests/run-multitests.py: Ignore lld_pdu_get_tx_flush_nb msgs from IDF.
BLE still functions correctly even though these messages are sometimes
printed by the IDF.  Ignoring them allows the multi_bluetooth tests to pass
on an esp32 board.

Signed-off-by: Damien George <damien@micropython.org>
2022-01-17 14:23:24 +11:00
1263 changed files with 61487 additions and 11061 deletions

View File

@@ -1,3 +1,15 @@
#all: Reformat remaining C code that doesn't have a space after a comma.
5b700b0af90591d6b1a2c087bb8de6b7f1bfdd2d
# ports: Reformat more C and Python source code.
5c32111fa0e31e451b0f1666bdf926be2fdfd82c
# all: Update Python formatting to latest Black version 22.1.0.
ab2923dfa1174dc177f0a90cb00a7e4ff87958d2
# all: Update Python formatting to latest Black version 21.12b0.
3770fab33449a5dadf8eb06edfae0767e75320a6
# tools/gen-cpydiff.py: Fix formatting of doc strings for new Black.
0f78c36c5aa458a954eed39a46942209107a553e

25
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,25 @@
---
name: Bug report
about: Report an issue
title: ''
labels: bug
assignees: ''
---
* Remove all placeholder text below before submitting.
* Please search existing issues before raising a new issue. For questions about MicroPython or for help using MicroPython, please see the MicroPython Forum -- https://forum.micropython.org/
* In your issue, please include a clear and concise description of what the bug is, the expected output, and how to replicate it.
* If this issue involves external hardware, please include links to relevant datasheets and schematics.
* If you are seeing code being executed incorrectly, please provide a minimal example and expected output (e.g. comparison to CPython).
* For build issues, please include full details of your environment, compiler versions, command lines, and build output.
* Please provide as much information as possible about the version of MicroPython you're running, such as:
- firmware file name
- git commit hash and port/board
- version information shown in the REPL (hit Ctrl-B to see the startup message)

11
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1,11 @@
blank_issues_enabled: false
contact_links:
- name: MicroPython Forum
url: https://forum.micropython.org/
about: Community discussion about all things MicroPython. This is the best place to start if you have questions about using MicroPython or getting started with MicroPython development.
- name: MicroPython Documentation
url: https://docs.micropython.org/
about: Documentation for using and working with MicroPython and libraries.
- name: MicroPython Downloads
url: https://micropython.org/download/
about: Pre-built firmware and information for most supported boards.

16
.github/ISSUE_TEMPLATE/documentation.md vendored Normal file
View File

@@ -0,0 +1,16 @@
---
name: Documentation issue
about: Report areas of the documentation or examples that need improvement
title: 'docs: '
labels: documentation
assignees: ''
---
* Remove all placeholder text below before submitting.
* Please search existing issues before raising a new issue. For questions about MicroPython or for help using MicroPython, please see the MicroPython Forum -- https://forum.micropython.org/
* Describe what was missing from the documentation and/or what was incorrect/incomplete.
* If possible, please link to the relevant page on https://docs.micropython.org/

View File

@@ -0,0 +1,24 @@
---
name: Feature request
about: Request a feature or improvement
title: ''
labels: enhancement
assignees: ''
---
* Remove all placeholder text below before submitting.
* Please search existing issues before raising a new issue. For questions about MicroPython or for help using MicroPython, please see the MicroPython Forum -- https://forum.micropython.org/
* Describe the feature you'd like to see added to MicroPython. In particular, what does this feature enable and why is it useful. MicroPython aims to strike a balance between functionality and code size, so please consider whether this feature can be optionally enabled and whether it can be provided in other ways (e.g. pure-Python library).
* For core Python features, where possible please include a link to the relevant PEP.
* For new architectures / ports / boards, please provide links to relevant documentation, specifications, and toolchains. Any information about the popularity and unique features about this hardware would also be useful.
* For features for existing ports (e.g. new peripherals or microcontroller features), please describe which port(s) it applies too, and whether this is could be an extension to the machine API or a port-specific module?
* For drivers (e.g. for external hardware), please link to datasheets and/or existing drivers from other sources.
* Who do you expect will implement the feature you are requesting? Would you be willing to sponsor this work?

16
.github/ISSUE_TEMPLATE/security.md vendored Normal file
View File

@@ -0,0 +1,16 @@
---
name: Security report
about: Report a security issue or vunerability in MicroPython
title: ''
labels: security
assignees: ''
---
* Remove all placeholder text before submitting the new issue.
* If you need to raise this issue privately with the MicroPython team, please email contact@micropython.org instead.
* Include a clear and concise description of what the security issue is.
* What does this issue allow an attacker to do?

21
.github/workflows/examples.yml vendored Normal file
View File

@@ -0,0 +1,21 @@
name: Check examples
on:
push:
pull_request:
paths:
- '.github/workflows/*.yml'
- 'examples/**'
- 'ports/unix/**'
- 'py/**'
- 'shared/**'
jobs:
embedding:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Build
run: make -C examples/embedding
- name: Run
run: test "$(./examples/embedding/hello-embed)" = "Hello world of easy embedding!"

18
.github/workflows/mpy_format.yml vendored Normal file
View File

@@ -0,0 +1,18 @@
name: .mpy file format and tools
on:
push:
pull_request:
paths:
- '.github/workflows/*.yml'
- 'tools/**'
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install packages
run: source tools/ci.sh && ci_mpy_format_setup
- name: Test mpy-tool.py
run: source tools/ci.sh && ci_mpy_format_test

View File

@@ -24,4 +24,4 @@ jobs:
run: source tools/ci.sh && ci_qemu_arm_build
- name: Print failures
if: failure()
run: grep --text "FAIL" ports/qemu-arm/build/console.out
run: grep --before-context=100 --text "FAIL" ports/qemu-arm/build/console.out

24
.github/workflows/ports_renesas-ra.yml vendored Normal file
View File

@@ -0,0 +1,24 @@
name: renesas-ra port
on:
push:
pull_request:
paths:
- '.github/workflows/*.yml'
- 'tools/**'
- 'py/**'
- 'extmod/**'
- 'lib/**'
- 'drivers/**'
- 'ports/renesas-ra/**'
jobs:
build_renesas_ra_board:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- name: Install packages
run: source tools/ci.sh && ci_renesas_ra_setup
- name: Build
run: source tools/ci.sh && ci_renesas_ra_board_build

View File

@@ -45,8 +45,6 @@ jobs:
run: source tools/ci.sh && ci_unix_standard_build
- name: Run main test suite
run: source tools/ci.sh && ci_unix_standard_run_tests
- name: Run performance benchmarks
run: source tools/ci.sh && ci_unix_standard_run_perfbench
- name: Print failures
if: failure()
run: tests/run-tests.py --print-failures
@@ -73,6 +71,8 @@ jobs:
run: source tools/ci.sh && ci_unix_coverage_build
- name: Run main test suite
run: source tools/ci.sh && ci_unix_coverage_run_tests
- name: Test merging .mpy files
run: source tools/ci.sh && ci_unix_coverage_run_mpy_merge_tests
- name: Build native mpy modules
run: source tools/ci.sh && ci_native_mpy_modules_build
- name: Test importing .mpy generated by mpy_ld.py

10
.gitmodules vendored
View File

@@ -13,7 +13,7 @@
[submodule "lib/stm32lib"]
path = lib/stm32lib
url = https://github.com/micropython/stm32lib
branch = work-F4-1.13.1+F7-1.5.0+L4-1.3.0
branch = work-F0-1.9.0+F4-1.16.0+F7-1.7.0+G4-1.3.0+H7-1.6.0+L0-1.11.2+L4-1.17.0+WB-1.10.0+WL-1.1.0
[submodule "lib/nrfx"]
path = lib/nrfx
url = https://github.com/NordicSemiconductor/nrfx.git
@@ -42,3 +42,11 @@
[submodule "lib/pico-sdk"]
path = lib/pico-sdk
url = https://github.com/raspberrypi/pico-sdk.git
[submodule "lib/fsp"]
path = lib/fsp
url = https://github.com/renesas/fsp.git
[submodule "lib/wiznet"]
path = lib/wiznet5k
url = https://github.com/andrewleech/wiznet_ioLibrary_Driver.git
# Requires https://github.com/Wiznet/ioLibrary_Driver/pull/120
# url = https://github.com/Wiznet/ioLibrary_Driver.git

View File

@@ -156,7 +156,7 @@ The STM32 version
The "stm32" port requires an ARM compiler, arm-none-eabi-gcc, and associated
bin-utils. For those using Arch Linux, you need arm-none-eabi-binutils,
arm-none-eabi-gcc and arm-none-eabi-newlib packages. Otherwise, try here:
https://launchpad.net/gcc-arm-embedded
https://developer.arm.com/tools-and-software/open-source-software/developer-tools/gnu-toolchain/gnu-rm
To build:

View File

@@ -74,7 +74,7 @@ copyright = '- The MicroPython Documentation is Copyright © 2014-2022, Damien P
#
# We don't follow "The short X.Y version" vs "The full version, including alpha/beta/rc tags"
# breakdown, so use the same version identifier for both to avoid confusion.
version = release = '1.18'
version = release = '1.19.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.

View File

@@ -221,23 +221,25 @@ as described above.
If a module is not enabled by default then the corresponding C preprocessor macro
must be enabled. This macro name can be found by searching for the ``MP_REGISTER_MODULE``
line in the module's source code (it usually appears at the end of the main source file).
The third argument to ``MP_REGISTER_MODULE`` is the macro name, and this must be set
to 1 using ``CFLAGS_EXTRA`` to make the module available. If the third argument is just
the number 1 then the module is enabled by default.
This macro should be surrounded by a ``#if X`` / ``#endif`` pair, and the configuration
option ``X`` must be set to 1 using ``CFLAGS_EXTRA`` to make the module available. If
there is no ``#if X`` / ``#endif`` pair then the module is enabled by default.
For example, the ``examples/usercmodule/cexample`` module is enabled by default so
has the following line in its source code:
.. code-block:: c
MP_REGISTER_MODULE(MP_QSTR_cexample, example_user_cmodule, 1);
MP_REGISTER_MODULE(MP_QSTR_cexample, example_user_cmodule);
Alternatively, to make this module disabled by default but selectable through
a preprocessor configuration option, it would be:
.. code-block:: c
MP_REGISTER_MODULE(MP_QSTR_cexample, example_user_cmodule, MODULE_CEXAMPLE_ENABLED);
#if MODULE_CEXAMPLE_ENABLED
MP_REGISTER_MODULE(MP_QSTR_cexample, example_user_cmodule);
#endif
In this case the module is enabled by adding ``CFLAGS_EXTRA=-DMODULE_CEXAMPLE_ENABLED=1``
to the ``make`` command, or editing ``mpconfigport.h`` or ``mpconfigboard.h`` to add

View File

@@ -64,7 +64,7 @@ hypothetical new module ``subsystem`` in the file ``modsubsystem.c``:
.globals = (mp_obj_dict_t *)&mp_module_subsystem_globals,
};
MP_REGISTER_MODULE(MP_QSTR_subsystem, mp_module_subsystem, MICROPY_PY_SUBSYSTEM);
MP_REGISTER_MODULE(MP_QSTR_subsystem, mp_module_subsystem);
#endif

View File

@@ -34,6 +34,7 @@ options for the ``ARCH`` variable, see below):
* ``x86`` (32 bit)
* ``x64`` (64 bit x86)
* ``armv6m`` (ARM Thumb, eg Cortex-M0)
* ``armv7m`` (ARM Thumb 2, eg Cortex-M3)
* ``armv7emsp`` (ARM Thumb 2, single precision float, eg Cortex-M4F, Cortex-M7)
* ``armv7emdp`` (ARM Thumb 2, double precision float, eg Cortex-M7)
@@ -171,7 +172,7 @@ The file ``Makefile`` contains:
# Source files (.c or .py)
SRC = factorial.c
# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin)
# Architecture to build for (x86, x64, armv6m, armv7m, xtensa, xtensawin)
ARCH = x64
# Include to get the rules for compiling and linking the module

View File

@@ -146,6 +146,9 @@ The following is an example of an ``mpconfigport.h`` file:
#define MICROPY_ERROR_REPORTING (MICROPY_ERROR_REPORTING_TERSE)
#define MICROPY_FLOAT_IMPL (MICROPY_FLOAT_IMPL_FLOAT)
// Enable u-modules to be imported with their standard name, like sys.
#define MICROPY_MODULE_WEAK_LINKS (1)
// Fine control over Python builtins, classes, modules, etc.
#define MICROPY_PY_ASYNC_AWAIT (0)
#define MICROPY_PY_BUILTINS_SET (0)
@@ -277,12 +280,7 @@ To add a custom module like ``myport``, first add the module definition in a fil
.globals = (mp_obj_dict_t *)&myport_module_globals,
};
MP_REGISTER_MODULE(MP_QSTR_myport, myport_module, 1);
Note: the "1" as the third argument in ``MP_REGISTER_MODULE`` enables this new module
unconditionally. To allow it to be conditionally enabled, replace the "1" by
``MICROPY_PY_MYPORT`` and then add ``#define MICROPY_PY_MYPORT (1)`` in ``mpconfigport.h``
accordingly.
MP_REGISTER_MODULE(MP_QSTR_myport, myport_module);
You will also need to edit the Makefile to add ``modmyport.c`` to the ``SRC_C`` list, and
a new line adding the same file to ``SRC_QSTR`` (so qstrs are searched for in this new file),
@@ -296,7 +294,7 @@ like this:
mphalport.c \
...
SRC_QSTR += modport.c
SRC_QSTR += modmyport.c
If all went correctly then, after rebuilding, you should be able to import the new module:

View File

@@ -8,7 +8,7 @@ Below is a list of finalised/accepted PEPs for Python 3.5 grouped into their imp
+----------------------------------------------------------------------------------------------------------+---------------+
| **Extensions to the syntax:** | **Status** |
+--------------------------------------------------------+-------------------------------------------------+---------------+
| `PEP 448 <https://www.python.org/dev/peps/pep-0448/>`_ | additional unpacking generalizations | |
| `PEP 448 <https://www.python.org/dev/peps/pep-0448/>`_ | additional unpacking generalizations | Partial |
+--------------------------------------------------------+-------------------------------------------------+---------------+
| `PEP 465 <https://www.python.org/dev/peps/pep-0465/>`_ | a new matrix multiplication operator | Completed |
+--------------------------------------------------------+-------------------------------------------------+---------------+
@@ -33,7 +33,7 @@ Below is a list of finalised/accepted PEPs for Python 3.5 grouped into their imp
+--------------------------------------------------------+-------------------------------------------------+---------------+
| `PEP 441 <https://www.python.org/dev/peps/pep-0441/>`_ | improved Python zip application support | |
+--------------------------------------------------------+-------------------------------------------------+---------------+
| `PEP 486 <https://www.python.org/dev/peps/pep-0486/>`_ | make the Python Laucher aware of virtual | |
| `PEP 486 <https://www.python.org/dev/peps/pep-0486/>`_ | make the Python Launcher aware of virtual | Not relevant |
| | environments | |
+--------------------------------------------------------+-------------------------------------------------+---------------+
| `PEP 484 <https://www.python.org/dev/peps/pep-0484/>`_ | type hints (advisory only) | In Progress |
@@ -97,7 +97,7 @@ Changes to built-in modules:
+-----------------------------------------------------------------------------------------------------------+---------------+
| `math <https://docs.python.org/3/whatsnew/3.5.html#math>`_ |
+-----------------------------------------------------------------------------------------------------------+---------------+
| Two new constants have been added to the math module: *inf* and *nan*. | |
| Two new constants have been added to the math module: *inf* and *nan*. | Completed |
+-----------------------------------------------------------------------------------------------------------+---------------+
| A new function *isclose()* provides a way to test for approximate equality. | |
+-----------------------------------------------------------------------------------------------------------+---------------+
@@ -140,7 +140,7 @@ Changes to built-in modules:
| The *socket.sendall()* method no longer resets the socket timeout every time bytes are received or sent. | |
| The socket timeout is now the maximum total duration to send all data. | |
+-----------------------------------------------------------------------------------------------------------+---------------+
| The backlog argument of the *socket.listen()* method is now optional. By default it is set to SOMAXCONN or| |
| The backlog argument of the *socket.listen()* method is now optional. By default it is set to SOMAXCONN or| Completed |
| to 128, whichever is less. | |
+-----------------------------------------------------------------------------------------------------------+---------------+
| `ssl <https://docs.python.org/3/whatsnew/3.5.html#ssl>`_ |

View File

@@ -78,7 +78,7 @@ Changes to built-in modules:
+--------------------------------------------------------------------------------------------------------------+----------------+
| `binascii <https://docs.python.org/3.6/whatsnew/3.6.html#binascii>`_ | |
+--------------------------------------------------------------------------------------------------------------+----------------+
| The b2a_base64() function now accepts an optional newline keyword argument to control whether the newline | |
| The b2a_base64() function now accepts an optional newline keyword argument to control whether the newline | Completed |
| character is appended to the return value | |
+--------------------------------------------------------------------------------------------------------------+----------------+
| `cmath <https://docs.python.org/3.6/whatsnew/3.6.html#cmath>`_ | |
@@ -121,7 +121,7 @@ Changes to built-in modules:
+--------------------------------------------------------------------------------------------------------------+----------------+
| `math <https://docs.python.org/3.6/whatsnew/3.6.html#math>`_ |
+--------------------------------------------------------------------------------------------------------------+----------------+
| The new math.tau (τ) constant has been added | |
| The new math.tau (τ) constant has been added | Completed |
+--------------------------------------------------------------------------------------------------------------+----------------+
| `os <https://docs.python.org/3.6/whatsnew/3.6.html#os>`_ |
+--------------------------------------------------------------------------------------------------------------+----------------+

View File

@@ -160,6 +160,7 @@ Use the :ref:`machine.Pin <machine.Pin>` class::
p4 = Pin(4, Pin.IN, Pin.PULL_UP) # enable internal pull-up resistor
p5 = Pin(5, Pin.OUT, value=1) # set pin high on creation
p6 = Pin(6, Pin.OUT, drive=Pin.DRIVE_3) # set maximum drive strength
Available Pins are from the following ranges (inclusive): 0-19, 21-23, 25-27, 32-39.
These correspond to the actual GPIO pin numbers of ESP32 chip. Note that many
@@ -167,6 +168,23 @@ end-user boards use their own adhoc pin numbering (marked e.g. D0, D1, ...).
For mapping between board logical pins and physical chip pins consult your board
documentation.
Four drive strengths are supported, using the ``drive`` keyword argument to the
``Pin()`` constructor or ``Pin.init()`` method, with different corresponding
safe maximum source/sink currents and approximate internal driver resistances:
- ``Pin.DRIVE_0``: 5mA / 130 ohm
- ``Pin.DRIVE_1``: 10mA / 60 ohm
- ``Pin.DRIVE_2``: 20mA / 30 ohm (default strength if not configured)
- ``Pin.DRIVE_3``: 40mA / 15 ohm
The ``hold=`` keyword argument to ``Pin()`` and ``Pin.init()`` will enable the
ESP32 "pad hold" feature. When set to ``True``, the pin configuration
(direction, pull resistors and output value) will be held and any further
changes (including changing the output level) will not be applied. Setting
``hold=False`` will immediately apply any outstanding pin configuration changes
and release the pin. Using ``hold=True`` while a pin is already held will apply
any configuration changes and then immediately reapply the hold.
Notes:
* Pins 1 and 3 are REPL UART TX and RX respectively
@@ -176,8 +194,7 @@ Notes:
* Pins 34-39 are input only, and also do not have internal pull-up resistors
* The pull value of some pins can be set to ``Pin.PULL_HOLD`` to reduce power
consumption during deepsleep.
* See :ref:`Deep_sleep_Mode` for a discussion of pin behaviour during sleep
There's a higher-level abstraction :ref:`machine.Signal <machine.Signal>`
which can be used to invert a pin. Useful for illuminating active-low LEDs
@@ -264,54 +281,99 @@ See more examples in the :ref:`esp32_pwm` tutorial.
ADC (analog to digital conversion)
----------------------------------
On the ESP32 ADC functionality is available on Pins 32-39. Note that, when
using the default configuration, input voltages on the ADC pin must be between
0.0v and 1.0v (anything above 1.0v will just read as 4095). Attenuation must
be applied in order to increase this usable voltage range.
On the ESP32, ADC functionality is available on pins 32-39 (ADC block 1) and
pins 0, 2, 4, 12-15 and 25-27 (ADC block 2).
Use the :ref:`machine.ADC <machine.ADC>` class::
from machine import ADC
adc = ADC(Pin(32)) # create ADC object on ADC pin
adc.read() # read value, 0-4095 across voltage range 0.0v - 1.0v
adc = ADC(pin) # create an ADC object acting on a pin
val = adc.read_u16() # read a raw analog value in the range 0-65535
val = adc.read_uv() # read an analog value in microvolts
adc.atten(ADC.ATTN_11DB) # set 11dB input attenuation (voltage range roughly 0.0v - 3.6v)
adc.width(ADC.WIDTH_9BIT) # set 9 bit return values (returned range 0-511)
adc.read() # read value using the newly configured attenuation and width
ADC block 2 is also used by WiFi and so attempting to read analog values from
block 2 pins when WiFi is active will raise an exception.
ESP32 specific ADC class method reference:
The internal ADC reference voltage is typically 1.1V, but varies slightly from
package to package. The ADC is less linear close to the reference voltage
(particularly at higher attenuations) and has a minimum measurement voltage
around 100mV, voltages at or below this will read as 0. To read voltages
accurately, it is recommended to use the ``read_uv()`` method (see below).
.. method:: ADC.atten(attenuation)
ESP32-specific ADC class method reference:
This method allows for the setting of the amount of attenuation on the
input of the ADC. This allows for a wider possible input voltage range,
at the cost of accuracy (the same number of bits now represents a wider
range). The possible attenuation options are:
.. class:: ADC(pin, *, atten)
- ``ADC.ATTN_0DB``: 0dB attenuation, gives a maximum input voltage
of 1.00v - this is the default configuration
- ``ADC.ATTN_2_5DB``: 2.5dB attenuation, gives a maximum input voltage
of approximately 1.34v
- ``ADC.ATTN_6DB``: 6dB attenuation, gives a maximum input voltage
of approximately 2.00v
- ``ADC.ATTN_11DB``: 11dB attenuation, gives a maximum input voltage
of approximately 3.6v
Return the ADC object for the specified pin. ESP32 does not support
different timings for ADC sampling and so the ``sample_ns`` keyword argument
is not supported.
To read voltages above the reference voltage, apply input attenuation with
the ``atten`` keyword argument. Valid values (and approximate linear
measurement ranges) are:
- ``ADC.ATTN_0DB``: No attenuation (100mV - 950mV)
- ``ADC.ATTN_2_5DB``: 2.5dB attenuation (100mV - 1250mV)
- ``ADC.ATTN_6DB``: 6dB attenuation (150mV - 1750mV)
- ``ADC.ATTN_11DB``: 11dB attenuation (150mV - 2450mV)
.. Warning::
Despite 11dB attenuation allowing for up to a 3.6v range, note that the
absolute maximum voltage rating for the input pins is 3.6v, and so going
near this boundary may be damaging to the IC!
Note that the absolute maximum voltage rating for input pins is 3.6V. Going
near to this boundary risks damage to the IC!
.. method:: ADC.width(width)
.. method:: ADC.read_uv()
This method allows for the setting of the number of bits to be utilised
and returned during ADC reads. Possible width options are:
This method uses the known characteristics of the ADC and per-package eFuse
values - set during manufacture - to return a calibrated input voltage
(before attenuation) in microvolts. The returned value has only millivolt
resolution (i.e., will always be a multiple of 1000 microvolts).
The calibration is only valid across the linear range of the ADC. In
particular, an input tied to ground will read as a value above 0 microvolts.
Within the linear range, however, more accurate and consistent results will
be obtained than using `read_u16()` and scaling the result with a constant.
The ESP32 port also supports the :ref:`machine.ADC <machine.ADCBlock>` API:
.. class:: ADCBlock(id, *, bits)
Return the ADC block object with the given ``id`` (1 or 2) and initialize
it to the specified resolution (9 to 12-bits depending on the ESP32 series)
or the highest supported resolution if not specified.
.. method:: ADCBlock.connect(pin)
ADCBlock.connect(channel)
ADCBlock.connect(channel, pin)
Return the ``ADC`` object for the specified ADC pin or channel number.
Arbitrary connection of ADC channels to GPIO is not supported and so
specifying a pin that is not connected to this block, or specifying a
mismatched channel and pin, will raise an exception.
Legacy methods:
.. method:: ADC.read()
This method returns the raw ADC value ranged according to the resolution of
the block, e.g., 0-4095 for 12-bit resolution.
.. method:: ADC.atten(atten)
Equivalent to ``ADC.init(atten=atten)``.
.. method:: ADC.width(bits)
Equivalent to ``ADC.block().init(bits=bits)``.
For compatibility, the ``ADC`` object also provides constants matching the
supported ADC resolutions:
- ``ADC.WIDTH_9BIT`` = 9
- ``ADC.WIDTH_10BIT`` = 10
- ``ADC.WIDTH_11BIT`` = 11
- ``ADC.WIDTH_12BIT`` = 12
- ``ADC.WIDTH_9BIT``: 9 bit data
- ``ADC.WIDTH_10BIT``: 10 bit data
- ``ADC.WIDTH_11BIT``: 11 bit data
- ``ADC.WIDTH_12BIT``: 12 bit data - this is the default configuration
Software SPI bus
----------------
@@ -453,6 +515,8 @@ See :ref:`machine.WDT <machine.WDT>`. ::
wdt = WDT(timeout=5000)
wdt.feed()
.. _Deep_sleep_mode:
Deep-sleep mode
---------------
@@ -472,15 +536,49 @@ Notes:
* Calling ``deepsleep()`` without an argument will put the device to sleep
indefinitely
* A software reset does not change the reset cause
* There may be some leakage current flowing through enabled internal pullups.
To further reduce power consumption it is possible to disable the internal pullups::
p1 = Pin(4, Pin.IN, Pin.PULL_HOLD)
Some ESP32 pins (0, 2, 4, 12-15, 25-27, 32-39) are connected to the RTC during
deep-sleep and can be used to wake the device with the ``wake_on_`` functions in
the :mod:`esp32` module. The output-capable RTC pins (all except 34-39) will
also retain their pull-up or pull-down resistor configuration when entering
deep-sleep.
After leaving deepsleep it may be necessary to un-hold the pin explicitly (e.g. if
it is an output pin) via::
If the pull resistors are not actively required during deep-sleep and are likely
to cause current leakage (for example a pull-up resistor is connected to ground
through a switch), then they should be disabled to save power before entering
deep-sleep mode::
p1 = Pin(4, Pin.OUT, None)
from machine import Pin, deepsleep
# configure input RTC pin with pull-up on boot
pin = Pin(2, Pin.IN, Pin.PULL_UP)
# disable pull-up and put the device to sleep for 10 seconds
pin.init(pull=None)
machine.deepsleep(10000)
Output-configured RTC pins will also retain their output direction and level in
deep-sleep if pad hold is enabled with the ``hold=True`` argument to
``Pin.init()``.
Non-RTC GPIO pins will be disconnected by default on entering deep-sleep.
Configuration of non-RTC pins - including output level - can be retained by
enabling pad hold on the pin and enabling GPIO pad hold during deep-sleep::
from machine import Pin, deepsleep
import esp32
opin = Pin(19, Pin.OUT, value=1, hold=True) # hold output level
ipin = Pin(21, Pin.IN, Pin.PULL_UP, hold=True) # hold pull-up
# enable pad hold in deep-sleep for non-RTC GPIO
esp32.gpio_deep_sleep_hold(True)
# put the device to sleep for 10 seconds
deepsleep(10000)
The pin configuration - including the pad hold - will be retained on wake from
sleep. See :ref:`Pins_and_GPIO` above for a further discussion of pad holding.
SD card
-------
@@ -562,18 +660,14 @@ The APA106 driver extends NeoPixel, but internally uses a different colour order
ap = APA106(pin, 8)
r, g, b = ap[0]
For low-level driving of a NeoPixel::
import esp
esp.neopixel_write(pin, grb_buf, is800khz)
.. Warning::
By default ``NeoPixel`` is configured to control the more popular *800kHz*
units. It is possible to use alternative timing to control other (typically
400kHz) devices by passing ``timing=0`` when constructing the
``NeoPixel`` object.
The low-level driver uses an RMT channel by default. To configure this see
For low-level driving of a NeoPixel see `machine.bitstream`.
This low-level driver uses an RMT channel by default. To configure this see
`RMT.bitstream_channel`.
APA102 (DotStar) uses a different driver as it has an additional clock pin.

View File

@@ -374,17 +374,13 @@ Use the ``neopixel`` module::
np.write() # write data to all pixels
r, g, b = np[0] # get first pixel colour
For low-level driving of a NeoPixel::
import esp
esp.neopixel_write(pin, grb_buf, is800khz)
.. Warning::
By default ``NeoPixel`` is configured to control the more popular *800kHz*
units. It is possible to use alternative timing to control other (typically
400kHz) devices by passing ``timing=0`` when constructing the
``NeoPixel`` object.
For low-level driving of a NeoPixel see `machine.bitstream`.
APA102 driver
-------------

View File

@@ -12,6 +12,8 @@ MicroPython documentation and references
esp8266/quickref.rst
esp32/quickref.rst
rp2/quickref.rst
mimxrt/quickref.rst
wipy/quickref.rst
unix/quickref.rst
zephyr/quickref.rst
renesas-ra/quickref.rst

View File

@@ -31,8 +31,8 @@ Functions
Conforms to `RFC 2045 s.6.8 <https://tools.ietf.org/html/rfc2045#section-6.8>`_.
Returns a bytes object.
.. function:: b2a_base64(data)
.. function:: b2a_base64(data, *, newline=True)
Encode binary data in base64 format, as in `RFC 3548
<https://tools.ietf.org/html/rfc3548.html>`_. Returns the encoded data
followed by a newline character, as a bytes object.
followed by a newline character if newline is true, as a bytes object.

View File

@@ -12,7 +12,7 @@ hold/accumulate various objects.
Classes
-------
.. function:: deque(iterable, maxlen[, flags])
.. class:: deque(iterable, maxlen[, flags])
Deques (double-ended queues) are a list-like container that support O(1)
appends and pops from either side of the deque. New deques are created
@@ -57,7 +57,7 @@ Classes
print(t1.name)
assert t2.name == t2[1]
.. function:: OrderedDict(...)
.. class:: OrderedDict(...)
``dict`` type subclass which remembers and preserves the order of keys
added. When ordered dict is iterated over, keys/items are returned in

View File

@@ -62,6 +62,21 @@ Functions
.. function:: flash_erase(sector_no)
.. function:: osdebug(level)
Turn esp os debugging messages on or off.
The *level* parameter sets the threshold for the log messages for all esp components.
The log levels are defined as constants:
* ``LOG_NONE`` -- No log output
* ``LOG_ERROR`` -- Critical errors, software module can not recover on its own
* ``LOG_WARN`` -- Error conditions from which recovery measures have been taken
* ``LOG_INFO`` -- Information messages which describe normal flow of events
* ``LOG_DEBUG`` -- Extra information which is not necessary for normal use (values, pointers, sizes, etc)
* ``LOG_VERBOSE`` -- Bigger chunks of debugging information, or frequent messages
which can potentially flood the output
.. function:: set_native_code_location(start, length)
**Note**: ESP8266 only

View File

@@ -30,6 +30,11 @@ Functions
or a tuple/list of valid Pin objects. *level* should be ``esp32.WAKEUP_ALL_LOW``
or ``esp32.WAKEUP_ANY_HIGH``.
.. function:: gpio_deep_sleep_hold(enable)
Configure whether non-RTC GPIO pin configuration is retained during
deep-sleep mode for held pads. *enable* should be a boolean value.
.. function:: raw_temperature()
Read the raw value of the internal temperature sensor, returning an integer.
@@ -68,17 +73,21 @@ Flash partitions
This class gives access to the partitions in the device's flash memory and includes
methods to enable over-the-air (OTA) updates.
.. class:: Partition(id)
.. class:: Partition(id, block_size=4096, /)
Create an object representing a partition. *id* can be a string which is the label
of the partition to retrieve, or one of the constants: ``BOOT`` or ``RUNNING``.
*block_size* specifies the byte size of an individual block.
.. classmethod:: Partition.find(type=TYPE_APP, subtype=0xff, label=None)
.. classmethod:: Partition.find(type=TYPE_APP, subtype=0xff, label=None, block_size=4096)
Find a partition specified by *type*, *subtype* and *label*. Returns a
(possibly empty) list of Partition objects. Note: ``subtype=0xff`` matches any subtype
and ``label=None`` matches any label.
*block_size* specifies the byte size of an individual block used by the returned
objects.
.. method:: Partition.info()
Returns a 6-tuple ``(type, subtype, addr, size, label, encrypted)``.

View File

@@ -97,6 +97,13 @@ the following libraries.
network.rst
uctypes.rst
The following libraries provide drivers for hardware components.
.. toctree::
:maxdepth: 1
wm8960.rst
Port-specific libraries
-----------------------

View File

@@ -8,28 +8,59 @@ The ADC class provides an interface to analog-to-digital convertors, and
represents a single endpoint that can sample a continuous voltage and
convert it to a discretised value.
For extra control over ADC sampling see :ref:`machine.ADCBlock <machine.ADCBlock>`.
Example usage::
import machine
from machine import ADC
adc = machine.ADC(pin) # create an ADC object acting on a pin
val = adc.read_u16() # read a raw analog value in the range 0-65535
adc = ADC(pin) # create an ADC object acting on a pin
val = adc.read_u16() # read a raw analog value in the range 0-65535
val = adc.read_uv() # read an analog value in microvolts
Constructors
------------
.. class:: ADC(id)
.. class:: ADC(id, *, sample_ns, atten)
Access the ADC associated with a source identified by *id*. This
*id* may be an integer (usually specifying a channel number), a
:ref:`Pin <machine.Pin>` object, or other value supported by the
underlying machine.
If additional keyword-arguments are given then they will configure
various aspects of the ADC. If not given, these settings will take
previous or default values. The settings are:
- *sample_ns* is the sampling time in nanoseconds.
- *atten* specifies the input attenuation.
Methods
-------
.. method:: ADC.init(*, sample_ns, atten)
Apply the given settings to the ADC. Only those arguments that are
specified will be changed. See the ADC constructor above for what the
arguments are.
.. method:: ADC.block()
Return the :ref:`ADCBlock <machine.ADCBlock>` instance associated with
this ADC object.
This method only exists if the port supports the
:ref:`ADCBlock <machine.ADCBlock>` class.
.. method:: ADC.read_u16()
Take an analog reading and return an integer in the range 0-65535.
The return value represents the raw reading taken by the ADC, scaled
such that the minimum value is 0 and the maximum value is 65535.
.. method:: ADC.read_uv()
Take an analog reading and return an integer value with units of
microvolts. It is up to the particular port whether or not this value
is calibrated, and how calibration is done.

View File

@@ -0,0 +1,58 @@
.. currentmodule:: machine
.. _machine.ADCBlock:
class ADCBlock -- control ADC peripherals
=========================================
The ADCBlock class provides access to an ADC peripheral which has a
number of channels that can be used to sample analog values. It allows
finer control over configuration of :ref:`machine.ADC <machine.ADC>`
objects, which do the actual sampling.
This class is not always available.
Example usage::
from machine import ADCBlock
block = ADCBlock(id, bits=12) # create an ADCBlock with 12-bit resolution
adc = block.connect(4, pin) # connect channel 4 to the given pin
val = adc.read_uv() # read an analog value
Constructors
------------
.. class:: ADCBlock(id, *, bits)
Access the ADC peripheral identified by *id*, which may be an integer
or string.
The *bits* argument, if given, sets the resolution in bits of the
conversion process. If not specified then the previous or default
resolution is used.
Methods
-------
.. method:: ADCBlock.init(*, bits)
Configure the ADC peripheral. *bits* will set the resolution of the
conversion process.
.. method:: ADCBlock.connect(channel)
ADCBlock.connect(source)
ADCBlock.connect(channel, source)
Connect up a channel on the ADC peripheral so it is ready for sampling,
and return an :ref:`ADC <machine.ADC>` object that represents that connection.
The *channel* argument must be an integer, and *source* must be an object
(for example a :ref:`Pin <machine.Pin>`) which can be connected up for sampling.
If only *channel* is given then it is configured for sampling.
If only *source* is given then that object is connected to a default
channel ready for sampling.
If both *channel* and *source* are given then they are connected together
and made ready for sampling.

View File

@@ -57,7 +57,7 @@ Constructors
of *scl* and *sda* that cannot be changed.
.. _machine.SoftI2C:
.. class:: SoftI2C(scl, sda, *, freq=400000, timeout=255)
.. class:: SoftI2C(scl, sda, *, freq=400000, timeout=50000)
Construct a new software I2C object. The parameters are:

View File

@@ -72,30 +72,34 @@ uasyncio::
sreader = uasyncio.StreamReader(audio_in)
num_read = await sreader.readinto(buf)
Some codec devices like the WM8960 or SGTL5000 require separate initialization
before they can operate with the I2S class. For these, separate drivers are
supplied, which also offer methods for controlling volume, audio processing and
other things. For these drivers see:
- :ref:`wm8960`
Constructor
-----------
.. class:: I2S(id, *, sck, ws, sd, mode, bits, format, rate, ibuf)
.. class:: I2S(id, *, sck, ws, sd, mck=None, mode, bits, format, rate, ibuf)
Construct an I2S object of the given id:
- ``id`` identifies a particular I2S bus.
``id`` is board and port specific:
- PYBv1.0/v1.1: has one I2S bus with id=2.
- PYBD-SFxW: has two I2S buses with id=1 and id=2.
- ESP32: has two I2S buses with id=0 and id=1.
- ``id`` identifies a particular I2S bus; it is board and port specific
Keyword-only parameters that are supported on all ports:
- ``sck`` is a pin object for the serial clock line
- ``ws`` is a pin object for the word select line
- ``sd`` is a pin object for the serial data line
- ``mck`` is a pin object for the master clock line;
master clock frequency is sampling rate * 256
- ``mode`` specifies receive or transmit
- ``bits`` specifies sample size (bits), 16 or 32
- ``format`` specifies channel format, STEREO or MONO
- ``rate`` specifies audio sampling rate (samples/s)
- ``rate`` specifies audio sampling rate (Hz);
this is the frequency of the ``ws`` signal
- ``ibuf`` specifies internal buffer length (bytes)
For all ports, DMA runs continuously in the background and allows user applications to perform other operations while

View File

@@ -23,7 +23,7 @@ Example usage::
Constructors
------------
.. class:: PWM(dest, \*, freq, duty_u16, duty_ns)
.. class:: PWM(dest, *, freq, duty_u16, duty_ns)
Construct and return a new PWM object using the following parameters:
@@ -42,7 +42,7 @@ Constructors
Methods
-------
.. method:: PWM.init(\*, freq, duty_u16, duty_ns)
.. method:: PWM.init(*, freq, duty_u16, duty_ns)
Modify settings for the PWM object. See the above constructor for details
about the parameters.
@@ -78,6 +78,13 @@ Methods
With a single *value* argument the pulse width is set to that value.
Specific PWM class implementations
----------------------------------
The following concrete class(es) implement enhancements to the PWM class.
| :ref:`pyb.Timer for PyBoard <pyb.Timer>`
Limitations of PWM
------------------
@@ -90,6 +97,11 @@ Limitations of PWM
80000000 / 267 = 299625.5 Hz, not 300kHz. If the divider is set to 266 then
the PWM frequency will be 80000000 / 266 = 300751.9 Hz, but again not 300kHz.
Some ports like the RP2040 one use a fractional divider, which allow a finer
granularity of the frequency at higher frequencies by switching the PWM
pulse duration between two adjacent values, such that the resulting average
frequency is more close to the intended one, at the cost of spectral purity.
* The duty cycle has the same discrete nature and its absolute accuracy is not
achievable. On most hardware platforms the duty will be applied at the next
frequency period. Therefore, you should wait more than "1/frequency" before

View File

@@ -42,7 +42,7 @@ Usage Model::
Constructors
------------
.. class:: Pin(id, mode=-1, pull=-1, *, value, drive, alt)
.. class:: Pin(id, mode=-1, pull=-1, *, value=None, drive=0, alt=-1)
Access the pin peripheral (GPIO pin) associated with the given ``id``. If
additional arguments are given in the constructor then they are used to initialise
@@ -87,9 +87,9 @@ Constructors
output pin value if given, otherwise the state of the pin peripheral remains
unchanged.
- ``drive`` specifies the output power of the pin and can be one of: ``Pin.LOW_POWER``,
``Pin.MED_POWER`` or ``Pin.HIGH_POWER``. The actual current driving capabilities
are port dependent. Not all ports implement this argument.
- ``drive`` specifies the output power of the pin and can be one of: ``Pin.DRIVE_0``,
``Pin.DRIVE_1``, etc., increasing in drive strength. The actual current driving
capabilities are port dependent. Not all ports implement this argument.
- ``alt`` specifies an alternate function for the pin and the values it can take are
port dependent. This argument is valid only for ``Pin.ALT`` and ``Pin.ALT_OPEN_DRAIN``
@@ -108,7 +108,7 @@ Constructors
Methods
-------
.. method:: Pin.init(mode=-1, pull=-1, *, value, drive, alt)
.. method:: Pin.init(mode=-1, pull=-1, *, value=None, drive=0, alt=-1)
Re-initialise the pin using the given parameters. Only those arguments that
are specified will be set. The rest of the pin peripheral state will remain
@@ -260,11 +260,13 @@ not all constants are available on all ports.
Selects whether there is a pull up/down resistor. Use the value
``None`` for no pull.
.. data:: Pin.LOW_POWER
Pin.MED_POWER
Pin.HIGH_POWER
.. data:: Pin.DRIVE_0
Pin.DRIVE_1
Pin.DRIVE_2
Selects the pin drive strength.
Selects the pin drive strength. A port may define additional drive
constants with increasing number corresponding to increasing drive
strength.
.. data:: Pin.IRQ_FALLING
Pin.IRQ_RISING

View File

@@ -122,3 +122,46 @@ You can set the pins used for SPI access by passing a tuple as the
*Note:* The current cc3200 SD card implementation names the this class
:class:`machine.SD` rather than :class:`machine.SDCard` .
mimxrt
``````
The SDCard module for the mimxrt port only supports access via dedicated SD/MMC
peripheral (USDHC) in 4-bit mode with 50MHz clock frequency exclusively.
Unfortunately the MIMXRT1011 controller does not support the USDHC peripheral.
Hence this controller does not feature the ``machine.SDCard`` module.
Due to the decision to only support 4-bit mode with 50MHz clock frequency the
interface has been simplified, and the constructor signature is:
.. class:: SDCard(slot=1)
:noindex:
The pins used for the USDHC peripheral have to be configured in ``mpconfigboard.h``.
Most of the controllers supported by the mimxrt port provide up to two USDHC
peripherals. Therefore the pin configuration is performed using the macro
``MICROPY_USDHCx`` with x being 1 or 2 respectively.
The following shows an example configuration for USDHC1::
#define MICROPY_USDHC1 \
{ \
.cmd = { GPIO_SD_B0_02_USDHC1_CMD}, \
.clk = { GPIO_SD_B0_03_USDHC1_CLK }, \
.cd_b = { GPIO_SD_B0_06_USDHC1_CD_B },\
.data0 = { GPIO_SD_B0_04_USDHC1_DATA0 },\
.data1 = { GPIO_SD_B0_05_USDHC1_DATA1 },\
.data2 = { GPIO_SD_B0_00_USDHC1_DATA2 },\
.data3 = { GPIO_SD_B0_01_USDHC1_DATA3 },\
}
If the card detect pin is not used (cb_b pin) then the respective entry has to be
filled with the following dummy value::
#define USDHC_DUMMY_PIN NULL , 0
Based on the definition of macro ``MICROPY_USDHC1`` and/or ``MICROPY_USDHC2``
the ``machine.SDCard`` module either supports one or two slots. If only one of
the defines is provided, calling ``machine.SDCard()`` or ``machine.SDCard(1)``
will return an instance using the respective USDHC peripheral. When both macros
are defined, calling ``machine.SDCard(2)`` returns an instance using USDHC2.

View File

@@ -143,9 +143,11 @@ Constants
for initialising the SPI bus to controller; this is only used for the WiPy
.. data:: SPI.MSB
SoftSPI.MSB
set the first bit to be the most significant bit
.. data:: SPI.LSB
SoftSPI.LSB
set the first bit to be the least significant bit

View File

@@ -63,6 +63,12 @@ Methods
- *timeout* specifies the time to wait for the first character (in ms).
- *timeout_char* specifies the time to wait between characters (in ms).
- *invert* specifies which lines to invert.
- ``0`` will not invert lines (idle state of both lines is logic high).
- ``UART.INV_TX`` will invert TX line (idle state of TX line now logic low).
- ``UART.INV_RX`` will invert RX line (idle state of RX line now logic low).
- ``UART.INV_TX | UART.INV_RX`` will invert both lines (idle state at logic low).
- *flow* specifies which hardware flow control signals to use. The value
is a bitmask.

View File

@@ -31,7 +31,7 @@ Constructors
Methods
-------
.. method:: wdt.feed()
.. method:: WDT.feed()
Feed the WDT to prevent it from resetting the system. The application
should place this call in a sensible place ensuring that the WDT is

View File

@@ -199,6 +199,7 @@ Classes
machine.Pin.rst
machine.Signal.rst
machine.ADC.rst
machine.ADCBlock.rst
machine.PWM.rst
machine.UART.rst
machine.SPI.rst

View File

@@ -0,0 +1,93 @@
.. currentmodule:: network
.. _network.LAN:
class LAN -- control an Ethernet module
=======================================
This class allows you to control the Ethernet interface. The PHY hardware type is board-specific.
Example usage::
import network
nic = network.LAN(0)
print(nic.ifconfig())
# now use socket as usual
...
Constructors
------------
.. class:: LAN(id, *, phy_type=<board_default>, phy_addr=<board_default>, phy_clock=<board_default>)
Create a LAN driver object, initialise the LAN module using the given
PHY driver name, and return the LAN object.
Arguments are:
- *id* is the number of the Ethernet port, either 0 or 1.
- *phy_type* is the name of the PHY driver. For most board the on-board PHY has to be used and
is the default. Suitable values are port specific.
- *phy_addr* specifies the address of the PHY interface. As with *phy_type*, the hardwired value has
to be used for most boards and that value is the default.
- *phy_clock* specifies, whether the data clock is provided by the Ethernet controller or the PYH interface.
The default value is the one that matches the board. If set to ``True``, the clock is driven by the
Ethernet controller, otherwise by the PHY interface.
For example, with the Seeed Arch Mix board you can use::
nic = LAN(0, phy_type=LAN.PHY_LAN8720, phy_addr=2, phy_clock=False)
Methods
-------
.. method:: LAN.active([state])
With a parameter, it sets the interface active if *state* is true, otherwise it
sets it inactive.
Without a parameter, it returns the state.
.. method:: LAN.isconnected()
Returns ``True`` if the physical Ethernet link is connected and up.
Returns ``False`` otherwise.
.. method:: LAN.status()
Returns the LAN status.
.. method:: LAN.ifconfig([(ip, subnet, gateway, dns)])
Get/set IP address, subnet mask, gateway and DNS.
When called with no arguments, this method returns a 4-tuple with the above information.
To set the above values, pass a 4-tuple with the required information. For example::
nic.ifconfig(('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8'))
.. method:: LAN.config(config_parameters)
Sets or gets parameters of the LAN interface. The only parameter that can be
retrieved is the MAC address, using::
mac = LAN.config("mac")
The parameters that can be set are:
- ``trace=n`` sets trace levels; suitable values are:
- 2: trace TX
- 4: trace RX
- 8: full trace
- ``low_power=bool`` sets or clears low power mode, valid values being ``False``
or ``True``.
Specific LAN class implementations
----------------------------------
On the mimxrt port, suitable values for the *phy_type* constructor argument are:
``PHY_KSZ8081``, ``PHY_DP83825``, ``PHY_DP83848``, ``PHY_LAN8720``, ``PHY_RTL8211F``.

View File

@@ -6,7 +6,7 @@ class WIZNET5K -- control WIZnet5x00 Ethernet modules
This class allows you to control WIZnet5x00 Ethernet adaptors based on
the W5200 and W5500 chipsets. The particular chipset that is supported
by the firmware is selected at compile-time via the MICROPY_PY_WIZNET5K
by the firmware is selected at compile-time via the MICROPY_PY_NETWORK_WIZNET5K
option.
Example usage::

View File

@@ -132,4 +132,5 @@ Methods
password Access password (string)
dhcp_hostname The DHCP hostname to use
reconnects Number of reconnect attempts to make (integer, 0=none, -1=unlimited)
txpower Maximum transmit power in dBm (integer or float)
============= ===========

View File

@@ -152,6 +152,7 @@ provide a way to control networking interfaces of various kinds.
network.WLANWiPy.rst
network.CC3K.rst
network.WIZNET5K.rst
network.LAN.rst
Network functions
=================

View File

@@ -4,13 +4,12 @@
class CAN -- controller area network communication bus
======================================================
CAN implements the standard CAN communications protocol. At
the physical level it consists of 2 lines: RX and TX. Note that
to connect the pyboard to a CAN bus you must use a CAN transceiver
to convert the CAN logic signals from the pyboard to the correct
CAN implements support for classic CAN (available on F4, F7 MCUs) and CAN FD (H7 series) controllers.
At the physical level CAN bus consists of 2 lines: RX and TX. Note that to connect the pyboard to a
CAN bus you must use a CAN transceiver to convert the CAN logic signals from the pyboard to the correct
voltage levels on the bus.
Example usage (works without anything connected)::
Example usage for classic CAN controller in Loopback (transceiver-less) mode::
from pyb import CAN
can = CAN(1, CAN.LOOPBACK)
@@ -18,6 +17,16 @@ Example usage (works without anything connected)::
can.send('message!', 123) # send a message with id 123
can.recv(0) # receive message on FIFO 0
Example usage for CAN FD controller with all of the possible options enabled::
# FD frame + BRS mode + Extended frame ID. 500 Kbit/s for arbitration phase, 1Mbit/s for data phase.
can = CAN(1, CAN.NORMAL, baudrate=500_000, brs_baudrate=1_000_000, sample_point=80)
can.setfilter(0, CAN.RANGE, 0, (0xFFF0, 0xFFFF))
can.send('a'*64, 0xFFFF, fdf=True, brs=True, extframe=True)
can.recv(0)
The following CAN module functions and their arguments are available
for both classic and FD CAN controllers, unless otherwise stated.
Constructors
------------
@@ -35,43 +44,48 @@ Constructors
- ``CAN(1)`` is on ``YA``: ``(RX, TX) = (Y3, Y4) = (PB8, PB9)``
- ``CAN(2)`` is on ``YB``: ``(RX, TX) = (Y5, Y6) = (PB12, PB13)``
Class Methods
-------------
.. classmethod:: CAN.initfilterbanks(nr)
Reset and disable all filter banks and assign how many banks should be available for CAN(1).
STM32F405 has 28 filter banks that are shared between the two available CAN bus controllers.
This function configures how many filter banks should be assigned to each. *nr* is the number of banks
that will be assigned to CAN(1), the rest of the 28 are assigned to CAN(2).
At boot, 14 banks are assigned to each controller.
Methods
-------
.. method:: CAN.init(mode, extframe=False, prescaler=100, *, sjw=1, bs1=6, bs2=8, auto_restart=False, baudrate=0, sample_point=75)
.. method:: CAN.init(mode, prescaler=100, *, sjw=1, bs1=6, bs2=8, auto_restart=False, baudrate=0, sample_point=75,
num_filter_banks=14, brs_sjw=1, brs_bs1=8, brs_bs2=3, brs_baudrate=0, brs_sample_point=75)
Initialise the CAN bus with the given parameters:
- *mode* is one of: NORMAL, LOOPBACK, SILENT, SILENT_LOOPBACK
- if *extframe* is True then the bus uses extended identifiers in the frames
(29 bits); otherwise it uses standard 11 bit identifiers
- *prescaler* is used to set the duration of 1 time quanta; the time quanta
will be the input clock (PCLK1, see :meth:`pyb.freq()`) divided by the prescaler
- *sjw* is the resynchronisation jump width in units of the time quanta;
it can be 1, 2, 3, 4
- *bs1* defines the location of the sample point in units of the time quanta;
it can be between 1 and 1024 inclusive
- *bs2* defines the location of the transmit point in units of the time quanta;
it can be between 1 and 16 inclusive
- *prescaler* is the value by which the CAN input clock is divided to generate the
nominal bit time quanta. The prescaler can be a value between 1 and 1024 inclusive
for classic CAN, and between 1 and 512 inclusive for CAN FD.
- *sjw* is the resynchronisation jump width in units of time quanta for nominal bits;
it can be a value between 1 and 4 inclusive for classic CAN, and between 1 and 128 inclusive for CAN FD.
- *bs1* defines the location of the sample point in units of the time quanta for nominal bits;
it can be a value between 1 and 16 inclusive for classic CAN, and between 2 and 256 inclusive for CAN FD.
- *bs2* defines the location of the transmit point in units of the time quanta for nominal bits;
it can be a value between 1 and 8 inclusive for classic CAN, and between 2 and 128 inclusive for CAN FD.
- *auto_restart* sets whether the controller will automatically try and restart
communications after entering the bus-off state; if this is disabled then
:meth:`~CAN.restart()` can be used to leave the bus-off state
- *baudrate* if a baudrate other than 0 is provided, this function will try to automatically
calculate a CAN bit-timing (overriding *prescaler*, *bs1* and *bs2*) that satisfies both
the baudrate and the desired *sample_point*.
- *sample_point* given in a percentage of the bit time, the *sample_point* specifies the position
of the last bit sample with respect to the whole bit time. The default *sample_point* is 75%.
calculate the CAN nominal bit time (overriding *prescaler*, *bs1* and *bs2*) that satisfies
both the baudrate and the desired *sample_point*.
- *sample_point* given in a percentage of the nominal bit time, the *sample_point* specifies the position
of the bit sample with respect to the whole nominal bit time. The default *sample_point* is 75%.
- *num_filter_banks* for classic CAN, this is the number of banks that will be assigned to CAN(1),
the rest of the 28 are assigned to CAN(2).
- *brs_prescaler* is the value by which the CAN FD input clock is divided to generate the
data bit time quanta. The prescaler can be a value between 1 and 32 inclusive.
- *brs_sjw* is the resynchronisation jump width in units of time quanta for data bits;
it can be a value between 1 and 16 inclusive
- *brs_bs1* defines the location of the sample point in units of the time quanta for data bits;
it can be a value between 1 and 32 inclusive
- *brs_bs2* defines the location of the transmit point in units of the time quanta for data bits;
it can be a value between 1 and 16 inclusive
- *brs_baudrate* if a baudrate other than 0 is provided, this function will try to automatically
calculate the CAN data bit time (overriding *brs_prescaler*, *brs_bs1* and *brs_bs2*) that satisfies
both the baudrate and the desired *brs_sample_point*.
- *brs_sample_point* given in a percentage of the data bit time, the *brs_sample_point* specifies the position
of the bit sample with respect to the whole data bit time. The default *brs_sample_point* is 75%.
The time quanta tq is the basic unit of time for the CAN bus. tq is the CAN
prescaler value divided by PCLK1 (the frequency of internal peripheral bus 1);
@@ -140,17 +154,17 @@ Methods
- number of pending RX messages on fifo 0
- number of pending RX messages on fifo 1
.. method:: CAN.setfilter(bank, mode, fifo, params, *, rtr)
.. method:: CAN.setfilter(bank, mode, fifo, params, *, rtr, extframe=False)
Configure a filter bank:
- *bank* is the filter bank that is to be configured.
- *mode* is the mode the filter should operate in.
- *bank* is the classic CAN controller filter bank, or CAN FD filter index, to configure.
- *mode* is the mode the filter should operate in, see the tables below.
- *fifo* is which fifo (0 or 1) a message should be stored in, if it is accepted by this filter.
- *params* is an array of values the defines the filter. The contents of the array depends on the *mode* argument.
+-----------+---------------------------------------------------------+
|*mode* |contents of *params* array |
|*mode* |Contents of *params* array for classic CAN controller |
+===========+=========================================================+
|CAN.LIST16 |Four 16 bit ids that will be accepted |
+-----------+---------------------------------------------------------+
@@ -165,10 +179,20 @@ Methods
|CAN.MASK32 |As with CAN.MASK16 but with only one 32 bit id/mask pair.|
+-----------+---------------------------------------------------------+
- *rtr* is an array of booleans that states if a filter should accept a
remote transmission request message. If this argument is not given
then it defaults to ``False`` for all entries. The length of the array
depends on the *mode* argument.
+-----------+---------------------------------------------------------+
|*mode* |Contents of *params* array for CAN FD controller |
+===========+=========================================================+
|CAN.RANGE |Two ids that represent a range of accepted ids. |
+-----------+---------------------------------------------------------+
|CAN.DUAL |Two ids that will be accepted. For example (1, 2) |
+-----------+---------------------------------------------------------+
|CAN.MASK |One filter ID and a mask. For example (0x111, 0x7FF) |
+-----------+---------------------------------------------------------+
- *rtr* For classic CAN controllers, this is an array of booleans that states if
a filter should accept a remote transmission request message. If this argument
is not given then it defaults to ``False`` for all entries. The length of the
array depends on the *mode* argument. For CAN FD, this argument is ignored.
+-----------+----------------------+
|*mode* |length of *rtr* array |
@@ -182,11 +206,17 @@ Methods
|CAN.MASK32 |1 |
+-----------+----------------------+
.. method:: CAN.clearfilter(bank)
- *extframe* If True the frame will have an extended identifier (29 bits),
otherwise a standard identifier (11 bits) is used.
.. method:: CAN.clearfilter(bank, extframe=False)
Clear and disables a filter bank:
- *bank* is the filter bank that is to be cleared.
- *bank* is the classic CAN controller filter bank, or CAN FD filter index, to clear.
- *extframe* For CAN FD controllers, if True, clear an extended filter (configured with extframe=True),
otherwise the clear a standard identifier (configured with extframe=False).
.. method:: CAN.any(fifo)
@@ -200,21 +230,22 @@ Methods
- *list* is an optional list object to be used as the return value
- *timeout* is the timeout in milliseconds to wait for the receive.
Return value: A tuple containing four values.
Return value: A tuple containing five values.
- The id of the message.
- A boolean that indicates if the message ID is standard or extended.
- A boolean that indicates if the message is an RTR message.
- The FMI (Filter Match Index) value.
- An array containing the data.
If *list* is ``None`` then a new tuple will be allocated, as well as a new
bytes object to contain the data (as the fourth element in the tuple).
bytes object to contain the data (as the fifth element in the tuple).
If *list* is not ``None`` then it should be a list object with a least four
elements. The fourth element should be a memoryview object which is created
If *list* is not ``None`` then it should be a list object with a least five
elements. The fifth element should be a memoryview object which is created
from either a bytearray or an array of type 'B' or 'b', and this array must
have enough room for at least 8 bytes. The list object will then be
populated with the first three return values above, and the memoryview object
populated with the first four return values above, and the memoryview object
will be resized inplace to the size of the data and filled in with that data.
The same list and memoryview objects can be reused in subsequent calls to
this method, providing a way of receiving data without using the heap.
@@ -225,7 +256,7 @@ Methods
# No heap memory is allocated in the following call
can.recv(0, lst)
.. method:: CAN.send(data, id, *, timeout=0, rtr=False)
.. method:: CAN.send(data, id, *, timeout=0, rtr=False, extframe=False, fdf=False, brs=False)
Send a message on the bus:
@@ -236,6 +267,13 @@ Methods
a remote transmission request. If *rtr* is True then only the length
of *data* is used to fill in the DLC slot of the frame; the actual
bytes in *data* are unused.
- *extframe* if True the frame will have an extended identifier (29 bits),
otherwise a standard identifier (11 bits) is used.
- *fdf* for CAN FD controllers, if set to True, the frame will have an FD
frame format, which supports data payloads up to 64 bytes.
- *brs* for CAN FD controllers, if set to True, the bitrate switching mode
is enabled, in which the data phase is transmitted at a differet bitrate.
See :meth:`CAN.init` for the data bit timing configuration parameters.
If timeout is 0 the message is placed in a buffer in one of three hardware
buffers and the method returns immediately. If all three buffers are in use
@@ -302,4 +340,10 @@ Constants
CAN.LIST32
CAN.MASK32
The operation mode of a filter used in :meth:`~CAN.setfilter()`.
The operation mode of a filter used in :meth:`~CAN.setfilter()` for classic CAN.
.. data:: CAN.DUAL
CAN.RANGE
CAN.MASK
The operation mode of a filter used in :meth:`~CAN.setfilter()` for CAN FD.

View File

@@ -122,3 +122,15 @@ Methods
dac2 = DAC(2)
dac1.write_timed(buf1, pyb.Timer(6, freq=100), mode=DAC.CIRCULAR)
dac2.write_timed(buf2, pyb.Timer(7, freq=200), mode=DAC.CIRCULAR)
Constants
---------
.. data:: DAC.NORMAL
NORMAL mode does a single transmission of the waveform in the data buffer,
.. data:: DAC.CIRCULAR
CIRCULAR mode does a transmission of the waveform in the data buffer, and wraps around
to the start of the data buffer every time it reaches the end of the table.

View File

@@ -98,7 +98,7 @@ Class methods
Methods
-------
.. method:: Pin.init(mode, pull=Pin.PULL_NONE, \*, value=None, alt=-1)
.. method:: Pin.init(mode, pull=Pin.PULL_NONE, *, value=None, alt=-1)
Initialise the pin:
@@ -237,17 +237,17 @@ pin X3.
For the pyboard, x3_af would contain:
[Pin.AF1_TIM2, Pin.AF2_TIM5, Pin.AF3_TIM9, Pin.AF7_USART2]
Normally, each peripheral would configure the af automatically, but sometimes
the same function is available on multiple pins, and having more control
is desired.
Normally, each peripheral would configure the alternate function automatically,
but sometimes the same function is available on multiple pins, and having more
control is desired.
To configure X3 to expose TIM2_CH3, you could use::
pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, af=pyb.Pin.AF1_TIM2)
pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, alt=pyb.Pin.AF1_TIM2)
or::
pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, af=1)
pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, alt=1)
Methods
-------

View File

@@ -51,7 +51,7 @@ Methods
Turn off the SPI bus.
.. method:: SPI.init(mode, baudrate=328125, *, prescaler, polarity=1, phase=0, bits=8, firstbit=SPI.MSB, ti=False, crc=None)
.. method:: SPI.init(mode, baudrate=328125, *, prescaler=-1, polarity=1, phase=0, bits=8, firstbit=SPI.MSB, ti=False, crc=None)
Initialise the SPI bus with the given parameters:

View File

@@ -262,3 +262,12 @@ Methods
for which the pulse is active. The value can be an integer or
floating-point number for more accuracy. For example, a value of 25 gives
a duty cycle of 25%.
Constants
---------
.. data:: Timer.UP
Timer.DOWN
Timer.CENTER
Configures the timer to count Up, Down, or from 0 to ARR and then back down to 0.

View File

@@ -298,6 +298,15 @@ Miscellaneous functions
The *high_speed* parameter, when set to ``True``, enables USB HS mode if
it is supported by the hardware.
Constants
---------
.. data:: pyb.hid_mouse
pyb.hid_keyboard
A tuple of (subclass, protocol, max packet length, polling interval, report
descriptor) to set appropriate values for a USB mouse or keyboard.
Classes
-------

View File

@@ -10,7 +10,7 @@ The ``rp2`` module contains functions and classes specific to the RP2040, as
used in the Raspberry Pi Pico.
See the `RP2040 Python datasheet
<https://datasheets.raspberrypi.org/pico/raspberry-pi-pico-python-sdk.pdf>`_
<https://datasheets.raspberrypi.com/pico/raspberry-pi-pico-python-sdk.pdf>`_
for more information, and `pico-micropython-examples
<https://github.com/raspberrypi/pico-micropython-examples/tree/master/pio>`_
for example code.

View File

@@ -66,19 +66,6 @@ Tuple address format for ``socket`` module:
Functions
---------
.. function:: socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP, /)
Create a new socket using the given address family, socket type and
protocol number. Note that specifying *proto* in most cases is not
required (and not recommended, as some MicroPython ports may omit
``IPPROTO_*`` constants). Instead, *type* argument will select needed
protocol automatically::
# Create STREAM TCP socket
socket(AF_INET, SOCK_STREAM)
# Create DGRAM UDP socket
socket(AF_INET, SOCK_DGRAM)
.. function:: getaddrinfo(host, port, af=0, type=0, proto=0, flags=0, /)
Translate the host/port argument into a sequence of 5-tuples that contain all the
@@ -176,6 +163,19 @@ Constants specific to WiPy:
class socket
============
.. class:: socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP, /)
Create a new socket using the given address family, socket type and
protocol number. Note that specifying *proto* in most cases is not
required (and not recommended, as some MicroPython ports may omit
``IPPROTO_*`` constants). Instead, *type* argument will select needed
protocol automatically::
# Create STREAM TCP socket
socket(AF_INET, SOCK_STREAM)
# Create DGRAM UDP socket
socket(AF_INET, SOCK_DGRAM)
Methods
-------

View File

@@ -70,6 +70,8 @@ Constants
* *name* - string "micropython"
* *version* - tuple (major, minor, micro), e.g. (1, 7, 0)
* *_machine* - string describing the underlying machine
* *_mpy* - supported mpy file-format version (optional attribute)
This object is the recommended way to distinguish MicroPython from other
Python implementations (note that it still may not exist in the very
@@ -132,6 +134,12 @@ Constants
If you need to check whether your program runs on MicroPython (vs other
Python implementation), use `sys.implementation` instead.
.. data:: ps1
ps2
Mutable attributes holding strings, which are used for the REPL prompt. The defaults
give the standard Python prompt of ``>>>`` and ``...``.
.. data:: stderr
Standard error `stream`.
@@ -144,6 +152,14 @@ Constants
Standard output `stream`.
.. data:: tracebacklimit
A mutable attribute holding an integer value which is the maximum number of traceback
entries to store in an exception. Set to 0 to disable adding tracebacks. Defaults
to 1000.
Note: this is not available on all ports.
.. data:: version
Python language version that this implementation conforms to, as a string.

View File

@@ -159,7 +159,7 @@ class ThreadSafeFlag
.. method:: ThreadSafeFlag.wait()
Wait for the flag to be set. If the flag is already set then it returns
immediately.
immediately. The flag is automatically reset upon return from ``wait``.
A flag may only be waited on by a single task at a time.

397
docs/library/wm8960.rst Normal file
View File

@@ -0,0 +1,397 @@
.. _wm8960:
:mod:`WM8960` -- Driver for the WM8960 codec
============================================
This driver is used to control a WM8960 codec chip. It is a Python
translation of the C-Code provided by NXP/Freescale for their i.MX RT series of
MCUs. Very little has been added, and just a few API related names were changed
or added to cope with the naming style of MicroPython.
The primary purpose of the driver is initialization and setting operation modes
of the codec. It does not do the audio data processing for the codec. That is
the task of a separate driver.
The WM8960 supports an I2C interface, in addition to the audio interface. The
connection depends on the interface used and the number of devices in the
system. For the I2C interface, SCL and SDA have to be connected, and of course
GND and Vcc. The I2C default address is ``0x1A``.
Constructor
-----------
.. class:: WM8960(i2c, sample_rate, *, bits=16, swap=SWAP_NONE, route=ROUTE_PLAYBACK_RECORD, left_input=INPUT_MIC3, right_input=INPUT_MIC2, sysclk_source=SYSCLK_MCLK, mclk_freq=None, primary=False, adc_sync=SYNC_DAC, protocol=BUS_I2S, i2c_address=WM8960_I2C_ADDR)
Create a WM8960 driver object, initialize the device with default settings and return the
WM8960 object.
Only the first two arguments are mandatory. All others are optional. The arguments are:
- *i2c* is the I2C bus object.
- *sample_rate* is the audio sample rate. Acceptable values are 8000,
11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 96000, 192000
and 384000. Note that not every I2S hardware will support all values.
- *bits* is the number of bits per audio word. Acceptable value are 16,
20, 24, and 32.
- *swap* swaps the left & right channel, if set; see below for options.
- *route* Setting the audio path in the codec; see below for options.
- *left_input* sets the audio source for the left input channel;
see below for options.
- *right_input* sets the audio source for the right input channel;
see below for options.
- *play_source* sets the audio target for the output audio;
see below for options.
- *sysclk_source* controls whether the internal master clock called
"sysclk" is directly taken from the MCLK input or derived from it
using an internal PLL. It is usually not required to change this.
- *mclk_freq* sets the mclk frequency applied to the MCLK pin of the
codec. If not set, default values are used.
- *primary* lets the WM8960 act as primary or secondary device. The
default setting is ``False``. When set to ``False``,
*sample_rate* and *bits* are controlled by the MCU.
- *adc_sync* sets which input is used for the ADC sync signal.
The default is using the DACLRC pin.
- *protocol* sets the communication protocol. The default is I2S.
See below for all options.
- *i2c_address* sets the I2C address of the WM8960, with default ``0x1A``.
If *mclk_freq* is not set the following default values are used:
- sysclk_source == SYSCLK_PLL: 11.2896 MHz for sample rates of 44100,
22050 and 11015 Hz, and 12.288 Mhz for sample rates < 48000, otherwise
sample_rate * 256.
- sysclk_source == SYSCLK_MCLK: sample_rate * 256.
If the MCLK signal is applied using, for example,. a separate oscillator,
it must be specified for proper operation.
Tables of parameter constants
-----------------------------
.. table:: **Swap Parameter**
:widths: auto
:align: left
===== ====
Value Name
===== ====
0 SWAP_NONE
1 SWAP_INPUT
2 SWAP_OUTPUT
===== ====
.. table:: **Protocol Parameter**
:widths: auto
:align: left
===== ====
Value Name
===== ====
2 BUS_I2S
1 BUS_LEFT_JUSTIFIED
0 BUS_RIGHT_JUSTIFIED
3 BUS_PCMA
19 BUS_PCMB
===== ====
.. table:: **Input Source Parameter**
:widths: auto
:align: left
===== ============ ====
Value Name Type
===== ============ ====
0 INPUT_CLOSED
1 INPUT_MIC1 Single ended
2 INPUT_MIC2 Differential
3 INPUT_MIC3 Differential
4 INPUT_LINE2
5 INPUT_LINE3
===== ============ ====
.. table:: **Route Parameter**
:widths: auto
:align: left
===== ====
Value Name
===== ====
0 ROUTE_BYPASS
1 ROUTE_PLAYBACK
2 ROUTE_PLAYBACK_RECORD
5 ROUTE_RECORD
===== ====
.. table:: **Master Clock Source Parameter**
:widths: auto
:align: left
===== ====
Value Name
===== ====
0 SYSCLK_MCLK
1 SYSCLK_PLL
===== ====
.. table:: **Module Names**
:widths: auto
:align: left
===== ====
Value Name
===== ====
0 MODULE_ADC
1 MODULE_DAC
2 MODULE_VREF
3 MODULE_HEADPHONE
4 MODULE_MIC_BIAS
5 MODULE_MIC
6 MODULE_LINE_IN
7 MODULE_LINE_OUT
8 MODULE_SPEAKER
9 MODULE_OMIX
10 MODULE_MONO_OUT
===== ====
.. table:: **Play Channel Names**
:widths: auto
:align: left
===== ====
Value Name
===== ====
1 PLAY_HEADPHONE_LEFT
2 PLAY_HEADPHONE_RIGHT
4 PLAY_SPEAKER_LEFT
8 PLAY_SPEAKER_RIGHT
===== ====
.. table:: **adc_sync Parameters**
:widths: auto
:align: left
===== ====
Value Name
===== ====
0 SYNC_ADC
1 SYNC_DAC
===== ====
Methods
-------
In addition to initialization, the driver provides some useful methods for
controlling its operation:
.. method:: WM8960.set_left_input(input_source)
Specify the source for the left input. The input source names are listed above.
.. method:: WM8960.set_right_input(input_source)
Specify the source for the right input. The input source names are listed above.
.. method:: WM8960.volume(module, volume_l=None, volume_r=None)
Sets or gets the volume of a certain module.
If no volume values are supplied, the actual volume tuple is returned.
If one or two values are supplied, it sets the volume of a certain module.
If two values are provided, the first one is used for the left channel,
the second for the right channel. If only one value is supplied, it is used
for both channels. The value range is normalized to 0.0-100.0 with a
logarithmic scale.
For a list of suitable modules and db/step, see the table below.
.. table:: **Module Names and dB steps**
:widths: auto
:align: center
======= ====
dB/Step Name
======= ====
1.28 MODULE_ADC
1.28 MODULE_DAC
0.8 MODULE_HEADPHONE
0.475 MODULE_LINE_IN
0.8 MODULE_SPEAKER
======= ====
.. method:: WM8960.mute(module, mute, soft=True, ramp=wm8960.MUTE_FAST)
Mute or unmute the output. If *mute* is True, the output is muted, if ``False``
it is unmuted.
If *soft* is set as True, muting will happen as a soft transition. The time for
the transition is defined by *ramp*, which is either ``MUTE_FAST`` or ``MUTE_SLOW``.
.. method:: WM8960.set_data_route(route)
Set the audio data route. For the parameter value/names, see the table above.
.. method:: WM8960.set_module(module, active)
Enable or disable a module, with *active* being ``False`` or ``True``. For
the list of module names, see the table above.
Note that enabling ``MODULE_MONO_OUT`` is different from the `WM8960.mono`
method. The first enables output 3, while the `WM8960.mono` method sends a
mono mix to the left and right output.
.. method:: WM8960.enable_module(module)
Enable a module. For the list of module names, see the table above.
.. method:: WM8960.disable_module(module)
Disable a module. For the list of module names, see the table above.
.. method:: WM8960.expand_3d(level)
Enable Stereo 3D exansion. *level* is a number between 0 and 15.
A value of 0 disables the expansion.
.. method:: WM8960.mono(active)
If *active* is ``True``, a Mono mix is sent to the left and right output
channel. This is different from enabling the ``MODULE_MONO_MIX``, which
enables output 3.
.. method:: WM8960.alc_mode(channel, mode=ALC_MODE)
Enables or disables ALC mode. Parameters are:
- *channel* enables and sets the channel for ALC. The parameter values are:
- ALC_OFF: Switch ALC off
- ALS_RIGHT: Use the right input channel
- ALC_LEFT: Use the left input channel
- ALC_STEREO: Use both input channels.
- *mode* sets the ALC mode. Input values are:
- ALC_MODE: act as ALC
- ALC_LIMITER: act as limiter.
.. method:: WM8960.alc_gain(target=-12, max_gain=30, min_gain=-17.25, noise_gate=-78)
Set the target level, highest and lowest gain levels and the noise gate as dB level.
Permitted ranges are:
- *target*: -22.5 to -1.5 dB
- *max_gain*: -12 to 30 dB
- *min_gain*: -17 to 25 dB
- *noise_gate*: -78 to -30 dB
Excess values are limited to the permitted ranges. A value of -78 or less
for *noise_gate* disables the noise gate function.
.. method:: WM8960.alc_time(attack=24, decay=192, hold=0)
Set the dynamic characteristic of ALC. The times are given as millisecond
values. Permitted ranges are:
- *attack*: 6 to 6140
- *decay*: 24 to 24580
- *hold*: 0 to 43000
Excess values are limited within the permitted ranges.
.. method:: WM8960.deemphasis(active)
Enables or disables a deemphasis filter for playback, with *active* being
``False`` or ``True``. This filter is applied only for sample rates of
32000, 44100 and 48000. For other sample rates, the filter setting
is silently ignored.
.. method:: WM8960.deinit()
Disable all modules.
Examples
--------
Run WM8960 in secondary mode (default)::
# Micro_python WM8960 Codec driver
#
# Setting the driver to Slave mode using the default settings
#
from machine import Pin, I2C
import wm8960
i2c = I2C(0)
wm=wm8960.WM8960(i2c, 32000, left_input=wm8960.INPUT_MIC1)
wm.set_volume(wm8960.MODULE_HEADPHONE, 100)
Run WM8960 in primary mode::
# Micro_python WM8960 Codec driver
#
# Setting the driver to Master mode using specific audio format settings
#
from machine import Pin, I2C
import wm8960
i2c = I2C(0)
wm=wm8960.WM8960(i2c, 44100, primary=True, bits=16)
Run WM8960 on a MIMXRT10xx_DEV board in secondary mode (default)::
# Micro_python WM8960 Codec driver
#
# Setting the driver to Slave mode using the default settings
# swap the input channels such that a MIMXRT Dev board mic, which
# is connected to the right input, is assigned to the left audio channel.
#
from machine import Pin, I2C
import wm8960
i2c = I2C(0)
wm=wm8960.WM8960(i2c, sample_rate=16_000,
adc_sync=wm8960.SYNC_DAC,
swap=wm8960.SWAP_INPUT,
sysclk_source=wm8960.SYSCLK_MCLK)
Record with a Sparkfun WM8960 breakout board with Teensy in secondary mode (default)::
# Micro_python WM8960 Codec driver
#
# The breakout board uses a fixed 24MHz MCLK. Therefore the internal
# PLL must be used as sysclk, which is the master audio clock.
# The Sparkfun board has the WS pins for RX and TX connected on the
# board. Therefore adc_sync must be set to sync_adc, to configure
# it's ADCLRC pin as input.
#
from machine import Pin, I2C
import wm8960
i2c = I2C(0)
wm=wm8960.WM8960(i2c, sample_rate=16_000,
adc_sync=wm8960.SYNC_ADC,
sysclk_source=wm8960.SYSCLK_PLL,
mclk_freq=24_000_000,
left_input=wm8960.INPUT_MIC1,
right_input=wm8960.INPUT_CLOSED)
Play with a Sparkfun WM8960 breakout board with Teensy in secondary mode (default)::
# The breakout board uses a fixed 24MHz MCLK. Therefore the internal
# PLL must be used as sysclk, which is the master audio clock.
# The Sparkfun board has the WS pins for RX and TX connected on the
# board. Therefore adc_sync must be set to sync_adc, to configure
# it's ADCLRC pin as input.
from machine import I2C
i2c=I2C(0)
import wm8960
wm=wm8960.WM8960(i2c, sample_rate=44_100,
adc_sync=wm8960.SYNC_ADC,
sysclk_source=wm8960.SYSCLK_PLL,
mclk_freq=24_000_000)
wm.set_volume(wm8960.MODULE_HEADPHONE, 100)

94
docs/mimxrt/general.rst Normal file
View File

@@ -0,0 +1,94 @@
.. _mimxrt_general:
General information about the MIMXRT port
=========================================
The i.MXRT MCU family is a high performance family of devices made by NXP.
Based on an ARM7 core, they provide many on-chip I/O units for building
small to medium sized devices.
Multitude of boards
-------------------
There is a multitude of modules and boards from different sources which carry
an i.MXRT chip. MicroPython aims to provide a generic port which runs on
as many boards/modules as possible, but there may be limitations. The
NXP IMXRT1020-EVK and the Teensy 4.0 and Teensy 4.1 development boards are taken
as reference for the port (for example, testing is performed on them).
For any board you are using please make sure you have a data sheet, schematics
and other reference materials so you can look up any board-specific functions.
The following boards are supported by the port:
- MIMXRT1010-EVK
- MIMXRT1020-EVK
- MIMXRT1050-EVK
- MIMXRT1060-EVK
- MIMXRT1064-EVK
- Teensy 4.0
- Teensy 4.1
Supported MCUs
--------------
+-------------+--------------------+-------------------------+
| Product | CPU | Memory |
+=============+====================+=========================+
| i.MX RT1064 | Cortex-M7 @600 MHz | 1 MB SRAM, 4 MB Flash |
+-------------+--------------------+-------------------------+
| i.MX RT1061 | Cortex-M7 @600 MHz | 1 MB SRAM |
+-------------+--------------------+-------------------------+
| i.MX RT1062 | Cortex-M7 @600 MHz | 1 MB SRAM |
+-------------+--------------------+-------------------------+
| i.MX RT1050 | Cortex-M7 @600 MHz | 512 kB SRAM |
+-------------+--------------------+-------------------------+
| i.MX RT1020 | Cortex-M7 @500 MHz | 256 kB SRAM |
+-------------+--------------------+-------------------------+
| i.MX RT1015 | Cortex-M7 @500 MHz | 128 kB SRAM |
+-------------+--------------------+-------------------------+
| i.MX RT1010 | Cortex-M7 @500 MHz | 128 kB SRAM |
+-------------+--------------------+-------------------------+
Note: Most of the controllers do not have internal flash memory. Therefore
their flash capacity is dependent on an external flash chip.
To make a generic MIMXRT port and support as many boards as possible the
following design and implementation decision were made:
* GPIO pin numbering is based on the board numbering as well as on the
MCU numbering. Please have the manual/pin diagram of your board at hand
to find correspondence between your board pins and actual i.MXRT pins.
* All MCU pins are supported by MicroPython but not all are usable on any given board.
Technical specifications and SoC datasheets
-------------------------------------------
The data sheets and other reference material for i.MXRT chip are available
from the vendor site: https://www.nxp.com/products/processors-and-microcontrollers/arm-microcontrollers/i-mx-rt-crossover-mcus:IMX-RT-SERIES .
They are the primary reference for the chip technical specifications, capabilities,
operating modes, internal functioning, etc.
For your convenience, a few technical specifications are provided below:
* Architecture: ARM Cortex M7
* CPU frequency: up to 600MHz
* Total RAM available: up to 1 MByte (see table)
* BootROM: 96KB
* External FlashROM: code and data, via SPI Flash; usual size 2 - 16 MB
Some boards provide additional external RAM and SPI flash.
* GPIO: up to 124 (GPIOs are multiplexed with other functions, including
external FlashROM, UART, etc.)
* UART: 4 or 8 RX/TX UART. Hardware handshaking is supported by the MCU,
but the boards used for testing do not expose the signals.
* SPI: 2 or 4 low power SPI interfaces (software implementation available on every pin)
* I2C: 2 or 4 low power I2C interfaces (software implementation available on every pin)
* I2S: 1 to 3 I2S interfaces
* ADC: one or two 12-bit SAR ADC converters
* Ethernet controller (except i.MX RT1010/-1015)
* Programming: using BootROM bootloader from USB - due to external FlashROM
and always-available BootROM bootloader, the MIMXRT is not brickable
The lower numbers for UART, SPI and I2C apply to the i.MXRT 101x MCU.
For more information see the i.MXRT data sheets or reference manuals.
NXP provides software support through it's SDK packages.

Binary file not shown.

After

Width:  |  Height:  |  Size: 125 KiB

380
docs/mimxrt/pinout.rst Normal file
View File

@@ -0,0 +1,380 @@
.. _mimxrt_pinout:
Pinout for the i.MXRT machine modules
=====================================
.. _mimxrt_uart_pinout:
|
UART pin assignment
-------------------
The pin assignment of UARTs to pins is fixed.
The UARTs are numbered 0..8. The rx/tx pins are assigned according to the
tables below:
================ =========== =========== =========== ===========
Board / Pin UART0 UART1 UART2 UART3
================ =========== =========== =========== ===========
Teensy 4.0 - 0/1 7/8 14/15
Teensy 4.1 - 0/1 7/8 14/15
MIMXRT1010-EVK Debug USB D0/D1 D7/D6 -
MIMXRT1015-EVK Debug USB D0/D1 D7/A1 -
MIMXRT1020-EVK Debug USB D0/D1 D9/D6 D10/D13
MIMXRT1050-EVK Debug USB D0/D1 D7/D6 D8/D9
MIMXRT1050-EVKB Debug USB D0/D1 D7/D6 D8/D9
MIMXRT1060-EVK Debug USB D0/D1 D7/D6 D8/D9
MIMXRT1064-EVK Debug USB D0/D1 D7/D6 D8/D9
MIMXRT1170-EVK Debug USB D0/D1 D12/D11 D10/D13
Olimex RT1010Py - RxD/TxD D5/D6 -
Seeed ARCH MIX - J3_19/J3_20 J4_16/J4_17 J4_06/J4_07
================ =========== =========== =========== ===========
|
================ =========== =========== ======= ======= =====
Board / Pin UART4 UART5 UART6 UART7 UART8
================ =========== =========== ======= ======= =====
Teensy 4.0 16/17 21/20 25/24 28/29 -
Teensy 4.1 16/17 21/20 25/24 28/29 34/35
MIMXRT1010-EVK - - - - -
MIMXRT1015-EVK - - - - -
MIMXRT1020-EVK D15/D14 A1/A0 - - -
MIMXRT1050-EVK A1/A0 - - - -
MIMXRT1050-EVKB A1/A0 - - - -
MIMXRT1060-EVK A1/A0 - - - -
MIMXRT1064-EVK A1/A0 - - - -
MIMXRT1170-EVK D15/D14 D25/D26 D33/D34 D35/D36 -
Olimex RT1010Py - - - - -
Seeed ARCH MIX J4_10/J4_11 J5_08/J5_12 - - -
================ =========== =========== ======= ======= =====
.. _mimxrt_pwm_pinout:
|
|
PWM pin assignment
------------------
Pins are specified in the same way as for the Pin class. The following tables show
the assignment of the board Pins to PWM modules:
=========== ========== ========== ====== ============== ======
Pin/ MIMXRT 1010 1015 1020 1050/1060/1064 1170
=========== ========== ========== ====== ============== ======
D0 - Q1/1 F1/1/B - -
D1 - Q1/0 F1/1/A - -
D2 F1/3/B F1/3/A - F1/3/B -
D3 F1/3/A F1/0/A F2/3/B F4/0/A F1/2/A
D4 F1/3/A (*) Q1/2 Q2/1 F2/3/A Q4/2
D5 F1/0/B (*) F1/0/B F2/3/A F1/3/A F1/2/B
D6 - F1/2/B F2/0/A Q3/2 F1/0/A
D7 - - F1/0/A Q3/3 -
D8 F1/0/A F1/1/B F1/0/B F1/1/X Q4/3
D9 F1/1/B (*) F1/2/A F2/0/B F1/0/X F1/0/B
D10 F1/3/B - F2/2/B F1/0/B (*) F2/2/B
D11 F1/2/A - F2/1/A F1/1/A (*) -
D12 F1/2/B - F2/1/B F1/1/B (*) -
D13 F1/3/A - F2/2/A F1/0/A (*) F2/2/A
D14 F1/0/B - - F2/3/B -
D15 F1/0/A - - F2/3/A -
A0 - - F1/2/A - -
A1 F1/3/X F1/3/B F1/2/B - -
A2 F1/2/X F1/3/A F1/3/A - -
A3 - F1/2/A F1/3/B - -
A4 - - - Q3/1 -
A5 - - - Q3/0 -
D31 - - - - F1/2/B
D32 - - - - F1/2/A
D33 - - - - F1/1/B
D34 - - - - F1/1/A
D35 - - - - F1/0/B
D36 - - - - F1/0/A
=========== ========== ========== ====== ============== ======
Pins denoted with (*) are by default not wired at the board.
==== ========== ==== ==========
Pin Teensy 4.0 Pin Teensy 4.1
==== ========== ==== ==========
0 F1/1/X 0 F1/1/X
1 F1/0/X 1 F1/0/X
2 F4/2/A 2 F4/2/A
3 F4/2/B 3 F4/2/B
4 F2/0/A 4 F2/0/A
5 F2/1/A 5 F2/1/A
6 F2/2/A 6 F2/2/A
7 F1/3/B 7 F1/3/B
8 F1/3/A 8 F1/3/A
9 F2/2/B 9 F2/2/B
10 Q1/0 10 Q1/0
11 Q1/2 11 Q1/2
12 Q1/1 12 Q1/1
13 Q2/0 13 Q2/0
14 Q3/2 14 Q3/2
15 Q3/3 15 Q3/3
18 Q3/1 18 Q3/1
19 Q3/0 19 Q3/0
22 F4/0/A 22 F4/0/A
23 F4/1/A 23 F4/1/A
24 F1/2/X 24 F1/2/X
25 F1/3/X 25 F1/3/X
28 F3/1/B 28 F3/1/B
29 F3/1/A 29 F3/1/A
33 F2/0/B 33 F2/0/B
- - 36 F2/3/A
- - 37 F2/3/B
DAT1 F1/1/B 42 F1/1/B
DAT0 F1/1/A 43 F1/1/A
CLK F1/0/B 44 F1/0/B
CMD F1/0/A 45 F1/0/A
DAT2 F1/2/A 46 F1/2/A
DAT3 F1/2/B 47 F1/2/B
- - 48 F1/0/B
- - 49 F1/2/A
- - 50 F1/2/B
- - 51 F3/3/B
- - 52 F1/1/B
- - 53 F1/1/A
- - 54 F3/0/A
==== ========== ==== ==========
|
========= ==============
Pin Seeed ARCH MIX
========= ==============
J3_04 Q4/3
J3_10 Q1/3
J3_12 Q2/3
J3_13 Q3/3
J3_16 Q3/0
J3_17 Q3/1
J3_19 F1/3/X
J3_20 F1/2/X
J4_08 F4/0/A
J4_09 F4/1/A
J4_16 Q3/2
J4_17 Q3/3
J5_32 Q1/0
J5_28 Q1/1
J5_29 Q1/2
J5_30 Q2/0
J5_04 Q2/1
J5_05 Q2/3
J5_06 F2/0/A
J5_07 F2/0/B
J5_08 F2/1/A
J5_12 F2/1/B
J5_13 F2/2/A
J5_14 F2/2/B
J5_23 F1/3/A
J5_24 F1/3/B
J5_25 F2/3/A
J5_26 F2/3/B
J5_42 Q3/0
J5_43 Q3/1
J5_50 F1/0/X
LED_RED F2/3/A
LED_GREEN F1/3/A
LED_BLUE F1/3/B
========= ==============
|
========= ===============
Pin Olimex RT1010PY
========= ===============
D0 -
D1 F1/0/B
D2 F1/0/A
D3 F1/1/B
D4 F1/1/A
D5 F1/2/B
D6 F1/2/A
D7 F1/3/B
D8 F1/3/A
D9 -
D10 F1/0/B
D11 F1/0/A
D12 F1/1/B
D13 F1/1/A
D14 -
A0 -
A1 F1/2/B
A2 F1/2/A
A3 F1/3/B
A4 F1/3/A
SDI F1/3/X
SDO F1/2/X
CS0 F1/1/X
SCK F1/0/X
========= ===============
Legend:
* Qm/n: QTMR module m, channel n
* Fm/n/l: FLEXPWM module m, submodule n, channel l. The pulse at a X channel
is always aligned to the period start.
Pins without a PWM signal are not listed. A signal may be available at more
than one Pin. FlexPWM pins may also be pure CPU pin, not assigned to a board
signal. In that case the PWM output is disabled. The PWM channel of a submodule
0 may still be used as synchronization source for other channels of the same
module, unless used by another peripheral.
Submodule 0 pins for i.MX RT1011:
================== =======
Pin Channel
================== =======
Pin.cpu.GPIO_01 B
Pin.cpu.GPIO_02 A
Pin.cpu.GPIO_AD_12 X
Pin.cpu.GPIO_SD_01 B
Pin.cpu.GPIO_SD_02 A
================== =======
Submodule 0 pins for i.MX RT1021:
===================== ==================
Pin Module & Channel
===================== ==================
Pin.cpu.GPIO_AD_B1_06 FLEXPWM1 Channel A
Pin.cpu.GPIO_AD_B1_07 FLEXPWM1 Channel B
Pin.cpu.GPIO_EMC_26 FLEXPWM1 Channel A
Pin.cpu.GPIO_EMC_27 FLEXPWM1 Channel B
Pin.cpu.GPIO_AD_B0_14 FLEXPWM2 Channel A
Pin.cpu.GPIO_AD_B0_15 FLEXPWM2 Channel B
Pin.cpu.GPIO_EMC_10 FLEXPWM2 Channel X
Pin.cpu.GPIO_EMC_38 FLEXPWM2 Channel A
Pin.cpu.GPIO_EMC_39 FLEXPWM2 Channel B
===================== ==================
Submodule 0 pins for i.MX RT1052, i.MX RT1062 and i.MX RT1064:
===================== ==================
Pin Module & Channel
===================== ==================
Pin.cpu.GPIO_AD_B0_02 FLEXPWM1 Channel X
Pin.cpu.GPIO_EMC_23 FLEXPWM1 Channel A
Pin.cpu.GPIO_EMC_24 FLEXPWM1 Channel B
Pin.cpu.GPIO_SD_B0_00 FLEXPWM1 Channel A
Pin.cpu.GPIO_SD_B0_01 FLEXPWM1 Channel B
Pin.cpu.GPIO_B0_06 FLEXPWM2 Channel A
Pin.cpu.GPIO_B0_07 FLEXPWM2 Channel B
Pin.cpu.GPIO_EMC_06 FLEXPWM2 Channel A
Pin.cpu.GPIO_EMC_07 FLEXPWM2 Channel B
Pin.cpu.GPIO_EMC_29 FLEXPWM3 Channel A
Pin.cpu.GPIO_EMC_30 FLEXPWM3 Channel B
Pin.cpu.GPIO_AD_B1_08 FLEXPWM4 Channel A
Pin.cpu.GPIO_EMC_00 FLEXPWM4 Channel A
Pin.cpu.GPIO_EMC_01 FLEXPWM4 Channel B
===================== ==================
Submodule 0 pins for i.MX RT1176
====================== ======================
Pin Module & Channel
====================== ======================
Pin.cpu.GPIO_EMC_B1_00 FLEXPWM4 Channel A (*)
Pin.cpu.GPIO_EMC_B1_01 FLEXPWM4 Channel B (*)
Pin.cpu.GPIO_EMC_B1_06 FLEXPWM2 Channel A (*)
Pin.cpu.GPIO_EMC_B1_07 FLEXPWM2 Channel B (*)
Pin.cpu.GPIO_EMC_B1_23 FLEXPWM1 Channel A (*)
Pin.cpu.GPIO_EMC_B1_24 FLEXPWM1 Channel B (*)
Pin.cpu.GPIO_EMC_B1_29 FLEXPWM3 Channel A (*)
Pin.cpu.GPIO_EMC_B1_30 FLEXPWM3 Channel B (*)
Pin.cpu.GPIO_AD_00 FLEXPWM1 Channel A
Pin.cpu.GPIO_AD_01 FLEXPWM1 Channel B
Pin.cpu.GPIO_AD_24 FLEXPWM2 Channel A
Pin.cpu.GPIO_AD_25 FLEXPWM2 Channel B
====================== ======================
.. _mimxrt_spi_pinout:
|
|
Hardware SPI pin assignment
---------------------------
The SPI signals have fixed assignments to GPIO pins.
It depends on the board design, which SPI's signals are exposed to the user, as
detailed in the table below. The signal order in the table is: CS0, CS1, MOSI, MISO, CLK.
================= ========================= ======================= ===============
Board / Pin SPI0 SPI1 SPI2
================= ========================= ======================= ===============
Teensy 4.0 10/-/11/12/13 0/-/26/1/27 -
Teensy 4.1 10/37/11/12/13 0/-/26/1/27 -/29/50/54/49
MIXMXRT1010-EVK D10/D7/D11/D12/D13 - -
MIXMXRT1015-EVK D10/-/D11/D12/D13 - -
MIXMXRT1020-EVK D10/-/D11/D12/D13 A3/D0/A5/A4/A0 -
MIXMXRT1050-EVK D10/-/D11/D12/D13 (*) - -
MIXMXRT1050-EVKB D10/-/D11/D12/D13 (*) - -
MIXMXRT1060-EVK D10/-/D11/D12/D13 (*) - -
MIXMXRT1064-EVK D10/-/D11/D12/D13 (*) - -
MIXMXRT1170-EVK D10/-/D11/D12/D13 D28/-/D25/D24/D26 -/-/D14/D15/D24
Olimex RT1010Py - CS0/-/SDO/SDI/SCK SDCARD with CS1
Seeed ARCH MIX J4_12/-/J4_14/J4_13/J4_15 J3_09/J3_05/J3_08_J3_11
================= ========================= ======================= ===============
Pins denoted with (*) are by default not wired at the board.
.. _mimxrt_i2c_pinout:
|
|
Hardware I2C pin assignment
---------------------------
The I2C signals have fixed assignments to GPIO pins.
It depends on the board design, which I2C's signals are exposed to the user, as
detailed in the table below. The signal order in the table is: SDA, SCL.
================= =========== =========== =========== ======= =======
Board / Pin I2C 0 I2C 1 I2C 2 I2C 3 I2C 4
================= =========== =========== =========== ======= =======
Teensy 4.0 18/19 17/16 25/24 - -
Teensy 4.1 18/19 17/16 25/24 - -
MIXMXRT1010-EVK D14/D15 D0/D1 - - -
MIXMXRT1015-EVK D14/D15 - - - -
MIXMXRT1020-EVK D14/D15 A4/A5 D0/D1 - -
MIXMXRT1050-EVK A4/A5 D1/D0 - - -
MIXMXRT1050-EVKB A4/A5 D1/D0 - - -
MIXMXRT1060-EVK A4/A5 D1/D0 - - -
MIXMXRT1064-EVK A4/A5 D1/D0 - - -
MIXMXRT1170-EVK D14/D15 D1/D0 A4/A5 D26/D25 D19/D18
Olimex RT1010Py - SDA1/SCL1 SDA2/SCL2 - -
Seeed ARCH MIX J3_17/J3_16 J4_06/J4_07 J5_05/J5_04 - -
================= =========== =========== =========== ======= =======
.. _mimxrt_i2s_pinout:
|
|
Hardware I2S pin assignment
---------------------------
Pin assignments for a few MIMXRT boards:
=============== == ===== ======== ======= ======= ======== ======= =======
Board ID MCK SCK_TX WS_TX SD_TX SCK_RX WS_RX SD_RX
=============== == ===== ======== ======= ======= ======== ======= =======
Teensy 4.0 1 23 26 27 7 21 20 8
Teensy 4.0 2 33 4 3 2 - - 5
Teensy 4.1 1 23 26 27 7 21 20 8
Teensy 4.1 2 33 4 3 2 - - 5
Seeed Arch MIX 1 J4_09 J4_14 J4_15 J14_13 J4_11 J4_10 J4_10
Olimex RT1010Py 1 D8 D6 D7 D4 D1 D2 D3
Olimex RT1010Py 3 - D10 D9 D11 - - -
MIMXRT_DEV 1 "MCK" "SCK_TX" "WS_TX" "SD_TX" "SCK_RX" "WS_RX" "SD_RX"
=============== == ===== ======== ======= ======= ======== ======= =======
Symbolic pin names are provided for the MIMXRT_10xx_DEV boards.
These are provided for the other boards as well.

546
docs/mimxrt/quickref.rst Normal file
View File

@@ -0,0 +1,546 @@
.. _mimxrt_quickref:
Quick reference for the i.MXRT family
=====================================
.. image:: img/teensy_4.1.jpg
:alt: Teensy 4.1 board
:width: 640px
The Teensy 4.1 board.
Below is a quick reference for i.MXRT-based boards. If it is your first time
working with this board it may be useful to get an overview of the microcontroller:
.. toctree::
:maxdepth: 1
general.rst
tutorial/intro.rst
pinout.rst
Installing MicroPython
----------------------
See the corresponding section of tutorial: :ref:`mimxrt_intro`. It also includes
a troubleshooting subsection.
General board control
---------------------
The MicroPython REPL is on the USB port, configured in VCP mode.
Tab-completion is useful to find out what methods an object has.
Paste mode (ctrl-E) is useful to paste a large slab of Python code into
the REPL.
The :mod:`machine` module::
import machine
machine.freq() # get the current frequency of the CPU
Delay and timing
----------------
Use the :mod:`time <time>` module::
import time
time.sleep(1) # sleep for 1 second
time.sleep_ms(500) # sleep for 500 milliseconds
time.sleep_us(10) # sleep for 10 microseconds
start = time.ticks_ms() # get millisecond counter
delta = time.ticks_diff(time.ticks_ms(), start) # compute time difference
Timers
------
The i.MXRT port has three hardware timers. Use the :ref:`machine.Timer <machine.Timer>` class
with a timer ID from 0 to 2 (inclusive)::
from machine import Timer
tim0 = Timer(0)
tim0.init(period=5000, mode=Timer.ONE_SHOT, callback=lambda t:print(0))
tim1 = Timer(1)
tim1.init(period=2000, mode=Timer.PERIODIC, callback=lambda t:print(1))
The period is in milliseconds.
Virtual timers are not currently supported on this port.
.. _mimxrt_Pins_and_GPIO:
Pins and GPIO
-------------
Use the :ref:`machine.Pin <machine.Pin>` class::
from machine import Pin
p0 = Pin('D0', Pin.OUT) # create output pin on GPIO0
p0.on() # set pin to "on" (high) level
p0.off() # set pin to "off" (low) level
p0.value(1) # set pin to on/high
p2 = Pin('D2', Pin.IN) # create input pin on GPIO2
print(p2.value()) # get value, 0 or 1
p4 = Pin('D4', Pin.IN, Pin.PULL_UP) # enable internal pull-up resistor
p5 = Pin('D5', Pin.OUT, value=1) # set pin high on creation
p6 = Pin(pin.cpu.GPIO_B1_15, Pin.OUT) # Use the cpu pin name.
Available Pins follow the ranges and labelling of the respective board, like:
- 0-33 for Teensy 4.0,
- 0-21 for the MIMXRT10xx-EVK board, or 'D0-Dxx', or 'A0-Ann',
- 0-14 for the Olimex RT1010Py board, or 'D0'-'Dxx' and 'A0'-'Ann'
- 'J3_xx', 'J4_xx', 'J5_xx' for the Seeed ARCH MIX board,
or the pin names of the Pin.board or Pin.cpu classes.
Notes:
* The MIMXRT1xxx-EVK boards may have other on-board devices connected to these
pins, limiting it's use for input or output.
* At the MIMXRT1010_EVK, pins D4, D5 and D9 of the Arduino connector are by
default not connected to the MCU. For details refer to the schematics.
* At the MIMXRT1170_EVK board, the inner rows of the Arduino connectors are assigned as follows:
- D16 - D23: J9, odd pin numbers; D17 is by default not connected.
- D24 - D27: J26, odd pin numbers; J63-J66 have to be closed to enable these pins.
- D29 - D36: J25, odd pin numbers; D29 and D30 are by default not connected.
There's a higher-level abstraction :ref:`machine.Signal <machine.Signal>`
which can be used to invert a pin. Useful for illuminating active-low LEDs
using ``on()`` or ``value(1)``.
UART (serial bus)
-----------------
See :ref:`machine.UART <machine.UART>`. ::
from machine import UART
uart1 = UART(1, baudrate=115200)
uart1.write('hello') # write 5 bytes
uart1.read(5) # read up to 5 bytes
The i.MXRT has up to eight hardware UARTs, but not every board exposes all
TX and RX pins for users. For the assignment of Pins to UART signals,
refer to the :ref:`UART pinout <mimxrt_uart_pinout>`.
PWM (pulse width modulation)
----------------------------
The i.MXRT has up to four dedicated PWM modules with four FLEXPWM submodules each
and up to four QTMR modules with four channels, which can be used to generate
a PWM signal or signal pair.
The PWM functions are provided by the :ref:`machine.PWM <machine.PWM>` class.
It supports all basic methods listed for that class and a few additional methods for
handling signal groups. ::
# Samples for Teensy
#
from machine import Pin, PWM
pwm2 = PWM(Pin(2)) # create PWM object from a pin
pwm2.freq() # get current frequency
pwm2.freq(1000) # set frequency
pwm2.duty_u16() # get current duty cycle, range 0-65535
pwm2.duty_u16(200) # set duty cycle, range 0-65535
pwm2.deinit() # turn off PWM on the pin
# create a complementary signal pair on Pin 2 and 3
pwm2 = PWM((2, 3), freq=2000, duty_ns=20000)
# Create a group of four synchronized signals.
# Start with Pin(4) at submodule 0, which creates the sync pulse.
pwm4 = PWM(Pin(4), freq=1000, align=PWM.HEAD)
# Pins 5, 6, and 9 are pins at the same module
pwm5 = PWM(Pin(5), freq=1000, duty_u16=10000, align=PWM.HEAD, sync=True)
pwm6 = PWM(Pin(6), freq=1000, duty_u16=20000, align=PWM.HEAD, sync=True)
pwm9 = PWM(Pin(9), freq=1000, duty_u16=30000, align=PWM.HEAD, sync=True)
pwm3 # show the PWM objects properties
PWM Constructor
```````````````
.. class:: PWM(dest, freq, duty_u16, duty_ns, *, center, align, invert, sync, xor, deadtime)
:noindex:
Construct and return a new PWM object using the following parameters:
- *dest* is the entity on which the PWM is output, which is usually a
:ref:`machine.Pin <machine.Pin>` object, but a port may allow other values,
like integers or strings, which designate a Pin in the machine.PIN class.
*dest* is either a single object or a two element object tuple.
If the object tuple is specified, the two pins act in complementary
mode. These two pins must be the A/B channels of the same submodule.
PWM objects are either provided by a FLEXPWM module or a QTMR module.
The i.MXRT devices have either two or four FLEXPWM and QTMR modules.
Each FLEXPWM module has four submodules with three channels, each,
called A, B and X. Each QTMR module has four channels.
Each FLEXPWM submodule or QTMR channel may be set to different parameters.
Not every channel is routed to a board pin. Details are listed below.
Setting *freq* affects the three channels of the same FLEXPWM submodule.
Only one of *duty_u16* and *duty_ns* should be specified at a time.
Keyword arguments:
- *freq* should be an integer which sets the frequency in Hz for the
PWM cycle. The valid frequency range is 15 Hz resp. 18Hz resp. 24Hz up to > 1 MHz.
- *duty_u16* sets the duty cycle as a ratio ``duty_u16 / 65536``.
The duty cycle of a X channel can only be changed, if the A and B channel
of the respective submodule is not used. Otherwise the duty_16 value of the
X channel is 32768 (50%).
- *duty_ns* sets the pulse width in nanoseconds. The limitation for X channels
apply as well.
- *center*\=value. An integer sets the center of the pulse within the pulse period.
The range is 0-65535. The resulting pulse will last from center - duty_u16/2 to
center + duty_u16/2.
- *align*\=value. Shortcuts for the pulse center setting, causing the pulse either at
the center of the frame (value=0), the leading edge at the begin (value=1) or the
trailing edge at the end of a pulse period (value=2).
- *invert*\=True|False channel_mask. Setting a bit in the mask inverts the respective channel.
Bit 0 inverts the first specified channel, bit 2 the second. The default is 0.
- *sync*\=True|False. If a channel of a module's submodule 0 is already active, other
submodules of the same module can be forced to be synchronous to submodule 0. Their
pulse period start then at at same clock cycle. The default is False.
- *xor*\=0|1|2. If set to 1 or 2, the channel will output the XOR'd signal from channels
A or B. If set to 1 on channel A or B, both A and B will show the same signal. If set
to 2, A and B will show alternating signals. For details and an illustration, please
refer to the MCU's reference manual, chapter "Double Switching PWMs".
- *deadtime*\=time_ns. This setting affects complementary channels and defines a deadtime
between an edge of a first channel and the edge of the next channel, in which both
channels are set to low. That allows connected H-bridges to switch off one side
of a push-pull driver before switching on the other side.
PWM Methods
```````````
The methods are identical to the generic :ref:`machine.PWM <machine.PWM>` class,
with additional keyword arguments to the init() method, matchings those of the constructor.
Each FLEX submodule or QTMR module may run at different frequencies. The PWM signal
is created by dividing the pwm_clk signal by an integral factor, according to the formula::
f = pwm_clk / (2**n * m)
with n being in the range of 0..7, and m in the range of 2..65536. pmw_clk is 125Mhz
for MIMXRT1010/1015/1020, 150 MHz for MIMXRT1050/1060/1064 and 160MHz for MIMXRT1170.
The lowest frequency is pwm_clk/2**23 (15, 18, 20Hz). The highest frequency with
U16 resolution is pwm_clk/2**16 (1907, 2288, 2441 Hz), the highest frequency
with 1 percent resolution is pwm_clk/100 (1.25, 1.5, 1.6 MHz). The highest achievable
frequency is pwm_clk/3 for the A/B channels, and pwm_clk/2 for the X channels and QTMR
signal.
PWM Pin Assignment
``````````````````
Pins are specified in the same way as for the Pin class. For the assignment of Pins
to PWM signals, refer to the :ref:`PWM pinout <mimxrt_pwm_pinout>`.
ADC (analog to digital conversion)
----------------------------------
On the i.MXRT ADC functionality is available on Pins labeled 'Ann'.
Use the :ref:`machine.ADC <machine.ADC>` class::
from machine import ADC
adc = ADC(Pin(32)) # create ADC object on ADC pin
adc.read_u16() # read value, 0-65536 across voltage range 0.0v - 3.3v
The resolution of the ADC is 12 bit with 10 to 11 bit accuracy, irrespective of the
value returned by read_u16(). If you need a higher resolution or better accuracy, use
an external ADC.
Software SPI bus
----------------
Software SPI (using bit-banging) works on all pins, and is accessed via the
:ref:`machine.SoftSPI <machine.SoftSPI>` class. ::
from machine import Pin, SoftSPI
# construct a SoftSPI bus on the given pins
# polarity is the idle state of SCK
# phase=0 means sample on the first edge of SCK, phase=1 means the second
spi = SoftSPI(baudrate=100000, polarity=1, phase=0, sck=Pin(0), mosi=Pin(2), miso=Pin(4))
spi.init(baudrate=200000) # set the baudrate
spi.read(10) # read 10 bytes on MISO
spi.read(10, 0xff) # read 10 bytes while outputting 0xff on MOSI
buf = bytearray(50) # create a buffer
spi.readinto(buf) # read into the given buffer (reads 50 bytes in this case)
spi.readinto(buf, 0xff) # read into the given buffer and output 0xff on MOSI
spi.write(b'12345') # write 5 bytes on MOSI
buf = bytearray(4) # create a buffer
spi.write_readinto(b'1234', buf) # write to MOSI and read from MISO into the buffer
spi.write_readinto(buf, buf) # write buf to MOSI and read MISO back into buf
The highest supported baud rate is 500000.
Hardware SPI bus
----------------
There are up to four hardware SPI channels that allow faster transmission
rates (up to 30Mhz). Hardware SPI is accessed via the
:ref:`machine.SPI <machine.SPI>` class and has the same methods as software SPI above::
from machine import SPI
spi = SPI(0, 10000000)
spi.write('Hello World')
For the assignment of Pins to SPI signals, refer to
:ref:`Hardware SPI pinout <mimxrt_spi_pinout>`.
Notes:
1. Even if the highest reliable baud rate at the moment is about 30 Mhz,
setting a baud rate will not always result in exactly that
frequency, especially at high baud rates.
2. Sending at higher baud rate is possible. In the tests receiving
worked up to 60 MHz, sending up to 90 MHz.
Software I2C bus
----------------
Software I2C (using bit-banging) works on all output-capable pins, and is
accessed via the :ref:`machine.SoftI2C <machine.SoftI2C>` class::
from machine import Pin, SoftI2C
i2c = SoftI2C(scl=Pin(5), sda=Pin(4), freq=100000)
i2c.scan() # scan for devices
i2c.readfrom(0x3a, 4) # read 4 bytes from device with address 0x3a
i2c.writeto(0x3a, '12') # write '12' to device with address 0x3a
buf = bytearray(10) # create a buffer with 10 bytes
i2c.writeto(0x3a, buf) # write the given buffer to the slave
The highest supported freq is 400000.
Hardware I2C bus
----------------
There are up to four hardware I2C channels that allow faster transmission rates
and support the full I2C protocol. The I2C signals have fixed assignments to GPIO pins.
For the assignment of Pins to I2C signals, refer to :ref:`Hardware I2C pinout <mimxrt_i2c_pinout>`.
Hardware I2C is accessed via the :ref:`machine.I2C <machine.I2C>` class and
has the same methods as software SPI above::
from machine import I2C
i2c = I2C(0, 400_000)
i2c.writeto(0x76, b"Hello World")
I2S bus
-------
See :ref:`machine.I2S <machine.I2S>`. Example using a Teensy 4.1 board with a simple
external Codec like UDA1334.::
from machine import I2S, Pin
i2s = I2S(2, sck=Pin(26), ws=Pin(27), sd=Pin(7),
mode=I2S.TX, bts=16,format=I2S.STEREO,
rate=44100,ibuf=40000)
i2s.write(buf) # write buffer of audio samples to I2S device
Example for using I2S with a MIMXRT10xx_DEV board::
from machine import I2S, I2C, Pin
import wm8960
i2c=I2C(0)
wm=wm8960.WM8960(i2c, sample_rate=SAMPLE_RATE_IN_HZ,
adc_sync=wm8960.sync_dac,
swap=wm8960.swap_input)
i2s = I2S(1, sck=Pin("SCK_TX"), ws=Pin("WS_TX"), sd=Pin("SD_RX"),
mck=Pin("MCK),mode=I2S.RX, bts=16,format=I2S.MONO,
rate=32000,ibuf=10000)
i2s.readinto(buf) # fill buffer with audio samples from I2S device
In this example, the input channels are swapped in the WM8960 driver, since the
on-board microphone is connected to the right channel, but mono audio is taken
from the left channel. Note, that the sck and ws pins are connected to the TX
signals of the I2S bus. That is intentional, since at the MW8960 codec these
signals are shared for RX and TX.
Example using the Teensy audio shield::
from machine import I2C, I2S, Pin
from sgtl5000 import CODEC
i2s = I2S(1, sck=Pin(21), ws=Pin(20), sd=Pin(7), mck=Pin(23),
mode=I2S.TX, bits=16,rate=44100,format=I2S.STEREO,
ibuf=40000,
)
# configure the SGTL5000 codec
i2c = I2C(0, freq=400000)
codec = CODEC(0x0A, i2c)
codec.mute_dac(False)
codec.dac_volume(0.9, 0.9)
codec.headphone_select(0)
codec.mute_headphone(False)
codec.volume(0.7, 0.7)
i2s.write(buf) # write buffer of audio samples to I2S device
The SGTL5000 codec used by the Teensy Audio shield uses the RX signals for both
RX and TX. Note that the codec is initialized after the I2S device. That is
essential since MCK is needed for its I2C operation and is provided by the I2S
controller.
MIMXRT boards may have 1 or 2 I2S buses available at the board connectors.
On MIMXRT1010 devices the bus numbers are 1 and 3. The I2S signals have
fixed assignments to GPIO pins. For the assignment of Pins to I2S signals,
refer to :ref:`I2S pinout <mimxrt_i2s_pinout>`.
Real time clock (RTC)
---------------------
See :ref:`machine.RTC <machine.RTC>`::
from machine import RTC
rtc = RTC()
rtc.datetime((2017, 8, 23, 1, 12, 48, 0, 0)) # set a specific date and time
rtc.datetime() # get date and time
rtc.now() # return date and time in CPython format.
The i.MXRT MCU supports battery backup of the RTC. By connecting a battery of
1.5-3.6V, time and date are maintained in the absence of the main power. The
current drawn from the battery is ~20µA, which is rather high. A CR2032 coin
cell will last for about one year.
SD card
-------
See :ref:`machine.SDCard <machine.SDCard>`::
import machine, os
sd = machine.SDCard()
fs = os.VfsFat(sd)
os.mount(fs, "/sd") # mount
os.listdir('/sd') # list directory contents
os.umount('/sd') # eject
Note: The i.mx-rt 1011 and 1015 based boards do not support the ``machine.SDCard``
class. For these, the SPI based driver ``sdcard.py`` from the MicroPython drivers
can be used. When using it, you have to overdrive the CS pin of the SPI hardware
module. Example::
import os, sdcard, machine
cs_pin = "D10"
spi = machine.SPI(0) # SPI0 with cs at Pin "D10" used for SDCARD
cs = machine.Pin(cs_pin, machine.Pin.OUT, value=1)
sd = sdcard.SDCard(spi, cs)
vfs = os.VfsFat(sd)
os.mount(vfs, "/sdcard")
OneWire driver
--------------
The OneWire driver is implemented in software and works on all pins::
from machine import Pin
import onewire
ow = onewire.OneWire(Pin(12)) # create a OneWire bus on GPIO12
ow.scan() # return a list of devices on the bus
ow.reset() # reset the bus
ow.readbyte() # read a byte
ow.writebyte(0x12) # write a byte on the bus
ow.write('123') # write bytes on the bus
ow.select_rom(b'12345678') # select a specific device by its ROM code
There is a specific driver for DS18S20 and DS18B20 devices::
import time, ds18x20
ds = ds18x20.DS18X20(ow)
roms = ds.scan()
ds.convert_temp()
time.sleep_ms(750)
for rom in roms:
print(ds.read_temp(rom))
Be sure to put a 4.7k pull-up resistor on the data line. Note that
the ``convert_temp()`` method must be called each time you want to
sample the temperature.
DHT driver
----------
The DHT driver is implemented in software and works on all pins::
import dht
import machine
d = dht.DHT11(machine.Pin(4))
d.measure()
d.temperature() # eg. 23 (°C)
d.humidity() # eg. 41 (% RH)
d = dht.DHT22(machine.Pin(4))
d.measure()
d.temperature() # eg. 23.6 (°C)
d.humidity() # eg. 41.3 (% RH)
Be sure to have a 4.7k pull-up resistor on the data line. Some
DHT modules may already have one.
Ethernet driver
---------------
All MIMXRT boards except the MIMXRT1011 based boards and Teensy 4.0 support
Ethernet. Example usage::
import network
lan = network.LAN(0)
lan.active(True)
If there is a DHCP server in the LAN, the IP address is supplied by that server.
Otherwise, the IP address can be set with lan.ifconfig(). The default address
is 192.168.0.1.
Teensy 4.1 does not have an Ethernet jack on the board, but PJRC offers an
adapter for self-assembly. The Seeed ARCH MIX board has no PHY hardware on the
board, however you can attach external PHY interfaces. By default, the firmware
for Seeed Arch Mix uses the driver for a LAN8720 PHY. The MIMXRT1170_EVK is
equipped with two Ethernet ports, which are addressed as LAN(0) for the 100M
port and LAN(1) for the 1G port.
For details of the network interface refer to the class :ref:`network.LAN <network.LAN>`.
Transferring files
------------------
Files can be transferred to the i.MXRT devices for instance with the ``mpremote``
tool or using an SD card. If Ethernet is available, you can also use ftp.
See the MicroPython forum for the FTP server or other community-supported
alternatives to transfer files to an i.MXRT board, like rshell or Thonny.

View File

@@ -0,0 +1,125 @@
.. _mimxrt_intro:
Getting started with MicroPython on the i.MXRT
==============================================
Using MicroPython is a great way to get the most of your i.MXRT board. And
vice versa, the i.MXRT chip is a great platform for using MicroPython. This
tutorial will guide you through setting up MicroPython, getting a prompt, using
the hardware peripherals, and controlling some external components.
Let's get started!
Requirements
------------
The first thing you need is a board with an i.MXRT chip. The MicroPython
software supports the i.MXRT chip itself and any board should work. The main
characteristic of a board is how the GPIO pins are connected to the outside
world, and whether it includes a built-in USB-serial converter to make the
UART available to your PC.
Names of pins will be given in this tutorial using the chip names (eg GPIO2)
and it should be straightforward to find which pin this corresponds to on your
particular board.
Powering the board
------------------
If your board has a USB connector on it then most likely it is powered through
this when connected to your PC. Otherwise you will need to power it directly.
Please refer to the documentation for your board for further details.
Getting the firmware
--------------------
Firmware versions are provided at the
`MicroPython download page <https://micropython.org/download/?port=mimxrt>`_.
You can download the most recent MicroPython firmware .hex or .bin file to load
onto your i.MXRT device. From that download page you have two main choices:
* stable firmware builds
* daily firmware builds
If you are just starting with MicroPython, the best bet is to go for the stable
firmware builds. If you are an advanced, experienced MicroPython i.MXRT user
who would like to follow development closely and help with testing new
features, there are daily builds.
Deploying the firmware
----------------------
Once you have the MicroPython firmware you need to load it onto your
i.MXRT device. The exact procedure for these steps is highly dependent
on the particular board and you will need to refer to its documentation
for details.
Teensy 4.0 and 4.1
~~~~~~~~~~~~~~~~~~
For Teensy 4.0 and 4.1 you have to use the built-in loader together with the PC
loader provided by PJRC. The built-in loader will be activated by pushing the
button on the board. Then you can upload the firmware with the command::
teensy_loader_cli --mcu=imxrt1062 -v -w firmware.hex
IMXRT10xx-EVK boards
~~~~~~~~~~~~~~~~~~~~
The IMXRT10xx-EVK boards have a second USB port connected to a support MCU.
Connecting that USB port to your PC will register a disk drive with the name of
the board. Just copy the firmware.bin file to this drive, and that will start
the flashing procedure. You will know that the flash was complete, if that
drive disappears and reappears. If you decided to install the very useful
Segger open-SDA firmware on that sidekick MCU, then you have to use the debugger
software to upload the i.MXRT firmware.
Seed ARCH MIX board
~~~~~~~~~~~~~~~~~~~
Firmware upload to the Seed ARCH MIX board is less convenient. The vendor
suggests using J-Link as a method and tool. For that, follow the instructions
given by Seed in their Wiki at
https://wiki.seeedstudio.com/Arch_Mix/#flashing-arduino-bootloader-to-arch-mix.
You will need a J-Link debug probe and software. You may find Segger JLink edu
or Segger JLink edu mini convenient. As a matching loader you can use
JFlashLite. The target address for loading is 0x60000000.
The MIMXRT family also support a serial upload method. The software for serial
upload is provided by NXP. The steps to use it are:
- Connect J3, Pin 19 to 3.3V (GPIO_AD_B0_05).
- Change the DIP-Switch settings from off-off-on-off to off-off-off-on
- Push Reset
- Run the upload with: ./FLASH.sh <firmware_image_file name>
- Once the upload has finished, set the DIP-switch back to off-off-on-off.
- Remove the Jumper to J3, Pin19 and push reset
To avoid running the Flash loader as superuser, you can copy the provided udev-rules
script to /etc/udev/rules.d/. FLASH.sh calls two binaries, blhost and sdphost,
which are provided by NXP under the BSD-3-Clause License. A version of these
binaries and the script can be downloaded at
https://github.com/robert-hh/Shared-Stuff/blob/master/mimxrt_serial_downloader.zip.
Serial downloading can be used for the NXP MIMXRT boards as well. But the built-in loader
is much more convenient to use.
Serial prompt
-------------
Once you have the firmware on the device you can access the REPL (Python prompt)
over USB.
From there you can follow the i.MXRT tutorial.
Troubleshooting installation problems
-------------------------------------
If you experience problems during flashing or with running firmware immediately
after it, here are some troubleshooting recommendations:
* Be aware of and try to exclude hardware problems. There are two common
problems: bad power source quality, and worn-out/defective Flash ROM.
Speaking of power source, not just raw amperage is important, but also low
ripple and noise/EMI in general. The most reliable and convenient power
source is a USB port.

View File

@@ -112,7 +112,8 @@ with an underscore as in ``_COLS``: this symbol is not visible outside the
module so will not occupy RAM.
The argument to ``const()`` may be anything which, at compile time, evaluates
to an integer e.g. ``0x100`` or ``1 << 8``. It can even include other const
to a constant e.g. ``0x100``, ``1 << 8`` or ``(True, "string", b"bytes")``
(see section below for details). It can even include other const
symbols that have already been defined, e.g. ``1 << BIT``.
**Constant data structures**
@@ -126,8 +127,9 @@ that the objects remain in flash memory rather than being copied to RAM. The
Python built-in types.
When considering the implications of frozen bytecode, note that in Python
strings, floats, bytes, integers and complex numbers are immutable. Accordingly
these will be frozen into flash. Thus, in the line
strings, floats, bytes, integers, complex numbers and tuples are immutable.
Accordingly these will be frozen into flash (for tuples, only if all their
elements are immutable). Thus, in the line
.. code::
@@ -146,16 +148,16 @@ As in the string example, at runtime a reference to the arbitrarily large
integer is assigned to the variable ``bar``. That reference occupies a
single machine word.
It might be expected that tuples of integers could be employed for the purpose
of storing constant data with minimal RAM use. With the current compiler this
is ineffective (the code works, but RAM is not saved).
Tuples of constant objects are themselves constant. Such constant tuples are
optimised by the compiler so they do not need to be created at runtime each time
they are used. For example:
.. code::
foo = (1, 2, 3, 4, 5, 6, 100000)
foo = (1, 2, 3, 4, 5, 6, 100000, ("string", b"bytes", False, True))
At runtime the tuple will be located in RAM. This may be subject to future
improvement.
This entire tuple will exist as a single object (potentially in flash if the
code is frozen) and referenced each time it is needed.
**Needless object creation**
@@ -214,7 +216,7 @@ buffer; this is both faster and more efficient in terms of memory fragmentation.
**Bytes are smaller than ints**
On most platforms an integer consumes four bytes. Consider the two calls to the
On most platforms an integer consumes four bytes. Consider the three calls to the
function ``foo()``:
.. code::
@@ -222,12 +224,16 @@ function ``foo()``:
def foo(bar):
for x in bar:
print(x)
foo([1, 2, 0xff])
foo((1, 2, 0xff))
foo(b'\1\2\xff')
In the first call a tuple of integers is created in RAM. The second efficiently
In the first call a `list` of integers is created in RAM each time the code is
executed. The second call creates a constant `tuple` object (a `tuple` containing
only constant objects) as part of the compilation phase, so it is only created
once and is more efficient than the `list`. The third call efficiently
creates a `bytes` object consuming the minimum amount of RAM. If the module
were frozen as bytecode, the `bytes` object would reside in flash.
were frozen as bytecode, both the `tuple` and `bytes` object would reside in flash.
**Strings Versus Bytes**

View File

@@ -219,6 +219,33 @@ Exceptions
If an ISR raises an exception it will not propagate to the main loop. The interrupt will be disabled unless the
exception is handled by the ISR code.
Interfacing to uasyncio
-----------------------
When an ISR runs it can preempt the `uasyncio` scheduler. If the ISR performs a `uasyncio`
operation the scheduler's operation can be disrupted. This applies whether the interrupt is hard
or soft and also applies if the ISR has passed execution to another function via
`micropython.schedule`. In particular creating or cancelling tasks is invalid in an ISR context.
The safe way to interact with `uasyncio` is to implement a coroutine with synchronisation performed by
`uasyncio.ThreadSafeFlag`. The following fragment illustrates the creation of a task in response
to an interrupt:
.. code:: python
tsf = uasyncio.ThreadSafeFlag()
def isr(_): # Interrupt handler
tsf.set()
async def foo():
while True:
await tsf.wait()
uasyncio.create_task(bar())
In this example there will be a variable amount of latency between the execution of the ISR and the execution
of ``foo()``. This is inherent to cooperative scheduling. The maximum latency is application
and platform dependent but may typically be measured in tens of ms.
General issues
--------------
@@ -339,8 +366,8 @@ A critical section can comprise a single line of code and a single variable. Con
This example illustrates a subtle source of bugs. The line ``count += 1`` in the main loop carries a specific race
condition hazard known as a read-modify-write. This is a classic cause of bugs in real time systems. In the main loop
MicroPython reads the value of ``t.counter``, adds 1 to it, and writes it back. On rare occasions the interrupt occurs
after the read and before the write. The interrupt modifies ``t.counter`` but its change is overwritten by the main
MicroPython reads the value of ``count``, adds 1 to it, and writes it back. On rare occasions the interrupt occurs
after the read and before the write. The interrupt modifies ``count`` but its change is overwritten by the main
loop when the ISR returns. In a real system this could lead to rare, unpredictable failures.
As mentioned above, care should be taken if an instance of a Python built in type is modified in the main code and

View File

@@ -57,7 +57,7 @@ Freezing source code
directory then all files in that directory will be frozen.
*opt* is the optimisation level to pass to mpy-cross when compiling ``.py``
to ``.mpy``.
to ``.mpy``. These levels are described in :func:`micropython.opt_level`.
.. function:: freeze_as_str(path)

View File

@@ -60,6 +60,25 @@ The full list of supported commands are:
$ mpremote disconnect
After a disconnect, auto soft-reset is enabled.
- resume a previous ``mpremote`` session:
.. code-block:: bash
$ mpremote resume
This disables auto soft-reset.
- perform a soft-reset of the device:
.. code-block:: bash
$ mpremote soft-reset
This will clear out the Python heap and restart the interpreter. It also
disables auto soft-reset.
- enter the REPL on the connected device:
.. code-block:: bash
@@ -114,14 +133,49 @@ The full list of supported commands are:
.. code-block:: bash
$ mpremote mount <local-dir>
$ mpremote mount [options] <local-dir>
During usage, Ctrl-D will soft-reboot and normally reconnect the mount automatically.
If the unit has a main.py running at startup however the remount cannot occur.
In this case a raw mode soft reboot can be used: Ctrl-A Ctrl-D to reboot,
then Ctrl-B to get back to normal repl at which point the mount will be ready.
Options are:
- ``-l``, ``--unsafe-links``: By default an error will be raised if the device
accesses a file or directory which is outside (up one or more directory levels) the
local directory that is mounted. This option disables this check for symbolic
links, allowing the device to follow symbolic links outside of the local directory.
- unmount the local directory from the remote device:
.. code-block:: bash
$ mpremote umount
Multiple commands can be specified and they will be run sequentially.
Auto connection and soft-reset
------------------------------
Connection and disconnection will be done automatically at the start and end of
the execution of the tool, if such commands are not explicitly given. Automatic
connection will search for the first available serial device. If no action is
specified then the REPL will be entered.
Once connected to a device, ``mpremote`` will automatically soft-reset the
device if needed. This clears the Python heap and restarts the interpreter,
making sure that subsequent Python code executes in a fresh environment. Auto
soft-reset is performed the first time one of the following commands are
executed: ``mount``, ``eval``, ``exec``, ``run``, ``fs``. After doing a
soft-reset for the first time, it will not be done again automatically, until a
``disconnect`` command is issued.
Auto soft-reset behaviour can be controlled by the ``resume`` command. And the
``soft-reset`` command can be used to perform an explicit soft reset.
Shortcuts
---------

View File

@@ -27,24 +27,16 @@ Compatibility is based on the following:
* Version of the .mpy file: the version of the file must match the version
supported by the system loading it.
* Bytecode features used in the .mpy file: there are two bytecode features
which must match between the file and the system: unicode support and
inline caching of map lookups in the bytecode.
* Small integer bits: the .mpy file will require a minimum number of bits in
a small integer and the system loading it must support at least this many
bits.
* Qstr compression window size: the .mpy file will require a minimum window
size for qstr decompression and the system loading it must have a window
greater or equal to this size.
* Native architecture: if the .mpy file contains native machine code then
it will specify the architecture of that machine code and the system
loading it must support execution of that architecture's code.
If a MicroPython system supports importing .mpy files then the
``sys.implementation.mpy`` field will exist and return an integer which
``sys.implementation._mpy`` field will exist and return an integer which
encodes the version (lower 8 bits), features and native architecture.
Trying to import an .mpy file that fails one of the first four tests will
@@ -58,7 +50,7 @@ If importing an .mpy file fails then try the following:
by executing::
import sys
sys_mpy = sys.implementation.mpy
sys_mpy = sys.implementation._mpy
arch = [None, 'x86', 'x64',
'armv6', 'armv6m', 'armv7m', 'armv7em', 'armv7emsp', 'armv7emdp',
'xtensa', 'xtensawin'][sys_mpy >> 10]
@@ -66,8 +58,6 @@ If importing an .mpy file fails then try the following:
print('mpy flags:', end='')
if arch:
print(' -march=' + arch, end='')
if not sys_mpy & 0x200:
print(' -mno-unicode', end='')
print()
* Check the validity of the .mpy file by inspecting the first two bytes of
@@ -90,7 +80,8 @@ and .mpy version.
=================== ============
MicroPython release .mpy version
=================== ============
v1.12 and up 5
v1.19 and up 6
v1.12 - v1.18 5
v1.11 4
v1.9.3 - v1.10 3
v1.9 - v1.9.2 2
@@ -103,6 +94,7 @@ MicroPython repository at which the .mpy version was changed.
=================== ========================================
.mpy version change Git commit
=================== ========================================
5 to 6 f2040bfc7ee033e48acef9f289790f3b4e6b74e5
4 to 5 5716c5cf65e9b2cb46c2906f40302401bdd27517
3 to 4 9a5f92ea72754c01cc03e5efcdfe94021120531e
2 to 3 ff93fd4f50321c6190e1659b19e64fef3045a484
@@ -114,21 +106,31 @@ initial version 0 d8c834c95d506db979ec871417de90b7951edc30
Binary encoding of .mpy files
-----------------------------
MicroPython .mpy files are a binary container format with code objects
stored internally in a nested hierarchy. To keep files small while still
MicroPython .mpy files are a binary container format with code objects (bytecode
and native machine code) stored internally in a nested hierarchy. The code for
the outer module is stored first, and then its children follow. Each child may
have further children, for example in the case of a class having methods, or a
function defining a lambda or comprehension. To keep files small while still
providing a large range of possible values it uses the concept of a
variably-encoded-unsigned-integer (vuint) in many places. Similar to utf-8
encoding, this encoding stores 7 bits per byte with the 8th bit (MSB) set
if one or more bytes follow. The bits of the unsigned integer are stored
in the vuint in LSB form.
The top-level of an .mpy file consists of two parts:
The top-level of an .mpy file consists of three parts:
* The header.
* The global qstr and constant tables.
* The raw-code for the outer scope of the module.
This outer scope is executed when the .mpy file is imported.
You can inspect the contents of a .mpy file by using ``mpy-tool.py``, for
example (run from the root of the main MicroPython repository)::
$ ./tools/mpy-tool.py -xd myfile.mpy
The header
~~~~~~~~~~
@@ -141,7 +143,26 @@ byte value 0x4d (ASCII 'M')
byte .mpy version number
byte feature flags
byte number of bits in a small int
vuint size of qstr window
====== ================================
The global qstr and constant tables
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
An .mpy file contains a single qstr table, and a single constant object table.
These are global to the .mpy file, they are referenced by all nested raw-code
objects. The qstr table maps internal qstr number (internal to the .mpy file)
to the resolved qstr number of the runtime that the .mpy file is imported into.
This links the .mpy file with the rest of the system that it executes within.
The constant object table is populated with references to all constant objects
that the .mpy file needs.
====== ================================
size field
====== ================================
vuint number of qstrs
vuint number of constant objects
... qstr data
... encoded constant objects
====== ================================
Raw code elements
@@ -153,24 +174,21 @@ contents are:
====== ================================
size field
====== ================================
vuint type and size
vuint type, size and whether there are sub-raw-code elements
... code (bytecode or machine code)
vuint number of constant objects
vuint number of sub-raw-code elements
... constant objects
vuint number of sub-raw-code elements (only if non-zero)
... sub-raw-code elements
====== ================================
The first vuint in a raw-code element encodes the type of code stored in this
element (the two least-significant bits), and the decompressed length of the code
(the amount of RAM to allocate for it).
element (the two least-significant bits), whether this raw-code has any
children (the third least-significant bit), and the length of the code that
follows (the amount of RAM to allocate for it).
Following the vuint comes the code itself. In the case of bytecode it also contains
compressed qstr values.
Following the vuint comes the code itself. Unless the code type is viper code
with relocations, this code is constant data and does not need to be modified.
Following the code comes a vuint counting the number of constant objects, and
another vuint counting the number of sub-raw-code elements.
The constant objects are then stored next.
If this raw-code has any children (as indicated by a bit in the first vuint),
following the code comes a vuint counting the number of sub-raw-code elements.
Finally any sub-raw-code elements are stored, recursively.

View File

@@ -0,0 +1,42 @@
.. _renesas-ra_general:
General information about Renesas RA port
=========================================
Overview
--------
The renesas-ra port supports boards powered by Renesas Electronics's
the flexible Renesas Advanced (RA) 32-bit microcontrollers (MCUs) family,
industry-leading 32-bit MCUs with the Arm® Cortex®-M33, -M23 and -M4
processor cores and PSA certification.
The ported hardware functionalities are Pin, SPI, I2C, UART and RTC at this present.
Other hardware functionalities such as Timer, PWM, USB, CAN and WDT are not implemented yet.
The following boards are officially supported.
* RA4M1-CLICKER
For the manual and other references for the board and RA Family MCU, please refer to the web page: `EK-RA4M1 CLICKER <https://www.mikroe.com/ra4m1-clicker>`_
* EK-RA6M2
For the manual and other references for the board and RA Family MCU, please refer to the web page: `EK-RA6M2 <https://www.renesas.com/products/microcontrollers-microprocessors/ra-cortex-m-mcus/ek-ra6m2-ra6m2-mcu-group-evaluation-board>`_
The following boards are unofficially supported.
* EK-RA4M1
For the manual and other references for the board and RA Family MCU, please refer to the web page: `EK-RA4M1 <https://www.renesas.com/products/microcontrollers-microprocessors/ra-cortex-m-mcus/ek-ra4m1-ra4m1-mcu-group-evaluation-board>`_
* EK-RA4W1
For the manual and other references for the board and RA Family MCU, please refer to the web page: `EK-RA4W1 <https://www.renesas.com/products/microcontrollers-microprocessors/ra-cortex-m-mcus/ek-ra4w1-ra4w1-mcu-group-evaluation-board>`_
* EK-RA6M1
For the manual and other references for the board and RA Family MCU, please refer to the web page: `EK-RA6M1 <https://www.renesas.com/products/microcontrollers-microprocessors/ra-cortex-m-mcus/ek-ra6m1-ra6m1-mcu-group-evaluation-board>`_
For more information, please visit the web page: `<https://github.com/renesas/micropython/wiki>`_

Binary file not shown.

After

Width:  |  Height:  |  Size: 177 KiB

View File

@@ -0,0 +1,415 @@
.. _renesas-ra_quickref:
Quick reference for the Renesas RA
==================================
.. image:: img/ek_ra6m2_board.jpg
:alt: Renesas Evaluation Kit for RA6M2 MCU Group
:width: 640px
The Renesas EK-RA6M2 board.
Below is a quick reference for the Renesas RA boards. If it is your first time
working with this board, it may be useful to get an overview of the microcontroller and the board:
.. toctree::
:maxdepth: 1
general.rst
tutorial/index.rst
Installing MicroPython
----------------------
See the corresponding section of tutorial: :ref:`renesas-ra_intro`. It also includes a troubleshooting subsection.
General board control
---------------------
The MicroPython REPL is accessed via the USB serial port. Tab-completion is useful to find out what methods an object has. Paste mode (ctrl-E) is useful to paste a large slab of Python code into the REPL. Some of features are not implemented for Renesas RA boards yet, please refer to the tutorial for more details.
The :mod:`machine` module::
import machine
machine.freq() # get the current frequency of the CPU
Following functions are supported::
machine.freq()
machine.reset()
machine.soft_reset()
machine.unique_id()
Following functions are not supported at the present::
machine.reset_cause()
machine.bootloader([value])
machine.disable_irq()
machine.enable_irq(state)
machine.freq([hz])
machine.idle()
machine.sleep()
machine.lightsleep()
machine.lightsleep([time_ms])
machine.deepsleep()
machine.deepsleep([time_ms])
machine.wake_reason()
machine.time_pulse_us(pin, pulse_level, timeout_us=1000000,/)
machine.bitstream(pin, encoding, timing, data, /)
machine.rng()
Delay and timing
----------------
Use the :mod:`time <time>` module::
import time
time.sleep(1) # sleep for 1 second
time.sleep_ms(500) # sleep for 500 milliseconds
time.sleep_us(10) # sleep for 10 microseconds
start = time.ticks_ms() # get value of millisecond counter
delta = time.ticks_diff(time.ticks_ms(), start) # compute time difference
Timers
------
The RA MCU's system timer peripheral provides a global microsecond timebase and generates interrupts for it. The software timer is available currently and there are unlimited number of them (memory permitting). There is no need to specify the timer id (id=-1 is supported at the moment) as it will default to this.
Use the :mod:`machine.Timer` class::
from machine import Timer
tim = Timer(-1)
tim.init(period=5000, mode=Timer.ONE_SHOT, callback=lambda t:print(1))
tim.init(period=2000, mode=Timer.PERIODIC, callback=lambda t: print(2))
Following functions are not supported at the present::
Timer(id) # hardware timer is not supported.
Pins and GPIO
-------------
Use the :ref:`machine.Pin <machine.Pin>` class::
from machine import Pin
p0 = Pin('P000', Pin.OUT) # create output pin on P000
p0.on() # set pin to "on" (high) level
p0.off() # set pin to "off" (low) level
p0.value(1) # set pin to on/high
p2 = Pin(Pin.cpu.P002, Pin.IN) # create input pin on P002
print(p2.value()) # get value, 0 or 1
p4 = Pin('P004', Pin.PULL_UP) # enable internal pull-up register
p5 = Pin('P005', Pin.OUT, value=1) # set pin high on creation
Pin id is available corresponding to the RA MCU's pin name which are Pin.cpu.P106 and 'P106'. The RA MCU has many feature's pins. However, there are some cases that pin feature is fixed or not connected by the board. Please confirm the board manual for the pin mapping.
UART (serial bus)
-----------------
The RA MCU has some hardware UARTs called SCI (Serial Communication Interface).
UART id is available corresponding to the RA MCU's SCI number which are UART(0) as SCI0 and UART(1) as SCI1.
See :ref:`machine.UART <machine.UART>`. ::
from machine import UART
uart1 = UART(1, 115200)
uart1.write('hello') # write 5 bytes
uart1.read(5) # read up to 5 bytes
Available UARTs and pins on the board are fixed and follows. One of these UARTs is used for REPL.
============= ============== ============== ==============
EK-RA4M1 UART0(REPL) UART1 UART2
============= ============== ============== ==============
tx P411 P401 P302
rx P410 P402 P301
============= ============== ============== ==============
============= ============== ============== ==============
EK-RA4W1 UART1 UART4(REPL) UART9
============= ============== ============== ==============
tx P213 P204 P109
rx P212 P206 P110
============= ============== ============== ==============
============= ============== ============== ==============
EK-RA6M1 UART0(REPL) UART2 UART8
============= ============== ============== ==============
tx P411 P302 P105
rx P410 P301 P104
============= ============== ============== ==============
============= ============== ============== ==============
EK-RA6M2 UART0(REPL) UART7 UART9
============= ============== ============== ==============
tx P411 P401 P602
rx P410 P402 P601
============= ============== ============== ==============
============= ============== ==============
RA4M1-CLICKER UART0 UART1(REPL)
============= ============== ==============
tx P411 P401
rx P410 P402
============= ============== ==============
Following functions are not supported at the present::
UART.init(baudrate) # now only 115200 is confirmed
UART.init(cts, rts) # Pins are fixed.
UART.init(invert)
UART.init(tx,rx) # Pins are fixed.
UART.init(txbuf)
UART.init(flow)
UART.irq(handler)
UART.irq(trigger=RX_ANY)
UART.irq(priority)
UART.irq(wake=machine.IDLE)
Real time clock (RTC)
---------------------
See :ref:`machine.RTC <machine.RTC>` ::
from machine import RTC
rtc = RTC()
rtc.datetime((2017, 8, 23, 1, 12, 48, 0, 0)) # set a specific date and time
# time, eg 2017/8/23 1:12:48
rtc.datetime() # get date and time
Following functions are not supported at the present::
RTC.init(datetime)
RTC.now()
RTC.deinit()
RTC.alarm()
RTC.alarm_left()
RTC.cancel()
RTC.irq()
ADC (analog to digital conversion)
----------------------------------
See :ref:`machine.ADC <machine.ADC>` ::
from machine import ADC
adc = ADC('P000') # create an ADC object acting on a pin
adc.read_u16() # read a raw analog value in the range 0-65535
Pin id is available corresponding to the RA MCU's pin name which are 'P000' as AN000 (analog channel 000). The RA MCU has many analog channels. However, there are some cases that pin feature is fixed or not available by the board. Please confirm the MCU and board manual for the pin mapping.
Following functions are not supported at the present::
ADC.init()
ADC(sample_ns)
ADC(atten)
ADC.read_uv()
ADC.block()
SPI bus
-------
The RA MCU has some hardware SPIs (Serial Peripheral Interface).
SPI id is available corresponding to the RA MCU's SPI number which are SPI(0) as SPI0 and SPI(1) as SPI1. If with no additional parameters, machine.SoftSPI() is called.
See :ref:`machine.SPI <machine.SPI>`. ::
from machine import SPI, Pin
spi = SPI(0, baudrate=500000)
cs = Pin.cpu.P103
cs(0)
spi.write(b"12345678")
cs(1)
Available SPIs and pins on the board are fixed and follows.
============= ====
EK-RA4M1 SPI0
============= ====
sck P102
mosi P101
miso P100
cs P206
============= ====
============= ====
EK-RA4W1 SPI0
============= ====
sck P102
mosi P101
miso P100
cs P103
============= ====
============= ====
EK-RA6M1 SPI0
============= ====
sck P102
mosi P101
miso P100
cs P103
============= ====
============= ==== ====
EK-RA6M2 SPI0 SPI1
============= ==== ====
sck P102 P702
mosi P101 P701
miso P100 P700
cs P103 P703
============= ==== ====
============= ====
RA4M1-CLICKER SPI0
============= ====
sck P102
mosi P101
miso P100
cs P103
============= ====
Following functions are not supported at the present::
SPI.init(firstbit) # now fixed with SPI.LSB
SPI.init(baudrate) # now confirmed only 500000
I2C bus
-------
The RA MCU has some hardware IIC (Inter-Integrated Circuit Bus).
I2C id is available corresponding to the RA MCU's I2C number which are I2C(0) as IIC0 and I2C(1) as IIC1. If with no additional parameters, machine.SoftI2C() is called.
See :ref:`machine.I2C <machine.I2C>` ::
from machine import I2C
i2c = I2C(0)
i2c.scan() # returns list of slave addresses
i2c.readfrom_mem(0x50, 0x10, 2, addrsize=16) # read 2 bytes from slave 0x50, slave memory 0x10
Available I2Cs and pins on the board are fixed and follows.
============= =============
EK-RA4M1 -
============= =============
scl not supported
sda not supported
============= =============
============= ====
EK-RA4W1 I2C0
============= ====
scl P204
sda P407
============= ====
============= ====
EK-RA6M1 I2C0
============= ====
scl P400
sda P401
============= ====
============= ====
EK-RA6M2 I2C2
============= ====
scl P512
sda P511
============= ====
============= ====
RA4M1-CLICKER I2C1
============= ====
scl P205
sda P206
============= ====
Following functions are not supported at the present::
I2C.init(freq) # now confirmed only 400000
I2C.deinit()
I2C.start()
I2C.stop()
PWM (pulse width modulation)
----------------------------
PWM is not supported.
WDT (Watchdog timer)
--------------------
WDT is not supported.
SDCard
------
The frozen sdcard driver (drivers/sdcard/sdcard.py) is available by connecting microSD card device to hardware SPI0 pins.::
from machine import Pin, SPI
import os, sdcard
spi = SPI(0, baudrate=500000)
cs = Pin.cpu.P103
sd = sdcard.SDCard(spi, cs)
os.mount(sd, '/sd')
os.listdir('/')
os.chdir('/sd')
os.umount('/sd')
OneWire driver
--------------
The OneWire driver is implemented in software and works on all pins::
from machine import Pin
import onewire
ow = onewire.OneWire(Pin(P012)) # create a OneWire bus on P012
ow.scan() # return a list of devices on the bus
ow.reset() # reset the bus
ow.readbyte() # read a byte
ow.writebyte(0x12) # write a byte on the bus
ow.write('123') # write bytes on the bus
ow.select_rom(b'12345678') # select a specific device by its ROM code
There is a specific driver for DS18S20 and DS18B20 devices::
import time, ds18x20
ds = ds18x20.DS18X20(ow)
roms = ds.scan()
ds.convert_temp()
time.sleep_ms(750)
for rom in roms:
print(ds.read_temp(rom))
Be sure to put a 4.7k pull-up resistor on the data line. Note that
the ``convert_temp()`` method must be called each time you want to
sample the temperature.
NeoPixel and APA106 driver
--------------------------
NeoPixel is not supported currently.

View File

@@ -0,0 +1,16 @@
.. _renesas-ra_tutorial:
MicroPython tutorial for Renesas RA port
========================================
This tutorial is intended to get you started using MicroPython on the Renesas RA port.
.. toctree::
:maxdepth: 1
:numbered:
intro.rst
using_peripheral.rst
program_in_flash.rst
reset.rst
troubleshooting.rst

View File

@@ -0,0 +1,67 @@
.. _renesas-ra_intro:
Getting started with MicroPython on the Renesas RA
==================================================
This tutorial will guide you through setting up MicroPython,
getting a prompt, using the hardware peripherals, using internal
flash file system, reset and boot modes, and Factory reset the
internal file system.
Requirements
------------
You need a board. For the information of available boards,
please refer to the general information about Renesas RA port: :ref:`renesas-ra_general`.
You need a USB-Serial conversion cable to connect the board and your PC.
Please get a type with separate signal pins so that you can connect to
the UART TX and RX pins on the board.
Flashing the MicroPython image with J-Link OB
---------------------------------------------
The board has a builtin programmer interface called J-Link OB.
Using the J-Link Software, you can flash the binary image "firmware.hex"
of MicroPython on the board via J-Link OB.
You can download the J-Link Software and Documentation pack from https://www.segger.com/downloads/jlink/.
After installing J-Link Software, start J-Flash-Lite program. Then specify following device in Device select menu in J-Flash-Lite.
=============== ================
Board Device
--------------- ----------------
EK-RA4M1 R7FA4M1AB
EK-RA4W1 R7FA4W1AD2CNG
EK-RA6M1 R7FA6M1AD
EK-RA6M2 R7FA6M2AF
RA4M1 CLICKER R7FA4M1AB
=============== ================
Select a firmware hex file in Data File of J-Link-Lite, and push Program Device button to flash the firmware.
Getting a prompt of MicroPython
-------------------------------
Cross connect USB-Serial conversion cable RX/TX/GND pins to TX/RX/GND pins on the board.
=============== =============== ===============
Board USB Serial RX USB Serial TX
--------------- --------------- ---------------
EK-RA4M1 P411 P410
EK-RA4W1 P205 P206
EK-RA6M1 P411 P410
EK-RA6M2 P411 P410
RA4M1 CLICKER P401 P402
=============== =============== ===============
Access the MicroPython REPL (the Python prompt) via USB serial or UART with 115200 baud rate, 1 stop bit and no parity bit using your favorite terminal software, picocom on Linux or Tera Term on Windows. You can try on Linux::
$ picocom /dev/ttyACM0
You can see the MicroPython REPL prompt like below::
MicroPython v1.18-293-g339aa09b8-dirty on 2022-03-26; RA6M2_EK with RA6M2
Type "help()" for more information.
>>>

View File

@@ -0,0 +1,62 @@
.. _renesas-ra_program_in_flash:
Write a program in internal file system
=======================================
Internal file system
--------------------
The FAT file system is created and initialized in the RA MCU's internal
flash when the MicroPython starts at the first time on the board.
The file system is mounted as "/flash", so you can access this flash system
and create a program file into the /flash directory.
As the factory setting, following size is allocated for the file system:
=============== ===================
Board File System Size
--------------- -------------------
EK-RA4M1 36KB ( 36864B)
EK-RA4W1 64KB ( 65536B)
EK-RA6M1 128KB (131072B)
EK-RA6M2 256KB (262144B)
RA4M1 CLICKER 36KB ( 36864B)
=============== ===================
As the factory setting, following 2 files are created in the file system:
* boot.py : executed first when the system starts
* main.py : executed after boot.py completes
Write a program in the internal file system
-------------------------------------------
You can write a program in main.py which is executed automatically
when the MicroPython starts. For example, you can write LED blinking
program like below::
import os
os.getcwd()
f = open('main.py', 'rw+')
print(f.read())
f.write('import time\n')
f.write('from machine import Pin\n')
f.write('led1 = Pin(Pin.cpu.P106)\n')
f.write('while True:\n')
f.write(' led1.on()\n')
f.write(' time.sleep(1)\n')
f.write(' led1.off()\n')
f.write(' time.sleep(1)\n')
f.close()
f = open('main.py', 'r')
print(f.read())
f.close()
Entering CTRL-D for software reset, the MicroPython reboots, displays
following messages::
MPY: sync filesystems
MPY: soft reboot
and main.py is executed and LED1 blinks per 1 second.
If you want to stop the program, please enter CTRL-C.

View File

@@ -0,0 +1,61 @@
.. _renesas-ra_reset:
Reset and boot mode
===================
Resetting the board
-------------------
If something goes wrong, you can reset the board in two ways. The first is
to press CTRL-D at the MicroPython prompt, which performs a soft reset.
You will see a message something like ::
MPY: sync filesystems
MPY: soft reboot
MicroPython v1.18-293-g339aa09b8-dirty on 2022-03-26; RA6M2_EK with RA6M2
Type "help()" for more information.
>>>
If that isn't working you can perform a hard reset (turn-it-off-and-on-again)
by pressing the RESET button. This will end your session, disconnecting
whatever program (PuTTY, screen, etc) that you used to connect to the board.
boot mode
---------
There are 3 boot modes:
* normal boot mode
* safe boot mode
* factory filesystem boot mode
boot.py and main.py are executed on "normal boot mode".
boot.py and main.py are *NOT* executed on "safe boot mode".
The file system of internal flash is initialized and *all files are erased* on "factory filesystem boot mode".
For changing boot mode, please push the RESET button with pressing USER SW1
on the board:
* For normal boot mode, release the USER SW1 after LED1 flashes 4 times or more
* For safe boot mode, release the USER SW1 after LED1 flashes 2 times
* For factory file system boot mode, release the USER SW1 after LED1 flashes 3 times.
You have created the main.py which executes LED1 blinking in the previous part.
If you change the boot mode to safe boot mode, the MicroPython starts without
the execution of main.py. Then you can remove the main.py by following
command or change the boot mode to factory file system boot mode.::
import os
os.remove('main.py')
or change the boot mode to factory file system boot mode.
You can confirm that the initialized file system that there are only boot.py and main.py files.::
import os
os.listdir()

View File

@@ -0,0 +1,18 @@
.. _renesas-ra_troubleshooting:
Trouble Shooting
===================
Flash file system
-------------------
* MicroPython REPL prompt is not displayed.
- Re-program the MicroPython image file.
- Confirm serial port connection.
The connection must be crossed that the board TXD pin is connected with
USB-serial conversion's RXD signal pin.
- If the prompt is not displayed suddenly, try to do factory file
system boot mode as the final method. Please note that all files are removed forever.

View File

@@ -0,0 +1,68 @@
.. _renesas-ra_using_peripheral:
Using peripherals
=================
For quick help information, please enter::
help()
You can access RA MCU's peripherals using MicroPython modules.
To list supported modules, please enter::
help('modules')
Especially `machine` module and class :ref:`machine.Pin <machine.Pin>` are very important for using
peripherals. Note that prefix 'u' is added to the module for MicroPython,
so you can see "umachine" in the list but you can use it like "import machine".
Using "from machine import Pin", Pin name is available corresponding to
the RA MCU's pin name which are Pin.cpu.P000 and 'P000'.
In addition, you can use 'LED1', 'LED2', 'SW1', and 'SW2' name if the board
has these LEDs and switches.
LED blinking
------------
As simple example, you can enter following program to blink LED1.
Please enter key 4 times after the input of last time.sleep(1). ::
import time
from machine import Pin
led1 = Pin('LED1')
print(led1)
while True:
led1.on()
time.sleep(1)
led1.off()
time.sleep(1)
You can see the LED1 blinking per 1 second.
If you want to stop the program, please enter CTRL-C. ::
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
KeyboardInterrupt:
This message is displayed, and the program stops.
The message means the program was interrupted at line 5 "while" statement.
Using print(led1), you can confirm that LED1 is assigned to Pin.cpu.P106
on the board.::
Pin(Pin.cpu.P106, mode=Pin.OUT, pull=Pin.PULL_NONE, drive=Pin.LOW_POWER)
So you can get the same result if Pin(Pin.cpu.P106) is specified
instead of Pin('LED1'). ::
import time
from machine import Pin
led1 = Pin(Pin.cpu.P106)
print(led1)
while True:
led1.on()
time.sleep(1)
led1.off()
time.sleep(1)

View File

@@ -11,7 +11,7 @@ Technical specifications and SoC datasheets
-------------------------------------------
For detailed technical specifications, please refer to the `datasheets
<https://datasheets.raspberrypi.org/rp2040/rp2040-datasheet.pdf>`_
<https://datasheets.raspberrypi.com/rp2040/rp2040-datasheet.pdf>`_
The RP2040 microcontroller is manufactured on a 40 nm silicon process in a 7x7mm
QFN-56 SMD package. The key features include:

View File

@@ -62,6 +62,10 @@
<a class="biglink" href="{{ pathto("rp2/quickref") }}">Quick reference for the Raspberry Pi RP2xxx</a><br/>
<span class="linkdescr">pinout for rp2xxx-based boards, snippets of useful code, and a tutorial</span>
</p>
<p class="biglink">
<a class="biglink" href="{{ pathto("mimxrt/quickref") }}">Quick reference for the NXP i.MXRT 10xx</a><br/>
<span class="linkdescr">general introduction, snippets of useful code, and a tutorial</span>
</p>
<p class="biglink">
<a class="biglink" href="{{ pathto("wipy/quickref") }}">Quick reference for the WiPy/CC3200</a><br/>
<span class="linkdescr">pinout for the WiPy/CC3200, snippets of useful code, and a tutorial</span>
@@ -74,6 +78,10 @@
<a class="biglink" href="{{ pathto("zephyr/quickref") }}">Quick reference for the Zephyr port</a><br/>
<span class="linkdescr">snippets of useful code and a tutorial</span>
</p>
<p class="biglink">
<a class="biglink" href="{{ pathto("renesas-ra/quickref") }}">Quick reference for the Renesas RA</a><br/>
<span class="linkdescr">general information for Renesas RA based boards, snippets of useful code, and a tutorial</span>
</p>
</td>
</tr></table>

View File

@@ -73,6 +73,8 @@ General options:
- ``-X heapsize=<n>[w][K|M]`` sets the heap size for the garbage collector.
The suffix ``w`` means words instead of bytes. ``K`` means x1024 and ``M``
means x1024x1024.
- ``-X realtime`` sets thread priority to realtime. This can be used to
improve timer precision. Only available on macOS.

View File

@@ -345,7 +345,7 @@ Example::
Create a server instance, see ``init`` for parameters of initialization.
.. method:: server.init(\*, login=('micro', 'python'), timeout=300)
.. method:: server.init(*, login=('micro', 'python'), timeout=300)
Init (and effectively start the server). Optionally a new ``user``, ``password``
and ``timeout`` (in seconds) can be passed.
@@ -368,7 +368,7 @@ Adhoc VFS-like support
WiPy doesn't implement full MicroPython VFS support, instead following
functions are defined in ``os`` module:
.. function:: mount(block_device, mount_point, \*, readonly=False)
.. function:: mount(block_device, mount_point, *, readonly=False)
Mounts a block device (like an ``SD`` object) in the specified mount
point. Example::

View File

@@ -31,8 +31,8 @@ With your serial program open (PuTTY, screen, picocom, etc) you may see a
blank screen with a flashing cursor. Press Enter (or reset the board) and
you should be presented with the following text::
*** Booting Zephyr OS build zephyr-v2.7.0 ***
MicroPython v1.17-288-gb695f5a70-dirty on 2022-01-03; zephyr-frdm_k64f with mk64f12
*** Booting Zephyr OS build zephyr-v3.0.0 ***
MicroPython v1.18-169-g665f0e2a6-dirty on 2022-03-02; zephyr-frdm_k64f with mk64f12
Type "help()" for more information.
>>>

View File

@@ -28,7 +28,9 @@
#include "py/mphal.h"
#define MP_SPI_ADDR_IS_32B(addr) (addr & 0xff000000)
#ifndef MICROPY_HW_SPI_ADDR_IS_32BIT
#define MICROPY_HW_SPI_ADDR_IS_32BIT(addr) (addr & 0xff000000)
#endif
enum {
MP_QSPI_IOCTL_INIT,
@@ -57,7 +59,7 @@ typedef struct _mp_soft_qspi_obj_t {
extern const mp_qspi_proto_t mp_soft_qspi_proto;
static inline uint8_t mp_spi_set_addr_buff(uint8_t *buf, uint32_t addr) {
if (MP_SPI_ADDR_IS_32B(addr)) {
if (MICROPY_HW_SPI_ADDR_IS_32BIT(addr)) {
buf[0] = addr >> 24;
buf[1] = addr >> 16;
buf[2] = addr >> 8;

753
drivers/codec/wm8960.py Normal file
View File

@@ -0,0 +1,753 @@
#
# Driver class for the WM8960 Codec to be used e.g. with MIMXRT_1xxx Boards.
# Derived from the NXP SDK drivers.
#
# Copyright (c) 2015, Freescale Semiconductor, Inc., (C-Code)
# Copyright 2016-2021 NXP, (C-Code)
# All rights reserved.
#
# Translated to MicroPython by Robert Hammelrath, 2022
#
# SPDX-License-Identifier: BSD-3-Clause
#
import array
from micropython import const
# Define the register addresses of WM8960.
_LINVOL = const(0x0)
_RINVOL = const(0x1)
_LOUT1 = const(0x2)
_ROUT1 = const(0x3)
_CLOCK1 = const(0x4)
_DACCTL1 = const(0x5)
_DACCTL2 = const(0x6)
_IFACE1 = const(0x7)
_CLOCK2 = const(0x8)
_IFACE2 = const(0x9)
_LDAC = const(0xA)
_RDAC = const(0xB)
_RESET = const(0xF)
_3D = const(0x10)
_ALC1 = const(0x11)
_ALC2 = const(0x12)
_ALC3 = const(0x13)
_NOISEG = const(0x14)
_LADC = const(0x15)
_RADC = const(0x16)
_ADDCTL1 = const(0x17)
# Register _ADDCTL2 = const(0x18)
_POWER1 = const(0x19)
_POWER2 = const(0x1A)
_ADDCTL3 = const(0x1B)
# Register _APOP1 = const(0x1C)
# Register _APOP2 = const(0x1D)
_LINPATH = const(0x20)
_RINPATH = const(0x21)
_LOUTMIX = const(0x22)
_ROUTMIX = const(0x25)
_MONOMIX1 = const(0x26)
_MONOMIX2 = const(0x27)
_LOUT2 = const(0x28)
_ROUT2 = const(0x29)
_MONO = const(0x2A)
_INBMIX1 = const(0x2B)
_INBMIX2 = const(0x2C)
_BYPASS1 = const(0x2D)
_BYPASS2 = const(0x2E)
_POWER3 = const(0x2F)
_ADDCTL4 = const(0x30)
_CLASSD1 = const(0x31)
# Register _CLASSD3 = const(0x33)
_PLL1 = const(0x34)
_PLL2 = const(0x35)
_PLL3 = const(0x36)
_PLL4 = const(0x37)
# WM8960 PLLN range */
_PLL_N_MIN_VALUE = const(6)
_PLL_N_MAX_VALUE = const(12)
# WM8960 CLOCK2 bits
_CLOCK2_BCLK_DIV_MASK = const(0x0F)
_CLOCK2_DCLK_DIV_MASK = const(0x1C0)
_CLOCK2_DCLK_DIV_SHIFT = const(0x06)
# Register _IFACE1
_IFACE1_FORMAT_MASK = const(0x03)
_IFACE1_WL_MASK = const(0x0C)
_IFACE1_WL_SHIFT = const(0x02)
_IFACE1_LRP_MASK = const(0x10)
_IFACE1_MS_MASK = const(0x40)
_IFACE1_DLRSWAP_MASK = const(0x20)
_IFACE1_ALRSWAP_MASK = const(0x100)
# Register _POWER1
_POWER1_VREF_MASK = const(0x40)
_POWER1_VREF_SHIFT = const(0x06)
_POWER1_AINL_MASK = const(0x20)
_POWER1_AINR_MASK = const(0x10)
_POWER1_ADCL_MASK = const(0x08)
_POWER1_ADCR_MASK = const(0x0)
_POWER1_MICB_MASK = const(0x02)
_POWER1_MICB_SHIFT = const(0x01)
# Register _POWER2
_POWER2_DACL_MASK = const(0x100)
_POWER2_DACR_MASK = const(0x80)
_POWER2_LOUT1_MASK = const(0x40)
_POWER2_ROUT1_MASK = const(0x20)
_POWER2_SPKL_MASK = const(0x10)
_POWER2_SPKR_MASK = const(0x08)
_POWER3_LMIC_MASK = const(0x20)
_POWER3_RMIC_MASK = const(0x10)
_POWER3_LOMIX_MASK = const(0x08)
_POWER3_ROMIX_MASK = const(0x04)
# Register _DACCTL1 .. 3
_DACCTL1_MONOMIX_MASK = const(0x10)
_DACCTL1_MONOMIX_SHIFT = const(0x4)
_DACCTL1_DACMU_MASK = const(0x08)
_DACCTL1_DEEM_MASK = const(0x06)
_DACCTL1_DEEM_SHIFT = const(0x01)
_DACCTL2_DACSMM_MASK = const(0x08)
_DACCTL2_DACMR_MASK = const(0x04)
_DACCTL3_ALCSR_MASK = const(0x07)
# _WM8060_ALC1 .. 3
_ALC_CHANNEL_MASK = const(0x180)
_ALC_CHANNEL_SHIFT = const(0x7)
_ALC_MODE_MASK = const(0x100)
_ALC_MODE_SHIFT = const(0x8)
_ALC_GAIN_MASK = const(0x70)
_ALC_GAIN_SHIFT = const(0x4)
_ALC_TARGET_MASK = const(0x0F)
_ALC_ATTACK_MASK = const(0x0F)
_ALC_DECAY_MASK = const(0xF0)
_ALC_DECAY_SHIFT = const(4)
_ALC_HOLD_MASK = const(0xF)
# Register _NOISEG
_NOISEG_LEVEL_SHIFT = const(3)
_I2C_ADDR = const(0x1A)
# WM8960 maximum volume values
_MAX_VOLUME_ADC = const(0xFF)
_MAX_VOLUME_DAC = const(0xFF)
_MAX_VOLUME_HEADPHONE = const(0x7F)
_MAX_VOLUME_LINEIN = const(0x3F)
_MAX_VOLUME_SPEAKER = const(0x7F)
# Config symbol names
# Modules
MODULE_ADC = const(0) # ADC module in WM8960
MODULE_DAC = const(1) # DAC module in WM8960
MODULE_VREF = const(2) # VREF module
MODULE_HEADPHONE = const(3) # Headphone
MODULE_MIC_BIAS = const(4) # Mic bias
MODULE_MIC = const(5) # Input Mic
MODULE_LINE_IN = const(6) # Analog in PGA
MODULE_LINE_OUT = const(7) # Line out module
MODULE_SPEAKER = const(8) # Speaker module
MODULE_OMIX = const(9) # Output mixer
MODULE_MONO_OUT = const(10) # Mono mix
# Route
ROUTE_BYPASS = const(0) # LINEIN->Headphone.
ROUTE_PLAYBACK = const(1) # I2SIN->DAC->Headphone.
ROUTE_PLAYBACK_RECORD = const(2) # I2SIN->DAC->Headphone, LINEIN->ADC->I2SOUT.
ROUTE_RECORD = const(5) # LINEIN->ADC->I2SOUT.
# Input
INPUT_CLOSED = const(0) # Input device is closed
INPUT_MIC1 = const(1) # Input as single ended mic, only use L/RINPUT1
INPUT_MIC2 = const(2) # Input as diff. mic, use L/RINPUT1 and L/RINPUT2
INPUT_MIC3 = const(3) # Input as diff. mic, use L/RINPUT1 and L/RINPUT3
INPUT_LINE2 = const(4) # Input as line input, only use L/RINPUT2
INPUT_LINE3 = const(5) # Input as line input, only use L/RINPUT3
# ADC sync input
SYNC_ADC = const(0) # Use ADCLRC pin for ADC sync
SYNC_DAC = const(1) # used DACLRC pin for ADC sync
# Protocol type
BUS_I2S = const(2) # I2S type
BUS_LEFT_JUSTIFIED = const(1) # Left justified mode
BUS_RIGHT_JUSTIFIED = const(0) # Right justified mode
BUS_PCMA = const(3) # PCM A mode
BUS_PCMB = const(3 | (1 << 4)) # PCM B mode
# Channel swap
SWAP_NONE = const(0)
SWAP_INPUT = const(1)
SWAP_OUTPUT = const(2)
# Mute settings
MUTE_FAST = const(0)
MUTE_SLOW = const(1)
# ALC settings
ALC_OFF = const(0)
ALC_RIGHT = const(1)
ALC_LEFT = const(2)
ALC_STEREO = const(3)
ALC_MODE = const(0) # ALC mode
ALC_LIMITER = const(1) # Limiter mode
# Clock Source
SYSCLK_MCLK = const(0) # sysclk source from external MCLK
SYSCLK_PLL = const(1) # sysclk source from internal PLL
class Regs:
# register cache of 56 register. Since registers cannot be read back, they are
# kept in the table for modification
# fmt: off
cache = array.array("H", (
0x0097, 0x0097, 0x0000, 0x0000, 0x0000, 0x0008, 0x0000,
0x000a, 0x01c0, 0x0000, 0x00ff, 0x00ff, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x007b, 0x0100, 0x0032, 0x0000,
0x00c3, 0x00c3, 0x01c0, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0100, 0x0100, 0x0050,
0x0050, 0x0050, 0x0050, 0x0000, 0x0000, 0x0000, 0x0000,
0x0040, 0x0000, 0x0000, 0x0050, 0x0050, 0x0000, 0x0002,
0x0037, 0x004d, 0x0080, 0x0008, 0x0031, 0x0026, 0x00e9
))
# fmt: on
def __init__(self, i2c, i2c_address=_I2C_ADDR):
self.value_buffer = bytearray(2)
self.i2c = i2c
self.i2c_address = i2c_address
def __getitem__(self, reg):
return self.cache[reg]
def __setitem__(self, reg, value):
if type(reg) is tuple:
if type(value) is tuple:
self[reg[0]] = value[0]
self[reg[1]] = value[1]
else:
self[reg[0]] = value
self[reg[1]] = value
else:
if type(value) is tuple:
val = (self.cache[reg] & (~value[0] & 0xFFFF)) | value[1]
else:
val = value
self.cache[reg] = val
self.value_buffer[0] = (reg << 1) | ((val >> 8) & 0x01)
self.value_buffer[1] = val & 0xFF
self.i2c.writeto(self.i2c_address, self.value_buffer)
class WM8960:
_bit_clock_divider_table = {
2: 0,
3: 1,
4: 2,
6: 3,
8: 4,
11: 5,
12: 6,
16: 7,
22: 8,
24: 9,
32: 10,
44: 11,
48: 12,
}
_dac_divider_table = {
1.0 * 256: 0b000,
1.5 * 256: 0b001,
2 * 256: 0b010,
3 * 256: 0b011,
4 * 256: 0b100,
5.5 * 256: 0b101,
6 * 256: 0b110,
}
_audio_word_length_table = {
16: 0b00,
20: 0b01,
24: 0b10,
32: 0b11,
}
_alc_sample_rate_table = {
48000: 0,
44100: 0,
32000: 1,
24000: 2,
22050: 2,
16000: 3,
12000: 4,
11025: 4,
8000: 5,
}
_volume_config_table = {
MODULE_ADC: (_MAX_VOLUME_ADC, _LADC, 0x100),
MODULE_DAC: (_MAX_VOLUME_DAC, _LDAC, 0x100),
MODULE_HEADPHONE: (_MAX_VOLUME_HEADPHONE, _LOUT1, 0x180),
MODULE_LINE_IN: (_MAX_VOLUME_LINEIN, _LINVOL, 0x140),
MODULE_SPEAKER: (_MAX_VOLUME_SPEAKER, _LOUT2, 0x180),
}
_input_config_table = {
INPUT_CLOSED: None,
INPUT_MIC1: (0x138, 0x117),
INPUT_MIC2: (0x178, 0x117),
INPUT_MIC3: (0x1B8, 0x117),
INPUT_LINE2: (0, 0xE),
INPUT_LINE3: (0, 0x70),
}
def __init__(
self,
i2c,
sample_rate=16000,
bits=16,
swap=SWAP_NONE,
route=ROUTE_PLAYBACK_RECORD,
left_input=INPUT_MIC3,
right_input=INPUT_MIC2,
sysclk_source=SYSCLK_MCLK,
mclk_freq=None,
primary=False,
adc_sync=SYNC_DAC,
protocol=BUS_I2S,
i2c_address=_I2C_ADDR,
):
self.regs = regs = Regs(i2c, i2c_address)
self.sample_rate = sample_rate
# check parameter consistency and set the sysclk value
if sysclk_source == SYSCLK_PLL:
if sample_rate in (11025, 22050, 44100):
sysclk = 11289600
else:
sysclk = 12288000
if sysclk < sample_rate * 256:
sysclk = sample_rate * 256
if mclk_freq is None:
mclk_freq = sysclk
else: # sysclk_source == SYSCLK_MCLK
if mclk_freq is None:
mclk_freq = sample_rate * 256
sysclk = mclk_freq
regs[_RESET] = 0x00
# VMID=50K, Enable VREF, AINL, AINR, ADCL and ADCR
# I2S_IN (bit 0), I2S_OUT (bit 1), DAP (bit 4), DAC (bit 5), ADC (bit 6) are powered on
regs[_POWER1] = 0xFE
# Enable DACL, DACR, LOUT1, ROUT1, PLL down, SPKL, SPKR
regs[_POWER2] = 0x1F8
# Enable left and right channel input PGA, left and right output mixer
regs[_POWER3] = 0x3C
if adc_sync == SYNC_ADC:
# ADC and DAC use different Frame Clock Pins
regs[_IFACE2] = 0x00 # ADCLRC 0x00:Input 0x40:output.
else:
# ADC and DAC use the same Frame Clock Pin
regs[_IFACE2] = 0x40 # ADCLRC 0x00:Input 0x40:output.
self.set_data_route(route)
self.set_protocol(protocol)
if sysclk_source == SYSCLK_PLL:
self.set_internal_pll_config(mclk_freq, sysclk)
if primary:
self.set_master_clock(sysclk, sample_rate, bits)
# set master bit.
self.regs[_IFACE1] = (0, _IFACE1_MS_MASK)
self.set_speaker_clock(sysclk)
# swap channels
if swap & SWAP_INPUT:
regs[_IFACE1] = (0, _IFACE1_ALRSWAP_MASK)
if swap & SWAP_OUTPUT:
regs[_IFACE1] = (0, _IFACE1_DLRSWAP_MASK)
self.set_left_input(left_input)
self.set_right_input(right_input)
regs[_ADDCTL1] = 0x0C0
regs[_ADDCTL4] = 0x60 # Set GPIO1 to 0.
regs[_BYPASS1] = regs[_BYPASS2] = 0x0
# ADC volume, 0dB
regs[_LADC, _RADC] = 0x1C3
# Digital DAC volume, 0dB
regs[_LDAC, _RDAC] = 0x1FF
# Headphone volume, LOUT1 and ROUT1, 0dB
regs[_LOUT1, _ROUT1] = 0x16F
# speaker volume 6dB
regs[_LOUT2, _ROUT2] = 0x1FF
# enable class D output
regs[_CLASSD1] = 0xF7
# Unmute DAC.
regs[_DACCTL1] = 0x0000
# Input PGA volume 0 dB
regs[_LINVOL, _RINVOL] = 0x117
self.config_data_format(sysclk, sample_rate, bits)
def deinit(self):
self.set_module(MODULE_ADC, False)
self.set_module(MODULE_DAC, False)
self.set_module(MODULE_VREF, False)
self.set_module(MODULE_LINE_IN, False)
self.set_module(MODULE_LINE_OUT, False)
self.set_module(MODULE_SPEAKER, False)
def set_internal_pll_config(self, input_mclk, output_clk):
regs = self.regs
pllF2 = output_clk * 4
pll_prescale = 0
sysclk_div = 1
frac_mode = 0
# disable PLL power
regs[_POWER2] = (1, 0)
regs[_CLOCK1] = (7, 0)
pllN = pllF2 // input_mclk
if pllN < _PLL_N_MIN_VALUE:
input_mclk //= 2
pll_prescale = 1
pllN = pllF2 // input_mclk
if pllN < _PLL_N_MIN_VALUE:
sysclk_div = 2
pllF2 *= 2
pllN = pllF2 // input_mclk
if (pllN < _PLL_N_MIN_VALUE) or (pllN > _PLL_N_MAX_VALUE):
raise ValueError("Invalid MCLK vs. sysclk ratio")
pllK = ((pllF2 % input_mclk) * (1 << 24)) // input_mclk
if pllK != 0:
frac_mode = 1
regs[_PLL1] = (frac_mode << 5) | (pll_prescale << 4) | (pllN & 0x0F)
regs[_PLL2] = (pllK >> 16) & 0xFF
regs[_PLL3] = (pllK >> 8) & 0xFF
regs[_PLL4] = pllK & 0xFF
# enable PLL power
regs[_POWER2] = (1, 1)
regs[_CLOCK1] = (7, ((0 if sysclk_div == 1 else sysclk_div) << 1) | 1)
def set_master_clock(self, sysclk, sample_rate, bit_width):
bit_clock_divider = (sysclk * 2) // (sample_rate * bit_width * 2)
try:
reg_divider = self._bit_clock_divider_table[bit_clock_divider]
except:
raise ValueError("Invalid ratio of sysclk sample rate and bits")
# configure the master bit clock divider
self.regs[_CLOCK2] = (_CLOCK2_BCLK_DIV_MASK, reg_divider)
def set_speaker_clock(self, sysclk):
speaker_divider_table = (1.5, 2, 3, 4, 6, 8, 12, 16)
for val in range(8):
divider = speaker_divider_table[val]
f = sysclk / divider
if 500_000 < f < 1_000_000:
break
else:
val = 7
self.regs[_CLOCK2] = (
_CLOCK2_DCLK_DIV_MASK,
val << _CLOCK2_DCLK_DIV_SHIFT,
)
def set_module(self, module, is_enabled):
is_enabled = 1 if is_enabled else 0
regs = self.regs
if module == MODULE_ADC:
regs[_POWER1] = (
_POWER1_ADCL_MASK | _POWER1_ADCR_MASK,
(_POWER1_ADCL_MASK | _POWER1_ADCR_MASK) * is_enabled,
)
elif module == MODULE_DAC:
regs[_POWER2] = (
_POWER2_DACL_MASK | _POWER2_DACR_MASK,
(_POWER2_DACL_MASK | _POWER2_DACR_MASK) * is_enabled,
)
elif module == MODULE_VREF:
regs[_POWER1] = (
_POWER1_VREF_MASK,
(is_enabled << _POWER1_VREF_SHIFT),
)
elif module == MODULE_LINE_IN:
regs[_POWER1] = (
_POWER1_AINL_MASK | _POWER1_AINR_MASK,
(_POWER1_AINL_MASK | _POWER1_AINR_MASK) * is_enabled,
)
regs[_POWER3] = (
_POWER3_LMIC_MASK | _POWER3_RMIC_MASK,
(_POWER3_LMIC_MASK | _POWER3_RMIC_MASK) * is_enabled,
)
elif module == MODULE_LINE_OUT:
regs[_POWER2] = (
_POWER2_LOUT1_MASK | _POWER2_ROUT1_MASK,
(_POWER2_LOUT1_MASK | _POWER2_ROUT1_MASK) * is_enabled,
)
elif module == MODULE_MIC_BIAS:
regs[_POWER1] = (
_POWER1_MICB_MASK,
(is_enabled << _POWER1_MICB_SHIFT),
)
elif module == MODULE_SPEAKER:
regs[_POWER2] = (
_POWER2_SPKL_MASK | _POWER2_SPKR_MASK,
(_POWER2_SPKL_MASK | _POWER2_SPKR_MASK) * is_enabled,
)
regs[_CLASSD1] = 0xF7
elif module == MODULE_OMIX:
regs[_POWER3] = (
_POWER3_LOMIX_MASK | _POWER3_ROMIX_MASK,
(_POWER3_LOMIX_MASK | _POWER3_ROMIX_MASK) * is_enabled,
)
elif module == MODULE_MONO_OUT:
regs[_MONOMIX1] = regs[_MONOMIX2] = is_enabled << 7
regs[_MONO] = is_enabled << 6
else:
raise ValueError("Invalid module")
def enable_module(self, module):
self.set_module(module, True)
def disable_module(self, module):
self.set_module(module, False)
def set_data_route(self, route):
regs = self.regs
if route == ROUTE_BYPASS:
# Bypass means from line-in to HP
# Left LINPUT3 to left output mixer, LINPUT3 left output mixer volume = 0dB
# Right RINPUT3 to right output mixer, RINPUT3 right output mixer volume = 0dB
regs[_LOUTMIX, _ROUTMIX] = 0x80
elif route == ROUTE_PLAYBACK:
# Data route I2S_IN-> DAC-> HP
#
# Left DAC to left output mixer, LINPUT3 left output mixer volume = 0dB
# Right DAC to right output mixer, RINPUT3 right output mixer volume = 0dB
regs[_LOUTMIX, _ROUTMIX] = 0x100
regs[_POWER3] = 0x0C
# Set power for DAC
self.set_module(MODULE_DAC, True)
self.set_module(MODULE_OMIX, True)
self.set_module(MODULE_LINE_OUT, True)
elif route == ROUTE_PLAYBACK_RECORD:
#
# Left DAC to left output mixer, LINPUT3 left output mixer volume = 0dB
# Right DAC to right output mixer, RINPUT3 right output mixer volume = 0dB
regs[_LOUTMIX, _ROUTMIX] = 0x100
regs[_POWER3] = 0x3C
self.set_module(MODULE_DAC, True)
self.set_module(MODULE_ADC, True)
self.set_module(MODULE_LINE_IN, True)
self.set_module(MODULE_OMIX, True)
self.set_module(MODULE_LINE_OUT, True)
elif route == ROUTE_RECORD:
# LINE_IN->ADC->I2S_OUT
# Left and right input boost, LIN3BOOST and RIN3BOOST = 0dB
regs[_POWER3] = 0x30
# Power up ADC and AIN
self.set_module(MODULE_LINE_IN, True)
self.set_module(MODULE_ADC, True)
else:
raise ValueError("Invalid route")
def set_left_input(self, input):
if not input in self._input_config_table.keys():
raise ValueError("Invalid input")
input = self._input_config_table[input]
regs = self.regs
if input is None:
regs[_POWER1] = (_POWER1_AINL_MASK | _POWER1_ADCL_MASK, 0)
elif input[0] == 0:
regs[_POWER1] = (0, _POWER1_AINL_MASK | _POWER1_ADCL_MASK)
regs[_INBMIX1] = input
else:
regs[_POWER1] = (0, _POWER1_AINL_MASK | _POWER1_ADCL_MASK | _POWER1_MICB_MASK)
regs[_LINPATH] = input[0]
regs[_LINVOL] = input[1]
def set_right_input(self, input):
if not input in self._input_config_table.keys():
raise ValueError("Invalid input name")
input = self._input_config_table[input]
regs = self.regs
if input is None:
regs[_POWER1] = (_POWER1_AINR_MASK | _POWER1_ADCR_MASK, 0)
elif input[0] == 0:
regs[_POWER1] = (0, _POWER1_AINL_MASK | _POWER1_ADCR_MASK)
regs[_INBMIX2] = input
else:
regs[_POWER1] = (0, _POWER1_AINR_MASK | _POWER1_ADCR_MASK | _POWER1_MICB_MASK)
regs[_RINPATH] = input[0]
regs[_RINVOL] = input[1]
def set_protocol(self, protocol):
self.regs[_IFACE1] = (
_IFACE1_FORMAT_MASK | _IFACE1_LRP_MASK,
protocol,
)
def config_data_format(self, sysclk, sample_rate, bits):
# Compute sample rate divider, dac and adc are the same sample rate
try:
divider = self._dac_divider_table[sysclk // sample_rate]
wl = self._audio_word_length_table[bits]
except:
raise ValueError("Invalid ratio sysclk/sample_rate or invalid bit length")
self.regs[_CLOCK1] = (0x1F8, divider << 6 | divider << 3)
self.regs[_IFACE1] = (_IFACE1_WL_MASK, wl << _IFACE1_WL_SHIFT)
def volume(self, module, volume_l=None, volume_r=None):
if not module in self._volume_config_table.keys():
raise ValueError("Invalid module")
if volume_l is None: # get volume
vol_max, regnum, _ = self._volume_config_table[module]
return (
int((self.regs[regnum] & vol_max) * 100 / vol_max + 0.5),
int((self.regs[regnum + 1] & vol_max) * 100 / vol_max + 0.5),
)
else: # set volume
if volume_r is None:
volume_r = volume_l
if not ((0 <= volume_l <= 100) and (0 <= volume_r <= 100)):
raise ValueError("Invalid value for volume")
elif not module in self._volume_config_table.keys():
raise ValueError("Invalid module")
vol_max, regnum, flags = self._volume_config_table[module]
self.regs[regnum] = int(volume_l * vol_max / 100 + 0.5) | flags
self.regs[regnum + 1] = int(volume_r * vol_max / 100 + 0.5) | flags
def mute(self, enable, soft=True, ramp=MUTE_FAST):
enable = _DACCTL1_DACMU_MASK if enable else 0
soft = _DACCTL2_DACSMM_MASK if soft else 0
ramp = _DACCTL2_DACMR_MASK if ramp == MUTE_SLOW else 0
self.regs[_DACCTL1] = (_DACCTL1_DACMU_MASK, enable)
self.regs[_DACCTL2] = (
_DACCTL2_DACSMM_MASK | _DACCTL2_DACMR_MASK,
soft | ramp,
)
def expand_3d(self, depth=0):
depth &= 0x0F
cutoff = 0 if self.sample_rate >= 32000 else 0b1100000
self.regs[_3D] = cutoff | depth << 1 | (1 if depth > 0 else 0)
def mono(self, enable):
enable = 1 if enable else 0
self.regs[_DACCTL1] = (
_DACCTL1_MONOMIX_MASK,
enable << _DACCTL1_MONOMIX_SHIFT,
)
def alc_mode(self, channel, mode=ALC_MODE):
if mode != ALC_MODE:
mode = ALC_LIMITER
channel &= 3
self.regs[_ALC1] = (
_ALC_CHANNEL_MASK,
channel << _ALC_CHANNEL_SHIFT,
)
self.regs[_ALC3] = (_ALC_MODE_MASK, mode << _ALC_MODE_SHIFT)
try:
rate = _alc_sample_rate_table[self.sample_rate]
except:
rate = 0
self.regs[_ADDCTL3] = (_DACCTL3_ALCSR_MASK, rate)
def alc_gain(self, target=-12, max_gain=30, min_gain=-17.25, noise_gate=-78):
def limit(value, minval, maxval):
value = int(value)
if value < minval:
value = minval
if value > maxval:
value = maxval
return value
target = limit((16 + (target * 2) // 3), 0, 15)
max_gain = limit((max_gain + 12) // 6, 0, 7)
min_gain = limit((min_gain * 4 + 69) // 24, 0, 7)
noise_gate = limit((noise_gate * 2 + 153) // 3, -1, 31)
self.regs[_ALC1] = (
_ALC_GAIN_MASK | _ALC_TARGET_MASK,
(max_gain << _ALC_GAIN_SHIFT) | target,
)
self.regs[_ALC2] = (_ALC_GAIN_MASK, (min_gain << _ALC_GAIN_SHIFT))
if noise_gate >= 0:
self.regs[_NOISEG] = noise_gate << _NOISEG_LEVEL_SHIFT | 1
else:
self.regs[_NOISEG] = 0
def alc_time(self, attack=24, decay=192, hold=0):
def logb(value, limit):
value = int(value)
lb = 0
while value > 1:
value >>= 1
lb += 1
if lb > limit:
lb = limit
return lb
attack = logb(attack / 6, 7)
decay = logb(decay / 24, 7)
hold = logb((hold * 3) / 8, 15)
self.regs[_ALC2] = (_ALC_HOLD_MASK, hold)
self.regs[_ALC3] = (
_ALC_DECAY_MASK | _ALC_ATTACK_MASK,
(decay << _ALC_DECAY_SHIFT) | attack,
)
def deemphasis(self, enable):
deem_table = (32000, 44100, 48000)
enable = not not enable
if enable and self.sample_rate in deem_table:
val = deem_table.index(self.sample_rate) + 1
else:
val = 0
self.regs[_DACCTL1] = (_DACCTL1_DEEM_MASK, val << _DACCTL1_DEEM_SHIFT)

View File

@@ -9,8 +9,10 @@ elif sys.platform == "mimxrt":
from mimxrt import dht_readinto
elif sys.platform == "rp2":
from rp2 import dht_readinto
else:
elif sys.platform == "pyboard":
from pyb import dht_readinto
else:
from machine import dht_readinto
class DHTBase:

View File

@@ -5,7 +5,7 @@ Source repo: https://github.com/hoihu/projects/tree/master/raspi-hat
The MIT License (MIT)
Copyright (c) 2021 Damien P. George
Copyright (c) 2021 Ibrahim Abdelkader <iabdalkader@openmv.io>
Copyright (c) 2021-2022 Ibrahim Abdelkader <iabdalkader@openmv.io>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -30,15 +30,20 @@ Basic example usage:
import time
from lsm6dsox import LSM6DSOX
from machine import Pin, I2C
from machine import Pin, SPI, I2C
# Init in I2C mode.
lsm = LSM6DSOX(I2C(0, scl=Pin(13), sda=Pin(12)))
# Or init in SPI mode.
#lsm = LSM6DSOX(SPI(5), cs_pin=Pin(10))
while (True):
print('Accelerometer: x:{:>8.3f} y:{:>8.3f} z:{:>8.3f}'.format(*lsm.read_accel()))
print('Gyroscope: x:{:>8.3f} y:{:>8.3f} z:{:>8.3f}'.format(*lsm.read_gyro()))
print("")
time.sleep_ms(100)
"""
import array
from micropython import const
@@ -73,7 +78,8 @@ class LSM6DSOX:
def __init__(
self,
i2c,
bus,
cs_pin=None,
address=_DEFAULT_ADDR,
gyro_odr=104,
accel_odr=104,
@@ -88,8 +94,13 @@ class LSM6DSOX:
accel_scale: (+/-2g, +/-4g, +/-8g, +-16g)
ucf: MLC program to load.
"""
self.i2c = i2c
self.bus = bus
self.cs_pin = cs_pin
self.address = address
self._use_i2c = hasattr(self.bus, "readfrom_mem")
if not self._use_i2c and cs_pin is None:
raise ValueError("A CS pin must be provided in SPI mode")
# check the id of the Accelerometer/Gyro
if self.__read_reg(_WHO_AM_I_REG) != 108:
@@ -149,13 +160,39 @@ class LSM6DSOX:
self.accel_scale = 32768 / accel_scale
def __read_reg(self, reg, size=1):
buf = self.i2c.readfrom_mem(self.address, reg, size)
if self._use_i2c:
buf = self.bus.readfrom_mem(self.address, reg, size)
else:
try:
self.cs_pin(0)
self.bus.write(bytes([reg | 0x80]))
buf = self.bus.read(size)
finally:
self.cs_pin(1)
if size == 1:
return int(buf[0])
return [int(x) for x in buf]
def __write_reg(self, reg, val):
self.i2c.writeto_mem(self.address, reg, bytes([val]))
if self._use_i2c:
self.bus.writeto_mem(self.address, reg, bytes([val]))
else:
try:
self.cs_pin(0)
self.bus.write(bytes([reg, val]))
finally:
self.cs_pin(1)
def __read_reg_into(self, reg, buf):
if self._use_i2c:
self.bus.readfrom_mem_into(self.address, reg, buf)
else:
try:
self.cs_pin(0)
self.bus.write(bytes([reg | 0x80]))
self.bus.readinto(buf)
finally:
self.cs_pin(1)
def reset(self):
self.__write_reg(_CTRL3_C, self.__read_reg(_CTRL3_C) | 0x1)
@@ -223,12 +260,12 @@ class LSM6DSOX:
"""Returns gyroscope vector in degrees/sec."""
mv = memoryview(self.scratch_int)
f = self.gyro_scale
self.i2c.readfrom_mem_into(self.address, _OUTX_L_G, mv)
self.__read_reg_into(_OUTX_L_G, mv)
return (mv[0] / f, mv[1] / f, mv[2] / f)
def read_accel(self):
"""Returns acceleration vector in gravity units (9.81m/s^2)."""
mv = memoryview(self.scratch_int)
f = self.accel_scale
self.i2c.readfrom_mem_into(self.address, _OUTX_L_XL, mv)
self.__read_reg_into(_OUTX_L_XL, mv)
return (mv[0] / f, mv[1] / f, mv[2] / f)

View File

@@ -5,6 +5,8 @@ from lsm6dsox import LSM6DSOX
from machine import Pin, I2C
lsm = LSM6DSOX(I2C(0, scl=Pin(13), sda=Pin(12)))
# Or init in SPI mode.
# lsm = LSM6DSOX(SPI(5), cs_pin=Pin(10))
while True:
print("Accelerometer: x:{:>8.3f} y:{:>8.3f} z:{:>8.3f}".format(*lsm.read_accel()))

View File

@@ -123,9 +123,9 @@ STATIC void mp_spiflash_read_data(mp_spiflash_t *self, uint32_t addr, size_t len
const mp_spiflash_config_t *c = self->config;
uint8_t cmd;
if (c->bus_kind == MP_SPIFLASH_BUS_SPI) {
cmd = MP_SPI_ADDR_IS_32B(addr) ? CMD_READ_32 : CMD_READ;
cmd = MICROPY_HW_SPI_ADDR_IS_32BIT(addr) ? CMD_READ_32 : CMD_READ;
} else {
cmd = MP_SPI_ADDR_IS_32B(addr) ? CMD_C4READ_32 : CMD_C4READ;
cmd = MICROPY_HW_SPI_ADDR_IS_32BIT(addr) ? CMD_C4READ_32 : CMD_C4READ;
}
mp_spiflash_transfer_cmd_addr_data(self, cmd, addr, len, NULL, dest);
}
@@ -218,7 +218,7 @@ STATIC int mp_spiflash_erase_block_internal(mp_spiflash_t *self, uint32_t addr)
}
// erase the sector
uint8_t cmd = MP_SPI_ADDR_IS_32B(addr) ? CMD_SEC_ERASE_32 : CMD_SEC_ERASE;
uint8_t cmd = MICROPY_HW_SPI_ADDR_IS_32BIT(addr) ? CMD_SEC_ERASE_32 : CMD_SEC_ERASE;
mp_spiflash_transfer_cmd_addr_data(self, cmd, addr, 0, NULL, NULL);
// wait WIP=0
@@ -236,7 +236,7 @@ STATIC int mp_spiflash_write_page(mp_spiflash_t *self, uint32_t addr, size_t len
}
// write the page
uint8_t cmd = MP_SPI_ADDR_IS_32B(addr) ? CMD_WRITE_32 : CMD_WRITE;
uint8_t cmd = MICROPY_HW_SPI_ADDR_IS_32BIT(addr) ? CMD_WRITE_32 : CMD_WRITE;
mp_spiflash_transfer_cmd_addr_data(self, cmd, addr, len, src, NULL);
// wait WIP=0

View File

@@ -31,6 +31,8 @@
int nina_bsp_init(void);
int nina_bsp_deinit(void);
int nina_bsp_atomic_enter(void);
int nina_bsp_atomic_exit(void);
int nina_bsp_read_irq(void);
int nina_bsp_spi_slave_select(uint32_t timeout);
int nina_bsp_spi_slave_deselect(void);

View File

@@ -90,6 +90,20 @@ int nina_bsp_deinit(void) {
return 0;
}
int nina_bsp_atomic_enter(void) {
#if MICROPY_ENABLE_SCHEDULER
mp_sched_lock();
#endif
return 0;
}
int nina_bsp_atomic_exit(void) {
#if MICROPY_ENABLE_SCHEDULER
mp_sched_unlock();
#endif
return 0;
}
int nina_bsp_read_irq(void) {
return mp_hal_pin_read(MICROPY_HW_NINA_GPIO0);
}
@@ -97,7 +111,7 @@ int nina_bsp_read_irq(void) {
int nina_bsp_spi_slave_select(uint32_t timeout) {
// Wait for ACK to go low.
for (mp_uint_t start = mp_hal_ticks_ms(); mp_hal_pin_read(MICROPY_HW_NINA_ACK) == 1; mp_hal_delay_ms(1)) {
if ((mp_hal_ticks_ms() - start) >= timeout) {
if (timeout && ((mp_hal_ticks_ms() - start) >= timeout)) {
return -1;
}
}

View File

@@ -28,6 +28,7 @@
*/
#include "py/mphal.h"
#include "py/mperrno.h"
#if MICROPY_PY_NETWORK_NINAW10
@@ -59,8 +60,7 @@
#define NINA_ARGS(...) (nina_args_t []) {__VA_ARGS__}
#define NINA_VALS(...) (nina_vals_t []) {__VA_ARGS__}
#define NINA_SSELECT_TIMEOUT (10000)
#define NINA_RESPONSE_TIMEOUT (1000)
#define NINA_SSELECT_TIMEOUT (1000)
#define NINA_CONNECT_TIMEOUT (10000)
#if NINA_DEBUG
@@ -129,18 +129,24 @@ typedef enum {
NINA_CMD_GET_MAC_ADDR = 0x22,
// Sockets commands.
NINA_CMD_SOCKET_OPEN = 0x3F,
NINA_CMD_SOCKET_CLOSE = 0x2E,
NINA_CMD_SOCKET_CONNECT = 0x2D,
NINA_CMD_SOCKET_ACCEPT = 0x2B,
NINA_CMD_SOCKET_BIND = 0x28,
NINA_CMD_SOCKET_STATE = 0x2F,
NINA_CMD_SOCKET_REMOTE_ADDR = 0x3A,
// TCP commands
NINA_CMD_TCP_SEND = 0x44,
NINA_CMD_TCP_RECV = 0x45,
NINA_CMD_TCP_ACK = 0x2A,
NINA_CMD_SOCKET_SOCKET = 0x70,
NINA_CMD_SOCKET_CLOSE = 0x71,
NINA_CMD_SOCKET_ERRNO = 0x72,
NINA_CMD_SOCKET_BIND = 0x73,
NINA_CMD_SOCKET_LISTEN = 0x74,
NINA_CMD_SOCKET_ACCEPT = 0x75,
NINA_CMD_SOCKET_CONNECT = 0x76,
NINA_CMD_SOCKET_SEND = 0x77,
NINA_CMD_SOCKET_RECV = 0x78,
NINA_CMD_SOCKET_SENDTO = 0x79,
NINA_CMD_SOCKET_RECVFROM = 0x7A,
NINA_CMD_SOCKET_IOCTL = 0x7B,
NINA_CMD_SOCKET_POLL = 0x7C,
NINA_CMD_SOCKET_SETSOCKOPT = 0x7D,
NINA_CMD_SOCKET_GETSOCKOPT = 0x7E,
NINA_CMD_SOCKET_GETPEERNAME = 0x7F,
// UDP commands.
NINA_CMD_UDP_SEND = 0x46,
@@ -200,28 +206,15 @@ static uint8_t nina_bsp_spi_read_byte(void) {
return byte;
}
static int nina_wait_for_cmd(uint8_t cmd, uint32_t timeout) {
uint8_t buf = 0;
for (mp_uint_t start = mp_hal_ticks_ms(); ;) {
buf = nina_bsp_spi_read_byte();
if (buf == CMD_ERROR || buf == cmd
|| ((mp_hal_ticks_ms() - start) >= timeout)) {
break;
}
mp_hal_delay_ms(1);
}
return (buf == cmd) ? 0 : -1;
}
static int nina_send_command(uint32_t cmd, uint32_t nargs, uint32_t width, nina_args_t *args) {
int ret = -1;
uint32_t length = 4; // 3 bytes header + 1 end byte
debug_printf("nina_send_command (cmd 0x%x nargs %d width %d): ", cmd, nargs, width);
nina_bsp_spi_slave_deselect();
if (nina_bsp_spi_slave_select(NINA_SSELECT_TIMEOUT) != 0) {
return -1;
goto error_out;
}
// Send command header.
@@ -264,29 +257,31 @@ error_out:
static int nina_read_response(uint32_t cmd, uint32_t nvals, uint32_t width, nina_vals_t *vals) {
int ret = -1;
uint32_t length = 3; // 3 bytes response header
uint8_t header[3] = {0, 0, 0};
debug_printf("nina_read_response(cmd 0x%x nvals %d width %d): ", cmd, nvals, width);
// Read reply
if (nina_bsp_spi_slave_select(NINA_SSELECT_TIMEOUT) != 0) {
return -1;
}
// Wait for CMD_START
if (nina_wait_for_cmd(CMD_START, NINA_RESPONSE_TIMEOUT) != 0) {
nina_bsp_spi_slave_deselect();
if (nina_bsp_spi_slave_select(0) != 0) {
goto error_out;
}
// Should return CMD + REPLY flag.
if (nina_bsp_spi_read_byte() != (cmd | CMD_REPLY)) {
if (nina_bsp_spi_transfer(NULL, header, sizeof(header)) != 0
|| header[1] != (cmd | CMD_REPLY)) {
// Read padding.
uint8_t header_padding = nina_bsp_spi_read_byte();
(void)header_padding;
debug_printf("nina_read_response() hdr 0x%x 0x%x 0x%x 0x%x\n",
header[0], header[1], header[2], header_padding);
goto error_out;
}
// Sanity check the number of returned values.
// NOTE: This is to handle the special case for the scan command.
uint32_t rvals = nina_bsp_spi_read_byte();
if (nvals > rvals) {
nvals = rvals;
if (nvals > header[2]) {
nvals = header[2];
}
// Read return value(s).
@@ -309,9 +304,12 @@ static int nina_read_response(uint32_t cmd, uint32_t nvals, uint32_t width, nina
// Set the size.
*(vals[i].size) = bytes;
length += bytes + width;
}
if (nina_bsp_spi_read_byte() != CMD_END) {
// Read CMD_END and padding.
uint8_t rspbuf_end[4];
if (nina_bsp_spi_transfer(NULL, rspbuf_end, ((length + 1) % 4) + 1) != 0 || rspbuf_end[0] != CMD_END) {
goto error_out;
}
@@ -327,21 +325,25 @@ error_out:
static int nina_send_command_read_ack(uint32_t cmd, uint32_t nargs, uint32_t width, nina_args_t *args) {
uint16_t size = 1;
uint8_t rval = SPI_ERR;
nina_bsp_atomic_enter();
if (nina_send_command(cmd, nargs, width, args) != 0 ||
nina_read_response(cmd, 1, ARG_8BITS, NINA_VALS({&size, &rval})) != 0) {
return -1;
rval = -1;
}
nina_bsp_atomic_exit();
return rval;
}
static int nina_send_command_read_vals(uint32_t cmd, uint32_t nargs,
uint32_t argsw, nina_args_t *args, uint32_t nvals, uint32_t valsw, nina_vals_t *vals) {
int ret = 0;
nina_bsp_atomic_enter();
if (nina_send_command(cmd, nargs, argsw, args) != 0 ||
nina_read_response(cmd, nvals, valsw, vals) != 0) {
return -1;
ret = -1;
}
return 0;
nina_bsp_atomic_exit();
return ret;
}
static void nina_fix_mac_addr(uint8_t *mac) {
@@ -366,16 +368,6 @@ static int nina_connection_status() {
return nina_send_command_read_ack(NINA_CMD_CONN_STATUS, 0, ARG_8BITS, NULL);
}
static int nina_socket_status(uint8_t fd) {
return nina_send_command_read_ack(NINA_CMD_SOCKET_STATE,
1, ARG_8BITS, NINA_ARGS(ARG_BYTE(fd)));
}
static int nina_server_socket_status(uint8_t fd) {
return nina_send_command_read_ack(NINA_CMD_SOCKET_STATE & 0xF9,
1, ARG_8BITS, NINA_ARGS(ARG_BYTE(fd)));
}
int nina_connect(const char *ssid, uint8_t security, const char *key, uint16_t channel) {
uint8_t status = NINA_STATUS_CONNECT_FAILED;
@@ -468,21 +460,13 @@ int nina_disconnect(void) {
}
int nina_isconnected(void) {
int status = nina_connection_status();
if (status == -1) {
return -1;
}
return status == NINA_STATUS_CONNECTED;
return nina_connection_status() == NINA_STATUS_CONNECTED;
}
int nina_connected_sta(uint32_t *sta_ip) {
return -1;
}
int nina_wait_for_sta(uint32_t *sta_ip, uint32_t timeout) {
return NINA_ERROR_TIMEOUT;
}
int nina_ifconfig(nina_ifconfig_t *ifconfig, bool set) {
uint16_t ip_len = NINA_IPV4_ADDR_LEN;
uint16_t sub_len = NINA_IPV4_ADDR_LEN;
@@ -597,7 +581,7 @@ int nina_scan(nina_scan_callback_t scan_callback, void *arg, uint32_t timeout) {
if (timeout && (mp_hal_ticks_ms() - start) >= timeout) {
// Timeout, no networks.
return NINA_ERROR_TIMEOUT;
return -MP_ETIMEDOUT;
}
mp_hal_delay_ms(100);
@@ -700,232 +684,240 @@ int nina_gethostbyname(const char *name, uint8_t *out_ip) {
return 0;
}
int nina_socket_socket(uint8_t type) {
uint16_t size = 1;
uint8_t sock = 0;
if (nina_send_command_read_vals(NINA_CMD_SOCKET_OPEN,
0, ARG_8BITS, NULL,
1, ARG_8BITS, NINA_VALS({&size, &sock})) != 0) {
return -1;
}
return sock;
}
int nina_socket_close(int fd) {
if (fd > 0 && fd < 255) {
if (nina_send_command_read_ack(NINA_CMD_SOCKET_CLOSE,
1, ARG_8BITS, NINA_ARGS(ARG_BYTE(fd))) != SPI_ACK) {
return -1;
}
for (mp_uint_t start = mp_hal_ticks_ms(); ; mp_hal_delay_ms(10)) {
if (nina_socket_status(fd) == SOCKET_STATE_CLOSED) {
break;
int nina_ioctl(uint32_t cmd, size_t len, uint8_t *buf, uint32_t iface) {
switch (cmd) {
case NINA_CMD_SET_PIN_MODE:
if (len != 2 || nina_send_command_read_ack(NINA_CMD_SET_PIN_MODE,
2, ARG_8BITS, NINA_ARGS(ARG_BYTE(buf[0]), ARG_BYTE(buf[1]))) != SPI_ACK) {
return -1;
}
if ((mp_hal_ticks_ms() - start) >= 5000) {
return NINA_ERROR_TIMEOUT;
break;
case NINA_CMD_SET_DIGITAL_WRITE:
if (len != 2 || nina_send_command_read_ack(NINA_CMD_SET_DIGITAL_WRITE,
2, ARG_8BITS, NINA_ARGS(ARG_BYTE(buf[0]), ARG_BYTE(buf[1]))) != SPI_ACK) {
return -1;
}
}
break;
case NINA_CMD_GET_DIGITAL_READ:
if (len != 1 || nina_send_command_read_vals(NINA_CMD_GET_DIGITAL_READ,
1, ARG_8BITS, NINA_ARGS(ARG_BYTE(buf[0])),
1, ARG_8BITS, NINA_VALS({(uint16_t *)&len, buf})) != 0) {
return -1;
}
break;
default:
return 0;
}
return 0;
}
int nina_socket_bind(int fd, uint8_t *ip, uint16_t port, int type) {
if (nina_send_command_read_ack(NINA_CMD_SOCKET_BIND,
3, ARG_8BITS,
NINA_ARGS(
ARG_SHORT(__REVSH(port)),
ARG_BYTE(fd),
ARG_BYTE(type))) != SPI_ACK) {
int nina_socket_socket(uint8_t type, uint8_t proto) {
uint16_t size = 1;
uint8_t sock = 0;
if (nina_send_command_read_vals(NINA_CMD_SOCKET_SOCKET,
2, ARG_8BITS, NINA_ARGS(ARG_BYTE(type), ARG_BYTE(proto)),
1, ARG_8BITS, NINA_VALS({&size, &sock})) != 0) {
return -1;
}
return (sock == NO_SOCKET_AVAIL) ? -1 : sock;
}
// Only TCP sockets' states should be checked.
if (type == NINA_SOCKET_TYPE_TCP &&
nina_server_socket_status(fd) != SOCKET_STATE_LISTEN) {
int nina_socket_close(int fd) {
if (nina_send_command_read_ack(NINA_CMD_SOCKET_CLOSE,
1, ARG_8BITS, NINA_ARGS(ARG_BYTE(fd))) != SPI_ACK) {
return -1;
}
return 0;
}
int nina_socket_errno(int *_errno) {
uint16_t size = 1;
*_errno = 0;
if (nina_send_command_read_vals(NINA_CMD_SOCKET_ERRNO,
0, ARG_8BITS, NULL,
1, ARG_8BITS, NINA_VALS({&size, _errno})) != 0) {
return -1;
}
return 0;
}
int nina_socket_bind(int fd, uint8_t *ip, uint16_t port) {
if (nina_send_command_read_ack(NINA_CMD_SOCKET_BIND,
2, ARG_8BITS,
NINA_ARGS(
ARG_BYTE(fd),
ARG_SHORT(__REVSH(port)))) != SPI_ACK) {
return -1;
}
return 0;
}
int nina_socket_listen(int fd, uint32_t backlog) {
return 0; // No listen ?
}
int nina_socket_accept(int fd, uint8_t *ip, uint16_t *port, int *fd_out, uint32_t timeout) {
uint16_t size = 2;
uint16_t sock = NO_SOCKET_AVAIL;
if (nina_server_socket_status(fd) != SOCKET_STATE_LISTEN) {
if (nina_send_command_read_ack(NINA_CMD_SOCKET_LISTEN,
2, ARG_8BITS,
NINA_ARGS(
ARG_BYTE(fd),
ARG_BYTE(backlog))) != SPI_ACK) {
return -1;
}
return 0;
}
for (mp_uint_t start = mp_hal_ticks_ms(); sock == 0 || sock == NO_SOCKET_AVAIL; mp_hal_delay_ms(10)) {
if (nina_send_command_read_vals(NINA_CMD_SOCKET_ACCEPT,
1, ARG_8BITS, NINA_ARGS(ARG_BYTE(fd)),
1, ARG_8BITS, NINA_VALS({&size, &sock})) != 0) {
return -1;
}
if (timeout && (mp_hal_ticks_ms() - start) >= timeout) {
return NINA_ERROR_TIMEOUT;
}
}
int nina_socket_accept(int fd, uint8_t *ip, uint16_t *port, int *fd_out) {
uint16_t fd_len = 1;
uint16_t port_len = 2;
uint16_t ip_len = NINA_IPV4_ADDR_LEN;
if (nina_send_command_read_vals(NINA_CMD_SOCKET_REMOTE_ADDR,
1, ARG_8BITS, NINA_ARGS(ARG_BYTE(sock)),
2, ARG_8BITS, NINA_VALS({&ip_len, ip}, {&port_len, port})) != 0) {
return -1;
}
*fd_out = sock;
*port = __REVSH(*port);
return 0;
}
int nina_socket_connect(int fd, uint8_t *ip, uint16_t port, uint32_t timeout) {
if (nina_send_command_read_ack(NINA_CMD_SOCKET_CONNECT,
4, ARG_8BITS,
NINA_ARGS(
ARG_WORD((*(uint32_t *)ip)),
ARG_SHORT(__REVSH(port)),
ARG_BYTE(fd),
ARG_BYTE(NINA_SOCKET_TYPE_TCP))) != SPI_ACK) {
return -1;
}
for (mp_uint_t start = mp_hal_ticks_ms(); ; mp_hal_delay_ms(10)) {
int state = nina_socket_status(fd);
if (state == -1) {
return -1;
}
if (state == SOCKET_STATE_ESTABLISHED) {
break;
}
if (timeout && (mp_hal_ticks_ms() - start) >= timeout) {
return NINA_ERROR_TIMEOUT;
}
}
return 0;
}
int nina_socket_send(int fd, const uint8_t *buf, uint32_t len, uint32_t timeout) {
uint16_t size = 2;
uint16_t bytes = 0;
if (nina_socket_status(fd) != SOCKET_STATE_ESTABLISHED) {
return -1;
}
if (nina_send_command_read_vals(NINA_CMD_TCP_SEND,
2, ARG_16BITS, NINA_ARGS(ARG_BYTE(fd), {len, buf}),
1, ARG_8BITS, NINA_VALS({&size, &bytes})) != 0 || bytes <= 0) {
return -1;
}
for (mp_uint_t start = mp_hal_ticks_ms(); ;) {
int resp = nina_send_command_read_ack(NINA_CMD_TCP_ACK,
1, ARG_8BITS, NINA_ARGS(ARG_BYTE(fd)));
if (resp == -1) {
return -1;
}
if (resp == SPI_ACK) {
break;
}
if (timeout && (mp_hal_ticks_ms() - start) >= timeout) {
return NINA_ERROR_TIMEOUT;
}
mp_hal_delay_ms(1);
}
return bytes;
}
int nina_socket_recv(int fd, uint8_t *buf, uint32_t len, uint32_t timeout) {
uint16_t bytes = 0;
if (nina_socket_status(fd) != SOCKET_STATE_ESTABLISHED) {
return -1;
}
for (mp_uint_t start = mp_hal_ticks_ms(); bytes == 0; mp_hal_delay_ms(1)) {
bytes = len;
if (nina_send_command_read_vals(NINA_CMD_TCP_RECV,
2, ARG_16BITS, NINA_ARGS(ARG_BYTE(fd), ARG_SHORT(bytes)),
1, ARG_16BITS, NINA_VALS({&bytes, buf})) != 0) {
return -1;
}
if (timeout && (mp_hal_ticks_ms() - start) >= timeout) {
return NINA_ERROR_TIMEOUT;
}
}
return bytes;
}
// Check from the upper layer if the socket is bound, if not then auto-bind it first.
int nina_socket_sendto(int fd, const uint8_t *buf, uint32_t len, uint8_t *ip, uint16_t port, uint32_t timeout) {
// TODO do we need to split the packet somewhere?
if (nina_send_command_read_ack(NINA_CMD_SOCKET_CONNECT,
4, ARG_8BITS,
NINA_ARGS(
ARG_WORD((*(uint32_t *)ip)),
ARG_SHORT(__REVSH(port)),
ARG_BYTE(fd),
ARG_BYTE(NINA_SOCKET_TYPE_UDP))) != SPI_ACK) {
return -1;
}
// Buffer length and socket number are passed as 16bits.
if (nina_send_command_read_ack(NINA_CMD_UDP_SEND,
2, ARG_16BITS, NINA_ARGS(ARG_BYTE(fd), {len, buf})) != SPI_ACK) {
return -1;
}
if (nina_send_command_read_ack(NINA_CMD_UDP_ACK,
1, ARG_8BITS, NINA_ARGS(ARG_BYTE(fd))) != SPI_ACK) {
return -1;
}
return 0;
}
// Check from the upper layer if the socket is bound, if not then auto-bind it first.
int nina_socket_recvfrom(int fd, uint8_t *buf, uint32_t len, uint8_t *ip, uint16_t *port, uint32_t timeout) {
uint16_t bytes = 0;
uint16_t port_len = 2;
uint16_t ip_len = NINA_IPV4_ADDR_LEN;
for (mp_uint_t start = mp_hal_ticks_ms(); bytes == 0; mp_hal_delay_ms(1)) {
bytes = len;
if (nina_send_command_read_vals(NINA_CMD_UDP_RECV,
2, ARG_16BITS, NINA_ARGS(ARG_BYTE(fd), ARG_SHORT(bytes)),
1, ARG_16BITS, NINA_VALS({&bytes, buf})) != 0) {
return -1;
}
if (timeout && (mp_hal_ticks_ms() - start) >= timeout) {
return NINA_ERROR_TIMEOUT;
}
}
if (nina_send_command_read_vals(NINA_CMD_SOCKET_REMOTE_ADDR,
*fd_out = 0;
if (nina_send_command_read_vals(NINA_CMD_SOCKET_ACCEPT,
1, ARG_8BITS, NINA_ARGS(ARG_BYTE(fd)),
2, ARG_8BITS, NINA_VALS({&ip_len, ip}, {&port_len, port})) != 0) {
3, ARG_8BITS, NINA_VALS({&fd_len, fd_out}, {&ip_len, ip}, {&port_len, port})) != 0) {
return -1;
}
return (*fd_out == NO_SOCKET_AVAIL) ? -1 : 0;
}
int nina_socket_connect(int fd, uint8_t *ip, uint16_t port) {
if (nina_send_command_read_ack(NINA_CMD_SOCKET_CONNECT,
3, ARG_8BITS,
NINA_ARGS(
ARG_BYTE(fd),
ARG_WORD((*(uint32_t *)ip)),
ARG_SHORT(__REVSH(port)))) != SPI_ACK) {
return -1;
}
return 0;
}
int nina_socket_send(int fd, const uint8_t *buf, uint32_t len) {
uint16_t size = 2;
uint16_t bytes = 0;
if (nina_send_command_read_vals(NINA_CMD_SOCKET_SEND,
2, ARG_16BITS, NINA_ARGS(ARG_BYTE(fd), {len, buf}),
1, ARG_8BITS, NINA_VALS({&size, &bytes})) != 0) {
return -1;
}
// Only args sizes (not args themselves) are reversed in read_response().
bytes = __REVSH(bytes);
if (bytes == 0) {
int _errno = 0;
if (nina_socket_errno(&_errno) != 0 || _errno != 0) {
return -1;
}
}
return bytes;
}
int nina_socket_setsockopt(int fd, uint32_t level, uint32_t opt, const void *optval, uint32_t optlen) {
return -1;
int nina_socket_recv(int fd, uint8_t *buf, uint32_t len) {
uint16_t bytes = len;
if (nina_send_command_read_vals(NINA_CMD_SOCKET_RECV,
2, ARG_8BITS, NINA_ARGS(ARG_BYTE(fd), ARG_SHORT(bytes)),
1, ARG_16BITS, NINA_VALS({&bytes, buf})) != 0) {
return -1;
}
if (bytes == 0) {
int _errno = 0;
if (nina_socket_errno(&_errno) != 0 || _errno != 0) {
return -1;
}
}
return bytes;
}
// Check from the upper layer if the socket is bound, if not then auto-bind it first.
int nina_socket_sendto(int fd, const uint8_t *buf, uint32_t len, uint8_t *ip, uint16_t port) {
uint16_t size = 2;
uint16_t bytes = 0;
if (nina_send_command_read_vals(NINA_CMD_SOCKET_SENDTO,
4, ARG_16BITS, NINA_ARGS(ARG_BYTE(fd), ARG_WORD((*(uint32_t *)ip)), ARG_SHORT(__REVSH(port)), {len, buf}),
1, ARG_8BITS, NINA_VALS({&size, &bytes})) != 0) {
return -1;
}
// Only args sizes (not args themselves) are reversed in read_response().
bytes = __REVSH(bytes);
if (bytes == 0) {
int _errno = 0;
if (nina_socket_errno(&_errno) != 0 || _errno != 0) {
return -1;
}
}
return bytes;
}
// Check from the upper layer if the socket is bound, if not then auto-bind it first.
int nina_socket_recvfrom(int fd, uint8_t *buf, uint32_t len, uint8_t *ip, uint16_t *port) {
uint16_t bytes = len;
uint16_t port_len = 2;
uint16_t ip_len = NINA_IPV4_ADDR_LEN;
if (nina_send_command_read_vals(NINA_CMD_SOCKET_RECVFROM,
2, ARG_8BITS, NINA_ARGS(ARG_BYTE(fd), ARG_SHORT(bytes)),
3, ARG_16BITS, NINA_VALS({&ip_len, ip}, {&port_len, port}, {&bytes, buf})) != 0) {
return -1;
}
if (bytes == 0) {
int _errno = 0;
if (nina_socket_errno(&_errno) != 0 || _errno != 0) {
return -1;
}
}
return bytes;
}
int nina_socket_ioctl(int fd, uint32_t cmd, void *argval, uint32_t arglen) {
uint16_t len = arglen;
if (nina_send_command_read_vals(NINA_CMD_SOCKET_IOCTL,
3, ARG_8BITS, NINA_ARGS(ARG_BYTE(fd), ARG_WORD(cmd), {len, argval}),
1, ARG_8BITS, NINA_VALS({&len, argval})) != 0 || arglen == 0) {
return -1;
}
return 0;
}
int nina_socket_poll(int fd, uint8_t *flags) {
uint16_t flags_len = 1;
if (nina_send_command_read_vals(NINA_CMD_SOCKET_POLL,
1, ARG_8BITS, NINA_ARGS(ARG_BYTE(fd)),
1, ARG_8BITS, NINA_VALS({&flags_len, flags})) != 0) {
return -1;
}
if (*flags & 0x80) {
// lwip_select() failed.
return -1;
}
return 0;
}
int nina_socket_setsockopt(int fd, uint32_t level, uint32_t optname, const void *optval, uint16_t optlen) {
if (nina_send_command_read_ack(
NINA_CMD_SOCKET_SETSOCKOPT,
3, ARG_8BITS,
NINA_ARGS(ARG_BYTE(fd), ARG_WORD(optname), {optlen, optval})) != SPI_ACK) {
return -1;
}
return 0;
}
int nina_socket_getsockopt(int fd, uint32_t level, uint32_t optname, void *optval, uint16_t optlen) {
if (nina_send_command_read_vals(
NINA_CMD_SOCKET_GETSOCKOPT,
3, ARG_8BITS, NINA_ARGS(ARG_BYTE(fd), ARG_WORD(optname), ARG_BYTE(optlen)),
1, ARG_8BITS, NINA_VALS({&optlen, optval})) != 0 || optlen == 0) {
return -1;
}
return 0;
}
#endif // MICROPY_PY_NINAW10

View File

@@ -38,9 +38,9 @@
#define NINA_MAX_NETWORK_LIST (10)
#define NINA_MAX_SOCKET (10)
#define NINA_FW_VER_MAJOR (1)
#define NINA_FW_VER_MINOR (4)
#define NINA_FW_VER_PATCH (8)
#define NINA_FW_VER_MIN_MAJOR (1)
#define NINA_FW_VER_MIN_MINOR (5)
#define NINA_FW_VER_MIN_PATCH (0)
#define NINA_FW_VER_MAJOR_OFFS (0)
#define NINA_FW_VER_MINOR_OFFS (2)
@@ -54,18 +54,11 @@ typedef enum {
} nina_security_t;
typedef enum {
NINA_SOCKET_TYPE_TCP = 0,
NINA_SOCKET_TYPE_UDP,
NINA_SOCKET_TYPE_TLS,
NINA_SOCKET_TYPE_UDP_MULTICAST,
NINA_SOCKET_TYPE_TLS_BEARSSL
NINA_SOCKET_TYPE_TCP = 1,
NINA_SOCKET_TYPE_UDP = 2,
NINA_SOCKET_TYPE_RAW = 3,
} nina_socket_type_t;
typedef enum {
NINA_ERROR_IO = -1,
NINA_ERROR_TIMEOUT = -2,
} nina_error_t;
typedef struct {
uint8_t ip_addr[NINA_IPV4_ADDR_LEN];
uint8_t subnet_addr[NINA_IPV4_ADDR_LEN];
@@ -97,7 +90,6 @@ int nina_start_ap(const char *ssid, uint8_t security, const char *key, uint16_t
int nina_disconnect(void);
int nina_isconnected(void);
int nina_connected_sta(uint32_t *sta_ip);
int nina_wait_for_sta(uint32_t *sta_ip, uint32_t timeout);
int nina_ifconfig(nina_ifconfig_t *ifconfig, bool set);
int nina_netinfo(nina_netinfo_t *netinfo);
int nina_scan(nina_scan_callback_t scan_callback, void *arg, uint32_t timeout);
@@ -105,16 +97,21 @@ int nina_get_rssi(void);
int nina_fw_version(uint8_t *fw_ver);
int nina_set_hostname(const char *name);
int nina_gethostbyname(const char *name, uint8_t *out_ip);
int nina_socket_socket(uint8_t type);
int nina_ioctl(uint32_t cmd, size_t len, uint8_t *buf, uint32_t iface);
int nina_socket_socket(uint8_t type, uint8_t proto);
int nina_socket_close(int fd);
int nina_socket_bind(int fd, uint8_t *ip, uint16_t port, int type);
int nina_socket_errno(int *_errno);
int nina_socket_bind(int fd, uint8_t *ip, uint16_t port);
int nina_socket_listen(int fd, uint32_t backlog);
int nina_socket_accept(int fd, uint8_t *ip, uint16_t *port, int *fd_out, uint32_t timeout);
int nina_socket_connect(int fd, uint8_t *ip, uint16_t port, uint32_t timeout);
int nina_socket_send(int fd, const uint8_t *buf, uint32_t len, uint32_t timeout);
int nina_socket_recv(int fd, uint8_t *buf, uint32_t len, uint32_t timeout);
int nina_socket_sendto(int fd, const uint8_t *buf, uint32_t len, uint8_t *ip, uint16_t port, uint32_t timeout);
int nina_socket_recvfrom(int fd, uint8_t *buf, uint32_t len, uint8_t *ip, uint16_t *port, uint32_t timeout);
int nina_socket_setsockopt(int fd, uint32_t level, uint32_t opt, const void *optval, uint32_t optlen);
int nina_socket_accept(int fd, uint8_t *ip, uint16_t *port, int *fd_out);
int nina_socket_connect(int fd, uint8_t *ip, uint16_t port);
int nina_socket_send(int fd, const uint8_t *buf, uint32_t len);
int nina_socket_recv(int fd, uint8_t *buf, uint32_t len);
int nina_socket_sendto(int fd, const uint8_t *buf, uint32_t len, uint8_t *ip, uint16_t port);
int nina_socket_recvfrom(int fd, uint8_t *buf, uint32_t len, uint8_t *ip, uint16_t *port);
int nina_socket_ioctl(int fd, uint32_t cmd, void *argval, uint32_t arglen);
int nina_socket_poll(int fd, uint8_t *flags);
int nina_socket_setsockopt(int fd, uint32_t level, uint32_t opt, const void *optval, uint16_t optlen);
int nina_socket_getsockopt(int fd, uint32_t level, uint32_t opt, void *optval, uint16_t optlen);
int nina_socket_getpeername(int fd, uint8_t *ip, uint16_t *port);
#endif // MICROPY_INCLUDED_DRIVERS_NINAW10_NINA_WIFI_DRV_H

View File

@@ -39,7 +39,7 @@ _TOKEN_DATA = const(0xFE)
class SDCard:
def __init__(self, spi, cs):
def __init__(self, spi, cs, baudrate=1320000):
self.spi = spi
self.cs = cs
@@ -51,7 +51,7 @@ class SDCard:
self.dummybuf_memoryview = memoryview(self.dummybuf)
# initialise the card
self.init_card()
self.init_card(baudrate)
def init_spi(self, baudrate):
try:
@@ -63,7 +63,8 @@ class SDCard:
# on pyboard
self.spi.init(master, baudrate=baudrate, phase=0, polarity=0)
def init_card(self):
def init_card(self, baudrate):
# init CS pin
self.cs.init(self.cs.OUT, value=1)
@@ -99,9 +100,11 @@ class SDCard:
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)
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))
c_size = (csd[6] & 0b11) << 10 | csd[7] << 2 | csd[8] >> 6
c_size_mult = (csd[9] & 0b11) << 1 | csd[10] >> 7
read_bl_len = csd[5] & 0b1111
capacity = (c_size + 1) * (2 ** (c_size_mult + 2)) * (2**read_bl_len)
self.sectors = capacity // 512
else:
raise OSError("SD card CSD format not supported")
# print('sectors', self.sectors)
@@ -111,12 +114,13 @@ class SDCard:
raise OSError("can't set 512 block size")
# set to high data rate now that it's initialised
self.init_spi(1320000)
self.init_spi(baudrate)
def init_card_v1(self):
for i in range(_CMD_TIMEOUT):
self.cmd(55, 0, 0)
if self.cmd(41, 0, 0) == 0:
# SDSC card, uses byte addressing in read/write/erase commands
self.cdv = 512
# print("[SDCard] v1 card")
return
@@ -128,8 +132,14 @@ class SDCard:
self.cmd(58, 0, 0, 4)
self.cmd(55, 0, 0)
if self.cmd(41, 0x40000000, 0) == 0:
self.cmd(58, 0, 0, 4)
self.cdv = 1
self.cmd(58, 0, 0, -4) # 4-byte response, negative means keep the first byte
ocr = self.tokenbuf[0] # get first byte of response, which is OCR
if not ocr & 0x40:
# SDSC card, uses byte addressing in read/write/erase commands
self.cdv = 512
else:
# SDHC/SDXC card, uses block addressing in read/write/erase commands
self.cdv = 1
# print("[SDCard] v2 card")
return
raise OSError("timeout waiting for v2 card")
@@ -156,6 +166,10 @@ class SDCard:
response = self.tokenbuf[0]
if not (response & 0x80):
# this could be a big-endian integer that we are getting here
# if final<0 then store the first byte to tokenbuf and discard the rest
if final < 0:
self.spi.readinto(self.tokenbuf, 0xFF)
final = -1 - final
for j in range(final):
self.spi.write(b"\xff")
if release:
@@ -280,3 +294,5 @@ class SDCard:
def ioctl(self, op, arg):
if op == 4: # get number of blocks
return self.sectors
if op == 5: # get block size in bytes
return 512

View File

@@ -137,7 +137,6 @@ SRC_C = $(addprefix ports/unix/,\
unix_mphal.c \
input.c \
modmachine.c \
modos.c \
moduselect.c \
alloc.c \
coverage.c \

View File

@@ -28,6 +28,7 @@
#include <stdio.h>
#include <stdlib.h>
#include "py/builtin.h"
#include "py/compile.h"
#include "py/runtime.h"
#include "py/gc.h"

View File

@@ -75,21 +75,18 @@
#define MICROPY_PY_SYS_EXIT (0)
#define MICROPY_PY_SYS_PLATFORM "linux"
#define MICROPY_PY_SYS_MAXSIZE (0)
#define MICROPY_PY_SYS_PATH_DEFAULT ".frozen"
#define MICROPY_PY_SYS_STDFILES (0)
#define MICROPY_PY_CMATH (0)
#define MICROPY_PY_UCTYPES (0)
#define MICROPY_PY_UZLIB (0)
#define MICROPY_PY_UJSON (0)
#define MICROPY_PY_UOS (1)
#define MICROPY_PY_URE (0)
#define MICROPY_PY_UHEAPQ (0)
#define MICROPY_PY_UHASHLIB (0)
#define MICROPY_PY_UBINASCII (0)
extern const struct _mp_obj_module_t mp_module_os;
#define MICROPY_PORT_BUILTIN_MODULES \
{ MP_ROM_QSTR(MP_QSTR_uos), MP_ROM_PTR(&mp_module_os) }, \
#define MICROPY_PORT_ROOT_POINTERS \
//////////////////////////////////////////

View File

@@ -0,0 +1,14 @@
# Location of top-level MicroPython directory
MPY_DIR = ../../..
# Name of module
MOD = features3
# Source files (.c or .py)
SRC = features3.c
# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin)
ARCH = x64
# Include to get the rules for compiling and linking the module
include $(MPY_DIR)/py/dynruntime.mk

View File

@@ -0,0 +1,60 @@
/* This example demonstrates the following features in a native module:
- using types
- using constant objects
- creating dictionaries
*/
// Include the header file to get access to the MicroPython API.
#include "py/dynruntime.h"
// A function that returns a tuple of object types.
STATIC mp_obj_t get_types(void) {
return mp_obj_new_tuple(9, ((mp_obj_t []) {
MP_OBJ_FROM_PTR(&mp_type_type),
MP_OBJ_FROM_PTR(&mp_type_NoneType),
MP_OBJ_FROM_PTR(&mp_type_bool),
MP_OBJ_FROM_PTR(&mp_type_int),
MP_OBJ_FROM_PTR(&mp_type_str),
MP_OBJ_FROM_PTR(&mp_type_bytes),
MP_OBJ_FROM_PTR(&mp_type_tuple),
MP_OBJ_FROM_PTR(&mp_type_list),
MP_OBJ_FROM_PTR(&mp_type_dict),
}));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(get_types_obj, get_types);
// A function that returns a tuple of constant objects.
STATIC mp_obj_t get_const_objects(void) {
return mp_obj_new_tuple(5, ((mp_obj_t []) {
mp_const_none,
mp_const_false,
mp_const_true,
mp_const_empty_bytes,
mp_const_empty_tuple,
}));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(get_const_objects_obj, get_const_objects);
// A function that creates a dictionary from the given arguments.
STATIC mp_obj_t make_dict(size_t n_args, const mp_obj_t *args) {
mp_obj_t dict = mp_obj_new_dict(n_args / 2);
for (; n_args >= 2; n_args -= 2, args += 2) {
mp_obj_dict_store(dict, args[0], args[1]);
}
return dict;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(make_dict_obj, 0, MP_OBJ_FUN_ARGS_MAX, make_dict);
// This is the entry point and is called when the module is imported.
mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) {
// This must be first, it sets up the globals dict and other things.
MP_DYNRUNTIME_INIT_ENTRY
// Make the functions available in the module's namespace.
mp_store_global(MP_QSTR_make_dict, MP_OBJ_FROM_PTR(&make_dict_obj));
mp_store_global(MP_QSTR_get_types, MP_OBJ_FROM_PTR(&get_types_obj));
mp_store_global(MP_QSTR_get_const_objects, MP_OBJ_FROM_PTR(&get_const_objects_obj));
// This must be last, it restores the globals dict.
MP_DYNRUNTIME_INIT_EXIT
}

View File

@@ -41,5 +41,5 @@ pwm = PIOPWM(0, 25, max_count=(1 << 16) - 1, count_freq=10_000_000)
while True:
for i in range(256):
pwm.set(i ** 2)
pwm.set(i**2)
sleep(0.01)

View File

@@ -31,7 +31,4 @@ const mp_obj_module_t example_user_cmodule = {
};
// Register the module to make it available in Python.
// Note: the "1" in the third argument means this module is always enabled.
// This "1" can be optionally replaced with a macro like MODULE_CEXAMPLE_ENABLED
// which can then be used to conditionally enable this module.
MP_REGISTER_MODULE(MP_QSTR_cexample, example_user_cmodule, 1);
MP_REGISTER_MODULE(MP_QSTR_cexample, example_user_cmodule);

View File

@@ -22,7 +22,4 @@ const mp_obj_module_t cppexample_user_cmodule = {
};
// Register the module to make it available in Python.
// Note: the "1" in the third argument means this module is always enabled.
// This "1" can be optionally replaced with a macro like MODULE_CPPEXAMPLE_ENABLED
// which can then be used to conditionally enable this module.
MP_REGISTER_MODULE(MP_QSTR_cppexample, cppexample_user_cmodule, 1);
MP_REGISTER_MODULE(MP_QSTR_cppexample, cppexample_user_cmodule);

View File

@@ -6,7 +6,7 @@ SRC_USERMOD_CXX += $(CPPEXAMPLE_MOD_DIR)/example.cpp
# Add our module directory to the include path.
CFLAGS_USERMOD += -I$(CPPEXAMPLE_MOD_DIR)
CXXFLAGS_USERMOD += -I$(CPPEXAMPLE_MOD_DIR)
CXXFLAGS_USERMOD += -I$(CPPEXAMPLE_MOD_DIR) -std=c++11
# We use C++ features so have to link against the standard library.
LDFLAGS_USERMOD += -lstdc++

View File

@@ -25,6 +25,7 @@ set(MICROPY_SOURCE_EXTMOD
${MICROPY_EXTMOD_DIR}/moduhashlib.c
${MICROPY_EXTMOD_DIR}/moduheapq.c
${MICROPY_EXTMOD_DIR}/modujson.c
${MICROPY_EXTMOD_DIR}/moduos.c
${MICROPY_EXTMOD_DIR}/moduplatform.c
${MICROPY_EXTMOD_DIR}/modurandom.c
${MICROPY_EXTMOD_DIR}/modure.c
@@ -53,9 +54,9 @@ set(MICROPY_SOURCE_EXTMOD
# Library for btree module and associated code
set(MICROPY_LIB_BERKELEY_DIR "${MICROPY_DIR}/lib/berkeley-db-1.xx")
if(MICROPY_PY_BTREE)
set(MICROPY_LIB_BERKELEY_DIR "${MICROPY_DIR}/lib/berkeley-db-1.xx")
if(EXISTS "${MICROPY_LIB_BERKELEY_DIR}/btree/bt_close.c")
add_library(micropy_extmod_btree OBJECT
${MICROPY_LIB_BERKELEY_DIR}/btree/bt_close.c
${MICROPY_LIB_BERKELEY_DIR}/btree/bt_conv.c
@@ -96,3 +97,153 @@ if(EXISTS "${MICROPY_LIB_BERKELEY_DIR}/btree/bt_close.c")
"virt_fd_t=void*"
)
endif()
# Library for mbedtls
if(MICROPY_SSL_MBEDTLS)
add_library(micropy_lib_mbedtls INTERFACE)
set(MICROPY_LIB_MBEDTLS_DIR "${MICROPY_DIR}/lib/mbedtls")
target_include_directories(micropy_lib_mbedtls INTERFACE
${MICROPY_LIB_MBEDTLS_DIR}/include
)
target_sources(micropy_lib_mbedtls INTERFACE
${MICROPY_LIB_MBEDTLS_DIR}/library/aes.c
${MICROPY_LIB_MBEDTLS_DIR}/library/aesni.c
${MICROPY_LIB_MBEDTLS_DIR}/library/arc4.c
${MICROPY_LIB_MBEDTLS_DIR}/library/asn1parse.c
${MICROPY_LIB_MBEDTLS_DIR}/library/asn1write.c
${MICROPY_LIB_MBEDTLS_DIR}/library/base64.c
${MICROPY_LIB_MBEDTLS_DIR}/library/bignum.c
${MICROPY_LIB_MBEDTLS_DIR}/library/blowfish.c
${MICROPY_LIB_MBEDTLS_DIR}/library/camellia.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ccm.c
${MICROPY_LIB_MBEDTLS_DIR}/library/certs.c
${MICROPY_LIB_MBEDTLS_DIR}/library/chacha20.c
${MICROPY_LIB_MBEDTLS_DIR}/library/chachapoly.c
${MICROPY_LIB_MBEDTLS_DIR}/library/cipher.c
${MICROPY_LIB_MBEDTLS_DIR}/library/cipher_wrap.c
${MICROPY_LIB_MBEDTLS_DIR}/library/cmac.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ctr_drbg.c
${MICROPY_LIB_MBEDTLS_DIR}/library/debug.c
${MICROPY_LIB_MBEDTLS_DIR}/library/des.c
${MICROPY_LIB_MBEDTLS_DIR}/library/dhm.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ecdh.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ecdsa.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ecjpake.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ecp.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ecp_curves.c
${MICROPY_LIB_MBEDTLS_DIR}/library/entropy.c
${MICROPY_LIB_MBEDTLS_DIR}/library/entropy_poll.c
${MICROPY_LIB_MBEDTLS_DIR}/library/error.c
${MICROPY_LIB_MBEDTLS_DIR}/library/gcm.c
${MICROPY_LIB_MBEDTLS_DIR}/library/havege.c
${MICROPY_LIB_MBEDTLS_DIR}/library/hmac_drbg.c
${MICROPY_LIB_MBEDTLS_DIR}/library/md2.c
${MICROPY_LIB_MBEDTLS_DIR}/library/md4.c
${MICROPY_LIB_MBEDTLS_DIR}/library/md5.c
${MICROPY_LIB_MBEDTLS_DIR}/library/md.c
${MICROPY_LIB_MBEDTLS_DIR}/library/md_wrap.c
${MICROPY_LIB_MBEDTLS_DIR}/library/oid.c
${MICROPY_LIB_MBEDTLS_DIR}/library/padlock.c
${MICROPY_LIB_MBEDTLS_DIR}/library/pem.c
${MICROPY_LIB_MBEDTLS_DIR}/library/pk.c
${MICROPY_LIB_MBEDTLS_DIR}/library/pkcs11.c
${MICROPY_LIB_MBEDTLS_DIR}/library/pkcs12.c
${MICROPY_LIB_MBEDTLS_DIR}/library/pkcs5.c
${MICROPY_LIB_MBEDTLS_DIR}/library/pkparse.c
${MICROPY_LIB_MBEDTLS_DIR}/library/pk_wrap.c
${MICROPY_LIB_MBEDTLS_DIR}/library/pkwrite.c
${MICROPY_LIB_MBEDTLS_DIR}/library/platform.c
${MICROPY_LIB_MBEDTLS_DIR}/library/platform_util.c
${MICROPY_LIB_MBEDTLS_DIR}/library/poly1305.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ripemd160.c
${MICROPY_LIB_MBEDTLS_DIR}/library/rsa.c
${MICROPY_LIB_MBEDTLS_DIR}/library/rsa_internal.c
${MICROPY_LIB_MBEDTLS_DIR}/library/sha1.c
${MICROPY_LIB_MBEDTLS_DIR}/library/sha256.c
${MICROPY_LIB_MBEDTLS_DIR}/library/sha512.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_cache.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_ciphersuites.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_cli.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_cookie.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_srv.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_ticket.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_tls.c
${MICROPY_LIB_MBEDTLS_DIR}/library/timing.c
${MICROPY_LIB_MBEDTLS_DIR}/library/x509.c
${MICROPY_LIB_MBEDTLS_DIR}/library/x509_create.c
${MICROPY_LIB_MBEDTLS_DIR}/library/x509_crl.c
${MICROPY_LIB_MBEDTLS_DIR}/library/x509_crt.c
${MICROPY_LIB_MBEDTLS_DIR}/library/x509_csr.c
${MICROPY_LIB_MBEDTLS_DIR}/library/x509write_crt.c
${MICROPY_LIB_MBEDTLS_DIR}/library/x509write_csr.c
${MICROPY_LIB_MBEDTLS_DIR}/library/xtea.c
)
target_compile_definitions(micropy_lib_mbedtls INTERFACE
MBEDTLS_CONFIG_FILE="${MICROPY_PORT_DIR}/mbedtls/mbedtls_config.h"
)
list(APPEND MICROPY_INC_CORE
"${MICROPY_LIB_MBEDTLS_DIR}/include"
)
endif()
# Library for lwIP network stack
if(MICROPY_PY_LWIP)
add_library(micropy_lib_lwip INTERFACE)
set(MICROPY_LIB_LWIP_DIR "${MICROPY_DIR}/lib/lwip/src")
target_include_directories(micropy_lib_lwip INTERFACE
${MICROPY_LIB_LWIP_DIR}/include
)
target_sources(micropy_lib_lwip INTERFACE
${MICROPY_DIR}/shared/netutils/netutils.c
${MICROPY_LIB_LWIP_DIR}/apps/mdns/mdns.c
${MICROPY_LIB_LWIP_DIR}/core/def.c
${MICROPY_LIB_LWIP_DIR}/core/dns.c
${MICROPY_LIB_LWIP_DIR}/core/inet_chksum.c
${MICROPY_LIB_LWIP_DIR}/core/init.c
${MICROPY_LIB_LWIP_DIR}/core/ip.c
${MICROPY_LIB_LWIP_DIR}/core/ipv4/autoip.c
${MICROPY_LIB_LWIP_DIR}/core/ipv4/dhcp.c
${MICROPY_LIB_LWIP_DIR}/core/ipv4/etharp.c
${MICROPY_LIB_LWIP_DIR}/core/ipv4/icmp.c
${MICROPY_LIB_LWIP_DIR}/core/ipv4/igmp.c
${MICROPY_LIB_LWIP_DIR}/core/ipv4/ip4.c
${MICROPY_LIB_LWIP_DIR}/core/ipv4/ip4_addr.c
${MICROPY_LIB_LWIP_DIR}/core/ipv4/ip4_frag.c
${MICROPY_LIB_LWIP_DIR}/core/ipv6/dhcp6.c
${MICROPY_LIB_LWIP_DIR}/core/ipv6/ethip6.c
${MICROPY_LIB_LWIP_DIR}/core/ipv6/icmp6.c
${MICROPY_LIB_LWIP_DIR}/core/ipv6/inet6.c
${MICROPY_LIB_LWIP_DIR}/core/ipv6/ip6.c
${MICROPY_LIB_LWIP_DIR}/core/ipv6/ip6_addr.c
${MICROPY_LIB_LWIP_DIR}/core/ipv6/ip6_frag.c
${MICROPY_LIB_LWIP_DIR}/core/ipv6/mld6.c
${MICROPY_LIB_LWIP_DIR}/core/ipv6/nd6.c
${MICROPY_LIB_LWIP_DIR}/core/mem.c
${MICROPY_LIB_LWIP_DIR}/core/memp.c
${MICROPY_LIB_LWIP_DIR}/core/netif.c
${MICROPY_LIB_LWIP_DIR}/core/pbuf.c
${MICROPY_LIB_LWIP_DIR}/core/raw.c
${MICROPY_LIB_LWIP_DIR}/core/stats.c
${MICROPY_LIB_LWIP_DIR}/core/sys.c
${MICROPY_LIB_LWIP_DIR}/core/tcp.c
${MICROPY_LIB_LWIP_DIR}/core/tcp_in.c
${MICROPY_LIB_LWIP_DIR}/core/tcp_out.c
${MICROPY_LIB_LWIP_DIR}/core/timeouts.c
${MICROPY_LIB_LWIP_DIR}/core/udp.c
${MICROPY_LIB_LWIP_DIR}/netif/ethernet.c
)
list(APPEND MICROPY_INC_CORE
${MICROPY_LIB_LWIP_DIR}/include
)
endif()

128
extmod/font_petme128_8x8.h Normal file
View File

@@ -0,0 +1,128 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
*
* 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_STM32_FONT_PETME128_8X8_H
#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, 0x4f, 0x4f, 0x00, 0x00, 0x00, // 33=!
0x00, 0x07, 0x07, 0x00, 0x00, 0x07, 0x07, 0x00, // 34="
0x14, 0x7f, 0x7f, 0x14, 0x14, 0x7f, 0x7f, 0x14, // 35=#
0x00, 0x24, 0x2e, 0x6b, 0x6b, 0x3a, 0x12, 0x00, // 36=$
0x00, 0x63, 0x33, 0x18, 0x0c, 0x66, 0x63, 0x00, // 37=%
0x00, 0x32, 0x7f, 0x4d, 0x4d, 0x77, 0x72, 0x50, // 38=&
0x00, 0x00, 0x00, 0x04, 0x06, 0x03, 0x01, 0x00, // 39='
0x00, 0x00, 0x1c, 0x3e, 0x63, 0x41, 0x00, 0x00, // 40=(
0x00, 0x00, 0x41, 0x63, 0x3e, 0x1c, 0x00, 0x00, // 41=)
0x08, 0x2a, 0x3e, 0x1c, 0x1c, 0x3e, 0x2a, 0x08, // 42=*
0x00, 0x08, 0x08, 0x3e, 0x3e, 0x08, 0x08, 0x00, // 43=+
0x00, 0x00, 0x80, 0xe0, 0x60, 0x00, 0x00, 0x00, // 44=,
0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, // 45=-
0x00, 0x00, 0x00, 0x60, 0x60, 0x00, 0x00, 0x00, // 46=.
0x00, 0x40, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x02, // 47=/
0x00, 0x3e, 0x7f, 0x49, 0x45, 0x7f, 0x3e, 0x00, // 48=0
0x00, 0x40, 0x44, 0x7f, 0x7f, 0x40, 0x40, 0x00, // 49=1
0x00, 0x62, 0x73, 0x51, 0x49, 0x4f, 0x46, 0x00, // 50=2
0x00, 0x22, 0x63, 0x49, 0x49, 0x7f, 0x36, 0x00, // 51=3
0x00, 0x18, 0x18, 0x14, 0x16, 0x7f, 0x7f, 0x10, // 52=4
0x00, 0x27, 0x67, 0x45, 0x45, 0x7d, 0x39, 0x00, // 53=5
0x00, 0x3e, 0x7f, 0x49, 0x49, 0x7b, 0x32, 0x00, // 54=6
0x00, 0x03, 0x03, 0x79, 0x7d, 0x07, 0x03, 0x00, // 55=7
0x00, 0x36, 0x7f, 0x49, 0x49, 0x7f, 0x36, 0x00, // 56=8
0x00, 0x26, 0x6f, 0x49, 0x49, 0x7f, 0x3e, 0x00, // 57=9
0x00, 0x00, 0x00, 0x24, 0x24, 0x00, 0x00, 0x00, // 58=:
0x00, 0x00, 0x80, 0xe4, 0x64, 0x00, 0x00, 0x00, // 59=;
0x00, 0x08, 0x1c, 0x36, 0x63, 0x41, 0x41, 0x00, // 60=<
0x00, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x00, // 61==
0x00, 0x41, 0x41, 0x63, 0x36, 0x1c, 0x08, 0x00, // 62=>
0x00, 0x02, 0x03, 0x51, 0x59, 0x0f, 0x06, 0x00, // 63=?
0x00, 0x3e, 0x7f, 0x41, 0x4d, 0x4f, 0x2e, 0x00, // 64=@
0x00, 0x7c, 0x7e, 0x0b, 0x0b, 0x7e, 0x7c, 0x00, // 65=A
0x00, 0x7f, 0x7f, 0x49, 0x49, 0x7f, 0x36, 0x00, // 66=B
0x00, 0x3e, 0x7f, 0x41, 0x41, 0x63, 0x22, 0x00, // 67=C
0x00, 0x7f, 0x7f, 0x41, 0x63, 0x3e, 0x1c, 0x00, // 68=D
0x00, 0x7f, 0x7f, 0x49, 0x49, 0x41, 0x41, 0x00, // 69=E
0x00, 0x7f, 0x7f, 0x09, 0x09, 0x01, 0x01, 0x00, // 70=F
0x00, 0x3e, 0x7f, 0x41, 0x49, 0x7b, 0x3a, 0x00, // 71=G
0x00, 0x7f, 0x7f, 0x08, 0x08, 0x7f, 0x7f, 0x00, // 72=H
0x00, 0x00, 0x41, 0x7f, 0x7f, 0x41, 0x00, 0x00, // 73=I
0x00, 0x20, 0x60, 0x41, 0x7f, 0x3f, 0x01, 0x00, // 74=J
0x00, 0x7f, 0x7f, 0x1c, 0x36, 0x63, 0x41, 0x00, // 75=K
0x00, 0x7f, 0x7f, 0x40, 0x40, 0x40, 0x40, 0x00, // 76=L
0x00, 0x7f, 0x7f, 0x06, 0x0c, 0x06, 0x7f, 0x7f, // 77=M
0x00, 0x7f, 0x7f, 0x0e, 0x1c, 0x7f, 0x7f, 0x00, // 78=N
0x00, 0x3e, 0x7f, 0x41, 0x41, 0x7f, 0x3e, 0x00, // 79=O
0x00, 0x7f, 0x7f, 0x09, 0x09, 0x0f, 0x06, 0x00, // 80=P
0x00, 0x1e, 0x3f, 0x21, 0x61, 0x7f, 0x5e, 0x00, // 81=Q
0x00, 0x7f, 0x7f, 0x19, 0x39, 0x6f, 0x46, 0x00, // 82=R
0x00, 0x26, 0x6f, 0x49, 0x49, 0x7b, 0x32, 0x00, // 83=S
0x00, 0x01, 0x01, 0x7f, 0x7f, 0x01, 0x01, 0x00, // 84=T
0x00, 0x3f, 0x7f, 0x40, 0x40, 0x7f, 0x3f, 0x00, // 85=U
0x00, 0x1f, 0x3f, 0x60, 0x60, 0x3f, 0x1f, 0x00, // 86=V
0x00, 0x7f, 0x7f, 0x30, 0x18, 0x30, 0x7f, 0x7f, // 87=W
0x00, 0x63, 0x77, 0x1c, 0x1c, 0x77, 0x63, 0x00, // 88=X
0x00, 0x07, 0x0f, 0x78, 0x78, 0x0f, 0x07, 0x00, // 89=Y
0x00, 0x61, 0x71, 0x59, 0x4d, 0x47, 0x43, 0x00, // 90=Z
0x00, 0x00, 0x7f, 0x7f, 0x41, 0x41, 0x00, 0x00, // 91=[
0x00, 0x02, 0x06, 0x0c, 0x18, 0x30, 0x60, 0x40, // 92='\'
0x00, 0x00, 0x41, 0x41, 0x7f, 0x7f, 0x00, 0x00, // 93=]
0x00, 0x08, 0x0c, 0x06, 0x06, 0x0c, 0x08, 0x00, // 94=^
0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, // 95=_
0x00, 0x00, 0x01, 0x03, 0x06, 0x04, 0x00, 0x00, // 96=`
0x00, 0x20, 0x74, 0x54, 0x54, 0x7c, 0x78, 0x00, // 97=a
0x00, 0x7f, 0x7f, 0x44, 0x44, 0x7c, 0x38, 0x00, // 98=b
0x00, 0x38, 0x7c, 0x44, 0x44, 0x6c, 0x28, 0x00, // 99=c
0x00, 0x38, 0x7c, 0x44, 0x44, 0x7f, 0x7f, 0x00, // 100=d
0x00, 0x38, 0x7c, 0x54, 0x54, 0x5c, 0x58, 0x00, // 101=e
0x00, 0x08, 0x7e, 0x7f, 0x09, 0x03, 0x02, 0x00, // 102=f
0x00, 0x98, 0xbc, 0xa4, 0xa4, 0xfc, 0x7c, 0x00, // 103=g
0x00, 0x7f, 0x7f, 0x04, 0x04, 0x7c, 0x78, 0x00, // 104=h
0x00, 0x00, 0x00, 0x7d, 0x7d, 0x00, 0x00, 0x00, // 105=i
0x00, 0x40, 0xc0, 0x80, 0x80, 0xfd, 0x7d, 0x00, // 106=j
0x00, 0x7f, 0x7f, 0x30, 0x38, 0x6c, 0x44, 0x00, // 107=k
0x00, 0x00, 0x41, 0x7f, 0x7f, 0x40, 0x00, 0x00, // 108=l
0x00, 0x7c, 0x7c, 0x18, 0x30, 0x18, 0x7c, 0x7c, // 109=m
0x00, 0x7c, 0x7c, 0x04, 0x04, 0x7c, 0x78, 0x00, // 110=n
0x00, 0x38, 0x7c, 0x44, 0x44, 0x7c, 0x38, 0x00, // 111=o
0x00, 0xfc, 0xfc, 0x24, 0x24, 0x3c, 0x18, 0x00, // 112=p
0x00, 0x18, 0x3c, 0x24, 0x24, 0xfc, 0xfc, 0x00, // 113=q
0x00, 0x7c, 0x7c, 0x04, 0x04, 0x0c, 0x08, 0x00, // 114=r
0x00, 0x48, 0x5c, 0x54, 0x54, 0x74, 0x20, 0x00, // 115=s
0x04, 0x04, 0x3f, 0x7f, 0x44, 0x64, 0x20, 0x00, // 116=t
0x00, 0x3c, 0x7c, 0x40, 0x40, 0x7c, 0x3c, 0x00, // 117=u
0x00, 0x1c, 0x3c, 0x60, 0x60, 0x3c, 0x1c, 0x00, // 118=v
0x00, 0x1c, 0x7c, 0x30, 0x18, 0x30, 0x7c, 0x1c, // 119=w
0x00, 0x44, 0x6c, 0x38, 0x38, 0x6c, 0x44, 0x00, // 120=x
0x00, 0x9c, 0xbc, 0xa0, 0xa0, 0xfc, 0x7c, 0x00, // 121=y
0x00, 0x44, 0x64, 0x74, 0x5c, 0x4c, 0x44, 0x00, // 122=z
0x00, 0x08, 0x08, 0x3e, 0x77, 0x41, 0x41, 0x00, // 123={
0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, // 124=|
0x00, 0x41, 0x41, 0x77, 0x3e, 0x08, 0x08, 0x00, // 125=}
0x00, 0x02, 0x03, 0x01, 0x03, 0x02, 0x03, 0x01, // 126=~
0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, // 127
};
#endif // MICROPY_INCLUDED_STM32_FONT_PETME128_8X8_H

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