Pré-visualização parcial do texto
Baixe Phan 2 - Embedded C Programming And The Atmel AVR 2nd Edition - created PDF by Huy Nam e outras Notas de estudo em PDF para Engenharia Elétrica, somente na Docsity!
cmi microconirlier anda PG usinE NS” A ) an attached MAX233 media driver, HR Figure 2 «à standard AVR processor with ) Tá Dr sertalsiçeal used é the microcontroller fis o E O e for " serial communication to the PC. The hardware shown in this hgu E sofk. in Fi unication example. ware shown in Figure 2-40 to ma! : ke the serial commi ftware is a program (Figure 2-40; char uses a swites, the PC. The exact message will depend on the PC. The ÀS CII code for the charaç- is example demonstrates both manual The serial communication example so construct to print one of three messages on whether an “a”, a “b”, or another key is pressed on ter pressed is sent serially to the microcontroller. Th - and intecrupt handling of USART functions. ” Usi ADCIIPAT -£g Reser ADOSIPAS aDESPAS ADCAIPAs ADC3PA3 IN = ADC2IPAZ vcc ADCUPAI ADeurAO vce scwpe7 Avcc Misorpas ” Mosupes ssipBs OCO AINHPII [ek] AREF INTZAINOIPB2 = TUPBI oniuta xckTaipeo 0c2e07 GND IcpurD6 OCIAPOS XTALI OCIBPD4 INTIVPDI INTUPDZ TXDHPD1 XTALZ RAZIPDO o EE) vCc Ig! o ves TN TIOUT HE K TaN TOUT A riouT RIN FE reour Ran É E A, u | eb ass mir | = car am E et UR V. 1 io v. c2 ve cz MAX233L, 8,9 Sho GERE FREE loleleleloladelo ne Q1 s2 | 6 MHz a TOSCHPCT7 TOSCI/PC6 20 pfd ig pá g BB Juaf-s ro E TDOIPC4 AGNO TMSIPC3 TCKIPC2 GND SDAIPC1 scuPCo ' 31 1 1 Ebkhbkkh: Eb D MEGAI6 Figure 2-39 Serial Communication Example Hardware RE ligentr = sndentr) JUDR = queue [sndentr++]; ) !*this function loads the queue and +/ Pestarts the sending process”*/ void sendmsg (char “de í ) gentr = 0; /*preset indices*/ sndcntr = 1; /*set to one Cecause first Character already sente/. queue[gentr++] = 0x0a; f"put CRLF into the queue First, queue[gcntr++)] = UxDa; while (ts) queue(gentr++] = *s++; /*put characters intc queue*; UDR = queue(9!; /*send first character to start. process"; ; E void main(void) 1 é j e char ch; /* character variable for received character=/ UCSRA=0x00; pes UCSRB=0x58; /*enable receiver, transmitter and transmit interrupt*/ UBRRH=0x00; /*baud rate = 9600*/ UBRRL=0x26; ' tasm("sei”) /*global interrupt enable */ while (1) ( ) if (UCSRA & 0x39) /*check for character received*/ t . ch = UDR; /*get character sent “from PC+/ switch (ch) so Serial Communication Example software (Continues) : x A separate index (in this'cas byte is retrieved, this index is in EE gram knows that the queue has .emp ra Actually, the CodeVisionAVR C langusse Rat : ceiver queue, or both using the "CodeWisanir eng PE feito remo ie vided to demonstrate how the Queue «works for educational reasons. con g aê E Getting back to the example program, the sendmig() function called from the switch státe- ment puts the message into the queue and Starts the transmit functión: Thê switch states ment Passes a pointer (an address) to the appropriate message when it calls the function. The function first puts the CRand LF characters into the queue ând then puts the message to be transmitted into the queue using the pointer. Finally, the function writes the first byte im the queue into the UDR to start the transmission process. After this Character has been. transmitted, the TXC in terrupt occurs and the ISR loads the next character from the queue into the UDR, and so the cycle continues until the queue is empty, as indicated by the two indices being equal. A more elaborate form of the queue function with additional explana- tion may be found in Chapter 3, “Standard I/D and Preprocessor Functions.” 2.9 ANALOG INTERFACES In spite ofthe prevalence of digital devices, the world is still actually analog by nature. A mi- crocontroller is able :» handle analog data by firsc converting the daza to digital “orm. An | AVR microconrroller includes both an anulog-to-digital conversion peripheral and an ana- log comparator peripheral. Each of these analog interfaces will be covered in this secti n, along with a brief background on analog-to-digital conversion. Microcontrollers use analog-to-digital converters to convert analog quantities such as tem- perature and voltage (for example, a low-battery monitor), tc convert audio to digital for- mats, and to perform a host of additional functions. « 2.9.1 ANALOG-TO-DIGITAL BACKGROUND Anialog-to-digital conversion (as well as digital-to-analog conversion) is largely à ms E proportion. That is, the digital number provided by the analog-to-digital converter ( E relates to the proportion that the input voltage is of the full voltage range a Fe Eesiesiá For instance, applying 2 V to the input ofan ADC with a full-scale range E jo. E a in a digital output that is 40 percent of the full range of the digital output ( =0.4). ADCSs are available that have a variety of input voltage ranges and ni rh The output digital ranges are usually expressed in terms of bits, su as8 e pro st e number of bits at the output determines the range of dra do at ha e im output of the converter. An 8-bit converter will provide di a p and a 10-bit converter will provide outputs from Oupto2-1or k di I i le in which 2 V was applied to a converter with a full-scale range ho “Se pesto read 40 percent of 255, or 102. The proportion/conversio o >2 Yan 8-bi ; pés i e the formula to solve for the + RR o j ing to display the actual voltage on of resolution. The resolution of mia. cant issue buried in this formula is the issue RREO Foto: or the finest increment that can be measured, Ea “ Visiscale, Vresolution = gtes : e resolution would be cal. ; E V, th For an 8-bit converter that has a full-scale input range pi da culated as follows: Vocaduio = 5 V/(28 = 1) = 5V/255 = 20 mV (approx.) 1 IS si É ade is e Therefore, the finest voltage increment tha: can be measured in es iene às 20 mV. dt would be inappropriate to attempt to make measurements that are, for example, accurate to “maithin 5 mV with this converter. 2.9.2 ANALO 3-TO-DIGITAL CONVERTER PERIPHERAL The ADC peripheral in the AVR microcontrollers is capable of 10-bit resolution and can operate at spceds as high as 15 kSPS (kilo-samples per second). It can read the voltage on one of eight different input pins of the microcontroller, meaning that it is capable of read- ing from eight different analog sources. * É Two registers control the analog-to-digital converter: The ADC contro! and status register (ADCSRA), controls the functioning of the ADC, and the ADC multiplexer select register “(ADMUX), controls which of the eight possible inputs are being measured. Figure 2-41 shows the bit definitions for the ADC control and status register. - “The ADC requires a-clock frequency in the range of 50 kHz to 200 kHz to operate at max- imum resolution. Higher clock frequencies are allowed but at decreased resolution. The ADC clock is derived from the system clock by means of a prescaler in a manner similar to the timers. The least significant three bits of ADCSRA control the prescaler division ratio. j These bits must be set so that the system clock, when divided by the selected division ratio, provides an ADC clock between 50 kHz and 200 kHz. The selection bits and division 13 tios are shown in Figure 2-42. Although it could be done by trial and error, the most direct method for choosing the ADC |. Set the thre jin ER 2. Set ADIE high to enable interrupt RR 3. Set ADEN high to enable ADC. o ion. 4. Set ADSC to immediately start a conversio! o ; E £ code would initialize the ADC to read the For a division factor of 8, the following lines O analog voltage on the ADC2 pin: regue pDC2+7 pias! sanii moGe, ES: res started*/ ; and starts the first conversion all at cycle after the ADC is enabled is an extra- The lorg cycle, then, occurs during the pt wil] occur immediately after ter is loaded with the ADMUX = 2; RDCSR = 0xcD; /*aDC on, The initialization above sets up the ADC, en once. Ehis is useful because the first conversion lorg cycle to allow for the setup time of the ADC. T! balance o? the program initialization, and the ADE interrupt wit O! the global interrupt enabled bit is set. Notice that the ADMURX regis number of the ADC channel to be read. the hardware and software, respectively, for a mit detector ltage to ADC channel 3. Briefy, the system lights the ghts the yellow LED if the input voltage is below ltage is within the range of2V to3V. a typical application for the ADC. The ables it, Figures 2-43 and 2-44 show system based on the analog input vo red LED if the input voltage exceeds 3 Vl 2 V, or lights the green LED if the input vo The limit detector program in Figure 2-44 shows ! ADC is initialized and started in main() by setting ADCSRA to 0xCE. ADC chanhel 3 is selected by setting ADMUX to 3. This starts the process so the ADC interrupt will occur at the end of the first conversion. Checking the ADC output to sec which LED to lightand lighting the appropriate LED are all handled in the ADC interrupt ISR. d by reading the data from ADCW. Notice that the 10-bit output from the ADC is rea nAVR that allows retrieving the data ADCYW is a pseudo-register provided by CodeVisio from :he two ADC result registers, ADCL and ADCH, at once. Other compilers would more likely require the programmer to read both ADC registers (in the correct order, even) and combine them in the 10-bit result as a part of the program. in the Also notice that the programmer has used the analog-to-digital conversion formula ISR. The compiler will do the math and create a constant that will actually be used in the ta Ê É program. You will find that this technique can be used to your advantage in several other places, such as loading the UBRR for the USART. The ADC peripheral in the AVR microcontrollers varies somewhat according to the spe ERlbE E] ATALZ RXDiPCO | as =] AGND Tuspc3 [2 43 Texipca [ds SND soapci | 23 scupco | O —>—— DS) MEGAIS Figure 2-43 ADC Example Hardware finclide /*Defina output Port and light types*/. fdefine LEDs PORTO gdefine red 0b11011111 É fdeíine green 0b01111111 fdefine yellow 0b10111111 /*aDC ISR, -reads ADC, sets lights*/ -Ânterrupt [ADC INT] void adc isr(void) é unsigned int adc data; /*variable for ADC resultst/ adc data = ADCW; !*read all 10 bits into variable*/ if (adc data >(3*1023)/5) LEDs = red; /*too high (>3W)*/ else if (adc data < (2+1023)/5) ( Figure 2-44 ADC Example Software (Continues) Analog Comparator bandgap gelo asilos = Analog Comparator Outpur bit. E ACE . Analog Comparator Interrupt Rag. i Alog Comparator Interrupr mask bir. E ACIC , Analog Comparator Input Capture bir. Ser to enable input capture on comparator change-of-state. ACIS1 Al 5 = og Converter Comparator Mode Select bits. ACISO (See definitions below.) Analog Compare Interrupt Mode Select Bit Definitions: ACIS! ACISO Interrupt Mode ) e Comparator interrupt on ACO toguie. Reserved — do noruse. | T 0 | Comparator interrupt on ACO falling edge. 1 (AIN1 becomes greater than AINO.) Comparator interrupt on ACO rising edge. n (AINO becomes greater than AIN.) 1 | ! | [ fi L Figure 2-45 AcSA Bit Definitions a E E ai a BEE A E “The system shown in Figure 2-46 is continuously monitoring the battery without expend ing any processor time whatsoever, because it is all handled by the analog comparator. When the battery voltage becomes too low, the LED is lighted. ; inp dividers: one is powered by the The two analog converter inputs are connected to voltage regulated +5 Vas a reference, and the other is powered direcily by the battery. The voltage divider powered by the +5 V is designed to provide E sa at its center E vide nisdesi he battery discharges to approxim The other voltage divider is designed so that when t E E 5 V, fia a cm of the voltage divider will also measure approximately E pe hero og esrstor is set to detect when the voltage ftom the battery's voltage divider drop: elow the 2.2 V provided by the reference divider. Is a re 2-47 h h E] omparator is 1 y 1 le. In this exampl 2 gu: shows using the anelog e o) tor is relativel Sao I : e CSR is loaded with DA to nable the analog comparator, to enable its interrupt, and to K » e : Sho MEGA 15 a É Figure 2-46 Analog Comparator Example Hordware Sinclude ; define LED PORTC.O rá unsigned int blirk count = 0; f*counter for LED blinker bes /* Analog Comparator interrupt service routine*/ interrupt [ANA COMP] void ana-.comp isr (void) ( , Raio ! 0; /*disable the comparator*/ ACSR = FPCCRO = 0x5; /*start'the timer*/ ) /* Timer O overflow interrupt service routine*/ interrupt (TIMO OVF] void timer0 ovf isr(void) Í NRO css Go ser cor avprox. ums overflow rate”! ++blirk count, /*increment blink counter*/ switch. (blink count) í Figure 2-47 Analog Comparator Example Software (Continues) da Ê :nz mode for this use. In this iently be run im DM sb That when the data is stored papo get be recorded. In free-running mode, the AD. - one-second interval, the most recent value é used to update the current temper. i canbi interrupt occurs at the end of each conversion pá ature value. : - lock frequency by choosin ; ri ropriate cioc E the initialization is to select an app E cn 50 KER «Si penis DC lock. The ADC Ce Ê Eta 64 will give a k this E you have a system clock of 8 MHz, and so à p'= clock of 125 kHz. The ADC initializaticn process invo. free-running mode, and starting the first conver end of the conversion; keeping the vrocess running: Ives choosing the channel to be ma enadling the sersion so that an interrupr will occur ar the /? ADC initialization*/ y É . “Dxux=0%3; /*select channel 3 and AREF pin as the reference VOTEAçaE .DMUX=0X3; iann VR inputs ADCSRA=CxE9; /*enable ADC, free run, started, The ADC ISR has the job of reading the current conversion value and converting it to temperatu re: clock prescaler of 64+/ /* ADC interrupt service >outine*/ interrupt [ADC INT] void ade isr(void) E unsigned int ADC DATA; ADC DATA = ADCW; /*get data from ADC result register*/. current temp = ((long)150 * (longJADC DATA)/ (long) 1023 + ) (Long) 100; ) SENDING COLLECTED DATA TO THE PC t The collected data is already converted to units of rpm and ºF, so this function needs only to send the data to a PC, This involves initializi E E ein fimetioi to format and send the data. BitA gana he USART and using huiheia ia The USART is initialized for 9600 bau e UART initialization td 0-0: d, 8 bits, and no parity as follows: sent to the PC is going. y > -shows that data can be inpui “This means that commas separate the data rates each line. That is, data sent as SO qa nino tea “QaRA, datiS: datado will appear in the spreadsheet exactly as shown above occupying a space two cells high by three cells wide. Ir this case, vou decide that the first column in the spreadsheet will con- tain the engine rp, the second will contain the shaft rpm, and the third will contain the engine temperature. Each line of the spreadsheet will contain one set of data, so each line will contain data taken one second after the data in the previous line. The following code is the while(1) from the main() function of the code: while (1) f if (IPINA.O) t*note: switch must be raleased before data ist/ unsig:.cd char x; * “temporary counter variapies, ab /*grinc column titles into the. spreadshest in the firs- row*/ printé ("$s50, 4s', BsiniEngine Rem) eisnare RoRE "Temperature"); For dz = 0x so ia) f /* print one set of data into one lixe on the spreadshset*/ printf ("td , sd , td Yn”,esromíx], s rombei, Cemplsii | ) E Bi “This routine sends the 120 sets of data (and a line of column titles) using the built-in printfl) function. A newline character (Nn”) is included with each set of data to cause the next set to appear in the following line of the spreadsheet. 2.10 SERIAL COMMUNICATION USING THE SPi The serial peripheral interface, SPI (pronounced “spy”, is another form of serial viga cation available in the AVR microcontrollers. It is a synchronous serial communication is meaning that the transmitter and receiver involved in SPI cosperuniçaçias pas De : same clock tu synchronize the detection of the bits at the receiver. Normally, the us | Description. RE SPIE = —-=—— === CTT SPIIaRAOpE MNE DS —— = [= SPE SPI Enable bit. Set to enable SPI operations. DORD A Data Order bir. Cleared causes the MSB of - A the data word to be transmitted first. MSTR Master/Slave Select bit. Set for the device to be the master. Essa à Clock Polarity bit. CPHA | Clock Phase bit. SPR1 SER SPI Clock Rate bits (see table below). SP! Clock Rate Bit Definitions: SPRI SPRO SCLK Frequency Salect 0 | 0 : System Clock / 4 0 | 1 System Clock / 16 1 RE System Cloe /64 1 1 System Clock / 128 Figure 2-49 SPCR Bit Definitions are connected to either a parallel port on the master or to a decoder that determines which device will be the slave. ; a The SPI control register, SPCR, controls the operation of the SPI interface. SPCR bit defi- nitions are shown in Figure 2-49. In a similar manner to the control registers studied pre- viously, there are bits to enable the SPI interface and its associated interrupt, e bits di control the communication speed. There is also a bit to set when a device is acting as the master, MSTR. In addition, there are bits to control the d clock polarity and the clock phase. These cation peripheral to other SPI devices. Figures 2-50 through 2-53 show the hardw tion system. The system reads the switch d t ata order, MSB first or LSB first, and tó select the bits are used when matching the SPI communi- are and software for a simple SPT denonstra-, ata ftom the dip switch on one system and 20 pfá 20 pfd á 3t ! E pre 2 Mem Tc AGNS END | So Figure 2-50 ATMega! 6 SPI Demonstration System Hardware dispiays the switch data on the other system, and vice versa. All communication E: Fai via the SPI bus. The Atmegal28 is the SPI Master, and the ATMegal6 i is the slave The Atmega128 reads the data to be sent from the dip switches on PORT F and ips it to the ATMegal6 slave, where it is displayed on PORT C. At the same time, the is from the ATMegaló (from the dip switch on PORT A) is returned to the AT Megal and displayed on its PORT A: The system continuously updates, making it appear to be instantaneous. PORT B (PORT B alternate functions include the SPI pins) ized as shown below: MEGAS | Pin Slave PORT B Master PORT 8 MOSI Input Output MISO Outpur Input SCK Input Output ES) Inpur Output on each processor is initial- j Se LV ERA ut new data veces a prróed Dn dava eae Maio monmanidánios cpotes dA " » v ço Í SPI output data = -SPDR; 'SPDR = SPI. input data;. a void-main(void) - x s & « ss = input. MISO output*/ j Fá E : DDRB = 0x40; /ºsclk, MOSI, DDRC = OxFF; /*ail outputt/ - E PORTA = 0xFF; /*pull ups o acarrepir: slave mode*/ SPCR=0xCL; /*enable SPI, an k terrupt flag* /* provided by CodevVisionaVR to clear the sPI inte q*/ e Ê E tasm , A CSO0mEDsT in 50, sper ú fendas fasm("sei")// Global enable incerrupts /*put code here to interpret spI results if sa geiaéio Figure 2-52 SPI Slave Software Example tinclude f&define SPI output data PORTA fdefine SPI input data PINF /* SPI interrupt service routine*/ interrupt ([SPI STC] void spi isr(void) ( . PORTB.O = 1; " /*ss high*/ SPI output data = -SPDR; /*read data from last* exchange*/ PORTB.O = 0; /*lower SS*/ * SPDR = SPI input data; ./*send new data out*/ J ; E Pigure 2-53 SPI Master Software Example (Continues) ROSTASORE SS: O Eca with DDRA=0xFF; /*a11 outpurty E E o PORTB = 0x01; !*start With SS HAgue, DDRB=0x07; I*ss;s u E "Sck, and MusT as + PRO O ria Ds dai / * SPSR=0x00; WA Clesrhthe les interrupt fasm fendasm /i Global enable interrupis fasm("sei") 2; u 7) SPDR = 0x00; f*write once to Start (proce Figure 2-53 SP| Maste; Software Example input port to SPDR. The slave ISR then merely accepts the new data and provides its own switch data for the next communication cycle. And the cycle repeats forever. An important concept to note is that the data going from the slave to the master is actually one cycle behind the data going to the slave. This occurs because the 'slave loads new data after it receives data from the master. i he sor pe The connections he SPI is ofi d to form a high-speed network within a ce. T t E EE “ie (ali the MISO pins tied together and all of the MOSI pins tied togerherhas ) in a large serial loop, where all of the data bits travel E dia Ep AS E d pes ; 1 i isters. lhe el method req od, RR sis od ago the data flow, while in the serial. RE ciais sera Fang of the devices. In either method, multiple É : e data flows t ic» ii a prt on a SPI-based network to share data.