9
1 SERIAL PERIPHERAL INTERFACE (SPI) HARDWARE Microcontrollers and Interfacing week 10 exercises 1 Serial Peripheral Interface (SPI) hardware Complex devices (persistent memory and flash memory cards, D/A and A/D converters, real-time clocks, etc.) often have serial connections instead of parallel. They behave a little like a shift register, exchanging parallel information using one or two serial data signals and a clock. The two most common protocols are Inter-Integrated Circuit (I 2 C) and Serial Peripheral Interface (SPI). The simpler (and in many ways the more flexible) of the two is SPI. 1.1 External ADC: MCP3204 To understand how SPI works, let’s increase the resolution of our analogue input by connecting an external analogue-to-digital converter and communicating with it using SPI. A popular device for this is the MCP3204 which has four independent 12-bit ADC channels. V DD (pin 14) 5V power supply DGND (pin 7) 0V digital ground V DD CLK D OUT MCP3204 1 2 3 4 14 13 12 11 10 9 8 5 6 7 V REF D IN CH0 CH1 CH2 CH3 CS /SHDN DGND AGND NC NC AGND (pin 12) 0V analogue ground V REF (pin 13) reference voltage, sets the upper limit of in- put voltage (corresponding to the maximum digital A/D output value) CH03 (pins 1–4) the four analogue input channels CLK (pin 11) SPI serial clock input D IN (pin 9) SPI serial data input (equivalent to MOSI) D OUT (pin 10) SPI serial data output (equivalent to MISO) CS (pin 8) SPI active-low chip select (equivalent to SS) Arduino SCK MOSI MCP3204 MISO SS serial clock master out, slave in master in, slave out slave select (active low) SCK (13) MOSI (11) MISO (12) SS (10) 5V GND DGND AGND V DD CH3 CH2 CH1 CH0 V REF 10k Connect a MCP3204 ADC to the Arduino. Use the following Arduino pins to carry the SPI signals: SPI / Arduino MCP3204 SS pin 10 pin 8 CS MOSI pin 11 pin 9 D IN MISO pin 12 pin 10 D OUT SCK pin 13 pin 11 CLK Be very careful to connect the MCP3204 the correct way around. Like the shift register, if the power is connected backwards the device will be damaged. Create a test voltage using a potentiometer (or a sensor of your choice) and connect it to the first input, CH0. Pin 1 , 1 Ask the instructor to check your work. 1 of 3

Microcontrollers and Interfacing - 立命館大学piumarta/topics4/arduino-lab-10.pdf · Microcontrollers and Interfacing week 10 exercises ... sources to the other ADC input channels

  • Upload
    buithu

  • View
    223

  • Download
    0

Embed Size (px)

Citation preview

1 SERIAL PERIPHERAL INTERFACE (SPI) HARDWARE

Microcontrollers and Interfacingweek 10 exercises

1 Serial Peripheral Interface (SPI) hardwareComplex devices (persistent memory and flash memory cards, D/A and A/D converters, real-time clocks, etc.) often have serialconnections instead of parallel. They behave a little like a shift register, exchanging parallel information using one or two serialdata signals and a clock. The two most common protocols are Inter-Integrated Circuit (I2C) and Serial Peripheral Interface(SPI). The simpler (and in many ways the more flexible) of the two is SPI.

1.1 External ADC: MCP3204To understand how SPI works, let’s increase the resolution of our analogue input byconnecting an external analogue-to-digital converter and communicating with it usingSPI. A popular device for this is the MCP3204 which has four independent 12-bitADC channels.

VDD (pin 14) 5V power supply

DGND (pin 7) 0V digital ground

© 2008 Microchip Technology Inc. DS21298E-page 1

MCP3204/3208

Features• 12-bit resolution• ± 1 LSB max DNL• ± 1 LSB max INL (MCP3204/3208-B)• ± 2 LSB max INL (MCP3204/3208-C)• 4 (MCP3204) or 8 (MCP3208) input channels• Analog inputs programmable as single-ended or

pseudo-differential pairs• On-chip sample and hold• SPI serial interface (modes 0,0 and 1,1)• Single supply operation: 2.7V - 5.5V• 100 ksps max. sampling rate at VDD = 5V• 50 ksps max. sampling rate at VDD = 2.7V• Low power CMOS technology:

- 500 nA typical standby current, 2 µA max.- 400 µA max. active current at 5V

• Industrial temp range: -40°C to +85°C • Available in PDIP, SOIC and TSSOP packages

Applications• Sensor Interface• Process Control• Data Acquisition• Battery Operated Systems

Functional Block Diagram

DescriptionThe Microchip Technology Inc. MCP3204/3208devices are successive approximation 12-bit Analog-to-Digital (A/D) Converters with on-board sample andhold circuitry. The MCP3204 is programmable toprovide two pseudo-differential input pairs or foursingle-ended inputs. The MCP3208 is programmableto provide four pseudo-differential input pairs or eightsingle-ended inputs. Differential Nonlinearity (DNL) isspecified at ±1 LSB, while Integral Nonlinearity (INL) isoffered in ±1 LSB (MCP3204/3208-B) and ±2 LSB(MCP3204/3208-C) versions.

Communication with the devices is accomplished usinga simple serial interface compatible with the SPIprotocol. The devices are capable of conversion ratesof up to 100 ksps. The MCP3204/3208 devices operateover a broad voltage range (2.7V - 5.5V). Low currentdesign permits operation with typical standby andactive currents of only 500 nA and 320 µA,respectively. The MCP3204 is offered in 14-pin PDIP,150 mil SOIC and TSSOP packages. The MCP3208 isoffered in 16-pin PDIP and SOIC packages.

Package Types

Comparator

SampleandHold

12-Bit SAR

DAC

Control Logic

CS/SHDN

VREF

