Maker Advent Calendar Day #9: Full Tilt!

Maker Advent Calendar Day #9: Full Tilt!

Welcome to day nine of your 12 Projects of Codemas Advent Calendar. Today we're going to be using a sensor that detects movement - but not like our PIR sensor from day #7 - this is a tilt sensor which can detect when it is tilted over a certain angle.

Whilst we'll be using a simple ball tilt sensor which provides ON/OFF style output, in the outside world much more advanced versions are used in car alarms, boat and airplane roll, robotics and more.

This is a nice simple sensor that gives us a HIGH signal when tilted over a certain angle. In fact, this is probably going to seem like a really easy day considering all of the components you've been tinkering with!

Box #9 Contents

In this box you will find:

  • 1x Tilt sensor/switch
  • 2x Male to male jumper wires
  • 2x Male to female jumper wires

Day 9 contents

Today’s Project

In today's box of fun is a ball tilt sensor - the little can with two legs sticking out. That can has a small metal ball inside. When you tilt the sensor, gravity pulls the ball downwards and makes it roll to the other end.

The legged end has two contacts inside which connect to each leg. When the ball rolls down to the legged end, it connects these contacts/legs together (as metal is conductive) which then provides our Pico with a HIGH signal. When we tilt it back, the ball rolls away and the connection is broken, sending the pin back to LOW.

Great for robotics projects as an auto kill switch if your robot manages to roll over!

Construct the Circuit

You know the drill...turn that Pico off before changing the circuit!

Once again we're going to start with just the LEDs and buzzer connected, so remove the temperature sensor parts from yesterday which should leave you with this as your starting circuit:

Day 09 - starting point

Now to add the tilt sensor. It acts like a switch so we only need to connect two wires, and we've included male to female jumper wires to allow you to wire the component without attaching it directly to the breadboard, giving you the flexibility to tilt the switch. We've also included some male to male wires if you'd prefer to wire this to a breadboard.

The legs are only so strong, so whilst supporting the legs with your fingers, gently push the sensor's pins into the female ends of the jumper wires, then connect one of these wires to 3.3V (physical pin 36) and the other to GPIO 26 (physical pin 31).

The legs have no polarity so don't worry about which leg goes where. Your circuit should look like this:

Tilt sensor circuit

Activity 1: Basic Tilt Sensor Program

Let's get a little program running to test our sensor and see how it works.

We only need a handful of lines to use this kind of tilt sensor as it works just like a button or switch, triggering HIGH or LOW signals.

This is very similar to our button code from day #3 - we set our sensor's pin with pull downs, then run a simple if statement looking for the pin to go HIGH.

# Imports
from machine import Pin
import time

# Set up tilt sensor pin
tilt = Pin(26, Pin.IN, Pin.PULL_DOWN)

while True: # Run forever

    time.sleep(0.01) # Short delay
    
    if tilt.value() == 1: # If sensor is HIGH

        print("I tilted!") # Print a string

Activity 2: Tilty McBuzzalot

Let's trigger our buzzer whenever the sensor detects tilting. This is a basic version of the kind of system used in car alarms to detect when the vehicle is being lifted at an angle.

