Library to control the 12 Bits Analog Digital Converter MCP4921

Mcp4921.cpp

Committer:
adelino
Date:
2013-11-17
Revision:
1:1352606a60c6
Parent:
0:38e03f9fa18a

File content as of revision 1:1352606a60c6:

#include "Mcp4921.h"

Mcp4921::Mcp4921(PinName _mosi,PinName _sck,PinName _cs, int _frequency):mySPI(_mosi,NC,_sck),myCs(_cs)
{
    myFrequency=_frequency;

    setup();
}
//---------------------------------------
int Mcp4921::getFrequency(void)
{
    return myFrequency;
}
//--------------------------------------
void Mcp4921::write(int dataIntNum)
{
 //valid input values are 0 - 4095.   4096 should scale to Vref.   
    char i=0;

    if(dataIntNum >4095)
        dataIntNum=4095;

    if(dataIntNum <0)
        dataIntNum=0;

    int16_t temp=0;
    temp=dataIntNum | 0x7000;

    myCs=0;
    for(i=0; i<50; i++);
    mySPI.write(temp);

    for(i=0; i<50; i++);
    myCs=1;
}
//--------------------------------------
void Mcp4921::write_mV(int millivolt){
    
    if(millivolt >3300)
        millivolt=3300;
        
    if(millivolt <0)
        millivolt=0;
        
  int val=(millivolt*4095)/3300;
  
  write(val);      
}
//--------------------------------------
void Mcp4921::write(float dataFloat)
{
//valid input values are 0.0 - 1.0   with 1.0 should scale to Vref.   
    if(dataFloat >1.0)
        dataFloat=1.0;

    if(dataFloat <0)
        dataFloat=0;

    float temp=4095*dataFloat;

    write((int)temp);
}
//--------------------------------------
void Mcp4921::operator=(int dataIntNum)
{
    write(dataIntNum);
}
//--------------------------------------
void Mcp4921::operator=(float dataFloat)
{
    write(dataFloat);
}
//--------------------------------------
void Mcp4921::setup(void)
{
    myCs=1;
    mySPI.frequency(myFrequency);  //
    mySPI.format(16,0);       //16 bits + mode 0
}
//