Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependents: Cube_Mini_Template
mcp4725.cpp
00001 #include "mcp4725.h" 00002 #include "mbed.h" 00003 00004 MCP4725::MCP4725(PinName sda, PinName scl, BusFrequency bus_frequency, int device_address_bits): _i2c_interface(sda, scl) 00005 { 00006 //Set the frequency 00007 int freq=0; 00008 switch(bus_frequency) 00009 { 00010 case Standard100kHz: 00011 freq = 100000; 00012 break; 00013 case Fast400kHz: 00014 freq = 400000; 00015 break; 00016 case HighSpeed3_4Mhz: 00017 freq = 3400000; 00018 break; 00019 } 00020 _i2c_interface.frequency(freq); 00021 00022 // Assemble the full I2C device address. 00023 _device_address = 0xC0; // Prime the full device address with the device code. 00024 _device_address |= (device_address_bits<<1); 00025 } 00026 00027 int MCP4725::read(enum PowerMode* mode, enum PowerMode* mode_eeprom, int* dac_value, int* dac_value_eeprom, bool* eeprom_write_in_progress) 00028 { 00029 char data[5]; 00030 int result; 00031 00032 // Read the raw data from the device. 00033 result = _i2c_interface.read(_device_address, data, sizeof(data)/sizeof(*data), false); 00034 00035 // Parse the raw data, extracting our fields. Refer to MCP4725 ref manual, section 6.2 00036 if (result == 0) 00037 { 00038 *eeprom_write_in_progress = (data[0] & 0x80)? false:true; 00039 00040 *mode = (enum PowerMode) ((data[0] & 0x06)>>1); 00041 00042 *dac_value = (data[1]<<4) + (data[2]>>4); 00043 00044 *mode_eeprom = (enum PowerMode)((data[3] & 0x60)>>5); 00045 00046 *dac_value_eeprom = ((data[3] & 0x0F) <<8) + data[4]; 00047 } 00048 00049 return result; 00050 } 00051 00052 00053 00054 int MCP4725::write(float dac_value, enum PowerMode mode, bool writeToEeprom) 00055 { 00056 00057 00058 int dac_value_2 = (int) (0xFFF * (dac_value/5.029f) ); // Divide dac_value by the reference voltage // Optimally the reference voltage is exactly 5.0V but this is not the case here. // The Ref voltage is 5.029V 00059 char data[3]={0}; 00060 int write_command; 00061 00062 //Which write command are we to use? 00063 if (writeToEeprom == true) 00064 { 00065 //Write DAC Register and EEPROM 00066 write_command = 3; 00067 } 00068 else 00069 { 00070 //Write DAC Register 00071 write_command = 2; 00072 } 00073 00074 //Assemble our three bytes of data - Refer to MCP4725 ref manual, section 6. 00075 data[0] = (write_command <<5) | ((int)mode<<1); 00076 data[1] = (dac_value_2>>4); 00077 data[2] = (dac_value_2<<4); 00078 00079 // Now write them to the device. 00080 return _i2c_interface.write(_device_address, data, sizeof(data)/sizeof(*data), false); 00081 }
Generated on Wed Jul 20 2022 02:40:23 by
