Newer
Older
mbed-os / TESTS / integration / COMMON / sample.txt
# Full API list

## Platform APIs

[Platform APIs](platform.html) provide general purpose MCU management infrastructure, common data structures and a consistent user experience on top of different standard libraries and toolchains.

<table>
<tbody>
<tr>
<td><a href="wait.html">Wait</a></td>
<td><a href="time.html">Time</a></td>
<td><a href="noncopyable.html">NonCopyable</a></td>
<td><a href="circularbuffer.html">CircularBuffer</a></td>
</tr>
<tr>
<td><a href="callback.html">Callback</a></td>
<td><a href="rtc.html">RTC</a></td>
<td><a href="shared-pointer.html">Shared pointer</a></td>
<td><a href="atcmdparser.html">ATCmdParser</a></td>
</tr>
<tr>
<td><a href="deepsleeplock.html">DeepSleepLock</a></td>
<td><a href="debug.html">Debug</a></td>
<td><a href="span.html">Span</a></td>
<td><a href="mbed-statistics.html">Mbed statistics</a></td>
</tr>
<tr>
<td><a href="power-management-sleep.html">Power management (sleep)</a></td>
<td><a href="memory-tracing.html">Memory tracing</a></td>
<td><a href="filehandle.html">FileHandle</a></td>
<td><a href="mpu-management.html">MPU management</a></td>
</tr>
<tr>
<td><a href="idle-loop.html">Idle loop</a></td>
<td><a href="error-handling.html">Error handling</a></td>
<td><a href="poll.html">Poll</a></td>
<td><a href="scopedramexecutionlock.html">ScopedRamExecutionLock</a></td>
</tr>
<tr>
<td><a href="criticalsectionlock.html">CriticalSectionLock</a></td>
<td><a href="assert.html">Assert</a></td>
<td><a href="platformmutex.html">PlatformMutex</a></td>
<td><a href="scopedromwritelock.html">ScopedRomWriteLock</a></td>
</tr>
</tbody>
</table>

## Drivers APIs

[Driver APIs](drivers.html) include analog and digital inputs and outputs on development boards, as well as digital interfaces, which allow your board to interface with a computer or external devices.

<table>
<tbody>
<tr>
<td><a href="analogin.html">AnalogIn</a></td>
<td><a href="busout.html">BusOut</a></td>
<td><a href="interruptin.html">InterruptIn</a></td>
<td><a href="lowpowertimer.html">LowPowerTimer</a></td>
<td><a href="quadspi-qspi.html">QuadSPI (QSPI)</a></td>
</tr>
<tr>
<td><a href="analogout.html">AnalogOut</a></td>
<td><a href="businout.html">BusInOut</a></td>
<td><a href="ticker.html">Ticker</a></td>
<td><a href="flash-iap.html">Flash IAP</a></td>
<td><a href="i2c.html">I2C</a></td>
</tr>
<tr>
<td><a href="digitalin.html">DigitalIn</a></td>
<td><a href="portin.html">PortIn</a></td>
<td><a href="timeout.html">Timeout</a></td>
<td><a href="rawserial.html">RawSerial</a></td>
<td><a href="i2cslave.html">I2CSlave</a></td>
</tr>
<tr>
<td><a href="digitalout.html">DigitalOut</a></td>
<td><a href="portout.html">PortOut</a></td>
<td><a href="timer.html">Timer</a></td>
<td><a href="serial.html">Serial</a></td>
<td><a href="can.html">CAN</a></td>
</tr>
<tr>
<td><a href="digitalinout.html">DigitalInOut</a></td>
<td><a href="portinout.html">PortInOut</a></td>
<td><a href="lowpowerticker.html">LowPowerTicker</a></td>
<td><a href="spi.html">SPI</a></td>
<td><a href="mbedcrc.html">MbedCRC</a></td>
</tr>
<tr>
<td><a href="busin.html">BusIn</a></td>
<td><a href="pwmout.html">PwmOut</a></td>
<td><a href="lowpowertimeout.html">LowPowerTimeout</a></td>
<td><a href="spislave.html">SPISlave</a></td>
</tr>
</tbody>
</table>

## RTOS APIs

The [Mbed OS RTOS](rtos.html) capabilities include managing objects such as threads, synchronization objects and timers. It also provides interfaces for attaching an application-specific idle hook function, reads the OS tick count and implements functionality to report RTOS errors.

<table>
<tbody>
<tr>
<td><a href="thread.html">Thread</a></td>
<td><a href="semaphore.html">Semaphore</a></td>
<td><a href="memorypool.html">MemoryPool</a></td>
<td><a href="event.html">Event</a></td>
</tr>
<tr>
<td><a href="thisthread.html">ThisThread</a></td>
<td><a href="queue.html">Queue</a></td>
<td><a href="mail.html">Mail</a></td>
<td><a href="conditionvariable.html">ConditionVariable</a></td>
</tr>
<tr>
<td><a href="mutex.html">Mutex</a></td>
<td><a href="eventqueue.html">EventQueue</a></td>
<td><a href="eventflags.html">EventFlags</a></td>
<td><a href="kernel-interface-functions.html">Kernel interface functions</a></td>
</tr>
</tbody>
</table>

## USB APIs

The Mbed OS classes providing USB peripheral functionality, also known as [USB components](../apis/usb.html), inherit from USBDevice and provide specific USB peripherial functionality.

<table>
<tbody>
<tr>
<td><a href="usbserial.html">USBSerial</a></td>
<td><a href="usbhid.html">USBHID</a></td>
<td><a href="usbcdc-ecm.html">USBCDC_ECM</a></td>
<td><a href="usbmidi.html">USBMIDI</a></td>
<td><a href="usbkeyboard.html">USBKeyboard</a></td>
</tr>
<tr>
<td><a href="usbaudio.html">USBAudio</a></td>
<td><a href="usbcdc.html">USBCDC</a></td>
<td><a href="usbmsd.html">USBMSD</a></td>
<td><a href="usbmouse.html">USBMouse</a></td>
<td><a href="usbmousekeyboard.html">USBMouseKeyboard</a></td>
</tr>
</tbody>
</table>

## Network socket APIs

[Network socket APIs](network-socket.html) include the application programming interface for IP networking. In Mbed OS, this API supports both TCP and UDP protocols.

<table>
<tbody>
<tr>
<td><a href="socket.html">Socket</a></td>
<td><a href="tcpsocket.html">TCPSocket</a></td>
<td><a href="non-ip-cellular-socket.html">Non-IP cellular socket</a></td>
<td><a href="tlssocket.html">TLSSocket</a></td>
<td><a href="socketstats.html">SocketStats</a></td>
</tr>
<tr>
<td><a href="udpsocket.html">UDPSocket</a></td>
<td><a href="socketaddress.html">SocketAddress</a></td>
<td><a href="dns-resolver.html">DNS resolver</a></td>
<td><a href="dtlssocket.html">DTLSSocket</a></td>
</tbody>
</table>

## Network interfaces APIs

[Network interfaces](network-interfaces.html) are the application level APIs where users choose the driver, connectivity method and IP stack. These include ethernet, Wi-Fi, cellular and mesh interfaces.

<table>
<tbody>
<tr>
<td><a href="ethernet.html">Ethernet</a></td>
<td><a href="cellular-api.html">Cellular</a></td>
<td><a href="network-status.html">Network status</a></td>
</tr>
<tr>
<td><a href="wi-fi.html">Wi-Fi</a></td>
<td><a href="mesh-api.html">Mesh</a></td>
</tr>
</tbody>
</table>

## Bluetooth Low Energy (BLE) APIs

[Bluetooth low energy (BLE)](bluetooth.html) is a low power wireless technology standard for building personal area networks. Typical applications of BLE are health care, fitness trackers, beacons, smart home, security, entertainment, proximity sensors, industrial and automotive.

<table>
<tbody>
<tr>
<td><a href="ble.html">BLE</a></td>
<td><a href="gattclient.html">GattClient</a></td>
<td><a href="securitymanager.html">SecurityManager</a></td>
<td><a href="heartrateservice.html">HeartRateService</a></td>
</tr>
<tr>
<td><a href="gap.html">GAP</a></td>
<td><a href="gattserver.html">GattServer</a></td>
<td><a href="batteryservice.html">BatteryService</a></td>
<td><a href="ibeacon.html">iBeacon</a></td>
</tr>
</tbody>
</table>

## LoRaWAN APIs

Arm Mbed OS provides a native network stack for [LoRaWAN](lorawan.html). LoRaWAN is a technology designed for low-power battery-powered devices. These devices operate in an unlicensed spectrum, creating high density wide-area networks.

<table>
<tbody>
<tr>
<td><a href="lorawan-api.html">LoRaWANInterface</a></td>
</tr>
<tr>
<td><a href="loraradio-api.html">LoRaRadio</a></td>
</tr>
</tbody>
</table>

## NFC APIs

You can use [Near-Field Communication (NFC)](nfc.html), a short-range radio technology, to enable use cases such as contactless payments, access control and device pairing.

<table>
<tbody>
<tr>
<td><a href="nfccontroller.html">NFCController</a></td>
<td><a href="messageparser.html">MessageParser</a></td>
<td><a href="messagebuilder.html">MessageBuilder</a></td>
</tr>
<tr>
<td><a href="nfc-eeprom.html">NFC EEPROM</a></td>
<td><a href="simplemessageparser.html">SimpleMessageParser</a></td>
</tr>
</tbody>
</table>

## Security API

With [Arm Mbed TLS](security.html), a comprehensive SSL/TLS solution, you can include cryptographic and SSL/TLS capabilities in your code.

<table>
<tbody>
<tr>
<td><a href="../apis/psa-initial-attestation.html">PSA attestation</a></td>
<td><a href="../apis/psa-lifecycle.html">PSA lifecycle</a></td>
<td><a href="devicekey.html">DeviceKey</a></td>
</tr>
<tr>
<td><a href="mbed-crypto.html">Mbed Crypto</a></td>
<td><a href="tls.html">TLS</a></td>
</tr>
</tbody>
</table>

## Storage APIs

The [storage APIs](storage.html) include file system APIs, for file system operations, and block devices, which provide the raw storage for the file systems.

<table>
<tbody>
<tr>
<td><a href="kvstore.html">KVStore</a></td>
<td><a href="littlefilesystem.html">LittleFileSystem</a></td>
<td><a href="chainingblockdevice.html">ChainingBlockDevice</a></td>
<td><a href="../apis/dataflashblockdevice.html">DataFlashBlockDevice</a></td>
</tr>
<tr>
<td><a href="static-global-api.html">Static Global API</a></td>
<td><a href="fatfilesystem.html">FATFileSystem</a></td>
<td><a href="slicingblockdevice.html">SlicingBlockDevice</a></td>
<td><a href="flashiapblockdevice.html">FlashIAPBlockDevice</a></td>
<td><a href="../apis/psa-internal-storage.html">PSA internal storage</a></td>
</tr>
<tr>
<td><a href="filesystem.html">FileSystem</a></td>
<td><a href="blockdevice.html">BlockDevice</a></td>
<td><a href="profilingblockdevice.html">ProfilingBlockDevice</a></td>
<td><a href="sdblockdevice.html">SDBlockDevice</a></td>
<td><a href="../apis/psa-protected-storage.html">PSA protected storage</a></td>
</tr>
<tr>
<td><a href="dir.html">Dir</a></td>
<td><a href="heapblockdevice.html">HeapBlockDevice</a></td>
<td><a href="bufferedblockdevice.html">BufferedBlockDevice</a></td>
<td><a href="spi-flash-block-device.html">SPIFlashBlockDevice</a></td>
</tr>
<tr>
<td><a href="file.html">File</a></td>
<td><a href="mbrblockdevice.html">MBRBlockDevice</a></td>
<td><a href="flashsimblockdevice.html">FlashSimBlockDevice</a></td>
<td><a href="qspifblockdevice.html">QSPIFBlockDevice</a></td>
</tr>
</tbody>
</table>
# BLE

Bluetooth low energy (BLE) is a low power wireless technology standard for building personal area networks. Typical applications of BLE are health care, fitness trackers, beacons, smart home, security, entertainment, proximity sensors, industrial and automotive.

