Rob Toulson / Mbed 2 deprecated PE_07-02_BidirectionalSPI

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /*Program Example 7.2. Sets the mbed up as Master, and exchanges data with a slave, sending its own switch positions, and displaying those of the slave. 
00002                                                                             */
00003 #include "mbed.h"
00004 
00005 SPI ser_port(p11, p12, p13);    // mosi, miso, sclk
00006 DigitalOut red_led(p25);   //red led
00007 DigitalOut green_led(p26); //green led
00008 DigitalOut cs(p14);        //this acts as “slave select”
00009 DigitalIn  switch_ip1(p5);
00010 DigitalIn  switch_ip2(p6);
00011 char switch_word ;        //word we will send
00012 char recd_val;            //value return from slave
00013 
00014 int main() {
00015   while (1){
00016     //Default settings for SPI Master chosen, no need for further configuration    
00017     //Set up the word to be sent, by testing switch inputs
00018     switch_word=0xa0;             //set up a recognisable output pattern
00019     if (switch_ip1==1)
00020       switch_word=switch_word|0x01;        //OR in lsb
00021     if (switch_ip2==1)
00022       switch_word=switch_word|0x02;        //OR in next lsb
00023     cs = 0;                                //select slave
00024     recd_val=ser_port.write(switch_word);  //send switch_word and receive data
00025     cs = 1;               
00026     wait(0.01);
00027   
00028     //set leds according to incoming word from slave
00029     red_led=0;              //preset both to 0
00030     green_led=0; 
00031     recd_val=recd_val&0x03; //AND out unwanted bits
00032     if (recd_val==1)
00033       red_led=1;
00034     if (recd_val==2)
00035       green_led=1;
00036     if (recd_val==3){
00037       red_led=1;
00038       green_led=1;
00039     }
00040   }    
00041 }    
00042