VSSVDD

CLK DOUT

ShiftRegister

CH0

ChannelMux

InputCH1

CH7*

* Note: Channels 5-7 available on MCP3208 Only

DIN

VDD

CLKDOUT

MC

P3204

1234

1413121110

98

567

VREF

DIN

CH0CH1CH2CH3

CS/SHDNDGND

AGND

NC

VDD

CLKDOUT

MC

P3208

1234

161514131211109

5678

VREF

DINCS/SHDNDGND

CH0CH1CH2CH3CH4CH5CH6CH7

NC

AGND

PDIP, SOIC, TSSOP

PDIP, SOIC

2.7V 4-Channel/8-Channel 12-Bit A/D Converterswith SPI Serial Interface

AGND (pin 12) 0V analogue ground

VREF (pin 13) reference voltage, sets the upper limit of in-put voltage (corresponding to the maximum digitalA/D output value)

CH0–3 (pins 1–4) the four analogue input channels

CLK (pin 11) SPI serial clock input

DIN (pin 9) SPI serial data input (equivalent to MOSI)

DOUT (pin 10) SPI serial data output (equivalent to MISO)

CS (pin 8) SPI active-low chip select (equivalent to SS)

Arduino

SCK

MOSI

MCP3204

MISO

SS

serial clock

master out, slave in

master in, slave out

slave select(active low)

SCK (13)

MOSI (11)

MISO (12)

SS (10)

5V

GND

DGND AGND

VDD

CH3

CH2

CH1

CH0

VREF

10k

� Connect a MCP3204 ADC to the Arduino. Use the following Arduino pins to carry the SPI signals:

SPI / Arduino MCP3204SS pin 10→ pin 8 CS

MOSI pin 11→ pin 9 DIN

MISO pin 12→ pin 10 DOUT

SCK pin 13→ pin 11 CLK

Be very careful to connect the MCP3204 thecorrect way around. Like the shift register, if thepower is connected backwards the device will bedamaged.

� Create a test voltage using a potentiometer (or asensor of your choice) and connect it to the firstinput, CH0.

Pin 1

, 1 Ask the instructor to check your work.

1 of 3

2 SPI COMMUNICATION SOFTWARE

2 SPI communication softwareSome microcontrollers (including the Arduino) provide SPI support in hardware. Access to the hardware’s SPI signals is madeavailable through a library. Other microcontrollers do not include harware SPI support, and communicating with SPI devicesrequires manual control of all four SPI signals. We will use both methods to communicate with the MCP3204.

2.1 Using the SPI libraryTo use a library, it is sufficient to include the associated header file at the beginning of the program. We will use the SPI libraryto quickly test our hardware.

� Create a new sketch. Make the SPI library available by in-cluding SPI.h at the beginning.

#include <SPI.h>

The SPI library manages the CLK, MISO and MOSI signals for us. It does not manage the slave select signal, so we will dothat ourselves.