Arm Mbed BLE, also called `BLE_API`, is the Bluetooth Low Energy software solution for Mbed. Many Mbed [targets and components](https://os.mbed.com/platforms/?mbed-enabled=15&connectivity=3) support Mbed BLE. Developers can use it to create new BLE enabled applications.

Mbed’s `BLE_API` interfaces with the BLE controller on the platform. It hides the BLE stack’s complexity behind C++ abstractions and is compatible with all BLE-enabled Mbed platforms. The Mbed OS `BLE_API` automatically configuring the clocks, timers and other hardware peripherals to work at their lowest power consumption.

## `BLE_API`, bridges and stacks

<span class="images">![](../../images/BLEDiagram.png)</span>

You can build a BLE application using Mbed OS, `BLE_API` and a controller-specific Bluetooth stack together with some bridge software to adapt it to `BLE_API`:

- `BLE_API` as described above.
- The bridge software is specific to each vendor’s platform. It provides the instantiations for the interfaces `BLE_API` offers and helps drive the underlying controller and Bluetooth stack.
- The Bluetooth stack implements the Bluetooth protocol and is specific to the controller, so a vendor using different controllers may provide different stacks.

## Inside `BLE_API`

<span class="images">![](../../images/Inside_API.png)</span>

`BLE_API` offers building blocks to help construct applications. These fall into two broad categories:

1. Interfaces under **`ble/`** to express BLE constructs, such as GAP, GATT, services and characteristics.

1. Classes under `ble/services` to offer reference implementations for many of the commonly used GATT profiles. The code under 'services/' isn't essential, but it’s a useful starting point for prototyping. We continue to implement the standard GATT profiles.

## The BLEDevice class and header

The entry point of Mbed's `BLE_API` is the BLE class accessible using the header `ble/BLE.h`. This class allows you to obtain a BLE object that includes the basic attributes of a spec-compatible BLE device and can work with any BLE radio:

```c TODO
#include "ble/BLE.h"

BLE& mydevicename = BLE::Instance();
```

The class's member functions can be divided by purpose:

1. Basic BLE operations, such as initializing the controller.

1. Accessor to Bluetooth Modules that manage GAP, GATT or the security.

## Usage

1. Set up advertising and connection modes.
1. Assign UUIDs to the service and its characteristic.
1. Create an input characteristic.
1. Construct a service class and add it to the BLE stack.
1. Push notifications when the characteristic's value changes.

## BLE class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_b_l_e.html)

## Example: BLE beacon

Here is an example demonstrating how you can create a BLE beacon.

[![View code](https://www.mbed.com/embed/?url=https://github.com/ARMmbed/mbed-os-example-ble/blob/master/BLE_Beacon/source)](https://github.com/ARMmbed/mbed-os-example-ble/blob/mbed-os-5.13/BLE_Beacon/source/main.cpp)

## Example: BLE heart rate monitor

Here is an example demonstrating how to build a heart rate sensor that can be connected and monitored by a BLE client such as your phone.

[![View code](https://www.mbed.com/embed/?url=https://github.com/ARMmbed/mbed-os-example-ble/blob/master/BLE_HeartRate/source)](https://github.com/ARMmbed/mbed-os-example-ble/blob/mbed-os-5.13/BLE_HeartRate/source/main.cpp)

## Related content

- Mbed Enabled [targets and components](https://os.mbed.com/platforms/?mbed-enabled=15&connectivity=3) that support BLE.
- [BLE tutorial](../tutorials/ble-tutorial.html).
- [Office Hours video about BLE](https://www.youtube.com/watch?v=j5RJ6UfkylA).
# BatteryService

It is often a requirement for devices operating on battery to report the battery charge level to the user.

The [Bluetooth Battery Service](https://www.bluetooth.org/docman/handlers/downloaddoc.ashx?doc_id=245138) defines how to expose a battery charge level through a BLE link. It allows a client - usually a smartphone application - of a device to read the current battery charge level and follow its evolution.

The BatteryService class implements the Bluetooth Battery Service as defined by the Bluetooth SIG. Makers of BLE devices operating on battery can use the API to expose interoperably the charge level of their products.

## BatteryService class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/mbed-os/v5.13/mbed-os-api-doxy/class_battery_service.html)

## BatteryService example

[![View code](https://www.mbed.com/embed/?url=https://github.com/ARMmbed/mbed-os-example-ble/blob/master/BLE_BatteryLevel/source)](https://github.com/ARMmbed/mbed-os-example-ble/blob/mbed-os-5.13/BLE_BatteryLevel/source/main.cpp)

## Related content

- [Bluetooth Battery Service](https://www.bluetooth.org/docman/handlers/downloaddoc.ashx?doc_id=245138) specification.
# EnvironmentalService

[Add description here.]

## EnvironmentalService class reference

[![View code](https://os.mbed.com/docs/development/mbed-os-api-doxy/class_environmental_service.html)

## EnvironmentalService example

[Add example here.]
# GAP

The Generic Access Profile is the layer of the stack that handles connectivity tasks. This includes link establishment and termination, advertising and scanning.

Devices with data to publish can use GAP to advertise. They can include the data in the advertisement itself, inside the scan response, or leave a peer device to query it after the connection has been established.

The other side of the process is the act of scanning, which listens for advertisements, allows you to query the advertisers for more data through a scan request or connect in order to query the peer device for the data you want.

Advertising, scanning and connection all have parameters that let you find a compromise between desired power consumption levels, latency and efficiency of these processes.

## Advertising

Advertising consists of broadcasting at a regular interval a small amount of data containing valuable information about the device. Peer devices listening on BLE advertising channels may scan these packets.

Scanners may also request additional information from device advertising by sending a scan request. If the broadcaster accepts scan requests, it can reply with a scan response packet containing additional information.

## Scanning

Scanning consists of listening for peer advertising packets. From a scan, a device can identify devices available in its environment.

If the device scans actively, it sends scan request to scannable advertisers and collects their scan responses.

## Extended and periodic advertising

BLE controllers supporting Bluetooth 5.0 may offer additional advertising and scanning options. Use `isFeatureSupported()` to check feature availability.

Extended advertising may use multiple PHYs and spread the payload across many packets. This allows for much larger payloads. In this scenario, advertising is split across primary advertising on the advertising channels and secondary advertising using channels normally used for sending data to connected devices.

Similarly, if the controller supports periodic advertising, you may use periodic advertising to send changing data to many peers. Each peer needs to scan the advertisements on the primary channels and create a sync with a periodic advertisement it's interested in.

There may be many advertising sets active at one time on a single advertiser. This allows it to advertise different data at the same time, possibly to different peers.

Devices that do not support extended and periodic advertising will not see these advertisements. You may use legacy advertising alongside extended advertising, running at the same time, to support older devices in the environment.

## Privacy

Privacy is a feature that allows a device to avoid being tracked by other (untrusted) devices. The device achieves it by periodically generating a new random address. The random address may be a resolvable random address, enabling trusted devices to recognize it as belonging to the same device. These trusted devices receive an Identity Resolution Key (IRK) during pairing. The SecurityManager handles this and relies on the other device accepting and storing the IRK.

You need to enable privacy by calling `enablePrivacy()` after initializing the SecurityManager because privacy requires SecurityManager to handle IRKs. Set the behavior of privacy enabled devices by using `setCentralPrivacyConfiguration()`, which specifies what the device should be with devices using random addresses, and `setPeripheralPrivacyConfiguration`. Random addresses that privacy enabled devices generate can be of two types: resolvable (by devices who have the IRK) and unresolvable. You can't use unresolvable addresses for connecting and connectable advertising; therefore, use a resolvable one for these, regardless of the privacy configuration.

## Modulation schemes

When supported by the host and controller, you can select different modulation schemes:

 - LE 1M PHY.
 - LE 2M PHY.
 - LE coded PHY.

These provide different compromises between bandwidth, power usage and error resiliency (see BLUETOOTH SPECIFICATION Version 5.0 Vol 1, Part A - 1.2).

You may set preferred PHYs (separately for RX and TX) using `setPreferredPhys()`. You may also set the currently used PHYs on a selected connection using `setPhy()`. Both of these settings are only advisory. The controller is allowed to make its own decision on the best PHY to use based on your request, the peer's supported features and the connection's physical conditions.

You may query the currently used PHY using `readPhy()`, which returns the result through a call to the registered event handler. You may register the handler with `setEventHandler()`. The events inform about the currently used PHY and of any changes to PHYs, which the controller or the peer may trigger autonomously.

## Data length (over-the-air MTU)

In addition to modulation schemes, Maximum Transmission Unit (MTU) size also strongly affects throughput. Newer controllers allow you to negotiate bigger MTUs. Because each packet contains overhead, bigger packets maximize throughput.

There are two separate MTUs to consider: the `ATT_MTU` (maximum attribute size) and data length. `GattServer` and `GattClient` affect `ATT_MTU`. `Gap` only deals with data length, which is the maximum size of the packet that carries attributes that are fragmented across many such packets.

The default value of data length supported by all controllers is 23 octets. If both controllers support data length extension and a higher value is negotiated, the BLE stack will call `onDataLengthChange` in the `Gap::EventHandler` registered by the user.

`ATT_MTU` and data length are independent of each other.

## GAP class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_gap.html)

## GAP example

Here is an example demonstrating how to use the GAP API to advertise, scan, connect and disconnect and how parameters influence efficiency of these actions.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed-os-examples/code/mbed-os-example-ble-GAP/)](https://os.mbed.com/teams/mbed-os-examples/code/mbed-os-example-ble-GAP/file/d2c272f79611/source/main.cpp)
# GattClient

You can use Generic Attribute Profile (GATT) to discover services, characteristics and descriptors and to perform operations on them. The interaction happens between two peers, one of which is the client (which initiates interactions) and the other is the server (which responds). You can use Attribute Protocol (ATT) to implement this interaction. `GattClient` defines procedures required for interacting with a remote `GattServer`.

## Discovery procedures

A GattServer hosts a fixed set of services. These services are a logical composition of characteristics that may be discovered, read or written and can broadcast their state to a connected client. These characteristics may also contain metainformation and named characteristic descriptors. A characteristic descriptor may indicate the unit used for a characteristic value, describe the characteristic purpose in a textual form or allow a client to register for update notifications for the characteristic value.

Prior to any interaction with a server characteristic, a GattClient discovers the layout of the services and characteristics present on the server.

The layout of the descriptors of a characteristic may also be issued as an extra discovery step.

## Attribute manipulation

As a result of the discovery process, the client can start interacting with the characteristic discovered. Depending on the characteristic properties (acquired during discovery), a client can read or write the value of a given characteristic.

Mbed BLE abstracts read and write operations to offer a single API that can be used to read or write characteristic values. The application code does not have to handle the necessary fragmentation or reassembly process if the attribute value to be transported can't fit in a single data packet.

## Attribute Protocol Maximum Transmission Unit (ATT_MTU)

`ATT_MTU` is the maximum size of the attribute protocol packet. Operation on attributes too large to fit into a single packet are split across multiple operations.

This is independent of the data length, which controls the over-the-air packet payload size (which the GAP handles). An L2CAP packet containing the attribute protocol packet is fragmented over many packets if required.

Only `GattClient` can trigger the exchange of `ATT_MTU` between client and server. Depending on the implementation of the bluetooth stack, the client may trigger the exchange upon connection. You may also manually request the exchange using `negotiateAttMtu`. If an exchange happens, the biggest value possible across both devices will be used. Negotiation is only a best-effort process and does not guarantee a higher value being set.

`ATT_MTU` is at least 23 octets by default. If a larger size is negotiated, the user application will be informed through the `onAttMtuChange` function called in the `GattClient::EventHandler`. (`GattServer::EventHandler` is also informed.)

## Server initiated events

When a server updates a characteristic value, it can forward the new value to any registered clients. Clients may register for these updates on a per-characteristic basis. The server sends the updates by using notifications (no confirmation from client) or indications (client confirms receipt). This mechanism minimizes the number of transactions between a client and a server by avoiding polling.

Clients register for these updates by setting the Client Characteristic Configuration Descriptor (CCCD) value. This is an attribute, and the client needs to discover its descriptor. It is present in the characteristic if its notify or indicate properties are set.

## GattClient class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_gatt_client.html)

## GattClient example

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed-os-examples/code/mbed-os-example-ble-GattClient/)](https://os.mbed.com/teams/mbed-os-examples/code/mbed-os-example-ble-GattClient/file/38639a71a0f1/source/main.cpp)
# GattServer

You can use Generic Attribute Profile (GATT) to discover services, characteristics and descriptors and to perform operations on them. The interaction happens between two peers, one of which is the client (which initiates interactions) and the other is the server (which responds). You can use Attribute Protocol (ATT) to implement this interaction.

`GattServer` is a collection of GattServices. These services contain characteristics that a `GattClient` on the peer connected to the device may read or write. These characteristics may also emit updates to subscribed clients when their values change.

## Server layout

Application code can add a GattService object to the server with the help of the function `addService()`. That function registers all the GattCharacteristics enclosed in the service, as well as all the characteristic descriptors (see GattAttribute) that these characteristics contain. Service registration assigns a unique handle to the various attributes that are part of the service. The user must use this handle to read or write these components.

There are no defined primitives that remove a single service; however, a call to the function `reset()` removes all services previously registered in the GattServer.

## Characteristic and attributes access

You must access values of the characteristic and the characteristic descriptor present in the GattServer through the handle assigned to them when you registered the service. The GattServer class offers several types of `read()` and `write()` functions that retrieve or mutate an attribute value.

You can query the server by invoking the function `areUpdatesEnabled()` to find out if a client has subscribed to a given characteristic's value update.

## Attribute Protocol Maximum Transmission Unit (ATT_MTU)

The Attribute Protocol Maximum Transmission Unit (`ATT_MTU`) is the maximum size of the attribute protocol packet. For details, please see the [GattClient Documentation](../apis/gattclient.html).

## Events

You can register several event handlers with the GattServer that it will call to notify you of client (remote application connected to the server) and server activities:

- `onDataSent`: Register an event handler with the GattServer that it will call to notify you when it sends a characteristic value update to a client.
- `onDataWriten`: Register an event handler with the GattServer that it will call to notify you when a client has written an attribute of the server.
- `onDataRead`: Register an event handler with the GattServer that it will call to notify you when a client has read an attribute of the server.
- `onUpdatesEnabled`: Register an event handler with the GattServer that it will call to notify you when a client subscribes to updates for a characteristic.
- `onUpdatesDisabled`: Register an event handler with the GattServer that it will call to notify you when a client unsubscribes from updates for a characteristic.
- `onConfimationReceived`: Register an event handler with the GattServer that it will call to notify you when a client acknowledges a characteristic value notification.

The term characteristic value update represents Characteristic Value Notification and Characteristic Value Indication when the nature of the server initiated is not relevant.

## GattServer class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_gatt_server.html)

## GattServer example

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed-os-examples/code/mbed-os-example-ble-GattServer/)](https://os.mbed.com/teams/mbed-os-examples/code/mbed-os-example-ble-GattServer/file/622c672f6d5f/source/main.cpp)
# HeartRateService

People practicing physical activities use heart rate monitors to track their pulse in real time and improve their physical performances.

The [Bluetooth Heart Rate Service](https://www.bluetooth.org/docman/handlers/downloaddoc.ashx?doc_id=239866) defines how data from a heart rate sensor should be exposed through a BLE link. The standard nature of the service allows seamless operations between collectors - usually smartphone applications - and heart rate monitors conforming to the service.

The HeartRateService class implements the Bluetooth Heart Rate service as defined by the Bluetooth body. Makers of BLE enabled fitness devices can use it to expose interoperably heart rate sensor data.

<span class="note"> **Note:** The Bluetooth Heart Rate Service is part of the [Bluetooth Heart Rate Profile](https://www.bluetooth.org/docman/handlers/downloaddoc.ashx?doc_id=239865), which defines behaviors that a Bluetooth heart rate sensor expects. You must ensure that your application conforms to the heart rate profile to guarantee interoperability of your heart rate sensors.</span>

## HeartRateService class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/mbed-os/v5.13/mbed-os-api-doxy/class_heart_rate_service.html)

## HeartRateService example

[![View code](https://www.mbed.com/embed/?url=https://github.com/ARMmbed/mbed-os-example-ble/blob/master/BLE_HeartRate/source)](https://github.com/ARMmbed/mbed-os-example-ble/blob/mbed-os-5.13/BLE_HeartRate/source/main.cpp)

## Related content

- [Bluetooth Heart Rate Service](https://www.bluetooth.org/docman/handlers/downloaddoc.ashx?doc_id=239866) specification.
- [Bluetooth Heart Rate Profile](https://www.bluetooth.org/docman/handlers/downloaddoc.ashx?doc_id=239865) specification.
# SecurityManager

SecurityManager deals with authentication and encryption for the Bluetooth Low Energy link. The pairing and optionally bonding processes provide this. The SecurityManager achieves bonding by saving the pairing information and reusing it on subsequent reconnections. This saves time because the pairing does not have to be performed again.

The pairing process may produce a set of keys to be used during current or later connections. The SecurityManager handles these, and they include the Long Term Encryption Key (LTK), the Identity Resolving Key (IRK) and the Connection Signature Resolving Key (CSRK). The SecurityManager uses the LTK to encrypt subsequent connections without having to pair again. The Link Controller uses IRK to identify peers who use random resolvable addresses. The application uses CSRK to sign and authenticate signed data.

The pairing process may provide man-in-the-middle protection (MITM). The SecurityManager achieves this through various means, including out of band communication, depending on the capabilities of the local and peer device.

The SecurityManager stores the keys, permanently if possible, to speed security requests on subsequent connections.

Security requests may come explicitly from the user application or implicitly from the GATT server based on attribute requirements.

## Pairing

There are several ways to provide different levels of security during pairing depending on your requirements and the facilities the application provides. The process starts with initializing the SecurityManager with default options for new connections. You can later change some settings per link or globally.

The important settings in the `init()` function are the MITM requirement and IO capabilities. MITM protection prevents an attack where one device can impersonate another device by pairing with both devices at the same time. You can achieve this protection by sharing information between the devices through an independent channel. The IO capabilities of both devices dictate what algorithm is used. For details, see BLUETOOTH SPECIFICATION Version 5.0 | Vol 3, Part H - 2.3.5.1. You can change the IO capabilities after initialization with `setIoCapability()`. This takes effect for all subsequent pairings.

Secure Connections, which relies on elliptical curve cryptography, provides the most secure pairing. Support for Secure Connections depends on both the stack and controller on both sides supporting it. If either side doesn't support it, legacy pairing is used. This is an older standard of pairing. If you require higher security, you can disable legacy pairing by calling `allowLegacyPairing(false);`.

## Out of band (OOB) data used in pairing

Sharing this information through IO capabilities means user interaction, which limits the degree of protection due to the limit of the amount of data that you can expect to transfer. Another solution is using out of band (OOB) communication to transfer this data. OOB communication can send more data and make MITM attacks less likely to succeed. The application must exchange OOB data and provide it to the SecurityManager. Use `setOOBDataUsage()` to indicate you want to use it. With this same call, you can set whether the communication channel you are using to transmit the OOB data is itself secure against MITM protection - this sets the level of the link security achieved using pairing that uses this data.

## Signing

Applications may require a level of security providing confidence that data transfers are coming from a trusted source. You can achieve this by encrypting the link, which also provides added confidentiality. Encryption is a good choice when a device stays connected but introduces latency due to the need for encrypting the link if the device only connects periodically to transfer data. If you do not require confidentiality, the GATT server may allow writes to happen over an unencrypted link but authenticated by a signature present in each packet. This signature relies on having sent a signing key to the peer during pairing prior to sending any signed packets.

## Persistence of security information

SecurityManager stores all the data required for its operation on active links. Depending on resources available on the device, it also stores data for disconnected devices, which have bonded to be reused when reconnected. If the application has initialized a file system and the SecurityManager has received a file path during the `init()` call, SecurityManager may also provide data persistence across resets. You must enable this by calling `preserveBondingStateOnReset()`. Persistence may fail if abnormally terminated. SecurityManager may also fall back to a nonpersistent implementation if the resources are too limited.

## How to use

Call `init()` with your chosen settings before calling any other SecurityManager functions.

The SecurityManager communicates with your application through events. These trigger calls in the EventHandler that you must provide by calling the `setSecurityManagerEventHandler()` function.

The most important process is pairing. You may trigger this manually by calling `requestPairing()`. Pairing may also result from the application requiring encryption by calling `setLinkEncryption()` or the application requiring MITM protection through `requestAuthentication()`.

You can call all of these implicitly by using `setLinkSecurity()` to set the required security for the link. The SecurityManager triggers the process required to achieve the set security level. You can only escalate the security level; asking the SecurityManager for a lower security level than the existing one does not fail, but results in an event informing the application through `linkEncryptionResult()` of the current level (which remains unchanged).

The chosen pairing algorithms depend on the IO capabilities and OOB use settings. They produce appropriate events, which your EventHandler must handle. If your event handler doesn't support all the calls, you must not set IO capabilities or set OOB use in such a way that would trigger them, or else the pairing fails (usually by timing out).

The simplest example is a pairing of a device with no IO capabilities and no OOB data available. This does not provide any MITM protection. The pairing (triggered implicitly or called explicitly) results in the generation of an event on the peer calling `pairingRequest()`. The event handler must make a decision (either in the application itself or based on user interaction) whether to accept the pairing and call `acceptPairing()` or `cancelPairing()`. An event calling `pairingResult()` in the EventHandler communicates te result on both peers.

## SecurityManager class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_security_manager.html)

## SecurityManager example

The SecurityManager example demonstrates both a central and a peripheral connecting, performing basic pairing and setting up link security.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed-os-examples/code/mbed-os-example-ble-SM/)](https://os.mbed.com/teams/mbed-os-examples/code/mbed-os-example-ble-SM/file/c394411633f6/source/main.cpp)
# UARTService

[Add description here.]

## UARTService class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/mbed-os/development/mbed-os-api-doxy/_u_a_r_t_service_8h_source.html)

## UARTService example

[Add example here.]
# Bluetooth overview

Bluetooth low energy (BLE) is a low power wireless technology standard for personal area networks. BLE, unlike the classic Bluetooth standard, reduces power consumption, allowing your BLE device to run for months or years on a coin-cell battery. Typical applications of BLE are health care, fitness trackers, beacons, smart home, security, entertainment, proximity sensors, industrial and automotive.

This two-way communication means you can use a single device to send information and perform actions based on that information. You could [water your garden](http://www.hosepipeban.org.uk/hosepipe-ban-current-situation/) when the ground is dry, put a beacon with your details on your dog's collar or flash a light when a car comes too close to your bicycle.

<span class="images">![](../../images/BLEsample.png)<span>A BLE setup requires a board with BLE support and a way to control it, for example a phone app or a local touchscreen.</span></span>

Arm Mbed BLE, also called `BLE_API`, is the Bluetooth Low Energy software solution for Mbed. Many targets support Mbed BLE. Developers can use it to create new BLE applications.

## Displaying information

The first thing you can do with a BLE device is display information. You can do that with lights or a [display](http://developer.mbed.org/components/cat/display/), or you can send the information to a nearby Bluetooth-enabled device, such as a mobile phone.

The information can be sensor input - for example, you could display the speed as provided by an [accelerometer](http://developer.mbed.org/components/cat/sensors-motion/) - or static information that you've programmed onto the device, such as your own details. 

## Processing information 

The two most common sources of information that you may want to process are sensors and user input. In either case, there are two main paradigms for processing:

1. *Local processing* means the device itself processes the data and determines what to do. One example is a thermostat, which knows to turn the heat on or off according to a room temperature input and doesn't need instructions from anywhere.

1. *Remote processing* means that you send data to a different device to be handled there. You then either wait for instructions from the remote device or go on gathering and sending data. For example, if you're trying to predict tomorrow's weather, the device sends data (temperature, barometric pressure and so on) to a computer that can analyze it. Then the local device doesn't need the processing power to run a weather program.

BLE is intended for low power, battery-operated devices, so typical applications will not perform complex processing on the device - processing burns through batteries. Applications will instead export the data to be processed remotely, and wait for a response.

## Sending or storing information

For a small and power-efficient device, don't store information locally. Instead, send it to a server.

Because of restrictions on energy use in radio operation, BLE is a short-range method, so you can send information over BLE only if your device and your destination are a few dozen meters apart or closer. If they're farther, you need to use Ethernet, Wi-Fi or radio.

## Working with apps or websites

One way to use BLE is to advertise information to any device in the area without becoming interactive. For example, you could notify every user entering your shop that you'll be open until late this evening. There is no need for any response from the users - it's similar to putting a notice on your door. Users only need a phone app to see these advertisements as notifications. What's key is that this app does not need to be specific to your project - the same notification app can work with any BLE device; there are several generic apps that can do this.

If an advertisement-only solution isn’t enough, you can have a transactional interaction (the fancy way of saying “conversation”) between a client and a device over a BLE connection. This usually requires a custom mobile or web-based app, though some generic apps may be enough to start. In addition to handling the data, the app may provide you with an interface through which you can send commands to the BLE device. A common example is mobile fitness apps that receive your heart rate information from a BLE-based heart rate monitor. The heart rate monitor doesn't store or process information - it just receives your heart rate and sends it to the app. The app displays the heart rate and gives you some control of the BLE device.

## The physical web and beacons

The physical web brings devices to the internet using websites (rather than device-specific applications), by using BLE as a business card that includes a link to the website. Interactions with the device are then performed using the website. Using websites rather than apps means that users don't have to install a new app for every device they want to interact with; the interaction is easier and more immediate.

The method used to provide the link is called a beacon. You can attach beacons to anything you want to provide information about or that you can provide any sort of interface for.

For example, you can attach the beacon to a vending machine. It sends you to a web interface that gives you control of the machine. It can let you make a large purchase (providing sodas for several people in one transaction) by letting you select several options and pay for them all at once.

## How a BLE device gets internet access

At the moment, BLE devices don't have independent internet access. To get internet access, you can do one of two things:

1. You can give your board a secondary communication method, such as Ethernet or Wi-Fi. This can easily double the price of the board.

1. The BLE device can use a gateway (which can be a mobile phone) to exchange data with the internet. The gateway needs to adapt the protocols used because BLE is a non-IP technology. This means that when the phone terminates the BLE connection, the BLE device loses its internet access. This doesn't require additional hardware, so it doesn't affect the price of the board. However, for the device to have constant internet access, it needs a phone (or BLE-enabled computer) next to it.

In the future, routers may accept BLE connections in the same way that they currently accept Wi-Fi connections.
# iBeacon

iBeacon is an Apple technology based on BLE that you can use as an indoor positioning system. It allows iOS apps to track if the user enters a specific region and offers actions and notification aware of the user context.

The iBeacon class builds an advertising payload mimicking an iBeacon and assigns it to a given BLE interface.

<span class="warnings"> **Warning:** To manufacture iBeacons, you must obtain a license from Apple. For more information, please see [Apple's website](https://developer.apple.com/ibeacon/). The license also grants access to the iBeacon's technical specification.</span>

## iBeacon class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/mbed-os/v5.13/mbed-os-api-doxy/classi_beacon.html)

## iBeacon example

[![View code](https://www.mbed.com/embed/?url=https://github.com/ARMmbed/mbed-os-example-ble/blob/master/BLE_Beacon/source)](https://github.com/ARMmbed/mbed-os-example-ble/blob/mbed-os-5.13/BLE_Beacon/source/main.cpp)

<span class="notes">**Note:** You can find more information at the [Apple iBeacon page](https://developer.apple.com/ibeacon/).</span>
# Connectivity overview
# AnalogIn

Use the AnalogIn API to read an external voltage applied to an analog input pin. `AnalogIn()` reads the voltage as a fraction of the system voltage. The value is a floating point from `0.0`(VSS) to `1.0`(VCC). For example, if you have a 3.3V system and the applied voltage is 1.65V, then `AnalogIn()` reads `0.5` as the value.

One of the most common types of analog to digital converters used in microcontrollers today is called the successive-approximation ADC. Successive-approximation is a popular choice in modern microcontrollers because of the fact that it is accurate and low-power and takes up a small amount of space inside of the microcontroller.

Another fairly common type of ADC is the flash ADC. Flash ADCs offer the fastest analog to digital solution. However, because of the way that flash ADCs are built, they use a lot of power and take up a lot of space, in that they use many components.

The resolution for an ADC is the smallest distinguishable change in analog input that causes the digital output to change. For example, a 12-bit ADC in a 3.3V system has 4,096 distinguishable outputs. Therefore, the resolution of a 12-bit ADC is 3.3/4096 = 0.81mV. In an Mbed Enabled system where the digital result from the analog input is in the range of 0.0 to 1.0, a change of 0.81mV in the analog input results in a change in the digital output of 1.0/4096 = 0.00024.

<span class="notes">**Note:** Only certain pins are capable of making these measurements, so check the pinmap of your board for compatible pins.</span>

## AnalogIn class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_analog_in.html)

## AnalogIn hello, world

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/AnalogIn_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/AnalogIn_HelloWorld/file/04e47b45f593/main.cpp)

## AnalogIn examples

### Example one

Control an R/C servo with analog input.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/AnalogIn_ex_1/)](https://os.mbed.com/teams/mbed_example/code/AnalogIn_ex_1/file/64493a867413/main.cpp)

### Example two

This example shows AnalogIn reading 16-bit normalized samples.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/AnalogIn_ex_2/)](https://os.mbed.com/teams/mbed_example/code/AnalogIn_ex_2/file/803d1b3eb85e/main.cpp)
# AnalogOut

Use the AnalogOut interface to set the output voltage of an analog output pin specified as a percentage or as an unsigned short. Mbed OS provides separate APIs to use percentage or range. Mbed OS supports a maximum resolution VCC/65,536 V, though the actual resolution depends on the hardware.

<span class="notes">**Note:** Not all pins are capable of being AnalogOut, so check the pinmap for your board.</span>

## AnalogOut class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_analog_out.html)

## AnalogOut hello, world

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/AnalogOut_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/AnalogOut_HelloWorld/file/f2c29bab3feb/main.cpp)

## AnalogOut example

Create a sine wave.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/AnalogOut_ex_1/)](https://os.mbed.com/teams/mbed_example/code/AnalogOut_ex_1/file/e758daa05e53/main.cpp)
# BusIn

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_bus_in.png)<span>BusIn class hierarchy</span></span>

With the BusIn API, you can combine number of DigitalIn pins to read them at once. This abstraction is useful for checking multiple inputs together as single interface instead of individual pins.

You can use any of the numbered Arm Mbed pins as a DigitalIn in the BusIn.

**Tips:**
* You can have up to 16 pins in a Bus.
* The order of pins in the constructor is the reverse order of the pins in the byte order. If you have `BusIn(a,b,c,d,e,f,g,h)` then the order of bits in the byte would be `hgfedcba` with `a` being bit 0, `b` being bit 1, `c` being bit 2 and so on.

## BusIn class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_bus_in.html)

## BusIn hello, world

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/BusIn_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/BusIn_HelloWorld/file/1e81bff34109/main.cpp)
# BusInOut

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_bus_in_out.png)<span>BusInOut class hierarchy</span></span>

Use the BusInOut interface as a bidirectional bus that supports up to 16 [DigitalInOut](digitalinout.html) pins that you can read and write as one value.

You can create a BusInOut object from any microcontroller pins that are capable of performing digital input and output functions. There is no restriction on the port or bus that the pins are physically connected to.

**Tip:**

The order of pins in the constructor is the reverse order of the pins in the byte order. If you have `BusInOut(a,b,c,d,e,f,g,h)`, then the order of bits in the byte is `hgfedcba` with `a` being bit 0, `b` being bit 1, `c` being bit 2 and so on.

## BusInOut class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_bus_in_out.html)

## BusInOut hello, world

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/BusInOut_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/BusInOut_HelloWorld/file/910f6ba3c4a3/main.cpp)

## Related content

- [DigitalInOut](digitalinout.html) API reference.
# BusOut

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_bus_out.png)<span>BusOut class hierarchy</span></span>

Use the BusOut interface to combine a number of [DigitalOut](digitalout.html) pins to write them at once. This API is useful for writing to multiple pins together as single interface instead of individual pins.

You can use any of the numbered Arm Mbed pins as a DigitalOut in the BusOut.

**Tips:**

- You can have up to 16 pins in a Bus.
- The order of pins in the constructor is the reverse order of the pins in the byte order. So if you have `BusOut(a,b,c,d,e,f,g,h)`, then the order of bits in the byte would be `hgfedcba` with `a` being bit 0, `b` being bit 1, `c` being bit 2 and so on.

## BusOut class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_bus_out.html)

## BusOut hello, world

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/BusOut_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/BusOut_HelloWorld/file/b07a5ecb7618/main.cpp)

## Related content

- [DigitalOut](digitalout.html) API reference.
# CAN

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_c_a_n.png)<span>CAN class hierarchy</span></span>

Controller-Area Network (CAN) is a bus standard that allows microcontrollers and devices to communicate with each other without going through a host computer.

<span class="notes">**Note:** You can use the CAN interface to write data words out of a CAN port. It will return the data received from another CAN device. You can configure the CAN clock frequency.</span>

## CAN class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_c_a_n.html)

## CAN hello, world

This example sends a counter from one CAN bus (can1) and listens for a packet on the other CAN bus (can2). Each bus controller should be connected to a CAN bus transceiver. These should be connected together at a CAN bus.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/CAN_ex_1/)](https://os.mbed.com/teams/mbed_example/code/CAN_ex_1/file/d6cbcdb04ada/main.cpp)
# DigitalIn

Use the DigitalIn interface to read the value of a digital input pin. The logic level is either 1 or 0.

You can use any of the numbered Arm Mbed pins can be used as a DigitalIn.

## DigitalIn class reference

API summary

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_digital_in.html)

## DigitalIn hello, world

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/DigitalIn_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/DigitalIn_HelloWorld/file/9377dcb1cef3/main.cpp)

## DigitalIn example

To handle an interrupt, see [InterruptIn](interruptin.html).

Examples of logical functions - boolean logic NOT, AND, OR, XOR:

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/DigitalIn_ex_1/)](https://os.mbed.com/teams/mbed_example/code/DigitalIn_ex_1/file/ad8683db322a/main.cpp)

## Related content

- [InterruptIn](interruptin.html) API reference.
# DigitalInOut

Use the DigitalInOut interface as a bidirectional digital pin:

* Read the value of a digital pin when set as an `input()`.
* Write the value when set as an `output()`.

You can use any of the numbered Arm Mbed pins as a DigitalInOut.

<span class="notes">**Note:** Some platforms have a time delay when switching between input and output.</span>

## DigitalInOut class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_digital_in_out.html)

## DigitalInOut hello, world

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/DigitalInOut_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/DigitalInOut_HelloWorld/file/5ed5244f3929/main.cpp)
# DigitalOut

Use the DigitalOut interface to configure and control a digital output pin by setting the pin to logic level 0 or 1.

## DigitalOut class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_digital_out.html)

## DigitalOut hello, world

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/DigitalOut_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/DigitalOut_HelloWorld/file/928e709317d9/main.cpp)
# Flash IAP

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_flash_i_a_p.png)<span>FlashIAP class hierarchy</span></span>

The flash in application programming provides an interface for access to MCU internal flash memory.

Flash IAP devices have different sized blocks for different operations. They allow you to read and program in defined-sized pages, but you must erase them in defined-sized sectors. The sector size must be a multiple of the page size. Sector sizes can differ within a device.

Flash IAP provides the following functionality:

- Read from a flash device.
- Program data to flash device pages.
- Erase flash device sectors.
- Get sector/flash or page sizes.
- Get the start address of the flash device.

Flash devices have some requirements and limitations based on the operation. Please read the documentation for each operation.

Be aware that Flash IAP might disable interrupts for a long time. This can affect the application latency.

This class is thread-safe.

## Flash IAP class reference

View the full C++ API:

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_flash_i_a_p.html)

## Flash IAP example

For an example that uses the `FlashIAP` driver, please see the [Mbed Stress Test](https://github.com/ARMmbed/mbed-stress-test).

# I2C

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_i2_c.png)<span>I2C class hierarchy</span></span>

The I2C interface provides I2C Master functionality. I2C is a two wire serial protocol that allows an I2C Master to exchange data with an I2C Slave. You can use it to communicate with I2C devices such as serial memories, sensors and other modules or integrated circuits.

The I2C protocol supports up to 127 devices per bus, and its default clock frequency is 100KHz.

<span class="notes">**Note:** Remember that you need a pull-up resistor on sda and scl. All drivers on the I2C bus are required to be open collector, and so it is necessary to use pull-up resistors on the two signals. A typical value for the pull-up resistors is around 2.2k ohms, connected between the pin and 3v3. </span>

## I2C class reference

<span class="notes">**Note:** The Arm Mbed API uses 8 bit addresses, so make sure to left-shift 7 bit addresses by 1 bit before passing them. </span>

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_i2_c.html)

## I2C hello, world

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/I2C_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/I2C_HelloWorld/file/afb2d7fd50ad/main.cpp)
# I2CSlave

