Hi guys! I'm having trouble with some code and am hoping somebody could help me out.
What I'm trying to accomplish:
I have 1 digital input (pin 7), 1 digital output (pin 2), and the pin 13 LED also set as an output. What this program should do is turn ON the LED and pin 2 should be set to HIGH when there is no change in the input signal for 3 or more seconds.
For example: If the input is LOW for 3 seconds, both pin 2 and LED should turn ON. However, if the input signal is switching from HIGH to LOW or LOW to HIGH continuously, we want the LED to stay OFF and pin 2 set to LOW.
Current problem I'm running into:
I'm currently connecting my Arduino to a function generator (I'm using square wave pulses to simulate a digital signal). The LED and pin 2 turn off immediately when I power on the function generator which is awesome, but after a short delay, they will turn back on. I've made sure all my physical connections are correct and I believe it is my code that has some kind of problem...
Here's my code:
// these won't change:
int signalIn = 7; // the pin that the input signal is attached to (digital input)
int led = 13; // the pin that the LED is attached to (output)
int signalOut = 2; //the pin that we are setting the output signal to (digital output)// Variables that will change:
int counter = 0;
int currentState = 0;
int previousState = 0;
int signal = 0;void setup() {
// initialize pin 7 as an input:
pinMode(signalIn, INPUT);
// initialize the LED as an output:
pinMode(led, OUTPUT);
//initialize pin 2 as an output:
pinMode(signalOut, OUTPUT);
// opens serial port, sets data rate to 9600 bps
Serial.begin(9600);
}void loop(){
signal = digitalRead(signalIn); // read input value
if (signal == HIGH)
{
currentState = 1;
}
else
{
currentState = 0;
}
if(currentState != previousState)
{
counter = 0;
digitalWrite(led, LOW);
digitalWrite(signalOut, LOW);
}
else
{
counter = counter + 1;
}
Serial.println(counter);if (counter >= 3000)
{ digitalWrite(led, HIGH);
digitalWrite(signalOut, HIGH);
}
previousState = currentState;}
I'd GREATLY appreciate it if someone could take it a look at it. If you need me to go into more detail please ask!