GebraBit

SGP41 sensor project with STM32F303 microcontroller series

متن سربرگ خود را وارد کنید

SGP41 gebrabit project

SGP41 sensor project with STM32F303 microcontroller series

SGP41 gebrabit project
  1. Home
  2. »
  3. Projects
  4. »
  5. SGP41 sensor project with STM32F303 microcontroller series

What's the purpose of this project?

In this section, we are going to launch the SGP41-D-R4 sensor using ARM microcontroller, STM32F series. In order to use more conveniently and optimally in this project, we use two ready modules GB605EN and GebraBit STM32F303. These two modules contain the minimum necessary elements of the SGP41-D-R4 sensor and the STM32F microcontroller, which are provided by the GebraBit team to facilitate the work.

What are we going to learn in this tutorial?

In this tutorial, in addition to setting up and using the SGP41-D-R4 sensor, you will get to know all the SGP41-D-R4 sensor registers, how to set the various parts of the STM32 microcontroller to set up this sensor using the I2C protocol, how to use the GB605EN module specific library and driver file. You will also learn how to declare functions and finally receive sensor data in the Keil compiler.    

What do we need to start this project?

As you probably know, we need some hardware and software to do this project. The titles of these hardware and software are provided to you in the table below and you can prepare/download by clicking on each of them and get ready to start.

Required hardware
Required software
Keil compiler 
 STM32CubeMX program
 ST-LINK/V2 programmer

First as shown in the image below, we connect the GebraBit SGP41 module to the GebraBit STM32F303 module as follows:

Note: Considering that the PA14 pin of the GebraBit STM32F303 microcontroller module is used to program the microcontroller, the I2C setting on the PA14 and PA15 pins is not possible in this version, so the GebraBit SGP41 module cannot be placed as a pin to pin on the GebraBit STM32F303 microcontroller module.

Finally, we will see the values of VOC and NOX in Real Time in the “Watch1” window of the Keil compiler in the “Debug Session” mode.

STM32CubeMX settings

In the following, we review the settings related to each of the “I2C”, “RCC”, “Debug”, and “Clock” sections in the STM32F303 microcontroller to develop the GebraBit SGP41 module.

RCC settings

Due to the presence of “8Mhz” crystal in the GebraBit STM32F303 module, we select the “external clock” in the “RCC” section:

Debug & Programming settings

Regarding the access to “SWCLK” and “SWDIO” pins in the GebraBit STM32F303 module, to reduce the number of pins during “Debug & Programming”, in the “SYS” block, we select the “Serial Wire” option in the “Debug” section:

I2C settings

Regarding the access to “SWCLK” and “SWDIO” pins in the GebraBit STM32F303 module, to reduce the number of pins during “Debug & Programming”, in the “SYS” block, we select the “Serial Wire” option in the “Debug” section:

According to the sensor data sheet, the settings of the I2C parameters in the “Parameter Settings” section will be set as shown in the above image.

Clock settings

The “clock” settings for each part of the STM32F303 microcontroller in this code, are as follows:

Project Manager settings

“Project Manager” settings are as follows, here we have used “MDK-ARM” version “5.32” compiler:

After completing all the above settings, we can develop our code easily just by one click on “GENERATE CODE” and adding the SGP41 library and driver (provided by GebraBit).

You can download the “STM32Cube MX”, “library”, “driver” and KEIL project at the end of this tutorial.    

SGP41 library and driver

In addition to the modular design of various sensors and ICs, GebraBit tries to provide variety of structured and hardware-independent libraries in C language for the ease of users in setting up and developing software.

For this purpose, after preparing each GebraBit module, the users can refer to the “tutorial” section of the desired module and download the dedicated library, which contains the “ .h” and “  .c” file (Header and Source) and a sample training program under “GebraBit STM32F303”, “GebraBit ATMEGA32A” or “Arduino” development boards.

All the defined functions and structures in the library are commented in full detail and all the received parameters in the arguments of the functions and their return values, are briefly explained. Since the libraries are hardware independed, the user can easily add the library in any of their favorite compilers and develop it by desired microcontroller and development board.

GebraBit_SGP41.h header file

