#include <SPI.h>
#define CS 10
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(CS, OUTPUT);
uint16_t data;
SPI.begin();
data = readADC(0, 1);
Serial.println("Data read from channel CH0");
Serial.println(data);
}
void loop() {
// put your main code here, to run repeatedly:
uint16_t data;
data = readADC(0, 1);
Serial.println("Data read from channel CH0");
Serial.println(data);
delay(100);
}
// channel CH0 - 0, CH1 - 1, CH2 - 2, CH3 - 3
// mode differential - 0, single - 1
uint16_t readADC(uint8_t channel, uint8_t mode)
{
uint16_t output;
uint8_t channelBits = channel<<6;
uint8_t modeBit = mode<<1;
uint8_t startBits;
//Select ADC
digitalWrite(CS, LOW); //Select the Connected MCP3208 by pulling _CS_PIN_ LOW.
if(channel>3) {
startBits = B00000101 | modeBit;
SPI.transfer(startBits); //Defines Single mode of Operation for the ADC. D2=1 Start Bit. D1=1 Sinfgle Ended Mode D0=0 For Channel 0-3. 1 For Channel 4-7
}
else
startBits = B00000100 | modeBit;
SPI.transfer(startBits);
// Note: simulation purpose. With real chip it will convert wrongly
SPI.transfer(channelBits);
uint8_t msb = SPI.transfer(channelBits); //Transfers 2nd Byte from MCU to MCP3208 which returns MSB of the read data.
uint8_t lsb = SPI.transfer(0x00);//Transfers 3rd Byte from MCU to MCP3208 which returns LSB of the read data.
digitalWrite(CS,HIGH); //Deselect the Connected MCP3208 by pulling _CS_PIN_ HIGH.
msb = msb & B00001111; // Make all 4 Higher bits of the MSB 0 as 12 Bit Resolution is provided by MCP3208
output = msb<<8 | lsb; //Combine MSB with LSB to form the 12 Bit Analog read Value.
return output; //Output Value
}