bme680_stm32f446/Core/Src/main.c

594 lines
18 KiB
C
Raw Normal View History

/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "bme680.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define AMBIENT_TEMP_GUESS 19.0
#define HEATER_TARGET 300.0
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
SPI_HandleTypeDef hspi2;
TIM_HandleTypeDef htim6;
UART_HandleTypeDef huart2;
/* USER CODE BEGIN PV */
double gBase = 8000; // 02NOV2023 //358714.656; // 27OCT2023 avg taken from clean room
double hBase = 40.0;
double tAmbient = 25.0*100.0; // was the integer value times 100 oC ?
double humidityScore;
double hWeight = 0.5;
double iaqPercent;
double iaqScore;
double eCO2Value;
double calc_air_q (double hRead, double tRead, double gRes)
{
double humidityScore = 0;
double gasScore = 0;
double humidityOffset = hRead - hBase; // Calculate the humidity offset from the baseline setting
double ambTemp = (tAmbient / 100);
double temperatureOffset = tRead - ambTemp; // Calculate the temperature offset from the ambient temperature
double humidityRatio = ((humidityOffset / hBase) + 1);
double temperatureRatio = (temperatureOffset / ambTemp);
// IAQ Calculations
if (humidityOffset > 0) { // Different paths for calculating the humidity score depending on whether the offset is greater than 0
humidityScore = (100 - hRead) / (100 - hBase);
}
else {
humidityScore = hRead / hBase;
}
humidityScore = humidityScore * hWeight * 100;
double gasRatio = (gRes / gBase);
if ( gasRatio > 1.0 ) {
asm("nop");
// problem the gas resistance should not be this high. This mean the
// gBase is too low!
gBase = gRes;
gasRatio = (gRes / gBase); // heuristic for now learning how this works
}
if ((gBase - gRes) > 0) { // Different paths for calculating the gas score depending on whether the offset is greater than 0
gasScore = gasRatio * (100 * (1 - hWeight));
}
else {
// Make sure that when the gas offset and humidityOffset are 0, iaqPercent is 95% - leaves room for cleaner air to be identified
gasScore = (double)((int)((70 + (5 * (gasRatio - 1))+0.5)));
if (gasScore > 75) {
gasScore = 75;
}
}
iaqPercent = (humidityScore + gasScore); // Air quality percentage is the sum of the humidity (25% weighting) and gas (75% weighting) scores
iaqScore = (100 - iaqPercent) * 5 ; // Final air quality score is in range 0 - 500 (see BME688 datasheet page 11 for details)
// eCO2 Calculations
//eCO2Value = 250 * pow(2.718 /*Math.E*/, (0.012 * iaqScore)); // Exponential curve equation to calculate the eCO2 from an iaqScore input
// Adjust eCO2Value for humidity and/or temperature greater than the baseline values
// if (humidityOffset > 0) {
// if (temperatureOffset > 0) {
// eCO2Value = eCO2Value * (humidityRatio + temperatureRatio);
// }
// else {
// eCO2Value = eCO2Value * humidityRatio;
// }
//}
// else if (temperatureOffset > 0) {
// eCO2Value = eCO2Value * (temperatureRatio + 1);
//}
//
// If measurements are taking place rapidly, breath detection is possible due to the sudden increase in humidity (~7-10%)
// If this increase happens within a 5s time window, 1200ppm is added to the eCO2 value
// (These values were based on 'breath-testing' with another eCO2 sensor with algorithms built-in)
//if ((measTime - measTimePrev) <= 5000) {
// if ((hRead - hPrev) >= 3) {
// eCO2Value = eCO2Value + 1500;
// }
//}
// eCO2Value = Math.trunc(eCO2Value);
if (iaqScore < 0)
asm ("nop");
return iaqScore;
}
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_SPI2_Init(void);
static void MX_TIM6_Init(void);
/* USER CODE BEGIN PFP */
// Assumes TIMER6 is set to count every 1uS and that it wraps around (or counts up to 65535)
// and that it counts UP.
void delay_micro_seconds(uint32_t period) {
int16_t a,then,now = *&htim6.Instance->CNT;
asm(" nop");
do {
then = *&htim6.Instance->CNT;
}
while ( (a=(then - now)) < period ); // hows about all that then.
asm(" nop");
}
int BME680init() { return 0; }
int BME680deinit() { return 0; }
int BME680_read_spi(uint8_t reg, uint8_t *dst, uint32_t size){
uint8_t Tx[2];
Tx[0] = reg | 0x80;
Tx[1] = 0;
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_3, GPIO_PIN_RESET); // NSS low
//HAL_SPI_TransmitReceive(&hspi2, Tx, dst, size, 1000); // timeout 1000msec;
HAL_SPI_Transmit(&hspi2, &reg, 1, 1000);
HAL_SPI_Receive(&hspi2, dst, size, 1000);
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_3, GPIO_PIN_SET); // NSS high
return 0;
}
int BME680_write_spi(uint8_t reg, uint8_t value)
{
int8_t Tx[2],Rx[2];
int32_t hal_status;
Tx[0] = reg & 0x7F;
Tx[1] = value;
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_3, GPIO_PIN_RESET); // NSS low
hal_status = HAL_SPI_Transmit(&hspi2, Tx, 2, 1000);
while(&hspi2.State == HAL_SPI_STATE_BUSY); // wait for xmission complete
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_3, GPIO_PIN_SET); // NSS high
return 0;
}
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
bme680_t bme680;
uint8_t mode;
int i;
int error = 0;
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_USART2_UART_Init();
MX_SPI2_Init();
MX_TIM6_Init();
/* USER CODE BEGIN 2 */
// start TIM6 used for sleeping
HAL_TIM_Base_Start(&htim6);
bme680.dev.init = BME680init;
bme680.dev.read = BME680_read_spi;
bme680.dev.write = BME680_write_spi;
bme680.dev.deinit = BME680deinit;
bme680.dev.sleep = delay_micro_seconds;
/* 2. set the device mode */
mode = BME680_MODE_FLOAT | BME680_SPI | BME680_ENABLE_GAS;
/* BME680_MODE_INT | BME680_I2C; */
/* 3. initialise dev func's, and check device id */
if (bme680_init(&bme680, mode) != 0) {
asm("nop");
error = 1;
}
/* 4. reset device */
bme680_reset(&bme680);
/* 5. read calibration parameters from the device and store in memory */
if (bme680_calibrate(&bme680) != 0) {
bme680_deinit(&bme680);
asm("nop");
error = 2;
}
/* debug */
bme680_print_calibration(&bme680);
/* 6. set up device config */
bme680.cfg.osrs_t = BME680_OVERSAMPLE_X16;
bme680.cfg.osrs_p = BME680_OVERSAMPLE_X16;
bme680.cfg.osrs_h = BME680_OVERSAMPLE_X8;
bme680.cfg.filter = BME680_IIR_COEFF_127;
/* configuring gas sensor. */
/* NB: mode |= BME680_ENABLE_GAS; */
/* there are 10 possible heater setpoints */
/* they can be thought of as frames that define one single gas-resistance measurement */
/* they do not carry over or affect each other in any way. */
for(i=0; i<10; i++) {
/* calculate a resistance target, based on desired temp, and ambient temp */
bme680.cfg.res_heat[i] = bme680_calc_target(&bme680, HEATER_TARGET, AMBIENT_TEMP_GUESS);
/* initial heating current for the setpoint. Could be useful in cold places or short gas_wait durations */
/* 7-bit word. Each step/lsb is equiv. to 1/8 mA; so max 16 mA */
/* a value of 20 would be equal to 2.5 mA */
/* this s.p. field is allowed to be left as 0 if no preload is required. */
bme680.cfg.idac_heat[i] = BME680_IDAC(100);
/* define the time between the start of heating and start of resistance sensing in this s.p.*/
/* Bosch datasheet suggests ~30 - 40ms is usually all that is required to get up to temp. */
/* ^ probably with a good idac_heat current but doesn't mention it. */
/* 25 * X4 = 100 ms wait before sampling resistance starts. */
/* the first value is 6-bit (0...63) with 1 ms step size. */
bme680.cfg.gas_wait[i] = BME680_GAS_WAIT(25, BME680_GAS_WAIT_X4);
}
/* The BME680 does not cycle between setpoints. They have to be manually set. */
/* After each "run", the setpoint has to be changed. */
/* the func bme680_write_setpoint_index() will write this field to the dev, without having to reconfigure */
bme680.setpoint = 0; /* 0 thru 9 */
/* 7. write config to device */
if (bme680_configure(&bme680) != 0) {
bme680_deinit(&bme680);
error = 3;
}
int counter = 0;
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* 8. Start forced measurement*. After it finishes, it should remember the previous config. */
/* * = bosch speak for one single T, P, H, GasRes measuring cycle. */
if (bme680_start(&bme680) != 0) {
error = 4;
bme680_deinit(&bme680);
}
/* 9. poll the meas_status register until all scheduled conversions are done */
/* this step can be skipped with SPI interrupt (3 wire SPI only. See 5.3.1.1 in datasheet; pg 29) */
if (bme680_poll(&bme680) != 0) {
error = 5;
bme680_deinit(&bme680);
}
/* 10. read the ADC's and perform a conversion */
if (bme680_read(&bme680) != 0) {
error = 6;
bme680_deinit(&bme680);
}
double airq = calc_air_q(bme680.fcomp.hum, bme680.fcomp.temp, bme680.fcomp.gas_res);
if (counter++ > 100) {
counter = 0;
asm("nop");
}
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure the main internal regulator output voltage
*/
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE3);
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = 16;
RCC_OscInitStruct.PLL.PLLN = 336;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4;
RCC_OscInitStruct.PLL.PLLQ = 2;
RCC_OscInitStruct.PLL.PLLR = 2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief SPI2 Initialization Function
* @param None
* @retval None
*/
static void MX_SPI2_Init(void)
{
/* USER CODE BEGIN SPI2_Init 0 */
/* USER CODE END SPI2_Init 0 */
/* USER CODE BEGIN SPI2_Init 1 */
/* USER CODE END SPI2_Init 1 */
/* SPI2 parameter configuration*/
hspi2.Instance = SPI2;
hspi2.Init.Mode = SPI_MODE_MASTER;
hspi2.Init.Direction = SPI_DIRECTION_2LINES;
hspi2.Init.DataSize = SPI_DATASIZE_8BIT;
hspi2.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi2.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi2.Init.NSS = SPI_NSS_SOFT;
hspi2.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16;
hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi2.Init.TIMode = SPI_TIMODE_DISABLE;
hspi2.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi2.Init.CRCPolynomial = 10;
if (HAL_SPI_Init(&hspi2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI2_Init 2 */
/* USER CODE END SPI2_Init 2 */
}
/**
* @brief TIM6 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM6_Init(void)
{
/* USER CODE BEGIN TIM6_Init 0 */
/* USER CODE END TIM6_Init 0 */
TIM_MasterConfigTypeDef sMasterConfig = {0};
/* USER CODE BEGIN TIM6_Init 1 */
/* USER CODE END TIM6_Init 1 */
htim6.Instance = TIM6;
htim6.Init.Prescaler = 84-1;
htim6.Init.CounterMode = TIM_COUNTERMODE_UP;
htim6.Init.Period = 65535;
htim6.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim6) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim6, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM6_Init 2 */
/* USER CODE END TIM6_Init 2 */
}
/**
* @brief USART2 Initialization Function
* @param None
* @retval None
*/
static void MX_USART2_UART_Init(void)
{
/* USER CODE BEGIN USART2_Init 0 */
/* USER CODE END USART2_Init 0 */
/* USER CODE BEGIN USART2_Init 1 */
/* USER CODE END USART2_Init 1 */
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART2_Init 2 */
/* USER CODE END USART2_Init 2 */
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* USER CODE BEGIN MX_GPIO_Init_1 */
/* USER CODE END MX_GPIO_Init_1 */
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOH_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_3, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin : B1_Pin */
GPIO_InitStruct.Pin = B1_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pin : PC3 */
GPIO_InitStruct.Pin = GPIO_PIN_3;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
/*Configure GPIO pin : LD2_Pin */
GPIO_InitStruct.Pin = LD2_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(LD2_GPIO_Port, &GPIO_InitStruct);
/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */