704|0

182

帖子

1

TA的资源

一粒金砂(高级)

楼主
 

【ST NUCLEO-U5A5ZJ-Q开发板测评】2、EXTI、PWM和串口的printf [复制链接]

串口printf输出

Nucleo-U5A5的串口1和STlinkV3的串口相连,用以输出打印日志。

在cubeMX中开启串口1,在工程中重定向,就可以使用printf了

/* USER CODE BEGIN Includes */
#include "stdio.h"
/* USER CODE END Includes */

#ifdef __GNUC__
    #define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
    #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif
    PUTCHAR_PROTOTYPE { HAL_UART_Transmit(&huart1 , (uint8_t *)&ch, 1, 0xFFFF); return ch; }

 


 

User_key按键的外部中断

 

在cubeMX中的NVIC中enable按键的中断,并修改优先级高于systic,在stm32u5xx_it.c中可以看到EXTI13对应的中断接口函数

/**
  * [url=home.php?mod=space&uid=159083]@brief[/url] This function handles EXTI Line13 interrupt.
  */
void EXTI13_IRQHandler(void)
{
  /* USER CODE BEGIN EXTI13_IRQn 0 */

  /* USER CODE END EXTI13_IRQn 0 */
  HAL_GPIO_EXTI_IRQHandler(USER_BUTTON_Pin);
  /* USER CODE BEGIN EXTI13_IRQn 1 */

  /* USER CODE END EXTI13_IRQn 1 */
}

cubeMX生成代码中已写好gpio中断函数,清除相应的中断标志位,并弱定义了中断返回,使用时再重新书写中断返回函数HAL_GPIO_EXTI_Rising_Callback(GPIO_Pin);或HAL_GPIO_EXTI_Falling_Callback(GPIO_Pin);即可

void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin)
{
  /* EXTI line interrupt detected */
  if (__HAL_GPIO_EXTI_GET_RISING_IT(GPIO_Pin) != 0U)
  {
    __HAL_GPIO_EXTI_CLEAR_RISING_IT(GPIO_Pin);
    HAL_GPIO_EXTI_Rising_Callback(GPIO_Pin);
  }

  if (__HAL_GPIO_EXTI_GET_FALLING_IT(GPIO_Pin) != 0U)
  {
    __HAL_GPIO_EXTI_CLEAR_FALLING_IT(GPIO_Pin);
    HAL_GPIO_EXTI_Falling_Callback(GPIO_Pin);
  }
}

在main中定义EXTI13的中断返回函数,按下Blue翻转

void HAL_GPIO_EXTI_Rising_Callback(uint16_t GPIO_Pin)
{
    if(GPIO_Pin == USER_BUTTON_Pin)
    {
        HAL_Delay(50);
        HAL_GPIO_TogglePin(LED_BLUE_GPIO_Port,LED_BLUE_Pin);
        printf("key exti callback\r\n");
    }
}

按键按下,BlueLED翻转

 


 

PWM输出呼吸灯

在cubeMX中配置GreenLED的定时器TIM3-Ch2

 

  • 预分频(84-1,也就得到1MHz的时钟频率作为定时器的时钟源)
  • 向上计数模式(从0开始向上计数至初值并发生上溢事件)
  • 计数器重装值(500-1,每计数500次发生溢出,最终PWM频率为1M/500=2kHz)
  • 内部时钟分频(可以理解为在预分频的基础上再进行一次分频,但只能2或4分频,这里不需要)
  • 计数器自动重装载使能

 

开启全局中断

 

以上按160M/160=1M,1M/1000=1K的频率计数,实现呼吸灯效果

HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_2);

