Hi, im having trouble writing code for a relay that i want to turn on if a value is received from analog pin 0. The problem is that i want the if statement to stop looping after one run. Heres what i have so far:
const int rPin = 8; // the number of the Relay pin
void setup() {
pinMode(rPin, OUTPUT);
}
void loop() {
int val = analogRead(0);
val = map(val, 0, 1023, 0, 10);
if (val == 9) {
// turn LED on:
digitalWrite(rPin, HIGH);//Turn on the relay
delay(850);//wait for the drive to open all the way
digitalWrite(rPin, LOW);//Turn off the relay
}
delay(10);
}
If I understand you correctly, something like this might be your best bet:
const int rPin = 8; // the number of the Relay pin
bool stop = false;
void setup() {
pinMode(rPin, OUTPUT);
}
void loop() {
if (stop)
return;
int val = analogRead(0);
val = map(val, 0, 1023, 0, 10);
if (val == 9) {
// turn LED on:
digitalWrite(rPin, HIGH);//Turn on the relay
delay(850);//wait for the drive to open all the way
digitalWrite(rPin, LOW);//Turn off the relay
stop = true;
}
delay(10);
}
You might want to put in a delay, because this code will loop very fast when stop is set. If you want to stop the program completely, of course you could do that also, but I'm guessing you don't want that.