Page 1 of 1

Can i write to a binary file in a callback

Posted: Wed Mar 06, 2019 2:02 pm
by rhubarbdog

Code: Select all

import pyb

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

def timer_cb(_):
    global file_
    global sensor

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

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

Posted: Wed Mar 06, 2019 8:16 pm
by Hanilein
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: ... rules.html