CS计算机代考程序代写 DT131B

DT131B
Embedded Systems Programming
Lecture 21-22: Introduction to: 1. Two Wire Interface (TWI/I2C)
2. Analog-to-Digital Conversion . Adapted from Barnett, Cox and O’Cull(2007), Embedded C
Programming and the Atmel AVR.
Dawit Mengistu (dawit.mengistu@hkr.se)

Contents
• Theory of ADC
• Programming the ADC
• Two Wire Interface (TWI or I2C)
2

Analog-to-Digital Conversion (ADC)
3

Data Acquisition Systems
• Areusedtoquantifyandstoredata
• Dedicatedmicroprocessors(microcontroller)based
systems consist of hardware and software to:
– Measure, store, interpret and assist in process control
Transducer
Signal Conditioning
Actuator
ADC
DAC
I/O Ports
Processing
Real World System
4

Analog-to-Digital Converters
• Ananalog-to-digitalconverter(ADCorA2D)isadevice that converts a continuous (analog) quantity to a discrete digital number.
• AnADCusuallyconvertsananalogvoltagetoadigital number proportional to the magnitude of the voltage.
• However, some non-electronic devices, such as rotary encoders, can also be considered ADCs.
• Usedwithtransducers,ADCsallowustomonitorreal- world inputs and perform control operations based on
these inputs.
5

ADC Encoding
• Typically the digital output of an ADC is a 2’s complement binary number that is proportional to the input.
• There are other possibilities, however, such as the Gray code.
• Stepsinanalog-to-digitalconversion: – Sampling and Holding
– Quantization
6

ADC – Sampling
7

ADC-Holding
8

The Sampling Theorem
• Acontinuoussignalcanberepresented completely by a set of instantaneous measurements or samples of its voltage which are made at equal spaced times.
• Theintervalbetweensuchsamplesmustbe less than one-half of the period of the highest-frequency component in the signal in order to reconstructed the original signal from the signals.
9

Sampling Theorem (cont’d)
Let x(t) be an analog signal with frequencies of no more than Fmax .
Then x(t) can be reconstructed exactly from its samples if the sampling rate Fs satisfies:
Fs ≥ 2Fmax.
10

Sample and Hold
12

Resulting Waveform
Analog
Sampled
13

Resulting Waveform (cont’)
Analog
Sample and Hold
14

Realization of ADC
• Different realizations of ADC available. – Single-slope (single ramp) ADC
– Dual-slope ADC
– Successive Approximation
–…
15

Single-Slope ADC
digital output
16

Successive Approx. ADC
digital output
17

Quantization
18

Quntization (cont’)
• Not possible to get an absolutely perfect reproduction of the input signal at the output
• Sampling changes a smooth analogue curve into an approximation composed of steps made up of horizontal and vertical lines
• Superimposing the approximation onto the original curve shows the divergence between them is a maximum at the sharp corners of the steps
19

Quntization (cont’)
• Noise (quantization noise) is introduced from sample voltages
• To lower the quantization noise, the height of the steps should be reduced by increasing the number of voltage levels at which the LSB changes by 1.
• This will require more hardware for the conversion of the voltage samples to digital.
20

ADC Parameters
• Number of bits n: The higher the number of bits, the more precise the digital output.
• Quantisation error Eq: the average difference between the analogue input and the quantized value. The quantization error of an ideal ADC is half of the step size.
• Sample time Tsample: a sampling capacitor must be charged for a duration of Thold before conversion taking place.
• Conversion time Tconv: time taken to convert the voltage on the sampling capacitor to a digital output.
21

Digital-to-Analog Conversion (DAC)
Note: DAC is replaced by PWM in most microcontrollers used for
applications such as motor control, lighting systems, etc.
23

Data Acquisition from Multiple Sources
24

Examples-1
• A digital instrument is required to measure physical quantities with an accuracy of 99%. What is the size of the ADC, assuming that the ADC converts analog voltages in the range 0 – 5V?
• How would your result for the above changes if the desired accuracy is 99.9%?
28

• •
Examples-2
What is the number of ADC bits needed to measure signals with a resolution of 2mv assuming a reference voltage of 5V?
Design an appropriate signal conditioning circuit to measure/digitize the following singnals via a 0 – 5V ADC.
– ADCsource0to+48V
– AnACsourcesuchasthemains(230Vrms)
– Theoutputofathermocouple(0to+32mv)
– Amicrophonewhoseoutputisintherange-25to+25mv.
29

ADC in Microcontrollers
• TheATmegafamilyprocessorshaveabuilt-inADC with the following features
– 10-bitresolution
– 6ormoremultiplexedsingleendedinputchannels
– 0.5LSBintegralnon-linearity
– ±2 LSB absolute accuracy
– 13-260μsconversiontime
– upto15KSPSatmaximumresolution
– 0-VccADCinputvoltagerange
– Selectable2.56VADCreferencevoltage
– LeftadjustmentforDACresultreadout
– Freerunningorsingleconversionmode
– ADCstartconversionbyauto-triggeringoninterruptsources – InterruptonADCconversioncomplete
30

