161006_BDK_SPIslave

Dependencies:   mbed

Fork of Nucleo_SPIslave_F303K8_KSS by CUBEBITE

main.cpp

Committer:
bcup
Date:
2016-10-05
Revision:
0:24e90e3ca3f4
Child:
1:3a338e553a54

File content as of revision 0:24e90e3ca3f4:

#include "mbed.h"

#define DEBUG_SPI

#ifdef DEBUG_SPI
#define PRINTD(arg1,arg2...)    printf(arg1,##arg2)
#endif

SPISlave spislave(PA_7, PA_6, PA_5, PA_4); // MOSI, MISO, SCLK(CLK), SSEL(CS)=NC
Serial pc(USBTX, USBRX);

void SPI_SlaveInit()
{
    PRINTD("Set the SPI SLAVE format\n");
    spislave.format(8,0); // setup 8bit 0 mode
    PRINTD("Set the SPI SLAVE frequency\n");
    spislave.frequency(); // default 1MHz
}

void SPI_SlaveWrite()
{
    char tx_buffer[255]={0};
    char reply;
    char i;
    char temp;
    char tx_cnt = 0;
    int value;
    PRINTD("Input Strging=");
    while(1)
    {
        
        temp=getchar();
        tx_buffer[tx_cnt++]=temp;
        if(temp==0x0d)
        {
            tx_buffer[tx_cnt]=0;
            PRINTD("\nData send Finish...\n");
            for(i=0;i<=tx_cnt;++i)
            {
                PRINTD("%c[%02x]",tx_buffer[i],tx_buffer[i]);
            }
            PRINTD("\n\n");
            for(i=0;i<=tx_cnt;++i)
            {
                value=tx_buffer[i];
                PRINTD("write[%d]=%c[%02x]\n",i,value,value);
                spislave.reply(value);
            }
            for(i=0;i<tx_cnt;++i)
            {
                tx_buffer[i]=0;
                PRINTD("init_tx_buf[%d]=%c\n",i,tx_buffer[i]);
            }
            tx_cnt=0;
            PRINTD("break\n");
            break;
        }
        else
        {
            PRINTD("%c[%02x]",tx_buffer[tx_cnt],tx_buffer[tx_cnt]);
        }
    }
    return;
}

int main()
{
    int i;
    char valueFromMaster;
    char rx_buffer[255]={0};
    char rx_cnt = -1;
    PRINTD("\n=========SLAVE=========\n");
    SPI_SlaveInit();
    
    while(1)
    {

        if(spislave.receive())
        { 
            PRINTD("----1\n");
            if(pc.readable())
            {
                SPI_SlaveWrite();
            }
            PRINTD("----2\n");
            valueFromMaster = spislave.read();
            PRINTD("----3\n");
            //PRINTD("valueFromMaster=");
            //PRINTD("[%c]%x\n",valueFromMaster,valueFromMaster);
            rx_buffer[++rx_cnt]=valueFromMaster;
            if(valueFromMaster==0)
            {   
                PRINTD("rx_string=");
                for(i=0;i<rx_cnt;i++) 
                {    
                    PRINTD("%c",rx_buffer[i]);
                }
                PRINTD("\n");
                for(i=0;i<=rx_cnt;i++)
                {
                    rx_buffer[i]=0;
                    PRINTD("Init_rx_buf[%d]=%c\n",i,rx_buffer[i]);
                }
                rx_cnt=-1;
               
            }//valueFromMaster if
            
        }// spislave.receive() if
     /*
                
            */
    }//end of while
}//end of main