Im trying to start and stop a program. It definitely start when i press the button but as i soon press the button again, it wont work. it continuously on the loop.
here is the code:
int run;
int buttonPin;
int stepPin = 11;
int dirPin = 10;
int enPin = 9;
int LimitSwitch_LEFT_Pin = 3;
int LimitSwitch_RIGHT_Pin = 5;
boolean bIsRaining = false;
String strRaining;
int nRainIn = A1;
int nRainDigitalIn = 2;
int nRainVal;
void setup() {
Serial.begin(9600);
run = 0;
buttonPin = 4;
pinMode(buttonPin, INPUT_PULLUP);
pinMode(2, INPUT);
pinMode(LimitSwitch_LEFT_Pin , INPUT);
pinMode(LimitSwitch_RIGHT_Pin , INPUT);
pinMode(stepPin, OUTPUT); // Sets the two pins as Outputs
pinMode(dirPin, OUTPUT);
pinMode(enPin, OUTPUT);
digitalWrite(enPin, LOW); // Set Dir to Home switch
digitalWrite(dirPin, HIGH); // Enables the motor to move in a particular direction
digitalWrite(buttonPin, HIGH);
}
void loop() {
if (digitalRead(4) == LOW)
{ if (run == 0)
{
run = 255;
}
else
{
run = 0;
}
}
if (run > 0)
{
nRainVal = analogRead(nRainIn);
bIsRaining = !(digitalRead(nRainDigitalIn));
if (bIsRaining) {
strRaining = "YES";
digitalWrite(3, LOW);
digitalWrite(5, HIGH);
digitalWrite(11, HIGH);
digitalWrite(enPin, LOW); //habilita em low invertida
digitalWrite(dirPin, HIGH); // low CW / high CCW
}
else {
strRaining = "NO"; //habilita em low invertida
digitalWrite(dirPin, LOW);
digitalWrite(5, LOW);
digitalWrite(3, HIGH);
}
int leftSw = digitalRead( LimitSwitch_LEFT_Pin);
int rightSw = digitalRead( LimitSwitch_RIGHT_Pin);
if ( (leftSw == HIGH && (digitalRead(dirPin) == HIGH)) ||
(rightSw == HIGH && (digitalRead(dirPin) == LOW)) ) {
motorStep(1);
}
else if ( leftSw == LOW && (digitalRead(dirPin) == HIGH) ) {
digitalWrite(dirPin, LOW);
delay(2000);
}
else if ( rightSw == LOW && (digitalRead(dirPin) == LOW ) ) {
digitalWrite(dirPin, HIGH);
delay(2000);
}
}
}
void motorStep( int MAX) {
for (int x = 0; x < MAX; x++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(500);
digitalWrite(stepPin, LOW);
delayMicroseconds(500);
}
}