MCP4822 dual 12-bit Digital to Analog Converter (DAC) chip.

Dependents:   ADC2DAC

The MCP4822 is a dual 12-bit Digital to Analog Converter that is controlled via an SPI interface. It is available in PDIP, SOIC or MSOP packages. The documentation for the chip is available at Microchip's MC4822 page.

The range also includes 8 or 10-bit DACs, which this library could easily be converted to.

MCP4822.cpp

Committer:
atyeomans
Date:
2013-03-04
Revision:
3:7484c0fe6f4d
Parent:
2:e60995ceccbd

File content as of revision 3:7484c0fe6f4d:

#include "MCP4822.h"

MCP4822::MCP4822(PinName dataout, PinName clock, PinName chipselect, PinName latch)  :
    cs(chipselect), latchpin(latch), spi(dataout, NC, clock)
      {
    cs = 1;
    latchpin = 1;
    spi.format(16);
}

void MCP4822::setA(float voltage)  {
    setvoltage(voltage);
}

void MCP4822::setB(float voltage)    {
    setvoltage(voltage, true);
}

void MCP4822::set(float voltageA, float voltageB)    {
    setvoltage(voltageA);
    setvoltage(voltageB, true);
}

void MCP4822::setvoltage(float voltage, bool chanB)    {
    int gain = 1;
    if (voltage > 2.048)    {
        gain = 2;
    }
    unsigned int v;
    v = (unsigned int) (voltage * 4096.0 / 2.048 / (float) gain);
    write(chanB, (gain == 1), v);
}

void MCP4822::latch()    {
    latchpin = 0;
    latchpin = 1;
}


void MCP4822::write(bool chanB, bool gain1, unsigned int voltage, bool shutdown)    {
    if (voltage < 4096) {
        int msg = 0x0000;
        if (chanB)  msg |= (0x1 << 15);
        if (gain1)  msg |= (0x1 << 13);
        if (!shutdown)   msg |= (0x1 << 12);
        msg |= voltage; 
        cs = 0;
        spi.write(msg);
        cs = 1;
    }
}

void MCP4822::shutdown()    {
    write(false, false, 0, true);
    write(true, false, 0, true);
}

void MCP4822::shutdownA()   {
    write(false, false, 0, true);
}

void MCP4822::shutdownB()   {
    write(true, false, 0, true);
}

void MCP4822::chipSel(){
    cs = !cs;
}