PA Designer Learn 3: Data Analysis

1. Capturing Data

Wouldn’t it be great if you could visualize what our loudness sensor is hearing? You can do that by plotting loudness values over time in a graph.

In the Variable Initialization cell, let’s declare two new variables called values and times and initialize them with empty lists. You will use these lists to store loudness values collected over time and record the times that these values were read.

Let’s also declare and initialize a smoothed_values list. You will use this for storing loudness values that you have “cleaned up”. More on that below.

Variable Initialization cell:

def init():
    # declare global variables that will be used by our program
    global start_time
    global values             # <= NEW
    global smoothed_values    # <= NEW
    global times              # <= NEW

    # perform a time-check at the start of our program
    start_time = time.time()

    # empty raw sensor values array (y axis data) 
    values = list()           # <= NEW

    # empty smoothed sensor values array (y axis data) 
    smoothed_values = list()  # <= NEW

    # empty sampling times array (x axis data)
    times = list()            # <= NEW

In the Main Code cell, instead of printing the loudness values let’s change our code to add them to the end of the values list. At the same time, let’s take a reading of the elapsed time and add that on to the end of the times list. 

The loudness sensor is sensitive to changes in the environment. A pre-written function called moving_average() helps to reduce the effects of its sensitivity. You can find what this function does in the second Template Function cell. moving_average() uses the numpy library imported at the top.

Let’s call moving_average(), passing in our values list and add the result to the end of our smoothed_values list. You will use a list function called append() to add values to the end of a list.

Main Code cell:

# perform all variable declaration and initialization 
init()
 
# repeat the following instructions for 10 seconds
while elapsed_time() < 10:

    # read loudness value and add it to end of the values list
    values.append(loudness.read())

    # add cleaned up value to the end of our “clean” data list
    smoothed_values.append(moving_average(values))

    # perform a time check and add elapsed time to end of the times list
    times.append(elapsed_time())

    time.sleep(0.02)