while (1)
  {
    /* USER CODE END WHILE */
    /* USER CODE BEGIN 3 */
        HAL_Delay(5);
        if(dir)led0pwmval++;                //dir==1 led0pwmval递增
        else led0pwmval--;                //dir==0 led0pwmval递减
        if(led0pwmval>900)dir=0;            //led0pwmval到达900后,方向为递减
        if(led0pwmval==0)dir=1;                //led0pwmval递减到0后,方向改为递增
        __HAL_TIM_SetCompare(&htim3,TIM_CHANNEL_2,led0pwmval);
   }

启动定时器通道:HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_2);

PWM比较输出:__HAL_TIM_SetCompare(&htim3,TIM_CHANNEL_2,led0pwmval);

 


 

简单封装一下LED和PWM程序:

按键配合PWM程序,按键按下中断开启LED的PWM,再按下LED缓慢熄灭

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * [url=home.php?mod=space&uid=1307177]@File[/url] : main.c
  * @brief          : Main program body
  ******************************************************************************
  * [url=home.php?mod=space&uid=1020061]@attention[/url] *
  * Copyright (c) 2024 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"
#include "adc.h"
#include "icache.h"
#include "tim.h"
#include "ucpd.h"
#include "usart.h"
#include "usb_otg.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
/* 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 ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void SystemPower_Config(void);
/* USER CODE BEGIN PFP */

#ifdef __GNUC__
    #define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
    #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif
    PUTCHAR_PROTOTYPE { HAL_UART_Transmit(&huart1 , (uint8_t *)&ch, 1, 0xFFFF); return ch; }

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
   	uint8_t dir=1;
   	uint16_t led0pwmval=0;
   	uint8_t pwmstate=1;

   	uint32_t uwIC2Value1 = 0;
   	uint32_t uwIC2Value2 = 0;
   	uint32_t uwDiffCapture = 0;
   	uint16_t uhCaptureIndex = 0;
   	uint32_t uwFrequency = 0;

   	uint32_t tim6_count = 0;


/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
	uint16_t adc_val;

  /* 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();

  /* Configure the System Power */
  SystemPower_Config();

  /* USER CODE BEGIN SysInit */
  HAL_PWREx_EnableVddA();
  HAL_PWREx_EnableVddIO2();

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_ADC1_Init();
  MX_ICACHE_Init();
  MX_TIM3_Init();
  MX_UCPD1_Init();
  MX_USART1_UART_Init();
  MX_USB_OTG_HS_HCD_Init();
  MX_TIM1_Init();
  MX_TIM6_Init();
  /* USER CODE BEGIN 2 */

  HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_2);//启动定时器PWM比较输出
  HAL_TIM_Base_Start_IT(&htim6);   //启定时器6中断

  printf("start\r\n");

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
	  if(HAL_GPIO_ReadPin(LED_BLUE_GPIO_Port,LED_BLUE_Pin))
	  {
		  LED_PWM(400);
	  }
	  else LED_PWM(0);

  }
  /* 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
  */
  if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_MSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.MSIState = RCC_MSI_ON;
  RCC_OscInitStruct.MSICalibrationValue = RCC_MSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_0;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI;
  RCC_OscInitStruct.PLL.PLLMBOOST = RCC_PLLMBOOST_DIV4;
  RCC_OscInitStruct.PLL.PLLM = 3;
  RCC_OscInitStruct.PLL.PLLN = 10;
  RCC_OscInitStruct.PLL.PLLP = 8;
  RCC_OscInitStruct.PLL.PLLQ = 2;
  RCC_OscInitStruct.PLL.PLLR = 1;
  RCC_OscInitStruct.PLL.PLLRGE = RCC_PLLVCIRANGE_1;
  RCC_OscInitStruct.PLL.PLLFRACN = 0;
  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_CLOCKTYPE_PCLK3;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB3CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief Power Configuration
  * @retval None
  */
static void SystemPower_Config(void)
{
  HAL_PWREx_EnableVddIO2();

  /*
   * Switch to SMPS regulator instead of LDO
   */
  if (HAL_PWREx_ConfigSupply(PWR_SMPS_SUPPLY) != HAL_OK)
  {
    Error_Handler();
  }
/* USER CODE BEGIN PWR */
/* USER CODE END PWR */
}

