如何決定 Baud Rate?

Embedded systems 常常用到 UART 傳送訊息,既然要用 UART ,選用適當的 baud rate 是免不了的。

舉個例子:為了方便除錯,我想採用 MCU 的 UART module ,經由 RS232 餵訊息給 PC ,然後秀到 COM port terminal 上。

以最近採用的 Evatronix R80515 來說,在 datasheet 上可以查到計算 baud rate 的式子:

(1)
\begin{align} baud\ rate = \frac {2^{smod} F_{clk}} {64 (2^{10}-s0rel)} \end{align}

這次打算餵 CPU 吃 12MHz 的時脈,所以 $F_{clk}=12000000$
此外,我們將 smod 設成 1

有了這些,還是不能亂設,因為 RS232 要正確傳輸資料,其 baud rate 誤差要小於 3% 。

時間多的話,當然可以針對常用的 baud rate ,一組組實際寫 firmware 測試。

因為厭倦這種無趣的反覆,於是呢,我就以爬說語來命令電腦代勞:

>>> s = lambda x: 1024-(2*12000000+64*x/2)/(64*x)
>>> b = lambda x: 2*12000000/(64*(1024-x))
>>> e = lambda x: (b(s(x))-x)/float(x)

隨便敲兩組進去算算誤差:

>>> e(9600)
0.0015625000000000001
>>> e(28800)
0.0015972222222222223

一口氣試試幾組標準 baud rate :

>>> r = [600,1200,2400,4800,9600,14400,19200,28800,38400,56000,57600,115200,128000,256000]
>>> for x in r:
        print x, e(x)

600 0.0
1200 -0.00166666666667
2400 0.00125
4800 0.00145833333333
9600 0.0015625
14400 0.00159722222222
19200 -0.0234375
28800 0.00159722222222
38400 -0.0234375 — 誤差範圍的最佳選擇
56000 -0.043375
57600 -0.0699479166667
115200 0.0850694444444
128000 -0.0234375
256000 0.46484375

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License