Page 1 of 1

Noob: access to variable assigned Objects

Posted: Sun Jun 20, 2021 5:28 am
by nptech
say I:

motor_forward = machine.Pin...
motor_backward = machine.Pin....


& I wish to create 2 routines

def forward():

backward():

is it possible to initialise the pin's within the main body of code & gain access to them within my sub routines...?

or

is it possible to initialise the pins within there own routine e.g. def init():, run the init routine and still gain access to the pins via
other routines...

Re: Noob: access to variable assigned Objects

Posted: Sun Jun 20, 2021 5:49 am
by Roberthh
If you declare these pin objects as global in the functions, you can access them within the functions. For the declaration, just write:

global motor_forward, motor_backward

That's a Python property.

Re: Noob: access to variable assigned Objects

Posted: Sun Jun 20, 2021 7:47 am
by stijn
You can also pass things around as arguments:

Code: Select all

def forward(motor):
  motor.high()
  motor.low()
  
def backward(motor):
  motor.low()
  motor.high()

def main()
  motor_forward = machine.Pin...
  motor_backward = machine.Pin....
  forward(motor_forward)
  backward(motor_backward)
which has the benefit it keeps on working when you add more motors

Re: Noob: access to variable assigned Objects

Posted: Sun Jun 20, 2021 8:49 am
by nptech
Thank you for the example reply :)