Changing PWM frequency with potentiometer
- October 27, 2023
- 3 replies
- 5740 views
Hi everyone, I am trying to generate PWM signal and change it's frequency with a potentiometer. I have connected an LED to the PWM output and it blinks only a few times and then stops. Sadly, I don't have an osciloscope to check the signal.
I am using Black Pill with STM32F401CCU6 chip.
Here's my code:
/* USER CODE BEGIN PD */
#define POT_MAX 4095
#define FREQ_MIN 6 // 1000/6=167Hz
#define FREQ_MAX 1000 // 1000/1000=1Hz
#define CLOCK_FREQ 84000000
/* USER CODE END PD */
/* Private variables ---------------------------------------------------------*/
ADC_HandleTypeDef hadc1;
TIM_HandleTypeDef htim1;
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_ADC1_Init(void);
static void MX_TIM1_Init(void);
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
uint32_t adc_val;
uint32_t freq;
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
{
adc_val = HAL_ADC_GetValue(&hadc1);
freq = (adc_val*(FREQ_MAX-FREQ_MIN)/POT_MAX)+FREQ_MIN-1;
TIM1->ARR = freq;
HAL_ADC_Start_IT (&hadc1);
}
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* Configure the system clock */
SystemClock_Config();
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_ADC1_Init();
MX_TIM1_Init();
/* USER CODE BEGIN 2 */
HAL_ADC_Start_IT (&hadc1);
HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1);
TIM1->CCR1 = 30;
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
also I have attached files with timer, adc and clock configuration. I hope someone can help me out.