Monday, March 26, 2012

The Bathroom Illusion

Last month we moved to a new workshop. The new space used to be a storage house, so you can imagine the mess. It is old and required lots of renovation work. Now you might think that the renovation work was boring... well... not for me.

One particular issue that needed urgent attention was the bathroom door. It had a fully transparent window.



One day my friend was having a piss..
I snapped a picture..

I developed the picture..
And sticked it to the window
And now my friend is always having a piss


Thursday, March 1, 2012

Class B Push-Pull Amplifier Design for DC Motor Analog Drive

I am currently involved in a project that requires analog speed control of a DC motor. One very popular method to achieve control of DC motors requires the use of a PWM signal along with an Hbridge circuit. Modular circuit website  provides a great resource for the Hbridge circuit and explains thoroughly different PWM driving techniques like Sign-Magnitude and Lock Anti-Phase Drive methods. However, and after doing a basic online search, I barely found any good resources on analog DC motor drives. There are many reasons for this mainly because switching drive methods are generally much more efficient than their analog counterparts and PWM signals are easily generated using microcontrollers as compared to the use of DAC for analog control. This does not mean that analog drive is obsolete as it is still the preferred method in some applications such as motor frequency response, continuous time control, and applications that are sensitive to the electromagnetic interference (EMI) that can be generated by a PWM switching circuit.

A famous method for transforming an analog signal into switching PWM signal is done using a class-D amplifier (switching amplifier). However such an amplifier design is complicated and requires lots of components. On the other hand, there are some commercially available power amplifiers such as the LM675, L165. Such ICs are a bit expensive and not widely available for the hobbyist to use.
In this post I will be reviewing DIY analog circuit designs to drive DC motors using BJT power transistors. This requires good knowledge of BJT transistors. If the terms base, collector, emitter, npn, pnp, cut-off, active and saturation regions do not mean anything to you, then maybe you should consider doing a BJT transistor research before continuing to read here.

I will be using a TIP31 npn transistor which has the following characteristics:
- Current gain: hfe=β= 50
- Collector-Emitter saturation voltage : Vce(sat)=1.2V
- Cut-off voltage Vbe(on) = 1.8V [according to the context-this will be called Vbe from now on]
I will be using also TIP32 which is the complimentary pnp transistor of the TIP31.

Common Emitter Configuration 

