|
供参考....
/**
******************************************************************************
* @file Dev_I2C.c
* @brief I2C共用的C文件..
* @author WuHan P&S 电力电子组.
* @version V 0.0.1
* @Target STM8L
* @date 11/10/2009
******************************************************************************
*/
#include "dev_i2c.h"
void I2C_Delay(u32 nCount)
{
/* Decrement nCount value */
while (nCount != 0)
{
nCount--;
}
}
// 释放I2C总线.
void I2C_BusRelease(void)
{
GPIO_Init(I2C_PORT, (I2C_SDA_PIN | I2C_SCL_PIN), GPIO_Mode_Out_PP_High_Fast);
I2C_Delay(500);
GPIO_WriteBit( I2C_PORT, I2C_SCL_PIN, RESET ); // SCL为低
GPIO_WriteBit( I2C_PORT, I2C_SDA_PIN, RESET ); // SDA为低
I2C_Delay( 500 );
GPIO_WriteBit( I2C_PORT, I2C_SCL_PIN, SET ); // SCL 为高
I2C_Delay( 500 );
GPIO_WriteBit( I2C_PORT, I2C_SDA_PIN, SET ); // SDA 为高
I2C_Delay( 500 );
}
/**
* @brief Initializes the I2C peripheral registers to communicate the EEPROM
* @par Parameters:
* None
* @retval None
* @par Required preconditions:
* None
*/
I2C_Op_TypeDef I2C_BusInit(void)
{
u32 lu32TimeOut;
I2C_BusRelease();
I2C_BusRelease();
I2C_BusRelease();
/* Optional: put here as example only */
I2C_DeInit( I2C1);
/*Enable I2C1 clock */
CLK_PeripheralClockConfig(CLK_Peripheral_I2C1, ENABLE);
/* I2C Peripheral Enable */
I2C_Cmd(I2C1, ENABLE);
/* Apply I2C configuration after enabling it */
I2C_Init(I2C1, I2C_Speed, I2C_OWN_ADDRESS7, I2C_Mode_I2C, I2C_DutyCycle_2, I2C_Ack_Enable, I2C_AcknowledgedAddress_7bit );
I2C_Delay( 100 );
while(I2C_GetFlagStatus(I2C1, I2C_FLAG_BUSY ))
{
if( lu32TimeOut ++ >= CNT_I2C_DELAY_COUNT )
{
return CNT_I2C_FAIL;
}
}
return CNT_I2C_SUCCESS;
}
/**
******************************************************************************
* @file Dev_I2C.h
* @brief I2C共用的头文件..
* @author WuHan P&S 电力电子组.
* @version V 0.0.1
* @Target STM8L
* @date 11/10/2009
******************************************************************************
*/
#ifndef __DEV_I2C__H
#define __DEV_I2C_H
/* Includes ------------------------------------------------------------------*/
#include "stm8l15x.h"
#define I2C_Speed 100000
#define I2C_OWN_ADDRESS7 0x88
// 若是STM8S2XX时,I2C的SCL--PE1, SDA--PE2.
#define I2C_PORT GPIOC
#define I2C_SDA_PIN GPIO_Pin_0
#define I2C_SCL_PIN GPIO_Pin_1
#define CNT_I2C_DELAY_COUNT 1000
typedef enum
{
CNT_I2C_SUCCESS = (u8) 1, // 操作成功
CNT_I2C_FAIL = (u8) 0 // 操作失败
} I2C_Op_TypeDef; // E2操作类.
void I2C_Delay(u32 u32Count);
// 释放I2C总线.
void I2C_BusRelease(void);
// I2C 初始化.
I2C_Op_TypeDef I2C_BusInit(void);
#endif // _DEV_I2C_H |
|