Can i write to a binary file in a callback

The official pyboard running MicroPython.
This is the reference design and main target board for MicroPython.
You can buy one at the store.
Target audience: Users with a pyboard.
Post Reply
rhubarbdog
Posts: 168
Joined: Tue Nov 07, 2017 11:45 pm

Can i write to a binary file in a callback

Post by rhubarbdog » Wed Mar 06, 2019 2:02 pm

Code: Select all

import pyb

file_ = open('somefile.bin', 'w')
sensor = pyb.ADC('X1')

def timer_cb(_):
    global file_
    global sensor
    file_.write(sensor.read())

Is the above callback legal?
Sorry the code is incomplete and may contain bugs I'm on my phone.

Hanilein
Posts: 29
Joined: Thu Jul 12, 2018 11:40 am
Location: Christchurch, New Zealand

Re: Can i write to a binary file in a callback

Post by Hanilein » Wed Mar 06, 2019 8:16 pm

Without having tested this particular code, most likely not!
You cannot access the heap in an Interrupt Service Routine (AKA callback).
Even though you may write innocent code in first instance, under the hood the system may try to allocate memory, and face-plants.

As an example, if you add values to a global integer(!) variable, that works fine in an ISR. But as soon as you reach the limit of the underlying hardware architecture (here 32 bit, limiting signed int to +2147483647), the systems tries to allocate memory to represent the number!

Which means, after days, weeks or months your program eventually fails.

But there is a solution: use the scheduler. In your ISR you invoke the scheduler with the address of your callback function. As soon as the ISR terminates, the scheduler will call the callback, and there you can access the heap.

The time it takes the system to switch from the ISR to your callback on a pyboard running with 168MHz is ~35µs - if no other IRQ is pending. That is usually fast enough.

Have a look at the documentation: https://docs.micropython.org/en/latest/ ... rules.html
Ivo Gorny

Post Reply