Tag Archives: pspice

Pure Analog Servo Control

A Standard Hobby ServoHobby servos, such as the one pictured at right, are wonderfully useful little devices.  You’ll find them moving control surfaces on model planes, in steering linkages on RC cars, and even in the feeding mechanism of an automatic ping-pong ball launcher (one of my simpler college design projects).

Anytime you need something to rotate to a specific position, think of the hobby servo.  They’re fairly low cost, and come in a variety of torque sizes, from tens to hundreds of ounce-inches.

So let’s say you’ve bought yourself a servo from Tower Hobbies (or wherever).  How are you going to control it?  Well, you could purchase a radio and receiver, but if you’re not planning on building your servo into a vehicle of some sort, that’s really overkill (and expensive).  You could program a microcontroller to generate the control signals, but that could get complicated if you’ve never worked with MCUs before.  Instead, what I’d like to discuss today is a purely analog circuit for PWM servo control.

First, let me give you a little background information.  Hobby servos are typically connected by three wires: power (red), ground (black), and signal (yellow/white).   The power and ground lines are typically hooked directly to your battery or power supply.  The signal line, however, is used to command the servo to move to a specific angular position.  This signaling is normally accomplished via pulse-width modulation (PWM).  That is, a digital pulse is sent to the servo on a routine basis (e.g. at 100Hz, or 100 times per second).  The width or duration of this pulse determines the position of the servo’s horn. For instance, a pulse width of 1ms commands a fully clockwise rotation, a width of 2ms commands a fully counter-clockwise rotation, and a width of 1.5ms will center the horn.

Now the question is, how do we generate such a signal?  Why, we simply use the following pulse-width modulator circuit (adapted from Maxim Application Note 3201):

PWM Generator SchematicAlright, so maybe you’re thinking, “Dude, that’s a big circuit.”  Well yea, it sortof is.

But then again, those three op-amps could actually all be housed inside a single 14-pin DIP/SOIC package.  And beyond that, all you need are eight resistors, one capacitor, and one potentiometer (a variable resistor).  So while this may be physically more complex than just plopping down a microcontroller, there’s no software required.

