摘 要: 為了縮小電路體積、降低硬件成本,同時又保證串口穩定可靠通信,采用的一種波特率自適應方法,該方法充分利用STC單片機運行速度快、擁有片內振蕩器、片內資源豐富的特點,在串行通信程序中,利用單片機I/O口和定時器,對主機發送的固定字符進行測量、計算,得到合適的波特率常數,從而實現波特率自適應。給出了設計原理、實現方法、誤差分析、流程圖和部分程序,并通過應用實例驗證該方法切實可行。
關鍵詞: STC單片機; 串口通信; 波特率選擇; 自適應方法
中圖分類號: TN911?34; TP391 文獻標識碼: A 文章編號: 1004?373X(2013)23?0041?03
Baud rate adaptive method for STC single?chip microcomputer
ZHAO Pei?yu
(School of Electromechanical and Architectural Engineering, Jianghan University, Wuhan 430056, China)
Abstract : To reduce circuit volume and hardware cost, and at the same time, guarantee the stable and reliable serial port communication, a baud rate adaptive method is proposed. This method makes full use of STC microcontroller′s characteristics of high?speed running, on?chip oscillator, rich on?chip resources. In the serial communication program, the microcontroller′s I/O port and timer are utilized to detect and calculate the fixed character transmitted by host for getting the right baud rate constant, so as to realize the baud rate self?adaption. The design principle and realization method, error analysis, flow chart and part of the program are also given in this paper. The feasibility of the method was verified by a true example.
Keywords: STC single?chip microcomputer; serial communication; baud rate selection; self?adaptive method
0 引 言
串口RS 232是工業控制、儀器儀表、計算機外設常用的一種通信協議。串口通信的波特率一般都是選取標準系列值,并要求通信雙方嚴格遵循相同的波特率,實際應用中,一臺設備往往要與多種其他設備聯絡,為適應各種不同設備的通信速度,就要求該設備能適應不同的波特率,實現這種要求的常見方法有兩種,一是增加波特率選擇開關,二是設計能自動適應各種常見通信速度的串口。第一種方法增加了硬件,同時針對不同對象需要重新設置開關,在不清楚對方波特率的情況下還無法使用。第二種方法采用軟硬件結合,通過檢測、計算,自動選擇正確的波特率,實際使用極其方便。
自適應波特率串口的實現方法通常有以下幾種:
(1)協議約定通信開始時主機固定發送1個字符,從機以不同的波特率試探接收, 當接收到的數據與約定相同時,確定該波特率即是正確的通信波特率。……