Interfacing AVRmicrocontroller to ADC and waveform generator

I am doing first project with AVR microcontroller ATmega32-A.

In this project I am interfacing with ADC (AD7798), waveform Generator[(AD9833), Multiplexer, Capacitive sensor, Demodulator. I have attached simple block diagram for understanding purpose.

I have to generate sine wave and give it to sensor and in return I will get sensor output with some phase shift. I have to select the sensor output and input signal using Multiplexer. The selected signal will pass through demodulator and to the ADC. Finally ADC to Micro controller.

The concept is I want calculate phase difference between two signals such as Input(Vg) and output(Vr). To calculate the phase value I have implemented algorithm as like below.

Phase of Vg (and so Vr in return) is what I can change, phase of demodulator switch (square signal from frequency divider) is constant and it is my background. I can put both Vg and Vr signal through demodulator.

The algorithm must look like this: put Vg through demodulator, sweep WGP(waveform generator signal phase) until you get highest DC value (now you store how many degrees it takes to get this highest DC, and you calculate Vg amplitude from that). Then put Vr signal through demodulator and also sweep WGP until highest DC value. This phase shift WGP value will be different for Vg and Vr. In result you have the amplitude of both signals and phase difference between them.

I have wrote all functions like To read ADC value, Generate signal with specified frequency,Changing phase of the signal, Phase sweep from 0 to 360 degrees etc.

I have written the fallowing code to select signal using Multiplexer and change the phase of the signal from 0 to 360 degree by one degree at each time and getting the max value of D.C voltage.

From the above code I am able to select signal using “MUXSEL” Command and I am able to sweep phase from 0 to 360 degree, I am able to get max D.C voltage and corresponding Phase value. I am able get above value whenever I add delay.


If I delete this delay from “Phaseshift” function, it is giving nothing even if I reduce also.

If I place that delay then I am getting Max D.C voltage and corresponding Phase after 45 secs. This is too large time in my application. Then I have change channel then it also take 45sec and i have to use this values in other calculation so it takes large time.

I want get Max D.C voltage and corresponding Phase value with in 2 to 3 sec.

Any one help me how to do this. … AD9833.pdf

added spi() function.

unsigned char spi(unsigned char data)

  //Start transmision 
  SPDR = data; 
  //Wait for transmision complete 
  while (!(SPSR & (1<<SPIF))); 
 return SPDR;