Chatur Chaalak

An opensource, full featured Stepper Motor Driver

Electronics Project

microstepping
h bridge
sin waveform
inductance

mosfet
rms current

speed control
pwm
bipolar

chopping

current sensing

dynamic torque
electronic braking
developed by:

current decay
DEVELOPED

variable speed

EXCLUSIVELY

Atul Singh Arora

FOR

CONTENTS
Acknowledgements Aim of the Project Quit Joking What’s with the title? Theoretical Research How it Started Digging Deeper Bipolar vs. Unipolar Microstepping Lets get down to vectors Good old sine function PWM Current in Inductors Voltage vs. Current in Steppers Current & Torque in Steppers H-Bridge, What is it & why H? Inductive Load on H-Bridge iv 1 1 2 2 2 3 4 7 9 10 12 13 13 14 14 15

CAUTION: Some experiments described here may deal with high Voltage and/or Temperature. Reproduction of any experiment must be done under guidance from experts.

CONTENTS
Square vs. Wave..fight Head Start & Sudden Halt Back EMF Ground Reality Bridge of Adventures Plus we’ll see what’s Basic Connect ‘em part by part Die Hard 22 25 26 30 20 20 21 22

CAUTION: Some experiments described here may deal with high Voltage and/or Temperature. Reproduction of any experiment must be done under guidance from experts.

Acknowledgments
Since I acquired most of my knowledge & skills from the internet, I would like to acknowledge everyone who’s been kind enough to share their experience and expertise with the rest of the world. Further, I would like to thank the folks from various open source and other technical communities, who’ve not only shared their projects, but have also taken enough pains to provide elaborated supporting documents. Now, for the more conventional kind of acknowledgment. I am thankful to my mother for her encouragement and moral support, my father and Mr. Apoorva Sharda for assisting me in this Project.

Chatur Chaalak
An opensource, full featured Stepper Motor Driver

Aim of the Project
The topic of the project is such, that if I were to formally list down the precise objectives, understanding it would become hard, since that would involve the use of many technical words, and each of those words would require a long explanation. So at the human level, the aim of this project is to create a device that can control a certain special type of motor.

Quit Joking
You gotto be kidding me! Controlling a motor is the aim of your project? Let me explain it better. Mechanical movement is often related to motors, fans being the most common example. In robotics, amongst the first problems I experienced while trying to conceptualize its design, was not that of moving (say an arm), but that of stopping/freezing it at the desired position. Later I found out mechanical ways of solving the problem but it too had certain limitations. (which I will discuss later in the document) Another problem that rises on further thinking, is how to control the amount of force being applied by the moving part, should it come in contact with something. An almost instinctual answer is controlling the speed. However, that doesn’t solve the problem. Easiest example justifying my statement would be to think of shaking hands, rather holding hands. Aren’t we capable of squeezing a fellow’s hand to both comfort and hurt? Speed is nowhere in the picture and yet we’re able to apply varied amounts of force. Now this problem can’t be solved using constant speed & constant torque conventional motors. And since I’m not the first to have faced this problem, certain motors called “Stepper Motors” are often used for these purposes. For details, Wikipedia has a very nicely formatted, informative document for the same. If the solution’s already there, what’s so innovative about your project? Let me explain this using an analogy. Let the special kind of motor be a special kind of car, and the special requirements be a special race that needs to be won. To win the race, you need the car, but more importantly you need a car driver to nail the race. Similarly, stepper motors can help achieve the special requirements but you need a stepper motor driver to use it right. Now the driver itself may vary in the level of sophistication and the kind of results it produces. I made my first embedded project when I was in class 7 and guess what, it was a stepper motor based robotic vehicle. However, that stepper motor driver wasn’t capable of controlling torque as such, even though it was capable of stopping the motor. Controlling the torque requires a whole new level of understanding, and the physics I learnt while preparing for IIT-JEE proved to be of great assistance here.
Page 1

Electronics Project
What’s with the title?
The title is in Hindi, written in English (so that non-Hindi speaking people can read it too) “Chatur Chaalak”. The word “Chatur” is a Hindi translation for Smart and “Chaalak” stands for Driver, which makes it Smart Driver. And besides, “Chatur Chaalak” sounds pretty awesome to me.

Background Research
How it started
For a fairly long duration, I had believed that stepper motors were obsolete and that servo motors were the way to go. I had no intention of working with stepper motors until I figured out their true potential and the technically correct meaning of the word ‘servo’, i.e. a device used to provide control of a desired operation through the use of feedback. [definition taken from wikipedia] Even before I began work on controlling servo motors (which weren’t quite easily available then) I was keen on making the best possible driver (supporting PWM [Pulse Width Modulation]) for a simple DC motor. PWM provides the simplest way to control the speed of a DC motor. After substantial amount of work, I figured out the answer; H-Bridge. H-Bridge commonly refers to a simple configuration of switching devices, made in such a way, that the direction of current flowing through the load can be reversed. Using transistors as the switching device was one simple option, but the threshold current was limited. So instead I looked up a design that used MOSFETs. I have always been interested in automation. The very first step towards formulating this goal was making a simple Rotary Table that could fit with a VMC (Vertical Machining Centre). For finalizing the mechanical design of the Rotary Table, I had to find a motor perfect for the task. The requirements for this specific task have been listed below: 1. Should have torque greater than 100 Kg Cm / N 2. Should have speed control (non mechanical) 3. Must not have any gears. 4. Should be brush less 5. Must be capable of stopping at any position specified 6. Must be capable of moving/stopping high rotary inertia.

Page 2

