Learn to code in Python - Lesson 1


This series of lessons is aimed at those who want to program the hub in Python, and have done some programming in the past, maybe with Scratch, and understand some of the concepts such as variables iteration and branching.

For this lesson I will be using the basic build of Tricky, with 2 drive motors and the distance sensor connected as per the App instructions.



For this program I want Tricky to be able to roam around the room on his own and avoid objects.

The algorithm (sequence of steps) I came up with was:

    1) Move forward

    2) If Tricky detects an object, stop, go backwards a little, then turn to the right by 90ish degrees 

    3) Repeat steps 1 & 2


Initially I coded this in Python, but as this is supposed to be a ‘lesson’ I have also coded in Scratch below. Make sure you understand how this works before looking at the Python code (maybe enter the blocks into the app and run it!)



The following code in Python should give almost the same actions as above (I think the angle that Tricky turns right is slightly different).


Type this code in and run in – there is no need to type the purple text, this is just to help you understand the code better. (Typing the code will help you to understand how it works.)

If Tricky does not move as intended and the power button on the hub flashes red for a second or so, it means there is an error.  At the bottom of the App screen click on the following handle and drag it up to reveal the console.


The text in red tells you what the error is, but look for ‘line xx’  (line 22 in the screenshot below).  This is the line of code where the error is, or in some cases it might be on the line before.

Using this information I looked at line 22, and can see that I have typed QQQwhile, instead of while.  Python does not have a QQQwhile command, so has given a Syntax Error.

 


If after a few attempts (do not give up too soon!) you cannot get the code to work, the file can be downloaded here.




Comments

  1. UPDATE: When creating this code, I used trial and error to work out the value of the turn on line 28 (10, "cm", 100). On my light piled carpet this turns about 45 degree. However, trying this on a hard floor, the angle of turn was about 90 degrees. So if you have hard floors and want 45 degrees, as initially intended, use 5 instead of 10 in line 28 - (5, "cm", 100). The new wheels are great on a hard surface but the curve across the width of the tyre means that they sink into the pile of the carpet causing a lot of resistance.

    ReplyDelete

Post a Comment