Worksheet 20
(Improvements to make maintenance easier)This should make the tuning of delays and motor speeds for a better square, much simpler.
Your code might look something like this:
This looks like a long, impenetrable chunk of code,
with numbers up and down it that control every movement.
1) Use functions to reduce repeats.
A "function" is a piece of code, that is gathered together, and given a name.
Simply gather up the bits of program that are repeated, and give each of them a name.
This bit does a side:
So put it into a function which we will call 'side'
put it at the top of your code, but below the imports
- Notice that you have to indent each line of the function definition
You can call up this function later in your program with the line:
Now do the same for the corners
- Define a function called 'corner', at the start of your program, just after the imports
- Put the 5 lines that do a corner into it. (Don't forget the indenting)
- Replace all the corners in your program with the line:
This means that the only place where there are
leftmotor , rightmotor, or utime commands
is inside the functions
2) Use variables for the delays and speeds.
The code above uses a spin delay of 0.4 for a right angle,
and a straight-line delay of 1.8 for the side length.
If you hadn't used functions, then to adjust all the corners,
you would have had to change all 3 instances.
Use a variable "spinTime" instead of 0.4
This means you can put all the adjustments together at the top of the program.
You create your variables by simply setting them to their values
Do this before they are used - you can put them as the very first part of your code
In the example above, I have used more meaningful names than "SpinDelay" and "SideDelay"
but you can use names that are meaningful to you.
lspeed and rspeed are different to make it go in a straight line
The functions now look something like this:
Now create a corner function to use speed variables, and the Angle variable.
For spin motor speeds you can use
lspeed and -rspeed.
Or you could have 2 more variables for the speeds while spinning.
Extension: Use a 'For loop' to further reduce repetition
You would only call side() and corner() once inside the loop
Hint: The clip below will print out "Hello" 4 times: