|
SPI单主单从试了很多次,数据总是乱飞,现在决定用互为主从通信,依然碰到错误,错误如下。
每次开机后,主机发送数据给从机,从机返回这个数据到主机,但是主机收到的数据是0x00,开机后第一次通信总是这样,之后就正常了,第二次给从机发送数据就能返回正常的数据了。根据测试,从机收到的数据是正常的,但是将数据返回给主机,数据就不正常了,程序如下:- #include "reg51.h"
- #define FOSC 22118400L
- #define BAUD (256 - FOSC / 32 / 115200)
- typedef unsigned char BYTE;
- typedef unsigned int WORD;
- typedef unsigned long DWORD;
- sfr AUXR = 0x8e; //Auxiliary register
- sfr SPSTAT = 0xcd; //SPI status register
- #define SPIF 0x80 //SPSTAT.7
- #define WCOL 0x40 //SPSTAT.6
- sfr SPCTL = 0xce; //SPI control register
- #define SSIG 0x80 //SPCTL.7
- #define SPEN 0x40 //SPCTL.6
- #define DORD 0x20 //SPCTL.5
- #define MSTR 0x10 //SPCTL.4
- #define CPOL 0x08 //SPCTL.3
- #define CPHA 0x04 //SPCTL.2
- #define SPDHH 0x00 //CPU_CLK/4
- #define SPDH 0x01 //CPU_CLK/16
- #define SPDL 0x02 //CPU_CLK/64
- #define SPDLL 0x03 //CPU_CLK/128
- sfr SPDAT = 0xcf; //SPI data register
- sbit SPISS = P1^3; //SPI slave select, connect to other MCU's SS(P1.4) pin
- sfr IE2 = 0xAF; //interrupt enable rgister 2
- #define ESPI 0x02 //IE2.1
- void InitUart();
- void InitSPI();
- void SendUart(BYTE dat); //send data to PC
- BYTE RecvUart(); //receive data from PC
- bit MSSEL; //1: master 0:slave
- ///////////////////////////////////////////////////////////
- void main()
- {
- InitUart(); //initial UART
- InitSPI(); //initial SPI
- IE2 |= ESPI;
- EA = 1;
- while (1)
- {
- if (RI)
- {
- SPCTL = SPEN | MSTR; //set as master
- MSSEL = 1;
- ACC = RecvUart();
- SPISS = 0; //pull low slave SS
- SPDAT = ACC; //trigger SPI send
- }
- }
- }
- ///////////////////////////////////////////////////////////
- void spi_isr() interrupt 9 using 1 //SPI interrupt routine 9 (004BH)
- {
- SPSTAT = SPIF | WCOL; //clear SPI status
- if (MSSEL)
- {
- SPCTL = SPEN; //reset as slave
- MSSEL = 0;
- SPISS = 1; //push high slave SS
- SendUart(SPDAT); //return received SPI data
- }
- else
- { //for salve (receive SPI data from master and
- SPDAT = SPDAT; // send previous SPI data to master)
- }
- }
- ///////////////////////////////////////////////////////////
- void InitUart()
- {
- SCON = 0x5a; //set UART mode as 8-bit variable baudrate
- TMOD = 0x20; //timer1 as 8-bit auto reload mode
- AUXR = 0x40; //timer1 work at 1T mode
- TH1 = TL1 = BAUD; //11 5200 bps
- TR1 = 1;
- }
- ///////////////////////////////////////////////////////////
- void InitSPI()
- {
- SPDAT = 0; //initial SPI data
- SPSTAT = SPIF | WCOL; //clear SPI status
- SPCTL = SPEN; //slave mode
- }
- ///////////////////////////////////////////////////////////
- void SendUart(BYTE dat)
- {
- while (!TI); //wait pre-data sent
- TI = 0; //clear TI flag
- SBUF = dat; //send current data
- }
- ///////////////////////////////////////////////////////////
- BYTE RecvUart()
- {
- while (!RI); //wait receive complete
- RI = 0; //clear RI flag
- return SBUF; //return receive data
- }
复制代码 |
阿莫论坛20周年了!感谢大家的支持与爱护!!
曾经有一段真挚的爱情摆在我的面前,我没有珍惜,现在想起来,还好我没有珍惜……
|