使用STM32F103 I2C驅動SHT30

2020-09-23 12:00:27

使用STM32F103 I2C驅動SHT30

SHT30的官方程式碼見《Sensirion_Humidity_Sensors_SHT3x_Sample_Code_V2》,不過官方是用GPIO模擬的I2C時序,現在修改為STM32F103的硬體I2C驅動SHT30.

使用STM32F103的I2C1實現該功能,相關標頭檔案定義如下:

#define SHT30_I2C 						    I2C1

#define SHT30_I2C_ADDR                     (0x44) 
	 
#define SHT30_I2C_SCL_PIN                  (GPIO_Pin_6)           /* PB.06 */
#define SHT30_I2C_SCL_GPIO_PORT            (GPIOB)
	 
#define SHT30_I2C_SDA_PIN                  (GPIO_Pin_7)           /* PB.07 */
#define SHT30_I2C_SDA_GPIO_PORT            (GPIOB)
	 
#define I2C_SPEED               100000U

官方程式碼在while(1)裡呼叫SHT3X_GetTempAndHumi函數獲取溫溼度值(時鐘延伸模式):
//-----------------------------------------------------------------------------

while(1)
 {
       SHT3X_GetTempAndHumi(&temperature, &humidity, REPEATAB_HIGH, MODE_CLKSTRETCH, 50);
        printf("temperature=%.1f℃\thumidity=%.1f%%RH\terror=%d\r\n",(float)temperature,(float)humidity,(u8)error);
  }

根據產品實際需求,在需要獲取溫溼度時呼叫SHT3X_GetTempAndHumi()函數即可。

//-----------------------------------------------------------------------------
1:獲取溫溼度函數SHT3X_GetTempAndHumi()

etError SHT3X_GetTempAndHumi(ft* temperature, ft* humidity,etRepeatability repeatability, etMode mode, u8t timeout)
{
    etError error;

    switch(mode)
    {
        case MODE_CLKSTRETCH: // get temperature with clock stretching mode 
            error = SHT3X_GetTempAndHumiClkStretch(temperature, humidity,repeatability, timeout);
            break;
        case MODE_POLLING:	// get temperature with polling mode 
            error = SHT3X_GetTempAndHumiPolling(temperature, humidity,repeatability, timeout);
            break; 
        default:
            error = PARM_ERROR; 
            break;
    }

    return error;
}

由於我們使用的是MODE_CLKSTRETCH時鐘延伸模式,因此只修改SHT3X_GetTempAndHumiClkStretch函數。

2:用時鐘延伸模式獲取溫溼度函數SHT3X_GetTempAndHumiClkStretch();

//-----------------------------------------------------------------------------
etError SHT3X_GetTempAndHumiClkStretch(ft* temperature, ft* humidity,etRepeatability repeatability, u8t timeout)
{
    etError error;	// error code
    u16t	rawValueTemp; // temperature raw value from sensor 
    u16t	rawValueHumi; // humidity raw value from sensor

    error = SHT3X_StartWriteAccess();

    // if no error ...
    if(error == NO_ERROR)
    {
        // start measurement in clock stretching mode
        // use depending on the required repeatability, the corresponding command
        

        switch(repeatability)
        {
            case REPEATAB_LOW:
                error = SHT3X_WriteCommand(CMD_MEAS_CLOCKSTR_L); 
                break;
            case REPEATAB_MEDIUM:
                error = SHT3X_WriteCommand(CMD_MEAS_CLOCKSTR_M); 
                break;
            case REPEATAB_HIGH:
                error = SHT3X_WriteCommand(CMD_MEAS_CLOCKSTR_H); 
                break;
            default:
                error = PARM_ERROR; 
                break;
        }
    }

    // if no error, start read access
    if(error == NO_ERROR) error = SHT3X_StartReadAccess();
    // if no error, read temperature raw values
    if(error == NO_ERROR) error = SHT3X_Read2BytesAndCrc(&rawValueTemp, ACK, timeout);
    // if no error, read humidity raw values
    if(error == NO_ERROR) error = SHT3X_Read2BytesAndCrc(&rawValueHumi, NACK, 0); 
    //SHT3X_StopAccess();
    // if no error, calculate temperature in °C and humidity in %RH
    if(error == NO_ERROR)
    {
        *temperature = SHT3X_CalcTemperature(rawValueTemp);
        *humidity = SHT3X_CalcHumidity(rawValueHumi);
    }
    else
	{
        SHT3X_StopAccess();
	}

    return error;
}

