/*********************STC12C5A60S2单片机SPI程序*****************************/
//程序功能:从机查询方式接收数据;定时器定时刷新显示接收值
//SPI特性:最高3Mbit/S(12Mosc),控制寄存器SPCTL,状态寄存器(SPSTAT)数据寄存器(SPDAT)
// SPICLK-P17,MOSI-P15,MISO-P16,SS-P14
// 连接方式:(主机)SPICLK --(从机)SPICLK
// (主机)MOSI ----(从机)MOSI
// (主机)MISO ----(从机)MISO
// (主机)CS ------(从机)SS
// 写SPDAT将启动一次数据传输
#include <STC12C5A60S2.H>
//#include <display.h>
unsigned char number;//往主机传送的数据
unsigned char temp = 0;
unsigned char code table[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
sbit LED = P0^3;//调试端口
sbit wei1=P0^0; //数码管的位选
sbit wei2=P0^1;
sbit wei3=P0^2;
/************SPI初始化****************/
void intial_SPI(void)
{
//SPSTAT = 0xC0;//SPIF置0,WCOL置0,写1清0
SPCTL = 0xC4;//SSIG=1(SS忽略),SPI使能,MSTR = 0(从机模式),高位在前,时钟极性CPOL=0相位CPHA0=1,速率00(CPUclock/4)
IE2 |= 0x02;//enable SPI interrupt -----允许SPI产生中断
}
/**************查询方式接受数据,接收到数据后立即启动(从机)发送****************/
unsigned char Slave_rev_send(void)
{
unsigned char ch = 0;
while(!(SPSTAT & 0x80));//SPIF=0等待
SPSTAT |= 0x80;//写1清0SPIF 接收完毕
ch = SPDAT;
SPDAT = ch;//接收到数据后立即启动发送
return(ch);
}
void delayus(unsigned int n)
{
while(n --);
}
void display(unsigned char temp) //显示函数
{
unsigned char A1,A2,A3;
A1 = temp/100;
A2 = (temp/10)%10;
A3 = temp%10;
wei1= 0;
wei2= 1;
wei3= 1;
P2 = table[A1];
delayus(10);
P2=0x00;
wei1= 1;
wei2= 0;
wei3= 1;
P0 = table[A2];
delayus(10);
P2=0x00;
wei1= 1;
wei2= 1;
wei3= 0;
P2 = table[A3];
delayus(10);
P2=0x00;
}
/**************主程序********************/
void main(void)
{
intial_SPI();//初始化SPI端口
EA = 1; // 打开中断总开关
number=111;//通过SPI要发送的数据
SPDAT=number;//第一次往主机发的数据
while(1)
{
for
// display(temp,0);//实时显示接收到的数据
display(temp);
}
}
/*************SPI中断接收程序***************/
void SPI(void) interrupt 9
{
LED =! LED;//进入中断闪烁
temp = SPDAT;//保存收到的数据
SPSTAT |= 0x80;//write 1 to SPIFlag for clear
delayus(200);
//SPDAT = number;//收到数据后立即发送
}
评论0