> [!CAUTION]
> **Important:** Chrome will be removing support for Chrome Apps on all platforms. Chrome browser and the Chrome Web Store will continue to support extensions. [**Read the announcement**](https://blog.chromium.org/2020/08/changes-to-chrome-app-support-timeline.html) and learn more about [**migrating your app**](https://developer.chrome.com/apps/migration).

This document describes how to use the [serial API](https://developer.chrome.com/apps/reference/serial) to read and write from serial devices. Chrome
Apps can also connect to [USB](https://developer.chrome.com/docs/apps/app_usb.md.txt) and [Bluetooth](https://developer.chrome.com/docs/apps/app_bluetooth.md.txt) devices.

> [!NOTE]
> **Note:** **Samples:** For examples that illustrate how Chrome Apps can connect to hardware devices through a serial port, see the [adkjs](https://github.com/GoogleChrome/chrome-app-samples/tree/master/samples/serial/adkjs#readme), [ledtoggle](https://github.com/GoogleChrome/chrome-app-samples/tree/master/samples/serial/ledtoggle#readme) and the [servo](https://github.com/GoogleChrome/chrome-app-samples/tree/master/samples/servo#readme) samples.

## Manifest requirement

You must add the "serial" permission to the manifest file:

```json
"permissions": [
  "serial"
]
```

## Listing available serial ports

To get a list of paths associated with available serial ports, use the [`serial.getDevices`](https://developer.chrome.com/docs/apps/reference/serial.md.txt#method-getDevices)
method. **Note:** not all serial ports are available. The API uses heuristics to only expose serial
devices that are expected to be safe.

```javascript
var onGetDevices = function(ports) {
  for (var i=0; i<ports.length; i++) {
    console.log(ports[i].path);
  }
}
chrome.serial.getDevices(onGetDevices);
```

## Connecting to a serial device

If you know the path associated with the serial port, you can connect to it using the
[`serial.connect`](https://developer.chrome.com/docs/apps/reference/serial.md.txt#method-connect) method:

```javascript
chrome.serial.connect(path, options, callback)
```

| Parameter | Description |
|---|---|
| path (string) | If the path associated with your device's port is unknown, you can use the [`serial.getDevices`](https://developer.chrome.com/apps/serial#method-getDevices) method. |
| options (object) | Parameter object with several configuration values. See details at [serial.ConnectionOptions](https://developer.chrome.com/apps/serial#type-ConnectionOptions) |
| callback | Invoked when the port has been successfully opened. The callback will be called with one parameter, `connectionInfo`, that has several important values. See details at [serial.ConnectionInfo](https://developer.chrome.com/apps/serial#type-ConnectionInfo). |

A simple example:

```javascript
var onConnect = function(connectionInfo) {
   // The serial port has been opened. Save its id to use later.
  _this.connectionId = connectionInfo.connectionId;
  // Do whatever you need to do with the opened port.
}
// Connect to the serial port /dev/ttyS01
chrome.serial.connect("/dev/ttyS01", {bitrate: 115200}, onConnect);
```

## Disconnect from a serial port

When an app terminates, connections to serial ports that are not persistent are automatically closed
by the platform. However, if you want to disconnect while your app is still running, you can use the
[serial.disconnect](https://developer.chrome.com/docs/apps/reference/serial.md.txt#method-disconnect) method:

```javascript
var onDisconnect = function(result) {
  if (result) {
    console.log("Disconnected from the serial port");
  } else {
    console.log("Disconnect failed");
  }
}
chrome.serial.disconnect(connectionId, onDisconnect);
```

## Reading from a serial port

The serial API reads from the serial port and delivers the read bytes as an ArrayBuffer to event
listeners. Every port that your application is connected to will generate read events to all
listeners added through `chrome.serial.onReceive.addListener(onReceiveCallback)`. If you are
connected to more than one port at the same time, you may find the corresponding `connectionId` of
an incoming read event in the callback parameter of [serial.onReceive](https://developer.chrome.com/docs/apps/reference/serial.md.txt#event-onReceive).

The following example can accumulate read bytes until a new line is read, converting the received
ArrayBuffer to String and calling a method when a newline is found as the last character received:

```javascript
var stringReceived = '';

var onReceiveCallback = function(info) {
    if (info.connectionId == expectedConnectionId && info.data) {
      var str = convertArrayBufferToString(info.data);
      if (str.charAt(str.length-1) === '\n') {
        stringReceived += str.substring(0, str.length-1);
        onLineReceived(stringReceived);
        stringReceived = '';
      } else {
        stringReceived += str;
      }
    }
  };

chrome.serial.onReceive.addListener(onReceiveCallback);

// [...] not shown here: connect to the serial port
```

## Sending data to a serial port

Sending data is simpler than reading. The only catch is that if your data protocol is String based,
you have to convert your output string to an `ArrayBuffer`. See the code example below:

```javascript
var writeSerial=function(str) {
  chrome.serial.send(connectionId, convertStringToArrayBuffer(str), onSend);
}
// Convert string to ArrayBuffer
var convertStringToArrayBuffer=function(str) {
  var buf=new ArrayBuffer(str.length);
  var bufView=new Uint8Array(buf);
  for (var i=0; i<str.length; i++) {
    bufView[i]=str.charCodeAt(i);
  }
  return buf;
}
```

## Flushing a serial port buffer

You can flush your serial port buffer by issuing the flush command:

```javascript
  chrome.serial.flush(connectionId, onFlush);
```

## More

The Serial API has several other features. You can, for example, set a connection to persistent, so
it can receive data even when your app is not running, or you can update connection parameters on
the fly, like bitrate, timeouts, control signals, and many others with the [serial.update](https://developer.chrome.com/docs/apps/reference/serial.md.txt#method-update)
method. See the full reference of the [serial](https://developer.chrome.com/docs/apps/reference/serial.md.txt) API for more information.