與官方原始碼相比,修改了函數SHT3X_StopAccess()的定義及使用方式。官方原始碼在接收到6個位元組的溫溼度資料後,呼叫SHT3X_StopAccess()模擬產生I2C通訊停止條件。而硬體I2C(主接收模式)關閉通訊則需要以下操作(RM0008中文參考手冊P499):

  主裝置在從 從裝置 接收到最後一個位元組後傳送一個NACK。接收到NACK後,從裝置釋放對SCL和SDA線的控制;主裝置就可以傳送一個停止/重起始條件.
 1:為了在收到最後一個位元組後產生NACK脈衝,在讀倒數第二個位元組之後必須清除ACK位.
 2:為了產生一個停止/重起始條件,軟體必須在讀第二個資料位元組之後設定STOP/START位.

主接收器傳送序列圖:
在這裡插入圖片描述

因此,應在接收最後一個位元組之前新增通訊停止程式碼,該程式碼會在I2c_ReadByte()函數裡描述。

3:開始寫入存取函數SHT3X_StartWriteAccess()。該函數先判斷匯流排是否busy,不忙的話產生開始條件,再傳送從機地址,然後等待從機應答。

//-----------------------------------------------------------------------------
static etError SHT3X_StartWriteAccess(void)
{
    etError error = NO_ERROR; // error code
   
	/*!< While the bus is busy */
	SHT30_Timeout = SHT30_LONG_TIMEOUT;
    while(I2C_GetFlagStatus(SHT30_I2C, I2C_FLAG_BUSY))
    {
	    if((SHT30_Timeout--) == 0) 
		{
			 error = TIMEOUT_ERROR;
			 return error;
		}
	}

    I2C_AcknowledgeConfig(SHT30_I2C, ENABLE);
   
    //I2c_StartCondition();
    // write a start condition 
    I2C_GenerateSTART(SHT30_I2C, ENABLE);
	 
	 /*!< Test on EV5 and clear it (cleared by reading SR1 then writing to DR) */
	 /** 
		* @brief  Communication start
		* 
		* After sending the START condition (I2C_GenerateSTART() function) the master 
		* has to wait for this event. It means that the Start condition has been correctly 
		* released on the I2C bus (the bus is free, no other devices is communicating).
		* 
		*/
	SHT30_Timeout = SHT30_FLAG_TIMEOUT;
    while(!I2C_CheckEvent(SHT30_I2C, I2C_EVENT_MASTER_MODE_SELECT))
    {
	    if((SHT30_Timeout--) == 0) 
		{
			 error = TIMEOUT_EV5_ERROR;
			 return error;
		}
	}

    // write the sensor I2C address with the write flag 
    //error = I2c_WriteByte(_i2cAddress << 1);
    //傳送地址後,等待從機確認 EV6
	I2C_Send7bitAddress(SHT30_I2C, (SHT30_I2C_ADDR << 1), I2C_Direction_Transmitter);
		
	/*!< Test on EV6 and clear it */ 
	SHT30_Timeout = SHT30_LONG_TIMEOUT;
    while(!I2C_CheckEvent(SHT30_I2C, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED))
	{
	    if((SHT30_Timeout--) == 0) 
		{
			error = TIMEOUT_EV6_ERROR;
			return error;
		}
	}

    return error;
}

//-----------------------------------------------------------------------------

4:寫命令函數SHT3X_WriteCommand()
從機應答主機地址後,SHT3X_WriteCommand()函數開始寫命令,先傳送高位元組,再發生低位元組。每個位元組傳送後均要等待從機應答。傳送完成後,主機產生停止訊號。

