What is a tilt sensor? How to adapt it into your project?

Introduction

A tilt sensor allows you to measure the inclination of your circuit or embedded system. This sensor can be very useful in a robot or an airplane, for instance.

The tilt sensor works on all axes. When you tilt the sensor along the axis you want to measure, it will indicate any deviation from that axis.

The tilt sensor can also detect vibrations. Indeed, these vibrations can cause the ball to move and thus be detected by the sensor.

How does a tilt sensor work?

A tilt sensor is a small box containing a ball that can move freely inside.

 

When the ball is at the bottom of the box, the sensor is in a vertical position and indicates a value of 0.

When the ball is on the other side of the box, it means that the sensor is tilted and thus indicates 1.

The tilt sensor is not very precise; it only tells you whether your circuit is tilted or not. It won’t give you the exact degree of tilt, for example. If you need a sensor that provides more precision, we recommend using a gyroscope, for instance.

The sensor pins!

Signal: Used to obtain the measurement from the sensor.

Vcc: Connect to the 3V or 5V on the Arduino board.

GND: Connect to the ground (0V) on the Arduino board.

Displaying values on the serial monitor

We will see how to display the values from the tilt sensor on the serial monitor. If the value is 1, it means the sensor is tilted; otherwise, it’s 0.

int tilt_sensor = 3;

void setup(){
  pinMode(tilt_sensor, INPUT); 
  Serial.begin(9600); 
}

void loop(){
  int value_sensor = digitalRead(3);
  Serial.print("Value of the tilt sensor:");
  Serial.println(value_sensor);
  delay(100); 
}

Turning on an LED with the inclination

Now, let’s see how to turn on an LED based on the titl of the sensor. The LED will light up if the sensor is tilted; otherwise, it will remain off.

const int tilt_sensor = 2;
const int led =  13;
int State_button  = 0;
 
void setup() {
 pinMode(led, OUTPUT);
 pinMode(tilt_sensor, INPUT); 
}
 
void loop() {
 State_button = digitalRead(tilt_sensor);
 if (State_button == HIGH) { 
   digitalWrite(led, HIGH); 
 } else {
   digitalWrite(led, LOW); 
 }
}

Servomotor and inclination

Next, we will learn how to adjust the position of the servomotor based on the tilt of the sensor. The servomotor’s position is set to 0° if the tilt sensor is not tilted; otherwise, it is positioned at 180°.

#include <Servo.h> 
int tilt_sensor = 2; 
Servo Servomotor; 

void setup(){
  pinMode(tilt_sensor, INPUT); 
  Servomotor.attach(13); 
}

void loop() {
  int value_read = digitalRead(tilt_sensor);
  if(value_read) {
    Servomotor.write(0); 
    Servomotor.write(180);
  }
}