Module 3 presentation

Module 3 presentation - 2011 Edition by D. G. Meyer...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 2011 Edition by D. G. Meyer Microcontroller-Based Digital System Design Module 3 Microcontroller Peripherals 1 Module 3 Desired Outcome: "An ability to effectively utilize the wide variety of peripherals integrated into a contemporary microcontroller" Part A: Analog-to-Digital Converter (ATD) Analog-to Part B: Serial Communications Interface (SCI) Part C: Serial Peripheral Interface (SPI) Part D: Timer Module (TIM) Part E: Pulse Width Modulation (PWM) 2 Outcome 3 Instructional Objectives To learn about peripheral devices that are typically integrated into contemporary microcontrollers, and how to use them To learn how the 9S12C32 integrated peripherals can be incorporated into a significant system design 3 Overview of 9S12C32 On-Chip Peripherals On- Several things to note..... 4 Overview of 9S12C32 On-Chip Peripherals On- Several things to note..... Analog-to-digital (ATD) converter module inputs are on Port PAD 5 Overview of 9S12C32 On-Chip Peripherals On- Several things to note..... Timer (TIM) module I/O on Port T 6 Overview of 9S12C32 On-Chip Peripherals On- Several things to note..... Pulse width modulator (PWM) here, I/O shared with TIM module on Port T MODRR register setting determines whether these Port T pins are mapped to the TIM or PWM 7 Overview of 9S12C32 On-Chip Peripherals On- Several things to note..... Asynchronous serial communications interface (SCI) on Port S 8 Overview of 9S12C32 On-Chip Peripherals On- Several things to note..... Controller area network (MSCAN) on Port M 9 Overview of 9S12C32 On-Chip Peripherals On- Several things to note..... Synchronous peripheral interface (SPI) on Port M 10 2011 Edition by D. G. Meyer Microcontroller-Based Digital System Design Module 3-A Integrated Peripherals: Analog-to-Digital Converter 11 Outline Analog conversion basics Sampling Quantization Converter types 9S12C ATD features and modes 9S12C ATD registers 9S12C ATD initialization ATD program-driven device driver programReference: Analog-to-Digital (ATD) Converter Block User Guide 12 Analog Conversion Basics Introduction A typical embedded system may have many input signals, some of which may be "analog" (continuous time) in nature (continuous time) Process of converting continuous time signals into discrete representations is called analog-to-digital conversion analog-to A-to-D (ATD) conversion process involves tothree distinct steps sampling quantizing encoding 13 Analog Conversion Basics Data acquisition system design issues Sampling rate required for sufficient bandwidth Number of bits required for sufficient dynamic range Type of converter most appropriate for a given application 14 Analog Conversion Basics Sampling Ideally would like to determine the digital equivalent of an analog signal at a precise instant of time ("snapshot") ("snapshot") Because ATD process takes a finite amount of time, a rapidly changing analog input signal can present an ATD converter with an ambiguous input ("blurred image") ("blurred image") One solution is to incorporate an "analog "analog memory" memory" that can hold a snapshot of the analog input for the converter Called a "sample-and-hold" (S/H) circuit "sample-and-hold" 15 Analog Conversion Basics Sampling rate Major design issue in data acquisition systems is the sampling rate Ts Need to know spectral characteristics of incoming signal (can be determined using a spectrum analyzer) analyzer) Sampling frequency Fs must be at least twice that of the highest frequency component present in input signal (called rate) the Nyquist rate) Use low-pass filter (LPF) to ensure no lowfrequency components in excess of Fs/2 are applied to ATD input 16 Analog Conversion Basics Sampling rate, continued Input LPF referred to as an "anti-aliasing" "anti-aliasing" filter Frequency components in excess of Fs/2 are "folded back" into the baseband at an "folded back" "alias" frequency (non-linear distortion) alias" (nonAliasing Example: If Fs = 20 KHz maximum input frequency component is 10 KHz If input frequency component is 11 KHz, will be encoded as a 9 KHz component 17 Illustration of Aliasing Frequencies 18 Analog Conversion Basics Quantization Another important design consideration is the number of bits required to obtain adequate resolution and/or sufficient dynamic range Quantization is the assignment of a fixed amplitude level (corresponding to an available binary code) to the incoming analog signal Note that the converted code is relative to the reference voltage(s) applied to the converter (VRH = voltage reference high, (V VRL = voltage reference low) 19 Quantizing Intervals and Quantization Error X Vrh X Vrh 20 Quantizing Intervals and Quantization Error X Vrh X Vrh 21 Quantizing Intervals and Quantization Error X Vrh X Vrh 22 Quantizing Intervals and Quantization Error X Vrh X Vrh 23 Quantizing Intervals and Quantization Error X Vrh X Vrh 24 Quantizing Intervals and Quantization Error X Vrh X Vrh 25 Quantizing Intervals and Quantization Error X Vrh X Vrh 26 Quantizing Intervals and Quantization Error X Vrh X Vrh 27 Quantizing Intervals and Quantization Error X Vrh X Vrh 28 Quantizing Intervals and Quantization Error X Vrh X Vrh 29 Quantizing Intervals and Quantization Error X Vrh X Vrh 30 Quantizing Intervals and Quantization Error X Vrh X Vrh 31 Quantizing Intervals and Quantization Error X Vrh X Vrh 32 Quantizing Intervals and Quantization Error X Vrh X Vrh 33 Quantizing Intervals and Quantization Error 0.1002 = X Vrh X Vrh 34 Quantizing Intervals and Quantization Error 0.1002 = Resolution = Vrh / 2n X Vrh X Vrh 35 Quantizing Intervals and Quantization Error Maximum input voltage that can be converted = Vrh X (2n-1)/(2n) 0.1002 = Resolution = Vrh / 2n X Vrh X Vrh 36 Quantizing Intervals and Quantization Error Maximum input voltage that can be converted = Vrh X (2n-1)/(2n) 0.1002 = Resolution = Vrh / 2n X Vrh Quantizing noise X Vrh 37 Quantizing Intervals and Quantization Error Maximum input voltage that can be converted = Vrh X (2n-1)/(2n) 0.1002 = Resolution = Vrh / 2n X Vrh Points of zero quantizing error Quantizing noise X Vrh 38 Analog Conversion Basics Quantization, continued The quantization error imposes "noise" on the converted value ("quantization noise") ("quantization noise") The dynamic range of a converter is its signal to quantizing noise ratio (SQNR), measured in dB: SQNR = 20 log10 (2n / 1) Example: For n = 8, SQNR = 20 log10 (256 / 1) 48 dB Solving for other values of n shows that the dynamic range is approximately 6 dB/bit 39 Relationship of n to Resolution and Dynamic Range Matlab Demo 40 Analog Conversion Basics Converter type Wide variety of types, but two basic categories Those requiring a DTA (digital-to-analog (digital-toconverter as an integral component) Those not requiring a DTA Successive approximation is one of the most common types of ATD converters integrated into microcontrollers High resolution Conversion time is a linear function of n Based on "binary guess a number" game 41 Successive Approximation Conversion Process (n = 4) Vrh X 0.875 0.750 0.625 0.500 0.375 0.250 0.125 0 1 2 3 4 42 Conversion clock cycles Successive Approximation Conversion Process (n = 4) Vrh X 0.875 0.750 0.625 0.500 0.375 0.250 0.125 0 1 2 3 4 43 Input voltage Conversion clock cycles Successive Approximation Conversion Process (n = 4) Vrh X 0.875 0.750 0.625 0.500 0.375 0.250 0.125 0 1 2 3 4 44 Input voltage First guess = 1000 "too low" Conversion clock cycles Successive Approximation Conversion Process (n = 4) Vrh X 0.875 0.750 0.625 0.500 0.375 0.250 0.125 0 1 2 3 4 45 Second guess = 1100 "too high" Input voltage First guess = 1000 "too low" Conversion clock cycles Successive Approximation Conversion Process (n = 4) Vrh X 0.875 0.750 0.625 0.500 0.375 0.250 0.125 0 1 2 3 4 46 Second guess = 1100 "too high" Input voltage Third guess = 1010 "too low" First guess = 1000 "too low" Conversion clock cycles Successive Approximation Conversion Process (n = 4) Vrh X 0.875 0.750 0.625 0.500 0.375 0.250 0.125 0 1 2 3 4 47 Second guess = 1100 "too high" Fourth guess = 1011 "got it" Input voltage Third guess = 1010 "too low" First guess = 1000 "too low" Conversion clock cycles Successive Approximation Converter Block Diagram 48 Clicker Quiz 49 1. 10-bit PCM audio would have a theoretical SQNR of approximately: A. B. C. D. E. 10 dB 30 dB 60 dB 100 dB none of the above 50 2. If the desired bandwidth for speech is 5 KHz, the sampling frequency used should be at least: A. B. C. D. E. 5 KHz 10 KHz 20 KHz 50 KHz none of the above 51 3. If a 7 KHz sine wave is sampled at 10 KHz, the reconstructed waveform will be a sine wave of frequency: A. B. C. D. E. 2 KHz 3 KHz 7 KHz 17 KHz none of the above 52 9S12C ATD Features and Modes Features 8 input channels 8/10-bit resolution, signed or unsigned 8/10 8 separate result registers programmable sample time fast conversion time (8 bits of accuracy in 9 microseconds) microseconds) may be program- or interrupt-driven programinterrupt port PAD pins may also be used as generalgeneralpurpose digital inputs (if ATD is not used) Conversion may be externally triggered 53 ATD Block Diagram Reference high/low voltages 16-bit result registers Analog input channels S/H "shutter speed" can be programmed Unused Port AD pins can be used as digital inputs 54 ATD Features and Operating Modes Operating modes a single conversion sequence consists of from 1 to 8 conversions there are 8 basic conversion modes non-scan modes: the sequence complete nonflag (SCF) is set after the prescribed sequence of conversions has been performed (and the ATD module halts) scan ("continuous conversion") modes: the sequence complete flag (SCF) is set after the prescribed sequence of conversions has been performed (and the ATD module continues to restart the sequence) 55 ATD Features and Operating Modes Operating modes in all modes, the conversion complete flag (CCF) for a given channel is set when the converted sample is loaded into the corresponding result register the conversion complete flag (CCF) for a given channel is automatically cleared when the corresponding result register is read a conversion sequence is initiated by writing to an ATD control register (specifically, ATDCTL5) ATDCTL5) 56 ATD Features and Operating Modes Reference voltages VRH reference high voltage VRL reference low voltage minimum (either): -0.3v maximum (either): +6.5v Conversion range and resolution If VRH = 5.0 v and VRL = 0.0 v, then an input voltage of 5.0 v will produce a converted output code of $FF, while an input voltage of 0.0 v will produce a converted output code of $00 (assuming unsigned mode) Here, the resolution (or "step size") of the converter is (VRH - VRL)/256 = 0.01953125 v 57 ATD Features and Operating Modes Conversion example: If VRH = 5.0 v and VRL = 0.0 v, then an input voltage of 2.90 v will produce what converted output code? Answer: 2.90 / 0.01953125 = 148 = $94 58 ATD Registers ATDCTL2 (control) ADPU (bit 7) ATD power up "0" ATD disabled "1" ATD enabled AFFC (bit 6) fast flag clear mode "0" normal CCF flag clearing mode (must read status register before reading result register to clear individual CCF) "1" fast CCF flag clearing mode (just reading the result register will clear CCF, i.e., do not need to read status register) register) indicates default mode after RESET 59 ATD Registers ATDCTL2 (control) ETRIGLE and ETRIGP (bits 4-3) 4Allows use of PAD7 to "trigger" an ATD conversion ETRIGE (bit 2) "0" - disable external trigger "1" - enable external trigger indicates default mode after RESET 60 ATD Registers ATDCTL2 (control) ASCIE (bit 1) sequence complete interrupt enable "0" ATD interrupt disabled "1" ATD interrupt enabled ASCIF (bit 0) interrupt flag "0" flag not set "1" flag is set indicates default mode after RESET indicates read only bit 61 ATD Registers ATDCTL3 (control) S8C, S4C, S2C, and SC1 (bits 6-3) 6conversion sequence length indicates default mode after RESET 62 ATD Registers ATDCTL3 (control) FIFO (bit 2) result register FIFO mode "0" non-FIFO mode (conversion results nonmap into result registers based on the conversion sequence) "1" FIFO mode (conversion results are placed in consecutive result registers between sequences) indicates default mode after RESET 63 ATD Registers ATDCTL4 (control) S10BM (bit 7) 10-bit mode control 10 "0" 10-bit resolution 10 "1" 8-bit resolution SMP (bits 6 & 5) sample time select "00" 2 ATD clock periods "01" 4 ATD clock periods "10" 8 ATD clock periods "11" 16 ATD clock periods indicates default mode after RESET 64 ATD Conversion Timing CCFn set sample and transfer time successive approximation conversion time = 6 + final sample time* = 2 + number of bits *2/4/8/16 cycles nominally 18 cycles for 8-bit resolution CH0 CH1 CH2 CH3 CH4 CH5 CH6 CH7 write to ATDCTL5 starts conversion SCF set if 4-ch mode SCF set if 8-ch mode Note: The SCF bit is cleared when a write to ATDCTL5 starts a new conversion (AFFC=0), or the first result register is read (AFFC=1) 65 ATD Registers ATDCTL4 (control) PRS (bits 4-0) clock pre-scalar 4pre "00000" divide by 2 "00001" divide by 4 . . . . . . maximum bus clock frequency "00101" divide by 12 (24/12 = 2 MHz) 24/12 MHz) "11111" divide by 64 maximum ATD clock frequency indicates default mode after RESET 66 ATD Registers ATDCTL5 (control) DJM (bit 7) result register data justification "0" left justified data "1" right justified data DSGN (bit 6) signed/unsigned result "0" unsigned data "1" two's complement data SCAN (bit 5) enable continuous scan "0" single conversion sequence "1" scan mode (continuous conversion) indicates default mode after RESET 67 Result Data Formats Left Justified Signed/Unsigned Output Codes 68 ATD Registers ATDCTL5 (control) MULT (bit 4) multi-channel mode multi "0" sample only one channel "1" sample across multiple (successive) channels CC-CB-CA (bits 2-0) input channel CC-CB2select (000 by default) indicates default mode after RESET 69 ATD Registers ATDSTAT (status, high byte) SCF (bit 7) sequence complete flag "0" conversion sequence not complete "1" conversion sequence is complete Cleared by either writing a "1" to this bit -or- starting a new conversion by writing orto ATDCTL5 (note that the SCF flag automatically clears if AFFC=1 and a result register is read) indicates default mode after RESET 70 ATD Registers ATDSTAT (status, high byte) ETORF (bit 5) external trigger overrun flag "0" no external trigger overrun occurred "1" edge detected while conversion in process overrun occurred Cleared by writing a "1" to the ETORF bit or by starting a new conversion indicates default mode after RESET 71 ATD Registers ATDSTAT (status, high byte) FIFOR (bit 4) FIFO overrun flag "0" no FIFO overrun occurred "1" result register has been written before its associated conversion complete flag (CCF) has been cleared Cleared by writing a "1" to the FIFOR bit or by starting a new conversion CC (bits 2-0) conversion counter for 2current sequence of conversions (read only) indicates default mode after RESET 72 ATD Registers ATDSTAT (status, low byte) CCF (bits 7-0) conversion complete 7flags for each ATD result register "0" conversion not complete "1" conversion is complete indicates default mode after RESET 73 ATD Registers ATDDIEN (digital input enable) IEN (bits 7-0) digital input enable on 7channel on Port AD pin "0" Port AD bit used as analog input "1" Port AD bit used as digital input indicates default mode after RESET 74 ATD Registers PORTAD (data input) register Returns digital value on Port AD pin if the corresponding ATDDIEN register bit is set to "1" ADRxH (result, 16-bit) registers 16 ADR0H ADR4H ADR1H ADR5H ADR6H ADR2H ADR7H ADR3H 75 Clicker Quiz 76 1. A conversion sequence can consist of up to __ conversions: A. B. C. D. E. 1 2 4 8 none of the above 77 2. A conversion sequence is initiated by writing the (starting) channel number to this register: A. B. C. D. E. ATDCTL2 ATDCTL3 ATDCTL4 ATDCTL5 none of the above 78 3. In non-FIFO mode, the first converted result will always be written to: A. ADR0H B. ADR1H C. the result register corresponding to the converted channel D. the next available result register E. none of the above 79 4. The results from a conversion sequence are valid when this flag is set: A. B. C. D. E. SCF CCF ETORF FIFOR none of the above 80 ATD Initialization Routine ; Initializes ATD for program-driven operation program; STEP (1) Enable ATD for normal flag clear ; mode with interrupts disabled atd_ini movb #____,atdctl2 #____,atdctl2 ; STEP (2) Set the conversion sequence length to one movb #____,atdctl3 #____,atdctl3 ; STEP (3) Select 8-bit resolution and nominal sample time 8- movb rts #____,atdctl4 #____,atdctl4 81 ATD Registers ATDCTL2 (control) ADPU (bit 7) ATD power up "0" ATD disabled "1" ATD enabled AFFC (bit 6) fast flag clear mode "0" normal CCF flag clearing mode (must read status register before reading result register to clear individual CCF) "1" fast CCF flag clearing mode (just reading the result register will clear CCF, i.e., do not need to read status register) register) indicates default mode after RESET 82 ATD Registers ATDCTL2 (control) ASCIE (bit 1) sequence complete interrupt enable "0" ATD interrupt disabled "1" ATD interrupt enabled ASCIF (bit 0) interrupt flag "0" flag not set "1" flag is set indicates default mode after RESET indicates read only bit 83 ATD Initialization Routine ; Initializes ATD for program-driven operation program; STEP (1) Enable ATD for normal flag clear ; mode with interrupts disabled atd_ini movb #$80,atdctl2 #$80,atdctl2 ; STEP (2) Set the conversion sequence length to one movb #____,atdctl3 #____,atdctl3 ; STEP (3) Select 8-bit resolution and nominal sample time 8- movb rts #____,atdctl4 #____,atdctl4 84 ATD Registers ATDCTL3 (control) S8C, S4C, S2C, and SC1 (bits 6-3) 6conversion sequence length indicates default mode after RESET 85 ATD Initialization Routine ; Initializes ATD for program-driven operation program; STEP (1) Enable ATD for normal flag clear ; mode with interrupts disabled atd_ini movb #$80,atdctl2 #$80,atdctl2 ; STEP (2) Set the conversion sequence length to one movb #$08,atdctl3 #$08,atdctl3 ; STEP (3) Select 8-bit resolution and nominal sample time 8- movb rts #____,atdctl4 #____,atdctl4 86 ATD Registers ATDCTL4 (control) $0064 S10BM (bit 7) 10-bit mode control 10 "0" 10-bit operation 10 "1" 8-bit operation SMP (bits 6 & 5) sample time select "00" 2 ATD clock periods "01" 4 ATD clock periods "10" 8 ATD clock periods "11" 16 ATD clock periods indicates default mode after RESET 87 ATD Registers ATDCTL4 (control) PRS (bits 4-0) clock pre-scalar 4pre "00000" divide by 2 "00001" divide by 4 . . . . . . maximum core clock frequency "00101" divide by 12 (24/12 = 2 MHz) 24/12 MHz) "11111" divide by 64 maximum ATD clock frequency indicates default mode after RESET 88 ATD Initialization Routine ; Initializes ATD for program-driven operation program; STEP (1) Enable ATD for normal flag clear ; mode with interrupts disabled atd_ini movb #$80,atdctl2 #$80,atdctl2 ; STEP (2) Set the conversion sequence length to one movb #$08,atdctl3 #$08,atdctl3 ; STEP (3) Select 8-bit resolution and nominal sample time 8- movb rts #$85,atdctl4 #$85,atdctl4 89 ProgramProgram-Driven ATD Device Driver At entry, (B) contains channel number; at exit, (A) contains converted sample 1. Write 3-bit channel number to 3lower 3 bits of ATDCTL5 register 2. Wait for conversion sequence to complete 3. Read sample from result register and return the result in (A) 90 ProgramProgram-Driven ATD Device Driver ; Channel number passed in B register ; Converted sample returned in A register ; STEP (1) Start conversion on desired channel inatd andb #$07 ;mask unwanted bits stab atdctl5 ;start conversion on ;selected channel in ;"default" mode ; STEP (2) Wait for conversion sequence to finish await brclr ______,_______,_______ ; STEP (3) Read result register and exit ldaa ______ ;(A)=(selected result) rts 91 ATD Registers ATDCTL5 (control) DJM (bit 7) result register data justification "0" left justified data "1" right justified data DSGN (bit 6) signed/unsigned result "0" unsigned data "1" two's complement data SCAN (bit 5) enable continuous scan "0" single conversion sequence "1" scan mode (continuous conversion) indicates default mode after RESET 92 ATD Registers ATDCTL5 (control) MULT (bit 4) multi-channel mode multi "0" sample only one channel "1" sample across multiple (successive) channels CC-CB-CA (bits 2-0) input channel CC-CB2select (000 by default) indicates default mode after RESET 93 ProgramProgram-Driven ATD Device Driver ; Channel number passed in B register ; Converted sample returned in A register ; STEP (1) Start conversion on desired channel inatd andb #$07 ;mask unwanted bits stab atdctl5 ;start conversion on ;selected channel in ;"default" mode ; STEP (2) Wait for conversion sequence to finish await brclr atdstat,$80,await ; STEP (3) Read result register and exit ldaa ______ ;(A)=(selected result) rts 94 ATD Registers ATDSTAT (status, high byte) SCF (bit 7) sequence complete flag "0" conversion sequence not complete "1" conversion sequence is complete Cleared by either writing a "1" to this bit -or- starting a new conversion by writing orto ATDCTL5 (note that the SCF flag automatically clears if AFFC=1 and a result register is read) indicates default mode after RESET 95 ProgramProgram-Driven ATD Device Driver ; Channel number passed in B register ; Converted sample returned in A register ; STEP (1) Start conversion on desired channel inatd andb #$07 ;mask unwanted bits stab atdctl5 ;start conversion on ;selected channel in ;"default" mode ; STEP (2) Wait for conversion sequence to finish await brclr atdstat,$80,await ; STEP (3) Read result register and exit ldaa adr0h ;(A)=(selected result) rts 96 ATD Registers ATDCTL3 (control) FIFO (bit 2) result register FIFO mode "0" non-FIFO mode (conversion results nonmap into result registers based on the conversion sequence) sequence) "1" FIFO mode (conversion results are placed in consecutive result registers between sequences) indicates default mode after RESET 97 ATD Registers PORTAD (data input) register Returns digital value on Port AD pin if the corresponding ATDDIEN register bit is set to "1" ADRxH (result, 16-bit) registers 16 ADR0H ADR4H ADR1H ADR5H ADR6H ADR2H ADR7H ADR3H 98 2011 Edition by D. G. Meyer Microcontroller-Based Digital System Design Module 3-B Serial Communications Interface (SCI) 99 Outline Background and motivation Asynchronous serial transmission SCI features SCI registers ProgramProgram-driven SCI operation InterruptInterrupt-driven SCI operation Reference: Serial Communications Interface (SCI) Block User Guide 100 Background and Motivation Motivation transmitting "parallel" data over a long distance using multi-conductor multicable is expensive each signal requires a "twisted pair" each signal requires a line driver and receiver Solution: Transmit data serially (potentially using a single twisted pair) 101 Background and Motivation Illustration of serial bit stream ("NRZ") LSB 0 Data Clk 1 1 0 0 1 0 0 MSB Td = period of one data bit time Data Transmitted = 0010 0110 = $26 102 Background and Motivation Basic components required for "half duplex" implementation Twisted Pair PISO Shift Register SIPO Shift Register 8-bit Data In 8-bit Data Out Clk Question: What components would be required for a "full duplex" implementation? 103 Background and Motivation Additional components required for "full duplex" implementation Twisted Pair 8-bit Data Out SIPO Shift Register PISO Shift Register 8-bit Data In Clk Answer: A duplicate, "mirror image" version of the circuit on the previous slide 104 Background and Motivation Note: Note: Would like to avoid sending clock in order to eliminate a twisted pair 8-bit Data In T Clk PISO Shift Register SIPO Shift Register 8-bit Data Out R Clk Question: What difficulties are associated with generating the "transmit" and "receive" clocks locally? X 105 Background and Motivation Note: Note: Would like to avoid sending clock in order to eliminate a twisted pair 8-bit Data In T Clk PISO Shift Register SIPO Shift Register 8-bit Data Out R Clk Question: What difficulties are associated with generating the "transmit" and "receive" clocks locally? Local clock synchronization X 106 Asynchronous Serial Transmission Solution: Solution: Sample serial data stream at a higher rate than the data rate (1/Td) 8-bit Data In T Clk PISO Shift Register SIPO Shift Register 8-bit Data Out R Clk Typically a local clock period (Tc) that is 1/16 of the data period (Td) is used i.e., the sampling rate (1/Tc) is 16 times the data rate (1/Td) 107 Asynchronous Serial Transmission Illustration of asynchronous serial data stream sampling Td Tc = period of local clock = 1/16 Td Note: Receiving end needs to know when a given code transmitted (ASCII character) starts and stops 108 Asynchronous Serial Transmission Solution: Solution: Append START bit (always "0") "0 to the beginning of each character sent Approximate "middle" of START bit Tc = period of local clock = 1/16 Td 109 Asynchronous Serial Transmission Solution: Solution: Sample successive data bits at intervals of 16 Tc referenced to START bit First data bit sampled 16 Tc after START bit Tc = period of local clock = 1/16 Td 110 Asynchronous Serial Transmission Solution: Solution: Sample successive data bits at intervals of 16 Tc referenced to START bit Second data bit sampled 32 Tc after START bit Tc = period of local clock = 1/16 Td 111 Asynchronous Serial Transmission Solution: Solution: Append STOP bit (always "1") "1 to the end of each character sent STOP bit at end of frame Tc = period of local clock = 1/16 Td 112 Character Format and Timing Reference 113 Asynchronous Serial Transmission Definition: Definition: BAUD rate is the number of bits per second transmitted over the serial link Example: Example: If 10 bit character frames are used, then if 960 characters/second are transmitted, the BAUD rate is 9600 Question: Question: What is the local clock frequency (assuming Td = 16 x Tc) required to support a 9600 BAUD data transmission rate? Answer: 9600 x 16 = 153,600 Hz 114 Asynchronous Serial Transmission Question: What is the tolerance required between the transmitting clock and the receiving clock? + 1/2 bit at end of frame 115 Asynchronous Serial Transmission Question: How can the integrity of the data received be tested? Solution: Add a parity bit to the character frame 116 Parity Generation/Detection 117 Asynchronous Serial Transmission Parity possibilities even parity here the parity bit is set so that there are an even number of "ones" transmitted in the data bits plus parity bit odd parity here the parity is set so that there are an odd number of "ones" transmitted in the data bits plus parity bit marking parity the parity bit is always the same value 118 Even Parity XOR 1 0 1 1 0 0 1 0 1 0 1 0 1 1 0 0 1 0 0 1 0 1 0 1 1 0 0 1 0 1 0 1 1 0 0 1 0 119 Odd Parity XNOR 1 0 1 1 0 0 1 0 1 1 1 0 1 1 0 0 1 0 0 1 1 1 0 1 1 0 0 1 0 1 0 1 1 0 0 1 0 120 Asynchronous Serial Transmission Question: Question: What kinds of errors can occur in asynchronous serial transmission? don't get STOP bit at end of frame framing error receiver doesn't read data from shift register before next character starts shifting in receiver overrun noise on the transmission line corrupts one or more bits in the data stream parity error 121 Asynchronous Serial Transmission Question: Question: What are the most likely causes of serial data transmission errors, and how can these errors be corrected? corrected? framing error cause: local clocks too far out of tolerance correction: bring clocks within tolerance overrun error cause: data not read "fast enough" correction: lower baud rate or fix software parity error cause: problem with cable/connector correction: repair/replace cable 122 Clicker Quiz 123 1. The baud rate of a serial transmission link refers to: A. the number of bits per second transferred B. the number of bytes per second transferred C. the local clock frequency D. the data error rate E. none of the above 124 2. Local clock error does not accumulate on an asynchronous communication link because: A. the sampling clock is 16 times faster than the data rate B. the receiver re-synchronizes every time a start bit is detected C. the transmitter periodically sends "sync" pulses D. the receiver re-synchronizes every time a stop bit is detected E. none of the above 125 3. The length of time required to transmit a 10-bit character frame at 19.2 Kbaud is approximately: A. 1.042 milliseconds B. 2.084 milliseconds C. 5.208 milliseconds D. 0.521 milliseconds E. none of the above 126 4. A possible cause of a framing error on a serial transmission link is: A. B. C. D. E. a bad cable or connector mismatch in baud rates error in the transmit side software error in the receive side software none of the above 127 SCI Features The 9S12C32 Serial Communications Interface (SCI) is a specific instance of a "UART" (universal asynchronous receiver/transmitter) Has software-selectable baud rates (derived softwarefrom system clock) Uses advanced data sampling technique Allows special single-wire and loop modes singleUses standard NRZ format Provides full duplex operation Has programmable word length Allows parity generation and checking May be program- or interrupt-driven programinterrupt128 SCI Features Illustration of double buffering Transmitter Receiver 129 SCI Features Illustration of data bit sampling Three successive samples taken in "middle" of each data bit; data bit is declared "valid" if two out of three samples agree (but noise flag "NF" is set to indicate that the "vote" was not "unanimous") 130 SCI Features WiredWired-OR Mode: Used in single-wire systems singlewith several SCI devices connected together (output pin is open-drain, requiring an openexternal pull-up resistor) pullSingleSingle-Wire Mode: Transmit/receive are from a single pin (of Port S); TxD pin is open-drain openand can therefore be used for sending or receiving data Loop Mode: Used for testing serial I/O software when the external device may not be available 131 SCI Registers SCIDRL (SCI data) register Read: receive data register (RDR) Write: transmit data register (TDR) SCIDRH (SCI data high) register R8 (bit 7) 9th serial bit received T8 (bit 6) 9th serial bit transmitted Note: Our device drivers will use SCIDRL as the receive/transmit data register (RDR/TDR) 132 SCI Registers SCICR1 (SCI Control) register LOOPS (bit 7) loop mode enable "0" normal operation "1" loop mode enabled WOMS (bit 6) wired OR mode "0" normal operation "1" output pins are open drain indicates default mode after RESET 133 SCI Registers SCICR1 (SCI Control) register RSRC (bit 5) receiver source (for loop mode) "0" receiver input connected internally to transmitter output "1" receiver input connected to TxD pin M (bit 4) mode (character format) "0" one start, 8 data, one stop "1" one start, 9 data, one stop indicates default mode after RESET 134 SCI Registers SCICR1 (SCI Control) register ILT (bit 3) idle line type "0" short idle line mode enabled "1" long idle line mode enabled WAKE (bit 2) wakeup mode "0" wake up by idle line recognition "1" wake up by address mark indicates default mode after RESET 135 SCI Registers SCICR1 (SCI Control) register PE (bit 1) parity enable "0" parity is disabled "1" parity is enabled PT (bit 0) parity type "0" even parity is selected "1" odd parity is selected indicates default mode after RESET 136 SCI Registers SCICR2 (SCI Control) register TIE (bit 7) transmit interrupt enable "0" transmit interrupts disabled "1" transmit interrupts enabled TCIE (bit 6) transmit complete interrupt enable "0" transmit complete interrupt disabled "1" transmit compete interrupt enabled indicates default mode after RESET 137 SCI Registers SCICR2 (SCI Control) register RIE (bit 5) receive interrupt enable "0" receive interrupts disabled "1" receive interrupts enabled ILE (bit 4) idle interrupt enable "0" idle interrupt disabled "1" idle interrupt enabled indicates default mode after RESET 138 SCI Registers SCICR2 (SCI Control) register TE (bit 3) transmitter enable "0" transmitter disabled "1" transmitter enabled RE (bit 2) receiver enable "0" receiver disabled "1" receiver enabled indicates default mode after RESET 139 SCI Registers SCICR2 (SCI Control) register RWU (bit 1) receiver wakeup control "0" exit receiver wake-up wake "1" enter receiver wake-up wake- SBK (bit 0) break control "0" terminate break "1" send break A break character contains all logic 0s and has no start, stop, or parity bit indicates default mode after RESET 140 SCI Registers SCISR1 (SCI Status) register TDRE (bit 7) transmit data register empty flag "0" not ready for new data "1" ready for new data Note: New data will not be transmitted unless SCISR1 is read before writing to the transmit data register (TDR) indicates default mode after RESET 141 SCI Registers SCISR1 (SCI Status) register TC (bit 6) transmit complete flag "0" transmitter busy "1" transmitter idle Note: The TC bit is cleared by reading SCISR1 followed by writing to the transmit data register (TDR) indicates default mode after RESET 142 SCI Registers SCISR1 (SCI Status) register RDRF (bit 5) receive data register full "0" no new data available "1" new receive data available Note: RDRF is cleared by reading SCISR1 followed by reading RDR IDLE (bit 4) idle line detected flag "0" receive data line idle "1" receive data line active indicates default mode after RESET 143 SCI Registers SCISR1 (SCI Status) register OR (bit 3) receiver overrun error flag "0" no overrun detected "1" overrun error detected NF (bit 2) noise flag "0" no noise detected in data bit sample "1" noise detected in data bit sample indicates default mode after RESET 144 SCI Registers SCISR1 (SCI Status) register FE (bit 1) framing error flag "0" no framing error detected "1" framing error detected PF (bit 0) parity error flag "0" parity correct (or disabled) "1" parity error detected indicates default mode after RESET 145 SCI Registers SCISR2 (SCI Status) register RAF (bit 0) receiver active flag "0" no character is being received "1" character is being received indicates default mode after RESET 146 SCI Registers Baud rate control SCIBDH (divisor high nibble) SCIBDL (divisor low byte) BR DIV = CLK / (16 x baud rate) here, CLK = 24 MHz Example: For operation at 9600 baud, a baud rate divisor of 156 (base 10) should be loaded into SCIBDL (leave SCIBDH in reset state) 147 Clicker Quiz 148 1. A possible cause of the noise flag (NF) being set in the SCI is: A. a bad cable or connector B. mismatch in baud rates C. error in the transmit side software D. error in the receive side software E. none of the above 149 2. A possible cause of the receiver overrun flag (OR) being set in the SCI is: A. a bad cable or connector B. mismatch in baud rates C. error in the transmit side software D. error in the receive side software E. none of the above 150 3. If the receiver overrun flag is not being set, a possible cause of "dropped characters" is: A. a bad quarterback and/or wide receiver B. mismatch in baud rates C. error in the transmit side software D. error in the receive side software E. none of the above 151 4. The SCI's TDRE flag is cleared by: A. writing a character to SCIDR B. reading SCISR1 and then writing a character to SCIDR C. reading SCISR1 D. writing a "1" to the TDRE bit of SCISR1 E. none of the above 152 5. The SCI's RDRF flag is cleared by: A. reading a character from SCIDR B. reading SCISR1 and then reading the character from SCIDR C. reading SCISR1 D. writing a "1" to the RDRF bit of SCISR1 E. none of the above 153 6. The SCI baud rate divisor that should be used in a 24 MHz system to transmit 11-bit character frames at 9600 baud is: A. 26 B. 52 C. 104 D. 156 E. none of the above 154 7. The number of 11-bit character frames that can be transmitted each second at 9600 baud is approximately: A. 873 B. 960 C. 8730 D. 9600 E. none of the above 155 8. For a 24 MHz system, the local clock error associated with transmitting 10-bit character frames at 9600 baud using the SCI is approximately: A. 5.0% B. 1.6% C. 0.5% D. 0.16% E. none of the above 156 SCI Program-Driven Operation ProgramDeclarations rxdrf txdre tron equ equ equ $20 $80 $0C ; ; ; ; RDRF mask TDRE mask transmitter and receiver enable mask 157 SCI Program-Driven Initialization Programsci_pini ; Initializes SCI for program-driven operation program; STEP (1) Set transmission rate to 9600 baud sci_pini movb #156t,scibdl ; STEP (2) Select character format (M bit) and parity (bits 1 & 0) via SCI Control Register #1 clr scicr1 ; STEP (3) Enable transmitter and receiver via SCI Control Register #2 (with interrupts off) movb #tron,scicr2 rts 158 SCI Program-Driven Initialization Programsci_pini ; Initializes SCI for program-driven operation program; STEP (1) Set transmission rate to 9600 baud sci_pini movb #156t,scibdl ; STEP (2) Select character format (M bit) and parity (bits 1 & 0) via SCI Control Register #1 clr scicr1 ; STEP (3) Enable transmitter and receiver via SCI Control Register #2 (with interrupts off) movb #tron,scicr2 rts 159 SCI Registers Baud rate control SCIBDH (divisor high nibble) SCIBDL (divisor low byte) BR DIV = CLK / (16 x baud rate) here, CLK = 24 MHz Example: For operation at 9600 baud, a baud rate divisor of 156 (base 10) should be loaded into SC0BDL (leave SC0BDH in reset state) 160 SCI Program-Driven Initialization Programsci_pini ; Initializes SCI for program-driven operation program; STEP (1) Set transmission rate to 9600 baud sci_pini movb #156t,scibdl ; STEP (2) Select character format (M bit) and parity (bits 1 & 0) via SCI Control Register #1 clr scicr1 ; STEP (3) Enable transmitter and receiver via SCI Control Register #2 (with interrupts off) movb #tron,scicr2 rts 161 SCI Registers SCICR1 (SCI Control) register RSRC (bit 5) receiver source (for loop mode) "0" receiver input connected internally to transmitter output "1" receiver input connected to TxD pin M (bit 4) mode (character format) "0" one start, 8 data, one stop "1" one start, 9 data, one stop indicates default mode after RESET 162 SCI Registers SCICR1 (SCI Control) register PE (bit 1) parity enable "0" parity is disabled "1" parity is enabled PT (bit 0) parity type "0" even parity is selected "1" odd parity is selected indicates default mode after RESET 163 SCI Program-Driven Initialization Programsci_pini ; Initializes SCI for program-driven operation program; STEP (1) Set transmission rate to 9600 baud sci_pini movb #156t,scibdl ; STEP (2) Select character format (M bit) and parity (bits 1 & 0) via SCI Control Register #1 clr scicr1 ; STEP (3) Enable transmitter and receiver via SCI Control Register #2 (with interrupts off) movb #tron,scicr2 rts 164 SCI Registers SCICR2 (SCI Control) register TIE (bit 7) transmit interrupt enable "0" transmit interrupts disabled "1" transmit interrupts enabled TCIE (bit 6) transmit complete interrupt enable "0" transmit complete interrupt disabled "1" transmit compete interrupt enabled indicates default mode after RESET 165 SCI Registers SCICR2 (SCI Control) register RIE (bit 5) receive interrupt enable "0" receive interrupts disabled "1" receive interrupts enabled ILE (bit 4) idle interrupt enable "0" idle interrupt disabled "1" idle interrupt enabled indicates default mode after RESET 166 SCI Registers SCICR2 (SCI Control) register TE (bit 3) transmitter enable "0" transmitter disabled "1" transmitter enabled RE (bit 2) receiver enable "0" receiver disabled "1" receiver enabled indicates default mode after RESET 167 SCI Program-Driven Device Drivers Programinchar ; Inputs ASCII character from SCI port and ; returns it in the A register ; No condition code bits or registers affected rxdrf equ $20 ; RDRF mask ; STEP (1) Check RDRF flag (wait until set) inchar brclr scisr1,rxdrf,inchar ; STEP (2) Load A with character in RDR ldaa scidrl rts 168 SCI Program-Driven Device Drivers Programinchar ; Inputs ASCII character from SCI port and ; returns it in the A register ; No condition code bits or registers affected rxdrf equ $20 ; RDRF mask ; STEP (1) Check RDRF flag (wait until set) inchar brclr scisr1,rxdrf,inchar ; STEP (2) Load A with character in RDR ldaa scidrl rts 169 SCI Registers SCISR1 (SCI Status) register RDRF (bit 5) receive data register full "0" no new data available "1" new receive data available Note: RDRF is cleared by reading SCISR1 followed by reading RDR IDLE (bit 4) idle line detected flag "0" receive data line idle "1" receive data line active indicates default mode after RESET 170 SCI Program-Driven Device Drivers Programoutchar ; Outputs character passed in A to the SCI port ; No condition code bits or registers affected txdre equ $80 ; TDRE mask ; STEP (1) Check TDRE flag (wait until set) outchar brclr scisr1,txdre,outchar ; STEP (2) Load TDR with character in A register staa scidrl rts 171 SCI Program-Driven Device Drivers Programoutchar ; Outputs character passed in A to the SCI port ; No condition code bits or registers affected txdre equ $80 ; TDRE mask ; STEP (1) Check TDRE flag (wait until set) outchar brclr scisr1,txdre,outchar ; STEP (2) Load TDR with character in A register staa scidrl rts 172 SCI Registers SCISR1 (SCI Status) register TDRE (bit 7) transmit data register empty flag "0" not ready for new data "1" ready for new data Note: New data will not be transmitted unless SCISR1 is read before writing to the transmit data register (TDR) indicates default mode after RESET 173 SCI Program-Driven Device Drivers Programoutchar ; Outputs character passed in A to the SCI port ; No condition code bits or registers affected txdre equ $80 ; TDRE mask ; STEP (1) Check TDRE flag (wait until set) outchar brclr scisr1,txdre,outchar ; STEP (2) Load TDR with character in A register staa scidrl rts 174 Motivation for Interrupt-Driven Mode InterruptWhat does an SCI receive interrupt mean? mean? "The next character is available to read...and please do so before the next one comes in!" in!" Note: SCI receive interrupts should be continuously enabled 175 Motivation for Interrupt-Driven Mode InterruptWhy buffer data received by the SCI? an entire string of characters may be needed to form a "command" (i.e., for the microcontroller to carry out some function) a "burst" of characters (representing a string of commands or an array of data) may come in faster than the microcontroller can interpret them (or execute "in-line") "in- 176 Motivation for Interrupt-Driven Mode InterruptWhat does an SCI transmit interrupt mean? mean? "Please send me the next character!" character!" Problem: The application program may not always have a character ready to send, resulting in an "unrelenting" interrupt request unrelenting" Solution: Enable SCI transmit interrupts only when characters are available to send Note: This means SCI transmit interrupts should initially be disabled 177 Motivation for Interrupt-Driven Mode InterruptWhy buffer data transmitted by the SCI? using a buffer effectively decouples the CPU from the speed limitations imposed by the SCI character transmission rate note that at 9600 baud, it takes about one millisecond to transmit each character 178 SCI Register Review SCIDRL (SCI data) register Read: receive data register (RDR) Write: transmit data register (TDR) Note: Our device drivers will use SCIDRL as the receive/transmit data register (RDR/TDR) 179 SCI Register Review SCICR1 (SCI Control) register PE (bit 1) parity enable "0" parity is disabled "1" parity is enabled PT (bit 0) parity type "0" even parity is selected "1" odd parity is selected indicates default mode after RESET 180 SCI Register Review SCICR2 (SCI Control) register TIE (bit 7) transmit interrupt enable "0" transmit interrupts disabled "1" transmit interrupts enabled RIE (bit 5) receive interrupt enable "0" receive interrupts disabled "1" receive interrupts enabled indicates default mode after RESET 181 SCI Register Review SCICR2 (SCI Control) register TE (bit 3) transmitter enable "0" transmitter disabled "1" transmitter enabled RE (bit 2) receiver enable "0" receiver disabled "1" receiver enabled indicates default mode after RESET 182 SCI Register Review SCISR1 (SCI Status) register TDRE (bit 7) transmit data register empty flag "0" not ready for new data "1" ready for new data Note: New data will not be transmitted unless SCISR1 is read before writing to the transmit data register (TDR) indicates default mode after RESET 183 SCI Register Review SCISR1 (SCI Status) register RDRF (bit 5) receive data register full "0" no new data available "1" new receive data available Note: RDRF is cleared by a read of the Receive Data Register (RDR) indicates default mode after RESET 184 SCI Register Review Baud rate control SCIBDH (divisor high nibble) SCIBDL (divisor low byte) BR DIV = CLK / (16 x baud rate) here, CLK = 24 MHz Example: For operation at 9600 baud, a baud rate divisor of 156 (base 10) should be loaded into SC0BDL (leave SC0BDH in reset state) 185 SCI Interrupt Mode Operation Register declarations rxdrf txdre tron rimask timask equ equ equ equ equ $20 $80 $0C $20 $80 ; ; ; ; ; RDRF mask TDRE mask transmit/receive enable receive interrupt mask transmit interrupt mask 186 SCI Interrupt-Mode Initialization InterruptBuffer and pointer declarations rsize rbuf rin rout tsize tbuf tin tout equ rmb fcb fcb equ rmb fcb fcb 40t ; receive buffer size rsize 0 ; receive buffer IN pointer 0 ; receive buffer OUT pointer 20t ; transmit buffer size tsize 0 ; transmit buffer IN pointer 0 ; transmit buffer OUT pointer 187 Useful Macro Macro for incrementing B register mod BUFSIZE Example: Example: incBmod 20 ; increments B modulo 20 incBmod MACRO incb cmpb #\1 bne $+3 clrb ENDM 188 SCI Interrupt-Mode Initialization Interrupt; Initializes SCI for interrupt-driven operation interrupt; STEP (1) Set transmission rate to 9600 baud scbini movb #156t,scibdl ; STEP (2) Select character format (M bit) and ; parity enable (and type, if parity enabled) clr scicr1 ; STEP (3) Enable transmitter and receiver, ; initially with receive interrupts enabled and ; transmit interrupts disabled movb #tron,scicr2 ;enable trans/recv tron,scicr2 trans/recv bset scicr2,rimask ;enable recv intrs scicr2,rimask cli ;enable IRQ intrs rts 189 Buffered Character Input "BCI" Routine Application program interface that returns the next character available from the receive buffer RBUF in the A register 1. Check status of receive buffer RBUF 2. If EMPTY, wait for character 3. Else, access character from RBUF[ROUT] and return it in (A) 4. ROUT = (ROUT+1) mod RSIZE 5. Exit 190 Buffered Character Input "BCI" Routine ; Returns next character from RBUF in A register ; STEP (1) Check RBUF status bci ldab rout ; STEP (2) If EMPTY, wait for character rwait cmpb rin ; perform EMPTY check beq rwait ; wait if RBUF empty 191 Buffered Character Input "BCI" Routine ; STEP (3) Access next character from RBUF ldx #rbuf ldaa b,x ;(A) = RBUF[ROUT] RBUF[ROUT] ; STEP (4) Increment ROUT modulo RSIZE incBmod rsize stab rout ; STEP (5) Exit rts 192 Buffered Character Output "BCO" Routine Application program interface that places character passed in A register into transmit buffer TBUF 1. Check status of transmit buffer TBUF 2. If FULL, wait for space 3. Else, store character passed in the A register at TBUF[TIN] 4. TIN = (TIN + 1) mod TSIZE 5. Enable SCI transmit interrupts 6. Exit 193 Buffered Character Output "BCO" Routine ; Places character passed in A into TBUF ; STEP (1) Check TBUF status bco ldab tin incBmod tsize ;(B) = (TIN+1) mod TSIZE (TIN+1) pshb ;save on stack ; STEP (2) If FULL, wait for space twait cmpb tout ;perform FULL check beq twait ;wait if TBUF full 194 Buffered Character Output "BCO" Routine "BCO" ; STEP (3) Place character in TBUF ldx #tbuf ldab tin staa b,x ; TBUF[TIN] = (A) TBUF[TIN] ; STEP (4) Increment TIN mod TSIZE pulb stab tin ; STEP (5) Enable SCI transmit interrupts bset scicr2,timask ; STEP (6) Exit rts 195 SCI Interrupt Service Routine Receive section R1. Check RDRF flag R2. If RDRF=0, go to transmit section; else, continue with receive section R3. Check status of receive buffer RBUF R4. If FULL, error exit (via "SWI") R5. Else, input character from SCI RDR R6. Store character at RBUF[RIN] R7. RIN = (RIN + 1) mod RSIZE 196 SCI Interrupt Service Routine Transmit section T1. Check TDRE flag T2. If TDRE=0, exit; else, continue T3. Check status of transmit buffer TBUF T4. If EMPTY, disable SCI transmit interrupts and exit; else, continue T5. Access character from TBUF[TOUT] T6. Output character to SCI TDR T7. TOUT = (TOUT + 1) mod TSIZE T8. Exit 197 SCI Interrupt Service Routine ; Handles both receive and transmit sections of SCI ; STEP (R1) Check RDRF flag (R1) ; STEP (R2) If RDRF=0, go to transmit section; (R2) RDRF=0, ; else, continue with receive section sciisr brclr scisr1,rxdrf,trans ; STEP (R3) Check status of RBUF (R3) ldab rin incBmod rsize ;(B) = (RIN+1) mod RSIZE (RIN+1) ; STEP (R4) If FULL, error exit; else, continue (R4) cmpb rout bne rok swi 198 SCI Interrupt Service Routine ; STEP (R5) Input character from SCI RDR (R5) rok pshb ; save (RIN+1) mod RSIZE (RIN+1) ldaa scidrl ; read SCI RDR ; STEP (R6) Store character at RBUF[RIN] (R6) RBUF[RIN] ldx #rbuf ldab rin staa b,x ; RBUF[RIN] = (RDR) RBUF[RIN] (RDR) ; STEP (R7) Increment RIN mod RSIZE (R7) pulb ; restore from stack stab rin ; RIN = (RIN+1) mod RSIZE (RIN+1) 199 SCI Interrupt Service Routine ; STEP (T1) Check TDRE flag (T1) ; STEP (T2) If TDRE=0, exit; else, continue (T2) TDRE=0, trans brclr scisr1,txdre,scexit ; STEP (T3) Check status of TBUF (T3) ldab tout cmpb tin ; STEP (T4) If EMPTY, disable SCI transmit (T4) ; interrupts and exit; else, continue bne tok bclr scicr2,timask ;disable trans intrs rti 200 SCI Interrupt Service Routine ; STEP (T5) Access character from TBUF (T5) tok ldx #tbuf ldaa b,x ; (A) = TBUF[TOUT] TBUF[TOUT] ; STEP (T6) Output character to SCI TDR (T6) staa scidrl ; (TDR) = TBUF[TOUT] (TDR) TBUF[TOUT] ; STEP (T7) Increment TOUT mod TSIZE (T7) incBmod tsize stab tout ; TOUT=(TOUT+1) mod TSIZE TOUT=(TOUT+1) ; STEP (T8) Exit (T8) scexit rti 201 2011 Edition by D. G. Meyer Microcontroller-Based Digital System Design Module 3-C Serial Peripheral Interface (SPI) 202 Outline Introduction Features Block Diagrams Registers Applications Reference: Serial Peripheral Interface (SPI) Block User Guide 203 Introduction Definition: Definition: The Serial Peripheral Interface provides a high speed, synchronous serial interface with external ("peripheral") devices Description: Description: A "master" and "slave" communicate by shifting bits to each other's registers; upon completion of eight bit shifts, a status flag is set and an interrupt is generated (if enabled) Where used: used: communicating with simple peripherals such as LCD drivers, D/A converters, etc. communicating with other microcontrollers 204 SPI Communication Block Diagram MASTER SLAVE MOSI Master Out, Slave In MISO Master In, Slave Out 205 SPI Features High speed synchronous serial interface May be used for inter-processor intercommunication Flexible clock format Full duplex operation May be program- or interrupt-driven programinterrupt- 206 SPI Block Diagram PM.4 PM.2 PM.5 24 MHz PM.3 Port M 207 SPI Registers SPICR1 (SPI control register 1) SPIE (bit 7) "0" SPI interrupts disabled "1" SPI interrupts enabled SPE (bit 6) "0" SPI system disabled "1" SPI system enabled SPTIE (bit 5) "0" SPTEF (transmit empty) interrupt disabled "1" SPTEF (transmit empty) interrupt enabled indicates default mode after RESET 208 SPI Registers SPICR1 (SPI control register 1) MSTR (bit 4) "0" slave mode enabled "1" master mode enabled CPOL (bit 3) "0" active high clock (SCK low in idle state) "1" active low clock (SCK high in idle state) CPHA (bit 2) "0" data sampling occurs at odd edges of SCK "1" data sampling occurs at even edges of SCK indicates default mode after RESET 209 SPI Clock Format with CPOL=0, CPHA=0 210 SPI Registers SPICR1 (SPI control register 1) SSOE (bit 1) "0" slave select output disabled "1" slave select output enabled (in master mode, provided MODFEN bit is also "1") LSBFE (bit 0) "0" data transferred most significant bit first "1" data transferred least significant bit first indicates default mode after RESET 211 SPI Registers SPICR2 (SPI control register 2) MODFEN (bit 4) allows detection of MODF "mode fault" failure (master mode only) "0" slave select (SS) port pin not used by SPI "1" slave select (SS) port pin enabled with MODF feature BIDIROE (bit 3) MOSI/MISO output enable in bi-directional mode bi "0" output buffer disabled "1" output buffer enabled SPC0 (bit 0) serial pin control bit "0" bi-directional mode is disabled bi- "1" bi-directional mode enabled bi- indicates default mode after RESET 212 SPI Modes Master Key: Master Slave Input Output 213 SPI Registers SPIBR (baud rate) SPRx (bits 2-0) baud rate pre2preselection bits SPPRx (bits 6-4) baud rate selection 6bits BaudRateDivisor = (SPPR + 1) 2 (SPR + 1) BaudRate = BusClock / BaudRateDivisor Example: If SPR=000 and SPPR=000 (default), then SPR=000 SPPR=000 BaudRateDivisor = 2 BaudRate = BusClock/2 214 SPI Registers SPISR (status) SPIF (bit 7) set after a received data byte is copied into the SPI data register "0" transfer not yet complete "1" received data copied to SPIDR Cleared by reading SPISR (status) register followed by reading SPIDR (data) register SPTEF (bit 5) set when the transmit data register is empty "0" SPI transmit data register not empty "1" SPI transmit data register is empty indicates default mode after RESET 215 SPI Registers SPISR (status) MODF (bit 4) "0" mode fault has not occurred "1" mode fault has occurred (MSTR control bit set and slave select input asserted, which is not permitted in normal operation) indicates default mode after RESET 216 SPI Registers SPIDR (data register) serves as both the input and the output data register for the SPI PORTM (Port M data register) MISO (bit 2) SS (bit 3) MOSI (bit 4) SCK (bit 5) 217 Clicker Quiz 218 1. Transmission of serial data using the SPI is inherently faster than using the SCI because: A. synchronous transmission does not require start/stop bits B. synchronous transmission requires an accompanying clock signal C. synchronous transmission does not require local synchronization D. all of the above E. none of the above 219 2. The "synchronous" aspect of an SPI interface means: A. data can only be transmitted in one direction B. data can be transmitted in both directions, but not at the same time C. data can be transmitted in both directions simultaneously D. data transmission requires a clock signal E. none of the above 220 3. The minimum SPI baud rate divisor possible is: A. 1 B. 2 C. 4 D. 8 E. none of the above 221 4. Based on a 24 MHz system clock, the maximum SPI data transfer rate possible (in bits/second) is: A. 2,000,000 bps B. 4,000,000 bps C. 8,000,000 bps D. 12,000,000 bps E. none of the above 222 5. The maximum SPI baud rate divisor possible is: A. 128 B. 896 C. 2048 D. 4608 E. none of the above 223 6. Based on a 24 MHz system clock, the minimum SPI data transfer rate possible (in bits/second) is approximately: A. 8,000 bps B. 11,719 bps C. 93,750 bps D. 1,500,000 bps E. none of the above 224 SPI Initialization Program-Driven Mode Program- ; Select 1.5 Mbps baud rate (24 MHz bus) spini movb #$12,spibr 225 SPI Registers SPIBR (baud rate) SPRx (bits 2-0) baud rate pre2preselection bits = 010 SPPRx (bits(6-4) baud rate selection (bits(6bits = 001 2 BaudRateDivisior = (1 + 1) 2 (2 + 1) = 16 BaudRate = 24 MHz / 16 = 1.5 Mbps SPIBR = x 001 x 010 = $12 226 SPI Initialization Program-Driven Mode Program- ; Select 1.5 Mbps baud rate (24 MHz bus) spini movb #$12,spibr ; Master mode, Interrupts off, CPOL=0, ; CPHA=0, slave select disabled, data ; transferred most significant bit first movb #$50,spicr1 227 SPI Registers SPICR1 (SPI control register 1) SPIE (bit 7) "0" SPI interrupts disabled "1" SPI interrupts enabled SPE (bit 6) "0" SPI system disabled "1" SPI system enabled SPTIE (bit 5) "0" SPTEF interrupt disabled "1" SPTEF interrupt enabled indicates default mode after RESET 228 SPI Registers SPICR1 (SPI control register 1) MSTR (bit 4) "0" slave mode enabled "1" master mode enabled CPOL (bit 3) "0" active high clock (SCK low in idle state) "1" active low clock (SCK high in idle state) CPHA (bit 2) "0" data sampling occurs at odd edges of SCK "1" data sampling occurs at even edges of SCK indicates default mode after RESET 229 SPI Registers SPICR1 (SPI control register 1) SSOE (bit 1) "0" slave select output disabled "1" slave select output enabled (in master mode, provided MODFEN bit is also "1") LSBFE (bit 0) "0" data transferred most significant bit first "1" data transferred least significant bit first indicates default mode after RESET 230 SPI Initialization Program-Driven Mode Program- ; Select 1.5 Mbps baud rate (24 MHz bus) spini movb #$12,spibr #$12,spibr ; Master mode, Interrupts off, CPOL=0, CPOL=0, ; CPHA=0, slave select disabled, data CPHA=0, ; transferred most significant bit first movb #$50,spicr1 #$50,spicr1 ; Normal (non-bidirectional) mode (nonclr spicr2 rts 231 SPI Registers SPICR2 (SPI control register 2) MODFEN (bit 4) allows detection of MODF "mode fault" failure (master mode only) "0" slave select (SS) port pin not used by SPI "1" slave select (SS) port pin enabled with MODF feature BIDIROE (bit 3) MOSI/MISO output enable in bi-directional mode bi "0" output buffer disabled "1" output buffer enabled SPC0 (bit 0) serial pin control bit "0" bi-directional mode is disabled bi- "1" bi-directional mode enabled bi- indicates default mode after RESET 232 SPI Transmit/Receive (I/O) Routine ;Transmit data passed in A register ;Return data read in B register ;Transmit - wait for SPTEF to set spio brclr spisr,$20,spio staa spidr ;transmit data ;Receive - wait for SPIF to set sprlp brclr spisr,$80,sprlp ldab spidr ;read data rts 233 SPI Registers SPISR (status) SPIF (bit 7) set after a received data byte is copied into the SPI data register "0" transfer not yet complete "1" received data copied to SPIDR Cleared by reading SPISR (status) register followed by reading SPIDR (data) register SPTEF (bit 5) set when the transmit data register is empty "0" SPI transmit data register not empty "1" SPI transmit data register is empty indicates default mode after RESET 234 SPI Application Multiple I/O Devices 235 SPI Application MC14489 Interface 236 SPI Application MC145050 Interface 237 2011 Edition by D. G. Meyer Microcontroller-Based Digital System Design Module 3-D Timer Module (TIM) 238 Outline Introduction Features Block Diagrams Registers Applications Reference: Timer (TIM) Block User Guide 239 Introduction Definition: Definition: The OUTPUT COMPARE function provides a mechanism to output a signal at a specific time, without CPU intervention time, Where used: waveform generation (e.g., PWM) fuel injection/ignition timing 240 Output Compare Function Here, the programmed output transition occurs when the free-running counter TCNT matches the programmed output compare value 241 Introduction Definition: Definition: The INPUT CAPTURE function provides a mechanism to capture the time at which an external event occurs, without CPU intervention Where used: waveform measurement acceleration/velocity measurement 242 Input Capture Function Here, the programmed input edge causes a "snapshot" of the free-running counter TCNT to be taken to serve as an event time stamp 243 Introduction Definition: Definition: The PULSE ACCUMULATOR function provides a mechanism to count external events, without CPU intervention events, Where used: speed measurement event counting 244 TIM & PA Module Block Diagram 245 TIM Features and Functions TIM supports any mixture of 8 input capture channels and/or output compare channels There is a unique interrupt vector for each TIM channel (plus a few extras) Actions (time stamps for input captures, output pin assertions for output compares) are based on the state of a 16-bit free-running 16freecounter ("TCNT") ("TCNT") Channel 7 is "special" it can be configured to reset TCNT (and generate an interrupt) upon a successful output compare, thereby providing the capability to produce very precise periodic interrupts 246 TIM Features and Functions The (single) pulse accumulator (PA) channel shares a port pin with TIM Channel 7 The PA and the TIM Ch 7 output compare functions can be used simultaneously by "disconnecting" the TIM pad logic from the port pin The "force output compare" mechanism provides an application program the ability to force the set of actions associated with an output compare to occur immediately (instead of waiting for the 16-bit counter to 16reach the programmed value) 247 TIM/PA Block Diagram Details 248 TIM/PA Block Diagram Details Port T pins that are not being used for TIM functions can be "disconnected" from the TIM module and accessed via the Port T register (requires appropriate Port T DDR settings) 249 TIM/PA Block Diagram Details The port pin for TIM Channel 7 is shared with the PA pin logic is provided that allows the TIM to be disconnected from the port pin so that an Output Compare 7 and the PA can be used independently 250 TIM/PA Block Diagram Details A Channel 7 output compare is "special" because it can be enabled to reset TCNT when it occurs 251 TIM/PA Block Diagram Details Another thing "special" about TIM Channel 7 is that when an Output Compare 7 occurs, a programmed bit pattern (in reg OC7D) can be output on selected (in reg OC7M) pins 252 TIM/PA Block Diagram Details Normally, the clock for TCNT is derived from the bus clock, but it can also be derived from the PA input pin 253 TIM Registers TIOS (IC/OC select) IOSx (bits 7-0) 7 "0" channel x acts as input capture "1" channel x acts as output compare indicates default mode after RESET 254 TIM Registers TSCR1 (timer system control register 1) TEN (bit 7) timer enable "0" timer subsystem disabled "1" timer functions enabled TFFCA (bit 4) fast flag clear all "0" normal flag clear mode "1" enables fast flag clear mode (input capture read -or- output compare orwrite automatically clears corresponding channel flag helps reduce software overhead) indicates default mode after RESET 255 TIM Registers TSCR2 (timer system control register 2) TOI (bit 7) timer overflow interrupt enable "0" interrupt inhibited "1" interrupt generated when TOF set TCRE (bit 3) timer counter reset enable "0" reset inhibited (free-running) (free "1" counter reset by successful output compare 7 indicates default mode after RESET 256 TIM Registers TSCR2 (timer system control register 2) PR2, PR1, PR0 (bits 2-0) prescalar 2 "000" prescale factor: 1 "001" prescale factor: 2 "010" prescale factor: 4 "011" prescale factor: 8 "100" prescale factor: 16 "101" prescale factor: 32 "110" prescale factor: 64 "111" prescale factor: 128 indicates default mode after RESET 257 TIM Registers TCTL1 (timer control register 1) TCTL2 (timer control register 2) OMx output mode for output compare OLx output level "00" timer disconnected from pin "01" toggle OCx output line "10" clear OCx output line to zero "11" set OCx output line to one indicates default mode after RESET 258 TIM Registers TCTL3 (timer control register 3) TCTL4 (timer control register 4) EDGExB input capture edge control EDGExA input capture edge control "00" capture disabled "01" capture on rising edges only "10" capture on falling edges only "11" capture on rising and falling edges indicates default mode after RESET 259 TIM Registers TIE (timer interrupt enable) CxI (bits 7-0) input capture/output 7compare interrupt enable "0" interrupt disabled "1" interrupt enabled indicates default mode after RESET 260 TIM Registers TFLG1 (timer interrupt flag 1) CxF (bits 7-0) 7 "0" channel x flag not set "1" channel x flag set Flag CxF is cleared by writing a "1" to bit x x of this register (unless the "fast flag clear" mode is used, in which case just reading (input capture) or writing (output compare) the channel register will automatically clear these flags indicates default mode after RESET 261 TIM Registers can be used to trigger the increment of the high byte/word of a time stamp TFLG2 (timer interrupt flag 2) TOF (bit 7) timer overflow flag "0" flag is not set "1" flag is set The TOF flag is set when the free-running timer overflows from $FFFF to $0000 Writing a "1" to bit 7 of this register clears the TOF flag indicates default mode after RESET 262 TIM Registers CFORC (timer compare force) FOCx (bits 7-0) 7 "0" no action "1" output compare occurs immediately, i.e., a write to this register with the corresponding bit(s) set causes the action programmed for that output compare to occur immediately (instead of at the "programmed time") indicates default mode after RESET 263 TIM Registers OC7M (output compare 7 mask) OC7Mx (bits 7-0) 7 "0" Port T in default state "1" Port T pin set for output mode OC7D (output compare 7 data) When a successful OC7 compare occurs, for each bit set in OC7M, the corresponding bit in OC7D is output to Port T indicates default mode after RESET 264 TIM Registers TTOV (timer toggle on overflow) TOVx (bits 7-0) 7 "0" feature is disabled "1" in output compare mode, channel port pin toggles when TCNT overflows indicates default mode after RESET 265 TIM Registers TC0 (IC/OC register 0) TC1 (IC/OC register 1) TC2 (IC/OC register 2) TC3 (IC/OC register 3) TC4 (IC/OC register 4) TC5 (IC/OC register 5) TC6 (IC/OC register 6) TC7 (IC/OC register 7) All are 16-bit 266 TIM Registers PORTT (timer data port) DDRT (data direction register) "0" port pin configured for input "1" port pin configured for output Note: The timer forces the state of DDRT to be "output" for each pin associated with an enabled OUTPUT COMPARE function indicates default mode after RESET 267 TIM Application Car Engine Control 268 Clicker Quiz 269 1. An application for which the input capture mode of the TIM module could be used is: A. generating a precisely timed sequence of output pulses B. precisely measuring the time interval between two input pulses C. counting the number of input pulses D. all of the above E. none of the above 270 2. An application for which the output compare mode of the TIM module could be used is: A. generating a precisely timed sequence of output pulses B. precisely measuring the time interval between two input pulses C. counting the number of input pulses D. all of the above E. none of the above 271 3. The TIM module can potentially provide a more accurate time base than the RTI module because: A. the TIM module uses a more accurate system clock than the RTI module B. the TIM module interrupt rates are based on powersof-two divisions of the system clock, while the RTI allows arbitrary divisions of the system clock C. the RTI interrupt rates are based on powers-of-two divisions of the system clock, while the TIM module allows arbitrary divisions of the system clock D. hidden behind the RTI is a Micruhsoft Winduhs Vister operating system, notorious for taking as much time as it pleases to do anything useful and socially redeeming E. none of the above 272 TIM Application Digital Clock Basic idea: Create a highly accurate digital idea: clock using the TIM module as a time base use prescaler of 16 to divide 24 MHz bus clock down to 1.5 MHz (will cause TCNT register to increment every 0.667 s) use Timer Channel 7 so that the TCNT register can be automatically reset when the Output Compare occurs set TC7 Output Compare register to 15,000 interrupt will occur every 10 ms call "clock" routine when 100 of these interrupts accumulate 273 TIM Application Digital Clock ; Initializes TIM for Digital Clock application ; STEP (1) Enable TIM subsystem tim_ini movb #$80,tscr1 #$80, ; STEP (2) Set prescale factor to 16, and enable ; counter reset after OC7 movb #$0C,tscr2 #$0C, ; STEP (3) Set Ch 7 for Output Compare movb #$80,tios #$80, ; STEP (4) Enable Ch 7 interrupt movb #$80,tie #$80, ; STEP (5) Set up Ch 7 to generate 10 ms interrupt rate movw #15000t,tch7 15000t, ; STEP (6) Enable system IRQ interrupts cli rts 274 PA Features and Functions The (single) pulse accumulator (PA) channel shares a port pin with TIM Channel 7 The PA and the TIM Ch 7 output compare functions can be used simultaneously by "disconnecting" the TIM pad logic from the port pin) There are two basic PA modes: event counting (programmed transition on PT7 increments the 16-bit PACNT register) 16 gated accumulation (PACNT incremented by scaled bus clock, assertion level on PT7 enables/disables counter) 275 PA Module Block Diagram 276 PA Module Block Diagram PA use requires that the port pin PT7 be "disconnected" from the associated TIM function 277 PA Module Block Diagram TCNT clocking path for "event counting" mode 278 PA Module Block Diagram TCNT clocking path for "gated accumulation" mode X 279 PA Module Block Diagram PA can simply be used as an edgesensitive interrupt device flag if desired 280 PA Module Block Diagram PA has two interrupt vectors: input interrupt (PAI) and overflow interrupt (PAOVI) 281 PA Registers PACTL (pulse accumulator control) PAEN (bit 6) pulse accumulator system enable "0" pulse accumulator system disabled "1" pulse accumulator system enabled PAMOD (bit 5) pulse accum mode "0" event counter mode "1" gated time accumulation mode indicates default mode after RESET 282 PA Registers PACTL (pulse accumulator control) PEDGE (bit 4) edge control (event) "0" count on falling edges "1" count on rising edges PEDGE (bit 4) edge control (gated) "0" input pin high enables accumulation "1" input pin low enables accumulation indicates default mode after RESET 283 Pulse Accumulator Modes Here, PEDGE = 1 means that PACNT increments every time a rising edge on pin PT7 is detected Bus clock divided by 64 PAMOD = 0 selects "event counting" mode 284 Pulse Accumulator Modes Here, PEDGE = 1 means that the accumulation is enabled on an active low assertion of pin PT7 Bus clock divided by 64 PAMOD = 1 selects "gated accumulation" mode Note that PACNT always increments on the negative edge of the scaled bus clock 285 PA Registers PACTL (pulse accumulator control) CLK1, CLK0 (bits 3,2) clock select "00" use timer prescalar clock as timer counter clock "01" use PACLK as input to timer counter clock "10" use PACLK/256 as timer clock freq "11" use PACLK/65536 as timer clock frequency indicates default mode after RESET 286 TIM/PA Block Diagram Details Normally, the clock for TCNT is derived from the bus clock, but it can also be derived from the PA input pin 287 PA Registers PACTL (pulse accumulator control) PAOVI (bit 1) pulse accumulator overflow interrupt enable "0" interrupt inhibited "1" interrupt enabled PAI (bit 0) pulse accumulator interrupt enable "0" interrupt inhibited "1" interrupt enabled indicates default mode after RESET 288 PA Registers PAFLG (pulse accumulator flag) PAOVF (bit 1) pulse accumulator overflow flag "0" no overflow has occurred "1" pulse accumulator has overflowed Writing a "1" to bit 1 of this register clears the PAOVF flag indicates default mode after RESET 289 PA Registers PAFLG (pulse accumulator flag) PAIF (bit 0) pulse accumulator interrupt flag "0" no edge detected on PA input "1" edge detected on PA input Writing a "1" to bit 0 of this register clears the PAIF flag indicates default mode after RESET 290 Clicker Quiz 291 1. An application for which the pulse accumulator mode of the TIM module could be used is: A. generating a precisely timed sequence of output pulses B. precisely measuring the time interval between two input pulses C. counting the number of input pulses D. all of the above E. none of the above 292 2. The TIM Ch 7 periodic interrupt generation capability and the pulse accumulator (PA) can be used simultaneously by: A. disconnecting the TIM Ch 7 output from the port pin B. re-routing the TIM Ch 7 output to a different port pin C. continuously changing the mode of the port pin D. re-routing the PA input to a different port pin E. none of the above 293 PA Application Digital Tachometer Basic idea: Estimate motor RPM based on idea: number of pulses accumulated from a slotted disk over a specified integration period PA used to accumulate pulses in "event counting" counting" mode either RTI or TIM module used to determine integration period for estimate pulse count converted to BCD number in software Thought question: Why doesn't it matter which one (RTI or TIM) is used as the time base for the RPM estimate estimate? 294 PA Application Digital Tachometer Basic idea: Estimate motor RPM based on idea: number of pulses accumulated from a slotted disk over a specified integration period PA used to accumulate pulses in "event counting" counting" mode either RTI or TIM module used to determine integration period for estimate pulse count converted to BCD number in software Thought question: Why doesn't it matter which one (RTI or TIM) is used as the time base for the RPM estimate Time-base estimate? Timeerror doesn't accumulate (unlike clock) 295 Not-SoNot-So-Quick Clicker Quiz 296 ;*********************************************************************** ; In this exercise we will investigate using the TIM module as ; a time base, and compare it to use of the RTI subsystem. ;*********************************************************************** ; ; The objective of this problem is to implement stopwatch that can count ; in increments of 0.1 second up to 999.9 seconds. ; Here, both the RTI and TIM modules will be used as time bases, with the ; opportunity to compare the results obtained using each approach. ; ; The following docking board resources will be used: ; - left pushbutton (PAD7): stopwatch reset ; - right pushbutton (PAD6): stopwatch start/stop ; - left LED (PT1): stopwatch run/stop state ; - right LED (PT0): stopwatch maxed out (999.9) state ; ; The four-digit stopwatch value (NNN.N) is to be updated on the terminal ; screen every one-tenth second (display both RTI and TIM values). ; Task list: ; 1. Calculate the expected difference between the two stopwatches and ; compare that with the actual values obtained ; ; 2. See if you can make the RTI-based stopwatch "more accurate" by ; changing the interrupt rate (and modifying maximum RTICNT) while *still successfully de-bouncing the pushbuttons* 297 ; ====================================================================== ; ; Variable declarations (SRAM) ; org RFLG TFLG LEFTPB RGHTPB RUNSTP rticnt timcnt prevpb rtime ttime $3800 rmb rmb rmb rmb rmb rmb rmb rmb rmb rmb 1 1 1 1 1 1 1 1 2 2 ; ; ; ; ; ; ; ; ; ; RTI one-tenth second flag (1 -> set, 0 -> clear) TIM one-tenth second flag (1 -> set, 0 -> clear) left pushbutton flag (1 -> set, 0 -> clear) right pushbutton flag (1 -> set, 0 -> clear) run/stop flag (1 -> run, 0 -> stop) RTICNT (variable) TIMCNT (variable) previous state of pushbuttons (variable) RTI stopwatch time NNN.N (variable) TIM stopwatch time NNN.N (variable) 298 ;*********************************************************************** ; ; RTI and TIM initializations given in the class notes ; ; set 8.192 ms RTI interrupt rate movb #$70,rtictl ; enable RTI interrupts bset crgint,$80 ; enable TIM subsystem movb #$80,tscr1 ; set TIM prescale factor to 16, and enable counter reset after OC7 movb #$0C,tscr2 ; set TIM Ch 7 for Output Compare movb #$80,tios ; enable TIM Ch 7 interrupt movb #$80,tie ; set TIM Ch 7 to generate 10.0 ms interrupt rate movw #15000,tc7 ; enable IRQ interrupts cli 299 ; ; ; ; ; ; ; ; ; ; ; If the "run/stop" flag is set, then - If the "RFLG" flag is set, then + clear the "RFLG" flag + increment the RTI stopwatch value by one tenth (in BCD) - Endif - If the "TFLG" flag is set, then + clear the "TFLG" flag + increment the TIM stopwatch value by one tenth (in BCD) + update the display - Endif Endif main1 brclr brclr clr ldaa adda daa staa ldaa adca daa staa RUNSTP,$01,main2 RFLG,$01,main12 RFLG rtime+1 #1 rtime+1 rtime #0 rtime 300 ; ; ; ; ; ; ; ; ; ; ; If the "run/stop" flag is set, then - If the "RFLG" flag is set, then + clear the "RFLG" flag + increment the RTI stopwatch value by one tenth (in BCD) - Endif - If the "TFLG" flag is set, then + clear the "TFLG" flag + increment the TIM stopwatch value by one tenth (in BCD) + update the display - Endif Endif main12 brclr clr ldaa adda daa staa ldaa adca daa staa jsr TFLG,$01,main2 TFLG ttime+1 #1 ttime+1 ttime #0 ttime rtdisp 301 main2 ; ; ; ; ; ; If the left pushbutton ("reset stopwatch") flag is set, then: - clear the left pushbutton flag - clear the "run/stop" flag - turn off both the "run/stop" and "maxed out" LEDs - reset the terminal display to "000.0" Endif brclr clr clr clr clr clr clr clr jsr LEFTPB,$01,main3 LEFTPB RUNSTP PTT rtime rtime+1 ttime ttime+1 rtdisp 302 main3 ; ; ; ; ; If the right pushbutton ("start/stop") flag is set, then - clear the right pushbutton flag - toggle the "run/stop" flag - toggle the "run/stop" LED Endif brclr clr ldaa eora staa ldaa eora staa RGHTPB,$01,main4 RGHTPB RUNSTP #$01 RUNSTP PTT #$02 PTT 303 main4 ; ; ; ; ; If the TIM stopwatch has reached "999.9", then: - clear the "run/stop" flag - turn on the "time expired" LED - turn off the "run/stop" LED Endif ldaa cmpa bne ldaa cmpa bne clr movb main41 jmp main1 ; continue looping ttime #$99 main41 ttime+1 #$99 main41 RUNSTP #$01,PTT 304 ;*********************************************************************** ; ; TIM interrupt service routine ; ; Interrupt generated every 10 ms on TC7 ; ; Use variable TIMCNT to count up to 10 of these ; and set TFLG when that happens ; ; NOTE: If the "runstp" flag is clear (stopwatch is "stopped") ; this routine should DO NOTHING other than clear ; the TC7 interrupt flag tim_isr bset brclr ldaa inca staa cmpa blt clr movb tdone rti TFLG1,$80 ; clear TC7 interrupt flag RUNSTP,$01,tdone timcnt timcnt #10 tdone timcnt #$01,TFLG ; count to 100 ms (10 x 10ms) ; set tenth-of-second flag 305 ;*********************************************************************** ; RTI interrupt service routine ; ; Keeps track of when 0.1 second of RTI interrupts has accumulated ; and sets RFLG ; ; Also, samples state of pushbuttons (PTAD7 = left, PTAD6 = right) ; If change in state from "high" to "low" detected, set pushbutton flag ; LEFTPB (for PTAD7 H -> L), RGHTPB (for PTAD6 H -> L) ; Recall that pushbuttons are momentary contact closures to ground rti_isr ; ; Using RTICNT, track when 0.1 second of RTI interrupts has accumulated Set the "RFLG" flag when this occurs and clear RTICNT bset brclr inc ldaa cmpa blt clr movb crgflg,$80 RUNSTP,$01,chkpb rticnt rticnt #12 ; based on initial 8.192 ms interrupt rate chkpb rticnt #$01,RFLG 306 ; ; Check the pushbuttons for a change of state (compare previous with current) If no change detected, exit service routine chkpb ldaa anda cmpa bne rti PTAD #$C0 prevpb didchg ; ; ; ; ; ; read current state of pushbuttons mask off PTAD7 and PTAD6 compare with previous PB state if current state != previous state figure out which pushbutton involved else, exit with no change ; ; State of PB changed -- check if action necessary Note: Not considering case when both PBs pressed simultaneously didchg psha ; ; ; save current state of PB If previous state of left PB was "H" and current state is "L" then set "LEFTPB" flag and proceed to exit; else, check right PB chklft anda eora psha ldab andb andb beq movb bra #$80 #$80 prevpb #$80 1,sp+ chkrgt ; isolate current left PB ; complement current left PB ; isolate previous left PB ; if AND=0, left PB did not change from H->L so exit ; else, set LEFTPB flag #$01,LEFTPB 307 rdone ; ; If previous state of right PB was "H" and current state is "L" then set "rghtpb" flag and proceed to exit chkrgt ldaa anda eora psha ldab andb andb beq movb 0,sp #$40 #$40 prevpb #$40 1,sp+ rdone ; reload current PB state ; isolate current right PB ; complement current right PB ; isolate previous right PB ; if AND=0, right PB did not change from H->L so exit ; else, set RGHTPB flag #$01,RGHTPB ; Since PB state changed, set PREVPB = current state read rdone pula staa rti prevpb ; update PB state 308 Q1. A practical lower limit on the RTI interrupt rate to ensure successful de-bouncing of the pushbuttons is: A. 0.01 ms B. 0.1 ms C. 1.0 ms D. 10 ms E. none of the above 309 Q2. The reason the RUNSTP flag needs to be checked in both the RTI and TIM interrupt service routines is because: A. there is no other way to start/stop the two stopwatches simultaneously B. timing error would otherwise be introduced when the stopwatches are started/stopped C. a race condition might otherwise occur if the RTI and TIM interrupts fire simultaneously D. the TIM and RTI need to remain pending E. none of the above 310 Q3. When the stopwatch runs to completion (TTIME = 999.9 secs), the difference between RTIME and TTIME will be approximately: A. 0.17 sec B. 1.7 secs C. 16.9 secs D. 17.2 secs E. none of the above 311 ; set 8.192 ms RTI interrupt rate movb #$70,rtictl ; set 8.192 ms RTI interrupt rate ;********************************************************************** rti_isr ; ; Using RTICNT, track when one-tenth second of RTI interrupts accumulated Set the "RFLG" flag when this occurs and clear RTICNT bset brclr inc ldaa cmpa blt clr movb crgflg,$80 runstp,$01,chkpb rticnt rticnt #12 ; 12 x 8.192 = 98.304 ms chkpb rticnt #$01,rflg RTIME runs "fast" ("1 sec" = 0.98304 sec actual) TTIME / 0.98304 = RTIME (off by 17.2 after 1000 secs) 312 Q4. If the RTI interrupt rate is changed to 1.024 ms and the RTICNT comparison value is adjusted appropriately, the difference between RTIME and TTIME can be reduced to approximately _______ when the stopwatch runs to completion. A. B. C. D. E. 0.35 sec 1.7 secs 3.5 secs 7.2 secs none of the above 313 ; set 1.024 ms RTI interrupt rate movb #$40,rtictl ; set 1.024 ms RTI interrupt rate ;********************************************************************** rti_isr ; ; Using RTICNT, track when one-tenth second of RTI interrupts accumulated Set the "rflg" flag when this occurs and clear RTICNT bset brclr inc ldaa cmpa blt clr movb crgflg,$80 runstp,$01,chkpb rticnt rticnt #98 ; 98 x 1.024 = 100.352 ms chkpb rticnt #$01,rflg RTIME runs "slow" ("1 sec" = 1.00352 sec actual) TTIME / 1.00352 = RTIME (off by 3.5 after 1000 secs) 314 Q5. Through careful choice of RTI interrupt rate, the difference between RTIME and TTIME can be reduced to approximately _______ when the stopwatch runs to completion while still successfully de-bouncing the pushbuttons. A. B. C. D. E. 0.03 sec 0.3 sec 1.5 secs 3.0 secs none of the above 315 ; set 1.408 ms RTI interrupt rate movb #$1A,rtictl ; set 1.408 ms RTI interrupt rate ***** ;********************************************************************** rti_isr ; ; Using RTICNT, track when one-tenth second of RTI interrupts accumulated Set the "rflg" flag when this occurs and clear RTICNT bset brclr inc ldaa cmpa blt clr movb crgflg,$80 runstp,$01,chkpb rticnt rticnt #71 ; 71 x 1.408 = 99.968 ms chkpb rticnt #$01,rflg RTIME runs "fast" ("1 sec" = 0.99968 sec actual) TTIME / 0.99968 = RTIME (off by 0.3 after 1000 secs) 316 2011 Edition by D. G. Meyer Microcontroller-Based Digital System Design Module 3-E Pulse Width Modulation (PWM) 317 Outline Introduction PWM features PWM registers PWM initialization Reference: Pulse Width Modulation (PWM) Block User Guide 318 Introduction Definition: Definition: The pulse width modulation unit provides the capability of producing a square wave output of varying duty cycle and sampling frequency 0% duty cycle always off 50% duty cycle symmetric square wave 100% duty cycle always on Where used D.C. motor speed control digital-to-analog conversion (in digital-toconjunction with low-pass filter) low319 PWM Encoding of an Analog Input Signal Referred to as "natural sampling" which is different than pulse-code modulation (PCM) Can be thought of as a one-bit A/D encoding system. The sampling frequency must be at least an order of magnitude higher than the highest frequency component of the input signal. The PWM output can be low-pass filtered to re-construct the analog signal. 320 PWM Encoding (Analog Modulator) and Signal Reconstruction low-pass filter 321 PWM Features and Operating Modes 6 independent channels with programmable period and duty cycle 8-bit resolution (6-channel mode) or 16-bit (616resolution (3-channel mode) (3Flexible clock generation wide range of sampling frequencies Period and duty cycle registers are doubledoublebuffered (allows immediate PWM update) Output pulse polarity and alignment are programmable Emergency shutdown capability 322 PWM Block Diagram 323 PWM Registers PWME (PWM channel enable) PWENx (bit x) channel x enable PWENx "0" disabled "1" enabled PWMPOL (PWM polarity select) PPOLx (bit x) channel x polarity PPOLx "0" active low "1" active high indicates default mode after RESET 324 PWM Registers PWMPERx PWMPERx (channel x period) the number of "clock ticks" that constitute one complete period of the PWM signal PWMDTYx PWMDTYx (channel x duty cycle) the number of "clock ticks" the PWM signal is asserted low* (PPOL=0) or high* (PPOL=1) low* high* *In ECE 270, we define duty cycle as the percent of the period that a signal is asserted (independent of assertion level) note that the definition used in the Freescale documentation is dependent on assertion level ("% of time signal is high"). 325 PWM Boundary Conditions 326 Polarity Select and Duty Cycle Duty Cycle (%) = 100 (PWMDTY)/(PWMPER) Sampling Frequency = (Input Clock)/(PWMPER) "Left Aligned" Mode (default) 327 PWM Clock Selection Diagram 328 PWM Clock Selection Diagram Pre-scale divisor range is 1 to 128 Clock source is the BUS CLOCK 329 PWM Registers PWMPRCLK (prescale clock select) PCKB2- PCKB0 (bits 6-4) Clock B prescaler PCKB26 PCKA2-PCKA0 (bits 2-0) Clock A prescaler PCKA22 "000" bus clock "001" bus clock/2 "010" bus clock/4 "011" bus clock/8 "100" bus clock/16 "101" bus clock/32 "110" bus clock/64 "111" bus clock/128 indicates default mode after RESET 330 Clock A is the pre-scaled bus clock, and Clock SA is the scaled Clock A In general: N = D/2 where N is the value to load in PWSCALA for clock divisor D PWM Channels 0, 1, 4, and 5 can select either Clock A or Clock SA Note that the range of SA is from A/2 to A/512 331 PWM Registers PWMCLK (clock source select) PCLK5 (bit 5) channel 5 clock select "0" use "Clock A" "1" use "Clock SA" PCLK4 (bit 4) channel 4 clock select "0" use "Clock A" "1" use "Clock SA" indicates default mode after RESET 332 PWM Registers PWMCLK (clock source select) PCLK1 (bit 1) channel 1 clock select "0" use "Clock A" "1" use "Clock SA" PCLK0 (bit 0) channel 0 clock select "0" use "Clock A" "1" use "Clock SA" indicates default mode after RESET 333 PWM Registers PWMSCLA (Scale A Register) 8-bit programmable scale value for Clock A Clock SA = Clock A / (2 PWMSCLA) $00 is used to represent 25610 334 Clock B is the pre-scaled bus clock, and Clock SB is the scaled Clock B In general: N = D/2 where N is the value to load in PWSCALB for clock divisor D Note that the range of SB is from B/2 to B/512 PWM Channels 2 and 3 can select either Clock B or Clock SB 335 PWM Registers PWMCLK (clock source select) PCLK3 (bit 3) channel 3 clock select "0" use "Clock B" "1" use "Clock SB" PCLK2 (bit 2) channel 2 clock select "0" use "Clock B" "1" use "Clock SB" indicates default mode after RESET 336 PWM Registers PWMSCLB (Scale B Register) 8-bit programmable scale value for Clock B Clock SB = Clock B / (2 PWMSCLB) $00 used to represent 25610 337 16-bit PWM Mode 338 PWM Registers PWMCTL (PWM control) CON45 (bit 6) concatenate chs 4 & 5 "0" channels 4 & 5 separate 8-bit 8 "1" channels 4 & 5 concatenated 16-bit 16- CON23 (bit 5) concatenate chs 2 & 3 "0" channels 2 & 3 separate 8-bit 8 "1" channels 2 & 3 concatenated 16-bit 16- CON01 (bit 4) concatenate chs 0 & 1 "0" channels 0 & 1 separate 8-bit 8 "1" channels 0 & 1 concatenated 16-bit 16indicates default mode after RESET 339 PWM Registers PWMCAE (center align enable) CAEx (bit x) center align channel x CAEx "0" operate ch x in left-aligned mode left "1" operate ch x in center-aligned mode centerNote: The center-aligned mode is useful for asynchronous motor control (e.g., for brushless DC motors) indicates default mode after RESET 340 Center-Aligned Mode Duty Cycle (%) = 100 (PWMDTY)/(PWMPER) Sampling Frequency = (Input Clock)/(2 PWMPER) 341 PWM Registers PWMSDN (PWM shutdown) PWMIF (bit 0) interrupt flag "0" PWM state has not changed "1" PWM state has changed PWMIE (bit 6) interrupt enable "0" PWM interrupt disabled "1" PWM interrupt enabled PWMRSTRT (bit 5) Used to restart PWM outputs after shutdown state is cleared indicates default mode after RESET 342 PWM Registers PWMSDN (PWM shutdown) PWMLVL (bit 4) shutdown output level "0" PWM outputs all forced low "1" PWM outputs all forced high PWM5IN (bit 2) Ch 5 input status Reflects current status of PWM5 pin PWM5INL (bit 1) shutdown active level "0" Active level is low "1" Active level is high PWM5ENA (bit 0) shutdown enable "0" PWM emergency shutdown disabled "1" PWM emergency shutdown enabled indicates default mode after RESET 343 PWM Registers Port P (data register) bits 0-5 used for PWM output channels 0-5 00 PWM takes precedence over generalgeneralpurpose I/O when enabled DDRP (data direction register) used to establish data direction of Port P bits when used for general-purpose I/O general- 344 Clicker Quiz 345 1. Useful applications of the PWM include: A. D.C. motor speed control B. digital-to-analog conversion C. controlling the intensity of an LED D. all of the above E. none of the above 346 2. The double buffering feature of the PWM unit: A. prevents a PWM output from changing the instant the period or duty register is written B. provides a larger window of time during which the PWM registers can be written C. provides a larger window of time during which the PWM registers can be read D. all of the above E. none of the above 347 3. Given a 24 MHz bus clock, in 8-bit mode the minimum frequency 50% duty cycle square wave that can be generated by the PWM unit is approximately: A. 0.15 Hz B. 1.50 Hz C. 15.00 Hz D. 150.0 Hz E. none of the above 348 4. Given a 24 MHz bus clock, in 8-bit mode the maximum frequency 50% duty cycle square wave that can be generated by the PWM unit is: A. 12,000 Hz B. 120,000 Hz C. 1,200,000 Hz D. 12,000,000 Hz E. none of the above 349 5. Given a 24 MHz system clock with PWMPRCLK = 0110 00002 and PWMCLK = 0000 01002, the following combination of PWM register initializations will produce a 100 Hz (approx.), 50% duty cycle square wave on Channel 2 (assuming PWMPOL = 0000 01002 and PWMEN = 0000 01002): A. PWSCALB = 9310, PMWPER2 = 2010, PMWDTY2 = 1010 B. PWSCALB = 18610, PWMPER2 = 2010, PWMDTY2 = 1010 C. PWSCALB = 5010, PWMPER2 = 10010, PWMDTY2 = 5010 D. PWSCALB = 4910, PWMPER2 = 10010, PWMDTY2 = 5010 E. none of the above 350 PWM Initialization Example Assume the bus clock is 24 MHz and that the PWM is used to generate four left-aligned leftactive high square wave signals: Ch 0 120,000 Hz 10% duty cycle Ch 1 20,000 Hz 30% duty cycle Ch 2 7,500 Hz 70% duty cycle Ch 3 250 Hz 85% duty cycle Determine the register initializations required to generate these four waveforms 351 PWM Initialization Example For Ch 0 (and Ch 1), need PWMPER = 100 to have a "resolution" of 1% in specifying the duty cycle need input clock frequency of at least 120,000 100 = 12 MHz (conveniently, this is half the 9S212C32 bus clock freq.) The "scale" register for Clock A can be used to produce the input clock for Ch 1, which is 20,000 100 = 2 MHz Clock SA = (Clock A)/6 PWSCALA = 3 352 PWM Initialization Example PWME = 0Fh (enables PWM Chs 0-3) PWMPER0 (ch 0 period) = 100t (ch Will allow PWMPER1 (ch 1 period) = 100t (ch resolution PWMPER2 (ch 2 period) = 100t (ch of 1% PWMPER3 (ch 3 period) = 100t (ch the number of "clock ticks" that constitute one complete period of the PWM signal Leftaligned mode 100 353 PWM Initialization Example PWMPOL = 0Fh (Chs 0-3 active high polarity) 0PWMDTY0 (Ch 0 duty cycle) = 10t (10%) PWMDTY1 (Ch 1 duty cycle) = 30t (30%) PWMDTY2 (Ch 2 duty cycle) = 70t (70%) PWMDTY3 (Ch 3 duty cycle) = 85t (85%) the number of "clock ticks" the PWM signal is asserted low (PPOL=0) or high (PPOL=1) Leftaligned mode 100 354 PWM Clock Selection Diagram 24 MHz 3 12 MHz 2 MHz 355 PWM Initialization Example For Ch 2 (and Ch 3), again need PWMPER = 100 to have a "resolution" of 1% in specifying the duty cycle need input clock frequency of at least 7,500 100 = 750 KHz = 24 MHz / 32 The "scale" register for Clock B can be used to produce the input clock for Ch 3, which is 250 100 = 25 KHz Clock SB = (Clock B) / 30 PWSCALB = 15 356 PWM Clock Selection Diagram 12 MHz 2 MHz 3 750 KHz 25 KHz 15 24 MHz 357 PWM Clock Selection Diagram 12 MHz 2 MHz 3 750 KHz 25 KHz 15 24 MHz PWMPRCLK = x101 x001 358 PWM Clock Selection Diagram 12 MHz 2 MHz 3 750 KHz 25 KHz 15 PWMCLK = xxxx 1010 24 MHz 359 PWM Applications/Interfaces Simple "D/A converter" (single pole LPF) PWM Port Pin A higher order (active) LPF can also be used the OP AMP provides isolation and additional output drive capability (not necessary if output load is high impedance) 360 PWM Applications/Interfaces Driving a small loudspeaker VCC PWM Port Pin The loudspeaker will "mechanically" low-pass filter the PWM signal 361 PWM Applications/Interfaces Motor speed and direction control using an "H"-bridge (here, a pair of "half-H" bridges) Output Port Pin PWM Port Pin 362 "H Bridge" V+ V+ motor V- V- 363 "H Bridge" V+ V+ + motor - V- V- 364 "H Bridge" V+ V+ - motor + V- V- 365 Not-SoNot-So-Quick Clicker Quiz 366 ;*********************************************************************** ; Analyze the following code ;*********************************************************************** ; ; initialize PWM Ch 0 movb movb movb movb movb movb movb movb movb movb #$01,MODRR #$01,PWME #$01,PWMPOL #$00,PWMCTL #$00,PWMCAE #$FF,PWMPER0 #$7F,PWMDTY0 #$07,PWMPRCLK #$01,PWMCLK #$00,PWMSCLA ; PT0 used as PWM Ch 0 output ; ; ; ; ; ; ; ; ; enable PWM Ch 0 set active high polarity no concatenate (8-bit) left-aligned output mode set maximum 8-bit period (255) set 50% duty cycle set Clock A = 24 MHz / 128 (max pre-scalar) select Clock SA for Ch 0 set Clock SA scalar to 512 (max scalar) ; initialize TIM Ch 1 movb movb movb movw movw eloop bra #$80,tscr1 #$07,tscr2 #$02,tios #$0004,tctl1 #$0000,tc1 eloop ; ; ; ; ; enable TC1 set TIM pre-scale factor to 128 (max) set TIM TC1 for Output Compare mode toggle PT1 on successful output compare value for OC1 ; infinite (do-nothing) loop 367 Q1. The PT0 "toggle rate" (in milliseconds) for the code as written will be approximately: A. B. C. D. E. 1.36 ms 2.73 ms 696 ms 699 ms none of the above 368 Q2. The PT1 "toggle rate" (in milliseconds) for the code as written will be approximately: A. B. C. D. E. 1.36 ms 350 ms 696 ms 699 ms none of the above 369 Q3. The PT0 and PT1 "toggle rates" could be made to be identical (i.e., exactly in sync) by: A. B. C. D. E. changing the value in PWMDTY0 to $80 changing the value in PWMPER0 to $00 changing the value in PWMSCLA to $01 changing the value in TC1 to $0100 none of the above 370 Q4. Increasing the value loaded into TC1 would: A. do nothing except change the (initial) relative phase of the PT0 and PT1 port pin toggling B. increase the PT1 port pin toggle rate C. decrease the PT1 port pin toggle rate D. disable port pin PT1 from toggling E. none of the above 371 Not-SoNot-So-Quick Clicker Quiz (after DPS) 372 ;*********************************************************************** ; ; In this exercise we will investigate ATD-PWM audio digitization ; and signal reconstruction as well as a "digital volume control". ; ;*********************************************************************** ; ; Resources used: ; - TIM TC7 - interrupt every 0.1 ms, used to initiate ATD conversion ; - ATD Ch 0 - audio input (PIN 5 on BREADBOARD HEADER) ; - ATD Ch 1 - potentiometer input for digital volume control (PIN 6 on ; BREADBOARD HEADER) ; - PWM Ch 0 - audio output (PIN 27 on BREADBOARD HEADER) ; ; CAUTION: Carefully adjust the function generator analog output for a ; D.C. offset of 2 V and a peak voltage no greater than 4 V ; (use the oscilloscope to confirm). ; Task list: ; 1. Determine the input sampling frequency and the output sampling ; frequency for the code as written. ; 2. Try varying the input and output sampling frequencies ; (independently), and note the effects. 373 ;*********************************************************************** ; START OF CODE ;*********************************************************************** ; initialize ATD (8 bit, unsigned, nominal sample time, seq length = 2) movb movb movb #$80,ATDCTL2 #$10,ATDCTL3 #$85,ATDCTL4 ; power up ATD ; set conversion sequence length to TWO ; select resolution and sample time ; initialize PWM Ch 0 (left aligned, positive polarity, max 8-bit period) movb movb movb movb movb movb movb movb movb movb #$01,MODRR #$01,PWME #$01,PWMPOL #$00,PWMCTL #$00,PWMCAE #$FF,PWMPER0 #$00,PWMDTY0 #$00,PWMPRCLK #$01,PWMCLK #$01,PWMSCLA ; ; ; ; ; ; ; ; ; ; ; PT0 used as PWM Ch 0 output enable PWM Ch 0 set active high polarity no concatenate (8-bit) left-aligned output mode set maximum 8-bit period initially clear DUTY register set Clock A = 24 MHz (prescaler = 1) select Clock SA for Ch 0 set Clock SA scalar to 2 **** change to modify output sampling rate 374 ; initialize TIM Ch 7 (periodic 0.1 ms interrupt) movb movb movb movb movw #$80,tscr1 #$0C,tscr2 ; enable TC7 ; set TIM prescale factor to 16 ; and enable counter reset after OC7 #$80,tios ; set TIM TC7 for Output Compare #$80,tie ; enable TIM TC7 interrupt #150,tc7 ; set up TIM TC7 to generate 0.1 ms interrupt rate ; **** change this to modify input sampling rate ; enable IRQ interrupts cli ; enable IRQ interrupts ; do nothing after initialization complete eloop bra eloop ; wait loop 375 ;*********************************************************************** ; TIM interrupt service routine ; Interrupt generated every 0.1 ms (default - may be changed) ; Initiate ATD conversion on Chs 0 and 1 ; Multiply analog input sample by potentiometer sample -> PWM Ch 0 ; tim_isr bset movb tflg1,$80 #$10,ATDCTL5 ; clear TC7 interrupt flag ; start conversion on ATD Ch 0 ; NOTE: "mult" (bit 4) needs to be set await brclr ldaa ldab mul adca staa rti ATDSTAT,$80,await ATDDR0 ATDDR1 #0 PWMDTY0 ; ; ; ; ; analog input sample potentiometer sample multiply input sample X pot setting round upper 8 bits of result copy result to PWM Ch 0 376 Q1. The input sampling frequency, for the code as written, is approximately: A. B. C. D. E. 1 KHz 2 KHz 5 KHz 10 KHz none of the above 377 Q2. An appropriate choice for anti-aliasing lowpass filter cut-off frequency, for the application as written, would be: A. 1 KHz B. 2 KHz C. 5 KHz D. 10 KHz E. none of the above 378 Q3. The output sampling frequency, for the code as written, is approximately: A. B. C. D. E. 10 KHz 12 KHz 47 KHz 94 KHz none of the above 379 Q4. If the value loaded in TSCR2 was changed to $0B and the value loaded into TC7 was changed to $00FF, the new input sampling frequency would be (approximately): A. B. C. D. E. 11,765 Hz 23,530 Hz 47,059 Hz 94,118 Hz none of the above 380 Q5. If the value loaded into PWMSCLA was changed to 4, the new output sampling frequency would be (approximately): A. 11,765 Hz B. 23,530 Hz C. 47,059 Hz D. 94,118 Hz E. none of the above 381 Q6. If the changes described in Q4 and Q5 were made, the reconstructed analog waveform would be ___ relative to the code as originally written. A. lower in amplitude B. less distorted C. more distorted D. higher in amplitude E. none of the above 382 Q7. The change in the reconstructed analog output waveform referred to in Q6 is caused by: A. uniformly sampling both the ATD input and the PWM output B. uniformly sampling the ATD input, but naturally sampling the PWM output C. naturally sampling the ATD input, but uniformly sampling the PWM output D. naturally sampling both the ATD input and the PWM output E. none of the above 383 ...
View Full Document

Ask a homework question - tutors are online