Use I2C Slave to communicate with I2C Master.

Synchronization level: not protected.

## I2CSlave class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_i2_c_slave.html)

## I2CSlave example

Try this example to see how an I2C responder works.

```c++ TODO
#include <mbed.h>

#if !DEVICE_I2CSLAVE
  #error [NOT_SUPPORTED] I2C Slave is not supported
#endif

I2CSlave slave(p9, p10);

int main() {
   char buf[10];
   char msg[] = "Slave!";

   slave.address(0xA0);
   while (1) {
       int i = slave.receive();
       switch (i) {
           case I2CSlave::ReadAddressed:
               slave.write(msg, strlen(msg) + 1); // Includes null char
               break;
           case I2CSlave::WriteGeneral:
               slave.read(buf, 10);
               printf("Read G: %s\n", buf);
               break;
           case I2CSlave::WriteAddressed:
               slave.read(buf, 10);
               printf("Read A: %s\n", buf);
               break;
       }
       for(int i = 0; i < 10; i++) buf[i] = 0;    // Clear buffer
   }
}
```
# InterruptIn

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_interrupt_in.png)<span>InterruptIn class hierarchy</span></span>

Use the InterruptIn interface to trigger an event when a digital input pin changes. You can trigger interrupts on the rising edge (change from 0 to 1) or falling edge (change from 1 to 0) of signals.

## InterruptIn class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_interrupt_in.html)

**Warnings:**

* No blocking code in ISR: avoid any call to wait, infinite while loop or blocking calls in general.

* No printf, malloc or new in ISR: avoid any call to bulky library functions. In particular, certain library functions (such as printf, malloc and new) are non re-entrant, and their behavior could be corrupted when called from an ISR.

* For `printfs` from interrupt context, use [Event](event.html) instead.

## Related

To read an input, see [DigitalIn](digitalin.html).

## InterruptIn hello, world

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/InterruptIn_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/InterruptIn_HelloWorld/file/de061b559d35/main.cpp)

## InterruptIn example

Try the following example to count rising edges on a pin.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/InterruptIn_ex_1/)](https://os.mbed.com/teams/mbed_example/code/InterruptIn_ex_1/file/49002ccc54b5/main.cpp)

## Related content

- [Event](event.html) API reference.
- [DigitalIn](digitalin.html) API reference.
# LowPowerTicker

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_low_power_ticker.png)<span>LowPowerTicker class hierarchy</span></span>

The LowPowerTicker class has the same methods as the Ticker class but operates in deep sleep mode and has less resolution. Use the LowPowerTicker interface to set up a recurring interrupt when you only need millisecond accuracy; it calls a function repeatedly and at a specified rate. Because the LowPowerTicker class can operate in deep sleep mode, it does not block deep sleep when active.

You can create any number of LowPowerTicker objects, allowing multiple outstanding interrupts at the same time. The function can be a static function, a member function of a particular object or a Callback object.

## Warnings and notes

- No blocking code in ISR: avoid any calls to wait, infinite while loops or blocking calls in general.

- No printf, malloc or new in ISR: avoid any calls to bulky library functions. In particular, certain library functions (such as printf, malloc and new) are not re-entrant, and their behavior could be corrupted when called from an ISR.

## LowPowerTicker class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_low_power_ticker.html)

## LowPowerTicker example

Try this program to set up a LowPowerTicker to repeatedly invert an LED:

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/LowPowerTicker_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/LowPowerTicker_HelloWorld/file/3ef1e3fe0d3b/main.cpp)

## Related content

- [Office Hours video about low power, tickless and sleep](https://www.youtube.com/watch?v=OFfOlBaegdg).
# LowPowerTimeout

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_low_power_timeout.png)<span>LowPowerTimeout class hierarchy</span></span>

Use the LowPowerTimeout interface to set up an interrupt to call a function after a specified delay. You can create any number of LowPowerTimeout objects. This allows multiple outstanding interrupts at the same time. For more information about power management, please see our [power management APIs](power-management-sleep.html).

## Notes

- No blocking code in ISR: Avoid any call to wait, infinite while loop or blocking calls in general.
- No printf, malloc or new in ISR: Avoid any call to bulky library functions. In particular, certain library functions (such as printf, malloc and new) are not re-entrant, and their behavior could be corrupted when called from an ISR.

## LowPowerTimeout class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_low_power_timeout.html)

## LowPowerTimeout example