Board Layout (Arduino Uno)
31

Programming the ADC
ADC Multiplexer Selection Register (ADCMUX)
• The ADC needs a reference voltage to work upon. There are three pins used for this purpose (AREF, AVCC and GND).
• We can supply our own reference voltage across AREF and GND or use the internal source VCC. We can also connect a capacitor across AREF pin and ground it to prevent noise.
REFS1
REFS0
ADLAR
MUX4
MUX3
MUX2
MUX1
MUX0
Bits 7:6 (REFS1:REFS0) are used to choose the reference voltage Vref . The following combinations are used:
00 = external reference voltage,
01 =+5v (internal reference, commonly used). 11 = Internal 2.56v
32

Programming the ADC (cont)
• MUX4-0:Selectanaloguechannelandgainselection • Analogueinputvoltagecanbeselectedamong
different pins.
• Differentialinputandcustomgainfactorcanalsobe chosen .
• ADLAR: ADC Left Adjust Result, 1 left adjust the result stored in ADC
ADLAR flag will determine how the 10-bit digital output will be stored in 16-bit output registers (more on this
later).
33

Conversion Interval – prescaler
• The conversion interval of the analog signal into digital is determined by the clock frequency.
• Because the CPU clock frequency is much higher, frequency division must take place with the help of a prescaler.
• A prescaler produces desired frequency from the external higher frequency using predefined division factors – 2, 4, 8, 16, 32, 64, and 128.
– E.g. a prescaler of 64 implies F_ADC = F_CPU/64. For F_CPU = 16MHz, F_ADC = 16M/64 = 250kHz.
• The choice of the prescaler value depends on
– the CPU speed
– the frequency of the signal being measured/sampled
– The accuracy desired. (Note that there is a trade-off between frequency and accuracy; the greater the frequency, the lesser the accuracy and vice-versa.) 34

Prescaler Settings
ADC Control and Status Register: ADCSRA
ADEN
ADSC
ADATE
ADIF
ADIE
ADPS2
ADPS1
ADPS0
ADC Prescaler Selections
35

