STM32F103硬件IIC与PT2258芯片通信

2024-07-01 12:28:54 浏览数 (2)

iic.c

代码语言:javascript复制
#include "iic.h"
#include "usart.h"

static __IO uint32_t  I2CTimeout = I2CT_LONG_TIMEOUT; 


void I2C_GPIO_Config(void)
{
    GPIO_InitTypeDef  GPIO_InitStructure;
    
    RCC_APB2PeriphClockCmd(IIC_GPIO_CLK,ENABLE);
    
    //SCL
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
    GPIO_InitStructure.GPIO_Pin = IIC_SCL_GPIO_PIN;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(IIC_SCL_GPIO_PORT,&GPIO_InitStructure);
    //SDA
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
    GPIO_InitStructure.GPIO_Pin = IIC_SDA_GPIO_PIN;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(IIC_SDA_GPIO_PORT,&GPIO_InitStructure);
}
void I2C_Mode_Config(void)
{
    I2C_InitTypeDef  I2C_InitStructure;
    
    RCC_APB1PeriphClockCmd(IIC_CLK,ENABLE);
    /* I2C 配置 */
    I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
    
    /* 高电平数据稳定,低电平数据变化 SCL 时钟线的占空比 */
    I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
    I2C_InitStructure.I2C_OwnAddress1 = I2Cx_OWN_ADDRESS7;
    //
    I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
    //寻址模式
    I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
    //通信速率
    I2C_InitStructure.I2C_ClockSpeed = I2C_Speed;
    
    I2C_Init(I2C1,&I2C_InitStructure);
    
    I2C_Cmd(I2C1,ENABLE);
}
void I2CInit(void)
{
    I2C_GPIO_Config();
    I2C_Mode_Config();
}

void PT2258Write(uint8_t OneDB,uint8_t TenDB)
{
    //发送起始信号
    I2C_GenerateSTART(I2C1,ENABLE);
    
    I2CTimeout = I2CT_FLAG_TIMEOUT;
    
    //等待EV5事件
    while(!I2C_CheckEvent(I2C1,I2C_EVENT_MASTER_MODE_SELECT))
    {
        if((I2CTimeout--) == 0)
        {
            printf("I2C 等待超时!errorCode is 0rn");
            return;
        }
    }
    
    I2CTimeout = I2CT_FLAG_TIMEOUT;
    
    //发送设备地址
    I2C_Send7bitAddress(I2C1,PT2258_ADDR,I2C_Direction_Transmitter);
    //等待EV6事件
    while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED))
    {
        if((I2CTimeout--) == 0)
        {
            printf("I2C 等待超时!errorCode is 1rn");
            return;
        }
    }
    //发送数据
    I2C_SendData(I2C1,0xE0   OneDB);
    I2CTimeout = I2CT_FLAG_TIMEOUT;
    while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
    {
        if((I2CTimeout--) == 0)
        {
            printf("I2C 等待超时!errorCode is 2rn");
            return;
        }
    }
    //
    I2C_SendData(I2C1,0xD0   TenDB);
    I2CTimeout = I2CT_FLAG_TIMEOUT;
    while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
    {
        if((I2CTimeout--) == 0)
        {
            printf("I2C 等待超时!errorCode is 3rn");
            return;
        }
    }
    
    //发送停止信号
    I2C_GenerateSTOP(I2C1,ENABLE);

    return ;
}

根据PT2258芯片手册,衰减1db与10db的指令是0xE0与0xD0

先发送设备地址后面发送数据,最大速率不超过100kHz

0 人点赞