SPI 总线在单片机系统中的实现 2007-04-28 10:56 来源:mcuzb //-----------------------函数声明,变量定义------------------------------------------#include #include sbit SCK=P1^0; // 将p1.0 口模拟时sbit MOSI=P1^1; // 将p1.1 口模拟主机sbit MISO=P1^2; // 将p1.2 口模拟主机sbit SS1=P1^3; // 将p1.3 口模拟片#define delayNOP(); {_nop_();_nop_();_nop_();_nop_();}; //-----------------------------------------------------------------------------------// 函数名称: SPISendByte // 入口参数: ch // 函数功能: 发送一个字节 //-----------------------------------------------------------------------------------void SPISendByte(unsigned char ch) { unsigned char idata n=8; // 向 SDA 上发送一位数据字节,共八位 SCK = 1 ; //时钟置高 SS1 = 0 ; //选择从机 while(n--) { delayNOP(); SCK = 0 ; //时钟置低 if((ch&0x80) == 0x80) // 若要发送的数据最高位为 1 则发送位 { MOSI = 1; // 传送位 1 } else { MOSI = 0; // 否则传送位 0 } delayNOP(); ch = ch<<1; // 数据左移一位 SCK = 1 ; //时钟置高 } } //-----------------------------------------------------------------------------------// 函数名称: SPIreceiveByte // 返回接收的数据 // 函数功能: 接收一字节子程序 //-----------------------------------------------------------------------------------unsigned char SPIreceiveByte() { unsigned char idata n=8; // 从 MISO 线上读取一上数据字节,共八位 unsigned char tdata; SCK = 1; //时钟为高 SS1 = 0; //选择从机 while(n--) { delayNOP(); SCK = 0; //时钟 delayNOP(); tdata = tdata<<1; // 左移一位,或_crol_(temp,1) if(MISO == 1) tdata = tdata|0x01; // 若接收到的位为 1,则数据的最后一位置 1 else tdata = tdata&0xfe; // 否则数据的最后一位置 0 SCK=1; } return(tdata); } //-----------------------------------------------------------------------------------// 函数名称: SPIsend_receiveByte // 入口参数: ch // 返回接收的数据 // 函数功能:串...