//-----------------------------------------------------------------------------
static etError SHT3X_WriteCommand(etCommands command)
{
    etError error = NO_ERROR; // error code

    // write the upper 8 bits of the command to the sensor 
    //error	= I2c_WriteByte(command >> 8);
	I2C_SendData(SHT30_I2C,command >> 8);
    /* --EV8 */
	SHT30_Timeout = SHT30_FLAG_TIMEOUT;
	while(!I2C_CheckEvent(SHT30_I2C,I2C_EVENT_MASTER_BYTE_TRANSMITTED))
	{
         if((SHT30_Timeout--) == 0) 
		 {
		      error = TIMEOUT_EV8_ERROR;
			  return error;
		}
	}
	  
    
    // write the lower 8 bits of the command to the sensor 
    //error |= I2c_WriteByte(command & 0x00FF);
	I2C_SendData(SHT30_I2C,command & 0x00FF);
	SHT30_Timeout = SHT30_FLAG_TIMEOUT;
	while(!I2C_CheckEvent(SHT30_I2C,I2C_EVENT_MASTER_BYTE_TRANSMITTED))//EV8_2
	{
	    if((SHT30_Timeout--) == 0) 
		{
			error = TIMEOUT_EV8_ERROR;
		    return error;
		}
	}
		
    I2C_GenerateSTOP(SHT30_I2C, ENABLE);//主傳送器通訊完成

    return error;
}

5:開始讀存取SHT3X_StartReadAccess()

//-----------------------------------------------------------------------------
static etError SHT3X_StartReadAccess(void)
{
    etError error; // error code

    // write a start condition 
    //I2c_StartCondition();
	
	  
   /*!< While the bus is busy */
   SHT30_Timeout = SHT30_LONG_TIMEOUT;
   while(I2C_GetFlagStatus(SHT30_I2C, I2C_FLAG_BUSY))
   {
	   if((SHT30_Timeout--) == 0) 
		{
			 error = TIMEOUT_ERROR;
			 return error;
		}
   }
	
	
    // write a start condition 
    //I2c_StartCondition();
	//EV5:After sending the START condition (I2C_GenerateSTART() function) the master 
    //has to wait for this event.
    I2C_GenerateSTART(SHT30_I2C, ENABLE);
	  
	 /*!< Test on EV5 and clear it (cleared by reading SR1 then writing to DR) */
	SHT30_Timeout = SHT30_FLAG_TIMEOUT;
    while(!I2C_CheckEvent(SHT30_I2C, I2C_EVENT_MASTER_MODE_SELECT))
    {
	    if((SHT30_Timeout--) == 0) 
			{
				 error = TIMEOUT_EV5_ERROR;
			   return error;
			}
	  }

      // write the sensor I2C address with the write flag 
      //error = I2c_WriteByte(_i2cAddress << 1);
	  //傳送地址後,等待從機確認 EV6
	  I2C_Send7bitAddress(SHT30_I2C, (SHT30_I2C_ADDR << 1), I2C_Direction_Receiver);
    
		/*!< Test on EV6 and clear it */ 
	  SHT30_Timeout = SHT30_FLAG_TIMEOUT;
	  while(!I2C_CheckEvent(SHT30_I2C, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED))
	  {
		  if((SHT30_Timeout--) == 0) 
		  {
			   error = TIMEOUT_EV6_ERROR;
			   return error;
		  }
	 }
                                     
    // write the sensor I2C address with the read flag 
    //error = I2c_WriteByte(_i2cAddress << 1 | 0x01);

    return error;
}

6:讀取兩個位元組資料和Crc:SHT3X_Read2BytesAndCrc()和官方程式碼一樣。

//-----------------------------------------------------------------------------
static etError SHT3X_Read2BytesAndCrc(u16t* data, etI2cAck finaleAckNack,u8t timeout)
{
 

    etError error;	// error code
    u8t	bytes[2]; // read data array 
    u8t	checksum; // checksum byte

    // read two data bytes and one checksum byte
    error = I2c_ReadByte(&bytes[0], ACK, timeout);
    if(error == NO_ERROR) error = I2c_ReadByte(&bytes[1], ACK, 0);
    if(error == NO_ERROR) error = I2c_ReadByte(&checksum, finaleAckNack, 0);

    // verify checksum
    if(error == NO_ERROR) error = SHT3X_CheckCrc(bytes, 2, checksum);

    // combine the two bytes to a 16-bit value
    *data = (bytes[0] << 8) | bytes[1];

    return error;
}

7:讀去位元組I2c_ReadByte()
為了防止讀取資料時,任務被中斷打斷導致資料出錯,讀取時先關閉中斷,讀取完成後,再開啟中斷。

