This project uses an infrared (IR) proximity sensor to identify close items without making physical contact. This exercise emphasizes the significance of ambient light correction and signal averaging in analog sensor design by demonstrating how embedded systems can measure reflected infrared light to determine object distance and instantaneously deliver visual feedback through an RGB LED.
Implementation
Important Elements:
Ambient Light Subtraction: Isolates the reflected signal by measuring background infrared while the LED is off.
Signal Averaging: Reduces noise and stabilizes readings by averaging twenty observations.
Analog discrepancies are mapped to six different distance ranges via distance calibration.
RGB LED Feedback: Color-coded, instantaneous visual representation of an object's proximity.
Distance Calibration:
The RGB LED indicates object proximity through color coding:
Green: No object within 20 cm
Blue: 16-20 cm
Yellow: 12-16 cm
Red: 8-12 cm
Magenta: 4-8 cm
White: 0-4 cm (very close)
Results
Observations:
RGB LED Color Change: When an object approaches the sensor, the LED's color shifts.
Detection Range: White indicates a distance of 0–4 cm, and the sensor consistently detects objects up to 20 cm away.
Noise Reduction: By averaging several samples, flickering was removed, and a steady LED output was produced.
Ambient Rejection: Constant room lighting was successfully disregarded by the background subtraction method.
Video Demonstration
Video 1. Final Output
The video shows the system in operation when an object is brought closer to the sensor. The RGB LED gently changes color as the object passes the calibrated thresholds, demonstrating the sensor's ability to measure distance in real time.
/* USER CODE BEGIN Header *//** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * Copyright (c) 2026 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 *//* USER CODE END Includes *//* Private typedef -----------------------------------------------------------*//* USER CODE BEGIN PTD *//* USER CODE END PTD *//* Private define ------------------------------------------------------------*//* USER CODE BEGIN PD *//* USER CODE END PD *//* Private macro -------------------------------------------------------------*//* USER CODE BEGIN PM *//* USER CODE END PM *//* Private variables ---------------------------------------------------------*/ADC_HandleTypeDefhadc1;TIM_HandleTypeDefhtim2;/* USER CODE BEGIN PV */floatvoltageReading=0;/* USER CODE END PV *//* Private function prototypes -----------------------------------------------*/voidSystemClock_Config(void);staticvoidMX_GPIO_Init(void);staticvoidMX_ADC1_Init(void);staticvoidMX_TIM2_Init(void);/* USER CODE BEGIN PFP *//* USER CODE END PFP *//* Private user code ---------------------------------------------------------*//* USER CODE BEGIN 0 */voidIRSensor(void){HAL_ADC_Start(&hadc1);HAL_ADC_PollForConversion(&hadc1,1);//HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_2);voltageReading=HAL_ADC_GetValue(&hadc1);voltageReading=(voltageReading*3.3)/4095.0;/* Channel1 = RED_LED Channel2 = GREEN_LED Channel3 = BLUE_LED Timer2, 1kHz Frequency, 16MHz Bus Frequency, 15 PSC, 999 ARR 20cm = 1.190V 16cm = 1.20V 12cm = 1.280V 8cm = 1.340V 4cm = 2.00V 0cm = ??? */if(voltageReading>=3.10){// Green (Far away: greater than 20cm / below 1.19V)__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_1,0);// R__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_2,999);// G__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_3,0);// B}elseif(voltageReading>=2.50){// Blue (16cm to 20cm)__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_1,0);// R__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_2,0);// G__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_3,999);// B}elseif(voltageReading>=2.00){// Yellow (12cm to 16cm) -> Red + Green__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_1,999);// R__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_2,224);// G__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_3,0);// B}elseif(voltageReading>=1.50){// Red (8cm to 12cm)__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_1,999);// R__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_2,0);// G__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_3,0);// B}elseif(voltageReading>=1.00){// Magenta (4cm to 8cm)__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_1,999);// R__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_2,0);// G__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_3,699);// B}else{// White (Very Close: 0cm to 4cm)__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_1,999);// R__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_2,999);// G__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_3,999);// B}}/* USER CODE END 0 *//** * @brief The application entry point. * @retval int */intmain(void){/* USER CODE BEGIN 1 *//* 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_ADC1_Init();MX_TIM2_Init();/* USER CODE BEGIN 2 */HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_1);HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_2);HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_3);/* USER CODE END 2 *//* Infinite loop *//* USER CODE BEGIN WHILE */while(1){/* USER CODE END WHILE *//* USER CODE BEGIN 3 */IRSensor();}/* USER CODE END 3 */}/** * @brief System Clock Configuration * @retval None */voidSystemClock_Config(void){RCC_OscInitTypeDefRCC_OscInitStruct={0};RCC_ClkInitTypeDefRCC_ClkInitStruct={0};/** Configure the main internal regulator output voltage */__HAL_RCC_PWR_CLK_ENABLE();__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);/** 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_NONE;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_HSI;RCC_ClkInitStruct.AHBCLKDivider=RCC_SYSCLK_DIV1;RCC_ClkInitStruct.APB1CLKDivider=RCC_HCLK_DIV1;RCC_ClkInitStruct.APB2CLKDivider=RCC_HCLK_DIV1;if(HAL_RCC_ClockConfig(&RCC_ClkInitStruct,FLASH_LATENCY_0)!=HAL_OK){Error_Handler();}}/** * @brief ADC1 Initialization Function * @param None * @retval None */staticvoidMX_ADC1_Init(void){/* USER CODE BEGIN ADC1_Init 0 *//* USER CODE END ADC1_Init 0 */ADC_ChannelConfTypeDefsConfig={0};/* USER CODE BEGIN ADC1_Init 1 *//* USER CODE END ADC1_Init 1 *//** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion) */hadc1.Instance=ADC1;hadc1.Init.ClockPrescaler=ADC_CLOCK_SYNC_PCLK_DIV8;hadc1.Init.Resolution=ADC_RESOLUTION_12B;hadc1.Init.ScanConvMode=DISABLE;hadc1.Init.ContinuousConvMode=DISABLE;hadc1.Init.DiscontinuousConvMode=DISABLE;hadc1.Init.ExternalTrigConvEdge=ADC_EXTERNALTRIGCONVEDGE_NONE;hadc1.Init.ExternalTrigConv=ADC_SOFTWARE_START;hadc1.Init.DataAlign=ADC_DATAALIGN_RIGHT;hadc1.Init.NbrOfConversion=1;hadc1.Init.DMAContinuousRequests=DISABLE;hadc1.Init.EOCSelection=ADC_EOC_SINGLE_CONV;if(HAL_ADC_Init(&hadc1)!=HAL_OK){Error_Handler();}/** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time. */sConfig.Channel=ADC_CHANNEL_0;sConfig.Rank=1;sConfig.SamplingTime=ADC_SAMPLETIME_480CYCLES;if(HAL_ADC_ConfigChannel(&hadc1,&sConfig)!=HAL_OK){Error_Handler();}/* USER CODE BEGIN ADC1_Init 2 *//* USER CODE END ADC1_Init 2 */}/** * @brief TIM2 Initialization Function * @param None * @retval None */staticvoidMX_TIM2_Init(void){/* USER CODE BEGIN TIM2_Init 0 *//* USER CODE END TIM2_Init 0 */TIM_ClockConfigTypeDefsClockSourceConfig={0};TIM_MasterConfigTypeDefsMasterConfig={0};TIM_OC_InitTypeDefsConfigOC={0};/* USER CODE BEGIN TIM2_Init 1 *//* USER CODE END TIM2_Init 1 */htim2.Instance=TIM2;htim2.Init.Prescaler=15;htim2.Init.CounterMode=TIM_COUNTERMODE_UP;htim2.Init.Period=999;htim2.Init.ClockDivision=TIM_CLOCKDIVISION_DIV1;htim2.Init.AutoReloadPreload=TIM_AUTORELOAD_PRELOAD_DISABLE;if(HAL_TIM_Base_Init(&htim2)!=HAL_OK){Error_Handler();}sClockSourceConfig.ClockSource=TIM_CLOCKSOURCE_INTERNAL;if(HAL_TIM_ConfigClockSource(&htim2,&sClockSourceConfig)!=HAL_OK){Error_Handler();}if(HAL_TIM_PWM_Init(&htim2)!=HAL_OK){Error_Handler();}sMasterConfig.MasterOutputTrigger=TIM_TRGO_RESET;sMasterConfig.MasterSlaveMode=TIM_MASTERSLAVEMODE_DISABLE;if(HAL_TIMEx_MasterConfigSynchronization(&htim2,&sMasterConfig)!=HAL_OK){Error_Handler();}sConfigOC.OCMode=TIM_OCMODE_PWM1;sConfigOC.Pulse=0;sConfigOC.OCPolarity=TIM_OCPOLARITY_HIGH;sConfigOC.OCFastMode=TIM_OCFAST_DISABLE;if(HAL_TIM_PWM_ConfigChannel(&htim2,&sConfigOC,TIM_CHANNEL_1)!=HAL_OK){Error_Handler();}if(HAL_TIM_PWM_ConfigChannel(&htim2,&sConfigOC,TIM_CHANNEL_2)!=HAL_OK){Error_Handler();}if(HAL_TIM_PWM_ConfigChannel(&htim2,&sConfigOC,TIM_CHANNEL_3)!=HAL_OK){Error_Handler();}/* USER CODE BEGIN TIM2_Init 2 *//* USER CODE END TIM2_Init 2 */HAL_TIM_MspPostInit(&htim2);}/** * @brief GPIO Initialization Function * @param None * @retval None */staticvoidMX_GPIO_Init(void){GPIO_InitTypeDefGPIO_InitStruct={0};/* USER CODE BEGIN MX_GPIO_Init_1 *//* USER CODE END MX_GPIO_Init_1 *//* GPIO Ports Clock Enable */__HAL_RCC_GPIOA_CLK_ENABLE();__HAL_RCC_GPIOB_CLK_ENABLE();/*Configure GPIO pin Output Level */HAL_GPIO_WritePin(Digital_Ground_GPIO_Port,Digital_Ground_Pin,GPIO_PIN_RESET);/*Configure GPIO pin : Digital_Ground_Pin */GPIO_InitStruct.Pin=Digital_Ground_Pin;GPIO_InitStruct.Mode=GPIO_MODE_OUTPUT_OD;GPIO_InitStruct.Pull=GPIO_NOPULL;GPIO_InitStruct.Speed=GPIO_SPEED_FREQ_LOW;HAL_GPIO_Init(Digital_Ground_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 */voidError_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 */voidassert_failed(uint8_t*file,uint32_tline){/* 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 */
Comments