STEAM DISCOVERY LAB
  • About
  • Tools
  • Projects
  • Resources
  • About
  • Tools
  • Projects
  • Resources
Search

Micro:bit Pendulum

Picture

​Lesson Objectives:
  1. Students will use programming to measure and analyze a physical system
  2. Students will learn to perform peak finding
  3. Students will learn to write data to files

Materials:
  • BBC micro:bit
  • Laptop with Mu Software 
  • LEGO pieces to make a pendulum
​
​Goal:
Use a micro:bit to create a data logger that measures the acceleration and calculates the period of a LEGO pendulum. 

Construction:
Use LEGO pieces to construct a pendulum. You should make it easy to adjust the length, so data can be collected for different lengths. The micro:bit and battery pack should attach to the bottom of the pendulum.
Picture
Basic Data Logger:
Create a micro:bit program to log sensor data to a text file. You likely will want to use accelerometer data, though you may want to use other/additional sensors. You also want to log the time each reading occurs at. Time can be calculated using microbit.running_time().

Think about how you want the user to interact with the logger. How does the user start and stop collecting data? How does the user know it is working properly? How much processing of the data is done in real time on the micro:bit vs later on your computer?

You should aim to collect data at least 10 Hz, though faster is better. Do not artificially slow down your code if it is faster than 10 Hz. 

​Check out the documentation on file input and output on micro:bit here.
​
Avoid Overwriting Files: 
If you use a fixed filename, every time the code is run the file will be overwritten. To get around this ​you can add a random number to the end of the filename. While not perfect, if you add a 3 digit number, the odds of overwriting 1 previous file goes from 100% to 0.1%. You still do not want to collect more than 2 or 3 runs of data at a time (you may also run into the micro:bit memory limit).

    
Take a look at the sample code below. Make sure you understand both your own code and the sample before continuing because everything will build on this base structure. Also, make a copy of your code before modifying it in the next step.
Basic Logger code

    
Instructions for Data Logger
  1. Flash this program onto microbit
  2. Smiley Face should appear on screen
  3. Disconnect microbit from computer and attach to pendulum
  4. Press Button A to begin logging data
  5. After a 1 second delay the microbit will display a heart and begin logging
  6. Press Button A again to stop logging data
  7. A Square should appear on the screen
  8. Reconnect to computer and open Mu
  9. Click the 'Files' Button
  10. Drag 'accelerometer_data_###.txt' from 'Files on your micro:bit:' to 'Files on your computer:'
  11. Right click the filename and select 'Open'
  12. You should see the accelerometer data

Period Calculation:​
One thing we may want to measure is the period of the pendulum. 
Understanding Period
​As you may or may not know, the period of a pendulum has the following relationship:
Picture
.Where T is period, L is the length of the pendulum, and g is the gravitational constant (9.81 m/s^2). So if we can measure the period of a pendulum we can determine the length (assuming we are on Earth). Conversely we can calculate an expected period based on the length and compare that to the measured value.

If you run the data logger you wrote and plot the accelerations you will see that they are sinusoidal. For the Y-axis, one oscillation is one stroke back and forth of the pendulum and the time that oscillation takes is the period.
Picture
We can determine the period by measuring the time between like-points in the pendulum's oscillation. Probably the simplest point to measure is when the acceleration reaches a local maximum. In order to do this we need to find what is called a peak. 

In the most basic sense, a data point is a peak if it is greater than both the point before it and the point after it. For the function y = -x^2, there is a peak at x = 0, because both the values for x < 0 and for x > 0 are less than the value at x = 0. 
Picture
Algorithm:​
The algorithm we are about to implement is based off the 
SciPy find_peaks() function. You may find this helpful to read, but we are not going to implement it exactly. 

Before continuing, make sure to make a copy of your code.

Let's make a function called find_peak that takes a list of 3 consecutive accelerometer readings as an input and returns a boolean True if the middle element is a peak and False if it is not. The element is a peak if it is greater than both of the of the other elements. Implement this conditional in the function and put the function at the top of your data logger code.

The overall structure of our algorithm is:
  1. Read in an accelerometer value and record the corresponding time
  2. Determine if that data point represents a peak
  3. If it is, calculate the period of the oscillation that just ended and write the period to a file

