STM32 USART 接收任意長度字元

2021-08-14 16:53:37 字數 2629 閱讀 6879

近段時間學習到 stm32 usart 部分,基本上在接收資料的時候都是採用定長,所以一直想實現接收任意長度的字串。這裡的任意長度不是指的無限長,而是在自己定義的緩衝區範圍之類。比如說緩衝區的大小是 1024 byte,那麼就能接收不大於 1024 個字串。

當時有兩個思路:

1、使用結尾標誌,如 "\r\n" 什麼的

2、定時判斷接收資料的長度,如果在規定的時間內長度沒有發生變化,證明已經接收完了任意長度的字元

因為思路 1 比較好實現,而且網上也有很多例程,所以著重講思路 2

巨集定義:

usart.h 檔案

#ifndef usart_h

#define usart_h

#include "stm32f4xx.h"

#define max_length 1024

#define usartx usart3

#define usart_clk rcc_apb1periph_usart3

#define usart_baud_tate 115200

#define usart_gpio_port gpiob

#define usart_gpio_clk rcc_ahb1periph_gpiob

#define usart_rx_pin gpio_pin_11

#define usart_tx_pin gpio_pin_10

#define usart_rx_pinsource gpio_pinsource11

#define usart_tx_pinsource gpio_pinsource10

#define gpio_af_usart gpio_af_usart3

#define usart_irqn usart3_irqn

#define usart_irq_handlder usart3_irqhandler

void usart_init(void);

char* usart_getstring(void);

注意:

本文中使用的是 stm32f405 系列的微控制器,使用的是 usart3 ,請讀者根據自己的微控制器型號和 usart 做出相應更改

usart.c 檔案

#include "./***/usart.h"		//*** 代表存放 usart.h 檔案的路徑

volatile char receivebuffer[max_length];

volatile uint16_t receivelength = 0;

volatile uint8_t rxflag = 0;

static char str[max_length + 1];

static void gpio_config(void)

static void nvic_config(void)

static void delay_us(uint16_t time)

}void usart_init(void)

char* usart_getstring(void)

} for(temp = 0; temp < receivelength; temp++)

receivelength = 0;

str[temp] = "\0";

return str;

}

stm32f4xx_it.c 檔案

#include "./***/usart.h"		//*** 代表存放 usart.h 檔案的路徑

extern volatile char receivebuffer[max_length];

extern volatile uint16_t receivelength;

extern volatile uint8_t rxflag;

/*usart3 中斷服務函式*/

void usart_irq_handlder(void)

if(!rxflag)

receivebuffer[receivelength++] = temp;

}}

main.c 檔案

#include "./***/usart.h"		//*** 代表存放 usart.h 檔案的路徑

int main()

}

總結:

當 usart 接收到乙個字元時進入中斷服務函式,在中斷服務函式中會將 rxflag 標誌置 1 ,然後判斷接收緩衝區 receivebuff 是否溢位。若沒有溢位,則將字元儲存到接收緩衝區中,接收長度 receivelength 做自加運算。

接收函式 getstring() 通過 500us 的間隔檢測 receivelength 是否發生改變,若沒有發生改變,意味著 usart 已經接受完所有資料,則從接收緩衝區中取出接收到的資料。若發生改變,則意味著 usart 尚未接收完所有資料,所以等待其接收完所有資料。

本程式中存在一些不足,首先是如果接收緩衝區溢位了並不會報錯,不過只能接收和緩衝區長度一致的字元。還有就是 receivelength 的檢測時間,理論上來說只需要設定為 3 * 接收一位資料的時間,即 3 / baud 秒,但是通過逐一除錯,發現只有大於 500us 時才能出現正確的結果。

STM32USART串列埠通訊

問題描述 利用usart串列埠程式,實現pc與stm32通訊,計算機傳送資料,stm32接受後,再傳送給pc端 1.gpio埠配置 根據手冊 pa.9為tx 傳送 pa.10為rx 接受 因此 pa.9為復用推挽輸出,pa.10為浮空輸入,一行 搞定 void gpio config 2.配置usa...

stm32 USART 串列埠通訊

簡單區分同步和非同步就是看通訊時需不需要對外提供時鐘輸出 usart 有專門控制傳送的傳送器 控制接收的接收器,還有喚醒單元 中斷控制等等。使用 usart 之前需要向 usart cr1 暫存器的 ue 位置 1 使能 usart,ue 位用來開啟供給給串列埠的時鐘。傳送或者接收資料字長可選 8 ...

stm32 USART使用標誌

在usart的傳送端有2個暫存器,乙個是程式可以看到的usart dr暫存器,另乙個是程式看不到的移位暫存器,對應usart資料傳送有兩個標誌,乙個是txe 傳送資料暫存器空,另乙個是tc 傳送結束 當usart dr中的資料傳送到移位暫存器後,txe被設定,此時移位暫存器開始向tx訊號線按位傳輸資...