tca9535 stm32库函数模拟iic驱动
时间: 2023-06-29 14:19:38 浏览: 242
以下是使用STM32库函数模拟I2C驱动TCA9535的示例代码:
```c
#include "stm32f10x.h"
#include "delay.h"
#define TCA9535_ADDRESS 0x20
GPIO_TypeDef* GPIO_PORT;
uint16_t SDA_PIN;
uint16_t SCL_PIN;
void I2C_Init(GPIO_TypeDef* GPIOx, uint16_t SDA, uint16_t SCL) {
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_PORT = GPIOx;
SDA_PIN = SDA;
SCL_PIN = SCL;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = SDA_PIN | SCL_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD;
GPIO_Init(GPIO_PORT, &GPIO_InitStructure);
GPIO_SetBits(GPIO_PORT, SDA_PIN | SCL_PIN);
}
void I2C_Start() {
GPIO_SetBits(GPIO_PORT, SDA_PIN);
GPIO_SetBits(GPIO_PORT, SCL_PIN);
delay_us(4);
GPIO_ResetBits(GPIO_PORT, SDA_PIN);
delay_us(4);
GPIO_ResetBits(GPIO_PORT, SCL_PIN);
}
void I2C_Stop() {
GPIO_ResetBits(GPIO_PORT, SDA_PIN);
delay_us(4);
GPIO_SetBits(GPIO_PORT, SCL_PIN);
delay_us(4);
GPIO_SetBits(GPIO_PORT, SDA_PIN);
}
void I2C_WriteByte(uint8_t data) {
uint8_t i = 8;
while(i--) {
if(data & 0x80) GPIO_SetBits(GPIO_PORT, SDA_PIN);
else GPIO_ResetBits(GPIO_PORT, SDA_PIN);
data <<= 1;
delay_us(2);
GPIO_SetBits(GPIO_PORT, SCL_PIN);
delay_us(2);
GPIO_ResetBits(GPIO_PORT, SCL_PIN);
delay_us(2);
}
GPIO_SetBits(GPIO_PORT, SDA_PIN);
delay_us(2);
GPIO_SetBits(GPIO_PORT, SCL_PIN);
delay_us(2);
GPIO_ResetBits(GPIO_PORT, SCL_PIN);
}
uint8_t I2C_ReadByte() {
uint8_t i = 8;
uint8_t data = 0;
GPIO_SetBits(GPIO_PORT, SDA_PIN);
while(i--) {
data <<= 1;
GPIO_ResetBits(GPIO_PORT, SCL_PIN);
delay_us(2);
GPIO_SetBits(GPIO_PORT, SCL_PIN);
delay_us(2);
if(GPIO_ReadInputDataBit(GPIO_PORT, SDA_PIN)) data |= 0x01;
delay_us(1);
}
GPIO_ResetBits(GPIO_PORT, SCL_PIN);
return data;
}
uint8_t TCA9535_Write(uint8_t reg, uint8_t data) {
I2C_Start();
I2C_WriteByte(TCA9535_ADDRESS<<1);
if(I2C_ReadByte() != 0x18) {
I2C_Stop();
return 1;
}
I2C_WriteByte(reg);
if(I2C_ReadByte() != 0x28) {
I2C_Stop();
return 1;
}
I2C_WriteByte(data);
if(I2C_ReadByte() != 0x28) {
I2C_Stop();
return 1;
}
I2C_Stop();
return 0;
}
int main() {
// 初始化模拟I2C
I2C_Init(GPIOB, GPIO_Pin_7, GPIO_Pin_6);
// 配置TCA9535的GPIO口为输出模式
TCA9535_Write(0x06, 0x00); // 二进制00000000,所有GPIO口均为输出模式
// 控制TCA9535的GPIO口输出高电平或低电平
TCA9535_Write(0x02, 0xFF); // 二进制11111111,所有GPIO口输出高电平
TCA9535_Write(0x02, 0x00); // 二进制00000000,所有GPIO口输出低电平
while(1);
}
```
注意,在使用上述代码之前,需要在STM32CubeMX中启用GPIOB,并且将PB6和PB7设置为GPIO通用输出模式,然后生成相应的库函数代码。