The trickiest part of this is that we need to know what comes after the point we are looking at to determine if it is a peak or not. In order to do this we need to collect the next data point before checking if the current one is a peak. This is why the point we are checking in find_peak is the middle element of the list. The process for this looks like:
  1. Add a new value to the end of the list (append)
  2. Call find_peak on the list
  3. Remove the first element from the list (pop) 
  4. Repeat

There are a few other things that need to be added to your program:
  • Collect several data points before we start calling find_peaks, so the list is the right length. 
  • Period calculation
  • File output

At this point the program should theoretically work. However, the micro:bit tends to repeat the same measurement consecutively a lot, so you may end up with an empty file. There are two quick ways to fix this for now, but we will improve on this in the next step.
  1. Add a sleep between each measurement, so the pendulum has time to move further (Try between 10 and 100 milliseconds)
  2. Change the conditional in find_peak from greater than to greater than or equal 
​
You should now have at least something in your results file, though the periods will likely be way smaller than expected. You may find it useful for debugging to write more things to the data file. 

The way the sample code is written is for a pendulum constructed with the y-axis perpendicular to the arm of the pendulum. When the y-axis is referred to, use what ever axis is perpendicular to the arm for your pendulum. ​
Logger with Simple Peak Finding

    

Complex Peak Finding:
Now that we have the basic structure of the code working, let's think about ways to improve the results. Take a look at some of the optional parameters of the SciPy find_peaks() function. Let's try to implement some of those concepts. 

Before continuing, make sure to make a copy of your code.

Global Variables:
To make it easy to test different values for the parameters and to follow good coding style, make each parameter a global variable. Global variables can be accessed from any part of your program, so they are good for things like mathematical constants that are used in a lot of places in your code, but not modified much. Be careful with them, as they can cause unexpected issues when multiple parts of your code change their values.  Global variables go at the top of your code, just below the import statements, and are commonly given names in ALL CAPS. 

Parameters:
Some parameters you may want to try implementing include:
  • SLEEP_TIME - Time to pause between measurements (see above)
  • WINDOW - Instead of just looking at 1 measurement on each side of possible peak, try looking at a larger window. If the point is not larger than all others in the window, it is not a peak. This should reduce the false positive rate. 
  • MIN_DISTANCE - Minimum number of measurements since the last peak until a new measurement can be considered a peak. You likely can assume the period of the pendulum you are testing is on the order of seconds, so if you detect 2 peaks in a small fraction of a second, you know something is wrong.
  • MIN_HEIGHT - Minimum accelerometer value to be considered a peak. If you test your sensor and know roughly how large you can expect the value of peaks to be, you can ignore everything significantly below that value.

​Additionally, as discussed in the last step, you likely will want to change the greater than in the find_peaks function to greater than or equal to. Otherwise, you may miss peaks, as the micro:bit accelerometer tends to repeat values a lot. 

Implement these parameters and then test different values to see what gives you the best results. There is no perfect answer, but the values that worked well for the sample setup are at the top of the code below. 

Your data file should contain mostly consistent measurements of the period (Ignore the first and last values as the micro:bit only was recording for part of those oscillations). Time your pendulum with a stop watch and see how it compares to the micro:bit's measurements.

Logger with Complex peak finding

    
References
The full documentation may be found here:
  • https://microbit-micropython.readthedocs.io/en/latest/microbit_micropython_api.html
Picture
200 Boston Ave, Medford, MA 02155
steamdiscoverylab@gmail.com
Center for Engineering Education and Outreach
​Tufts University
About
Tools
Projects
Resources
​
Contact
LEGO®, the LEGO® logo, the Brick, MINDSTORMS®, and the Minifigure are trademarks of ©The LEGO® Group. On some parts of this site  you will get access to so-called “developer software”, which offers documentation on different ways to operate the LEGO® Education SPIKE™ Prime Hub and technology. Whatever use you make of the developer software, bear in mind that the results are not experiences that the LEGO Group endorses, is with or will be liable for. No rights in or to trademarks of the LEGO Group are implied or given, and you may not apply to or register any protection anywhere in the world for intellectual property or industrial rights or similar in respect of any developer software, derivative or other result achieved through its use. The developer software is made available “as is” and, to the extent possible, no warranties or representations are implied or given in relation to it by the LEGO Group. It’s your responsibility to ensure all uses that you make and enable others to make comply with all applicable laws and best practices. By accessing the developer software, you acknowledge that the terms and conditions set out above and in LEGO Education’s terms of use for SPIKE Prime apply.
  • About
  • Tools
  • Projects
  • Resources