// Define pins for stepper motor control
#define DIR_PIN 8
#define STEP_PIN 9
// Define pins for buttons and limit switches
#define UP_BUTTON 2
#define DOWN_BUTTON 3
#define STOP_BUTTON 4
#define LIMIT_SWITCH_1 5
#define LIMIT_SWITCH_2 6
enum MotorStates
{
STOPPED=0,
MOVING
};
#define BTN_PRESSED LOW
#define LIMSW_PRESSED LOW
const uint32_t kFadeTime = 3000000ul; //3-second ramp time
const uint32_t kInitSpeed = 1000ul; //2x == uS/step
const uint32_t kFinalSpeed = 250ul; //2x == uS/step
const uint32_t kAccelDelay = (uint32_t)(kFadeTime / (kInitSpeed - kFinalSpeed) );
uint32_t
ulStepDelay,
tNow,
tAccel = 0ul;
bool
bAccel;
void setup()
{
// Set pins for motor control as output
pinMode(DIR_PIN, OUTPUT);
pinMode(STEP_PIN, OUTPUT);
// Set pins for buttons and limit switches as input
pinMode(UP_BUTTON, INPUT_PULLUP);
pinMode(DOWN_BUTTON, INPUT_PULLUP);
pinMode(STOP_BUTTON, INPUT_PULLUP);
pinMode(LIMIT_SWITCH_1, INPUT_PULLUP);
pinMode(LIMIT_SWITCH_2, INPUT_PULLUP);
// Set initial state of DIR_PIN to LOW
digitalWrite(DIR_PIN, LOW);
bAccel = false;
}//setup
void loop()
{
static uint8_t
motorState = STOPPED,
pinLimit;
if( digitalRead( STOP_BUTTON ) == BTN_PRESSED )
{
motorState = STOPPED;
}
switch( motorState )
{
case STOPPED:
if( digitalRead( UP_BUTTON ) == BTN_PRESSED )
{
digitalWrite(DIR_PIN, LOW);
pinLimit = LIMIT_SWITCH_1;
ulStepDelay = kInitSpeed;
tAccel = micros();
bAccel = true;
motorState = MOVING;
}//if
else if( digitalRead( DOWN_BUTTON ) == BTN_PRESSED )
{
digitalWrite(DIR_PIN, HIGH);
pinLimit = LIMIT_SWITCH_2;
ulStepDelay = kInitSpeed;
tAccel = micros();
bAccel = true;
motorState = MOVING;
}//if
break;
case MOVING:
tNow = micros();
if( bAccel )
{
if( (tNow - tAccel) >= kAccelDelay )
{
tAccel = tNow;
ulStepDelay--;
if( ulStepDelay == kFinalSpeed )
bAccel = false;
}//if
}//if
if( digitalRead( pinLimit ) != LIMSW_PRESSED )
{
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(ulStepDelay);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(ulStepDelay);
}//if
else
{
motorState = STOPPED;
}//if
break;
}//switch
}//loop