Noob: access to variable assigned Objects

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
nptech
Posts: 4
Joined: Sun Jun 20, 2021 5:21 am

Noob: access to variable assigned Objects

Post by nptech » Sun Jun 20, 2021 5:28 am

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...

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: Noob: access to variable assigned Objects

Post by Roberthh » Sun Jun 20, 2021 5:49 am

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.

stijn
Posts: 735
Joined: Thu Apr 24, 2014 9:13 am

Re: Noob: access to variable assigned Objects

Post by stijn » Sun Jun 20, 2021 7:47 am

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

nptech
Posts: 4
Joined: Sun Jun 20, 2021 5:21 am

Re: Noob: access to variable assigned Objects

Post by nptech » Sun Jun 20, 2021 8:49 am

Thank you for the example reply :)

Post Reply