Interrupts on AVR

Interrupt is neither same  for all hardware’s nor for the compilers. Some hardwares support multi level interrupt or nested interrupt and some chips use single interrupt flag. The Atmel architecture interrupt works as following

1. As Interrupt triggered processor finishes pending instruction

2. Stops fetching further instruction

3. Clear Global interrupt enable bit(This is why arduino denies nested interrupt, but you can use)

4.  Push PC(program counter) on stack

5. Jump to interrupt vector(specific address where the corresponding interrupt handler expected to be)

6. Next is the ISR code in case of C compiler do a lot job for you and if you are using assembly all that have to do youself.

Push the status register to stack and also any other register that you may use in this ISR block

Execute the actual ISR handler code i.e. whatever you want to do when the specific interrupt occours

When the actual task is done, rollback the things you changed i.e. POP the stack to status register and other register you had pussed

7. Now last assembly code RETI which rollback the PC from stack and Reenables Global Interrupt

So in the whole process all except the step 6 and 7 are automatic user need not worry about the steps.


ISR in C

use variables with volatile type modifier other compiler optimiser may think the varible is static(assuming not changed in main())

  • Keep the ISR code as short possible in execution time not in length.
  • Don’t activate or deactivate interrupt inside ISR
  • Don’t call another function that uses interrupt

Now the above rules are for the ideal people, you can do it if u know what the hardware and the compiler does. Suppose you have to do some of the banned things immediately after the interrupt triggered, i have to methods one is the method being ideal another is to break the rules.

A.If your main loop contains things that only run when a interrupt is triggered and interrupt are not overlapping, in this case u can set special flag to activate a part of main code (code u want to run in ISR), the flag need to set in the original ISR and cleared in main loop part of ISR.


B. Next method is really complicated. You need to mess with the hardware and the compiler, you know when interrupt occurs global interrupt enable is cleared ,PC pushed to stack by hardware and Status register and other registers moved to stack by compiler, So here

if you want to get another interrupt you have to set GIE and if interrupt occours it will again push pc and but the compiler part is complex.

Some people make multilevel interrupt with software. The main interrupt handler acts as the first interrupt handler which catches the interrupt event and stores necessary data and exit ISR(the basic isr) and start the secondary interrupt handler. exiting the fast interrupt handler triggers RETI so all interrupts resumed.


Complex Impedance calculation

Impedance is always calculated as complex value, a magnitude with a phase value. The magnitude is the total equivalent resistance of the circuit and the phase angle shows whether current follows or leads the voltage signal.

For calculation of impedance we need two signals one is the voltage applied to the circuit and the next one is the current signal. This can be done in both digital or analog method.

We need to calculate the In-Phase component and Quadrature (90 deg Outofphase) component. This can be done by multiplication of sin component of the signal with it self to get the qudrature component and the cosine component with the signal to get the inphase component.

In analog systems we can achive the cosine part by phase shifting the signal and multiplication/dot product by modulators.

Magnitude=sqrroot((inphase component)^2+(Quadrature component)^2)


Continued ….

Disobeying the Nyquist theorem

Undersampling or violating the nyquist criterion is a technique often utilised in ADC applications. RF communications and high performance test equipment such as oscilloscopes are to name just a few. This is a ‘grey’ area and confusion often arises over the necessity to obey Nyquist in order to retrieve the information content of a signal. Examination of both the Nyquist and Shannon theorems will demonstrate that the choice of ADC sampling frequency has a strong correlation to the ratio of maximum input signal frequency to input signal bandwidth.

Nyquist theorem states that to reconstruct an analogue signal waveform without error from sample point taken at equal time intervals, the sampling frequency must be greater than or equal to twice the highest frequency component in the analogue signal.

In practice, analogue signals are not simple sine waves and usually have complex waveforms with components or harmonics at many frequencies. Therefore to reliably reproduce a square wave from time-interleaved samples, the sampling frequency according to Nyquist must be many times higher than the square wave’s fundamental frequency.

Sampling an analogue signal fa, at a sampling rate fs, actually produces two aliased components, one at fs+fa and the other at fs-fa. The frequency domain representation of this is shown in figure 1.

Figure 1. Signal Sampling Produces Aliased Components

Generally, it is only the lower alias component which may cause problems because it can fall within the Nyquist bandwidth and corrupt wanted signals. Based on the aliasing phenomenon of sampling systems the Nyquist criteria requires sampling at a rate of fs > fa in order to avoid overlapping aliased components into the first Nyquist zone. To prevent unwanted interference, any signals which fall outside the bandwidth of interest should be filtered before sampling. This explains the necessity for anti-alias filters in many sampling systems.

However, methods exist which use aliasing to one’s advantage in signal processing applications.One can quickly see the limitations implied by the Nyquist theorem. Nyquist assumes that the desiredinformation bandwidth is equal to the Nyquist bandwidth or half the sampling frequency. It should be observed that the required minimum sampling frequency is actually a function of the input signal bandwidth. Shannon’s theorem examines this further.

An analogue signal with a bandwidth fb, must be sampled at a rate of fs > 2fb in order to avoid the loss of information. The signal bandwidth may extend from DC to fb (baseband sampling) or from f1 to f2 where fb =f2 – f1 (undersampling).

So Shannon’s theorem states that the actual minimum required sampling frequency is a function of the signal bandwidth and not only its maximum frequency component. In general the sampling rate must be at least twice the signal bandwidth and the sampled signal must not cross an integer multiple of fs/2 to prevent overlapping of the aliased components. Note that for large ratios of fMAX (maximum frequency component of the analog signal) to signal bandwidth B, the minimum sampling frequency approaches 2B.

In many applications this greatly reduces the demand placed on the ADC required. Sampling a signal with a maximum signal frequency of 150MHz but with a bandwidth of 10MHz would require perhaps a 22MSPS ADC instead of a >300MSPS ADC as stipulated by nyquist.

Otherwise stated, due to harmonic folding or undersampling, every ADC input frequency component outside the Nyquist bandwidth is always folded back into the first Nyquist zone. Sub-sampling has many uses in practical electronic systems. One such popular application of undersampling is in digital receivers. Lets first explain in a little more detail the process of sub-sampling.

The process of sub-sampling or folding can be thought of as mixing the ADC input signal with the sampling frequency and its harmonics. This means that many frequencies can be mixed down to DC and their original frequency can no longer be determined. Sub-sampling cannot be used if the original input frequency must be determined at the ADC output. This is because the Nyquist criteria is violated. Sub-sampling still proves useful if there is no need to determine the carrier frequency at the ADC output. This is true for many communication systems such as cellular base-station receivers since the receiver only needs to recover the information on the carrier and not the carrier itself.

Figure 2. Many Frequencies are mixed down towards DC when Sub-Sampling

Consider a GSM/EDGE base-station with RF carrier frequencies of 900MHz Europe and 1800MHz USA. The receive chain of a mobile base-station is similar to that shown in Figure 3. The high frequency RF carrier signal is first down-converted in the mixer and local oscillator stage to an IF frequency in the range of 150 -190MHz for analogue to digital conversion. Shannon theory shows that the required sampling frequency is a function of the signal bandwidth or 200kHz in a GSM/EDGE system. The dynamic range specifications of a GSM system require a minimum ADC resolution of 10 bits although 12 bits are used in practically all cases. Given the vast choice of high speed ADCs available in the market a digital receiver system designer has to make a choice based upon system dynamic range requirements and also component cost. For these reasons, ADCs with sampling rates of 50 -70MSPS are the most popular choice for GSM receivers. Although the 150 – 190 MHz signal is undersampled at for example 66MSPS (using National’s ADC12DL066, dual 12-bit 66MSPS ADC)

Nyquist is not violated for the required information bandwidth of 200kHz. This provides more than enough headroom for the 200kHz bandwidth information signal as well as providing over 20dB’s of processing gain(explained below). Note that for many reasons, it is not practical to continually increase processing gain by increasing sampling frequency. Higher sampling rate 12-bit ADCs such as the 12-bit 80MSPS ADCs are available (National’s ADC12L080) and some >100MSPS 12-bit ADCs exist for specialised applications but the cost differential between sub-100MSPS and >100MSPS sampling rate ADCs is quite significant.

