Hardware h2.0

= Overview =
The device consists of two separate blocks: 
# The controller unit (139x98x57 mm 3D-printed plastic enclosure of my design), containing a single PCB of my design with most of the electronics: WeMos D1 Mini microcontroller, DRV8825 Stepper Motor Driver board, ST7735 color LCD display, I/O Expander chip MCP23S17, LD1117V33 Voltage Regulator for 3.3V, 4x4 keypad, a mini-piezo, two LEDs, power switch, power connector, RJ45 connector (for connecting to the motor unit), a few resistors, capacitors, and a transistor, and a battery holder for 8 AA batteries.
# The motor unit: stepper motor attached to the Velbon Mag Slider macro rail with two steel brackets and a shaft-to-focusing-knob coupler, in an aluminum DIY enclosure, with a small breadboard (two optocouplers - for camera's shutter and AF control), connectors: RJ-45 (for the controller) and 3.5mm stereo-phone socket (for the camera). The other addition is two limiting micro-switches glued to the plastic top of the macro rail - this is essential to prevent the rail hitting the two physical limits while in operation. (Once properly calibrated, the rail is programmed to never hit the switches. Re-calibration should be rarely required, and is easily accomplished by pressing a two-key command "#C".)
I use a standard Ethernet (Cat 5/6) patch cable to connect the controller unit to the motor unit (this is the only cable connecting the two modules). The cable has 8 wires, and handles everything: driving the stepper motor (4 wires), driving the camera shutter and autofocus (two wires), reading the limiting switches on the rail (one wire), plus the common ground wire. Only straight 8-wire Ethernet patch cables can be used (with my design, connecting a crossover cable by accident shouldn't damage anything, but don't take any chances!). Also, since h1.3 only AWG 24 or 22 versions of Cat5 cables can be used; other kinds are too thin and will result in poor motor torque. One of the important advantages of Ethernet patch cables compared to many other types of cables is the fact that Cat 5/6 connectors securely lock to sockets, so the chance of disconnecting during the rail operation is minimized. This is critical, as disconnecting the stepper motor cable during its operation will likely fry the motor driver circuits.
IMPORTANT While working on h2.0 I discovered (using an oscilloscope) the source of the fake limiter switches triggering which has plagued all my prior hardware versions. As I always suspected, this was due to the electromagnetic interference inside the Cat-5 cable, from high voltage/current stepper motor wires, to the low voltage/current wire used to read the state of the two limiting switches. The interference voltage spikes were very short (0.4 us) but high in amplitude - up to 1.3V, in both positive and negative directions. This was already causing issues with my older (h1.x) designs, where the 5V logic was used, and became a major issue in h2.0 where I switched to 3.3V logic. Fortunately, I found the solution - one has to solder a small (3.3-10nF) ceramic capacitor right on top of the microcontroller, between the limiter reading input pin (D8 in h2.0) and the ground pin. This results in the noise spikes being dramatically stretched (to 15-50 us), which correspondingly reduces their amplitude. The timings are still short enough not to affect the limiting switches performance. I haven't tried it, but the same hack will likely fix this issue on the older hardware as well (h1.x).
Here is the list of the essential parts I used (USD; prices include shipping). Important: as most of the parts I used are no longer available from the original sellers, below I listed parts which appear to be identical or similar to my parts - but there is no guarantee they are an exact match. You might have to modify slightly the PCB or the enclosure to accomodate them.
Part 	Price ($)	Comments
Velbon Super Mag Slider 	110 	A decent quality manual focusing rail. Has both a focusing knob (this is the one which will be driven by the stepper motor in this project) and a side motion knob (remains fully functional in this project). The rail remains fully functional for its original purpose (manual focusing) after the modifications; one has to simply unscrew the motor unit and remove the two micro-switches glued to the plastic cover of the rail. The Neewer Pro 4-Way Macro Focusing Focus Rail seems to be essentially identical to the Velbon rail, for half the price, but I have no experience with it.
Stepper motor 	12.00 	Nema 17 stepper motor with low enough resistance (<4 Ohm per coil) and high enough amperage (>1.3A per coil) to provide very decent torque when powered from 10V (8 AA batteries) or 12V AC adapter. 4 wires, 1.8 degrees steps. 5mm shaft with one side flat.
WEMOS D1 Mini Rev.1 (based on ESP8266) 	2.90 	Microcontroller
1.8" 160x128 pixels TFT LCD (based on ST7735 chip; SPI interface)	9.10 	Color 160x128 pixels LCD display. This is the 11-pin version I happened to have (8-pin version is now more common).
DRV8825 Stepper Motor Driver 	2.40 	Stepper motor driver with up tp 32 microsteps/step and up to 2.2A/coil rating. Has a tiny pot which I set to the maximum motor current my motor + AC adapter can handle (1.5A/coil), to maximize the torque.
8 AA batteries box 	3.80 	
4x4 keypad 	3.77 	These are real (comfortable) keys, not a cheap membrane keyboard.
16-ports SPI I/O Expander chip MCP23S17-E/SP 	2.00 	CAD $2 + shipping on digikey.ca / mouser
LD1117V33 Voltage Regulator 3.3V 950mA TO-220 	0.67 	CAD $0.84 + shipping on digikey.ca / mouser
2 pcs of Sharp PC817 optocouplers 	0.88 	To independently operate the camera shutter and autofocus. CAD $1.10 + shipping on digikey.ca
Stereo headphone socket 3.5 mm 	2.99 	The price is for 10 pieces; you need only one. This is to connect your camera to the motor unit. One could also use 2.5mm stereo socket (which would match the Yongnuo shutter cable available for Canon and Nikon DSLRs), but only the 3.5mm model can be found as a screw type, which makes it more durable.
Motor brass coupler 	5.00 	You need a rigid coupler with the 5mm hole on one side (for the motor shaft), and a hole matching the screw you attach to the focusing knob on the other side (7mm in my case).
Two RJ45 sockets 	1.00 	One goes inside the motor unit, the other one - inside the controller unit.
Mini-piezo PKM13EPYH4000-A0 	0.37 	CAD 0.46 on digikey.ca
8-pin, 2.0mm pitch connector and cable 	- 	For the keypad
2-pin, 2.54mm pitch connector x 2 	- 	For the battery module, and for the power switch
Rocker 2-way power switch 	1.30 	
DC 5.5-2.1 power jack connector 	0.25 	For the external 12V AC power supply
NPN transitsor BC547 	- 	Almost any NPN transistor will do. Used to operate the mini-piezo
Resistors(1/4W - 1/8W) 	- 	1k x 4, 3k, 8.2k, 10k x 2, 68k
Capacitors 	- 	10nF, 22uF x 50V, 47uF x 16V, 100uF x 35V, 220uF x 16V
Red and green LEDs 	- 	One red and one green LEDs, round, 3mm diameter.
I already had some other parts (nuts and bolts, wires, sheet metal for DIY brackets and metal enclosure, breadboards etc.). 
Microswitches: I couldn't find good micro-switches (small enough, but with fairly long levers) on ebay, but I managed to find good ones in a local surplus store, 1$ apiece. The ones I have have 30mm long levers, and importantly - the "overtravel" distance is more than 1.0mm (this distance is critical, as it determines the breaking distance during calibration; if it's smaller than 1.0mm it will result in significantly higher deceleration required during calibration, which is bad for the rail). I haven't tried these, but they might work: SS-3FL111P-3 (1.0mm overtravel), or these (1.2mm overtravel).
The essential non-trivial tools you'll need:
* Drill press with a drill press vise. I almost ruined my Velbon Mag Slider by trying to drill the holes for the motor brackets with a hand-held drill. The Velbon is made of a special kind of hardened magnesium alloy, with the nasty property that when one uses a hand drill to make a hole, the drill bit travels a lot sideways (can be 2-3 mm), which will make it impossible to attach motor brackets properly. I ended up buying a drill press because of this. (But I always wanted to have one.) With a drill press one can do a much better job - just make sure the head doesn't move much sideways (<0.5 mm), and make the exposed part of your drill bit fairly short (so it doesn't bend much).
* Taps and dies set. You'll need these to cut a thread (M4 is about right) in the Velbon rail, for four bolts, to attach two motor brackets to the rail.
* Fret saw (or coping saw): to make rectangular holes in the aluminum (motor unit) enclosure - for the RJ-45 socket.
= Motor unit =
The most critical step (don't do anything else until/unless you've succeeded with this one): proper coupling between the stepper motor and the focusing knob of the Velbon rail. Unfortunately the core of the focusing knob is made of (very hard) plastic, not metal:
In addition, it has a hole in the middle (you'll see it once you remove the rubber covering of the knob), so one has to be very careful with creating the coupling to the motor:
May be I was lucky, but I happened to have some old steel furniture screws laying around, with the threaded part which fitted perfectly the hole inside the focusing knob. I just had to carefully screw the bolt into the hole keeping it parallel to the knob axis, until the wider screw part touched the end of the knob:
(To give you the scale in the above image, the full length of my screw is 45.6 mm; the inner thread diameter is 4.14 mm, the outer thread diameter is 5.90 mm; the thread length is 11 mm.) I didn't use any glue. At the end, the screw was sitting almost perfectly parallel to the knob's axis, and very tight (I couldn't turn it with my hand):
Another great feature of the screw was that the non-threaded part is a solid metal with exactly 7mm diameter. I managed to find on ebay a nice metal coupler from 7mm to 5mm (the shaft diameter of the stepper motor I used) which worked perfectly with the screw I had (I just had to cut off the head of the screw). I couldn't find identical furniture screws on ebay, but hopefully you can find something similar in a local store, or perhaps will come up with another idea on how to couple the plastic knob with the motor.
The motor shaft shaft happened to be a bit too long for my brackets, so I ended up cutting ~2-3mm from the shaft's end. Warning: the motor shaft is made of extremely hard steel, so no regular saw will do the job. I used a Dremel knockoff tool with a cutting disk, and took extreme precautions to make sure no metal particles could enter the motor - you can very easily ruin your motor if you are not careful, as it has very strong magnets inside. (I wrapped the motor in multiple layers of kitchen plastic wrap, with just a minimum hole for the shaft.) 
Warning: before doing anything to the focusing knob, you have to remove it from the Velbon rail - otherwise you will likely damage the mostly plastic bearings inside the rail. Once you attached the screw to the knob, cut off its head, and shaved off one side, you can put the knob back into the rail. Check the post #3 here for the instructions on how to remove the focusing knob from the rail.
The next critical step is to find (or make - as I did) two metal (best if steel or iron) brackets shaped like this : [ ] . They should be thick enough (probably at least 1.5 mm; I used 3mm iron) to provide a good support to the motor unit, and should be made with a high accuracy: the longer side should have the same length for the both brackets, and the shorter sides should be exactly parallel to each other, for each bracket. On one side the short ends will be attached to the Velbon rail (to the left and to the right from the focusing knob); you'll have to use a drill press to make four holes in the Velbon rail (very close to the edges of the rail - make sure the holes don't go inside the rail and potentially damage the rail's bearings), and then use taps and dies set to cut a thread inside the holes (I did M4 threading). The stepper motor will be attached to the opposite shorter sides of the brackets. (I used only two diagonally placed bolts in the motor to attach the motor to the two brackets; the remaining two bolts were left unattached).
The length of the longer side of the brackets will be determined by the length of the exposed part of the focusing knob + the length of the exposed part of the screw you put inside the focusing knob + the length of the motor shaft. You don't have to be super-accurate here, as the coupler gives you a bit of a leeway in terms of the distance between the motor and the rail. Drilling the two holes for the motor in the short sides of the brackets should be the last operation here: you want to find such locations for the holes that the motor shaft is almost exactly on the same axis as the focusing knob, or else the motor will not have enough of torque to move the rail. I accomplished this step by securing the coupler to the motor shaft (tightening a bolt), inserting the screw put inside the focusing knob inside the coupler (don't secure it with a bolt), and then finding the positions for the two holes on the short sides of the brackets for the two motor bolts. 
This is how it looks like assembled (warning - this is the h1.x version, with relays; in h2.0 I replaced the relays + resistors + diodes with 2 optocouplers):
The remaining steps are much less critical. One can put a metal (better aluminum) enclosure around the brackets, which has multiple purposes:
* It simplifies attaching the small bread board to the motor unit.
* It makes the motor attachment to the rail more tight and secure.
* It hides all the wiring inside.
* It prevents you from turning the focusing knob by hand - this is bad because it breaks the rail calibration, and it can also burn your motor driver (by induced voltage) if the controller is attached to the motor unit.
* It looks nicer and more professional.
Warning: when designing the brackets and the enclosure, make sure that the bottom part of the assembly doesn't protrude below the bottom of the rail (specifically the top part of the rail, with the focusing knob), otherwise you won't be able to use the detachable bottom part of the rail, with the manual knob to move your camera sideways:
This is not absolutely essential, but it would be a pity if the bottom part of the rail was wasted, and the sideway motion knob does simplify the job of macro-photography.
Then you should make a small breadboard and solder there the two relays, two diodes, two resistors, two external connectors (RJ-45 and 3.5 mm phone) and ideally a couple of internal connectors (for the motor and the limiting micro-switches; this will make it easier to disassemble the motor unit).
Finally, you need to attach the two limiting micro-switches to the rail, in a way that one of them would be triggered before the rail hits one of the physical limits. When a switch is triggered, there still should be enough of travel distance - 2 mm or more - left for the rail to properly decelerate and stop. The only way I could attach my micro-switches to the rail was by gluing them with a super-glue to the plastic cover of the rail, at a slight angle (to ensure there is the required 3mm gap when the switch is triggered). This worked pretty well:
Then you have to solder the switches sequentially, in a way that normally (when switches are not engaged) the two wires going to the controller unit would be shorted, and only if one of the switches is triggered the connection would be broken. This is used by Arduino to calibrate the rail (to make sure that the rail will never trigger the switches during its normal operation.) With time the calibration will be lost, so a re-calibration would be required once in a while. Calibration is triggered automatically if during its normal work the moving rail will trigger one of the switches, or one can request a re-calibration manually.
= Controller unit =
In h2.0, the controller unit is completely redesigned. It has all new electronics components, with most of them soldered to a factory-manufactured PCB, inside a 3D-printed enclosure.
== 3D printed enclose ==
Thingiverse link for the design of my 3d-printable enclosure for the controller unit:
https://www.thingiverse.com/thing:4946939
I did the design using the free software Autodesk Fusion 360. I included the Autodesk design files on the thingiverse page. This design is paramteric, so you can adjust many of the parameters without the need to redo the whole design.
I printed all parts in ABS (but any other filament will do) on my modified Anet A8 3D printer, using 0.2mm layers and 25% infill. I needed supports for the bottom part (which has two bars for securing the battery compartment). 
The only tricky part was the battery compartment lid - you'll need to play a bit with it's parameters (width and thickness of the exterior part which slides inside the slots of the enclosure), until the lid slides inside with just the right amount of friction, and also clicks properly when it is fully inserted.
The thingiverse page also has designs for a couple of printed parts for the PCB - a raiser/holder for the two LEDs, and two small cylinders to support one side of the LCD module (the other side is supported by header raisers).
== PCB ==
I designed a 2-layered PCB (94x99 mm) for the controller unit using the web-based tool https://easyeda.com . Then I used that design to produce the PCB (Fabrication > PCB Order; the manufacturing site is https://jlcpcb.com/). The costs for manufacturing (in China) and express shipping was 16$ US (for 5 copies of the PCB). It took around 10 days to get the boards. The only issue (which was resolved) was the confusion around the area where the voltage regulator (LD1117V33) is screwed to the PCB. They thought that that area is a cutout, but I clarified that this is not a cutout, but rather an area without any silk (so the heat conduction is better).
Here are the JSON files for my schematic and PCB:
* Schematic
* PCB
In all likelihood you will have to modify a bit the PCB design, as some of your parts will likely be slightly different. https://easyeda.com allows you to design and re-design your own PCB, with a convenient auto-routing option.
You have to check and recheck multiple times all the connections before attempting to power it on for the first time. It is especially critical for the camera shutter connectors: make it absolutely sure you are not sending high voltage inside your DSLR by mistake. Test this with any new Cat5/6 cable you plan to use with the rail.
Warning: never let anyone to attach your rail to a networking device (computer, laptop, router) via Cat5/6 cable! I use RJ-45 sockets and Cat5/6 cables here for convenience; they have nothing to do with Ethernet. If somebody does attach the rail to another device, this will most likely burn the networking board on that device, and might also burn the motor driver in the controller unit. It wouldn't hurt to put a red label on your controller unit next to the RJ-45 socket with such a warning.
= Schematic =
Controller schematics:
Notes for the schematics:
* R1 value. The smaller the better (minimizes interference inside the Cat5 cable from the stepper motor high-current wires -> minimizes a chance of a false limiting switch triggering - but the actual solution was adding the capacitor C5; see below), but cannot be smaller than 275 Ohm (because otherwise the DP of the microcontroller will get overloaded - it cannot handle more than 12 mA). Also, if it is too small, too much current will be constantly wasted (a problem when running from batteries). 3.3k (resulting in 1 mA constant current loss) is a good starting point. The current is still 4x larger than in my old setup where I used internal Arduino pullup resistors (5V/20k=0.25 mA current).
* R2 / R3 values. This is a voltage divider. The values of 68k and 10k allows one to safely measure the input voltage up to 3.2V*(10k+68k)/10k=25V, which is a good safety margin for the actual voltage (12V). The constant current flow is 12V/(10k+68k)=150uA which is perfectly acceptable.
* R4 / R5 values. These are current limiting resistors for the two PC817 optocouplers (located inside the motor unit). Forward voltage for these is 1.2V. With the logic voltage 3.3V, with 1k limiting resistor we get current (3.3V-1.2V)/1k ~ 2mA. With CTR>=0.5, this can drive the load up to 1mA - likely sufficient to trigger shutter and AF of the DSLR. Also, 2mA is large enough to minimize the noise induced by the stepper motor wires in the same Cat5 cable. If the noise is till too large and/or the output current is not large enough to trigger the shutter/AF, you can decrease R4/R5, with the smallest allowed value being 42 Ohm (results in the maximum allowed input current - 50 mA). For the reference, my 3D Scanner gadget uses 5V/200 Ohm = 25mA input current with PC817, and that is sufficient to trigger my Canon 6D shutter and AF.
* R6 value: probably around 10k. Transistor BC545 has hFE=110-800. The one I have has hFE=329. Maximum collector current Ic is 100 mA. (That means that the load resistance cannot be smaller than 12V/100mA=120 Ohm.) With R6=10k, the base current is 0.33 mA, this is more than enough to get the full 100 mA load current (0.33 mA * 329 = 109 mA). From this calculator, even with the smallest load resistance (120 Ohm), the base resistor <= 10.9k can completely saturate the transistor. So R6=10k should work for any allowed load.
* R7 value. R7 is the discharge resistor for my passive mini-piezo (PKM13EPYH4000-A0). The datasheet suggests the value of 1k, so it's a good starting point. You can play with it trying to increase the piezo volume (make sure not to overload the transistor - it can handle loads up to 100 mA). With the piezo's capacitance C=5.5nF and R7=1k, the RC timing is 190 kHz - more than enough to work well at the rated frequency of the piezo (4 kHz).
* R8 / R9 values. Choose values when the red and green LEDs have similar brightness, and comparable in brightness to the TFT display. My red LED is much brighter than the green LED, so my values are quite different for the two resistors (8k and 1k).
* C4 value, 47 uF. With R3=10k, forms an RC filter with the frequency of 0.3 Hz - should be sufficient to smoothen measuremnt noise for the VCC voltage.
* The ceramic capacitor C5, 10nF (in red) is not a part of the PCB. Instead, it should be soldered directly to the top of the microcontroller board, between the pin reading the state of the rail's limiting switches (D8) and the ground. Without it, the pin would get very strong impulse noise from the Cat5 cable (interference with the stepper motor wires) - 1.2V impulses (both negative and positive), 0.4 us long, once every 10 us or so. As a result, you'd get constant fake limiter switches triggering. A 10nF capacitor completely solves this problem.
Motor unit schematics:
== RJ-45 sockets ==
RJ-45 socket (view from the bottom of the breadboard):
This is the wiring I did for the RJ-45 socket I got on ebay. The one you have might have a different layout.
You can only use a straight (not crossover) Cat5/6 patch cable!. Test first any cable you plan to use with the rail.
Here is the RJ-45 pin assignment:
* 1 (white-orange): camera shutter
* 2 (orange): common ground
* 3 (white-green): camera autofocus
* 6 (green): micro switches
* 4,5 (blues) : motor A
* 7,8 (browns): motor B
The pin assignment was done to minimize the risk of damaging anything if you by accident connect a wrong (crossover) patch cable. In a crossover patch cable, the following pins are swapped: 1<->3, 2<->6. As you can see, using a crossover cable will render the macro rail non operational, but will not send the high voltage / high current motor signals to a wrong destination. Still, better be safe than sorry, so always test any Cat5/6 cable you plan to use (to make sure it is a 8-wire straight cable) before using it in your rail!
= Electronic shutter adapter = 
Starting from s1.14, my rail supports Full Resolution Silent Picture mode of Magic Lantern (alternative firmware for Canon cameras), which is basically electronic shutter (great for extending the lifespan of your camera when doing focus stacking). Very importantly, I figured out and implemented a way to use the electronic shutter with an external flash, which is a must for focus stacking. This required a new software feature - mirror_lock=2 mode, and soldering a simple adapter consisting of one 3.5mm stereo jack, one 3.5mm stereo socket, and a hot shoe for flash (I use it to connect it to my RF flash controller, YN-RF603, which wirelessly triggers my flash, YN-560III). The purpose of the adapter is to let the shutter relay inside my rail to operate an external flash. (Under FRSP, photos are taken by using the AF switch, not the shutter switch.)
Here is the schematics for the adapter: