I am using a 1.8 Resolution Stepper Motor controlled by a L298N driver and Arduino Mega. I have attached the ACE 128 Absolute encoder to the motor to use it as a closed loop system. The idea is for the motor to remember its absolute position even when the power is turned off. The code I am using is the following: however, when I run this the motor doesn't seem to reach its desired position. Any advice please? Thanks in advance!

//Libraries to include
#include AccelStepper.h
#include ACE128.h
#include ACE128map12345678.h // mapping for pin order 12345678 

#include Wire.h // I2C bus communication library - required to support ACE128

//Define stepper pins
AccelStepper stepper1(4, 11, 10, 9, 8); //4 = full steps for 4 wire stepper motor (8 for halfsteps)
                                        //MEGA pins 11, 10, 9, 8 connected to IN1, IN2, IN3, IN4 of driver pins

//defto different Arduino Mega pins (e.g. pin 2 arduino mega connected to pin 1 encoder, etc)
ACE128 myACE(2,3,4,5,6,7,8,9, (uint8_t*)encoderMap_12345678); //Arduino MEGA pin 2 connected to pin 1 of encoder, etc...
int16_t SOURCE; //variable to hold multiturn value of encoder (-32768 to 32767)
//uint8_t rawPos = 0;

//Stepper Travel Variables
long Travel_1; //Used to store motor 1 value entered in serial monitor
int move_finished = 1; //Used to verify move is completed

void setup() {
  int error = 1;
  Serial.begin(9600); //Start Serial monitor with speed of 9600 bauds
  //Print out instructions on Serial Monitor at Start
  Serial.println("Enter Travel Distance Values");
  Serial.print("Enter Move Values Now: ");

  stepper1.setMaxSpeed(100.0); //Set max speed of stepper
  stepper1.setAcceleration(500.0); //Acceleration of stepper

  myACE.begin();    // initialise encoder library

void loop() {
  while (Serial.available()>0) { //Check if values are in serial buffer

  Travel_1 = Serial.parseInt(); //Put first numeric value from buffer in Travel_1 variable
  Serial.println("Stepper 1 travel, ");

  stepper1.moveTo(Travel_1); //move to target position
  delay(1000); //Wait 1s before moving stepper


  if (stepper1.distanceToGo() != 0) {

    stepper1.run();  // Move Stepper 1 into position


  //Check if steppers have moved to desired posiition
  SOURCE = myACE.mpos();  // encoder reads POSITION stepper has moved to

  if(SOURCE != Travel_1) { //if there is difference between desired and actual position
    stepper1.run(); //Run stepper 1 until reaches desired Travel_1 position 

  //If move is completed display message on Serial Monitor
  if ((move_finished == 0) && (SOURCE == Travel_1)) {
    Serial.println("Enter nex move values"); //Get ready for new serial monitor values
    move_finished = 1; //Reset move variable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.