MSP430f5529模拟IIC协议

MSP430f5529模拟IIC协议

读取数据之前需要释放总线,被这问题卡了好久

#include "msp430f5529.h"
//P8.1 SCL
//P8.2 SDA
#define    SCL_HIGH    P8OUT|=BIT1
#define    SCL_LOW     P8OUT&=~BIT1
#define    SDA_HIGH    P8OUT|=BIT2
#define    SDA_LOW     P8OUT&=~BIT2
#define    SDA_OUT     P8DIR|=BIT2
#define    SDA_IN      P8DIR&=~BIT2
#define    SCL_OUT     P8DIR|=BIT1
#define    SDA         P8IN&BIT2

void IIC_start();
void IIC_stop();
void IIC_writebyte(unsigned char IIC_byte);
unsigned char IIC_readebyte();
unsigned char IIC_testACK();
void IIC_masterACK();
void IIC_masterNACK();

void IIC_start()
{
    
    
	SDA_OUT;
	SCL_OUT;
    SCL_HIGH;
    SDA_HIGH;
    __delay_cycles(10);
    SDA_LOW;
    __delay_cycles(10);
    SCL_LOW;
}

void IIC_stop()
{
    
    
	SDA_OUT;
	SCL_OUT;
    SCL_LOW;
    SDA_LOW;
    __delay_cycles(10);
    SCL_HIGH;
    __delay_cycles(10);
    SDA_HIGH;
    __delay_cycles(10);
}

void IIC_writebyte(unsigned char IIC_byte)
{
    
    
    unsigned char i;
	SDA_OUT;
	SCL_OUT;
	SCL_LOW;
	__delay_cycles(10);
    for(i=0;i<8;i++)  
    {
    
    
        if(IIC_byte&0x80)    //写1
            SDA_HIGH;
        else                 //写0
            SDA_LOW;
		__delay_cycles(10);
        SCL_HIGH;
	    __delay_cycles(10);
        SCL_LOW;
	    __delay_cycles(10);
        IIC_byte<<=1;         //循环左移,取最高位
    }
}

unsigned char IIC_readebyte()
{
    
    
    unsigned char i,k=0; 
	SDA_IN;       //SDA设置为输入
	SCL_OUT;
	SCL_LOW;
	__delay_cycles(50);
	for(i=0;i<8;i++)
	{
    
    
		SCL_HIGH;
		k=k<<1;
		if(SDA)
			k|=1;
        SCL_LOW;
        __delay_cycles(50);
	}
	SDA_OUT;        //SDA设置为输出
	__delay_cycles(50);
	return k;
}

unsigned char IIC_testACK()
{
    
    
	SCL_LOW;
	//SDA_IN;       //SDA设置为输入
	//SDA_UP;
	__delay_cycles(50);
	SCL_HIGH;
	__delay_cycles(50);
	SCL_LOW;
	//SDA_OUT;        //SDA设置为输出
	__delay_cycles(50);
	return 1;	
}

void IIC_masterACK()
{
    
       
    SDA_OUT;
	SCL_OUT;
	SCL_LOW;
	SDA_LOW;
    SCL_HIGH;
	__delay_cycles(5);
	SCL_LOW;
	__delay_cycles(5);
}
	
void IIC_masterNACK()
{
    
    
	SDA_OUT;
	SCL_OUT;
	SCL_LOW;
	SDA_HIGH;
	__delay_cycles(5);
    SCL_HIGH;
	__delay_cycles(5);
	SCL_LOW;
	__delay_cycles(5);	
}

猜你喜欢

转载自blog.csdn.net/qq_43710693/article/details/103172993