MCP4822 dual 12-bit Digital to Analog Converter (DAC) chip.
Embed:
(wiki syntax)
Show/hide line numbers
MCP4822.cpp
00001 #include "MCP4822.h" 00002 00003 MCP4822::MCP4822(PinName dataout, PinName clock, PinName chipselect, PinName latch) : 00004 cs(chipselect), latchpin(latch), spi(dataout, NC, clock) 00005 { 00006 cs = 1; 00007 latchpin = 1; 00008 spi.format(16); 00009 } 00010 00011 void MCP4822::setA(float voltage) { 00012 setvoltage(voltage); 00013 } 00014 00015 void MCP4822::setB(float voltage) { 00016 setvoltage(voltage, true); 00017 } 00018 00019 void MCP4822::set(float voltageA, float voltageB) { 00020 setvoltage(voltageA); 00021 setvoltage(voltageB, true); 00022 } 00023 00024 void MCP4822::setvoltage(float voltage, bool chanB) { 00025 int gain = 1; 00026 if (voltage > 2.048) { 00027 gain = 2; 00028 } 00029 unsigned int v; 00030 v = (unsigned int) (voltage * 4096.0 / 2.048 / (float) gain); 00031 write(chanB, (gain == 1), v); 00032 } 00033 00034 void MCP4822::latch() { 00035 latchpin = 0; 00036 latchpin = 1; 00037 } 00038 00039 00040 void MCP4822::write(bool chanB, bool gain1, unsigned int voltage, bool shutdown) { 00041 if (voltage < 4096) { 00042 int msg = 0x0000; 00043 if (chanB) msg |= (0x1 << 15); 00044 if (gain1) msg |= (0x1 << 13); 00045 if (!shutdown) msg |= (0x1 << 12); 00046 msg |= voltage; 00047 cs = 0; 00048 spi.write(msg); 00049 cs = 1; 00050 } 00051 } 00052 00053 void MCP4822::shutdown() { 00054 write(false, false, 0, true); 00055 write(true, false, 0, true); 00056 } 00057 00058 void MCP4822::shutdownA() { 00059 write(false, false, 0, true); 00060 } 00061 00062 void MCP4822::shutdownB() { 00063 write(true, false, 0, true); 00064 } 00065 00066 void MCP4822::chipSel(){ 00067 cs = !cs; 00068 }
Generated on Thu Jul 21 2022 04:01:51 by 1.7.2