unsigned long ledTimer, ledInterval = 250; // led interval - 250 = fast wigwag
unsigned long sirenTimer, sirenInterval = 50; // siren interval, 50 = fast warble
byte Led1Pin = 2, Led2Pin = 3, BuzzerPin = 4; // pins for LEDs and buzzer
int count = 1; // siren cycle counter
// int sirenCycles = 10; // larger numbers for testing siren
int sirenCycles = 20; // one full cycle (2 directions)
int sirenTone = 700, sirenDirection = 10; //
bool state = 0, led = 1, siren = 1; // enter sketch led/siren ON
void setup() {
Serial.begin(115200);
pinMode(Led1Pin, OUTPUT);
pinMode(Led2Pin, OUTPUT);
pinMode(BuzzerPin, OUTPUT);
}
void loop() {
if (led) // if the "led" flag is set
ledOn(); // call the LED function
if (siren) // if the "led" flag is set
sirenOn(); // call the siren function
}
void ledOn() {
if (millis() - ledTimer > ledInterval) { // time difference = ledInterval?
ledTimer = millis(); // reset ledTimer
state = !state; // on/off/on/off...
if (state) { // when state is HIGH
Serial.print("Siren cycle ");
Serial.print(count);
Serial.print(" RED ");
}
if (!state) { // when state is LOW
Serial.println("BLU ");
}
// alternate on/off state of LEDs
digitalWrite(Led1Pin, !digitalRead(Led1Pin)); // state
digitalWrite(Led2Pin, !digitalRead(Led1Pin)); // opposite state
}
}
void sirenOn() {
if (millis() - sirenTimer > sirenInterval) { // time difference > interval?
sirenTimer = millis(); // reset timer
sirenTone += sirenDirection; // change frequency up/down
tone(BuzzerPin, sirenTone); // make the tone
if (sirenTone < 700 || sirenTone > 800) { // frequency range
sirenDirection = -sirenDirection; // change frequency direction
if (count == sirenCycles) { // make two cycles (1) up (2) down
sirenOff(); // turn off siren
}
count++;
}
}
}
void sirenOff() {
Serial.println("\nSiren OFF");
digitalWrite(Led1Pin, LOW); // turn off red LED
digitalWrite(Led2Pin, LOW); // turn off blu LED
noTone(BuzzerPin); // turn off siren
siren = 0; // flag to stop going to siren function
led = 0; // flag to stop going to led function
}