1. 程式人生 > >STM32 IIC

STM32 IIC

/***************
 ****************
 Time:2016.12.8
 Name:MichaelBeechan
 Dress:Chongqing university of science and technology
****************
****************/
#include "IIC.h"
void I2C_init()  //IIC init
{
GPIO_InitTypeDef GPIO_InitStructure; //define GPIO structure pointer
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);   //open PA(GPIO) clock 

GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Pin = I2C_SCL|I2C_SDA;    
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;  //push-pull output
GPIO_Init(GPIOA,&GPIO_InitStructure);   //GPIO init

I2C_SCL_H;  //idle state for high level
I2C_SDA_H;
}




void I2C_SDA_OUT() //SDA output
{
GPIO_InitTypeDef GPIO_InitStructure; //define GPIO structure pointer

GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Pin = I2C_SDA;    
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;  //push-pull output
GPIO_Init(GPIOA,&GPIO_InitStructure);   //GPIO init
}
void I2C_SDA_IN() //SDA input
{
GPIO_InitTypeDef GPIO_InitStructure; //define GPIO structure pointer

GPIO_InitStructure.GPIO_Pin = I2C_SDA;    
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;  //up-pull input
GPIO_Init(GPIOA,&GPIO_InitStructure);   //GPIO init
}


//According to timing sequence compile
void I2C_Start() //Start signal
{
I2C_SDA_OUT(); //SDA output

I2C_SDA_H;
I2C_SCL_H;
delay_us(5);
I2C_SDA_L;
delay_us(6);
I2C_SCL_L;
}
void I2C_Stop() //stop signal
{
I2C_SDA_OUT(); //SDA output

I2C_SCL_L;
I2C_SDA_L;
I2C_SCL_H;
delay_us(6);
I2C_SDA_H;
delay_us(6);
}
void I2C_Ack() //boss ack...Main engine ack
{
I2C_SCL_L;
I2C_SDA_OUT(); //SDA output
I2C_SDA_L;
delay_us(2);
I2C_SCL_H;
delay_us(5);
I2C_SCL_L;
}
void I2C_NAck()  //boss No_ack...Main engine no_ack  
{
I2C_SCL_L;
I2C_SDA_OUT(); //SDA output
I2C_SDA_H;
delay_us(2);
I2C_SCL_H;
delay_us(5);
I2C_SCL_L;
}
u8 I2C_Wait_Ack() //wait slave(從機) ack :return 1 --> ack failure;return 0 --> ack success
{
u8 tempTime = 0;
I2C_SDA_IN();
I2C_SDA_H;
delay_us(1);
I2C_SCL_H;
delay_us(1);

while(GPIO_ReadInputDataBit(GPIO_I2C,I2C_SDA))
{
tempTime ++;
if(tempTime > 250)
{
I2C_Stop();
return 1;
}
}
I2C_SCL_L;
return 0;
}
void I2C_Send_Byte(u8 txd)
{
u8 i = 0;
I2C_SDA_OUT(); //SDA output
I2C_SCL_L; //only low power can ensure data line change or else data line stable
for(i = 0; i < 8; i ++)
{
if((txd&0x80) > 0)
{
I2C_SDA_H;
}
else 
{
I2C_SDA_L;
}
txd <<= 1;
I2C_SCL_H;
delay_us(2);
I2C_SCL_L;
delay_us(2);
}
}
u8 I2C_Read_Byte(u8 ack)
{
u8 i = 0, receive = 0;
I2C_SDA_IN();

for(i = 0; i < 8; i ++)
{
I2C_SCL_L;
delay_us(2);
I2C_SCL_H;
receive <<= 1;
if(GPIO_ReadInputDataBit(GPIO_I2C,I2C_SDA))
{
receive ++;
}
delay_us(1);

}
if(ack == 0)
{
I2C_NAck();  //boss No_ack...Main engine no_ack  
}
else
{
I2C_Ack();  //boss ack...Main engine ack  
}
return receive;

}