Showing preview only (646K chars total). Download the full file or copy to clipboard to get everything.
Repository: arduino-libraries/ArduinoBLE
Branch: master
Commit: a769ff82f323
Files: 130
Total size: 606.8 KB
Directory structure:
gitextract_54t7sr_k/
├── .codespellrc
├── .github/
│ ├── dependabot.yml
│ └── workflows/
│ ├── compile-examples.yml
│ ├── report-size-deltas.yml
│ ├── spell-check.yml
│ ├── sync-labels.yml
│ └── unit-tests.yml
├── .gitignore
├── CHANGELOG
├── LICENSE
├── README.md
├── docs/
│ ├── api.md
│ └── readme.md
├── examples/
│ ├── Central/
│ │ ├── LedControl/
│ │ │ └── LedControl.ino
│ │ ├── PeripheralExplorer/
│ │ │ └── PeripheralExplorer.ino
│ │ ├── Scan/
│ │ │ └── Scan.ino
│ │ ├── ScanCallback/
│ │ │ └── ScanCallback.ino
│ │ └── SensorTagButton/
│ │ └── SensorTagButton.ino
│ └── Peripheral/
│ ├── Advertising/
│ │ ├── EnhancedAdvertising/
│ │ │ └── EnhancedAdvertising.ino
│ │ └── RawDataAdvertising/
│ │ └── RawDataAdvertising.ino
│ ├── BatteryMonitor/
│ │ └── BatteryMonitor.ino
│ ├── ButtonLED/
│ │ └── ButtonLED.ino
│ ├── CallbackLED/
│ │ └── CallbackLED.ino
│ ├── EncryptedBatteryMonitor/
│ │ └── EncryptedBatteryMonitor.ino
│ └── LED/
│ └── LED.ino
├── extras/
│ ├── arduino-ble-parser.py
│ └── test/
│ ├── .gitignore
│ ├── CMakeLists.txt
│ ├── include/
│ │ ├── Arduino.h
│ │ ├── test_advertising_data/
│ │ │ └── FakeBLELocalDevice.h
│ │ ├── test_discovered_device/
│ │ │ └── FakeGAP.h
│ │ └── util/
│ │ ├── Common.h
│ │ ├── HCIFakeTransport.h
│ │ ├── Stream.h
│ │ ├── String.h
│ │ ├── TestUtil.h
│ │ └── itoa.h
│ └── src/
│ ├── Arduino.cpp
│ ├── test_advertising_data/
│ │ ├── FakeBLELocalDevice.cpp
│ │ ├── test_advertising_data.cpp
│ │ ├── test_local_name.cpp
│ │ ├── test_manufacturer.cpp
│ │ └── test_service.cpp
│ ├── test_characteristic/
│ │ ├── test_permissions.cpp
│ │ └── test_writeValue.cpp
│ ├── test_discovered_device/
│ │ ├── FakeGAP.cpp
│ │ └── test_discovered_device.cpp
│ ├── test_main.cpp
│ ├── test_uuid/
│ │ └── test_uuid.cpp
│ └── util/
│ ├── Common.cpp
│ ├── HCIFakeTransport.cpp
│ ├── String.cpp
│ ├── TestUtil.cpp
│ └── itoa.c
├── keywords.txt
├── library.properties
└── src/
├── ArduinoBLE.h
├── BLEAdvertisingData.cpp
├── BLEAdvertisingData.h
├── BLECharacteristic.cpp
├── BLECharacteristic.h
├── BLEDescriptor.cpp
├── BLEDescriptor.h
├── BLEDevice.cpp
├── BLEDevice.h
├── BLEProperty.h
├── BLEService.cpp
├── BLEService.h
├── BLEStringCharacteristic.cpp
├── BLEStringCharacteristic.h
├── BLETypedCharacteristic.h
├── BLETypedCharacteristics.cpp
├── BLETypedCharacteristics.h
├── local/
│ ├── BLELocalAttribute.cpp
│ ├── BLELocalAttribute.h
│ ├── BLELocalCharacteristic.cpp
│ ├── BLELocalCharacteristic.h
│ ├── BLELocalDescriptor.cpp
│ ├── BLELocalDescriptor.h
│ ├── BLELocalDevice.cpp
│ ├── BLELocalDevice.h
│ ├── BLELocalService.cpp
│ └── BLELocalService.h
├── remote/
│ ├── BLERemoteAttribute.cpp
│ ├── BLERemoteAttribute.h
│ ├── BLERemoteCharacteristic.cpp
│ ├── BLERemoteCharacteristic.h
│ ├── BLERemoteDescriptor.cpp
│ ├── BLERemoteDescriptor.h
│ ├── BLERemoteDevice.cpp
│ ├── BLERemoteDevice.h
│ ├── BLERemoteService.cpp
│ └── BLERemoteService.h
└── utility/
├── ATT.cpp
├── ATT.h
├── BLELinkedList.h
├── BLEUuid.cpp
├── BLEUuid.h
├── CordioHCICustomDriver.h
├── GAP.cpp
├── GAP.h
├── GATT.cpp
├── GATT.h
├── HCI.cpp
├── HCI.h
├── HCICordioTransport.cpp
├── HCICordioTransport.h
├── HCINinaSpiTransport.cpp
├── HCINinaSpiTransport.h
├── HCISilabsTransport.cpp
├── HCISilabsTransport.h
├── HCITransport.h
├── HCIUartTransport.cpp
├── HCIUartTransport.h
├── HCIVirtualTransport.cpp
├── HCIVirtualTransport.h
├── HCIVirtualTransportAT.cpp
├── HCIVirtualTransportAT.h
├── HCIVirtualTransportRPC.cpp
├── HCIVirtualTransportRPC.h
├── HCIVirtualTransportZephyr.cpp
├── HCIVirtualTransportZephyr.h
├── L2CAPSignaling.cpp
├── L2CAPSignaling.h
├── bitDescriptions.cpp
├── bitDescriptions.h
├── btct.cpp
├── btct.h
├── keyDistribution.cpp
└── keyDistribution.h
================================================
FILE CONTENTS
================================================
================================================
FILE: .codespellrc
================================================
# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/spell-check/.codespellrc
# See: https://github.com/codespell-project/codespell#using-a-config-file
[codespell]
# In the event of a false positive, add the problematic word, in all lowercase, to a comma-separated list here:
ignore-words-list = ,
skip = ./.git,./.licenses,__pycache__,node_modules,./go.mod,./go.sum,./package-lock.json,./poetry.lock,./yarn.lock,./extras/test
builtin = clear,informal,en-GB_to_en-US
check-filenames =
check-hidden =
================================================
FILE: .github/dependabot.yml
================================================
# See: https://docs.github.com/en/code-security/supply-chain-security/configuration-options-for-dependency-updates#about-the-dependabotyml-file
version: 2
updates:
# Configure check for outdated GitHub Actions actions in workflows.
# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/dependabot/README.md
# See: https://docs.github.com/en/code-security/supply-chain-security/keeping-your-actions-up-to-date-with-dependabot
- package-ecosystem: github-actions
directory: / # Check the repository's workflows under /.github/workflows/
schedule:
interval: daily
labels:
- "topic: infrastructure"
================================================
FILE: .github/workflows/compile-examples.yml
================================================
name: Compile Examples
# See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows
on:
push:
paths:
- ".github/workflows/compile-examples.yml"
- "examples/**"
- "src/**"
pull_request:
paths:
- ".github/workflows/compile-examples.yml"
- "examples/**"
- "src/**"
schedule:
# Run every Tuesday at 8 AM UTC to catch breakage caused by changes to external resources (libraries, platforms).
- cron: "0 8 * * TUE"
workflow_dispatch:
repository_dispatch:
jobs:
build:
name: ${{ matrix.board.fqbn }}
runs-on: ubuntu-latest
env:
SKETCHES_REPORTS_PATH: sketches-reports
strategy:
fail-fast: false
matrix:
board:
- fqbn: arduino:samd:mkrwifi1010
platforms: |
- name: arduino:samd
libraries: |
- name: Arduino_SpiNINA
artifact-name-suffix: arduino-samd-mkrwifi1010
- fqbn: arduino:samd:nano_33_iot
platforms: |
- name: arduino:samd
libraries: |
- name: Arduino_SpiNINA
artifact-name-suffix: arduino-samd-nano_33_iot
- fqbn: arduino:megaavr:uno2018:mode=on
platforms: |
- name: arduino:megaavr
libraries: |
- name: Arduino_SpiNINA
artifact-name-suffix: arduino-megaavr-uno2018
- fqbn: arduino:mbed_nano:nano33ble
platforms: |
- name: arduino:mbed_nano
libraries: ""
artifact-name-suffix: arduino-mbed_nano-nano33ble
- fqbn: arduino:mbed_nano:nanorp2040connect
platforms: |
- name: arduino:mbed_nano
libraries: |
- name: Arduino_SpiNINA
artifact-name-suffix: arduino-mbed_nano-nanorp2040connect
- fqbn: arduino:mbed_portenta:envie_m7
platforms: |
- name: arduino:mbed_portenta
libraries: ""
artifact-name-suffix: arduino-mbed_portenta-envie_m7
- fqbn: arduino:mbed_nicla:nicla_vision
platforms: |
- name: arduino:mbed_nicla
libraries: ""
artifact-name-suffix: arduino-mbed_nicla-nicla_vision
- fqbn: arduino:mbed_giga:giga
platforms: |
- name: arduino:mbed_giga
libraries: ""
artifact-name-suffix: arduino-mbed_giga-giga
- fqbn: arduino:mbed_opta:opta
platforms: |
- name: arduino:mbed_opta
libraries: ""
artifact-name-suffix: arduino-mbed_opta-opta
- fqbn: arduino:renesas_uno:unor4wifi
platforms: |
- name: arduino:renesas_uno
libraries: ""
artifact-name-suffix: arduino-renesas_uno-unor4wifi
- fqbn: arduino:renesas_portenta:portenta_c33
platforms: |
- name: arduino:renesas_portenta
libraries: ""
artifact-name-suffix: arduino-renesas_portenta-portenta_c33
- fqbn: arduino:esp32:nano_nora
platforms: |
- name: arduino:esp32
libraries: ""
artifact-name-suffix: arduino-esp32-nano_nora
- fqbn: arduino:zephyr_main:giga
platforms: |
- name: arduino:zephyr_main
libraries: ""
artifact-name-suffix: arduino-zephyr_main-giga
- fqbn: arduino:zephyr_main:nano33ble
platforms: |
- name: arduino:zephyr_main
libraries: ""
artifact-name-suffix: arduino-zephyr_main-nano33ble
- fqbn: arduino:zephyr_main:portentah7
platforms: |
- name: arduino:zephyr_main
libraries: ""
artifact-name-suffix: arduino-zephyr_main-portentah7
- fqbn: arduino:zephyr_main:niclasense
platforms: |
- name: arduino:zephyr_main
libraries: ""
artifact-name-suffix: arduino-zephyr_main-niclasense
- fqbn: arduino:zephyr_main:portentac33
platforms: |
- name: arduino:zephyr_main
libraries: ""
artifact-name-suffix: arduino-zephyr_main-portentac33
- fqbn: arduino:zephyr_main:opta
platforms: |
- name: arduino:zephyr_main
libraries: ""
artifact-name-suffix: arduino-zephyr_main-opta
- fqbn: arduino:zephyr:unoq
platforms: |
- name: arduino:zephyr
libraries: |
- name: MsgPack
artifact-name-suffix: arduino-zephyr-unoq
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Compile examples
uses: arduino/compile-sketches@v1
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
fqbn: ${{ matrix.board.fqbn }}
platforms: ${{ matrix.board.platforms }}
libraries: |
# Install the library from the local path.
- source-path: ./
${{ matrix.board.libraries }}
sketch-paths: |
- examples
enable-deltas-report: true
sketches-report-path: ${{ env.SKETCHES_REPORTS_PATH }}
- name: Save sketches report as workflow artifact
uses: actions/upload-artifact@v7
with:
if-no-files-found: error
path: ${{ env.SKETCHES_REPORTS_PATH }}
name: sketches-report-${{ matrix.board.artifact-name-suffix }}
build-for-esp32:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
fqbn:
- esp32:esp32:esp32
- esp32:esp32:esp32s3
- esp32:esp32:esp32c3
- esp32:esp32:esp32c6
- esp32:esp32:esp32h2
# Not supported out of the box by ESP32 Arduino core
#- esp32:esp32:esp32c2
steps:
- uses: actions/checkout@v6
- uses: arduino/compile-sketches@v1
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
fqbn: ${{ matrix.fqbn }}
libraries: |
${{ matrix.libraries }}
platforms: |
- name: esp32:esp32
source-url: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
sketch-paths: |
- examples/Central/Scan
- examples/Central/PeripheralExplorer
- examples/Central/ScanCallback
- examples/Central/SensorTagButton
- examples/Peripheral/Advertising/EnhancedAdvertising
- examples/Peripheral/Advertising/RawDataAdvertising
cli-compile-flags: |
- --warnings="none"
================================================
FILE: .github/workflows/report-size-deltas.yml
================================================
name: Report Size Deltas
# See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows
on:
push:
paths:
- ".github/workflows/report-size-deltas.yml"
schedule:
# Run at the minimum interval allowed by GitHub Actions.
# Note: GitHub Actions periodically has outages which result in workflow failures.
# In this event, the workflows will start passing again once the service recovers.
- cron: "*/5 * * * *"
workflow_dispatch:
repository_dispatch:
jobs:
report:
runs-on: ubuntu-latest
steps:
- name: Comment size deltas reports to PRs
uses: arduino/report-size-deltas@v1
with:
# Regex matching the names of the workflow artifacts created by the "Compile Examples" workflow
sketches-reports-source: ^sketches-report-.+
================================================
FILE: .github/workflows/spell-check.yml
================================================
# Source: https://github.com/per1234/.github/blob/main/workflow-templates/spell-check.md
name: Spell Check
# See: https://docs.github.com/en/actions/reference/events-that-trigger-workflows
on:
push:
pull_request:
schedule:
# Run every Tuesday at 8 AM UTC to catch new misspelling detections resulting from dictionary updates.
- cron: "0 8 * * TUE"
workflow_dispatch:
repository_dispatch:
jobs:
spellcheck:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Spell check
uses: codespell-project/actions-codespell@v2
================================================
FILE: .github/workflows/sync-labels.yml
================================================
# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/sync-labels.md
name: Sync Labels
# See: https://docs.github.com/en/actions/reference/events-that-trigger-workflows
on:
push:
paths:
- ".github/workflows/sync-labels.ya?ml"
- ".github/label-configuration-files/*.ya?ml"
pull_request:
paths:
- ".github/workflows/sync-labels.ya?ml"
- ".github/label-configuration-files/*.ya?ml"
schedule:
# Run daily at 8 AM UTC to sync with changes to shared label configurations.
- cron: "0 8 * * *"
workflow_dispatch:
repository_dispatch:
env:
CONFIGURATIONS_FOLDER: .github/label-configuration-files
CONFIGURATIONS_ARTIFACT: label-configuration-files
jobs:
check:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Download JSON schema for labels configuration file
id: download-schema
uses: carlosperate/download-file-action@v2
with:
file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/arduino-tooling-gh-label-configuration-schema.json
location: ${{ runner.temp }}/label-configuration-schema
- name: Install JSON schema validator
run: |
sudo npm install \
--global \
ajv-cli \
ajv-formats
- name: Validate local labels configuration
run: |
# See: https://github.com/ajv-validator/ajv-cli#readme
ajv validate \
--all-errors \
-c ajv-formats \
-s "${{ steps.download-schema.outputs.file-path }}" \
-d "${{ env.CONFIGURATIONS_FOLDER }}/*.{yml,yaml}"
download:
needs: check
runs-on: ubuntu-latest
strategy:
matrix:
filename:
# Filenames of the shared configurations to apply to the repository in addition to the local configuration.
# https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/sync-labels
- universal.yml
steps:
- name: Download
uses: carlosperate/download-file-action@v2
with:
file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/${{ matrix.filename }}
- name: Pass configuration files to next job via workflow artifact
uses: actions/upload-artifact@v7
with:
path: |
*.yaml
*.yml
if-no-files-found: error
name: ${{ env.CONFIGURATIONS_ARTIFACT }}
sync:
needs: download
runs-on: ubuntu-latest
steps:
- name: Set environment variables
run: |
# See: https://docs.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-environment-variable
echo "MERGED_CONFIGURATION_PATH=${{ runner.temp }}/labels.yml" >> "$GITHUB_ENV"
- name: Determine whether to dry run
id: dry-run
if: >
github.event_name == 'pull_request' ||
(
(
github.event_name == 'push' ||
github.event_name == 'workflow_dispatch'
) &&
github.ref != format('refs/heads/{0}', github.event.repository.default_branch)
)
run: |
# Use of this flag in the github-label-sync command will cause it to only check the validity of the
# configuration.
echo "::set-output name=flag::--dry-run"
- name: Checkout repository
uses: actions/checkout@v6
- name: Download configuration files artifact
uses: actions/download-artifact@v8
with:
name: ${{ env.CONFIGURATIONS_ARTIFACT }}
path: ${{ env.CONFIGURATIONS_FOLDER }}
- name: Remove unneeded artifact
uses: geekyeggo/delete-artifact@v6
with:
name: ${{ env.CONFIGURATIONS_ARTIFACT }}
- name: Merge label configuration files
run: |
# Merge all configuration files
shopt -s extglob
cat "${{ env.CONFIGURATIONS_FOLDER }}"/*.@(yml|yaml) > "${{ env.MERGED_CONFIGURATION_PATH }}"
- name: Install github-label-sync
run: sudo npm install --global github-label-sync
- name: Sync labels
env:
GITHUB_ACCESS_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
# See: https://github.com/Financial-Times/github-label-sync
github-label-sync \
--labels "${{ env.MERGED_CONFIGURATION_PATH }}" \
${{ steps.dry-run.outputs.flag }} \
${{ github.repository }}
================================================
FILE: .github/workflows/unit-tests.yml
================================================
name: Unit Tests
on:
pull_request:
paths:
- ".github/workflows/unit-tests.yml"
- 'extras/test/**'
- 'src/**'
push:
paths:
- ".github/workflows/unit-tests.yml"
- 'extras/test/**'
- 'src/**'
jobs:
test:
name: Run unit tests
runs-on: ubuntu-latest
env:
COVERAGE_DATA_PATH: extras/coverage-data/coverage.info
steps:
- name: Checkout
uses: actions/checkout@v6
- uses: arduino/cpp-test-action@main
with:
runtime-paths: |
- extras/test/build/bin/TEST_TARGET_UUID
- extras/test/build/bin/TEST_TARGET_DISC_DEVICE
- extras/test/build/bin/TEST_TARGET_ADVERTISING_DATA
coverage-exclude-paths: |
- '*/extras/test/*'
- '/usr/*'
coverage-data-path: ${{ env.COVERAGE_DATA_PATH }}
# A token is used to avoid intermittent spurious job failures caused by rate limiting.
- name: Set up Codecov upload token
run: |
if [[ "${{ github.repository }}" == "arduino-libraries/ArduinoBLE" ]]; then
# In order to avoid uploads of data from forks, only use the token for runs in the parent repo.
# Token is intentionally exposed.
# See: https://community.codecov.com/t/upload-issues-unable-to-locate-build-via-github-actions-api/3954
CODECOV_TOKEN="8118de48-b2af-48b4-a66a-26026847bfc5"
else
# codecov/codecov-action does unauthenticated upload if empty string is passed via the `token` input.
CODECOV_TOKEN=""
fi
echo "CODECOV_TOKEN=$CODECOV_TOKEN" >> "$GITHUB_ENV"
- name: Upload coverage report to Codecov
uses: codecov/codecov-action@v3
with:
file: "${{ env.COVERAGE_DATA_PATH }}"
fail_ci_if_error: true
token: ${{ env.CODECOV_TOKEN }}
================================================
FILE: .gitignore
================================================
.DS_Store
================================================
FILE: CHANGELOG
================================================
ArduinoBLE ?.?.? - ????.??.??
ArduinoBLE 1.1.2 - 2019.11.12
* cordio: switch to lower power when polling with timeout
* Fixed issue with wrong types for disconnection event handling. Thanks @cparata
ArduinoBLE 1.1.1 - 2019.09.05
* [Cordio] Fixed crashing when BLE.begin() is not called
* Fixed ACL RX packet fragmentation, affected devices that supported large MTUs
* Fixed BLECharacteristic::readValue(...) triggering a read request after a notification/indication was received
* Added support for case insensitive comparison of UUID or address string inputs
* Added (optional) company ID argument to BLE.setManufacturerData(...). Thanks @konikoni428
ArduinoBLE 1.1.0 - 2019.08.27
* Added BLE Central support
ArduinoBLE 1.0.0 - 2019.07.31
* Added support for Arduino Nano 33 BLE boards
ArduinoBLE 0.1.2 and older
* Changes not recorded
================================================
FILE: LICENSE
================================================
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
(This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.)
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
{description}
Copyright (C) {year} {fullname}
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random
Hacker.
{signature of Ty Coon}, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
================================================
FILE: README.md
================================================
# ArduinoBLE
[](https://github.com/arduino-libraries/ArduinoBLE/actions?workflow=Compile+Examples) [](https://github.com/arduino-libraries/ArduinoBLE/actions?workflow=Spell+Check)
Enables Bluetooth® Low Energy connectivity on the Arduino MKR WiFi 1010, Arduino UNO WiFi Rev2, Arduino Nano 33 IoT, Arduino Nano 33 BLE, Arduino Portenta H7, Arduino Giga R1 and Arduino UNO R4 WiFi.
This library supports creating a Bluetooth® Low Energy peripheral & central mode.
For more information about this library please visit us at:
https://www.arduino.cc/en/Reference/ArduinoBLE
## Firmware compatibility
| Board | Library Version | Required Firmware |
| :--- | :--- | :--- |
| **MKR WiFi 1010, UNO WiFi Rev2,<br>Nano 33 IoT, Nano RP2040 Connect** | **v2.0.0 or later** | [NINA-W102](https://github.com/arduino/nina-fw) **v3.0.0+** |
| **MKR WiFi 1010, UNO WiFi Rev2,<br>Nano 33 IoT, Nano RP2040 Connect** | **Versions prior to v2.0.0** | [NINA-W102](https://github.com/arduino/nina-fw) **v1.2.0 – v2.0.0** |
| **Arduino UNO R4 WiFi** | All versions | [ESP32-S3](https://github.com/arduino/uno-r4-wifi-usb-bridge) **v0.2.0+** |
## License
```
Copyright (c) 2019 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
```
================================================
FILE: docs/api.md
================================================
# ArduinoBLE library
## BLE class
Used to enable the Bluetooth® Low Energy module.
### `BLE.begin()`
Initializes the Bluetooth® Low Energy device.
#### Syntax
```
BLE.begin()
```
#### Parameters
None
#### Returns
- 1 on success
- 0 on failure
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
```
### `BLE.end()`
Stops the Bluetooth® Low Energy device.
#### Syntax
```
BLE.end()
```
#### Parameters
None
#### Returns
Nothing
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// ....
BLE.end();
```
### `BLE.poll()`
Poll for Bluetooth® Low Energy radio events and handle them.
#### Syntax
```
BLE.poll()
BLE.poll(timeout)
```
#### Parameters
**timeout**: optional timeout in ms, to wait for event. If not specified defaults to 0 ms.
#### Returns
Nothing
#### Example
```arduino
// assign event handlers for connected, disconnected to peripheral
BLE.setEventHandler(BLEConnected, blePeripheralConnectHandler);
BLE.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler);
BLE.poll();
```
### `BLE.setEventHandler()`
Set the event handler (callback) function that will be called when the specified event occurs.
#### Syntax
```
BLE.setEventHandler(eventType, callback)
```
#### Parameters
- **eventType**: event type (BLEConnected, BLEDisconnected)
- **callback**: function to call when event occurs
#### Returns
Nothing.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// ...
// assign event handlers for connected, disconnected to peripheral
BLE.setEventHandler(BLEConnected, blePeripheralConnectHandler);
BLE.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler);
void blePeripheralConnectHandler(BLEDevice central) {
// central connected event handler
Serial.print("Connected event, central: ");
Serial.println(central.address());
}
void blePeripheralDisconnectHandler(BLEDevice central) {
// central disconnected event handler
Serial.print("Disconnected event, central: ");
Serial.println(central.address());
}
```
### `BLE.connected()`
Query if another Bluetooth® Low Energy device is connected
#### Syntax
```
BLE.connected()
```
#### Parameters
None
#### Returns
- **true** if another Bluetooth® Low Energy device is connected,
- otherwise **false**.
#### Example
```arduino
// while the central is still connected to peripheral:
while (BLE.connected()) {
// ...
}
```
### `BLE.disconnect()`
Disconnect any Bluetooth® Low Energy devices that are connected
#### Syntax
```
BLE.disconnect()
```
#### Parameters
None
#### Returns
- **true** if any Bluetooth® Low Energy device that was previously connected was disconnected,
- otherwise **false**.
#### Example
```arduino
if (BLE.connected()) {
BLE.disconnect();
}
```
### `BLE.address()`
Query the Bluetooth® address of the Bluetooth® Low Energy device.
#### Syntax
```
BLE.address()
```
#### Parameters
None
#### Returns
- The **Bluetooth® address** of the Bluetooth® Low Energy device (as a String).
#### Example
```arduino
String address = BLE.address();
Serial.print("Local address is: ");
Serial.println(address);
```
### `BLE.rssi()`
Query the RSSI (Received signal strength indication) of the connected Bluetooth® Low Energy device.
#### Syntax
```
BLE.rssi()
```
#### Parameters
None
#### Returns
- The **RSSI** of the connected Bluetooth® Low Energy device, 127 if no Bluetooth® Low Energy device is connected.
#### Example
```arduino
if (BLE.connected()) {
Serial.print("RSSI = ");
Serial.println(BLE.rssi());
}
```
### `BLE.setAdvertisedServiceUuid()`
Set the advertised service UUID used when advertising.
#### Syntax
```
BLE.setAdvertisedServiceUuid(uuid)
```
#### Parameters
- **uuid:** 16-bit or 128-bit Bluetooth® Low Energy UUID in **String** format
#### Returns
Nothing
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
BLE.setAdvertisedServiceUuid("19B10000-E8F2-537E-4F6C-D104768A1214");
// ...
// start advertising
BLE.advertise();
```
### `BLE.setAdvertisedService()`
Set the advertised service UUID used when advertising to the value of the BLEService provided.
#### Syntax
```
BLE.setAdvertisedService(bleService)
```
#### Parameters
- **bleService:** BLEService to use UUID from
#### Returns
Nothing
#### Example
```arduino
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // Bluetooth® Low Energy LED Service
// ...
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
BLE.setAdvertisedService(ledService);
// ...
// start advertising
BLE.advertise();
```
### `BLE.setManufacturerData()`
Set the manufacturer data value used when advertising.
#### Syntax
```
BLE.setManufacturerData(data, length)
```
#### Parameters
- **data:** byte array containing manufacturer data
- **length:** length of manufacturer data array
#### Returns
Nothing
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
byte data[5] = { 0x01, 0x02, 0x03, 0x04, 0x05};
BLE.setManufacturerData(data, 5);
// ...
// start advertising
BLE.advertise();
```
### `BLE.setLocalName()`
Set the local value used when advertising.
#### Syntax
```
BLE.setLocalName(name)
```
#### Parameters
- **name:** local name value to use when advertising
#### Returns
Nothing
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
BLE.setLocalName("LED");
// ...
// start advertising
BLE.advertise();
```
### `BLE.setDeviceName()`
Set the device name in the built in device name characteristic. If not set, the value defaults to “Arduino”.
#### Syntax
```
BLE.setDeviceName(name)
```
#### Parameters
- **name:** device name value
#### Returns
Nothing
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
BLE.setDeviceName("LED");
// ...
// start advertising
BLE.advertise();
```
### `BLE.setAppearance()`
Set the appearance in the built in appearance characteristic. If not set, the value defaults to 0x0000.
#### Syntax
```
BLE.setAppearance(appearance)
```
#### Parameters
- **appearance:** appearance value
#### Returns
Nothing
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
BLE.setAppearance(0x8000);
// ...
// start advertising
BLE.advertise();
```
### `BLE.addService()`
Add a BLEService to the set of services the Bluetooth® Low Energy device provides
#### Syntax
```
BLE.addService(service)
```
#### Parameters
- **service:** BLEService to add
#### Returns
Nothing
#### Example
```arduino
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // Bluetooth® Low Energy LED Service
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// ...
BLE.addService(ledService);
// ...
```
### `BLE.advertise()`
Start advertising.
#### Syntax
```
BLE.advertise()
```
#### Parameters
None
#### Returns
- 1 on success,
- 0 on failure.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// ...
BLE.advertise();
// ...
```
### `BLE.stopAdvertise()`
Stop advertising.
#### Syntax
```
BLE.stopAdvertise()
```
#### Parameters
None
#### Returns
Nothing
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// ...
BLE.advertise();
// ...
BLE.stopAdvertise();
```
### `BLE.central()`
Query the central Bluetooth® Low Energy device connected.
#### Syntax
```
BLE.central()
```
#### Parameters
None
#### Returns
- **BLEDevice** representing the central.
#### Example
```arduino
// listen for Bluetooth® Low Energy peripherals to connect:
BLEDevice central = BLE.central();
// if a central is connected to peripheral:
if (central) {
Serial.print("Connected to central: ");
// print the central's MAC address:
Serial.println(central.address());
}
```
### `BLE.setAdvertisingInterval()`
Set the advertising interval in units of 0.625 ms. Defaults to 100ms (160 * 0.625 ms) if not provided.
#### Syntax
```
BLE.setAdvertisingInterval(advertisingInterval)
```
#### Parameters
- **advertisingInterval:** advertising interval in units of 0.625 ms
#### Returns
Nothing.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// ...
BLE.setAdvertisingInterval(320); // 200 * 0.625 ms
BLE.advertise();
```
### `BLE.setConnectionInterval()`
Set the minimum and maximum desired connection intervals in units of 1.25 ms.
#### Syntax
```
BLE.setConnectionInterval(minimum, maximum)
```
#### Parameters
- **minimum:** minimum desired connection interval in units of 1.25 ms
- **maximum:** maximum desired connection interval in units of 1.25 ms
#### Returns
Nothing.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// ...
BLE.setConnectionInterval(0x0006, 0x0c80); // 7.5 ms minimum, 4 s maximum
```
### `BLE.setConnectable()`
Set if the device is connectable after advertising, defaults to **true**.
#### Syntax
```
BLE.setConnectable(connectable)
```
#### Parameters
- **true**: the device will be connectable when advertising
- **false**: the device will NOT be connectable when advertising
#### Returns
Nothing.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// ...
BLE.setConnectable(false); // make the device unconnectable when advertising
```
### `BLE.scan()`
Start scanning for Bluetooth® Low Energy devices that are advertising.
#### Syntax
```
BLE.scan()
BLE.scan(withDuplicates)
```
#### Parameters
- **withDuplicates:** optional, defaults to **false**. If **true**, advertisements received more than once will not be filtered
#### Returns
- 1 on success,
- 0 on failure.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
}
```
### `BLE.scanForName()`
Start scanning for Bluetooth® Low Energy devices that are advertising with a particular (local) name.
#### Syntax
```
BLE.scanForName(name)
BLE.scanForName(name, withDuplicates)
```
#### Parameters
- **name:** (local) name of device (as a **String**) to filter for
- **withDuplicates:** optional, defaults to **false**. If **true**, advertisements received more than once will not be filtered.
#### Returns
- 1 on success,
- 0 on failure.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scanForName("LED");
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
}
```
### `BLE.scanForAddress()`
Start scanning for Bluetooth® Low Energy devices that are advertising with a particular (Bluetooth®) address.
#### Syntax
```
BLE.scanForAddress(address)
BLE.scanForAddress(address, withDuplicates)
```
#### Parameters
- **address:** (Bluetooth®) address (as a String) to filter for
- **withDuplicates:** optional, defaults to **false**. If **true**, advertisements received more than once will not be filtered
#### Returns
- 1 on success,
- 0 on failure.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scanForAddress("aa:bb:cc:ee:dd:ff");
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
}
```
### `BLE.scanForUuid()`
Start scanning for Bluetooth® Low Energy devices that are advertising with a particular (service) UUID.
#### Syntax
```
BLE.scanForUuid(uuid)
BLE.scanForUuid(uuid, withDuplicates)
```
#### Parameters
- **uuid:** (service) UUID (as a **String**) to filter for
- **withDuplicates:** optional, defaults to **false**. If **true**, advertisements received more than once will not be filtered.
#### Returns
- 1 on success,
- 0 on failure.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scanForUuid("aa10");
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
}
```
### `BLE.stopScan()`
Stop scanning for Bluetooth® Low Energy devices that are advertising.
#### Syntax
```
BLE.stopScan()
```
#### Parameters
None
#### Returns
Nothing
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLE.stopScan();
```
### `BLE.available()`
Query for a discovered Bluetooth® Low Energy device that was found during scanning.
#### Syntax
```
BLE.available()
```
#### Parameters
Nothing
#### Returns
- **BLEDevice** representing the discovered device.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
}
```
## BLEDevice Class
Used to get information about the devices connected or discovered while scanning
### `bleDevice.poll()`
Poll for Bluetooth® Low Energy radio events for the specified Bluetooth® Low Energy device and handle them.
#### Syntax
```
bleDevice.poll()
bleDevice.poll(timeout)
```
#### Parameters
- **timeout**: optional timeout in ms, to wait for event. If not specified defaults to 0 ms.
#### Returns
Nothing
#### Example
```arduino
// listen for Bluetooth® Low Energy centrals to connect:
BLEDevice central = BLE.central();
// if a central is connected to peripheral:
if (central) {
central.poll();
// ...
}
```
### `bleDevice.connected()`
Query if a Bluetooth® Low Energy device is connected
#### Syntax
```
bleDevice.connected()
```
#### Parameters
None
#### Returns
- **true** if the Bluetooth® Low Energy device is connected,
- otherwise **false**.
#### Example
```arduino
// listen for Bluetooth® Low Energy centrals to connect:
BLEDevice central = BLE.central();
// while the central is still connected
while (central.connected()) {
// ...
}
```
### `bleDevice.disconnect()`
Disconnect the Bluetooth® Low Energy device, if connected
#### Syntax
```
bleDevice.disconnect()
```
#### Parameters
None
#### Returns
- **true** if the Bluetooth® Low Energy device was disconnected,
- otherwise **false**.
#### Example
```arduino
// listen for Bluetooth® Low Energy centrals to connect:
BLEDevice central = BLE.central();
central.disconnect();
```
### `bleDevice.address()`
Query the Bluetooth® address of the Bluetooth® Low Energy device.
#### Syntax
```
bleDevice.address()
```
#### Parameters
None
#### Returns
- **Bluetooth® address** of the Bluetooth® Low Energy device (as a String).
#### Example
```arduino
// listen for Bluetooth® Low Energy peripherals to connect:
BLEDevice central = BLE.central();
// if a central is connected to peripheral:
if (central) {
Serial.print("Connected to central: ");
// print the central's MAC address:
Serial.println(central.address());
}
```
### `bleDevice.rssi()`
Query the RSSI (Received signal strength indication) of the Bluetooth® Low Energy device.
#### Syntax
```
bleDevice.rssi()
```
#### Parameters
None
#### Returns
- **RSSI** of the connected Bluetooth® Low Energy device, 127 if the Bluetooth® Low Energy device is not connected.
#### Example
```arduino
if (bleDevice.connected()) {
Serial.print("RSSI = ");
Serial.println(bleDevice.rssi());
}
```
### `bleDevice.characteristic()`
Get a BLECharacteristic representing a Bluetooth® Low Energy characteristic the device provides.
#### Syntax
```
bleDevice.characteristic(index)
bleDevice.characteristic(uuid)
bleDevice.characteristic(uuid, index)
```
#### Parameters
- **index**: index of characteristic
- **uuid**: uuid (as a **String**)
#### Returns
- **BLECharacteristic** for provided parameters
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
BLECharacteristic batteryLevelCharacteristic = peripheral.characteristic("2a19");
if (batteryLevelCharacteristic) {
// use the characteristic
} else {
Serial.println("Peripheral does NOT have battery level characteristic");
}
// ...
}
```
### `bleDevice.discoverAttributes()`
Discover all of the attributes of Bluetooth® Low Energy device.
#### Syntax
```
bleDevice.discoverAttributes()
```
#### Parameters
None
#### Returns
- **true**, if successful,
- **false** on failure.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
// ...
}
```
### `bleDevice.discoverService()`
Discover the attributes of a particular service on the Bluetooth® Low Energy device.
#### Syntax
```
bleDevice.discoverService(serviceUuid)
```
#### Parameters
- **serviceUuid:** service UUID to discover (as a **String**)
#### Returns
- **true**, if successful,
- **false** on failure.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover service attributes
Serial.println("Discovering service attributes ...");
if (peripheral.serviceUuid("fffe")) {
Serial.println("Service attributes discovered");
} else {
Serial.println("Service attribute discovery failed!");
peripheral.disconnect();
return;
}
// ...
}
```
### `bleDevice.deviceName()`
Query the device name (BLE characteristic UUID 0x2a00) of a Bluetooth® Low Energy device.
#### Syntax
```
bleDevice.deviceName()
```
#### Parameters
None
#### Returns
- **Device name** (as a String).
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
// read and print device name of peripheral
Serial.println();
Serial.print("Device name: ");
Serial.println(peripheral.deviceName());
Serial.print("Appearance: 0x");
Serial.println(peripheral.appearance(), HEX);
Serial.println();
// ...
}
```
### `bleDevice.appearance()`
Query the appearance (BLE characteristic UUID 0x2a01) of a Bluetooth® Low Energy device.
#### Syntax
```
bleDevice.appearance()
```
#### Parameters
None
#### Returns
- **Appearance value** (as a number).
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
// read and print device name of peripheral
Serial.println();
Serial.print("Device name: ");
Serial.println(peripheral.deviceName());
Serial.print("Appearance: 0x");
Serial.println(peripheral.appearance(), HEX);
Serial.println();
// ...
}
```
### `bleDevice.serviceCount()`
Query the number of services discovered for the Bluetooth® Low Energy device.
#### Syntax
```
bleDevice.serviceCount()
```
#### Parameters
None
#### Returns
- The number of **services discovered** for the Bluetooth® Low Energy device.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
int serviceCount = peripheral.serviceCount();
Serial.print(serviceCount);
Serial.println(" services discovered");
// ...
}
```
### `bleDevice.hasService()`
Query if the Bluetooth® Low Energy device has a particular service.
#### Syntax
```
bleDevice.hasService(uuid)
bleDevice.hasService(uuid, index)
```
#### Parameters
- **uuid**: uuid to check (as a **String**)
- **index**: optional, index of service to check if the device provides more than on. Defaults to 0, if not provided.
#### Returns
- **true**, if the device provides the service,
- **false** otherwise.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
if (peripheral.hasService("180f")) {
Serial.println("Peripheral has battery service");
}
// ...
}
```
### `bleDevice.service()`
Get a BLEService representing a Bluetooth® Low Energy service the device provides.
#### Syntax
```
bleDevice.service(index)
bleDevice.service(uuid)
bleDevice.service(uuid, index)
```
#### Parameters
- **index**: index of service
- **uuid**: uuid (as a **String**)
#### Returns
- **BLEService** for provided parameters
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
BLEService batteryService = peripheral.service("180f");
if (batteryService) {
// use the service
} else {
Serial.println("Peripheral does NOT have battery service");
}
// ...
}
```
### `bleDevice.characteristicCount()`
Query the number of characteristics discovered for the Bluetooth® Low Energy device.
#### Syntax
```
bleDevice.characteristicCount()
```
#### Parameters
None
#### Returns
- The **number of characteristics** discovered for the Bluetooth® Low Energy device.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
int characteristicCount = peripheral.characteristicCount();
Serial.print(characteristicCount);
Serial.println(" characteristics discovered");
// ...
}
```
### `bleDevice.hasCharacteristic()`
Query if the Bluetooth® Low Energy device has a particular characteristic.
#### Syntax
```
bleDevice.hasCharacteristic(uuid)
bleDevice.hasCharacteristic(uuid, index)
```
#### Parameters
- **uuid**: uuid to check (as a **String**)
- **index**: optional, index of characteristic to check if the device provides more than on. Defaults to 0, if not provided.
#### Returns
- **true**, if the device provides the characteristic,
- **false** otherwise.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
if (peripheral.hasCharacteristic("2a19")) {
Serial.println("Peripheral has battery level characteristic");
}
// ...
}
```
### `bleDevice.hasLocalName()`
Query if a discovered Bluetooth® Low Energy device is advertising a local name.
#### Syntax
```
bleDevice.hasLocalName()
```
#### Parameters
Nothing
#### Returns
- **true**, if the device is advertising a local name,
- **false** otherwise.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
// print the local name, if present
if (peripheral.hasLocalName()) {
Serial.print("Local Name: ");
Serial.println(peripheral.localName());
}
// ...
}
```
### `bleDevice.hasAdvertisedServiceUuid()`
Query if a discovered Bluetooth® Low Energy device is advertising a service UUID.
#### Syntax
```
bleDevice.hasAdvertisedServiceUuid()
bleDevice.hasAdvertisedServiceUuid(index)
```
#### Parameters
- **index**: optional, defaults to 0, the index of the service UUID, if the device is advertising more than one.
#### Returns
- **true**, if the device is advertising a service UUID,
- **false** otherwise.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
// print the advertised service UUIDs, if present
if (peripheral.hasAdvertisedServiceUuid()) {
Serial.print("Service UUIDs: ");
for (int i = 0; i < peripheral.advertisedServiceUuidCount(); i++) {
Serial.print(peripheral.advertisedServiceUuid(i));
Serial.print(" ");
}
Serial.println();
}
// ...
}
```
### `bleDevice.advertisedServiceUuidCount()`
Query the number of advertised services a discovered Bluetooth® Low Energy device is advertising.
#### Syntax
```
bleDevice.advertisedServiceUuidCount()
```
#### Parameters
None
#### Returns
- The **number of advertised services** a discovered Bluetooth® Low Energy device is advertising.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
// print the advertised service UUIDs, if present
if (peripheral.hasAdvertisedServiceUuid()) {
Serial.print("Service UUIDs: ");
for (int i = 0; i < peripheral.advertisedServiceUuidCount(); i++) {
Serial.print(peripheral.advertisedServiceUuid(i));
Serial.print(" ");
}
Serial.println();
}
// ...
}
```
### `bleDevice.localName()`
Query the local name a discovered Bluetooth® Low Energy device is advertising with.
#### Syntax
```
bleDevice.localName()
```
#### Parameters
Nothing
#### Returns
- **Advertised local name** (as a String).
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
// print the local name, if present
if (peripheral.hasLocalName()) {
Serial.print("Local Name: ");
Serial.println(peripheral.localName());
}
// ...
}
```
### `bleDevice.advertisedServiceUuid()`
Query an advertised service UUID discovered Bluetooth® Low Energy device is advertising.
#### Syntax
```
bleDevice.advertisedServiceUuid()
bleDevice.advertisedServiceUuid(index)
```
#### Parameters
- **index**: optional, defaults to 0, the index of the **service UUID**, if the device is advertising more than one.
#### Returns
- Advertised service **UUID** (as a String).
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
// print the advertised service UUIDs, if present
if (peripheral.hasAdvertisedServiceUuid()) {
Serial.print("Service UUIDs: ");
for (int i = 0; i < peripheral.advertisedServiceUuidCount(); i++) {
Serial.print(peripheral.advertisedServiceUuid(i));
Serial.print(" ");
}
Serial.println();
}
// ...
}
```
### `bleDevice.connect()`
Connect to a Bluetooth® Low Energy device.
#### Syntax
```
bleDevice.connect()
```
#### Parameters
None
#### Returns
- **true**, if the connection was successful,
- **false** otherwise.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// ...
}
```
## BLEService Class
Used to enable the services board provides or interact with services a remote board provides.
### `BLEService()`
Create a new Bluetooth® Low Energy service.
#### Syntax
```
BLEService(uuid)
```
#### Parameters
- **uuid**: 16-bit or 128-bit UUID in **String** format
#### Returns
- New **BLEService** with the specified **UUID**
#### Example
```arduino
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // Bluetooth® Low Energy LED Service
```
### `bleService.uuid()`
Query the UUID of the specified BLEService.
#### Syntax
```
bleService.uuid()
```
#### Parameters
None
#### Returns
- UUID of the Bluetooth® Low Energy service as a **String**.
#### Example
```arduino
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // Bluetooth® Low Energy LED Service
Serial.print("LED service UUID = ");
Serial.println(ledService.uuid());
```
### `bleService.addCharacteristic()`
Add a BLECharacteristic to the Bluetooth® Low Energy service.
#### Syntax
```
bleService.addCharacteristic(bleCharacteristic)
```
#### Parameters
None
#### Returns
Nothing
#### Example
```arduino
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // Bluetooth® Low Energy LED Service
// Bluetooth® Low Energy LED Switch Characteristic - custom 128-bit UUID, readable and writable by central
BLECharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite, 1);
// add the characteristic to the service
ledService.addCharacteristic(switchCharacteristic);
```
### `bleService.characteristicCount()`
Query the number of characteristics discovered for the Bluetooth® Low Energy service.
#### Syntax
```
bleService.characteristicCount()
```
#### Parameters
None
#### Returns
- The **number of characteristics** discovered for the Bluetooth® Low Energy service.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
BLEService batteryService = peripheral.service("180f");
if (batteryService) {
// use the service
int characteristicCount = batteryService.characteristicCount();
Serial.print(characteristicCount);
Serial.println(" characteristics discovered in battery service");
} else {
Serial.println("Peripheral does NOT have battery service");
}
// ...
}
```
### `bleService.hasCharacteristic()`
Query if the Bluetooth® Low Energy service has a particular characteristic.
#### Syntax
```
bleService.hasCharacteristic(uuid)
bleService.hasCharacteristic(uuid, index)
```
#### Parameters
- **uuid**: uuid to check (as a **String**)
- **index**: optional, index of characteristic to check if the device provides more than on. Defaults to 0, if not provided.
#### Returns
- **true**, if the service provides the characteristic,
- **false** otherwise.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
BLEService batteryService = peripheral.service("180f");
if (batteryService) {
// use the service
if (batteryService.hasCharacteristic("2a19")) {
Serial.println("Battery service has battery level characteristic");
}
} else {
Serial.println("Peripheral does NOT have battery service");
}
// ...
}
```
### `bleService.characteristic()`
Get a BLECharacteristic representing a Bluetooth® Low Energy characteristic the service provides.
#### Syntax
```
bleService.characteristic(index)
bleService.characteristic(uuid)
bleService.characteristic(uuid, index)
```
#### Parameters
- **index**: index of characteristic
- **uuid**: uuid (as a **String**)
#### Returns
- **BLECharacteristic** for provided parameters
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
BLEService batteryService = peripheral.service("180f");
if (batteryService) {
// use the service
BLECharacteristic batteryLevelCharacteristic = peripheral.characteristic("2a19");
if (batteryLevelCharacteristic) {
// use the characteristic
} else {
Serial.println("Peripheral does NOT have battery level characteristic");
}
} else {
Serial.println("Peripheral does NOT have battery service");
}
// ...
}
```
## BLECharacteristic Class
Used to enable the characteristics board offers in a service or interact with characteristics a remote board provides.
### `BLECharacteristic()`
Create a new Bluetooth® Low Energy characteristic.
#### Syntax
```
BLECharacteristic(uuid, properties, valueSize)
BLECharacteristic(uuid, properties, valueSize, fixedLength)
BLECharacteristic(uuid, properties, stringValue)
BLEBoolCharacteristic(uuid, properties)
BLEBooleanCharacteristic(uuid, properties)
BLECharCharacteristic(uuid, properties)
BLEUnsignedCharCharacteristic(uuid, properties)
BLEByteCharacteristic(uuid, properties)
BLEShortCharacteristic(uuid, properties)
BLEUnsignedShortCharacteristic(uuid, properties)
BLEWordCharacteristic(uuid, properties)
BLEIntCharacteristic(uuid, properties)
BLEUnsignedIntCharacteristic(uuid, properties)
BLELongCharacteristic(uuid, properties)
BLEUnsignedLongCharacteristic(uuid, properties)
BLEFloatCharacteristic(uuid, properties)
BLEDoubleCharacteristic(uuid, properties)
```
#### Parameters
- **uuid**: 16-bit or 128-bit UUID in **String** format
- **properties**: mask of the properties (BLEBroadcast, BLERead, BLEWriteWithoutResponse, BLEWrite, BLENotify, BLEIndicate)
- **valueSize**: (maximum) size of characteristic value
- **fixedLength**: if true, size of characteristic value is fixed
- **stringValue**: value as a string
#### Returns
- New **BLECharacteristic** with the specified **UUID** and value
#### Example
```arduino
// Bluetooth® Low Energy Battery Level Characteristic
BLEUnsignedCharCharacteristic batteryLevelChar("2A19", // standard 16-bit characteristic UUID
BLERead | BLENotify); // remote clients will be able to get notifications if this characteristic changes
```
### `bleCharacteristic.uuid()`
Query the UUID of the specified BLECharacteristic.
#### Syntax
```
bleCharacteristic.uuid()
```
#### Parameters
None
#### Returns
- **UUID** of the Bluetooth® Low Energy service as a **String**.
#### Example
```arduino
// Bluetooth® Low Energy LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
Serial.print("Switch characteristic UUID = ");
Serial.println(switchCharacteristic.uuid());
```
### `bleCharacteristic.properties()`
Query the property mask of the specified BLECharacteristic.
#### Syntax
```
bleCharacteristic.properties()
```
#### Parameters
None
#### Returns
- **Properties of the characteristic masked** (BLEBroadcast, BLERead, BLEWriteWithoutResponse, BLEWrite, BLENotify, BLEIndicate)
#### Example
```arduino
// Bluetooth® Low Energy LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
byte properties = switchCharacteristic.properties();
if (properties & BLERead) {
// characteristic is readable ...
}
if (properties & (BLEWrite | BLEWriteWithoutResponse)) {
// characteristic is writable ...
}
```
### `bleCharacteristic.valueSize()`
Query the maximum value size of the specified BLECharacteristic.
#### Syntax
```
bleCharacteristic.valueSize()
```
#### Parameters
None
#### Returns
- The **maximum value** size of the characteristic (in bytes)
#### Example
```arduino
// Bluetooth® Low Energy LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
Serial.print("value size = ");
Serial.println(switchCharacteristic.valueSize());
```
### `bleCharacteristic.value()`
Query the current value of the specified BLECharacteristic.
#### Syntax
```
bleCharacteristic.value()
```
#### Parameters
None
#### Returns
- The **current value** of the characteristic, value type depends on the constructor used
#### Example
```arduino
// Bluetooth® Low Energy LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
if (switchCharacteristic.value()) { // any value other than 0
Serial.println("LED on");
digitalWrite(ledPin, HIGH); // will turn the LED on
} else { // a 0 value
Serial.println(F("LED off"));
digitalWrite(ledPin, LOW); // will turn the LED off
}
```
### `bleCharacteristic.valueLength()`
Query the current value size of the specified BLECharacteristic.
#### Syntax
```
bleCharacteristic.valueLength()
```
#### Parameters
None
#### Returns
- The **current value** size of the characteristic (in bytes)
#### Example
```arduino
// Bluetooth® Low Energy LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
Serial.print("value length = ");
Serial.println(switchCharacteristic.valueLength());
```
### `bleCharacteristic.readValue()`
Read the current value of the characteristic. If the characteristic is on a remote device, a read request will be sent.
#### Syntax
```
bleCharacteristic.readValue(buffer, length)
bleCharacteristic.readValue(value)
```
#### Parameters
- **buffer:** byte array to read value into length: size of buffer argument in bytes
- **value**: variable to read value into (by reference)
#### Returns
- **Number of bytes** read
#### Example
```arduino
while (peripheral.connected()) {
// while the peripheral is connected
// check if the value of the simple key characteristic has been updated
if (simpleKeyCharacteristic.valueUpdated()) {
// yes, get the value, characteristic is 1 byte so use byte value
byte value = 0;
simpleKeyCharacteristic.readValue(value);
if (value & 0x01) {
// first bit corresponds to the right button
Serial.println("Right button pressed");
}
if (value & 0x02) {
// second bit corresponds to the left button
Serial.println("Left button pressed");
}
}
}
```
### `bleCharacteristic.writeValue()`
Write the value of the characteristic. If the characteristic is on a remote device, a write request or command will be sent.
#### Syntax
```
bleCharacteristic.writeValue(buffer, length)
bleCharacteristic.writeValue(value)
```
#### Parameters
- **buffer**: byte array to write value with
- **length**: number of bytes of the buffer argument to write
- **value**: value to write
#### Returns
- 1 on success,
- 0 on failure
#### Example
```arduino
// read the button pin
int buttonState = digitalRead(buttonPin);
if (oldButtonState != buttonState) {
// button changed
oldButtonState = buttonState;
if (buttonState) {
Serial.println("button pressed");
// button is pressed, write 0x01 to turn the LED on
ledCharacteristic.writeValue((byte)0x01);
} else {
Serial.println("button released");
// button is released, write 0x00 to turn the LED off
ledCharacteristic.writeValue((byte)0x00);
}
}
```
### `bleCharacteristic.setEventHandler()`
Set the event handler (callback) function that will be called when the specified event occurs.
#### Syntax
```
bleCharacteristic.setEventHandler(eventType, callback)
```
#### Parameters
- **eventType**: event type (BLESubscribed, BLEUnsubscribed, BLERead, BLEWritten)
- **callback**: function to call when the event occurs
#### Returns
Nothing
#### Example
```arduino
// create switch characteristic and allow remote device to read and write
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
// assign event handlers for characteristic
switchCharacteristic.setEventHandler(BLEWritten, switchCharacteristicWritten);
void switchCharacteristicWritten(BLEDevice central, BLECharacteristic characteristic) {
// central wrote new value to characteristic, update LED
Serial.print("Characteristic event, written: ");
if (switchCharacteristic.value()) {
Serial.println("LED on");
digitalWrite(ledPin, HIGH);
} else {
Serial.println("LED off");
digitalWrite(ledPin, LOW);
}
}
```
### `bleCharacteristic.broadcast()`
Broadcast the characteristics value as service data when advertising.
#### Syntax
```
bleCharacteristic.broadcast()
```
#### Parameters
None
#### Returns
- 1 on success,
- 0 on failure
#### Example
```arduino
// create button characteristic and allow remote device to get notifications
BLEByteCharacteristic buttonCharacteristic("19B10012-E8F2-537E-4F6C-D104768A1214", BLERead | BLENotify | BLEBroadcast);
buttonCharacteristic.broadcast();
```
### `bleCharacteristic.written()`
Query if the characteristic value has been written by another Bluetooth® Low Energy device.
#### Syntax
```
bleCharacteristic.written()
```
#### Parameters
None
#### Returns
- **true** if the characteristic value has been written by another Bluetooth® Low Energy device,
- **false** otherwise
#### Example
```arduino
// Bluetooth® Low Energy LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
// listen for Bluetooth® Low Energy peripherals to connect:
BLEDevice central = BLE.central();
// if a central is connected to peripheral:
if (central) {
Serial.print("Connected to central: ");
// print the central's MAC address:
Serial.println(central.address());
// while the central is still connected to peripheral:
while (central.connected()) {
// if the remote device wrote to the characteristic,
// use the value to control the LED:
if (switchCharacteristic.written()) {
if (switchCharacteristic.value()) { // any value other than 0
Serial.println("LED on");
digitalWrite(ledPin, HIGH); // will turn the LED on
} else { // a 0 value
Serial.println(F("LED off"));
digitalWrite(ledPin, LOW); // will turn the LED off
}
}
}
// when the central disconnects, print it out:
Serial.print(F("Disconnected from central: "));
Serial.println(central.address());
}
```
### `bleCharacteristic.subscribed()`
Query if the characteristic has been subscribed to by another Bluetooth® Low Energy device.
#### Syntax
```
bleCharacteristic.subscribed()
```
#### Parameters
None
#### Returns
- **true** if the characteristic value has been subscribed to by another Bluetooth® Low Energy device,
- **false** otherwise
#### Example
```arduino
// Bluetooth® Low Energy Battery Level Characteristic
BLEUnsignedCharCharacteristic batteryLevelChar("2A19", // standard 16-bit characteristic UUID
BLERead | BLENotify); // remote clients will be able to get notifications if this characteristic changes
if (batteryLevelChar.subscribed()) {
// set a new value , that well be pushed to subscribed Bluetooth® Low Energy devices
batteryLevelChar.writeValue(0xab);
}
```
### `bleCharacteristic.addDescriptor()`
Add a BLEDescriptor to the characteristic.
#### Syntax
```
bleCharacteristic.addDescriptor(bleDescriptor)
```
#### Parameters
- **bleDescriptor**: descriptor to add to the characteristic
#### Returns
Nothing
#### Example
```arduino
// Bluetooth® Low Energy Battery Level Characteristic
BLEUnsignedCharCharacteristic batteryLevelChar("2A19", // standard 16-bit characteristic UUID
BLERead | BLENotify); // remote clients will be able to get notifications if this characteristic changes
BLEDescriptor batteryLevelDescriptor("2901", "millis");
batteryLevelChar.addDescriptor(batteryLevelDescriptor);
```
### `bleCharacteristic.descriptorCount()`
Query the number of Bluetooth® Low Energy descriptors discovered for the characteristic.
#### Syntax
```
bleCharacteristic.descriptorCount()
```
#### Parameters
None
#### Returns
- The **number of Bluetooth® Low Energy descriptors** discovered for the characteristic
#### Example
```arduino
// loop the descriptors of the characteristic and explore each
for (int i = 0; i < characteristic.descriptorCount(); i++) {
BLEDescriptor descriptor = characteristic.descriptor(i);
// ...
}
```
### `bleCharacteristic.hasDescriptor()`
Check if a characteristic has a particular descriptor.
#### Syntax
```
bleCharacteristic.hasDescriptor(uuid)
bleCharacteristic.hasDescriptor(uuid, index)
```
#### Parameters
- **index**: index of descriptor
- **uuid**: uuid (as a **String**)
#### Returns
- **true**, if the characteristic has a matching descriptor,
- otherwise **false**.
#### Example
```arduino
if (characteristic.hasDescriptor("2901")) {
Serial.println("characteristic has description descriptor");
}
```
### `bleCharacteristic.descriptor()`
Get a BLEDescriptor that represents a characteristics Bluetooth® Low Energy descriptor.
#### Syntax
```
bleCharacteristic.descriptor(index)
bleCharacteristic.descriptor(uuid)
bleCharacteristic.descriptor(uuid, index)
```
#### Parameters
- **index**: index of descriptor
- **uuid**: uuid (as a **String**)
#### Returns
- BLEDescriptor that represents a characteristics Bluetooth® Low Energy descriptor
#### Example
```arduino
if (characteristic.hasDescriptor("2901")) {
Serial.println("characteristic has description descriptor");
}
```
### `bleCharacteristic.canRead()`
Query if a Bluetooth® Low Energy characteristic is readable.
#### Syntax
```
bleCharacteristic.canRead()
```
#### Parameters
None
#### Returns
- **true**, if characteristic is readable,
- **false** otherwise
#### Example
```arduino
if (characteristic.canRead("2901")) {
Serial.println("characteristic is readable");
}
```
read
Perform a read request for the characteristic.
#### Syntax
```
bleCharacteristic.read()
```
#### Parameters
None
#### Returns
- **true**, if successful,
- **false** on failure
#### Example
```arduino
if (characteristic.read()) {
Serial.println("characteristic value read");
// ...
} else {
Serial.println("error reading characteristic value");
}
```
### `bleCharacteristic.canWrite()`
Query if a Bluetooth® Low Energy characteristic is writable.
#### Syntax
```
bleCharacteristic.canWrite()
```
#### Parameters
None
#### Returns
- **true**, if characteristic is writable,
- **false** otherwise
#### Example
```arduino
if (characteristic.canWrite()) {
Serial.println("characteristic is writable");
}
```
### `bleCharacteristic.canSubscribe()`
Query if a Bluetooth® Low Energy characteristic is subscribable.
#### Syntax
```
bleCharacteristic.canSubscribe()
```
#### Parameters
None
#### Returns
- **true**, if characteristic is subscribable,
- **false** otherwise
#### Example
```arduino
if (characteristic.canSubscribe()) {
Serial.println("characteristic is subscribable");
}
```
### `bleCharacteristic.subscribe()`
Subscribe to a Bluetooth® Low Energy characteristics notification or indications.
#### Syntax
```
bleCharacteristic.subscribe()
```
#### Parameters
None
#### Returns
- **true**, on success,
- **false** on failure
#### Example
```arduino
// ...
// retrieve the simple key characteristic
BLECharacteristic simpleKeyCharacteristic = peripheral.characteristic("ffe1");
// subscribe to the simple key characteristic
Serial.println("Subscribing to simple key characteristic ...");
if (!simpleKeyCharacteristic) {
Serial.println("no simple key characteristic found!");
peripheral.disconnect();
return;
} else if (!simpleKeyCharacteristic.canSubscribe()) {
Serial.println("simple key characteristic is not subscribable!");
peripheral.disconnect();
return;
} else if (!simpleKeyCharacteristic.subscribe()) {
Serial.println("subscription failed!");
peripheral.disconnect();
return;
}
// ...
```
### `bleCharacteristic.canUnsubscribe()`
Query if a Bluetooth® Low Energy characteristic is unsubscribable.
#### Syntax
```
bleCharacteristic.canUnsubscribe()
```
#### Parameters
None
#### Returns
- **true**, if characteristic is unsubscribable,
- **false** otherwise
#### Example
```arduino
if (characteristic.canUnsubscribe()) {
Serial.println("characteristic is unsubscribable");
}
```
### `bleCharacteristic.unsubscribe()`
Unsubscribe to a Bluetooth® Low Energy characteristics notifications or indications.
#### Syntax
```
bleCharacteristic.unsubscribe()
```
#### Parameters
None
#### Returns
- **true**, on success,
- **false** on failure
#### Example
```arduino
// ...
// retrieve the simple key characteristic
BLECharacteristic simpleKeyCharacteristic = peripheral.characteristic("ffe1");
// subscribe to the simple key characteristic
Serial.println("Subscribing to simple key characteristic ...");
if (!simpleKeyCharacteristic) {
Serial.println("no simple key characteristic found!");
peripheral.disconnect();
return;
} else if (!simpleKeyCharacteristic.canSubscribe()) {
Serial.println("simple key characteristic is not subscribable!");
peripheral.disconnect();
return;
} else if (!simpleKeyCharacteristic.subscribe()) {
Serial.println("subscription failed!");
peripheral.disconnect();
return;
}
// ...
simpleKeyCharacteristic.unsubscribe();
```
### `bleCharacteristic.valueUpdated()`
Has the characteristics value been updated via a notification or indication.
#### Syntax
```
bleCharacteristic.valueUpdated()
```
#### Parameters
None
#### Returns
- **true**, if the characteristics value been updated via a notification or indication
#### Example
```arduino
while (peripheral.connected()) {
// while the peripheral is connected
// check if the value of the simple key characteristic has been updated
if (simpleKeyCharacteristic.valueUpdated()) {
// yes, get the value, characteristic is 1 byte so use byte value
byte value = 0;
simpleKeyCharacteristic.readValue(value);
if (value & 0x01) {
// first bit corresponds to the right button
Serial.println("Right button pressed");
}
if (value & 0x02) {
// second bit corresponds to the left button
Serial.println("Left button pressed");
}
}
}
```
## BLEDescriptor Class
Used to describe a characteristic the board offers
### `BLEDescriptor()`
Create a new Bluetooth® Low Energy descriptor.
#### Syntax
```
BLEDescriptor(uuid, value, valueSize)
BLEDescriptor(uuid, stringValue)
```
#### Parameters
- **uuid**: 16-bit or 128-bit UUID in string format
- **value**: byte array value
- **valueSize**: size of byte array value
- **stringValue**: value as a string
#### Returns
- New **BLEDescriptor** with the specified **UUID** and value
#### Example
```arduino
BLEDescriptor millisLabelDescriptor("2901", "millis");
```
### `bleDescriptor.uuid()`
Query the UUID of the specified BLEDescriptor.
#### Syntax
```
bleDescriptor.uuid()
```
#### Parameters
None
#### Returns
- **UUID** of the Bluetooth® Low Energy descriptor (as a String).
#### Example
```arduino
BLEDescriptor millisLabelDescriptor("2901", "millis");
Serial.print("millis label descriptor UUID = ");
Serial.println(millisLabelDescriptor.uuid());
```
### `bleDescriptor.valueSize()`
Query the value size of the specified BLEDescriptor.
#### Syntax
```
bleDescriptor.valueSize()
```
#### Parameters
None
#### Returns
- **Value size** (in bytes) of the Bluetooth® Low Energy descriptor.
#### Example
```arduino
BLEDescriptor millisLabelDescriptor("2901", "millis");
Serial.print("millis label descriptor value size = ");
Serial.println(millisLabelDescriptor.valueSize());
```
### `bleDescriptor.valueLength()`
Query the length, in bytes, of the descriptor current value.
#### Syntax
```
bleDescriptor.valueLength()
```
#### Parameters
None
#### Returns
- **Length of descriptor** value in bytes.
#### Example
```arduino
// read the descriptor value
descriptor.read();
// print out the value of the descriptor
Serial.print(", value 0x");
printData(descriptor.value(), descriptor.valueLength());
// ...
void printData(const unsigned char data[], int length) {
for (int i = 0; i < length; i++) {
unsigned char b = data[i];
if (b < 16) {
Serial.print("0");
}
Serial.print(b, HEX);
}
}
```
### `bleDescriptor.value()`
Query the value of the specified BLEDescriptor.
#### Syntax
```
bleDescriptor.value()
```
#### Parameters
None
#### Returns
- Value byte array of the **BLE descriptor**.
#### Example
```arduino
BLEDescriptor millisLabelDescriptor("2901", "millis");
int descriptorValueSize = millisLabelDescriptor.valueSize();
byte descriptorValue[descriptorValueSize];
for (int i = 0; i < descriptorValueSize; i++) {
descriptorValue[i] = millisLabelDescriptor.value()[i];
}
```
### `bleDescriptor.readValue()`
Read the current value of the descriptor. If the descriptor is on a remote device, a read request will be sent.
#### Syntax
```
bleDescriptor.readValue(buffer, length)
bleDescriptor.readValue(value)
```
#### Parameters
- **buffer**: byte array to read value into
- **length**: size of buffer argument in bytes
- **value**: variable to read value into (by reference)
#### Returns
- **Number of bytes** read
#### Example
```arduino
byte value = 0;
// get the value, descriptor is 1 byte so use byte value
descriptor.readValue(value);
```
### `bleDescriptor.read()`
Perform a read request for the descriptor.
#### Syntax
```
bleDescriptor.read()
```
#### Parameters
None
#### Returns
- **true**, if successful,
- **false** on failure
#### Example
```arduino
if (descriptor.read()) {
Serial.println("descriptor value read");
// ...
} else {
Serial.println("error reading descriptor value");
}
```
================================================
FILE: docs/readme.md
================================================
# ArduinoBLE library
This library supports all the Arduino boards that have the hardware enabled for Bluetooth® Low Energy and Bluetooth® 4.0 and above; these include Nano 33 BLE, Arduino NANO 33 IoT, Uno WiFi Rev2, MKR WiFi 1010, Nicla Sense ME.
To use this library
``#include <ArduinoBLE.h>``
## A quick introduction to BLE
Bluetooth® 4.0 includes both traditional Bluetooth®, now labeled "Bluetooth® Classic", and the Bluetooth® Low Energy. Bluetooth® Low Energy is optimized for low power use at low data rates, and was designed to operate from simple lithium coin cell batteries.
Unlike standard Bluetooth® communication basically based on an asynchronous serial connection (UART) a Bluetooth® LE radio acts like a community bulletin board. The computers that connect to it are like community members that read the bulletin board. Each radio acts as either the bulletin board or the reader. If your radio is a bulletin board (called a peripheral device in Bluetooth® LE parlance) it posts data for all radios in the community to read. If your radio is a reader (called a central device in Bluetooth LE terms) it reads from any of the bulletin boards (peripheral devices) that have information about which it cares. You can also think of peripheral devices as the servers in a client-server transaction, because they contain the information that reader radios ask for. Similarly, central devices are the clients of the Bluetooth® LE world because they read information available from the peripherals.

Think of a Bluetooth® LE peripheral device as a bulletin board and central devices as viewers of the board. Central devices view the services, get the data, then move on. Each transaction is quick (a few milliseconds), so multiple central devices can get data from one peripheral.
The information presented by a peripheral is structured as **services**, each of which is subdivided into **characteristics**. You can think of services as the notices on a bulletin board, and characteristics as the individual paragraphs of those notices. If you're a peripheral device, you just update each service characteristic when it needs updating and don't worry about whether the central devices read them or not. If you're a central device, you connect to the peripheral then read the boxes you want. If a given characteristic is readable and writable, then the peripheral and central can both change it.
## Notify
The Bluetooth® LE specification includes a mechanism known as **notify** that lets you know when data's changed. When notify on a characteristic is enabled and the sender writes to it, the new value is automatically sent to the receiver, without the receiver explicitly issuing a read command. This is commonly used for streaming data such as accelerometer or other sensor readings. There's a variation on this specification called **indicate** which works similarly, but in the indicate specification, the reader sends an acknowledgment of the pushed data.
The client-server structure of Bluetooth® LE, combined with the notify characteristic, is generally called a **publish-and-subscribe model**.
## Update a characteristic
Your peripheral should update characteristics when there's a significant change to them. For example, when a switch changes from off to on, update its characteristic. When an analog sensor changes by a significant amount, update its characteristic.
Just as with writing to a characteristic, you could update your characteristics on a regular interval, but this wastes processing power and energy if the characteristic has not changed.
## Central and Peripheral Devices
**Central** devices are **clients**. They read and write data from peripheral devices. **Peripheral** devices are **servers**. They provide data from sensors as readable characteristics, and provide read/writable characteristics to control actuators like motors, lights, and so forth.
## Services, characteristics, and UUIDs
A Bluetooth® Low Energy peripheral will provide **services**, which in turn provide **characteristics**. You can define your own services, or use standard services (see section 3.4 in the [Assigned Numbers document](https://www.bluetooth.com/specifications/assigned-numbers/)).
Services are identified by unique numbers known as UUIDs. You know about UUIDs from other contexts. Standard services have a 16-bit UUID and custom services have a 128-bit UUID. The ability to define services and characteristics depends on the radio you're using and its firmware.
## Service design patterns
A characteristic value can be up to 512 bytes long. This is a key constraint in designing services. Given this limit, you should consider how best to store data about your sensors and actuators most effectively for your application. The simplest design pattern is to store one sensor or actuator value per characteristic, in ASCII encoded values.
|**Characteristic**|**Value**|
|------------------|---------|
|Accelerometer X|200|
|Accelerometer Y|134|
|Accelerometer Z|150|
This is also the most expensive in memory terms, and would take the longest to read. But it's the simplest for development and debugging.
You could also combine readings into a single characteristic, when a given sensor or actuator has multiple values associated with it.
|**Characteristic**|**Value**|
|------------------|---------|
|Motor Speed, Direction|150,1|
|Accelerometer X, Y, Z|200,133,150|
This is more efficient, but you need to be careful not to exceed the 512-byte limit. The accelerometer characteristic above, for example, takes 11 bytes as an ASCII-encoded string.
## Read/write/notify/indicate
There are 4 things a central device can do with a characteristic:
- **Read:** ask the peripheral to send back the current value of the characteristic. Often used for characteristics that don't change very often, for example characteristics used for configuration, version numbers, etc.
- **Write:** modify the value of the characteristic. Often used for things that are like commands, for example telling the peripheral to turn a motor on or off.
- **Indicate** and **Notify:** ask the peripheral to continuously send updated values of the characteristic, without the central having to constantly ask for it.
## Advertising and GAP
BLE devices let other devices know that they exist by advertising using the **General Advertising Profile (GAP)**. Advertising packets can contain a device name, some other information, and also a list of the services it provides.
Advertising packets have a limited size. You will only be able to fit a single 128-bit service UUID in the packet. Make sure the device name is not too long, or you won't even be able to fit that.
You can provide additional services that are not advertised. Central devices will learn about these through the connection/bonding process. Non-advertised services cannot be used to discover devices, though. Sometimes this is not an issue. For example, you may have a custom peripheral device with a custom service, but in your central device app you may know that it also provides the Battery Service and other services.
## GATT
The Bluetooth LE protocol operates on multiple layers. **General Attribute Profile (GATT)** is the layer that defines services and characteristics and enables read/write/notify/indicate operations on them. When reading more about GATT, you may encounter GATT concepts of a "server" and "client". These don't always correspond to central and peripherals. In most cases, though, the peripheral is the GATT server (since it provides the services and characteristics), while the central is the GATT client.
## Library structure
As the library enables multiple types of functionality, there are a number of different classes.
- `BLE` used to enable the Bluetooth® Low Energy module.
- `BLEDevice` used to get information about the devices connected or discovered while scanning.
- `BLEService` used to enable the services board provides or interact with services a remote board provides.
- `BLECharacteristic` used to enable the characteristics board offers in a service or interact with characteristics a remote board provides.
- `BLEDescriptor` used to describe a characteristic the board offers.
================================================
FILE: examples/Central/LedControl/LedControl.ino
================================================
/*
LED Control
This example scans for Bluetooth® Low Energy peripherals until one with the advertised service
"19b10000-e8f2-537e-4f6c-d104768a1214" UUID is found. Once discovered and connected,
it will remotely control the Bluetooth® Low Energy peripheral's LED, when the button is pressed or released.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
- Button with pull-up resistor connected to pin 2.
You can use it with another board that is compatible with this library and the
Peripherals -> LED example.
This example code is in the public domain.
*/
#include <ArduinoBLE.h>
// variables for button
const int buttonPin = 2;
int oldButtonState = LOW;
void setup() {
Serial.begin(9600);
while (!Serial);
// configure the button pin as input
pinMode(buttonPin, INPUT);
// initialize the Bluetooth® Low Energy hardware
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("Bluetooth® Low Energy Central - LED control");
// start scanning for peripherals
BLE.scanForUuid("19b10000-e8f2-537e-4f6c-d104768a1214");
}
void loop() {
// check if a peripheral has been discovered
BLEDevice peripheral = BLE.available();
if (peripheral) {
// discovered a peripheral, print out address, local name, and advertised service
Serial.print("Found ");
Serial.print(peripheral.address());
Serial.print(" '");
Serial.print(peripheral.localName());
Serial.print("' ");
Serial.print(peripheral.advertisedServiceUuid());
Serial.println();
if (peripheral.localName() != "LED") {
return;
}
// stop scanning
BLE.stopScan();
controlLed(peripheral);
// peripheral disconnected, start scanning again
BLE.scanForUuid("19b10000-e8f2-537e-4f6c-d104768a1214");
}
}
void controlLed(BLEDevice peripheral) {
// connect to the peripheral
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
// retrieve the LED characteristic
BLECharacteristic ledCharacteristic = peripheral.characteristic("19b10001-e8f2-537e-4f6c-d104768a1214");
if (!ledCharacteristic) {
Serial.println("Peripheral does not have LED characteristic!");
peripheral.disconnect();
return;
} else if (!ledCharacteristic.canWrite()) {
Serial.println("Peripheral does not have a writable LED characteristic!");
peripheral.disconnect();
return;
}
while (peripheral.connected()) {
// while the peripheral is connected
// read the button pin
int buttonState = digitalRead(buttonPin);
if (oldButtonState != buttonState) {
// button changed
oldButtonState = buttonState;
if (buttonState) {
Serial.println("button pressed");
// button is pressed, write 0x01 to turn the LED on
ledCharacteristic.writeValue((byte)0x01);
} else {
Serial.println("button released");
// button is released, write 0x00 to turn the LED off
ledCharacteristic.writeValue((byte)0x00);
}
}
}
Serial.println("Peripheral disconnected");
}
================================================
FILE: examples/Central/PeripheralExplorer/PeripheralExplorer.ino
================================================
/*
Peripheral Explorer
This example scans for Bluetooth® Low Energy peripherals until one with a particular name ("LED")
is found. Then connects, and discovers + prints all the peripheral's attributes.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
You can use it with another board that is compatible with this library and the
Peripherals -> LED example.
This example code is in the public domain.
*/
#include <ArduinoBLE.h>
void setup() {
Serial.begin(9600);
while (!Serial);
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("Bluetooth® Low Energy Central - Peripheral Explorer");
// start scanning for peripherals
BLE.scan();
}
void loop() {
// check if a peripheral has been discovered
BLEDevice peripheral = BLE.available();
if (peripheral) {
// discovered a peripheral, print out address, local name, and advertised service
Serial.print("Found ");
Serial.print(peripheral.address());
Serial.print(" '");
Serial.print(peripheral.localName());
Serial.print("' ");
Serial.print(peripheral.advertisedServiceUuid());
Serial.println();
// see if peripheral is a LED
if (peripheral.localName() == "LED") {
// stop scanning
BLE.stopScan();
explorerPeripheral(peripheral);
// peripheral disconnected, we are done
while (1) {
// do nothing
}
}
}
}
void explorerPeripheral(BLEDevice peripheral) {
// connect to the peripheral
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
// read and print device name of peripheral
Serial.println();
Serial.print("Device name: ");
Serial.println(peripheral.deviceName());
Serial.print("Appearance: 0x");
Serial.println(peripheral.appearance(), HEX);
Serial.println();
// loop the services of the peripheral and explore each
for (int i = 0; i < peripheral.serviceCount(); i++) {
BLEService service = peripheral.service(i);
exploreService(service);
}
Serial.println();
// we are done exploring, disconnect
Serial.println("Disconnecting ...");
peripheral.disconnect();
Serial.println("Disconnected");
}
void exploreService(BLEService service) {
// print the UUID of the service
Serial.print("Service ");
Serial.println(service.uuid());
// loop the characteristics of the service and explore each
for (int i = 0; i < service.characteristicCount(); i++) {
BLECharacteristic characteristic = service.characteristic(i);
exploreCharacteristic(characteristic);
}
}
void exploreCharacteristic(BLECharacteristic characteristic) {
// print the UUID and properties of the characteristic
Serial.print("\tCharacteristic ");
Serial.print(characteristic.uuid());
Serial.print(", properties 0x");
Serial.print(characteristic.properties(), HEX);
// check if the characteristic is readable
if (characteristic.canRead()) {
// read the characteristic value
characteristic.read();
if (characteristic.valueLength() > 0) {
// print out the value of the characteristic
Serial.print(", value 0x");
printData(characteristic.value(), characteristic.valueLength());
}
}
Serial.println();
// loop the descriptors of the characteristic and explore each
for (int i = 0; i < characteristic.descriptorCount(); i++) {
BLEDescriptor descriptor = characteristic.descriptor(i);
exploreDescriptor(descriptor);
}
}
void exploreDescriptor(BLEDescriptor descriptor) {
// print the UUID of the descriptor
Serial.print("\t\tDescriptor ");
Serial.print(descriptor.uuid());
// read the descriptor value
descriptor.read();
// print out the value of the descriptor
Serial.print(", value 0x");
printData(descriptor.value(), descriptor.valueLength());
Serial.println();
}
void printData(const unsigned char data[], int length) {
for (int i = 0; i < length; i++) {
unsigned char b = data[i];
if (b < 16) {
Serial.print("0");
}
Serial.print(b, HEX);
}
}
================================================
FILE: examples/Central/Scan/Scan.ino
================================================
/*
Scan
This example scans for Bluetooth® Low Energy peripherals and prints out their advertising details:
address, local name, advertised service UUID's.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
This example code is in the public domain.
*/
#include <ArduinoBLE.h>
void setup() {
Serial.begin(9600);
while (!Serial);
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("Bluetooth® Low Energy Central scan");
// start scanning for peripheral
BLE.scan();
}
void loop() {
// check if a peripheral has been discovered
BLEDevice peripheral = BLE.available();
if (peripheral) {
// discovered a peripheral
Serial.println("Discovered a peripheral");
Serial.println("-----------------------");
// print address
Serial.print("Address: ");
Serial.println(peripheral.address());
// print the local name, if present
if (peripheral.hasLocalName()) {
Serial.print("Local Name: ");
Serial.println(peripheral.localName());
}
// print the advertised service UUIDs, if present
if (peripheral.hasAdvertisedServiceUuid()) {
Serial.print("Service UUIDs: ");
for (int i = 0; i < peripheral.advertisedServiceUuidCount(); i++) {
Serial.print(peripheral.advertisedServiceUuid(i));
Serial.print(" ");
}
Serial.println();
}
// print the RSSI
Serial.print("RSSI: ");
Serial.println(peripheral.rssi());
Serial.println();
}
}
================================================
FILE: examples/Central/ScanCallback/ScanCallback.ino
================================================
/*
Scan Callback
This example scans for Bluetooth® Low Energy peripherals and prints out their advertising details:
address, local name, advertised service UUIDs. Unlike the Scan example, it uses
the callback style APIs and disables filtering so the peripheral discovery is
reported for every single advertisement it makes.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
This example code is in the public domain.
*/
#include <ArduinoBLE.h>
void setup() {
Serial.begin(9600);
while (!Serial);
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("Bluetooth® Low Energy Central scan callback");
// set the discovered event handle
BLE.setEventHandler(BLEDiscovered, bleCentralDiscoverHandler);
// start scanning for peripherals with duplicates
BLE.scan(true);
}
void loop() {
// poll the central for events
BLE.poll();
}
void bleCentralDiscoverHandler(BLEDevice peripheral) {
// discovered a peripheral
Serial.println("Discovered a peripheral");
Serial.println("-----------------------");
// print address
Serial.print("Address: ");
Serial.println(peripheral.address());
// print the local name, if present
if (peripheral.hasLocalName()) {
Serial.print("Local Name: ");
Serial.println(peripheral.localName());
}
// print the advertised service UUIDs, if present
if (peripheral.hasAdvertisedServiceUuid()) {
Serial.print("Service UUIDs: ");
for (int i = 0; i < peripheral.advertisedServiceUuidCount(); i++) {
Serial.print(peripheral.advertisedServiceUuid(i));
Serial.print(" ");
}
Serial.println();
}
// print the RSSI
Serial.print("RSSI: ");
Serial.println(peripheral.rssi());
Serial.println();
}
================================================
FILE: examples/Central/SensorTagButton/SensorTagButton.ino
================================================
/*
SensorTag Button
This example scans for Bluetooth® Low Energy peripherals until a TI SensorTag is discovered.
It then connects to it, discovers the attributes of the 0xffe0 service,
subscribes to the Simple Key Characteristic (UUID 0xffe1). When a button is
pressed on the SensorTag a notification is received and the button state is
outputted to the Serial Monitor when one is pressed.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
- TI SensorTag
This example code is in the public domain.
*/
#include <ArduinoBLE.h>
void setup() {
Serial.begin(9600);
while (!Serial);
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("Bluetooth® Low Energy Central - SensorTag button");
Serial.println("Make sure to turn on the device.");
// start scanning for peripheral
BLE.scan();
}
void loop() {
// check if a peripheral has been discovered
BLEDevice peripheral = BLE.available();
if (peripheral) {
// discovered a peripheral, print out address, local name, and advertised service
Serial.print("Found ");
Serial.print(peripheral.address());
Serial.print(" '");
Serial.print(peripheral.localName());
Serial.print("' ");
Serial.print(peripheral.advertisedServiceUuid());
Serial.println();
// Check if the peripheral is a SensorTag, the local name will be:
// "CC2650 SensorTag"
if (peripheral.localName() == "CC2650 SensorTag") {
// stop scanning
BLE.stopScan();
monitorSensorTagButtons(peripheral);
// peripheral disconnected, start scanning again
BLE.scan();
}
}
}
void monitorSensorTagButtons(BLEDevice peripheral) {
// connect to the peripheral
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering service 0xffe0 ...");
if (peripheral.discoverService("ffe0")) {
Serial.println("Service discovered");
} else {
Serial.println("Attribute discovery failed.");
peripheral.disconnect();
while (1);
return;
}
// retrieve the simple key characteristic
BLECharacteristic simpleKeyCharacteristic = peripheral.characteristic("ffe1");
// subscribe to the simple key characteristic
Serial.println("Subscribing to simple key characteristic ...");
if (!simpleKeyCharacteristic) {
Serial.println("no simple key characteristic found!");
peripheral.disconnect();
return;
} else if (!simpleKeyCharacteristic.canSubscribe()) {
Serial.println("simple key characteristic is not subscribable!");
peripheral.disconnect();
return;
} else if (!simpleKeyCharacteristic.subscribe()) {
Serial.println("subscription failed!");
peripheral.disconnect();
return;
} else {
Serial.println("Subscribed");
Serial.println("Press the right and left buttons on your SensorTag.");
}
while (peripheral.connected()) {
// while the peripheral is connected
// check if the value of the simple key characteristic has been updated
if (simpleKeyCharacteristic.valueUpdated()) {
// yes, get the value, characteristic is 1 byte so use byte value
byte value = 0;
simpleKeyCharacteristic.readValue(value);
if (value & 0x01) {
// first bit corresponds to the right button
Serial.println("Right button pressed");
}
if (value & 0x02) {
// second bit corresponds to the left button
Serial.println("Left button pressed");
}
}
}
Serial.println("SensorTag disconnected!");
}
================================================
FILE: examples/Peripheral/Advertising/EnhancedAdvertising/EnhancedAdvertising.ino
================================================
#include <ArduinoBLE.h>
BLEService myService("fff0");
BLEIntCharacteristic myCharacteristic("fff1", BLERead | BLEBroadcast);
// Advertising parameters should have a global scope. Do NOT define them in 'setup' or in 'loop'
const uint8_t manufactData[4] = {0x01, 0x02, 0x03, 0x04};
const uint8_t serviceData[3] = {0x00, 0x01, 0x02};
void setup() {
Serial.begin(9600);
while (!Serial);
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
myService.addCharacteristic(myCharacteristic);
BLE.addService(myService);
// Build scan response data packet
BLEAdvertisingData scanData;
// Set parameters for scan response packet
scanData.setLocalName("Test enhanced advertising");
// Copy set parameters in the actual scan response packet
BLE.setScanResponseData(scanData);
// Build advertising data packet
BLEAdvertisingData advData;
// Set parameters for advertising packet
advData.setManufacturerData(0x004C, manufactData, sizeof(manufactData));
advData.setAdvertisedService(myService);
advData.setAdvertisedServiceData(0xfff0, serviceData, sizeof(serviceData));
// Copy set parameters in the actual advertising packet
BLE.setAdvertisingData(advData);
BLE.advertise();
Serial.println("advertising ...");
}
void loop() {
BLE.poll();
}
================================================
FILE: examples/Peripheral/Advertising/RawDataAdvertising/RawDataAdvertising.ino
================================================
#include <ArduinoBLE.h>
BLEService myService("fff0");
BLEIntCharacteristic myCharacteristic("fff1", BLERead | BLEBroadcast);
// Advertising parameters should have a global scope. Do NOT define them in 'setup' or in 'loop'
const uint8_t completeRawAdvertisingData[] = {0x02,0x01,0x06,0x09,0xff,0x01,0x01,0x00,0x01,0x02,0x03,0x04,0x05};
void setup() {
Serial.begin(9600);
while (!Serial);
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
myService.addCharacteristic(myCharacteristic);
BLE.addService(myService);
// Build advertising data packet
BLEAdvertisingData advData;
// If a packet has a raw data parameter, then all the other parameters of the packet will be ignored
advData.setRawData(completeRawAdvertisingData, sizeof(completeRawAdvertisingData));
// Copy set parameters in the actual advertising packet
BLE.setAdvertisingData(advData);
// Build scan response data packet
BLEAdvertisingData scanData;
scanData.setLocalName("Test advertising raw data");
// Copy set parameters in the actual scan response packet
BLE.setScanResponseData(scanData);
BLE.advertise();
Serial.println("advertising ...");
}
void loop() {
BLE.poll();
}
================================================
FILE: examples/Peripheral/BatteryMonitor/BatteryMonitor.ino
================================================
/*
Battery Monitor
This example creates a Bluetooth® Low Energy peripheral with the standard battery service and
level characteristic. The A0 pin is used to calculate the battery level.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
You can use a generic Bluetooth® Low Energy central app, like LightBlue (iOS and Android) or
nRF Connect (Android), to interact with the services and characteristics
created in this sketch.
This example code is in the public domain.
*/
#include <ArduinoBLE.h>
// Bluetooth® Low Energy Battery Service
BLEService batteryService("180F");
// Bluetooth® Low Energy Battery Level Characteristic
BLEUnsignedCharCharacteristic batteryLevelChar("2A19", // standard 16-bit characteristic UUID
BLERead | BLENotify); // remote clients will be able to get notifications if this characteristic changes
int oldBatteryLevel = 0; // last battery level reading from analog input
long previousMillis = 0; // last time the battery level was checked, in ms
void setup() {
Serial.begin(9600); // initialize serial communication
while (!Serial);
pinMode(LED_BUILTIN, OUTPUT); // initialize the built-in LED pin to indicate when a central is connected
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
/* Set a local name for the Bluetooth® Low Energy device
This name will appear in advertising packets
and can be used by remote devices to identify this Bluetooth® Low Energy device
The name can be changed but maybe be truncated based on space left in advertisement packet
*/
BLE.setLocalName("BatteryMonitor");
BLE.setAdvertisedService(batteryService); // add the service UUID
batteryService.addCharacteristic(batteryLevelChar); // add the battery level characteristic
BLE.addService(batteryService); // Add the battery service
batteryLevelChar.writeValue(oldBatteryLevel); // set initial value for this characteristic
/* Start advertising Bluetooth® Low Energy. It will start continuously transmitting Bluetooth® Low Energy
advertising packets and will be visible to remote Bluetooth® Low Energy central devices
until it receives a new connection */
// start advertising
BLE.advertise();
Serial.println("Bluetooth® device active, waiting for connections...");
}
void loop() {
// wait for a Bluetooth® Low Energy central
BLEDevice central = BLE.central();
// if a central is connected to the peripheral:
if (central) {
Serial.print("Connected to central: ");
// print the central's BT address:
Serial.println(central.address());
// turn on the LED to indicate the connection:
digitalWrite(LED_BUILTIN, HIGH);
// check the battery level every 200 ms
// while the central is connected:
while (central.connected()) {
long currentMillis = millis();
// if 200 ms have passed, check the battery level:
if (currentMillis - previousMillis >= 200) {
previousMillis = currentMillis;
updateBatteryLevel();
}
}
// when the central disconnects, turn off the LED:
digitalWrite(LED_BUILTIN, LOW);
Serial.print("Disconnected from central: ");
Serial.println(central.address());
}
}
void updateBatteryLevel() {
/* Read the current voltage level on the A0 analog input pin.
This is used here to simulate the charge level of a battery.
*/
int battery = analogRead(A0);
int batteryLevel = map(battery, 0, 1023, 0, 100);
if (batteryLevel != oldBatteryLevel) { // if the battery level has changed
Serial.print("Battery Level % is now: "); // print it
Serial.println(batteryLevel);
batteryLevelChar.writeValue(batteryLevel); // and update the battery level characteristic
oldBatteryLevel = batteryLevel; // save the level for next comparison
}
}
================================================
FILE: examples/Peripheral/ButtonLED/ButtonLED.ino
================================================
/*
Button LED
This example creates a Bluetooth® Low Energy peripheral with service that contains a
characteristic to control an LED and another characteristic that
represents the state of the button.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
- Button connected to pin 4
You can use a generic Bluetooth® Low Energy central app, like LightBlue (iOS and Android) or
nRF Connect (Android), to interact with the services and characteristics
created in this sketch.
This example code is in the public domain.
*/
#include <ArduinoBLE.h>
const int ledPin = LED_BUILTIN; // set ledPin to on-board LED
const int buttonPin = 4; // set buttonPin to digital pin 4
BLEService ledService("19B10010-E8F2-537E-4F6C-D104768A1214"); // create service
// create switch characteristic and allow remote device to read and write
BLEByteCharacteristic ledCharacteristic("19B10011-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
// create button characteristic and allow remote device to get notifications
BLEByteCharacteristic buttonCharacteristic("19B10012-E8F2-537E-4F6C-D104768A1214", BLERead | BLENotify);
void setup() {
Serial.begin(9600);
while (!Serial);
pinMode(ledPin, OUTPUT); // use the LED as an output
pinMode(buttonPin, INPUT); // use button pin as an input
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// set the local name peripheral advertises
BLE.setLocalName("ButtonLED");
// set the UUID for the service this peripheral advertises:
BLE.setAdvertisedService(ledService);
// add the characteristics to the service
ledService.addCharacteristic(ledCharacteristic);
ledService.addCharacteristic(buttonCharacteristic);
// add the service
BLE.addService(ledService);
ledCharacteristic.writeValue(0);
buttonCharacteristic.writeValue(0);
// start advertising
BLE.advertise();
Serial.println("Bluetooth® device active, waiting for connections...");
}
void loop() {
// poll for Bluetooth® Low Energy events
BLE.poll();
// read the current button pin state
char buttonValue = digitalRead(buttonPin);
// has the value changed since the last read
bool buttonChanged = (buttonCharacteristic.value() != buttonValue);
if (buttonChanged) {
// button state changed, update characteristics
ledCharacteristic.writeValue(buttonValue);
buttonCharacteristic.writeValue(buttonValue);
}
if (ledCharacteristic.written() || buttonChanged) {
// update LED, either central has written to characteristic or button state has changed
if (ledCharacteristic.value()) {
Serial.println("LED on");
digitalWrite(ledPin, HIGH);
} else {
Serial.println("LED off");
digitalWrite(ledPin, LOW);
}
}
}
================================================
FILE: examples/Peripheral/CallbackLED/CallbackLED.ino
================================================
/*
Callback LED
This example creates a Bluetooth® Low Energy peripheral with service that contains a
characteristic to control an LED. The callback features of the
library are used.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
You can use a generic Bluetooth® Low Energy central app, like LightBlue (iOS and Android) or
nRF Connect (Android), to interact with the services and characteristics
created in this sketch.
This example code is in the public domain.
*/
#include <ArduinoBLE.h>
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // create service
// create switch characteristic and allow remote device to read and write
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
const int ledPin = LED_BUILTIN; // pin to use for the LED
void setup() {
Serial.begin(9600);
while (!Serial);
pinMode(ledPin, OUTPUT); // use the LED pin as an output
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// set the local name peripheral advertises
BLE.setLocalName("LEDCallback");
// set the UUID for the service this peripheral advertises
BLE.setAdvertisedService(ledService);
// add the characteristic to the service
ledService.addCharacteristic(switchCharacteristic);
// add service
BLE.addService(ledService);
// assign event handlers for connected, disconnected to peripheral
BLE.setEventHandler(BLEConnected, blePeripheralConnectHandler);
BLE.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler);
// assign event handlers for characteristic
switchCharacteristic.setEventHandler(BLEWritten, switchCharacteristicWritten);
// set an initial value for the characteristic
switchCharacteristic.setValue(0);
// start advertising
BLE.advertise();
Serial.println(("Bluetooth® device active, waiting for connections..."));
}
void loop() {
// poll for Bluetooth® Low Energy events
BLE.poll();
}
void blePeripheralConnectHandler(BLEDevice central) {
// central connected event handler
Serial.print("Connected event, central: ");
Serial.println(central.address());
}
void blePeripheralDisconnectHandler(BLEDevice central) {
// central disconnected event handler
Serial.print("Disconnected event, central: ");
Serial.println(central.address());
}
void switchCharacteristicWritten(BLEDevice central, BLECharacteristic characteristic) {
// unused parameters
(void)central;
(void)characteristic;
// central wrote new value to characteristic, update LED
Serial.print("Characteristic event, written: ");
if (switchCharacteristic.value()) {
Serial.println("LED on");
digitalWrite(ledPin, HIGH);
} else {
Serial.println("LED off");
digitalWrite(ledPin, LOW);
}
}
================================================
FILE: examples/Peripheral/EncryptedBatteryMonitor/EncryptedBatteryMonitor.ino
================================================
/*
Battery Monitor
This example creates a BLE peripheral with the standard battery service and
level characteristic. The A0 pin is used to calculate the battery level.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
You can use a generic BLE central app, like LightBlue (iOS and Android) or
nRF Connect (Android), to interact with the services and characteristics
created in this sketch.
This example code is in the public domain.
*/
#include <ArduinoBLE.h>
#define PAIR_BUTTON 3 // button for pairing
#define PAIR_LED 24 // LED used to signal pairing
#define PAIR_LED_ON LOW // Blue LED on Nano BLE has inverted logic
#define PAIR_LED_OFF HIGH // ... so these are inverted as well
#define PAIR_INTERVAL 30000 // interval for pairing after button press in ms
#define CTRL_LED LED_BUILTIN
// BLE Battery Service
BLEService batteryService("180F");
// BLE Battery Level Characteristic
BLEUnsignedCharCharacteristic batteryLevelChar("2A19", // standard 16-bit characteristic UUID
BLERead | BLENotify); // remote clients will be able to get notifications if this characteristic changes
BLEStringCharacteristic stringcharacteristic("183E", BLERead | BLEWrite, 31);
// Add BLEEncryption tag to require pairing. This controls the LED.
BLEUnsignedCharCharacteristic secretValue("2a3F", BLERead | BLEWrite | BLEEncryption);
int oldBatteryLevel = 0; // last battery level reading from analog input
unsigned long previousMillis = 0; // last time the battery level was checked, in ms
unsigned long pairingStarted = 0; // pairing start time when button is pressed
bool wasConnected = 0;
bool acceptOrReject = true;
void setup() {
Serial.begin(9600); // initialize serial communication
while (!Serial);
pinMode(CTRL_LED, OUTPUT); // initialize the built-in LED pin to indicate when a central is connected
pinMode(PAIR_LED, OUTPUT);
pinMode(PAIR_BUTTON, INPUT_PULLUP);
Serial.println("Serial connected");
// Callback function with confirmation code when new device is pairing.
BLE.setDisplayCode([](uint32_t confirmCode){
Serial.println("New device pairing request.");
Serial.print("Confirm code matches pairing device: ");
char code[7];
sprintf(code, "%06d", confirmCode);
Serial.println(code);
});
// Callback to allow accepting or rejecting pairing
BLE.setBinaryConfirmPairing([](){
Serial.print("Should we confirm pairing? ");
delay(5000);
if(acceptOrReject){
acceptOrReject = false;
Serial.println("yes");
return true;
}else{
acceptOrReject = true;
Serial.println("no");
return false;
}
});
// IRKs are keys that identify the true owner of a random mac address.
// Add IRKs of devices you are bonded with.
BLE.setGetIRKs([](uint8_t* nIRKs, uint8_t** BDaddrTypes, uint8_t*** BDAddrs, uint8_t*** IRKs){
// Set to number of devices
*nIRKs = 2;
*BDAddrs = new uint8_t*[*nIRKs];
*IRKs = new uint8_t*[*nIRKs];
*BDaddrTypes = new uint8_t[*nIRKs];
// Set these to the mac and IRK for your bonded devices as printed in the serial console after bonding.
uint8_t device1Mac[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t device1IRK[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t device2Mac[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t device2IRK[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
(*BDaddrTypes)[0] = 0; // Type 0 is for pubc address, type 1 is for static random
(*BDAddrs)[0] = new uint8_t[6];
(*IRKs)[0] = new uint8_t[16];
memcpy((*IRKs)[0] , device1IRK,16);
memcpy((*BDAddrs)[0], device1Mac, 6);
(*BDaddrTypes)[1] = 0;
(*BDAddrs)[1] = new uint8_t[6];
(*IRKs)[1] = new uint8_t[16];
memcpy((*IRKs)[1] , device2IRK,16);
memcpy((*BDAddrs)[1], device2Mac, 6);
return 1;
});
// The LTK is the secret key which is used to encrypt bluetooth traffic
BLE.setGetLTK([](uint8_t* address, uint8_t* LTK){
// address is input
Serial.print("Received request for address: ");
btct.printBytes(address,6);
// Set these to the MAC and LTK of your devices after bonding.
uint8_t device1Mac[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t device1LTK[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t device2Mac[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t device2LTK[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
if(memcmp(device1Mac, address, 6) == 0) {
memcpy(LTK, device1LTK, 16);
return 1;
}else if(memcmp(device2Mac, address, 6) == 0) {
memcpy(LTK, device2LTK, 16);
return 1;
}
return 0;
});
BLE.setStoreIRK([](uint8_t* address, uint8_t* IRK){
Serial.print(F("New device with MAC : "));
btct.printBytes(address,6);
Serial.print(F("Need to store IRK : "));
btct.printBytes(IRK,16);
return 1;
});
BLE.setStoreLTK([](uint8_t* address, uint8_t* LTK){
Serial.print(F("New device with MAC : "));
btct.printBytes(address,6);
Serial.print(F("Need to store LTK : "));
btct.printBytes(LTK,16);
return 1;
});
while(1){
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BT init");
delay(200);
/* Set a local name for the BLE device
This name will appear in advertising packets
and can be used by remote devices to identify this BLE device
The name can be changed but maybe be truncated based on space left in advertisement packet
*/
BLE.setDeviceName("Arduino");
BLE.setLocalName("BatteryMonitor");
BLE.setAdvertisedService(batteryService); // add the service UUID
batteryService.addCharacteristic(batteryLevelChar); // add the battery level characteristic
batteryService.addCharacteristic(stringcharacteristic);
batteryService.addCharacteristic(secretValue);
BLE.addService(batteryService); // Add the battery service
batteryLevelChar.writeValue(oldBatteryLevel); // set initial value for this characteristic
const char* stringCharValue = "string";
stringcharacteristic.writeValue(stringCharValue);
secretValue.writeValue(0);
delay(1000);
// prevent pairing until button is pressed (will show a pairing rejected message)
BLE.setPairable(false);
/* Start advertising BLE. It will start continuously transmitting BLE
advertising packets and will be visible to remote BLE central devices
until it receives a new connection */
// start advertising
if(!BLE.advertise()){
Serial.println("failed to advertise bluetooth.");
BLE.stopAdvertise();
delay(500);
}else{
Serial.println("advertising...");
break;
}
BLE.end();
delay(100);
}
}
void loop() {
// wait for a BLE central
BLEDevice central = BLE.central();
// If button is pressed, allow pairing for 30 sec
if (!BLE.pairable() && digitalRead(PAIR_BUTTON) == LOW){
pairingStarted = millis();
BLE.setPairable(Pairable::ONCE);
Serial.println("Accepting pairing for 30 s");
} else if (BLE.pairable() && millis() > pairingStarted + PAIR_INTERVAL){
BLE.setPairable(false);
Serial.println("No longer accepting pairing");
}
// Make LED blink while pairing is allowed, steady ON when paired
bool led_status = BLE.pairable() ? (millis()%400)<200 : BLE.paired();
digitalWrite(PAIR_LED, led_status ? PAIR_LED_ON : PAIR_LED_OFF);
// if a central is connected to the peripheral:
if (central && central.connected()) {
if (!wasConnected){
wasConnected = true;
Serial.print("Connected to central: ");
// print the central's BT address:
Serial.println(central.address());
}
// check the battery level every 200ms
// while the central is connected:
long currentMillis = millis();
// if 200ms have passed, check the battery level:
if (currentMillis - previousMillis >= 1000) {
previousMillis = currentMillis;
updateBatteryLevel();
digitalWrite(CTRL_LED, secretValue.value()>0 ? HIGH : LOW);
}
} else if (wasConnected){
wasConnected = false;
Serial.print("Disconnected from central: ");
Serial.println(central.address());
}
}
void updateBatteryLevel() {
/* Read the current voltage level on the A0 analog input pin.
This is used here to simulate the charge level of a battery.
*/
int battery = analogRead(A0);
int batteryLevel = map(battery, 0, 1023, 0, 100);
if (batteryLevel != oldBatteryLevel) { // if the battery level has changed
// Serial.print("Battery Level % is now: "); // print it
// Serial.println(batteryLevel);
batteryLevelChar.writeValue(batteryLevel); // and update the battery level characteristic
oldBatteryLevel = batteryLevel; // save the level for next comparison
}
}
================================================
FILE: examples/Peripheral/LED/LED.ino
================================================
/*
LED
This example creates a Bluetooth® Low Energy peripheral with service that contains a
characteristic to control an LED.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
You can use a generic Bluetooth® Low Energy central app, like LightBlue (iOS and Android) or
nRF Connect (Android), to interact with the services and characteristics
created in this sketch.
This example code is in the public domain.
*/
#include <ArduinoBLE.h>
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // Bluetooth® Low Energy LED Service
// Bluetooth® Low Energy LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
const int ledPin = LED_BUILTIN; // pin to use for the LED
void setup() {
Serial.begin(9600);
while (!Serial);
// set LED pin to output mode
pinMode(ledPin, OUTPUT);
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// set advertised local name and service UUID:
BLE.setLocalName("LED");
BLE.setAdvertisedService(ledService);
// add the characteristic to the service
ledService.addCharacteristic(switchCharacteristic);
// add service
BLE.addService(ledService);
// set the initial value for the characteristic:
switchCharacteristic.writeValue(0);
// start advertising
BLE.advertise();
Serial.println("BLE LED Peripheral");
}
void loop() {
// listen for Bluetooth® Low Energy peripherals to connect:
BLEDevice central = BLE.central();
// if a central is connected to peripheral:
if (central) {
Serial.print("Connected to central: ");
// print the central's MAC address:
Serial.println(central.address());
// while the central is still connected to peripheral:
while (central.connected()) {
// if the remote device wrote to the characteristic,
// use the value to control the LED:
if (switchCharacteristic.written()) {
if (switchCharacteristic.value()) { // any value other than 0
Serial.println("LED on");
digitalWrite(ledPin, HIGH); // will turn the LED on
} else { // a 0 value
Serial.println(F("LED off"));
digitalWrite(ledPin, LOW); // will turn the LED off
}
}
}
// when the central disconnects, print it out:
Serial.print(F("Disconnected from central: "));
Serial.println(central.address());
}
}
================================================
FILE: extras/arduino-ble-parser.py
================================================
'''
Convert ArduinoBLE debug files into Btsnoop files ready to be analyzed using wireshark or hcidump
Btsnoop file format reference
https://www.fte.com/WebHelpII/Sodera/Content/Technical_Information/BT_Snoop_File_Format.htm
'''
import os
import argparse
DEBUG = False
parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='inputPath', type=str, required=True, help='input file containing debug log')
parser.add_argument('-o', dest='outputPath', type=str, required=True, help='result file that will contain the btsnoop encoded debug file')
args = parser.parse_args()
# Extract only hci debug messages
def extractHCIDebugPrint(inputPath, outputPath):
inputFile = open(inputPath, 'r')
outputFile = open(outputPath, 'w')
for inputLine in inputFile:
lineItems = inputLine.split()
if (len(lineItems) < 7) or (lineItems[1] != "->") or (lineItems[2] != "HCI"):
if (len(lineItems) < 4) or (lineItems[0] != "HCI") or ((lineItems[3] != "<-") and (lineItems[3] != "->")):
continue
outputFile.write(inputLine)
outputFile.close()
# Return packet in btsnoop format
def buildBinaryPacket(hciMessage, hciDirection, hciType):
commandFlag = 1 if (hciType == "COMMAND" or hciType == "EVENT") else 0
directionFlag = 0 if (hciDirection == "TX") else 1
flagHex = ("0" * 7) + str((commandFlag * 2) + directionFlag)
timestampHex = "0" * 16
packetDropHex = "0" * 8
dataLengthHex = format( (int(len(hciMessage) / 2)), 'x')
packetLengthHex = ("0" * (8 - len(dataLengthHex))) + dataLengthHex
binaryPacket = bytearray.fromhex(packetLengthHex + packetLengthHex + flagHex + packetDropHex + timestampHex + hciMessage)
if DEBUG:
print(len(hciMessage))
print(dataLengthHex)
print(packetLengthHex)
print(flagHex)
print('\n')
return binaryPacket
def buildBinaryHeader():
defaultHeader = "6274736e6f6f700000000001000003ea"
binaryHeader = bytearray.fromhex(defaultHeader)
return binaryHeader
def convertToBtsnoop(inputPath, outputPath):
# Open output file and write the Btsnoop header
outputFile = open(outputPath,'wb')
header = buildBinaryHeader()
outputFile.write(header)
# Open input file containing HCI debug packets
inputFile = open(inputPath, 'r')
for inputLine in inputFile:
lineItems = inputLine.split()
# For a safer script, do not use indexes but look for symbols in the line
baseIndex = lineItems.index("HCI")
hciMessage = lineItems[baseIndex + 4]
hciDirection = lineItems[baseIndex + 2]
hciType = lineItems[baseIndex + 1]
# Build and write the encoded line
btsnoopPacket = buildBinaryPacket(hciMessage, hciDirection, hciType)
outputFile.write(btsnoopPacket)
if DEBUG:
print(hciDirection)
print(hciMessage)
print(hciType)
print('\n')
outputFile.close()
inputPath = args.inputPath
outputPath = args.outputPath
tempFile = "temp-debug-print.txt"
# Run
extractHCIDebugPrint(inputPath,tempFile)
convertToBtsnoop(tempFile, outputPath)
# Delete temp file
os.remove(tempFile)
================================================
FILE: extras/test/.gitignore
================================================
build
### CMake ###
CMakeLists.txt.user
CMakeCache.txt
CMakeFiles
CMakeScripts
Testing
Makefile
cmake_install.cmake
install_manifest.txt
compile_commands.json
CTestTestfile.cmake
_deps
### CMake Patch ###
# External projects
*-prefix/
================================================
FILE: extras/test/CMakeLists.txt
================================================
##########################################################################
set(CMAKE_VERBOSE_MAKEFILE ON)
cmake_minimum_required(VERSION 3.5)
##########################################################################
project(testArduinoBLE)
Include(FetchContent)
FetchContent_Declare(
Catch2
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG v3.4.0
)
FetchContent_MakeAvailable(Catch2)
##########################################################################
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
##########################################################################
set(COMMON_TEST_SRCS
src/test_main.cpp
src/Arduino.cpp
src/util/itoa.c
src/util/TestUtil.cpp
src/util/String.cpp
src/util/Common.cpp
)
set(DUT_SRCS
../../src/utility/BLEUuid.cpp
../../src/BLEDevice.cpp
../../src/BLECharacteristic.cpp
../../src/BLEDescriptor.cpp
../../src/BLEService.cpp
../../src/BLEAdvertisingData.cpp
../../src/utility/ATT.cpp
../../src/utility/GAP.cpp
../../src/utility/HCI.cpp
../../src/utility/GATT.cpp
../../src/utility/L2CAPSignaling.cpp
../../src/utility/keyDistribution.cpp
../../src/utility/bitDescriptions.cpp
../../src/utility/btct.cpp
../../src/local/BLELocalAttribute.cpp
../../src/local/BLELocalCharacteristic.cpp
../../src/local/BLELocalDescriptor.cpp
../../src/local/BLELocalDevice.cpp
../../src/local/BLELocalService.cpp
../../src/remote/BLERemoteAttribute.cpp
../../src/remote/BLERemoteCharacteristic.cpp
../../src/remote/BLERemoteDescriptor.cpp
../../src/remote/BLERemoteDevice.cpp
../../src/remote/BLERemoteService.cpp
../../src/BLEStringCharacteristic.cpp
../../src/BLETypedCharacteristics.cpp
)
set(TEST_TARGET_UUID_SRCS
# Test files
${COMMON_TEST_SRCS}
src/test_uuid/test_uuid.cpp
# DUT files
#${DUT_SRCS}
../../src/utility/BLEUuid.cpp
)
set(TEST_TARGET_DISC_DEVICE_SRCS
# Test files
${COMMON_TEST_SRCS}
src/test_discovered_device/test_discovered_device.cpp
# DUT files
${DUT_SRCS}
# Fake classes files
src/util/HCIFakeTransport.cpp
src/test_discovered_device/FakeGAP.cpp
)
set(TEST_TARGET_ADVERTISING_DATA_SRCS
# Test files
${COMMON_TEST_SRCS}
src/test_advertising_data/test_advertising_data.cpp
src/test_advertising_data/test_service.cpp
src/test_advertising_data/test_local_name.cpp
src/test_advertising_data/test_manufacturer.cpp
# DUT files
${DUT_SRCS}
# Fake classes files
src/util/HCIFakeTransport.cpp
src/test_advertising_data/FakeBLELocalDevice.cpp
)
set(TEST_TARGET_CHARACTERISTIC_SRCS
# Test files
${COMMON_TEST_SRCS}
src/test_characteristic/test_permissions.cpp
src/test_characteristic/test_writeValue.cpp
# DUT files
${DUT_SRCS}
# Fake classes files
src/util/HCIFakeTransport.cpp
src/test_advertising_data/FakeBLELocalDevice.cpp
)
##########################################################################
set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "--coverage")
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "--coverage")
##########################################################################
add_executable(TEST_TARGET_UUID ${TEST_TARGET_UUID_SRCS})
add_executable(TEST_TARGET_DISC_DEVICE ${TEST_TARGET_DISC_DEVICE_SRCS})
add_executable(TEST_TARGET_ADVERTISING_DATA ${TEST_TARGET_ADVERTISING_DATA_SRCS})
add_executable(TEST_TARGET_CHARACTERISTIC_DATA ${TEST_TARGET_CHARACTERISTIC_SRCS})
##########################################################################
include_directories(include)
include_directories(include/util)
include_directories(../../src)
include_directories(../../src/local)
include_directories(../../src/remote)
include_directories(../../src/utility)
target_include_directories(TEST_TARGET_DISC_DEVICE PUBLIC include/test_discovered_device)
target_include_directories(TEST_TARGET_ADVERTISING_DATA PUBLIC include/test_advertising_data)
target_include_directories(TEST_TARGET_CHARACTERISTIC_DATA PUBLIC include/test_advertising_data)
##########################################################################
target_compile_definitions(TEST_TARGET_DISC_DEVICE PUBLIC FAKE_GAP)
target_compile_definitions(TEST_TARGET_ADVERTISING_DATA PUBLIC FAKE_BLELOCALDEVICE)
target_compile_definitions(TEST_TARGET_CHARACTERISTIC_DATA PUBLIC FAKE_BLELOCALDEVICE)
##########################################################################
# Build unit tests as a post build step
add_custom_command(TARGET TEST_TARGET_UUID POST_BUILD
COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/TEST_TARGET_UUID
)
add_custom_command(TARGET TEST_TARGET_DISC_DEVICE POST_BUILD
COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/TEST_TARGET_DISC_DEVICE
)
add_custom_command(TARGET TEST_TARGET_ADVERTISING_DATA POST_BUILD
COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/TEST_TARGET_ADVERTISING_DATA
)
add_custom_command(TARGET TEST_TARGET_CHARACTERISTIC_DATA POST_BUILD
COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/TEST_TARGET_CHARACTERISTIC_DATA
)
##########################################################################
target_link_libraries( TEST_TARGET_UUID Catch2WithMain )
target_link_libraries( TEST_TARGET_DISC_DEVICE Catch2WithMain )
target_link_libraries( TEST_TARGET_ADVERTISING_DATA Catch2WithMain )
target_link_libraries( TEST_TARGET_CHARACTERISTIC_DATA Catch2WithMain )
================================================
FILE: extras/test/include/Arduino.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef TEST_ARDUINO_H_
#define TEST_ARDUINO_H_
/******************************************************************************
INCLUDE
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "String.h"
#include "Stream.h"
#include "itoa.h"
#include "Common.h"
/******************************************************************************
TYPEDEF
******************************************************************************/
typedef arduino::String String;
typedef bool boolean;
#if defined(__cplusplus)
#undef F
// C++11 F replacement declaration
template <typename T1>
auto F(T1&& A)
-> const arduino::__FlashStringHelper*
{
return (const arduino::__FlashStringHelper*)A;
}
#endif
/******************************************************************************
FUNCTION PROTOTYPES
******************************************************************************/
#endif /* TEST_ARDUINO_H_ */
================================================
FILE: extras/test/include/test_advertising_data/FakeBLELocalDevice.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _FAKE_BLELOCALDEVICE_H_
#define _FAKE_BLELOCALDEVICE_H_
#define private public
#define protected public
#include "BLELocalDevice.h"
class FakeBLELocalDevice : public BLELocalDevice {
public:
FakeBLELocalDevice();
virtual ~FakeBLELocalDevice();
int advertise();
};
#endif
================================================
FILE: extras/test/include/test_discovered_device/FakeGAP.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _FAKE_GAP_H_
#define _FAKE_GAP_H_
#define private public
#define protected public
#include "GAP.h"
class FakeGAPClass : public GAPClass {
public:
FakeGAPClass();
virtual ~FakeGAPClass();
};
#endif
================================================
FILE: extras/test/include/util/Common.h
================================================
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C"{
#endif
void yield(void);
typedef enum {
LOW = 0,
HIGH = 1,
CHANGE = 2,
FALLING = 3,
RISING = 4,
} PinStatus;
typedef enum {
INPUT = 0x0,
OUTPUT = 0x1,
INPUT_PULLUP = 0x2,
INPUT_PULLDOWN = 0x3,
} PinMode;
typedef enum {
LSBFIRST = 0,
MSBFIRST = 1,
} BitOrder;
#define PI 3.1415926535897932384626433832795
#define HALF_PI 1.5707963267948966192313216916398
#define TWO_PI 6.283185307179586476925286766559
#define DEG_TO_RAD 0.017453292519943295769236907684886
#define RAD_TO_DEG 57.295779513082320876798154814105
#define EULER 2.718281828459045235360287471352
#define SERIAL 0x0
#define DISPLAY 0x1
#ifndef constrain
#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt)))
#endif
#ifndef radians
#define radians(deg) ((deg)*DEG_TO_RAD)
#endif
#ifndef degrees
#define degrees(rad) ((rad)*RAD_TO_DEG)
#endif
#ifndef sq
#define sq(x) ((x)*(x))
#endif
typedef void (*voidFuncPtr)(void);
typedef void (*voidFuncPtrParam)(void*);
// interrupts() / noInterrupts() must be defined by the core
#define lowByte(w) ((uint8_t) ((w) & 0xff))
#define highByte(w) ((uint8_t) ((w) >> 8))
#define bitRead(value, bit) (((value) >> (bit)) & 0x01)
#define bitSet(value, bit) ((value) |= (1UL << (bit)))
#define bitClear(value, bit) ((value) &= ~(1UL << (bit)))
#define bitToggle(value, bit) ((value) ^= (1UL << (bit)))
#define bitWrite(value, bit, bitvalue) (bitvalue ? bitSet(value, bit) : bitClear(value, bit))
#ifndef bit
#define bit(b) (1UL << (b))
#endif
/* TODO: request for removal */
typedef bool boolean;
typedef uint8_t byte;
typedef uint16_t word;
void init(void);
void initVariant(void);
int atexit(void (*func)()) __attribute__((weak));
int main() __attribute__((weak));
#ifdef EXTENDED_PIN_MODE
// Platforms who wnat to declare more than 256 pins need to define EXTENDED_PIN_MODE globally
typedef uint32_t pin_size_t;
#else
typedef uint8_t pin_size_t;
#endif
void pinMode(pin_size_t pinNumber, PinMode pinMode);
void digitalWrite(pin_size_t pinNumber, PinStatus status);
PinStatus digitalRead(pin_size_t pinNumber);
int analogRead(pin_size_t pinNumber);
void analogReference(uint8_t mode);
void analogWrite(pin_size_t pinNumber, int value);
unsigned long millis(void);
unsigned long micros(void);
void delay(unsigned long);
void delayMicroseconds(unsigned int us);
unsigned long pulseIn(pin_size_t pin, uint8_t state, unsigned long timeout);
unsigned long pulseInLong(pin_size_t pin, uint8_t state, unsigned long timeout);
void shiftOut(pin_size_t dataPin, pin_size_t clockPin, BitOrder bitOrder, uint8_t val);
pin_size_t shiftIn(pin_size_t dataPin, pin_size_t clockPin, BitOrder bitOrder);
void attachInterrupt(pin_size_t interruptNumber, voidFuncPtr callback, PinStatus mode);
void attachInterruptParam(pin_size_t interruptNumber, voidFuncPtrParam callback, PinStatus mode, void* param);
void detachInterrupt(pin_size_t interruptNumber);
void setup(void);
void loop(void);
#ifdef __cplusplus
} // extern "C"
#endif
#ifdef __cplusplus
template<class T, class L>
auto min(const T& a, const L& b) -> decltype((b < a) ? b : a)
{
return (b < a) ? b : a;
}
template<class T, class L>
auto max(const T& a, const L& b) -> decltype((b < a) ? b : a)
{
return (a < b) ? b : a;
}
#else
#ifndef min
#define min(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a < _b ? _a : _b; })
#endif
#ifndef max
#define max(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; })
#endif
#endif
#ifdef __cplusplus
/* C++ prototypes */
uint16_t makeWord(uint16_t w);
uint16_t makeWord(byte h, byte l);
#define word(...) makeWord(__VA_ARGS__)
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout = 1000000L);
unsigned long pulseInLong(uint8_t pin, uint8_t state, unsigned long timeout = 1000000L);
void tone(uint8_t _pin, unsigned int frequency, unsigned long duration = 0);
void noTone(uint8_t _pin);
// WMath prototypes
long random(long);
long random(long, long);
void randomSeed(unsigned long);
long map(long, long, long, long, long);
#endif // __cplusplus
================================================
FILE: extras/test/include/util/HCIFakeTransport.h
================================================
//#include "Common.h"
#pragma once
#include "HCITransport.h"
class HCIFakeTransportClass : public HCITransportInterface
{
public:
HCIFakeTransportClass() {};
~HCIFakeTransportClass() {};
int begin() {return 0;}
void end() {return;}
void wait(unsigned long timeout) {return;}
int available() {return 0;}
int peek() {return 0;}
int read() {return 0;}
size_t write(const uint8_t* data, size_t length) {return 0;}
};
================================================
FILE: extras/test/include/util/Stream.h
================================================
//#include "Common.h"
#pragma once
#define DEC 10
#define HEX 16
#define OCT 8
#define BIN 2
class Stream
{
public:
Stream(const char *name = NULL);
~Stream();
void flush() {}
size_t print(const char[]) { return 0; }
size_t print(char) { return 0; }
size_t print(unsigned char, int) { return 0; }
size_t print(int, int) { return 0; }
size_t print(unsigned int, int) { return 0; }
size_t print(long, int) { return 0; }
size_t print(unsigned long, int) { return 0; }
size_t print(long long, int) { return 0; }
size_t print(unsigned long long, int) { return 0; }
size_t print(double, int) { return 0; }
size_t print(void) { return 0; }
size_t println(const char[]) { return 0; }
size_t println(char) { return 0; }
size_t println(unsigned char, int) { return 0; }
size_t println(int, int) { return 0; }
size_t println(unsigned int, int) { return 0; }
size_t println(long, int) { return 0; }
size_t println(unsigned long, int) { return 0; }
size_t println(long long, int) { return 0; }
size_t println(unsigned long long, int) { return 0; }
size_t println(double, int) { return 0; }
size_t println(void) { return 0; }
};
================================================
FILE: extras/test/include/util/String.h
================================================
/*
String library for Wiring & Arduino
...mostly rewritten by Paul Stoffregen...
Copyright (c) 2009-10 Hernando Barragan. All right reserved.
Copyright 2011, Paul Stoffregen, paul@pjrc.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef __cplusplus
#ifndef __ARDUINO_STRINGS__
#define __ARDUINO_STRINGS__
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
namespace arduino {
// When compiling programs with this class, the following gcc parameters
// dramatically increase performance and memory (RAM) efficiency, typically
// with little or no increase in code size.
// -felide-constructors
// -std=c++0x
class __FlashStringHelper;
#define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal)))
// An inherited class for holding the result of a concatenation. These
// result objects are assumed to be writable by subsequent concatenations.
class StringSumHelper;
// The string class
class String
{
friend class StringSumHelper;
// use a function pointer to allow for "if (s)" without the
// complications of an operator bool(). for more information, see:
// http://www.artima.com/cppsource/safebool.html
typedef void (String::*StringIfHelperType)() const;
void StringIfHelper() const {}
public:
// constructors
// creates a copy of the initial value.
// if the initial value is null or invalid, or if memory allocation
// fails, the string will be marked as invalid (i.e. "if (s)" will
// be false).
String(const char *cstr = "");
String(const String &str);
String(const __FlashStringHelper *str);
#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
String(String &&rval);
String(StringSumHelper &&rval);
#endif
explicit String(char c);
explicit String(unsigned char, unsigned char base=10);
explicit String(int, unsigned char base=10);
explicit String(unsigned int, unsigned char base=10);
explicit String(long, unsigned char base=10);
explicit String(unsigned long, unsigned char base=10);
//explicit String(float, unsigned char decimalPlaces=2);
//explicit String(double, unsigned char decimalPlaces=2);
~String(void);
// memory management
// return true on success, false on failure (in which case, the string
// is left unchanged). reserve(0), if successful, will validate an
// invalid string (i.e., "if (s)" will be true afterwards)
unsigned char reserve(unsigned int size);
inline unsigned int length(void) const {return len;}
// creates a copy of the assigned value. if the value is null or
// invalid, or if the memory allocation fails, the string will be
// marked as invalid ("if (s)" will be false).
String & operator = (const String &rhs);
String & operator = (const char *cstr);
//String & operator = (const __FlashStringHelper *str);
#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
String & operator = (String &&rval);
String & operator = (StringSumHelper &&rval);
#endif
// concatenate (works w/ built-in types)
// returns true on success, false on failure (in which case, the string
// is left unchanged). if the argument is null or invalid, the
// concatenation is considered unsucessful.
unsigned char concat(const String &str);
unsigned char concat(const char *cstr);
unsigned char concat(char c);
unsigned char concat(unsigned char c);
unsigned char concat(int num);
unsigned char concat(unsigned int num);
unsigned char concat(long num);
unsigned char concat(unsigned long num);
unsigned char concat(float num);
//unsigned char concat(double num);
unsigned char concat(const __FlashStringHelper * str);
// if there's not enough memory for the concatenated value, the string
// will be left unchanged (but this isn't signalled in any way)
String & operator += (const String &rhs) {concat(rhs); return (*this);}
String & operator += (const char *cstr) {concat(cstr); return (*this);}
String & operator += (char c) {concat(c); return (*this);}
String & operator += (unsigned char num) {concat(num); return (*this);}
String & operator += (int num) {concat(num); return (*this);}
String & operator += (unsigned int num) {concat(num); return (*this);}
String & operator += (long num) {concat(num); return (*this);}
String & operator += (unsigned long num) {concat(num); return (*this);}
String & operator += (float num) {concat(num); return (*this);}
//String & operator += (double num) {concat(num); return (*this);}
String & operator += (const __FlashStringHelper *str){concat(str); return (*this);}
friend StringSumHelper & operator + (const StringSumHelper &lhs, const String &rhs);
friend StringSumHelper & operator + (const StringSumHelper &lhs, const char *cstr);
friend StringSumHelper & operator + (const StringSumHelper &lhs, char c);
friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned char num);
friend StringSumHelper & operator + (const StringSumHelper &lhs, int num);
friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned int num);
friend StringSumHelper & operator + (const StringSumHelper &lhs, long num);
friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned long num);
friend StringSumHelper & operator + (const StringSumHelper &lhs, float num);
//friend StringSumHelper & operator + (const StringSumHelper &lhs, double num);
//friend StringSumHelper & operator + (const StringSumHelper &lhs, const __FlashStringHelper *rhs);
// comparison (only works w/ Strings and "strings")
operator StringIfHelperType() const { return buffer ? &String::StringIfHelper : 0; }
int compareTo(const String &s) const;
int compareTo(const char *cstr) const;
unsigned char equals(const String &s) const;
unsigned char equals(const char *cstr) const;
friend unsigned char operator == (const String &a, const String &b) { return a.equals(b); }
friend unsigned char operator == (const String &a, const char *b) { return a.equals(b); }
friend unsigned char operator == (const char *a, const String &b) { return b == a; }
friend unsigned char operator < (const String &a, const String &b) { return a.compareTo(b) < 0; }
friend unsigned char operator < (const String &a, const char *b) { return a.compareTo(b) < 0; }
friend unsigned char operator < (const char *a, const String &b) { return b.compareTo(a) > 0; }
friend unsigned char operator != (const String &a, const String &b) { return !(a == b); }
friend unsigned char operator != (const String &a, const char *b) { return !(a == b); }
friend unsigned char operator != (const char *a, const String &b) { return !(a == b); }
friend unsigned char operator > (const String &a, const String &b) { return b < a; }
friend unsigned char operator > (const String &a, const char *b) { return b < a; }
friend unsigned char operator > (const char *a, const String &b) { return b < a; }
friend unsigned char operator <= (const String &a, const String &b) { return !(b < a); }
friend unsigned char operator <= (const String &a, const char *b) { return !(b < a); }
friend unsigned char operator <= (const char *a, const String &b) { return !(b < a); }
friend unsigned char operator >= (const String &a, const String &b) { return !(a < b); }
friend unsigned char operator >= (const String &a, const char *b) { return !(a < b); }
friend unsigned char operator >= (const char *a, const String &b) { return !(a < b); }
unsigned char equalsIgnoreCase(const String &s) const;
unsigned char startsWith( const String &prefix) const;
unsigned char startsWith(const String &prefix, unsigned int offset) const;
unsigned char endsWith(const String &suffix) const;
// character acccess
char charAt(unsigned int index) const;
void setCharAt(unsigned int index, char c);
char operator [] (unsigned int index) const;
char& operator [] (unsigned int index);
void getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index=0) const;
void toCharArray(char *buf, unsigned int bufsize, unsigned int index=0) const
{ getBytes((unsigned char *)buf, bufsize, index); }
const char* c_str() const { return buffer; }
char* begin() { return buffer; }
char* end() { return buffer + length(); }
const char* begin() const { return c_str(); }
const char* end() const { return c_str() + length(); }
// search
int indexOf( char ch ) const;
int indexOf( char ch, unsigned int fromIndex ) const;
int indexOf( const String &str ) const;
int indexOf( const String &str, unsigned int fromIndex ) const;
int lastIndexOf( char ch ) const;
int lastIndexOf( char ch, unsigned int fromIndex ) const;
int lastIndexOf( const String &str ) const;
int lastIndexOf( const String &str, unsigned int fromIndex ) const;
String substring( unsigned int beginIndex ) const { return substring(beginIndex, len); };
String substring( unsigned int beginIndex, unsigned int endIndex ) const;
// modification
void replace(char find, char replace);
void replace(const String& find, const String& replace);
void remove(unsigned int index);
void remove(unsigned int index, unsigned int count);
void toLowerCase(void);
void toUpperCase(void);
void trim(void);
// parsing/conversion
long toInt(void) const;
float toFloat(void) const;
double toDouble(void) const;
protected:
char *buffer; // the actual char array
unsigned int capacity; // the array length minus one (for the '\0')
unsigned int len; // the String length (not counting the '\0')
protected:
void init(void);
void invalidate(void);
unsigned char changeBuffer(unsigned int maxStrLen);
unsigned char concat(const char *cstr, unsigned int length);
// copy and move
String & copy(const char *cstr, unsigned int length);
String & copy(const __FlashStringHelper *pstr, unsigned int length);
#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
void move(String &rhs);
#endif
};
class StringSumHelper : public String
{
public:
StringSumHelper(const String &s) : String(s) {}
StringSumHelper(const char *p) : String(p) {}
StringSumHelper(char c) : String(c) {}
StringSumHelper(unsigned char num) : String(num) {}
StringSumHelper(int num) : String(num) {}
StringSumHelper(unsigned int num) : String(num) {}
StringSumHelper(long num) : String(num) {}
StringSumHelper(unsigned long num) : String(num) {}
//StringSumHelper(float num) : String(num) {}
//StringSumHelper(double num) : String(num) {}
};
} // namespace arduino
#endif // __cplusplus
#endif // __ARDUINO_STRINGS__
================================================
FILE: extras/test/include/util/TestUtil.h
================================================
/*
* Copyright (c) 2020 Arduino. All rights reserved.
*/
================================================
FILE: extras/test/include/util/itoa.h
================================================
/*
Copyright (c) 2016 Arduino LLC. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
// Standard C functions required in Arduino API
// If these functions are not provided by the standard library, the
// core should supply an implementation of them.
#ifdef __cplusplus
extern "C" {
#endif
extern char* itoa(int value, char *string, int radix);
extern char* ltoa(long value, char *string, int radix);
extern char* utoa(unsigned value, char *string, int radix);
extern char* ultoa(unsigned long value, char *string, int radix);
#ifdef __cplusplus
} // extern "C"
#endif
================================================
FILE: extras/test/src/Arduino.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/******************************************************************************
INCLUDE
******************************************************************************/
#include <Arduino.h>
/******************************************************************************
GLOBAL VARIABLES
******************************************************************************/
static unsigned long current_millis = 0;
/******************************************************************************
PUBLIC FUNCTIONS
******************************************************************************/
void set_millis(unsigned long const millis)
{
current_millis = millis;
}
unsigned long millis()
{
return current_millis;
}
================================================
FILE: extras/test/src/test_advertising_data/FakeBLELocalDevice.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "FakeBLELocalDevice.h"
FakeBLELocalDevice::FakeBLELocalDevice()
{
}
FakeBLELocalDevice::~FakeBLELocalDevice()
{
}
int FakeBLELocalDevice::advertise()
{
_advertisingData.updateData();
_scanResponseData.updateData();
return 1;
}
FakeBLELocalDevice FakeBLEObj;
BLELocalDevice& BLE = FakeBLEObj;
================================================
FILE: extras/test/src/test_advertising_data/test_advertising_data.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <catch2/catch_test_macros.hpp>
#define private public
#define protected public
#include "FakeBLELocalDevice.h"
#include "BLEAdvertisingData.h"
TEST_CASE("Test flags override", "[ArduinoBLE::BLEAdvertisingData]")
{
// Mocking advertisement packet
BLEAdvertisingData advData;
// Expected results
const uint8_t defaultData[] = {0x02, BLEFieldFlags, 0x06};
const uint8_t goldenFlags[] = {0x02, 0x01, BLEFlagsBREDRNotSupported};
WHEN("Default options for flags")
{
BLE.advertise();
REQUIRE( 0 == (memcmp(defaultData, BLE.getAdvertisingData().data(), sizeof(defaultData))) );
REQUIRE( BLE.getScanResponseData().dataLength() == 0 );
}
WHEN("Setting external advertising data which has flags")
{
advData.setFlags(BLEFlagsBREDRNotSupported);
advData.updateData();
BLE.setAdvertisingData(advData);
BLE.advertise();
REQUIRE( 3 == BLE.getAdvertisingData().dataLength());
REQUIRE
gitextract_54t7sr_k/
├── .codespellrc
├── .github/
│ ├── dependabot.yml
│ └── workflows/
│ ├── compile-examples.yml
│ ├── report-size-deltas.yml
│ ├── spell-check.yml
│ ├── sync-labels.yml
│ └── unit-tests.yml
├── .gitignore
├── CHANGELOG
├── LICENSE
├── README.md
├── docs/
│ ├── api.md
│ └── readme.md
├── examples/
│ ├── Central/
│ │ ├── LedControl/
│ │ │ └── LedControl.ino
│ │ ├── PeripheralExplorer/
│ │ │ └── PeripheralExplorer.ino
│ │ ├── Scan/
│ │ │ └── Scan.ino
│ │ ├── ScanCallback/
│ │ │ └── ScanCallback.ino
│ │ └── SensorTagButton/
│ │ └── SensorTagButton.ino
│ └── Peripheral/
│ ├── Advertising/
│ │ ├── EnhancedAdvertising/
│ │ │ └── EnhancedAdvertising.ino
│ │ └── RawDataAdvertising/
│ │ └── RawDataAdvertising.ino
│ ├── BatteryMonitor/
│ │ └── BatteryMonitor.ino
│ ├── ButtonLED/
│ │ └── ButtonLED.ino
│ ├── CallbackLED/
│ │ └── CallbackLED.ino
│ ├── EncryptedBatteryMonitor/
│ │ └── EncryptedBatteryMonitor.ino
│ └── LED/
│ └── LED.ino
├── extras/
│ ├── arduino-ble-parser.py
│ └── test/
│ ├── .gitignore
│ ├── CMakeLists.txt
│ ├── include/
│ │ ├── Arduino.h
│ │ ├── test_advertising_data/
│ │ │ └── FakeBLELocalDevice.h
│ │ ├── test_discovered_device/
│ │ │ └── FakeGAP.h
│ │ └── util/
│ │ ├── Common.h
│ │ ├── HCIFakeTransport.h
│ │ ├── Stream.h
│ │ ├── String.h
│ │ ├── TestUtil.h
│ │ └── itoa.h
│ └── src/
│ ├── Arduino.cpp
│ ├── test_advertising_data/
│ │ ├── FakeBLELocalDevice.cpp
│ │ ├── test_advertising_data.cpp
│ │ ├── test_local_name.cpp
│ │ ├── test_manufacturer.cpp
│ │ └── test_service.cpp
│ ├── test_characteristic/
│ │ ├── test_permissions.cpp
│ │ └── test_writeValue.cpp
│ ├── test_discovered_device/
│ │ ├── FakeGAP.cpp
│ │ └── test_discovered_device.cpp
│ ├── test_main.cpp
│ ├── test_uuid/
│ │ └── test_uuid.cpp
│ └── util/
│ ├── Common.cpp
│ ├── HCIFakeTransport.cpp
│ ├── String.cpp
│ ├── TestUtil.cpp
│ └── itoa.c
├── keywords.txt
├── library.properties
└── src/
├── ArduinoBLE.h
├── BLEAdvertisingData.cpp
├── BLEAdvertisingData.h
├── BLECharacteristic.cpp
├── BLECharacteristic.h
├── BLEDescriptor.cpp
├── BLEDescriptor.h
├── BLEDevice.cpp
├── BLEDevice.h
├── BLEProperty.h
├── BLEService.cpp
├── BLEService.h
├── BLEStringCharacteristic.cpp
├── BLEStringCharacteristic.h
├── BLETypedCharacteristic.h
├── BLETypedCharacteristics.cpp
├── BLETypedCharacteristics.h
├── local/
│ ├── BLELocalAttribute.cpp
│ ├── BLELocalAttribute.h
│ ├── BLELocalCharacteristic.cpp
│ ├── BLELocalCharacteristic.h
│ ├── BLELocalDescriptor.cpp
│ ├── BLELocalDescriptor.h
│ ├── BLELocalDevice.cpp
│ ├── BLELocalDevice.h
│ ├── BLELocalService.cpp
│ └── BLELocalService.h
├── remote/
│ ├── BLERemoteAttribute.cpp
│ ├── BLERemoteAttribute.h
│ ├── BLERemoteCharacteristic.cpp
│ ├── BLERemoteCharacteristic.h
│ ├── BLERemoteDescriptor.cpp
│ ├── BLERemoteDescriptor.h
│ ├── BLERemoteDevice.cpp
│ ├── BLERemoteDevice.h
│ ├── BLERemoteService.cpp
│ └── BLERemoteService.h
└── utility/
├── ATT.cpp
├── ATT.h
├── BLELinkedList.h
├── BLEUuid.cpp
├── BLEUuid.h
├── CordioHCICustomDriver.h
├── GAP.cpp
├── GAP.h
├── GATT.cpp
├── GATT.h
├── HCI.cpp
├── HCI.h
├── HCICordioTransport.cpp
├── HCICordioTransport.h
├── HCINinaSpiTransport.cpp
├── HCINinaSpiTransport.h
├── HCISilabsTransport.cpp
├── HCISilabsTransport.h
├── HCITransport.h
├── HCIUartTransport.cpp
├── HCIUartTransport.h
├── HCIVirtualTransport.cpp
├── HCIVirtualTransport.h
├── HCIVirtualTransportAT.cpp
├── HCIVirtualTransportAT.h
├── HCIVirtualTransportRPC.cpp
├── HCIVirtualTransportRPC.h
├── HCIVirtualTransportZephyr.cpp
├── HCIVirtualTransportZephyr.h
├── L2CAPSignaling.cpp
├── L2CAPSignaling.h
├── bitDescriptions.cpp
├── bitDescriptions.h
├── btct.cpp
├── btct.h
├── keyDistribution.cpp
└── keyDistribution.h
SYMBOL INDEX (242 symbols across 72 files)
FILE: extras/arduino-ble-parser.py
function extractHCIDebugPrint (line 18) | def extractHCIDebugPrint(inputPath, outputPath):
function buildBinaryPacket (line 30) | def buildBinaryPacket(hciMessage, hciDirection, hciType):
function buildBinaryHeader (line 47) | def buildBinaryHeader():
function convertToBtsnoop (line 52) | def convertToBtsnoop(inputPath, outputPath):
FILE: extras/test/include/Arduino.h
type arduino (line 38) | typedef arduino::String String;
type boolean (line 39) | typedef bool boolean;
FILE: extras/test/include/test_advertising_data/FakeBLELocalDevice.h
function class (line 27) | class FakeBLELocalDevice : public BLELocalDevice {
FILE: extras/test/include/test_discovered_device/FakeGAP.h
function class (line 27) | class FakeGAPClass : public GAPClass {
FILE: extras/test/include/util/Common.h
type PinStatus (line 10) | typedef enum {
type PinMode (line 18) | typedef enum {
type BitOrder (line 25) | typedef enum {
type boolean (line 75) | typedef bool boolean;
type byte (line 76) | typedef uint8_t byte;
type word (line 77) | typedef uint16_t word;
type pin_size_t (line 87) | typedef uint32_t pin_size_t;
type pin_size_t (line 89) | typedef uint8_t pin_size_t;
FILE: extras/test/include/util/HCIFakeTransport.h
function class (line 6) | class HCIFakeTransportClass : public HCITransportInterface
FILE: extras/test/include/util/Stream.h
function class (line 9) | class Stream
FILE: extras/test/include/util/String.h
function namespace (line 31) | namespace arduino {
function String (line 195) | String substring( unsigned int beginIndex ) const { return substring(beg...
function class (line 230) | class StringSumHelper : public String
FILE: extras/test/src/Arduino.cpp
function set_millis (line 36) | void set_millis(unsigned long const millis)
function millis (line 41) | unsigned long millis()
FILE: extras/test/src/test_characteristic/test_permissions.cpp
function createCharacteristic (line 69) | std::unique_ptr<BLECharacteristic> createCharacteristic(const char* uuid...
FILE: extras/test/src/util/Common.cpp
function delay (line 22) | void delay(unsigned long)
function map (line 28) | long map(long x, long in_min, long in_max, long out_min, long out_max)
function makeWord (line 33) | uint16_t makeWord(uint16_t w) { return w; }
function makeWord (line 34) | uint16_t makeWord(uint8_t h, uint8_t l) { return (h << 8) | l; }
FILE: extras/test/src/util/String.cpp
type arduino (line 29) | namespace arduino {
function String (line 175) | String & String::copy(const char *cstr, unsigned int length)
function String (line 221) | String & String::operator = (const String &rhs)
function String (line 232) | String & String::operator = (String &&rval)
function String (line 238) | String & String::operator = (StringSumHelper &&rval)
function String (line 245) | String & String::operator = (const char *cstr)
function StringSumHelper (line 364) | StringSumHelper & operator + (const StringSumHelper &lhs, const String...
function StringSumHelper (line 371) | StringSumHelper & operator + (const StringSumHelper &lhs, const char *...
function StringSumHelper (line 378) | StringSumHelper & operator + (const StringSumHelper &lhs, char c)
function StringSumHelper (line 385) | StringSumHelper & operator + (const StringSumHelper &lhs, unsigned cha...
function StringSumHelper (line 392) | StringSumHelper & operator + (const StringSumHelper &lhs, int num)
function StringSumHelper (line 399) | StringSumHelper & operator + (const StringSumHelper &lhs, unsigned int...
function StringSumHelper (line 406) | StringSumHelper & operator + (const StringSumHelper &lhs, long num)
function StringSumHelper (line 413) | StringSumHelper & operator + (const StringSumHelper &lhs, unsigned lon...
function String (line 617) | String String::substring(unsigned int left, unsigned int right) const
FILE: src/BLEAdvertisingData.cpp
function BLEAdvertisingData (line 104) | BLEAdvertisingData& BLEAdvertisingData::operator=(const BLEAdvertisingDa...
FILE: src/BLEAdvertisingData.h
type BLEFlags (line 29) | enum BLEFlags {
type BLEAdField (line 35) | enum BLEAdField {
type BLEAdvertisingRawData (line 49) | struct BLEAdvertisingRawData {
function class (line 54) | class BLEAdvertisingData {
FILE: src/BLECharacteristic.cpp
function BLELocalCharacteristic (line 348) | BLELocalCharacteristic* BLECharacteristic::local()
function BLEDescriptor (line 400) | BLEDescriptor BLECharacteristic::descriptor(int index) const
function BLEDescriptor (line 409) | BLEDescriptor BLECharacteristic::descriptor(const char * uuid) const
function BLEDescriptor (line 414) | BLEDescriptor BLECharacteristic::descriptor(const char * uuid, int index...
FILE: src/BLECharacteristic.h
type BLECharacteristicEvent (line 27) | enum BLECharacteristicEvent {
function class (line 45) | class BLECharacteristic {
FILE: src/BLEDescriptor.cpp
function BLELocalDescriptor (line 226) | BLELocalDescriptor* BLEDescriptor::local()
FILE: src/BLEDescriptor.h
function class (line 28) | class BLEDescriptor {
FILE: src/BLEDevice.cpp
function String (line 77) | String BLEDevice::address() const
function String (line 128) | String BLEDevice::localName() const
function String (line 151) | String BLEDevice::advertisedServiceUuid() const
function String (line 156) | String BLEDevice::advertisedServiceUuid(int index) const
function String (line 296) | String BLEDevice::deviceName()
function BLEService (line 392) | BLEService BLEDevice::service(int index) const
function BLEService (line 405) | BLEService BLEDevice::service(const char * uuid) const
function BLEService (line 410) | BLEService BLEDevice::service(const char * uuid, int index) const
function BLECharacteristic (line 488) | BLECharacteristic BLEDevice::characteristic(int index) const
function BLECharacteristic (line 516) | BLECharacteristic BLEDevice::characteristic(const char * uuid) const
function BLECharacteristic (line 521) | BLECharacteristic BLEDevice::characteristic(const char * uuid, int index...
FILE: src/BLEDevice.h
type BLEDeviceEvent (line 27) | enum BLEDeviceEvent {
function class (line 39) | class BLEDevice {
FILE: src/BLEProperty.h
type BLEProperty (line 25) | enum BLEProperty {
type BLEPermission (line 36) | enum BLEPermission {
type BLE_GATT_PERM_ (line 65) | enum BLE_GATT_PERM_ {
FILE: src/BLEService.cpp
function BLECharacteristic (line 147) | BLECharacteristic BLEService::characteristic(int index) const
function BLECharacteristic (line 156) | BLECharacteristic BLEService::characteristic(const char * uuid) const
function BLECharacteristic (line 161) | BLECharacteristic BLEService::characteristic(const char * uuid, int inde...
function BLELocalService (line 183) | BLELocalService* BLEService::local()
FILE: src/BLEService.h
function class (line 28) | class BLEService {
FILE: src/BLEStringCharacteristic.cpp
function String (line 32) | String BLEStringCharacteristic::value(void)
FILE: src/BLEStringCharacteristic.h
function class (line 27) | class BLEStringCharacteristic : public BLECharacteristic
FILE: src/BLETypedCharacteristic.h
function setValue (line 31) | int setValue(T value) { return writeValue(value); }
function setValueLE (line 35) | int setValueLE(T value) { return writeValueLE(value); }
function setValueBE (line 39) | int setValueBE(T value) { return writeValueBE(value); }
FILE: src/BLETypedCharacteristics.h
function class (line 25) | class BLEBoolCharacteristic : public BLETypedCharacteristic<bool> {
function class (line 30) | class BLEBooleanCharacteristic : public BLETypedCharacteristic<bool> {
function class (line 35) | class BLECharCharacteristic : public BLETypedCharacteristic<char> {
function class (line 40) | class BLEUnsignedCharCharacteristic : public BLETypedCharacteristic<unsi...
function class (line 45) | class BLEByteCharacteristic : public BLETypedCharacteristic<byte> {
function class (line 50) | class BLEShortCharacteristic : public BLETypedCharacteristic<short> {
function class (line 55) | class BLEUnsignedShortCharacteristic : public BLETypedCharacteristic<uns...
function class (line 60) | class BLEWordCharacteristic : public BLETypedCharacteristic<word> {
function class (line 65) | class BLEIntCharacteristic : public BLETypedCharacteristic<int> {
function class (line 70) | class BLEUnsignedIntCharacteristic : public BLETypedCharacteristic<unsig...
function class (line 75) | class BLELongCharacteristic : public BLETypedCharacteristic<long> {
function class (line 80) | class BLEUnsignedLongCharacteristic : public BLETypedCharacteristic<unsi...
function class (line 85) | class BLEFloatCharacteristic : public BLETypedCharacteristic<float> {
function class (line 90) | class BLEDoubleCharacteristic : public BLETypedCharacteristic<double> {
FILE: src/local/BLELocalAttribute.cpp
type BLEAttributeType (line 47) | enum BLEAttributeType
FILE: src/local/BLELocalAttribute.h
type BLEAttributeType (line 27) | enum BLEAttributeType {
function class (line 35) | class BLELocalAttribute
FILE: src/local/BLELocalCharacteristic.cpp
type BLEAttributeType (line 78) | enum BLEAttributeType
function BLELocalDescriptor (line 206) | BLELocalDescriptor* BLELocalCharacteristic::descriptor(unsigned int inde...
FILE: src/local/BLELocalCharacteristic.h
function class (line 34) | class BLELocalCharacteristic : public BLELocalAttribute {
FILE: src/local/BLELocalDescriptor.cpp
type BLEAttributeType (line 41) | enum BLEAttributeType
FILE: src/local/BLELocalDescriptor.h
function class (line 27) | class BLELocalDescriptor : public BLELocalAttribute {
FILE: src/local/BLELocalDevice.cpp
function String (line 247) | String BLELocalDevice::address() const
function BLEAdvertisingData (line 312) | BLEAdvertisingData& BLELocalDevice::getAdvertisingData()
function BLEAdvertisingData (line 317) | BLEAdvertisingData& BLELocalDevice::getScanResponseData()
function BLEDevice (line 375) | BLEDevice BLELocalDevice::central()
function BLEDevice (line 382) | BLEDevice BLELocalDevice::available()
FILE: src/local/BLELocalDevice.h
type Pairable (line 27) | enum Pairable {
FILE: src/local/BLELocalService.cpp
type BLEAttributeType (line 49) | enum BLEAttributeType
function BLELocalCharacteristic (line 84) | BLELocalCharacteristic* BLELocalService::characteristic(unsigned int ind...
FILE: src/local/BLELocalService.h
function class (line 31) | class BLELocalService : public BLELocalAttribute {
FILE: src/remote/BLERemoteAttribute.h
function class (line 25) | class BLERemoteAttribute
FILE: src/remote/BLERemoteCharacteristic.cpp
function BLERemoteDescriptor (line 228) | BLERemoteDescriptor* BLERemoteCharacteristic::descriptor(unsigned int in...
FILE: src/remote/BLERemoteCharacteristic.h
function class (line 30) | class BLERemoteCharacteristic : public BLERemoteAttribute {
FILE: src/remote/BLERemoteDescriptor.h
function class (line 25) | class BLERemoteDescriptor : public BLERemoteAttribute {
FILE: src/remote/BLERemoteDevice.cpp
function BLERemoteService (line 43) | BLERemoteService* BLERemoteDevice::service(unsigned int index) const
FILE: src/remote/BLERemoteDevice.h
function class (line 27) | class BLERemoteDevice /*: public BLEDevice*/ {
FILE: src/remote/BLERemoteService.cpp
function BLERemoteCharacteristic (line 57) | BLERemoteCharacteristic* BLERemoteService::characteristic(unsigned int i...
FILE: src/remote/BLERemoteService.h
function class (line 28) | class BLERemoteService : public BLERemoteAttribute {
FILE: src/utility/ATT.cpp
function BLERemoteDevice (line 464) | BLERemoteDevice* ATTClass::device(uint8_t addressType, const uint8_t add...
function BLEDevice (line 588) | BLEDevice ATTClass::central()
type AttError (line 679) | struct __attribute__ ((packed)) AttError {
type FindInfoReq (line 754) | struct __attribute__ ((packed)) FindInfoReq {
type FindByTypeReq (line 842) | struct __attribute__ ((packed)) FindByTypeReq {
type ReadByGroupReq (line 895) | struct __attribute__ ((packed)) ReadByGroupReq {
type BLEAttributeType (line 1028) | enum BLEAttributeType
type ReadByTypeReq (line 1125) | struct __attribute__ ((packed)) ReadByTypeReq {
type WriteBuffer (line 1381) | struct __attribute__ ((packed)) WriteBuffer {
type PrepWriteReq (line 1415) | struct __attribute__ ((packed)) PrepWriteReq {
type HandleNotifyOrInd (line 1524) | struct __attribute__ ((packed)) HandleNotifyOrInd {
type RawService (line 1621) | struct __attribute__ ((packed)) RawService {
type RawCharacteristic (line 1683) | struct __attribute__ ((packed)) RawCharacteristic {
type RawDescriptor (line 1752) | struct __attribute__ ((packed)) RawDescriptor {
FILE: src/utility/ATT.h
type PEER_ENCRYPTION (line 39) | enum PEER_ENCRYPTION {
FILE: src/utility/BLEUuid.h
function class (line 27) | class BLEUuid
FILE: src/utility/GAP.cpp
function BLEDevice (line 151) | BLEDevice GAPClass::available()
FILE: src/utility/GAP.h
function class (line 27) | class GAPClass {
FILE: src/utility/GATT.cpp
function BLELocalAttribute (line 125) | BLELocalAttribute* GATTClass::attribute(unsigned int index) const
FILE: src/utility/HCI.cpp
function String (line 77) | String metaEventToString(LE_META_EVENT event)
function String (line 89) | String commandToString(LE_COMMAND command){
type HCILocalVersion (line 221) | struct __attribute__ ((packed)) HCILocalVersion {
type HCIReadRssi (line 267) | struct __attribute__ ((packed)) HCIReadRssi {
type HCILeBufferSize (line 295) | struct __attribute__ ((packed)) HCILeBufferSize {
type HCILeAdvertisingParameters (line 322) | struct __attribute__ ((packed)) HCILeAdvertisingParameters {
type HCILeAdvertisingData (line 347) | struct __attribute__ ((packed)) HCILeAdvertisingData {
type HCILeScanResponseData (line 361) | struct __attribute__ ((packed)) HCILeScanResponseData {
type HCILeSetScanParameters (line 381) | struct __attribute__ ((packed)) HCILeSetScanParameters {
type HCILeSetScanEnableData (line 400) | struct __attribute__ ((packed)) HCILeSetScanEnableData {
type HCILeCreateConnData (line 416) | struct __attribute__ ((packed)) HCILeCreateConnData {
type HCILeConnUpdateData (line 455) | struct __attribute__ ((packed)) HCILeConnUpdateData {
type AddDevice (line 487) | struct __attribute__ ((packed)) AddDevice {
type Request (line 523) | struct __attribute__ ((packed)) Request {
type Response (line 536) | struct __attribute__ ((packed)) Response {
type StoreLK (line 550) | struct __attribute__ ((packed)) StoreLK {
type Request (line 565) | struct __attribute__ ((packed)) Request {
type HCIACLHdr (line 642) | struct __attribute__ ((packed)) HCIACLHdr {
type HCIDisconnectData (line 674) | struct __attribute__ ((packed)) HCIDisconnectData {
type HCIACLHdr (line 729) | struct __attribute__ ((packed)) HCIACLHdr {
type HCIL2CapHdr (line 782) | struct __attribute__ ((packed)) HCIL2CapHdr {
type HCIEventHdr (line 872) | struct __attribute__ ((packed)) HCIEventHdr {
type DisconnComplete (line 883) | struct __attribute__ ((packed)) DisconnComplete {
type EncryptionChange (line 899) | struct __attribute__ ((packed)) EncryptionChange {
type CmdComplete (line 984) | struct __attribute__ ((packed)) CmdComplete {
type CmdStatus (line 1005) | struct __attribute__ ((packed)) CmdStatus {
type CmdHardwareError (line 1044) | struct __attribute__ ((packed)) CmdHardwareError {
type LeMetaEventHeader (line 1054) | struct __attribute__ ((packed)) LeMetaEventHeader {
type EvtLeConnectionComplete (line 1063) | struct __attribute__ ((packed)) EvtLeConnectionComplete {
type EvtLeConnectionComplete (line 1114) | struct __attribute__ ((packed)) EvtLeConnectionComplete {
type EvtLeAdvertisingReport (line 1153) | struct __attribute__ ((packed)) EvtLeAdvertisingReport {
type LTKRequest (line 1180) | struct __attribute__ ((packed)) LTKRequest
type LTKReply (line 1215) | struct __attribute__ ((packed)) LTKReply
type LTKReplyResult (line 1230) | struct __attribute__ ((packed)) LTKReplyResult
type RemoteConnParamReq (line 1260) | struct __attribute__ ((packed)) RemoteConnParamReq {
type RemoteConnParamReqReply (line 1282) | struct __attribute__ ((packed)) RemoteConnParamReqReply {
type EvtReadLocalP256Complete (line 1299) | struct __attribute__ ((packed)) EvtReadLocalP256Complete{
type PairingPublicKey (line 1308) | struct __attribute__ ((packed)) PairingPublicKey
type F4Params (line 1338) | struct __attribute__ ((packed)) F4Params
type PairingConfirm (line 1349) | struct __attribute__ ((packed)) PairingConfirm
type EvtLeDHKeyComplete (line 1387) | struct __attribute__ ((packed)) EvtLeDHKeyComplete{
type LeEncryptCommand (line 1448) | struct __attribute__ ((packed)) LeEncryptCommand
function AuthReq (line 1524) | AuthReq HCIClass::localAuthreq(){
FILE: src/utility/HCI.h
type LE_COMMAND (line 34) | enum LE_COMMAND {
type LE_META_EVENT (line 43) | enum LE_META_EVENT {
function class (line 55) | class HCIClass {
FILE: src/utility/HCICordioTransport.cpp
type BLE_NAMESPACE (line 60) | namespace BLE_NAMESPACE {
type CordioHCIHook (line 61) | struct CordioHCIHook {
method CordioHCIDriver (line 62) | static CordioHCIDriver& getDriver() {
method CordioHCITransportDriver (line 66) | static CordioHCITransportDriver& getTransportDriver() {
method setDataReceivedHandler (line 70) | static void setDataReceivedHandler(void (*handler)(uint8_t*, uint8_t...
function init_wsf (line 82) | void init_wsf(BLE_NAMESPACE::buf_pool_desc_t& buf_pool_desc) {
function wsf_mbed_ble_signal_event (line 110) | void wsf_mbed_ble_signal_event(void)
function bleLoop (line 116) | static void bleLoop()
function scheduleMbedBleEvents (line 188) | void scheduleMbedBleEvents(BLE::OnEventsToProcessCallbackContext *contex...
function completeCallback (line 192) | void completeCallback(BLE::InitializationCompleteCallbackContext *contex...
FILE: src/utility/HCICordioTransport.h
function class (line 29) | class HCICordioTransportClass : public HCITransportInterface {
FILE: src/utility/HCINinaSpiTransport.h
function class (line 16) | class BleDrv
function class (line 27) | class HCINinaSpiTransportClass : public HCITransportInterface {
FILE: src/utility/HCISilabsTransport.cpp
function strcasecmp (line 30) | int strcasecmp(char const *a, char const *b) {
function hci_common_transport_transmit (line 114) | uint32_t hci_common_transport_transmit(uint8_t *data, int16_t len)
FILE: src/utility/HCISilabsTransport.h
function class (line 25) | class HCISilabsTransportClass : public HCITransportInterface {
FILE: src/utility/HCITransport.h
function class (line 25) | class HCITransportInterface {
FILE: src/utility/HCIUartTransport.h
function class (line 25) | class HCIUartTransportClass : public HCITransportInterface {
FILE: src/utility/HCIVirtualTransport.cpp
function notify_host_send_available (line 29) | static void notify_host_send_available(void)
function notify_host_recv (line 33) | static int notify_host_recv(uint8_t *data, uint16_t length)
function bleTask (line 44) | void bleTask(void *pvParameters)
FILE: src/utility/HCIVirtualTransport.h
function class (line 35) | class HCIVirtualTransportClass : public HCITransportInterface {
FILE: src/utility/HCIVirtualTransportAT.h
function class (line 27) | class HCIVirtualTransportATClass : public HCITransportInterface {
FILE: src/utility/HCIVirtualTransportRPC.h
function class (line 29) | class HCIVirtualTransportRPCClass : public HCITransportInterface {
FILE: src/utility/HCIVirtualTransportZephyr.cpp
type k_fifo (line 33) | struct k_fifo
type device (line 34) | struct device
function cyw4343_set_baudrate (line 48) | static int cyw4343_set_baudrate(const struct device *uart, uint32_t baud...
function cyw4343_download_firmware (line 72) | static int cyw4343_download_firmware(const struct device *uart) {
type device (line 137) | struct device
type net_buf (line 179) | struct net_buf
type net_buf (line 185) | struct net_buf
type bt_buf_type (line 216) | enum bt_buf_type
type net_buf (line 217) | struct net_buf
FILE: src/utility/HCIVirtualTransportZephyr.h
function class (line 26) | class HCIVirtualTransportZephyrClass : public HCITransportInterface {
FILE: src/utility/L2CAPSignaling.cpp
type L2CAPConnectionParameterUpdateRequest (line 72) | struct __attribute__ ((packed)) L2CAPConnectionParameterUpdateRequest {
type L2CAPSignalingHdr (line 89) | struct __attribute__ ((packed)) L2CAPSignalingHdr {
type L2CAPSignalingHdr (line 118) | struct __attribute__ ((packed)) L2CAPSignalingHdr {
type PairingRequest (line 142) | struct __attribute__ ((packed)) PairingRequest {
type PairingResponse (line 177) | struct __attribute__ ((packed)) PairingResponse {
type PairingRandom (line 198) | struct __attribute__ ((packed)) PairingRandom {
type PairingResponse (line 207) | struct __attribute__ ((packed)) PairingResponse {
type PairingFailed (line 270) | struct __attribute__ ((packed)) PairingFailed
type IdentityInformation (line 281) | struct __attribute__ ((packed)) IdentityInformation {
type IdentityAddress (line 291) | struct __attribute__ ((packed)) IdentityAddress {
type ConnectionPairingPublicKey (line 307) | struct __attribute__ ((packed)) ConnectionPairingPublicKey {
type GenerateDHKeyCommand (line 311) | struct __attribute__ ((packed)) GenerateDHKeyCommand {
type L2CAPConnectionParameterUpdateRequest (line 465) | struct __attribute__ ((packed)) L2CAPConnectionParameterUpdateRequest {
type L2CAPConnectionParameterUpdateResponse (line 477) | struct __attribute__ ((packed)) L2CAPConnectionParameterUpdateResponse {
FILE: src/utility/L2CAPSignaling.h
function class (line 54) | class L2CAPSignalingClass {
FILE: src/utility/bitDescriptions.h
function class (line 5) | class AuthReq{
type IOCap (line 33) | enum IOCap {
FILE: src/utility/btct.cpp
type CmacInput (line 72) | struct __attribute__ ((packed)) CmacInput
type F6Input (line 99) | struct __attribute__ ((packed)) F6Input
type CmacInput (line 151) | struct __attribute__ ((packed)) CmacInput {
FILE: src/utility/btct.h
function class (line 6) | class BluetoothCryptoToolbox{
FILE: src/utility/keyDistribution.h
function class (line 5) | class KeyDistribution{
Condensed preview — 130 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (655K chars).
[
{
"path": ".codespellrc",
"chars": 543,
"preview": "# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/spell-check/.codespellrc"
},
{
"path": ".github/dependabot.yml",
"chars": 670,
"preview": "# See: https://docs.github.com/en/code-security/supply-chain-security/configuration-options-for-dependency-updates#about"
},
{
"path": ".github/workflows/compile-examples.yml",
"chars": 6797,
"preview": "name: Compile Examples\n\n# See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-wor"
},
{
"path": ".github/workflows/report-size-deltas.yml",
"chars": 843,
"preview": "name: Report Size Deltas\n\n# See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-w"
},
{
"path": ".github/workflows/spell-check.yml",
"chars": 653,
"preview": "# Source: https://github.com/per1234/.github/blob/main/workflow-templates/spell-check.md\nname: Spell Check\n\n# See: https"
},
{
"path": ".github/workflows/sync-labels.yml",
"chars": 4676,
"preview": "# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/sync-labels.md\nname: Sync Label"
},
{
"path": ".github/workflows/unit-tests.yml",
"chars": 1892,
"preview": "name: Unit Tests\n\non:\n pull_request:\n paths:\n - \".github/workflows/unit-tests.yml\"\n - 'extras/test/**'\n "
},
{
"path": ".gitignore",
"chars": 11,
"preview": "\n.DS_Store\n"
},
{
"path": "CHANGELOG",
"chars": 847,
"preview": "ArduinoBLE ?.?.? - ????.??.??\n\nArduinoBLE 1.1.2 - 2019.11.12\n\n* cordio: switch to lower power when polling with timeout\n"
},
{
"path": "LICENSE",
"chars": 26461,
"preview": " GNU LESSER GENERAL PUBLIC LICENSE\n Version 2.1, February 1999\n\n Copyright (C) 19"
},
{
"path": "README.md",
"chars": 2121,
"preview": "# ArduinoBLE\n\n[`\n\nInitializes the"
},
{
"path": "docs/readme.md",
"chars": 8394,
"preview": "# ArduinoBLE library\n\nThis library supports all the Arduino boards that have the hardware enabled for Bluetooth® Low Ene"
},
{
"path": "examples/Central/LedControl/LedControl.ino",
"chars": 3577,
"preview": "/*\n LED Control\n\n This example scans for Bluetooth® Low Energy peripherals until one with the advertised service\n \"19"
},
{
"path": "examples/Central/PeripheralExplorer/PeripheralExplorer.ino",
"chars": 4563,
"preview": "/*\n Peripheral Explorer\n\n This example scans for Bluetooth® Low Energy peripherals until one with a particular name (\""
},
{
"path": "examples/Central/Scan/Scan.ino",
"chars": 1665,
"preview": "/*\n Scan\n\n This example scans for Bluetooth® Low Energy peripherals and prints out their advertising details:\n addres"
},
{
"path": "examples/Central/ScanCallback/ScanCallback.ino",
"chars": 1914,
"preview": "/*\n Scan Callback\n\n This example scans for Bluetooth® Low Energy peripherals and prints out their advertising details:"
},
{
"path": "examples/Central/SensorTagButton/SensorTagButton.ino",
"chars": 3825,
"preview": "/*\n SensorTag Button\n\n This example scans for Bluetooth® Low Energy peripherals until a TI SensorTag is discovered.\n "
},
{
"path": "examples/Peripheral/Advertising/EnhancedAdvertising/EnhancedAdvertising.ino",
"chars": 1334,
"preview": "#include <ArduinoBLE.h>\n\nBLEService myService(\"fff0\");\nBLEIntCharacteristic myCharacteristic(\"fff1\", BLERead | BLEBroadc"
},
{
"path": "examples/Peripheral/Advertising/RawDataAdvertising/RawDataAdvertising.ino",
"chars": 1244,
"preview": "#include <ArduinoBLE.h>\n\nBLEService myService(\"fff0\");\nBLEIntCharacteristic myCharacteristic(\"fff1\", BLERead | BLEBroadc"
},
{
"path": "examples/Peripheral/BatteryMonitor/BatteryMonitor.ino",
"chars": 3979,
"preview": "/*\n Battery Monitor\n\n This example creates a Bluetooth® Low Energy peripheral with the standard battery service and\n "
},
{
"path": "examples/Peripheral/ButtonLED/ButtonLED.ino",
"chars": 2907,
"preview": "/*\n Button LED\n\n This example creates a Bluetooth® Low Energy peripheral with service that contains a\n characteristic"
},
{
"path": "examples/Peripheral/CallbackLED/CallbackLED.ino",
"chars": 2944,
"preview": "/*\n Callback LED\n\n This example creates a Bluetooth® Low Energy peripheral with service that contains a\n characterist"
},
{
"path": "examples/Peripheral/EncryptedBatteryMonitor/EncryptedBatteryMonitor.ino",
"chars": 9290,
"preview": "/*\n Battery Monitor\n\n This example creates a BLE peripheral with the standard battery service and\n level characterist"
},
{
"path": "examples/Peripheral/LED/LED.ino",
"chars": 2682,
"preview": "/*\n LED\n\n This example creates a Bluetooth® Low Energy peripheral with service that contains a\n characteristic to con"
},
{
"path": "extras/arduino-ble-parser.py",
"chars": 3028,
"preview": "'''\nConvert ArduinoBLE debug files into Btsnoop files ready to be analyzed using wireshark or hcidump\nBtsnoop file forma"
},
{
"path": "extras/test/.gitignore",
"chars": 235,
"preview": "build\n### CMake ###\nCMakeLists.txt.user\nCMakeCache.txt\nCMakeFiles\nCMakeScripts\nTesting\nMakefile\ncmake_install.cmake\ninst"
},
{
"path": "extras/test/CMakeLists.txt",
"chars": 5311,
"preview": "##########################################################################\n\nset(CMAKE_VERBOSE_MAKEFILE ON)\ncmake_minimum"
},
{
"path": "extras/test/include/Arduino.h",
"chars": 1828,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "extras/test/include/test_advertising_data/FakeBLELocalDevice.h",
"chars": 1136,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "extras/test/include/test_discovered_device/FakeGAP.h",
"chars": 1053,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "extras/test/include/util/Common.h",
"chars": 4266,
"preview": "#pragma once\n#include <stdint.h>\n\n#ifdef __cplusplus\nextern \"C\"{\n#endif\n\nvoid yield(void);\n\ntypedef enum {\n LOW = 0"
},
{
"path": "extras/test/include/util/HCIFakeTransport.h",
"chars": 451,
"preview": "//#include \"Common.h\"\n#pragma once\n\n#include \"HCITransport.h\"\n\nclass HCIFakeTransportClass : public HCITransportInterfac"
},
{
"path": "extras/test/include/util/Stream.h",
"chars": 1171,
"preview": "//#include \"Common.h\"\n#pragma once\n\n#define DEC 10\n#define HEX 16\n#define OCT 8\n#define BIN 2\n\nclass Stream \n{\npublic:\n "
},
{
"path": "extras/test/include/util/String.h",
"chars": 11167,
"preview": "/*\n String library for Wiring & Arduino\n ...mostly rewritten by Paul Stoffregen...\n Copyright (c) 2009-10 Hernando Ba"
},
{
"path": "extras/test/include/util/TestUtil.h",
"chars": 60,
"preview": "/*\n * Copyright (c) 2020 Arduino. All rights reserved.\n */\n"
},
{
"path": "extras/test/include/util/itoa.h",
"chars": 1285,
"preview": "/*\n Copyright (c) 2016 Arduino LLC. All right reserved.\n\n This library is free software; you can redistribute it and/"
},
{
"path": "extras/test/src/Arduino.cpp",
"chars": 1564,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "extras/test/src/test_advertising_data/FakeBLELocalDevice.cpp",
"chars": 1148,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "extras/test/src/test_advertising_data/test_advertising_data.cpp",
"chars": 6663,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "extras/test/src/test_advertising_data/test_local_name.cpp",
"chars": 3198,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "extras/test/src/test_advertising_data/test_manufacturer.cpp",
"chars": 7191,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "extras/test/src/test_advertising_data/test_service.cpp",
"chars": 5686,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "extras/test/src/test_characteristic/test_permissions.cpp",
"chars": 4077,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "extras/test/src/test_characteristic/test_writeValue.cpp",
"chars": 13797,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "extras/test/src/test_discovered_device/FakeGAP.cpp",
"chars": 979,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "extras/test/src/test_discovered_device/test_discovered_device.cpp",
"chars": 1587,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "extras/test/src/test_main.cpp",
"chars": 975,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "extras/test/src/test_uuid/test_uuid.cpp",
"chars": 1767,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "extras/test/src/util/Common.cpp",
"chars": 1168,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "extras/test/src/util/HCIFakeTransport.cpp",
"chars": 961,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "extras/test/src/util/String.cpp",
"chars": 16950,
"preview": "/*\n String library for Wiring & Arduino\n ...mostly rewritten by Paul Stoffregen...\n Copyright (c) 2009-10 Hernando Ba"
},
{
"path": "extras/test/src/util/TestUtil.cpp",
"chars": 60,
"preview": "/*\n * Copyright (c) 2020 Arduino. All rights reserved.\n */\n"
},
{
"path": "extras/test/src/util/itoa.c",
"chars": 2236,
"preview": "/*\n Copyright (c) 2014 Arduino LLC. All right reserved.\n\n This library is free software; you can redistribute it and/"
},
{
"path": "keywords.txt",
"chars": 2985,
"preview": "#######################################\n# Syntax Coloring Map For ArduinoBLE\n#######################################\n\n##"
},
{
"path": "library.properties",
"chars": 489,
"preview": "name=ArduinoBLE\nversion=2.0.1\nauthor=Arduino\nmaintainer=Arduino <info@arduino.cc>\nsentence=Enables Bluetooth® Low Energy"
},
{
"path": "src/ArduinoBLE.h",
"chars": 1051,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/BLEAdvertisingData.cpp",
"chars": 10949,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/BLEAdvertisingData.h",
"chars": 3816,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/BLECharacteristic.cpp",
"chars": 9455,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/BLECharacteristic.h",
"chars": 4023,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/BLEDescriptor.cpp",
"chars": 4175,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/BLEDescriptor.h",
"chars": 2003,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/BLEDevice.cpp",
"chars": 12542,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/BLEDevice.h",
"chars": 3408,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/BLEProperty.h",
"chars": 4319,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/BLEService.cpp",
"chars": 3737,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/BLEService.h",
"chars": 1898,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/BLEStringCharacteristic.cpp",
"chars": 1425,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/BLEStringCharacteristic.h",
"chars": 1267,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/BLETypedCharacteristic.h",
"chars": 2718,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/BLETypedCharacteristics.cpp",
"chars": 3026,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/BLETypedCharacteristics.h",
"chars": 3157,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/local/BLELocalAttribute.cpp",
"chars": 1522,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/local/BLELocalAttribute.h",
"chars": 1545,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/local/BLELocalCharacteristic.cpp",
"chars": 5778,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/local/BLELocalCharacteristic.h",
"chars": 2755,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/local/BLELocalDescriptor.cpp",
"chars": 1742,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/local/BLELocalDescriptor.h",
"chars": 1536,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/local/BLELocalDevice.cpp",
"chars": 11124,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/local/BLELocalDevice.h",
"chars": 4408,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/local/BLELocalService.cpp",
"chars": 2296,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/local/BLELocalService.h",
"chars": 1762,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/remote/BLERemoteAttribute.cpp",
"chars": 1314,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2019 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/remote/BLERemoteAttribute.h",
"chars": 1170,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2019 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/remote/BLERemoteCharacteristic.cpp",
"chars": 5936,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2019 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/remote/BLERemoteCharacteristic.h",
"chars": 2500,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2019 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/remote/BLERemoteDescriptor.cpp",
"chars": 2825,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2019 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/remote/BLERemoteDescriptor.h",
"chars": 1487,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2019 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/remote/BLERemoteDevice.cpp",
"chars": 1478,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2019 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/remote/BLERemoteDevice.h",
"chars": 1301,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2019 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/remote/BLERemoteService.cpp",
"chars": 1847,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2019 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/remote/BLERemoteService.h",
"chars": 1626,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2019 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/ATT.cpp",
"chars": 56857,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/ATT.h",
"chars": 7808,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/BLELinkedList.h",
"chars": 3026,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/BLEUuid.cpp",
"chars": 1924,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/BLEUuid.h",
"chars": 1250,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/CordioHCICustomDriver.h",
"chars": 494,
"preview": "#if defined(CORE_CM4)\n\n#include \"CyH4TransportDriver.h\"\n\nble::vendor::cypress_ble::CyH4TransportDriver& ble_cordio_get_h"
},
{
"path": "src/utility/GAP.cpp",
"chars": 6703,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/GAP.h",
"chars": 2268,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/GATT.cpp",
"chars": 5686,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/GATT.h",
"chars": 2147,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/HCI.cpp",
"chars": 49867,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/HCI.h",
"chars": 6370,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/HCICordioTransport.cpp",
"chars": 8969,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2019 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/HCICordioTransport.h",
"chars": 1602,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2019 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/HCINinaSpiTransport.cpp",
"chars": 5038,
"preview": "/*\n This file is part of the ArduinoBLE library.\n\n Copyright (c) 2024 Arduino SA\n\n This Source Code Form is subject t"
},
{
"path": "src/utility/HCINinaSpiTransport.h",
"chars": 1009,
"preview": "/*\n This file is part of the ArduinoBLE library.\n\n Copyright (c) 2024 Arduino SA\n\n This Source Code Form is subject t"
},
{
"path": "src/utility/HCISilabsTransport.cpp",
"chars": 3097,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2024 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/HCISilabsTransport.h",
"chars": 1301,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/HCITransport.h",
"chars": 1574,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/HCIUartTransport.cpp",
"chars": 2138,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/HCIUartTransport.h",
"chars": 1398,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/HCIVirtualTransport.cpp",
"chars": 3809,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/HCIVirtualTransport.h",
"chars": 1494,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/HCIVirtualTransportAT.cpp",
"chars": 2742,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/HCIVirtualTransportAT.h",
"chars": 1315,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/HCIVirtualTransportRPC.cpp",
"chars": 2683,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018-2025 Arduino SA. All rights reserved.\n\n This lib"
},
{
"path": "src/utility/HCIVirtualTransportRPC.h",
"chars": 1558,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018-2025 Arduino SA. All rights reserved.\n\n This lib"
},
{
"path": "src/utility/HCIVirtualTransportZephyr.cpp",
"chars": 5809,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018-2025 Arduino SA. All rights reserved.\n\n This lib"
},
{
"path": "src/utility/HCIVirtualTransportZephyr.h",
"chars": 1410,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018-2025 Arduino SA. All rights reserved.\n\n This lib"
},
{
"path": "src/utility/L2CAPSignaling.cpp",
"chars": 17200,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/L2CAPSignaling.h",
"chars": 3290,
"preview": "/*\n This file is part of the ArduinoBLE library.\n Copyright (c) 2018 Arduino SA. All rights reserved.\n\n This library "
},
{
"path": "src/utility/bitDescriptions.cpp",
"chars": 1110,
"preview": "#include \"bitDescriptions.h\"\n\n\n#define BONDING_BIT 0b00000001\n#define MITM_BIT 0b00000100\n#define SC_BIT 0b00"
},
{
"path": "src/utility/bitDescriptions.h",
"chars": 1243,
"preview": "#ifndef _BIT_DESCRIPTIONS_H_\n#define _BIT_DESCRIPTIONS_H_\n#include <Arduino.h>\n\nclass AuthReq{\npublic:\n AuthReq();\n "
},
{
"path": "src/utility/btct.cpp",
"chars": 11563,
"preview": "#include \"btct.h\"\n#include <Arduino.h>\n#include \"HCI.h\"\n#include \"ArduinoBLE.h\"\nBluetoothCryptoToolbox::BluetoothCryptoT"
},
{
"path": "src/utility/btct.h",
"chars": 1275,
"preview": "#ifndef _BTCT_H_\n#define _BTCT_H_\n#include <Arduino.h>\n\n// Implementation of functions defined in BTLE standard\nclass Bl"
},
{
"path": "src/utility/keyDistribution.cpp",
"chars": 1272,
"preview": "#include \"keyDistribution.h\"\n\nKeyDistribution::KeyDistribution():_octet(0){}\nKeyDistribution::KeyDistribution(uint8_t oc"
},
{
"path": "src/utility/keyDistribution.h",
"chars": 915,
"preview": "#ifndef _KEY_DISTRIBUTION_H_\n#define _KEY_DISTRIBUTION_H_\n#include <Arduino.h>\n\nclass KeyDistribution{\npublic:\n KeyDi"
}
]
About this extraction
This page contains the full source code of the arduino-libraries/ArduinoBLE GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 130 files (606.8 KB), approximately 162.9k tokens, and a symbol index with 242 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.