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

Dependencies:   mbed

Fork of SPI_MCP3002 by Advanced_Instrumentation_2019

Committer:
acabate
Date:
Tue Oct 30 22:11:27 2018 +0000
Revision:
1:178a0f92d2ab
Parent:
0:08026df17556
Lab 10/30/18

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;
acabate 1:178a0f92d2ab 22 aout = 0.0;
billcooke51 0:08026df17556 23 // Supply voltage is nominally 3.3V
billcooke51 0:08026df17556 24 float VCC=3.3, vIn;
billcooke51 0:08026df17556 25 while(1) {
billcooke51 0:08026df17556 26 for (channel = 0; channel<2; channel++){
billcooke51 0:08026df17556 27 if(channel == 0){
billcooke51 0:08026df17556 28 mask = MCP3002_CH0;
billcooke51 0:08026df17556 29 }else{
billcooke51 0:08026df17556 30 mask = MCP3002_CH1;
billcooke51 0:08026df17556 31 }
billcooke51 0:08026df17556 32 cs = 0;
billcooke51 0:08026df17556 33 data1 = spi.write(mask);
acabate 1:178a0f92d2ab 34 cs = 1;
billcooke51 0:08026df17556 35 data2 = spi.write(0);
acabate 1:178a0f92d2ab 36 //cs = 1;
billcooke51 0:08026df17556 37 // Format for MSB set
billcooke51 0:08026df17556 38 data1 &= 0x03; // keep only three bits
billcooke51 0:08026df17556 39 data2 |= data1 << 8 ; // shift and add to LSB
billcooke51 0:08026df17556 40 // data2 ranges from 0 to 1023 for voltage from 0 to VCC
billcooke51 0:08026df17556 41 vIn = VCC*data2/1000.;
billcooke51 0:08026df17556 42 pc.printf("Channel %i Voltage is %f \r\n",channel,vIn);
billcooke51 0:08026df17556 43 }
acabate 1:178a0f92d2ab 44 aout = aout + 0.1;
acabate 1:178a0f92d2ab 45 float volt = aout;
acabate 1:178a0f92d2ab 46 pc.printf("Analog output of mbed is %f \r\n", volt);
acabate 1:178a0f92d2ab 47 //wait(1);
billcooke51 0:08026df17556 48 }
billcooke51 0:08026df17556 49 }