stm32 软件IIC
.h文件
#ifndef __SOFT_IIC_H
#define __SOFT_IIC_H
#include "Sys.h"
#define SDA_IN() {GPIOB->CRL&=0X0FFFFFFF;GPIOB->CRL|=(u32)8<<28;}
#define SDA_OUT() {GPIOB->CRL&=0X0FFFFFFF;GPIOB->CRL|=(u32)3<<28;}
#define IIC_SCL PBout(6)
#define IIC_SDA PBout(7)
#define READ_SDA PBin(7)
typedef enum {ACK = 0, NOACK = !ACK} ACKfalg;
#define IS_ACK_PERIPH(ACKx) (((ACKx) == NOACK) || ((ACKx) == ACK))
typedef enum {NOSTOP = 0, STOP = !NOSTOP} STOPflag;
#define IS_STOP_PERIPH(STOPx) (((STOPx) == NOSTOP) || ((STOPx) == STOP))
void IIC_Init(void);
void IIC_Start(void);
ACKfalg IIC_Send_Byte(u8 txd, STOPflag STOPx);
u8 IIC_Read_Byte(ACKfalg ACKx);
#endif
.c文件
#include "soft_IIC.h"
void IIC_Init(void)
{
Delay_Init();
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE );
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6|GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP ;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
IIC_SCL=1;
IIC_SDA=1;
}
void IIC_Start(void)
{
SDA_OUT();
IIC_SDA=1;
IIC_SCL=1;
delay_us(4);
IIC_SDA=0;
delay_us(4);
IIC_SCL=0;
}
void IIC_Stop(void)
{
SDA_OUT();
IIC_SCL=0;
IIC_SDA=0;
delay_us(4);
IIC_SCL=1;
delay_us(4);
IIC_SDA=1;
delay_us(4);
}
ACKfalg IIC_Wait_Ack(void){
u8 ucErrTime=0;
IIC_SDA=1;
SDA_IN();
IIC_SCL=1;
while(READ_SDA)
{
ucErrTime++;
if(ucErrTime>250)
{
IIC_Stop();
return NOACK;
}
}
IIC_SCL=0;
return ACK;
}
ACKfalg IIC_Send_Byte(u8 txd, STOPflag STOPx)
{
u8 t;
assert_param(IS_STOP_PERIPH(STOPx));
SDA_OUT();
IIC_SCL=0;
for(t=0;t<8;t++)
{
IIC_SDA=(txd&0x80)>>7;
txd<<=1;
delay_us(2);
IIC_SCL=1;
delay_us(4);
IIC_SCL=0;
delay_us(2);
}
if(STOPx){
if(IIC_Wait_Ack()){
return NOACK;
}
IIC_Stop();
return ACK;
}
return IIC_Wait_Ack();
}
void IIC_Ack(void)
{
IIC_SCL=0;
SDA_OUT();
IIC_SDA=0;
delay_us(2);
IIC_SCL=1;
delay_us(4);
IIC_SCL=0;
}
void IIC_NAck(void)
{
IIC_SCL=0;
SDA_OUT();
IIC_SDA=1;
delay_us(2);
IIC_SCL=1;
delay_us(4);
IIC_SCL=0;
}
u8 IIC_Read_Byte(ACKfalg ACKx)
{
unsigned char i,receive=0;
assert_param(IS_ACK_PERIPH(ACKx));
SDA_IN();
for(i=0;i<8;i++ )
{
IIC_SCL=0;
delay_us(4);
IIC_SCL=1;
receive<<=1;
delay_us(1);
if(READ_SDA)receive|=0x01;
}
if (ACKx){
IIC_NAck();
IIC_Stop();
}
else{
IIC_Ack();
}
return receive;
}
|