In this file, based on the datasheet of the sensor or IC, all address registers, the values of each register are defined in the form of “Enumeration”. Also, the casing of the SGP41 sensor and the configurations related to each of the SGP41 sensor internal blocks are defined in the form of a “STRUCT” with the name GebraBit_ SGP41 Finally, in the Debug Session environment, all the configurations related to each block can be seen in real time.          

USER REGISTER MAP

The registry map or sensor commands are defined in this section:

				
					1. #define SGP41_I2C		              &hi2c1
 2. #define SGP41_ADDRESS 				  0x59
 3. #define SGP41_WRITE_ADDRESS 		  ((SGP41_ADDRESS<<1)|0)
 4. #define SGP41_READ_ADDRESS 		      ((SGP41_ADDRESS<<1)|1)
 5. #define SGP41_GET_SERIAL_NUMBER   	  0x3682
 6. #define SGP41_PERFORM_SELF_TEST   	  0x280E
 7. #define SGP41_EXECUTE_CONDITIONING	  0x2612
 8. #define SGP41_MEASURE_RAW_SIGNAL	  0x2619
 9. #define SGP41_TURN_HEATER_OFF    	  0x3615		
10. #define DATA_BUFFER_SIZE              9
11. #define CMD_BUFFER_SIZE				  8
12. #define CRC8_POLYNOMIAL 			  0x31
13. #define CRC8_INIT 					  0xFF
14. #define CRC8_LEN 					  1
15. #define WORD_SIZE					  2
16.  

				
			

SGP41_Ability Enum

This enum is used to activate and deactivate different parts of the sensor:

				
					1. typedef enum Ability
2. {  
3. 	Disable = 0 ,                      
4. 	Enable     
5. }SGP41_Ability;   
6.  

				
			

SGP41_Activity Enum

By using this enum, the status of performing an action in the sensor is determined:

				
					1. typedef enum Activity 
2. {
3.   NOT_DONE = 0,
4.   DONE     = 1
5. } SGP41_Activity;
6.  

				
			

SGP41_Command Enum

The values of this enum are used to execute sensor commands:

				
					1. typedef enum Command
2. {
3.  GET_SERIAL_NUMBER   	=	0x3682 ,
4.  PERFORM_SELF_TEST   	=	0x280E ,
5.  EXECUTE_CONDITIONING	=	0x2612 ,
6.  MEASURE_RAW_SIGNAL		=	0x2619 ,
7.  TURN_HEATER_OFF    	    =	0x3615	
8. }SGP41_Command;
9.  

				
			

SGP41_CRC_Status Enum

To know the CRC status, the values of this Enum are used:

				
					1. typedef enum CRC_Status 
2. {  
3. 	CRC_ERROR = 0 ,                      
4. 	CRC_OK     
5. }SGP41_CRC_Status;
6.  

				
			

SGP41 struct

All sensor properties, calibration coefficients and sensor data are defined in this “struct” and all the information and configuration implemented on the sensor are stored in this “structure” and you can see the changes in each part of the sensor in the “Debug Session” environment.

				
					1. typedef	struct SGP41
 2. {
 3. 	  uint8_t                       	   REGISTER_CACHE;
 4. 	  uint8_t							   BUFFER[DATA_BUFFER_SIZE];
 5. 	  SGP41_Command 				       COMMAND;
 6. 	  uint8_t						       CMD_BUFFER[CMD_BUFFER_SIZE];
 7. 	  uint16_t                       	   SERIAL_NUMBER1;
 8. 	  uint16_t                       	   SERIAL_NUMBER2;
 9. 	  uint16_t                       	   SERIAL_NUMBER3;
10. 	  SGP41_Activity                  	   SELF_TEST;
11.   	  SGP41_Ability						   HUMIDITY_COMPENSATION;
12. 	  SGP41_Activity					   HEATER_OFF;
13. 	  float								   COMPENSATION_HUMIDITY;
14. 	  float								   COMPENSATION_TEMPERATURE;
15. 	  uint16_t							   DEFAULT_HUMIDITY;
16. 	  uint16_t							   DEFAULT_TEMPERATURE;
17. 	  SGP41_Activity                       FACTORY_RESET; 
18. 	  uint8_t 							   SGP41_CRC;
19. 	  SGP41_CRC_Status			           CRC_CHECK;
20. 	  uint16_t                             SRAW_VOC;
21. 	  uint16_t							   SRAW_NOX;
22. 	  int32_t							   VOC_INDEX_VALUE;
23.       int32_t							   NOX_INDEX_VALUE;  
24. }GebraBit_SGP41;
25.  

				
			

