Loading...
 

ArduinoNano Tilt Sensor Example

Tilt Sensor

The tilt sensor is essentially a button, activated by its movement rather than a click with your finger.
So these sensors are used to detect movements.
For example, you can place a tilt sensor to an object and then you can monitor its movement.

Hardware Required

  • Arduino Board
  • Tilt sensor
  • LED
  • Resistor 220 ohm

Circuit

Image
Connect the tilt sensor to the Ground and 5V PINs of your board.
Between the 5V and the tilt PIN there's a 10K resistance.
Then wire up the 5V PIN of the sensor to the Arduino Board PIN digital 2.

Schematics

Image

Code

The sketch code defines variable used to control the Tilt sensor and the LED.
There are also other varibles used to determine the current/previous status, a variable to evaulate the threshold and timing.
The void loop repeatly reads the tilt sensor PIN.
If a movement is detected, it changes the LED status to HIGH or LOW.
The LED status is changed if the current read operation has been made after "threshold" time.
If the tilt sensor does not detect a movement after "threshold" time elapsed, the LED status will be reset.

int tiltPin = 2;
int ledPin = 13;
 
int LEDstate = HIGH;
int tilt_status;
int previous = LOW;
long time = 0;
long threshold = 50;
 
void setup() {
	pinMode(tiltPin, INPUT);
	pinMode(ledPin, OUTPUT);
	
	//Turn on the pull-up resistor
	digitalWrite(tiltPin, HIGH);
}
 
void loop() {
	int switchstate;
	
	//Read the tilt sensor status
	tilt_status = digitalRead(tiltPin);

	//Update time if a movement is detected
	if (tilt_status != previous)
		time = millis();

	//If the right amount of time has passed
	//update the LED status
	if ((millis() - time) > threshold) {
		switchstate = tilt_status;
		if (switchstate == HIGH)
			LEDstate = LOW;
		else
			LEDstate = HIGH;
	}
	digitalWrite(ledPin, LEDstate);
	previous = tilt_status;
}


This is how the Tilt Sensor example is shown on the new Arduino Studio. Check it out!
Image