Stepper Motor Position Using Button Presets

The code is really similar to what you see in hundreds of tutorials. You just need to combine various techniques.

As the stepper has no way to know where it is upon boot, you might need a homing process - ie you move the motor in one direction until you reach a known position that you define as position 0. For that you need a sensor (limit switch, magnet, …) marking this position. As you do that once, this is typically done in the setup() part of the code.

Then the code just loops waiting for a command to do something.

To handle the buttons I’d suggest you use one of the numerous button library such as Button in easyRun or OneButton or Toggle or EasyButton or Bounce2, ...

When you detect a button press, A B C or D you move to that position. You’ll need to have a way to define how many steps are needed or when you arrive. You could either hardcode the number of steps (the position from home) or have sensors along the way to mark the A, B, C and D positions.

Hardcoding the position makes the code simpler but might be error prone over time as your motor could miss steps and you would not end up in the exact location you wanted to be.

Having sensors at the target positions makes it more precise and if you order the path HOME ➜ A ➜ B ➜ C ➜ D and you know you are say at HOME and want to go to C, you’ll know you need to go forward until you registered 3 sensor’s hits (A then B then C). If you are in C and want to go back to A you can do the math and know you need to go backwards until 2 hits (B and A) are recorded.

Activating a solenoid requires some specialized circuit as your pin likely won’t have the power nor the protection needed for such an operation. You’ll need a relay / mosfet / with suitable diode (freewheel) protection and then it is just a matter of setting the control pin HIGH or LOW to drive the load.

Finally, you need to decide if the code is blocking while operating or if you need to be able to change your mind (ie you click on D and realize you wanted to click on C - can you click on C right away and the code will adjust or do you need to wait until D has been reached to send the C command ?)

I would suggest you start small:

  • learn the basics about C++, Arduino, the IDE. Play with simple tutorials, blink LEDs etc
  • Learn to handle whatever sensor you’ll use. Limit switches are just buttons so a library comes handy.
  • learn to drive the stepper forwards backwards up to a sensor
  • Learn to handle your solenoid correctly (with suitable protection)

If you want the asynchronous non blocking approach, you might benefit from studying how to handle time and asynchronous processes

Once you master all the building blocks, you’ll see that your project is not so difficult and we can help along the way

1 Like