Hi,
I have the following code that runs in loop and i only want it to run once when the sensor is activated. Ive tried putting it in the setup and leaving the loop section blank, however Im told that the loop section is required in an arduino program. Can someone tell me how to rewrite this code to only run one time when the sensor is activated?
int sol = 13;
int sen = 3;
void setup() {
pinMode(sol, OUTPUT);
pinMode(sen, INPUT);
}
void loop() {
int val = digitalRead(sen);
if(val == HIGH){
digitalWrite(sol, LOW);
delay(250);
}else{
digitalWrite(sol, HIGH);
delay(1000);
}
}
If you want the section of code to only run when an input goes true, you set a flag that prevents the block of code from rerunning until the flag is cleared by the input signal going false.
in your example above your code is OUTSIDE the setup() block
Im a beginner and have no idea what you mean. haha Im trying to learn by reading the arduino book...but it doesnt address this specific issue.
Could you write it out for me?
thanks Larry. The issue i have is that each time this runs, the relay is switched three quick times before the program runs. it activates a solenoid for a pneumatic piston. So it rapid fires for 3 times before running the program.
I need to find a way to make the program run one time, when a limit switch is closed so that the pneumatic piston extends for a second and then retracts.
Here is what i have
arduino unoR3
a limit switch
a relay
solenoid
a pneumatic cylinder
Here is what i want to happen:
When something hits the limit switch, i want it to turn the relay on for 1 second and then off. so that the pneumatic cylinder goes down and then up again. Its needs to stay up, until the limit switch is tripped again.
Correction--Here is what i have
arduino unoR3
a limit switch
laser and sensor
a relay
solenoid
a pneumatic cylinder
Here is what i want to happen:
When something hits the limit switch, it turns off the laser which causes the relay to turn on for 1 second and then off. so that the pneumatic cylinder goes down and then up again. Its needs to stay up, until the limit switch is tripped again.
Thanks Steve. Im trying my best...haha
Im a welder/fabricator and know nothing about electronics. Im trying to learn this so i can complete the project Im building.
One way is to put all your code in the setup() function, using an if statement to test when the switch has been activated.
Then as mentioned above add:
void loop()
{
}
What will happen is your solenoid would operate one time, the program will proceed to the loop() which has no instructions. The processor will continually go through the loop but not do anything except test the loop function.
The only way to have it run again is to cycle power to the board or push the reset button.
There are ways to control how often an action can be activated. So it is possible to write code so your solenoid would actuate no more than once a minute, or once an hour or once every