Declaration of functions

At the end of this file, all the functions for reading and writing in SGP41 registers, sensor configuration and receiving data from the sensor are declared:

				
					1. extern void GB_SGP41_Send_Command(GebraBit_SGP41 * SGP41 , uint16_t cmd)  ;
 2. extern void GB_SGP41_Write_Data(GebraBit_SGP41 * SGP41 , uint16_t cmd , uint16_t data1 , uint16_t data2 ) ;
 3. extern void GB_SGP41_Read_Data(GebraBit_SGP41 * SGP41 , uint8_t* buffer, uint16_t size) ;
 4. extern void GB_SGP41_Delay_uSecond(uint32_t useconds)      ;
 5. extern void GB_SGP41_CRC_Generate(GebraBit_SGP41 * SGP41 ,const uint8_t* data, uint16_t count)  ;
 6. extern void GB_SGP41_CRC_Check(GebraBit_SGP41 * SGP41 ,const uint8_t* data,uint16_t count,uint8_t checksum)    ;
 7. extern void GB_SGP41_Get_Serial_Number(GebraBit_SGP41 * SGP41 )    ;
 8. extern void GB_SGP41_Perform_Self_Test(GebraBit_SGP41 * SGP41 )      ;
 9. extern void GB_SGP41_Turn_Heater_Off(GebraBit_SGP41 * SGP41 )  ;
10. extern void GB_SGP41_Deactivate_Humidity_Compensation (GebraBit_SGP41 * SGP41)          ;
11. extern void GB_SGP41_Set_Compensation_Humidity_Temperature_Values(GebraBit_SGP41 * SGP41 , float humidity  , float temp , SGP41_Ability Compensation )   ;
12. extern void GB_SGP41_Execute_Conditioning(GebraBit_SGP41 * SGP41) ;  
13. extern void GB_SGP41_Measure_Raw_Signal(GebraBit_SGP41 * SGP41) ;
14. extern void GB_SGP41_initialize( GebraBit_SGP41 * SGP41 )     ;
15. extern void GB_SGP41_Configuration(GebraBit_SGP41 * SGP41, SGP41_Ability Compensation)    ;
16. extern void GB_SGP41_Get_Data(GebraBit_SGP41 * SGP41)         ;
17.  

				
			

GebraBit_SGP41.c source file

In this file, which is written in C language, all the functions are commented in full detail, and all the parameters received in the arguments of the functions and their return values are clearly explained so we confine to these explanations and invite users to check this file directly for more information.

Sample program in Keil

After making the Keil project by STM32CubeMX and adding the “GebraBit_SGP41.c” library provided by GebraBit, we will examine the “main .c” file of the sample tutorial and view the output of the GebraBit_SGP41 module in the “watch” part in the Keil compiler “Debugging” environment.

Description of “main.c” file

Enums and functions required by GebraBit SGP41 module have been added to the structures. In the next part, a variable named SGP41_Module of the GebraBit_SGP41 structure type (this structure is in the GebraBit_SGP41 header and is explained in the GebraBit_SGP41 library description section) is defined for the configuration of the GebraBit SGP41 module:   

				
					/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
GebraBit_SGP41 SGP41_Module;
/* USER CODE END PTD */

				
			

In the next part of the written code, using the GB_SGP41_initialize (&SGP41_Module) and GB_ SGP41_Configuration (&SGP41_Module) functions, we set the GebraBit SGP41 module and finally, in the while part of the program, the data is read from the sensor and the VOC and NOx values are continuously received:   

				
					1. /* USER CODE BEGIN 2 */
 2. 	GB_SGP41_initialize(&SGP41_Module);
 3. 	GB_SGP41_Configuration(&SGP41_Module);
 4.   /* USER CODE END 2 */
 5.  
 6.   /* Infinite loop */
 7.   /* USER CODE BEGIN WHILE */
 8.   while (1)
 9.   {
10.     /* USER CODE END WHILE */
11.  
12.     /* USER CODE BEGIN 3 */
		//GB_SGP41_Get_Data(&SGP41_Module);
14.   }
15.   /* USER CODE END 3 */
16. }
17.  

				
			

