In the previous lessons, you have used the Finch sensors to make measurements, and you have stored these measurements in variables. In this lesson, you will learn to use a new type of variable called a list. A list can hold many values, instead of just one.
Creating a List
To create a list in Snap!, just declare a variable. For now, name your variable practiceList. At the beginning of a program, you need to make sure that the list is empty. Use the set to block on the Variables menu to make practiceList equal to an empty list. The default value of the list block is a list with one blank item. To get an empty list, click on the left black triangle to remove the blank item.
To add items to a list, you can use the add to block in the Variables menu. For example, the block below adds the number 3 to practiceList. Try adding a few other values to practiceList. Notice that each value is added to the bottom of the list. By default, the list is shown in the stage area, although you can deselect the list to hide it.
Write a program that records 60 measurements with the accelerometer. The program should wait 0.5 seconds between measurements. Be sure to save this code, because you will need it later.
Using Items in a List
Often, you will want to use a loop to move through all of the items in a list. You can do this using a counter variable and a repeat block. An example is shown below. Before the repeat block, the variable count is set to 1, corresponding to the first item in the list. In order to repeat the contents of the loop for each item in the list, the number of repetitions in the repeat block is set to the length of the list using the length of block (Variables menu). Each time through the loop, the item in the list that corresponds to count is displayed, and then the value of count is increased by 1. Try out this script to make sure you understand how it works.
Return to your program from the last exercise. After you collect the accelerometer measurements, use a loop to move through the list. Use each item in the list to determine the position of the sprite on the screen. Remember, you may need to scale the accelerometer value so that you can see the sprite move.
Search through your list to find the largest value.
Modify your program so that it calculates the sum of the items in your list in a variable called sum. Then use the block below to calculate the mean acceleration. The addition block with .0 is required to get a decimal value for the mean instead of rounding to the nearest whole number (which is probably 0).