A tilt switch is used to detect the orientation or tilt of a system. It is often used to indicate if a system (such as an agricultural vehicle) is beyond its operating tilt range, or to detect the orientation of a display and thus change its layout. It does not provide as much information as an accelerometer but is more robust and does not require a special program to process.
Material
- Computer
- Arduino UNO
- USB A Male Cable
- Tilt Switch
Principle of operation
The tilt switch (tilt switch or ball tilt or mercury sensor) consists of a ball (or a mass of mercury) and a contactor. When the orientation with respect to the horizon changes, the ball, subjected to gravity, moves and comes into contact with two poles. This short-circuits them and closes the switch.
Scheme
The tilt switch is connected, like a push button, preferably on a digital pin of the microcontroller because it returns a high or low, closed or open state.
- By connecting the ground and a digital pin (here pin 2)
- By using an external pullup resistor (if the microcontroller or the pin used does not have an internal pullup)
Code
The tilt switch works like a switch. The sensor management code will therefore strongly resemble that of a push button. It is good to note that, generally, a ball makes the contact and closes the switch. It happens that this ball bounces at the change of state. To avoid taking into account these parasitic bounces, we use an anti-bounce logic.
//Parameters const int tiltPin = 2; //Variables bool tiltStatus = false; bool oldTiltStatus = false; unsigned long lastDebounceTime = 0; unsigned long debounceDelay = 50; void setup() { //Init Serial USB Serial.begin(9600); Serial.println(F("Initialize System")); //Init digital input pinMode(tiltPin, INPUT); } void loop() { debounceTilt(); } void debounceTilt( ) { /* function debounceTilt */ ////debounce TiltSwitch int reading = digitalRead(tiltPin); if (reading != oldTiltStatus) { lastDebounceTime = millis(); } if ((millis() - lastDebounceTime) > debounceDelay) { if (reading != tiltStatus) { tiltStatus = reading; Serial.print(F("Sensor state : ")); Serial.println(tiltStatus); } } oldTiltStatus = reading; }
Results
By tilting the ball sensor, you should see its status change on the serial monitor. By doing several tests, you should be able to adjust the debounceDelay parameter to ensure that the status read is reliable
Applications
- Detect the orientation of an object