用过MCP23S08的请进,请教下
我现在用51模拟SPI控制MCP23S08低4位输出,高4为输入
现在能写但读不出来,不过写的时候乱跳。比如控制第二口输出1时老是1,0的乱跳还会波及到其他口
请教下经验模拟SPI应该怎样写呢
下面的SO,SI为MCP23S08上的引脚
#define MCP_ADD0x40 //
#define IODIR 0x00
#define GPPU 0x06
#define GPIO 0x09
#define IOCON 0x05
#define OLAT 0x0a
sbit sck=P3^2;
sbit si =P3^4;
sbit so =P3^3;
sbit cs =P3^5;
unsigned char spiin(void)
{
unsigned char readdata=0,count;
for(count=0;count<8;count++)
{
readdata<<=1;
sck=0;delay(2);
sck=1;delay(2);
if(so)readdata|=0x01;
else readdata&=0xfe;
delay(2);
}
return (readdata);
}
void spiout(unsigned char dat)
{
unsigned char i,maskcode=0x80;
for(i=0;i<8;i++)
{
if(maskcode&dat) si=1;
elsesi=0;
sck=0; delay(2);
sck=1; delay(2);
maskcode>>=1;
delay(2);
}
}
void spiwrite(unsigned char device_add,unsigned char add,unsigned char dat)
{
cs=0;
spiout(device_add);
spiout(add);
spiout(dat);
cs=1;
}
unsigned char spiread(unsigned char device_add,unsigned char add)
{
unsigned char dat=0;
cs=0;
spiout(device_add|0x01);
spiout(add);
dat=spiin();
cs=1;
return dat;
} 下面是主程序用到的
spiwrite(MCP_ADD,IODIR,0xF0);
spiwrite(MCP_ADD,GPIO,0x00);初始化
spiwrite(MCP_ADD,GPIO,0x01);
spiwrite(MCP_ADD,GPIO,0x02);端口输出
dat=spiread(MCP_ADD,GPIO);读端口
页:
[1]