So just how does this circuit create our PWM signal?  Well let’s start with the “Integrator” section.  This group of components (R1, C1, and U1) mathematically integrate or sum the voltage wired into the left terminal of R1 (line label #5).  Put simply, the capacitor C1 is summing up this input voltage over time.  To see how this happens, let’s start by analyzing the node between R1 and C1 (label #2).  Now assuming all of our op-amps are ideal (a fair assumption in most cases), no current will enter or leave their inverting (-) and non-inverting (+) terminals.  Since the current flowing through a series connection of electrical components (R1 and C1) must be equal, we can write the following:

Integrator Equation Derivation

The first half of this formula may look familiar; it’s ohm’s law (V/R = I).  However, we’ve defined the voltage across R1 as (V5 – 2.5).  Why?  This is because the voltage at the input terminals (+ and -) of our ideal op-amp must be equal since we have a negative feedback path (a connection from output to inverting (-) terminal) through the capacitor.  And we know that the voltage at the non-inverting (+) terminal of the op-amp must be 2.5V because of the voltage divider at node #1.  Thus, since C1 is providing a feedback path for the op-amp, we can safely assume that the inverting terminal is also at 2.5V.  The second half of this equation comes from the I-V relationship for capacitors, I = C*dv/dt.

So if we solve this equation for V3, with an initial capacitor voltage of zero, we get:

Integrator Equation DerivationIf we keep the voltage V5 constant, we’re left with just an equation for a straight line.  Basically, the output V3 starts at 2.5V, then ramps linearly up/down, depending on V5, as time (t) goes on.  If left unchecked, the output of U1 would eventually hit a supply limit (either 0V or 5V). However, the second half of the above circuit, labeled “Oscillator Comparator” ensures that this does not happen by switching V5 between 0V and 5V.

Let’s take a look at U2, the second op-amp pictured above.  You’ll notice there’s no feedback path between its output and its inverting (-) terminal.  So what we’ve got is a comparator.  That is, if the voltage on its non-inverting (+) terminal is greater than that on its inverting (-) terminal, the output of U2 will be roughly 5V (our positive supply voltage). Otherwise, the output will be roughly 0V.  I say “roughly” because this op-amp (TL072) can’t operate “rail-to-rail”, which means its output can’t quite reach our supply voltages.

In order to understand this comparator a little better, let’s take a look at the point at which it switches between its high (5V) and low (0V) output.  Since the inverting terminal of U2 is fixed at 2.5V by the voltage divider at node #1, this switching must take place when node #4 passes 2.5V.  Let’s determine the voltage V3 necessary for this to occur.  To begin, I’ll equate the currents through R2 and R3 (since again, no current flows into the + terminal):

Switching Point DerivationNow don’t be confused about where that 2.5V is coming from.  This is the switching voltage for U2.  We’re not saying that U2’s non-inverting (+) terminal is fixed at 2.5V.  It’s not, because we don’t have negative feedback.  This voltage will vary based on V3 and V5.  Anyway, solving for the switching-point voltage V3 we obtain the following:

Switching Point DerivationSo we’re going to have two switching points, based on the two possible values of V5.  When V5 is 5V, V3 will be decreasing linearly, and a switch will occur at V3 = 1.325V. However, when V5 is 0V, V3 will be increasing linearly, and switching will occur at V3 = 3.675V. So this is how the oscillation happens: V3 ramps linearly in one direction until it reaches a switching threshold, at which point the integration reverses and V3 ramps backwards.  So what does this give you?  A triangle wave, as seen in green in this PSpice simulation:

PSpice Simulation (Red = Threshold, Green = Triangle Wave Oscillation, Blue = Output)

Of course, we can’t just use a triangle wave to signal our servo.  What we need now is a third comparator to generate a PWM signal using this triangle wave and a variable threshold voltage (the red line pictured above).   This is where the components around U5 come into play.  Again, since U5 has no negative feedback path, it operates as a comparator.  Thus, its output can only be 5V or 0V (roughly).  So if we feed our triangle wave into its non-inverting (+) input, and a DC threshold voltage into its inverting (-) input, what we get at the output is a square wave (the blue line) whose pulse width is inversely proportional to our threshold (i.e. a higher threshold yields a shorter pulse).

The last trick here is that we can’t just hook up a potentiometer (pot) between power and ground.  That would give us a threshold voltage variable from 0V to 5V. What we actually need is a threshold voltage that varies from about 3.2V to 3.5V, for a pulse width ranging from 1-2ms (based on the form of triangle wave shown above).  Well in order to accomplish this, I’ve placed two additional resistors (Rx and Ry) in series with the potentiometer (Rpot).  In order to determine appropriate values for these resistors, I’ll start with two voltage divider formulae which are based on the two limits of the potentiometer:

Comparator Threshold Resistance DerivationSo when the pot’s screw is turned fully clockwise, the pot’s entire 10kΩ resistance will be placed between Rx and the inverting (-) input of U5.  This will produce our maximum threshold voltage, VH.   However, when the screw is turned fully counter-clockwise, the pot will act as a short between Rx and U5, yielding our lowest threshold voltage, VL.  If we now combine and solve these two formulae, we can determine values for Rx and Ry:

Comparator Threshold Resistance DerivationNote: To determine resistances for different potentiometer values, you’d just need to replace the 10k in the first set of equations with your updated value and re-solve.

Now of course, all we really need here is a means of controlling the threshold voltage at U5’s inverting (-) terminal.  Back when I was working on my automatic ping-pong ball launcher, I wanted to use my laptop and a DAQ card to control my servo.  The DAQ card I had available at the time didn’t allow me to generate precisely-timed digital signals.  However, it did provide several analog outputs, which I could have connected directly to U5 in order to control this circuit’s pulse width.  But I didn’t know about this circuit back then, so I actually just used a microcontroller programmed to generate the appropriate signals based on an ADC input connected to my DAQ hardware.

Finally, you may also be wondering, how can I calculate the frequency of this PWM signal?  (Or maybe you’re getting sick of all these equations?)  Well, given the above formulae, it’s actually quite simple to calculate.  We just need to set the integration formula equal to the switching voltage formula, like so:

Switching Frequency DerivationWe now solve for the time t, then multiply by four (since this equation gives you the time required by one quarter of a full cycle), and invert to find the frequency:

Switching Frequency DerivationAlright, enough of these crazy formulae.  Pictures of the final circuit?  Yes, please!

Protoboard Closeup

You’ll notice that Rx is actually a series combination of three resistors, while Ry is a series combination of two resistors.  This is because I didn’t have suitable values for Rx and Ry just lying around.  Oh well, it just makes things a little messier!  Here’s the full setup:

Full Protoboard SetupFinally, here’s a screenshot of the IOBoard oscilloscope VI I used to test out my PWM circuitry.  You’ll notice that, as I mentioned earlier, the comparator’s output doesn’t quite reach 0V and 5V because these op-amps (TL072) do not have rail-to-rail outputs:

IOBoard Scope - 2ms Pulse Width

One final note on the schematic above.   The resistance R10 should have been unnecessary. I initially included it because PSpice wouldn’t run my simulation with U5’s output floating.  However, after constructing this circuit I found it necessary for reliably servo operation.  I’m not entirely sure why this was the case; perhaps the voltage levels without R10 were slightly outside of the servo’s acceptable range?  The signal on the screen certainly didn’t appear much different with or without it.  Perhaps if I had a higher frequency/resolution scope I’d see something more telling…  Oh well, it may not be an issue with your servo.

Anyway, if you have any questions on this circuit or would like to make suggestions, feel free to leave a comment.  I’d love to hear about your experience.

Also, please help yourself to my PSpice files (from the Orcad 16.0 student demo).  These were used to create the schematic shown here as well to perform simulations.

PWM Generator Schematic 2

Here’s my final bill of materials (BOM):

  • 2x TL072 Operational Amplifier
  • 1x Hitec HS-81 Servo
  • 1x 4.7uF Capacitor (Can be electrolytic, despite the slight negative voltage)
  • 1x 10kΩ Potentiometer
  • 2x 20kΩ Resistor
  • 2x 1kΩ Resistor
  • 1x 470Ω
  • 1x 119kΩ Resistor
  • 1x 166kΩ Resistor

Update (11/2/2010): It was pointed out that the TL072 may require a minimum supply voltage of 7V, so 5V could be cutting it a little close here.  Now I’ve looked through the datasheet and don’t see a specific limit mentioned, but most of the graphs do only go down to ±3.5V (which I suppose you could interpret as 7V).  Regardless, the circuit works fine with a single 5V supply, although the outputs don’t go rail-to-rail (which is normal operation), as I mentioned earlier.  The real concern with most op-amps is their upper supply limit, as you don’t want to fry anything.  Also, you might be more interested in the TL074 for this project, which contains four op-amps in one package.  I didn’t happen to have a quad op-amp lying around when I built this circuit, hence the two duals.


The AVR AM Radio Transmitter (and Plantenna)

Fair warning: the following details on what led me to experiment with AVR-based AM radio transmission are rather long and convoluted. Feel free to skip to the good stuff.

Well just a couple of months ago I was in Toronto presenting a paper at this year’s IEEE CASE conference. While there I happened to speak with one gentlemen about his work in agricultural automation. He was looking for ways to autonomously and uniquely identify plants growing in the rows of a field. Now although each plant could be easily identified by the base of its stalk, the leaves of several plants often grew together. So if you wanted to take samples of a certain plant’s leaves, you might have trouble tracing base to leaf (particularly if you were a robot). Well this got me to thinking: what if we measured the electrical resistance between stalk base and leaf while sampling? Then perhaps we could determine which leaves belong to which stalk, thereby uniquely identifying our samples.

To test this idea, I popped outside with my multimeter and started sampling. Sadly, my initial resistance measurements, made by poking sewing needles into leaves and stems, proved unfruitful. Each pair of points I tested showed an impedance in the megaohm range, regardless of whether or not the points were located on the same plant. In other words, I couldn’t find a way to distinguish measurements taken on the same plant from measurements taken between plants. Well eventually I got to thinking that perhaps this was due to capacitance within the plant, and that I should instead try an AC impedance measurement. This technique has actually proven much more interesting. I’m still in the process of performing frequency response tests, but I’ll likely post my results next week.

The Plantenna?

So how does the electrical impedance of plants relate to AM radio transmission? Well, as I was injecting different high-frequency (10-100kHz) signals into my philodendron, I noticed that even with my second electrode disconnected, I still picked up a small but measurable radiated signal. This got me to thinking – can plants act as decent antennae? Or rather, plantennae? To find out, I decided to build a simple radio transmitter. And the simplest technique for radio transmission, as far as I know, is amplitude modulation.

The Technique

Faced with the task of constructing an AM transmitter, most people would probably build themselves a purely analog circuit based on one of the thousands of schematics available online. However, I don’t have much of a selection of analog parts and oscillators. Plus, I wanted to build something I’ve yet to see online: a microcontroller-based AM transmitter.

First, a little background is in order. According to the US Office of Spectrum Management, the AM broadcast band runs from 535 to 1605kHz; it’s the largest blue strip shown in the frequency allocation chart below (an equivalent chart for the UK can be found here):

US Frequency Allocation ChartSo the first thing I needed was a carrier wave oscillating somewhere within this frequency range. I then needed a way of modulating the amplitude of said carrier wave at any given audio frequency. This is the basic principle of amplitude modulation: your low-frequency audio signal essentially “rides” on top of a high-frequency carrier wave.

To accomplish this task, I used one of the timer/counter modules provided on my ATMega324, an 8-bit AVR microcontroller. With the chip internally clocked at 8Mhz, I configured counter TC1 to generate a PWM signal at approximately 540kHz. This output was then modulated via changes to its duty cycle (scroll to the end for source code):

AVR Amplitude Modulation Technique (not to scale)
At the top of the above image, in blue, is the PWM output generated by the ATMega324. You can see that its duty cycle is being modulated between about 5% and 50%. The rate of this modulation is controlled by a second MCU counter (TC0). Now this square-wave output isn’t quite ready for transmission. While it could be fed straight into an antenna, it should first be filtered to eliminate the harmonics inherent in any square-wave. This filtering actually converts the square-wave into a sine wave, producing the modulated output shown in yellow above. This signal can now be picked up by any AM radio, which will then convert this modulated transmission into an audio signal (the red line above).

In order to filter the AVR’s square-wave output into a sinusoidal AM signal, I designed a simple resonant RLC circuit. Not only does this clip off most of the square-wave’s harmonics, it actually provides a slight voltage amplification through resonance between C1 and L1. The resistance R3 in this circuit was needed to prevent excessive current draw from the AVR, and R2 is included to model the series resistance of the inductor L1:

PSpice RLC Circuit Schematic - The antenna is connected at the voltage probe.

PSpice Bode Plot - Cursors are located at ~540kHz

Now unfortunately, the components I had available yielded a resonant frequency of about 563kHz – slightly higher than my 540kHz target. However, the PSpice bode plot above still predicts a significant gain from the RLC circuit at 540kHz. Computing the resonant frequency of any RLC circuit can also be accomplished by using this simple formula:

RLC Resonant FrequencyIn addition, I ran simulations of this circuit’s transient response using a pulse input:

PSpice RLC Circuit Transient Response Schematic - The antenna is connected at the voltage probe.

PSpice Transient Plot
The ringing you see in the transient response above is not intentional, but has to do with the input frequency being slightly different from the resonant frequency. This is a phenomenon called beating. Fortunately, the beat frequency above is about 20kHz, which is well outside of the audio range, so this won’t impact the transmission of any signals.

So with the components selected, I proceeded to build and program my transmitter. An antenna was connected between the inductor and capacitor shown in the schematics above. Initially I used a piece of wire about 40.6″ in length (an even fraction of the transmitted wavelength). As planned, I also tested the system using a shorter length of wire (about 36″) connected to a houseplant via a small sewing pin. Interestingly, the plant actually did function slightly better than the wire whip antenna:

AVR AM Radio Circuitry

The receiver I used was a simple Timex clock radio, positioned on the other side of the plant, approximately three feet from my electronics and wire antenna:

Timex Clock Radio ReceiverAs I mentioned, the “plantenna” did slightly improve reception. However, the effect was admittedly quite small. My fingers actually had a greater impact on the signal’s strength than did the plantenna. Whenever I touched the leads of the resistor in my RLC filter, the volume and clarity of the received signal were noticably improved. Perhaps I need to try a few other varieties of plants?

Of course, what this circuit really needs is an active amplifier. However, increasing my transmission radius much beyond three feet would probably fracture a law or two. As it stands, I imagine my radiated power is somewhere in the microwatt range, so I doubt the FCC will be banging down my door any time soon. But you never know…

One final thing I found interesting: high-power AM signals actually transmit significantly farther at night than during the day. I’d read about this, but had never experienced the effect until the other night. During the daytime, AM540 had been almost completely clear of broadcasts. But at night, I was pulling in one station very clearly. In fact, it was almost overpowering my teeny transmitter. According to this website, “distant AM radio stations are better received at night because the ionosphere that reflects AM stations is protected from ionizing radiation and ionized particles from the Sun.” Pretty nifty, eh?

The Video

So having successfully tested this AM transmitter, my next logical step was to program it to play music. And the first thing that came to mind? The Tetris theme! I’ve played so much of that game it’s practically burned into my memory. So creating the following video wasn’t too tough, it just took a bit of trial and error getting the timing right. (And sadly, something weird seems to have happened to the audio during upload compression…)


  • The complete AVR Studio project can be found here
  • Or, if you just want a peek at the source code, try: am_test.c