EMBEDDED DESIGN OF AUDIO ACQUISITION SYSTEM Bhavin Ketankumar Gandhi B.E., Gujarat University, India, 2008 PROJECT Submitted in partial satisfaction of the requirements for the degree of MASTER OF SCIENCE in ELECTRICAL AND ELECTRONIC ENGINEERING at CALIFORNIA STATE UNIVERSITY, SACRAMENTO FALL 2010 EMBEDDED DESIGN OF AUDIO ACQUISITION SYSTEM A Project by Bhavin Ketankumar Gandhi Approved by: __________________________________, Committee Chair Jing Pang, Ph.D. __________________________________, Second Reader Preetham Kumar, Ph.D. ____________________________ Date ii Student: Bhavin Ketankumar Gandhi I certify that this student has met the requirements for format contained in the University format manual, and that this project is suitable for shelving in the Library and credit is to be awarded for the Project. __________________________, Graduate Coordinator ________________ Preetham Kumar, Ph.D. Date Department of Electrical and Electronic Engineering iii Abstract of EMBEDDED DESIGN OF AUDIO ACQUISITION SYSTEM by Bhavin Ketankumar Gandhi The audio processing is of great importance in today’s world of portable mobile devices for large data storage. The purpose of the project is to record an audio data, store it in a memory storage device, and then retrieve it for later use. This will aid audio processing in its verification on hardware if data are processed before and after storing. Embedded design includes collecting audio data from a microphone and capturing it in an AVR microcontroller using an embedded Analog to Digital Converter (ADC) and an external preamplifier. Then, sampled data are stored in a flash memory. Stored data are then used for playback through the speakers. The Pulse Width Modulation (PWM) was used as a Digital to Analog Converter (DAC) for converting digital data into analog signal, followed by a filter and an amplifier for driving speakers. The project was implemented on an Atmel Corporation STK500 kit along with an AVR microcontroller. The required ADC and PWM logic were available in the AVR iv microcontroller. Serial Peripheral Interface (SPI) was also a feature the AVR microcontroller. It was used to interface a flash with an AVR microcontroller. The filter circuit and the amplifier circuit for the microphone were designed using operational amplifiers LM358 and LM324. _______________________, Committee Chair Jing Pang, Ph.D. _______________________ Date v ACKNOWLEDGEMENTS I would like to take this opportunity to acknowledge everyone whose contributions played a significant role in the success of this project. I will start with thanking Professor Jing Pang under whose guidance this project was initiated and accomplished. Her vision was the main driving force for the accomplishment of this project. Professor Jing Pang’s knowledge in the field of audio processing was extremely helpful. During this project, I learned many different concepts relevant to audio engineering. I would also like to thank Dr. Preetham Kumar for providing his guidance and significant feedback in writing this project report. With his effort and assistance the reader will better understand this report. His experience as the EEE coordinator was very useful from the inception to the end of the project in many different ways. I would also like to extend my thanks to the ECS department and the Graduate Studies department at California State University, Sacramento for their support. I would also like to thank my family members, roommates and friends for always inspiring me in this important phase in the process of completion of my master degree and special thanks to my lab mate Mitul Shah for his technical help in the lab during the execution of my project. vi TABLE OF CONTENTS Page Acknowledgements ............................................................................................................ vi List of Tables ..................................................................................................................... ix List of Figures ......................................................................................................................x Chapter 1. INTRODUCTION ...........................................................................................................1 1.1 Goal of the Project.................................................................................................1 1.2 Overview of Project Implementation ....................................................................2 1.3 Organization of Report ..........................................................................................3 2. ANALOG TO DIGITAL CONVERSION ......................................................................4 2.1 A to D Theory of Operation ..................................................................................4 2.2 ADC in AVR .........................................................................................................5 2.2.1 ADC Initialization ..........................................................................................6 2.2.2 ADC Conversion............................................................................................8 3. PULSE WIDTH MODULATION .................................................................................10 3.1 Using PWM as DAC ...........................................................................................10 3.2 PWM in AVR ......................................................................................................11 4. FLASH MEMORY AND SPI INTERFACE ................................................................14 vii 4.1 SPI .......................................................................................................................14 4.1.1 SPI Protocol .................................................................................................15 4.1.2 SPI Initialization in AVR .............................................................................16 4.2 Flash ....................................................................................................................17 4.2.1 Flash Write ...................................................................................................17 4.2.2 Flash Read ....................................................................................................19 4.2.3 Flash Erase ...................................................................................................20 5. EMBEDDED SYSTEM DESIGN .................................................................................21 5.1 Microphone Preamplifier ....................................................................................21 5.2 PWM Filter..........................................................................................................24 5.3 Software Design Flow .........................................................................................25 5.3.1 Main Module................................................................................................26 5.3.2 Recording .....................................................................................................28 5.3.3 Playback .......................................................................................................31 5.3.4 Erase .............................................................................................................33 6. CONCLUSION AND FUTURE WORK ......................................................................34 Appendix – Implementation Code ................................................................................ 35 References ..................................................................................................................... 44 viii LIST OF TABLES Page 1. Table 2.1 ADC Conversion Time .......................................................................... 5 ix LIST OF FIGURES Page 1. Figure 1.1 Block Diagram of the Project ................................................................ 1 2. Figure 2.1 Block Diagram of SAR ADC ................................................................ 4 3. Figure 2.2 Algorithm for ADC Initialization ......................................................... 6 4. Figure 2.3 Algorithm for A to D Conversion ......................................................... 8 5. Figure 3.1 PWM Output Waveform ..................................................................... 11 6. Figure 3.2 Algorithm for Initializing Timer in PWM Mode ................................ 12 7. Figure 4.1 SPI Interface Signals .......................................................................... 15 8. Figure 4.2 Algorithm for Initializing SPI ............................................................ 16 9. Figure 4.3 Algorithm for Writing into Flash ....................................................... 17 10. Figure 4.4 Algorithm for Reading Data from Flash ............................................ 19 11. Figure 4.5 Algorithm for Erasing Flash ............................................................... 20 12. Figure 5.1 Microphone Pre-amplifier Circuit ...................................................... 22 13. Figure 5.2 Oscilloscope Waveform of a Pre-amplifier Input and Output............. 23 14. Figure 5.3 Analog Filter Circuit ........................................................................... 24 15. Figure 5.4 Algorithm for Main Module of the Program Part 1 ............................ 26 16. Figure 5.5 Algorithm for Main Module of the Program Part 2 ........................... 27 17. Figure 5.6 Algorithm for Recoding Module Part 1 .............................................. 29 18. Figure 5.7 Algorithm for Recoding Module Part 2 .............................................. 30 19. Figure 5.8 Algorithm for Playback ...................................................................... 31 20. Figure 5.9 Algorithm for Erase Module .............................................................. 33 x 1 Chapter 1 INTRODUCTION This chapter begins with a description of the project’s goal and an overview of its implementation. It also provides information about the organization of the project report. 1.1 Goal of the Project Figure 1.1 describes the block diagram of the project. This project is about acquiring an audio data, storing it, and then playing it back. As shown in the block diagram, the project involved the use of a microphone for converting audio signal into analog signal, because of its low amplitude needs to be amplified. Microphone pre-amplifier Circuit To Speaker Analog to Digital converter in ATMEGA 32 Flash as an external memory Filter Circuit PWM as DAC in ATMEGA 32 Figure 1.1 Block Diagram of the Project The microphone preamplifier circuit was used for amplification. After amplifying, analog data was converted into digital form by using an analog to digital converter. These digital data 2 was stored into the flash memory. The first half of the project involved the recording of audio data. The next half involved with playing it back through speaker. For this, digital data needs to be converted into analog form. Pulse width modulation (PWM) is used as a digital to analog converter (DAC). PWM DAC is followed by a filter which is eventually followed by a speaker that converts analog signals into an audio signal. 1.2 Overview of Project Implementation An ATMEGA32 as an AVR microcontroller and STK 500 kit was used for the implementation of the project. Each has everything required for the successful implementation of this project. The biggest advantage of the STK500 is its compatibility with the ATMEL microcontrollers. It also has a separate power switch and a reset switch. The reset switch restarts the microcontroller program. There are 2 serial ports for communication with a personal computer. Switches and LED were used for debugging and making the project user friendly. User guides for the STK 500 are also easily available on web. These features make the STK 500 the perfect kit for the implementation of this project. Main feature of the AVR microcontroller is its advanced RISC architecture, thus making it faster. It has 1024 bytes of EEPROM and 2k bytes of internal SRAM. It has an ADC and a timer with the PWM mode which can be used as a DAC. AVR Studio was used for loading the microcontroller using STK500 firmware. ATMEGA32 has an inbuilt ADC which was used for analog to digital conversion of amplified data. A timer with the PWM mode which was used as a DAC and its output was given to the filter circuit. The SPI feature of an AVR microcontroller was used for interfacing the flash 3 memory with a microcontroller. General operational amplifiers LM358 and LM324 were used in amplification and filter circuits. [2][4] 1.3 Organization of Report This section describes the organization of the project report which will help the reader’s when reading the report. The organization of the report also appears in the index. However, only the names of the concepts are included; this section will include detailed information of the reports organization. This report is organized chapter wise, and each chapter has information relevant to its name. Chapter one includes project’s background; defines the goal and significance of the project. Chapter two provides the information about the operation of the ADC. It also describes how the ADC was configured in the ATMEGA32 microcontroller. Chapter three describes using a PWM as a DAC and its configuration in an AVR microcontroller. Chapter four describes SPI protocol and how flash can be written, read and erased. Chapter five describes how the amplifier and the filter were designed, and also explains software design flow. Chapter six summarizes the project and discusses possible future work. 4 Chapter 2 ANALOG TO DIGITAL CONVERSION 2.1 A to D Theory of Operation The figure 2.1 shows the basic architecture of successive approximation ADC. SAR ADC includes sample-and-hold circuit for holding the analog signal during conversion. EOC or Busy Timing Convert Start SHA Analog Input Comparator Control logic: Successive Approximation Register (SAR) Digital Output DAC Figure 2.1 Block Diagram of SAR ADC [6] As shown in the figure 2.1 the sample-and-hold circuit is placed in hold mode, after sampling present input signal on the assertion of start conversion bit. At the same time internal the DAC (Digital to Analog Converter) is placed to its midscale. The Comparator compares the outputs of the DAC and the SHA circuit and stores the result in the successive approximation register (SAR). After comparison, depending on the bit 1 (most significant bit) of the SAR register, the DAC is scaled to 25% or 75% of its highest scale. If the bit is 1, then the DAC is 5 scale to 75% and if the bit is 0, the DAC is scaled to 25%. After that once again comparison is done and a bit 2 is set accordingly. This process continues until the logic levels of the all the bits are determined. The final value of the SAR register is the digital representation of the sampled analog input. [6] 2.2 ADC in AVR ADC in AVR also uses the SAR method for analog to digital conversion. The SAR method of conversion has an advantage of accuracy and speed over other methods of analog to digital conversion, but with additional hardware. The ATMEGA32 has 10 bit 8 channel ADC. It has differential as well as single ended inputs. It also has an inbuilt operational amplifier. The single ended inputs refer zero voltage to ground. The ADC also has sample and holds circuit which holds the value of input voltage until ADC logic converts analog input voltage to digital. Two differential channels have programmable gain of 1x, 10x or 200x. [2] Condition Sample and Hold (Cycle) Conversion Time (Cycles) First Conversion 13.5 25 Normal conversion, single 1.5 13 Auto Triggered conversion 2 13.5 Normal Conversion, 15./2.5 13/14 ended Differential Table 2.1 ADC Conversion Time [2] 6 The ADC can have any of 3 different reference voltages. One of those is the internal reference voltage of 2.56V and other two are the externals. ADC can be used in the single conversion mode or a free running mode. Important feature of the AVR ADC is its noise cancelling technique. The conversion time of and ADC is an important parameter for the calculation of a sampling frequency. It is given in the table 2.1. [2] 2.2.1 ADC Initialization ADC Initialization Select ADC channel zero, single ended single conversion mode with no amplifying gain and external Aref voltage as reference voltage using resistor ADMUX. Disable Analog Comparator Enable ADC and ADC interrupt and set clock division by 32. Return Figure 2.2 Algorithm for ADC Initialization [2] 7 There are mainly two registers ADMUX and ADCSRA are used for the ADC’s configuration. As show in the figure 2.2 the register ADMUX is used for selecting the ADC channel in a single ended or a differential mode with or without amplification of 1X or 10X. It is also used to select reference voltage and a resolution of the ADC to be used. The register ADCSRA is used for scaling the ADC’s internal clock’s frequency with respect to the crystal frequency. It is the register which is used to enable the ADC for its use. Its other uses are for enabling the ADC interrupt mechanism and for starting a conversion when the ADC is used in single conversion mode. Algorithm also shows to disable analog comparator logic if it is not in use to save power when initializing the ADC. [2] This project’s implementation configures the ATMEGA32 ADC’s channel zero in single conversion, single ended mode with no amplification. The external reference voltage was selected with given Aref voltage of 2.0V. The Aref voltage decided after monitoring the output voltage range of the microphone pre-amplifier. The frequency of the ADC’s internal clock was equal to crystal frequency divided by 16 and the ADC interrupt mechanism was enabled. The analog comparator was kept disable to save power. [2] 8 2.2.2 ADC Conversion RUN ADC Start ADC Conversion using ADCSRA register NO ADC conversion complete interrupt set? YES Clear ADC conversion complete interrupt Return Digital value from ADCH register Figure 2.3 Algorithm for A to D Conversion [2] The figure 2.3 shows the algorithm for the implementation of analog to digital conversion ATMEGA32 ADC. The RUN ADC module is used when there is a need of an analog to digital conversion. The register ADCSRA’s start conversion bit is set in order to start a new conversion in single conversion mode and then wait for the ADC’s conversion complete interrupt bit to be set. When set, it shows that ADC’s current conversion has been complete and digital data is 9 available in ADC data register. The ADC is now ready for the next conversion. There are two 8bit ADC data register, ADCH and ADCL. The data is read from them as per the configuration of the ADC. If the ADC is configured in 8bit or less resolution then only the ADCH register is read, and if higher resolution is used then both register are to be read. [2] 10 Chapter 3 PULSE WIDTH MODULATION Most of the applications in embedded systems need digital to analog conversion. It was no different for this project. After storing digital audio data in to the flash through the ADC, they need to be converted into analog during playback stage of that audio. There are two ways with which this part could be done. One of them is to use a Digital to Analog converter IC. Because of the requirement of using multiple power supplies for the Digital to Analog converter IC, it was decided to use Pulse Width Modulated signal for digital to analog conversion. PWM signal was generated using Timer 0 of the AVR microcontroller in the fast PWM timer mode. This chapter first describes how the PWM is used as DAC and then the configuration of the PWM in the AVR microcontroller. 3.1 Using PWM as DAC As its name suggest, the PWM signal in generated by modulating pulsed width of the square wave. The frequency of the PWM signal remains constant but the pulse width is changed. Change in the pulse width is nothing but change in the duty cycle. The figure 3.1 shows a PWM output signal with constant frequency and variable duty cycle. [1] The frequency of the PWM signal is so high that the change in its duty cycle can be seen as alternating analog voltage by the device which is using it. Depending on the application, before using the PWM signal, a filter circuit may be needed or not. Best illustration for understanding the application of the PWM signal is to control the brightness of the LED. 11 Figure 3.1 PWM Output Waveform When a very high frequency PWM signal is given to the LED, it is seen as ON and duty cycle of PWM signal controls the brightness of the LED. The LED will be seen as ON, as human eyes won’t be able to capture the change in the LED state at the fast PWM frequency rate. The brightness of the LED for a period of PWM cycle will be decided by duty cycle during that period. If the Duty cycle is 80%, it means 80% of the time, signal is ON and thus the brightness of LED will be 80% of its highest. Similarly 40% of full brightness is appeared at 40% duty cycle. The same concept is implemented in case of the speaker. The requirement of the filter was an addition between a speaker and PWM output in order to reduce high frequency components and thus, reduce noise. [1] 3.2 PWM in AVR The PWM signal was generated using Timer 0 of ATMEGA32 in the fast PWM mode. In the fast PWM mode the counter called the timer counter register (TCNY0) counts from zero to 12 its maximum value and the comparator scans the timer value and compares it continuously with the value of TCCR0 register. Based on the mode of the operation, timer sets or resets the output on OC0 pin, and keeps it constant until it reaches the maximum value, where it returns to its previous logic level. Same steps are followed for each period of the PWM. Thus the value of the TCCR0 register changes the duty cycle of the PWM output at PWM frequency. This is how the Pulse Width Modulation is implemented in an AVR microcontroller. [2] Initialize Timer for PWM Set Timer for fast PWM non-inverting mode with no clock scaling Initially set PWM for 50% duty cycle Clears Timer/Counter interrupt flags Enable Timer counter overflow interrupt Return Figure 3.2 Algorithm for Initializing Timer in PWM Mode [2] 13 The figure 3.2 shows the algorithm for configuring Timer 0 of ATMEGA 32 in the PWM mode, which is used for reproducing the sound. The register TCCRO is used for configuring the timer in timer mode, counter mode, fast PWM or Phase correct PWM mode. Because of its high fundamental frequency, the fast PWM mode was used. Initial duty cycle is kept 50 % for PWM frequency. During timer initialization it was made sure that the timer counter interrupt mechanism is enabled. This interrupt is set when the timer counter rolls over its maximum value and returns back to zero. This is used to reload the value of the CCRO register as per the sampled data read from the flash for changing the duty cycle for the next period and thus changing the sound generated. The frequency of the PWM output is given by the equation 3.1. [2] π ππ π ππππ = π∗256 …..………………………………………… (3.1)[2] Where, ππππ is the frequency of PWM output, πππ π is the frequency of the oscillator and N is the divider of the clock frequency for the timer logic. 14 Chapter 4 FLASH MEMORY AND SPI INTERFACE After converting analog data from a preamplifier into digital, it has to be stored somewhere for later processing and reproduction. Internal memory of the ATMEGA32A has 1Kb of EEPROM which is very small for storing audio data sampled at 15k and having 8bits per sample. Thus there was a requirement of an external flash memory. The Flash used was Winbond W25Q80BV. It has a storage capacity of 1M bytes. It works on maximum of 3.6V, and has a fast read and writes time. It supports SPI interface, and also has pin for write protection. All requirements for this project were met by this flash and thus it was decided to use this flash. Only problem that was faced because of using flash memory in this project was to run whole project at 3.6V or use dual power supplies for this system. Reason for the requirement of dual power supply was that, LM386 used for amplification during the filter stage, works on minimum of 4V. Using dual power supply was not a good choice. Thus it was decided to run the whole project at 3.6V by use of speakers with internal amplification. This chapter will describe SPI protocol and flash write, read and erase module. [7] 4.1 SPI For serial communication with flash, SPI protocol was used. The SPI is a synchronous serial interface in which 8-bit byte data can be shifted in and/or out, one bit at a time. SPI interface feature is also available in AVR microcontroller. SPI protocol and its implementation in AVR device is shown in the section below. 15 4.1.1 SPI Protocol The SPI is a synchronous, duplex protocol. It has four pins namely MOSI (Master Out Serial In), MISO (Master In Serial Out), SCK (Clock) and CS (Chip Select). It is a single master – multiple slave communication protocol. In this project there is only one master called ATMEGA32 microcontroller and one slave called serial flash. AVR SPI uses three wires for synchronous data transfer and can operate as a master or a slave. It allows LSB or MSB as a first bit to be transfer and supports multiple bit rates. It also has an end of transmission interrupt. Figure 4.1 show the interface signals of SPI. Figure 4.1 SPI Interface Signals [2] As mentioned above, the SPI requires three wires for communication between master and slave, and fourth signal is optional, and can be used for selecting slave. Master device controls the clock for communication. No communication takes place when clock is not available. In this project all four signals were used. SPI interface is mainly dependent on to three registers: SPCR, SPSR and SPDR; SPCR register is a control register and main register for setting up SPI. [2] 16 4.1.2 SPI Initialization in AVR SPI Initialiazation Enable SPI in Master mode 3 and set clock polarity and clock phase Return Figure 4.2 Algorithm for Initializing SPI [2] Figure 4.2 shows the algorithm to initialize the SPI. SPI initialization in microcontroller is done using SPCR register. It’s a SPI control register. It is used to enable SPI logic, and then configure it. It selects controller mode of operation either to be slave or master. It also selects clock polarity and clock phase. It is also used to select data order of either LSB first or MSB first. It has a clock divider to divide SPI internal clock with respect to microcontroller’s crystal frequency. It also enables or disables the interrupt. The Maximum clock frequency can be used for the SPI logic is equal to the crystal frequency divided by 4. In this project SPI is running at 2 MHz clock with a crystal frequency of 8 MHz. Microcontroller was set as a master mode. Clock polarity and clock phase were kept by default. SPI interrupt was enabled. [2] 17 4.2 Flash 4.2.1 Flash Write Flash Write Select flash and enable its command decoder Send write command Send Address Writing finish? NO YES Return + Figure 4.3 Algorithm for Writing into Flash [2] 18 Figure 4-3 shows the algorithm for writing data to flash. Flash has its own internal register which is needed to be configured for writing and reading. Master Out Serial In pin is used for writing data into the flash and Master In Serial Out pin is used for reading data from the flash. Before sending any bits to the flash, it has to be selected by driving the CS pin from high to low. High to low transition will also reset flash’s command decoder. After that, if write is to be done then write command is send serially on MOSI pin and 24 bits address is send. Flash has 1 M bytes of storage which is equal to 8 M bits. Thus minimum of 3 bytes of address is required in order to select address of 8Mbits of storage. After address has been sent, 8 bits of data is sent. After sending data, the corresponding status register of the flash is read to ensure write has been completed. Once it has been ensured that write has been completed, controller is ready for the next instruction. [2][7] 19 4.2.2 Flash Read Flash Read Select flash and enable its command decoder Send Read command Send Address Send dummy byte on MOSI pin to get data on MISO pin Return Read Data Figure 4.4 Algorithm for Reading Data from Flash [2] The figure 4.4 shows the algorithm for reading the data from the data flash. Similar to the write operation, initially flash is selected and its command decoder is reset. Then read command is sent on MOSI pin followed by a read address. In order to keep the read logic of flash active, it 20 is necessary to keep the clock of master SPI clocking. For that reason 8 bit dummy data is sent while receiving 8 bit serial data from the flash into the SPI data register SPDR. [2] 4.2.3 Flash Erase Flash Erase Select flash and enable its command decoder Send Erase command NO Erase done? YES Return Figure 4.5 Algorithm for Erasing Flash [2] The figure 4.5 shows the algorithm for erasing the data flash. Erasing the data flash is easy. It just needs to reset the command decoder of the flash. Then, send an erase command to erase the data flash. After erase command has been sent, in order to ensure that flash has been erased, read the respective status register of the data flash. [2] 21 Chapter 5 EMBEDDED SYSTEM DESIGN This chapter describes the overall implementation of the audio acquisition system. It describes the designs of the microphone pre-amplifier and analog filter, which were the part of hardware design. It also describes the software design flow for recording, playing back and erasing. These three modules use the different modules which were explained in the previous chapters. Recording uses ADC and flash write module while playback uses flash read and PWM module and erase uses erase module. 5.1 Microphone Preamplifier Microphone output was very small and because of the presence of the noise, the SNR was very low. Before the small voltage analog signal of the microphone is given to the ADC it has to be pre-amplified and then filtered. This will increase the SNR by increasing signal voltage and decreasing noise. Pre-amplification was done using LM358, an op-amp best suited for amplifying low voltage of the microphone. LM358 was setup in a non-inverting mode. Following circuit was used as preamplifier followed by a simple Butterworth low pass filter. LM358 was setup in a non-inverting mode. The problem faced during pre-amplification stage was of getting a rail to rail output form LM358. LM358 is not capable of producing rail to rail output. After, measuring the output range of LM358 for microphone input with the help of oscilloscope, decision was made to solve this problem, was of changing a bias voltage at the inverting pin of the op-amp, which creates virtual ground for the non-inverting pin. 22 VCC R1 10K C3 U1A 8 3 V+ + R4 33u OUT 2 1 4K - 4 LM358 VR3 30K R2 3.85K C1 1u R5 10K C2 1u 0 Figure 5.1 Microphone Pre-amplifier Circuit [10] LM358 was setup in a non-inverting mode. The problem faced during pre-amplification stage was of getting a rail to rail output form LM358. LM358 is not capable of producing rail to rail. Thus, bias voltage was kept half of the maximum output voltage available from the LM358. In order to make this compatible with the analog to digital converter, an analog reference voltage also needed to be changed to maximum output voltage swing of LM358 which was 2V. Voltage divider resistors values were chosen in a way to give the required bias voltage of 1 volt. π£ππ πππ’π‘ = π 2 ∗ π 1+π 2……………………………………………………..(5.1) The value of the gain was chosen to be 3.85k after monitoring the amplifier output for the microphone for the optimum value. Simple RC Low pass filter was used to reduce the unwanted noise which is generated through a pre-amplifier stage. 23 Formula for RC filter is 1 ππ = 2∗π∗π ∗πΆ………………………………………….(5.2) Where, ππ is the cut off frequency. R and C are the resistance and the capacitance of the Butterworth filter respectively. Figure 5.2 Oscilloscope Waveform of a Pre-amplifier Input and Output Gain of an amplifier was kept to 4. Thus, the output voltage appears to be four times the input voltage. Gain for non-inverting amplifier is calculated by the equation πΊπππ = 1 + π π π π ……………………………………………(5.3) Rf is feedback resistor and Ri is the input resistor for the inverting pin. From the preamplifier circuit Rf is equal to 30k and Ri is equal to 10k. Thus gain is equal to 4. 24 5.2 PWM Filter Analog filter was required to be designed for filtering PWM output into a decent sine wave to give it to the speakers. Lots of high frequency harmonics are there in the PWM output from the microcontroller. Frequency of PWM itself is very high, and thus produces a high pitch noise which is to be filtered. VCC R4 1k C2 0.1u C4 R1 R2 U1 8 3 1u 5K V+ + R5 3.3K OUT 2 R3 1k 1 4.7K - 11 LM324 0.01u C1 VC3 0.01u 0 Figure 5.3 Analog Filter Circuit [9] ππ πππ =π 1 2 2 π +π1 π +π0 ……….…………...………………………(5.4) [5] Where, π0 = 1 π1 = πΆ1 ∗ (π 1 + π 2) 25 π2 = 2 ∗ π 1 ∗ π 2 ∗ πΆ1 ∗ πΆ2 1 ππ = 2∗π∗π 4∗πΆ4 …………………………………………………(5.5) So a low pass active filter with a cutoff frequency of 3.3 kHz was created ensure that all the components having a human voice frequency doesn’t filtered out. Second order Chebyshey order was design with a cutoff frequency of 3.3 kHz and having 3 dB band ripple and a unity gain. This filter has little bit band pass ripple but it was acceptable in our design due to its low amplitude. The transfer function of the filter is shown in figure 4.4. The values of the resistance were chosen in a way to have a value of capacitors which were available in the lab. 1 st order Butterworth filter was also designed to follow Chebyshev filter to minimize noise of PWM frequency. Cut-off frequency of the Butterworth filter was chosen to be of 4k hz. This is similar to cut-off frequency of Butterworth filter during pre-amplification. [5][9] 5.3 Software Design Flow This section describes the software design flow for recording, playing back and erasing. These three modules use the modules which were explained in previous chapters. These three modules are used by a module called main module. Recording uses ADC and flash write module while playback uses flash read and PWM module and erase uses erase module. 26 5.3.1 Main Module Main module Ports initialization using I/O INIT PWM initialization using TIMER INI module SPI initialization using module SPI ADC initialization using ADC INIT module Run ADC once using RUNADC module 1 Figure 5.4 Algorithm for Main Module of the Program Part 1[3] 27 1 Recording Switch Pressed? YES Start recording module YES Start Playback module NO Playback Switch Pressed? NO Erase Switch Pressed? YES Start Erase module NO Figure 5.5 Algorithm for Main Module of the Program Part 2 [3] Figures 5.4 and 5.5 show the algorithms for the main module of the project. Initially all the logics of the ATMEGA32 to be used are initialize in the main module and then the switches are scanned for the other operation. If recording switch is pressed then recording module is called. Similarly, if playback switch is pressed then playback module is called and erase module is called if erase switch is pressed. The following section will elaborate recording, playback and erase module. Recording module sample the audio data and store it into a memory while 28 playback retrieve the stored audio data and then play it on speakers. Erase module erase the memory 5.3.2 Recording The recording is one of the main functions of the whole design. Function involves sampling audio data using ADC and then storing that sampled digital data into the flash. This function also decides the sampling rate of the ADC. Thus it eventually decides the amount of data that can be stored in the memory of 1 M bytes. The figure 5.6 and 5.7 shows the algorithm for the recoding module. It starts when the recording switch is pressed and keeps on recording until switch is released. First thing it does after switch is pressed is checking whether the data flash memory is full or not. If it is full then there is no point in recording and module is exited indicating through led that data flash is full. If flash is not full it starts recording and converts the pre-amplified microphone output into the digital sample through ADC. Digital data of the ADC is taken into the local register and then that data is written into the next available location of the flash. For converting analog data into digital, RUNADC module of the ADC is used and for writing data into the flash, WRITE FLASH module is used. After it is made sure that data is written into the flash, it is disabled by driving its chip select pin high so that no fake data is written into it. Figure 5.7 also shows that once analog to digital conversion and flash writing for the data, the loop for 32 clocks is run before starting any other data sampling. This loop of 32 cycles decides the sampling frequency of the ADC. 29 Record Recoding Switch Pressed? Return NO YES Is flash full? NO Display respective leds for showing flash is full YES Display respective led to show recording Convert Preamplifier output into digital using module RUN ADC Get converted ADC sampled data in to local register 1 Figure 5.6 Algorithm for Recoding Module Part 1 [3] 30 1 Write sampled data into Flash using WRITE FLASH module Set chip select to disable Flash Loop for 32 clocks Return Figure 5.7 Algorithm for Recoding Module Part 2 [3] This value of 32 was chosen after coming up with the following calculations. Crystal frequency for the microcontroller is = 8 Mhz. Thus for 8 Mhz crystal frequency, PWM frequency comes to 31.25 Mhz. Which means the counter of the PWM will update its value at the rate of 31.25 Mhz i.e. every 256 clocks. Each ADC conversion, in single conversion mode, takes 14 cycles and the ADC logic was configured to run at frequency equal to frequency of crystal divided by 16. Thus one ADC conversion will take total of 224 crystal cycles. Also after converting data in to digital it needed to be written into the flash. Writing to the flash was done in parallel, thus in order to use each sample for producing the signal back, the sampling frequency should be matched to the counter update rate of the PWM. Thus total of 256-224 = 32 cycles of delay was chosen for having a sampling rate, which takes care of both, perfect signal reproduction and optimum storage. 31 5.3.3 Playback Playing back Playback Switch Pressed? NO Return YES Is flash empty? NO Display respective leds for showing flash is empty YES Display respective led to show playingback Read sample from the Flash using FLASH READ module Write read data into Counter register of timer 0 Loop for 60 clocks. Return Figure 5.8 Algorithm for Playback [3] 32 The figure 5.8 shows the algorithm for playing back the sound which was stored in flash by using the Playback module. Similar to recording, the playback starts with the pressing of the playback switch. It first checks for the availability of the data into the flash. If the data is not available in the flash then that playback module is exited indicating through the led that there is no data available for playing back. Playback needs conversion of digital data into analog, and then filtering it out for the quality sound. Filtering is done with the help of an external filter, while analog to digital conversion is done using PWM. After, reading the 8 bit sample from the flash, it is written to the OCR0 register of the Timer 0. Thus PWM output on OC0 pin will vary its duty cycle according to this vale and thus making it to look like an analog value to the filter because of its high frequency. After, writing data to the OCR0 register delay, of 64 clocks is kept. The reason for this delay is not to lose any data from the flash. The Frequency of PWM comes to 31.25 at 8 Mhz and thus its counter value will be updated after every 256 clocks. Reading a flash takes 48 SPI cycles and the frequency of SPI being 2 Mhz, it will take total of 192 oscillator clock cycle. Now total of 256 -192= 64 cycles of wait is required for not losing any data before the timer counter updates it. Thus 64 cycles of delay is kept before starting the playback module again. [2] 33 5.3.4 Erase Erase Erase Switch Pressed? Return NO YES Erase flash using ERASE FLASH module Display respective led to show flash has been erased Return Figure 5.9 Algorithm for Erase Module [3] The figure 5.9 shows the erase module for erasing the data flash for the new recording. This was the easiest of the any other module in this project. It simply scans for the erase switch and when it is pressed it calls the ERASE FLASH module of flash and displays the respective led showing that the erase has been done. 34 Chapter 6 CONCLUSION AND FUTURE WORK It can be concluded from this project that designing an embedded system for acquiring audio data can be done successfully on the STK 500 kit using an AVR microcontroller. The preamplifier circuit, analog to digital conversion, data writing into and reading data from flash, digital to analog conversion, and filter circuit, are all modules that can be successfully implemented without any error and are explained with thorough details in the project report. More improvement in sound quality than the one which is currently available may be achieved by using a specific audio amplifier instead of a general amplifier. If the amplifier IC with a rail-to-rail output is used, the SNR can be increased but at the cost of increase in the quantization error of the ADC. The optimum design for this tradeoff may improve output. This project has provided the basic platform for many other projects. Different types of audio processing like compression, decompression, speech recognition, etc., can be performed on the audio samples which are stored in the memory. 35 APPENDIX Implementation Code acquisition_system.c #include<avr/io.h> #include<avr/sfr_defs.h> #define F_CPU 8000000 #include<util/delay.h> // This is for using the _delay_ms() function unsigned char data,Level; static unsigned long int i =0, j=0; void io_init(); void Flash_SPI_init (void); unsigned char Flsah_SPI_RW (unsigned char output); unsigned char Read_Flash_status (void); void Flash_Write_Enable(void); void Flash_page_write(unsigned long int byte_counter, unsigned char data); void Flash_chip_erase(void); void Flash_page_read(unsigned long int byte_counter); unsigned int run_adc(); void ADC_init(); void pwm_init(); 36 void pwm_init() { TCCR0 = 0x00; TCNT0 = 0x00; TCCR0 = 0x79; OCR0 = 0x7F; TIFR = 0x00; TIMSK = 0x01; } unsigned int run_adc() { ADCSRA|=0x40;//Start ADC conversion while((ADCSRA & 0x10)==0);// wait while ADC interrupt is enabled. ADCSRA|=0x10;//clears the interrupt flag return ADCH;// return 8bit digital value } void ADC_init() { ADCSRA=0x00; // Disable ADC 37 ADMUX = 0x20; // External AREF,ADC result left adjusted ADC channel in 0 single conversion mode ACSR = 0x80;// Disable analog comparator ADCSRA = 0x8C; // Enable ADC, ADC Intrrupt Enable, Clock division by 32 . } void Flash_SPI_init (void) { SPCR = (1<<SPE) | (1<<MSTR) | (1<<CPHA) | (1<<CPOL); //Enable SPI in Master mode, mode 3 } unsigned char Flash_SPI_RW (unsigned char output) { unsigned char input; SPDR = output; while(!(SPSR & 0x80)); input = SPDR; return input; } //put byte 'output' in SPI data register //wait for transfer complete, poll SPIF-flag //read value in SPI data reg. //return the byte clocked in from SPI slave 38 unsigned char Read_Flash_status (void) { unsigned char result; PORTB |= (1<<PORTB4); //make sure to toggle CS signal in order PORTB &= ~(1<<PORTB4); //to reset dataflash command decoder result = Flash_SPI_RW(0x05); result = Flash_SPI_RW(0x00); return result; //send status register read op-code //dummy write to get result //return the read status register value } void Flash_Write_Enable(void) { unsigned char result; PORTB |= (1<<PORTB4); PORTB &= ~(1<<PORTB4); result = Flash_SPI_RW(0x06); } //make sure to toggle CS signal in order //to reset dataflash command decoder //send status register read op-code 39 void Flash_page_write(unsigned long int byte_counter, unsigned char data) { unsigned char result; Flash_Write_Enable(); PORTB |= (1<<PORTB4); //make sure to toggle CS signal in order PORTB &= ~(1<<PORTB4); result = Flash_SPI_RW(0x02); result = Flash_SPI_RW((char)(byte_counter>>16)); result = Flash_SPI_RW((char)(byte_counter>>8)); result = Flash_SPI_RW((char)(byte_counter)); result = Flash_SPI_RW(data); while((Read_Flash_status() & 0x01)); } void Flash_page_read(unsigned long int byte_counter) { unsigned char result; PORTB |= (1<<PORTB4); //make sure to toggle CS signal in order PORTB &= ~(1<<PORTB4); result = Flash_SPI_RW(0x0B); result = Flash_SPI_RW((char)(byte_counter>>16)); 40 result = Flash_SPI_RW((char)(byte_counter>>8)); result = Flash_SPI_RW((char)(byte_counter)); result = Flash_SPI_RW(0x00); } void Flash_chip_erase(void) { unsigned char result; Flash_Write_Enable(); PORTB |= (1<<PORTB4); PORTB &= ~(1<<PORTB4); result = Flash_SPI_RW(0xC7); while((Read_Flash_status() & 0x01)); } void io_init() { //--------------- output DDRD=0xff; DDRC=0xff; //make sure to toggle CS signal in order 41 //--------------- seting port A 0 for input and 1 for output DDRB = 0b10111111;//Port B used for PWM output and SPI interface for Flash DDRA=0x00;// Port A used for ADC input and Switched } int main(void) { io_init(); Flash_SPI_init(); pwm_init(); ADC_init(); PORTD = 0xF0; _delay_ms(100); PORTD = 0x0F; Level=run_adc(); while (1) { if (!(PINA & 0x80)) 42 { if (i<0x000FFFFF) { PORTD = 0x7F; Level=run_adc(); Flash_page_write(i,Level); PORTB |= (1<<PORTB4); i=i+1; _delay_us(7); } else { PORTD = (!(0x7F)); } } if (!(PINA & 0x40)) { if (i<0x000FFFFF) { PORTD = 0xBF; while (!(PINA & 0x40)) 43 { while (!(TIFR & 0x01)); Flash_page_read(j); data = Flash_SPI_RW(0x00); OCR0 = data; TIFR = TIFR | 0x0; j = j+1; PORTD = data; _delay_us(56); } } else { PORTD = (!(0xBF)); } } if (!(PINA & 0x20)) { Flash_chip_erase(); PORTD = 0xDF; }}} 44 REFERENCES [1] D. M Alter, “Using PWM output as a digital to analog converter on a TMS320C240 DSP”, Texax Instruments Inc., 2009. [2] Atmel Corporation, “8-bit AVR microcontroller with 32K bytes in-system programmable flash ATMEGA32”, 2004. [3] Atmel Corporation, “Application note AVR 335: digital sound recorder with AVR and data flash”, 2005. [4] Atmel Corporation, “AVR STK 500 user guide”, Rev. 1925C-AVR, March 2003. [5] Perry Miller, “Aspects of data acquisition system design”, Texax Instruments Inc., 2005. [6] Walt Kester, “MT-021: ADC architectures II: successive approximation ADCs”, Rev. 0, January 2006. [7] Winbond Electronics Corp., “SPI flash W25Q80”, Rev. A3, February 2007. [8] D. Gupta, & V. Nandikonda, “Embedded system design 4840”, Columbia University, 2004. [9] R. Sinha, & W. Chung, “Voice compression using ADPCM algorithm”, Cornell University, January 2005. [10] Joel Chan & Jeremy Tan, “Sound effect processor”, Cornell University, November 2003.