2014年6月20日 星期五

STM32 SMBUS example

為了要控制一顆USB PD IC需要用SMBUS溝通,所以我利用STM32來發送SMBUS command。下面相關的程式碼步驟。
I want to control a USB-PD IC and communicate with it by SMBUS. I used the STM32 to transmit SMBUS command. The following code are steps to set STM32 sending complete SMBUS Write Word command.





1. Setup the system clock
/* Enable HSI Clock 16MHz*/
RCC_HSICmd(ENABLE);
/*!< Wait till HSI is ready */
while (RCC_GetFlagStatus(RCC_FLAG_HSIRDY) == RESET)
{}
RCC_SYSCLKConfig(RCC_SYSCLKSource_HSI);

RCC_MSIRangeConfig(RCC_MSIRange_6);
RCC_HSEConfig(RCC_HSE_OFF); 
if(RCC_GetFlagStatus(RCC_FLAG_HSERDY) != RESET )
{
while(1);
}
RCC_AHBPeriphClockCmd( RCC_AHBPeriph_GPIOB , ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);
2. Configure the GPIO to be I2C function pin
GPIO_SetBits(GPIOB, LD_BLUE_GPIO_PIN);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 |GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_40MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource8, GPIO_AF_I2C1);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource9, GPIO_AF_I2C1);


3. Configure the I2C and  set I2C to be SMBUS
  /* I2C1 configuration: SMBus Host ------------------------------------------*/
I2C_InitStructure.I2C_Mode = I2C_Mode_SMBusHost ;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 = 0x01;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = 100000;
I2C_Init(I2C1, &I2C_InitStructure);
I2C_Cmd(I2C1, ENABLE);

4. Start to send I2C Start bit.
I2C_GenerateSTART(I2C1, ENABLE); 
  /* Test on I2C1 EV5 and clear it */
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT));

 5. Send PD IC Slave address 18h.
 Because the last bit is R/W bit in slave address command, the address value need to be left shift one bit. 
 I2C_Send7bitAddress(I2C1, 0x30,I2C_Direction_Transmitter);  
  /* Test on I2C1 EV6 and clear it */
 while(!I2C_CheckEvent(I2C1,I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED));
          /* Send Command */
 6. Send the register address you want to write.
  I2C_SendData(I2C1, 0x30);
/* Test on I2C1 EV8 and clear it */
   while(!I2C_CheckEvent(I2C1,I2C_EVENT_MASTER_BYTE_TRANSMITTING)); 
 7. Send the data you want to write.
  /* Send data low byte */
  I2C_SendData(I2C1, 0x04);
/* Test on I2C1 EV8 and clear it */
   while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTING)); 
  /* Send data high byte */
  I2C_SendData(I2C1, 0xC8);
/* Test on I2C1 EV8 and clear it */

  8Send I2C Stop bit
   while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED)); 
        /* Send I2C1 STOP Condition */
  I2C_GenerateSTOP(I2C1, ENABLE);

沒有留言: