SPI-Master

Dependencies:   mbed

main.cpp

Committer:
gerardo_carmona
Date:
2014-09-26
Revision:
0:795863b0916e

File content as of revision 0:795863b0916e:

/*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. 
*/

#include "mbed.h"

SPI ser_port(D11, D12, D13);        // mosi, miso, sclk
DigitalOut red_led(LED_RED);        //red led
DigitalOut green_led(LED_GREEN);    //green led
DigitalOut cs(D2);                  //this acts as “slave select”
DigitalIn  switch_ip1(SW2);
DigitalIn  switch_ip2(SW3);
 
char switch_word ;                  //word we will send
char recd_val;                      //value return from slave

//continued over

int main() {
    switch_ip1.mode(PullUp);
    switch_ip2.mode(PullUp);
    red_led = 1;
    green_led=1;
    while (1){
        //Default settings for SPI Master chosen, no need for further configuration    
        //Set up the word to be sent, by testing switch inputs
        switch_word=0xa0;             //set up a recognisable output pattern
        if (switch_ip1==0)
          switch_word=switch_word|0x01;        //OR in lsb
        if (switch_ip2==0)
          switch_word=switch_word|0x02;        //OR in next lsb
        cs = 0;                                //select slave
        recd_val=ser_port.write(switch_word);  //send switch_word and receive data
        cs = 1;               
        wait(0.01);
        //set leds according to incoming word from slave
        red_led=1;              //preset both to 0
        green_led=1; 
        recd_val=recd_val&0x03; //AND out unwanted bits
        
        if (recd_val==0x1)
          red_led=0;
        
        if (recd_val==0x2)
          green_led=0;
        
        if (recd_val==0x3){
          red_led=0;
          green_led=0;
        }

    }    
}