嵌入式单片机设计吧 关注:24贴子:93
  • 0回复贴,共1

51单片机IIC驱动程序

只看楼主收藏回复

//SCL<->PB7
//SDA<->PB8
//IM<->PB9
sbit IIC_SCL = P1^0;
sbit IIC_SDA = P1^1;
//???IIC
void IIC_Init(void)
{
IIC_SCL=1;
IIC_SDA=1;
}
void delay_us(char num)
{
_nop_();_nop_();_nop_();_nop_();
_nop_();_nop_();_nop_();_nop_();
_nop_();_nop_();_nop_();_nop_();
_nop_();_nop_();_nop_();_nop_();
}
//??IIC????
void IIC_Start(void)
{
//SDA_OUT(); //sda???
IIC_SDA=1;
IIC_SCL=1;
delay_us(4);
IIC_SDA=0;//START:when CLK is high,DATA change form high to low
delay_us(4);
IIC_SCL=0;//??I2C??,?????????
}
//??IIC????
void IIC_Stop(void)
{
//SDA_OUT();//sda???
IIC_SCL=0;
IIC_SDA=0;//STOP:when CLK is high DATA change form low to high
delay_us(4);
IIC_SCL=1;
IIC_SDA=1;//??I2C??????
delay_us(4);
}
//????????
//???:1,??????
// 0,??????
u8 IIC_Wait_Ack(void)
{
u8 ucErrTime=0;
//SDA_IN(); //SDA?????
IIC_SDA=1;delay_us(1);
IIC_SCL=1;delay_us(1);
while(IIC_SDA)
{
ucErrTime++;
if(ucErrTime>250)
{
IIC_Stop();
return 1;
}
}
IIC_SCL=0;//????0
return 0;
}
//??ACK??
void IIC_Ack(void)
{
IIC_SCL=0;
//SDA_OUT();
IIC_SDA=0;
delay_us(2);
IIC_SCL=1;
delay_us(2);
IIC_SCL=0;
}
//???ACK??
void IIC_NAck(void)
{
IIC_SCL=0;
//SDA_OUT();
IIC_SDA=1;
delay_us(2);
IIC_SCL=1;
delay_us(2);
IIC_SCL=0;
}
//IIC??????
//????????
//1,???
//0,???
void IIC_Send_Byte(u8 txd)
{
u8 t;
//SDA_OUT();
IIC_SCL=0;//??????????
for(t=0;t<8;t++)
{
IIC_SDA=(txd&0x80)>>7;
txd<<=1;
delay_us(2); //?TEA5767??????????
IIC_SCL=1;
delay_us(2);
IIC_SCL=0;
delay_us(2);
}
}
//?1???,ack=1?,??ACK,ack=0,??nACK
u8 IIC_Read_Byte(unsigned char ack)
{
unsigned char i,receive=0;
//SDA_IN();//SDA?????
for(i=0;i<8;i++ )
{
IIC_SCL=0;
delay_us(2);
IIC_SCL=1;
receive<<=1;
if(IIC_SDA)receive++;
delay_us(1);
}
if (!ack)
IIC_NAck();//??nACK
else
IIC_Ack(); //??ACK
return receive;
}
void IIC_WriteBytes(u8 WriteAddr,u8* datas,u8 dataLength)
{
u8 i;
IIC_Start();
IIC_Send_Byte(WriteAddr); //?????
IIC_Wait_Ack();
for(i=0;i<dataLength;i++)
{
IIC_Send_Byte(datas[i]);
IIC_Wait_Ack();
}
IIC_Stop();//????????
delay_ms(10);
}
void IIC_ReadBytes(u8 deviceAddr, u8 writeAddr,u8* datas,u8 dataLength)
{
u8 i;
IIC_Start();
IIC_Send_Byte(deviceAddr); //?????
IIC_Wait_Ack();
IIC_Send_Byte(writeAddr);
IIC_Wait_Ack();
IIC_Send_Byte(deviceAddr|0X01);//??????
IIC_Wait_Ack();
for(i=0;i<dataLength-1;i++)
{
datas[i] = IIC_Read_Byte(1);
}
datas[dataLength-1] = IIC_Read_Byte(0);
IIC_Stop();//????????
delay_ms(10);
}
void IIC_Read_One_Byte(u8 daddr,u8 addr,u8* datas)
{
IIC_Start();
IIC_Send_Byte(daddr); //?????
IIC_Wait_Ack();
IIC_Send_Byte(addr);//????
IIC_Wait_Ack();
IIC_Start();
IIC_Send_Byte(daddr|0X01);//??????
IIC_Wait_Ack();
*datas = IIC_Read_Byte(0);
IIC_Stop();//????????
}
void IIC_Write_One_Byte(u8 daddr,u8 addr,u8 datas)
{
IIC_Start();
IIC_Send_Byte(daddr); //?????
IIC_Wait_Ack();
IIC_Send_Byte(addr);//????
IIC_Wait_Ack();
IIC_Send_Byte(datas); //????
IIC_Wait_Ack();
IIC_Stop();//????????
delay_ms(10);
}


IP属地:北京1楼2022-05-09 16:21回复