# EECS 373 Lab 7: Data Converters

Copyright © 2010 - Ye-Sheng Kuo, Thomas Schmid, Matt Smith, and Prabal Dutta.

## Schedule

See posted lab schedule for due dates, in-lab, and post-lab due dates.

## Introduction

As you might guess, with all the other goodies included in SmartFusion MSS the folks at Actel did not forget ADC and DAC resources. The MSS ACE (Analog Computing Engine) is relatively complex component providing DAC/ADC functionality, sampling control, analog threshold detection, filtering and DMA access just to mention a few. Despite this apparent complexity, the ACE can be relatively easy to use. The ACE like the other MSS components is automatically interfaced to the peripheral bus and a user friendly GUI is provided for configuration.

## Objectives

The purpose of this lab is to...

1. Learn how to configure the ACE for basic DAC and ADC operations.
2. Learn to measure ADC quantization and typical transfer function characteristics.
3. Learn the basics of sampling by observing aliasing of sampled sine wave.
4. Learn how to build a simple audio amplifier.
5. Sample and record an audio signal for playback using the ACE and your audio amplifier.

## Background

### ADC Quantization and Transfer Function Characteristics

Quantizing error is inherent in most measurements and limits the certainty a measurement. The quantizing error for an ADC is defined to be 1 LSB. It can also be expressed in volts or LSBv for an n-bit ADC .

Quantizing error in volts = voltage range of conversion/2^n

For our converter, the voltage range is 2.56 volts.  If we program the ACE to be an 8 bit ADC, the quantizing error in milli-volts will be

LSBv = 2.56 volts/2^8 = 10 mv

So, you can only know the value to 10 mv. The ideal quantum size of 1 LSB can actually vary to be larger or smaller from fabrication issues and other sources. These effects are characterized as integral non-linearity (INL) and differential non-linearity (DNL).  Under normal conditions in the lab you will NOT observe this.

Plotting the conversion value against the analog value defines the ADC transfer characteristic or input to output relationship.

The first graph shows the ideal transfer function excluding quantizing effects. The second case illustrates the affect of quantizing resulting in a stair case like transfer function. In this case the quantization error is from 0 LSB to 1 LSB. The last graph illustrates an ADC model that shifts the transfer function to center the quantizing error over the conversion intervals. In this case, the quantization error is +/-  ½  LSB. In both cases the quantizing error is 1 LSB, but the relationship of the conversion value to the input voltage is shifted by ½ LSB.

### Sampling Basics

When converting relatively stable voltages to digital values a few samples are sufficient to represent the voltage. However, when sampling time varying signals the question arises, just how many samples are required to represent the signal. The Nyquist-Shannon sampling theorem predicts that periodic signals can be reproduced when the original signal is sampled at >= 2 times its period. If the signal is sampled at a rate that is less than the 2 times its period, the reconstructed signal will have a different frequency and shape. A simple predictor is given by the following equation:

alias frequency = sampled signal frequency - sampling frequency

The reconstructed signal is commonly referred to as an alias and is a common problem in applied signal processing. There are many topics forming the foundation of signal processing, but these basics should cover our needs for the present.

## Overview

### Pre-Lab Assignment

1. Read through the lab 7 notes.
2. Read through the data converter lecture.

### In-Lab Assignment

2. Aliasing, Quantization error, Smoothing filter
3. Simple Audio system

## In-Lab Assignment

### Aliasing, Quantization error

#### Configuring the SmartFusion ACE

Each SmartFusion Eval Kit has 10 direct analog input channel and 2 Sigma-delta DAC. We want to use just one of each. Open the Libero, SmartDesign. Double click ACE

In left column, add a ADC Direct Input service. Put ADC_input0 in Signal Name and check Send raw ADC result to DMA, and click OK. On the top of configurator, set the resolution to 8 bits.

Add another Sigma Delta DAC service, select ACE Accumulator as DAC input and select the DAC resolution to 8 bits. Click OK.

Set your ADC Direct Input Package Pin to V12 ( ADC5 ), and Sigma Delta DAC Package Pin to V7 ( SDD0 )
Go to Controller tab, select ADC1_MAIN. Add all Available signals to sampling rate requirement. Click Calculate Sequence and Actual Rate

