C Code for Interfacing SPI module in AVR MCU

Microcontroller Topics
Post Reply
User avatar
Magneto
Major
Major
Posts: 430
Joined: Wed Jul 15, 2009 1:52 pm
Location: London

C Code for Interfacing SPI module in AVR MCU

Post by Magneto » Sat Oct 24, 2009 11:18 pm

spi.h Header File

Code: Select all

extern void spi_master_init(void);
extern void spi_slave_init(void);

extern int spi_master_putc(unsigned char data);
extern int spi_slave_getc(void);

spi.c FIle

Code: Select all

#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/signal.h>

#include "spi.h"

void spi_master_init(void) {
	//Init Master
	// Set MOSI and SCK output, all others input
	DDRB = (1<<DDB2)|(1<<DDB1)|(1<<DDB0);
	//Enable SPI, Master, set clock rate fck/16
	SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);
	PORTB &= ~(1<<PB0);
}

void spi_slave_init(void) {
	//Set MISO output, all others input
	DDRB = (1<<DDB3);
	// Enable SPI 
	SPCR = (1<<SPE);
}

int spi_master_putc(unsigned char data) {
	SPDR = data;
	while(!(SPSR & (1<<SPIF)));
	return 0;
}

int spi_slave_getc(void) {
	//Wait for reception complete
	while(!(SPSR & (1<<SPIF)));
	// Return data register
	//uart_putc(SPDR);
	return SPDR;
}


/*void spi_master_init(void) {
	char dummy;
	//Init Master
	// Set MOSI and SCK output, all others input
	DDRB = (1<<DDB2)|(1<<DDB1)|(1<<DDB0);
	//Enable SPI, Master, set clock rate fck/16
	SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0)|(1<<SPIE);
	
	dummy = SPSR;
	dummy = SPDR;
	
	PORTB &= ~(1<<PB0);
}

void spi_slave_init(void) {
	char dummy;
	//Set MISO output, all others input
	DDRB = (1<<DDB3);
	// Enable SPI
	SPCR = (1<<SPE)|(1<<SPIE);
	
	dummy = SPSR;
	dummy = SPDR;
}

SIGNAL(SIG_SPI) {
	while(!(SPSR & (1<<SPIF)));
	
	if() {
		uart_putc(SPDR);
	} else {
	
	}
}*/
Post Reply

Return to “Microcontrollers”