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.

Revision:
0:74353da3eacd
Child:
2:e60995ceccbd
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MCP4822.cpp	Wed Feb 13 16:08:13 2013 +0000
@@ -0,0 +1,56 @@
+#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);
+}
\ No newline at end of file