Learn to code in Python - Lesson 2 (Plus build instruction)

 In part 1 we developed a simple program so that Tricky could roam around a room and avoid objects. Although this simple program works well for obstacles that are directly in front, objects at either side are not always detected. What would make this better would be to use 3 sensors one for left, one for front and one for right.

The Robot Inventor kit only has the one sensor. But what if we use one sensor and move it, left to right a bit like a RADAR sweep?

In this lesson we will add the RADAR to the front of Tricky, and then program it to detect obstacles from a wider area.


Tricky RADAR


To download the build instructions to add the RADAR to Tricky, click here.


The Python Code

My initial thoughts for an algorithm (step by step instructions) were:

1) Move sensor forward. If obstacle detected turn Tricky 180 degree and continue

2) Move the sensos to the left. If an obstacle is detected turn Tricky right by 30 degrees and continue

3) Move the sensor to the right. If an obstacle is detected turn Tricky left by 30 degrees and continue

4) Go back to step 1

 

Once I started to code, it occurred to me that to move the sensor from the left to the right, it has to pass through facing front, so it might as well detect for obstacle again at that point. My revised algorithm is:

1) Move sensor forward. If obstacle detected turn Tricky 180 degree and continue

2) Move the sensos to the left. If an obstacle is detected turn Tricky right by 30 degrees and continue

3) Move sensor forward. If obstacle detected turn Tricky 180 degree and continue

4) Move the sensor to the right. If an obstacle is detected turn Tricky left by 30 degrees and continue

5) Go back to step 1


The code is very similar to Lesson 1, so I have not done a Scratch program. Look at lesson 1 if you need any help or ask questions in the comments.

 

If you type this code in line by line you will start to understand and learn Python. However if you cannot get it to work, but have tired several times, then you can dowenload the code here.


(Anyone with experience of coding/Python will probably think that this code could be a lot more concise with the use of functions/procedures. I have purposely avoided their use as I wanted to keep the programming concepts simple. If you understand procedures and functions, please feel free to refine!)

Depending on the surface Tricky is driving on, you might need to change some of the numbers – such as the distance for detection, the speed or the turn angle. Experiment and find numbers that work for your environment.

If you are running Tricky on a carpet and find that he is dragging and drifting, please see my post on doubling up the drive wheels to reduce the drag - click here.



Comments