使用STM32F103 I2C驱动SHT30

   日期:2020-09-24     浏览:134    评论:0    
核心提示:使用STM32F103 I2C驱动SHT30SHT30的官方代码见《Sensirion_Humidity_Sensors_SHT3x_Sample_Code_V2》,不过官方是用GPIO模拟的I2C时序,现在修改为STM32F103的硬件I2C驱动SHT30.

使用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) 
#define SHT30_I2C_SCL_GPIO_PORT (GPIOB)
	 
#define SHT30_I2C_SDA_PIN (GPIO_Pin_7) 
#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
   
	
	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);
	 
	 
	 
	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);
		
	 
	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);
    
	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();
	
	  
   
   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);
	  
	 
	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);
    
		 
	  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
	{ 
	    //关闭通信:
	    
	   I2C_AcknowledgeConfig(SHT30_I2C, DISABLE);
       (void)SHT30_I2C->SR2;
       I2C_GenerateSTOP(SHT30_I2C, ENABLE);
	}
		
	//从机端接收到主机地址后,开始向主机发送数据
	 
	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)
	 { 
		
		//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);

    
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);	
	I2C_DeInit(I2C1);
	
    
	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;
  
	
	I2C_Init(I2C1, &I2C_InitStructure);
		
	
	I2C_Cmd(I2C1, ENABLE);
}

起始条件+地址+写命令+命令码高字节:

命令码低字节+停止条件+起始条件+地址+读命令+时钟延伸(等待转换结果):

获取的温湿度值:

 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服