#ifndef __MYIIC_H_
#define __MYIIC_H_
#include "common.h"
#include "delay.h"
#include "debugserial.h"
//sda 027 scl 028
//IO方向设置
#define IIC1_SDA_IN() P0dir(27) = 0
#define IIC1_SDA_OUT() P0dir(27) = 1
//IO操作函数
#define IIC1_READ_SDA P0in(27) //输入SDA
void my_iic_init(void); //初始化IIC的IO口
void my_iic_start(void); //发送IIC开始信号
void my_iic_stop(void); //发送IIC停止信号
void my_iic_sendByte(u8 txd); //IIC发送一个字节
u8 my_iic_readByte(void); //IIC读取一个字节
u8 my_iic_waitAck(void); //IIC等待ACK信号
void my_iic_ack(void); //IIC发送ACK信号
void my_iic_nAck(void); //IIC不发送ACK信号
#endif
#include "myiic.h"
//该驱动针对模拟IIC操作
void my_iic_init(void) //初始化IIC的IO口
{
LPC_SC->PCONP |= (1<<15);
LPC_IOCON->P0_27 = 0x00;//选择gpio功能,禁止迟滞 不反向 正常推挽
LPC_IOCON->P0_27 |= (1<<8);//与引脚配置相关 根据实际引脚进行修改
LPC_IOCON->P0_28 = 0x00;//选择gpio功能,禁止迟滞 不反向 正常推挽
LPC_IOCON->P0_28 |= (1<<8);//与引脚配置相关 根据实际引脚进行修改
P0dir(27) = 1;//scl输出
P0dir(28) = 1;//sda输出
P0high(27) = 1;//初始化都是高电平
P0high(28) = 1;
}
void my_iic_start(void) //发送IIC开始信号
{
IIC1_SDA_OUT(); //sda线输出
P0high(27)=1; //SDA HIGH
P0high(28)=1; //SCL HIGH
DelayUs(5);
P0low(27)=1; //SDA LOW
DelayUs(5);
P0low(28)=1; //SCL LOW
}
void my_iic_stop(void) //发送IIC停止信号
{
IIC1_SDA_OUT(); //sda线输出
P0high(28)=1; //SCL HIGH
P0low(27)=1; //SDA LOW
DelayUs(5);
P0high(27)=1; //发送I2C总线结束信号 SDA HIGH
DelayUs(5);
}
void my_iic_sendByte(u8 txd) //IIC发送一个字节
{
u8 t;
IIC1_SDA_OUT();
for(t=0;t<8;t++)
{
if(((txd&0x80)>>7))
P0high(27) = 1;
else
P0low(27) = 1;
txd<<=1;
P0high(28)=1; //SCL HIGH
DelayUs(5);
P0low(28)=1; //SCL LOW
DelayUs(5);
}
}
u8 my_iic_readByte(void) //IIC读取一个字节
{
unsigned char i,receive=0;
IIC1_SDA_IN();//SDA设置为输入
for(i=0;i<8;i++ )
{
receive<<=1;
P0high(28)=1; //SCL HIGH
DelayUs(5);
if(IIC1_READ_SDA)receive++;
P0low(28)=1; //SCL LOW
DelayUs(5);
}
return receive;
}
u8 my_iic_waitAck(void) //IIC等待ACK信号
{
u8 ucErrTime=0;
IIC1_SDA_OUT();
P0high(27)=1; //SDA HIGH
DelayUs(5);
IIC1_SDA_IN(); //SDA设置为输入
P0high(28)=1; //SCL HIGH
DelayUs(5);
while(IIC1_READ_SDA)
{
ucErrTime++;
DelayUs(1);
if(ucErrTime>250)
{
my_iic_stop();
return 1;
}
}
P0low(28)=1; //时钟输出 SCL LOW
DelayUs(5);
return 0;
}
void my_iic_ack(void) //IIC发送ACK信号
{
IIC1_SDA_OUT();
P0low(27)=1; //SDA LOW
DelayUs(2);
P0high(28)=1; //SCL HIGH
DelayUs(5);
P0low(28)=1; //SCL LOW
DelayUs(5);
}
void my_iic_nAck(void) //IIC不发送ACK信号
{
IIC1_SDA_OUT();
P0high(27)=1; //SDA HIGH
DelayUs(2);
P0high(28)=1; //SCL HIGH
DelayUs(5);
P0low(28)=1; //SCL LOW
DelayUs(5);
}