12bit 8ch ADC with SPI interface for STM32 Nucleo to support 16-bit words. SPI speed bumped up to 8MHz

Fork of MCP3208_Y by Michael Chuah

mcp3208.cpp

Committer:
mcx
Date:
2018-10-04
Revision:
4:d2fa630c69e1
Parent:
3:1c34c302cbfb

File content as of revision 4:d2fa630c69e1:

//
//
//
#include "mcp3208.h"


MCP3208::MCP3208(PinName mosi, PinName miso, PinName clk, PinName cs)
:   _spi(mosi,miso,clk),
    _cs(cs),
    _vref(5.0)
{
    _spi.frequency(2000000);
//    _spi.frequency(8000000); // Out of MCP3208 spec
//    _spi.format(12,3);
    _spi.format(16,3);       // To accomodate STM32 Nucleo support for only 8-bit and 16-bit words.
    _cs = 1;
}

int MCP3208::binary(int ch)
{
    _cs = 0;
//    int ret = _spi.write((0x18|ch)<<2);
    unsigned long ret = _spi.write((0x18|ch)<<2);
//    int adb = _spi.write(0);   // commented out due to bug with STM32 Nucleo 16-bit words sending another 16-bit word immediately after the 1st one
    int adb = _spi.write(0)>>4;   // mbed fixed my fix (-_-). 
//    int adb = ret>>20;           // Bitshifting by 16-bits to get rid of the initial 1111 1110, another 4-bit to get the 12-bits of data
    _cs = 1;
    return adb;
}

float
MCP3208::volt(int ch)
{
    return _vref * binary(ch) / 4095;
}