gpop1:
study blink with out delay example and look at INPUT_PULLUP. you will need to change the code example to suit a input .
int ledPin = 13; // choose the pin for the LED
int inPin = 8; // choose the input pin (for a pushbutton)
byte forceOff = 7;
unsigned long previousMillis = 0;
unsigned long interval = 5000;
byte lightled = 0;
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(forceOff, INPUT_PULLUP); // declare LED as output
pinMode(inPin, INPUT_PULLUP); // declare pushbutton as input
}
void loop() {
unsigned long currentMillis = millis();
byte val = digitalRead(inPin); // read input value
byte offbutton = digitalRead(forceOff); // read input value
if ((val == LOW) && (offbutton == HIGH)) {
lightled = 1;
}
if (offbutton == LOW) {
lightled = 0;
}
if (lightled == 1) {
if (currentMillis - previousMillis <= interval) {
digitalWrite(ledPin, HIGH); // turn LED ON
} else {
lightled = 0;
}
} else {//lighted not equal 1
digitalWrite(ledPin, LOW); // turn LED OFF
previousMillis = currentMillis;
}
}
Most of those brackets are unnecessary and only serve to make the code harder to read.
It can be done more simply, too.
Since Brian's original version used active-high inputs, I've kept true to that, since I thought there might have been a good reason, but they're easily converted to active-low with input pullups and 'hard' resistors removed if necessary:-
// Connect pushbuttons between input pins and +5V. (Not 12V)
// and resistors from input pins to ground.
const byte pLED = 13; // LED on pin 13, active-high.
const byte inSig1 = 8; // First input signal on pin 8, active-high.
const byte inSig2 = 7; // Second input signal on pin 7, active-high.
unsigned long prevMillis; // Will hold millis() count.
void setup()
{
pinMode(pLED, OUTPUT); // Make LED pin an output.
pinMode(inSig1, INPUT); // Make signal pins inputs.
pinMode(inSig2, INPUT); // " " " "
}
void loop()
{
while (digitalRead(inSig1) == LOW){} // Wait for first signal.
digitalWrite(pLED, HIGH); // Got first signal - turn LED on.
prevMillis = millis(); // Save current 'millis' value.
while (millis() - prevMillis < 5000) // Keep LED on for 5 seconds.
{
if (digitalRead(inSig2) == HIGH) // Check if second signal has arrived and if so
break; // break out of 'while' loop.
}
digitalWrite(pLED, LOW); // Turn LED off.
while (digitalRead(inSig2) == HIGH){} // Wait for second signal to end before continuing.
}
Either way, now Brian's seen two different ways of doing it.
There's more than one way to skin a cat. (39, according to the robot in 'Lost in Space'.
)
And Brian, note that the second pushbutton/input signal is connected to pin 7.