主机IO口初始化
//CSK--->PC5
PC_DDR_bit.DDR5 = 1;
PC_CR1_bit.C15 = 1;
PC_CR2_bit.C25 = 1;
//MOSI--->PC6
PC_DDR_bit.DDR6 = 1;
PC_CR1_bit.C16 = 1;
PC_CR2_bit.C26 = 1;
//MISO--->PC7
PC_DDR_bit.DDR7 = 0;
PC_CR1_bit.C17 = 0;
PC_CR2_bit.C27 = 0;
//NSS--->PA3
PA_DDR_bit.DDR3 = 1;
PA_CR1_bit.C13 = 1;
PA_CR2_bit.C23 = 1;
SPI设置
void SPI_Init()
{
SPI_CR1_bit.BR = 1; //设置SPI速率 /4
SPI_CR1_bit.CPOL = 0; //
SPI_CR1_bit.CPHA = 0;
SPI_CR1_bit.MSTR = 1; //主设备模式
SPI_CR2_bit.SSI = 1; //主设备 SSI引脚不用
SPI_CR2_bit.SSM = 1;
SPI_CR1_bit.LSBFIRST = 0; //先发送MSB位
SPI_CR1_bit.SPE = 1; //使能SPI设备
}
写入单字节
unsigned char spi_rw_byte(unsigned char byte)
{
unsigned char retry = 0;
while(SPI_SR_bit.TXE == 0)
{
retry++;
if(retry > 200)
return 0;
}
SPI_DR = byte;
retry=0;
while(SPI_SR_bit.RXNE == 0) //等待接收完一个byte
{
retry++;
if(retry > 200)return 0;
}
return SPI_DR; //返回收到的数据
}
主函数
初始化后一秒钟发个字节
spi_io_initial();
SPI_Init();
while(1)
{
SPI_NSS=0;
spi_rw_byte(a);
SPI_NSS=1;
delay(1000);
LED=~LED;
a++;
}
//////////////////////////
从机
IO口初始化
//CSK--->PC5
PC_DDR_bit.DDR5 = 0;
PC_CR1_bit.C15 = 0;
PC_CR2_bit.C25 = 0;
//MOSI--->PC6
PC_DDR_bit.DDR6 = 0;
PC_CR1_bit.C16 = 0;
PC_CR2_bit.C26 = 0;
//MISO--->PC7
PC_DDR_bit.DDR7 = 1;
PC_CR1_bit.C17 = 1;
PC_CR2_bit.C27 = 1;
//SPI_NSS--->PA3
PA_DDR_bit.DDR3 = 0;
PA_CR1_bit.C13 = 1;
PA_CR2_bit.C23 = 0;
SPI设置
void SPI_Init()
{
// SPI_CR1_bit.BR = 1; //设置SPI速率 /4
SPI_CR1_bit.CPOL = 0; //空闲时SCK为高
SPI_CR1_bit.CPHA = 0; //数据从第一个时钟沿开始
SPI_CR1_bit.LSBFIRST = 0; //先发送MSB位
SPI_CR2_bit.SSM = 0;
SPI_CR2_bit.SSI = 0;
SPI_CR1_bit.MSTR = 0; //从设备模式
SPI_CR2_bit.SSM = 1; //使能SPI设备
}
写入单字节
unsigned char spi_rw_byte(unsigned char byte)
{
unsigned char retry = 0;
while(SPI_SR_bit.TXE == 0)
{
retry++;
if(retry > 200)
return 0;
}
SPI_DR = byte;
retry=0;
while(SPI_SR_bit.RXNE == 0) //等待接收完一个byte
{
retry++;
if(retry > 200)return 0;
}
return SPI_DR; //返回收到的数据
}
主函数
等待中断接收数据改变指示灯
spi_io_initial();
SPI_Init();
SPI_ICR = 0x40;
asm("rim");
while(1);
/** SPI中断服务函数 */
#pragma vector = 12
__interrupt void SPI_IRQHandler(void)
{
if(SPI_SR_bit.RXNE==1)
LED=~LED;
SPI_SR_bit.RXNE=0;
}
//////////////////////////////////////
主机和从机基本这么写了的,用swim调试,就没看见SPI_DR里面有过数据,从机也没看见进过中断,请问高手们,我这个是主机还是从机,哪里有问题,就是不可以用呢?
|