Unit 9: Bad Vibrations
Code for Sketch One:
const int piezoPin = A0; // Pin for the piezo sensor
const int buzzerPin = 9; // Pin for the active buzzer
// Vibration threshold
const int threshold = 250;
// Alarm duration
const int alarmDuration = 1000; // 3 seconds
void setup() {
pinMode(buzzerPin, OUTPUT);
Serial.begin(9600); // Begin serial communication for debugging
}
void loop() {
int piezoValue = analogRead(piezoPin);
Serial.println(piezoValue); // Debugging: Print piezo value
if (piezoValue > threshold) {
triggerAlarm();
}
// Add a small delay to avoid overwhelming the serial output
delay(100);
}
void triggerAlarm() {
// Sound the alarm
digitalWrite(buzzerPin, HIGH);
delay(alarmDuration);
digitalWrite(buzzerPin, LOW);
}