Figure 3. Communications Signal Chain

ADC noise performance is typically limited by thermal noise and when an ADC is specified, the noise bandwidth is normally defined as the nyquist bandwidth. At FS = 66MSPS the integrated noise-floor measurement is expressed in dB’s relative to full scale (dBFS) in a 33MHz bandwidth at a particular input signal frequency. For the ADC12L066 the integrated noise-floor is -62dBFS for an input signal frequency of 150MHz. However filtering the ADC output results in a much narrower bandwidth such as that provided by Nationals digital down converter, the CLC5903. The filtering process provides noise processing gain as a function of the bandwidth reduction.

Figure 4. Narrowing the bandwidth by filtering improves noise performance

Choosing the correct sampling rate ADC for an application requires more than just knowledge of the highest analogue frequency for conversion. Shannon’s theorem demonstrates that signal bandwidth is of equal importance. We have also discovered that sampling at greater than the Shannon rate brings other benefits such as vast improvements in dynamic range brought about by processing gain. Armed with this knowledge, a system designer can make the right choice for ADC sampling frequency and resolution based upon readily available and affordable standard ADCs.

Original article:Effects and Benefits of Undersampling in High-Speed ADC Applications (Published in the May 24, 2004 issue of Design & Elektronik )

Translated By: Analog Devices

My first run with ADUC842

Today I got a ADUC development board in our store, so I started with my task, the same task sinewave generation, reading back the sinewave and saving the sinewave samples in external ram(actually the xram is inside the chip, but it is interfaced as external). There was a crystal attached to the chip . but the crystal attached to the chip was not active by default. The system clock is decided by a internal PLL circuit and is controlled by CONFG842 sfr.

Sinewave generation with the DAC0

I had taken 6 samples per cycle which was not enough(which was simulated accurate sinewave in proteus). So I had to increase the sample rate to 36 per cycle(10 degree interval). Rest job was to read the sinewave .

Reading Sinewave normal and DMA mode

Using adc with ADUC is a bit complex at software part and simple at hardware, because you have to configure 3 sfr’s ADC1-3. The data will be written at ADCDATAH and ADCDATAL two 8bit registers. Actually ADCDATAH contains the ADC channel id at the higher 4 bit locations and the higher 4 bit of the ADCread value at the lower 4 cells. Save both the values in an integer variable.

Saving the data in RAM

The adcread values need to b saved at some location for further processing. This is better with some external RAM(XRAM), fortunately we have 2KB of external ram inside the microcontroller.

Signal processing

Perhaps this is the last job that I have to do for my thesis, I need some FFT calculation to get the impedance value from the samples read by ADC.

Is it simple

This is all I have to do for now. From the first stage to the last stage there are a lot of hidden problems. Getting a pure sinewave at a high frequency wwith tradeoff between frequency and sinewave shape…

Impedance measurement with microcntroller

Generally impendance is measured through LCR Meters in lab. LCR Meters are very costly (I have seen only agilant products). For amateurs and for low cost product which involve impendance measurement needs an alternative method. What the commercial products contain is of two types fixed frequency and variable frequency type. Both uses a sine wave as excitation to the circuit and the input/output gain and phase relations give the impendance of the load.

For our purpose we can do the same things with some microcontrollers, ANALOG-DEVICE has a number of products for this, the most useful one is AD5933:  1 MSPS, 12 Bit Impedance Converter Network Analyzer

If you choose AD5933 then you have to do nothing just read the impendance data through a I2C protocol on any microcontroller.

  • Otherwise do all the job sinewave generation
  • Reading the output wave (sine wave but it is phase shifted and attenuated by the load impendance)
  • Save the sinewave data or export to PC through serial port
  • Process the data to get the impendance data.

For all the above jobs there are FPGA chips available from ANALOG DEVICES