etError I2c_ReadByte(u8t *rxByte, etI2cAck ack, u8t timeout)
{
    etError error = NO_ERROR; 

	__set_PRIMASK(1);//關總中斷
		
    if(ack == ACK)
	{
		I2C_AcknowledgeConfig(SHT30_I2C, ENABLE);
	}
	else
	{
	    //關閉通訊:
	    /* 主裝置在從 從裝置 接收到最後一個位元組後傳送一個NACK。接收到NACK後,從裝置
		 * 釋放對SCL和SDA線的控制;主裝置就可以傳送一個停止/重起始條件.
		 * 1:為了在收到最後一個位元組後產生NACK脈衝,在讀倒數第二個位元組之後必須清除ACK位.
		 * 2:為了產生一個停止/重起始條件,軟體必須在讀第二個資料位元組之後設定STOP/START位.
		  */
	   I2C_AcknowledgeConfig(SHT30_I2C, DISABLE);
       (void)SHT30_I2C->SR2;
       I2C_GenerateSTOP(SHT30_I2C, ENABLE);
	}
		
	//從機端接收到主機地址後,開始向主機傳送資料
	/*!< Test on EV7 */ 
	SHT30_Timeout = SHT30_LONG_TIMEOUT;
	while(!I2C_CheckEvent(SHT30_I2C, I2C_EVENT_MASTER_BYTE_RECEIVED))
	{
		if((SHT30_Timeout--) == 0) 
		{
			error = TIMEOUT_EV7_ERROR;
			return error;
		}
    }
    *rxByte  = I2C_ReceiveData(SHT30_I2C);
		
	 if(ack == NACK)
	 {
		/* Wait to make sure that STOP control bit has been cleared */
		//STOP位:監測到停止條件時,由硬體清除。
		SHT30_Timeout = SHT30_FLAG_TIMEOUT;
		while(SHT30_I2C->CR1 & I2C_CR1_STOP)
		{
			if((SHT30_Timeout--) == 0) 
			{
				error = TIMEOUT_ERROR;
				return error;
			}
		}
	}
	__set_PRIMASK(0);//開總中斷
    return error;		//return with no error
}

8:SHT3X_CheckCrc()和官方程式碼一樣。

//-----------------------------------------------------------------------------
static etError SHT3X_CheckCrc(u8t data[], u8t nbrOfBytes, u8t checksum)
{
    u8t crc;	// calculated checksum

    // calculates 8-Bit checksum
    crc = SHT3X_CalcCrc(data, nbrOfBytes);

    // verify checksum
    if(crc != checksum) return CHECKSUM_ERROR; 
    else	return NO_ERROR;
}

9:SHT3X_StopAccess()
修改了SHT3X_StopAccess函數的內容及使用方式,當檢測到有ERROR時,呼叫該函數,重新初始化I2C。

static void SHT3X_StopAccess(void)
{
	 I2C_DeInit(SHT30_I2C);
	 SHT30_Init(SHT30_I2C_ADDR);
}

10: I2C設定:SHT30_Init()

void SHT30_Init(uint8_t i2cAddress)
{
	I2C_InitTypeDef  I2C_InitStructure;
	GPIO_InitTypeDef  GPIO_InitStructure;
	
	/*設定時鐘*/
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_AFIO, ENABLE);

    GPIO_InitStructure.GPIO_Pin = SHT30_I2C_SCL_PIN|SHT30_I2C_SDA_PIN;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
    GPIO_Init(SHT30_I2C_SCL_GPIO_PORT, &GPIO_InitStructure);

    /*!< SHT30_I2C Periph clock enable */
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);	
	I2C_DeInit(I2C1);
	
    /*!< I2C configuration */
	I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
	I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
	I2C_InitStructure.I2C_OwnAddress1 = i2cAddress;
	I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
	I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
	I2C_InitStructure.I2C_ClockSpeed = I2C_SPEED;
  
	/* Apply I2C configuration after enabling it */
	I2C_Init(I2C1, &I2C_InitStructure);
		
	/* I2C Peripheral Enable */
	I2C_Cmd(I2C1, ENABLE);
}

起始條件+地址+寫命令+命令碼高位元組:
起始條件+地址+寫命令+命令碼高位元組
命令碼低位元組+停止條件+起始條件+地址+讀命令+時鐘延伸(等待轉換結果):
命令碼低位元組+停止條件+起始條件+地址+讀命令+時鐘延伸(等待轉換結果)
獲取的溫溼度值:
在這裡插入圖片描述