2.发送程序:clock拉低,sdo输出0或1(数据),延时一定时间,clock拉高,延时一定时间,这样A就发送一位数据到B,循环8次就发送一个字节数据
3.接收程序:检测clock状态,如果为低,就读取sdi,直到clock拉高,结束该次输入,重复8次,读取一个字节
注意:
1。clock空闲状态为高,发送数据就拉低;
2.还需要加入起始停止同步协议,可根据需要进行完善
这是 读写pcf2127a的程序。用spi接口。cpu 是51兼容系列 cy7c68013
#define spi_read 0x20
#define spi_write 0xa0
void spi_start(void)
{ OEE|=spi_ce+spi_di+spi_clk
OEE &= ~spi_do
SYNCDELAY
IOE&=~(spi_ce|spi_clk)
SYNCDELAY
}
void spi_stop(void)
{
IOE |=spi_ce
SYNCDELAY
}
void spi_wr(unsigned char command)
{
char i
for (i=0i<8i++)
{
if((command&0x80)==0x80) {IOE |=spi_di}else {IOE &=~spi_di}
command<<=1
SYNCDELAY
IOE |=spi_clk
SYNCDELAY
IOE &=~spi_clk
SYNCDELAY
SYNCDELAY
}
}
unsigned char spi_rd(void)
{
unsigned char bret
char i
bret=0
for (i=0i<8i++)
{IOE |=spi_clk
bret<<=1
SYNCDELAY
SYNCDELAY
if((IOE&spi_do)==spi_do){ bret++}
IOE &= ~spi_clk
SYNCDELAY
SYNCDELAY
}
return bret
}
void spi_writedata(unsigned char address,unsigned char command)
{
address&=0x1f
address|=0x20
spi_start()
spi_wr(address)
SYNCDELAY
spi_wr(command)
spi_stop()
}
unsigned char spi_readdata(unsigned char address)
{unsigned char bret
address&=0x1f
address |=0xa0
spi_start()
spi_wr(address)
SYNCDELAY
bret=spi_rd()
spi_stop()
return bret
}
void read_time(unsigned char address)
{spi_start()
spi_wr(address|0xa0)
EP0BUF[8] =spi_rd()//秒
EP0BUF[9]= spi_rd()//分
EP0BUF[10]= spi_rd()//时
EP0BUF[11]= spi_rd()//日
EP0BUF[12]= spi_rd()
hEP0BUF[13]= spi_rd()//月
EP0BUF[14]= spi_rd()//年
spi_stop()
}
void write_ram(unsigned int address,unsigned int command)
{unsigned char addh,addl,commandh,commandl
addh=(address&0xff00)>>8
addl=address&0x00ff
commandh=(command&0xff00)>>8
commandl=command&0x00ff
spi_writedata(0x1a,addh)
spi_writedata(0x1b,addl)
spi_writedata(0x1c,commandh)
spi_writedata(0x1c,commandl)
}
unsigned int read_ram(unsigned int address)
{
unsigned char addh,addl,commandh,commandl
unsigned int command
addh=(address&0xff00)>>8
addl=address&0x00ff
spi_writedata(0x1a,addh)
spi_writedata(0x1b,addl)
commandl=spi_readdata(0x1d)
commandh=spi_readdata(0x1d)
command=(commandh<<8)+commandl
return command
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)