求大侠们,ADXL345与STC15系列单片机进行SPI通讯程序,或者类似单片机的SPI通讯程序

 我来答
百度网友283d78e
2015-03-02 · 知道合伙人IT服务行家
百度网友283d78e
知道合伙人IT服务行家
采纳数:1491 获赞数:2979

向TA提问 私信TA
展开全部
stc spi的例程

#include "reg51.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

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; //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
}
查晓筠0i5
2015-03-02 · TA获得超过2752个赞
知道大有可为答主
回答量:2.1万
采纳率:1%
帮助的人:4905万
展开全部
需要给你完成一份吗
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式