lpc1788IO口模擬IIC
#ifndef __MYIIC_H_
#define __MYIIC_H_
#include "common.h"
#include "delay.h"
#include "debugserial.h"
//sda 027 scl 028
//IO方向設(shè)置
#define IIC1_SDA_IN() P0dir(27) = 0
#define IIC1_SDA_OUT() P0dir(27) = 1
//IO操作函數(shù)
#define IIC1_READ_SDA P0in(27) //輸入SDA
void my_iic_init(void); //初始化IIC的IO口
void my_iic_start(void); //發(fā)送IIC開(kāi)始信號(hào)
void my_iic_stop(void); //發(fā)送IIC停止信號(hào)
void my_iic_sendByte(u8 txd); //IIC發(fā)送一個(gè)字節(jié)
u8 my_iic_readByte(void);//IIC讀取一個(gè)字節(jié)
u8 my_iic_waitAck(void); //IIC等待ACK信號(hào)
void my_iic_ack(void); //IIC發(fā)送ACK信號(hào)
void my_iic_nAck(void); //IIC不發(fā)送ACK信號(hào)
#endif
#include "myiic.h"
//該驅(qū)動(dòng)針對(duì)模擬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);//與引腳配置相關(guān) 根據(jù)實(shí)際引腳進(jìn)行修改
LPC_IOCON->P0_28=0x00;//選擇gpio功能,禁止遲滯 不反向 正常推挽
LPC_IOCON->P0_28|=(1<<8);//與引腳配置相關(guān) 根據(jù)實(shí)際引腳進(jìn)行修改
P0dir(27)=1;//scl輸出
P0dir(28)=1;//sda輸出
P0high(27)=1;//初始化都是高電平
P0high(28)=1;
}
void my_iic_start(void) //發(fā)送IIC開(kāi)始信號(hào)
{
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) //發(fā)送IIC停止信號(hào)
{
IIC1_SDA_OUT(); //sda線輸出
P0high(28)=1; //SCL HIGH
P0low(27)=1; //SDA LOW
DelayUs(5);
P0high(27)=1; //發(fā)送I2C總線結(jié)束信號(hào) SDA HIGH
DelayUs(5);
}
void my_iic_sendByte(u8 txd) //IIC發(fā)送一個(gè)字節(jié)
{
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讀取一個(gè)字節(jié)
{
unsigned char i,receive=0;
IIC1_SDA_IN();//SDA設(shè)置為輸入
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);
}
returnreceive;
}
u8 my_iic_waitAck(void) //IIC等待ACK信號(hào)
{
u8 ucErrTime=0;
IIC1_SDA_OUT();
P0high(27)=1; //SDA HIGH
DelayUs(5);
IIC1_SDA_IN(); //SDA設(shè)置為輸入
P0high(28)=1; //SCL HIGH
DelayUs(5);
while(IIC1_READ_SDA)
{
ucErrTime++;
DelayUs(1);
if(ucErrTime>250)
{
my_iic_stop();
return1;
}
}
P0low(28)=1; //時(shí)鐘輸出 SCL LOW
DelayUs(5);
return0;
}
void my_iic_ack(void) //IIC發(fā)送ACK信號(hào)
{
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不發(fā)送ACK信號(hào)
{
IIC1_SDA_OUT();
P0high(27)=1; //SDA HIGH
DelayUs(2);
P0high(28)=1; //SCL HIGH
DelayUs(5);
P0low(28)=1; //SCL LOW
DelayUs(5);
}