微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 嵌入式设计 > MSP430单片机模式IIC协议C语言程序

MSP430单片机模式IIC协议C语言程序

时间:11-28 来源:互联网 点击:
#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;

}

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top