I am trying to move a stepper motor when a specific command is send to Arduino Mega 2560. This command is read character by character and stored in a string variable. Whenever a new command is sent, an act should be performed. However, it is not happening and I believe that the problem is in reading the sent command. I tried clearing the character and string variables, but to no avail. The sketch should run a loop that moves the motor clockwise or counterclockwise according to the command sent, which can be "crx*" for clockwise or "clx*" for anticlockwise, where "*" is the reading stop criterion of the characters.
Any suggestions what to do?
The script:
void(* resetFunc) (void) = 0;//Reset turn
// Stepper Motor X
const int stepPinX = 2; //X.STEP
const int dirPinX = 5; // X.DIR
const int pinEnable = 8;
// String read
char c;
String readString; //main captured String
// Unit steps
double av_len = 1.029; //medium length
double interval;
int cnt_steps = 0;
const int num_d = 200;//parameterized step
int fact = int(num_d / av_len);
int unit_len = fact * 1;//unit length (1mm)
void setup()
{
// Sets pins as Outputs
pinMode(stepPinX, OUTPUT);
pinMode(dirPinX, OUTPUT);
pinMode(pinEnable, OUTPUT);
digitalWrite(pinEnable, HIGH);//lock driver on cnc shield
Serial.begin(115200);
Serial.setTimeout(1);
while (1) {
while ( (Serial.available() == 0) )
{
}
if (Serial.available()) {
c = Serial.read(); //gets one byte from serial buffer
//Serial.println(readString);
if (c == '*') {
Serial.println(readString);//test response
if (readString == "crx") {
cnt_steps = cnt_steps + 1;
Serial.println(cnt_steps);
digitalWrite(pinEnable, LOW);
digitalWrite(dirPinX, HIGH);
for (int x = 0; x < unit_len; x++) {
digitalWrite(stepPinX, HIGH);
delayMicroseconds(500);
digitalWrite(stepPinX, LOW);
delayMicroseconds(500);
}
}
else if (readString == "clx") {
cnt_steps += -1;
Serial.println(cnt_steps);
digitalWrite(pinEnable, LOW);
digitalWrite(dirPinX, LOW);
for (int x = 0; x < unit_len; x++) {
digitalWrite(stepPinX, HIGH);
delayMicroseconds(500);
digitalWrite(stepPinX, LOW);
delayMicroseconds(500);
}
}
digitalWrite(pinEnable, HIGH);//lock driver on cnc shield
c = (char)0;
Serial.flush();
readString = "";
//resetFunc();
}
else {
readString += c; //makes the string readString
}
}
}
}
void loop() {
}