For sinewave generation upto 50MHz with I KHz steps: AD9835

Phase Detector/Frequency Synthesizer

Phase Detector/Frequency Synthesizer : ADF4002

For Phase detection, gain detection: AD8302

please read the application note AN691(low frequency phase detection) from analog devices

A similar device, also available from Analog Devices, Inc., is the AD5934, a 2.7 V to 5.5 V, 250 kSPS, 12-bit impedance converter, with an internal temperature sensor and is packaged in a 16-lead SSOP.


  • Electrochemical analysis
  • Bioelectrical impedance analysis
  • Impedance spectroscopy
  • Complex impedance measurement
  • Corrosion monitoring and protection equipment
  • Biomedical and automotive sensors
  • Proximity sensing
  • Nondestructive testing
  • Material property analysis
  • Fuel/battery cell condition monitoring


ADC DAC External Memory(RAM)

This is what I am assigned to do, what are the aim

  • Generate Sinewave through DAC (why not PWM?)
  • Read the sinewave(through ADC810)
  • Save the values in a 32KB Ram.

And the tradeoffs are

  • Generate the highest frequency which will lead to impure sinewave.
  • DAC and ADC speed must match.
  • Simultaneously i have to save the data in RAM


The microcontroller U5 (AT89C51) is generating sinewave, loaded with the following code


void delay(int k)

