-
format your code with Cntrl+T in arduino
-
put it in code brackets
int value;
for(value = 0; value <= 255; value += 5)
is the same as
for(int value = 0; value <= 255; value += 5)
-
int switchState = digitalRead(2); should just be int switchState = 0; for initialization.
-
in the arduino ide direction (part of int direction = LOW; and other places) is orange colored which means it may already be used my the Arduino as a function or something, change the name a little.
-
just a tip, you dont have to use a int for reading a digital pin, as it is 0 or 1(LOW or HIGH), cant just use a boolean type instead.
-
why do you create another value integer and direction integer in this code?:
else if (sensorValue == LOW){
int value; //here----
int direction = LOW;
digitalWrite(M1, direction);
digitalWrite(M2, direction);
analogWrite(E1, LOW); //PWM Speed Control
analogWrite(E2, LOW); //PWM Speed Control
}
should be like this, i think, if i understand correctly:
else if (sensorValue == LOW){
digitalWrite(M1, direction);
digitalWrite(M2, direction);
analogWrite(E1, LOW); //PWM Speed Control
analogWrite(E2, LOW); //PWM Speed Control
}
- now onto your original question
you may want to try debouncing(http://arduino.cc/it/Tutorial/Debounce), and or interrupt based button press detection:
volatile long lastDebounceTime = 0; // the last time the interrupt was triggered
#define debounceDelay 50 // the debounce time; decrease if quick button presses are ignored
#define BtnPin 2
void setup() {
// put your setup code here, to run once:
attachInterrupt(BtnPin,FireEvent, RISING);
}
void loop() {
// put your main code here, to run repeatedly:
}
void FireEvent()
{
if ((millis() - lastDebounceTime) > debounceDelay)
{
lastDebounceTime = millis();
//switch was pressed, do stuff like turn off your motor.
}
}
hope it helps! feel free to ask more questions.