Sunday, March 11, 2012

Code for the Potentiometer Controlled Stepper Motor.

I received two requests for the code I used in this demo
------------------------------------------------------------------
#include
AF_Stepper motor1(225, 1);
int analogPin = 0;     // potentiometer wiper (middle terminal)
//connected to analog pin 3
// outside leads to ground and +5V
int val = 0;           // variable to store the value read
int prepos = 0;
int pos = 0; //0 to 224 .
void setup()
{
  motor1.setSpeed(60);  // 30 rpm  
}

void loop() {
 
  prepos = pos;
  val = analogRead(analogPin);    // read the input pin
 
  pos = map (val, 0, 1024, 0, 224);
 
  if (pos != prepos){
    int diststep = pos - prepos;
    if (diststep < 0) {
    motor1.step(-diststep, BACKWARD, INTERLEAVE);
    }
    if (diststep > 0) {
    motor1.step(diststep, FORWARD, INTERLEAVE);
    }
   
  }
 
}
--------------------------------------------------------------------------
AFMotor is the Adafruit stepper library used with their motor shield.
The motor I used has 3.2 degrees rotation per step, but I have the driver in half step interleaved mode, so 1.6 degrees per step. So 360 deg./1.6 deg. = 225 steps per revolution, thus the 0-224 values of pos.

7 comments:

TROGLODISME said...

Hello there, I saw your video and I was trying to use this code but I can't get it to work at all... Are you sure it is the one you are using? Would be amazing to see it working...
why is that " int diststep = pos - prepos; " inside the loop? is that right?
sorry to bother you but this is the only example i found that does exactly what i want but it doesn't move my stepper at all!
thanks a lot

Nick Carter said...

First check that your potentiometer is returning values between 0 and 1024 (1023? need to check that), check that the AF motor library is installed correctly and test basic function of your stepper. The " int diststep = pos - prepos; " determines how far the new position of the potentiometer is from the previous position, so it needs to be in the loop.
Best bet it to ask on the Adafruit forums or the Arduino forums. I'm just a noob myself.

soffer said...

(not sure if last comment made it - page crashed - so just incase...) Thank you for sharing this :-)
Do you think it's possible to do the same using an optical encoder?
Thank you

Felice Luftschein said...

It should be possible, although I think it would be radically different in terms of reading the optical encoder values.

soffer said...

Thought so... :-)
If anyone has an example I'd appreciate the tip.

Unknown said...

hello! nice project. Im trying to make the same and I have one question about the dirver how you use.. can I use diferent driver ?
I have this driver "SMC11" is ok for this project?

Felice Luftschein said...

I'm using an Arduino, I don't know about drivers.