The example below adds the buzzer back into the code (which means we have to import PWM as we have done previously), sets the buzzer frequency before the while loop (as we won't be changing the frequency) and then simply increases the buzzer duty (volume) when a tilt is detected.

Give it a go!

The Code

# Imports
from machine import Pin, PWM
import time

# Set up tilt sensor pin
tilt = Pin(26, Pin.IN, Pin.PULL_DOWN)

# Set up the Buzzer pin as PWM
buzzer = PWM(Pin(13)) # Set the buzzer to PWM mode

# Set PWM frequency to 1000
buzzer.freq(1000)

while True: # Run forever
    
    time.sleep(0.01) # Short delay
    
    if tilt.value() == 1: # If sensor is HIGH
        
        print("***TILT DETECTED***") # Print a string
        
        buzzer.duty_u16(10000) # Set duty (volume up)
        
        time.sleep(0.2) # Short delay
        
        buzzer.duty_u16(0) # Duty to zero (volume off)

Activity 3: Tilt Counter

In some projects, counting the number of times a sensor has detected something can be very useful, like knowing how many times someone has entered a room or attempted to move an object.

Let's alter our code to count each time a tilt is detected.

The example below is a little smarter than our previous counters as we've added a new state variable to ensure the pin always returns back to LOW before we count again - otherwise if we kept the sensor tilted (HIGH), it would just keep counting forever!

We start the state at 0 then use and in our if statements to check for two conditions (remember this from day #3 with the buttons to check if both were being held down?):

  • The first if statement won't run unless the state is 0 and the pin is HIGH. When it does run, the block of code inside this if statement changes the state to 1 meaning it can't run this counting block again until we return that state to 0.
  • The second if statement handles this. The second if statement only runs if the state is 1 and the pin is LOW...meaning we're forced to tilt the sensor back to trigger this block, return the state to 0, ready to be tilted again.

The Code

Try this example, and remember to keep an eye on the jumper wires as they have a habit of popping out when you least expect it!

# Imports
from machine import Pin
import time

# Set up tilt sensor pin
tilt = Pin(26, Pin.IN, Pin.PULL_DOWN)

# Set up a counter variable at zero
tiltcount = 0

# Create a state variable at zero
state = 0

while True: # Run forever
    
    time.sleep(0.1) # Short delay
        
    if state == 0 and tilt.value() == 1: # If state is 0 and our pin is HIGH
                    
         tiltcount = tiltcount + 1 # Add +1 to tiltcount
            
         state = 1 # Change state to 1
            
         print("tilts =",tiltcount) # Print our new tiltcount
            
    if state == 1 and tilt.value() == 0: # If state is 1 and our pin is LOW
                            
        state = 0 # Change the state to 0

Now return to activity #2 and think about how you could improve this in the same way, waiting for the pin to trigger LOW again before allowing the buzzer to sound...or perhaps add the LEDs in for visual feedback on the tilt? 

Day #9 Complete!

Well done makers, we've cracked another sensor. Today's sensor (some might call it a switch) was a little easier than others, especially as you're now so familiar with MicroPython and the approaches we're taking, but we thought a little breather would be good before we adventure on to the fun yet slightly-more-advanced goodies in the final three boxes!

Today you have:

  • Learnt what a tilt sensor/switch is and why you might use one
  • Learnt how to wire a tilt sensor into your circuit (easy peasy!)
  • How to use variables and if statements in a way that improves the robustness and accuracy of our project
  • Made a basic tilt alarm
  • Re-used lots of things you've already learnt!

As always, please do not disassemble the circuit until tomorrow where we will explore the next fun component - see you then!


We used Fritzing to create the breadboard wiring diagram images for this page.

Featured Products

6 comments

Martin Schnitzer

Martin Schnitzer

Hello people,
I love this calendar, taking new opportunities every day to make my own code with the new component.
it is real fun.

Hello people,
I love this calendar, taking new opportunities every day to make my own code with the new component.
it is real fun.

Rowan Summerfield

Rowan Summerfield

In response to my last comment, I resolved the problem, I had pushed the pins too far into the tilt sensor and the ball wasn’t moving! As the task said, they arent that strong

In response to my last comment, I resolved the problem, I had pushed the pins too far into the tilt sensor and the ball wasn’t moving! As the task said, they arent that strong

Rowan Summerfield

Rowan Summerfield

Hello, when completing activity 3, the loop only happens once so I only get “tilts = 1” printed and it doesn’t count up. Any ideas what could have gone wrong? Thanks

Hello, when completing activity 3, the loop only happens once so I only get “tilts = 1” printed and it doesn’t count up. Any ideas what could have gone wrong? Thanks

Martin Packer

Martin Packer

Rather than have the buzzer go off, I changed it so that the green LED comes on if there is no tilt and red on tilt. (No idea what to do with amber, though.) :-)

It’s really nice to think of variants – using each new day’s kit. I see others have done this as well.

Rather than have the buzzer go off, I changed it so that the green LED comes on if there is no tilt and red on tilt. (No idea what to do with amber, though.) :-)

It’s really nice to think of variants – using each new day’s kit. I see others have done this as well.

The Pi Hut

The Pi Hut

@Al Glad you’re getting along well with the projects. The light sensor won’t work like an LED (even though it looks a lot like one) – in fact you may even damage it if you try that :(

@Al Glad you’re getting along well with the projects. The light sensor won’t work like an LED (even though it looks a lot like one) – in fact you may even damage it if you try that :(

Al

Al

Hi,
I feel I’ve started getting the hang of this the last few days, it’s good fun. I’m saving all the tutorial pages so I can look at it over the holidays and work on making my own projects. It’s great to have all the different components to have different combinations.
One question, the LED used for the Light sensor, could it be connected like the LEDs on day 2 and can it be a different colour like blue?

Hi,
I feel I’ve started getting the hang of this the last few days, it’s good fun. I’m saving all the tutorial pages so I can look at it over the holidays and work on making my own projects. It’s great to have all the different components to have different combinations.
One question, the LED used for the Light sensor, could it be connected like the LEDs on day 2 and can it be a different colour like blue?

Leave a comment

All comments are moderated before being published.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.