spi.c 1.44 KB
Newer Older
Øystein Smith's avatar
Øystein Smith committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
/**** A P P L I C A T I O N   N O T E   ************************************
*
* Title			: SPI hardware module on ATmega
* Version		: beta
* Last updated	: 01.10.14
* Target		: Node1
* Clock			: 16MHz
* Pinout		: See bottom of board.h
*
* written by GNR
***************************************************************************
*/
#include "board.h"		//Include board file (must include AVR libs & PIN defines)
#include "spi.h"
#include "can.h"		//Need MCP2515 define (controller type)

#define JIBBERISH 0xCE


void SPI_init()
{
	// Set MOSI, SCK and SS to output
	MCP_SPI_dir |= (1 << MCP_SPI_MOSI_pin) | (1 << MCP_SPI_SCK_pin);
	MCP_SPI_SS_dir |= (1 << MCP_SPI_MCP_SS_pin);
	
	//Ensure MISO is input
	MCP_SPI_dir &= ~(1 << MCP_SPI_MISO_pin);

	// Enable SPI, Master, set clock rate fck/4
	SPCR = (1 << SPE) | (1 << MSTR);

	// Set MCP2515 CS output and high (not selected)
	MCP_SPI_SS_port |= (1 << MCP_SPI_MCP_SS_pin);


}

uint8_t SPI_transmit(uint8_t byte)
{
	
	// Start transmission
	SPDR = byte;
	
	// Wait for transmission complete
	while(!(SPSR & (1<<SPIF)));
	
	// Return the received byte
	return SPDR;
}

uint8_t SPI_read(void)
{
	return SPI_transmit(0);
}

void SPI_write(uint8_t byte){
	SPI_transmit(byte);
}

void SPI_slave_select(uint8_t slave)
{
	// Set CS low
	if (slave == MCP2515){
		MCP_SPI_SS_port &= ~(1 << MCP_SPI_MCP_SS_pin);
	}
}
void SPI_slave_deselect(){
	// De select all SPI slaves

	//MCP 2515
	MCP_SPI_SS_port |= (1 << MCP_SPI_MCP_SS_pin);

}