{int i,j=k*10;














// P1=0x80; //delay(3); //10

// P1=0x96;//delay(3); //20

//P1=0xAB;//delay(3); //30

// P1=0xC0; //delay(3);     //40

// P1=0xD2; //delay(3); //50

P1=0xE2;    //delay(3);     //60

// P1=0xEE;    //delay(3);        //70

// P1=0xF8; //delay(3);    //80

//P1=0xFE; //delay(3); //90

//P1=0xFF; //delay(3);         //100

//P1=0xFE;     //delay(3);

P1=0xF8;    //delay(3);          //120


//P1=0xEF; //delay(3);


//P1=0xD2;//delay(3);         //150

//P1=0xC0; //delay(3);

// P1=0xAB; //delay(3);

P1=0x96;    //delay(3);         //180

//P1=0x80;    //delay(3);

//P1=0x69; //delay(3);

//P1=0x54; //delay(3);         //210

//P1=0x40; //delay(3);

//P1=0x2D;     //delay(3);

P1=0x1D;    //delay(3);     //240                



//P1=0x01; //delay(3);     //270

//P1=0x00; //delay(3);

//P1=0x01;    //delay(3);

P1=0x07;    //delay(3);     //300

//P1=0x11; //delay(3);


//P1=0x2D;//delay(3);     //330

// P1=0x40; //delay(3);

// P1=0x54; //delay(3);

P1=0x69;    //delay(3);     //360



















And the U1 doing 2 jobs one is to read the sinewave through a ADC810 and other is two save sinewave data to a external RAM 32KB. U1 loaded with following code

8051 External Memory with keil

Hi friends you must have interfaced memory chips to 8085 or 8086 microprocessor. Same is the case here as both are with 8 bit processing 16 bit address space. In both cases the higher address port is shared with the data port. Means one port dedicated lower byte of address and higher byte of address is goes through a data-address multiplexed chanel.

Here in 8051 P0 is for lower address and P2 used for upper address byte and for data also. The hardware connection is also same as in case of microprocessors. You have to use a latch to latch the higher byte of address .

And the Code….

I had searched a lot both in google and the help pages, but didn’t get anything except the DATA type declaration, but how will it do all the things.

unsigned char xdata datg[32000]; //I had used a 32K byte RAM to save my data.


Do you know about pointers, have u ever tried to store a variable at some specific memory location. (I guess u never tried this), if u have done please mail me the code.

We declare pointers like

Int *ptr ;


Char * ptr;


Unsigned Char * ptr;

Where ptr is the address of the variable. Value of the variable is *ptr is an integear.

But we can’t write

ptr=0x1278; assuming 0x1278 is a memory location. Try it.


Ok u may ask what is the use of pointing to specific location(usually called static pointer). In microcontrollers we have very less memory we can use the memory randomly. It may lead to data segmentation.

After a long search I got two three lines

*datg = (char xdata *) 0x0400;

volatile unsigned int *myPointer = (volatile unsigned int *)0x1234;

#define data (*((char *) 0x0170))    

The first one is quite odd, it doesn’t look like a type declaration statement, rather seems like a assignment statement.



Keil application note

Servo motors and Servo amplifiers

A  servo, is an automatic device that uses error-sensing negative feedback to correct the performance of a mechanism. The term correctly applies only to systems where the feedback or error-correction signals help control mechanical position or other parameters. For example, an automotive power window control is not a servomechanism, as there is no automatic feedback that controls position—the operator does this by observation. By contrast the car’s cruise control uses closed loop feedback, which classifies it as a servomechanism.

A servomechanism may or may not use a servomotor. For example, a household furnace controlled by a thermostat is a servomechanism, yet there is no motor being controlled directly by the servomechanism. A common type of servo provides position control.


Introduction to Servo Amplifiers

The output stage of all servo amplifiers is an analog circuit. The analog circuit provides a means to allow the voltage and current for the motor to be adjusted to control position, velocity, and torque. The feedback and comparator stages can be any mixture of digital and analog devices. For example, if the feedback section uses a resolver, the output of this device is analog, so the section it works with is generally also analog. If the feedback device is an encoder, its output is digital, and the digital signal can be converted through a frequency-to-voltage converter so that the signal is usable in an analog circuit. Or it can be filtered and can use a digital value. The advent of microprocessors has allowed the digital values to be used through every part of the servo controller except the final output stage.

Figure 1 shows a diagram of the components in a typical servo linear amplifier. The circuit shows the motor winding connected to a set of transistors (TR1 and TR2). The transistors can control positive (+V) or negative (—V) voltage to make the motor turn in the clockwise or counterclockwise direction. The transistors can be pulsed on and off as in a pulse-width modulation (PWM) circuit, or they can ramped up and down as a simple linear circuit. The base of the transistors can be controlled by a controller section of an amplifier that is completely linear. Or the controller can be digital with a D/A converter to provide the analog control signal to the base of Q1 and Q2, or the controller can be completely digital and the base of transistors Q1 and Q2 can be pulsed directly by the digital controller. Typically IGBTs (insulated gate bipolar transistors) are used in modern servo amplifiers where PWM or other switching circuits are used. The IGBTs allow the transistors to be switched on and off at frequencies that limit the harmonic hum in a motor or amplifier. The high-pitched hum represents both audio and electronic noise that must be eliminated or controlled.

A typical linear amplifier for a servo system.

The amplifier circuits for DC servomotors are similar to the AC circuits used for pulse-width modulation or other switching systems. In fact the complete amplifier for AC servomotors will be similar to the variable-frequency drive amplifiers shown earlier in this chapter.

Early Amplifiers (Push-Pull Amps)

The design of amplifiers has changed rapidly over the last 15 years because transistors, triacs, and SCRs have become able to handle larger voltages and currents without damaging themselves. It is easy to see the advantages that the changes in these devices have brought to motor drive amplifiers, but you must keep in mind that the early amplifiers were built so well that you will run into them even today when you are asked to troubleshoot a drive system. For this reason it is prudent to leam their basic parts and functions so you will be able to troubleshoot and analyze them. It is also a good idea to understand their basic operation because this is what has been modified to make the newer drives more efficient and more powerful.

One of the earliest types of linear amplifiers is called a push-pull amplifier, which was designed so that two transistors switched on and off to share the current load for the motor. Figure 2 shows an example of this type of amplifier, and you can see that Q2and Q3 are the power transistors. They are connected to the primary winding of transformer T2. The servomotor winding is connected to the secondary winding of transformer T2.

The operation of the push-pull amplifier begins with a sine wave signal that enters the input of the push-pull amplifier through capacitor C1. Capacitor C1 makes sure that the input signal is a pure sine wave with no DC bias. The base circuit of transistor Q1 has a DC bias on it of approximately 13.5 volts. The base-emitter junction needs only 0.7 volt to turn it on, the rest of the DC bias voltage providing DC current through R2 and R3. This causes the sine-wave input signal to practically turn transistor Q1 off at its minimum, causing Q2 to be driven almost into saturation at the sine wave’s maximum. This causes current to flow through the primary winding of transformer T1. Notice the secondary of T1 is center tapped to ground. When the positive half of the sine wave appears on the secondary, it appears across the entire secondary. Because of the center tap, only the upper portion of the secondary sees a positive voltage, and this forward bias transistor Q2 allows it to conduct. Transistor Q3 is turned off because it sees a negative voltage at its base. With Q2 conducting, current flows up through the primary of T2, providing a positive pulse to the secondary of T2. When Q3 conducts, a negative pulse is provided to the primary of T2.

FIGURE 2 Push-pull amplifier for an AC ser-vomotor. This diagram shows the power stages of the amplifier.

Chopper Amplifiers

Another type of early amplifier for a servomotor is called the chopper amplifier (see Fig. 3). In this type of amplifier the positive rectangular DC pulses arrive at the input of the amplifier circuit at capacitor C1. These pulses arrive at the base of Q1 as narrow spikes, which momentarily turn Q1on. This in turn momentarily turns Q2 on, which allows current to flow through the primary of transformer T1. Now the primary of transformer T1 is really an L-C tank circuit. (Remember that the primary winding of the transformer is actually a big inductor.) When this tank circuit is hit by a pulse, it will produce a cycle or two of pure sine wave. When hit, in other words, the tank circuit will ring like a bell. The amplifier circuit is the clapper that rings the bell. Notice the secondary of T1 is center tapped to —60 Vp. The secondary of T1 sees a pure AC sine wave, and to this AC signal, the —60Vp appears as a ground. This means that for the positive half-cycle of the sine wave, Q3 would see a positive pulse, and Q4 would see a negative pulse. Both power transistors are NPN transistors, so a positive bias is needed at the base to cause them to conduct. As both bases are grounded , Q4 would go into conduction because its emitter is lower than its base, giving it a forward base-emitter bias. The output of the tapped control winding would then be a sine wave. It should be noticed that the tapped control winding has +60 Vp on it, and the secondary of T1 has —60 Vp on it. This means that the output of the tapped control winding is going to be a 120-Vp sine wave.

FIGURE 3 Output stages of a chopper amplifier for an AC servomotor.

FIGURE 4 Two-transistor amplifier for a DC servomotor.

PLC Vs Microcontrollers

I have never worked with a PLC , but I have read a number of articles on PLC. Microcontrollers!!! it is my life. I have heard a number of people arguing for importance of PLC over Microcontrollers. The following threads from some popular forums discussing the same.

What I have concluded from the comments is that

PLC is actually runs with a microprocessor or microcontroller based design which supports PLC instructions as its inputs and decodes it to execute it.

If you are good at programming microcontroller and your job to be done with the system is fixed, then it is unnecessary to use a PLC. PLC is a user easy option for electricians where they don’t need to understand all the circuitry and no need to train for every other processor we are using.

If you have employees who are unknown to microcontrollers and the programming language(or unknown to the specific microcontroller you are using) then it is tedious for them understand the things.

But the PLC is independent of the processor inside the instructions are standard.

Atmega with AVR Codevision

Hi friends,

Atmega is the best microcontroller to start with and the AVR Codevision compiler is the easiest C compiler to learn. It has a no of library functions for LCD, serial/SPI/I2C communication, delay and floating point math (which is the most complicated). It has a inbuilt chip burner and code generator. Download the evaluation version from its site


This is how the CodevisionAVR Desktop looks like. You can drag and drop the boxes. The first box shows source codes and other files associated with your project. The second box

Click at File->New, a pop up will be appear as shown below, select projects

Select yes to use CodeWizardAVR

Now the code wizard will appear, as shown below

Now you can set