Python while loops – Driving lesson #5

  • Pre-driving checks

If you are here you should be able use an editor to write Python code to control  your Pi-Car and understand what we mean when we talk about constants, variables and print statements. If not by all means have a go at this lesson but if you get stuck try Driving Lesson#1Driving Lesson#2Driving Lesson#3 or Driving Lesson#4.

  • What’s in this driving lesson?

In this lesson we will look at another type of logical instruction and how we can use it to affect the ‘flow’ of the program. The instruction we will look at is called a ‘while loop’. This will help greatly in helping us to make the Raspberry Pi repeat instructions rather than have to continually write them out.

As with the other lessons you may get to the end and not realise how powerful the instruction is but try and think of examples in bigger programs how it could be used.

  • A little theory

Unless you already know what a while instruction is you probably do need to read the theory section as it takes a little bit of time to get used to it. However, you can of course jump into the driving part and then come back to review this if necessary.

while instructions (also known as ‘while loops’)
In the real world we sometimes need to repeat the same task over and over again a number times until it’s finished.

An example of this is a race where we have to drive around a track a fixed number of times to complete it. Sometimes we will count down the number of laps completed i.e count down from 10 taking 1 off each time (10,9,8 etc) until we get to 0 and are finished.

Other times we will count up (1, 2, 3 etc) once each lap is finished, until we reach the number of laps to complete the race. We may also say we are on the third lap once we start it but do not count it until that lap is completed.

We may also want to do things whilst a certain situation is true e.g switch on windscreen wipers which will then continue to wipe whilst they are turned on, (or if you have sensors until  they go of automatically as there’s no longer any rain). Another example is when we start a car, the engine will continually run whilst the key is turned in the ignition.

In a program we also want to be able to do this sort of thing. The above examples are perfect examples of while loops in a program. What a while loop lets us do is tell the Raspberry Pi to repeat a certain block of instructions either a certain number of times or whilst a certain thing is true – such as the value of a variable currently being a certain value.

  • Lets get driving…

The first thing we have to do before we start racing is to start the engine. Once you have done that you can then race the car around the track. So how can we do this in a python program?

A while loop lets us tell the Raspberry Pi to keep on repeating an instruction or set of instructions. It will go through the block of instructions in order and then start at the beginning of the block again.

We can also tell the Raspberry Pi to only repeat the instructions if a certain thing is true, a bit like we did in the if statement in the last lesson. The way we write this in the Python file is as follows:

engineStarted = "on"

while engineStarted == "on":
  print "Pi-Car engine running"
  time.sleep(2)

You can see above that we write the word ‘while’ followed by something that we want to check. If it is correct – this is also called being ‘true’ – the indented instructions below it will be repeated again and again. As with the if statement you can make the instructions indented by just pressing the tab key at the start of the line.

In the example above the variable engineStarted is being checked as to whether it is equal to on. Remember that the == symbol means ‘equal to’ and note how it is two equal signs rather than one. If engineStarted is equal to ‘on’ then the Raspberry Pi will execute the instructions below it – meaning it will print out some text and then wait for 2 seconds. Also notice that you need to put a colon ‘:’ symbol after the check – you have to do this, it is what the Python language accepts to make the Raspberry Pi process the instruction correctly.

If you run this program you will see it continually printing out “Pi-Car engine running” with a 3 second wait. The Raspberry Pi will continue to do this again and again and again. This is because in the code we wrote engineStarted will always be equal to “on” as this is what we set it to at the top of the file and we don’t change it anywhere else.

This does give us a bit of a problem in that we want to do something else rather than just watch the Raspberry Pi print out a statement forever. To stop the program and the while loop running you can press CTR + D or CTR + C.

So now we understand the while loop lets make it do something useful. We want it to make the Pi-Car do a certain number of laps before stopping. To do this we can combine the while statement with the if statement that we learnt in the last lesson.

engineStarted = "on"
lapsCompleted = 0

while engineStarted == "on":
       GPIO.output(FORWARDS, ON)
       GPIO.output(RIGHT, ON)
       print("Engine running, Pi-Car should be driving in a circle")
       if (lapsCompleted < 10) :
              print("Staring a new lap, laps completed",lapsCompleted)
              time.sleep(3)
              lapsCompleted = lapsCompleted + 1
       else :
              print("Laps done = ",lapsCompleted," race finished lets turn off the Pi-Car")
              GPIO.output(FORWARDS,OFF)
              GPIO.output(RIGHT,OFF)
              GPIO.cleanup()
              engineStarted = "off"

The main thing to discuss here is how we have added the if statement in the indented code after the while statement. This means that every time the Raspberry Pi goes through all of the code in the while loop it will evaluate the line

if (lapsCompleted < 10) :

