Repository: rust-embedded/linux-embedded-hal
Branch: master
Commit: e9ccbf9e0b71
Files: 20
Total size: 65.6 KB
Directory structure:
gitextract_x2z4flh9/
├── .github/
│ ├── CODEOWNERS
│ └── workflows/
│ ├── ci.yml
│ ├── clippy.yml
│ └── rustfmt.yml
├── .gitignore
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── examples/
│ └── transactional-i2c.rs
└── src/
├── cdev_pin.rs
├── delay.rs
├── i2c.rs
├── lib.rs
├── serial.rs
├── spi.rs
├── sysfs_pin.rs
└── timer.rs
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/CODEOWNERS
================================================
* @rust-embedded/embedded-linux
================================================
FILE: .github/workflows/ci.yml
================================================
on:
push: # Run CI for all branches except GitHub merge queue tmp branches
branches-ignore:
- "gh-readonly-queue/**"
pull_request: # Run CI for PRs on any branch
merge_group: # Run CI for the GitHub merge queue
name: Continuous integration
jobs:
ci-linux:
name: CI
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
rust: [stable]
target: [x86_64-unknown-linux-gnu, armv7-unknown-linux-gnueabihf]
features:
- ''
- 'async-tokio,gpio_cdev,gpio_sysfs,i2c,spi'
include:
- rust: 1.84.0 # MSRV
target: x86_64-unknown-linux-gnu
# Test nightly but don't fail
- rust: nightly
experimental: true
target: x86_64-unknown-linux-gnu
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@master
with:
toolchain: ${{ matrix.rust }}
target: ${{ matrix.target }}
- name: Install armv7 libraries
if: ${{ matrix.target == 'armv7-unknown-linux-gnueabihf' }}
run: |
sudo apt-get update
sudo apt-get install -y libc6-armhf-cross libc6-dev-armhf-cross gcc-arm-linux-gnueabihf
- run: cargo check --target=${{ matrix.target }} --features=${{ matrix.features }}
================================================
FILE: .github/workflows/clippy.yml
================================================
on:
push: # Run CI for all branches except GitHub merge queue tmp branches
branches-ignore:
- "gh-readonly-queue/**"
pull_request: # Run CI for PRs on any branch
merge_group: # Run CI for the GitHub merge queue
name: Clippy check
jobs:
clippy_check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@master
with:
toolchain: 1.84.0
components: clippy
- run: cargo clippy --all-features -- --deny=warnings
================================================
FILE: .github/workflows/rustfmt.yml
================================================
on:
push: # Run CI for all branches except GitHub merge queue tmp branches
branches-ignore:
- "gh-readonly-queue/**"
pull_request: # Run CI for PRs on any branch
merge_group: # Run CI for the GitHub merge queue
name: Code formatting check
jobs:
fmt:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@master
with:
toolchain: nightly
components: rustfmt
- run: cargo fmt --check
================================================
FILE: .gitignore
================================================
/target/
**/*.rs.bk
Cargo.lock
================================================
FILE: CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).
## [Unreleased]
### Changed
- MSRV is now 1.84.0.
- Set `resolver = "3"`, which implies `resolver.incompatible-rust-versions = "fallback"`
### Added
- Added async `DelayNs` implementation for `tokio`.
- Added feature flag for `serial`.
### Fixed
- Fix UB (and remove unsafe block) in handling of SpiOperation::TransferInPlace
## [v0.4.0] - 2024-01-10
### Changed
- Updated to `embedded-hal` `1.0.0` release ([API changes](https://github.com/rust-embedded/embedded-hal/blob/master/embedded-hal/CHANGELOG.md#v100---2023-12-28))
- Updated to `embedded-hal-nb` `1.0.0` release ([API changes](https://github.com/rust-embedded/embedded-hal/blob/master/embedded-hal-nb/CHANGELOG.md#v100---2023-12-28))
## [v0.4.0-alpha.4] - 2024-01-03
### Changed
- [breaking-change] Replace serial-rs with the serialport-rs crate. `Serial::open` now needs a baud-rate argument as well.
- [breaking-change] Split `Spidev` into `SpidevDevice` and `SpidevBus`, implementing the respective `SpiDevice` and `SpiBus` traits (#100)
- Updated to `embedded-hal` `1.0.0-rc.3` release ([API changes](https://github.com/rust-embedded/embedded-hal/blob/master/embedded-hal/CHANGELOG.md#v100-rc3---2023-12-14))
- Updated to `embedded-hal-nb` `1.0.0-rc.3` release ([API changes](https://github.com/rust-embedded/embedded-hal/blob/master/embedded-hal-nb/CHANGELOG.md#v100-rc3---2023-12-14))
- Updated to `spidev` `0.6.0` release([API changes](https://github.com/rust-embedded/rust-spidev/blob/master/CHANGELOG.md#060--2023-08-03))
- Updated to `i2cdev` `0.6.0` release([API changes](https://github.com/rust-embedded/rust-i2cdev/blob/master/CHANGELOG.md#v060---2023-08-03))
- Updated to `gpio_cdev` `0.6.0` release([API changes](https://github.com/rust-embedded/gpio-cdev/blob/master/CHANGELOG.md#v060--2023-09-11))
- Updated to `nix` `0.27.1`
- MSRV is now 1.65.0.
### Fixed
- Fix using SPI transfer with unequal buffer sizes (#97, #98).
## [v0.4.0-alpha.3] - 2022-08-04
### Added
- Added feature flag for `spi` and `i2c`
### Changed
- Updated to `embedded-hal` `1.0.0-alpha.8` release ([API changes](https://github.com/rust-embedded/embedded-hal/blob/master/embedded-hal/CHANGELOG.md#v100-alpha8---2022-04-15))
## [v0.4.0-alpha.2] - 2022-02-15
### Added
- Mappings for `embedded-hal` error kinds
### Changed
- Updated to `embedded-hal` `1.0.0-alpha.7` release (significant [API changes](https://github.com/rust-embedded/embedded-hal/blob/master/embedded-hal/CHANGELOG.md#v100-alpha7---2022-02-09))
- Updated dependencies to force use of newer nix version
- `spidev` to version `0.5.1`
- `i2cdev` to version `0.5.1`
- `gpio-cdev` to version `0.5.1`
- `sysfs_gpio` to version `0.6.1`
## [v0.4.0-alpha.1] - 2021-10-07
### Added
- Implement `embedded_hal::digital::blocking::IoPin` for `CdevPin` and `SysfsPin`
- `CountDown` implementation for `SysTimer`.
- `Default` implementation for `SysTimer`.
### Changed
- Modified `OutputPin` behavior for active-low pins to match `InputPin` behavior.
- Set default features to build both sysfs and cdev pin types.
- Removed `Pin` export, use `CdevPin` or `SysfsPin`.
- Adapted to `embedded-hal` `1.0.0-alpha.5` release.
- Increased the Minimum Supported Rust Version to `1.46.0` due to an update of `bitflags`.
- Updated `spidev` to version `0.5`.
- Updated `i2cdev` to version `0.5`.
- Updated `gpio-cdev` to version `0.5`.
- Updated `sysfs_gpio` to version `0.6`.
- Updated `nb` to version `1`.
## [v0.3.2] - 2021-10-25
### Fixed
- Readd `Pin` type export as an alias to `SysfsPin` for compatibility with the `0.3.0` version.
## [v0.3.1] - 2021-09-27
### Added
- Added implementation of transactional SPI and I2C traits.
- `CountDown` implementation for `SysTimer`.
- `Default` implementation for `SysTimer`.
### Changed
- Set default features to build both sysfs and cdev pin types.
- Removed `Pin` export, use `CdevPin` or `SysfsPin`.
- Updated `embedded-hal` to version `0.2.6`.
- Updated `nb` to version `0.1.3`.
- Updated `gpio-cdev` to version `0.5`.
- Updated `i2cdev` to version `0.5`.
- Updated `spidev` to version `0.5`.
- Updated `sysfs-gpio` to version `0.6`.
- Updated `cast` to version `0.3`.
### Fixed
- Modified `OutputPin` behavior for active-low pins to match `InputPin` behavior.
## [v0.3.0] - 2019-11-25
### Added
- Added serial::Read/Write implementation.
- Added feature flag for Chardev GPIO
### Fixed
- Do write and read in one transaction in WriteRead implementation.
- Removed #[deny(warnings)]
### Changed
- Use embedded-hal::digital::v2 traits.
- Updated to i2cdev 0.4.3 (necessary for trasactional write-read).
- Updated to spidev 0.4
- Added feature flag for Sysfs GPIO
## [v0.2.2] - 2018-12-21
### Changed
- updated to i2cdev 0.4.1 (removes superflous dependencies)
## [v0.2.1] - 2018-10-25
### Added
- implementation of the unproven `embedded_hal::::digital::InputPin` trait.
## [v0.2.0] - 2018-05-14
### Changed
- [breaking-change] moved to v0.2.x of `embedded-hal`.
## [v0.1.1] - 2018-02-13
### Added
- implementation of `embedded_hal::blocking::Delay*` traits in the form of the `Delay` zero sized
type.
- implementation of the `embedded_hal::blocking::i2c` traits in the form of the `I2cdev` newtype.
## v0.1.0 - 2018-01-17
Initial release
[Unreleased]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.4.0...HEAD
[v0.4.0]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.4.0-alpha.4...v0.4.0
[v0.4.0-alpha.4]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.4.0-alpha.3...v0.4.0-alpha.4
[v0.4.0-alpha.3]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.4.0-alpha.2...v0.4.0-alpha.3
[v0.4.0-alpha.2]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.4.0-alpha.1...v0.4.0-alpha.2
[v0.4.0-alpha.1]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.3.0...v0.4.0-alpha.1
[v0.3.2]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.3.1...v0.3.2
[v0.3.1]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.3.0...v0.3.1
[v0.3.0]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.2.2...v0.3.0
[v0.2.2]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.2.1...v0.2.2
[v0.2.1]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.2.0...v0.2.1
[v0.2.0]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.1.1...v0.2.0
[v0.1.1]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.1.0...v0.1.1
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# The Rust Code of Conduct
## Conduct
**Contact**: [HAL team](https://github.com/rust-embedded/wg#the-hal-team)
* We are committed to providing a friendly, safe and welcoming environment for all, regardless of level of experience, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, nationality, or other similar characteristic.
* On IRC, please avoid using overtly sexual nicknames or other nicknames that might detract from a friendly, safe and welcoming environment for all.
* Please be kind and courteous. There's no need to be mean or rude.
* Respect that people have differences of opinion and that every design or implementation choice carries a trade-off and numerous costs. There is seldom a right answer.
* Please keep unstructured critique to a minimum. If you have solid ideas you want to experiment with, make a fork and see how it works.
* We will exclude you from interaction if you insult, demean or harass anyone. That is not welcome behavior. We interpret the term "harassment" as including the definition in the [Citizen Code of Conduct](http://citizencodeofconduct.org/); if you have any lack of clarity about what might be included in that concept, please read their definition. In particular, we don't tolerate behavior that excludes people in socially marginalized groups.
* Private harassment is also unacceptable. No matter who you are, if you feel you have been or are being harassed or made uncomfortable by a community member, please contact one of the channel ops or any of the [HAL team][team] immediately. Whether you're a regular contributor or a newcomer, we care about making this community a safe place for you and we've got your back.
* Likewise any spamming, trolling, flaming, baiting or other attention-stealing behavior is not welcome.
## Moderation
These are the policies for upholding our community's standards of conduct.
1. Remarks that violate the Rust standards of conduct, including hateful, hurtful, oppressive, or exclusionary remarks, are not allowed. (Cursing is allowed, but never targeting another user, and never in a hateful manner.)
2. Remarks that moderators find inappropriate, whether listed in the code of conduct or not, are also not allowed.
3. Moderators will first respond to such remarks with a warning.
4. If the warning is unheeded, the user will be "kicked," i.e., kicked out of the communication channel to cool off.
5. If the user comes back and continues to make trouble, they will be banned, i.e., indefinitely excluded.
6. Moderators may choose at their discretion to un-ban the user if it was a first offense and they offer the offended party a genuine apology.
7. If a moderator bans someone and you think it was unjustified, please take it up with that moderator, or with a different moderator, **in private**. Complaints about bans in-channel are not allowed.
8. Moderators are held to a higher standard than other community members. If a moderator creates an inappropriate situation, they should expect less leeway than others.
In the Rust community we strive to go the extra step to look out for each other. Don't just aim to be technically unimpeachable, try to be your best self. In particular, avoid flirting with offensive or sensitive issues, particularly if they're off-topic; this all too often leads to unnecessary fights, hurt feelings, and damaged trust; worse, it can drive people away from the community entirely.
And if someone takes issue with something you said or did, resist the urge to be defensive. Just stop doing what it was they complained about and apologize. Even if you feel you were misinterpreted or unfairly accused, chances are good there was something you could've communicated better — remember that it's your responsibility to make your fellow Rustaceans comfortable. Everyone wants to get along and we are all here first and foremost because we want to talk about cool technology. You will find that people will be eager to assume good intent and forgive as long as you earn their trust.
The enforcement policies listed above apply to all official embedded WG venues; including official IRC channels (#rust-embedded); GitHub repositories under rust-embedded; and all forums under rust-embedded.org (forum.rust-embedded.org).
*Adapted from the [Node.js Policy on Trolling](http://blog.izs.me/post/30036893703/policy-on-trolling) as well as the [Contributor Covenant v1.3.0](https://www.contributor-covenant.org/version/1/3/0/).*
[team]: https://github.com/rust-embedded/wg#the-hal-team
================================================
FILE: Cargo.toml
================================================
[package]
authors = [
"The Embedded Linux Team <embedded-linux@teams.rust-embedded.org>",
"Jorge Aparicio <jorge@japaric.io>"
]
categories = ["embedded", "hardware-support"]
description = "Implementation of the `embedded-hal` traits for Linux devices"
keywords = ["Linux", "hal"]
license = "MIT OR Apache-2.0"
name = "linux-embedded-hal"
repository = "https://github.com/rust-embedded/linux-embedded-hal"
version = "0.5.0-alpha.0"
edition = "2018"
rust-version = "1.84"
resolver = "3"
[features]
gpio_sysfs = ["sysfs_gpio"]
gpio_cdev = ["gpio-cdev"]
async-tokio = ["gpio-cdev/async-tokio", "dep:embedded-hal-async", "tokio/time"]
i2c = ["i2cdev", "nix"]
spi = ["spidev"]
serial = ["serialport", "embedded-hal-nb"]
default = [ "gpio_cdev", "gpio_sysfs", "i2c", "spi", "serial" ]
[dependencies]
embedded-hal = "1"
embedded-hal-nb = { version = "1", optional = true }
embedded-hal-async = { version = "1", optional = true }
gpio-cdev = { version = "0.6.0", optional = true }
sysfs_gpio = { version = "0.6.1", optional = true }
i2cdev = { version = "0.6.0", optional = true }
nb = "1"
serialport = { version = "4.2.0", default-features = false, optional = true }
spidev = { version = "0.6.1", optional = true }
nix = { version = "0.27.1", optional = true }
tokio = { version = "1", default-features = false, optional = true }
[dev-dependencies]
openpty = "0.2.0"
[dependencies.cast]
# we don't need the `Error` implementation
default-features = false
version = "0.3"
================================================
FILE: LICENSE-APACHE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: LICENSE-MIT
================================================
Copyright (c) 2018 Jorge Aparicio
Copyright (c) 2019-2024 The Rust embedded linux team and contributors.
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
================================================
FILE: README.md
================================================
[](https://crates.io/crates/linux-embedded-hal)
[](https://crates.io/crates/linux-embedded-hal)
[](https://docs.rs/linux-embedded-hal)

# `linux-embedded-hal`
> Implementation of the [`embedded-hal`] traits for Linux devices
This project is developed and maintained by the [Embedded Linux team][team].
[`embedded-hal`]: https://crates.io/crates/embedded-hal
## [Documentation](https://docs.rs/linux-embedded-hal)
## GPIO character device
Since Linux kernel v4.4 the use of sysfs GPIO was deprecated and replaced by the character device GPIO.
See [gpio-cdev documentation](https://github.com/rust-embedded/gpio-cdev#sysfs-gpio-vs-gpio-character-device) for details.
This crate includes feature flag `gpio_cdev` that exposes `CdevPin` as wrapper around `LineHandle` from [gpio-cdev](https://crates.io/crates/gpio-cdev).
To enable it update your Cargo.toml. Please note that in order to prevent `LineHandle` fd from closing you should
assign to a variable, see [cdev issue](https://github.com/rust-embedded/gpio-cdev/issues/29) for more details.
```
linux-embedded-hal = { version = "0.4", features = ["gpio_cdev"] }
```
`SysfsPin` can be still used with feature flag `gpio_sysfs`.
With `default-features = false` you can enable the features `gpio_cdev`, `gpio_sysfs`, `i2c`, and `spi` as needed.
## Minimum Supported Rust Version (MSRV)
This crate is guaranteed to compile on stable Rust 1.84.0 and up. It *might*
compile with older versions but that may change in any new patch release.
## License
Licensed under either of
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or
http://www.apache.org/licenses/LICENSE-2.0)
- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.
## Code of Conduct
Contribution to this crate is organized under the terms of the [Rust Code of
Conduct][CoC], the maintainer of this crate, the [HAL team][team], promises
to intervene to uphold that code of conduct.
[CoC]: CODE_OF_CONDUCT.md
[team]: https://github.com/rust-embedded/wg/#the-embedded-linux-team
================================================
FILE: examples/transactional-i2c.rs
================================================
use embedded_hal::i2c::{I2c, Operation as I2cOperation};
use linux_embedded_hal::I2cdev;
const ADDR: u8 = 0x12;
struct Driver<I2C> {
i2c: I2C,
}
impl<I2C> Driver<I2C>
where
I2C: I2c,
{
pub fn new(i2c: I2C) -> Self {
Driver { i2c }
}
fn read_something(&mut self) -> Result<u8, I2C::Error> {
let mut read_buffer = [0];
let mut ops = [
I2cOperation::Write(&[0xAB]),
I2cOperation::Read(&mut read_buffer),
];
self.i2c.transaction(ADDR, &mut ops).and(Ok(read_buffer[0]))
}
}
fn main() {
let dev = I2cdev::new("/dev/i2c-1").unwrap();
let mut driver = Driver::new(dev);
let value = driver.read_something().unwrap();
println!("Read value: {}", value);
}
================================================
FILE: src/cdev_pin.rs
================================================
//! Implementation of [`embedded-hal`] digital input/output traits using a Linux CDev pin
//!
//! [`embedded-hal`]: https://docs.rs/embedded-hal
use std::fmt;
/// Newtype around [`gpio_cdev::LineHandle`] that implements the `embedded-hal` traits
///
/// [`gpio_cdev::LineHandle`]: https://docs.rs/gpio-cdev/0.5.0/gpio_cdev/struct.LineHandle.html
pub struct CdevPin(pub gpio_cdev::LineHandle, gpio_cdev::LineInfo);
impl CdevPin {
/// See [`gpio_cdev::Line::request`][0] for details.
///
/// [0]: https://docs.rs/gpio-cdev/0.5.0/gpio_cdev/struct.Line.html#method.request
pub fn new(handle: gpio_cdev::LineHandle) -> Result<Self, gpio_cdev::errors::Error> {
let info = handle.line().info()?;
Ok(CdevPin(handle, info))
}
fn get_input_flags(&self) -> gpio_cdev::LineRequestFlags {
if self.1.is_active_low() {
return gpio_cdev::LineRequestFlags::INPUT | gpio_cdev::LineRequestFlags::ACTIVE_LOW;
}
gpio_cdev::LineRequestFlags::INPUT
}
fn get_output_flags(&self) -> gpio_cdev::LineRequestFlags {
let mut flags = gpio_cdev::LineRequestFlags::OUTPUT;
if self.1.is_active_low() {
flags.insert(gpio_cdev::LineRequestFlags::ACTIVE_LOW);
}
if self.1.is_open_drain() {
flags.insert(gpio_cdev::LineRequestFlags::OPEN_DRAIN);
} else if self.1.is_open_source() {
flags.insert(gpio_cdev::LineRequestFlags::OPEN_SOURCE);
}
flags
}
/// Set this pin to input mode
pub fn into_input_pin(self) -> Result<CdevPin, gpio_cdev::errors::Error> {
if self.1.direction() == gpio_cdev::LineDirection::In {
return Ok(self);
}
let line = self.0.line().clone();
let input_flags = self.get_input_flags();
let consumer = self.1.consumer().unwrap_or("").to_owned();
// Drop self to free the line before re-requesting it in a new mode.
std::mem::drop(self);
CdevPin::new(line.request(input_flags, 0, &consumer)?)
}
/// Set this pin to output mode
pub fn into_output_pin(
self,
state: embedded_hal::digital::PinState,
) -> Result<CdevPin, gpio_cdev::errors::Error> {
if self.1.direction() == gpio_cdev::LineDirection::Out {
return Ok(self);
}
let line = self.0.line().clone();
let output_flags = self.get_output_flags();
let consumer = self.1.consumer().unwrap_or("").to_owned();
// Drop self to free the line before re-requesting it in a new mode.
std::mem::drop(self);
let is_active_low = output_flags.intersects(gpio_cdev::LineRequestFlags::ACTIVE_LOW);
CdevPin::new(line.request(
output_flags,
state_to_value(state, is_active_low),
&consumer,
)?)
}
}
/// Converts a pin state to the gpio_cdev compatible numeric value, accounting
/// for the active_low condition.
fn state_to_value(state: embedded_hal::digital::PinState, is_active_low: bool) -> u8 {
if is_active_low {
match state {
embedded_hal::digital::PinState::High => 0,
embedded_hal::digital::PinState::Low => 1,
}
} else {
match state {
embedded_hal::digital::PinState::High => 1,
embedded_hal::digital::PinState::Low => 0,
}
}
}
/// Error type wrapping [gpio_cdev::errors::Error](gpio_cdev::errors::Error) to implement [embedded_hal::digital::Error]
#[derive(Debug)]
pub struct CdevPinError {
err: gpio_cdev::errors::Error,
}
impl CdevPinError {
/// Fetch inner (concrete) [`gpio_cdev::errors::Error`]
pub fn inner(&self) -> &gpio_cdev::errors::Error {
&self.err
}
}
impl From<gpio_cdev::errors::Error> for CdevPinError {
fn from(err: gpio_cdev::errors::Error) -> Self {
Self { err }
}
}
impl fmt::Display for CdevPinError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.err)
}
}
impl std::error::Error for CdevPinError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.err)
}
}
impl embedded_hal::digital::Error for CdevPinError {
fn kind(&self) -> embedded_hal::digital::ErrorKind {
use embedded_hal::digital::ErrorKind;
ErrorKind::Other
}
}
impl embedded_hal::digital::ErrorType for CdevPin {
type Error = CdevPinError;
}
impl embedded_hal::digital::OutputPin for CdevPin {
fn set_low(&mut self) -> Result<(), Self::Error> {
self.0
.set_value(state_to_value(
embedded_hal::digital::PinState::Low,
self.1.is_active_low(),
))
.map_err(CdevPinError::from)
}
fn set_high(&mut self) -> Result<(), Self::Error> {
self.0
.set_value(state_to_value(
embedded_hal::digital::PinState::High,
self.1.is_active_low(),
))
.map_err(CdevPinError::from)
}
}
impl embedded_hal::digital::InputPin for CdevPin {
fn is_high(&mut self) -> Result<bool, Self::Error> {
self.0
.get_value()
.map(|val| {
val == state_to_value(
embedded_hal::digital::PinState::High,
self.1.is_active_low(),
)
})
.map_err(CdevPinError::from)
}
fn is_low(&mut self) -> Result<bool, Self::Error> {
self.is_high().map(|val| !val)
}
}
impl core::ops::Deref for CdevPin {
type Target = gpio_cdev::LineHandle;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for CdevPin {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
================================================
FILE: src/delay.rs
================================================
//! Implementation of [`embedded-hal`] delay traits
//!
//! [`embedded-hal`]: https://docs.rs/embedded-hal
use embedded_hal::delay::DelayNs;
use std::thread;
use std::time::Duration;
/// Empty struct that provides delay functionality on top of `thread::sleep`,
/// and `tokio::time::sleep` if the `async-tokio` feature is enabled.
pub struct Delay;
impl DelayNs for Delay {
fn delay_ns(&mut self, n: u32) {
thread::sleep(Duration::from_nanos(n.into()));
}
fn delay_us(&mut self, n: u32) {
thread::sleep(Duration::from_micros(n.into()));
}
fn delay_ms(&mut self, n: u32) {
thread::sleep(Duration::from_millis(n.into()));
}
}
#[cfg(feature = "async-tokio")]
impl embedded_hal_async::delay::DelayNs for Delay {
async fn delay_ns(&mut self, n: u32) {
tokio::time::sleep(Duration::from_nanos(n.into())).await;
}
async fn delay_us(&mut self, n: u32) {
tokio::time::sleep(Duration::from_micros(n.into())).await;
}
async fn delay_ms(&mut self, n: u32) {
tokio::time::sleep(Duration::from_millis(n.into())).await;
}
}
================================================
FILE: src/i2c.rs
================================================
//! Implementation of [`embedded-hal`] I2C traits
//!
//! [`embedded-hal`]: https://docs.rs/embedded-hal
use std::fmt;
use std::ops;
use std::path::{Path, PathBuf};
use embedded_hal::i2c::NoAcknowledgeSource;
/// Newtype around [`i2cdev::linux::LinuxI2CDevice`] that implements the `embedded-hal` traits
///
/// [`i2cdev::linux::LinuxI2CDevice`]: https://docs.rs/i2cdev/0.5.0/i2cdev/linux/struct.LinuxI2CDevice.html
pub struct I2cdev {
inner: i2cdev::linux::LinuxI2CDevice,
path: PathBuf,
address: Option<u16>,
}
impl I2cdev {
/// See [`i2cdev::linux::LinuxI2CDevice::new`][0] for details.
///
/// [0]: https://docs.rs/i2cdev/0.5.0/i2cdev/linux/struct.LinuxI2CDevice.html#method.new
pub fn new<P>(path: P) -> Result<Self, i2cdev::linux::LinuxI2CError>
where
P: AsRef<Path>,
{
let dev = I2cdev {
path: path.as_ref().to_path_buf(),
inner: i2cdev::linux::LinuxI2CDevice::new(path, 0)?,
address: None,
};
Ok(dev)
}
fn set_address(&mut self, address: u16) -> Result<(), i2cdev::linux::LinuxI2CError> {
if self.address != Some(address) {
self.inner = i2cdev::linux::LinuxI2CDevice::new(&self.path, address)?;
self.address = Some(address);
}
Ok(())
}
}
impl ops::Deref for I2cdev {
type Target = i2cdev::linux::LinuxI2CDevice;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl ops::DerefMut for I2cdev {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
mod embedded_hal_impl {
use super::*;
use embedded_hal::i2c::ErrorType;
use embedded_hal::i2c::{I2c, Operation as I2cOperation, SevenBitAddress, TenBitAddress};
use i2cdev::core::{I2CMessage, I2CTransfer};
use i2cdev::linux::LinuxI2CMessage;
impl ErrorType for I2cdev {
type Error = I2CError;
}
impl I2c<TenBitAddress> for I2cdev {
fn transaction(
&mut self,
address: u16,
operations: &mut [I2cOperation],
) -> Result<(), Self::Error> {
// Map operations from generic to linux objects
let mut messages: Vec<_> = operations
.as_mut()
.iter_mut()
.map(|a| match a {
I2cOperation::Write(w) => LinuxI2CMessage::write(w),
I2cOperation::Read(r) => LinuxI2CMessage::read(r),
})
.collect();
self.set_address(address)?;
self.inner
.transfer(&mut messages)
.map(drop)
.map_err(|err| I2CError { err })
}
}
impl I2c<SevenBitAddress> for I2cdev {
fn transaction(
&mut self,
address: u8,
operations: &mut [I2cOperation],
) -> Result<(), Self::Error> {
I2c::<TenBitAddress>::transaction(self, u16::from(address), operations)
}
}
}
/// Error type wrapping [LinuxI2CError](i2cdev::linux::LinuxI2CError) to implement [embedded_hal::i2c::ErrorKind]
#[derive(Debug)]
pub struct I2CError {
err: i2cdev::linux::LinuxI2CError,
}
impl I2CError {
/// Fetch inner (concrete) [`LinuxI2CError`]
pub fn inner(&self) -> &i2cdev::linux::LinuxI2CError {
&self.err
}
}
impl From<i2cdev::linux::LinuxI2CError> for I2CError {
fn from(err: i2cdev::linux::LinuxI2CError) -> Self {
Self { err }
}
}
impl fmt::Display for I2CError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.err)
}
}
impl std::error::Error for I2CError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.err)
}
}
impl embedded_hal::i2c::Error for I2CError {
fn kind(&self) -> embedded_hal::i2c::ErrorKind {
use embedded_hal::i2c::ErrorKind;
use nix::errno::Errno::*;
let errno = match &self.err {
i2cdev::linux::LinuxI2CError::Errno(e) => nix::Error::from_i32(*e),
i2cdev::linux::LinuxI2CError::Io(e) => match e.raw_os_error() {
Some(r) => nix::Error::from_i32(r),
None => return ErrorKind::Other,
},
};
// https://www.kernel.org/doc/html/latest/i2c/fault-codes.html
match errno {
EBUSY | EINVAL | EIO => ErrorKind::Bus,
EAGAIN => ErrorKind::ArbitrationLoss,
ENODEV => ErrorKind::NoAcknowledge(NoAcknowledgeSource::Data),
ENXIO => ErrorKind::NoAcknowledge(NoAcknowledgeSource::Address),
_ => ErrorKind::Other,
}
}
}
================================================
FILE: src/lib.rs
================================================
//! Implementation of [`embedded-hal`] traits for Linux devices
//!
//! [`embedded-hal`]: https://docs.rs/embedded-hal
//!
//! # Drivers
//!
//! This crate lets you use a bunch of platform agnostic drivers that are based on the
//! `embedded-hal` traits. You can find them on crates.io by [searching for the embedded-hal
//! keyword][0].
//!
//! [0]: https://crates.io/keywords/embedded-hal
#![deny(missing_docs)]
#[cfg(feature = "i2c")]
pub use i2cdev;
pub use nb;
#[cfg(feature = "serial")]
pub use serialport;
#[cfg(feature = "spi")]
pub use spidev;
#[cfg(feature = "gpio_sysfs")]
pub use sysfs_gpio;
#[cfg(feature = "gpio_cdev")]
pub use gpio_cdev;
#[cfg(feature = "gpio_sysfs")]
/// Sysfs Pin wrapper module
mod sysfs_pin;
#[cfg(feature = "gpio_cdev")]
/// Cdev Pin wrapper module
mod cdev_pin;
#[cfg(feature = "gpio_cdev")]
/// Cdev pin re-export
pub use cdev_pin::{CdevPin, CdevPinError};
#[cfg(feature = "gpio_sysfs")]
/// Sysfs pin re-export
pub use sysfs_pin::{SysfsPin, SysfsPinError};
mod delay;
#[cfg(feature = "i2c")]
mod i2c;
#[cfg(feature = "serial")]
mod serial;
#[cfg(feature = "spi")]
mod spi;
mod timer;
pub use crate::delay::Delay;
#[cfg(feature = "i2c")]
pub use crate::i2c::{I2CError, I2cdev};
#[cfg(feature = "serial")]
pub use crate::serial::{Serial, SerialError};
#[cfg(feature = "spi")]
pub use crate::spi::{SPIError, SpidevBus, SpidevDevice};
pub use crate::timer::{CountDown, Periodic, SysTimer};
================================================
FILE: src/serial.rs
================================================
//! Implementation of [`embedded-hal`] serial traits
//!
//! [`embedded-hal`]: https://docs.rs/embedded-hal
use serialport::{SerialPortBuilder, TTYPort};
use std::fmt;
use std::io::{ErrorKind as IoErrorKind, Read, Write};
/// Newtype around [`serialport::TTYPort`] that implements
/// the `embedded-hal` traits.
pub struct Serial(pub TTYPort);
impl Serial {
/// Open a `serialport::TTYPort` by providing the port path and baud rate
pub fn open(path: String, baud_rate: u32) -> Result<Serial, serialport::Error> {
Ok(Serial(serialport::new(path, baud_rate).open_native()?))
}
/// Open a `serialport::TTYPort` by providing `serialport::SerialPortBuilder`
pub fn open_from_builder(builder: SerialPortBuilder) -> Result<Serial, serialport::Error> {
Ok(Serial(builder.open_native()?))
}
}
/// Helper to convert std::io::Error to the nb::Error
fn translate_io_errors(err: std::io::Error) -> nb::Error<SerialError> {
match err.kind() {
IoErrorKind::WouldBlock | IoErrorKind::TimedOut | IoErrorKind::Interrupted => {
nb::Error::WouldBlock
}
err => nb::Error::Other(SerialError { err }),
}
}
impl embedded_hal_nb::serial::ErrorType for Serial {
type Error = SerialError;
}
impl embedded_hal_nb::serial::Read<u8> for Serial {
fn read(&mut self) -> nb::Result<u8, Self::Error> {
let mut buffer = [0; 1];
let bytes_read = self.0.read(&mut buffer).map_err(translate_io_errors)?;
if bytes_read == 1 {
Ok(buffer[0])
} else {
Err(nb::Error::WouldBlock)
}
}
}
impl embedded_hal_nb::serial::Write<u8> for Serial {
fn write(&mut self, word: u8) -> nb::Result<(), Self::Error> {
self.0.write(&[word]).map_err(translate_io_errors)?;
Ok(())
}
fn flush(&mut self) -> nb::Result<(), Self::Error> {
self.0.flush().map_err(translate_io_errors)
}
}
/// Error type wrapping [io::ErrorKind](IoErrorKind) to implement [embedded_hal::serial::ErrorKind]
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct SerialError {
err: IoErrorKind,
}
impl SerialError {
/// Fetch inner (concrete) [`IoErrorKind`]
pub fn inner(&self) -> &IoErrorKind {
&self.err
}
}
impl fmt::Display for SerialError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.err)
}
}
impl std::error::Error for SerialError {}
impl embedded_hal_nb::serial::Error for SerialError {
#[allow(clippy::match_single_binding)]
fn kind(&self) -> embedded_hal_nb::serial::ErrorKind {
use embedded_hal_nb::serial::ErrorKind::*;
// TODO: match any errors here if we can find any that are relevant
Other
}
}
#[cfg(test)]
mod test {
use embedded_hal_nb::serial::{Read, Write};
use std::io::{Read as IoRead, Write as IoWrite};
use super::*;
fn create_pty_and_serial() -> (std::fs::File, Serial) {
let (master, _slave, name) =
openpty::openpty(None, None, None).expect("Creating pty failed");
let serial = Serial::open(name, 9600).expect("Creating TTYPort failed");
(master, serial)
}
#[test]
fn create_serial_from_builder() {
let (_master, _slave, name) =
openpty::openpty(None, None, None).expect("Creating pty failed");
let builder = serialport::new(name, 9600);
let _serial = Serial::open_from_builder(builder).expect("Creating TTYPort failed");
}
#[test]
fn test_empty_read() {
let (mut _master, mut serial) = create_pty_and_serial();
assert_eq!(Err(nb::Error::WouldBlock), serial.read());
}
#[test]
fn test_read() {
let (mut master, mut serial) = create_pty_and_serial();
master.write_all(&[1]).expect("Write failed");
assert_eq!(Ok(1), serial.read());
}
#[test]
fn test_write() {
let (mut master, mut serial) = create_pty_and_serial();
serial.write(2).expect("Write failed");
let mut buf = [0; 2];
assert_eq!(1, master.read(&mut buf).unwrap());
assert_eq!(buf, [2, 0]);
}
}
================================================
FILE: src/spi.rs
================================================
//! Implementation of [`embedded-hal`] SPI traits
//!
//! [`embedded-hal`]: https://docs.rs/embedded-hal
//!
use std::cmp::Ordering;
use std::fmt;
use std::io;
use std::ops;
use std::path::Path;
/// Spidev wrapper providing the embedded-hal [`SpiDevice`] trait.
///
/// Use this struct when you want a single spidev device, using a Linux-managed CS (chip-select) pin,
/// which is already defined in your device tree. Linux will handle sharing the bus
/// between different SPI devices, even between different processes.
///
/// You get an object that implements [`SpiDevice`], which is what most drivers require,
/// but does not implement [`SpiBus`]. In some rare cases, you may require [`SpiBus`]
/// instead; for that refer to [`SpidevBus`] below. You may also want to use [`SpiBus`]
/// if you want to handle all the CS pins yourself using GPIO.
///
/// This struct wraps a [`spidev::Spidev`] struct, so it can be constructed directly
/// and the inner struct accessed if needed, for example to (re)configure the SPI settings.
///
/// Note that [delay operations] on this device are capped to 65535 microseconds.
///
/// [`SpiDevice`]: embedded_hal::spi::SpiDevice
/// [`SpiBus`]: embedded_hal::spi::SpiBus
/// [`spidev::Spidev`]: spidev::Spidev
/// [delay operations]: embedded_hal::spi::Operation::DelayUs
pub struct SpidevDevice(pub spidev::Spidev);
/// Spidev wrapper providing the embedded-hal [`SpiBus`] trait.
///
/// Use this struct when you require direct access to the underlying SPI bus, for
/// example when you want to use GPIOs as software-controlled CS (chip-select) pins to share the
/// bus with multiple devices, or because a driver requires the entire bus (for
/// example to drive smart LEDs).
///
/// Do not use this struct if you're accessing SPI devices that already appear in your
/// device tree; you will not be able to drive CS pins that are already used by `spidev`
/// as GPIOs. Instead use [`SpidevDevice`].
///
/// This struct must still be created from a [`spidev::Spidev`] device, but there are two
/// important notes:
///
/// 1. The CS pin associated with this `spidev` device will be driven whenever any device accesses
/// this bus, so it should be an unconnected or unused pin.
/// 2. No other `spidev` device on the same bus may be used as long as this `SpidevBus` exists,
/// as Linux will _not_ do anything to ensure this bus has exclusive access.
///
/// It is recommended to use a dummy `spidev` device associated with an unused CS pin, and then use
/// regular GPIOs as CS pins if required. If you are planning to share this bus using GPIOs, the
/// [`embedded-hal-bus`] crate may be of interest.
///
/// If necessary, you can [configure] the underlying [`spidev::Spidev`] instance with the
/// [`SPI_NO_CS`] flag set to prevent any CS pin activity.
///
/// [`SpiDevice`]: embedded_hal::spi::SpiDevice
/// [`SpiBus`]: embedded_hal::spi::SpiBus
/// [`embedded-hal-bus`]: https://docs.rs/embedded-hal-bus/
/// [`spidev::Spidev`]: spidev::Spidev
/// [delay operations]: embedded_hal::spi::Operation::DelayUs
/// [configure]: spidev::Spidev::configure
/// [`SPI_NO_CS`]: spidev::SpiModeFlags::SPI_NO_CS
pub struct SpidevBus(pub spidev::Spidev);
impl SpidevDevice {
/// See [`spidev::Spidev::open`] for details.
///
/// The provided `path` is for the specific device you wish to access.
/// Access to the bus is shared with other devices via the Linux kernel.
pub fn open<P>(path: P) -> Result<Self, SPIError>
where
P: AsRef<Path>,
{
spidev::Spidev::open(path)
.map(SpidevDevice)
.map_err(|e| e.into())
}
}
impl SpidevBus {
/// See [`spidev::Spidev::open`] for details.
///
/// The provided `path` must be the _only_ device in use on its bus,
/// and note its own CS pin will be asserted for all device access,
/// so the path should be to a dummy device used only to access
/// the underlying bus.
pub fn open<P>(path: P) -> Result<Self, SPIError>
where
P: AsRef<Path>,
{
spidev::Spidev::open(path)
.map(SpidevBus)
.map_err(|e| e.into())
}
}
impl ops::Deref for SpidevDevice {
type Target = spidev::Spidev;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ops::DerefMut for SpidevDevice {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl ops::Deref for SpidevBus {
type Target = spidev::Spidev;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ops::DerefMut for SpidevBus {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
mod embedded_hal_impl {
use super::*;
use embedded_hal::spi::ErrorType;
use embedded_hal::spi::{Operation as SpiOperation, SpiBus, SpiDevice};
use spidev::SpidevTransfer;
use std::convert::TryInto;
use std::io::{Read, Write};
impl ErrorType for SpidevDevice {
type Error = SPIError;
}
impl ErrorType for SpidevBus {
type Error = SPIError;
}
impl SpiBus<u8> for SpidevBus {
fn read(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
self.0.read_exact(words).map_err(|err| SPIError { err })
}
fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {
self.0.write_all(words).map_err(|err| SPIError { err })
}
fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Self::Error> {
let read_len = read.len();
match read_len.cmp(&write.len()) {
Ordering::Less => self.0.transfer_multiple(&mut [
SpidevTransfer::read_write(&write[..read_len], read),
SpidevTransfer::write(&write[read_len..]),
]),
Ordering::Equal => self
.0
.transfer(&mut SpidevTransfer::read_write(write, read)),
Ordering::Greater => {
let (read1, read2) = read.split_at_mut(write.len());
self.0.transfer_multiple(&mut [
SpidevTransfer::read_write(write, read1),
SpidevTransfer::read(read2),
])
}
}
.map_err(|err| SPIError { err })
}
fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
self.0
.transfer(&mut SpidevTransfer::read_write_in_place(words))
.map_err(|err| SPIError { err })
}
fn flush(&mut self) -> Result<(), Self::Error> {
self.0.flush().map_err(|err| SPIError { err })
}
}
impl SpiDevice for SpidevDevice {
/// Perform a transaction against the device. [Read more][transaction]
///
/// [Delay operations][delay] are capped to 65535 microseconds.
///
/// [transaction]: SpiDevice::transaction
/// [delay]: SpiOperation::DelayUs
fn transaction(
&mut self,
operations: &mut [SpiOperation<'_, u8>],
) -> Result<(), Self::Error> {
let mut transfers = Vec::with_capacity(operations.len());
for op in operations {
match op {
SpiOperation::Read(buf) => transfers.push(SpidevTransfer::read(buf)),
SpiOperation::Write(buf) => transfers.push(SpidevTransfer::write(buf)),
SpiOperation::Transfer(read, write) => match read.len().cmp(&write.len()) {
Ordering::Less => {
let n = read.len();
transfers.push(SpidevTransfer::read_write(&write[..n], read));
transfers.push(SpidevTransfer::write(&write[n..]));
}
Ordering::Equal => transfers.push(SpidevTransfer::read_write(write, read)),
Ordering::Greater => {
let (read1, read2) = read.split_at_mut(write.len());
transfers.push(SpidevTransfer::read_write(write, read1));
transfers.push(SpidevTransfer::read(read2));
}
},
SpiOperation::TransferInPlace(buf) => {
transfers.push(SpidevTransfer::read_write_in_place(buf));
}
SpiOperation::DelayNs(ns) => {
let us = {
if *ns == 0 {
0
} else {
let us = *ns / 1000;
if us == 0 {
1
} else {
(us).try_into().unwrap_or(u16::MAX)
}
}
};
transfers.push(SpidevTransfer::delay(us));
}
}
}
self.0
.transfer_multiple(&mut transfers)
.map_err(|err| SPIError { err })?;
self.flush()?;
Ok(())
}
}
}
/// Error type wrapping [io::Error](io::Error) to implement [embedded_hal::spi::ErrorKind]
#[derive(Debug)]
pub struct SPIError {
err: io::Error,
}
impl SPIError {
/// Fetch inner (concrete) [`LinuxI2CError`]
pub fn inner(&self) -> &io::Error {
&self.err
}
}
impl From<io::Error> for SPIError {
fn from(err: io::Error) -> Self {
Self { err }
}
}
impl embedded_hal::spi::Error for SPIError {
#[allow(clippy::match_single_binding)]
fn kind(&self) -> embedded_hal::spi::ErrorKind {
use embedded_hal::spi::ErrorKind;
// TODO: match any errors here if we can find any that are relevant
ErrorKind::Other
}
}
impl fmt::Display for SPIError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.err)
}
}
impl std::error::Error for SPIError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.err)
}
}
================================================
FILE: src/sysfs_pin.rs
================================================
//! Implementation of [`embedded-hal`] digital input/output traits using a Linux Sysfs pin
//!
//! [`embedded-hal`]: https://docs.rs/embedded-hal
use std::fmt;
use std::path::Path;
/// Newtype around [`sysfs_gpio::Pin`] that implements the `embedded-hal` traits
///
/// [`sysfs_gpio::Pin`]: https://docs.rs/sysfs_gpio/0.6.0/sysfs_gpio/struct.Pin.html
pub struct SysfsPin(pub sysfs_gpio::Pin);
impl SysfsPin {
/// See [`sysfs_gpio::Pin::new`][0] for details.
///
/// [0]: https://docs.rs/sysfs_gpio/0.6.0/sysfs_gpio/struct.Pin.html#method.new
pub fn new(pin_num: u64) -> Self {
SysfsPin(sysfs_gpio::Pin::new(pin_num))
}
/// See [`sysfs_gpio::Pin::from_path`][0] for details.
///
/// [0]: https://docs.rs/sysfs_gpio/0.6.0/sysfs_gpio/struct.Pin.html#method.from_path
pub fn from_path<P>(path: P) -> sysfs_gpio::Result<Self>
where
P: AsRef<Path>,
{
sysfs_gpio::Pin::from_path(path).map(SysfsPin)
}
/// Convert this pin to an input pin
pub fn into_input_pin(self) -> Result<SysfsPin, sysfs_gpio::Error> {
self.set_direction(sysfs_gpio::Direction::In)?;
Ok(self)
}
/// Convert this pin to an output pin
pub fn into_output_pin(
self,
state: embedded_hal::digital::PinState,
) -> Result<SysfsPin, sysfs_gpio::Error> {
self.set_direction(match state {
embedded_hal::digital::PinState::High => sysfs_gpio::Direction::High,
embedded_hal::digital::PinState::Low => sysfs_gpio::Direction::Low,
})?;
Ok(self)
}
}
/// Error type wrapping [sysfs_gpio::Error](sysfs_gpio::Error) to implement [embedded_hal::digital::Error]
#[derive(Debug)]
pub struct SysfsPinError {
err: sysfs_gpio::Error,
}
impl SysfsPinError {
/// Fetch inner (concrete) [`sysfs_gpio::Error`]
pub fn inner(&self) -> &sysfs_gpio::Error {
&self.err
}
}
impl From<sysfs_gpio::Error> for SysfsPinError {
fn from(err: sysfs_gpio::Error) -> Self {
Self { err }
}
}
impl fmt::Display for SysfsPinError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.err)
}
}
impl std::error::Error for SysfsPinError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.err)
}
}
impl embedded_hal::digital::Error for SysfsPinError {
fn kind(&self) -> embedded_hal::digital::ErrorKind {
use embedded_hal::digital::ErrorKind;
ErrorKind::Other
}
}
impl embedded_hal::digital::ErrorType for SysfsPin {
type Error = SysfsPinError;
}
impl embedded_hal::digital::OutputPin for SysfsPin {
fn set_low(&mut self) -> Result<(), Self::Error> {
if self.0.get_active_low().map_err(SysfsPinError::from)? {
self.0.set_value(1).map_err(SysfsPinError::from)
} else {
self.0.set_value(0).map_err(SysfsPinError::from)
}
}
fn set_high(&mut self) -> Result<(), Self::Error> {
if self.0.get_active_low().map_err(SysfsPinError::from)? {
self.0.set_value(0).map_err(SysfsPinError::from)
} else {
self.0.set_value(1).map_err(SysfsPinError::from)
}
}
}
impl embedded_hal::digital::InputPin for SysfsPin {
fn is_high(&mut self) -> Result<bool, Self::Error> {
if !self.0.get_active_low().map_err(SysfsPinError::from)? {
self.0
.get_value()
.map(|val| val != 0)
.map_err(SysfsPinError::from)
} else {
self.0
.get_value()
.map(|val| val == 0)
.map_err(SysfsPinError::from)
}
}
fn is_low(&mut self) -> Result<bool, Self::Error> {
self.is_high().map(|val| !val).map_err(SysfsPinError::from)
}
}
impl core::ops::Deref for SysfsPin {
type Target = sysfs_gpio::Pin;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for SysfsPin {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
================================================
FILE: src/timer.rs
================================================
//! Implementation of [`embedded-hal`] timer traits
//!
//! [`embedded-hal`]: https://docs.rs/embedded-hal
use core::convert::Infallible;
use std::time::{Duration, Instant};
/// Marker trait that indicates that a timer is periodic
pub trait Periodic {}
/// A count down timer
///
/// Note that this is borrowed from `embedded-hal` 0.2.x and will be in use until the `1.x` version provides one.
///
/// # Contract
///
/// - `self.start(count); block!(self.wait());` MUST block for AT LEAST the time specified by
/// `count`.
///
/// *Note* that the implementer doesn't necessarily have to be a *downcounting* timer; it could also
/// be an *upcounting* timer as long as the above contract is upheld.
///
/// # Examples
///
/// You can use this timer to create delays
///
/// ```
/// use std::time::Duration;
/// use nb::block;
/// use linux_embedded_hal::{CountDown, SysTimer};
///
/// fn main() {
/// let mut led: Led = {
/// // ..
/// # Led
/// };
/// let mut timer = SysTimer::new();
///
/// Led.on();
/// timer.start(Duration::from_millis(1000)).unwrap();
/// block!(timer.wait()); // blocks for 1 second
/// Led.off();
/// }
///
/// # use core::convert::Infallible;
/// # struct Seconds(u32);
/// # trait U32Ext { fn s(self) -> Seconds; }
/// # impl U32Ext for u32 { fn s(self) -> Seconds { Seconds(self) } }
/// # struct Led;
/// # impl Led {
/// # pub fn off(&mut self) {}
/// # pub fn on(&mut self) {}
/// # }
/// ```
pub trait CountDown {
/// An enumeration of `CountDown` errors.
///
/// For infallible implementations, will be `Infallible`
type Error: core::fmt::Debug;
/// The unit of time used by this timer
type Time;
/// Starts a new count down
fn start<T>(&mut self, count: T) -> Result<(), Self::Error>
where
T: Into<Self::Time>;
/// Non-blockingly "waits" until the count down finishes
///
/// # Contract
///
/// - If `Self: Periodic`, the timer will start a new count down right after the last one
/// finishes.
/// - Otherwise the behavior of calling `wait` after the last call returned `Ok` is UNSPECIFIED.
/// Implementers are suggested to panic on this scenario to signal a programmer error.
fn wait(&mut self) -> nb::Result<(), Self::Error>;
}
impl<T: CountDown> CountDown for &mut T {
type Error = T::Error;
type Time = T::Time;
fn start<TIME>(&mut self, count: TIME) -> Result<(), Self::Error>
where
TIME: Into<Self::Time>,
{
T::start(self, count)
}
fn wait(&mut self) -> nb::Result<(), Self::Error> {
T::wait(self)
}
}
/// A periodic timer based on [`std::time::Instant`][instant], which is a
/// monotonically nondecreasing clock.
///
/// [instant]: https://doc.rust-lang.org/std/time/struct.Instant.html
pub struct SysTimer {
start: Instant,
duration: Duration,
}
impl SysTimer {
/// Create a new timer instance.
///
/// The `duration` will be initialized to 0, so make sure to call `start`
/// with your desired timer duration before calling `wait`.
pub fn new() -> SysTimer {
SysTimer {
start: Instant::now(),
duration: Duration::from_millis(0),
}
}
}
impl Default for SysTimer {
fn default() -> SysTimer {
SysTimer::new()
}
}
impl CountDown for SysTimer {
type Error = Infallible;
type Time = Duration;
fn start<T>(&mut self, count: T) -> Result<(), Self::Error>
where
T: Into<Self::Time>,
{
self.start = Instant::now();
self.duration = count.into();
Ok(())
}
fn wait(&mut self) -> nb::Result<(), Self::Error> {
if (Instant::now() - self.start) >= self.duration {
// Restart the timer to fulfill the contract by `Periodic`
self.start = Instant::now();
Ok(())
} else {
Err(nb::Error::WouldBlock)
}
}
}
impl Periodic for SysTimer {}
#[cfg(test)]
mod tests {
use super::*;
/// Ensure that a 100 ms delay takes at least 100 ms,
/// but not longer than 500 ms.
#[test]
fn test_delay() {
let mut timer = SysTimer::new();
let before = Instant::now();
timer.start(Duration::from_millis(100)).unwrap();
nb::block!(timer.wait()).unwrap();
let after = Instant::now();
let duration_ms = (after - before).as_millis();
assert!(duration_ms >= 100);
assert!(duration_ms < 500);
}
/// Ensure that the timer is periodic.
#[test]
fn test_periodic() {
let mut timer = SysTimer::new();
let before = Instant::now();
timer.start(Duration::from_millis(100)).unwrap();
nb::block!(timer.wait()).unwrap();
let after1 = Instant::now();
let duration_ms_1 = (after1 - before).as_millis();
assert!(duration_ms_1 >= 100);
assert!(duration_ms_1 < 500);
nb::block!(timer.wait()).unwrap();
let after2 = Instant::now();
let duration_ms_2 = (after2 - after1).as_millis();
assert!(duration_ms_2 >= 100);
assert!(duration_ms_2 < 500);
}
}
gitextract_x2z4flh9/
├── .github/
│ ├── CODEOWNERS
│ └── workflows/
│ ├── ci.yml
│ ├── clippy.yml
│ └── rustfmt.yml
├── .gitignore
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── examples/
│ └── transactional-i2c.rs
└── src/
├── cdev_pin.rs
├── delay.rs
├── i2c.rs
├── lib.rs
├── serial.rs
├── spi.rs
├── sysfs_pin.rs
└── timer.rs
SYMBOL INDEX (125 symbols across 8 files)
FILE: examples/transactional-i2c.rs
constant ADDR (line 4) | const ADDR: u8 = 0x12;
type Driver (line 6) | struct Driver<I2C> {
function new (line 14) | pub fn new(i2c: I2C) -> Self {
function read_something (line 18) | fn read_something(&mut self) -> Result<u8, I2C::Error> {
function main (line 28) | fn main() {
FILE: src/cdev_pin.rs
type CdevPin (line 10) | pub struct CdevPin(pub gpio_cdev::LineHandle, gpio_cdev::LineInfo);
method new (line 16) | pub fn new(handle: gpio_cdev::LineHandle) -> Result<Self, gpio_cdev::e...
method get_input_flags (line 21) | fn get_input_flags(&self) -> gpio_cdev::LineRequestFlags {
method get_output_flags (line 28) | fn get_output_flags(&self) -> gpio_cdev::LineRequestFlags {
method into_input_pin (line 42) | pub fn into_input_pin(self) -> Result<CdevPin, gpio_cdev::errors::Erro...
method into_output_pin (line 57) | pub fn into_output_pin(
type Error (line 136) | type Error = CdevPinError;
method set_low (line 140) | fn set_low(&mut self) -> Result<(), Self::Error> {
method set_high (line 149) | fn set_high(&mut self) -> Result<(), Self::Error> {
method is_high (line 160) | fn is_high(&mut self) -> Result<bool, Self::Error> {
method is_low (line 172) | fn is_low(&mut self) -> Result<bool, Self::Error> {
type Target (line 178) | type Target = gpio_cdev::LineHandle;
method deref (line 180) | fn deref(&self) -> &Self::Target {
method deref_mut (line 186) | fn deref_mut(&mut self) -> &mut Self::Target {
function state_to_value (line 83) | fn state_to_value(state: embedded_hal::digital::PinState, is_active_low:...
type CdevPinError (line 99) | pub struct CdevPinError {
method inner (line 105) | pub fn inner(&self) -> &gpio_cdev::errors::Error {
method from (line 111) | fn from(err: gpio_cdev::errors::Error) -> Self {
method fmt (line 117) | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
method source (line 123) | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
method kind (line 129) | fn kind(&self) -> embedded_hal::digital::ErrorKind {
FILE: src/delay.rs
type Delay (line 11) | pub struct Delay;
method delay_ns (line 29) | async fn delay_ns(&mut self, n: u32) {
method delay_us (line 33) | async fn delay_us(&mut self, n: u32) {
method delay_ms (line 37) | async fn delay_ms(&mut self, n: u32) {
method delay_ns (line 14) | fn delay_ns(&mut self, n: u32) {
method delay_us (line 18) | fn delay_us(&mut self, n: u32) {
method delay_ms (line 22) | fn delay_ms(&mut self, n: u32) {
FILE: src/i2c.rs
type I2cdev (line 14) | pub struct I2cdev {
method new (line 24) | pub fn new<P>(path: P) -> Result<Self, i2cdev::linux::LinuxI2CError>
method set_address (line 36) | fn set_address(&mut self, address: u16) -> Result<(), i2cdev::linux::L...
type Target (line 46) | type Target = i2cdev::linux::LinuxI2CDevice;
method deref (line 48) | fn deref(&self) -> &Self::Target {
method deref_mut (line 54) | fn deref_mut(&mut self) -> &mut Self::Target {
method transaction (line 70) | fn transaction(
method transaction (line 94) | fn transaction(
type Error (line 66) | type Error = I2CError;
type I2CError (line 106) | pub struct I2CError {
method inner (line 112) | pub fn inner(&self) -> &i2cdev::linux::LinuxI2CError {
method from (line 118) | fn from(err: i2cdev::linux::LinuxI2CError) -> Self {
method fmt (line 124) | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
method source (line 130) | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
method kind (line 136) | fn kind(&self) -> embedded_hal::i2c::ErrorKind {
FILE: src/serial.rs
type Serial (line 11) | pub struct Serial(pub TTYPort);
method open (line 15) | pub fn open(path: String, baud_rate: u32) -> Result<Serial, serialport...
method open_from_builder (line 20) | pub fn open_from_builder(builder: SerialPortBuilder) -> Result<Serial,...
type Error (line 36) | type Error = SerialError;
method read (line 40) | fn read(&mut self) -> nb::Result<u8, Self::Error> {
method write (line 52) | fn write(&mut self, word: u8) -> nb::Result<(), Self::Error> {
method flush (line 57) | fn flush(&mut self) -> nb::Result<(), Self::Error> {
function translate_io_errors (line 26) | fn translate_io_errors(err: std::io::Error) -> nb::Error<SerialError> {
type SerialError (line 64) | pub struct SerialError {
method inner (line 70) | pub fn inner(&self) -> &IoErrorKind {
method fmt (line 76) | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
method kind (line 85) | fn kind(&self) -> embedded_hal_nb::serial::ErrorKind {
function create_pty_and_serial (line 99) | fn create_pty_and_serial() -> (std::fs::File, Serial) {
function create_serial_from_builder (line 107) | fn create_serial_from_builder() {
function test_empty_read (line 115) | fn test_empty_read() {
function test_read (line 121) | fn test_read() {
function test_write (line 128) | fn test_write() {
FILE: src/spi.rs
type SpidevDevice (line 32) | pub struct SpidevDevice(pub spidev::Spidev);
method open (line 74) | pub fn open<P>(path: P) -> Result<Self, SPIError>
type Target (line 102) | type Target = spidev::Spidev;
method deref (line 104) | fn deref(&self) -> &Self::Target {
method deref_mut (line 110) | fn deref_mut(&mut self) -> &mut Self::Target {
type SpidevBus (line 67) | pub struct SpidevBus(pub spidev::Spidev);
method open (line 91) | pub fn open<P>(path: P) -> Result<Self, SPIError>
type Target (line 116) | type Target = spidev::Spidev;
method deref (line 118) | fn deref(&self) -> &Self::Target {
method deref_mut (line 124) | fn deref_mut(&mut self) -> &mut Self::Target {
method read (line 146) | fn read(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
method write (line 150) | fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {
method transfer (line 154) | fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Se...
method transfer_in_place (line 175) | fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), Self::...
method flush (line 181) | fn flush(&mut self) -> Result<(), Self::Error> {
type Error (line 138) | type Error = SPIError;
type Error (line 142) | type Error = SPIError;
method transaction (line 193) | fn transaction(
type SPIError (line 246) | pub struct SPIError {
method inner (line 252) | pub fn inner(&self) -> &io::Error {
method from (line 258) | fn from(err: io::Error) -> Self {
method kind (line 265) | fn kind(&self) -> embedded_hal::spi::ErrorKind {
method fmt (line 273) | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
method source (line 279) | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
FILE: src/sysfs_pin.rs
type SysfsPin (line 11) | pub struct SysfsPin(pub sysfs_gpio::Pin);
method new (line 17) | pub fn new(pin_num: u64) -> Self {
method from_path (line 24) | pub fn from_path<P>(path: P) -> sysfs_gpio::Result<Self>
method into_input_pin (line 32) | pub fn into_input_pin(self) -> Result<SysfsPin, sysfs_gpio::Error> {
method into_output_pin (line 38) | pub fn into_output_pin(
type Error (line 89) | type Error = SysfsPinError;
method set_low (line 93) | fn set_low(&mut self) -> Result<(), Self::Error> {
method set_high (line 101) | fn set_high(&mut self) -> Result<(), Self::Error> {
method is_high (line 111) | fn is_high(&mut self) -> Result<bool, Self::Error> {
method is_low (line 125) | fn is_low(&mut self) -> Result<bool, Self::Error> {
type Target (line 131) | type Target = sysfs_gpio::Pin;
method deref (line 133) | fn deref(&self) -> &Self::Target {
method deref_mut (line 139) | fn deref_mut(&mut self) -> &mut Self::Target {
type SysfsPinError (line 52) | pub struct SysfsPinError {
method inner (line 58) | pub fn inner(&self) -> &sysfs_gpio::Error {
method from (line 64) | fn from(err: sysfs_gpio::Error) -> Self {
method fmt (line 70) | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
method source (line 76) | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
method kind (line 82) | fn kind(&self) -> embedded_hal::digital::ErrorKind {
FILE: src/timer.rs
type Periodic (line 9) | pub trait Periodic {}
type CountDown (line 55) | pub trait CountDown {
method start (line 65) | fn start<T>(&mut self, count: T) -> Result<(), Self::Error>
method wait (line 77) | fn wait(&mut self) -> nb::Result<(), Self::Error>;
type Error (line 81) | type Error = T::Error;
type Time (line 83) | type Time = T::Time;
method start (line 85) | fn start<TIME>(&mut self, count: TIME) -> Result<(), Self::Error>
method wait (line 92) | fn wait(&mut self) -> nb::Result<(), Self::Error> {
type Error (line 126) | type Error = Infallible;
type Time (line 127) | type Time = Duration;
method start (line 129) | fn start<T>(&mut self, count: T) -> Result<(), Self::Error>
method wait (line 138) | fn wait(&mut self) -> nb::Result<(), Self::Error> {
type SysTimer (line 101) | pub struct SysTimer {
method new (line 111) | pub fn new() -> SysTimer {
method default (line 120) | fn default() -> SysTimer {
function test_delay (line 158) | fn test_delay() {
function test_periodic (line 171) | fn test_periodic() {
Condensed preview — 20 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (70K chars).
[
{
"path": ".github/CODEOWNERS",
"chars": 32,
"preview": "* @rust-embedded/embedded-linux\n"
},
{
"path": ".github/workflows/ci.yml",
"chars": 1316,
"preview": "on:\n push: # Run CI for all branches except GitHub merge queue tmp branches\n branches-ignore:\n - \"gh-readonly-que"
},
{
"path": ".github/workflows/clippy.yml",
"chars": 514,
"preview": "on:\n push: # Run CI for all branches except GitHub merge queue tmp branches\n branches-ignore:\n - \"gh-readonly-que"
},
{
"path": ".github/workflows/rustfmt.yml",
"chars": 488,
"preview": "on:\n push: # Run CI for all branches except GitHub merge queue tmp branches\n branches-ignore:\n - \"gh-readonly-que"
},
{
"path": ".gitignore",
"chars": 32,
"preview": "\n/target/\n**/*.rs.bk\nCargo.lock\n"
},
{
"path": "CHANGELOG.md",
"chars": 6686,
"preview": "# Change Log\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Chang"
},
{
"path": "CODE_OF_CONDUCT.md",
"chars": 4584,
"preview": "# The Rust Code of Conduct\n\n## Conduct\n\n**Contact**: [HAL team](https://github.com/rust-embedded/wg#the-hal-team)\n\n* We "
},
{
"path": "Cargo.toml",
"chars": 1476,
"preview": "[package]\nauthors = [\n \"The Embedded Linux Team <embedded-linux@teams.rust-embedded.org>\",\n \"Jorge Aparicio <jorge"
},
{
"path": "LICENSE-APACHE",
"chars": 10847,
"preview": " Apache License\n Version 2.0, January 2004\n http"
},
{
"path": "LICENSE-MIT",
"chars": 1129,
"preview": "Copyright (c) 2018 Jorge Aparicio\nCopyright (c) 2019-2024 The Rust embedded linux team and contributors.\n\nPermission is "
},
{
"path": "README.md",
"chars": 2593,
"preview": "[](https://crates.io/crates/linux-embedded-hal)\n[![c"
},
{
"path": "examples/transactional-i2c.rs",
"chars": 754,
"preview": "use embedded_hal::i2c::{I2c, Operation as I2cOperation};\nuse linux_embedded_hal::I2cdev;\n\nconst ADDR: u8 = 0x12;\n\nstruct"
},
{
"path": "src/cdev_pin.rs",
"chars": 5799,
"preview": "//! Implementation of [`embedded-hal`] digital input/output traits using a Linux CDev pin\n//!\n//! [`embedded-hal`]: http"
},
{
"path": "src/delay.rs",
"chars": 1113,
"preview": "//! Implementation of [`embedded-hal`] delay traits\n//!\n//! [`embedded-hal`]: https://docs.rs/embedded-hal\n\nuse embedded"
},
{
"path": "src/i2c.rs",
"chars": 4663,
"preview": "//! Implementation of [`embedded-hal`] I2C traits\n//!\n//! [`embedded-hal`]: https://docs.rs/embedded-hal\n\nuse std::fmt;\n"
},
{
"path": "src/lib.rs",
"chars": 1435,
"preview": "//! Implementation of [`embedded-hal`] traits for Linux devices\n//!\n//! [`embedded-hal`]: https://docs.rs/embedded-hal\n/"
},
{
"path": "src/serial.rs",
"chars": 4172,
"preview": "//! Implementation of [`embedded-hal`] serial traits\n//!\n//! [`embedded-hal`]: https://docs.rs/embedded-hal\n\nuse serialp"
},
{
"path": "src/spi.rs",
"chars": 10247,
"preview": "//! Implementation of [`embedded-hal`] SPI traits\n//!\n//! [`embedded-hal`]: https://docs.rs/embedded-hal\n//!\n\nuse std::c"
},
{
"path": "src/sysfs_pin.rs",
"chars": 4084,
"preview": "//! Implementation of [`embedded-hal`] digital input/output traits using a Linux Sysfs pin\n//!\n//! [`embedded-hal`]: htt"
},
{
"path": "src/timer.rs",
"chars": 5175,
"preview": "//! Implementation of [`embedded-hal`] timer traits\n//!\n//! [`embedded-hal`]: https://docs.rs/embedded-hal\n\nuse core::co"
}
]
About this extraction
This page contains the full source code of the rust-embedded/linux-embedded-hal GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 20 files (65.6 KB), approximately 17.8k tokens, and a symbol index with 125 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.