Lab 10/24/18 and 10/30/18

Dependencies:   mbed

Fork of SPI_MCP3002 by Advanced_Instrumentation_2019

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 // Bits are: Start (1), SGL/DIFF (1 for single), ODD/SIGN (0 for channel 0), MSBF (1 for MSB first)
00003 #define MCP3002_CH0 0x68  // 0110 1000
00004 #define MCP3002_CH1 0x78  // 0111 1000
00005 
00006 Serial pc(USBTX, USBRX);
00007 SPI spi(p5, p6, p7); // mosi, miso, sclk
00008 DigitalOut cs(p20); // Chip select, active low
00009 AnalogOut aout(p18);
00010 
00011 // Note that using CS means that the chip itself has no address
00012 
00013 int main() {
00014     pc.printf("Starting program \r\n");
00015     // Chip must be deselected
00016     cs = 1;
00017     // Setup the spi for 8 bit data, CPOL = 0, CPHA = 0
00018     // with a 10KHz clock rate
00019     spi.format(8,0);
00020     spi.frequency(10000);
00021     int data1, data2, mask, channel;
00022     aout = 0.0;
00023     // Supply voltage is nominally 3.3V
00024     float VCC=3.3, vIn;
00025     while(1) {
00026         for (channel = 0; channel<2; channel++){
00027             if(channel == 0){
00028                 mask = MCP3002_CH0;
00029             }else{
00030                 mask = MCP3002_CH1;
00031             }     
00032             cs = 0;
00033             data1 = spi.write(mask);
00034             cs = 1;
00035             data2 = spi.write(0);
00036             //cs = 1;
00037 // Format for MSB set
00038             data1 &= 0x03;  // keep only three bits
00039             data2 |= data1 << 8 ; // shift and add to LSB
00040 // data2 ranges from 0 to 1023 for voltage from 0 to VCC
00041             vIn = VCC*data2/1000.;
00042             pc.printf("Channel %i Voltage is %f \r\n",channel,vIn);
00043         }
00044         aout = aout + 0.1;
00045         float volt = aout;
00046         pc.printf("Analog output of mbed is %f \r\n", volt);
00047         //wait(1);
00048     }
00049 }