BBC micro:bit Modified tilt sensor in Python

This is a modified version of the previous tilt sensor application, this one tidies the code a little for readability, adding more comments and adds the ability to adjust the sensitivity.

Enjoy!

from microbit import *

#Program to read accelerometer and show tilt direction

#Sensitivity of readings (lower value to make more sensitive)
#Suggested range 20 - 240
sensitivity = 20

#Create image for when micro:bit is level
centred = Image("00400:"
                "00400:"
                "44944:"
                "00400:"
                "00400")

#Main loop
while True:
    #Get tilt readings for x and y axes
    tilt_x = accelerometer.get_x()
    tilt_y = accelerometer.get_y()
    #Use sensitivity value to adjust size of null window
    #If tilt_x or tilt_y are < sensitivity, register as level
    x_null = -sensitivity < tilt_x < sensitivity
    y_null = -sensitivity < tilt_y < sensitivity
    
	#Allow sensitivity adjustment: button a to increase, button b to decrease
    if button_a.is_pressed() and sensitivity >= 40:
        #Increase sensitivity by 20 (reduce size of null window)
        sensitivity -= 20
        #Pause 100ms so single click doesn't register as multiple presses
        sleep(100)
    elif button_b.is_pressed() and sensitivity <= 220:
        #Decrease sensitivity (increase size of null window)
        sensitivity += 20
        #Pause 100ms so single click doesn't register as multiple presses
        sleep(100)
        
    #Check if micro:bit is tilted
    #If tilted forward and x-axis is within null window point N
    if tilt_y < -sensitivity and x_null:
        display.show(Image.ARROW_N)
	#If tilted forward and right point NE
    elif tilt_x > sensitivity and tilt_y < -sensitivity:
        display.show(Image.ARROW_NE)
    #If tilted right and y-axis is within null window point E
    elif tilt_x > sensitivity and y_null:
        display.show(Image.ARROW_E)
    #If tilted back and to the right point SE
    elif tilt_x > sensitivity and tilt_y >sensitivity:
        display.show(Image.ARROW_SE)
    #If tilted back and x-axis is within null window point S
    elif tilt_y > sensitivity and x_null:
        display.show(Image.ARROW_S)
    #If tilted back and to the left point SW
    elif tilt_x < -sensitivity and tilt_y > sensitivity:
        display.show(Image.ARROW_SW)
    #If tilted left and y-axis is within null window point W
    elif tilt_x < -sensitivity and y_null:
        display.show(Image.ARROW_W)
    #If tilted forward and left point NW
    elif tilt_x < -sensitivity and tilt_y < -sensitivity:
        display.show(Image.ARROW_NW)
    
    else:
        #If level display our custom cross
        display.show(centred)
adjustable_tilt_sensor.py

 

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *