/******************************************
Mega64(L)
******************************************/
#ifndef __SPI__H
#define __SPI__H
#define SS PB0 //pin 10
#define SCK PB1 //pin 11
#define MOSI PB2 //pin 12
#define MISO PB3 //pin 13
#define SPI_RX_SIZE 7
#define SPI_TX_SIZE 5
#define SS_L() PORTB &=~ (1<<SS);
#define SS_H() PORTB |= (1<<SS);
#define SPI_RX 0
#define SPI_TX 1
unsigned char spi_rx_buffer[SPI_RX_SIZE]; //SPI recv buffer
unsigned char spi_rx_head; //SPI recv handle
unsigned char spi_rx_flag; //rx busy
unsigned char spi_tx_buffer[SPI_TX_SIZE]; //SPI command buffer
unsigned char spi_tx_head; //spi send handle
unsigned char spi_tx_flag; //tx busy
unsigned char spi_mode; //spi mode
unsigned char spi_command_flag; //1:接收到完整数据帧
/******************************************
init
******************************************/
void spi_rx_init( void )
{
unsigned char temp;
temp = SPSR;
temp = SPCR;
DDRB &= ~((1<<MOSI)|(1<<SCK)|(1<<SS));
SS_H();
PORTB |= (1<<MOSI)|(1<<SCK);
PORTB |= 1<<MISO;
SPCR = 0xE3; //setup SPI
SPSR = 0x00; //setup SPI
spi_rx_head = 0;
spi_rx_flag = 0;
spi_mode = SPI_RX;
spi_command_flag = 0;
}
void spi_tx_init( void )
{
unsigned char temp;
DDRB &= ~(1<<MISO);
DDRB |= (1<<SS) | (1<<SCK) | (1<<MOSI); //Set MOSI, SCK AND SS as outputs
SS_H();
PORTB |= 1<<MISO;
SPCR = 0x00;
SPCR = 0xF3;
temp = SPSR; //prepare for sending
temp = SPCR;
spi_mode = SPI_TX;
spi_tx_head = 0;
spi_command_flag = 0;
}
/**************************************
0x7F type xx xx xx xx 0x0D
type : 0x01 : AD转换结果
0x02 : 其他类型数据
//byte in SPDR has been sent/received
**************************************/
#pragma interrupt_handler spi_stc_isr:18
void spi_stc_isr(void)
{
unsigned char temp;
temp = SPDR;
//Uart0_Transmit(temp);
if (spi_mode == SPI_TX) //发送模式
{
SS_H();
spi_tx_head ++;
if (spi_tx_head < SPI_TX_SIZE) //发送缓冲区不为空
{
delay_us(20);
SS_L();
SPDR = spi_tx_buffer[spi_tx_head]; //发送下一个字节
}
if (spi_tx_head == SPI_TX_SIZE) //发送缓冲区为空
{
spi_tx_head = 0;
spi_rx_init(); //重新初始化成接收模式
spi_tx_flag = 0;
}
}
|