经过上一次的帖子,简单介绍过cube的使用后STM32L031测评之:用cube点亮你的LED,这次我们继续用cube来玩串口第一步:使用uart2(STM32L031K6 NUCLEO32使用USART2连接stlink 的vcp)所以我们不需要另外的转串口工具
我们采用异步串口,所以选用Asynchronous
第二步:配置USART的参数,我们采用115200,8-n-1配置
1、点击configuration:
2、双击connectivity中的USART2
3、Baud Rate选项输入115200
4、Word Length 选择8bit,其他保持默认
5、使能中断
6、点击Apply,OK
第三步:编写主函数
- 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_USART2_UART_Init();
- /* USER CODE BEGIN 2 */
- printf("%s\r\n", "UART2 实验------");
- printf("硬件平台:%s\r\n", "STM32L031K6 NUCLEO32");
- printf("This is a UART2 Demo \r\n" );
- printf("("__DATE__ " - " __TIME__ ") \r\n");
- /* USER CODE END 2 */
- /* Infinite loop */
- /* USER CODE BEGIN WHILE */
- while (1)
- {
- /* USER CODE END WHILE */
- /* USER CODE BEGIN 3 */
- }
- /* USER CODE END 3 */
- }
这里用到了printf函数,所以需要重定向
在usart.c添加以下代码:
- #pragma import(__use_no_semihosting)
-
- struct __FILE
- {
- int handle;
- /* Whatever you require here. If the only file you are using is */
- /* standard output using printf() for debugging, no file handling */
- /* is required. */
- };
- /* FILE is typedef’ d in stdio.h. */
- FILE __stdout;
- void _sys_exit(int x)
- {
- x = x;
- }
- int fputc(int ch, FILE *f)
- {
- while( (USART2->ISR&0x40) == 0 );
- USART2->TDR = (uint8_t) ch;
- return ch;
- }
实现现象:
上传工程代码:
STM32L031_USART.rar
(4.2 MB, 下载次数: 151)
|