Im working on with a stepper motor but im having problem with a pushbutton…
My function only needs to run once and that is when arduino is powered… so i put my function in setup() so it will only run once.
void setup(){
MoveHome();
}
void MoveHome(void)
{
int sRead = digitalRead(HOME_SENSOR);
if (sRead != lastButtonState2) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
state = sRead;
}
lastButtonState2 = sRead;
if(state != lastButtonState) {
lastButtonState = sRead;
pressCount++;
}
// Seek home sensor switch first
if (digitalRead(HOME_SENSOR)==LOW){
digitalWrite(dirPin,HIGH);
for(int x=0;(x<200) && (digitalRead(HOME_SENSOR)==LOW);x++){ // 200*1.8 = 360
digitalWrite(clkPin,HIGH);
delay(20);
digitalWrite(clkPin,LOW);
delay(20);
//this works when arduino is powered on it starts rotating and when it hits the switch and goes from LOW to HIGH.. the motor reverse the rotate for double checking..
}
}
// Then move out of home sensor
digitalWrite(dirPin,LOW); // change direction
for(int x=0;(x<200) && (pressCount%4==0);x++){ // 200*1.8 = 360
digitalWrite(clkPin,HIGH);
delay(20);
digitalWrite(clkPin,LOW);
delay(20);
//Here comes the problem when it hits the switch again it does not stop instead it rotates until x=200 and then stops.. it must break when it hits the switch again meaning it is really the end of the flag.
}
present_position = 0;
}
Why is it not stopping when it hits the switch?.. thanks.
yeah dat’s my problem but how can i read inside a for loop… i’ve been having a hard time doing it… can u give me a sample on how to read a button inside a for loop.
if i change it to like this i need to hold down the button for it to rotate then if i release it will stop… though it works but not what i needed…
snapshots:
yeah dat’s my problem but how can i read inside a for loop… i’ve been having a hard time doing it… can u give me a sample on how to read a button inside a for loop.
if i change it to like this i need to hold down the button for it to rotate then if i release it will stop… though it works but not what i needed…
I’m not exactly certain, but I think your problem is you don’t know about the break statement - ie:
for (int x=0; x < 200; x++) {
if (digitalRead(HOME_SENSOR) == HIGH) {
break; // exit for-loop
}
}
// here is what is executed when the above loop "breaks"
Maybe you can take the above code and make it work for what you need to do?
or (int x=0; x < 200; x++) {
if (digitalRead(HOME_SENSOR) == HIGH) {
break; // exit for-loop
}
}
as
this one…
f
or(int x=0;(x<200) && (digitalRead(HOME_SENSOR)==HIGH);x++){
//things to do if HOME_SENSOR is HIgh
//break if HOME_SENSOR is low
}
//things to do after break;
Am i Ryt?..
what i need to achieve is:
-BUtton starts at low then rotate motor
-If button is pressed reverse the motor
-if button is pressed again then break… thus stopping the motor.