你的浏览器版本过低,可能导致网站不能正常访问!
为了你能正常使用网站功能,请使用这些浏览器。

【经验分享】STM32 HAL库 UART使用printf

[复制链接]
STMCU小助手 发布时间:2022-2-7 21:10
  1. // 添加这个函数
  2. int fputc(int ch,FILE *f)
  3. {
  4.     uint8_t temp[1]={ch};
  5.     HAL_UART_Transmit(&UartHandle,temp,1,2);
  6. }
复制代码
MDK设置:勾选Use Micro LIB

579586-20151011092549581-1741992362.jpg

测试板子:STM32F746NG-DISCOVERY
main.c文件
  1. /* Includes ------------------------------------------------------------------*/
  2. #include "main.h"
  3. #include <stdio.h>
  4. /** @addtogroup STM32F7xx_HAL_Examples
  5.   * @{
  6.   */

  7. /** @addtogroup UART_TwoBoards_ComDMA
  8.   * @{
  9.   */

  10. /* Private typedef -----------------------------------------------------------*/
  11. /* Private define ------------------------------------------------------------*/
  12. #define TRANSMITTER_BOARD

  13. /* Private macro -------------------------------------------------------------*/
  14. /* Private variables ---------------------------------------------------------*/
  15. /* UART handler declaration */
  16. UART_HandleTypeDef UartHandle;
  17. __IO ITStatus UartReady = RESET;
  18. __IO uint32_t UserButtonStatus = 0;  /* set to 1 after User Button interrupt  */

  19. /* Buffer used for transmission */
  20. uint8_t aTxBuffer[] = " ****UART_TwoBoards communication based on DMA****  ****UART_TwoBoards communication based on DMA****  ****UART_TwoBoards communication based on DMA**** ";

  21. /* Buffer used for reception */
  22. uint8_t aRxBuffer[RXBUFFERSIZE];

  23. /* Private function prototypes -----------------------------------------------*/
  24. void SystemClock_Config(void);
  25. static void Error_Handler(void);
  26. static uint16_t Buffercmp(uint8_t* pBuffer1, uint8_t* pBuffer2, uint16_t BufferLength);
  27. static void MPU_Config(void);
  28. static void CPU_CACHE_Enable(void);

  29. /* Private functions ---------------------------------------------------------*/
  30. UART_HandleTypeDef UartHandle;
  31. uint8_t sendbuf[]="send ok ";

  32. // 添加这个函数
  33. int fputc(int ch,FILE *f)
  34. {
  35.     uint8_t temp[1]={ch};
  36.     HAL_UART_Transmit(&UartHandle,temp,1,2);
  37. }

  38. /**
  39.   * @brief  Main program
  40.   * @param  None
  41.   * @retval None
  42.   */
  43. int main(void)
  44. {
  45.   /* Configure the MPU attributes as Write Through */
  46.   MPU_Config();

  47.   /* Enable the CPU Cache */
  48.   CPU_CACHE_Enable();
  49.   /* STM32F7xx HAL library initialization:
  50.        - Configure the Flash ART accelerator
  51.        - Systick timer is configured by default as source of time base, but user
  52.          can eventually implement his proper time base source (a general purpose
  53.          timer for example or other time source), keeping in mind that Time base
  54.          duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and
  55.          handled in milliseconds basis.
  56.        - Set NVIC Group Priority to 4
  57.        - Low Level Initialization
  58.      */
  59.   HAL_Init();

  60.   /* Configure the system clock to 216 MHz */
  61.   SystemClock_Config();
  62.   
  63.   /* Configure LED1 */
  64.   BSP_LED_Init(LED1);
  65.    
  66.   UartHandle.Instance        = DISCOVERY_COM1;

  67.   UartHandle.Init.BaudRate   = 9600;
  68.   UartHandle.Init.WordLength = UART_WORDLENGTH_8B;
  69.   UartHandle.Init.StopBits   = UART_STOPBITS_1;
  70.   UartHandle.Init.Parity     = UART_PARITY_NONE;
  71.   UartHandle.Init.HwFlowCtl  = UART_HWCONTROL_NONE;
  72.   UartHandle.Init.Mode       = UART_MODE_TX_RX;
  73.     BSP_COM_DeInit(COM1,&UartHandle);
  74.     BSP_COM_Init(COM1,&UartHandle);
  75.    
  76. //    HAL_UART_Transmit(&UartHandle,sendbuf,sizeof(sendbuf),10);
  77.   /* Configure User push-button in Interrupt mode */
  78.   BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_EXTI);
  79.   
  80.   /* Wait for User push-button press before starting the Communication.
  81.      In the meantime, LED1 is blinking */
  82.     printf("hello");
  83.    
  84.    
  85.   while(UserButtonStatus == 0)
  86.   {
  87.       /* Toggle LED1*/
  88.       BSP_LED_Toggle(LED1);
  89.       HAL_Delay(100);
  90.   }
  91.   /* Turn on LED1 if test passes then enter infinite loop */
  92.   BSP_LED_On(LED1);
  93.   /* Infinite loop */
  94.   while (1)
  95.   {
  96.   }
  97. }

  98. /**
  99.   * @brief  System Clock Configuration
  100.   *         The system Clock is configured as follow :
  101.   *            System Clock source            = PLL (HSE)
  102.   *            SYSCLK(Hz)                     = 216000000
  103.   *            HCLK(Hz)                       = 216000000
  104.   *            AHB Prescaler                  = 1
  105.   *            APB1 Prescaler                 = 4
  106.   *            APB2 Prescaler                 = 2
  107.   *            HSE Frequency(Hz)              = 25000000
  108.   *            PLL_M                          = 25
  109.   *            PLL_N                          = 432
  110.   *            PLL_P                          = 2
  111.   *            PLL_Q                          = 9
  112.   *            VDD(V)                         = 3.3
  113.   *            Main regulator output voltage  = Scale1 mode
  114.   *            Flash Latency(WS)              = 7
  115.   * @param  None
  116.   * @retval None
  117.   */
  118. void SystemClock_Config(void)
  119. {
  120.   RCC_ClkInitTypeDef RCC_ClkInitStruct;
  121.   RCC_OscInitTypeDef RCC_OscInitStruct;
  122.   HAL_StatusTypeDef ret = HAL_OK;

  123.   /* Enable HSE Oscillator and activate PLL with HSE as source */
  124.   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  125.   RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  126.   RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  127.   RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  128.   RCC_OscInitStruct.PLL.PLLM = 25;
  129.   RCC_OscInitStruct.PLL.PLLN = 432;
  130.   RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  131.   RCC_OscInitStruct.PLL.PLLQ = 9;
  132.   
  133.   ret = HAL_RCC_OscConfig(&RCC_OscInitStruct);
  134.   if(ret != HAL_OK)
  135.   {
  136.     while(1) { ; }
  137.   }
  138.   
  139.   /* Activate the OverDrive to reach the 216 MHz Frequency */  
  140.   ret = HAL_PWREx_EnableOverDrive();
  141.   if(ret != HAL_OK)
  142.   {
  143.     while(1) { ; }
  144.   }
  145.   
  146.   /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */
  147.   RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2);
  148.   RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  149.   RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  150.   RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;  
  151.   RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
  152.   
  153.   ret = HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_7);
  154.   if(ret != HAL_OK)
  155.   {
  156.     while(1) { ; }
  157.   }  
  158. }

  159. /**
  160.   * @brief  Tx Transfer completed callback
  161.   * @param  UartHandle: UART handle.
  162.   * @note   This example shows a simple way to report end of DMA Tx transfer, and
  163.   *         you can add your own implementation.
  164.   * @retval None
  165.   */
  166. void HAL_UART_TxCpltCallback(UART_HandleTypeDef *UartHandle)
  167. {
  168.   /* Set transmission flag: trasfer complete*/
  169.   UartReady = SET;

  170.   
  171. }

  172. /**
  173.   * @brief  Rx Transfer completed callback
  174.   * @param  UartHandle: UART handle
  175.   * @note   This example shows a simple way to report end of DMA Rx transfer, and
  176.   *         you can add your own implementation.
  177.   * @retval None
  178.   */
  179. void HAL_UART_RxCpltCallback(UART_HandleTypeDef *UartHandle)
  180. {
  181.   /* Set transmission flag: trasfer complete*/
  182.   UartReady = SET;

  183.   
  184. }

  185. /**
  186.   * @brief  UART error callbacks
  187.   * @param  UartHandle: UART handle
  188.   * @note   This example shows a simple way to report transfer error, and you can
  189.   *         add your own implementation.
  190.   * @retval None
  191.   */
  192. void HAL_UART_ErrorCallback(UART_HandleTypeDef *UartHandle)
  193. {
  194.     Error_Handler();
  195. }


  196. /**
  197.   * @brief EXTI line detection callbacks
  198.   * @param GPIO_Pin: Specifies the pins connected EXTI line
  199.   * @retval None
  200.   */
  201. void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
  202. {
  203.   if(GPIO_Pin == KEY_BUTTON_PIN)
  204.   {  
  205.     UserButtonStatus = 1;
  206.   }
  207. }

  208. /**
  209.   * @brief  Compares two buffers.
  210.   * @param  pBuffer1, pBuffer2: buffers to be compared.
  211.   * @param  BufferLength: buffer's length
  212.   * @retval 0  : pBuffer1 identical to pBuffer2
  213.   *         >0 : pBuffer1 differs from pBuffer2
  214.   */
  215. static uint16_t Buffercmp(uint8_t* pBuffer1, uint8_t* pBuffer2, uint16_t BufferLength)
  216. {
  217.   while (BufferLength--)
  218.   {
  219.     if ((*pBuffer1) != *pBuffer2)
  220.     {
  221.       return BufferLength;
  222.     }
  223.     pBuffer1++;
  224.     pBuffer2++;
  225.   }

  226.   return 0;
  227. }

  228. /**
  229.   * @brief  This function is executed in case of error occurrence.
  230.   * @param  None
  231.   * @retval None
  232.   */
  233. static void Error_Handler(void)
  234. {
  235.   /* Turn LED1 on */
  236.   BSP_LED_On(LED1);
  237.   while(1)
  238.   {
  239.     /* Error if LED1 is slowly blinking (1 sec. period) */
  240.     BSP_LED_Toggle(LED1);
  241.     HAL_Delay(1000);
  242.   }  
  243. }

  244. #ifdef  USE_FULL_ASSERT

  245. /**
  246.   * @brief  Reports the name of the source file and the source line number
  247.   *         where the assert_param error has occurred.
  248.   * @param  file: pointer to the source file name
  249.   * @param  line: assert_param error line source number
  250.   * @retval None
  251.   */
  252. void assert_failed(uint8_t* file, uint32_t line)
  253. {
  254.   /* User can add his own implementation to report the file name and line number,
  255.      ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  256.   /* Infinite loop */
  257.   while (1)
  258.   {
  259.   }
  260. }
  261. #endif

  262. /**
  263.   * @brief  Configure the MPU attributes as Write Through for SRAM1/2.
  264.   * @note   The Base Address is 0x20010000 since this memory interface is the AXI.
  265.   *         The Region Size is 256KB, it is related to SRAM1 and SRAM2  memory size.
  266.   * @param  None
  267.   * @retval None
  268.   */
  269. static void MPU_Config(void)
  270. {
  271.   MPU_Region_InitTypeDef MPU_InitStruct;
  272.   
  273.   /* Disable the MPU */
  274.   HAL_MPU_Disable();

  275.   /* Configure the MPU attributes as WT for SRAM */
  276.   MPU_InitStruct.Enable = MPU_REGION_ENABLE;
  277.   MPU_InitStruct.BaseAddress = 0x20010000;
  278.   MPU_InitStruct.Size = MPU_REGION_SIZE_256KB;
  279.   MPU_InitStruct.AccessPermission = MPU_REGION_FULL_ACCESS;
  280.   MPU_InitStruct.IsBufferable = MPU_ACCESS_NOT_BUFFERABLE;
  281.   MPU_InitStruct.IsCacheable = MPU_ACCESS_CACHEABLE;
  282.   MPU_InitStruct.IsShareable = MPU_ACCESS_NOT_SHAREABLE;
  283.   MPU_InitStruct.Number = MPU_REGION_NUMBER0;
  284.   MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL0;
  285.   MPU_InitStruct.SubRegionDisable = 0x00;
  286.   MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_ENABLE;

  287.   HAL_MPU_ConfigRegion(&MPU_InitStruct);

  288.   /* Enable the MPU */
  289.   HAL_MPU_Enable(MPU_PRIVILEGED_DEFAULT);
  290. }

  291. /**
  292.   * @brief  CPU L1-Cache enable.
  293.   * @param  None
  294.   * @retval None
  295.   */
  296. static void CPU_CACHE_Enable(void)
  297. {
  298.   /* Enable I-Cache */
  299.   SCB_EnableICache();

  300.   /* Enable D-Cache */
  301.   SCB_EnableDCache();
  302. }

  303. /**
  304.   * @}
  305.   */

  306. /**
  307.   * @}“stdio.h”
  308.   */

  309. /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
