// Define pin numbers
const int buttonPin = 2;
const int led1Pin = 3;
const int led2Pin = 4;
const int sirenPin = 5;
// Define variables to track button state
int buttonState = 0;
int lastButtonState = 0;
// Define variables to track timing for flashing LEDs and siren activation
unsigned long previousMillis1 = 0;
unsigned long previousMillis2 = 100; // Start LED 2 flashing a bit after LED 1
const long interval = 400; // Flashing interval for both LEDs (milliseconds)
bool led1State = false; // Initial state of LED 1
bool led2State = false; // Initial state of LED 2
unsigned long activationTime = 0; // Time when the siren and lights were activated
// Define variable for siren state
bool sirenOn = false;
void setup() {
// Set pin modes
pinMode(buttonPin, INPUT);
pinMode(led1Pin, OUTPUT);
pinMode(led2Pin, OUTPUT);
pinMode(sirenPin, OUTPUT);
}
void loop() {
// Read the state of the button
buttonState = digitalRead(buttonPin);
// Check if the button state has changed
if (buttonState != lastButtonState) {
// If the button is pressed
if (buttonState == HIGH) {
// Toggle siren state
sirenOn = !sirenOn;
// If siren is activated, turn it on
if (sirenOn) {
// Also turn on the lights
digitalWrite(led1Pin, HIGH);
digitalWrite(led2Pin, HIGH);
activationTime = millis(); // Record the activation time
} else { // If siren is deactivated, turn it off
// Also turn off the lights
digitalWrite(led1Pin, LOW);
digitalWrite(led2Pin, LOW);
}
}
delay(50); // Debounce delay
}
// Store the current button state for the next iteration
lastButtonState = buttonState;
// Flashing LED 1
unsigned long currentMillis1 = millis();
if (currentMillis1 - previousMillis1 >= interval) {
previousMillis1 = currentMillis1;
led1State = !led1State;
digitalWrite(led1Pin, led1State); // Toggle LED state
}
// Flashing LED 2
unsigned long currentMillis2 = millis();
if (currentMillis2 - previousMillis2 >= interval) {
previousMillis2 = currentMillis2;
led2State = !led2State;
digitalWrite(led2Pin, led2State); // Toggle LED state
}
// If siren is activated
if (sirenOn) {
unsigned long elapsedTime = millis() - activationTime;
// Modulate the siren frequency over time to create the police siren effect
if (elapsedTime < 3000) {
// Rising frequency phase
tone(sirenPin, 300 + elapsedTime / 10); // Increase frequency over time
} else if (elapsedTime < 6000) {
// Falling frequency phase
tone(sirenPin, 600 - (elapsedTime - 3000) / 10); // Decrease frequency over time
} else {
// Loop back to the start of the siren cycle after 6 seconds
activationTime = millis(); // Restart the activation time
}
} else {
// Turn off the siren if it's not activated
noTone(sirenPin);
}
// Turn off the siren and lights after 10 seconds
if (sirenOn && millis() - activationTime >= 10000) {
sirenOn = false;
digitalWrite(led1Pin, LOW);
digitalWrite(led2Pin, LOW);
}
}