You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

136 lines
1.9 KiB

#include "myiic1.h"
#include "delay.h"
//产生MYMYIIC11起始信号
void MYIIC1_Start(void)
{
SDA1_OUT(); //sda线输出
MYIIC1_SDA=1;
MYIIC1_SCL=1;
delay_us(4);
MYIIC1_SDA=0; //SDA 由高变低
delay_us(4);
MYIIC1_SCL=0; //准备发送或接收数据
}
//产生MYIIC1停止信号
void MYIIC1_Stop(void)
{
SDA1_OUT(); //sda线输出
MYIIC1_SCL=0;
MYIIC1_SDA=0;
delay_us(4);
MYIIC1_SCL=1; //SDA 由低变高
delay_us(4);
MYIIC1_SDA=1; //发送I2C总线结束信号
delay_us(4);
}
//等待应答信号到来
//返回值:1,接收应答失败
// 0,接收应答成功
u8 MYIIC1_Wait_Ack(void)
{
u8 ucErrTime=0;
SDA1_IN(); //SDA设置为输入
MYIIC1_SDA=1;delay_us(1);
MYIIC1_SCL=1;delay_us(1);
while(READ1_SDA)
{
ucErrTime++;
if(ucErrTime>250)
{
MYIIC1_Stop();
return 1;
}
}
MYIIC1_SCL=0;//时钟输出0
return 0;
}
//产生ACK应答
void MYIIC1_Ack(void)
{
MYIIC1_SCL=0;
SDA1_OUT();
MYIIC1_SDA=0;
delay_us(2);
MYIIC1_SCL=1;
delay_us(2);
MYIIC1_SCL=0;
}
//不产生ACK应答
void MYIIC1_NAck(void)
{
MYIIC1_SCL=0;
SDA1_OUT();
MYIIC1_SDA=1;
delay_us(2);
MYIIC1_SCL=1;
delay_us(2);
MYIIC1_SCL=0;
}
//MYIIC1发送一个字节
void MYIIC1_Send_Byte(u8 txd)
{
u8 t;
SDA1_OUT();
MYIIC1_SCL=0;//拉低时钟开始数据传输
for(t=0;t<8;t++)
{
if((txd&0x80)>>7)
MYIIC1_SDA=1;
else
MYIIC1_SDA=0;
txd<<=1;
delay_us(2);
MYIIC1_SCL=1;
delay_us(2);
MYIIC1_SCL=0;
delay_us(2);
}
}
//读1个字节,ack=1时,发送ACK应答,ack=0,发送nACK(不应答)
u8 MYIIC1_Read_Byte(unsigned char ack)
{
unsigned char i,receive=0;
SDA1_IN();//SDA设置为输入
for(i=0;i<8;i++ )
{
MYIIC1_SCL=0;
delay_us(2);
MYIIC1_SCL=1;
receive<<=1;
if(READ1_SDA)receive++;
delay_us(1);
}
if (!ack)
MYIIC1_NAck();//发送nACK
else
MYIIC1_Ack(); //发送ACK
return receive;
}