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)

1 Answer 1

1

Use getattr(); e.g.,

self.pin = getattr(board, 'GP1')
Sign up to request clarification or add additional context in comments.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.