id from Pin object

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
bitrat
Posts: 41
Joined: Fri Jul 26, 2019 4:13 am

id from Pin object

Post by bitrat » Fri Oct 08, 2021 6:31 pm

I seem to recall that the interrupt handler for edges on pins used to take a pin id (typically an int in my case) as an argument, but apparently it now takes the pin object, 'Pin(10)', or whatever...

I've searched in vain for a way to get the id from the Pin object. Do I need to parse the string rep??

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

Re: id from Pin object

Post by pythoncoder » Sat Oct 09, 2021 9:10 am

On a Pyboard if p is a Pin instance p.name() returns the CPU pin name:

Code: Select all

>>> import machine
>>> p = machine.Pin('Y1', machine.Pin.IN)
>>> p.name()
'C6'
Alternatively you could maintain a dict of names:

Code: Select all

pins = {}
name = 'Y1'
p = machine.Pin(name, machine.Pin.IN)
pins[id(p)] = name
which would enable retrieval of the name you used to instantiate the pin.
Peter Hinch
Index to my micropython libraries.

bitrat
Posts: 41
Joined: Fri Jul 26, 2019 4:13 am

Re: id from Pin object

Post by bitrat » Sun Oct 10, 2021 8:09 pm

Hi Peter,

thanks for this. Unfortunately, on my board, there's no

Code: Select all

Pin.name()
The dictionary approach is against my principles, in that it introduces more than one record of the same information and moves locally accessible data into a global scope.

I'm using ints as pin names (eg: 'GPIO14' is 14). I'll investigate when I have time, but from memory the outdated MP I was using earlier was passing that int to the pin's interrupt handler callback, not the whole Pin object.

It seems reasonable to pass the object, but it's extremely annoying to have no way to easily extract the integer. The object's __str__() method prints, for example, 'Pin(14)' where I just want 14. I use the one liner:

Code: Select all

 id = int(''.join(char for char in s if char.isdigit()))
to get WIW, but ...meh. None of this is happening in the actual interrupt handler (which just schedules a user space handler) but it's the kind of finagling that sucks cycles and introduces bugs.

All I'm doing with the pin identifier is sending it to another device in a UDP message, and I just want the number of the pin, not the whole string.

I'm planning to build MP from source so I'll probably add a method for this in C. Maybe you'll get a PR for it. :-)

Post Reply