u8 RxBuf[10];
02 u8 spi_cnt=0;
03
04 main(void)
05 {
06 ......
07 SPI_SLAVE_Init();
08 SPI_SLAVE_SendByte(0x12);//SPI首字节0x12,作为从机标识
09 __enable_interrupt();
10 ......
11 }
12
13 void SPI_SLAVE_Init(void)
14 {
15 SPI_DeInit();
16 /* 初始化SPI , 从机和主机的相位有效沿一定要一致*/
17 SPI_Init(SPI_FIRSTBIT_MSB, SPI_BAUDRATEPRESCALER_2,SPI_MODE_SLAVE,\
18 SPI_CLOCKPOLARITY_LOW, SPI_CLOCKPHASE_1EDGE, \
19 SPI_DATADIRECTION_2LINES_FULLDUPLEX, SPI_NSS_SOFT, 0x07);
20
21 SPI_ITConfig(SPI_IT_RXNE,ENABLE);
22 SPI_NSSInternalSoftwareCmd(DISABLE);//产生SSI从机信号,也可放在外部中断里来使能从机中断
23 SPI_Cmd(ENABLE);
24 }
25
26 u8 SPI_SLAVE_SendByte(u8 byte)//把while判断非空标志全部去掉,不然等待时间太长会错帧,判断等待交给主机做
27 {
28 /* Loop while DR register in not emplty */
29 // while (SPI_GetFlagStatus( SPI_FLAG_TXE) == RESET);
30 /* Send byte through the SPI1 peripheral */
31 SPI_SendData(byte);
32 /* Wait to receive a byte */
33 // while (SPI_GetFlagStatus(SPI_FLAG_RXNE) == RESET);
34 /* Return the byte read from the SPI bus */
35 return SPI_ReceiveData();
36 }
37
38 //SPI从机中断
39 INTERRUPT_HANDLER(SPI_IRQHandler, 10)
40 {
41 /* In order to detect unexpected events during development,
42 it is recommended to set a breakpoint on the following instruction.
43 */
44 uint8_t Rx_byte,spi_head;
45
46 // if(GPIO_ReadInputPin(GPIOD, GPIO_PIN_3)==0)//确认CS脚拉低的这个判断太慢了,总是出错,另谋他法吧!
47 // {
48 Rx_byte = SPI_SLAVE_SendByte(0x36);//设置下一个字节,同时读回主机当前CLK下的字节
49
50 if((spi_cnt == 0)&&((Rx_byte == 0xef)||(Rx_byte == 0x7e))) //首字为0xef或者0x7e,就认为是有效包
51 {
52 spi_head = 1;
53 }
54 if(spi_head) //在有效包内的话就将读回的字节放入数组
55 {
56 RxBuf[spi_cnt] = Rx_byte; //注意,首字会在这个数组里
57 spi_cnt += 1; //地址+1
58 }
59 if(spi_cnt==10) //包满归零
60 {
61 spi_head=0;
62 spi_cnt=0;
63 SPI_SLAVE_SendByte(0x12);//设置下一轮发送的首字节0x12
64 }
65 // }
66 }
|