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

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers mcp3208.cpp Source File

mcp3208.cpp

00001 //
00002 //
00003 //
00004 #include "mcp3208.h"
00005 
00006 
00007 MCP3208::MCP3208(PinName mosi, PinName miso, PinName clk, PinName cs)
00008 :   _spi(mosi,miso,clk),
00009     _cs(cs),
00010     _vref(5.0)
00011 {
00012     _spi.frequency(2000000);
00013 //    _spi.frequency(8000000); // Out of MCP3208 spec
00014 //    _spi.format(12,3);
00015     _spi.format(16,3);       // To accomodate STM32 Nucleo support for only 8-bit and 16-bit words.
00016     _cs = 1;
00017 }
00018 
00019 int MCP3208::binary(int ch)
00020 {
00021     _cs = 0;
00022 //    int ret = _spi.write((0x18|ch)<<2);
00023     unsigned long ret = _spi.write((0x18|ch)<<2);
00024 //    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
00025     int adb = _spi.write(0)>>4;   // mbed fixed my fix (-_-). 
00026 //    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
00027     _cs = 1;
00028     return adb;
00029 }
00030 
00031 float
00032 MCP3208::volt(int ch)
00033 {
00034     return _vref * binary(ch) / 4095;
00035 }
00036