Video Gives you the Basics of DIY Rotary Encoders

Is it really possible to build a rotary encoder out of a flattened tin can and a couple of photodetectors? Sure it’s possible, but what kind of resolution are you going to get from such a contraption? Is there any way that you’d be able to put them to work in a DIY project like a CNC router? If you pay attention to the basics then the answer is yes, and [HomoFaciens] wants to prove that to you with this detailed video on homebrew encoder design.

Faithful Hackaday readers will no doubt recognize [HomoFaciens] from a number of prior appearances on these pages, including this recent hardware store CNC router build. When we first ran across his builds, we admit a snicker or two was had at the homemade encoders, but if you watch the results he manages to get out of his builds, you quickly realize how much you can accomplish with very little. The video is a primer on encoder design, walking you through the basics of sensing rotation with phototransistors, and how a pair of detectors is needed to determine the direction of rotation. He also discusses the relative merits of the number of teeth in the chopper; turns out more isn’t necessarily better. And in the end he manages to turn a car wiper motor into a high-torque servo, which could be a handy trick to have filed away.

45 thoughts on “Video Gives you the Basics of DIY Rotary Encoders

      1. True, not a stepper, but a servo that is better, in many ways, than a stepper. I’ve done this with the super fine optical encoders from inkjet printers. It’s possible to program an arduino to accept step-and-direction inputs from another arduino with GRBL firmware, and operate the motors just like you would a stepper, with its step-and-direction controller’s inputs.

  1. Pretty neat. The encoders in modern servos are pretty amazing, I have some Yaskawa Sigma V servo motors, 50 and 100W and about the size of a NEMA 17 motor. The come standard with 20bit absolute encoders, that 1,048,576 counts per rev. Insane, the new Sigma 7 series has 24bit encoders (16.7mil counts per rev)

      1. There are a few advantages of high resolution encoders. One is you may not need a gearbox for an application where you needed higher resolution than the encoder technology of the time allowed. One example is telescope mounts. Most mounts are driven by a worm gear and have periodic error inherent from the worm driving the main gear. With a high res encoder you can eliminate the gearbox and drive the telescope directly which really comes in handy for stuff like astrophotography. Also no backlash from a gearbox to give you issues. Of course there can be an issue of inertial mismatch which could make tuning a PITA.

        Most of these drives that run these high resolution encoders also have built in electronic gearing functions where you can turn down the resolution of the encoder to match a specific need. Say you are using the drive in step/direction pulse mode and you want a ballscrew attached to move a rational numerical distance instead of something with lots of decimal places, with a high res encoder you can come up with a ratio to get you there.

        Also higher encoder count motors run smoother, especially at very low speeds.

        Yes, these motors are pretty expensive new. I think the new price on one of the Sigma V series 100W motors is somewhere over $2000 and then you still have to buy the drive. But on ebay you can buy the servos used for about $100 and I scored a bunch of NIB drives for about $40 each. Though they usually sell for a lot more, I got incredibly lucky. I use servos in just about all my projects, my Monarch lathe has a 5kw Mitsubishi for the spindle motor, my CNC Mill has Mitsubishi 1kw motors on X and Y, 1.5kw on Z and a 3.5kw on the spindle. The laser cutter I had used dc brushed motors with Elmo drives, my CNC lathe uses Mitsubishi servos, and my Laser welder uses older Yaskaw Sigma IIs. The telescope mount I have been building uses Mitsubishi servos as well.

        If you ever build a machine with servos I highly, highly recommend using more recent servo/drive packages from Mitsubishi or Yaskawa/Omron. Series MR-h or MR-J2 or newer for the Mitsu and Sigma II or newer for the Yaskawa. They have spent an incredible amount of time on the auto tuning and it gets better on every iteration of the drives. They can handle instantaneous load changes and you pretty much dont have to do anything tuning wise once you install them. The cheap brushless servos coming out of china like the Leadshines and even the nice Granite drives out of europe dont hold a candle to the ease of operation and installation that the Mitsubishi and Yaskawa drives have.

          1. There are a lot of drive variants in the same series for both Yaskawa and Mitsubishi. Some are more useful than others like with the ability to use step/direction, analog, or encoder following inputs. Others use serial communication protocols that are not useful outside of industrial automation, If you have any questions about selecting a servo/drive combo let me know.

            Here is an old video I made for someone to demo the encoder follow mode on the Mitsubishi drive: https://www.youtube.com/watch?v=FT5Z4nvCtxo

        1. High resolution is not the same as accuracy, and much of all this is marketing.

          Most industrial rotary encoders use an analog sine/cosine output signal in addition to some sort of serial absolute position indication. You can then, with A/D-conversion of the sine/cosine signal, calculate the inverse tangent and decide if you need a high resolution or a high frequency signal or both.

          There are some propietary industrial encoders like the abovementioned 20-bit encoders, but you will have trouble decoding the high-bitrate serial signal, because the baudrate is usually in the high megabit range. Most microcontroller UARTs can not handle this – you need an FPGA. The benefit of using a high-res serial encoder is marginal, because with the conventinal sine/cosine output signal (128, 256 or 512 periods per revolution are commonplace) you get the same accuracy. Or better. The question really is not about resolution but accuracy. Any industry-standard rotary encoder nowadays is by far more precise than the mechanical drivetrain, if you use anything other than a direct drive without belts or gearing. And then again, the question is if you need high accuracy or highly dynamic positioning in milliseconds. Control loop autotuning as also a de-facto standard on a wide variety of servo drives. But with the analog encoder solutions, you have a much wider choice of cheap used hardware.

          My suggestion would be to use a drive that is not only cheap but that has a well-documented interface (e.g. CANopen, EtherCAT) that you can use for your future DIY projects and that you can interface to your PC or to the BeagleBone or whatever.

          1. Good to see there is another expert to consult if I need industrial encoders. Yes, documentation is essential and the better it is, the more time it saves you. And another yes: Resolution is nothing without accuracy. When making a video it is always good to have a bad device to demonstrate the weak points and a good one to show that there are always ways around those shortcomings.

  2. Great resource, lots of hand information in that video. The printer part hack is interesting, I wonder if you could hack an old floppy drive to me a magnetic encoder wheel. 28 sectors of 512 bytes would let you have 7168 divisions each with their own 16 bit position code, or an accuracy of 0.05 degrees. You would not need the steppers in the floppy drive, just a disk with the sector/byte code pattern and the read head. Actually if it can do 28×512 bytes on the shorter inner tracks the outer track should be able to hold many more sectors, so 0.01 degrees accuracy may be possible.

    1. Assuming it has to read the data in the sector you would have a problem if you stopped mid way in an encoder and interrupted the read. There are magnetic encoders out there. Some of them are not bad.

      1. Oh you can fix that with a bit pattern across tracks so when you start up you rotate onto a bit then sweep the head to read the position, then when you know that off you go. You can even use a 16 bit shift register pair and N/AND gates to set and forget the position you need to rotate to. Load target into register 1 and when the input bit stream off the disk matches, it triggers a stop. However that does not let you do nice stuff with acceleration deceleration control, for that you need an MCU or FPGA watching the bits come in.

        1. I guess the head of a floppy drive only can read data while the disc spins with a certain revolution speed. Remember that the signal is caused by induction and the induced voltage is lower the lower the disc speed becomes. You won’t get a clear signal when starting/stopping that special encoder disc.

          1. That may be a fatal problem, would need to test for that first. I doubt the details of the performance of “final generation” floppy disk drive read write heads was ever published but it would sure be handy to have those specs. I’m going to put it on my list of things to hack because I’m sure the embodied geometry and precision in those drives can be utilised is some similar way.

          2. Problem solved, like the finding the position issue when paused, just oscillate the head arm and you induce the signal. Remember we have complete control of the bit pattern on the disk so the outer track can be 3 normal tracks wide. Even then you may only need a movement of less than a full track width.

    2. We did something similar for an electric harvester project years ago. (Commercial prototype, not home hacking.)
      The motor had hall effect sensors built into the stator that detected the poles of the rotor passing over them. They were positioned on the different phases of the stator; 3 phase motor, so 3 detectors.
      We’d get a 3-bit gray pattern. Downside was similar to that of mechanical encodes however: the hall sensors still needed debouncing to get an accurate count.

  3. How well would ink/toner block infrared I wonder? You could thoretically “print” a rotor encoder onto overhead transparency film and cut that out, stick it to a clear plastic disc to make a more precise rotor. Careful positioning of the detectors on the stator should let you get pretty high resolutions.

    1. Wouldn’t bother. You can take apart an inkjet printer and get a high resolution (thousand(s) pulses/rev) encoder wheel from the shaft that moves the paper. Plus you get the matching quadrature optical sensor.

    2. I tried that, but the signal wasn’t as good as with the metal disc. With my (old, chep laser printer) it is comparable to the absorption of paper as demonstrated in the video. Maybe with a better laser printer you can create encoder discs on overhead film – give if a try.

  4. It appears that my first attempt at posting to this page was blocked for reasons unknown. I tried posting it again thinking that I somehow improperly pressed the ‘post comment’ button, but was instantly greeted with a message saying that I had already posted that message. Many hours have passed, and still my message is nowhere to be found.

    I am forging on, with hopes that some day, or year, it will somehow make its way here. I now am providing further information on creating optical encoders with the inclusion of the link to information, software, and templates, to aid in the creation of these optical encoders.

    http://www.mindspring.com/~tom2000/Delphi/Codewheel.html

    Hope this is helpful.

      1. And just how did you arrive at that conclusion, since my first post cannot been seen?!

        How could it be because of a link, being there is a link in the comment to which you are responding to?

          1. I think once you’ve been posting a while, your links go through anyway. Either that, or certain links are whitelisted on a site-by-site basis. And maybe a blacklist too. Who knows?

  5. How does one coordinate 3 of these in a cnc (say with grbl)? I realize you could use a PID algorithm for each, but if x gets to its target before y, then the result will be off. Hmm, I just realize grbl sends only one step at a time so maybe the amount of being off is not so much.
    So would a cnc just use a pid on each for only 1 step? It seems like that would move slow (on grbl at least ).
    If not issuing grbl, but some other controller that requests “x go 50 and y go 1000”, how would one coordinate the PIDs to arrive at the same time?

    1. Of course you have to ensure that both axes are synchronized which is achieved by transmitting only single steps, thus a straightforward PID algorithm makes (almost) no sense. grbl uses more complex algorithms to optimize machine speed:
      “Grbl includes full acceleration management with look ahead. That means the controller will look up to 18 motions into the future and plan its velocities ahead to deliver smooth acceleration and jerk-free cornering.”

    2. The cnc control has a trajectory planner that calculates how fast each axis needs to go and handles calculating for acceleration/deceleration which is all in there. Also with a CNC machine the PID loops are much, much tighter and more responsive so there is very little you have to compensate for there. Also the better drives have a feed forward gain setting that compensates for the follow error inherent in servos.

      1. The trajectory planner in GRBL (which controls acceleration) has nothing to do with the motor/PID. GRBL only accelerates the rate of issuing steps to whatever motor controller that is downstream( between GRBL and the motors).

        So my question remains.

        Can you explain the “feed forward”? (I don’t understand how you can possibly achieve full speed with a servo if the motor controller only knows that a single step has been requested by grbl – it doesn’t know if another step is coming so it can’t spin to max rpm or it may overshoot).

        I’m finishing my cnc build with steppers/GRBL so this topic interests me (checkout my YouTube videos using my user name).

        1. I researched and answered my question:

          Even though grbl only outputs a single step at a time for each axis, your motor controller can keep track of the total steps and thus the absolute position required. Use that as the target in the servo code which continually updates the motor position (full PID code could be in effect I think!!) Pretty neat.

        2. I dont use GRBL, I was referring to what happens in commercial controls that actually control the whole servo loop, something like a FANUC control.

          In a step/direction mode the pulses go into a counter and the servo drive just tries to keep up with it, basically. The newer drives have a lot of smarts in them to make them run well.

          Feed forward is not something I have really had anything to deal with, I usually dont used it on the drives I use. More info can be found here: http://support.ctc-control.com/customer/elearning/younkin/currentFeedForward.pdf

        3. Hi,

          > I don’t understand how you can possibly achieve full speed with a servo if the motor controller only knows that a single step has been requested by grbl – it doesn’t know if another step is coming so it can’t spin to max rpm or it may overshoot.

          The answer is, indeed, you can not achieve “full speed” with a multi-axis servo drive unless there is a superordinated closed-loop controller for the tracking error of the multi-axis system.

          I.e. the position controller must be fed back every axis true momentary position and be able to compare this with the requested setpoint. The actuating (or correcting) variable can then simply be the (time) parameter of the (3D) curve setpoint. By the way, IMO, you can design the system such that the superordinated controller is able to “turn back time” if negative corrective action is needed. It is also possible to control the advancement speed of the curve parameter instead of the paramter istself.

          The simplest form of this for a DIY system can be to slow down the generation of the step pulses everytime the tracking error exceeds a given limit.

          But then again, if you have reasonably-sized servos, a trajectory-planner with an also reasonable safety-factor for each axis maximum acceleration and speed is probably just as good.

  6. Off topic but I have to say that [homo faciens]’ posts & turtorials are enjoyable both for their low budget-high analysis/utility approach and the Arnold accent.

    Of course, with this video, “Get to the choppa” would be appropriate.

    1. Agreed. I watched this (servo) video, and then enjoyed watching about an hour’s worth of his other videos. Really great stuff. Thanks a ton, Norbert!

      The one with the automatic car chassis is fantastic / terrifying. I think it’s the end of a “big motors” post.

      Watched a couple in German too, just to hear if he has that same accent and low-key delivery. Yup! It’s marvelous. But isn’t Arnold Austrian?

      1. You’re welcome!
        You don’t have to fear that you will get harmed by the automatic car. Meanwhile it is retransformed into a 2CV (the restoring process is almost finished). It was just the final joke at the end of my video about physical computing. It never drove more than 10m and never hit the road (the short road sequence was recorded using another 2CV with only the bonnet removed and me on the steering wheel).

        I start my videos with writing a script and the audiotrack is recorded sentence by sentence so that I can eliminate errors immediately (especially the phrases of the English version typically have to be recorded more than twice until the result is acceptable). It’s a less natural speaking, but that’s the way I like it.

        Yes, Arnold is a native Austrian.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s