Steppers in a for() loop - error: 'class String' has no member named...(solved)


Fairly new to programming in general so please forgive the basic question.

I’m trying to make a bank of 9 (small) stepper motors move simultaneously using the Accelstepper library. Generally the motors are turning as the should, but rather than reproducing the code to do so 9 times I thought it would be neater make a function with a for() loop. The steppers are called stepper1, stepper2, stepper3 etc and the code to take a step is simply,


But I can’t seem to get the name of the stepper from being a String to an actual usable class name (if this is the right term). Is it not possible to use a for() loop in this way?

The compile error I get is error: ‘class String’ has no member named ‘runSpeedToPosition’

Would really appreciate any advice…

void takeAStep(int stepperNumber) {

for(int m = 1; m < noOfSteppers; m++) {                                    // scan through all motors   
      String currentStepper = "stepper" + m;                               // concatenate the word 'stepper' and the stepper number 'm' to get current stepper name
      currentStepper.runSpeedToPosition();                                 //Take a step
      Serial.println("Stepping motor " + currentStepper);

While I can't tell from your listing, it seems likely that each stepper is controlled by a different pin. If that's true, why not write the function to accept the pin number that controls the stepper as the argument rather than a motor name?

Doesn’t work like that.

Once it is compiled, the variable names ‘stepper1’ ‘stepper2’ etc. don’t exist anymore, so trying to use a String to create a variable name won’t work at all.

You could try making an array of AccelStepper objects:

AccelStepper stepperMotors[noOfSteppers] = {AccelStepper(4,1,2,3,4), AccelStepper(4,5,6,7,8), etc};

and then call:

for(int m = 1; m < noOfSteppers; m++) {                                    // scan through all motors   
  stepperMotors[m].runSpeedToPosition();                                 //Take a step

BTW, next time post ALL OF YOUR CODE! not just a small snippet of code which has no context.

Thanks guys,

Tom - that worked a treat - thanks so much - will post whole code next time...