We have already defined the lapsCompleted variable earlier in the program to a value of 0. We want to check on each loop that the value of lapsCompleted is not over a certain amount – we have chosen 10 here. In the last lesson we used the > symbol which means ‘more than’. Here we are using the opposite which means ‘less than’.

To make this while loop work we also have to increase  the lapsCompleted each time by one, if we didn’t it would mean that the loop would go on forever as before. This is referred to in programming as an infinite loop and can happen surprisingly often and easily.

The way we increase the number of laps completed is as follows:

lapsCompleted = lapsCompleted + 1

Notice that even though the code we have looked at so far does check for the number of laps completed, it does not actually do anything to stop the while loop. This is done in the else section:

else :
              print("Laps done = ",lapsCompleted," race finished lets turn off the Pi-Car")
              GPIO.output(FORWARDS,OFF)
              GPIO.output(RIGHT,OFF)
              GPIO.cleanup()
              engineStarted = "off"

You can see us here turning off the GPIO pins and also setting the enigneStarted variable to another value. This means that when the while loop next runs and checks whether engineStarted is equal to “on”, it will calculate that it is not – and therefore would not go through the indented code beneath it but would move onto the next set of instructions.

The full set of code should now look like the following:

import time, RPi.GPIO as GPIO

ON = 1
OFF = 0
FORWARDS=12
BACKWARDS=11
LEFT=13
RIGHT=15
PETROL_USED_PER_MOVE=20

#variables
petrolLeft=50
engineStarted = "on"
lapsCompleted = 0

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(FORWARDS,GPIO.OUT)
GPIO.setup(BACKWARDS,GPIO.OUT)
GPIO.setup(LEFT,GPIO.OUT)
GPIO.setup(RIGHT,GPIO.OUT)

while engineStarted == "on":
       GPIO.output(FORWARDS, ON)
       GPIO.output(RIGHT, ON)
       print("Engine running, Pi-Car should be driving in a circle")
       if (lapsCompleted < 10) :
              print("Staring a new lap, laps completed",lapsCompleted)
              time.sleep(3)
              lapsCompleted = lapsCompleted + 1
       else :
              print("Laps done = ",lapsCompleted," race finished lets turn off the Pi-Car")
              GPIO.output(FORWARDS,OFF)
              GPIO.output(RIGHT,OFF)
              GPIO.cleanup()
              engineStarted = "off"

If you run the program you will now see that 10 laps are completed before the program exits the while loop as the engineStarted variable is changed. Pi-Car then stops. When you run the code change some of the variables – like the number of laps and see what happens.

  • Driving Lesson review

while statements:

How to use:

1. Use the word ‘while’ followed by a statement. This statement should be evaluated and if correct, (or true) the indented lines of code below it should be executed one by one. When it reaches the last one, it will check whether the while statement is still true and then execute each line one by one:

engineStarted = "on"
lapsCompleted = 0

while engineStarted == "on":
       GPIO.output(FORWARDS, ON)
       GPIO.output(RIGHT, ON)
       print("Engine running, Pi-Car should be driving in a circle")
       if (lapsCompleted < 10) :
              print("Staring a new lap, laps completed",lapsCompleted)
              time.sleep(3)
              lapsCompleted = lapsCompleted + 1
       else :
              print("Laps done = ",lapsCompleted," race finished lets turn off the Pi-Car")
              GPIO.output(FORWARDS,OFF)
              GPIO.output(RIGHT,OFF)
              GPIO.cleanup()
              engineStarted = "off"

2. The thing you are checking will normally be a variable on the left compared to a value, or the value of a variable, on the right hand side.

Why do they help?

1. While loops are really helpful for not having to write extra lines in your program yourself. The while loop will do this for you and will also check on each loop whether it should continue based on.

  • Gotcha’s

In any engineering things rarely work first time so don’t worry. Hopefully the list below will help. If not email us at info@pi-cars.com and leave a comment providing your code and what you tried to do, the solution will be obvious as soon as you see it!

  1. Remember after an while statement you need to have a colon and then indent the lines you want the Raspberry Pi to execute if the statement is true. You can indent by pressing the tab at the start of the line.
  2. Remember that you need to run Python (or idle 3) as sudo to interact with the GPIO pins.
  3. When you are checking a variable is the same as a string make sure you put  the speech marks around the things you are comparing. For example engineStarted == “on” is correct engineStarted == on will not be correct.

Next -> Driving Lesson #6 More logic – Emergency Stops and procedures

Previous -> Driving Lesson  #4 – Python If statements

PDF Version

PDF version of this article – Python while loops – Driving lesson #5 _ Pi-Cars

Advertisements

About Barnaby Kent

http://www.myactionreplay.com
This entry was posted in Uncategorized, Under the bonnet and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s