[材料]
- STM32F103C8T6 主板 x 1
- 麵包板 x 1
- STLINK V2 模擬下載器 x 1
- CP2102 USB to TTL x 1
- 連接線 x n 條
[接線與電路圖]
我用的 USB to TTL 是 CP2102,與 STM32F103C8T6 的連接的方式如下:| STM32F103C8 | USB TTL轉換器 |
|---|---|
| +3.3v | +3.3v |
| GND | GND |
| PA10 | TXD |
| PA9 | RXD |
[程式]
主程式一開始先對 USART 進行初始化,進入迴圈循環後,就等 USART 接收和傳送字串進行通訊,主程式 main.c 如下:#include "stm32f10x.h"
#include "stm32f10x_rcc.h"
#include "stm32f10x_gpio.h"
#include "delay.h"
#include "USART.h"
u8 ch2;
int main (void)
{
delay_init();
USART_User_Init(115200);
while (1)
{
}
}
USART.c 程式如下:#include "stm32f10x.h"
#define TXD GPIO_Pin_9
#define RXD GPIO_Pin_10
#define USART_GPIO GPIOA
extern u8 ch2;
void USART_User_Init(uint32_t BaudRate)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
// Config GPIO
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = TXD; // Output PA9
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
GPIO_Init(USART_GPIO, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = RXD; // Input 10
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(USART_GPIO, &GPIO_InitStructure);
// Config USART
USART_InitTypeDef USART_InitStructure;
USART_DeInit(USART1);
USART_InitStructure.USART_BaudRate = BaudRate; //一般設定爲 9600 或 115200;
USART_InitStructure.USART_WordLength = USART_WordLength_8b; // 資料長度 = 8 Bits
USART_InitStructure.USART_StopBits = USART_StopBits_1; // 1 個停止位
USART_InitStructure.USART_Parity = USART_Parity_No; //無奇偶校驗位
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; //無硬體流控(即禁止 RTS 和 CTS )
USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx; //收發模式
USART_Init(USART1, &USART_InitStructure);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); //開啓 ENABLE 中斷
USART_Cmd(USART1, ENABLE);
// Config NVIC
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; //主優先級1
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //次優先級0
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //啟用IRQ通道
NVIC_Init(&NVIC_InitStructure);
}
void USART1_IRQHandler(void)
{
if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
{
ch2 = USART_ReceiveData(USART1); //接收來自終端機資料
USART_SendData(USART1, ch2);
// USART_SendData(USART1, USART_ReceiveData(USART1)); // 將上兩列合併
USART_ClearITPendingBit(USART1, USART_IT_RXNE);
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
}
}
USART.h 程式如下:#ifndef __USARTX_H #define __USARTX_H void USART_User_Init(uint32_t BaudRate); #endif完整的程式請參考 Github:6. USART Serial Communication
[結果]
勾選左下方 Send Seting 的「loop」,預設為 1000ms 送一次訊息,在 Send 左邊的方框輸入傳送字串,按下 Send 即可與 STM32 進行通訊。STM32 也會回應傳送的字串。[參考資料]
- STM32F103 Reference manual
- STM32F10xxx參考手冊
- STM32F103入門 | 12.PWM實現呼吸燈
- STM32微控制器(七). USART串列埠、IIC和CAN通訊
上一篇:STM32(20):USART串列通訊(上)


張貼留言