新聞中心

EEPW首頁 > 嵌入式系統 > 設計應用 > MSP430 IIC總線程序

MSP430 IIC總線程序

作者: 時間:2016-11-23 來源:網絡 收藏
#ifndef _I2C_H
#define _I2C_H
#define SDA_1 P4OUT|=0x02 //SDA = 1
#define SDA_0 P4OUT&=~0x02 //SDA = 0
#define SCL_1 P4OUT|=0x01 //SCL = 1
#define SCL_0 P4OUT&=~0x01 //SCL = 0
#define SDA_IN P4DIR&=~0x02; //I/O口為輸入
#define SDA_OUT P4DIR|=0x02 //I/0口為輸出
#define J_SDA_1_or_0 (P4IN&0x02)==0x02
//--------------------------------------------
//--------以下為24C64讀寫子函數
//DELAY 函數程序//功能:延時子程序
//==========================================
static void Delay(unsigned int n)
{
while(n!=0)
{n--;}
}
//=========================================
//START 函數程序
//功能:開始閃存操作
//==========================================
void Start(void)
{
SDA_OUT;
SDA_1;
Delay(10);
SCL_1;
Delay(10);
SDA_0;
Delay(10);
SCL_0;
Delay(10);
}
//=========================================
//STOP 函數程序
//功能:停止閃存操作
//==========================================
void Stop(void)
{
SDA_0;
Delay(10);
SCL_1;
Delay(10);
SDA_1;
Delay(10);
}

void TX_Byte(unsigned char WriteData)
{
unsigned char i,j;
j=WriteData;
SDA_OUT;
for (i=0; i<8; i++)
{
if ((j&0x80)==0)
{ SDA_0;}
else
{ SDA_1;}
j <<=1;
Delay(10);
SCL_1;
Delay(10);
SCL_0;
Delay(10);
}
}

unsigned char RX_Byte(void)
{
unsigned char i;
unsigned char TempData = 0;
SDA_IN;
for (i=0; i<8; i++)
{
Delay(10);
SCL_1;
Delay(10);
TempData <<= 1;
if (J_SDA_1_or_0)
{ TempData++; }
SCL_0;
Delay(10);
}
SDA_OUT;
return(TempData);
}
//=========================================
//ACK 函數程序
//功能:掛高電平表示閃存時鐘信號
//==========================================
void ReceiveAck(void)
{
SDA_IN;
SCL_1;
Delay(10);
while (J_SDA_1_or_0)
{}
SCL_0;
SDA_OUT;
Delay(10);
}

unsigned char ReadWord(unsigned long int unit)
{
unsigned char LowAdd= 0;
unsigned char HighAdd = 0;
unsigned charTempData = 0;
LowAdd= (unsigned char)unit;
HighAdd = (unsigned char)(unit >> 8);
SDA_OUT;
Start();
TX_Byte(0xa0);
ReceiveAck();
TX_Byte(HighAdd);
ReceiveAck();
TX_Byte(LowAdd);
ReceiveAck();
Start();
TX_Byte(0xa1);
ReceiveAck();
TempData= RX_Byte();
Stop();
Delay(8000);
return(TempData);
}

void WriteWord(unsigned long int unit, unsigned char WriteData)
{
unsigned char LowAdd= 0;
unsigned char HighAdd = 0;
LowAdd= (unsigned char)unit;
HighAdd = (unsigned char)(unit >> 8);
Start();
TX_Byte(0xa0);
ReceiveAck();
TX_Byte(HighAdd);
ReceiveAck();
TX_Byte(LowAdd);
ReceiveAck();
TX_Byte(WriteData);
ReceiveAck();
Stop();
Delay(8000);
}
#endif


關鍵詞: MSP430IIC總線程

評論


技術專區(qū)

關閉