Entry point for hard realtime C statemachine

C programming, build, interpreter/VM.
Target audience: MicroPython Developers.
Post Reply
flindt
Posts: 11
Joined: Tue Jun 20, 2017 8:51 am

Entry point for hard realtime C statemachine

Post by flindt » Tue Oct 31, 2017 9:41 am

We've implemented a simple protocol in micropython delivering input and output values for a fairly complex motordrive with feedback on current and position.

Micropython works great for the ease and speed of implementation, however the feedback loop we have for the motor is way too slow. Currently our loop time is around 0.5 ms and we need to reduce that at least 10-50 times.

Now it seems we have at least two options.

a) reimplement everything in C.
b) keep the micropython for the protocol part and add a fast control loop in C.

For know option b is the way we are going. Currently we have a custom module implemented that can deliver an array of inputs and outputs to a C function.
The question I am facing is where would be a good place to hook up a C statemachine, so it will have higher priority than the micropython interpreter?

I have only just started looking into the code and any pointers would be greatly appreciated :)

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Entry point for hard realtime C statemachine

Post by pythoncoder » Thu Nov 02, 2017 8:19 am

You haven't told us what platform you're using. Assuming the Pyboard, there are options besides writing a C module. MicroPython has support for inline ARM Thumb assembler http://docs.micropython.org/en/latest/p ... index.html. This provides an easy way to implement small amounts of code which need to run at the highest possible speed.

There are techniques for writing MicroPython code intended for high performance. These are described here http://docs.micropython.org/en/latest/p ... ython.html. But given the level of performance you need in this loop I think you'll need to resort to assembler or C.

Your post hints at a requirement for concurrency. Normal approaches (uasyncio, _thread) would be too slow.

The idea of a C state machine running in the background is outside of my experience; but I think it's impractical. The MicroPython VM can run for a few ms when doing garbage collection so the SM would halt for the duration unless it ran in an interrupt context (hardware interrupts do pre-empt garbage collection).

My approach would be to have the fast code triggered by a timer interrupt, which would be my first port of call if I were developing this. The fast code could be an assembler function or a C module.
Peter Hinch
Index to my micropython libraries.

Post Reply