Pages

2016/03/05

Controlling NEMA-17 stepper motor speed with trimpot without using Delay()

This post is a summary of how to control the speed of a NEMA-17 stepper motor using a trimpot (variable resistor). The code is done without using the delay function for reason illustrated clearly at the very beginning of the Arduino Blink Without Delay page (see below quote).

"Sometimes you need to do two things at once. For example you might want to blink an LED while reading a button press. In this case, you can't use delay(), because Arduino pauses your program during the delay(). If the button is pressed while Arduino is paused waiting for the delay() to pass, your program will miss the button press."

The Schematic



The Code
---------------------------------------------------------------------------------------------------------------------
int motorState = LOW;                    // motorState used to set the motor
unsigned long previousMillis = 0;        // Store the last time the stepper motor direction was changed

void setup() {
  Serial.begin(9600);

  // Setup the motor control pins
  pinMode(A3, INPUT);           // Trimpot input for motor RPM control (0: Slowest, 1023: Fastest)
  pinMode(6, OUTPUT);           // Motor Direction Pin
  pinMode(7, OUTPUT);           // Motor Step Pin
  digitalWrite(6, LOW);         // Set the motor direction  
}

void loop() {
  unsigned long currentMillis = millis();   // Read the current time

  int x = analogRead(A3);                   // Read the trimpot (speed control) value on pin A3 into x

  //Serial.print("Analog value: ");       // Display the trimpot value via serial monitor
  //Serial.print(x);
  //Serial.print(" ");

  int d = (x/50) * 1;    // RPM range is adjusted by changing the multiplier, was 100
                          // * 1 -> RPM Range: 60 (counter clockwise) ~ 3 (clockwise)
                          // * 2 -> RPM Range: 60 (counter clockwise) ~ 1 (clockwise)
  //  Serial.println(d);

  if (d <= 1) d = 1;    // Get rid of d = 0 to give enough delay for stepper motor to function properly
  //Serial.print("Delay: ");
  //Serial.println(d);

  // Check to see if it's time to change the motor step state (HIGH -> LOW, LOW -> HIGH). If the difference between the current time and the last time
  // the state was changed is greaer than the interval, it's time to change the state.

  if (currentMillis - previousMillis >= d) {
    // save the latest time the state is changed
    previousMillis = currentMillis;

    // Change the state
    if (motorState == LOW) {
      motorState = HIGH;
    } else {
      motorState = LOW;
    }

  digitalWrite(7, motorState);
  }
}

---------------------------------------------------------------------------------------------------------------------

Reference:

Blink Without Delay
https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

No comments:

Post a Comment