复制代码

今天调试了stm32f407的ADC,一切顺利,然而用串口发送ADC结果时都是16进制数,看着很不爽。于是打算用用牛B的“printf”函数,按照以前的做法,在main文件中添加了“stdio.h”,写好了“printf”函数,沏杯茶,打算边品茶边坐等结果,然而这一坐竟坐了半天也没见结果
。一调试发现程序停在了printf函数处,百思不得其解,百度之,得答案,不敢独享,分享如下:

STM32串口通信中使用printf发送数据配置方法(开发环境 Keil RVMDK)
标签: STM32 串口通信 printf方法 2011-06-29 23:29
在STM32串口通信程序中使用printf发送数据,非常的方便。可在刚开始使用的时候总是遇到问题,常见的是硬件访真时无法进入main主函数,其实只要简单的配置一下就可以了。

下面就说一下使用printf需要做哪些配置。

有两种配置方法:
一、对工程属性进行配置,详细步骤如下
1、首先要在你的main 文件中 包含“stdio.h” (标准输入输出头文件)。
2、在main文件中重定义<fputc>函数 如下:
// 发送数据
int fputc(int ch, FILE *f)
{
USART_SendData(USART1, (unsigned char) ch);// USART1 可以换成 USART2 等
while (!(USART1->SR & USART_FLAG_TXE));
return (ch);
}
// 接收数据
int GetKey (void) {
while (!(USART1->SR & USART_FLAG_RXNE));
return ((int)(USART1->DR & 0x1FF));
}
这样在使用printf时就会调用自定义的fputc函数,来发送字符。
3、在工程属性的 “Target" -> "Code Generation" 选项中勾选 "Use MicroLIB"”
MicroLIB 是缺省C的备份库,关于它可以到网上查找详细资料。