/* USER CODE BEGIN 4 */
void LED_PWM(uint16_t num)
{

	if(num!=0)
		pwmstate = 1;
	else
		pwmstate = 0;

	switch(pwmstate)
	{
		case 0:
			if(0 == led0pwmval) break;
			else
			{
				HAL_Delay(5);
				led0pwmval--;
				__HAL_TIM_SetCompare(&htim3,TIM_CHANNEL_2,led0pwmval);
			}
		case 1:
			{
				HAL_Delay(5);
				if(dir)led0pwmval++;				//dir==1 led0pwmval递增
				else led0pwmval--;					//dir==0 led0pwmval递减
				if(led0pwmval>num)dir=0;			//led0pwmval到达x00后,方向为减
				if(led0pwmval<=0) dir=1;			//led0pwmval递减x00后,方向为增
				__HAL_TIM_SetCompare(&htim3,TIM_CHANNEL_2,led0pwmval);
			}
	}
}

//按键上升沿触发中断返回函数
void HAL_GPIO_EXTI_Rising_Callback(uint16_t GPIO_Pin)
{
	if(GPIO_Pin == USER_BUTTON_Pin)
	{
		HAL_Delay(50);
		HAL_GPIO_TogglePin(LED_BLUE_GPIO_Port,LED_BLUE_Pin);
		printf("key exti callback\r\n");
		printf("Blue state is : %d\r\n",HAL_GPIO_ReadPin(LED_BLUE_GPIO_Port,LED_BLUE_Pin));
	}
}

//输入捕获函数
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
	if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1)
	  {
	    if(uhCaptureIndex == 0)
	    {
	      /* Get the 1st Input Capture value */
	      uwIC2Value1 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1);
	      uhCaptureIndex = 1;
	    }
	    else if(uhCaptureIndex == 1)
	    {
	      /* Get the 2nd Input Capture value */
	      uwIC2Value2 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1);

	      /* Capture computation */
	      if (uwIC2Value2 > uwIC2Value1)
	      {
	        uwDiffCapture = (uwIC2Value2 - uwIC2Value1);
	      }
	      else if (uwIC2Value2 < uwIC2Value1)
	      {
	        /* 0xFFFF is max TIM1_CCRx value */
	        uwDiffCapture = ((0xFFFF - uwIC2Value1) + uwIC2Value2) + 1;
	      }
	      else
	      {
	        /* If capture values are equal, we have reached the limit of frequency
	           measures */
	        Error_Handler();
	      }

	      /* Frequency computation: for this example TIMx (TIM1) is clocked by
	         APB2Clk */
	      uwFrequency = HAL_RCC_GetPCLK2Freq() / uwDiffCapture;
	      uhCaptureIndex = 0;
	    }
	  }
}

//定时器6产生时基
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	if(htim == &htim6)
	{
		tim6_count++;
	}
}

/* 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 */

 

 

VID_20240227_113651

 

 

此帖出自stm32/stm8论坛
点赞 关注
 

回复
举报
您需要登录后才可以回帖 登录 | 注册

随便看看
查找数据手册?

EEWorld Datasheet 技术支持

相关文章 更多>>
关闭
站长推荐上一条 1/7 下一条

 
EEWorld订阅号

 
EEWorld服务号

 
汽车开发圈

About Us 关于我们 客户服务 联系方式 器件索引 网站地图 最新更新 手机版

站点相关: 国产芯 安防电子 汽车电子 手机便携 工业控制 家用电子 医疗电子 测试测量 网络通信 物联网

北京市海淀区中关村大街18号B座15层1530室 电话:(010)82350740 邮编:100190

电子工程世界版权所有 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号 Copyright © 2005-2025 EEWORLD.com.cn, Inc. All rights reserved
快速回复 返回顶部 返回列表