Tilt sensor
A tilt sensor is a type of sensor that detects the orientation or tilt of an object. It consists of a small metal ball or a mercury switch inside a small metal canister. When the sensor is tilted, the ball or switch rolls to a different position and makes or breaks an electrical connection, indicating a change in orientation.
Here is an Arduino code with comments that explains how to use a tilt sensor to light up an LED when the sensor is tilted:
int tiltPin = 2; // the digital pin connected to the tilt sensor
int ledPin = 11; // the digital pin connected to the LED
void setup() {
pinMode(tiltPin, INPUT); // set the tilt sensor pin as input
pinMode(ledPin, OUTPUT); // set the LED pin as output
Serial.begin(9600); // initialize serial communication
}
void loop() {
int tiltValue = digitalRead(tiltPin); // read the tilt sensor value
if (tiltValue == HIGH) { // if the tilt sensor is tilted
digitalWrite(ledPin, HIGH); // turn on the LED
Serial.println(“Tilted”); // print “Tilted” on the serial monitor
}
else { // if the tilt sensor is not tilted
digitalWrite(ledPin, LOW); // turn off the LED
Serial.println(“Not tilted”); // print “Not tilted” on the serial monitor
}
delay(100); // wait for 100 milliseconds before reading again
}
In this code, the tilt sensor is connected to digital pin 2 and the LED is connected to digital pin 11. When the sensor is tilted, the digitalRead() function reads a HIGH value from the tiltPin and the code turns on the LED by setting the ledPin to HIGH. If the sensor is not tilted, the digitalRead() function reads a LOW value and the code turns off the LED by setting the ledPin to LOW. The Serial.println() function is used to print a message on the serial monitor to indicate whether the sensor is tilted or not.