Notice that the Total sampling rate should be 87.000 ksps. We want to slow it down to 8 ksps.
Select the Operating sequence entry to Manual and insert a operating sequence slot.

Insert a WAIT TIME and configure it to 115us. Move the Wait for 115.00us above Restarts the execution sequence for this timeslot. Click Calculate Actual Rate. The Actual Rate for ADC / DAC should be 8.000 ksps. Click OK and go to Firmware tab. Check the UART, ACE, NVM, PDMA drivers.

Click Save and Generate. Put the IP core to canvas and run the synthesis, place & route and flash your SmartFusion.

Create a C project in Softconsole as you did before, set the linker script, import the drivers. The following code reads the ADC
and  write the DAC with the ADC conversion value

```#include <stdio.h>
#include <inttypes.h>
#include "drivers/mss_ace/mss_ace.h"
#include "drivers/mss_uart/mss_uart.h"

int main(){
ACE_init();
ACE_configure_sdd(
SDD1_OUT,
SDD_8_BITS,
SDD_VOLTAGE_MODE | SDD_RETURN_TO_ZERO,
INDIVIDUAL_UPDATE
);
ACE_enable_sdd(SDD1_OUT);

while(1){
}
return 0;
}
```

Put the code in a main.c file. Compile the source code and launch the debugger session.

#### Connecting to the DAC and ADC

Hook the signal generator to the extension board  header pin 5 ( paper label)  in the bottom right corner to provide input to the DAC. If you don't have a paper label this is labeled ADC1. Observe the DAC output on the BNC shown connected.

Using the signal generator as a signal source, provide a sine wave that centers a sine wave over the input range of the ADC (0 - 2.56 volts). A DC offset of 1.25 volts should be fine with a Vpp (peak to peak) voltage of 2.5 volts. Be sure the signal generator output is set to High Z to insure accurate signal levels. Verify with the scope before attaching to the kit to avoid damage to the ACE.

#### Aliasing Measurements

Slowly increase the frequency of the signal generator while observing and measuring the frequency of DAC. Determine the frequencies or frequency ranges for the following questions. You will need this information to answer questions in the post lab.
1. Over what frequency range is the reproduced signal frequency (DAC output) and signal shape visually reproduced well?
2. Over what frequency range is the reproduced signal frequency intact, but the signal shape noticeably quantized?
3. At what frequency is the reproduced signal frequency nearly zero?
4. At what frequency is the reproduced signal frequency nearly half the source?

#### Implementing a Smoothing Filter

Quantizing in the DAC output can produce high frequency components that in the audible range sound like common radio static. To remove these components a low frequency pass filter can be used to reject the high frequency components. We will use a simple passive filter consisting of 2 components.

To remove the high frequency components, consider a half power point near the max frequency that you wish to pass. The half power point or 3db down point (.707 volts below input voltage) is give for a low pass filter to be 2pi f = 1/RC. Let's consider the case for smoothing a 1 KHz signal. Choosing 2 KHz for the 3 db down point gives 6.28 × 2000Hz × RC = 1. We must choose common RC values. Starting with 1K ohm resistor gives a C of 0.08 UF (micro farads or 10^-6 farads). The closest value in the lab is .068 uf. This will produce a 3db frequency of ~2.34KHz. Close enough!

Set the source signal to 1 KHz sine wave. Observe the DAC output. Notice the quantizing steps in the output wave form. With the input and output waveforms displayed on the scope, it should look something like this.

For the post lab, record the number of quantizing steps there are per cycle.

Construct a low pass filter with a 1K ohm resistor and 0.068uf capacitor on a protoboard. Wire the DAC to the input of the filter and observe the output.

You should notice a signal that is pretty close to a continuous sine wave. The signal will be attenuated because of the filter.

The filter output amplitude should be about 0.707 the value of the input voltage value at the 3db down frequency (2.34KHz) . Notice that it is considerably lower. Adjust the frequency until the filter output value is 0.707 the value of the source frequency and record the frequency for the post lab.

#### Measuring Quantization Error

In order to observe the ADC result correctly, we output the data through screen instead of using the scope. Adding the following line in the while(1) loop.
`printf("adc_result: %u\r\n", (adc_data>>4));`

