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

Dependencies:   mbed

Fork of SPI_MCP3002 by Advanced_Instrumentation_2019

Committer:
billcooke51
Date:
Mon Oct 02 01:52:48 2017 +0000
Revision:
0:08026df17556
Child:
1:178a0f92d2ab
Checked bit ordering

Who changed what in which revision?

UserRevisionLine numberNew contents of line
billcooke51 0:08026df17556 1 #include "mbed.h"
billcooke51 0:08026df17556 2 // Bits are: Start (1), SGL/DIFF (1 for single), ODD/SIGN (0 for channel 0), MSBF (1 for MSB first)
billcooke51 0:08026df17556 3 #define MCP3002_CH0 0x68 // 0110 1000
billcooke51 0:08026df17556 4 #define MCP3002_CH1 0x78 // 0111 1000
billcooke51 0:08026df17556 5
billcooke51 0:08026df17556 6 Serial pc(USBTX, USBRX);
billcooke51 0:08026df17556 7 SPI spi(p5, p6, p7); // mosi, miso, sclk
billcooke51 0:08026df17556 8 DigitalOut cs(p20); // Chip select, active low
billcooke51 0:08026df17556 9 AnalogOut aout(p18);
billcooke51 0:08026df17556 10
billcooke51 0:08026df17556 11 // Note that using CS means that the chip itself has no address
billcooke51 0:08026df17556 12
billcooke51 0:08026df17556 13 int main() {
billcooke51 0:08026df17556 14 pc.printf("Starting program \r\n");
billcooke51 0:08026df17556 15 // Chip must be deselected
billcooke51 0:08026df17556 16 cs = 1;
billcooke51 0:08026df17556 17 // Setup the spi for 8 bit data, CPOL = 0, CPHA = 0
billcooke51 0:08026df17556 18 // with a 10KHz clock rate
billcooke51 0:08026df17556 19 spi.format(8,0);
billcooke51 0:08026df17556 20 spi.frequency(10000);
billcooke51 0:08026df17556 21 int data1, data2, mask, channel;
billcooke51 0:08026df17556 22 // Supply voltage is nominally 3.3V
billcooke51 0:08026df17556 23 float VCC=3.3, vIn;
billcooke51 0:08026df17556 24 while(1) {
billcooke51 0:08026df17556 25 for (channel = 0; channel<2; channel++){
billcooke51 0:08026df17556 26 if(channel == 0){
billcooke51 0:08026df17556 27 mask = MCP3002_CH0;
billcooke51 0:08026df17556 28 }else{
billcooke51 0:08026df17556 29 mask = MCP3002_CH1;
billcooke51 0:08026df17556 30 }
billcooke51 0:08026df17556 31 cs = 0;
billcooke51 0:08026df17556 32 data1 = spi.write(mask);
billcooke51 0:08026df17556 33 data2 = spi.write(0);
billcooke51 0:08026df17556 34 cs = 1;
billcooke51 0:08026df17556 35 // Format for MSB set
billcooke51 0:08026df17556 36 data1 &= 0x03; // keep only three bits
billcooke51 0:08026df17556 37 data2 |= data1 << 8 ; // shift and add to LSB
billcooke51 0:08026df17556 38 // data2 ranges from 0 to 1023 for voltage from 0 to VCC
billcooke51 0:08026df17556 39 vIn = VCC*data2/1000.;
billcooke51 0:08026df17556 40 pc.printf("Channel %i Voltage is %f \r\n",channel,vIn);
billcooke51 0:08026df17556 41 }
billcooke51 0:08026df17556 42 wait(1);
billcooke51 0:08026df17556 43 }
billcooke51 0:08026df17556 44 }