stm32串列埠通訊程式之UART2(TTL)
阿新 • • 發佈:2019-01-06
一、硬體連線
二、串列埠助手設定:
三、keil下程式設計
1.要新增的工程檔案
二要編寫的user檔案
1.main.c
2.printf.c#include "printf.h" int main() { printf_init(); printf("\luoyiran is a nice boy\n"); printf("xixi\n"); printf("serial communications is so mystical and interesting!\n"); printf("keep striving!\n"); }
#include "printf.h" #include "stm32f10x.h" #include "stm32f10x_rcc.h" #include "stm32f10x_gpio.h" #include "stm32f10x_usart.h" #include "misc.h" int fputc(int ch,FILE *f) { while(USART_GetFlagStatus(USART2,USART_FLAG_TC) != SET); USART_SendData(USART2,(unsigned char)ch); while(USART_GetFlagStatus(USART2,USART_FLAG_TC) != SET); return (ch); } /*函式名printf_init() 描述:配置USART2的GPIO口, 工作模式為:位元率115200 資料位:8位 奇偶校驗位:N 停止位:1 輸入:無 輸出:無 ****************************/ void printf_init(void) { GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; /*config USART clock*/ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_AFIO,ENABLE); RCC_APB1PeriphClockCmd( RCC_APB1Periph_USART2,ENABLE); /*USART1 GPIO config*/ GPIO_InitStructure.GPIO_Pin= GPIO_Pin_2; GPIO_InitStructure.GPIO_Mode= GPIO_Mode_AF_PP; //複用推輓輸出 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA,&GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin= GPIO_Pin_3; GPIO_InitStructure.GPIO_Mode= GPIO_Mode_IN_FLOATING; //複用開漏輸入 GPIO_Init(GPIOA,&GPIO_InitStructure); /*USART1 mode Config*/ USART_InitStructure.USART_BaudRate = 115200; USART_InitStructure.USART_WordLength = USART_WordLength_8b; USART_InitStructure.USART_StopBits = USART_StopBits_1; USART_InitStructure.USART_Parity = USART_Parity_No; USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; USART_Init(USART2,&USART_InitStructure); USART_Cmd(USART2,ENABLE); }
printf.h
#ifndef __printf_H
#define __printf_H
#include "stm32f10x.h"
#include <stdio.h>
void printf_init(void);
int fputc(int ch,FILE *f);
#endif
四、編譯檔案,點選load,開啟串列埠除錯助手,接上跳線帽子,觀察串列埠助手列印現象