I have a switch that triggers when it gets pushed
A physical switch WILL NOT give you accurate end stops. They are used for emergency stops on CNCs (everything has turned to mud at this point), but they are not typically used to provide an accurate home position. Using a switch (at both ends of your travel I assume) will therefore be inaccurate for your scanning.
You should use an opto interrupter to produce your home signal (at one end of your travel, and a typical methodology is:
- If not Home, seek to home at slow speed
- When home signal occurs, stop (this may involve slowing down)
- Seek forward at really slow speed till Home disappears and stop
- Seek forward for Home offset and set Zero position
You now have an Home position that is your Zero count and can seek to your maximum count and back to the Zero position. You then only need the Home flag for initialization.
Home sensors such as this work well and provide reasonable accuracy (0.1-0.2mm or better) when you use the narrow aperture version.
If you are dealing with cheap Arduino type sensors such as this, which are analog then you can have significant drift in your home sensor position with temperature. I don't recommend them.
how do I reverse the direction when it gets to the end?
You don't specify what type of H-Bridge you are using to drive the stepper. Assuming that you are using an A4988 or DRV8825 then you already produce your Step/DIR signal in your MCU. All you need to do to scan is:
- Start scan from Zero, set DIR and step count (you may be doing acceleration and deceleration control of course)
- Stop at step count
- Scan reverse to Zero, set DIR and step count
- Stop at Zero
If you are using something more primitive to drive the stepper, you really should consider moving to Step/Dir control, it will reduce your software development considerably.
There would seem to be no reason to try and implement a hardware direction change, since this would mean the accuracy of the trip points would depend absolutely on your switch, which will not be accurate. Your stepper motor count is way more accurate and repeatable.