#include <Stepper.h>
//ULN2003
const int speedPBInc = 18; //define input pin
const int stopPB = 5; //define input pin for Stop push button
const int speedPBDec = 4; //define input pin
const int motorPin[] = {19, 21, 22, 23};
const int direction = 0; //0 for CW, 1 for CCW;
const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution
int speedStep = 1;
int stepMinimum = 40;
int stepMaximum = 178;
int stopType = 0; //0=fully stopped , 1=hold (consumes energy)
int currentSpeed = 115;
int currentSPR = stepsPerRevolution;
#define START 1 //
#define STOP 0
#define CW 1
#define CCW -1
#define MotorInterfaceType 8
int motorStopState = START; //change if you need to
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, motorPin[0], motorPin[1], motorPin[2], motorPin[3]);
//----------------------------------------------------------------------
void setup() {
myStepper.setSpeed(115);
// initialize the serial port:
Serial.begin(9600);
pinMode(speedPBInc, INPUT_PULLUP);
pinMode(stopPB, INPUT_PULLUP);
pinMode(speedPBDec, INPUT_PULLUP);
//attachInterrupt(digitalPinToInterrupt(stopPB), stopMotor, FALLING);
}
//----------------------------------------------------------------------
void loop() {
updateState();
if (!motorStopState) {
currentSPR = 0;
}
else {
currentSPR = stepsPerRevolution;
}
myStepper.setSpeed(currentSpeed);
if (direction == 1) {
myStepper.step(-currentSPR);
}
else {
myStepper.step(currentSPR);
}
}
//----------------------------------------------------------------------
void updateState() {
if (digitalRead(stopPB) == LOW) {
motorStopState = 1 - motorStopState; // stop the motor
if (motorStopState == STOP) {
stopMotor();
}
delay(500);
}
if (digitalRead(speedPBInc) == LOW) {
motorStopState = START;
currentSpeed += speedStep;
Serial.println(currentSpeed);
if ( currentSpeed >= stepMaximum )
currentSpeed = stepMaximum ;
}
if (digitalRead(speedPBDec) == LOW) {
motorStopState = START;
currentSpeed -= speedStep;
Serial.println(currentSpeed);
if ( currentSpeed < stepMinimum ) currentSpeed = stepMinimum ;
}
}
//----------------------------------------------------------------------
void stopMotor(){
if (stopType == 0) {
for (int i = 0; i < 4; i++) {
digitalWrite(motorPin[i], LOW);
}
}
}