MicroPython Driver for ADXL335 Accelerometer
Contents
Introduction
This a MicroPython driver written specifically for the BBC micro:bit that will work with the ADXL335 accelerometer sensor.
The ADXL335 sensor is discussed in some detail here.
FIG 1 - ADXL335 breakout board: [Left] front view, [Right] rear view
The sensor is quite small and for projects using a breadboard its much easier to use a breakout board. The breakout boards are not particularly expensive.
Connecting the ADXL335
This sensor's output is analog. The output pins must be connected to analog pins on the micro:bit.
| micro:bit | Sensor board |
|---|---|
| 3.3V | VCC |
| GND | GND |
| Pin 0 | X_OUT |
| Pin 1 | Y_OUT |
| Pin 2 | Z_OUT |
This utilises three of the micro:bit's analog pins. The analog pins used on the micro:bit with this driver are configurable when declaring an instance of the sensor. However the defaults (above) are probably the simplest to use.
Driver Overview
The driver implements everything mentioned in the datasheet; i.e. measurement of acceleration in the X-axis, Y-axis and Z-axis. Additionally, oversampling options are offered and a simple angle measurement tool is provided.
Driver codeThe driver code can be:
- Copied from this webpage onto the clipboard then pasted into the MicroPython editor e.g. the Mu Editor. It should be saved as fc_adxl335.py - OR -
- Download as a zip file using the link. Unzip the file and save it as fc_adxl335.py into the default directory where the MicroPython editor e.g. Mu Editor saves python code files.
After saving the fc_adxl335.py file to the computer it should be copied to the small filesystem on the micro:bit. The examples on this page will not work if this step is omitted. Any MicroPython editor that recognises the micro:bit will have an option to do this.
The Mu Editor is recommended for its simplicity. It provides a Files button on the toolbar for just this purpose.
Class constructorThe driver is implemented as a class.The first thing to do is call the constructor of the ADXL335 class to obtain a sensor object.
Syntax:
ADXL335(Xpin=pin0, Ypin=pin1, Zpin=pin2)
Where:
Xpin, Ypin, Zpin : The analog pins on the micro:bit,
connected to the respective analog output pins on
the ADXL335.
Example
from fc_adxl335 import *
# Declare a ADXL335 sensor object
# The default analog pins are used.
sensor = ADXL335()
This assumes that the file fc_adxl335.py has been successfully copied to the micro:bit's filesystem as described above.
Methods and PropertiesThe driver provides methods and properties to:
-
Set and get applied oversampling :
SetOSR(), GetOSR -
Read acceleration:
Reading, X, Y, Z -
Angle measurement:
Xangle, Yangle
Measuring Acceleration
After optionally setting the oversampling, it's a very simple process to read acceleration values from the sensor. The acceleration values have units of g (1g = 9.8 m/sec2).
Syntax:
SetOSR(OSR=1)
Method that sets the amount of oversampling.
Increasing oversampling uses more power but
increases the accuracy. Expected values of OSR
are in the range of 1 to 8.
GetOSR
Property that returns the oversampling rate.
Syntax:
Reading
Property that returns acceleration in all three axis.
Values are returned in a tuple in the follow order:
(X-axis, Y-axis, Z-axis)
X
Property that returns the acceleration in the X-axis.
Y
Property that returns the acceleration in the Y-axis.
Z
Property that returns the acceleration in the Z-axis.
Example:
from fc_adxl335 import *
# Declare a ADXL335 sensor object
# The default analog pins are used.
sensor = ADXL335()
# Set a high OSR for increased accuracy.
sensor.SetOSR(8)
# Read acceleration of all three axis.
acc = sensor.Reading
print('(X-axis, Y-axis, Z-axis):', acc)
# Read acceleration separately from each axis.
sleep(100)
print('\nX-axis:', sensor.X)
print('Y-axis:', sensor.Y)
print('Z-axis:', sensor.Z)
Typical Output:
(X-axis, Y-axis, Z-axis): (0.01775568, -0.06747159, 1.019176)
X-axis: 0.01657197
Y-axis: -0.07339015
Z-axis: 1.02036
In the above example the ADXL335 was mounted on a breadboard that was lying on a flat horizontal surface. In this position the X and Y axis would be expected to return values very close to 0g. The Z axis value should be very close to 1g as the result of Earth's gravity.
Measuring Angles
Accelerometers measures:
- static : The sensor is stationary but is under the influence of the Earth's gravitational field
- dynamic : The component of acceleration resulting from the motion or changes in velocity experienced by the sensor over time.
When the accelerometer is stationary and lying perfectly perpendicular to the direction of the Earths gravity, the X-axis and Y-axis acceleration will both be 0g. The Z-axis acceleration will be 1g.
This fact along with some simple trigonometry can be used to measure angles in the X-axis or Y-axis.
Syntax:
Xangle
Property returns inclination of X-axis from the
horizontal in degrees.
Yangle
Property returns inclination of Y-axis from the
horizontal in degrees.
Example:
# Demonstrates the calculation of the
# X-axis angle from the horizontal.
# While the program is running change
# the X-axis tilt angle to output different
# angle values.
from fc_adxl335 import *
from microbit import sleep
# Declare an ADXL335 sensor object
# The default analog pins are used.
sensor = ADXL335()
# Set a high OSR for increased accuracy.
sensor.SetOSR(8)
# Calculate the X-axis angle every two seconds.
# Terminate the program in the REPL with
# Ctrl/C on Windows or Command/C on Mac.
while True:
sleep(2000)
print(sensor.Xangle)
Typical Output:
0.1340118
0.470123
19.99308
38.43481
60.79782
77.70642
44.74195
19.7488
8.391671
0.4685246
Traceback (most recent call last):
File "main.py", line 21, in <module>
KeyboardInterrupt:
In the above example the breadboard containing the ADXL335 was oriented at different angles along the X-axis.
Enjoy!
ADXL335 Driver Code for micro:bit
Download as zip file
'''
ADXL335 3-Axis Accelerometer
MicroPython driver for BBC micro:bit
AUTHOR: fredscave.com
DATE : 2025/08
VERSION : 1.00
Acceleration is returned in g units.
'''
from microbit import *
from math import atan, sqrt, pi
# Sensitivity at 3.3V from datasheet = 340.3 mV/g.
# Converting to 10-bit ADC sensitivity
SENSITIVITY = 105.6
class ADXL335():
def __init__(self, Xpin=pin0, Ypin=pin1, Zpin=pin2):
self.Xpin = Xpin
self.Ypin = Ypin
self.Zpin = Zpin
self.OSR = 1
self.Xerror = 0
self.Yerror = 0
# Sets the oversampling rate.
# A value between 1 and 8.
# This is the number of samples
# taken and then averaged for
# the output acceleration.
def SetOSR(self, osr=1):
if osr not in range(1, 9):
self.OSR = 1
else:
self.OSR = osr
# Returns acceleration of all three
# axis and returned as a tuple.
@property
def Reading(self):
x = self.X
y = self.Y
z = self.Z
return (x, y, z)
# Returns the acceleration
# in the X-axis.
@property
def X(self):
sum = 0
for __ in range(self.OSR):
raw = self.Xpin.read_analog()
sum += raw
return (self._scale(sum/self.OSR))
# Returns the acceleration
# in the Y-axis.
@property
def Y(self):
sum = 0
for __ in range(self.OSR):
raw = self.Ypin.read_analog()
sum += raw
return (self._scale(sum/self.OSR))
# Returns the acceleration
# in the Z-axis.
@property
def Z(self):
sum = 0
for __ in range(self.OSR):
raw = self.Zpin.read_analog()
sum += raw
return (self._scale(sum/self.OSR))
def _scale(self, raw):
return (raw - 512) / SENSITIVITY
# Returns inclination of X-axis from the
# horizontal in degrees. Offsets are
# subtracted if a calibration has been done.
@property
def Xangle(self):
t = self.Reading
X, Y, Z = t[0], t[1], t[2]
p = atan(X / sqrt((Y*Y + Z*Z))) * 180 / pi
return p - self.Xerror
# Returns inclination of Y-axis from the
# horizontal in degrees. Offsets are
# subtracted if a calibration has been done.
@property
def Yangle(self):
t = self.Reading
X, Y, Z = t[0], t[1], t[2]
p = atan(Y / sqrt((X*X + Z*Z))) * 180 / pi
return p - self.Yerror
# Returns the oversampling rate (OSR)
# Value between 1 and 8
@property
def GetOSR(self):
return self.OSR
Comparison of Angle Measurements
This project will measure a tilt angle in the X-axis and compare the results with that obtained from a commercial inclinometer. The inclinometer has a magnetic base which easily mounts on a breadboard.
The image below shows the setup used.
Code:
# This program measures a tilt angle (X-axis)
# using an ADXL335 accelerometer mounted on
# a breadboard.
# A commercial inclinometer can be mounted on
# the breadboard inline with the sensor as a
# check on the accuracy of the ADXL335's
# measurement.
from fc_adxl335 import *
sensor = ADXL335()
sensor.SetOSR(8)
# Endless loop:
# Pressing Button A on the micro:bit
# returns the X-axis angle.
while True:
print('\nPress Button A to calculate the angle')
while not button_a.was_pressed():
sleep(100)
print('Tilt in X-axis:', sensor.Xangle, 'degrees')
Typical Output:
Press Button A to calculate the angle
Tilt in X-axis: -22.05697 degrees
Press Button A to calculate the angle
Tilt in X-axis: -22.30622 degrees
Press Button A to calculate the angle
Tilt in X-axis: -21.74835 degrees
There is a difference of just less than 3° between the ADXL335 and the Shane inclinometer readings. The setup for this test is quite primitive with everything attached to a breadboard that's probably not exactly square. So, this isn't such a bad result!