In this configuration we can achieve current control for the motor. Since for a DC motor the torque is proportional to current (T=K*ic where K is a constant that depends on the motor's winding configuration), torque control can be achieve using this circuit. While in active mode, the equation relating ic to Vin can be found (note Vbe = Vbe(on))


Let us understand this model intuitively:
  • For Vin<Vbe  transistor is in cut-off region and motor is off.
  • For Vin>Vbe and Vce>Vce(sat) transistor is in active region, motor torque T is proportional to Vin.
  • As we increase Vin, ib increases which means ic increases and Vce decreases. 
  • For Vin>>Vbe and Vce=Vce(sat):saturation region, motor reaches its maximum torque/speed capacity.
If we follow the DC motor's mechanical model developed in the following Carnegie Melon tutorial and assuming the only torque applied on the motor shaft is that of shaft inertia (Jm) and damping (B) we can compute the transfer function of the speed (w) versus ΔV=Vin-Vbe

According to the transfer function the steady state relationship between speed and voltage in the case of no load condition is
According to this result, decreasing Rb would cause the speed to go higher. Of course this method has its pros and cons:
  • pro: Assuming β is constant we can achieve linear current (torque) control of DC motor
  • con: The model is highly dependent on the current gain β (hfe) which varies alot specially for high power BJT (in the case of TIP31 it varies between 10 and 100). Hence the model is non linear!
Common Collector Configuration (also called Emitter-Follower)

In order to cancel the effect of β on the system we connect the motor in a common collector configuration. In this configuration, the motor is connected to the emitter of the BJT as shown in the following figure. This configuration is called emitter follower because the voltage on the emitter will always be following that of the input with a voltage drop of Vbe. So the gain of this configuration is a bit less than 1.


Again, and to evaluate the circuit, we need to find the transfer function ω/ΔV where ΔV=Vin-Vbe.
In this configuration when the transistor is turned on, Ve=Vb-Vbe. Knowing that ΔV=Vin-Vbe, the relation between the motor current, motor voltage and Vin can be found:

According to the mechanical model of the motor we know that the motor torque is equal to


Since T=K*ie and performing the Laplace transform we obtain


Equating the two equations we get the following relation:


The electrical model of the motor gives

Where R and L are the internal resistance and inductance of the motor coils. We are assuming in here that the motor is ideal and the generated EMF constant (K) is equal to that of the torque/current proportionality constant. Combining the electrical model with the previous equations of Ve and ie we obtain the following transfer function

From this transfer function we notice that if we choose Rb = 0 the effect of β on the motor is canceled. The transfer function then becomes


This is exactly the transfer function of a DC motor. However we haven't considered yet the rotation of the motor in both directions (Clockwise CW and counterclockwise CCW)

Class B Push-Pull Amplifier
In order to be able to rotate the motor in both clockwise and counterclockwise directions we should be capable of providing a negative current to the motor. This can be achieved using a push-pull amplifier. A push pull amplifier is a Class B type of amplifier that either drives a positive or a negative current into a load. It consist of a pair of complimentary transistors, in our case NPN and PNP BJT transistors, connected in common collector configuration.


When +Vcc>Vin>Vbe the upper transistor (NPN) is in active region and the lower transistor (PNP) would be in cutoff region. When -Vcc<Vin<-Vbe the lower transisor (PNP) will be in active region and the upper one will be in cutoff. The same theory developed in the previous section can be applied in here.
In order to be able to drive the transistors from a high output impedance source (potentiometer - DAC etc.) we need an impedance matching device. This can be achieved using a UA741 op-amp. The feedback for the op-amp needs to be implemented depending on the gain needed. In our case unity gain is required.

In order to test the class B push-pull amplifier I devised a setup consisting of a DC motor of maximum speed 30RPM connected to a quadrature encoder to measure speed. The data acquisition is accomplished using a dspic30F4012 microcontroller. Running at 120Mhz and 30MIPS this dspic computes the instantaneous velocity and communicates serially with a Matlab code in order to display in real time this velocity. I connected a potentiometer to the input of the amplifier. I would set the pot at a certain voltage and then wait for steady state condition to measure the velocity of the motor.

The amplifier/DC motor/encoder/acquisition setup used for the experimentation
The following plot shows the RPM vs voltage (Vin) curve for the Class B push pull amplifier design shown above.



We notice from this plot that there is a dead zone around 0V. This dead zone is called "crossover distortion" in the literature. This is obviously due to base-emitter voltage necessary for the NPN transistor to be in the active region (in the case of positive Vin) and for the PNP transistor to be in the active region (in the case of negative Vin). In the case of TIP31 and TIP32 this crossover distortion is of about 2Vbe=2*1.8=3.6volts. This  is not desirable at all since it provides non-linearity that will cause the frequency response analysis or the closed loop control to fail.

In the following allaboutcircuits.com article a solution for this crossover distortion was suggested which consists of connecting the op-amp with the negative feedback in the following manner


Without any loss of generality and in order to understand better this circuit we are going to analyze the NPN half of it. A is the gain of the amplifier.

Assuming Vin=ε is the voltage  responsible for switching the transistor from the cut-off region to the active region. Considering the case when the transistor is about to switch to the active region, then Vbe=1.8V while Ve is still 0V, hence according to the previous formula

Since the opamp has a very large gain A (about 200000 for ua741), this shows that ε is infinitesimal and very close to zero.
The following plot shows the RPM vs voltage (Vin) curve for the improved Class B push pull amplifier design with opamp feedback as compared to  the previous case


We notice from the plot that the crossover distortion has been reduced from a value of 3.6 volts to a value of 0.5v with the improved feedback design. We know from the theory that the new crossover distortion is supposed to be infinitesimally small, however in practice, this turned out not to be true. The reason for this is unknown to me but most probably it has to do with the imperfections in the opamp. If you have an idea about the reason please don't hesitate to comment.

I do realize that this design might need improvements and maybe the implementation of a class AB amplifier would have provide a better response, however for my current analog control of a DC motor application the Class B push-pull amplifier turned out to be very useful as it provided an almost linear relation between RPM and voltage. If you have any suggestions or improvements please comment on this post.

References and suggested readings:

Monday, January 16, 2012

DIY smartphone headphone adapter (with MIC & control button)



  • Do you happen to own a very expensive and personal set of headphones?
  • Do you have a special connection with your personal headphones such that you cannot listen to music without them?
  • Do you wish your personal headphones have the feature of the remote control (buttons) and MIC that smartphone earphones usually have? 
  • Do you have an AUX line in your car's radio and you like to listen to your smartphone's music in your car?
  • Are you bothered when you receive a phone call while driving because you'll have to unhook your phone from the AUX input to answer, which can get you into an accident?
  • Are you like me and you prefer not paying tens of dollars for something that you can build yourself and will only cost you time (and a few dollars). There is nothing more rewarding then DIY!  
Ja3far had the same problems mentioned above and in the video below he will show you the solution he came up with. (This is my first time shooting a DIY video, and I think I am a bad illustrator, so excuse my sloppy technique)



In the video, Ja3far decided to make an adapter which he can hook up to his expensive headphones (or any other earphone/headphone). This connector has a microphone and a button. Ja3far can use the button to play/pause/move to the next track/answer phone calls (the features of the button depends really on the operating system of your smartphone). And the MIC is obviously used to communicate during a phone call without having to bother (very useful while driving).

This project requires little knowledge of electronics and soldering. You just need the following items:
1- Solder and Soldering Iron
2- Wires*
3- Electret MIC*
4- Push Button*
5- TRRS (Tip-Ring-Ring-Sleeve) audio Jack*
6- Multimeter (not necessary, but it is good to be able to perform continuity testing to follow the connections of the Jack)

*total cost is about 2$
All these items can be found at your local electronics shop.
The TRRS jack goes into the smartphone audio input, while it is important to note that regular earphones and headphones have a TRS type of jack as shown below:
A TRRS audio jack

Headphones TRS jack
For a headphone jack: TIP is connected to Left channel, RING is connected to the Right channel, and Sleeve is connected to the Ground.
Oh and this is a final image of the adapter.

I know it doesn't look great but hey it does the job, and trust me wearing your headphones with this geeky looking gadget will definitely make you stand out.
So I leave the aesthetics for the aesthetic minded.

Tuesday, August 23, 2011

Chaos Theory: Simulating a double pendulum to understand how I owe my existence to Gaddafi's apple

"Does God Play Dice? The New Mathematics of Chaos" is a beautiful book by Ian Stewart. It provided me with a valuable introduction into the concept of chaos and chaos theory. Motivated by the book I decided to experiment with Chaos and write a dynamics simulator on MATLAB to simulate a 2 degrees of freedom pendulum (double pendulum).

In chaos theory 'Chaos' does not necessarily mean random (or a state of disorder). "Chaos occurs when a deterministic system behaves in an apparently random manner". Chaos is actually all around us. Chaos is the rule rather than the exception.

It is only when you think that everything is under 'control' that you wake up one morning to see that yesterday's weather forecast was all wrong and there is a huge storm outside, you check the stock market only to find out that you have lost thousands of dollars. HELL! you turn on the news only to realize that  suddenly the Libyan people rose against a crazy tyrant who ruled them for 42 years. Chaos.

An important characteristic of Chaotic systems is their high sensitivity to initial conditions. Even for a deterministic system (with no random elements), this high sensitivity to initial conditions is what causes the impossibility of long term prediction of the system's behavior. A slight change in the initial conditions would yield completely different and diverging end results.

To experiment with Chaos, I wrote a dynamic simulation of a double pendulum (2DOF pendulum) on MATLAB. The double pendulum is a classical example of Chaos theory.   I used the "Simple Forward Kinematics library for Robotic Chains" that I developed back in 2010 (click here to download), and I developed a new library to compute the joint-space dynamic equations and to perform the simulation for any kinematic chain (click here to download). So back to our chaos theory. To experiment, I ran two simulations:
- The first (on the left in the video below) is a simulation with a base joint initial position of 130 degrees
- The second (on the right in the video below) is a simulation with a base joint initial position of 129 degrees



Notice that although the initial conditions are almost the same, a difference in the trajectory begins to be noticeable only after 7 seconds. This difference increases as time passes. And after 40 seconds we notice that each pendulum is located on a totally different position in space.
We've all heard of the vivid and beautiful term "the butterfly effect". Here it is. The impossibility of predicting the long term behavior of the pendulum.

In 1972, Muammar Al-Gaddafi, while having diner in his tent and surrounded by his beautiful amazonian guards, decided to eat an apple rather than a banana. Imagine he ate the banana instead and it turned out the banana was contaminated with a deadly bacteria. He would have died after a month of suffering. Libya would have been 'inherited' by a crazier person (as is always the case). This person would have changed the entire political scene in the region, maybe causing the Lebanese civil war to be more intense. My father would have decided to flee the war and immigrate to Canada and he wouldn't have met my mother.  I wouldn't have existed. I owe my existence to Gaddafi's apple.

MATLAB Files:
- Simple Forward Kinematics library for Robotic Chains
- Dynamics Simulator for Kinematic Chains