用STM32实现模拟iiC软件配置的代码
时间: 2024-05-06 09:18:30 浏览: 129
以下是基于STM32实现模拟I2C软件配置的代码:
```c
#include "stm32f10x.h"
#define SDA_OUT() GPIOB->CRL &= 0X0FFFFFFF;GPIOB->CRL |= 0x30000000//PB6输出模式
#define SDA_IN() GPIOB->CRL &= 0X0FFFFFFF;GPIOB->CRL |= 0x80000000//PB6输入模式
#define IIC_SCL PBout(7) //SCL
#define IIC_SDA PBout(6) //SDA
#define READ_SDA PBin(6) //SDA IN
void IIC_Init(void)
{
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;
IIC_SDA = 1;
delay_us(4);
}
u8 IIC_Wait_Ack(void)
{
u8 ucErrTime = 0;
SDA_IN();
IIC_SDA = 1;
delay_us(1);
IIC_SCL = 1;
delay_us(1);
while (READ_SDA) {
ucErrTime++;
if (ucErrTime > 250) {
IIC_Stop();
return 1;
}
}
IIC_SCL = 0;
return 0;
}
void IIC_Ack(void)
{
IIC_SCL = 0;
SDA_OUT();
IIC_SDA = 0;
delay_us(2);
IIC_SCL = 1;
delay_us(2);
IIC_SCL = 0;
}
void IIC_NAck(void)
{
IIC_SCL = 0;
SDA_OUT();
IIC_SDA = 1;
delay_us(2);
IIC_SCL = 1;
delay_us(2);
IIC_SCL = 0;
}
void IIC_Send_Byte(u8 txd)
{
u8 t;
SDA_OUT();
IIC_SCL = 0;
for (t = 0; t < 8; t++) {
if ((txd & 0x80) >> 7)
IIC_SDA = 1;
else
IIC_SDA = 0;
txd <<= 1;
delay_us(2);
IIC_SCL = 1;
delay_us(2);
IIC_SCL = 0;
delay_us(2);
}
}
u8 IIC_Read_Byte(unsigned char ack)
{
unsigned char i, receive = 0;
SDA_IN();
for (i = 0; i < 8; i++) {
IIC_SCL = 0;
delay_us(2);
IIC_SCL = 1;
receive <<= 1;
if (READ_SDA)
receive++;
delay_us(1);
}
if (!ack)
IIC_NAck();
else
IIC_Ack();
return receive;
}
u8 single_write(u8 addr, u8 reg, u8 data)
{
u8 res;
IIC_Start();
IIC_Send_Byte(addr << 1 | 0);
res = IIC_Wait_Ack();
IIC_Send_Byte(reg);
res |= IIC_Wait_Ack();
IIC_Send_Byte(data);
res |= IIC_Wait_Ack();
IIC_Stop();
return res;
}
u8 single_read(u8 addr, u8 reg, u8* data)
{
u8 res;
IIC_Start();
IIC_Send_Byte(addr << 1 | 0);
res = IIC_Wait_Ack();
IIC_Send_Byte(reg);
res |= IIC_Wait_Ack();
IIC_Start();
IIC_Send_Byte(addr << 1 | 1);
res |= IIC_Wait_Ack();
*data = IIC_Read_Byte(0);
IIC_Stop();
return res;
}
```
注:以上代码仅供参考,具体实现要根据自己的硬件和需求进行修改。
阅读全文