Simple library for SPI DAC MCP4801

Dependents:   DAC_MCP4801_example

MCP4801.cpp

Committer:
JohnnyK
Date:
2020-03-03
Revision:
0:886b1ee1370b

File content as of revision 0:886b1ee1370b:

#include "mbed.h"
#include "MCP4801.h"

MCP4801::MCP4801(SPI &spi, PinName ssel, PinName ldacLowPin,PinName shutdownLowPin): _slaveSelectLow(ssel), _ldacLow(ldacLowPin),_shutdownLow(shutdownLowPin){
  //initialize pins
    _slaveSelectLow = 1;
    _spi = &spi;
    _spi->format(8,0);
    _spi->frequency(1000000);
    if(_ldacLow.is_connected()) _ldacLow = 0;
    if(_shutdownLow.is_connected()) _shutdownLow = 0;
}

void MCP4801::setOutput_state(uint8_t state, bool soft){
    if(soft){
        shutdown = state;
    }else{
        if(_shutdownLow.is_connected()) _shutdownLow = state;
    }
    
}

void MCP4801::updateOutput(){
    if(_ldacLow.is_connected()){
        _ldacLow = 1;
        wait_us(5000);
        _ldacLow = 0;
    }
}


int MCP4801::setVOutput(float voltage){
    uint8_t gain_bit = 0;
    unsigned short int value = 0;
    int error;
  
    //auto choose range
    if(voltage < VREF){ 
        gain_bit = 1; //gain 1
        value = voltage/VREF*RES8BIT;
    }else{ 
        gain_bit = 0; //gain 2
        value = 0.5*voltage/VREF*RES8BIT;
    } 
    char packet[]= {0x00,0x00};
    packet[0] = value >> 4;
    packet[1] = value << 4;
    packet[0] |= shutdown << 4;                             //shutdown - output state
    packet[0] |= gain_bit << 5;                             //gain
    
    _slaveSelectLow = 0;                                    //set chip as listener 
    error = _spi->write(packet, sizeof(packet), NULL, 0);   //send packet (const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length)
    _slaveSelectLow = 1;                                    //release chip select
    if(_ldacLow.is_connected()) _ldacLow = 0;               //pull latch down
    wait_us(1);
    if(_ldacLow.is_connected()) _ldacLow = 1;               //pull latch up
    
    return error;
}