Page 1 of 1

Call I2C to method of Micropython from C

Posted: Tue Mar 09, 2021 7:24 am
by Krasn4ck
Hi, again I have a doubt about how to implement some methods to use the I2C from C, this is as an educational purpose, currently I want to use the functions contained in the pyb_i2c.c file located in ports/stm32.

using these functions that are defined for micropython:

Code: Select all

{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&pyb_i2c_init_obj) },
{ MP_ROM_QSTR(MP_QSTR_mem_read), MP_ROM_PTR(&pyb_i2c_mem_read_obj) },
{ MP_ROM_QSTR(MP_QSTR_mem_write), MP_ROM_PTR(&pyb_i2c_mem_write_obj) 
In this case I want to use

Code: Select all

mp_call_function_n_kw
to call the functions, but I have not found any clear example of how to implement the call, it would be very helpful, some example of using this method.

Thank you very much in advance for any advice.

Re: Call I2C to method of Micropython from C

Posted: Thu Mar 11, 2021 6:00 am
by jimmo
Krasn4ck wrote:
Tue Mar 09, 2021 7:24 am
to call the functions, but I have not found any clear example of how to implement the call, it would be very helpful, some example of using this method.
It's worth searching the codebase to find other places that use it, but the general idea is:

But for a specific example, let's say you wanted to the equivalent of

foo(1, "hello", obj, thing=True)

Then it would look something like:

Code: Select all

mp_obj_t args[3 + 2*1];        // where N is the number of positional args, plus twice the number of keyword args.
args[0] = MP_NEW_SMALL_INT(1);
args[1] = MP_QSTR_hello;
args[2] = obj;
args[3] = MP_QSTR_thing;
args[x+1] = mp_obj_new_bool(True);
mp_call_function_n_kw(foo_obj, 3, 1, args);