Set up a time out to invert an LED after a given time:

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/LowPowerTimeout-example/)](https://os.mbed.com/teams/mbed_example/code/LowPowerTimeout-example/file/28699dc8770e/main.cpp)

## Related content

- [Power management APIs](power-management-sleep.html).
- [Office Hours video about low power, tickless and sleep](https://youtu.be/OFfOlBaegdg?t=669).
# LowPowerTimer

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_low_power_timer.png)<span>LowPowerTimer class hierarchy</span></span>

LowPowerTimer inherits from the Timer Class. The timer in this case continues operating even in deep sleep mode. It relies on `lp_ticker`, which is the low power ticker.

You can use the LowPowerTimer interface to create, start, stop and read a timer for measuring small times (between microseconds and seconds). You can independently create, start and stop any number of LowPowerTimer objects. For more information about power management, please see our [power management APIs](power-management-sleep.html).

## LowPowerTimer class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_low_power_timer.html)

## LowPowerTimer example

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/LowPowerTimer-example/)](https://os.mbed.com/teams/mbed_example/code/LowPowerTimer-example/file/13760b19fc77/main.cpp)

## Related content

- [Power management APIs](power-management-sleep.html).
- [Office Hours video about low power, tickless and sleep](https://youtu.be/OFfOlBaegdg?t=669).
# MbedCRC

The MbedCRC Class provides support for Cyclic Redundancy Check (CRC) algorithms. MbedCRC is a template class with polynomial value and polynomial width as arguments.

You can use the `compute` API to calculate CRC for the selected polynomial. If data is available in parts, you must call the `compute_partial_start`, `compute_partial` and `compute_partial_stop` APIs in the proper order to get the correct CRC value. You can use the `get_polynomial` and `get_width` APIs to learn the current object's polynomial and width values.

ROM polynomial tables are for supported 8/16-bit CCITT, 16-bit IBM and 32-bit ANSI polynomials. By default, ROM tables are used for CRC computation. If ROM tables are not available, then CRC is computed at runtime bit by bit for all data input.

For platforms that support [hardware CRC](mbedcrc.html), the MbedCRC API replaces the software implementation of CRC to take advantage of the hardware acceleration the platform provides.

## MbedCRC class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_mbed_c_r_c.html)

## MbedCRC examples

### Example 1

Below is a CRC example to compute 32-bit CRC.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/CRC_example/)](https://os.mbed.com/teams/mbed_example/code/CRC_example/file/a9d9b5c4a32b/main.cpp)

### Example 2

Below is a 32-bit CRC example using `compute_partial` APIs.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/CRC_partial_example/)](https://os.mbed.com/teams/mbed_example/code/CRC_partial_example/file/d4c48b62da22/main.cpp)

### Example 3

Below is a CRC example for the SD driver.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/CRC_eample_sd/)](https://os.mbed.com/teams/mbed_example/code/CRC_eample_sd/file/97e3e51ca5d5/main.cpp)

## Related content

- [Hardware CRC](mbedcrc.html).
# PortIn

Use the PortIn interface to define which pins of a hardware GPIO port are set as an input and to read the value of those pins. The port name is device specific and defined in the device's `PortNames.h` file in the `mbed-os/targets` folder.

A bit mask defines which pins of the GPIO port are set as an input (`1b` = include, `0b` = ignore). The default mask value is `0xFFFFFFFF`, which sets all pins as an input.

The device-specific `PinNames.h` and the respective datasheet or reference manual define the pins associated with a GPIO port.

<span class="notes">**Note:** You can combine pins from different GPIO ports using the [BusIn](busin.html) interface. Use [PortOut](portout.html) to define which GPIO pins are to be used as digital output.</span>

## PortIn class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_port_in.html)

## PortIn hello, world

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/users/mbed_official/code/PortIn_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/PortIn_HelloWorld/file/e78266d48649/main.cpp)

## Related content

- [BusIn](busin.html) API reference.
- [PortOut](portout.html) API reference.
# PortInOut

Use the PortInOut interface to read and write an underlying GPIO port as one value. This is much faster than [BusInOut](businout.html) because you can write a port all at once, but it is much less flexible because you are constrained by the port and bit layout of the underlying GPIO ports.

A mask can be supplied so you only use certain parts of a port, allowing other bits to be used for other interfaces.

## PortInOut class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_port_in_out.html)

## PortInOut hello, world

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/users/mbed_official/code/PortInOut_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/PortInOut_HelloWorld/file/3f1944b9de6a/main.cpp)

## Related content

- [BusInOut](businout.html) API reference.
# PortOut

Use the PortOut interface to define which pins of a hardware GPIO port are set as an output and to write those pins. The port name is device specific and defined in the device's `PortNames.h` file in the `mbed-os/targets` folder.

A bit mask defines which pins of the GPIO port are set as an output (`1b` = include, `0b` = ignore). The default mask value is `0xFFFFFFFF` which sets all pins as an output.

The device-specific `PinNames.h` and the respective datasheet or reference manual define the pins associated with a GPIO port.

<span class="notes">**Note:** You can combine pins from different GPIO ports using the [BusOut](busout.html) interface. Use [PortIn](portin.html) to define which GPIO pins are to be used as digital input.</span>

## PortOut class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_port_out.html)

## PortOut hello, world

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/PortOut_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/PortOut_HelloWorld/file/e4e6fab14d21/main.cpp)

## Related content

- [BusOut](busout.html) API reference.
- [PortIn](portin.html) API reference.
# PwmOut

Use the PwmOut interface to control the frequency and duty cycle of a PWM signal.

**Tips:**

- Set the cycle time first, and then set the duty cycle using either a relative time period via the write() function or an absolute time period using the pulsewidth() function.
- The default period is 0.020s, and the default pulse width is 0.

## PwmOut class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/mbed-os/v5.13/mbed-os-api-doxy/classmbed_1_1_pwm_out.html)

## PwmOut hello, world

This code example uses the default period of 0.020s and ramps the duty cycle from 0% to 100% in increments of 10%.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/PwmOut_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/PwmOut_HelloWorld/file/10bf740dc758/main.cpp)

## PwmOut code examples

### Example one

This code example sets the period in seconds and the duty cycle as a percentage of the period in floating point (range: 0 to 1). The effect of this code snippet will be to blink LED2 over a four-second cycle, 50% on, for a pattern of two seconds on, two seconds off.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/PwmOut_ex_1/)](https://os.mbed.com/teams/mbed_example/code/PwmOut_ex_1/file/3b6d08ebe2b0/main.cpp)

### Example two

The following example does the same thing, but instead of specifying the duty cycle as a relative percentage of the period, it specifies it as an absolute value in seconds. In this case we have a four-second period and a two-second duty cycle, meaning the LED will be on for two seconds and off for two seconds.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/PwmOut_ex_2/)](https://os.mbed.com/teams/mbed_example/code/PwmOut_ex_2/file/cab93cb2f242/main.cpp)
# QuadSPI (QSPI)

## QSPI class hierarchy

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_q_s_p_i.png)</span><span>QSPI class hierarchy</span>

The QSPI driver in Mbed OS provides functionality to configure and access QSPI devices connected over a QuadSPI interface.

The QSPI protocol provides a serial communication interface on four data lines between the host and the device. It uses up to six lines in total: one line for chip select, one line for clock and four lines for data in/out. You can use this interface for communication with QSPI devices, such as Flash memory, display devices and other types of devices providing QuadSPI communication support. You can also configure the QSPI interface to work in Single-SPI (traditional SPI) mode or Dual-SPI mode.

The default configuration for the QSPI interface is 1 MHz, Single-SPI, Mode 0.

<span class="images">![](../../images/quadspi.png)</span>

The above diagram shows an example hardware configuration of a Flash memory connected over a QSPI interface.

For more information, please review the related content.

## QuadSPI class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_q_s_p_i.html)

## QuadSPI example

 [![View Example](https://www.mbed.com/embed/?url=https://github.com/ARMmbed/mbed-os-examples-docs_only/blob/master/QSPI)](https://github.com/ARMmbed/mbed-os-examples-docs_only/blob/master/QSPI/main.cpp)

## Related content

- [QSPI flash block device](https://github.com/ARMmbed/qspif-blockdevice).
- [STMicroelectronics Quad-SPI documentation](https://www.st.com/content/ccc/resource/technical/document/application_note/group0/b0/7e/46/a8/5e/c1/48/01/DM00227538/files/DM00227538.pdf/jcr:content/translations/en.DM00227538.pdf).
- [Macronix MX25R6435F flash memory with Quad-SPI](http://www.macronix.com/Lists/Datasheet/Attachments/6270/MX25R6435F,%20Wide%20Range,%2064Mb,%20v1.4.pdf).
- [Nordic Quad-SPI support in NRF52840](http://infocenter.nordicsemi.com/pdf/nRF52840_OPS_v0.5.pdf).
# RawSerial

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_raw_serial.png)<span>RawSerial class hierarchy</span></span>

The RawSerial class provides UART functionality without the use of Stream's print and scan functions the way the Serial class does. RawSerial does not retarget the standard library print and scan functions. Instead, RawSerial reimplements the print and scan functions to use each target's underlying serial communication functions. See the porting guide for [target serial support](../porting/serial-port.html). This makes RawSerial suitable for use in interrupt handlers with the RTOS.

Serial channels have the following configurable parameters in the constructor:

  - _TX and RX Pin_ - The physical serial transmit and receive pins. You can specify a TX or RX pin as Not Connected (NC) to get Simplex communication, or specify both to get Full Duplex communication.
  - _Baud Rate_ - This setting is an optional constructor parameter. Standard baud rates range from a few hundred bits per second to megabits per second. The default baud rate for a serial connection on the microcontroller is 9600 baud. This setting may also be configured at run time.

The following parameters can be configured at run time in the RawSerial object. You can view more information about the configurable settings and functions in the class reference.

  - _Baud Rate_ - Standard baud rates range from a few hundred bits per second to megabits per second. The default setting for a serial connection on the microcontroller is 9600 baud.
  - _Data length_ - Transferred data can be either 7 or 8 bits long. The default setting for a serial connection on the microcontroller is 8 bits.
  - _Parity_ - You can add an optional parity bit. The RawSerial object automatically sets the parity bit to make the number of 1s in the data either odd or even. Parity settings are *Odd*, *Even* or *None*. The default setting for a serial connection on the microcontroller is None.
  - _Stop Bits_ - After the transmission of data and parity bits, the RawSerial object inserts one or two stop bits to "frame" the data. The default setting for a serial connection on the microcontroller is one stop bit.

The default settings for the microcontroller are described as _9600-8-N-1_, a common notation for serial port settings.

## RawSerial class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_raw_serial.html)

<span class="notes">**Note**: On a Windows machine, you need to install a USB serial driver. See [Windows serial configuration](../tutorials/serial-communication.html#windows-serial-driver).</span>

## RawSerial hello, world

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/RawSerial_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/RawSerial_HelloWorld/file/112a40a5991a/main.cpp)

## RawSerial examples

### Example one

Write a message to a device at a baud rate of 19200.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/RawSerial_ex_1/)](https://os.mbed.com/teams/mbed_example/code/RawSerial_ex_1/file/6a0d9cb21969/main.cpp)

### Example two

Attach a function to call during the generation of serial interrupts. This function defaults to interrupt on an RX pin.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/RawSerial_ex_2/)](https://os.mbed.com/teams/mbed_example/code/RawSerial_ex_2/file/3ad999bfc3c4/main.cpp)

### Mbed OS example

Common use cases for RawSerial are IRQ heavy UART operations, such as the [ATParser](https://github.com/ARMmbed/ATParser/blob/3209400df676cbf0183a5894f648c71727602d30/BufferedSerial/BufferedSerial.cpp#L29) in the ESP8266 driver. This driver uses UART on user supplied pins to communicate with the offchip ESP8266 module.
# SPI

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_s_p_i.png)<span>SPI class hierarchy</span></span>

The SPI Interface provides a Serial Peripheral Interface Master.

You can use this interface for communication with SPI slave devices, such as FLASH memory, LCD screens and other modules or integrated circuits.

## Interface

<span class="images">![](../../images/pin_out.png)<span>A pinout map.</span></span>

The default settings of the SPI interface are 1MHz, 8-bit, Mode 0.

You can use the SPI interface to write data words out of the SPI port, returning the data received back from the SPI slave. You can also configure the SPI clock frequency and format. The format is set to data word length 8 to 16 bits, and the mode as per the table below:

Mode |  Polarity |  Phase
---|---|---
0 | 0 | 0
1 | 0 | 1
2 | 1 | 0
3 | 1 | 1

The SPI master generates a clock to synchronously drive a serial bit stream slave. The slave returns a bit stream, also synchronous to the clock. To communicate with multiple slave devices connected over the same SPI peripheral, you must use multiple SPI objects, one for each slave, but instantiate them with a different Slave select (SSEL) and configuration corresponding to each slave. Note that the SPI object automatically configures the SPI peripheral with the current object's configuration when the application code invokes the interfaces on the SPI object.

## SPI class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_s_p_i.html)

## SPI hello, world

The following example uses the WHOAMI register. The WHOAMI register is an ID register of the slave device. In other words, it's just an example that you can write to a slave's register. In this example, Mbed OS acts as the SPI master, and DigitalOut acts as the slave chip select (cs).

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/SPI_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/SPI_HelloWorld/file/3789302f33bc/main.cpp)
# SPISlave

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_s_p_i_slave.png)<span>SPISlave class hierarchy</span></span>

Use the SPISlave class to communicate with a SPI master device.

The default format is set to 8 bits, mode 0 and a clock frequency of 1MHz. Synchronization level: not protected.

## SPISlave class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_s_p_i_slave.html)

## SPISlave example

Reply to a SPI master as slave:

```c++
#include "mbed.h"

SPISlave device(D9, D11, D12, D13); // mosi, miso, sclk, ssel

int main() {
   device.reply(0x00);              // Prime SPI with first reply
   while(1) {
       if(device.receive()) {
           int v = device.read();   // Read byte from master
           v = (v + 1) % 0x100;     // Add one to it, modulo 256
           device.reply(v);         // Make this the next reply
       }
   }
}
```
# Serial

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_serial.png)<span>Serial class hierarchy</span></span>

The [Serial](../introduction/glossary.html) interface provides UART functionality. The serial link has two unidirectional channels, one for sending and one for receiving. The link is asynchronous, and so both ends of the serial link must be configured to use the same settings.

One of the serial connections uses the Arm Mbed USB port, allowing you to easily communicate with your host PC.

## Serial class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_serial.html)

<span class="notes">**Note**: On a Windows machine, you will need to install a USB serial driver. See [Windows serial configuration](../tutorials/windows-serial-driver.html).</span>

Serial channels have the following configurable parameters:

  - _TX and RX Pin_ - The physical serial transmit and receive pins. You can specify a TX or RX pin as Not Connected (NC) to get Simplex communication, or specify both to get Full Duplex communication.
  - _Baud Rate_ - Standard baud rates range from a few hundred bits per second to megabits per second. The default setting for a serial connection on the microcontroller is 9600 baud.
  - _Data length_ - Transferred data can be either 7 or 8 bits long. The default setting for a serial connection on the microcontroller is 8 bits.
  - _Parity_ - You can add an optional parity bit. The Serial object automatically sets the parity bit to make the number of 1s in the data either odd or even. Parity settings are *Odd*, *Even* or *None*. The default setting for a serial connection on the microcontroller is None.
  - _Stop Bits_ - After the transmission of data and parity bits, the Serial object inserts one or two stop bits to "frame" the data. The default setting for a serial connection on the microcontroller is one stop bit.

The default settings for the microcontroller are described as _9600-8-N-1_, a common notation for serial port settings.

## Serial hello, world

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/Serial_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/Serial_HelloWorld/file/18e08b8afd16/main.cpp)

## Serial examples

### Example one

Write a message to a device at a baud rate of 19200.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/Serial_ex_1/)](https://os.mbed.com/teams/mbed_example/code/Serial_ex_1/file/40997137fc4d/main.cpp)

### Example two

Provide a serial pass-through between the PC and an external UART.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/Serial_ex_2/)](https://os.mbed.com/teams/mbed_example/code/Serial_ex_2/file/4cf190502c9e/main.cpp)

## Related content

- [Serial](../introduction/glossary.html) glossary entry.
- [Windows serial configuration](../tutorials/windows-serial-driver.html).
# Ticker

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_ticker.png)<span>Ticker class hierarchy</span></span>

Use the Ticker interface to set up a recurring interrupt; it calls a function repeatedly and at a specified rate.

You can create any number of Ticker objects, allowing multiple outstanding interrupts at the same time. The function can be a static function, a member function of a particular object or a Callback object.

## Warnings and notes

- No blocking code in ISR: avoid any call to wait, infinite while loop or blocking calls in general.

- No printf, malloc or new in ISR: avoid any call to bulky library functions. In particular, certain library functions (such as printf, malloc and new) are not re-entrant, and their behavior could be corrupted when called from an ISR.

- While an event is attached to a Ticker, deep sleep is blocked to maintain accurate timing. If you don't need microsecond precision, consider using the LowPowerTicker class instead because that does not block deep sleep mode.

## Ticker class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_ticker.html)

## Ticker hello, world

Try this program to set up a Ticker to repeatedly invert an LED:

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/Ticker_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/Ticker_HelloWorld/file/1b2dcb20aad0/main.cpp)

## Ticker examples

Use this example to attach a member function to a ticker:

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/Ticker_Example/)](https://os.mbed.com/teams/mbed_example/code/Ticker_Example/file/982ebb531653/main.cpp)

## Related content

- [Application flow control tutorial](../tutorials/application-flow-control.html).
- [Office Hours video about low power, tickless and sleep](https://youtu.be/OFfOlBaegdg?t=669).
# Timeout

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_timeout.png)<span>Timeout class hierarchy</span></span>

Use the Timeout interface to set up an interrupt to call a function after a specified delay.

You can create any number of Timeout objects, allowing multiple outstanding interrupts at the same time.

## Warnings and notes

* No blocking code in ISR: avoid any call to wait, infinite while loop or blocking calls in general.

* No printf, malloc or new in ISR: Avoid any call to bulky library functions. In particular, certain library functions (such as printf, malloc and new) are not re-entrant, and their behavior could be corrupted when called from an ISR.

* While a Timeout is running, deep sleep is blocked to maintain accurate timing. If you don't need microsecond precision, consider using the LowPowerTimeout class instead because this does not block deep sleep mode.

## Timeout class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_timeout.html)

## Timeout hello, world

Set up a Timeout to invert an LED after a given timeout:

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/Timeout_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/Timeout_HelloWorld/file/5692f58a7971/main.cpp)

## Timeout example