You will measure the transition or boundary voltages for the first 4 ADC conversion values 0, 1, 2 and 3. The lab power supply 0-6 volts output can be adjusted to ~ 1mv, so you can use this as a voltage source. The voltage meter on the power supply is not accurate enough for 1 mv measurements, so you should use the DMM. Be sure to use the cable configurations shown in the following configuration or you will introduce interference that will make it difficult to resolve the transition voltages.

The procedure for measuring the transitions voltages is to simply start at 0 volts then gradually increase the voltage until you see the conversion value change. The voltage at which the conversion value changes Is the transition voltage. You will likely find that the transition voltage does not occur neatly on a 1mv boundary. In fact, it will waggle between adjacent conversion values for several millivolts. Measure this transition phase by measuring when the waggling starts and stops. Record the following values to answer questions in the post lab assignment. The start and end boundary values should be no more than a few millivolts apart. If they are, consult your lab instructor.
Conversion Value Low Boundary Start (mv) Low Boundary End (mv) High Boundary Start (mv) High Boundary End (mv)
0 0 0
1
2
3

### Build a Simple Voice Recorder

Now, we learned how to use ADC / DAC in SoftConsole, we want to build a voice recorder using the SmartFusion Eval. Kit. However, we cannot connect the microphone directly to the ADC and connect the speaker to DAC. We need some signal conditioning between the board and mic / speaker.

You should received the following components in this lab.
Components Value Quantity
MIC 1
Speaker 1
OP Amp LM741 2
Power Amp LM386 1
Resistor 10 Ω 1
1k Ω 1
2.2k Ω 2
10k Ω 2
22k Ω 2
100k Ω 1
Capacitor 0.047uF 1
0.068uF 2
0.47uF 1
220uF 3

#### The Circuits

We want to implement the voice recorder system. The system is composed of three parts,

1. Power Supply filter
2. MIC Pre-Amp circuit
3. Speaker Power-Amp circuit
The first part of the circuit is just simply placing the decoupling capacitors on the breadboard. The function of the capacitor is to stabilize the supply voltage.
The second part consists of two OP-Amps. The OP-Amp is a circuit which has high open-circuit gain with high imput impedance and low output impedance. The OP-Amp is widely use in many cuircuits board. In our system, the first OP-Amp(close to MIC one) is use to amplify the signal. The Second OP-Amp sets a DC-bias before sending  to ADC.

The last part of the circuit uses another amplifier to amplify the signal from DAC. Check the data sheet for the amplifier used in this circuit.  Can we replace the amplifier with LM741? Why or why not? Provide this answer for you post lab.

#### Building the Amplifier on a Breadboard

Before building your circuit, you may want to check these references.

• If you are not famaliar with the breadboard, go to the Wikipedia : BreadBoard make sure you understanding the connection of the board before you start.
• Resistor codes keeping you up at night? Check the Resistor Color Code for the meaning of color code and get a good nights sleep.
• Don't know the device pin assignment? Check the datasheet on the top of the page "additional materials" for datasheet of LM741 and LM386.
• Please note that the 220uF capacitor is polarized, make sure you have the right connection.

The following circuit is for your reference. Keep your connections short and neat as shown.

Once you are done with the Pre-Amp part, connect the power supply to the board. In this circuit, we need +/- 10 Volt for +/- VSS. Be careful not to short the power to ground. If you notice the current goes thru the roof, turn off the output of power supply! This usually means your circuit has a short between power and gnd. Connect the scope to the Pre-Amp output and the microphone(positive), observe the amplified signal. What is the gain(Vout/Vin) of the circuit? Do not need to consider the DC offset, which means you can set the scope to AC coupling to observe the gain.

When you finish the Power-Amp part, do not connect to the SmartFusion kit immediately. Instead, verify the operation of the by connecting the first part and second part together. Try to generate some voice in MIC. Can you hear the voice from speaker? If not, check the circuit until you can hear your voice in the speaker.

### Connect to SmartFusion Eval Kit

Connect the pre-amp output to the ADC1 as you did before, and DAC1 output to power-amp. In this typical application, we will record voice for 10 seconds  to memory. The size of the data = 8k Samples/sec × 1 Byte/Sample × 10 sec = 80k bytes. We are memory limited at the moment and have to share the space with the program code.