� Create a definition (using #define or const int to as-sociate the symbol SSN (‘slave select, active-low’) with pinnumber 10.

const int SSN = 10; // slave select

� Create a setup() function that performs the following ini-tialisation steps:

1. Start the Serial interface at 9600 baud.

2. Configure the SSN pin as an OUTPUT, and set its valueto inactive.

3. Start the SPI interface using a clock divider of 4, SPImode 0,0, and transfers with most significant bit first.

void setup(){Serial.begin(9600);pinMode(SSN, OUTPUT);digitalWrite(SSN, HIGH); // device inactiveSPI.begin();SPI.setClockDivider(SPI_CLOCK_DIV4); // 4 MHzSPI.setDataMode(SPI_MODE0); // low, leadingSPI.setBitOrder(MSBFIRST);

}

� Create a function int readADC(int channel) that reads and returns a value from the given ADC channel. To readfrom the ADC using SPI, you will have to do the following steps:

1. Turn on the ADC by setting SSN active.

2. Use SPI.transfer() to send (and receive) three bytes from the ADC. The first byte contains five zeros, a start bit 1,and mode bit 1 (single-ended conversion), and the most significant bit of the three-bit channel number. The second bytecontains the least significant two bits of the channel number, followed by 6 zeros. The third byte can contain anything.

3. Collect the values returned by the second and third calls to SPI.transfer(). The least significant four bits of thefirst value are the four most significant bits of the ADC result. The second value contains the eight least significant bitsof the result. Recombine them into a 12-bit result.

4. Turn off the ADC by setting SSN inactive.

5. Return the result from the ADC.

int readADC(unsigned char channel){digitalWrite(SSN, LOW);int adval = 0;SPI.transfer(0b00000110 + ((channel >> 2) & 1));adval = ((unsigned char)SPI.transfer(channel << 6) & 0b00001111) << 8;adval |= ((unsigned char)SPI.transfer(0));digitalWrite(SSN, HIGH);return adval;

}

� Test your sketch with a loop() that prints the results of read-ing channel 0, then pauses for a quarter of a second. (Don’tforget to open the serial monitor to view the output generatedby the sketch.)

void loop(){Serial.println(readADC(0));delay(250);

}

, 2 Ask the instructor to check your work.

2 of 3

2.2 Implementing SPI manually 3 CHALLENGES

2.2 Implementing SPI manuallyLet’s simulate what would be needed on a microcontroller that does not have SPI hardware or a library giving access to it. Thisinvolves driving the SPI slave select, clock and data signals directly using digitalWrite(). (This technique is informallyknown as “bit banging” the interface.)

� Save your sketch from the previous section under a new name. We are going to remove all references to the SPI library andgenerate the necessary SPI signals explicitly.

� Delete the #include <SPI.h> from the beginning of the sketch.

� Keep the defintion for SSN. Add three more definitions for MOSI (pin 11), MISO (pin 12), and SCK (pin 13).

� In setup(), delete the four lines that configure the SPI library. Replace them with code that performs the following actions:

1. Configure MOSI as an OUTPUT.2. Configure MISO as an INPUT.3. Configure SCK as an OUPUT and set it to idle (LOW).

, 3 Ask the instructor to check your work.

� Implement a function void sendBit(int value) that writes the least significant bits of value to the SPI device. Youwill have to perform two steps to do this:

1. Write (using digitalWrite()) the least significant bit (only) of value to MOSI.2. Generate a positive pulse on SCK by setting it HIGH then back to LOW.

� Implement a function int recvBit(void) that reads one bit from the SPI device. You will have to perform four steps todo this:

1. Set SCK active (HIGH) to ensure data is available on MISO.2. Use digitalRead() to obtain the value (0 or 1) of MISO.3. Set SCK inactive (LOW) to end the clock cycle.4. Return the bit that was read from MISO.

, 4 Ask the instructor to check your work.

� Delete the three lines in readADC() that refer to SPI.transfer(). Replace them with code that explicitly initiates aconversion. (Refer to the timing diagram in Appendix B.) Your code will perform the following steps:

1. Use sendBit() to send a 1 (start bit) followed by another 1 (single-ended mode) to the ADC. (We do not need to sendthe initial 5 zeros that were necessary when using the byte-oriented SPI library.)

2. Use sendBit() to write the least significant three bits of channel to the ADC.3. Use sendBit() to write two ‘don’t care’ bits to the ADC.4. Use recvBit() to read 12 bits from the ADC. For each bit read you will have to shift adval one bit left, then add to

it the bit read from the ADC. At the end of this you will have reconstructed the 12 bits of ADC result.5. Return the final value of adval.

Test your code. (You can leave the original loop() unmodified.)

, 5 Ask the instructor to check your work.

3 Challenges� Modify loop() (in either of your sketches) to display the values of all four ADC channels. Connect one or more voltage

sources to the other ADC input channels and verify that the sketch prints the correct results.

, 6 Ask the instructor to check your work.

� Disable (comment out) the Serial.println() and delay() from loop() in your two sketches. Modify loop to per-form many conversions (call readADC() many times). Use millis() to record the time before and after performing theconversions. Calculate how many conversions per second are being peformed.

SPI library conversions per second: Manual SPI conversions per second:

, 7 Ask the instructor to check your work.

� Connect a MCP4288 digital-to-analogue converter and use it to generate a sine wave. (See the appendix for the relevant partsof the data sheet.)

3 of 3

ReferenceA Serial communicationA shift register can convert a single serial signal (containing a fixed-length ‘message’ sequence of N single bits) into N parallelsignals. We can generalise this very simple protocol in several ways:

• connect the serial signal to more than one external converter device,

• send information in both directions (from microcontroller to device, or from device back to microcontroller),

• use variable-length ‘message’ sequences, etc.

Two popular general protocols are the Serial Peripheral Interface (SPI) and Inter-Integrated Circuit (I2C). Both are ‘in-system’ protocols, meant for communication between components within a single piece of equipment.

Useful devices that use these protocols include Electrically-Erasable Programmable Read-Only Memory (EEPROM),Analog-to-Digital Converter (ADC), Digital-to-Analog Converter (DAC), real-time clocks (RTC), various sensors, Liquid Crys-tal Display (LCD) controllers, Secure Digital (SD) memory cards, the SM (system management) bus on Intel motherboards, etc.

A.1 Inter-Integrated Circuit (I2C)I2C was developed in 1982 by Philips Semiconductor to enable communication between digital devices in television sets.

I2C is a bus-based protocol. Up to 127 devices can be connected to the bus, each having a unique 7-bit address. Devicescommunicate by exchanging byte-oriented messages with each other. I2C therefore creates a ‘mini network’, in which sendersand receivers are chosen dynamically according to a relatively complex protocol.

An I2C bus needs just two wires: serial data SDA and serial clock SCL. The bus can be in one of two states, active or idle.When idle, both SDA and SCL are high, and no communication is taking place. When the bus is active, the clock cycles fromhigh to low and back again while serial communication takes place on SDA. During a clock cycle, SDA is permitted to changeonly when SCL is low and must remain stable (for the receiver to sample) when SCL is high.

Any device can initiate a message send by (temporarily) claiming ownership of the I2C bus while the bus is idle. Ownershipis claimed by generating a falling edge on SDA while SCL is high, a condition that should never occur while the bus is active.

bus

idle

busclaimed bit 1 bit 2 bit 3

serial clock SCL

serial data SDA

For the duration of the message exchange, the device that initiates the exchange is called the master and the device respond-ing to the message is the slave. The master controls SCL throughout the message exchange. At various times during a messageexchange, one of these devices is the transmitter and the other is the receiver. The transmitter controls SDA, regardless of whichdevice is the master.

Every byte transmitted is followed by a single-bit acknowledgement from the destination device. Nine bits of data aretherefore exchanged for each byte of data transmitted, with the receiver controlling the final acknowledgement bit.

bit 1 bit 2 bit 3 bit 4 bit 5 bit 6 bit 7 bit 8

ack

serial clock SCL

transmitter SDA

receiver SDA

At the end of data transfer, the master releases the bus by generating a rising edge on SDA while SCL is high, which (again)is a condition that never occurs while the bus is active.

bit 7 bit 8 (ack) bus

release

bus idleserial clock SCL

transmitter SDA

Each message begins with the master transmitting a byte containing seven address bits and one R/W ‘direction’ bit. Thedirection bit indicates if the master is writing to the slave or reading from it. The slave sends back a single bit acknowledgingthe receipt of the message. Master and slave then exchange an arbitrary number of data bytes, in the direction specified by thedirection bit.

SDA (bus claim)

seven-bit slave address R/W ack 1× slave address and direction byteeight data bits ack N× data bytes

SDA (bus release)

I2C permits two devices to communicate with each other in both directions, but only in one direction at a time (for a givenmessage). It is therefore a half-duplex protocol. I2C has relatively low performance, with typical maximum clock speeds of100 kHz or 400 kHz. It is particularly good for configuring and monitoring devices that have control registers and/or statusregisters.

1

A.2 Serial Peripheral Interface (SPI)SPI was developed by Motorola in 1985 for communication between a mi-crocontroller (originally the M68HC11) and its external devices.

SPI is a point-to-point protocol. It connects a single master device toone or more slave devices. The slave devices have no address, but each onehas an active-low ‘slave select’ (SS) input. When SS is inactive (high), theslave device ignores its other SPI input signals and disables its SPI output (bymaking it high-impedance). This allows several slaves to share a single SPIconnection, but only one of them can be active at a given time. The lack ofaddressing makes SPI a relatively simple protocol.

SCK

MOSI

master

MISO

SS

SCK

MOSI

slave

MISO

SS

serial clock

master out, slave in

master in, slave out

slave select(active low)

SPI needs four wires: an active-low slave select SS, a serial clock SCK and two uni-directional data signals, master-out/slave-in MOSI and master-in/slave-out MISO. Several different conventions are possible for clocking, but the most usual is‘mode 0,0’ in which the clock idles low (polarity 0) and received data signals are sampled on the leading (positive) edge of theclock signal (phase 0).

polarity 0 = idle low

phase 0 = leading edge

serial clock SCK

slave select SS

master out MOSI msb ... ... ... lsb

master in MISO msb ... ... ... lsb

SPI clock mode clock active(phase,polarity) idles edge

0,0 low leading (rising)0,1 low trailing (falling)1,0 high leading (falling)1,1 high trailing (rising)

When using multiple slaves, each slave requires its own separate SS signal. SPI therefore requires 3 +N wires to commu-nicate with N slave devices.

SCK

MOSI

master

MISO

SS0

serial clock

master out, slave in

master in, slave out

slave selects

SCK

MOSI

slave 0

MISO

SS

SCK

MOSI

slave 1

MISO

SS

SCK

MOSI

slave 2

MISO

SS

SCK

MOSI

slave 3

MISO

SS

SS1

SS2

SS3

If N is large then the number of outputs required to generate the SS sig-nals can be reduced using a serial to parallel converter (shift register) or abinary decoder. (A binary decoder has N inputs, representing a N -bit bi-nary numeric value, and 2N outputs of which only one is active at any time,selected according to the numeric value of the input number. It effectivelyconverts a N -bit ‘address’ into N individual ‘chip select’ signals.)

SPI permits the master and slave to exchange information in both direc-tions at the same time. It is therefore a full-duplex protocol. SPI has relativelyhigh performance, with typical maximum clock frequencies of 20–30MHz(fast enough to transmit high-definition multi-channel audio, for example).It is particularly good for transferring streams of data, for example betweena microcontroller and an external analogue-to-digital or digital-to-analogueconverter.

SCK

MOSI

MISO

D0

serial clock

master out, slave in

master in, slave out

D1

N to 2N

binarydecoder

0

1

2

3

N0

N1

SS0

SS1

SS2

SS3

slave selectsslave number

2

B MCP3204: 4-channel 12-bit A/D converter with SPIThe 10-bit ADC on the Arduino can be too limited for some applications. Increasing the resolution to 12 bits is easy using anexternal ADC. (Higher resolution ADCs are available, but beyond 14 bits or so it becomes quite difficult to design and buildcircuits with low enough noise to make the extra bits useful.)

A popular device is the MCP3204, containing 4 separate 12-bit A/D converters. The maximum clock frequency is 2MHz,or a maximum conversion rate of approximately 100,000 samples per second.

VDD 5V power supply

DGND 0V digital ground

AGND 0V analogue ground

VREF reference voltage, sets the upper limit of input voltage (corresponding to themaximum digital A/D output value)

CH0–CH4 the four analogue input channels

CLK SPI serial clock input

DIN SPI serial data input (equivalent to MOSI)

DOUT SPI serial data output (equivalent to MISO)

CS SPI active-low chip select (equivalent to SS)

© 2008 Microchip Technology Inc. DS21298E-page 1

MCP3204/3208

Features• 12-bit resolution• ± 1 LSB max DNL• ± 1 LSB max INL (MCP3204/3208-B)• ± 2 LSB max INL (MCP3204/3208-C)• 4 (MCP3204) or 8 (MCP3208) input channels• Analog inputs programmable as single-ended or

pseudo-differential pairs• On-chip sample and hold• SPI serial interface (modes 0,0 and 1,1)• Single supply operation: 2.7V - 5.5V• 100 ksps max. sampling rate at VDD = 5V• 50 ksps max. sampling rate at VDD = 2.7V• Low power CMOS technology:

- 500 nA typical standby current, 2 µA max.- 400 µA max. active current at 5V

• Industrial temp range: -40°C to +85°C • Available in PDIP, SOIC and TSSOP packages

Applications• Sensor Interface• Process Control• Data Acquisition• Battery Operated Systems

Functional Block Diagram

DescriptionThe Microchip Technology Inc. MCP3204/3208devices are successive approximation 12-bit Analog-to-Digital (A/D) Converters with on-board sample andhold circuitry. The MCP3204 is programmable toprovide two pseudo-differential input pairs or foursingle-ended inputs. The MCP3208 is programmableto provide four pseudo-differential input pairs or eightsingle-ended inputs. Differential Nonlinearity (DNL) isspecified at ±1 LSB, while Integral Nonlinearity (INL) isoffered in ±1 LSB (MCP3204/3208-B) and ±2 LSB(MCP3204/3208-C) versions.

Communication with the devices is accomplished usinga simple serial interface compatible with the SPIprotocol. The devices are capable of conversion ratesof up to 100 ksps. The MCP3204/3208 devices operateover a broad voltage range (2.7V - 5.5V). Low currentdesign permits operation with typical standby andactive currents of only 500 nA and 320 µA,respectively. The MCP3204 is offered in 14-pin PDIP,150 mil SOIC and TSSOP packages. The MCP3208 isoffered in 16-pin PDIP and SOIC packages.

Package Types

Comparator

SampleandHold

12-Bit SAR

DAC

Control Logic

CS/SHDN

VREF

VSSVDD

CLK DOUT

ShiftRegister

CH0

ChannelMux

InputCH1

CH7*

* Note: Channels 5-7 available on MCP3208 Only

DIN

VDD

CLKDOUT

MC

P3204

1234

1413121110

98

567

VREF

DIN

CH0CH1CH2CH3

CS/SHDNDGND

AGND

NC

VDD

CLKDOUT

MC

P3208

1234

161514131211109

5678

VREF

DINCS/SHDNDGND

CH0CH1CH2CH3CH4CH5CH6CH7

NC

AGND

PDIP, SOIC, TSSOP

PDIP, SOIC

2.7V 4-Channel/8-Channel 12-Bit A/D Converterswith SPI Serial Interface

To perform an A/D conversion, the number of the channel to be read is clocked into the device via MOSI as a five-bitvalue: a single ‘start bit’ (high), a single bit to select single-ended or differential mode, followed by three bits of binary channelnumber (for protocol compatibility with the MCP3208, which has eight input channels). The device then begins the requestedconversion. Two clock cycles later it provides the result of the conversion on MISO as a 13-bit value, as one leading zero bitfollowed by the 12 result bits. The 12 bits of converted value are therefore sent back to the master device beginning three clockcycles after the address has been supplied, or seven cycles after the start bit was written.

© 2008 Microchip Technology Inc. DS21298E-page 21

MCP3204/3208

6.0 APPLICATIONS INFORMATION

6.1 Using the MCP3204/3208 with Microcontroller (MCU) SPI Ports

With most microcontroller SPI ports, it is required tosend groups of eight bits. It is also required that themicrocontroller SPI port be configured to clock out dataon the falling edge of clock and latch data in on therising edge. Because communication with theMCP3204/3208 devices may not need multiples ofeight clocks, it will be necessary to provide more clocksthan are required. This is usually done by sending‘leading zeros’ before the start bit. As an example,Figure 6-1 and Figure 6-2 illustrate how the MCP3204/3208 can be interfaced to a MCU with a hardware SPIport. Figure 6-1 depicts the operation shown in SPIMode 0,0, which requires that the SCLK from the MCUidles in the ‘low’ state, while Figure 6-2 shows thesimilar case of SPI Mode 1,1, where the clock idles inthe ‘high’ state.

As is shown in Figure 6-1, the first byte transmitted tothe A/D converter contains five leading zeros beforethe start bit. Arranging the leading zeros this wayallows the output 12 bits to fall in positions easilymanipulated by the MCU. The MSB is clocked out ofthe A/D converter on the falling edge of clock number12. Once the second eight clocks have been sent to thedevice, the MCU’s receive buffer will contain threeunknown bits (the output is at high impedance for thefirst two clocks), the null bit and the highest order fourbits of the conversion. Once the third byte has beensent to the device, the receive register will contain thelowest order eight bits of the conversion results.Employing this method ensures simpler manipulationof the converted data.

Figure 6-2 shows the same thing in SPI Mode 1,1,which requires that the clock idles in the high state. Aswith mode 0,0, the A/D converter outputs data on thefalling edge of the clock and the MCU latches data fromthe A/D converter in on the rising edge of the clock.

FIGURE 6-1: SPI Communication using 8-bit segments (Mode 0,0: SCLK idles low).

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

CS

SCLK

DIN

X = “Don’t Care” Bits

17 18 19 20 21 22 23 24

DOUT

NULLBIT B11 B10 B9 B8 B7 B6 B5 B4 B3 B2 B1 B0HI-Z

MCU latches data from A/D

Data is clocked out of A/Dconverter on falling edges

converter on rising edges of SCLK

DO Don’t CareSGL/DIFF

D1D2Start

0 0 0 0 0 1 X X X X XDO X X X X X X X X

B7 B6 B5 B4 B3 B2 B1 B0B11 B10 B9 B80? ? ? ? ? ? ? ? ? ? ?

D1D2SGL/DIFF

StartBit

(Null)

MCU Transmitted Data(Aligned with fallingedge of clock)

MCU Received Data(Aligned with risingedge of clock)

X

Data stored into MCU receiveregister after transmission of first8 bits

Data stored into MCU receiveregister after transmission ofsecond 8 bits

Data stored into MCU receiveregister after transmission of last8 bits

Don’t Care

0 0 0 0 0 1 X X X X XDO X X X X X X X X

B7 B6 B5 B4 B3 B2 B1 B0B11 B10 B9 B80? ? ? ? ? ? ? ? ? ? ?

D1D2SGL/DIFF

(Null)

X

23

B1

X

When communicating over SPI one byte at a time (with the Arduino SPI library, for example) three bytes of data mustbe exchanged to initiate the conversion and then read back the result. From sending the start bit to receiving the last bit ofconverted result is a total of 19 clock cycles. Sending five zero bits before the start will therefore conveniently right-justify theresult in the last 12 bits of the 24 that are read back.

3

C MCP4288: 2-channel 12-bit D/A converter with SPI

¤ 2

010

Mic

roch

ip T

echn

olog

y In

c.D

S22

249A

-pag

e 1

MC

P48

02/4

812/

4822

Feat

ures

•M

CP

4802

: Dua

l 8-B

it Vo

ltage

Out

put D

AC

•M

CP

4812

: Dua

l 10-

Bit

Volta

ge O

utpu

t DA

C•

MC

P48

22: D

ual 1

2-B

it Vo

ltage

Out

put D

AC

•R

ail-t

o-R

ail O

utpu

t•

SP

I Int

erfa

ce w

ith 2

0M

Hz

Clo

ck S

uppo

rt•

Sim

ulta

neou

s La

tchi

ng o

f the

Dua

l DA

Cs

with

LD

AC

pin

•Fa

st S

ettli

ng T

ime

of 4

.5µs

•S

elec

tabl

e U

nity

or 2

x G

ain

Out

put

•2.

048V

Inte

rnal

Vol

tage

Ref

eren

ce•

50pp

m/°

C V

RE

F Te

mpe

ratu

re C

oeffi

cien

t•

2.7V

to 5

.5V

Sin

gle-

Sup

ply

Ope

ratio

n•

Ext

ende

d Te

mpe

ratu

re R

ange

:-40

°C to

+12

5°C

App

licat

ions

•S

et P

oint

or O

ffset

Trim

min

g•

Sen

sor C

alib

ratio

n•

Pre

cisi

on S

elec

tabl

e Vo

ltage

Ref

eren

ce•

Por

tabl

e In

stru

men

tatio

n (B

atte

ry-P

ower

ed)

•C

alib

ratio

n of

Opt

ical

Com

mun

icat

ion

Dev

ices

Des

crip

tion

The

MC

P480

2/48

12/4

822

devi

ces

are

dual

8-b

it, 1

0-bi

tan

d 12

-bit

buffe

red

volta

ge o

utpu

t D

igita

l-to-

Anal

ogC

onve

rters

(D

ACs)

, re

spec

tivel

y. T

he d

evic

es o

pera

tefro

m a

sin

gle

2.7V

to 5

.5V

supp

ly w

ith S

PI c

ompa

tible

Seria

l Per

iphe

ral I

nter

face

. Th

e de

vice

s ha

ve a

hig

h pr

ecis

ion

inte

rnal

vol

tage

refe

renc

e (V

RE

F =

2.04

8V).

The

user

can

con

figur

e th

efu

ll-sc

ale

rang

e of

the

devi

ce to

be

2.04

8V o

r 4.0

96V

by

setti

ng th

e G

ain

Sele

ctio

n O

ptio

n bi

t (ga

in o

f 1 o

f 2).

Each

D

AC

chan

nel

can

be

oper

ated

in

A

ctiv

e or

Shut

dow

n m

ode

indi

vidu

ally

by

setti

ng th

e C

onfig

urat

ion

regi

ster

bits

. In

Shu

tdow

n m

ode,

mos

t of

the

inte

rnal

circ

uits

in th

e sh

utdo

wn

chan

nel a

re tu

rned

off

for p

ower

savi

ngs

and

the

outp

ut a

mpl

ifier

is c

onfig

ured

to p

rese

nta

know

n hi

gh re

sist

ance

out

put l

oad

(500

k:�t

ypic

al�.

The

devi

ces

incl

ude

doub

le-b

uffe

red

regi

ster

s,al

low

ing

sync

hron

ous

upda

tes

of t

wo

DA

C o

utpu

tsus

ing

the

LDA

C p

in. T

hese

dev

ices

als

o in

corp

orat

e a

Pow

er-o

n R

eset

(PO

R) c

ircui

t to

ensu

re re

liabl

e po

wer

-up

.Th

e de

vice

s ut

ilize

a r

esis

tive

strin

g ar

chite

ctur

e, w

ithits

inh

eren

t ad

vant

ages

of

low

DN

L er

ror,

low

rat

iom

etric

tem

pera

ture

coe

ffici

ent

and

fast

set

tling

tim

e.Th

ese

devi

ces

are

spec

ified

ov

er

the

exte

nded

tem

pera

ture

rang

e (+

125°

C).

The

devi

ces

prov

ide

high

acc

urac

y an

d lo

w n

oise

perfo

rman

ce f

or c

onsu

mer

and

indu

stria

l app

licat

ions

whe

re c

alib

ratio

n or

com

pens

atio

n of

sig

nals

(suc

h as

tem

pera

ture

, pre

ssur

e an

d hu

mid

ity) a

re re

quire

d.

The

MC

P48

02/4

812/

4822

dev

ices

are

ava

ilabl

e in

the

PD

IP, S

OIC

and

MS

OP

pac

kage

s.

Pac

kage

Typ

es

Rel

ated

Pro

duct

s(1)

P/N

DA

C

Res

olut

ion

No.

of

Cha

nnel

s

Volta

ge

Ref

eren

ce(V

RE

F)

MC

P48

018

1

Inte

rnal

(2.0

48V

)

MC

P48

1110

1M

CP

4821

121

MC

P48

028

2M

CP

4812

102

MC

P48

2212

2M

CP

4901

81

Ext

erna

l

MC

P49

1110

1M

CP

4921

121

MC

P49

028

2M

CP

4912

102

MC

P49

2212

2N

ote

1:Th

e pr

oduc

ts l

iste

d he

re h

ave

sim

ilar

AC

/DC

per

form

ance

s.

MCP48X2

8-P

in P

DIP

, SO

IC, M

SO

P

1 2 3 4

8 7 6 5

CS

SC

K

SD

I

VD

D

VSS

VO

UTA

VO

UTB

LDA

C

MC

P48

02: 8

-bit

dual

DA

CM

CP

4812

: 10-

bit d

ual D

ACM

CP

4822

: 12-

bit d

ual D

AC

8/10

/12-

Bit

Dua

l Vol

tage

Out

put D

igita

l-to-

Ana

log

Con

vert

erw

ith In

tern

al V

RE

F an

d SP

I Int

erfa

ce

¤ 2

010

Mic

roch

ip T

echn

olog

y In

c.D

S22

249A

-pag

e 15

MC

P48

02/4

812/

4822

3.0

PIN

DE

SC

RIP

TIO

NS

The

desc

riptio

ns o

f the

pin

s ar

e lis

ted

in T

able

3-1.

3.1

Sup

ply

Volta

ge P

ins

(VD

D, V

SS)

VD

D is

the

posi

tive

supp

ly v

olta

ge in

put p

in. T

he in

put

supp

ly v

olta

ge is

rel

ativ

e to

VS

S a

nd c

an r

ange

fro

m2.

7V to

5.5

V. T

he p

ower

sup

ply

at th

e V D

D p

in s

houl

dbe

as

clea

n as

pos

sibl

e fo

r a g

ood

DA

C p

erfo

rman

ce.

It is

rec

omm

ende

d to

use

an

appr

opria

te

bypa

ssca

paci

tor

of a

bout

0.1

µF (

cera

mic

) to

gro

und.

An

addi

tiona

l 10

µF c

apac

itor (

tant

alum

) in

para

llel i

s al

sore

com

men

ded

to

furth

er

atte

nuat

e hi

gh-fr

eque

ncy

nois

e pr

esen

t in

appl

icat

ion

boar

ds.

VSS

is th

e an

alog

gro

und

pin

and

the

curr

ent r

etur

n pa

thof

the

devi

ce. T

he u

ser m

ust c

onne

ct th

e V S

S p

in to

agr

ound

pla

ne th

roug

h a

low

-impe

danc

e co

nnec

tion.

Ifan

ana

log

grou

nd p

ath

is a

vaila

ble

in t

he a

pplic

atio

nP

rinte

d C

ircui

t Boa

rd (P

CB

), it

is h

ighl

y re

com

men

ded

that

the

VS

S pi

n be

tied

to th

e an

alog

gro

und

path

or

isol

ated

with

in a

n an

alog

gro

und

plan

e of

the

circ

uit

boar

d.

3.2

Chi

p S

elec

t (C

S)

CS

is

the

Chi

p S

elec

t in

put

pin,

whi

ch r

equi

res

anac

tive-

low

to e

nabl

e se

rial c

lock

and

dat

a fu

nctio

ns.

3.3

Ser

ial C

lock

Inpu

t (S

CK

)

SC

K is

the

SP

I com

patib

le s

eria

l clo

ck in

put p

in.

3.4

Ser

ial D

ata

Inpu

t (S

DI)

SD

I is

the

SP

I com

patib

le s

eria

l dat

a in

put p

in.

3.5

Latc

h D

AC

Inpu

t (LD

AC

)

LDA

C (l

atch

DA

C s

ynch

roni

zatio

n in

put)

pin

is u

sed

totra

nsfe

r the

inpu

t lat

ch re

gist

ers

to th

eir c

orre

spon

ding

DA

C re

gist

ers

(out

put l

atch

es, V

OU

T). W

hen

this

pin

islo

w, b

oth

VO

UTA

and

VO

UTB

are

upd

ated

at t

he s

ame

time

with

thei

r inp

ut re

gist

er c

onte

nts.

Thi

s pi

n ca

n be

tied

to lo

w (

VS

S)

if th

e V

OU

T up

date

is d

esire

d at

the

risin

g ed

ge o

f the

CS

pin

. Thi

s pi

n ca

n be

driv

en b

y an

exte

rnal

con

trol d

evic

e su

ch a

s an

MC

U I/

O p

in.

3.6

Ana

log

Out

puts

(VO

UTA

, VO

UTB

)

VO

UTA

is th

e D

AC

A o

utpu

t pin

, and

VO

UTB

is th

e D

AC

B o

utpu

t pin

. Eac

h ou

tput

has

its

own

outp

ut a

mpl

ifier

.Th

e fu

ll-sc

ale

rang

e of

th

e D

AC

ou

tput

is

fro

mV

SS

toG

* V

RE

F, w

here

G is

the

gai

n se

lect

ion

optio

n(1

x or

2x)

. Th

e D

AC

ana

log

outp

ut c

anno

t go

hig

her

than

the

supp

ly v

olta

ge (V

DD

).

TAB

LE 3

-1:

PIN

FU

NC

TIO

N T

AB

LE F

OR

MC

P48

02/4

812/

4822

MC

P48

02/4

812/

4822

Sym

bol

Des

crip

tion

MS

OP,

PD

IP, S

OIC

1V

DD

Sup

ply

Volta

ge In

put (

2.7V

to 5

.5V

)2

CS

Chi

p S

elec

t Inp

ut3

SC

KS

eria

l Clo

ck In

put

4S

DI

Ser

ial D

ata

Inpu

t5

LDA

CS

ynch

roni

zatio

n In

put.

This

pin

is u

sed

to tr

ansf

er D

AC

set

tings

(In

put R

egis

ters

) to

the

outp

ut re

gist

ers

(VO

UT)

6V

OU

TBD

AC

B O

utpu

t7

VS

SG

roun

d re

fere

nce

poin

t for

all

circ

uitry

on

the

devi

ce8

VO

UTA

DA

CA O

utpu

t

4

MC

P480

2/48

12/4

822

DS

2224

9A-p

age

22¤

201

0 M

icro

chip

Tec

hnol

ogy

Inc.

REG

ISTE

R 5

-1:

WR

ITE

CO

MM

AN

D R

EGIS

TER

FO

R M

CP4

822

(12-

BIT

DA

C)

REG

ISTE

R 5

-2:

WR

ITE

CO

MM

AN

D R

EGIS

TER

FO

R M

CP4

812

(10-

BIT

DA

C)

REG

ISTE

R 5

-3:

WR

ITE

CO

MM

AN

D R

EGIS

TER

FO

R M

CP4

802

(8-B

IT D

AC

)

Whe

re:

W-x

W-x

W-x

W-0

W-x

W-x

W-x

W-x

W-x

W-x

W-x

W-x

W-x

W-x

W-x

W-x

A/B

—G

AS

HD

ND

11D

10D

9D

8D

7D

6D

5D

4D

3D

2D

1D

0bi

t 15

bit 0

W-x

W-x

W-x

W-0

W-x

W-x

W-x

W-x

W-x

W-x

W-x

W-x

W-x

W-x

W-x

W-x

A/B

—G

AS

HD

ND

9D

8D

7D

6D

5D

4D

3D

2D

1D

0x

xbi

t 15

bit 0

W-x

W-x

W-x

W-0

W-x

W-x

W-x

W-x

W-x

W-x

W-x

W-x

W-x

W-x

W-x

W-x

A/B

—G

AS

HD

ND

7D

6D

5D

4D

3D

2D

1D

0x

xx

xbi

t 15

bit 0

bit 1

5A

/B: D

AC

A o

r DA

CB S

elec

tion

bit

1 =

Writ

e to

DA

CB

0 =

Writ

e to

DA

CA

bit 1

4

Don

’t C

are

bit 1

3G

A: O

utpu

t Gai

n S

elec

tion

bit

1 =

1x (V

OU

T =

VR

EF

* D

/409

6)0

=2x

(VO

UT

= 2

* V

RE

F *

D/4

096)

, w

here

inte

rnal

VR

EF

= 2.

048V

.bi

t 12

SHD

N: O

utpu

t Shu

tdow

n C

ontro

l bit

1 =

Act

ive

mod

e op

erat

ion.

VO

UT

is a

vaila

ble.

� 0

=S

hutd

own

the

sele

cted

DA

C c

hann

el. A

nalo

g ou

tput

is n

ot a

vaila

ble

at th

e ch

anne

l tha

t was

shu

t dow

n.

V

OU

T pi

n is

con

nect

ed to

500

k:��t

ypic

al)�

bit 1

1-0

D11

:D0:

DA

C In

put D

ata

bits

. Bit

x is

igno

red.

Lege

ndR

= R

eada

ble

bit

W =

Writ

able

bit

U =

Uni

mpl

emen

ted

bit,

read

as

‘0’

-n =

Val

ue a

t PO

R1

= bi

t is

set

0 =

bit i

s cl

eare

dx

= bi

t is

unkn

own

¤ 2

010

Mic

roch

ip T

echn

olog

y In

c.D

S22

249A

-pag

e 23

MC

P480

2/48

12/4

822

FIG

UR

E 5-

1:W

rite

Com

man

d fo

r MC

P48

22 (1

2-bi

t DA

C).

FIG

UR

E 5-

2:W

rite

Com

man

d fo

r MC

P48

12 (1

0-bi

t DA

C).

FIG

UR

E 5-

3:W

rite

Com

man

d fo

r MC

P48

02 (8

-bit

DA

C).

SD

I

SC

K

CS

02

1

A/B

—G

AS

HD

ND

11D

10

conf

ig b

its12

dat

a bi

ts

LDA

C

34

D9

56

7 D8

D7

D6

89

1012

D5

D4

D3

D2

D1

D0

1113

1415

VO

UT

(Mod

e 1,

1)

(Mod

e 0,

0)

SD

I

SC

K

CS

02

1

A/B

—G

AS

HD

N D

9 D

8

conf

ig b

its12

dat

a bi

ts

LDA

C

34

D7

56

7 D6

D5

D4

89

1012

D3

D2

D1

D0

X X

1113

1415

VO

UT

(Mod

e 1,

1)

(Mod

e 0,

0)

Not

e:X

= “d

on’t

care

” bits

.

SD

I

SC

K

CS

02

1

A/B

—G

AS

HD

N

conf

ig b

its12

dat

a bi

ts

LDA

C

34

56

7

XD

7D

6

89

1012

D5

D4

D3

D2

D1

D0

1113

1415

VO

UT

(Mod

e 1,

1)

(Mod

e 0,

0)

XX

X

Not

e:X

= “d

on’t

care

” bits

.

5

D Week 10 — example solution to ‘bit banging’ exercise

#define SSN 10 // slave select pin#define MOSI 11 // master out pin#define MISO 12 // master in pin#define SCK 13 // serial clock pin

void setup(){Serial.begin(9600);pinMode(SSN, OUTPUT);digitalWrite(SSN, HIGH); // slave select inactivepinMode(MOSI, OUTPUT);pinMode(MISO, INPUT);pinMode(SCK, OUTPUT);digitalWrite(SCK, LOW); // clock idle

}

void sendBit(unsigned char bit){digitalWrite(MOSI, bit & 1); // value to writedigitalWrite(SCK, HIGH); // clock data into devicedigitalWrite(SCK, LOW); // clock idle

}

int recvBit(void){digitalWrite(SCK, HIGH); // clock don’t care bit into deviceint bit = digitalRead(MISO); // result bit from devicedigitalWrite(SCK, LOW); // clock idlereturn bit;

}

int readADC(int channel){digitalWrite(SSN, LOW); // slave select active

sendBit(1); // start bitsendBit(1); // single-ended modesendBit(channel >> 2);sendBit(channel >> 1);sendBit(channel);sendBit(0); // discard empty result bitsendBit(0); // discard null result bit

int advalue = 0;for (int i= 0; i < 12; ++i)advalue = (advalue << 1) + recvBit();

digitalWrite(SSN, HIGH); // slave select inactive

return advalue;}

void loop(){Serial.println(readADC(0));delay(250);

}

6