Sensor and stepper working together

Hello everyone.

I need a sensor to measure a distance to an object and a stepper to rotate the object for multiple points mesurement. I have the codes for both, everithing works fine.
The problem is that i dont know how to combine the codes for them to work together.

Code for sensor:

const int irsensorpin = A0;

void setup() {
  // put your setup code here, to run once:

void loop(){
  // Reads the InfraRed sensor analog values and convert into distance.
  int sensorValue = analogRead(irsensorpin);
  double IRdistance = 187754 * pow(sensorValue, -1.51);
  // A delay is added for a stable and precise input

Code for stepper:

/*Example sketch to control a stepper motor with A4988 stepper motor driver, AccelStepper library and Arduino: continuous rotation. More info: */
// Include the AccelStepper library:
#include <AccelStepper.h>
// Define stepper motor connections and motor interface type. Motor interface type must be set to 1 when using a driver:
#define dirPinX 5
#define stepPinX 2
#define motorInterfaceType 1
// Create a new instance of the AccelStepper class:
AccelStepper stepperX = AccelStepper(motorInterfaceType, stepPinX, dirPinX);
int dirX = 0;
void setup()
  Serial.println("Press a to start the motor and b to stop it.");
void loop()
  char c;
  if (Serial.available()) {
    c =;
    if (c == 'a') {  // start
      dirX = 1000;
      Serial.println("Motor X: running.");
    if (c == 'b') {  // break
      dirX = 0;
      Serial.println("Motor X: offline.");


This tutorial Multi-tasking in Arduino has a complete stepper example controlled by both user input and a temperature sensor.

When dirX is 1000, every time through loop() this is going to tell the stepper to move ANOTHER 1000 steps and then give it an opportunity to maybe move one step.

If you want to move 1000 steps every time through loop(), use .runToPosition() instead off .run(). Of course that will prevent it from looking for new input until the new position is reached.

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