Greetings,
I have a weird problem about a bit of code.
//define pin numbers
const int directionPin = 2;// direction
const int stepPin = 5;// step
...
int detectorLeft = 9; // Left stop sensor
int detectorRight = 11; // right stop sensor
...
// define variables
const int ritardo = 50; // Minimum = 50
int inputCode = 2; // Default is 2 => the machine is stopped
boolean valD;
boolean valL;
...
// declare functions
...
void stepRight(int steps);
void stepLeft(int steps);
void setup()
{
Serial.begin (9600);
pinMode(detectorRight, INPUT);
pinMode(detectorLeft, INPUT);
pinMode(stepPin, OUTPUT);
pinMode(directionPin, OUTPUT);
...
delay(300);
}
void loop() {
if (Serial.available() > 0) {
// read the incoming integer
inputCode = Serial.parseInt();
}
switch (inputCode) {
...
case 9 :
Serial.println("Enter 9");
stepLeft(1000);
break; /* optional */
case 10 :
Serial.println("Enter 10");
stepRight(1000);
break; /* optional */
default :
break;
}
}
...
/* One or multiple steps to the right */
void stepLeft(int steps) {
int count = 0;
while (count < steps) {
valL = digitalRead(detectorRight);
digitalWrite(directionPin, LOW);
count++;
if (valL == 1) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(ritardo);
digitalWrite(stepPin, LOW);
delayMicroseconds(ritardo);
} else {
digitalWrite(stepPin, LOW);
}
}
inputCode = 2;
}
/* One or multiple steps to the left */
void stepRight(int steps) {
int count = 0;
while (count < steps) {
valD = digitalRead(detectorLeft);
digitalWrite(directionPin, HIGH);
count++;
if (valL == 1) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(ritardo);
digitalWrite(stepPin, LOW);
delayMicroseconds(ritardo);
} else {
digitalWrite(stepPin, LOW);
}
}
inputCode = 2;
}
Here is what's happening. When I upload the code and then open the serial monitor, I send the input 10. The monitor prints the message but nothing happens (my stepper motor doesn't run). Then when I type 9 (or anything else), the respective function is called and only now if I type 10, the stepRight() function is called too. it is really weird. I've done a ton of tests and the observations are :
- case switch above 9 don't work (I've tried with case 11) when they're first called after an upload.
- One case switch between 1-9 has to be called before
- The print message is always called (so the program enters the switch case) but the stepRight() is not called.
Thanks for your help