Chatur Chaalak
An opensource, full featured Stepper Motor Driver
Reasons for the constraints/requirements listed above. 1. That’s based on an experimentally observed value 2. This is to enable the machine to rotate at a higher speed when its away from its target and slow down its speed as it approaches its final position. 3. Gears wear off with time, leading to play. This compromises on the accuracy of the machine which eventually decides its sophistication. 4. Since this machine is designed for industrial applications it must be heavy duty. Non-contact motor usually have a much longer life compared to motors with brushes, which is an important factor to consider. 5. Rotary tables usually come with mechanical fixtures that help it stop at the desired positions. The one in discussion is supposed to eliminate that dependance on mechanics and is designed to rely on an encoder and its motor for accuracy. This is where another factor for choosing the motor comes in. The motor must be capable of stopping exactly where its expected and must not overshoot from its position. 6. This is related to the point mentioned above, that is inertia plays an important role when it comes to moving heavy loads, which would be the case here. With all these factors in mind, I started looking for the right kind of motor, which was preferably supposed to be a DC brushless, gearless motor (since I had already explored its driver circuitry using an H-Bridge). I was looking through the catalogue of various motor manufacturers and I couldn’t help but notice expensive Stepper Motor Drivers. Upon finding out the details, I figured stepper motors are a hidden gem. I also remember having read the word “H-Bridge” which was surprising enough for forcing me to read more about it. [After this point I’m assuming that all facts & technical terms stated in the Wikipedia article about Stepper Motors (the document is attached herewith) are either known to or have been understood by the reader. I know it's a lengthy document but its concepts are essential to continue further with the discussion.]

Digging Deeper
I’ve come across numerous situations when I have way too many interrelated concepts in mind to effectively put them all in such a sequence that each part can be clearly understood as you read. This seems to be one such situation. Therefore I would like to recommend that you continue reading this section, even if there are certain parts which don’t make complete sense at first and/or seem unrelated. [Please note here that no part of this discussion has been experimentally verified by me. I had looked up various resources online and have discussed my understanding of the concepts. The resources have been listed at the end of this document]
Page 3

Electronics Project
Ok, here are 13 concepts which shouldn’t exactly be divided in the first place, but for the sake of clarity and simplicity, here we go. Concept 1: Bipolar vs. Unipolar Concept 2: Microstepping Concept 3: Lets get down to vectors, remember vectors? Concept 4: Good old sine function! Concept 5: PWM Concept 6: Current Rise & Decay in an Inductor (RI circuit) Concept 7: Voltage vs. Current for Stepper Motor Concept 8: Current and Torque relation in Stepper Motor Concept 9: H-Bridge, what is it & why H? Concept 10: Inductive Load on an H-Bridge Concept 11: Voltage is a Square Wave & Current is a Sine Wave. Sure? Concept 12: Head Start & Sudden Halt Concept 13: Back EMF Get Set, GO! Concept 1: Bipolar vs. Unipolar Bipolar and unipolar stepper motors have been discussed at great length in the document titled “Different Kinds of Stepper Motors” enclosed here (its link can be found on the last page). What I intend to talk about here is the kind of motor I’d be targeting and the reasons for the choice. Basically these different configurations affect the kind of circuitry involved. In a Unipolar motor, the direction of magnetism can be reversed by simply switching three connections as can be understood from the series of diagrams given below. This is one of the coils of a stepper motor, wired in the unipolar configuration.
S1 S3 S2

A typical Wiring Circuit with three switches. This is the easiest method to reverse the flow of current.
DIAGRAM 1B

DIAGRAM 1A

With reference to Diagram 1B, when S1 & S3 are closed, the current flows in one direction, and when S2 & S3 are closed, the current flows in opposite direction.

Page 4

Chatur Chaalak
An opensource, full featured Stepper Motor Driver
Bipolar configuration utilizes the entire coil unlike unipolar configuration which basically means it can provide a higher torque, however, the drive circuitry becomes fairly complex in order for the current to reverse direction. The circuitry used usually comprises of an H-Bridge but its details will be covered later. Keeping all factors in mind, I decided to use Bipolar wiring configuration

This is one of the coils of a stepper motor, wired in the bipolar configuration. Reversing the current requires special circuitry.
DIAGRAM 1C

Lets now talk about the arrangement of these coils within a stepper motor, cause this must be known for making its driver. A typical representational diagram 1D, shows four coils around the rotor, which has been assumed to be a simple bar magnet. Here I must emphasize on the fact that the actual stepper motors don’t have a physical step size of ninety degrees. 8-Wire Interface This is a general interface. Stepper Motors that come with 8 wires can be used in both, Bipolar or Unipolar mode depending on the requirement of the driver. An interesting fact is that of how number of phases is related here. For a Bipolar configuration, there’s one coil per phase and for a Unipolar configuration, again there’s one coil per phase but that coil has one middle wire tapped. The coils can be wired differently as will be discussed in just a while, but the term’s significance is infact independent of that. It basically refers to the number of different current channels being used by the motor.

2B’ 2B

1A’ 1A

1B 1B’ 2A 2A’

DIAGRAM 1D

Here we’re talking of a 2 phase motor. The terminology in the diagrams is related to this. Say for instance 1B’. The number refers to the phase/coil, A or B name one part of that coil, the apostrophe (’) refers to that wire of the coil which is further away
Page 5

Electronics Project
1A 6-Wire Unipolar Interface (can be used as Bipolar also) Compare this to Diagram 1B and you’ll find that they are identical except for the fact that there are two coils and both have been ‘split’ into two. The terminology is same as explained before, except the middle numbers don’t have an alphabet, that’s because they belong to both parts. This setup can also be used with bipolar circuitry, for which 1’ and 2’ wires won’t be used at all.

1’

1B 2B 2’ 2A
DIAGRAM 1E

1A

1A

1B 2B x 2A
DIAGRAM 1F

1B 2B 2A
DIAGRAM 1G

Diagram 1F is a 5 wire unipolar configuration, but this can NOT be used with a bipolar driver. Diagram 1G is a 4 wire bipolar configuration and as is obvious, this can NOT be used as unipolar. The eight wire interface an be converted into any of these as per the requirement. The current version of “Chatur Chaalak” would support only Bipolar, 2 Phase stepper motors. In accordance with the diagrams, all wiring configurations except the 5 wire configuration can be used.

Page 6

Chatur Chaalak
An opensource, full featured Stepper Motor Driver
Concept 2: Microstepping As the name suggests, in this technique, the step size of the motor (which depends on the make of the motor, usually 1.8 degree) can be electronically reduced by flowing a fractional value of current, through two coils simultaneously. How exactly these fractions are calculated has been discussed later. Here I would like to mention the reasons that make micro stepping desirable,(apart from increasing resolution). 1. Stepping in discreet jumps causes vibrations which is not desirable. 2. This leads to resonance of the rotor, which basically compromises on the accuracy of the motor. [Avoiding Ambiguity: Please note that the problems listed above are caused if micro stepping is not employed] The first point is simple and is a direct reference to the fact that certain machines of which this motor would be a part of, might not function as expected due to vibrations. The vibrations are caused by the phenomenon that the motor would be in motion for a short duration of time, and would be halted for another different short duration of time. The duration of the first interval is a function of a variety of constants/variables including motor torque, load, current etc. whereas the second interval is dependant on the controller. Larger the interval, slower the speed. This behavior can be understood graphically as shown below. Please note that the second problem has been ignored here and is not shown in the graph.
Motion Interval Rotor’s Angular Position Complete Rotation

Static Interval With ideal microstepping 1 Step (0,0) Without microstepping Time

Rotor’s Angular Position

Complete Rotation

Without Microstepping 1 Physical Step (0,0) With ideal Microstepping Time

Page 7

Electronics Project
The second point requires some explanation. As the coils are powered in a consecutive sequence, the rotor moves from one position to the other. Lets assume a situation where the rotor is standing stationary and is aligned along coil A. The reason for this assumption is to initially define a position where, when coil A is powered, no motion is produced since the rotor is already at the stable equilibrium position. When coil B is powered, the rotor moves towards the direction of the torque, which is always directed towards the second equilibrium position, i.e. rotor aligned along coil B. As you must have already noticed, under ideal conditions, this should behave somewhat like a Simple Harmonic Motion (SHM) and thus would keep oscillating instead of stopping at the next stop (which is along coil B). Since in reality, there’s friction (actually there are a bunch of other forces, but to start with), which dampens the motion, therefore the rotor eventually does stop at its final destination. Below is the graphical representation for better understanding.
Max. Amplitude of Oscillations Maximum Overshoot Position

Rotor’s Angular Position

Final Position: Aligned with Coil 2

Initial Position: Aligned with Coil 1 (0,0) Time

However, the motion of the rotor during this duration is undesirable for two major reasons. One is obvious, that the rotor is not rotating by a fixed step and this can cause major glitches in certain application. Second reason is that this motion may result in resonance of either the motor, or the machine its attached to. This by itself can be very dangerous since even bridges have collapsed due to non consideration of resonance during the design process. As mentioned earlier also, this increases the resolution of the stepper motor considerably. By resolution I mean, reducing the step size further electrically. Step size is usually a reference to the smallest angle a stepper motor can turn. When microstepping is not used, step size is dependant only on the physical factors, that is the make of the stepper motor itself. (For the sake of clarity, I refer to it as Physical Step size.) However, with microstepping, even thought the physical step size can’t be reduced, the step size can be. And the best part is the results produced are quite accurate for even 1/64th of the step. By accurate I mean, the steps are uniform. The inaccuries are usually attributed to physical factors and/or the electronic circuitry.

Page 8

Chatur Chaalak
An opensource, full featured Stepper Motor Driver
Concept 3: Lets get down to Vectors Ah, good old Vectors. One part of mathematics, most extensively used in physics (can’t say most extensively, cause otherwise Calculus would get angry). But the good news is that most of the long stuff is over. Rest of the concepts are gonna be pretty concise. Ok to start with, here’s an ideal model we’re gonna assume. 1. The stepper motor has four poles only, distributed uniformly similar to the model shown in the previous concept. 2. Next assumption: torque would be directly proportional to current applied through the coil. 3. The forces applied by the magnetic field follow vector addition laws. Justifications for the assumptions 1. In an actual stepper motor, the poles aren’t mutually perpendicular, however, the theoretical mathematical calculations work in real life as well. This can be proved by both experimental results, and slightly more complex mathematical calculations, but they’ll be omitted here. 2. This is a result of a derivation and can easily be proved using concepts of inductance. Again, omitted here. 3. This is an observed phenomenon, and should be just as true as it was with other forces we studied in classical physics. 1A Consider Full Step Driving sequence (written in the wiki article) Coil 1A 2A 1B 2B 1 X X 2 X X 3 4 X 1 X X 2 X X 1B .... 2B

X X

2A

X

Here, if we assume the force applied by each coil to be vector A, we get this. A 2A So the total force applied by on the stator would be 1.41 times that applied by a single coil. So far so good. Things get interesting when we use half step driving mode. This is where the magnitude of force being applied begins to alternate with each step. For a better understanding, look at the next page. A
Page 9

Electronics Project
Consider Full Step Driving sequence (written in the wiki article) Coil 1A 2A 1B 2B 1 X X 2 X 3 X X 4 5 6 7 X 8 X 1 X X ...

X

X X

X

X

As is evident, the steps can be grouped into two types. First where two coils are powered, and second where only one is powered. In accordance with the explanation given previously, the magnitude of the force would be 1.41 times higher when two coils are powered compared to when only one coil is energized. Force, implying torque changing in magnitude is not usually desirable for a motor. To solve this problem of torque dependence on position of rotor, we find the limiting factor, that is the minimum torque, which was assumed to be A. Now for making the magnitude of force A at the positions where two coils are powered, we simply reduce the amount of force applied by each torque so that the resultant is A. A 2A A 2 A A A 2 So the as per simple calculations, the force should be about 0.7 times of maximum a coil can produce, so that when two coils are powered simultaneously, the resultant is A. The good thing about knowing this concept is that the direction of the force and its resultant can easily be calculated which in turn decides where the rotor will point. If the current is varied in the right sequence through different coils, we could achieve what is known as microstepping.

Concept 4: Good Old Sine Wave Following from the discussion above, it’s clear that we’d be keeping the torque constant, and that would have to be equal to its minimum value as observed in Half Step driving mode. A sin wave comes in the picture due to one simple constraint, i.e. the step size (I’m talking about after microstepping, and not the physical step size) needs to be constant. Why the constraint you may wonder. The reason is further dependant on the application. When stepper motors were invented, the main use was to be able to control the motion of the motor without actually requiring any sensors/feedback mechanism. This is one reason why the step size must be constant, else the results won’t

Page 10

Chatur Chaalak
An opensource, full featured Stepper Motor Driver
match the electronically expected position. If the stepper motor is equipped with a feedback mechanism, like encoders etc., and this information is used to control the movement, then it becomes a servo stepper hybrid. This combination would still require a constant step at high speeds to keep the motion smooth. At slower speeds when the rotor is approaching its final target, the step size may vary and why at all this should be done would be explained in just a bit. The math behind this is pretty simple and so I’m not gonna go into its derivation here. As explained earlier, torque and current are assumed to be directly proportional, so here I’d talk about current since that’s what I’d be controlling using Chatur Chaalak. Representational Definitions: In accordance with the cartesian coordinate system, the X-Axis here represents the current flowing through Coil 2, and the Y-Axis represent current through Coil 1. The general angle phi is assumed to be measure from +ve X-Axis. Now any vector at an angle phi, with magnitude I can be resolved into its components along Coil 1 and Coil 2. Current through Coil 1= I cos(ø) Current through Coil 2= I sin(ø) [Note: This is what the number one looks like: 1 and is clearly different from capital I. Don’t get confused.] Now as per our discussion, we’re concerned about making a constant step microstepping driver. So for that, as is evident, the currents flowing through each coil must be calculated. If ø is incremented by k, 90/k values of the sin function need to be calculated and stored into an array of variables since its not feasible to calculate it in real time. Smaller the value of k, smoother will be the motion, and higher will be its resolution. But what exactly constraints the value of k? It does depend on the memory of the microprocessor being used but it also depends on various other factors like the speed at which the motor is expected to be moved at, the technique used for Digital to Analogue Conversion etc. To be more specific, lets consider a case similar to what’s described above. The system has feedback mechanisms and the encoder can sense 1/10th of the (micro) step size. When the rotor of the motor approaches closer to its final destination, the rotor must move in the smallest step, and highest speed possible AND the software shouldn’t be the cause of the constraint. It took me some time to come up with its solution, but its fairly straight forward. The constraint begins with the smallest variation possible with the DAC system. Let it be d. Mathematically, for a given value ø, find the current variables for both the Coils. Now depending on the direction reduce the value of current through Coil 1 by d. Now since sin square ø plus cos square ø should be one, calculate current through Coil 2. Continue the process until the rotor reaches it final destination. The calculations demand negligible processing and can easily be achieved in realtime. While writing this, another method struck my mind that could also be used.

[ NEW ]

Page 11

Electronics Project
A

[

A The other method could be linearly varying the value of currents in accordance with d, between two precalculated values of sinø and cosø respectively through each Coil. The mathematical computation may further reduce, improving performance. The only drawback in comparison with the previously explained method will be variance in torque which may or may not be an issue depending on the application. The graph above shows a comparison of both techniques. Its not quite as accurately made but it can be used to understand the basic concept. The anomaly is that while comparing one aspect, other factors should be constant, and in the graph above, d isn’t constant. Further, for the sake of clarity, the number of precalculated angles and the value of d are shown to be small.

NEW ]

Concept 5: PWM Now most concepts after this are gonna be really short, so if you’ve come this far, hard part is almost over. DAC (Digital to Analogue Conversion) is a process of...well converting Digital information into Analogue. Pulse Width Modulation (PWM) can be used to convert Digital information to Analogue. How it works is pretty straight forward. For simplicity, take the example of an LED which is expected to glow at different intensities as programmed. What we do can easily be understood by the graph below. The cycle duration is normally kept constant. The number of divisions and the cycle duration are programmable.
half cycle complete cycle complete cycle

50% intensity Voltage

25% intensity

Time
Page 12

Chatur Chaalak
An opensource, full featured Stepper Motor Driver
Concept 6: Current in Inductors In the world of physics, this is a well defined and known phenomena. H.C. Verma gives a concise explanation on all the concepts required, to name one distinguished author. In his book, Concepts of Physics, Part 2, (third reprint) the required information can be found on page 292 onwards. The topics are: 1. Self Inductance of a long Solenoid 2. Section 38.6 a. Growth of Current Concept 7: Stepper: Voltage vs. Current What decides the speed of a stepper motor? What limits the maximum speed? Does torque decay with speed? These are some of the questions I’m gonna try to answer in this section. Speed of a stepper motor depends on various factors. Here I’m gonna limit the discussion to that caused by electronic designs. For making a stepper motor rotate, the coils must be energized in the right sequence, that depends on the kind of motor & its driver. Talking about unipolar stepper motors for now, the following figure shows the variation of current with time for rotating the motor, as was discussed in earlier concepts. The graph is theoretically showing the current in each coil for different driving techniques. Speed here is related because one may think that to increase the speed of the motor, all that’s required is a high speed sequential energizing of the motor. However, this is not true because of the concepts discussed before. The current takes time to rise and fall. When the speed is slow, this effect can be practically neglected. However, when the speed is high, these effects become a problem. The current doesn’t rise or fall quickly enough and thus, torque is reduced. Further, if the speed is too high, the current may not even rise enough to show any noticeable motion. The current rise and fall time can be calculated using theoretical knowledge of inductors and it comes quite close to the observed once. On the next page, I’ve drawn a sketch of the graph obtained to give a rough idea of what happens when the coils are given a potential difference at very high speeds.

Page 13

Electronics Project

Concept 8: Current & Torque A very close to real approximation is that current is directly proportional to torque. This can easily be derived using simple concepts of physics and maths. The important thing is to remember that the potential difference can only drive the current, but applying a potential difference doesn’t mean that a proportional torque would be generated by that particular coil. In reality, at slow speeds, it may seem true since, as said earlier, the current rises quickly, but when dealing with microstepping and/or high speed control of stepper motors, this must be clearly understood.

Concept 9: H-Bridge, What is it? Why H? H Bridge is such a configuration of switches that enables the flow of current through a given load in both directions, and its designed as shown below. The switching devices themselves maybe solid state (like transistors, MOSFETs etc.) or could even be relays, depending on the way its designed to be used. The diodes are placed there for protection. They are usually used for decaying current with inductive loads and the flow of current recharges power back to the system since current flows from ground to positive potential.
Page 14

Chatur Chaalak
An opensource, full featured Stepper Motor Driver
For PWM, we require solid state devices only. Designing with a transistor is simple, but not as effective since there are a lot of heat losses at higher currents. MOSFETs require driving ICs or driving circuitry & may even seem more complex but are worth the effort. I had to spend a substantially high amount of time to be able to locate the right driver (meaning the one with a fairly high current rating, and high speed switching and more importantly, is available in India at a price less than that of my microcontroller, i.e. ATmega16) Finally I did find the driver of my choice, and it took some time to get it to work but its working fabulously now. The MOSFETs are of high current rating (about 10A) and are running ice cold (ok, exaggerated but really, they’re not getting heated up at all) even with about 3A load. Further, PWM works like a charm too. I’ll limit the discussion to this. Details of the driver will come in the practical section.

Concept 9: Load on Bridge Things get interesting when we start putting the concepts together, and end up with a new concept. Remember how we can’t drive the steppers fast enough by simply applying a potential difference quickly in the right sequence? Below is a representation of how this may be achieved by simply adding a current control system and operate the motor at a higher potential, to reduce time lag of current due to inductance.

Page 15

Electronics Project
Ok, that sounds cool so whats hard about it? Thinking on how this may be achieved, the design must first be clear. Our task is to measure the current flowing through the coil and give the feedback to our computer/microcontroller, controlling the motor. To answer that question, I looked up the net. I came across this: http://techtrain.microchip.com/webseminars/documents/StepperMotorsWithdsPIC_010710.pdf The document is worth reading but if you’ve followed me so far, the following explanation should be sufficient. (Images shown in this section, hereafter were taken from the document mentioned above)

First things first. How to configure an H-Bridge with a stepper motor and which type to use. One of the obvious things to observe here is that we’re controlling a bipolar stepper motor using two H-Bridges, one for each coil being controlled. Now without putting in too much brain into unipolar configuration etc., lets now talk about how these can be used to control the current through the motor’s coils to enable microstepping and to increase its speed, while torque is still retained. Next page contains the most relevant slides taken from the document, with the explanations where necessary.
Page 16

Chatur Chaalak
An opensource, full featured Stepper Motor Driver

The images show the current flow, and the switches/MOSFETs being turned on are represented by PWM1H1,1L1,1H2 & 1L2 as shown on the graph. A high on the graph represents the corresponding switches (in the diagram labelled as Q1A is PWM1H1, Q2B is PWM1H2, Q2A is PWM1L1 and Q1B is PWM1L2)

Page 17

Electronics Project

After the potential difference is applied, there’s some current flowing and the current can’t immediately be stopped (inductors you know) so a path for the current to decay is required to be provided. This is can be done in multiple ways. Here only fast decay has been shown. Slow decay mode has been shown later.

Page 18

Chatur Chaalak
An opensource, full featured Stepper Motor Driver

Slow decay can be achieved by closing any loop for the current to flow directly from 1 point to another of the inductor/coil. As you can see, I’ve skipped certain pictures but the concept can be understood using these alone. The current recirculates through the coil till it reaches zero. The current can be made to flow through 1 diode, 1 FET or 2 FETs. Further, the FET/diodes may be on the higher potential side.

to ADC

Page 19

Electronics Project
Almost forgot, the question for current sensing. Current sensing is done (refer to the diagram shown on the previous page) by putting reading the potential drop across the resistor. One thing that must be remembered is that the value read will be positive. Software methods must be used to find out the direction of current, as per this system. Concept 11: Square & Wave..Fight Even though I think you would’ve guessed what this ones about, still, this section talks about how the potential difference applied would be a square wave (kind of like PWM) but the current, because of properties of inductors, would always lag behind. The results would be similar to those shown graphically earlier, even though there are certain inaccuracies. One such inaccuracy is caused by the fact that the rise and fall should follow a logarithmic function. Why I made a separate section for this must be understood. The reason is a question: Why can’t the voltage be a wave function? The drive voltage here (thats provided across the H-Bridge) is gonna be constant. Now for a system to be efficient, we need to utilize this energy with minimum losses. Putting a digital to analogue convertor, which itself would require to be amplified since no DAC can provide the kind of power required here as an economical solution. Further, there would be high losses of first converting to digital, then amplifying which would further cause heating and make the system inefficient and expensive. Another reason is that it doesn’t help us achieve anything special that PWM can’t. The results achieved actually depend a lot on the software about which we’ll talk shortly. Concept 12: Head Start & Sudden Halt One last (you’ll see why) thing to talk about at the advanced level (by advanced I mean closer to its real application and away from the finer details, basically meaning simplest to understand) of motor control. The motor, when starts, actually has (or rather we’re assuming here) some load to move which is at rest. Now to move this, the force required would obviously be higher than that required to maintain its motion. If the current initially is increased to say one & a half times for a few seconds, the coil won’t heat up immediately but this would give the motor a head start. This basically ensures instant motion which is desirable in most applications. Sudden halt is another similar application, except that the current would be used to stop the motor immediately. This may seem rather silly because we can use regenerative braking also but it’s intended to be used only where sudden halt is desired. In the usual circumstance when the target is approaching but hasn’t yet come close enough, the regenerative breaks may be used.

Page 20

Chatur Chaalak
An opensource, full featured Stepper Motor Driver
Concept 13: Back EMF Alright, everyone knows what this is about and since its nothing hard to understand after having studying it in 12th, I’d let wikipedia explain it. Here’s the link: http://en.wikipedia.org/wiki/Counter-electromotive_force I’ve attached a hard copy of all these as well for the sake of convenience and simplicity.

Page 21

Electronics Project
Ground Reality
Bridge of Adventures
Finding the right driver for MOSFETs was the tough part. I’ve covered the basics of H-Bridges earlier, so here I’ll concentrate on how to make one practically. The golden IC is IR2110. This bad boy can handle everything you can imagine, and the cost it comes for is..find it out you’ll be surprised, and surprised good. Its capable of switching within nanoseconds, far quicker than required. MOSFETs are IRF540 which can handle a current of even 10 A without any problems. Finding the PCB for it was also hell of a task since I don’t have any “solid” knowledge of MOSFETs and their functioning as such. I’m more of a programmer turned into electronics enthusiast kinds. The schematic has been taken from Circuit Projects (next page). While I was making the H-Bridge..well it wasn’t easy to say the least. I had to redesign the PCB in Corel Draw. After I got the PCB made from outside (by made I don’t mean design), assembling was a breeze. Finally when it was turned on, with a Tape Recorder motor as the load, the only observable fact was heating up of the IC and MOSFETs of one of the sides. While I experimented with the input signals, suddenly the motor turned for a few seconds. I repeated my actions but there was no motion this time. Soon after, one of the capicitors exploded. Horrified, when I checked, it was the one attached to stabilize the AC adapter voltage. Reason was a fake label that said its rated 25V but it exploded at 18V. I wasn’t able to understand what was going wrong. After the heating up of various components of the H Bridge, it was essential to find out the faulty/dead components before being able to locate the problem. Starting with the MOSFETs, I needed some way to check if they were still working. Again, Mr. Internet came to help. I found a PDF that described a method of doing exactly that. Below is the schematic taken from the document.

Page 22

Chatur Chaalak
An opensource, full featured Stepper Motor Driver

Page 23

Electronics Project

The MOSFET tester itself didn’t work in the first go. The LEDs weren’t glowing the way they were expected to. I tested it with a brand new MOSFET and the results were just the same. Then I replaced the diodes with LEDs (which are also diodes after all), which eventually did make some sense because the current had to flow from one diode or the LED, and when both were LEDs, one of them had to glow. The pattern wasn’t the same as described by the document I was referring to. Yet I just took the pattern of a new MOSFET as reference and compared the once that got heated. The result was same, implying that the MOSFETs were working just fine. I was back to square one. Then I saw I’d missed one connection while redesigning the PCB. I fixed that using a tinned wire and the H-Bridge got alive again. Problems weren’t completely over yet, or rather one problem. Observation; when the input signal was high, for 3-4 seconds, the bridge conducts then it goes off again. To make the bridge conduct again, the input was required to be pulled low and then high again. The result also repeated itself. Inference; since I was using n channel MOSFETs for both positive and negative switching (as was stated in the datasheet of IR2110), one of the capacitors that was supposed to boost voltage (I’m guessing) wasn’t retaining the charge long enough. I replaced it with a higher capacitance value and it FINALLY worked like a charm. Below is the PCB I’d redesigned. Its on scale as well.

LOAD Gnd 12v Gnd PWM PWR

Chatur Chaalak: MOSFET based H-Bridge

The missing link

Page 24

Chatur Chaalak
An opensource, full featured Stepper Motor Driver

Plus we’ll see what’s Basic
Ok here I must explain a little more about the choice of Microcontroller, its compilers and programmers. In this project, I’d be using Atmel AVRs, the Atmega series. They can be programmed using ISP that , stands for In System Programming. This is what I’ve been using from day 1. Then I’d found something called Pony Programmer, and it's a beautiful application. The best part about ISP was that I just needed to connect certain wires of the parallel port directly to the microcontroller and that’s it. The programmer consisted of simply the cable. I recently looked up a different programmer that used USB cause otherwise I can’t use my laptop to program the ICs. The details of it can be found on my blog, or by using the keyword “usb programmer avrasp”. The programmer consists of one microcontroller (an Atmega8!) which is used to program other Atmega8s (and most other AVRs). The first Atmega was programmed using my parallel port programmer and since then I’ve been using my USB programmer! Stating the obvious, first paragraph was about programmers & micro controllers. Now about compilers. I’ve been using Bascom [Basic language] for all my projects so far. Easy thing to do would have been to continue with it for this project. But that wouldn’t have been good for various reasons. So I decided to shift to AVR-GCC. AVR-GCC is a strong opensource GNU compiler for C/C++ for the AVR platform. WinAVR is the windows version for the same. Using Bascom was a cakewalk. You find something useful on the internet, needn’t worry about the libraries, or the makefiles. It will work on your compiler too. But with WinAVR, since there’s a full control over every step of compilation, there are a lot more concepts to be understood before the compiler can even compile a simple “Hello World”. Funny thing about microcontrollers is that you can’t really make a “Hello World” application until you interface it with something else, like an LCD or a UART (serial port) and these thing in GCC need libraries. Finding these libraries ain’t hard thanks to the generous technical folks out there but using them for the first time is pain. Getting this to work was quite a task for me but eventually it did work! Below is a screenshot of WinAVR with a makefile loaded.

Page 25

Electronics Project
The fun part about this experience was that I got the results, but they weren’t upto the mark. To be more specific, I was able to compile my first code but it took some time to get the LCD library to be combined. Then finally when it did compile, the LCD didn’t show anything. After further experimentation, I found that with Bascom, the RW pin of the LCD needs to be earthed whereas with GCC, the RW pin must be attached to a pin of the microcontroller and it should be programmed accordingly. Finally when the LCD also worked, I wasn’t able to get classes to compile. Then I had to fiddle around with the makefile but had to give up. Later while looking for something to do with boolean algebra on avrfreaks, I came across this thread that said either rename files to .cpp (which didn’t work for me) or change one line in the makefile (which one is shown below) and that worked. So it took some time but one by one everything worked out perfectly..

Connect ‘em part by part
With the H-Bridge done and my compiler set, it was time to get things together. I started with connecting a small Tape Recorder motor (simple DC motor, works at 12V) to the H-Bridge, powered the H-Bridge with a power supply of 9 V. Connected one of the inputs of the H-Bridge to my microcontroller and programmed it with a simple software implemented PWM. It worked. Then I programmed it to vary the PWM duty from zero to hundred percent and then to zero again. This also worked. However there were two observations I still can’t explain with certainty. 1. For a particular PWM frequency, the motor generates a kind of sound (rather noise) 2. At certain PWM frequency and speed, the motor’s speed would fade in and fade out, but not in complete sync with the PWM. The first observation maybe justified by hysterisis etc. but the second observation was rather unexpected.

Page 26

Chatur Chaalak
An opensource, full featured Stepper Motor Driver
And I haven’t yet been able to come up with an explanation, except may be the fact that current is probably following a different wave. The code I’d written for each experiment has been attached herewith. So far, as per my understanding, the current sensing circuit was done as discussed earlier. What I’d assumed was that the current would always flow towards the earth (conventional electric current). This meant that there’s no way to find the direction of current electronically and transmit the same to the microcontroller. To overcome this problem, I’d come up with the following theoretical design. According to the graph, let the top graph be a function of V (Potential applied), second graph be that of current flowing through the coil (Ic) and the last be the potential drop across the resistor (Ir). Now let d() be a function that returns -1 for negative number, and +1 for positive numbers (incl zero). The direction of current flowing through the coil can easily be calculated by the following formula: d(Ic)=d(V)xd(Ir)

Page 27

Electronics Project
With that in mind, I decided to connect one coil of the stepper motor to the driver and see the results. I made a simple program that could read the current flowing through the coils using the resistor as discussed. The main program was simple. All it did was reading the current, if the current was higher than A(a fixed constant), then turn off potential, else turn on potential. This was easy. I simply displayed the value of current to the LCD with each iteration. Now the value of current was expected to be somewhat constant, but that just didn’t happen. The values kept changing rapidly and even touched zero! Then when I was experimenting with the wiring configuration, I reversed the direction of current by connecting the other input of the H-Bridge to the controller’s PWM output. Suddenly the ADC stopped working (meaning the value of current). It got stuck. This basically meant that current had flown in the opposite direction, meaning away from the earth. To avoid this in the future, I added a diode for protection and that worked. The results were just the same. On thinking about this further I realized, the hard part was displaying the information without time lag. Here we’re talking about microseconds and displaying this information in realtime to the LCD using the method I was using here, is theoretically not possible. So I had to think of ways of getting this entire process to work. Usually in these kind of researches, people use oscilloscopes but they’re expensive items. I don’t have one as a hobbyist and had to think of alternatives to get this to work. The first thing I tried was outputting the information to LEDs directly. The program was simply designed to glow, say LED 1 if the current is within the limit expected, and otherwise off. This resulted in PWM actually and the LED did glow but was dim. This output didn’t help much. Then I programmed LED 2 to do the opposite, stay on if the current is out of limit and off when within limit so that I could compare them. No luck. The intensities were too hard to differentiate between. Eventually I got back to my LCD. I added a counter to the program which would increment if the current was within the range expected. Then I added another general counter that would add up each time the loop executes. When this counter reaches 10000, the process is halted for 3 seconds and the information is displayed on the LCD. This worked indeed but what wasn’t favorable was the result I got from reading the LCD. I was expecting the LCD to show atleast 90% of the times, the current was within the limit expected. That didn’t happen, it showed a mere 40% with one motor, & 16% with the other. The only inference I could make out of this was that the microcontroller isn’t responsive enough or wasn’t fast enough. This seemed rather weird since the microcontroller was running at 8 MHz and this is way faster than the speed at which current can rise. These new developments scared me and even after a lot more experimenting, I couldn’t get better results. I even tried increasing the range of “correct current” but that barely increased the accuracy being displayed. Further I increased the accuracy of the ADC by setting the prescale to the highest value possible (details are in the Atmega datasheet) but no luck.

Page 28

Chatur Chaalak
An opensource, full featured Stepper Motor Driver
The current sensing wasn’t successful but I was too curious to find out if I could drive Stepper Motor without any of the advanced features at its RMS current. For this I wrote a simple PWM class and implemented it on the AVR and that worked in the very first go! The logic was simple. Instead of directly turning the coils on and off, I used PWM for fading in the current and fading it out. That did work pretty well at slow speeds but at high speed there was no torque. This is quite the expected result without current control as explained earlier. What was killing me was how can the processor be too slow to control a simple stepper motor? And if the current rises in less than a microsecond, why bother about current control and why can’t the motor easily go at high speeds without issues? The answer came from Mr. Internet yet again. It was a microchip document, application note to be precise. Here’s the link: http://ww1.microchip.com/downloads/en/AppNotes/01307A.pdf Absolutely fabulous piece of knowledge. This explained everything I’d been experiencing. Actually what was happening was this. When the current decays, it does through either the diodes or the MOSFETs (when switched for high speed drain) away from the earth. This is basically putting energy back to the powersource (regenerative) but this is what caused the ADC to blow. If the current flows away from earth, the potential to be read by the ADC would be less than earth, which is taken as reference 0 by Atmega. This also explains that after putting the diode, why was the LCD reading 0 at times. This was when the current was decaying. Below is a graph from the document mentioned above. Shunt shows the current as read by the microprocessor. The sub-zero current destroyed my ADC. The Decay Change shows the potential being applied. So basically the actual current needs to be recreated using the software. In my case I had to come up with a new method since for reading sub zero voltage, I haven’t used any special IC(s). I’m simply using diodes.

Page 29

Electronics Project
Die Hard
After gaining new knowledge, it was time to evolve it further so that I could use it for my own project with my setup. This part is conceptual only and hasn’t experimentally been tested yet. I changed the configuration of current sensor as follows:

Now what happens is, if current flows away from ground, my ADC will read it, else the value will be zero. Now to read the current under all given circumstances, lets assume the current is flowing as shown below. In the start of every iteration, the processor first applies potential in one direction, reads the ADC into a variable say A, then reverses the potential and reads the ADC into B. Let C be the current (with negative meaning opposite direction), then mathematically C=A-B. Now if C is known, the current flowing through the coil, with direction is known. Using a precalculated sin table, the software can apply the potential as required to maintain/bring the current to the level expected. The switching described above is done within 3-4 microseconds and is too quick for the current to change appreciably. How & why it works can be understood from the graphs below and by reading the other document by Microchip about stepper motors. I would be developing the software for this algorithm and testing it soon. Once done, I’d upload it to my blog. Also, an updated version of this document might also be published on Scribd. I hope this was useful and wasn’t a pain to read. Thanks Atul PS: Don’t forget to look at the references. They’re all worth a read!

Page 30

http://www.pi

clist.com/techref/io

/stepper/wires
in cume ars/do

.htm

nts/Ste

pp

rsW erMoto

IC_0 ithdsP

10710

ht

htrain tp://tec

.mi

rochip c

.com/w

ebsem

/ tp:/ ht

en

ikip .w

dia e

.or

g

ki/ /wi

St

r ppe e

_

to mo

.pdf

r

olarbotics.net/library/pdflib/pdf/motorbas.pdf www.s
http ://

ww

w.e u

clid

http://w

w1.

microch

res

.co

ip

m/ap

ps/s

tepp

er_

mot

or/s

.com/do

tepp

er.h

wnload

tml

s/en/Ap

pNotes

/01307

A.pdf

Chatur Chaalak
An opensource, full featured Stepper Motor Driver

Electronics Project
for any further details or clarification, suggestions etc., contact me Email: toatularora@gmail.com ~ Cell: +91 9818055646 ~ Landline: +91 011 65683657 Website: www.atulsingharora.com ~ Blog: KnowledgePayBack.blogspot.com

Temporary Drawing Page

Ah, good old Vectors. One part of mathematics, most extensively used in physics (can’t say most extensively, cause otherwise Calculus would get angry) Ideal model Torque in Various driving methods Concept 4: Good old sine function! How sin wave comes into picture 2 phase sin advantages and similarities with microstepping mathematic ways of quickly computing sin & cosine mention how to go smoother without being expensive when have external sensors Concept 5: PWM what exactly it is (will need simple diagram) how it works as dac how its use here Concept 6: Current Rise & Decay in an Inductor (RI circuit) HC Verma hopefully exact Concept 7: Voltage vs. Current for Stepper Motor talk about driving a simple stepper (might need a graph) Concept 8: Current and Torque relation in Stepper Motor Mathematical derivation of torque in stepper motor with current Concept 9: H-Bridge, what is it & why H? Working of H-bridge Concept 10: Inductive Load on an H-Bridge Most of the microchip discussion fast & slow decay, and the like including current sensing Concept 11: Voltage is a Square Wave & Current is a Sine Wave. Sure? Chopping/PWM circuit to create a sin wave using H-Bridge

Sign up to vote on this title
UsefulNot useful