Skip to content

Commit da1c80d

Browse files
peterhinchpfalcon
authored andcommitted
docs/reference/isr_rules.rst Add tutorial on use of micropython.schedule().
1 parent cc7fece commit da1c80d

1 file changed

Lines changed: 21 additions & 0 deletions

File tree

docs/reference/isr_rules.rst

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ This summarises the points detailed below and lists the principal recommendation
2121

2222
* Keep the code as short and simple as possible.
2323
* Avoid memory allocation: no appending to lists or insertion into dictionaries, no floating point.
24+
* Consider using ``micropython.schedule`` to work around the above constraint.
2425
* Where an ISR returns multiple bytes use a pre-allocated ``bytearray``. If multiple integers are to be
2526
shared between an ISR and the main program consider an array (``array.array``).
2627
* Where data is shared between the main program and an ISR, consider disabling interrupts prior to accessing
@@ -158,6 +159,26 @@ On platforms with hardware floating point (such as the Pyboard) the inline ARM T
158159
round this limitation. This is because the processor stores float values in a machine word; values can be shared
159160
between the ISR and main program code via an array of floats.
160161

162+
Using micropython.schedule
163+
~~~~~~~~~~~~~~~~~~~~~~~~~~
164+
165+
This function enables an ISR to schedule a callback for execution "very soon". The callback is queued for
166+
execution which will take place at a time when the heap is not locked. Hence it can create Python objects
167+
and use floats. The callback is also guaranteed to run at a time when the main program has completed any
168+
update of Python objects, so the callback will not encounter partially updated objects.
169+
170+
Typical usage is to handle sensor hardware. The ISR acquires data from the hardware and enables it to
171+
issue a further interrupt. It then schedules a callback to process the data.
172+
173+
Scheduled callbacks should comply with the principles of interrupt handler design outlined below. This is to
174+
avoid problems resulting from I/O activity and the modification of shared data which can arise in any code
175+
which pre-empts the main program loop.
176+
177+
Execution time needs to be considered in relation to the frequency with which interrupts can occur. If an
178+
interrupt occurs while the previous callback is executing, a further instance of the callback will be queued
179+
for execution; this will run after the current instance has completed. A sustained high interrupt repetition
180+
rate therefore carries a risk of unconstrained queue growth and eventual failure with a ``RuntimeError``.
181+
161182
Exceptions
162183
----------
163184

0 commit comments

Comments
 (0)