Programming the ADC (Cont’)
ADC Control and Status Register: ADCSRA
• Bit 7 – ADEN – ADC Enable –enables the ADC feature. Unless this is enabled,
ADC operations cannot take place across PORTA.
• Bit 6 – ADSC – ADC Start Conversion – Write this to ‘1’ before starting any conversion. This 1 is written as long as the conversion is in progress, after which it returns to zero.
• Bit 5 – ADATE – ADC Auto Trigger Enable – Setting it to ‘1’ enables auto- triggering of ADC. ADC is triggered automatically at every rising edge of clock pulse. (ADC unit can operate in two modes: manual or auto-trigger.
ADEN
ADSC
ADATE
ADIF
ADIE
ADPS2
ADPS1
ADPS0
In manual mode, set bit ADSC will start conversion.
In auto-trigger mode, a predefined event will start conversion.
36

Programming the ADC (Cont’)
ADC Control and Status Register (ADCCSRA)
• Bit 4 – ADIF – ADC Interrupt Flag – Whenever a conversion is finished and the registers are updated, this bit is set to ‘1’ automatically. Thus, this is used to check whether the conversion is complete or not.
• Bit 3 – ADIE – ADC Interrupt Enable – When this bit is set to ‘1’, the ADC interrupt is enabled. This is used in the case of interrupt-driven ADC.
ADEN
ADSC
ADATE
ADIF
ADIE
ADPS2
ADPS1
ADPS0
37

Programming the ADC (Cont’)
ADCL and ADCH – ADC Data Registers
• The result of the ADC conversion is stored here.
• Since the ADC has a resolution of 10 bits, it requires 10 bits to store the result. We therefore need two registers – ADCL and ADCH (ADC Low byte and ADC High byte).
• The two can be called together as ADC.
38

Example
Write a program to initialize the appropriate ADC registers and perform analog-to-digital conversion according to the following requirements:
ADC source: channel 0
Reference voltage: AVCC = 5V Alignment: left, top 8-bit in ADCH Auto-trigger: Disable
ADC interrupt: Disable
Prescaler: 2 (fastest conversion)
39

Void initADC() {
// Configure the ADC module
ADMUX = 0b01100000;
// REFS1:0 = 01 -> AVCC as reference, // ADLAR = 1 -> Left adjust
// MUX4:0 = 00000 -> ADC0 as input ADCSRA = 0b10000001;
// ADEN = 1: enable ADC,
// ADSC = 0: don’t start conversion yet // ASPS2:0 = 001: prescaler = 2
// ADATE = 0: disable auto trigger,
// ADIE = 0: disable ADC interrupt
}
Char doconversion (void){
// Start conversion by setting flag ADSC
ADCSRA |= (1 << ADSC); // Wait until conversion is completed while (ADCSRA & (1 << ADSC)){;} // Read the top 8 bits, output to PORTB result = ADCH; return result; } 40 #include int main (void){
unsigned char result;
DDRB = 0xFF; // set port B for output
initADC();
while(1){ // main loop PORTB = doConversion(); }
return 0;
}

What changes are needed to reprogram the previous ADC with interrupt enabled?
Example
#include #include volatile unsigned char result; ISR(ADC_vect){
result = ADCH; // Read the top 8 bits, and store in variable result }
int main (void){
DDRB = 0xFF; // set port B for output
// Configure the ADC module
ADMUX = 0b01100000; // REFS1:0 = 01 -> AVCC as reference, //ADLAR=1->Leftadjust //MUX4:0=00000->ADC0asinput ADCSRA = 0b10001111; // ADEN = 1: enable ADC, //ADSC=0:don’tstartconversionyet //ADATE=0:disableautotrigger, //ADIE = 1: enable ADC interrupt // ASPS2:0 = 002: prescaler = 2 sei(); // enable interrupt system globally
while(1){ // main loop
ADCSRA |= (1 << ADSC); // start a conversion PORTB = ~result; // display on port B } return 0; } 41 Inter Integrated Circuit (I2C) Communication (Also called Two Wire Interface/ TWI) 42 The I2C Bus • A well-known bus commonly used to link micro-controllers with other systems or devices. • Developed by Philips in the mid 1980’s. • The master is usually a microcontroller. • Slaves are often sensors, control units, real-time clocks, etc. Master Device Slave Device Slave Device Slave Device SCL SDL SCL – Clock SDL - Data I2C Basic Characteristics • Two-wired bus • originally to interact within small number of devices (radio/TV tuning, ...) • speeds: – 100kbps(standardmode) – 400kbps(fastmode) – 3.4Mbps(high-speedmode,notavailableonATMega328) • data transfers: serial, 8-bit oriented, bi-directional • master/slave relationships with multi-master option (arbitration) • master can operate as transmitter or receiver • addressing: 7-bit unique addresses (supports up to 128 devices) Masters and Slaves • Masterdevice – controls the SCL – starts and stops data transfer – controls addressing of other devices • Slavedevice – device addressed by master • Transmitter/Receiver – master or slave – master-transmitter sends data to slave-recevier – master-receiver requires data from slave-transmitter I2C Bus Data Transfer • Data bits are transferred after start condition • Transmission is byte oriented • Interrupt supported • byte = 8 bits + one acknowledge bit • Most significant bit (MSB) first • Slave address is also data – firstbytetransferred – duringthefirstbytetransfer: • master is transmitter • addressed slave is receiver – nextbytes:dependsonthelastbitinaddressbyte I2C Bus Wires and Signals • Two-wired bus – serial data line (SDA) – serialclockline(SCL) • Voltage levels – HIGH 1 – LOW 0 • Bit transfer – SCL=1⇒SDA=validdata – oneclockpulseperdatabit – stabledataduringhighclocks – datachangeduringlowclocks Data Transfer - SCL • Master sets SCL = 0 and generates pulse for each data bit • 8 pulses for data bits are followed by one pulse for ack bit • After ack: – mastertriestogeneratenextbyte’sfirstpulse – slavecanholdSCLlow→masterswitchestowaitstate Data Transfer - SDA • Data bits are generated by transmitter as SCL pulses • 9-th pulse: – transmitter releases SDA – receivermustholdSDAlowinordertoack.receiveddata – slavemustreleaseSDAafterack.bit(allowsmastertoendframe) Addressing by 7 bits • The first byte transmitted by master followed by, start condition – 7bits: address – 1 bit: direction (R/W) 0 ... master writes data (W), becomes transmitter 1 ... master reads data (R), becomes receiver • Data transfer terminated by stop condition • Master may generate repeated start and address another device • Each device listens to address – addressmatchesitsown→deviceswitchesstateaccordingtoR/Wbit • Address = fixed part + programmable part – fixedpartassignedbyI2Ccommittee master-transmitter I2C Frame Formats master-receiver (since second byte) Programming I2C The I2C has the following programmable registers: • Bit Rate Register (TWBR): – Controls/sets the SCL period according to the formula: SCL Frequency = CPU Clock Frequency 16 + (2 . TWBRR) (prescaler value) – Prescaler values: 1, 4, 16, 64 • AddressRegister(TWAR): – holds the seven-bit address of a device involved in data transfer (slave transmitter, for ex.) 55 Programming I2C (cont’) • Address/DataShiftRegister(TWDR): – contains the address or data bytes to be transmitted, or the address or data bytes received. • StatusRegister(TWSR): – sets the prescaler for bit rate. – Used to examine status of data transfer (ACK or NACK) – Used by TWI interrupt to inform status • ControlRegister(TWCR) – defines the settings of TWI operations – Used to test the status of TWI operations 56 Example: Master Transmitter 1. TWCR = (1<