【庫函數版】 #include <stm32f10x.h>
void delay(void) { uint32_t i; for (i = 0; i < 2000000; i++); }
void config_gpio(void) { GPIO_InitTypeDef gpio; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB, ENABLE); gpio.GPIO_Mode = GPIO_Mode_Out_PP; gpio.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9; // LED燈 gpio.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOB, &gpio); gpio.GPIO_Mode = GPIO_Mode_AF_PP; gpio.GPIO_Pin = GPIO_Pin_9; // TX GPIO_Init(GPIOA, &gpio); gpio.GPIO_Mode = GPIO_Mode_IPU; gpio.GPIO_Pin = GPIO_Pin_10; // RX GPIO_Init(GPIOA, &gpio); }
void config_usart(void) { USART_InitTypeDef usart; RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); USART_StructInit(&usart); // 直接採用默認的串口參數 USART_Init(USART1, &usart); USART_DMACmd(USART1, USART_DMAReq_Tx, ENABLE); // 允許通過DMA發送數據 USART_Cmd(USART1, ENABLE); }
// 用DMA方式發送批量數據 void usart_send_data(void *data, uint16_t size) { DMA_InitTypeDef dma; DMA_StructInit(&dma); dma.DMA_PeripheralBaseAddr = (uint32_t)&USART1->DR; dma.DMA_MemoryBaseAddr = (uint32_t)data; dma.DMA_DIR = DMA_DIR_PeripheralDST; // 從主存到外設 dma.DMA_BufferSize = size; dma.DMA_MemoryInc = DMA_MemoryInc_Enable; // 主存地址自動後移 DMA_Init(DMA1_Channel4, &dma); DMA_Cmd(DMA1_Channel4, ENABLE); }
int main(void) { config_gpio(); config_usart(); while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET); // 開機時必須等到TC=1後才能發送數據 USART_SendData(USART1, 'a'); while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET); // 等待字符發送完畢 USART_SendData(USART1, '\n'); while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET); usart_send_data("Hello World!\n", 13); // 用DMA方式發送 while (1) { delay(); GPIO_SetBits(GPIOB, GPIO_Pin_8); delay(); GPIO_ResetBits(GPIOB, GPIO_Pin_8); } }
|