Beginner - Stepper motor help

Hi, I am trying to write some code for a project to move a stepper motor whenever one of 4 buttons is pressed. Each button is laid 90 degrees apart around the motor in a circle, the motor will essentially point to the button that has been pressed and then to the next one that is pressed etc. (I will later swap the buttons for sensors but for now I am just using buttons)

Could someone show me an example code for how this could be done? I expect I will need to do some if/else logic and set up states for each different movement but I am not exactly sure what this would look like.

Also, when the stepper is turning 180 degrees I would like to make is random whether it goes clockwise or anticlockwise, how would I do this?
And how can I make the motor know which position it is pointing in upon startup so that it isn't out of sync?

I am using a 200 step 2 phase motor (
and an Uno with an adafruit motorshield V2 (Adafruit Motor/Stepper/Servo Shield for Arduino v2 Kit [v2.3] : ID 1438 : $19.95 : Adafruit Industries, Unique & fun DIY electronics and kits)

Here is the code I am starting with, it is working fine to move the stepper so far:
StepperCode.ino (1.2 KB)

The answer to that question is to add a sensor of some type, possibly a microswitch, that your program will move the stepper motor to in the setup() part of your program.

1 Like

If You read the first topic telling how to get the best from the Forum You will notice "code tags" for posting code. Many helpers can't, or just don't want to fill up their computers with code from members.
More helpers will read it and reply.

My tutorial on Multi-tasking in Arduino includes a complete stepper example driven by a sensor and user commands. You can add your button inputs in place of the commands.

I presume you want 90 degree moves to be the short direction and 180's to be random? Perhaps write a function that takes the previous and current button's as
arguments and figures out whether to return +90, -90, +180 or -180, and then map that to step counts?

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.