I am working on an Arduino project for Halloween. There are lights connected to a relay and sound is played using an Adafruit FX board. The code will automatically trigger a flash every 35 seconds. I also have a remote control relay connected to A2 and 5V that is being used to manually trigger it. The issue I am having is if I turn the relay on it will keep activating again and again. I want it to only activate once every time the relay is activated. The code I am using is written by Chat-GPT. I asked it to fix the issue and it had many solutions but none of them worked. I did add a 2-second delay to it so I have 2 seconds to turn it off but if the remote comes out of range it will still flash continuously.
My code:
// Pin Definitions
const int lightningPin = A6; // Pin for lightning effect
const int buttonPin = A2; // Pin connected to remote relay (A2) to manually trigger lightning
const int soundPin = A4; // Pin to send a pulse for sound activation
unsigned long previousMillis = 0; // Stores last time the lightning flashed
unsigned long lightningInterval = 35000; // Interval for automatic lightning (20 seconds)
unsigned long flashDuration = 175; // Duration of each lightning flash (100 ms)
bool lightningActive = false; // To track whether lightning is flashing
bool buttonPressed = false; // To track the button state
void setup() {
pinMode(lightningPin, OUTPUT); // Set lightning pin as output
pinMode(buttonPin, INPUT); // Set button pin as input
pinMode(soundPin, OUTPUT); // Set sound pin as output
digitalWrite(lightningPin, LOW); // Start with lightning off
digitalWrite(soundPin, HIGH); // Start with sound off
Serial.begin(9600); // Initialize serial communication for debugging
}
void loop() {
unsigned long currentMillis = millis(); // Get current time
// Check if the button (A2) is pressed for manual activation
if (digitalRead(buttonPin) == HIGH && !buttonPressed) {
triggerLightningAndSound(); // Trigger both lightning and sound
Serial.println("Triggered by button press!");
buttonPressed = true; // Prevent multiple triggers from a single press
delay(2000);
}
// Reset button state when released
if (digitalRead(buttonPin) == LOW) {
buttonPressed = false;
}
// Automatic lightning effect every 20 seconds
if (currentMillis - previousMillis >= lightningInterval) {
triggerLightningAndSound(); // Trigger both lightning and sound
Serial.println("Automatically triggered!");
previousMillis = currentMillis; // Reset timer for next interval
}
}
void triggerLightningAndSound() {
// Simulate a quick lightning flash
digitalWrite(lightningPin, HIGH); // Turn lightning on
delay(flashDuration); // Keep it on for flash duration
digitalWrite(lightningPin, LOW); // Turn lightning off
// Activate sound with a quick pulse
digitalWrite(soundPin, LOW); // Ensure pin starts LOW
delay(500); // Short delay (debounce)
digitalWrite(soundPin, HIGH); // Send pulse to sound pin (trigger sound)
}
Thank you so much for your help!!!