#include "reg51.h"
#define FOSC18432000L
#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 SPIF0x80//SPSTAT.7
#define WCOL0x40//SPSTAT.6
sfr SPCTL = 0xce //SPI control register
#define SSIG0x80//SPCTL.7
#define SPEN0x40//SPCTL.6
#define DORD0x20//SPCTL.5
#define MSTR0x10//SPCTL.4
#define CPOL0x08//SPCTL.3
#define CPHA0x04//SPCTL.2
#define SPDHH 0x00//CPU_CLK/4
#define SPDH0x01//CPU_CLK/16
#define SPDL0x02//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 ESPI0x02//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 //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
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)