Master SPI Port

Initialise

#define INTERBOARD_COMMS_SS_PIN				LATDbits.LATD3
#define INTERBOARD_COMMS_PACKET_LENGTH		10

	//----- SETUP SSP2 AS SPI BUS -----
	//Used for: 
	//CLK idle in low state
	//Devices clock in data on the rising edge, output data on the falling edge
	SSP2STAT = 0b11000000;
	SSP2CON1 = 0b00100010;		//16MHz Fosc / 64 = 250000kHz

	//----- INIT SPI -----
	//Send a dummy byte to trigger the BF bit
	SSP2BUF = 0;
	INTERBOARD_COMMS_SS_PIN = 1;
TX and Receive

		//Exit if TX in progress
		if (!SSP2STATbits.BF)
			return;

		//Exit if pausing
		if (interboard_comms_10ms_timer > 0)
			return;

		if (spi_comms_byte_index == 0xff)
		{
			//DONE COMPLETE PACKET
			Nop();		//Ensure a delay after clock of last byte
			Nop();
			Nop();
			Nop();
			Nop();
			INTERBOARD_COMMS_SS_PIN = 1;

			spi_comms_byte_index = 0;
			interboard_comms_10ms_timer = 2;		//Wait 10-20ms before next comms
			return;
		}


		if (spi_comms_byte_index == 0)
		{
			//----- BYTE 0 -----
			INTERBOARD_COMMS_SS_PIN = 0;

			spi_tx_rx_data[0] = 0x10;
			spi_tx_rx_data[1] = 0x11;
			spi_tx_rx_data[2] = 0x12;
			spi_tx_rx_data[3] = 0x13;
			spi_tx_rx_data[4] = 0x14;
			spi_tx_rx_data[5] = 0x15;
			spi_tx_rx_data[6] = 0x16;
			spi_tx_rx_data[7] = 0x17;
			spi_tx_rx_data[8] = 0x18;
			spi_tx_rx_data[9] = 0x19;
		}

		data = SSP2BUF;
		SSP2BUF = spi_tx_rx_data[spi_comms_byte_index];
		spi_tx_rx_data[spi_comms_byte_index] = data;


		spi_comms_byte_index++;
		if (spi_comms_byte_index >= INTERBOARD_COMMS_PACKET_LENGTH)
			spi_comms_byte_index = 0xff;		//Flag packet all done

 

Slave SPI Port

Initialise

	//----- SETUP SSP2 AS SPI BUS -----
	//SLAVE MODE
	TRISDbits.TRISD0 = 1;
	TRISDbits.TRISD3 = 1;
	SSP2STAT = 0b01000000;
	SSP2CON1 = 0b00100100;		//SPI slave mode, SS is used

	PIE3bits.SSP2IE = 1;		//Enable interrupt

 

UK Electronic Designer
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.