UART - 透过 USB 转 Serial 模组与 PC 通讯

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。为了相容于Arduino的Software Serial API,Ameba在取名上沿用Software Serial,但底层是硬体而不是软体模拟。

材料准备

  • AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1

  • USB to TTL Adapter x 1

范例说明

In this example, we use UART to connect USB to TTL adapter to Ameba. USB to TTL adapter sends data to Ameba, the data would be returned by Ameba, and showed on the screen.

安装USB to TTL Adapter

USB to TTL adapter converts USB to serial interface. Normally, there are at least 4 pins on the adapter, that is 3V3 (or 5V), GND, TX and RX. Generally, installing the driver for the USB to TTL adapter would be required before using it. If the adapter uses the chip of FTDI, Windows will search and install the driver automatically, otherwise, you may need to install corresponding driver yourself. Afterwards, open device manager. You can find corresponding serial port number of the USB to TTL adapter:

../../../../_images/image174.png

Executing the Example

Open the “SoftwareSerialExample” example in “File” “Examples” “AmebaSoftwareSerial” “SoftwareSerial_Basic”:

../../../../_images/image268.png

并且我们这样接线, USB to TTL Adapter的TX接到Ameba的D0(即RX), USB to TTL Adapter的RX接到Ameba的D1(即TX):

AMB21 / AMB22 接线图如下:

../../../../_images/image345.png

AMB23 接线图如下:

../../../../_images/image3-17.png

BW16 接线图如下:

../../../../_images/image3-36.png

BW16-TypeC Wiring Diagram:

../../../../_images/image3-43.png

接着我们打开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。

../../../../_images/image433.png

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

../../../../_images/image525.png

设定完之后按下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”, 就会出现这样:

../../../../_images/image613.png

程式码说明

First, use SoftwareSerial:begin(speed) to set the baud rate for the serial communication: https://www.arduino.cc/en/Reference/SoftwareSerialBegin

Use write() to send data, and use SoftwareSerial:available() to get the number of bytes available for reading from a software serial port: https://www.arduino.cc/en/Reference/SoftwareSerialAvailable

如果有资料进来, 就使用read将资料读进来。