通過(guò)學(xué)習(xí)USART1深入STM32F107VCT6的串口通信
例:
#include "stm32f10x.h"
#include "stm32_eval.h"
#include USART_InitTypeDef USART_InitStructure; //定義結(jié)構(gòu)體類(lèi)型變量 void GPIO_Configuration(void); //聲明GPIO配置函數(shù) #ifdef __GNUC__ #define PUTCHAR_PROTOTYPE int __io_putchar(int ch) //此處定義為putchar應(yīng)用 #else #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f) #endif { SystemInit(); //配置系統(tǒng)時(shí)鐘 RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1| RCC_APB2Periph_AFIO, ENABLE); //打開(kāi)APB2功能時(shí)鐘(UART1為連接在APB2上的高速外設(shè))開(kāi)啟了串口時(shí)鐘和復(fù)用功能時(shí)鐘 GPIO_Configuration(); //調(diào)用GPIO配置函數(shù) USART_InitStructure.USART_BaudRate = 115200; //設(shè)置USART傳輸波特率 USART_InitStructure.USART_WordLength = USART_WordLength_8b; //設(shè)置USART傳輸數(shù)據(jù)位一幀為8位 USART_InitStructure.USART_StopBits = USART_StopBits_1; //設(shè)置USART傳輸每幀一個(gè)停止位 USART_InitStructure.USART_Parity = USART_Parity_No; //設(shè)置USART無(wú)奇偶校驗(yàn) USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; //設(shè)置USART無(wú)硬件流控制 USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;//開(kāi)啟USART發(fā)送和接受功能 USART_Init(USART1, &USART_InitStructure); //初始化USART1設(shè)置 USART_Cmd(USART1, ENABLE); //開(kāi)啟USART1 printf(" 李繼超是個(gè)好人嗎? "); printf(" 回答:李繼超是個(gè)大好人! "); printf(" 菏澤是個(gè)是個(gè)美麗的地方! "); printf(" 發(fā)生了什么?你是猴子請(qǐng)來(lái)的救兵嗎? "); printf(" 嗯!李繼超的確是個(gè)大好人!?。∧悴拍У滥?!哼!??! "); //配置輸出數(shù)據(jù) while (1) { } } void GPIO_Configuration(void) { GPIO_InitTypeDef GPIO_InitStructure; //定義結(jié)構(gòu)體變量類(lèi)型 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); //打開(kāi)GPIOA的功能時(shí)鐘 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //選擇GPIO引腳GPIO_Pin_9 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //設(shè)置GPIO速率 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //設(shè)置GPIO_pin_9為 復(fù)用功能 推挽輸出 GPIO_Init(GPIOA, &GPIO_InitStructure); //初始化GPIO_Pin_9設(shè)置 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; //選擇GPIO引腳GPIO_Pin_10 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //設(shè)置GPIO_Pin_10浮空輸入 GPIO_Init(GPIOA, &GPIO_InitStructure); //初始化GPIO_Pin_10設(shè)置 } PUTCHAR_PROTOTYPE //重定義printf函數(shù) { USART_SendData(USART1, (uint8_t) ch); //發(fā)送字符串 while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET)// 檢測(cè)是否發(fā)送完成 {} return ch; } #ifdef USE_FULL_ASSERT void assert_failed(uint8_t* file, uint32_t line) { while (1) {} } #endif
int main(void)
評(píng)論