In the code below I would like the stepper to bounce back and forward between two limit switches and while it is doing this it should turn and than wait for e.g. 1 second.
I thought I could achieve this with the if ((unsigned long)(currentMillis - previousMillis) >= interval)
part, but it doesn't work.It won't turn. Any help would be great. Thank you.
// defines pins numbers
const int stepPin = 5;
const int dirPin = 4;
const int enPin = 12;
const int homeSwitchPin = 9;
const int homeSwitchPin2 = 11;
unsigned long interval=1000; // the time we need to wait
unsigned long previousMillis=0; // millis() returns an unsigned long.
void setup() {
Serial.begin(9600);
// Sets the two pins as Outputs
pinMode(stepPin,OUTPUT);
pinMode(dirPin,OUTPUT);
pinMode(homeSwitchPin , INPUT);
pinMode(homeSwitchPin2 , INPUT);
pinMode(enPin,OUTPUT);
digitalWrite(enPin,LOW);
// Set Dir to Home switch
digitalWrite(dirPin,LOW); // Enables the motor to move in a particular direction
}
void loop() {
int homeSw = digitalRead( homeSwitchPin);
int homeSw2 = digitalRead( homeSwitchPin2);
if( homeSw == HIGH && (digitalRead(dirPin) == LOW) ){
unsigned long currentMillis = millis();
if ((unsigned long)(currentMillis - previousMillis) >= interval) {
motorStep(1);
previousMillis = millis();
}
}
else if( homeSw == LOW && (digitalRead(dirPin) == LOW) ){
digitalWrite(dirPin,HIGH);
delay(2000);
}
if( homeSw2 == HIGH && (digitalRead(dirPin) == HIGH)){
motorStep(1);
// motorStep(32000);
//digitalWrite(dirPin,LOW);
//delay(2000);
}
else if( homeSw2 == LOW && (digitalRead(dirPin) == HIGH) ){
digitalWrite(dirPin,LOW);
delay(2000);
}
}
void motorStep( int MAX){
for(int x = 0; x < MAX; x++) {
digitalWrite(stepPin,HIGH);
delayMicroseconds(100);
digitalWrite(stepPin,LOW);
delayMicroseconds(100);
}
}
bounce back and forward
between waits? ...... your description is unclearprint()
s to determine if you are actually hitting the contents of theif()
statement?