0

I am trying to create a digitalio.DigitalInOut object in a class in CircuitPython. The pin used is defined as a parameter in the class (pin_number). Is there a way to do it other than with exec()? My attempt at doing this is below, and, as you can see, it is very messy (and does not work due to problems with exec() and classes).

exec("self.pin = digitalio.DigitalInOut(board.GP"+str(pin_number)+")", globals(), locals())

In MicroPython, I just did this:

self.pin = Pin(pin_number, Pin.OUT)

If possible, I would like to do something similar with CircuitPython, so that my main program to be compatible with either MicroPython or CircuitPython depending on which file you import from it (my main code looks something like the below).

b1 = led(pin_number=1)
Llamax
  • 313
  • 2
  • 13

1 Answers1

0

Use getattr(); e.g.,

self.pin = getattr(board, 'GP1')
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
  • 1
    Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Aug 14 '22 at 08:13