#include “msp430x22x4.h”
#define I2C_SDA(operation) operation(3,1)
#define I2C_SCL(operation) operation(3,2)
#define PORT_SET(port,bit) P##port##OUT|=(1<
#define PORT_CLR(port,bit) P##port##OUT&=~(1<
#define SET_GPIO_MODE(port,bit) P##port##SEL&=~(1<
#define SET_OUTPUT_MODE(port,bit) P##port##DIR|=(1<
#define SET_INPUT_MODE(port,bit) P##port##DIR&=~(1<
#define DISABLE_PULL_RESISTOR(port,bit) P##port##REN&=~(1<
#define READ_PORT(port,bit) P##port##IN&(1<
void I2C_init()
{
I2C_SDA(SET_GPIO_MODE);I2C_SCL(SET_GPIO_MODE);
I2C_SDA(DISABLE_PULL_RESISTOR);I2C_SCL(DISABLE_PULL_RESISTOR);
I2C_SDA(SET_INPUT_MODE);I2C_SCL(SET_INPUT_MODE);
I2C_SDA(PORT_CLR);I2C_SCL(PORT_CLR);
}
void Start(void)
{
I2C_SCL(SET_INPUT_MODE); //SCL=1
_NOP();
I2C_SDA(SET_INPUT_MODE); //SDA=1
_NOP();
I2C_SDA(SET_OUTPUT_MODE); //SDA=0
}
void Stop(void)
{
I2C_SCL(SET_OUTPUT_MODE); //SCL=0
_NOP();
I2C_SDA(SET_OUTPUT_MODE); //SDA=0
_NOP();
I2C_SCL(SET_INPUT_MODE); //SCL=1
_NOP();
I2C_SDA(SET_INPUT_MODE); //SDA=1
}
void Transfer(unsigned char data)
{
unsigned char i;
for(i=0;i<8;i++)
{
I2C_SCL(SET_OUTPUT_MODE); //SCL=0
if(data&0x80)I2C_SDA(SET_INPUT_MODE); //SDA=1
else I2C_SDA(SET_OUTPUT_MODE); //SDA=0
data=data<<1;
I2C_SCL(SET_INPUT_MODE); //SCL=1
}
}
unsigned char Acknowledge(void)
{
I2C_SCL(SET_OUTPUT_MODE); //SCL=0
_NOP();
I2C_SDA(SET_INPUT_MODE); //release SDA
_NOP();
I2C_SCL(SET_INPUT_MODE); //SCL=1
if(I2C_SDA(READ_PORT)) return 0xff;
else return 0;
}
unsigned char I2C_Write_Byte(unsigned char device_address, unsigned char data)
{
Start();
Transfer(device_address&0xfe);
if(Acknowledge()!=0)return 0x00;
Transfer(data);
if(Acknowledge()!=0)return 0x00;
Stop();
return 0xff;
}
unsigned char I2C_Write_Word(unsigned char device_address, unsigned int data)
{
unsigned char LowByte, HighByte;
LowByte=(unsigned char)data;
HighByte=(unsigned char)(data >> 8);
Start();
Transfer(device_address&0xfe);
if(Acknowledge()!=0)return 0x00;
Transfer(HighByte);
if(Acknowledge()!=0)return 0x00;
Transfer(LowByte);
if(Acknowledge()!=0)return 0x00;
Stop();
return 0xff;
}
声明:本文内容来自网络转载或用户投稿,文章版权归原作者和原出处所有。文中观点,不代表本站立场。若有侵权请联系本站删除(kf@86ic.com)https://www.86ic.net/dianyuan/kaiguan/255873.html