Page 1 of 1

Creating/accessing Timer and UART from a C module

Posted: Sun Jan 24, 2021 6:39 pm
by mark_melvin
Hi There,

I have been using micropython for quite some time (from Python) and have written some simple C modules in the past but I am trying to use micropython in a new way and could use some advice.

I am wrapping an existing bunch of embedded C code that communicates over a serial port and requires both a UART and a Timer to function. I ported the entire library to pure micropython and despite hours of work and many refactors it simply is not fast enough. I can't get the scheduling right to service the serial data fast enough.

So now I am attempting to reuse the entire existing C code and wrap it in a micropython module. As I said, it requires the use of a high-speed timer as well as a UART. It needs to respond to the interrupts of both and push data through some internal state machines, and it interacts with the user code via a couple of callbacks.

I see two options:
  • Have the user create the Timer and UART in Python and pass them into the C API (my preference)
  • Just create the Timer and UART instances I need in C (and maybe have the user pass in the pin names and timer number to use?)
My problem in both cases is that it looks like there is no generic "Timer" module/classes in C. All of the code seems to be port-specific. I want my module to be independent of the specific micropython "port" (i.e. I don't want to #include code from the STM32 port, and I don't want to write a version of my module for every port either).

For the second case where I create the objects in C, I thought I could use the C API to import pyb.Timer (via `mp_module_get`) and create objects that way but I don't see any examples of anyone else doing this so perhaps that is a dumb idea?

What do other developers do in this case?


Re: Creating/accessing Timer and UART from a C module

Posted: Sun Jan 24, 2021 10:24 pm
by mark_melvin
Actually, I may have finally got my code balanced enough that the pure uPython implementation works. I was trying to use asyncio for everything, but converting my main serial receive to a UART.irq callback it seems to be running smoothly now. I'll continue down this path for the time-being. But being able to use the existing C library without having to maintain my own uPython port of it in parallel would be nice so my original questions still stand.