Send data to Arduino via Serial

You're getting closer.
I think that you want to be sending and then parsing a message with both the direction and the number of steps.
For example "1,234\n".

You can follow the Serial Input Basics example number 5 and use strtok, to separate the lead character of the message at the comma and use atoi to convert the remaining text to a number.

Alternatively, but less generically, you can easily determine the first character in the receivedChars character array which is at receivedChars[0] and then you use atoi on the receivedChars after the comma with atoi(&receivedChars[2])

#include <Stepper.h>
int stepsPerRevolution = 0;
Stepper motor1(stepsPerRevolution, 50, 51);
const byte numChars = 32;
char receivedChars[numChars]; // an array to store the received data
boolean newData = false;

void setup() {
  Serial.begin(115200);
  motor1.setSpeed(200); //RPM - MAX: 370
  Serial.println("");
}

void loop() {
  recvWithEndMarker();
  showNewData();
  stepperControl();
}

void recvWithEndMarker() {
  static byte ndx = 0;
  char endMarker = '\n';
  char rc;

  while (Serial.available() > 0 && newData == false) {
    rc = Serial.read();

    if (rc != endMarker) {
      receivedChars[ndx] = rc;
      ndx++;
      if (ndx >= numChars) {
        ndx = numChars - 1;
      }
    }
    else {
      receivedChars[ndx] = '\0'; // terminate the string
      ndx = 0;
      newData = true;
    }
  }
}

void showNewData() {
  if (newData == true) {
    Serial.print("This just in ... ");
    Serial.println(receivedChars);
    //newData = false;
  }
}

void stepperControl(){
  if (newData == true)
  {
    if (receivedChars[0] == '1')
    {
      Serial.println("Right");
      stepsPerRevolution = atoi(&receivedChars[2]);
      Serial.print("stepsPerRevolution ...");
      Serial.println(stepsPerRevolution);
      motor1.step(stepsPerRevolution);
    }

    else if (receivedChars[0] == '2') {
      Serial.println("Left");
      stepsPerRevolution = atoi(&receivedChars[2]);
      Serial.print("-stepsPerRevolution...");
      Serial.println(-stepsPerRevolution);
      motor1.step(-stepsPerRevolution);
    }
    newData = false;
  }
}
1 Like