The data is stored in 0x6002b000, if you put your code in eVNM, make sure the data won't override your code

Open the Libro, we want to configure the ACE with interrupt telling the microprocessor the DAC data has been sampled. In other words, we want to generate the 8K Hz interrupt and update the DAC registers. Go to the controller tab, insert operation sequence slot, select SET INTERRUPT

Configure the interrupt bit to GP0, click OK.

Generate the design, synthesis and program your SmartFusion. Updating the following code to SoftConsole. Find out how to subscribe the interrupt generated by ACE. (PC0_FLAG0) Update the DAC data once the interrupt is fired.

`#include <stdio.h>#include <inttypes.h>#include "drivers/mss_uart/mss_uart.h"#include "drivers/mss_watchdog/mss_watchdog.h"#include "drivers/mss_ace/mss_ace.h"#include "drivers/mss_gpio/mss_gpio.h"#include "drivers/mss_nvm/mss_nvm.h"#include "drivers/mss_pdma/mss_pdma.h"uint8_t *envm = (uint8_t *) 0x6002b000;uint32_t envm_idx;#define FREE_BUFFER         	0#define UNDER_DMA_CONTROL   	1#define DATA_READY          	2#define SAMPLES_BUFFER_SIZE	128#define NB_OF_SAMPLE_BUFFERS	2#define	TOTAL_SAMPLE_SIZE	81920/* PDMA  destination */uint32_t samples_buffer[NB_OF_SAMPLE_BUFFERS][SAMPLES_BUFFER_SIZE];uint8_t buffer_status[NB_OF_SAMPLE_BUFFERS];void ace_pdma_rx_handler();void process_samples();void free_samples(uint8_t);void play_samples();volatile uint8_t pdma_buffer_idx = NB_OF_SAMPLE_BUFFERS;int main(){    uint8_t full = 0;    envm_idx = 0;    dac_irq = 0;    MSS_WD_disable();    ACE_init();    ACE_configure_sdd(    	SDD1_OUT,    	SDD_8_BITS,    	SDD_VOLTAGE_MODE | SDD_RETURN_TO_ZERO,    	INDIVIDUAL_UPDATE    );    ACE_enable_sdd(SDD1_OUT);    PDMA_init();    PDMA_configure    (        PDMA_CHANNEL_0,        PDMA_FROM_ACE,        PDMA_LOW_PRIORITY | PDMA_WORD_TRANSFER | PDMA_INC_DEST_FOUR_BYTES,        PDMA_DEFAULT_WRITE_ADJ    );    PDMA_set_irq_handler( PDMA_CHANNEL_0, ace_pdma_rx_handler );    NVIC_EnableIRQ( DMA_IRQn );    free_samples(full);    while (1)    {	// recording mode    	if (full==0)	   process_samples();	// playing mode    	else{	    play_samples();    	}    	if (envm_idx>=TOTAL_SAMPLE_SIZE){    		envm_idx = 0;    		if (full)    			full = 0;    		else    			full = 1;    		free_samples(full);    	}    }    return 0;}void free_samples(uint8_t full_flag){	uint32_t i;	for ( i = 0; i < NB_OF_SAMPLE_BUFFERS; ++i ){		buffer_status[i] = FREE_BUFFER;	}	pdma_buffer_idx = 0;	buffer_status[pdma_buffer_idx] = UNDER_DMA_CONTROL;	if (full_flag){	}	else{		PDMA_enable_irq( PDMA_CHANNEL_0 );	    PDMA_start	    (	        PDMA_CHANNEL_0,	        (uint32_t) PDMA_ACE_PPE_DATAOUT,	        (uint32_t) samples_buffer[pdma_buffer_idx],	        SAMPLES_BUFFER_SIZE	    );	}}// PDMA recived interruptvoid ace_pdma_rx_handler(){    PDMA_clear_irq( PDMA_CHANNEL_0 );    buffer_status[pdma_buffer_idx] = DATA_READY;    PDMA_disable_irq( PDMA_CHANNEL_0 );}void process_samples(){    uint8_t i;    if ( buffer_status[pdma_buffer_idx] == DATA_READY){    	uint32_t proc_buffer_idx = pdma_buffer_idx;    	if (pdma_buffer_idx==(NB_OF_SAMPLE_BUFFERS-1))    		pdma_buffer_idx = 0;    	else			pdma_buffer_idx++;    	if (envm_idx<TOTAL_SAMPLE_SIZE){	    PDMA_start (	    PDMA_CHANNEL_0,	    /* Read PPE_PDMA_DOUT */	    (uint32_t) PDMA_ACE_PPE_DATAOUT,	    /* This is in MSS ESRAM */	    (uint32_t)samples_buffer[pdma_buffer_idx],	    SAMPLES_BUFFER_SIZE	    );	    PDMA_enable_irq( PDMA_CHANNEL_0 );    	}	buffer_status[pdma_buffer_idx] = UNDER_DMA_CONTROL;	uint8_t data_processed[SAMPLES_BUFFER_SIZE];        for ( i = 0; i < SAMPLES_BUFFER_SIZE; ++i ){	    volatile uint16_t raw_value;	    raw_value =  ACE_translate_pdma_value(samples_buffer[proc_buffer_idx][i], 0);	    data_processed[i] = raw_value>>4;        }	NVM_write((uint32_t)(envm+envm_idx), data_processed, SAMPLES_BUFFER_SIZE);        envm_idx += SAMPLES_BUFFER_SIZE;    }}// put your code herevoid play_samples(){}`

