top of page
Search
Writer's pictureBen

Tales from the Slack: Q&A

Ben asked a question about using DEF in Python. I thought the conversation was worth adding to the blog for everybody to see...


BEN: I'm working on some code for the driving controls. Could you send us some of that code where you say the distance?

KEVIN: Remember we're just faking everything right now. But if I understand your question, I think you're talking about a DEF that receives a variable? I'll spell it out here for everybody.


A "def" is chunk of repeatable code. If you find that your code is going to be doing the same thing over and over, you turn it into a def.In the case of the code I wrote during the meeting, my defs were stupid placeholders.


def goForward20cm():

print("I am going forward 20cm")


The intention was to one day replace them with actual working code, but for now the print statement is enough to tell me what the program wants to do until I have a real robot. One day that same code may look like this:


def goForward20cm():

drive("MotorA", 100, 20) # I made this up

drive("MotorB", 100, 20) # I made this up too

drive("MotorA", 0, 0)

drive("MotorB", 0, 0)


Now...

What I think you're looking for is a bit where you offer the def a variable to do something different with each time.A much more useful def would be: def goForward(distance):

print("I am going forward ", distance, "cm") Now my def can do more than go forward 20cm... It can go forward any number I pop into the program: goForward(10)

goForward(50)

goForward(1000)

goForward(-5) Now... remember this line? drive("MotorA", 100, 20) # I made this up My assumption is that when it comes time to control the actual motors of the actual robot, the Robot will have its own set of defs that we need to call, and each def will have a set of expectations. Maybe:

  • name of Port (what the motor is plugged into)

  • Speed of motor

  • time to run motor

  • number of revolutions

(FYI: I don't know what these are yet, but ... I just did a 5 second google search and found the answer here: https://www.dexterindustries.com/BrickPi/brickpi-tutorials-documentation/program-it/python/brickpi-python-idle/ (You can pop in there yourself if you're curious but it's not important right now.)


Whatever the BrickPi code is, that's the final part of the interface. For our sake we'll want something like:


def drive(port, speed, time)


That def will communicate with the brickPi, and you will never have to think about it again. All YOU have to do is communicate with this def.


if command == "go":

drive(MotorA, 100, 20) # drive MotorA at speed 100 for 20 seconds


It doesn't matter if whatever is in the drive def is 1000 lines long - we don't have to worry about that (well, one of us does to set up the communication)... we make our own defs to make communicating with the robot easier for us.

2 views0 comments

Recent Posts

See All

Comments


bottom of page