至此完成配置,在工程中可以随意使用printf向串口发送数据了。

二、第二种方法是在工程中添加“Regtarge.c”文件
1、在main文件中包含 “stdio.h” 文件
2、在工程中创建一个文件保存为 Regtarge.c , 然后将其添加工程中
在文件中输入如下内容(直接复制即可)
#include <stdio.h>
#include <rt_misc.h>
#pragma import(__use_no_semihosting_swi)
extern int SendChar(int ch); // 声明外部函数,在main文件中定义
extern int GetKey(void);
struct __FILE {
int handle; // Add whatever you need here
};
FILE __stdout;
FILE __stdin;
int fputc(int ch, FILE *f) {
return (SendChar(ch));
}
int fgetc(FILE *f) {
return (SendChar(GetKey()));
}
void _ttywrch(int ch) {
SendChar (ch);
}
int ferror(FILE *f) { // Your implementation of ferror
return EOF;
}
void _sys_exit(int return_code) {
label: goto label; // endless loop
}

3、在main文件中添加定义以下两个函数
int SendChar (int ch) {
while (!(USART1->SR & USART_FLAG_TXE)); // USART1 可换成你程序中通信的串口
USART1->DR = (ch & 0x1FF);
return (ch);
}
int GetKey (void) {
while (!(USART1->SR & USART_FLAG_RXNE));
return ((int)(USART1->DR & 0x1FF));
}

收藏 评论0 发布时间:2022-2-7 21:10

举报

0个回答

所属标签

相似分享

官网相关资源

关于
我们是谁
投资者关系
意法半导体可持续发展举措
创新与技术
意法半导体官网
联系我们
联系ST分支机构
寻找销售人员和分销渠道
社区
媒体中心
活动与培训
隐私策略
隐私策略
Cookies管理
行使您的权利
官方最新发布
STM32N6 AI生态系统
STM32MCU,MPU高性能GUI
ST ACEPACK电源模块
意法半导体生物传感器
STM32Cube扩展软件包
关注我们
st-img 微信公众号
st-img 手机版