幾種常用的模擬SPI讀寫一體化模塊(C51)
說明:
SPI接口有一個(gè)特點(diǎn),即在時(shí)鐘SCK的上升沿打入數(shù)據(jù)MOSI,在下降沿讀入數(shù)據(jù)MISO.
片選信號(hào)CS有正負(fù)區(qū)別.在硬件上MOSI與MISO是可以短路變?yōu)镾IO可讀寫IO的.
故SPI可為(不包括CS)
三線(SCK,MOSI,MISO)協(xié)議,兩線(SCK,SIO)協(xié)議
再者,SPI一般為雙向同時(shí)高速收發(fā)數(shù)據(jù)的,方向由時(shí)鐘SCK的跳變沿決定。
根據(jù)以上所述,模擬SPI讀寫模塊編制成為一體化模塊是必要的。
而且調(diào)用規(guī)則只需注意讀數(shù)據(jù)時(shí)要寫入0xff即可。非常方便好用。
例如:
res = SpiReadWrite(val);//模塊寫
SpiReadWrite(0xff);//模塊讀
對(duì)于具體器件,由于涉及到命令、地址及數(shù)據(jù)等,故一個(gè)完整的SPI讀或?qū)懖僮?br/>可能需要幾個(gè)模擬SPI讀寫一體化模塊來完成。
所以一般完整的SPI讀或?qū)懖僮餍枰韵潞瘮?shù)組合完成
void SpiOpen(void); //打開片選 CS=0或CS=1
void SpiClose(void); //關(guān)閉片選 CS=1或CS=0
unsigned char SpiReadWrite(val); //模擬SPI讀寫一體化模塊
void SpiWriteEnable(void); //使能寫操作
void SpiWriteDISAble(void); //禁止寫操作
unsigned char SpiReadStatus(void); //讀狀態(tài)
void SpiWriteStatus(unsigned char val); //寫狀態(tài)
void SpiWriteWait(void); //等待寫入完成
void SpiWriteByte(unsigned int addr, unsigned char val);//寫一個(gè)字節(jié)
void SpiWriteWord(unsigned char addr, unsigned int val);//寫一個(gè)字
unsigned char SpiReadByte(unsigned int addr); //讀一個(gè)字節(jié)
unsigned int SpiReadWord(unsigned char addr); //讀一個(gè)字
/*----------------------------------------------------------------------------
/*-----------------------------------------------
例:
X5045模擬SPI讀寫一體化模塊
PTR905模擬SPI讀寫一體化模塊
------------------------------------------------*
unsigned char SpiReadWrite(unsigned char val)
{
unsigned char i;
ACC = val;
for (i = 8; i > 0; i --)
{
CY = MISO;//取數(shù)據(jù)SO
_rlca_();//存數(shù)據(jù)ACC.0讀數(shù)據(jù)ACC.7同時(shí)進(jìn)行
MOSI = CY;//送數(shù)據(jù)SI
SCK = 1;//上升沿打入數(shù)據(jù)
_nop_();//延時(shí)
SCK = 0;//下降沿讀入數(shù)據(jù)
}
return ACC;
}
/*-----------------------------------------------
例:
X5045模擬SPI讀寫一體化模塊
ISD4004模擬SPI讀寫一體化模塊
------------------------------------------------*
unsigned char SpiReadWrite(unsigned char val)
{
unsigned char i;
ACC = val;
for (i = 8; i > 0; i --)
{
SCK = 0;//下降沿讀入數(shù)據(jù)
_nop_();//延時(shí)
CY = MISO;//取數(shù)據(jù)SO
_rlca_();//存數(shù)據(jù)ACC.0讀數(shù)據(jù)ACC.7同時(shí)進(jìn)行
MOSI = CY;//送數(shù)據(jù)SI
_nop_();//延時(shí)
SCK = 1;//上升沿打入數(shù)據(jù)
MOSI = 1;//釋放總線SI
}
return ACC;
}
/*-----------------------------------------------
例:
AT93C46模擬SPI讀寫模塊
------------------------------------------------*
sbit ACC_7 = ACC^7;
unsigned char SpiReadWrite(unsigned char val)
{
unsigned char i;
ACC = val;
for (i = 8; i > 0; i --)
{
CY = ACC_7;//讀數(shù)據(jù)ACC.7
MOSI = CY;//送數(shù)據(jù)SI
SCK = 1;//上升沿打入數(shù)據(jù)
CY = MISO;//取數(shù)據(jù)SO
_rlca_();//存數(shù)據(jù)ACC.0
SCK = 0;//下降沿
}
return ACC;
}