Unit 26: Handle with care
Code for Sketch One:
const int tiltPin = 13; // Tilt sensor connected to pin 13
const int buzzerPin = 3; // Buzzer connected to pin 3
const int buttonPin = 7; // Button connected to pin 7
void setup() {
pinMode(tiltPin, INPUT); // Set tilt sensor as input
pinMode(buzzerPin, OUTPUT); // Set buzzer as output
pinMode(buttonPin, INPUT_PULLUP); // Enable internal pull-up for button
Serial.begin(9600); // Begin Serial communication
}
void loop() {
int tiltState = digitalRead(tiltPin); // Read the state of the tilt sensor
int buttonState = digitalRead(buttonPin); // Read the state of the button
Serial.print("Tilt State: ");
Serial.println(tiltState);
Serial.print("Button State: ");
Serial.println(buttonState);
// If the tilt sensor is triggered and the button is not pressed
if (tiltState == LOW && buttonState == HIGH) {
Serial.println("Buzzer ON");
digitalWrite(buzzerPin, HIGH); // Turn on buzzer
} else {
Serial.println("Buzzer OFF");
digitalWrite(buzzerPin, LOW); // Turn off buzzer
}
delay(500); // Delay for stability
}
Code for Sketch Two
const int tiltPin = 13; // Tilt sensor connected to pin 13
const int buzzerPin = 3; // Buzzer connected to pin 3
const int buttonPin = 7; // Button connected to pin 7
int tiltCount = 0; // Count the number of tilt triggers
void setup() {
pinMode(tiltPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP); // Button setup with internal pullup
Serial.begin(9600); // Initialize serial communication
}
void loop() {
int tiltState = digitalRead(tiltPin);
int buttonState = digitalRead(buttonPin);
Serial.print(“Tilt State: “);
Serial.println(tiltState);
Serial.print(“Button State: “);
Serial.println(buttonState);
Serial.print(“Tilt Count: “);
Serial.println(tiltCount);
// If tilt sensor is triggered, increase the tilt count
if (tiltState == LOW) { // Tilt detected (LOW means triggered)
tiltCount++;
Serial.println(“Tilt Detected, Count Increased”);
delay(500); // Delay to avoid multiple counts for a single tilt
}
// If the count exceeds 3, activate the buzzer
if (tiltCount > 3) {
Serial.println(“Buzzer ON - Alarm Triggered!”);
digitalWrite(buzzerPin, HIGH); // Turn on the buzzer
}
// If the button is pressed, reset the counter and buzzer
if (buttonState == LOW) { // Button pressed (LOW means pressed)
tiltCount = 0; // Reset the tilt counter
digitalWrite(buzzerPin, LOW); // Turn off the buzzer
Serial.println(“Button Pressed - Counter Reset”);
delay(500); // Debounce delay for the button press
}
delay(100); // Stability delay
}