Datasheet
Chapter 7. The I
2
C Device Routines
28
Since the DAC is a relatively simple device, using the routine is quite straightforward. Although the
MCP4726 includes a number of other features like RAM & EEPROM[MCP6], what the designer generally
wants from a DAC is to output a specific voltage. The MCP4726write() function provides that capability.
In order to use any of the I
2
C routines, the user must include i2c.h and the header file for the particular
device, in this case, MCP4726.h.
#include "../include/i2c.h"
#include "../include/MCP4726.h"
Before using any of the device routines, the I
2
C peripheral must be initialized. The function InitI2C()
performs this initialization. The function sets the peripheral to master, establishes the baud rate, and sets
reasonable defaults for a number of I
2
C parameters.
InitI2C();
This need be done only once.
All that remains, then, is to write the data to the DAC. The MCP4726write() function takes two
parameters, the address of the device and the value to be written. The MCP4726 is a 12-bit DAC, so the
value is a 12 bit value.
MCP4726write( 0x60, nValue );
Typically, the developer will want to write some fraction of "full scale" to the DAC, but it is possible that
a specific voltage is desired. When presented with a value of 4095, the DAC will output the reference
voltage, typically 5V. With a zero the device will output zero volts. Thus, if a 2048 is entered, the DAC will
deliver 2.5 volts. If speed is not a concern, then, the code might look something like:
/* Voltage fVolts from previous calculation */
fDACvalue = (fVolts / 5.0) * 4095.0;
nDACvalue = (int)fDACvalue;
MCP4726write( 0x60, nDACvalue );
or more directly:
MCP4726write( DACADDR, (int)((fVolts / 5.0) * 4095.0) );
The floating point library is large and slow, so the programmer may prefer to stick with integers. In this
case, it is important to avoid overflow in the calculations. While the DAC value may easily fit in an integer,
an integer voltage would have low resolution, and multiplying millivolts by 4095 will often result in an
integer overflow. The solution is to force the compiler to use long values for the intermediate calculations:
/* Voltage nMillivolts from previous calculation */
nDACvalue = (int)( (long)nMillivolts * 4095L / 5000L );
MCP4726write( 0x60, nDACvalue );
7.3. Using the MCP23008 I/O Expander