Sei sulla pagina 1di 11
Chapter 13: Digital to Analog Conversion and Sound Embedded Systems - Shape The World Jonathan Valvano and Ramesh Yerraballi As we have seen throughout this clas, an embedded system uses its input/output devices to interact with the extemal world. Input devices allow the system to gather information about the world, and output devices ean allt vissal, mechanical, chemical, auditory, and biologic processes in the world In this chapter we wil literally “Shape The World” We present a technique for the system to generate an analog output using a digital to analog ‘converter (DAC), Together with periodic interups the system can generate waveforms, which are analog voltages that vary in time aad amplitude ‘We will then connect the waveform (oa speaker und generale sound. Learning Objectives: Develop a means for a digital computer to interact with the analog world Study digitization: Quantization, range, precision and resolution, Introduce sampling and the Nyquist Theorem Bal Study the basics of sound: eleetromagnets, speakers, AC vs. DC power, = perception of sound Understand how to ereate sound: loudness, pitch, envelope, and shape Use SysTiek to ereate sounds by programming variable frequencies, Video 13.0. Introduction to Sound gre Sine wave > — SDS seconds of a 220 Hz sine wave Problems playing ths file? See media hel. 13.1. Approximating continuous signals in the digital domain ‘An analog signal is one that is continuous in both amplitude and time. Neglecting quantum physics, most signals in the world exist as continuous functions of time in an analog fashion (eg, voltage, curent, postion, angle, speed, free, pressure, temperature, and flow ete )in other words the signal ‘has amplitude that ean vary over time, bul the value cannot instantaneously change. To represent signal inthe digital domain we must approximate it intwo ways: amplitude quantizing and time quantizing (or Sampling). From an amplitude perspective, we will first place limits onthe signal restricting it coexist between a minimam and maximum value (e,, 0 to+3V), and second, we will divide this amplitude range into finite set of discrete values. ‘The range of the system is the maximum minus the minimum value. The precision of the system defines the number of values ftom which the amplitude ofthe digital signal is selected, Precision can be given in numberof altematives, binary bits, or decimal digits. The resolution isthe smallest ‘change in value tha is significant. Furthermore, with respect to time one considers analog signals to exist ftom time equals minus infinity zo plus infinity. Because memory is finite, when representing signals on a digital computer, we will restrict signal to finite time, or we could have afnite set of data that are repeated overand over, Figure 13.1 shows a temperature waveform (solid line), with a corresponding digital representation sampled at | Tz and stored asa S-bit integer number With a range of 0 to 31 °C. Because it is digitized in both amplitude and time, the digital samples (individual dots) i» Figure 13.1 must exist a an intersection of grey lines. Because it is a time-varying signal (mathematically, this is called a function), we have one amplitude for each time, but itis possible for thereto be 0,1, or more times for cach amplitude at g EI £ 4 SS x g = Discrete digital signal Veo 1.1. Pedant of 5 Digitization & 8-- Continuous analog signal at o 1 23 4°58 6 7 8 9 10 Time (s) Figure 13.1. An analog signal is represented in the digital domain as discrete samples ‘The second approximation occurs in the time domain, Time quantizing is caused by the finite sampling interval. For example, the data are sempled ‘every | second in Figure 13.1 In practice we will use a periodic timer to trigger an analog to digital converter (ADC) to digitize information, ‘converting ftom the analog to the digital domain. Similasly, if we are converting from the digital to the analog domain, we use the periodic timer to ‘output new data to a digital to analog converter (DAC). Tae Nyquist Theorem states that ifthe signal is sampled with a frequency off then the digital samples only contain fequeney components fom 0 to ¥ f, Conversely, ifthe analog signal does contain fequency components larger than Ys fx then there will be an aliasing error during the sampling process (performed with a fequency off) Aliasing is whem the digital signal appears (o have a different equency than the original analog signal, Also note, the digital date has 11 values at times 0 to 10, but no information before time=D, and no information ater time=10 Checkpoint 13.1} Why can't the digital samples represent the litle wiggles inthe analog signal? Checkpoint 13.2 } Why can’t the digital samples represent temperatures above 31 °C? Checkpoint 19.3 What range of Gequencies is represented inthe digital samples when the ADC is sampled once every millisecond? Checkpoint 19.4 ¢ 111 wanted to create an analog output wave with requency components from 0 fo 11 klfz, what isthe slowest rate at which I could output to the DAC? Proving the Nyquist Theorem mathematically is beyond the scope of this course, but we ean presenta couple examples to support the basic idea ofthe [Nyquist Theorem: we must sample at sate faster than twice the rate a: which signal itsel's oscillating. Video 13.2. The Nyquist Theorem Ilustrated Example 1) There is a long distance race with runners circling around an oval track and itis your job to count the number of times a particular runner circles the track. Assume the fastest time a runner can make a lap is 60 seconds. You want to read a book and ‘occasionally look up to see where your runner is. How often to you have to look at your runner to guarantee you properly count the laps? I'you look at a period faster than every 30 seconds you will see the runner at least ovice per lap and properly count the laps. If ‘you look ata period slower than every 30 seconds, you may only see the runner once per lap and not know ifthe runner is going very fast or very slow. In this ease, the runner oscillates at most I lap per minute and thus you must observe the runner at arate faster than twice per minute Example 2) You live on an island and want to take the boat back to the mainland as soon as possible. There is a boat that arrives at the island once a day, waits atthe dock for 12 hours and then it sets sail tothe mainland, Because of weather conditions, the exact time of arrival is unknown, but the boat will always wait at the dock for 12 hours before it leaves, How often do you need to walk down to the dock to see if the boat is there? IF the boat is atthe dock, you get on the boat and take the next trip back to the mainland. Ifyou walk down to the dock every 13 hours, itis possible to miss the boat. However, if you walk down to the dock every 12 hours or less, you'll never miss the boat. In this case, the boat fequency is once/day and you must sample it (goto the dock) two times/day. Interactive Too! 13.4 Discover the Nyquist Theorem. A Continuous waveform like Figure 13.1 is shown, V = 1.5 + 1"sin(2pi60)}+0.5'cos(2pi 2004). You may Select the sampling rate and the precision (n bits) to see the signal captured. Notice that at sampling rates above 100 Hz you capture the essence of the S0Hz periodic wave, and above 400 Hz you capture the essence of both the 50 and 200 Hz waves. To ‘capture the essence" ‘means the analog and digital signal go up and down at ihe same rate. # sampling frequency = 400 Hz Et Number of ADC bit 5 bitts) 13.2. Digital to Analog Conversion A DAC converts digital signals info analog form as illustrated in Figure 13 2. Although one ean interface « DAC to a regular output port, most DACS: fare interfaced using high-speed synchronous protocols, lke the SSI. For more information about SSI, see Embedded Systems: RealTime Interfcing to ARME Cortex™M Microcanttolless,2014, ISBN: 978-1463590154. The DAC output can be cumeat or voltage. Additional analog processing may be requited to filter, amplify, or modulate the signal. We can also use DACs to design variable pain or variable offset analog circuits. ‘The DAC precision isthe number of distinguishable DAC outputs (eg, 16 altematives 4 bits). The DAC range isthe mximur and minimum DAC ‘output (volts amps) The DAC resolution is the smallest distinguishable change in output. The units of resolution are in volts or amps depending on ‘whether the ourput is voltage or cutent. The resolution is the change in output that occurs when the digital input changes by 1. For most DACs tere is simple relationship between range precision ard zesolution Rangetvotts) cision(altematives)+ Resolution(voits) Digital Input Analog 4 |" Output “ pac Analog signal (volts) 0123456789 wu His Video 13.3. Design of a DAC eireuit 4-bit Digital Input ana Figure 13.2. A 4-bit DAC provides analog output. Interactive Tool 13.2 Leam about DAC precision using this tool. The analog output is fixed in the range 0 to 3.3V. You may adjust the number of bits from 1 to 10 to see how close the fi isto the straight line. iB 10 Number of DAC bits 2s target signal 20. digital DAC output 10) ‘The DAC accuracy is (Actual - Ideal) Ideal where Idea is referred tothe National Insitute of Standards and Technology (NIST). One can choose the full scale range of the DAC to simplify the use of fixed-point math, For example, ian 8-bit DAC lnad a full scale range of 0 to 2.55 vols, then the resolution would be exectly 10 mV. This means that ifthe DAC digital input were 123, then the DAC output voltage would be 123 volts, Checkpoint 13.5 } A 10-bit DAC hasa range of 0 to 2.5V, what is the approximate resolution? Checkpoint 19.6 ; Youneed «DAC with ange of0 to 2V, and resolution of | mV. What isthe smallest number obits could you use forthe DAC? Txample 13.1, Design ad-bil bnany-weighted DAC with arango oT fo TS3V wang aso Solution, We begin by specifying the desued input/output relationship of the Toe Vout 0 it DAC. The design specifications are shown in Table 13.1 oo 00 10 3.3 11 2 3.3 0 22 ereery 33 able 13.1. Specifications of the Z-bit inary-weighted DAC Assume the ovtput high voltage (Vy) ofthe microcontroller is 33 V, and its output low voltage (Vor) is 0. With a binary-weighled DAC, we choose the resistor ratio to be 2/1 so Qy itis twice as significant asthe Qo bit, as shown in Figure 133, Considering the circuit on the left (no headphones), i both Q; and Qo are 0, the output Vaypi8 2210 IQ, is 0 and Qo is~3.3V, the output V4 is determined by the resistor divider nevwork Note the total impedance ftom 3 3V to ground inthe above circuit i 18k, Using Ohm's Law, withthe voltage divider equation, we can calculate Voy tobe 3 3V*6KO 18KN, which is | 1V, FQ) 1s+3 3V and Qo 1s, the output Vay 18 determined by the network 33V 6LQ yy 1%KQ — Qy ee ae Q ‘Again notice the total impedance ftom 3.3V to ground inthis second circuit is [RKO But this time we calculate Fy to be 3 3V* 12KQ/IBKA, whieh is 2.2V_Ifbath Qy and Qo are +3.3V, the output Fny i¢+3.3V. The output impedance af this DAC is approximately 12 kO, which means it eannot source ‘orsink much eusent 6kQ. 6kQ TMC] Q Tout 320 Vout Headphones Figure 13.3, A 2-bit binary-weighted DAC, ‘we eonnect headphones to this DAAC, as shown in the right sie of Figure 13.3, we could hear sounds generated by software writing a sequence of data tothe DAC. However, since the impedance ofthe headphones is much smaller than the impedance ofthe DAC, the output voltages will be very small, but we could calculate the currents into the headphones. Considering the circuit on the right (with headphones), if both Q, and Qg are 0, the output current is zero. If Q) is 0 and Qo is +3.3V, the output current, Joy, is 3.3V divided by 12.032kQ which is 0.275mA. If Qo is 0 and Qy is +3.3V, ‘the output curent, fgg is 3 3V divided by 6,032k0 which is 05S0mA. And finally, if both Qy and Qo are 33V, Jog is the sum of 0 275+0 380 (Kinkhot?s Curent Law, whieh is about © 825mA. Notice the current into the headphones is linearly related othe digital value In other words, digital values of0,1.2.3 map to currents of0,0275,0.550,0.825mA. Interactive Too! 13.3 ‘Shows how to compute Vout for the two scenarios bit1=0;bit0=1 and bitT= ;bit0=0. Using superposition, the scenario bitt=1;bitO=1 is ‘imply the sum of the two cases: bit1=0;bt0=1 and bit = {;bit0-0. bito.[ov ¥ bitt:[ov bits. 0 ov ov aov 1 ov 3av4.av 2 33V OV 22 Vout = ov You can realistically build a6-bit DAC using the binary-weighted method, Checkpoint 13.7 : How do-you build 3-bt binary-weighted DAC using this method? 13.3, Sound Generated by Speakers Before we generate sound, let's look at how a typical speaker works Sound exists as varying pressure waves that are created when a physical object moves, vibrating the air next to it. These air pressure waves travel through the arin all diections at about 343 misec, Sound can also be generated in Water, where it travels at 1484 msec. Our ews ean sense sounds ffom: 20 Lz to about 20 kilz In other words, the pressure wave must be oscillating faster than 20 Hand slower than 20 kHz forus to hearit, See Figure 134 Figure 13.4. Sound waves exist as pressure waves in media such as air, water, and non-porous solids. For more information on sound, see hup:iiwww mediacollege com/audio/0/sound-waves him! ‘There are two magnets in a speaker. There is a large permanent magnetic that creates a static magnetic field oriented in the direction the speaker is facing, and there is an electromagnet ereated by a spit fleld generated by a eylindrically-wound coil ‘wound coil oriented in the same direction Figure 135 shows a magnetic Figure 13.5. The magnetic field produced by a coil is very strong oriented in the direction of the cylinder. For more information on magnetic flelds produced by a coil, see huip:/www,ndi-ed.org/EducationResouces/CommunityCollege/MagParticie/Physies/CoilField him ‘The stength and direction of the magnetic field are related o the strength and direction ofthe electrical current conducted through the coiled wire Figure 13.6 shows e cut away of a typical speaker. The altemating magnetic field generated by the coil interacts with the constant magnetic field produced by the permanent magnet To generate sound we will crete an ascillating current through the coil, this will create an oscillating magnetic Feld, and will vibrate the voice coil. The diaphragm and spider hold the voice coil to the suspension allowing it ta vibrate up and down, Wher the ‘voice coil vibrates up and down it creates sound waves, The frequency and amplitude ofthe sound is directly related to the frequency and amplitude of ‘the eurent passing through the coil, The resistance ofthe coi in atypical headphone is 32.0, lHow Speakers Work AMEN ag dust cap suspension basket spider magnet Figure 13.6, A speaker can generate sound by vibrating the voice coil using an electromagnet. For more information on speakers, see Itp:/aeww how stuffvorks. com/speaker6. him or http:/www audiocircuit.com/DIYDynamic-Speakers/Article:How-dynamic- loudspeakers work Checkpoint 13.8 + Some speakers are heavier than others These heavy speakers have larger permanent magnets, Why would we want a ‘Permanent magnet that can eeate a large: magnetic field? 13.4, Music Generation Most digital music devices rely on high-speed DACs to create the analog waveforms required to produce high-quality sound. In this section, we will discuss a very simple sound generation system that illustrates this application of the DAC. ‘Te hardware consists ofa DAC and a speaker interface, ‘You can drive headphones ditectly from a DAC output, but to drive a regular speaker, you will need to add an audi amplifier as illustrated in Figure 37. 10kQ DAC ] headphones DAC ] O.1nF 20kQ speaker Out Out L/w : O.1nE yy yy MC34119 mt “ “ ety MC34119. Video 13.4. Sound as an analog signal: Loudness, pitch and shape ‘The quality ofthe music will depend on both hardware and soflwae factors. The precision ofthe DAC, external noise, and the dynamic range ofthe speaker are some ofthe hardware factors, Software factors include the DAC output rate and the complexity ofthe stored sound data. Ifyou output a sequence of numbers to the DAC that form a sine wave, then you will hear @ continuous tone on the speaker, as shown in Figute 138, The loudness of the tone is determined by the amplitude ofthe wave. The piteh is defined asthe fequency of the wave, Table 13.2 contains Hequency values forthe notes in one octave The frequency ofthe wave, fn, Will be determined by the equency ofthe inlerupt fp divided by the size of the table, The size ‘ofthe table in Progrem 13.1 is | loudness San San pitch = L/period Figure 13.8. The loudness and pitch are controlled by the amplitude and frequency. The frequency of each musical note can be calculated by multiplying the previous frequency by ‘V2. You can use this method to determine the frequencies oF additional notes above and below the ones in Table 13.2, There are twelve notes in an actave, therefore moving up ane octave doubles the fequency sas liz B 494 Hz Be 466 Hz A Holz ne as Hz G 392 Hz o 370 Hz F 349 Kz E 330 Hz & 311 Hz D 294 He be 277Hz c 262 He ‘Table 13.2. Fundamental frequencies of standard musical notes. The frequency for ‘A’ is exact. Figure 139 illustrates the concept of instrument. You cen efine she type of sound by the shape ofthe voltage versus time waveform. Bress instruments have avery large frst harmonic frequency Figure 13.9. A waveform shape that generates « trumpet sound. “The fempo ofthe music defines the speed of the song, In 2/4 3/4 or 4/4 music, « heat is defined a a quarter note. A moderate tempo is 120 beats/min, which means a quariernote has a duration of % second, sequence of notes can be separated by pauses silences) so that each note is heard separately ‘The envelope of the note defines the amplitude versus time relationship. A very simple envelope is illustrated in Figute 13.10. The Cortex™-M ‘processor has plenty of processing power to create these types of waves, 330 Hz 330 Hz 523 Hz Figure 13.10, You can control the amplitude, frequency and duration of each note (not drawn to scale). <— 05s ><— 0.58 ot 1.0s > “The smooth-shaped envelope, as illustrated in Figure 13 11 causes less staceato and more melodie sound, This type of sound generation is possible to produce in realtime on the Cortex™-M microcontoller Figure 13.11. The amplitude of a plucked string drops exponentially in time. A chord is created by playing multiple notes simultaneously. When two piano keys ae stuck simultaneously both notes are created, and the sounds fare mixed arithmetically. You can create the same effect by adding two waves together in software, before sending the wave tothe DAC. Figure 13.12 plots the mathematical audition ofa 262 Hz (low C) and a 392 Hz sine wave (G), cating a simple chord 2 1 Sound Amplitud: ° 0 0.005 0.01 0.015 0.02 Time (sec) Figure 13.12, 4 simple chord mixing the notes C and G. Example 132, Design 8 FR RIRDAC and uve [eto creates 100 Hizsine Wave Video 13.5a, Design ofa System that produces a 100H: Sine Wave. Video 13.5d. Construction of the DAC Cirewit Solution: We begin by specifying the desired input/output relationship ofthe 3-bit DAC. Table 13.3 shows the design specification. It willbe abe to ‘generate § different current oulpuls with a resolution of about 12.5 ju. The cizeuit is presented i Figuve 13.13, Ta BAD 00) 3 125 250 3 375 500 <3 625 3 750 133.3 875 ‘Table 133. Speciications of the 3b RR DAG wu ccwweds ‘We assume the output high voltage (Vy) of the microcontroller is 3.3 V, and its output low voltage (Vx) is 0. A 3-bit R-2R DAC will use two R tesistrs(11k0) and five 2R resistors Q22KED, a8 shown in Figure 13.13. The maximum catzent output wil be (1/2 | 1/4 + 1/8)*3 3V/33KQ= 87.5 WA. TMAC} Figure 13.13, A 3-bit R-2R DAC. ‘The way to analyze an R-2R DAC is o employ the Law of Superposition. We will consider the three basis elements (1,2, and 4) Ifthese three eases are demonstrated, then the Law of Superposition guarantees the other five will work. When one ofthe digital inputs is ue then Vig(3.3V)is connected t0 the R-2R ladder, and when the digital input is false, then the connection is giounded. See Figure 13.14 Since 22,000 is much bigger than 32, we can neglect the 32-2 resistance when calculating curent. Figure 13.14, Analysis of the three basis elements (001, 010, 100} of the 3-bit unsigned R2R DAC. Video 13.56. Analysis of a R-2R Ladder circuit In each ofthe thre testcase, the curent across the active switch is [p=Vry (BR). This curtent i divided by 2at each branch point Le, fy ~1y!2, and lp = 1y/2. Current injected trom the lower bits will be divided more times Since each stage diviges by two, the exponential bshavior 1s produced. An actual DAC is implemented with current switch rather than a voltage switch, Nevertheless, this simple circuit illustrates the operation ofthe R-2R ladder function. When the input is 001, Vygis presented tothe left. The effective impedance fo ground is 3R, so the eurent injected into the ROR ladder is g- Vp! (3K), The cuent is divided in hal thre times, and Jpg"Vryp! Q4R) ‘When the input is 010, Fis presente in the middle, The effective impedance to ground is stil 3R, so the curren injected into the R-2R ladder is Jo-Veag! GR), The eurent is divided in half twice, and Jpj9=Vrep! (128 ‘Wher the input is 100, Vis presented on the right The effective impedance to ground is once wgain 3X, s0 the current injected into the K-23 ladder is lg-Veg!(3R) The curent Is divided 9 hal once, and I, q0=Vre! (SR), Using the Law of Superposition, the output voltage is linear combination of the thee digital inputs, (4B) + 2by + byVpr! (AR). A current to voltage circuit isused to create a voltage output. T increase the precision one simply adds more stages ta the ROR ladder ‘To generate sound we need a table of data and a periodic intemupt. Program 13.1 shows C code that defines a 16-element 3-bit sine wave. The fiequency of the sound will be the intemupt frequency divided by 11 size of the table) So, to erate a 100 Hz wave we need Systick to interrupt at 16100 Hz, 1600 HIF the bus elack is 89 MHz, then the initialization should be called wath an input parameter of value 50000, The const modifier will place the data in ROM. The intcrupt software will output ane value t the DAC. See Figure 1315. Tn this example, the 3-bit DAC is interfaced to ‘output pins PR2-0, To output to this DAC we simply wnt to Port B, In order to create the sound, i s necessary to ouzpt just one number to the DAC upon each interrupt. The DAC range is 010 87 5 WA. A Periodic ISR 3-bit sin table z 6 3 4 QZ LOO an 1= (1) S0x0F a y 0 ‘Acknowledge Interrupt 02 4 6 8 10121416 t Index I return Figure 13,15, A DAC and a periodic interrupt are used o create sound. Oulput is discrete in time and voltage, const unsigned char SineWave[16) = (4,5,6,7/7,7,6/5/4/3,2/2/2,1,2,3)7 unsigned char Index=0; U1 tndax' varies Exon’ 0' to 15 7/ sieseveetssensDAG initesssevesnasenenearess // initialize 3-pit BAC 7/ input: none 7/ output: none void DAC_Init(void) (unsigned long volatile delay; SYSCTE_RCGC2_R |= SYSCTL_RCGC? GPIOB; // activate port B delay = SYSCTi_RCGC?_R; ~ // allow tine to finish activating Ger. PORTR AMSEL R E= ~0x07; 71 no analog GPLO_PORTS_PCTL_R &= ~0x00000FFF; // regular GPIO function GPIO_PORTS_DIR_R |= 0x07 1] make PB2-0 out GPIOPORTBLAFSEL R = ~0x07; // disable alt funct on PB2-0 007 71 enable digital 1/0 on PB2-0 J] seeeeueeenensesound_Inithsnnennennseassnnnnes // Initialize Systick periodic interrupts 7/ input: interrupt period uy Unite of period are 12.5na us Maximum is 2°24-1 uw Minimen is determined by length of ISR 77 output: none void Sound_Init (unsigned long period) { DAC_Init); 7/ Port Bis DAC Indax NVIC_s?_CTRL_R = 0 // disable Systick during setup NVIC_ST_RELOAD_R = poriod-1;// reload value NVIC_ST_CURRENE_R = 0; 71 any weite to current clears it NVIC_SYS_PRI3_R= (WVIC_SYS_PRI3_REOxOOFFFFFF) |0x20000000; // priority 1 NVIC_ST_EIRL_R = 040007; //"enable Systick with core clock and interrupts ]/ tetcceeeDAG OuLt EEE eteeeetnie 7/ output to DAC // input: 3-bit data, 0 to 7 7/ output: none void DAC_Out (unsigned long data) (GPrO_PORTE_DATA'R = data; // the sound frequency will be (interrupt frequency) /(size of the table) void SysTick_Handler (void) { Index = (Ihdextl) 20x0F; W856, )7/ 7,6 8p 43,2) 2/1/2,2/3, DAC Out (SineWavelIndex]); // output ne value each’ interrupt void main (void) { Init 07 J] as clock at 80 Mix Switch Tie): 7] port F is onboard auitches, LEDs, profiling Sound Tait (50000); // instialize SysTack tamer, 1.6kE= wailed) ( , Program 13.1. The periodic interrupt outputs one value to the DAC. Video 13.5¢. Program walkthrough Video 13.5e. Demonstration of the Solution using a Scope Reprinted with approval from Embedded Systems: Introduction to ARM Cortex-M Microcontrollers, 2014, ISBN 978- 1477508992, ttp://users.ece.utexas.edu/-valvano/armvoutline1, htm from Embedded Svstoms: Real-Time Interfacing to ARM Cortex"™LM Microcontrollers, 2014, ISBN: 978-1463590154, /Vusers.ece,utexas.edu/-valvano/arm/outline,htm Embedded Systems - Shape the World by Jonathan Valvano and Ramesh Yerraball is licensed under a Creative NonCommercial-NoDerivatives 4.0 International License Based on a work at hip //users ece utexas edu/~valvano/arm/oulline| htm,

Potrebbero piacerti anche