Getting Started with MicroPython and the SparkFun Inventor's Kit for micro:bit

Pages
Contributors: LightningHawk
Favorited Favorite 5

Experiment 10: Using the Accelerometer

Introduction

In this experiment you will look at combining the use of the accelerometer on the micro:bit to measure the orientation of the micro:bit and using it to control the angle of a servo.

Ready to shake, rattle and roll?

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 1x micro-B USB Cable
  • 1x Hobby Servo
  • 3x Jumper Wires

Didn't Get the SIK for micro:bit?

If you are conducting this experiment and didn't get the Inventor's Kit, we suggest using these parts:

micro:bit v2 Board

micro:bit v2 Board

DEV-17287
$16.50
7
Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$5.50
48
Servo - Generic (Sub-Micro Size)

Servo - Generic (Sub-Micro Size)

ROB-09065
$9.95
13
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
$2.10
2
SparkFun Qwiic micro:bit Breakout (with Headers)

SparkFun Qwiic micro:bit Breakout (with Headers)

BOB-16446
$6.25
2
USB Micro-B Cable - 6 Foot

USB Micro-B Cable - 6 Foot

CAB-10215
$5.50
15

Introducing the Accelerometer

The accelerometer is a component that you won't find in the kit's bag of parts. Why? Because it is on the micro:bit itself! On the back of the micro:bit you can see a number of small chips. One of them is the accelerometer. The micro:bit has an onboard accelerometer that measures gravitational force. Depending on the version that you have, the accelerometer and compass can be on separate ICs or combined into a single IC.

v1.0 w/ Accelerometer on Sepearate IC v1.5 w/ Combined Accelerometer and Magnetometer
v1.0 w/ Accelerometer on Separate IC v1.5 w/ Combined Accelerometer and Magnetometer

An accelerometer is a sensor that measures the gravitational forces pulling on it in all three dimensions of the chip's X, Y and Z axes.

Triple Axis Accelerometer Visualization

Visualization of a Common Accelerometer (ADXL345) with Three Axes

Not only can an accelerometer measure the raw forces pulling on the chip and the object that the chip is sitting on, but it can also detect steps, shakes and other motions that have a specific pattern. On top of that, you can use an accelerometer to simply detect the orientation of the device. Did you ever wonder how your phone knows when you turn it from portrait to landscape? It is all because of the accelerometer in your phone!

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram below to see how everything is connected.

Polarized Components Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Wiring Diagram for the Experiment

Fritzing Diagram: Exp 10

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Run Your Script

Let's read an accelerometer and control a servo. Type (or copy) the program into your Mu editor, or download all the programs from this GitHub Repository and open the Ex10_usingAccel.py program. Save it, then click the Flash icon to program your micro:bit.

language:python
# SparkFun Electronics
# Experiment 10
# Using the Accelerometer

from microbit import *


class Servo:
    def __init__(self, pin, freq=50, min_us=600, max_us=2400, angle=180):
        self.min_us = min_us
        self.max_us = max_us
        self.us = 0
        self.freq = freq
        self.angle = angle
        self.analog_period = 0
        self.pin = pin
        analog_period = round((1/self.freq) * 1000)  # hertz to miliseconds
        self.pin.set_analog_period(analog_period)

    def write_us(self, us):
        us = min(self.max_us, max(self.min_us, us))
        duty = round(us * 1024 * self.freq // 1000000)
        self.pin.write_analog(duty)
        sleep(100)
        self.pin.write_digital(0)  # turn the pin off

    def write_angle(self, degrees=None):
        if degrees is None:
            degrees = math.degrees(radians)
        degrees = degrees % 360
        total_range = self.max_us - self.min_us
        us = self.min_us + total_range * degrees // self.angle
        self.write_us(us)


Servo(pin0).write_angle(0)
while True:
    num = accelerometer.get_x()
    Servo(pin0).write_angle(num * 180 / 2048 + 90)

alt text

Code to Note

Ignoring the servo class code again [1], we've got some new stuff!

accelerometer.get_x()

The accelerometer module comes with five built-in functions and recognizes 11 gestures. To see the full documentation, click here. The accelerometer.get_x() statement will return the acceleration measurement on the x-axis as a number between -1024 and 1024, depending on the direction.

Since the value stored in num needs to translated to an angle between 0-180 from a range between -1024 and 1024 it needs to be scaled. Adding 90 to the scaled value sets a range of angles for the negative accelerometer values from 0-89, and positive accelerometer values from 90-180.

What You Should See

At the beginning of the program the servo should move to 0 degrees and then react to the orientation of the micro:bit. If you hold the micro:bit flat, the servo will be at 90 degrees. Then if you tilt the servo to the left, it will move less than 90 degrees toward the value of 0. If you move it to the right, the servo will move toward 180.

Exp 8 and 10 Final Assembly

Troubleshooting

This Seems Backward

You may be holding the micro:bit in a different orientation. Flip it around and try again!

Servo Isn't Working

Double check your wiring! Remember, red to 3.3 volts, black to ground, and white to signal.