1

I would like to control my stepper via serial monitor and unfortunatley the code below did not work. Serial monitor works (Serial.println()), but it does not execute the stepperOne() part. Any ideas why would be awesome. Thank you.

#include <AccelStepper.h>

const int stepPin = 5;
const int dirPin = 4;
const int enPin = 12;

String msg;

unsigned int DEST = 800;
unsigned int SPD = 1600;
unsigned int ACCEL = 1600;
const int TEST = 3;

void setup() {

  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
  pinMode(enPin,OUTPUT);
  digitalWrite(enPin,HIGH);
  Serial.begin(9600);  // Start Serial

}

void loop() {

if (Serial.available()>0) {
    msg = "";
    while (Serial.available()) {
      delay(10);
      char tmp = Serial.read();
      // msg += tmp;
     if( tmp!='\r' && tmp!='\n' ) msg+=tmp; // Does not work either
    }
    msg.replace(" ","");
    if (msg=="G") {
      stepperOne();
      Serial.println("Stepper turned.");
    }
    Serial.flush();
  }
}

void stepperOne() {

  AccelStepper stepper(1,stepPin,dirPin);
  digitalWrite(enPin,LOW);
  stepper.setMaxSpeed(SPD);
  stepper.setAcceleration(ACCEL);
  stepper.move(DEST);
  if (DEST > 0) {
    while ( stepper.distanceToGo() > 0 ) {
      stepper.run();
      }
  digitalWrite(enPin,HIGH);
  }
 }
9
  • 1
    It you type "G" in the serial console, it will send "G\r\n" (with an "enter" at the end). Your code doesn't account for the carriage return and newline at the end.
    – Gerben
    Feb 11, 2019 at 15:44
  • How can I account for carriage return ?
    – digit
    Feb 11, 2019 at 15:45
  • 1
    You could opt to ignore it. if( tmp!='\r' && tmp!='\n' ) msg+=tmp;
    – Gerben
    Feb 11, 2019 at 15:49
  • 1
    Stupid question can the Arduino version (older Uno) be the reason for this ? Or am I missing something ? Thanks
    – digit
    Feb 11, 2019 at 15:56
  • 1
    I found the solution, it was the Arduino, older version R2, the R3 works like a charm. I didn't know that the version could cause so much trouble. Sorry.
    – digit
    Feb 12, 2019 at 9:17

1 Answer 1

0

I found the solution, it was the Arduino, older version R2, the R3 works like a charm. I didn't know that the version could cause so much trouble. But in case someone encounters the same problem R3 did it for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.