#### Answer These Questions and Provide the Voice Recorder Modification Demo for the Post Lab.

In the above code, we use the PDMA to transfer the data from ADC register to SRAM, after a simple processing, the data was stored to eNVM. However, the code uses 8K Hz interrupt to send the data from eNVM to DAC.

Questions

1. The PDMA uses a common technique called "double buffer." Explain how the double buffer works.
2. Can we use the 8KHz interrupt in ADC? Why or why not? What is the advantage of using PDMA?

Voice Recorder Modification

1. Now, you have built your own voice recorder. Extend your code to support double speed, half speed and backward play. Show your recorder to the instructional staff for signature.
2. Improve the quality of your audio voice recorder. There are 2 basic ways to do this: increasing the sampling and amplitude resolution. Are sampling resolution is currently limited. Try improving the vertical resolution. Do you hear a difference. Demonstrate to the instructional staff.

## Post-Lab Assignment

#### Quantization Questions

Submit the values transitions values you measured for the In-lab. Add a column for each conversion value and calculate the difference between the start boundary high value and start boundary low value. Assume this voltage difference represents the voltage range for each conversion interval. Answer the following questions:

1. What is the voltage range for the first conversion interval (0)? What is this value in LSBs?
2. What is the voltage range for the subsequent intervals? What is this value in LSBs?
3. Why do you suppose the conversion values do not neatly change with 1mv change in voltage?
4. What transfer function graph illustrated in the In-Lab does this ADC represent?
5. Is there any advantage generally speaking to this transfer function compared to the other? (Hint: Consider how the quantizing error is expressed.)

#### Sampling Questions

1. At what frequency did you notice the aliasing frequency was nearly zero? How does it compare to the sampling frequency?
2. At what frequency did you notice the reproduced freq was half the input frequency? Does this follow the aliasing prediction?
3. At what frequency did you begin to notice quantizing steps in the reproduced signal? In light of the sample frequency, why does this become easy to observe?
4. For the on 1KHz source frequency example, how many quantizing steps did you observer per cycle? What is the ratio of the source frequency to the sampling frequency? How does this compare to the number of quantizing steps you observe?
5. The amplitude of the low pass signal was considerably lower than expected for the 3db down frequency. This likely from the DAC source resistance output loading the filter and effectively changing the 3b down point frequency. After adjusting the source frequency, at what freq did you find the 3db point to be? Given the RC values of the filter and the measured 3db freq, what value do you think the DAC source freq is? Hint: The combined filter resistance is the DAC source resistance plus the filter resistance.
6. Check the SmartFusion specification and see how the DAC source resistance compares to your calculated value. smartfusion Hint: Search for DAC output impedance.

Voice recorder

Provide the answers from questions in the In-Lab and a Signoff sheet for your modified voice recorder.