Try this example to attach a member function:

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/Timeout_Example/)](https://os.mbed.com/teams/mbed_example/code/Timeout_Example/file/517d40d18f1c/main.cpp)

## Related content

- [Office Hours video about low power, tickless and sleep](https://youtu.be/OFfOlBaegdg?t=669).
# Timer

<span class="images">![](../../images/classmbed_1_1_timer.png)<span>Timer class hierarchy</span></span>

Use the Timer interface to create, start, stop and read a timer for measuring precise times (better than millisecond precision).

You can independently create, start and stop any number of Timer objects.

## Warnings and notes

- Timers are based on 64-bit unsigned microsecond counters, but for backward compatibility, the `read_ms()` and `read_us()` methods only return 32-bit signed integers. This limits their range before wrapping to 49 days and 35 minutes respectively. Use `read_high_resolution_us()` to access the full range of over 500,000 years.
- While a Timer is running, deep sleep is blocked to maintain accurate timing. If you don't need microsecond precision, consider using the LowPowerTimer class instead because this does not block deep sleep mode.

## Timer class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/_timer_8h_source.html)

## Timer hello, world

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/Timer_HelloWorld/)](https://os.mbed.com/teams/mbed_example/code/Timer_HelloWorld/file/0d21eea06da7/main.cpp)

## Related content

- [Office Hours video about low power, tickless and sleep](https://youtu.be/OFfOlBaegdg?t=669).
# Watchdog

[Add description here.]

## Watchdog class reference

[Add class reference here. Ask your editor for help if you've never done this before.]

## Watchdog example

[Add example here.]
# Drivers overview

Drivers provide access to general purpose microcontroller hardware. Drivers typically access a microcontroller's hardware peripherals directly, and may form the lowest lever of a protocol or network stack.

The Mbed OS driver APIs include analog and digital inputs and outputs on development boards, as well as digital interfaces, which allow your board to interface with a computer or external devices. With these drivers, you can read or set the voltage of analog pins, control digital pins individually or grouped into a bus and trigger an event when more data is available on the bus. You can also control the frequency and mark to space ratio, or duty cycle, of a Pulse Width Modulated (PWM) digital output.

## Blocking nature

By default, all Mbed OS driver APIs are blocking. In the drivers, blocking APIs cause the current thread to wait until the hardware operation completes. Blocking APIs simplify control flow, allow for linearly structured programs and make debugging intuitive. We suggest using blocking APIs as a starting point. You should only consider more complex APIs if the blocking APIs do not satisfy your requirements.

Mbed OS is built around an RTOS, and to complement this, the drivers are thread safe. This means that if you use multiple drivers in a blocking manner, as long as the drivers are in separate threads, their operations can still be carried out in parallel. When a driver blocks a thread, the RTOS either switches to any nonblocked threads or sleeps. This means that in most cases, an application using blocking APIs has the same advantages as one using nonblocking APIs.

In some cases, the drivers provide nonblocking APIs. These APIs configure hardware to run in the background of the processor, without blocking a thread. Nonblocking drivers signal through the attach function once the background operation is complete.

## Attaching callbacks to drivers

In Mbed OS, the standard API for asynchronous events is the attach function. You can use the attach function to attach a callback function. Drivers call the attached callback function during specific events. You can use this to learn when the state of a nonblocking operation changes or whether other asynchronous events occur.

For example, you can attach a callback function on a [Serial](serial.html) object, which the Serial object calls when the serial line receives a packet on the RX line.

One important thing to note is that when you attach callbacks with this function, the driver calls them in interrupt context. Interrupt context runs at a higher priority than any thread, which means that any code called from the attach callback must be interrupt safe. This excludes any blocking APIs such as blocking drivers, malloc, and mutexes. Or you risk preventing other high-priority interrupts from running, which may break other parts of the OS.

When you need to call code that’s not interrupt safe from interrupt context, you must first defer from the interrupt context to a thread. The easiest way to defer to a thread is to signal a waiting thread through a [Semaphore](semaphore.html). In more complex use cases, you can use an [EventQueue](eventqueue.html) to manage multiple events at once.
<h1 id="loraradio-api">LoRa radio driver</h1>

`LoRaRadio` is a pure virtual class that defines APIs for a LoRa radio driver.

An implementation of this class is passed to the Arm Mbed LoRaWAN stack. Please see existing [Mbed OS supported drivers](https://github.com/ARMmbed/mbed-semtech-lora-rf-drivers) for more information.

To configure this class, please see the [LoRa configuration documentation](../reference/lorawan-configuration.html).

## LoRaRadio class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_lo_ra_radio.html)

## LoRaRadio example

[![View code](https://www.mbed.com/embed/?url=https://github.com/ARMmbed/mbed-os-example-lorawan)](https://github.com/ARMmbed/mbed-os-example-lorawan/blob/mbed-os-5.13/main.cpp)

## Related content

- [LoRa architecture](../reference/lora-tech.html).
- [LoRa configuration documentation](../reference/lorawan-configuration.html).
<h1 id="lorawan-api">LoRaWAN network interface</h1>

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_lo_ra_w_a_n_interface.png)<span>
LoRaWANInterface class hierarchy</span></span>

The [LoRaWANInterface](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_lo_ra_w_a_n_interface.html) provides a C++ API for connecting to the internet over a LoRa network. This subsection explains the `LoRaWANInterface` API reference and then presents an example that you can directly import to the Arm Mbed Online Compiler.

To configure this class, please see the [LoRa configuration documentation](../reference/lorawan-configuration.html).

## LoRaWANInterface class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_lo_ra_w_a_n_interface.html)

## LoRaWAN example

Please visit our Arm Mbed Online Compiler example, and follow the instructions in the `README.md`.

[![View code](https://www.mbed.com/embed/?url=https://github.com/ARMmbed/mbed-os-example-lorawan)](https://github.com/ARMmbed/mbed-os-example-lorawan/blob/mbed-os-5.13/main.cpp)

## Related content

- [LoRa configuration documentation](../reference/lorawan-configuration.html).
- [LoRa architecture](../reference/lora-tech.html).
- End-to-end [LoRa on Arm Mbed tutorial](../tutorials/LoRa-tutorial.html).
- [Blog post: Adding a LoRaWAN stack to Mbed OS 5.8](https://os.mbed.com/blog/entry/Adding-a-LoRaWAN-stack-to-Mbed-OS-58/).
# LoRaWAN overview

LoRaWAN is a technology designed for low-power battery powered devices. These devices operate in an unlicensed spectrum, creating high density wide-area networks.

Arm Mbed OS provides a native network stack for LoRaWAN, which can run on any Mbed Enabled device with a LoRa radio onboard.

The [LoRaWANInterface](lorawan-api.html) provides a C++ API for connecting to the internet over a LoRa network.

## Usage

To bring up the Mbed LoRaWAN stack, consider the following progression:

1) An [EventQueue](eventqueue.html) object:

```cpp TODO
// construct an event queue
EventQueue ev_queue(NUM_EVENTS * EVENTS_EVENT_SIZE);
```

2) A [LoRaRadio](lorawan-api.html) object:

```CPP TODO
// construct a LoRadio object
SX1272_LoRaRadio radio(PIN_NAMES ... );
```

3) Instantiate `LoRaWANInterface`, and pass `LoRaRadio` object:

```CPP TODO
LoRaWANInterface lorawan(radio) ;
```

4) Initialize mac layer and pass `EventQueue` object:

```CPP TODO
lorawan.initialize(&ev_queue);
```

5) Set up the event callback:

```cpp TODO
lorawan_app_callbacks_t callbacks
callbacks.events = mbed::callback(YOUR_EVENT_HANDLER);
lorawan.add_app_callbacks(&callbacks);
```

6) Add network credentials (security keys) and any configurations:

```CPP TODO
lorawan_connect_t connection;

connection.connect_type = LORAWAN_CONNECTION_OTAA;
connection.connection_u.otaa.app_eui = YOUR_APP_EUI_KEY;
connection.connection_u.otaa.dev_eui = YOUR_DEV_EUI_KEY;
connection.connection_u.otaa.app_key = YOUR_APP_KEY;
connection.connection_u.otaa.nb_trials = MBED_CONF_LORA_NB_TRIALS;

lorawan.connect(connection);
```

Owing to the fact that most of the LoRaWAN devices are simple telemetry devices, the stack and its operation need to be as simple as possible. That's why the Mbed LoRaWAN stack is event driven.

### Network events and callbacks

Here is the list of possible events that you can post from the stack to the application:

| Event    | Description
| --------------- | ------------- |
| `CONNECTED` | When the connection is complete |
| `DISCONNECTED` | When the protocol is shut down in response to disconnect() |
| `TX_DONE` | When a packet is transmitted |
| `TX_TIMEOUT` | When the stack is unable to send packet in TX window |
| `TX_ERROR` | A general TX error |
| `TX_CRYPTO_ERROR` | If MIC fails, or any other crypto related error |
| `TX_SCHEDULING_ERROR` | When the stack is unable to schedule a packet |
| `TX_TIMEOUT` | When the stack is unable to send a packet in TX window  |
| `RX_DONE` | When a packet is received |
| `RX_ERROR` | A general RX error |

The application must attach an event handler to the stack. The `LoRaWANInterface` provides an API to attach various callbacks to the stacks. One such callback is the event handler callback.

### Application callbacks

The Mbed LoRaWAN stack currently maps 3 different callbacks:

| Callback type   | Description
| --------------- | ------------- |
| `Event callback` | Mandatory, Direction: from stack to application |
| `Link check response callback` |Optional, Direction: from stack to application |
| `Battery level callabck` | Optional, Direction: from application to stack |

#### Event handler

An example of attaching your event handler to the stack:

```CPP TODO

void your_event_handler(lorawan_event_t event)
{
    switch (event) {
        case CONNECTED:
        //do something
            break;
        case DISCONNECTED:
            break;
	....
	....
    }
}
lorawan_app_callbacks_t callbacks;

callbacks.events = mbed::callback(your_event_handler);
//lorawan is the LoRaWANInterface object
lorawan.add_app_callbacks(&callbacks);
```

#### Link check response handler

Link check request is a MAC command defined by the LoRaWAN specification. To receive the response of this MAC command, set the `link_check_resp` callback.

```CPP TODO
void your_link_check_response(uint8_t demod_margin, uint8_t num_gw)
{
	//demod_margin is the demodulation margin
	// num_gw represents the number of gateways involved in the path
}

callbacks.link_check_resp = mbed::callback(your_link_check_response);
lorawan.add_app_callbacks(&callbacks);

```

#### Battery level handler

The battery level callback is different from others. The direction of this callback is from the application to the stack. In other words, it provides information to the stack. The application is reponsible for letting the stack know about the current battery level.

```CPP TODO
uint8_t your_battery_level()
{
	return battery_level;
}

callbacks.battery_level = mbed::callback(your_battery_level);
lorawan.add_app_callbacks(&callbacks);
```

#### Error codes

All operations on `LoRaWANInterface` return an error code `lorawan_status_t` that reflects success or failure of the operation.

Below is the list of error codes and their description.

| Error code    | Value | Description |
| --------------- | ------------- | ----------|
| `LORAWAN_STATUS_OK`| 0 | Service done successfully |
| `LORAWAN_STATUS_BUSY`| -1000|  Stack busy |
|`LORAWAN_STATUS_WOULD_BLOCK`| -1001 | Stack cannot send at the moment or have nothing to read |
| `LORAWAN_STATUS_SERVICE_UNKNOWN`| -1002 | Unknown service request |
| `LORAWAN_STATUS_PARAMETER_INVALID`| -1003 | Invalid parameter  |
| `LORAWAN_STATUS_FREQUENCY_INVALID`| -1004| Invalid frequency  |
| `LORAWAN_STATUS_DATARATE_INVALID` | -1005| Invalid frequency and datarate  |
| `LORAWAN_STATUS_FREQ_AND_DR_INVALID`| -1006| When stack was unable to send packet in TX window  |
|`LORAWAN_STATUS_NO_NETWORK_JOINED`| -1009 | Device is not part of a network yet (Applicable only for OTAA) |
|`LORAWAN_STATUS_LENGTH_ERROR`| -1010 | Payload length error |
| `LORAWAN_STATUS_DEVICE_OFF`| -1011 | The device is off, in other words, disconnected state |
| `LORAWAN_STATUS_NOT_INITIALIZED`| -1012| Stack not initialized  |
| `LORAWAN_STATUS_UNSUPPORTED`| -1013| Unsupported service |
| `LORAWAN_STATUS_CRYPTO_FAIL`| -1014| Crypto failure  |
|`LORAWAN_STATUS_PORT_INVALID`| -1015 | Invalid port |
|`LORAWAN_STATUS_CONNECT_IN_PROGRESS`| -1016 | Connection in progress (application should wait for CONNECT event) |
|`LORAWAN_STATUS_NO_ACTIVE_SESSIONS`| -1017 | No active session in progress |
|`LORAWAN_STATUS_IDLE`| -1018 | Stack idle at the moment |
|`LORAWAN_STATUS_DUTYCYCLE_RESTRICTED`| -1020 | Transmission will be delayed because of duty cycling |
|`LORAWAN_STATUS_NO_CHANNEL_FOUND`| -1021 | No channel is enabled at the moment |
|`LORAWAN_STATUS_NO_FREE_CHANNEL_FOUND`| -1022 | All channels marked used, cannot find a free channel at the moment |
|`LORAWAN_STATUS_METADATA_NOT_AVAILABLE`| -1023 | Metadata is stale, cannot be made available as its not relevant |

You can find the API documentation for the LoRaWANInterface and LoRaRadio classes below:

- [LoRaWANInterface API docs](lorawan.html): The class that provides APIs for LoRaWAN network stack.
- [LoRaRadio API docs](loraradio-api.html): The class that provides pure virtual APIs to implement a LoRa radio driver.
<h1 id="cellular-api">Cellular API</h1>

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_cellular_interface.png)<span>CellularInterface class hierarchy</span></span>

The [CellularInterface](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_cellular_interface.html) class provides a C++ API for connecting to the internet over a Cellular device.

## Getting started

1. Choose an [Mbed board that supports cellular](https://os.mbed.com/platforms/?mbed-enabled=15&connectivity=1), such as the [UBLOX-C027](https://os.mbed.com/platforms/u-blox-C027/) or [MTS-DRAGONFLY](https://os.mbed.com/platforms/MTS-Dragonfly/).

1. Clone [`mbed-os-example-cellular`](https://os.mbed.com/teams/mbed-os-examples/code/mbed-os-example-cellular/). Follow the instructions in the repository.

    1. Compile the code.
    1. Flash the board.

   You see output similar to the excerpt below:

```
mbed-os-example-cellular
Establishing connection ......

Connection Established.
TCP: connected with echo.mbedcloudtesting.com server
TCP: Sent 4 Bytes to echo.mbedcloudtesting.com
Received from echo server 4 Bytes


Success. Exiting
```

## Basic working principles

You can use and extend a cellular interface in various different ways. For example,

- Using AT commands to control sockets in an existing IP stack built into the cellular modem.

<span class="images">![](../../images/Cell_AT.png)</span>

- Using a PPP (Point-to-Point Protocol) pipe to pass IP packets between an Mbed OS supported IP stack and cellular modem device.

<span class="images">![](../../images/Cell_PPP.png)</span>

[`mbed-os-example-cellular`](https://os.mbed.com/teams/mbed-os-examples/code/mbed-os-example-cellular/) uses PPP or AT mode depending on the modem. We can summarize this particular design as follows:

- It uses an external IP stack, such as LWIP, or on-chip network stacks such as when the modem does not support PPP.
- The easy cellular connection uses standard 3GPP AT 27.007 AT commands to set up the cellular modem and to register to the network.
- After registration, the driver opens a PPP pipe using LWIP with the cellular modem and connects to the internet. If AT only mode is in use, then modem-specific AT commands are used for socket data control.

## CellularInterface class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_cellular_interface.html)

## Usage

To bring up the network interface:

1. Instantiate an implementation of the CellularInterface class.
1. Call the `connect(pincode, apn)` function with a PIN code for your SIM card and an APN for your network.
1. Once connected, you can use Mbed OS [network sockets](network-socket.html) as usual.

## Cellular example: connection establishment

This example establishes connection with the cellular network using Mbed OS CellularInterface.

[![View code](https://www.mbed.com/embed/?url=https://github.com/ARMmbed/mbed-os-example-cellular)](https://github.com/ARMmbed/mbed-os-example-cellular/blob/mbed-os-5.13/main.cpp)

## Related content

- [Network socket](network-socket.html) API reference overview.
- [Cellular overview](../reference/cellular-networking.html) describes cellular architecture and its usage in more detail.
- [Cellular configuration documentation](../reference/configuration-connectivity.html).
# Ethernet

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_eth_interface.png)<span>EthInterface class hierarchy</span></span>

The `EthInterface` provides a C++ API for connecting to the internet over Ethernet.
By default, this class does not require any configuration. It is able to pick up the default
Ethernet driver for the target and select correct network stack.


## Usage

To statically initialize the driver, create an object without passing any parameters:

```cpp TODO
EthernetInterface eth;
```

Then, if the default configuration is enough, bring up the interface:

```cpp TODO
nsapi_error_t status = eth.connect();
```

Now, the interface is ready to be used for [network sockets](network-socket.html).

```cpp TODO
// Open a TCP socket
TCPSocket socket;
socket.open(&eth);

// Open a UDP socket
UDPSocket socket;
socket.open(&eth);
```

## Configuration

For EthernetInterface, there are two possible configurations:

- Use DHCP for network addressing. This is the default.
- Use statically configured IP addresses.

Refer to the API below for how to set the IP addresses by calling the `set_network()` function.

## Troubleshooting information

Network interface `connect` failure causes:

- `NSAPI_ERROR_NO_CONNECTION` indicates that the Ethernet link up has failed. Check that the Ethernet connection is working.
- `NSAPI_ERROR_DHCP_FAILURE` indicates that acquiring the IP address has failed. Check that the IP address configuration service is working.

## EthInterface class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_eth_interface.html)

## EthInterface example

Here is an example of an HTTP client program. The program brings up Ethernet as the underlying network interface and uses it to perform an HTTP transaction over a TCPSocket:

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/TCPSocket_Example/)](https://os.mbed.com/teams/mbed_example/code/TCPSocket_Example/file/50f1485931f1/main.cpp)

## Related content

- [Network socket](network-socket.html) API reference overview.
- [Ethernet architecture](../reference/ethernet-technology.html).
<h1 id="mesh-api">Mesh</h1>

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_mesh_interface.png)<span>MeshInterface class hierarchy</span></span>

The Arm Mbed Mesh API allows the application to use the IPv6 mesh network topologies through the [Nanostack](../reference/nanostack-introduction-tech.html) networking stack.

Mbed OS provides three types of IPv6-based mesh networks:

- [Wi-SUN](../reference/wisun-tech.html), following the specification from the Wi-SUN alliance.
- [Thread](../reference/thread-tech.html), following the specification from Thread Group.
- [6LoWPAN-ND](../reference/6LoWPAN-ND-tech.html), loosely following the Zigbee-IP specification.

The application can use the `LoWPANNDInterface`, `WisunInterface` or `ThreadInterface` object to connect to the mesh network. When successfully connected, the application can use the Mbed [C++ socket APIs](network-socket.html) to create a socket to start communication with a remote peer. You can use the [Network status API](network-status.html) to monitor changes in the network status.

You can configure the mesh interface by providing values in `mbed_app.json`, as the [mesh configuration](../reference/configuration-mesh.html) section documents.

## Mesh class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_mesh_interface.html)

## Mesh example

The following code snippet illustrates how you can use the MeshInterface API:

```c++
#include "mbed.h"

int main(void)
{
    MeshInterface *mesh = MeshInterface::get_default_instance();

    int status = mesh->connect();
    if (status) {
        printf("Connection failed! error %d\n", status);
        return status;
    }

    printf("Connected!\n");

    UDPSocket sock;
    status = sock.open(mesh);
    if (status) {
        printf("Failed to open socket, error %d\n", status);
    }

    // Now the interface is connected, and I can communicate with Sockets
}

```

## Related content

- [Mesh tutorial](../tutorials/mesh-tutorial.html) to start using mesh technology.
- [Light control tutorial](../tutorials/light-control.html), in which devices can control the LED status of all devices in the network.
- [Mesh configuration](../reference/configuration-mesh.html).
- [Networking connectivity](../reference/networking.html) architecture reference material.
<h1 id="network-status">Network status</h1>

This interface informs you about connection state changes asynchronously. Providing a method to register a callback function to a socket accomplishes this. Each time the network interface's state changes, it triggers the callback.

![Network states](../../images/NetworkinterfaceStates.png)

## Usage

The callback needs to handle these possible network states:

```cpp NOCI
/** Enum of connection status types
 *
 *  Valid error codes have negative values.
 *
 *  @enum nsapi_connection_status
 */
 typedef enum nsapi_connection_status {
    NSAPI_STATUS_LOCAL_UP,            /*!< local IP address set */
    NSAPI_STATUS_GLOBAL_UP,           /*!< global IP address set */
    NSAPI_STATUS_DISCONNECTED,        /*!< no connection to network */
    NSAPI_STATUS_CONNECTING,          /*!< connecting to network */
    NSAPI_STATUS_ERROR_UNSUPPORTED  = NSAPI_ERROR_UNSUPPORTED
} nsapi_connection_status_t;
```

This API requires an interface to be monitored. For example, Ethernet:

```cpp NOCI
EthernetInterface eth;
```

You need to provide the callback function, for example:

```cpp NOCI

bool is_connected = false;

void status_callback(nsapi_event_t status, intptr_t param)
{
    if (status == NSAPI_EVENT_CONNECTION_STATUS_CHANGE) {
        switch(param) {
            case NSAPI_STATUS_GLOBAL_UP:
                if (!is_connected) {
                    start_my_cloud_client();
                    is_connected = true;
                }
                break;
            default:
                if (is_connected) {
                    stop_my_cloud_client();
                    is_connected = false;
                }
                break;
        }
    }
}
```

Now, the callback function is registered to the interface.

```cpp NOCI
    eth.attach(&status_callback);
```

This allows the application to monitor if network interface gets disconnected.

Optionally, the application might want to set the `connect()` method to nonblocking mode and wait until connectivity is fully established.

```cpp NOCI
    eth.set_blocking(false);
    eth.connect();              // Return immediately
```

By default, the `connect()` call blocks until `NSAPI_STATUS_GLOBAL_UP` state is reached. Some applications might require only link-local connectivity and therefore do not need to block that long. In those case monitoring the state changes is the preferred behavior.

## Using multiple connection status callbacks

The NetworkInterface API includes two functions that the applications can use to register more than one status callback for each network interface:

```
    /** Add event listener for interface.
     *
     * This API allows multiple callback to be registered for a single interface.
     * When first called, an internal list of event handlers is created and registered to
     * interface through attach() API.
     *
     * The application may only use the attach() or add_event_listener() interface. Mixing use
     * of both leads to undefined behavior.
     *
     *  @param status_cb The callback for status changes.
     */
    void add_event_listener(mbed::Callback<void(nsapi_event_t, intptr_t)> status_cb);

    /** Remove event listener from interface.
     *
     * Remove previously added callback from the handler list.
     *
     *  @param status_cb The callback to unregister.
     */
    void remove_event_listener(mbed::Callback<void(nsapi_event_t, intptr_t)> status_cb);
```

The callback prototype is the same as that for the `NetworkInterface::attach()`.

The `NetworkInterface::attach()` is still functional, and it is a porting API that each interface should provide. The functions above use `NetworkInterface::attach()` internally, so the application cannot use both at the same time.

You must either refactor the application by replacing `NetworkInterface::attach()` calls with `NetworkInterface::add_event_listener()`, or the application must remain using the `NetworkInterface::attach()`.

This optional and has a small RAM and ROM increase, so applications are not required to use it. Both APIs are still supported, but use is limited to one at a time.

## Example

Registering a status callback that connection state changes trigger depends on whether the network interface provides this functionality.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/TCPSocket_ConnStateCb_Example/)](https://os.mbed.com/teams/mbed_example/code/TCPSocket_ConnStateCb_Example/file/c66df92cf71b/main.cpp)

## Related content

- [Network socket](network-socket.html) API reference overview.
# Wi-Fi

<span class="images">![](http://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_wi_fi_interface.png)<span>WiFiInterface class hierarchy</span></span>

The WifiInterface provides a simple C++ API for connecting to the internet over a Wi-Fi device.

## Wi-Fi class reference

[![View code](https://www.mbed.com/embed/?type=library)](http://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_wi_fi_interface.html)

## Usage

To bring up the network interface of an external Wi-Fi device (for example, the ESP8266Interface):

1. Instantiate an implementation of the WiFiInterface class.
    1. Initialize the AT command parser.
1. Call the `connect()` function with an SSID and password for the Wi-Fi network.
    1. Command the Wi-Fi device to connect to network.
1. Once connected, you can use the WiFiInterface as a target for opening [network sockets](network-socket.html).

To bring up the network interface of an Ethernet-like driver (for example, the OdinWiFiInterface):

1. Instantiate an implementation of the WiFiInterface class.
    1. Initialize the Wi-Fi driver for the target.
    1. Initialize network stack (LWIP).
1. Call the `connect()` function with an SSID and password for the Wi-Fi network.
    1. Connect the Wi-Fi driver to the Wi-Fi network.
    2. Ensure the network stack acquires the IP address and DNS server address.
1. Once connected, you can use the WiFiInterface as a target for opening [network sockets](network-socket.html).

## Troubleshooting information

Network interface `connect()` and `set_credential()` might return following errors:

| Error code | Possible reason |
|------------|-----------------|
| `NSAPI_ERROR_UNSUPPORTED` | Security mode is unsupported. |
| `NSAPI_ERROR_PARAMETER` | Wrong parameters supplied for the given security mode, for example, no password. |
| `NSAPI_ERROR_NO_SSID` | The device did not find the given Wi-Fi network. |
| `NSAPI_ERROR_AUTH_FAILURE` | Wrong password given. |
| `NSAPI_ERROR_DEVICE_ERROR` | Unknown failure happened in the device. The device may not be capable of reporting more descriptive error codes. |

## Security

For specifying security settings, both `connect()` and `set_credential()` have optional parameter `nsapi_security_t security`, which defines the security mode the device uses. WifiInterface supports the following security modes:

| `nsapi_security_t`        | Security mode |
|---------------------------|---------------|
| `NSAPI_SECURITY_NONE`     | Not secure. Require no password or encryption. |
| `NSAPI_SECURITY_WEP`      | WEP security. Outdated. |
| `NSAPI_SECURITY_WPA`      | WPA security mode. Obsolete by WPA2; do not use. |
| `NSAPI_SECURITY_WPA2`     | WPA2 security. Mostly used security mode. |
| `NSAPI_SECURITY_WPA_WPA2` | Allows either WPA or WPA2 security. |

Please note that settings should match the security mode from the access point. Also, not all drivers support every mode. For most compatible settings, use `NSAPI_SECURITY_WPA_WPA2`, and set the Wi-Fi access point to allow only WPA2 mode.

## Wi-Fi example

This program scans for Wi-Fi access points in the area. There are multiple [Wi-Fi components](https://os.mbed.com/components/cat/wifi/) that implement the WiFiInterface class. The example below uses the [ESP8266Interface](https://github.com/armmbed/esp8266-driver) and [OdinWiFiInterface](https://github.com/u-blox/ublox-odin-w2-drivers-docs-mbed-5).

The ESP8266Interface uses AT commands over serial interface to connect to an external Wi-Fi device. The OdinWiFiInterface provides an Ethernet-like driver to the Mbed OS network stack. The network stack uses the driver to connect to Wi-Fi:

[![View code](https://www.mbed.com/embed/?url=https://github.com/ARMmbed/mbed-os-example-wifi)](https://github.com/ARMmbed/mbed-os-example-wifi/blob/mbed-os-5.13/main.cpp)

## Related content

- [Wi-Fi components](https://os.mbed.com/components/cat/wifi/).
- [Network socket](network-socket.html) API overview.
- [Wi-Fi architecture](../reference/wlan-technology.html).
# Network interface overview

A socket requires a NetworkInterface instance to indicate which NetworkInterface the socket should be created on. The NetworkInterface provides a network stack that implements the underlying socket operations.

NetworkInterface is also the controlling API that the application uses to specify the network configuration.

## Existing network interfaces:

- [Ethernet](ethernet.html): API for connecting to the internet over an Ethernet connection.
- [Wi-Fi](wi-fi.html): API for connecting to the internet with a Wi-Fi device.
- [Cellular](cellular-api.html): API for connecting to the internet using a cellular device.
- [Mesh networking interface](mesh-api.html): API for connecting to the IPv6-based mesh networks.

## Network connectivity states

When you create a network interface, it starts from the disconnected state. When you call `NetworkInteface::connect()`, the interface stays connected until you call `NetworkInterface::disconnect()`. The following diagram illustrates the state changes:

![Network states](../../images/NetworkinterfaceStates.png)

The interface handles all state changes between `Connecting`, `Local connectivity` and `Global route found`. Calling `NetworkInterface::connect()` might return when either local or global connectivity states are reached. This depends on the connectivity. For example, Ethernet and Wi-Fi interfaces return when global connectivity is reached. 6LoWPAN-based mesh networks depend on the standard you're using. The `LoWPANNDInterface` returns from `connect()` call when it connects to a border router that provides a global connection. The `ThreadInterface` returns from `connect()` call when it joins a local mesh network. It may later get a global connection when it finds a border router.

When a network or route is lost or any other cause limits the connectivity, the interface may change its state back to `Connecting`, `Local connectivity` or `Disconnected`. In the `Connecting` and `Local connectivity` states, the interface reconnects until the application chooses to call `NetworkInterface::disconnect()`. Depending on the network, this reconnection might have internal backoff periods, and not all interfaces implement the reconnection logic at all. Please refer to table below for information on how different interfaces behave.

An application may check the connection status by calling `nsapi_connection_status_t get_connection_status()` or register a callback to monitoring status changes. The following table lists defined network states with actions that applictions should take on the state change:

| State             |`nsapi_connection_status_t` | Actions to do on application |
|-------------------|----------------------------|------------------------------|
| Disconnected       | `NSAPI_STATUS_DISCONNECTED`| Call `connect()`. Close socket connections, if previously was connected. |
| Connecting         | `NSAPI_STATUS_CONNECTING`  | Close and destroy all open sockets. Wait until connection is established. |
| Local connectivity | `NSAPI_STATUS_LOCAL_UP`    | You can create sockets and communicate with local devices in the same network. |
| Global route found | `NSAPI_STATUS_GLOBAL_UP`   | You can create sockets and communicate with all hosts. |

Use the following API to register status callbacks:

- [Network status](network-status.html): API for monitoring network status changes.

Error handling and reconnection logic depends on the network interface. Please use the following table to determine what actions your application needs to do on each network type.

| `NetworkInterface` subclass | Does it reconnect automatically? | Possible states |
|------------------------------|---------------------------------|-----------------|
| `EthernetInterface` | Yes | 1.`NSAPI_STATUS_DISCONNECTED`<br />2.`NSAPI_STATUS_CONNECTING`<br />3.`NSAPI_STATUS_GLOBAL_UP`|
| `WiFiInterface` | Yes, when onboard network stack is used.<br />For external modules, it depends on the driver.<br />See examples below. | - |
| `OdinWiFiInterface` or<br /> `RTWInterface` | Yes | 1.`NSAPI_STATUS_DISCONNECTED`<br />2.`NSAPI_STATUS_CONNECTING`<br />3.`NSAPI_STATUS_GLOBAL_UP`|
| `ESP8266Interface` | Yes  | 1.`NSAPI_STATUS_DISCONNECTED`<br />2.`NSAPI_STATUS_CONNECTING`<br />3.`NSAPI_STATUS_GLOBAL_UP`|
| `CellularInterface` | Mostly no | 1.`NSAPI_STATUS_DISCONNECTED`<br />2.`NSAPI_STATUS_CONNECTING`<br />3.`NSAPI_STATUS_GLOBAL_UP`<br />`CellularInterface` may also send Cellular specific states specified in `CellularCommon.h` |
| `LoWPANNDInterface` or<br />`ThreadInterface` or<br />`WisunInterface` | Yes | 1.`NSAPI_STATUS_DISCONNECTED`<br />2.`NSAPI_STATUS_CONNECTING`<br />4.`NSAPI_STATUS_LOCAL_UP`<br />4.`NSAPI_STATUS_GLOBAL_UP`|

## Default network interface

In Mbed OS, targets that provide network connectivity also provide a default network interface. This can be Ethernet, Wi-Fi, mesh or cellular. Using a default interface allows you to port applications to different targets and connectivity options.

The following example uses a default interface to connect to the network:

```
NetworkInterface *net = NetworkInterface::get_default_instance();

if (!net) {
    printf("Error! No network inteface found.\n");
    return 0;
}

net->connect();
```

This example works on all IP-based connectivity options that Mbed OS supports. The Mbed OS configuration system provides configuration for the default interface at build time, so at run time, you can call `connect()` without any parameters.

For example, when providing a Wi-Fi SSID and password, you may use the following `mbed_app.json`:

```
{
    "target_overrides": {
        "*": {
            "nsapi.default-wifi-security": "WPA_WPA2",
            "nsapi.default-wifi-ssid": "\"ssid\"",
            "nsapi.default-wifi-password": "\"password\""
        }
    }
}
```

Please see [Selecting the default network interface](../reference/configuration-connectivity.html#selecting-the-default-network-interface) for information about how to supply required configuration parameters on different connections.

Targets with connectivity set the `target.network-default-interface-type` configuration variable appropriately, either to their only interface or the one most commonly used. For targets that provide more than one type of connectivity, you may choose the default by overriding the `target.network-default-interface-type` configuration variable.

Applications may also ask for a specific type of connection, as the following table shows:

|Method|What connectivity is returned| Requirements |
|------|-----------------------------|--------------|
|`*WiFiInterface::get_default_instance()`| Wi-Fi interface | Requires security parameters (mode, SSID, password). |
|`*EthInterface::get_default_instance()` | Wired Ethernet interface, not Wi-Fi | none |
|`*MeshInterface::get_default_instance()` | Returns either `LoWPANNDInterface` or `ThreadInterface`, depending on which is set to default | Target provides a driver or macro `DEVICE_802_15_4_PHY` is enabled. |
| `*CellularInterface::get_default_instance()` | Return cellular connectivity | Requires network parameters (pin, APN, username, password). |
| `*NetworkInterface::get_default_instance()` | One of the above, depending on `target.network-default-interface-type`. |  |

Note that the calls for a specific interface type do not preconfigure credentials such as SSID because an interface-type-specific application is expected to configure these in code. `NULL` is returned if no interface of that type is available.

Calls for a NetworkInterface request one of the interface types depending on `target.default-network-interface-type`, and preconfigure the credentials. If credentials can't be preconfigured (for example, because `nsapi.default-wifi-ssid` isn't set), the call returns `NULL` rather than an unconfigured interface.

An application may check the type of interface returned by `NetworkInterface::get_default_instance()` using "dynamic downcast" methods:

```
// net set from NetworkInterface::get_default_instance() as above
WiFiInterface *wifi = net->wifiInterface();
if (wifi) {
    printf("This is a Wi-Fi board.")
    // call WiFi-specific methods
}
```

## Notes on portable applications

When you expect an application to be portable between different network interfaces, please use the following guidelines:

1. Use only `NetworkInterface::get_default_instance()` for getting the interface.
1. Register the network status handler, and implement reconnection logic.

Please see the previous section, [Default network interface](#default-network-interface), on how to use the portable API for the network interface.

For network status changes, the API is specified in [Network status](network-status.html) section. Being portable means that your application only communicates after `NSAPI_STATUS_GLOBAL_UP` is received and tries to reconnect the network if `NSAPI_STATUS_DISCONNECTED` is received without calling `NetworkInterface::disconnect()`.

## Using multiple network interfaces

In Mbed OS, applications usually use one network interface at a time, and most APIs are designed this way. With few limitations, applications are able to operate more than one NetworkInterface. In Mbed OS, there are two built-in IP stacks and many external IP stacks provided by modules. Please refer to the [Architecture:IP networking](../reference/ip-networking.html) section for an explanation of how different stacks are integrated into Mbed OS.

When you use two network interfaces and both are operating on different IP stacks, the interfaces can work independently because there is no common data path, for example an application that uses an on-board Ethernet interface and any of the external Wi-Fi modules.

When you use two network interfaces and both use the same IP stacks, there are limitations.

We have modified the LwIP routing core to support multiple active interfaces, but when more than one interface is active in LwIP, only one is the default. All the outgoing traffic flows through it.

If you need to force the traffic to only one of the interfaces, you need to use `Socket::setsockopt(NSAPI_SOCKET, NSAPI_BIND_TO_DEVICE, <interface name>, <interface name length>)` to bind the socket into one interface. You can fetch the interface name from the `NetworkInterface::get_interface_name()` call.

Another, more common, case is where only one of the interface is active at a time. In this case, there is no need for `Socket::setsockopt()` if another interface is brought down because there is only one route option. This works with LwIP but is not verified with Nanostack because it is used only on specific use cases, such as mesh routing.

## Asynchronous operation

`NetworkInterface::connect()` and `NetworkInterface::disconnect()` are blocking by default. When an application prefers asynchronous operation, it can set the interface into nonblocking mode by calling `NetworkInterface::set_blocking(false)`. This has to be done for each interface separately.

When an interface operates in asynchronous mode, the return values of `connect()` and `disconnect()` have slightly different meanings. Calling `connect()` starts the asynchronous operation, which puts the device in the `GLOBAL_UP` state. Calling `disconnect()` puts the target in the `DISCONNECTED` state. Return code in asynchronous mode does not reflect the connection status. The most common return codes in asynchronous mode is `NSAPI_ERROR_OK`, which means that operation just started. Please refer to the Doxygen documentation of [NetworkInterface::connect()](https://os.mbed.com/docs/mbed-os/v5.13/mbed-os-api-doxy/class_network_interface.html#aaf6bf1dfffbe6a5626b7b52eaa542b6e) and [NetworkInterface::disconnect()](https://os.mbed.com/docs/mbed-os/v5.13/mbed-os-api-doxy/class_network_interface.html#afdda3f62c7d73df183ee2d352e8cd146) for return values of these functions.

To check whether the interface is connected, the application needs to register the status callback for the interface. Please refer to the [Network status API](network-status.html) for information on how to do so.

## Related content

- [Configuring the default network interface](../reference/configuration-connectivity.html#selecting-the-default-network-interface).
- [Network connectivity](../reference/networking.html).
- [IP networking](../reference/ip-networking.html).
- [Network status API](network-status.html).
- [Network sockets](../apis/network-socket.html).
# Non-IP cellular socket

The CellularNonIPSocket class provides, through standard socket `send` and `recv` member functions, the ability to send and receive 3GPP non-IP datagrams (NIDD) using our cellular IoT feature. This feature is implemented in the [`ControlPlane_netif`](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_control_plane__netif.html) class.

The constructor takes no parameters. To initialize the socket on a specified NetworkInterface, you must call the `open` method, which takes a CellularContext pointer.

[`CellularContext`](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/_cellular_context_8h.html) sets up the modem into the Control Plane optimization mode of operation if it is requested and if the cellular network supports it.

Control plane optimization is a new feature for cellular IoT (CIoT). With it, the device can use cellular control channels for data communications, to save power and resources by using less radio signaling.

Note: <span class="notes">**Note:** Non-IP use usually requires integration to a cellular operator messaging service. The service supports a web API to send to and receive the non-IP using devices.</span>

You can request Control Plane optimization mode either with CellularDevice's [`create_context`](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_cellular_device.html#a43b9e992dff1cb5d880acec576e9d06f) or by configuring it in the cellular `mbed_lib.json`:

```json
{
    "name": "cellular",
    "config": {
        "control-plane-opt": {
            "help": "Enables control plane CIoT EPS optimisation",
            "value": true
        }
    }
}
```

## CellularNonIPSocket class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1_cellular_non_i_p_socket.html)

## CellularNonIPSocket example

The following code demonstrates how to create and use a cellular non-IP socket:

```

#include "mbed.h"
#include "CellularNonIPSocket.h"
#include "CellularDevice.h"

// Network interface
NetworkInterface *iface;

int main() {
    // Bring up the cellular interface
    iface = CellularContext::get_default_nonip_instance();
    MBED_ASSERT(iface);

    // sim pin, apn, credentials and possible plmn are taken automatically from json when using NetworkInterface::set_default_parameters()
    iface->set_default_parameters();

    printf("Cellular Non-IP Socket example\n");
    if(NSAPI_ERROR_OK != iface->connect() || NSAPI_STATUS_GLOBAL_UP != iface->get_connection_status()) {
        printf("Error connecting\n");
        return -1;
    }

    CellularNonIPSocket sock;

    nsapi_error_t retcode = sock.open((CellularContext*)iface);

    if (retcode != NSAPI_ERROR_OK) {
        printf("CellularNonIPSocket.open() fails, code: %d\n", retcode);
        return -1;
    }

    const char *send_string = "TEST";

    if(0 > sock.send((void*) send_string, sizeof(send_string))) {
        printf("Error sending data\n");
        return -1;
    }

    printf("Success sending data\n");

    char recv_buf[4];
    if(0 > sock.recv((void *)recv_buf, sizeof(recv_buf))) {
        printf("Error receiving data\n");
        return -1;
    }

    printf("Success receiving data\n");

    // Close the socket and bring down the network interface
    sock.close();
    iface->disconnect();
    return 0;
}

```
# DNS Resolver

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_d_n_s.png)<span>DNS class hierarchy</span></span>

The DNS resolver provides an interface to do DNS host name resolutions. You can use DNS host name resolution to convert resource names to IP addresses. You can make DNS host name resolution after connecting the interface. You can use the returned IP address to make the socket connection.

### Usage

The DNS resolver supports both blocking and asynchronous DNS host name resolutions.

To make a DNS host name resolution:

1. Instantiate and connect a network interface.
1. Call the `gethostbyname()` function to resolve address.

To make an asynchronous DNS host name resolution:

1. Create a callback function for asynchronous host name resolution.
1. Instantiate and connect network interface.
1. Call the `gethostbyname_async()` with callback function to resolve address.

To cancel an asynchronous host name resolution:

1. Store the unique ID that the `gethostbyname_async()` call returns.
1. Call the `gethostbyname_async_cancel()` with a unique ID to cancel the asynchronous address resolution.

### Asynchronous operation

The DNS resolver has a cache for the host names and IP addresses. If the host name is found from the cache, the `gethostbyname_async()` function returns a success right away. The callback is called before the function returns.

If the address is not in the cache, `gethostbyname_async()` returns an unique ID for the operation. The callback is called after a response arrives from the DNS server on the network or a timeout occurs. You can use the unique ID to cancel the DNS host name resolution if needed.

If `gethostbyname_async()` returns a failure, the callback is not called.

When designing the callback function, take following considerations into account:

Callback is called from thread context. If the callback takes more than 10ms to execute, it might prevent underlying thread processing. Do not make calls to network operations due to stack size limitations; the callback should not perform expensive operations, such as socket recv/send calls or blocking operations.

## DNS resolver class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_d_n_s.html)

## DNS resolver example

This DNS resolver example makes asynchronous DNS host name resolution.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/DNS_GetHostbyNameAsync_Example/)](https://os.mbed.com/teams/mbed_example/code/DNS_GetHostbyNameAsync_Example/file/d0f7d306a900/main.cpp)

## Troubleshooting information

Network interface `gethostbyname()` and `gethostbyname_async()` failure causes:

- `NSAPI_ERROR_DNS_FAILURE` indicates that DNS failed to complete successfully. Check the host name and network connection.
- `NSAPI_ERROR_NO_MEMORY` indicates that there was not enough memory on heap to make an address resolution.

## Related content

- [Network socket](network-socket.html) API overview.
# DTLSSocket

`DTLSSocket` and `DTLSSocketWrapper` implement DTLS stream over the existing `Socket` transport. You can find design and implementation details in the [Secure Socket](../reference/secure-socket.html) page.

To use secure DTLS connections, application use the `DTLSSocketWrapper` through the Socket API, so existing applications and libraries are compatible.

`DTLSSocketWrapper` inherits `TLSSocketWrapper` and uses the same API. The only difference is that it uses timers to keep track of DTLS timeouts. Please see [TLSSocket](tlssocket.html) for an example.

## DTLSSocket class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_d_t_l_s_socket.html)

## DTLSSocket example

Please see the TLSSocket example:

[![View code](https://www.mbed.com/embed/?url=https://github.com/ARMmbed/mbed-os-example-tls-socket/blob/master/)](https://github.com/ARMmbed/mbed-os-example-tls-socket/blob/mbed-os-5.13/main.cpp)

## Related content

- [Secure Socket](../reference/secure-socket.html).
- [TLSSocket](tlssocket.html).
# SocketAddress

Use the SocketAddress class to represent the IP address and port pair of a unique network endpoint. Most network functions are also overloaded to accept string representations of IP addresses, but you can use SocketAddress to avoid the overhead of parsing IP addresses during repeated network transactions, and you can pass it around as a first class object.

## SocketAddress class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_socket_address.html)

## SocketAddress example

Here is an example to read current UTC time. This example uses the SocketAddress class to get the server IP address and port.

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/mbed-os-example-udp-sockets/)](https://os.mbed.com/teams/mbed_example/code/mbed-os-example-udp-sockets/file/cf516d904427/main.cpp)

## Related content

- [IP networking architecture](../reference/ip-networking.html).
# SocketStats

Use the SocketStats class to read the network socket statistics. When statistics are enabled, you can create the SocketStats class object with the `InternetSocket` class by using the `nsapi.socket-stats-enabled` configuration option.

The `SocketStats` class provides the static function `mbed_stats_socket_get_each` to get the network socket information for all sockets both currently in use and closed. Using this function, you can know how many sockets are open, destination IP addresses, the amount of data sent and received in bytes, the type of socket and the timestamp of recent "socket state" changes recorded in `last_change_tick`.

Socket statistics are stored in an internal data buffer and maintained for closed sockets, as well. If the internal data buffer is full, the socket closed with the oldest timestamp will be overwritten. You can configure the maximum amount of sockets statistics stored by using the `nsapi.socket-stats-max-count` configuration option.

## SocketStats class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_socket_stats.html)

## SocketStats example

Here is an example to collect socket statistics.

[![View Example](https://www.mbed.com/embed/?url=https://github.com/ARMmbed/mbed-os-example-socket-stats)](https://github.com/ARMmbed/mbed-os-example-socket-stats/blob/mbed-os-5.13/main.cpp)

## Related content

- [IP networking architecture](../reference/ip-networking.html).
# TCPSocket

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_t_c_p_socket.png)<span>TCPSocket class hierarchy</span></span>

The TCPSocket class provides the ability to send a stream of data over TCP. TCPSockets maintain a stateful connection that starts with the `connect` member function. After successfully connecting to a server, you can use the `send` and `recv` member functions to send and receive data (similar to writing or reading from a file).

The constructor takes no parameters. To initialize the socket on a specified NetworkInterface, you must call `open` method, which takes a NetworkStack pointer.

## Server socket

You can also use TCP to listen to incoming connections. To do this:

1. Bind socket to specific port by calling `TCPSocket::bind()`.
1. Set socket to listening mode by calling `TCPSocket::listen()`.
1. Accept incoming connection by calling `TCPSocket::accept()`.

Accepting a new connection returns a pointer to a new `Socket` object that you can use to communicate with the connected peer. Afterward, call this socket's `close()` function to shut down the connection and clean up the reserved resources.

Accepting a connection leaves the original socket in listening mode. You can continue to accept new connections until you destroy the listening socket, or call its `close()` method.

## TCPSocket class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_t_c_p_socket.html)

## TCPSocket example

Here is a client example of HTTP transaction over TCPSocket:

[![View code](https://www.mbed.com/embed/?url=https://github.com/ARMmbed/mbed-os-example-sockets)](https://github.com/ARMmbed/mbed-os-example-sockets/blob/mbed-os-5.13/main.cpp)

## Related content

- [Socket](socket.html) API reference.
# TLSSocket

`TLSSocket` and `TLSSocketWrapper` implement TLS stream over the existing `Socket` transport. You can find design and implementation details in the [SecureSocket](../reference/secure-socket.html) page.

To use secure TLS connections, the application uses the `TLSSocketWrapper` through the Socket API, so existing applications and libraries are compatible.

## TLSSocket class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_t_l_s_socket.html)

## TLSSocket example

The TLSSocket example creates TLS connection to the HTTPS server and receives a simple response from the server:

[![View code](https://www.mbed.com/embed/?url=https://github.com/ARMmbed/mbed-os-example-tls-socket/blob/master/)](https://github.com/ARMmbed/mbed-os-example-tls-socket/blob/mbed-os-5.13/main.cpp)

## Related content

- [SecureSocket](../reference/secure-socket.html).
# UDPSocket

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_u_d_p_socket.png)<span>UDPSocket class hierarchy</span></span>

The UDPSocket class provides the ability to send packets of data over UDP, using the `sendto` and `recvfrom` member functions. Packets can be lost or arrive out of order, so we suggest using a [TCPSocket](../apis/tcpsocket.html) when you require guaranteed delivery.

The constructor takes no parameters. To initialize the socket on a specified NetworkInterface, you must call `open` method, which takes a NetworkStack pointer.

UDP is a connectionless protocol. This allows you to send and receive packets to and from any remote addresses. Therefore, `Socket::listen()` and `Socket::accept()` functions are not implemented on UDPSocket.

If you prefer to use `send()` and `recv()` functions and work only with one peer, UDPSocket does support the `Socket::connect()` function, which sets a permanent peer address to the socket. Setting the peer address starts filtering incoming packets, so they are accepted only from that specific address. You can reset the filtering and peer address by calling `connect()` with empty `SocketAddress`.

## UDPSocket class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_u_d_p_socket.html)

## UDPSocket example

This UDP example reads the current UTC time by sending a request to the NIST Internet Time Service:

[![View code](https://www.mbed.com/embed/?url=https://os.mbed.com/teams/mbed_example/code/mbed-os-example-udp-sockets)](https://os.mbed.com/teams/mbed_example/code/mbed-os-example-udp-sockets/file/cf516d904427/main.cpp)

## Related content

- [TCPSocket](tcpsocket.html) API reference.
<h1 id="network-socket">Network socket overview</h1>

The application programming interface for IP networking is the Socket API. As described in the [IP networking](../reference/ip-networking.html) section, the Socket API relates to OSI layer 4, the Transport layer. In Mbed OS, the Socket API is abstract and supports various protocols such as TCP, UDP and non-IP data delivery for NB-IoT cellular networks.

<span class="images">![](../../images/ip-networking.png)<span>Sockets</span></span>

In Mbed OS, this socket API is C++ based but closely follows the functionality from the POSIX standard (IEEE Std 1003.1) and relevant RFC standards. The Socket interface is abstract and protocol agnostic and requires you to specify the protocol only when creating the socket. With libraries and interfaces, you may use the abstract base class, which allows you to port applications from one protocol to another.

## General use

The following steps describe the typical application flow:

1. Initialize a network interface.
1. Create a socket.
1. Connect (optional step for datagram protocols).
1. Send data.
1. Receive data.
1. Close the socket.

The following code demonstrates those steps by sending an HTTP query to a server:

```
// Initialize network interface
EthernetInterface eth;
eth.connect();

// Create a socket
TCPSocket sock;
sock.open(&eth);

// Connect
sock.connect("arm.com", 80);

// Send data
sock.send("GET / HTTP/1.0\r\n\r\n", 18);

// Receive data
char buf[100];
sock.recv(buf, 100);

// Close the socket
sock.close();
```

## Changes in Mbed OS 5.10

The 5.10 release refactors the Mbed OS Socket API. For most of the applications, these changes are not noticeable because the `TCPSocket` and `UDPSocket` classes still emulate legacy behavior.

The new design contains an abstract socket interface that applications can use directly. Casting `Socket` pointers back to `TCPSocket` or `UDPSocket` is no longer necessary.

Upcasting any protocol specific class to `Socket` has no side effect and is a recommended API design. Knowing the exact type is only required when you create the socket.

The new design also emphasizes use of `SocketAddress` for holding the IP addresses, instead on textual format. `SocketAddress` is a container class that protocols other than IP can use in the future. Legacy string versions of `connect()`, `bind()` and `sendto()` functions do not exist in the `Socket` base class, but they exist in `TCPSocket` and `UDPSocket` classes.

The new design also renders the TCPServer API unnecessary, moving its functionality directly into TCPSocket itself. The legacy TCPServer class still exists and is fully functional.

## Using DNS names

IP stacks operate only on binary IP addresses, but in Internet, servers are known by their symbolic domain name (DNS). To use these names with Socket interface, each name has to be resolved before.

Previously Socket interface contained methods that can directly accept DNS names and port numbers and do the resolving internally. These APIs are not recommended as they might hide problems in DNS system.

Recommended way is to use [DNS resolver](dns-resolver.html) to convert symbolic names to IP addresses. The following example shows how to use DNS in Mbed OS:

```
NetworkInteface *net;    // Initialized elsewhere

SocketAddress addr;
nsapi_error_t ret = net->gethostbyname("www.arm.com", &addr);  // Resolve www.arm.com and store into addr

if (ret == NSAPI_ERROR_OK) {
    // Resolving was succesfull
}
```

See [DNS resolver](dns-resolver.html) for more information.

## Server sockets

Some connection oriented protocols, for example TCP, can also be used for listening incomming connections. To do this

1. Bind socket to specific port by calling `Socket::bind()`
1. Set socket to listening mode by calling `Socket::listen()`
1. Accept incomming connection by calling `Socket::accept()`

Accepting new connection return you a pointer to a new `Socket` object that can be used to communicate with the connected peer. When done, you should call this socket's `close()` function to shut down the connection and clean up the reserved resources.

Accepting a connection will leave the original socket to listening mode. You can continue to accept new connections until you destroy the listening socket, or call its `close()` method.

For connectionless protocols, like UDP, each socket can receive from any peer. Therefore `listen()` and `accept()` are not required.

## Network socket interfaces and classes

The network socket API provides a common interface for using sockets on network devices. It's a class-based interface, which is familiar to users experienced with other socket APIs.

- [Socket](socket.html): Abstract base class for all protocols. Specifies the API.
- [UDPSocket](udpsocket.html): This class provides the ability to send packets of data over UDP.
- [TCPSocket](tcpsocket.html): This class provides the ability to send a stream of data over TCP.
- [SocketAddress](socketaddress.html): You can use this class to represent the IP address and port pair of a unique network endpoint.
- [CellularNonIPSocket](../apis/non-ip-cellular-socket.html): This class provides the ability to send and receive 3GPP non-IP datagrams (NIDD) using the cellular IoT feature.
- [Network status](network-status.html): API for monitoring network status changes.
- [DNS resolver](dns-resolver.html): API for resolving DNS names

## Network errors

The convention of the network socket API is for functions to return negative error codes to indicate failure. On success, a function may return zero or a non-negative integer to indicate the size of a transaction. On failure, a function must return a negative integer, which is one of the error codes in the `nsapi_error_t` [enum](../mbed-os-api-doxy/group__netsocket.html#gac21eb8156cf9af198349069cdc7afeba):

``` cpp NOCI
/** Enum of standardized error codes
 *
 *  Valid error codes have negative values and may
 *  be returned by any network operation.
 *
 *  @enum nsapi_error
 */
enum nsapi_error {
    NSAPI_ERROR_OK                  =  0,        /*!< no error */
    NSAPI_ERROR_WOULD_BLOCK         = -3001,     /*!< no data is not available but call is non-blocking */
    NSAPI_ERROR_UNSUPPORTED         = -3002,     /*!< unsupported functionality */
    NSAPI_ERROR_PARAMETER           = -3003,     /*!< invalid configuration */
    NSAPI_ERROR_NO_CONNECTION       = -3004,     /*!< not connected to a network */
    NSAPI_ERROR_NO_SOCKET           = -3005,     /*!< socket not available for use */
    NSAPI_ERROR_NO_ADDRESS          = -3006,     /*!< IP address is not known */
    NSAPI_ERROR_NO_MEMORY           = -3007,     /*!< memory resource not available */
    NSAPI_ERROR_NO_SSID             = -3008,     /*!< ssid not found */
    NSAPI_ERROR_DNS_FAILURE         = -3009,     /*!< DNS failed to complete successfully */
    NSAPI_ERROR_DHCP_FAILURE        = -3010,     /*!< DHCP failed to complete successfully */
    NSAPI_ERROR_AUTH_FAILURE        = -3011,     /*!< connection to access point failed */
    NSAPI_ERROR_DEVICE_ERROR        = -3012,     /*!< failure interfacing with the network processor */
    NSAPI_ERROR_IN_PROGRESS         = -3013,     /*!< operation (eg connect) in progress */
    NSAPI_ERROR_ALREADY             = -3014,     /*!< operation (eg connect) already in progress */
    NSAPI_ERROR_IS_CONNECTED        = -3015,     /*!< socket is already connected */
    NSAPI_ERROR_CONNECTION_LOST     = -3016,     /*!< connection lost */
    NSAPI_ERROR_CONNECTION_TIMEOUT  = -3017,     /*!< connection timed out */
};
```

## Nonblocking operation

The network socket API also supports nonblocking operations. The `set_blocking()` member function changes the state of a socket. When a socket is in nonblocking mode, socket operations return `NSAPI_ERROR_WOULD_BLOCK` when a transaction cannot immediately complete.

To allow efficient use of nonblocking operations, the socket classes provide a `sigio()` member function to register a callback on socket state changes. When the socket can successfully receive, send or accept or when an error occurs, the system triggers a callback. It may call the callback spuriously without reason.

You may call the callback in interrupt context, but do not make any read or write calls until it is on a thread.

The following example shows how to set up an asynchronous handler for socket:

```
nsapi_size_or_error_t send_query(TCPSocket *socket) {
    return socket->send(QUERY, QUERY_LEN);
}

nsapi_size_or_error_t receive_data(TCPSocket *socket) {
    // Simplified example, does not properly handle streaming and appending to buffer
    return socket->recv(my_buffer, remaining_len);
}

void handle_socket_sigio(EventFlags *evt, TCPSocket *socket)
{
    static enum {
        CONNECTING,
        SEND,
        RECEIVE,
        CLOSE,
    } next_state = CONNECTING;

    switch (next_state) {
        case CONNECTING:
            switch(socket->connect("api.ipify.org", 80)) {
                case NSAPI_ERROR_IN_PROGRESS:
                    // Connecting to server
                    break;
                case NSAPI_ERROR_ALREADY:
                    // Now connected to server
                    next_state = SEND;
                    break;
                default:
                    // Error in connection phase
                    next_state = CLOSE;
            }
        case SEND:
            if (send_query(socket) > 0)
                next_state = RECEIVE;
            else
                next_state = CLOSE; // Error
            break;
        case RECEIVE:
            if (receive_data(socket) == NSAPI_ERROR_WOULD_BLOCK)
                break;
            next_state = CLOSE;
            break;
        case CLOSE:
            socket->close();
            evt->set(1); // Signal the main thread
            break;
    }
}

int main() {
    EthernetInterface net;
    net.connect();

    TCPSocket socket;
    socket.open(&net);

    EventFlags completed;
    EventQueue *queue = mbed_event_queue();

    Event<void()> handler = queue->event(handle_socket_sigio, &completed, &socket);

    socket.set_blocking(false);
    socket.sigio(handler);
    handler();                   // Kick the state machine to start connecting

    completed.wait_any(1);
}
```
# Socket

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_socket.png)<span>Socket class hierarchy</span></span>

Socket is the abstract base class for all of the protocol-specific socket types. It defines all of the functions that comprise the Mbed OS Socket API. You cannot directly create a Socket object because it is abstract, but you can upcast any protocol-specific object to an abstract Socket object.

You can use this interface when designing portable application interfaces that do not require specific protocol to be defined. For example, instead of using `TCPSocket*` in methods, the application can use `Socket*` to allow either UDP or TCP to work, or even TLS.

The Socket class defines the Mbed OS Socket API and loosely follows the POSIX standard ([IEEE Std 1003.1](http://pubs.opengroup.org/onlinepubs/9699919799/)). The following table lists the methods from the Socket API and their relevant POSIX standards:

| Method | Description | POSIX standard |
|--------|-------------|----------------|
| `Socket::connect()`  | Connect socket to a remote address | [connect](http://pubs.opengroup.org/onlinepubs/9699919799/functions/connect.html) |
| `Socket::close`      | Closes any open connection and deallocates any memory associated with the socket | [close](http://pubs.opengroup.org/onlinepubs/9699919799/functions/close.html) |
| `Socket::send()`     | Send data over a socket | [send](http://pubs.opengroup.org/onlinepubs/9699919799/functions/send.html) |
| `Socket::recv()`     | Receive data from a socket | [recv](http://pubs.opengroup.org/onlinepubs/9699919799/functions/recv.html) |
| `Socket::sendto()`   | Sends data to the specified address. | [sendto](http://pubs.opengroup.org/onlinepubs/9699919799/functions/sendto.html) |
| `Socket::recvfrom()` | Receives data and stores the source address | [recvfrom](http://pubs.opengroup.org/onlinepubs/9699919799/functions/recvfrom.html) |
| `Socket::bind()`     | Bind a specific address to a socket | [bind](http://pubs.opengroup.org/onlinepubs/9699919799/functions/bind.html) |
| `Socket::listen()`   | Listen for incoming connections | [listen](http://pubs.opengroup.org/onlinepubs/9699919799/functions/listen.html) |
| `Socket::accept()`   | Accept incoming connection | [accept](http://pubs.opengroup.org/onlinepubs/9699919799/functions/accept.html) |
| `Socket::setsockopt()` | Set the socket options | [setsockopt](http://pubs.opengroup.org/onlinepubs/9699919799/functions/setsockopt.html) |
| `Socket::getsockopt()` | Get the socket options | [getsockopt](http://pubs.opengroup.org/onlinepubs/9699919799/functions/getsockopt.html) |

Not all protocols implement every function from the Socket API. For example, UDP does not implement the `listen()` and `accept()` functions. Also, socket options are mostly specific to the IP stack; they are not implemented on all stacks.

## Socket class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/class_socket.html)

## Socket example

Here is a client example of HTTP transaction over TCPSocket:

[![View code](https://www.mbed.com/embed/?url=https://github.com/ARMmbed/mbed-os-example-sockets)](https://github.com/ARMmbed/mbed-os-example-sockets/blob/mbed-os-5.13/main.cpp)

## Related content

- [TCPSocket](tcpsocket.html) API reference.
- [UDPSocket](tcpsocket.html) API reference.
- [Socket](../reference/ip-networking.html#socket-api) architecture.
# MessageBuilder

Mbed OS provides this API to construct NDEF messages, the common data format exchange for NFC messages. The class `mbed::nfc::ndef::MessageBuilder` builds an NDEF message into a user-provided buffer. `URI`, `Text` and `Mime` types can be serialized in the builder with the help of the member function `append_as_record`.

## MessageBuilder class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1nfc_1_1ndef_1_1_message_builder.html)

## MessageBuilder example

```
#include "nfc/ndef/MessageBuilder.h"

using mbed::nfc::ndef::MessageBuilder;
using mbed::nfc::ndef::common::Text;
using mbed::nfc::ndef::common::URI;

size_t build_ndef_message(const Span<uint8_t> &buffer) {
    MessageBuilder builder(buffer);

    URI uri(URI::HTTPS_WWW, span_from_cstr("mbed.com"));
    Text text(Text::UTF8, span_from_cstr("en-US"), span_from_cstr("Mbed website"));

    uri.append_as_record(builder);
    text.append_as_record(builder, /* last record */ true);

    return builder.get_message().size();
}
```

## Related content

- [MessageParser](messageparser.html) API reference.
- [SimpleMessageParser](simplemessageparser.html) API reference.
- [NFC architecture](../reference/nfc-technology.html).
# MessageParser

The MessageParser class is an event-driven NDEF message parser. This class parses a buffer of data in input and produces parsing events. It then forwards these parsing events to its delegate.

## MessageParser class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1nfc_1_1ndef_1_1_message_parser.html)

## MessageParser example

```
void set_delegate(Delegate *delegate);
void parse(const Span<const uint8_t> &data_buffer);
```

## Related content

- [SimpleMessageParser](simplemessageparser.html) API reference.
- [MessageBuilder](messagebuilder.html) API reference.
- [NFC architecture](../reference/nfc-technology.html).
# NFC

Near-Field Communication (NFC) is a short-range radio technology. Mbed OS supports NFC card emulation through a controller or NFC EEPROM:

 - [NFCController](nfccontroller.html) API reference.
 - [NFCEEPROM](nfc-eeprom.html) API reference.

## NDEF API

The common data format for an NFC message is an NDEF message. An NDEF message is a collection of separate NDEF records. Each of these records is defined by a type, such as URI, Mime and Text, that identifies a payload and what the record contains.

Mbed OS provides this API to construct and parse NDEF messages:

- [MessageParser](messageparser.html).
- [SimpleMessageParser](simplemessageparser.html).
- [MessageBuilder](messagebuilder.html).

### Related content

- [NFC architecture](../reference/nfc-technology.html).
# NFCController

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1nfc_1_1_n_f_c_controller.png)<span>NFCController class hierarchy</span></span>

Using an NFC controller with Mbed OS allows you to emulate NFC tags that a smartphone can read, as well as generate NDEF messages on demand.

To use an NFC controller, you must initiate the instance with a driver instance, an event queue and a scratch buffer for NDEF messages.

## NFCController class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1nfc_1_1_n_f_c_controller.html)

## NFCController example

```cpp TODO
#include "stdint.h"

#include "NFC.h"
#include "events/EventQueue.h"
#include "nfc/controllers/PN512Driver.h"
#include "nfc/controllers/PN512SPITransportDriver.h"

static uint8_t ndef_buffer[1024] = {0};

int main() {
    mbed::nfc::PN512SPITransportDriver pn512_transport(D11, D12, D13, D10, A1, A0);
    mbed::nfc::PN512Driver pn512_driver(&pn512_transport);
    events::EventQueue queue;
    mbed::nfc::NFCController nfc(&pn512_driver, &queue, ndef_buffer);

    ...
}
```

A delegate mechanism handles events throughout the API.

For instance, a delegate for a NFC controller can look similar to this:

```cpp TODO
struct NFCDelegate : mbed::nfc::NFCController::Delegate {
    virtual void on_discovery_terminated(nfc_discovery_terminated_reason_t reason) {
        printf("Discovery terminated:\r\n");
        if(reason != nfc_discovery_terminated_completed) {
            nfc_ptr->start_discovery(); // Error, restart discovery
        }
    }
    virtual void on_nfc_initiator_discovered(const SharedPtr< mbed::nfc::NFCRemoteInitiator> &nfc_initiator) {
        printf("Remote inititator detected\r\n");
        nfc_initiator->set_delegate(nfc_initiator_delegate_ptr);
        nfc_initiator->connect(); // Connect to the initiator
    }
};
```

### Related content

- [NFC architecture](../reference/nfc-technology.html).
# NFC EEPROM

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1nfc_1_1_n_f_c_e_e_p_r_o_m.png)<span>NFCEEPROM class hierarchy</span></span>

An NFC EEPROM can store NDEF messages. You can use a smartphone access the message through the NFC interface the EEPROM exposes.

To use an NFC EEPROM, you must initiate the instance with a driver instance, an event queue and a scratch buffer for NDEF messages.

## NFCEEPROM class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1nfc_1_1_n_f_c_e_e_p_r_o_m.html)

## NFCEEPROM example

```cpp TODO
#include "stdint.h"

#include "NFC.h"
#include "events/EventQueue.h"
#include "m24sr_driver.h"

static uint8_t ndef_buffer[1024] = {0};

int main() {
    mbed::nfc::vendor::ST::M24srDriver m24sr_driver(p10, p11);
    events::EventQueue queue;
    mbed::nfc::NFCEEPROM nfc(&m24sr_driver, &queue, ndef_buffer);

    ...
    nfc.write_ndef_message();
}
```

### Related content

- [NFC architecture](../reference/nfc-technology.html).
# SimpleMessageParser

<span class="images">![](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1nfc_1_1ndef_1_1common_1_1_simple_message_parser.png)<span>SimpleMessageParser class hierarchy</span></span>

The SimpleMessageParser class is a more integrated parser than the MessageParser class. Like MessageParser, SimpleMessageParser parses data and sends parsing events to its delegate. However, SimpleMessageParser also includes subparsers for well-known NFC types records, such as Text, URI or Mime records, and produces usable objects out of the box. User defined parsers can be injected at runtime to extend the capabilities of the SimpleMessageParser.

## SimpleMessageParser class reference

[![View code](https://www.mbed.com/embed/?type=library)](https://os.mbed.com/docs/v5.13/mbed-os-api-doxy/classmbed_1_1nfc_1_1ndef_1_1common_1_1_simple_message_parser.html)

## SimpleMessageParser example

```
#include "nfc/ndef/common/SimpleMessageParser.h"

using mbed::nfc::ndef::Record;
using mbed::nfc::ndef::RecordType;
using mbed::nfc::ndef::RecordID;
using mbed::nfc::ndef::MessageParser;
using mbed::nfc::ndef::common::Text;
using mbed::nfc::ndef::common::URI;
using mbed::nfc::ndef::common::Mime;

using mbed::nfc::ndef::common::SimpleMessageParser;

void parse_ndef_message(const Span<const uint8_t> &buffer) {
    SimpleMessageParser parser;
    struct : SimpleMessageParser::Delegate {
        virtual void on_parsing_started() {
            printf("parsing started\r\n");
        }

        virtual void on_text_parsed(const Text &text, const RecordID &) {
            printf("Text record parsed.\r\n");
            printf(
                "\tlanguage: %.*s\r\n",
                text.get_language_code().size(), text.get_language_code().data()
            );
            printf("\ttext: %.*s\r\n",  text.get_text().size(), text.get_text().data());
        }

        virtual void on_uri_parsed(const URI &uri, const RecordID &) {
            printf("URI parsed.\r\n");
            printf("\tid: %d\r\n", uri.get_id());
            printf("\tvalue: %.*s\r\n",  uri.get_uri_field().size(), uri.get_uri_field().data());
        }

        virtual void on_mime_parsed(const Mime &mime, const RecordID &) {
            printf("Mime object parsed.\r\n");
            printf("\ttype: %.*s\r\n", mime.get_mime_type().size(), mime.get_mime_type().data());
            printf("\tcontent size: %d\r\n", mime.get_mime_content().size());
        }

        virtual void on_unknown_record_parsed(const Record &record) {
            printf("Unknown record parsed.\r\n");
            printf(
                "\ttype: %d, type_value: %.*s\r\n",
                record.type.tnf, record.type.value.size(), record.type.value.data()
            );
            printf(
                "\tpayload size: %d, payload: %.*s\r\n",
                record.payload.size(), record.payload.size(), record.payload.data()
            );
        }

        virtual void on_parsing_terminated() {
            printf("parsing terminated\r\n");
        }

        virtual void on_parsing_error(MessageParser::error_t error) {
            printf("Parsing error: %d\r\n", error);
        }
    } delegate;

    parser.set_delegate(&delegate);
    parser.parse(buffer);
}
```

An application can extend capabilities of `SimpleMessageParser` by adding new record parsers (`mbed::nfc::ndef::RecordParser`) at runtime.

## Related content

- [MessageParser](messageparser.html) API reference.
- [MessageBuilder](messagebuilder.html) API reference.
- [NFC architecture](../reference/nfc-technology.html).