/* drive a step motor with 3 buttons each button as a function: On, Back, Stop An Led will give the right input about the button that is pressed It works with a Nema 17 Motor together with a driver A4988 + a Fabduino AKF or directly my own board the inspiration come from this video: https://www.youtube.com/channel/UCmMfiWIApA-eHCxsMiBcpOQ */ //I include these 2 libraries #include #include //I define the Pins const int motoreDir = 3; const int motoreStep = 10; const int pinBtnOn = 4; const int pinBtnStop = 5; const int pinBtnBack = 6; const int pinEnable = 8; //I use an external LED in order to have a feedback everytime I press a button const int pinLedState = 7; /* Motor speed is in "number of Steps for seconds" As said in description of the "AccelStepper library", max 4000 for an Arduino UNO. 4000 steps per second at a clock frequency of 16 MHz on Arduino such as Uno WATCH OUT IF YOU ARE USING CLOCK OF 8 MHZ */ const float Speed = 100; //Millisecond for the button debounce const int debounceMs = 10; //Stato e direzione boolean avaiable, Direction; //Create an istance for the motor AccelStepper motore(AccelStepper::DRIVER, motoreStep, motoreDir); //Create instance for the buttons Bounce btnOn = Bounce(); Bounce btnStop = Bounce(); Bounce btnBack = Bounce(); void setup() { //set the initial State and Direction (motor stationary) avaiable = Direction = false; //defintions of each pins pinMode(pinBtnOn, INPUT); pinMode(pinBtnStop, INPUT); pinMode(pinBtnBack, INPUT); pinMode(pinEnable, OUTPUT); pinMode(pinLedState, OUTPUT); //set pullUp for the button pins digitalWrite(pinBtnOn, HIGH); digitalWrite(pinBtnStop, HIGH); digitalWrite(pinBtnBack, HIGH); //set Pin state enable and LEd state digitalWrite(pinEnable, !avaiable); digitalWrite(pinLedState, avaiable); //motor settings motore.setMaxSpeed(Speed); motore.setSpeed(Speed); //buttons initialize btnOn.attach(pinBtnOn); btnOn.interval(debounceMs); btnStop.attach(pinBtnStop); btnStop.interval(debounceMs); btnBack.attach(pinBtnBack); btnBack.interval(debounceMs); } void loop() { //refresh buttons states btnOn.update(); btnStop.update(); btnBack.update(); //read buttons values int valStop = btnStop.read(); int valOn = btnOn.read(); int valBack = btnBack.read(); //set actions if (valStop == LOW) { avaiable = false; } if (valOn == LOW) { avaiable = true; Direction = true; } if (valBack == LOW) { avaiable = true; Direction = false; } //change Pin state of the Enable Pin and LEdStato digitalWrite(pinEnable, !avaiable); digitalWrite(pinLedState, avaiable); //if authorized == true if (avaiable) { //depends on the direction value if (Direction) { //set speed and (orientation) motore.setSpeed(Speed); } else { //set other opposite orientation speed motore.setSpeed(-Speed); } //move motor motore.runSpeed(); } else { //if authorized == false //honestly this instruction it's ignored because the Enable Pin is //set to HIGH and so all the other exits FET are switched off motore.stop(); } }