How to control almost continuously a Stepper motor

Good morning everyone!
I have the following problem: I am using an Arduino Nano to control a stepper motor through an A4988 driver so that it moves according to some specific rotation protocols. I would like to obtain a motor rotation according to the wave in the figure attached, representing the evolution of the angular position during 1 second. Any suggestions about the code or useful libraries?

Thank you very much!

You could put a series of positions in an array of positions and send the elements of the array to the stepper. Here is code to illustrate that method. Adjust the stepper speed to accomplish the series in the time that you want.

#include <AccelStepper.h>

const unsigned int NUM_STEPS = 6;

unsigned int xArray[NUM_STEPS] = {0, 3, 65, 40, 65, 10};

const byte enablePin = 8;

AccelStepper stepper(AccelStepper::DRIVER, 2, 5);

void setup()
{
   Serial.begin(115200);
   pinMode(enablePin, OUTPUT);
   digitalWrite(enablePin, LOW);
   stepper.setAcceleration(2000);
   stepper.setMaxSpeed(200);
   stepper.setSpeed(200);
   stepper.setCurrentPosition(0);
}

void loop()
{
   static unsigned int index = 0;
   if (stepper.run() == 0)  // stepper stopped. load next position and run
   {
      Serial.println(index);
      stepper.moveTo(xArray[index]);

      index++;
      if (index >= NUM_STEPS)
      {
         index = 0;
      }
   }
}

Something like this (for AccelStepper):

int index = 0 ;
int data [MAX_DATAPOINTS] {.....}

void loop()
{
  static unsigned long timepoint = 0 ;

  stepper.run() ;  // YOU MUST CALL THIS OFTEN FOR AccelStepper to work

  if (millis() - timepoint > MS_PER_DATAPOINT)  // every MS_PER_DATAPOINT milliseconds
  {
    timepoint += MS_PER_DATAPOINT ;

    if (index < MAX_DATAPOINTS)  // wrap index for endless repeat
      index = 0 ;
    stepper.moveTo (data[index++]) ;  // setup new destination
  }
}

[ not complete example, just showing the method ]

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.