/********************************************************************
汇诚科技
实现功能:STC12C5A60S2单片机之串口通信互为主从
使用芯片:STC12C5A60S2
晶振:11.0592MHZ
波特率:115200
编译环境:Keil
作者:zhangxinchun
网站:www.ourhc.cn
淘宝店:
汇诚科技 http://ourhc.taobao.com
郑兴电子直销部 http://shop68451856.taobao.com
【声明】此程序仅用于学习与参考,引用请注明版权和作者信息!
*********************************************************************/
#include "REG52.H"
#include "INTRINS.H"
#define FOSC 18432000L
#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
void InitUart();
void InitSPI();
void SendUart(BYTE dat); //send data to PC
BYTE RecvUart(); //receive data from PC
BYTE SPISwap(BYTE dat); //swap SPI data between master and slave
///////////////////////////////////////////////////////////
void main()
{
InitUart(); //initial UART
InitSPI(); //initial SPI
while (1)
{
if (RI)
{
SPCTL = SPEN | MSTR; //set as master
SendUart(SPISwap(RecvUart()));
SPCTL = SPEN; //reset as slave
}
if (SPSTAT & SPIF)
{
SPSTAT = SPIF | WCOL; //clear SPI status
SPDAT = SPDAT; //mov data from receive buffer to send buffer
}
}
}
///////////////////////////////////////////////////////////
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; //115200 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
}
///////////////////////////////////////////////////////////
BYTE SPISwap(BYTE dat)
{
SPISS = 0; //pull low slave SS
SPDAT = dat; //trigger SPI send
while (!(SPSTAT & SPIF)); //wait send complete
SPSTAT = SPIF | WCOL; //clear SPI status
SPISS = 1; //push high slave SS
return SPDAT; //return received SPI data
}
/********************************************************************
结束
*********************************************************************/
|