Lab 4: Understanding Your Code

Purpose

I noticed that some people are struggling with understanding what the code does. So we will spend some time to go through this.

Learning Goals

After completing this exercise, you should be able to

  • understand the order in which lines of the code are executed when running the program
  • differentiate between initial declarations, measurement function, and measurement loop.
  • describe what is happening inside the measurement loop
  • be able to place the additional lines of code in the correct location of the program

Initial Program

You were provided with this initial program:

We can split this program into four parts:

  1. Initialization: The first part of the program, loads the require Python modules and sets up the GPIO to communicate with the sensor.
  2. Measurement Function:The second part of the code defines a function that is later executed to conduct the measurements. This function contains all the steps necessary to conduct a single distance measurement.
  3. Measurement Loop: After the program is initialized and the measurement function is defined, we can conduct measurements. This is done in a loop to perform multiple consecutive measurements.
  4. Shut down: The final part of the code, de-initializes the GPIO so that this resource is being released rather than abruptly terminated when the program ends.

Task:

Go through the program below and identify each of the four program sections:

import RPi.GPIO as GPIO
import time
 
#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)
 
#set GPIO Pins
GPIO_TRIGGER = 21
GPIO_ECHO = 20
 
#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
 
def distance():
    # set Trigger to HIGH
    GPIO.output(GPIO_TRIGGER, True)
 
    # set Trigger after 0.01ms to LOW
    time.sleep(0.00001)
    GPIO.output(GPIO_TRIGGER, False)
 
    StartTime = time.time()
    StopTime = time.time()
 
    # save StartTime
    while GPIO.input(GPIO_ECHO) == 0:
        StartTime = time.time()
 
    # save time of arrival
    while GPIO.input(GPIO_ECHO) == 1:
        StopTime = time.time()
 
    # time difference between start and arrival
    TimeElapsed = StopTime - StartTime
    # multiply with the sonic speed (34326 cm/s)
    # and divide by 2, because there and back
    distance = (TimeElapsed * 34326) / 2
 
    return distance

for x in range(100):
    dist = distance()
    print ("Measured Distance = %.1f cm" % dist)
    time.sleep(.1)

GPIO.cleanup()

Make sure that you understand what each line in the measurement loop does.

Answer the following questions:

  1. What line executes the measurement?
  2. How often are measurements conducted?
  3. What is likely a good approximation of the time step (\(\Delta t\)) between measurements?

Code Additions

You were asked to add two functionalities to your code:

  1. Code to save each measurement to a csv-file:
    for x in range(...):
        ...
        print("Measured Distance = %1.f cm" % dist)
        f = open("ultrasounddata.csv", "a")
        f.write('\n' + "Actual Distance = , 10 cm, Measured Distance , %.2f" % dist)
        f.close()
        ...
  1. Code to switch on an LED as soon as a measurement hits a certain threshold
GPIO_LED = 17   # 
GPIO.setup(GPIO_LED, GPIO.OUT)
if (dist < 5):
       GPIO.output(GPIO_LED, GPIO.HIGH)
       print (“WARNING!!!!”)
else:
       GPIO.output(GPIO_LED, GPIO.LOW)

Task:

DO this in your group:

  1. Go through these line by line to make sure that you understand what each line does.
  2. Decide where in the code each line has to go to accomplish.
  3. How would you implement a speed calculation in your code?