The “main.c” file code text:

				
					  1. /* USER CODE BEGIN Header */
  2. /*
  3.  * ________________________________________________________________________________________________________
  4.  * Copyright (c) 2020 GebraBit Inc. All rights reserved.
  5.  *
  6.  * This software, related documentation and any modifications thereto (collectively “Software”) is subject
  7.  * to GebraBit and its licensors' intellectual property rights under U.S. and international copyright
  8.  * and other intellectual property rights laws. 
  9.  *
 10.  * GebraBit and its licensors retain all intellectual property and proprietary rights in and to the Software
 11.  * and any use, reproduction, disclosure or distribution of the Software without an express license agreement
 12.  * from GebraBit is strictly prohibited.
 13.  
 14.  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT 
 15.  * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT IN  
 16.  * NO EVENT SHALL GebraBit BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, 
 17.  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
 18.  * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
 19.  * OF THE SOFTWARE.
 20.  * ________________________________________________________________________________________________________
 21.  */
 22. /**
 23.   ******************************************************************************
 24.   * @file           : main.c
 25.   * @brief          : Main program body
 26. 	* @Author       	: Mehrdad Zeinali
 27.   ******************************************************************************
 28.   * @attention
 29.   *
 30.   * Copyright (c) 2022 STMicroelectronics.
 31.   * All rights reserved.
 32.   *
 33.   * This software is licensed under terms that can be found in the LICENSE file
 34.   * in the root directory of this software component.
 35.   * If no LICENSE file comes with this software, it is provided AS-IS.
 36.   *
 37.   ******************************************************************************
 38.   */
 39. /* USER CODE END Header */
 40. /* Includes ------------------------------------------------------------------*/
 41. #include "main.h"
 42. #include "i2c.h"
 43. #include "gpio.h"
 44.  
 45. /* Private includes ----------------------------------------------------------*/
 46. /* USER CODE BEGIN Includes */
 47. #include "GebraBit_SGP41.h"
 48. //#include "sensirion_gas_index_algorithm.h"
 49. /* USER CODE END Includes */
 50.  
 51. /* Private typedef -----------------------------------------------------------*/
 52. /* USER CODE BEGIN PTD */
 53. GebraBit_SGP41 SGP41_Module;
 54. /* USER CODE END PTD */
 55.  
 56. /* Private define ------------------------------------------------------------*/
 57. /* USER CODE BEGIN PD */
 58. /* USER CODE END PD */
 59.  
 60. /* Private macro -------------------------------------------------------------*/
 61. /* USER CODE BEGIN PM */
 62.  
 63. /* USER CODE END PM */
 64.  
 65. /* Private variables ---------------------------------------------------------*/
 66.  
 67. /* USER CODE BEGIN PV */
 68.  
 69. /* USER CODE END PV */
 70.  
 71. /* Private function prototypes -----------------------------------------------*/
 72. void SystemClock_Config(void);
 73. /* USER CODE BEGIN PFP */
 74.  
 75. /* USER CODE END PFP */
 76.  
 77. /* Private user code ---------------------------------------------------------*/
 78. /* USER CODE BEGIN 0 */
 79.  
 80. /* USER CODE END 0 */
 81.  
 82. /**
 83.   * @brief  The application entry point.
 84.   * @retval int
 85.   */
 86. int main(void)
 87. {
 88.   /* USER CODE BEGIN 1 */
 89.  
 90.   /* USER CODE END 1 */
 91.  
 92.   /* MCU Configuration--------------------------------------------------------*/
 93.  
 94.   /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
 95.   HAL_Init();
 96.  
 97.   /* USER CODE BEGIN Init */
 98.  
 99.   /* USER CODE END Init */
100.  
101.   /* Configure the system clock */
102.   SystemClock_Config();
103.  
104.   /* USER CODE BEGIN SysInit */
105.  
106.   /* USER CODE END SysInit */
107.  
108.   /* Initialize all configured peripherals */
109.   MX_GPIO_Init();
110.   MX_I2C1_Init(); 
111.   /* USER CODE BEGIN 2 */
112. 	// initialize gas index parameters
113.   GB_SGP41_initialize( &SGP41_Module );
114. 	GB_SGP41_Configuration( &SGP41_Module , Enable );
115. 	//GB_SGP41_Configuration( &SGP41_Module , Disable );
116.   /* USER CODE END 2 */
117.  
118.   /* Infinite loop */
119.   /* USER CODE BEGIN WHILE */
120.   while (1)
121.   {
122.     /* USER CODE END WHILE */
123.  
124.     /* USER CODE BEGIN 3 */
125. 		GB_SGP41_Get_Data( &SGP41_Module );
126.   }
127.   /* USER CODE END 3 */
128. }
129.  
130. /**
131.   * @brief System Clock Configuration
132.   * @retval None
133.   */
134. void SystemClock_Config(void)
135. {
136.   RCC_OscInitTypeDef RCC_OscInitStruct = {0};
137.   RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
138.   RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
139.  
140.   /** Initializes the RCC Oscillators according to the specified parameters
141.   * in the RCC_OscInitTypeDef structure.
142.   */
143.   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
144.   RCC_OscInitStruct.HSEState = RCC_HSE_ON;
145.   RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
146.   RCC_OscInitStruct.HSIState = RCC_HSI_ON;
147.   RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
148.   RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
149.   RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
150.   if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
151.   {
152.     Error_Handler();
153.   }
154.  
155.   /** Initializes the CPU, AHB and APB buses clocks
156.   */
157.   RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
158.                               |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
159.   RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
160.   RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
161.   RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
162.   RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
163.  
164.   if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
165.   {
166.     Error_Handler();
167.   }
168.   PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_I2C1;
169.   PeriphClkInit.I2c1ClockSelection = RCC_I2C1CLKSOURCE_SYSCLK;
170.   if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
171.   {
172.     Error_Handler();
173.   }
174. }
175.  
176. /* USER CODE BEGIN 4 */
177.  
178. /* USER CODE END 4 */
179.  
180. /**
181.   * @brief  This function is executed in case of error occurrence.
182.   * @retval None
183.   */
184. void Error_Handler(void)
185. {
186.   /* USER CODE BEGIN Error_Handler_Debug */
187.   /* User can add his own implementation to report the HAL error return state */
188.   __disable_irq();
189.   while (1)
190.   {
191.   }
192.   /* USER CODE END Error_Handler_Debug */
193. }
194.  
195. #ifdef  USE_FULL_ASSERT
196. /**
197.   * @brief  Reports the name of the source file and the source line number
198.   *         where the assert_param error has occurred.
199.   * @param  file: pointer to the source file name
200.   * @param  line: assert_param error line source number
201.   * @retval None
202.   */
203. void assert_failed(uint8_t *file, uint32_t line)
204. {
205.   /* USER CODE BEGIN 6 */
206.   /* User can add his own implementation to report the file name and line number,
207.      ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
208.   /* USER CODE END 6 */
209. }
210. #endif /* USE_FULL_ASSERT */
211.  

				
			

Program output

After generating the Keil project using STM32CubeMX and adding the library, we connect the STLINK V2 programmer to the GebraBit STM32F303 using the STLINKV2 adapter:

STLINKV2 adapter

By connecting the STLINK V2 programmer to the GebraBit STM32F303, there is no need to apply power to the GebraBit STM32F303 and GebraBit SGP41 modules, because they receive their supply voltage directly from the STLINK V2 programmer.

Finally, enter the “Debug” mode and by adding the “SGP41_Module” to the “watch” window and running the program, we can see the changes in the VOC and NOx values of the GebraBit SGP41 module:

In the following, you can download the “GebraBit SGP41 module setup project” using the GebraBit STM32F303 module in the Keil environment, the “STM32CubeMX file”, the schematic of the modules and the “SGP41 datasheet”.   

Program output video

این مقاله را با دوستانتان به اشتراک بگذارید!

Be the first to write a review

Please help the Gebra team to improve the quality by sending comments and ratings

Your email address will not be published. Required fields are marked *

Shopping cart
Start typing to see posts you are looking for.

Sign in

No account yet?