How to know if I am allocating memory?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
Duramaximizer
Posts: 12
Joined: Wed Mar 25, 2020 8:53 pm

How to know if I am allocating memory?

Post by Duramaximizer » Wed May 06, 2020 2:34 pm

Hello,

I have a very simple sleep function which is giving me a memory error, memory allocation failed heap if locked. I have the emergency allocation buffer enabled to get the error information.

function here:

Code: Select all

   def _sleep(t):
            	stm.mem32[stm.PWR + stm.PWR_CSR] |= 1 << 8  # setup wake on rising edge PA0 (PushButton)
            	machine.deepsleep()
I've tested using micropython.heap_lock() and manually doing these and it works. Is there a better way to figure out if you are allocating memory? It's complaining about the stm.mem32 line in particular.

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: How to know if I am allocating memory?

Post by dhylands » Wed May 06, 2020 4:54 pm

If a number can be represented as a31-bit signed number, then no memory allocation is required. However, if the number doesn't fit, then a memory allocation is required to allocate a large int.

This failure could be happening with either the address or the value. It looks like none of the PWR registers use any of the upper bits so you should be ok on that front.

It looks like stm.PWR has the value 1073770496 (0x40007000). The largest positive value that can be stored in a 31-bit signed number is 0x3FFFFFFF which is what's probably causing the problem.

You should be able to do something like add:

Code: Select all

PWR_CSR = cosnt(stm.PWR + stm.PWR_CSR)
outside your function (the const bit is optional) and then use

Code: Select all

stm.mem32[PWR_CSR]
inside your function to move the memory allocation to where the declaration occurs rather than inside your function.

Post Reply