UART - 使用UART与电脑沟通
UART介绍
- UART使用了两条线让双方可以同时传送资料。其中一条是Transmitting, 另一条则是Receiving,双方使用约定好的频率(baud rate)来传资料。Arduino 称呼UART 为Serial, 在Arduino Uno上只有一组硬体UART,并且这组UART主要被当作印出讯息使用(即Log UART),所以当Arduino要使用硬体的UART时,就会占用Log UART的资源。为了提供多组UART, Arduino Uno利用软体将Serial Pin模拟成UART的行为,称之为Software Serial。Ameba除了Log UART之外,还提供多组硬体的UART。为了相容于Arudino的Software Serial API,Ameba在取名上沿用Software Serial,但底层是硬体而不是软体模拟。
材料准备
- Ameba x 1
- USB to TTL Adapter x 1
范例说明
USB to TTL Adapter送出资料给Ameba,Ameba回传相同的资料,最后显示在萤幕上。
- 安装USB to TTL Adapter
USB to TTL Adapter是个将USB转成Serial介面的晶片。它一般会有4根脚,分别是3V3(或5V), GND, TX, RX。在使用USB to TTL Adapter时,通常都需要安装驱动程式。如果你的晶片是FTDI的,Windows会上网找驱动程式并自动安装,或者也可以自己找驱动程式。
安装完驱动程式之后, 会在装置管理员找到对应的Serial Port, 像图中我的FTDI USB to TTL Adapter在COM8, 而Silicon USB to TTL Adapter则在COM6:
- 执行范例
首先先打开SoftwareSerialExamle范例, 它在 “File” -> “Examples” -> “AmebaSoftwareSerial” -> “SoftwareSerialExample”:

RTL8710 接线图如下:
接着我们打开Serial Port Terminal, 常见的Serial Port Terminal有Putty, Tera Term。我们以Putty说明如何设定, 先将Connection Type选择Serial, 并且将Serial line填入USB to TTL Adapter所在的Port, (Ex. COM8)。Speed指的就是USB的baud rate,需要与Serial的另一端做搭配,这个在范例里为4800,所以我们设定4800。

接着我们切换左边的Category到Serial的页面,其中Data bits为8, Stop bits为1, Stop bits为1, Parity为None, Flow control为None。

设定完之后按下Open, 并且按下Ameba的Reset按钮,Putty就会出现“Hello, world?” 的讯息, 这时候你在键盘上敲字,会经由USB to TTL Adapter的TX送到Ameba的Serial RX, 在程式码里面再送到Ameba的Serial TX, 最后由USB to TTL Adapter的RX接收并印出来。所以如果我们敲这个讯息“I am fine”, 就会出现这样:
程式码说明
首先需要设定UART的Baud rate, 使用SoftwareSerial:Begin():
https://www.arduino.cc/en/Reference/SoftwareSerialBegin
使用write送出资料, 并且使用Software:available()来检查是否有资料送进来:
https://www.arduino.cc/en/Reference/SoftwareSerialAvailable
如果有资料进来, 就使用read将资料读进来。
https://www.arduino.cc/en/Reference/SoftwareSerialBegin
使用write送出资料, 并且使用Software:available()来检查是否有资料送进来:
https://www.arduino.cc/en/Reference/SoftwareSerialAvailable
如果有资料进来, 就使用read将资料读进来。
Realtek IoT/Wi-Fi MCU Solutions . All Rights Reserved. 使用条款