├── .gitattributes
├── .github
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ ├── feature_request.md
│ └── implementation-question.md
├── PULL_REQUEST_TEMPLATE.md
├── README.md
└── workflows
│ ├── ci-clang-format.yml
│ ├── ci-compile.yml
│ └── ci-doxygen.yml
├── .gitignore
├── LICENSE
├── examples
├── BackgroundRead
│ ├── .due.test.skip
│ ├── .esp32.test.skip
│ ├── .esp8266.test.skip
│ ├── .m4.test.skip
│ ├── .zero.test.skip
│ └── BackgroundRead.ino
├── BackgroundRead_ESP32
│ ├── .due.test.skip
│ ├── .esp8266.test.skip
│ ├── .leonardo.test.skip
│ ├── .m4.test.skip
│ ├── .mega2560.test.skip
│ ├── .uno.test.skip
│ ├── .zero.test.skip
│ └── BackgroundRead_ESP32.ino
├── DataLogger
│ ├── .due.test.skip
│ ├── .esp32.test.skip
│ ├── .esp8266.test.skip
│ ├── .leonardo.test.skip
│ ├── .m4.test.skip
│ ├── .mega2560.test.skip
│ ├── .uno.test.skip
│ ├── .zero.test.skip
│ └── DataLogger.ino
└── DisplayReadings
│ └── DisplayReadings.ino
├── images
├── INA226.jpg
├── horizontal.png
├── horizontal_narrow.png
├── horizontal_narrow_small.png
├── icon.png
├── ina.ai
├── logo.svg
├── vertical.png
└── wiki.png
├── keywords.txt
├── library.properties
└── src
├── INA.cpp
└── INA.h
/.gitattributes:
--------------------------------------------------------------------------------
1 | ########################################################################
2 | # This section defines which file types are associated with which #
3 | # linguist-documentation language types. Initially this was set so that#
4 | # the "Arduino" language was chosen, but that is no longer considered #
5 | # a language so everything has been reverted to "c++" #
6 | # #
7 | # Date Author Comments #
8 | # ========== ========== ============================================== #
9 | # 2018-06-24 SV-Zanshin Changed file #
10 | # #
11 | ########################################################################
12 | examples/ linguist-documentation=false
13 | *.c linguist-language=c++
14 | *.ino linguist-language=c++
15 | *.pde linguist-language=c++
16 | *.c linguist-language=c++
17 | *.h linguist-language=c++
18 | *.cpp linguist-language=c++
19 |
20 | ########################################################################
21 | # Auto detect text files and perform LF normalization #
22 | ########################################################################
23 | * text=auto
24 |
25 | ########################################################################
26 | # Custom setting for Visual Studio/Atmel Studio files #
27 | ########################################################################
28 | *.cs diff=csharp
29 |
30 | ########################################################################
31 | # Standard to msysgit #
32 | ########################################################################
33 | *.doc diff=astextplain
34 | *.DOC diff=astextplain
35 | *.docx diff=astextplain
36 | *.DOCX diff=astextplain
37 | *.dot diff=astextplain
38 | *.DOT diff=astextplain
39 | *.pdf diff=astextplain
40 | *.PDF diff=astextplain
41 | *.rtf diff=astextplain
42 | *.RTF diff=astextplain
43 |
--------------------------------------------------------------------------------
/.github/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, sex characteristics, gender identity and expression,
9 | level of experience, education, socio-economic status, nationality, personal
10 | appearance, race, religion, or sexual identity and orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or
41 | reject comments, commits, code, wiki edits, issues, and other contributions
42 | that are not aligned to this Code of Conduct, or to ban temporarily or
43 | permanently any contributor for other behaviors that they deem inappropriate,
44 | threatening, offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | ## Enforcement
56 |
57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
58 | reported by contacting the project team at Zanduino_Github@Zanduino.Com. All
59 | complaints will be reviewed and investigated and will result in a response that
60 | is deemed necessary and appropriate to the circumstances. The project team is
61 | obligated to maintain confidentiality with regard to the reporter of an incident.
62 | Further details of specific enforcement policies may be posted separately.
63 |
64 | Project maintainers who do not follow or enforce the Code of Conduct in good
65 | faith may face temporary or permanent repercussions as determined by other
66 | members of the project's leadership.
67 |
68 | ## Attribution
69 |
70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72 |
73 | [homepage]: https://www.contributor-covenant.org
74 |
75 | For answers to common questions about this code of conduct, see
76 | https://www.contributor-covenant.org/faq
77 |
78 | [ ](https://zanduino.github.io)
79 |
--------------------------------------------------------------------------------
/.github/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | The more people that participate in correcting and enhancing code, the better the result is, so everyone with something to contribute is welcome to do so!
4 |
5 | Fork, then clone the repository and program your changes, making sure that the new version compiles and runs correctly.
6 |
7 | Open up an issue with the problem description, the proposed solution and the tests done to make sure that there are no regression errors
8 |
9 | Push to your fork and submit a gitHub pull request.
10 |
11 | At this point the ball is no longer in your court but on our side. There will be a response within a couple of days, at most.
12 |
13 | Some things that will increase the speed at which a pull request is completed:
14 |
15 | * Write tests.
16 | * Follow the existing coding style, using [Google Style Guide](https://google.github.io/styleguide/cppguide.html)
17 | * Follow the existing program documentation style using [doxygen](http://www.doxygen.nl/)
18 | * Write as much information as a beginner would need to understand the problem and solution
19 |
20 | [ ](https://zanduino.github.io)
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Submit a bug report
4 | title: {Add Short one-line Bug title}
5 | labels: bug
6 | assignees: SV-Zanshin
7 |
8 | ---
9 |
10 | ## Expected Behavior
11 |
12 | _Detail what the expected program behavior should be, or what is expected to happen._
13 |
14 | ## Actual Behavior
15 |
16 | _Detail what actually happens._
17 |
18 | ## Steps to Reproduce the Problem
19 |
20 | _Explain what needs to be done in order to reproduce the problem._
21 | 1.
22 | 2.
23 | 3.
24 |
25 | ## Specifications
26 |
27 | - Library Version:
28 | - IDE Version:
29 | - Platform:
30 | - Subsystem:
31 | - _any other details needed to reproduce the problem_
32 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: {add one-line description of the feature request}
5 | labels: enhancement
6 | assignees: SV-Zanshin
7 |
8 | ---
9 |
10 | **Describe what the feature request is and if it solves an issue or adds functionality**
11 | _A clear and concise description of what the problem is which would be solved by the feature request. Example "It would be helpful to add a function newFunc() to solve the problem of [...]"_
12 |
13 | **Describe the solution you'd like**
14 | _A clear and concise description of what you want to have changed or added._
15 |
16 | **Describe alternatives you've considered**
17 | _A clear and concise description of any alternative solutions or features you've considered._
18 |
19 | **Additional context**
20 | _Add any other context or screenshots about the feature request here._
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/implementation-question.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Implementation Question
3 | about: Ask a question about the library implementation
4 | title: {One-Line descriptive question title}
5 | labels: question
6 | assignees: SV-Zanshin
7 |
8 | ---
9 |
10 | _Ask your question or post your comment here, adding any information, examples, links, etc. that someone would reasonably be expected to have in order to give a response._
11 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | # Description
2 | _Please include a text summary of the change and which issue(s) is/are fixed or addressed. Should the change have any dependencies
3 | then these should be listed here._
4 |
5 | Fixes # (issue)
6 | _In order to make tracking easier and to properly document the process,
7 | pull requests should always refer to an active issue in the list - be it a bug fix or an enhancement or some other type of issue._
8 |
9 | ## Type of change
10 |
11 | _Please delete options that are not relevant._
12 |
13 | - [ ] Bug fix (non-breaking change which fixes an issue)
14 | - [ ] New feature (non-breaking change which adds functionality)
15 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
16 | - [ ] This change requires a documentation update
17 |
18 | # How Has This Been Tested?
19 |
20 | _Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration_
21 |
22 | - [ ] Test A
23 | - [ ] Test B
24 |
25 | **Test Configuration**:
26 | * Arduino version:
27 | * Arduino Hardware:
28 | * SDK: (Arduino IDE, Atmel Studio, Visual Studio, Visual Micro, etc.)
29 | * Development system: (Windows, Web, Linux, etc.)
30 |
31 | # Checklist:
32 |
33 | - [ ] The changes made link back to an existing issue number
34 | - [ ] I have performed a self-review of my own code
35 | - [ ] My code follows the style guidelines of this project
36 | - [ ] I have commented my code, particularly in hard-to-understand areas
37 | - [ ] The code adheres to the [Google Style Guide](https://google.github.io/styleguide/cppguide.html)
38 | - [ ] The code follows the existing program documentation style using [doxygen](http://www.doxygen.nl/)
39 | - [ ] I have made corresponding changes to the documentation / Wiki Page(s)
40 | - [ ] My changes generate no new warnings
41 | - [ ] The automated TRAVIS-CI run has a status of "passed"
42 | - [ ] I have checked potential areas where regression errors could occur and have found no issues
43 | - [ ] I have added tests that prove my fix is effective or that my feature works
44 | - [ ] New and existing unit tests pass locally with my changes
45 |
46 | [ ](https://zanduino.github.io)
47 |
--------------------------------------------------------------------------------
/.github/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | [](https://www.gnu.org/licenses/gpl-3.0) [](https://github.com/Zanduino/INA/actions?query=workflow%3ABuild) [](https://github.com/Zanduino/INA/actions?query=workflow%3AFormat) [](https://github.com/Zanduino/INA/wiki) [](https://Zanduino.github.io/INA/html/index.html) [](https://www.ardu-badge.com/INA2xx)
4 | # INA2*xx* Devices
5 |
6 | _Arduino_ library to access multiple INA2xx High-Side/Low-Side Bi-Directional I2C Current and Power Monitors at the same time. Details of the library methods and example programs are to be found [at the INA wiki pages]
7 |
8 |
9 | Texas Instruments produces this family of power monitors and the library supports the following devices:
10 |
11 | | Device | Max V | Package | Shunt mV | Description | Tested |
12 | | ------------------------------------------- | ------| --------- | -------- |------------ | ------ |
13 | | [INA219](http://www.ti.com/product/INA219) ([datasheet](http://www.ti.com/lit/ds/symlink/ina219.pdf)) | 26V | SOT-23 8p | ±40,±80,±160,±320mV | | Yes |
14 | | [INA220](http://www.ti.com/product/INA220) ([datasheet](http://www.ti.com/lit/ds/symlink/ina220.pdf)) | 26V | VSSOP 10p | ±40,±80,±160,±320mV | identical to INA219 | - |
15 | | [INA220-Q1](http://www.ti.com/product/INA220-Q1) ([datasheet](http://www.ti.com/lit/ds/symlink/ina220-Q1.pdf)) | 26V | VSSOP 10p | ±40,±80,±160,±320mV | Identical to INA219 | - |
16 | | [INA226](http://www.ti.com/product/INA226) ([datasheet](http://www.ti.com/lit/ds/symlink/ina226.pdf)) | 36V | VSSOP 10p | ±81.92mV | | Yes |
17 | | [INA230](http://www.ti.com/product/INA230) ([datasheet](http://www.ti.com/lit/ds/symlink/ina230.pdf)) | 28V | QFN 16p | ±81.92mV | Identical to INA226 | - |
18 | | [INA231](http://www.ti.com/product/INA231) ([datasheet](http://www.ti.com/lit/ds/symlink/ina231.pdf)) | 28V | DSBGA-12 | ±81.92mV | Identical to INA226 | - |
19 | | [INA260](http://www.ti.com/product/INA260) ([datasheet](http://www.ti.com/lit/ds/symlink/ina260.pdf)) | 36V | TSSOP 16p | n.a. | 2 mΩ shunt, ±15A | Yes |
20 | | [INA3221](http://www.ti.com/product/INA3221) ([datasheet](http://www.ti.com/lit/ds/symlink/ina3221.pdf)) | 26V | VQFN(16) | ±163.8mV | 3 concurrent circuits | Yes |
21 |
22 | Texas Instruments has a document which describes and details the differences between the various INA-devices, this PDF document can be read at [Digital Interfaces for Current Sensing Devices](http://www.ti.com/lit/an/sboa203/sboa203.pdf)
23 | ## Hardware layout
24 | The packages are small and a lot of work to solder, but fortunately there are now several sources for breakout boards for the various devices which are worth it in time savings. My first test with a INA226 involved a blank breakout board, some solder paste, a frying pan, desoldering braid, a magnifying glass and quite a bit of time to set up the first breadboard.
25 | ## Library description
26 | The library locates all INA2xx devices on the I2C chain. Each unit can be individually configured with 2 setup parameters describing the expected maximum voltage, shunt/resistor values which then set the internal configuration registers is ready to begin accurate measurements. The details of how to setup the library along with all of the publicly available methods can be found on the [INA wiki pages](https://github.com/Zanduino/INA/wiki).
27 |
28 | Great lengths have been taken to avoid the use of floating point in the library. This keeps the library size down because floating point support doesn't have to be compiled into the code. The results are returned as 32-bit integers to keep the original level of precision without loss but to allow the full range of voltages and amperes to be returned the amperage .
29 |
30 | Since the functionality differs between the supported devices there are some functions which will only work for certain devices.
31 |
32 | ## Documentation
33 | The documentation has been done using Doxygen and can be found at [doxygen documentation](https://Zanduino.github.io/INA/html/index.html)
34 |
35 | [ ](https://zanduino.github.io)
36 |
37 |
--------------------------------------------------------------------------------
/.github/workflows/ci-clang-format.yml:
--------------------------------------------------------------------------------
1 | ####################################################################################################
2 | ## YAML file for the github Action that performs "clang-format" to check the c++ source files for ##
3 | ## adherence to the defined standards. If no ".clang-format" file is defined at the root of the ##
4 | ## project then the standard file is copied there. The default clang-format style is "Google", ##
5 | ## with a couple of minor tweaks. ##
6 | ## ##
7 | ## ##
8 | ## Version Date Developer Comments ##
9 | ## ======= ========== ============== ============================================================ ##
10 | ## 1.0.1 2020-12-07 SV-Zanshin Shortened name to "Format" ##
11 | ## 1.0.0 2020-12-06 SV-Zanshin Initial coding ##
12 | ## ##
13 | ####################################################################################################
14 | name: 'Format'
15 | on:
16 | push:
17 | pull_request:
18 | workflow_dispatch:
19 | jobs:
20 | source-checks:
21 | name: 'clang-format'
22 | runs-on: ubuntu-latest
23 | steps:
24 | - name: 'Install "Python"'
25 | uses: actions/setup-python@v1
26 | with:
27 | python-version: '3.x'
28 | - name: 'Checkout the repository'
29 | uses: actions/checkout@v2
30 | - name: 'Checkout the "Zanduino/Common" repository'
31 | uses: actions/checkout@v2
32 | with:
33 | repository: Zanduino/Common
34 | path: Common
35 | - name: 'Install "clang-format"'
36 | run: bash ${GITHUB_WORKSPACE}/Common/Scripts/install_clang_actions.sh
37 | - name: 'Check formatting of all c++ files'
38 | run: python3 ${GITHUB_WORKSPACE}/Common/Python/run-clang-format.py -e "ci/*" -e "bin/*" -r .
39 |
--------------------------------------------------------------------------------
/.github/workflows/ci-compile.yml:
--------------------------------------------------------------------------------
1 | ####################################################################################################
2 | ## YAML file for github Actions that will attempt to compile the c++ artefacts using the Arduino ##
3 | ## CLI for various platforms. ##
4 | ## ##
5 | ## Version Date Developer Comments ##
6 | ## ======= ========== ============== ============================================================ ##
7 | ## 1.0.1 2020-12-07 SV-Zanshin Changed name to a short text ##
8 | ## 1.0.0 2020-12-05 SV-Zanshin Initial coding ##
9 | ## ##
10 | ####################################################################################################
11 | name: 'Build'
12 | on:
13 | push:
14 | pull_request:
15 | workflow_dispatch:
16 | jobs:
17 | compile-on-platforms:
18 | name: 'Compile using Arduino IDE on selected platforms'
19 | runs-on: ubuntu-latest
20 | steps:
21 | - name: 'Install "python 3.x" package'
22 | uses: actions/setup-python@v1
23 | with:
24 | python-version: '3.x'
25 | - name: 'Checkout the repository from github'
26 | uses: actions/checkout@v2
27 | - name: 'Checkout the "Zanduino/Common" repository from github'
28 | uses: actions/checkout@v2
29 | with:
30 | repository: Zanduino/Common
31 | path: Common
32 | - name: 'Install Arduino CLI package'
33 | run: bash ${GITHUB_WORKSPACE}/Common/Scripts/install_arduino_cli.sh
34 | - name: 'Run master compile python program'
35 | run: python3 ${GITHUB_WORKSPACE}/Common/Python/build_platform.py uno leonardo mega2560 esp8266 esp32
36 |
--------------------------------------------------------------------------------
/.github/workflows/ci-doxygen.yml:
--------------------------------------------------------------------------------
1 | ####################################################################################################
2 | ## YAML file for github Actions that will perform project checking for adhering to doxygen ##
3 | ## documentation standards and to also deploy the generated HTML documentation to gh-pages ##
4 | ## ##
5 | ## ##
6 | ## Version Date Developer Comments ##
7 | ## ======= ========== ============== ============================================================ ##
8 | ## 1.0.0 2020-12-04 SV-Zanshin Initial coding ##
9 | ## ##
10 | ####################################################################################################
11 | name: 'Doxygen'
12 |
13 | ####################################################################################################
14 | ## Action runs when committing (push), doing a pull request, or a workflow_dispatch ##
15 | ####################################################################################################
16 | on:
17 | push:
18 | pull_request:
19 | workflow_dispatch:
20 | jobs:
21 | doxygen:
22 | name: 'Generate doxygen'
23 | runs-on: ubuntu-latest
24 | steps:
25 | - name: 'Checkout the repository from github'
26 | uses: actions/checkout@v2
27 | - name: 'Checkout the "Zanduino/Common" repository from github'
28 | uses: actions/checkout@v2
29 | with:
30 | repository: Zanduino/Common
31 | path: Common
32 | - name: 'Create doxygen html documentation'
33 | env:
34 | GH_REPO_TOKEN: ${{ secrets.GH_REPO_TOKEN }}
35 | ##########################################################################################
36 | ## The following 5 lines need to be set here each project ##
37 | ##########################################################################################
38 | PRETTYNAME: "INA2xx Arduino Library"
39 | PROJECT_NAME: "INA2xx"
40 | PROJECT_NUMBER: "v1.1.0"
41 | PROJECT_BRIEF: "Arduino Library to read current, voltage and power data from one or more INA2xx device(s)"
42 | PROJECT_LOGO: ""
43 | run: bash ${GITHUB_WORKSPACE}/Common/Scripts/doxy_gen_and_deploy.sh
44 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ########################################################################
2 | # This file defines which file types are to be ignored and skipped by #
3 | # git so that they are not transferred and committed. #
4 | # #
5 | # Date Author Comments #
6 | # ========== ========== ============================================== #
7 | # 2021-12-11 SV-Zanshin New ignore for Visual Studio 2022 *.vcxitems #
8 | # 2020-12-11 SV-Zanshin Ignores for doxygen and clang-format files #
9 | # 2019-01-31 SV-Zanshin Ignores for doxygen #
10 | # 2018-09-22 SV-Zanshin Ignores for MS VS 2017 #
11 | # 2018-06-24 SV-Zanshin Changed file #
12 | # #
13 | ########################################################################
14 |
15 | ########################################################################
16 | # Windows image file caches #
17 | ########################################################################
18 | Thumbs.db
19 | ehthumbs.db
20 |
21 | ########################################################################
22 | # Windows folder config file #
23 | ########################################################################
24 | Desktop.ini
25 |
26 | ########################################################################
27 | # Recycle Bin used on file shares #
28 | ########################################################################
29 | $RECYCLE.BIN/
30 |
31 | ########################################################################
32 | # Windows Installer files #
33 | ########################################################################
34 | *.cab
35 | *.msi
36 | *.msm
37 | *.msp
38 |
39 | ########################################################################
40 | # Windows shortcuts #
41 | ########################################################################
42 | *.lnk
43 |
44 | ########################################################################
45 | # Operating System Files - OSX #
46 | ########################################################################
47 | .DS_Store
48 | .AppleDouble
49 | .LSOverride
50 |
51 | ########################################################################
52 | # Thumbnails #
53 | ########################################################################
54 | ._*
55 |
56 | ########################################################################
57 | # Files that might appear in the root of a volume #
58 | ########################################################################
59 | .DocumentRevisions-V100
60 | .fseventsd
61 | .Spotlight-V100
62 | .TemporaryItems
63 | .Trashes
64 | .VolumeIcon.icns
65 |
66 | ########################################################################
67 | # Directories potentially created on remote AFP share #
68 | ########################################################################
69 | .AppleDB
70 | .AppleDesktop
71 | Network Trash Folder
72 | Temporary Items
73 | .apdisk
74 |
75 | ########################################################################
76 | # Files and directories from the Atmel Studio Arduino IDE #
77 | ########################################################################
78 | .vs
79 | __vm
80 | Debug
81 | Release
82 | *.atsln
83 | *.componentinfo.xml
84 | *.cppproj
85 |
86 | ########################################################################
87 | # Files and directories from Microsoft Visual Studio #
88 | ########################################################################
89 | *.sln
90 | *.vcxproj
91 | *.filters
92 | *.user
93 | *.vcxitems
94 |
95 | ########################################################################
96 | # Files and directories from doxygen #
97 | ########################################################################
98 | html
99 | Doxyfile
100 |
101 | ########################################################################
102 | # Clang-format files #
103 | ########################################################################
104 | .clang-format
105 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------
/examples/BackgroundRead/.due.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/BackgroundRead/.due.test.skip
--------------------------------------------------------------------------------
/examples/BackgroundRead/.esp32.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/BackgroundRead/.esp32.test.skip
--------------------------------------------------------------------------------
/examples/BackgroundRead/.esp8266.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/BackgroundRead/.esp8266.test.skip
--------------------------------------------------------------------------------
/examples/BackgroundRead/.m4.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/BackgroundRead/.m4.test.skip
--------------------------------------------------------------------------------
/examples/BackgroundRead/.zero.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/BackgroundRead/.zero.test.skip
--------------------------------------------------------------------------------
/examples/BackgroundRead/BackgroundRead.ino:
--------------------------------------------------------------------------------
1 | /*!
2 | *
3 | * @file BackgroundRead.ino
4 | *
5 | * @brief Example program for the INA Library demonstrating background reads
6 | *
7 | * @section BackgroundRead_section Description
8 | *
9 | * Program to demonstrate using the interrupt pin of any INA2xx which supports that functionality.
10 | * It uses a pin-change interrupt handler and programs any INA2xx found to to read voltage and
11 | * current information in the background while allowing the main Arduino code to continue processing
12 | * normally until it is ready to consume the readings.\n\n
13 | *
14 | * The example program uses the Arduino AVR-based interrupt mechanism and will not function on other
15 | * platforms\n\n
16 | *
17 | * Detailed documentation can be found on the GitHub Wiki pages at
18 | * https://github.com/Zanduino/INA/wiki \n\n Since the INA library allows multiple devices of
19 | * different types and this program demonstrates interrupts and background processing, it will limit
20 | * itself to using the first INA226 detected. This is easily changed in the if another device type
21 | * or device number to test is required.\n
22 | *
23 | * This example is for a INA226 set up to measure a 5-Volt load with a 0.1Ohm resistor in place,
24 | * this is the same setup that can be found in the Adafruit INA226 breakout board. The complex
25 | * calibration options are done at runtime using the 2 parameters specified in the "begin()" call
26 | * and the library has gone to great lengths to avoid the use of floating point to conserve space
27 | * and minimize runtime. This demo program uses floating point only to convert and display the data
28 | * conveniently. The INA226 uses 15 bits of precision, and even though the current and watt
29 | * information is returned using 32-bit integers the precision remains the same.\n The INA226 is set
30 | * up to measure using the maximum conversion length (and maximum accuracy) and then average those
31 | * readings 64 times. This results in readings taking 8.244ms x 64 = 527.616ms or just less than 2
32 | * times a second. The pin-change interrupt handler is called when a reading is finished and the
33 | * INA226 pulls the pin down to ground, it resets the pin status and adds the readings to the global
34 | * variables. The main program will do whatever processing it has to and every 5 seconds it will
35 | * display the current averaged readings and reset them.\n
36 | *
37 | * The datasheet for the INA226 can be found at http://www.ti.com/lit/ds/symlink/INA226.pdf and it
38 | * contains the information required in order to hook up the device. Unfortunately it comes as a
39 | * VSSOP package but it can be soldered onto a breakout board for breadboard use. The INA226 is
40 | * quite similar to the INA219 mentioned above, but it can take bus voltages of up to 36V (which I
41 | * needed in order to monitor a 24V battery system which goes above 28V while charging and which is
42 | * above the absolute limits of the INA219). It is also significantly more accurate than the INA219,
43 | * plus has an alert pin.\n The interrupt is set to pin 8. The tests were done on an Arduino Micro,
44 | * and the Atmel 82U4 chip only allows pin change interrupt on selected pins (SS,SCK,MISO,MOSI,8) so
45 | * pin 8 was chosen.
46 | *
47 | * @section BackgroundRead_license GNU General Public License v3.0
48 | *
49 | * This program is free software : you can redistribute it and/or modify it under the terms of the
50 | * GNU General Public License as published by the Free Software Foundation, either version 3 of the
51 | * License, or (at your option) any later version.This program is distributed in the hope that it
52 | * will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
53 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.You should
54 | * have received a copy of the GNU General Public License along with this program(see
55 | * https://github.com/Zanduino/INA/blob/master/LICENSE). If not, see
56 | * .
57 | *
58 | * @section BackgroundRead_author Author
59 | *
60 | * Written by Arnd at https://www.github.com/SV-Zanshin
61 | *
62 | * @section BackgroundRead_versions Changelog
63 | *
64 | * Version | Date | Developer | Comments
65 | * ------- | ---------- | ----------- | ------------------------------------------------------------
66 | * 1.0.5 | 2020-12-01 | SV-Zanshin | Corrected "alertOnConversion()" call
67 | * 1.0.4 | 2019-02-16 | SV-Zanshin | ifdef so that sketch won't compile on incompatible platforms
68 | * 1.0.3 | 2019-01-09 | SV-Zanshin | Cleaned up doxygen formatting
69 | * 1.0.2 | 2018-12-28 | SV-Zanshin | Converted comments to doxygen format
70 | * 1.0.0 | 2018-06-23 | SV-Zanshin | Cloned and adapted example from old deprecated INA226
71 | * library
72 | *
73 | */
74 | #if !defined(__AVR__)
75 | #error Example program only functions on Atmel AVR-Based platforms
76 | #endif
77 |
78 | /**************************************************************************************************
79 | ** Declare all include files **
80 | **************************************************************************************************/
81 | #include // Include the INA library
82 |
83 | /**************************************************************************************************
84 | ** Declare program Constants **
85 | **************************************************************************************************/
86 | const uint8_t INA_ALERT_PIN = 8; ///< Pin-Change pin used for the INA "ALERT" functionality
87 | const uint8_t GREEN_LED_PIN = 13; ///< Arduino standard green LED
88 | const uint32_t SERIAL_SPEED = 115200; ///< Use fast serial speed
89 |
90 | /**************************************************************************************************
91 | ** Declare global variables and instantiate classes **
92 | **************************************************************************************************/
93 | INA_Class INA; ///< INA class instantiation
94 | volatile uint8_t deviceNumber = UINT8_MAX; ///< Device Number to use in example
95 | volatile uint64_t sumBusMillVolts = 0; ///< Sum of bus voltage readings
96 | volatile int64_t sumBusMicroAmps = 0; ///< Sum of bus amperage readings
97 | volatile uint8_t readings = 0; ///< Number of measurements taken
98 |
99 | ISR(PCINT0_vect) {
100 | /*!
101 | @brief Interrupt service routine for the PCINT0_vect
102 | @details Routine is called whenever the INA_ALERT_PIN changes value
103 | */
104 | *digitalPinToPCMSK(INA_ALERT_PIN) &= ~bit(digitalPinToPCMSKbit(INA_ALERT_PIN)); // Disable PCMSK
105 | PCICR &= ~bit(digitalPinToPCICRbit(INA_ALERT_PIN)); // disable interrupt for the group
106 | sei(); // Enable interrupts (for I2C calls)
107 | digitalWrite(GREEN_LED_PIN, !digitalRead(GREEN_LED_PIN)); // Toggle LED
108 | sumBusMillVolts += INA.getBusMilliVolts(deviceNumber); // Add current value to sum
109 | sumBusMicroAmps += INA.getBusMicroAmps(deviceNumber); // Add current value to sum
110 | readings++;
111 | INA.waitForConversion(deviceNumber); // Wait for conversion & INA int. flag
112 | cli(); // Disable interrupts
113 | *digitalPinToPCMSK(INA_ALERT_PIN) |=
114 | bit(digitalPinToPCMSKbit(INA_ALERT_PIN)); // Enable PCMSK pin
115 | PCIFR |= bit(digitalPinToPCICRbit(INA_ALERT_PIN)); // clear any outstanding interrupt
116 | PCICR |= bit(digitalPinToPCICRbit(INA_ALERT_PIN)); // enable interrupt for the group
117 | } // of ISR handler for INT0 group of pins
118 |
119 | /*!
120 | @brief Arduino method called once at startup to initialize the system
121 | @details This is an Arduino IDE method which is called first upon boot or restart. It is only
122 | called one time and then control goes to the main "loop()" method, from which control
123 | never returns
124 | @return void
125 | */
126 | void setup() {
127 | pinMode(GREEN_LED_PIN, OUTPUT); // Make the internal LED an output pin
128 | digitalWrite(GREEN_LED_PIN, true); // Turn on the LED
129 | pinMode(INA_ALERT_PIN, INPUT_PULLUP); // Declare pin with internal pull-up resistor
130 | *digitalPinToPCMSK(INA_ALERT_PIN) |= bit(digitalPinToPCMSKbit(INA_ALERT_PIN)); // Enable PCMSK
131 | PCIFR |= bit(digitalPinToPCICRbit(INA_ALERT_PIN)); // clear any outstanding interrupt
132 | PCICR |= bit(digitalPinToPCICRbit(INA_ALERT_PIN)); // enable interrupt for the group
133 | Serial.begin(SERIAL_SPEED);
134 | #ifdef __AVR_ATmega32U4__ // If this is a 32U4 processor, wait 2 seconds for initialization
135 | delay(2000);
136 | #endif
137 | Serial.print(F("\n\nBackground INA Read V1.0.5\n"));
138 | uint8_t devicesFound = 0;
139 | while (deviceNumber == UINT8_MAX) // Loop until we find the first device
140 | {
141 | devicesFound = INA.begin(1, 100000); // +/- 1 Amps maximum for 0.1 Ohm resistor
142 | for (uint8_t i = 0; i < devicesFound; i++) {
143 | /* Change the "INA226" in the following statement to whatever device you have attached
144 | and want to measure */
145 | if (strcmp(INA.getDeviceName(i), "INA226") == 0) {
146 | deviceNumber = i;
147 | INA.reset(deviceNumber); // Reset device to default settings
148 | break;
149 | } // of if-then we have found an INA226
150 | } // of for-next loop through all devices found
151 | if (deviceNumber == UINT8_MAX) {
152 | Serial.print(F("No INA found. Waiting 5s and retrying...\n"));
153 | delay(5000);
154 | } // of if-then no INA226 found
155 | } // of if-then no device found
156 | Serial.print(F("Found INA at device number "));
157 | Serial.println(deviceNumber);
158 | Serial.println();
159 | INA.setAveraging(64, deviceNumber); // Average each reading 64 times
160 | INA.setBusConversion(8244, deviceNumber); // Maximum conversion time 8.244ms
161 | INA.setShuntConversion(8244, deviceNumber); // Maximum conversion time 8.244ms
162 | INA.setMode(INA_MODE_CONTINUOUS_BOTH, deviceNumber); // Bus/shunt measured continuously
163 | INA.alertOnConversion(true, deviceNumber); // Make alert pin go low on finish
164 | } // of method setup()
165 |
166 | void loop() {
167 | /*!
168 | @brief Arduino method for the main program loop
169 | @details This is the main program for the Arduino IDE, it is called in an infinite loop. The
170 | INA226 measurements are triggered by the interrupt handler each time a conversion is
171 | ready and stored in variables. The main program doesn't call any INA library functions,
172 | that is done in the interrupt handler. Each time 10 readings have been collected the
173 | program will output the averaged values and measurements resume from that point onwards
174 | @return void
175 | */
176 | static long lastMillis = millis(); // Store the last time we printed something
177 | if (readings >= 10) {
178 | Serial.print(F("Averaging readings taken over "));
179 | Serial.print((float)(millis() - lastMillis) / 1000, 2);
180 | Serial.print(F(" seconds.\nBus voltage: "));
181 | Serial.print((float)sumBusMillVolts / readings / 1000.0, 4);
182 | Serial.print(F("V\nBus amperage: "));
183 | Serial.print((float)sumBusMicroAmps / readings / 1000.0, 4);
184 | Serial.print(F("mA\n\n"));
185 | lastMillis = millis();
186 | cli(); // Disable interrupts to reset values
187 | readings = 0;
188 | sumBusMillVolts = 0;
189 | sumBusMicroAmps = 0;
190 | sei(); // Enable interrupts again
191 | } // of if-then we've reached the required amount of readings
192 | } // of method loop()
193 |
--------------------------------------------------------------------------------
/examples/BackgroundRead_ESP32/.due.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/BackgroundRead_ESP32/.due.test.skip
--------------------------------------------------------------------------------
/examples/BackgroundRead_ESP32/.esp8266.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/BackgroundRead_ESP32/.esp8266.test.skip
--------------------------------------------------------------------------------
/examples/BackgroundRead_ESP32/.leonardo.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/BackgroundRead_ESP32/.leonardo.test.skip
--------------------------------------------------------------------------------
/examples/BackgroundRead_ESP32/.m4.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/BackgroundRead_ESP32/.m4.test.skip
--------------------------------------------------------------------------------
/examples/BackgroundRead_ESP32/.mega2560.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/BackgroundRead_ESP32/.mega2560.test.skip
--------------------------------------------------------------------------------
/examples/BackgroundRead_ESP32/.uno.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/BackgroundRead_ESP32/.uno.test.skip
--------------------------------------------------------------------------------
/examples/BackgroundRead_ESP32/.zero.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/BackgroundRead_ESP32/.zero.test.skip
--------------------------------------------------------------------------------
/examples/BackgroundRead_ESP32/BackgroundRead_ESP32.ino:
--------------------------------------------------------------------------------
1 | /*!
2 | *
3 | * @file BackgroundRead_ESP32.ino
4 | *
5 | * @brief Example program for the INA Library demonstrating background reads
6 | *
7 | * @section BackgroundRead_ESP32_section Description
8 | *
9 | * Program to demonstrate using the interrupt pin of any INA2xx which supports that functionality.
10 | * It uses a pin-change interrupt handler and programs any INA2xx found to to read voltage and
11 | * current information in the background while allowing the main Arduino code to continue processing
12 | * normally until it is ready to consume the readings.\n\n
13 | *
14 | * This example program is designed for the ESP32/ESP8266 and will not function on other
15 | * platforms\n\n
16 | *
17 | * Detailed documentation can be found on the GitHub Wiki pages at
18 | * https://github.com/Zanduino/INA/wiki \n\n Since the INA library allows multiple devices of
19 | * different types and this program demonstrates interrupts and background processing, it will limit
20 | * itself to using the first INA226 detected. This is easily changed in the if another device type
21 | * or device number to test is required.\n
22 | *
23 | * This example is for a INA226 set up to measure a 5-Volt load with a 0.1Ohm resistor in place,
24 | * this is the same setup that can be found in the Adafruit INA226 breakout board. The complex
25 | * calibration options are done at runtime using the 2 parameters specified in the "begin()" call
26 | * and the library has gone to great lengths to avoid the use of floating point to conserve space
27 | * and minimize runtime. This demo program uses floating point only to convert and display the data
28 | * conveniently. The INA226 uses 15 bits of precision, and even though the current and watt
29 | * information is returned using 32-bit integers the precision remains the same.\n The INA226 is set
30 | * up to measure using the maximum conversion length (and maximum accuracy) and then average those
31 | * readings 64 times. This results in readings taking 8.244ms x 64 = 527.616ms or just less than 2
32 | * times a second. The pin-change interrupt handler is called when a reading is finished and the
33 | * INA226 pulls the pin down to ground, it resets the pin status and adds the readings to the global
34 | * variables. The main program will do whatever processing it has to and every 5 seconds it will
35 | * display the current averaged readings and reset them.\n
36 | *
37 | * The datasheet for the INA226 can be found at http://www.ti.com/lit/ds/symlink/INA226.pdf and it
38 | * contains the information required in order to hook up the device. Unfortunately it comes as a
39 | * VSSOP package but it can be soldered onto a breakout board for breadboard use. The INA226 is
40 | * quite similar to the INA219 mentioned above, but it can take bus voltages of up to 36V (which I
41 | * needed in order to monitor a 24V battery system which goes above 28V while charging and which is
42 | * above the absolute limits of the INA219). It is also significantly more accurate than the INA219,
43 | * plus has an alert pin.\n
44 | *
45 | * The interrupt is set to pin 8. The tests were done on an Arduino Micro, and the Atmel 82U4 chip
46 | * only allows pin change interrupt on selected pins (SS,SCK,MISO,MOSI,8) so pin 8 was chosen.\n
47 | *
48 | * @section BackgroundRead_ESP32_license GNU General Public License v3.0
49 | *
50 | * This program is free software : you can redistribute it and/or modify it under the terms of the
51 | * GNU General Public License as published by the Free Software Foundation, either version 3 of the
52 | * License, or (at your option) any later version.This program is distributed in the hope that it
53 | * will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
54 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.You should
55 | * have received a copy of the GNU General Public License along with this program(see
56 | * https://github.com/Zanduino/INA/blob/master/LICENSE). If not, see
57 | * .
58 | *
59 | * @section BackgroundRead_ESP32_author Author
60 | *
61 | * Written by Arnd at https://www.github.com/SV-Zanshin
62 | *
63 | * @section BackgroundRead_ESP32_versions Changelog
64 | *
65 | * Version | Date | Developer | Comments
66 | * ------- | ---------- | ----------- | --------
67 | * 1.0.3 | 2020-12-02 | SV-Zanshin | Corrected call to "AlertOnConversion()"
68 | * 1.0.2 | 2020-06-30 | SV-Zanshin | Issue #58 - clang-formatted document
69 | * 1.0.1 | 2020-03-24 | SV-Zanshin | Issue #53 - Doxygen documentation
70 | * 1.0.0 | 2019-02-17 | SV-Zanshin | Cloned and adapted from "BackgroundRead.ino" program
71 | *
72 | */
73 | #if !defined(ESP32)
74 | #error Example program only functions on the ESP32 / ESP8266 platforms
75 | #endif
76 |
77 | /**************************************************************************************************
78 | ** Declare all include files **
79 | **************************************************************************************************/
80 | #include // Include the INA library
81 |
82 | /**************************************************************************************************
83 | ** Declare program Constants, global variables and instantiate classes **
84 | **************************************************************************************************/
85 | INA_Class INA; ///< INA class instantiation
86 | const uint8_t INA_ALERT_PIN = A0; ///< Pin-Change used for INA "ALERT" functionality
87 | const uint32_t SERIAL_SPEED = 115200; ///< Use fast serial speed
88 | volatile uint8_t deviceNumber = UINT8_MAX; ///< Device Number to use in example
89 | volatile uint64_t sumBusMillVolts = 0; ///< Sum of bus voltage readings
90 | volatile int64_t sumBusMicroAmps = 0; ///< Sum of bus amperage readings
91 | volatile uint8_t readings = 0; ///< Number of measurements taken
92 | portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED; ///< Synchronization variable
93 |
94 | void IRAM_ATTR InterruptHandler() {
95 | /*!
96 | @brief Interrupt service routine for the INA pin
97 | @details Routine is called whenever the INA_ALERT_PIN changes value
98 | */
99 | portENTER_CRITICAL_ISR(&mux);
100 | sei(); // Enable interrupts (for I2C calls)
101 | sumBusMillVolts += INA.getBusMilliVolts(deviceNumber); // Add current value to sum
102 | sumBusMicroAmps += INA.getBusMicroAmps(deviceNumber); // Add current value to sum
103 | readings++;
104 | INA.waitForConversion(deviceNumber); // Wait for conv and reset interrupt
105 | cli(); // Disable interrupts
106 | portEXIT_CRITICAL_ISR(&mux);
107 | } // of ISR for handling interrupts
108 |
109 | void setup() {
110 | /*!
111 | @brief Arduino method called once at startup to initialize the system
112 | @details This is an Arduino IDE method which is called first upon boot or restart. It is only
113 | called one time and then control goes to the main "loop()" method, from which control
114 | never returns
115 | @return void
116 | */
117 | pinMode(INA_ALERT_PIN, INPUT_PULLUP);
118 | attachInterrupt(digitalPinToInterrupt(INA_ALERT_PIN), InterruptHandler, FALLING);
119 | Serial.begin(SERIAL_SPEED);
120 | Serial.print(F("\n\nBackground INA Read V1.0.1\n"));
121 | uint8_t devicesFound = 0;
122 | while (deviceNumber == UINT8_MAX) // Loop until we find the first device
123 | {
124 | devicesFound = INA.begin(1, 100000); // +/- 1 Amps maximum for 0.1 Ohm resistor
125 | Serial.println(INA.getDeviceName(devicesFound - 1));
126 | for (uint8_t i = 0; i < devicesFound; i++) {
127 | /* Change the "INA226" in the following statement to whatever device you have attached and
128 | want to measure */
129 | if (strcmp(INA.getDeviceName(i), "INA219") == 0) {
130 | deviceNumber = i;
131 | INA.reset(deviceNumber); // Reset device to default settings
132 | break;
133 | } // of if-then we have found an INA226
134 | } // of for-next loop through all devices found
135 | if (deviceNumber == UINT8_MAX) {
136 | Serial.print(F("No INA found. Waiting 5s and retrying...\n"));
137 | delay(5000);
138 | } // of if-then no INA226 found
139 | } // of if-then no device found
140 | Serial.print(F("Found INA at device number "));
141 | Serial.println(deviceNumber);
142 | Serial.println();
143 | INA.setAveraging(64, deviceNumber); // Average each reading 64 times
144 | INA.setBusConversion(8244, deviceNumber); // Maximum conversion time 8.244ms
145 | INA.setShuntConversion(8244, deviceNumber); // Maximum conversion time 8.244ms
146 | INA.setMode(INA_MODE_CONTINUOUS_BOTH, deviceNumber); // Bus/shunt measured continuously
147 | INA.alertOnConversion(true, deviceNumber); // Make alert pin go low on finish
148 | } // of method setup()
149 |
150 | void loop() {
151 | /*!
152 | @brief Arduino method for the main program loop
153 | @details This is the main program for the Arduino IDE, it is called in an infinite loop. The
154 | INA226 measurements are triggered by the interrupt handler each time a conversion is
155 | ready and stored in variables. The main program doesn't call any INA library functions,
156 | that is done in the interrupt handler. Each time 10 readings have been collected the
157 | program will output the averaged values and measurements resume from that point onwards
158 | @return void
159 | */
160 | static long lastMillis = millis(); // Store the last time we printed something
161 | if (readings >= 10) {
162 | Serial.print(F("Averaging readings taken over "));
163 | Serial.print((float)(millis() - lastMillis) / 1000, 2);
164 | Serial.print(F(" seconds.\nBus voltage: "));
165 | Serial.print((float)sumBusMillVolts / readings / 1000.0, 4);
166 | Serial.print(F("V\nBus amperage: "));
167 | Serial.print((float)sumBusMicroAmps / readings / 1000.0, 4);
168 | Serial.print(F("mA\n\n"));
169 | lastMillis = millis();
170 | cli(); // Disable interrupts to reset values
171 | readings = 0;
172 | sumBusMillVolts = 0;
173 | sumBusMicroAmps = 0;
174 | sei(); // Enable interrupts again
175 | } // of if-then we've reached the required amount of readings
176 | } // of method loop()
177 |
--------------------------------------------------------------------------------
/examples/DataLogger/.due.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/DataLogger/.due.test.skip
--------------------------------------------------------------------------------
/examples/DataLogger/.esp32.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/DataLogger/.esp32.test.skip
--------------------------------------------------------------------------------
/examples/DataLogger/.esp8266.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/DataLogger/.esp8266.test.skip
--------------------------------------------------------------------------------
/examples/DataLogger/.leonardo.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/DataLogger/.leonardo.test.skip
--------------------------------------------------------------------------------
/examples/DataLogger/.m4.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/DataLogger/.m4.test.skip
--------------------------------------------------------------------------------
/examples/DataLogger/.mega2560.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/DataLogger/.mega2560.test.skip
--------------------------------------------------------------------------------
/examples/DataLogger/.uno.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/DataLogger/.uno.test.skip
--------------------------------------------------------------------------------
/examples/DataLogger/.zero.test.skip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/examples/DataLogger/.zero.test.skip
--------------------------------------------------------------------------------
/examples/DataLogger/DataLogger.ino:
--------------------------------------------------------------------------------
1 | /*
2 | Program to demonstrate using the interrupt pin of any INA2xx which supports that functionality in
3 | order to trigger readings in the background and using a timer on the Arduino to trigger data
4 | averaging and storing or displaying the computed values.
5 |
6 | The INA226 is set up to pull the alert pin down when a measurement is ready. The program has set
7 | the bus and shunt to the maximum conversion time of 8.244ms and then averaging to 8, so each
8 | measurement will take about 64ms. The interrupt vector "PCINT0_vect" is called and the readings
9 | from the INA226 are read and added to the averages.
10 |
11 | A timer interrupt is defined in the setup() method that triggers a call to the vector
12 | "TIMER1_COMPA_vect" once every second. The average values collected in the "PCINT0_vect" call are
13 | then taken and stored in memory. As the amount of RAM is limited and the absolute readings are 2
14 | Bytes long while the delta values to the previous measurement are usually quite small, a variable
15 | length Huffmann coding has been implemented at a nibble (4 bit) level to provide a higher-density
16 | method of storing data. Each array is declared at 600 Bytes (one array for voltage measurements and
17 | one array for shunt voltage) and those 1200 Bytes total can store up to 18 minutes of per-second
18 | data, which would otherwise occupy over 4Kb memory. The Huffmann encoding method is described in
19 | more detail in the interrupt code below.
20 |
21 | This example works on Atmel-Arduinos since it uses Atmel interrupts which are different on
22 | processors such as the ESP32. The value of ARRAY_BYTES is set at 1200, which works on Arduinos with
23 | 2K or more of RAM, smaller processors would need to reduce this value in order to work correctly.
24 | The example is also coded for the INA226, as a chip with an ALERT pin is required for the program
25 | to work; additionally the hard-coded LSB values for the bus voltage and shunt voltage have been set
26 | to those used in the INA226.
27 |
28 | Detailed documentation can be found on the GitHub Wiki pages at
29 | https://github.com/Zanduino/INA/wiki
30 |
31 | This example is for a INA226 set up to measure a 5-Volt load with a 0.1Ω resistor in place, this is
32 | the same setup that can be found in the Adafruit INA226 breakout board. The complex calibration
33 | options are done at runtime using the 2 parameters specified in the "begin()" call and the library
34 | has gone to great lengths to avoid the use of floating point to conserve space and minimize
35 | runtime. This demo program uses floating point only to convert and display the data conveniently.
36 | The INA226 uses 15 bits of precision, and even though the current and watt information is returned
37 | using 32-bit integers the precision remains the same.
38 |
39 | The INA226 is set up to measure using the maximum conversion length (and maximum accuracy) and then
40 | average those readings 64 times. This results in readings taking 8.244ms x 64 = 527.616ms or just
41 | less than 2 times a second. The pin-change interrupt handler is called when a reading is finished
42 | and the INA226 pulls the pin down to ground, it resets the pin status and adds the readings to the
43 | global variables. The main program will do whatever processing it has to and every 5 seconds it
44 | will display the current averaged readings and reset them.
45 |
46 | The datasheet for the INA226 can be found at http://www.ti.com/lit/ds/symlink/INA226.pdf and it
47 | contains the information required in order to hook up the device. Unfortunately it comes as a VSSOP
48 | package but it can be soldered onto a breakout board for breadboard use. The INA226 is quite
49 | similar to the INA219 mentioned above, but it can take bus voltages of up to 36V (which I needed in
50 | order to monitor a 24V battery system which goes above 28V while charging and which is above the
51 | absolute limits of the INA219). It is also significantly more accurate than the INA219, plus has an
52 | alert pin.
53 |
54 | Interrupts on Arduinos can get a bit confusing, differentiating between external interrupts and pin
55 | change interrupts. The external interrupts are limited and which pins are available are different
56 | for each processor, see
57 | https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/ for
58 | additional information. Pin Change interrupts, on the other hand, can be assigned to most pins, but
59 | these interrupts are shared in groups of pins (call "ports") and when the interrupts are triggered
60 | they call one of 3 possible ISRs. This program makes use of PCINT0_vect and the interrupt is set to
61 | pin 8. The tests were done on an Arduino UNO and Arduino Micro using this pin
62 |
63 | Sometimes the INA devices will do a soft/hard reset on voltage spikes (despite using decoupling
64 | capacitors) and since the "PCINT0_vect" is called only when the ALERT pin is pulled low and the
65 | default mode of the INA226 upon reset is "off, this would result in the program never collecting
66 | statistics. For this reason the TIMER1 is used as a watchdog timer, triggering an interrupt every
67 | second. If no measurements are detected then the INA226 is manually reset and processing continues.
68 |
69 | GNU General Public License 3
70 | ============================
71 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU
72 | General Public License as published by the Free Software Foundation, either version 3 of the
73 | License, or (at your option) any later version. This program is distributed in the hope that it
74 | will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
75 | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should
76 | have received a copy of the GNU General Public License along with this program (see
77 | https://github.com/Zanduino/INA/blob/master/LICENSE). If not, see
78 | .
79 |
80 | Vers. Date Developer Comments
81 | ====== ========== ========== ==============================================================
82 | 1.0.1 2020-06-30 SV-Zanshin Issue #58 - clang-formatted document
83 | 1.0.0 2018-10-13 SV-Zanshin Ready for publishing
84 | 1.0.0 2018-10-03 SV-Zanshin Cloned and adapted example
85 | */
86 | #include // INA Library
87 |
88 | #include "MB85_FRAM.h" // I2C FRAM Library
89 | /**************************************************************************************************
90 | ** Declare program Constants **
91 | **************************************************************************************************/
92 | const uint8_t INA_ALERT_PIN = 8; // Pin 8.
93 | const uint8_t GREEN_LED_PIN = 13; // Green LED (standard location)
94 | const uint32_t SERIAL_SPEED = 115200; // Use fast serial speed
95 | const uint16_t ARRAY_BYTES = 1200; // Bytes in data array
96 | /**************************************************************************************************
97 | ** Declare global variables, structures and instantiate classes **
98 | **************************************************************************************************/
99 | uint8_t deviceNumber = UINT8_MAX; // Device Number to use in example
100 | volatile uint64_t sumBusRaw = 0; // Sum of bus raw values
101 | volatile int64_t sumShuntRaw = 0; // Sum of shunt raw values
102 | volatile uint8_t readings = 0; // Number of measurements taken
103 | uint8_t chips_detected = 0; // Number of I2C FRAM chips detected
104 | volatile uint32_t framIndex = 0; // Index to the next free position
105 | INA_Class INA; // INA class instantiation
106 | MB85_FRAM_Class FRAM; // FRAM Memory class instantiation
107 |
108 | void writeNibble(uint8_t dataArray[], const uint16_t nibblePos, const uint8_t nibbleData) {
109 | /************************************************************************************************
110 | ** Method "writeNibble()" will write the LSB 4 bits of "nibbleData" to the "dataArray" nibble **
111 | ** offset "nibblePos", each index position is 4 bits. **
112 | ************************************************************************************************/
113 | uint8_t writeByte = *(dataArray + (nibblePos / 2)); // Read the correct byte and select
114 | if (nibblePos & 1) { // whether the LSB or MSB is to be set
115 | writeByte = (writeByte & 0xF0) | (nibbleData & 0xF); // Keep MSB & set the LSB to value
116 | } else {
117 | writeByte = (nibbleData << 4) | (writeByte & 0xF); // Keep LSB & set the MSB to value
118 | } // of if-then-else nibblePos is odd
119 | *(dataArray + (nibblePos / 2)) = writeByte; // Write the new value to array
120 | } // of method "writeNibble()"
121 | uint8_t readNibble(uint8_t dataArray[], const uint16_t nibblePos) {
122 | /************************************************************************************************
123 | ** Method "readNibble()" will read the nibble addressed by "nibblePos" into the write the 4 **
124 | ** LSB bits of the return value. Each index position of the virtual array is 4 bits. **
125 | ************************************************************************************************/
126 | uint8_t returnVal = *(dataArray + (nibblePos / 2)); // Read the correct byte and select
127 | if (nibblePos & 1) { // whether the LSB or MSB is to be returned
128 | returnVal = returnVal & 0xF; // Use the 4 LSB bits
129 | } else {
130 | returnVal = returnVal >> 4; // Use the 4 MSB bits
131 | } // of if-then-else nibblePos is odd
132 | return returnVal; // Return the computed nibble
133 | } // of method "readNibble()"
134 | ISR(PCINT0_vect) {
135 | /************************************************************************************************
136 | ** Declare interrupt service routine for the pin-change interrupt on pin 8 which is set in the **
137 | ** setup() method **
138 | ************************************************************************************************/
139 | static uint16_t tempsumBusRaw; // Declare as static to only init 1
140 | static int16_t tempsumShuntRaw; // Declare as static to only init 1
141 | *digitalPinToPCMSK(INA_ALERT_PIN) &= ~bit(digitalPinToPCMSKbit(INA_ALERT_PIN)); // Disable PCMSK
142 | PCICR &= ~bit(digitalPinToPCICRbit(INA_ALERT_PIN)); // disable interrupt for the group
143 | digitalWrite(GREEN_LED_PIN, !digitalRead(GREEN_LED_PIN)); // Toggle LED to show we are working
144 | sei(); // Enable interrupts for I2C calls
145 | tempsumBusRaw = INA.getBusRaw(deviceNumber); // Read the current value into temp
146 | tempsumShuntRaw = INA.getShuntRaw(deviceNumber); // Read the current value into temp
147 | INA.waitForConversion(deviceNumber); // Resets interrupt flag and start
148 | cli(); // Disable interrupts
149 | sumBusRaw += tempsumBusRaw; // copy value while ints disabled
150 | sumShuntRaw += tempsumShuntRaw; // copy value while ints disabled
151 | readings++; // Increment the number of readings
152 | *digitalPinToPCMSK(INA_ALERT_PIN) |= bit(digitalPinToPCMSKbit(INA_ALERT_PIN)); // Enable PCMSK
153 | PCIFR |= bit(digitalPinToPCICRbit(INA_ALERT_PIN)); // clear any outstanding interrupt
154 | PCICR |= bit(digitalPinToPCICRbit(INA_ALERT_PIN)); // enable interrupt for the group
155 | } // of ISR handler for INT0 group of pins
156 | void writeDataToArray(uint8_t dataArray[], uint16_t &nibbleIndex, const int16_t deltaData) {
157 | /************************************************************************************************
158 | ** Function "writeDataToArray()" writes 4LSB from "nibbleData" to the "nibbleIndex" nibble in **
159 | *"dataArray". A Huffmann-like encoding with variable length is used to write the delta values **
160 | ** to the appropriate array. Each array "index" element is one nibble (4 bits) and the MSB **
161 | ** characters of the MSB nibble denote the record type. If the MSB is "B0" then it is a **
162 | ** 1-nibble long value, if the 2 MSB are "B10" then it is a 2 nibble value, if "B110" then 3 **
163 | ** nibbles, "B1110" denotes 4 and "B1111" denotes 5 nibbles. See the table below: **
164 | ** **
165 | ** 24-Bit representation Data Bits Value Range **
166 | ** ===================== ============ =============== **
167 | ** ----------------0xxx 3 bits data -4 to 3 **
168 | ** ------------10xxxxxx 6 bits data -16 to 15 **
169 | ** --------110xxxxxxxxx 9 bits data -256 to 255 **
170 | ** ----1110xxxxxxxxxxxx 12 bits data -2048 to 2047 **
171 | ** 1111xxxxxxxxxxxxxxxx 16 bits data -32768 to 32767 **
172 | ************************************************************************************************/
173 |
174 | if (deltaData >= -4 && deltaData <= 3) // 1N, format 0xxx
175 | {
176 | writeNibble(dataArray, nibbleIndex++, deltaData & B111); // Write 1N to array
177 | } else {
178 | if (deltaData >= -16 && deltaData <= 15) // 2N, format 10xxxxxx
179 | {
180 | writeNibble(dataArray, nibbleIndex++, ((deltaData >> 4) & B11) | B1000); // write MSB
181 | writeNibble(dataArray, nibbleIndex++, deltaData); // write LSB
182 | } else {
183 | if (deltaData >= -256 && deltaData <= 255) // 3N, format 110xxxxxxxxx
184 | {
185 | writeNibble(dataArray, nibbleIndex++, ((deltaData >> 8) & 1) | B1100); // Set 3MSB 9th bit
186 | writeNibble(dataArray, nibbleIndex++, deltaData >> 4 & B1111); // write 4 MSB bits byte 1
187 | writeNibble(dataArray, nibbleIndex++, deltaData); // write 4 LSB bits byte 1
188 | } else {
189 | if (deltaData >= -2048 && deltaData <= 2047) // 4N, format 1110xxxxxxxxxxxx
190 | {
191 | writeNibble(dataArray, nibbleIndex++, B1110); // Header nibble
192 | writeNibble(dataArray, nibbleIndex++, deltaData >> 8); // next nibble
193 | writeNibble(dataArray, nibbleIndex++, deltaData >> 4); // next nibble
194 | writeNibble(dataArray, nibbleIndex++, deltaData); // LSB nibble
195 | } else { // 5N, fmt 1111xxxxxxxxxxxxxxxx
196 | writeNibble(dataArray, nibbleIndex++, B1111); // Header nibble
197 | writeNibble(dataArray, nibbleIndex++, deltaData >> 12); // MSB nibble
198 | writeNibble(dataArray, nibbleIndex++, deltaData >> 8); // next nibble
199 | writeNibble(dataArray, nibbleIndex++, deltaData >> 4); // next nibble
200 | writeNibble(dataArray, nibbleIndex++, deltaData); // LSB nibble
201 | } // if-then-else value fits in 4 or 5 nibbles
202 | } // if-then-else value fits in 3 nibbles
203 | } // if-then-else value fits in 2 nibbles
204 | } // if-then-else value fits in 1 nibble
205 | } // of method "WriteDataToArray()"
206 | int16_t readDataFromArray(uint8_t dataArray[], uint16_t &nibbleIndex) {
207 | /************************************************************************************************
208 | ** Function "readDataToArray()" returns a 2-Byte signed integer from "dataArray" starting at **
209 | ** "nibbleIndex" and expanding the Array's internal Huffmann-encoding values. See the descrip- **
210 | ** tion of writeDataToArray() for details **
211 | ************************************************************************************************/
212 |
213 | int16_t outValue = 0; // Declare return variable
214 | uint8_t controlBits = readNibble(dataArray, nibbleIndex++); // Read the header nibble
215 | if (controlBits >> 3 == 0) // ----------------0xxx 3 bits data - 4 to 3
216 | {
217 | outValue = controlBits & B111; // mask High Bit
218 | if (outValue >> 2 & B1) { outValue |= 0xFFF8; } // If it is a negative number
219 | } else {
220 | if (controlBits >> 2 == B10) // ------------10xxxxxx 6 bits data - 16 to 15
221 | {
222 | outValue = (controlBits & B11) << 4; // mask 2 High Bits
223 | outValue |= readNibble(dataArray, nibbleIndex++); // move in 4 LSB
224 | if (outValue >> 5 & B1) { outValue |= 0xFFE0; } // If it is a negative number
225 | } else {
226 | if (controlBits >> 1 == B110) // --------110xxxxxxxxx 9 bits data - 256 to 255
227 | {
228 | outValue = (controlBits & B1) << 8; // mask 2 High Bits
229 | outValue |= readNibble(dataArray, nibbleIndex++) << 4; // move in 4 middle bits
230 | outValue |= readNibble(dataArray, nibbleIndex++); // move in 4 LSB
231 | if (outValue >> 8 & B1) { outValue |= 0xFE00; } // If it is a negative number
232 | } else {
233 | if (controlBits == B1110) // ----1110xxxxxxxxxxxx 12 bits data - 2048 to 2047
234 | {
235 | outValue = readNibble(dataArray, nibbleIndex++) << 8; // move in 4 high bits
236 | outValue |= readNibble(dataArray, nibbleIndex++) << 4; // move in 4 middle bits
237 | outValue |= readNibble(dataArray, nibbleIndex++); // move in 4 low bits
238 | if (outValue >> 11 & B1) { outValue |= 0xF000; } // If it is a negative number
239 | } else {
240 | if (controlBits == B1111) // 1111xxxxxxxxxxxxxxxx 16 bits data - 16384 to 16383
241 | {
242 | outValue = readNibble(dataArray, nibbleIndex++) << 12; // move in 4 high bits
243 | outValue |= readNibble(dataArray, nibbleIndex++) << 8; // move in 4 middle bits
244 | outValue |= readNibble(dataArray, nibbleIndex++) << 4; // move in 4 middle bits
245 | outValue |= readNibble(dataArray, nibbleIndex++); // move in 4 low bits
246 | } // if-then 5 nibbles
247 | } // if-then-else 4 nibbles
248 | } // if-then-else 3 nibbles
249 | } // if-then-else 2 nibbles
250 | } // if-then-else 1 nibble
251 | return (outValue);
252 | } // of method "readDataFromArray()"
253 |
254 | ISR(TIMER1_COMPA_vect) {
255 | /**********************************************************************************************
256 | ** Declare interrupt service routine for TIMER1, which is set to trigger once every second **
257 | **********************************************************************************************/
258 | static int16_t deltaBus, deltaShunt; // Difference value from last
259 | static uint16_t arrayNibbleIndex = 0; // Array index in Nibbles
260 | static int16_t lastBusRaw = 0; // Value from last reading
261 | static int16_t lastShuntRaw = 0; // Value from last reading
262 | static int16_t baseBusRaw = 0; // Base value for delta readings
263 | static int16_t baseShuntRaw = 0; // Base value for delta readings
264 | static uint16_t arrayReadings = 0; // Number of readings in array
265 | static uint8_t dataArray[ARRAY_BYTES]; // Array for bus and shunt readings
266 | if (arrayNibbleIndex == 0 && millis() < 3000) { // Skip first 3 seconds
267 | baseBusRaw = (int16_t)(sumBusRaw / readings); // after startup to allow settings
268 | lastBusRaw = baseBusRaw; // to settle
269 | baseShuntRaw = (int16_t)(sumShuntRaw / readings);
270 | lastShuntRaw = baseShuntRaw;
271 | readings = 0; // then skip readings to let the
272 | sumBusRaw = 0; // sensor settle down
273 | sumShuntRaw = 0; // Reset values
274 | return;
275 | } // of if-then first second after startup
276 | deltaBus = ((int16_t)(sumBusRaw / readings) - lastBusRaw); // Compute the delta bus
277 | deltaShunt = ((int16_t)(sumShuntRaw / readings) - lastShuntRaw); // Compute the delta shunt
278 | writeDataToArray(dataArray, arrayNibbleIndex, deltaBus); // Add bus reading to array
279 | writeDataToArray(dataArray, arrayNibbleIndex, deltaShunt); // Add shunt reading to array
280 | arrayReadings++; // increment the counter
281 | lastBusRaw = sumBusRaw / readings; // Reset values
282 | lastShuntRaw = sumShuntRaw / readings; // Reset values
283 | readings = 0; // Reset values
284 | sumBusRaw = 0; // Reset values
285 | sumShuntRaw = 0; // Reset values
286 | /*****************************************************************************************************************
287 | ** Once the array could fill up on the next reading (2x max reading of 5 nibbles) then it is
288 | *time to flush the **
289 | ** the accumulated readings. **
290 | *****************************************************************************************************************/
291 | if ((arrayNibbleIndex + 10) / 2 >= ARRAY_BYTES) // //
292 | { // //
293 | int16_t busValue = 0; // Contains current bus value //
294 | int16_t shuntValue = 0; // Contains current shunt value //
295 | uint16_t workNibbleIndex = 0; // Index into array for reading //
296 | /***************************************************************************************************************
297 | ** If there is a FRAM memory board attached, then copy the array contents to it **
298 | ***************************************************************************************************************/
299 | if (chips_detected > 0) // Only execute if there is memory //
300 | { // //
301 | if ((framIndex + sizeof(dataArray) <
302 | FRAM.totalBytes())) // Only write when space available //
303 | { // //
304 | cli(); // Enable interrupts temporarily //
305 | Serial.print(millis() / 1000 / 60); // //
306 | Serial.print(" "); // //
307 | Serial.print(F("Writing ")); // //
308 | Serial.print(sizeof(dataArray)); // //
309 | Serial.print(" Bytes to memory @"); // //
310 | Serial.print(framIndex); // //
311 | Serial.print(".\n"); // //
312 | sei(); // Disable interrupts again //
313 | FRAM.write(framIndex, dataArray); // Write the whole array to FRAM //
314 | framIndex += sizeof(dataArray); // set index to new location //
315 | } // of if-then there is space in the EEPROM // //
316 | } // of if-then we have at least one EEPROM attached to the I2C bus // //
317 | for (uint16_t readingNo = 1; readingNo <= arrayReadings;
318 | readingNo++) // Process every reading in array //
319 | { // //
320 | busValue = readDataFromArray(dataArray, workNibbleIndex); // Get next bus value from array //
321 | baseBusRaw += busValue; // apply delta value to bus base //
322 | shuntValue =
323 | readDataFromArray(dataArray, workNibbleIndex); // Get shunt next value from array //
324 | baseShuntRaw += shuntValue; // apply delta value to shunt base //
325 | /*************************************************************************************************************
326 | ** Insert code here to save data to static RAM or to a SD-Card or elsewhere **
327 | *************************************************************************************************************/
328 |
329 | cli(); // Enable interrupts temporarily //
330 | Serial.print(millis() / 1000);
331 | Serial.print(" ");
332 | Serial.print(readingNo);
333 | Serial.print(" ");
334 | Serial.print(baseBusRaw * 0.00125, 4);
335 | Serial.print("V ");
336 | Serial.print(0.0025 * baseShuntRaw);
337 | Serial.println("mA");
338 | sei(); // Disable interrupts again //
339 |
340 | } // of for-next each array reading // //
341 | arrayNibbleIndex = 0; // reset //
342 | arrayReadings = 0; // reset //
343 | } // of if-then the internal array is full // //
344 | } // of ISR "TIMER1_COMPA_vect" // //
345 |
346 | /*******************************************************************************************************************
347 | ** Method Setup(). This is an Arduino IDE method which is called first upon initial boot or
348 | *restart. It is only **
349 | ** called one time and all of the variables and other initialization calls are done here prior to
350 | *entering the **
351 | ** main loop for data measurement. **
352 | *******************************************************************************************************************/
353 | void setup() // //
354 | { // //
355 | pinMode(GREEN_LED_PIN, OUTPUT); // Define the green LED as an output//
356 | digitalWrite(GREEN_LED_PIN, true); // Turn on the LED //
357 | pinMode(INA_ALERT_PIN, INPUT_PULLUP); // Declare pin with pull-up resistor//
358 | *digitalPinToPCMSK(INA_ALERT_PIN) |=
359 | bit(digitalPinToPCMSKbit(INA_ALERT_PIN)); // Enable PCMSK pin //
360 | PCIFR |= bit(digitalPinToPCICRbit(INA_ALERT_PIN)); // clear any outstanding interrupt //
361 | PCICR |= bit(digitalPinToPCICRbit(INA_ALERT_PIN)); // enable interrupt for the group //
362 | Serial.begin(SERIAL_SPEED); // Start serial communications //
363 | #ifdef __AVR_ATmega32U4__ // If this is a 32U4 processor, //
364 | delay(2000); // wait 3 seconds for serial port //
365 | #endif // interface to initialize //
366 | Serial.print(
367 | F("\n\nINA Data Logging with interrupts V1.0.3\n")); // Display program information //
368 | uint8_t devicesFound = 0; // Number of INA2xx found on I2C //
369 | while (deviceNumber == UINT8_MAX) // Loop until we find devices //
370 | { // //
371 | devicesFound = INA.begin(1, 100000); // ±1Amps maximum for 0.1Ω resistor //
372 | for (uint8_t i = 0; i < devicesFound; i++) // the first INA226 device found //
373 | { // Change "INA226" to "INA260" or //
374 | // whichever INA2xx to measure //
375 | if (strcmp(INA.getDeviceName(i), "INA226") == 0) // Set deviceNumber appropriately //
376 | { // //
377 | deviceNumber = i; // //
378 | INA.reset(deviceNumber); // Reset device to default settings //
379 | break; // //
380 | } // of if-then we have found an INA226 // //
381 | } // of for-next loop through all devices found // //
382 | if (deviceNumber == UINT8_MAX) // Try again if no device found //
383 | { // //
384 | Serial.print(F("No INA226 found. Waiting 5s.\n")); // //
385 | delay(5000); // //
386 | } // of if-then no INA226 found // //
387 | } // of if-then no device found // //
388 | Serial.print(F("Found INA226 at device number ")); // //
389 | Serial.println(deviceNumber); // //
390 | Serial.println(); // //
391 | INA.setAveraging(64, deviceNumber); // Average each reading 64 times //
392 | INA.setAveraging(8, deviceNumber); // Average each reading 4 times //
393 | INA.setBusConversion(82440, deviceNumber); // Maximum conversion time 8.244ms //
394 | INA.setShuntConversion(82440, deviceNumber); // Maximum conversion time 8.244ms //
395 | INA.setMode(INA_MODE_CONTINUOUS_BOTH, deviceNumber); // Bus/shunt measured continuously //
396 | INA.AlertOnConversion(true, deviceNumber); // Make alert pin go low on finish //
397 | chips_detected = FRAM.begin(); // return number of memories //
398 | if (chips_detected > 0) { // //
399 | Serial.print(F("Found ")); // //
400 | Serial.print(chips_detected); // //
401 | Serial.print(F(" FRAM with a total of ")); // //
402 | uint32_t totalMemory = 0; // //
403 | for (uint8_t i = 0; i < chips_detected; i++) { // //
404 | totalMemory += FRAM.memSize(i); // Add memory of chip to total //
405 | } // of for-next each memory // //
406 | Serial.print(totalMemory / 1024); // //
407 | Serial.println(F("KB memory.")); // //
408 | } // if-then we have found a FRAM memory // //
409 | cli(); // disable interrupts while setting //
410 | TCCR1A = 0; // TCCR1A register reset //
411 | TCCR1B = 0; // TCCR1B register reset //
412 | TCNT1 = 0; // initialize counter //
413 | OCR1A = 15624; // ((16*10^6) / (1*1024)) - 1 //
414 | TCCR1B |= (1 << WGM12); // Enable CTC mode //
415 | TCCR1B |= (1 << CS12) | (1 << CS10); // CS10 & CS12 for 1024 prescaler //
416 | TIMSK1 |= (1 << OCIE1A); // Enable timer compare interrupt //
417 | sei(); // re-enable interrupts //
418 | } // of method setup() // //
419 |
420 | /*******************************************************************************************************************
421 | ** This is the main program for the Arduino IDE, it is called in an infinite loop. The INA226
422 | *measurements are **
423 | ** triggered by the interrupt handler each time a conversion is ready, and another interrupt is
424 | *triggered every **
425 | ** second to store the collected readings. Thus the main program is free to do other tasks. **
426 | *******************************************************************************************************************/
427 | void loop() // //
428 | { // //
429 | delay(10000);
430 | } // of method loop //----------------------------------//
431 |
--------------------------------------------------------------------------------
/examples/DisplayReadings/DisplayReadings.ino:
--------------------------------------------------------------------------------
1 | /*!
2 | @file DisplayReadings.ino
3 |
4 | @brief Example program for the INA Library demonstrating reading an INA device and displaying
5 | results
6 |
7 | @section DisplayReadings_section Description
8 |
9 | Program to demonstrate the INA library for the Arduino. When started, the library searches the
10 | I2C bus for all INA2xx devices. Then the example program goes into an infinite loop and displays
11 | the power measurements (bus voltage and current) for all devices.\n\n
12 |
13 | Detailed documentation can be found on the GitHub Wiki pages at
14 | https://github.com/Zanduino/INA/wiki \n\n This example is for a INA set up to measure a 5-Volt
15 | load with a 0.1 Ohm resistor in place, this is the same setup that can be found in the Adafruit
16 | INA219 breakout board. The complex calibration options are done at runtime using the 2
17 | parameters specified in the "begin()" call and the library has gone to great lengths to avoid the
18 | use of floating point to conserve space and minimize runtime. This demo program uses floating
19 | point only to convert and display the data conveniently. The INA devices have 15 bits of
20 | precision, and even though the current and watt information is returned using 32-bit integers the
21 | precision remains the same.\n\n
22 |
23 | The library supports multiple INA devices and multiple INA device types. The Atmel's EEPROM is
24 | used to store the 96 bytes of static information per device using
25 | https://www.arduino.cc/en/Reference/EEPROM function calls. Although up to 16 devices could
26 | theoretically be present on the I2C bus the actual limit is determined by the available EEPROM -
27 | ATmega328 UNO has 1024k so can support up to 10 devices but the ATmega168 only has 512 bytes
28 | which limits it to supporting at most 5 INAs. Support has been added for the ESP32 based
29 | Arduinos, these use the EEPROM calls differently and need specific code.
30 |
31 | @section DisplayReadings_license GNU General Public License v3.0
32 |
33 | This program is free software : you can redistribute it and/or modify it under the terms of the
34 | GNU General Public License as published by the Free Software Foundation, either version 3 of the
35 | License, or (at your option) any later version.This program is distributed in the hope that it
36 | will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
37 | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.You should
38 | have received a copy of the GNU General Public License along with this program(see
39 | https://github.com/Zanduino/INA/blob/master/LICENSE). If not, see
40 | .
41 |
42 | @section DisplayReadings_author Author
43 |
44 | Written by Arnd at https://www.github.com/SV-Zanshin
45 |
46 | @section DisplayReadings_versions Changelog
47 |
48 | | Version | Date | Developer | Comments |
49 | | ------- | ---------- | -----------| ----------------------------------------------------------- |
50 | | 1.0.8 | 2020-12-01 | SV-Zanshin | Issue #72. Allow dynamic RAM allocation instead of EEPROM |
51 | | 1.0.7 | 2020-06-30 | SV-Zanshin | Issue #58. Changed formatting to use clang-format |
52 | | 1.0.6 | 2020-06-29 | SV-Zanshin | Issue #57. Changed case of functions "Alert..." |
53 | | 1.0.5 | 2020-05-03 | SV-Zanshin | Moved setting of maxAmps and shunt to constants |
54 | | 1.0.4 | 2019-02-16 | SV-Zanshin | Reformatted and refactored for legibility and clarity |
55 | | 1.0.3 | 2019-02-10 | SV-Zanshin | Issue #38. Made pretty-print columns line up |
56 | | 1.0.3 | 2019-02-09 | SV-Zanshin | Issue #38. Added device number to display |
57 | | 1.0.2 | 2018-12-29 | SV-Zanshin | Converted comments to doxygen format |
58 | | 1.0.1 | 2018-09-22 | SV-Zanshin | Comments corrected, add INA wait loop, removed F("") calls |
59 | | 1.0.0 | 2018-06-22 | SV-Zanshin | Initial release |
60 | | 1.0.0b | 2018-06-17 | SV-Zanshin | INA219 and INA226 completed, including testing |
61 | | 1.0.0a | 2018-06-10 | SV-Zanshin | Initial coding |
62 | */
63 |
64 | #if ARDUINO >= 100 // Arduino IDE versions before 100 need to use the older library
65 | #include "Arduino.h"
66 | #else
67 | #include "WProgram.h"
68 | #endif
69 | #include // Zanshin INA Library
70 |
71 | #if defined(_SAM3XA_) || defined(ARDUINO_ARCH_SAMD)
72 | // The SAM3XA architecture needs to include this library, it is already included automatically on
73 | // other platforms //
74 | #include // Needed for the SAM3XA (Arduino Zero)
75 | #endif
76 |
77 | /**************************************************************************************************
78 | ** Declare program constants, global variables and instantiate INA class **
79 | **************************************************************************************************/
80 | const uint32_t SERIAL_SPEED{115200}; ///< Use fast serial speed
81 | const uint32_t SHUNT_MICRO_OHM{100000}; ///< Shunt resistance in Micro-Ohm, e.g. 100000 is 0.1 Ohm
82 | const uint16_t MAXIMUM_AMPS{1}; ///< Max expected amps, clamped from 1A to a max of 1022A
83 | uint8_t devicesFound{0}; ///< Number of INAs found
84 | INA_Class INA; ///< INA class instantiation to use EEPROM
85 | // INA_Class INA(0); ///< INA class instantiation to use EEPROM
86 | // INA_Class INA(5); ///< INA class instantiation to use dynamic memory rather
87 | // than EEPROM. Allocate storage for up to (n) devices
88 |
89 | void setup() {
90 | /*!
91 | * @brief Arduino method called once at startup to initialize the system
92 | * @details This is an Arduino IDE method which is called first upon boot or restart. It is only
93 | * called one time and then control goes to the "loop()" method, from which control
94 | * never returns. The serial port is initialized and the INA.begin() method called to
95 | * find all INA devices on the I2C bus and then the devices are initialized to given
96 | * conversion and averaging rates.
97 | * @return void
98 | */
99 | Serial.begin(SERIAL_SPEED);
100 | #ifdef __AVR_ATmega32U4__ // If a 32U4 processor, then wait 2 seconds to initialize serial port
101 | delay(2000);
102 | #endif
103 | Serial.print("\n\nDisplay INA Readings V1.0.8\n");
104 | Serial.print(" - Searching & Initializing INA devices\n");
105 | /************************************************************************************************
106 | ** The INA.begin call initializes the device(s) found with an expected ±1 Amps maximum current **
107 | ** and for a 0.1Ohm resistor, and since no specific device is given as the 3rd parameter all **
108 | ** devices are initially set to these values. **
109 | ************************************************************************************************/
110 | devicesFound = INA.begin(MAXIMUM_AMPS, SHUNT_MICRO_OHM); // Expected max Amp & shunt resistance
111 | while (devicesFound == 0) {
112 | Serial.println(F("No INA device found, retrying in 10 seconds..."));
113 | delay(10000); // Wait 10 seconds before retrying
114 | devicesFound = INA.begin(MAXIMUM_AMPS, SHUNT_MICRO_OHM); // Expected max Amp & shunt resistance
115 | } // while no devices detected
116 | Serial.print(F(" - Detected "));
117 | Serial.print(devicesFound);
118 | Serial.println(F(" INA devices on the I2C bus"));
119 | INA.setBusConversion(8500); // Maximum conversion time 8.244ms
120 | INA.setShuntConversion(8500); // Maximum conversion time 8.244ms
121 | INA.setAveraging(128); // Average each reading n-times
122 | INA.setMode(INA_MODE_CONTINUOUS_BOTH); // Bus/shunt measured continuously
123 | INA.alertOnBusOverVoltage(true, 5000); // Trigger alert if over 5V on bus
124 | } // method setup()
125 |
126 | void loop() {
127 | /*!
128 | * @brief Arduino method for the main program loop
129 | * @details This is the main program for the Arduino IDE, it is an infinite loop and keeps on
130 | * repeating. In order to format the output use is made of the "sprintf()" function, but in the
131 | * Arduino implementation it has no support for floating point output, so the "dtostrf()" function
132 | * is used to convert the floating point numbers into formatted strings.
133 | * @return void
134 | */
135 | static uint16_t loopCounter = 0; // Count the number of iterations
136 | static char sprintfBuffer[100]; // Buffer to format output
137 | static char busChar[8], shuntChar[10], busMAChar[10], busMWChar[10]; // Output buffers
138 |
139 | Serial.print(F("Nr Adr Type Bus Shunt Bus Bus\n"));
140 | Serial.print(F("== === ====== ======== =========== =========== ===========\n"));
141 | for (uint8_t i = 0; i < devicesFound; i++) // Loop through all devices
142 | {
143 | dtostrf(INA.getBusMilliVolts(i) / 1000.0, 7, 4, busChar); // Convert floating point to char
144 | dtostrf(INA.getShuntMicroVolts(i) / 1000.0, 9, 4, shuntChar); // Convert floating point to char
145 | dtostrf(INA.getBusMicroAmps(i) / 1000.0, 9, 4, busMAChar); // Convert floating point to char
146 | dtostrf(INA.getBusMicroWatts(i) / 1000.0, 9, 4, busMWChar); // Convert floating point to char
147 | sprintf(sprintfBuffer, "%2d %3d %s %sV %smV %smA %smW\n", i + 1, INA.getDeviceAddress(i),
148 | INA.getDeviceName(i), busChar, shuntChar, busMAChar, busMWChar);
149 | Serial.print(sprintfBuffer);
150 | } // for-next each INA device loop
151 | Serial.println();
152 | delay(10000); // Wait 10 seconds before next reading
153 | Serial.print(F("Loop iteration "));
154 | Serial.print(++loopCounter);
155 | Serial.print(F("\n\n"));
156 | } // method loop()
157 |
--------------------------------------------------------------------------------
/images/INA226.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/images/INA226.jpg
--------------------------------------------------------------------------------
/images/horizontal.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/images/horizontal.png
--------------------------------------------------------------------------------
/images/horizontal_narrow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/images/horizontal_narrow.png
--------------------------------------------------------------------------------
/images/horizontal_narrow_small.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/images/horizontal_narrow_small.png
--------------------------------------------------------------------------------
/images/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/images/icon.png
--------------------------------------------------------------------------------
/images/ina.ai:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/images/ina.ai
--------------------------------------------------------------------------------
/images/logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
79 |
--------------------------------------------------------------------------------
/images/vertical.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/images/vertical.png
--------------------------------------------------------------------------------
/images/wiki.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Zanduino/INA/d89299ddfcf36e7fdcfd95a750dfb6ff27b3eb6c/images/wiki.png
--------------------------------------------------------------------------------
/keywords.txt:
--------------------------------------------------------------------------------
1 | ################################
2 | # Classes/Datatypes (KEYWORD1) #
3 | ################################
4 | INA_Class KEYWORD1
5 |
6 | ####################################
7 | # Methods and Functions (KEYWORD2) #
8 | ####################################
9 | begin KEYWORD2
10 | getBusMilliVolts KEYWORD2
11 | getShuntMicroVolts KEYWORD2
12 | getBusMicroAmps KEYWORD2
13 | getBusMicroWatts KEYWORD2
14 | getBusRaw KEYWORD2
15 | getShuntRaw KEYWORD2
16 | reset KEYWORD2
17 | setMode KEYWORD2
18 | setAveraging KEYWORD2
19 | setBusConversion KEYWORD2
20 | setShuntConversion KEYWORD2
21 | AlertOnConversion KEYWORD2
22 | waitForConversion KEYWORD2
23 | conversionFinished KEYWORD2
24 | AlertOnShuntOverVoltage KEYWORD2
25 | AlertOnShuntUnderVoltage KEYWORD2
26 | AlertOnBusOverVoltage KEYWORD2
27 | AlertOnBusUnderVoltage KEYWORD2
28 |
29 | ########################
30 | # Constants (LITERAL1) #
31 | ########################
32 | INA219 LITERAL1
33 | INA226 LITERAL1
34 | INA230 LITERAL1
35 | INA231 LITERAL1
36 | INA260 LITERAL1
37 | INA_MODE_SHUTDOWN LITERAL1
38 | INA_MODE_TRIGGERED_SHUNT LITERAL1
39 | INA_MODE_TRIGGERED_BOTH LITERAL1
40 | INA_MODE_POWER_DOWN LITERAL1
41 | INA_MODE_CONTINUOUS_SHUNT LITERAL1
42 | INA_MODE_CONTINUOUS_BOTH LITERAL1
43 | _EEPROM_offset LITERAL1
44 |
45 |
46 |
--------------------------------------------------------------------------------
/library.properties:
--------------------------------------------------------------------------------
1 | name=INA2xx
2 | version=1.1.0
3 | author=Arnd
4 | maintainer=Arnd
5 | sentence=Read current, voltage and power data from one or more INA2xx device(s)
6 | paragraph=This library allows a number of INA2xx devices (mixed types allowed) to be read and controlled simultaneously.
7 | category=Sensors
8 | url=https://github.com/Zanduino/INA
9 | architectures=*
10 |
--------------------------------------------------------------------------------
/src/INA.cpp:
--------------------------------------------------------------------------------
1 | /*!
2 | * @file INA.cpp
3 | *
4 | * @section INAcpp_intro_section Description
5 | *
6 | * Arduino Library for accessing the INA2xx Family of power measurement devices\n\n
7 | * See main library header file "INA.h" for details and license information
8 | *
9 | */
10 | #include ///< Include the header definition
11 | #include ///< I2C Library definition
12 | #if defined(__AVR__) || defined(CORE_TEENSY) || defined(ESP32) || defined(ESP8266) || \
13 | defined(STM32F1)
14 | #include ///< Include the EEPROM library for AVR-Boards
15 | #endif
16 | inaDet::inaDet() {} ///< constructor for INA Detail class
17 | inaDet::inaDet(inaEEPROM &inaEE) {
18 | /*! @brief INA Detail Class Constructor (Overloaded)
19 | @details Construct the class using the saved EEPROM data structure
20 | @param[in] inaEE Saved EEPROM Values */
21 | type = inaEE.type;
22 | operatingMode = inaEE.operatingMode;
23 | address = inaEE.address;
24 | maxBusAmps = inaEE.maxBusAmps;
25 | microOhmR = inaEE.microOhmR;
26 | current_LSB = (uint64_t)maxBusAmps * 1000000000 / 32767; // Get the best possible LSB in nA
27 | power_LSB = (uint32_t)20 * current_LSB; // Default multiplier per device
28 | switch (type) {
29 | case INA219:
30 | busVoltageRegister = INA_BUS_VOLTAGE_REGISTER;
31 | shuntVoltageRegister = INA219_SHUNT_VOLTAGE_REGISTER;
32 | currentRegister = INA219_CURRENT_REGISTER;
33 | busVoltage_LSB = INA219_BUS_VOLTAGE_LSB;
34 | shuntVoltage_LSB = INA219_SHUNT_VOLTAGE_LSB;
35 | break;
36 | case INA226:
37 | case INA230:
38 | case INA231:
39 | power_LSB = (uint32_t)25 * current_LSB; // issue #66 corrected multiplier
40 | busVoltageRegister = INA_BUS_VOLTAGE_REGISTER;
41 | shuntVoltageRegister = INA226_SHUNT_VOLTAGE_REGISTER;
42 | currentRegister = INA226_CURRENT_REGISTER;
43 | busVoltage_LSB = INA226_BUS_VOLTAGE_LSB;
44 | shuntVoltage_LSB = INA226_SHUNT_VOLTAGE_LSB;
45 | break;
46 |
47 | case INA228:
48 | power_LSB = 0; // TODO
49 | busVoltageRegister = INA228_BUS_VOLTAGE_REGISTER;
50 | busVoltage_LSB = INA228_BUS_VOLTAGE_LSB;
51 | shuntVoltageRegister = INA228_SHUNT_VOLTAGE_REGISTER;
52 |
53 | currentRegister = INA226_CURRENT_REGISTER;
54 | shuntVoltage_LSB = INA226_SHUNT_VOLTAGE_LSB;
55 | break;
56 |
57 | case INA260:
58 | busVoltageRegister = INA_BUS_VOLTAGE_REGISTER;
59 | shuntVoltageRegister = INA260_SHUNT_VOLTAGE_REGISTER; // Register not present
60 | currentRegister = INA260_CURRENT_REGISTER;
61 | busVoltage_LSB = INA260_BUS_VOLTAGE_LSB;
62 | current_LSB = 1250000; // Fixed LSB of 1.25mv
63 | power_LSB = 10000000; // Fixed multiplier per device
64 | break;
65 | case INA3221_0:
66 | case INA3221_1:
67 | case INA3221_2:
68 | busVoltageRegister = INA_BUS_VOLTAGE_REGISTER;
69 | shuntVoltageRegister = INA3221_SHUNT_VOLTAGE_REGISTER;
70 | currentRegister = 0; // INA3221 has no current Reg
71 | busVoltage_LSB = INA3221_BUS_VOLTAGE_LSB;
72 | shuntVoltage_LSB = INA3221_SHUNT_VOLTAGE_LSB;
73 | current_LSB = 0; // INA3221 has no current reg.
74 | power_LSB = 0; // INA3221 has no power reg.
75 | if (type == INA3221_1) {
76 | busVoltageRegister += 2; // Reg for 2nd bus voltage
77 | shuntVoltageRegister += 2; // Reg for 2nd shunt voltage
78 | } else {
79 | if (type == INA3221_2) {
80 | busVoltageRegister += 4; // Reg for 3rd bus voltage
81 | shuntVoltageRegister += 4; // Reg for 3rd shunt voltage
82 | } // of if-then INA322_2
83 | } // of if-then-else INA3221_1
84 | break;
85 | } // of switch type
86 | } // of constructor
87 | INA_Class::INA_Class(uint8_t expectedDevices) : _expectedDevices(expectedDevices) {
88 | /*!
89 | @brief Class constructor
90 | @details If called without a parameter or with a 0 value, then the constructor does nothing,
91 | but if a value is passed then using EEPROM is disabled and each INA-Device found
92 | has its data (inaEEPROM structure size) stored in a array dynamically allocated during
93 | library instatiation here. If there is not enough space then the pointer isn't init-
94 | ialized and the program will abort later on. No error checking can be done here
95 | @param[in] expectedDevices Number of elements to initialize array to if non-zero
96 | */
97 | if (_expectedDevices) {
98 | _DeviceArray = new inaEEPROM[_expectedDevices];
99 | } // if-then use memory rather than EEPROM
100 | } // of class constructor
101 | INA_Class::~INA_Class() {
102 | /*!
103 | @brief Class destructor
104 | @details If dynamic memory has been allocated for device storage rather than the default EEPROM,
105 | then that memory is freed here; otherwise the destructor does nothing
106 | */
107 | if (_expectedDevices) { delete[] _DeviceArray; } // if-then use memory rather than EEPROM
108 | } // of class destructor
109 | int16_t INA_Class::readWord(const uint8_t addr, const uint8_t deviceAddress) const {
110 | /*! @brief Read one word (2 bytes) from the specified I2C address
111 | @details Standard I2C protocol is used, but a delay of I2C_DELAY microseconds has been
112 | added to let the INAxxx devices have sufficient time to get the return data ready
113 | @param[in] addr I2C address to read from
114 | @param[in] deviceAddress Address on the I2C device to read from
115 | @return integer value read from the I2C device */
116 | Wire.beginTransmission(deviceAddress); // Address the I2C device
117 | Wire.write(addr); // Send register address to read
118 | Wire.endTransmission(); // Close transmission
119 | delayMicroseconds(I2C_DELAY); // delay required for sync
120 | Wire.requestFrom(deviceAddress, (uint8_t)2); // Request 2 consecutive bytes
121 | return ((uint16_t)Wire.read() << 8) | Wire.read();
122 | } // of method readWord()
123 | int32_t INA_Class::read3Bytes(const uint8_t addr, const uint8_t deviceAddress) const {
124 | /*! @brief Read 3 bytes from the specified I2C address
125 | @details Standard I2C protocol is used, but a delay of I2C_DELAY microseconds has been
126 | added to let the INAxxx devices have sufficient time to get the return data ready
127 | @param[in] addr I2C address to read from
128 | @param[in] deviceAddress Address on the I2C device to read from
129 | @return integer value read from the I2C device */
130 | Wire.beginTransmission(deviceAddress); // Address the I2C device
131 | Wire.write(addr); // Send register address to read
132 | Wire.endTransmission(); // Close transmission
133 | delayMicroseconds(I2C_DELAY); // delay required for sync
134 | Wire.requestFrom(deviceAddress, (uint8_t)3); // Request 3 consecutive bytes
135 | return ((uint32_t)Wire.read() << 16) | ((uint32_t)Wire.read() << 8) | ((uint32_t)Wire.read());
136 | } // of method readWord()
137 | void INA_Class::writeWord(const uint8_t addr, const uint16_t data,
138 | const uint8_t deviceAddress) const {
139 | /*! @brief Write 2 bytes to the specified I2C address
140 | @details Standard I2C protocol is used, but a delay of I2C_DELAY microseconds has been
141 | added to let the INAxxx devices have sufficient time to process the data
142 | @param[in] addr I2C address to write to
143 | @param[in] data 2 Bytes to write to the device
144 | @param[in] deviceAddress Address on the I2C device to write to */
145 | Wire.beginTransmission(deviceAddress); // Address the I2C device
146 | Wire.write(addr); // Send register address to write
147 | Wire.write((uint8_t)(data >> 8)); // Write the first (MSB) byte
148 | Wire.write((uint8_t)data); // and then the second byte
149 | Wire.endTransmission(); // Close transmission and actually send data
150 | delayMicroseconds(I2C_DELAY); // delay required for sync
151 | } // of method writeWord()
152 | void INA_Class::readInafromEEPROM(const uint8_t deviceNumber) {
153 | /*! @brief Read INA device information from EEPROM
154 | @details Retrieve the stored information for a device from EEPROM. Since this method is
155 | private and access is controlled, no range error checking is performed
156 | @param[in] deviceNumber Index to device array */
157 | if (deviceNumber == _currentINA || deviceNumber > _DeviceCount) return; // Skip if correct device
158 | if (_expectedDevices == 0) {
159 | #if defined(__AVR__) || defined(CORE_TEENSY) || defined(ESP32) || defined(ESP8266) || (__STM32F1__)
160 | #ifdef __STM32F1__ // STM32F1 has no built-in EEPROM
161 | uint16_t e = deviceNumber * sizeof(inaEE); // it uses flash memory to emulate
162 | uint16_t *ptr = (uint16_t *)&inaEE; // "EEPROM" calls are uint16_t type
163 | for (uint8_t n = sizeof(inaEE) + _EEPROM_offset; n; --n) // Implement EEPROM.get template
164 | {
165 | EEPROM.read(e++, ptr++); // for ina (inaDet type)
166 | } // of for-next each byte
167 | #else
168 | EEPROM.get(_EEPROM_offset + (deviceNumber * sizeof(inaEE)), inaEE); // Read EEPROM values
169 | #endif
170 | #else
171 | inaEE = _EEPROMEmulation[deviceNumber];
172 | #endif
173 | } else {
174 | inaEE = _DeviceArray[deviceNumber];
175 | } // if-then-else use EEPROM
176 | _currentINA = deviceNumber;
177 | ina = inaEE; // see inaDet constructor
178 | } // of method readInafromEEPROM()
179 | void INA_Class::writeInatoEEPROM(const uint8_t deviceNumber) {
180 | /*! @brief Write INA device information to EEPROM
181 | @details Write the stored information for a device from EEPROM. Since this method is
182 | private and access is controlled, no range error checking is performed
183 | @param[in] deviceNumber Index to device array */
184 | inaEE = ina; // only save relevant part of ina to EEPROM
185 | if (_expectedDevices == 0) {
186 | #if defined(__AVR__) || defined(CORE_TEENSY) || defined(ESP32) || defined(ESP8266) || (__STM32F1__)
187 | #ifdef __STM32F1__ // STM32F1 has no built-in EEPROM
188 | uint16_t e = deviceNumber * sizeof(inaEE); // it uses flash memory to emulate
189 | const uint16_t *ptr = (const uint16_t *)&inaEE; // "EEPROM" calls are uint16_t type
190 | for (uint8_t n = sizeof(inaEE) + _EEPROM_offset; n; --n) // Implement EEPROM.put template
191 | {
192 | EEPROM.update(e++, *ptr++); // for ina (inaDet type)
193 | } // for-next
194 | #else
195 | EEPROM.put(_EEPROM_offset + (deviceNumber * sizeof(inaEE)), inaEE); // Write the structure
196 | #ifdef ESP32
197 | EEPROM.commit(); // Force write to EEPROM when ESP32
198 | #endif
199 | #endif
200 | #else
201 | _EEPROMEmulation[deviceNumber] = inaEE;
202 | #endif
203 | } else {
204 | _DeviceArray[deviceNumber] = inaEE;
205 | } // if-then-else use EEPROM to store data
206 | } // of method writeInatoEEPROM()
207 | void INA_Class::setI2CSpeed(const uint32_t i2cSpeed) const {
208 | /*! @brief Set a new I2C speed
209 | @details I2C allows various bus speeds, see the enumerated type I2C_MODES for the standard
210 | speeds. The valid speeds are 100KHz, 400KHz, 1MHz and 3.4MHz. Default to 100KHz
211 | when not specified. No range checking is done.
212 | @param[in] i2cSpeed [optional] changes the I2C speed to the rate specified in Herz */
213 | Wire.setClock(i2cSpeed);
214 | } // of method setI2CSpeed
215 | uint8_t INA_Class::begin(const uint16_t maxBusAmps, const uint32_t microOhmR,
216 | const uint8_t deviceNumber) {
217 | /*! @brief Initializes the contents of the class
218 | @details Searches for possible devices and sets the INA Configuration details, without
219 | which meaningful readings cannot be made. If it is called without the optional
220 | deviceNumber parameter then the settings are applied to all devices, otherwise
221 | just that specific device is targeted. If the optional third parameter, devNo, is
222 | specified that specific device gets the two specified values set for it. Can be
223 | called multiple times, but the 3 parameter version will only function after the 2
224 | parameter version finds all devices.\n
225 | @param[in] maxBusAmps Integer value holding the maximum expected bus amperage, this value is
226 | used to compute a device's internal power register
227 | @param[in] microOhmR Shunt resistance in micro-ohms, this value is used to compute a
228 | device's internal power register
229 | @param[in] deviceNumber Device number to explicitly set the maxBusAmps and microOhmR values,
230 | by default all devices found get set to the same initial values for these 2 params
231 | @return The integer number of INAxxxx devices found on the I2C bus
232 | */
233 | uint16_t originalRegister, tempRegister;
234 | if (_DeviceCount == 0) // Enumerate all devices on first call
235 | {
236 | uint16_t maxDevices = 32;
237 | /***************************************************************************************************
238 | ** The AVR devices need to use EEPROM to save memory, some other devices have emulation for EEPROM**
239 | ** functionality while some devices have no such function calls. This library caters for these **
240 | ** differences, with specialized calls for those platforms which have EEPROM calls and it makes **
241 | ** the assumption that if the platform has no EEPROM call then it has sufficient RAM available at **
242 | ** runtime to allocate sufficient space for 32 devices. **
243 | ***************************************************************************************************/
244 | #if defined(ESP32) || defined(ESP8266)
245 | EEPROM.begin(_EEPROM_size + _EEPROM_offset); // If ESP32 then allocate 512 Bytes
246 | maxDevices = (_EEPROM_size) / sizeof(inaEE); // and compute number of devices
247 | #elif defined(__STM32F1__) // Emulated EEPROM for STM32F1
248 | maxDevices = (EEPROM.maxcount() - _EEPROM_offset) / sizeof(inaEE); // Compute max possible
249 | #elif defined(CORE_TEENSY) // TEENSY doesn't have EEPROM.length
250 | maxDevices = (2048 - _EEPROM_offset) / sizeof(inaEE); // defined, so use 2Kb as value
251 | #elif defined(__AVR__)
252 | maxDevices = (EEPROM.length() - _EEPROM_offset) / sizeof(inaEE); // Compute max possible
253 | #else
254 | maxDevices = 32;
255 | #endif
256 | Wire.begin();
257 |
258 | if (maxDevices > 255) // Limit number of devices to an 8-bit number
259 | {
260 | maxDevices = 255;
261 | } // of if-then more than 255 devices possible
262 | for (uint8_t deviceAddress = 0x40; deviceAddress <= 0x4F;
263 | deviceAddress++) // Loop for each I2C addr
264 | {
265 | Wire.beginTransmission(deviceAddress);
266 | uint8_t good = Wire.endTransmission();
267 | if (good == 0 && _DeviceCount < maxDevices) // If no error and EEPROM has space
268 | {
269 | originalRegister = readWord(INA_CONFIGURATION_REGISTER, deviceAddress); // Save settings
270 | writeWord(INA_CONFIGURATION_REGISTER, INA_RESET_DEVICE, deviceAddress); // Force reset
271 | tempRegister = readWord(INA_CONFIGURATION_REGISTER, deviceAddress); // Read reset reg.
272 | if (tempRegister == INA_RESET_DEVICE) // If the register wasn't reset then not an INA
273 | {
274 | writeWord(INA_CONFIGURATION_REGISTER, originalRegister, deviceAddress); // restore value
275 | } else {
276 | if (tempRegister == 0x399F) {
277 | inaEE.type = INA219;
278 | } else {
279 | if (tempRegister == 0x4127) // INA226, INA230, INA231
280 | {
281 | tempRegister = readWord(INA_DIE_ID_REGISTER, deviceAddress); // Read the INA high-reg
282 | if (tempRegister == INA226_DIE_ID_VALUE) {
283 | inaEE.type = INA226;
284 | } else {
285 | if (tempRegister != 0) {
286 | inaEE.type = INA230;
287 | } else {
288 | inaEE.type = INA231;
289 | } // of if-then-else a INA230 or INA231
290 | } // of if-then-else an INA226
291 | } else {
292 | if (tempRegister == 0x6127) {
293 | inaEE.type = INA260;
294 | } else {
295 | if (tempRegister == 0x7127) {
296 | inaEE.type = INA3221_0;
297 | } else {
298 | if (tempRegister == 0x0) {
299 | inaEE.type = INA228;
300 | } else {
301 | inaEE.type = INA_UNKNOWN;
302 | } // of if-then-else it is an INA228
303 | } // of if-then-else it is an INA3221
304 | } // of if-then-else it is an INA260
305 | } // of if-then-else it is an INA226, INA230, INA231
306 | } // of if-then-else it is an INA209, INA219, INA220
307 | if (inaEE.type != INA_UNKNOWN) // Increment device if valid INA2xx
308 | {
309 | inaEE.address = deviceAddress;
310 | inaEE.maxBusAmps = maxBusAmps > 1022 ? 1022 : maxBusAmps; // Clamp to maximum of 1022A
311 | inaEE.microOhmR = microOhmR;
312 | ina = inaEE; // see inaDet constructor
313 | if (inaEE.type == INA3221_0) {
314 | ina.type = INA3221_0; // Set to INA3221 1st channel
315 | initDevice(_DeviceCount);
316 | _DeviceCount = ((_DeviceCount + 1) % maxDevices);
317 | ina.type = INA3221_1; // Set to INA3221 2nd channel
318 | initDevice(_DeviceCount);
319 | _DeviceCount = ((_DeviceCount + 1) % maxDevices);
320 | ina.type = INA3221_2; // Set to INA3221 3rd channel
321 | initDevice(_DeviceCount);
322 | _DeviceCount = ((_DeviceCount + 1) % maxDevices);
323 | } else {
324 | initDevice(_DeviceCount); // perform initialization on device
325 | _DeviceCount = ((_DeviceCount + 1) % maxDevices); // start again at 0 if overflow
326 | } // of if-then inaEE.type
327 | } // of if-then we can add device
328 | } // of if-then-else we have an INA-Type device
329 | } // of if-then we have a device
330 | } // for-next each possible I2C address
331 | } else {
332 | readInafromEEPROM(deviceNumber); // Load EEPROM to ina structure
333 | ina.maxBusAmps = maxBusAmps > 1022 ? 1022 : maxBusAmps; // Clamp to maximum of 1022A
334 | ina.microOhmR = microOhmR;
335 | initDevice(deviceNumber);
336 | } // of if-then-else first call
337 | _currentINA = UINT8_MAX; // Force read on next call
338 | return _DeviceCount;
339 | } // of method begin()
340 | void INA_Class::initDevice(const uint8_t deviceNumber) {
341 | /*! @brief Initializes the the given devices using the settings from the internal structure
342 | @details This includes (re)computing the device's calibration values.
343 | @param[in] deviceNumber Device number to explicitly initialize. */
344 | ina.operatingMode = INA_DEFAULT_OPERATING_MODE; // Default to continuous mode
345 | writeInatoEEPROM(deviceNumber); // Store the structure to EEPROM
346 | uint8_t programmableGain; // work variable for the programmable gain
347 | uint16_t calibration, maxShuntmV, tempRegister; // Calibration temporary variables
348 | switch (ina.type) {
349 | case INA219: // Set up INA219 or INA220
350 | // Compute calibration register
351 | calibration = (uint64_t)409600000 /
352 | ((uint64_t)ina.current_LSB * (uint64_t)ina.microOhmR / (uint64_t)100000);
353 | writeWord(INA_CALIBRATION_REGISTER, calibration, ina.address); // Write calibration
354 | /* Determine optimal programmable gain with maximum accuracy so no chance of an overflow */
355 | maxShuntmV = ina.maxBusAmps * ina.microOhmR / 1000; // Compute maximum shunt mV
356 | if (maxShuntmV <= 40)
357 | programmableGain = 0; // gain x1 for +- 40mV
358 | else if (maxShuntmV <= 80)
359 | programmableGain = 1; // gain x2 for +- 80mV
360 | else if (maxShuntmV <= 160)
361 | programmableGain = 2; // gain x4 for +- 160mV
362 | else
363 | programmableGain = 3; // dflt gain x8 for +- 320mV
364 | tempRegister = 0x399F & INA219_CONFIG_PG_MASK; // Zero programmable gain
365 | tempRegister |= programmableGain << INA219_PG_FIRST_BIT; // Overwrite the new values
366 | bitSet(tempRegister, INA219_BRNG_BIT); // set to 1 for 0-32 volts
367 | writeWord(INA_CONFIGURATION_REGISTER, tempRegister, ina.address); // Write to config register
368 | break;
369 | case INA226:
370 | case INA230:
371 | case INA231:
372 | // Compute calibration register
373 | calibration = (uint64_t)51200000 /
374 | ((uint64_t)ina.current_LSB * (uint64_t)ina.microOhmR / (uint64_t)100000);
375 | writeWord(INA_CALIBRATION_REGISTER, calibration, ina.address); // Write calibration
376 | break;
377 | case INA260:
378 | case INA3221_0:
379 | case INA3221_1:
380 | case INA3221_2: break;
381 | } // of switch type
382 | } // of method initDevice()
383 | void INA_Class::setBusConversion(const uint32_t convTime, const uint8_t deviceNumber) {
384 | /*! @brief specifies the conversion rate in microseconds, rounded to the nearest valid value
385 | @details INA devices can have a conversion rate of up to 68100 microseconds
386 | @param[in] convTime The conversion time in microseconds, invalid values are rounded to the
387 | nearest valid value
388 | @param[in] deviceNumber [optional] When specified, only that specified device number gets
389 | changed, otherwise all devices are set to the same averaging rate
390 | */
391 | uint16_t configRegister;
392 | int16_t convRate;
393 | for (uint8_t i = 0; i < _DeviceCount; i++) // Loop for each device found
394 | {
395 | if (deviceNumber == UINT8_MAX || deviceNumber % _DeviceCount == i) // If device needs setting
396 | {
397 | readInafromEEPROM(i); // Load EEPROM values to ina structure
398 | configRegister = readWord(INA_CONFIGURATION_REGISTER, ina.address); // Get current register
399 | switch (ina.type) {
400 | case INA219:
401 | if (convTime >= 68100)
402 | convRate = 15;
403 | else if (convTime >= 34050)
404 | convRate = 14;
405 | else if (convTime >= 17020)
406 | convRate = 13;
407 | else if (convTime >= 8510)
408 | convRate = 12;
409 | else if (convTime >= 4260)
410 | convRate = 11;
411 | else if (convTime >= 2130)
412 | convRate = 10;
413 | else if (convTime >= 1060)
414 | convRate = 9;
415 | else if (convTime >= 532)
416 | convRate = 8;
417 | else if (convTime >= 276)
418 | convRate = 2;
419 | else if (convTime >= 148)
420 | convRate = 1;
421 | else
422 | convRate = 0;
423 | configRegister &= ~INA219_CONFIG_BADC_MASK; // zero out the averages part
424 | configRegister |= convRate << 7; // shift in the BADC averages
425 | break;
426 | case INA226:
427 | case INA230:
428 | case INA231:
429 | case INA3221_0:
430 | case INA3221_1:
431 | case INA3221_2:
432 | case INA260:
433 | if (convTime >= 8244)
434 | convRate = 7;
435 | else if (convTime >= 4156)
436 | convRate = 6;
437 | else if (convTime >= 2116)
438 | convRate = 5;
439 | else if (convTime >= 1100)
440 | convRate = 4;
441 | else if (convTime >= 588)
442 | convRate = 3;
443 | else if (convTime >= 332)
444 | convRate = 2;
445 | else if (convTime >= 204)
446 | convRate = 1;
447 | else
448 | convRate = 0;
449 | if (ina.type == INA226 || ina.type == INA3221_0 || ina.type == INA3221_1 ||
450 | ina.type == INA3221_2) {
451 | configRegister &= ~INA226_CONFIG_BADC_MASK; // zero out the averages part
452 | configRegister |= convRate << 6; // shift in averages
453 | } else {
454 | configRegister &= ~INA260_CONFIG_BADC_MASK; // zero out the averages part
455 | configRegister |= convRate << 7; // shift in the averages
456 | } // of if-then an INA226 or INA260
457 | break;
458 | } // of switch type
459 | writeWord(INA_CONFIGURATION_REGISTER, configRegister,
460 | ina.address); // Save new value to device
461 | } // of if this device needs to be set
462 | } // for-next each device loop
463 | } // of method setBusConversion()
464 | void INA_Class::setShuntConversion(const uint32_t convTime, const uint8_t deviceNumber) {
465 | /*! @brief specifies the conversion rate in microseconds, rounded to the nearest valid value
466 | @details INA devices can have a conversion rate of up to 68100 microseconds
467 | @param[in] convTime Conversion time in microseconds. Out-of-Range values are set to the
468 | closest valid value
469 | @param[in] deviceNumber to return the device name for[optional] When specified, only that
470 | specified device number gets changed, otherwise all devices are set to the same
471 | averaging rate
472 | */
473 | int16_t configRegister, convRate;
474 | for (uint8_t i = 0; i < _DeviceCount; i++) { // Loop for each device found
475 | if (deviceNumber == UINT8_MAX ||
476 | deviceNumber % _DeviceCount == i) // If this device needs setting
477 | {
478 | readInafromEEPROM(i); // Load EEPROM to ina structure
479 | configRegister = readWord(INA_CONFIGURATION_REGISTER, ina.address); // Get register contents
480 | switch (ina.type) {
481 | case INA219:
482 | if (convTime >= 68100)
483 | convRate = 15;
484 | else if (convTime >= 34050)
485 | convRate = 14;
486 | else if (convTime >= 17020)
487 | convRate = 13;
488 | else if (convTime >= 8510)
489 | convRate = 12;
490 | else if (convTime >= 4260)
491 | convRate = 11;
492 | else if (convTime >= 2130)
493 | convRate = 10;
494 | else if (convTime >= 1060)
495 | convRate = 9;
496 | else if (convTime >= 532)
497 | convRate = 8;
498 | else if (convTime >= 276)
499 | convRate = 2;
500 | else if (convTime >= 148)
501 | convRate = 1;
502 | else
503 | convRate = 0;
504 | configRegister &= ~INA219_CONFIG_SADC_MASK; // zero out the averages part
505 | configRegister |= convRate << 3; // shift in the SADC averages
506 | break;
507 | case INA226:
508 | case INA230:
509 | case INA231:
510 | case INA3221_0:
511 | case INA3221_1:
512 | case INA3221_2:
513 | case INA260:
514 | if (convTime >= 8244)
515 | convRate = 7;
516 | else if (convTime >= 4156)
517 | convRate = 6;
518 | else if (convTime >= 2116)
519 | convRate = 5;
520 | else if (convTime >= 1100)
521 | convRate = 4;
522 | else if (convTime >= 588)
523 | convRate = 3;
524 | else if (convTime >= 332)
525 | convRate = 2;
526 | else if (convTime >= 204)
527 | convRate = 1;
528 | else
529 | convRate = 0;
530 | if (ina.type == INA226 || ina.type == INA3221_0 || ina.type == INA3221_1 ||
531 | ina.type == INA3221_2) {
532 | configRegister &= ~INA226_CONFIG_SADC_MASK; // zero out the averages part
533 | } else {
534 | configRegister &= ~INA260_CONFIG_SADC_MASK; // zero out the averages part
535 | } // of if-then-else either INA226/INA3221 or a INA260
536 | configRegister |= convRate << 3; // shift in the averages to register
537 | break;
538 | } // of switch type
539 | writeWord(INA_CONFIGURATION_REGISTER, configRegister,
540 | ina.address); // Save new value to device
541 | } // of if this device needs to be set
542 | } // for-next each device loop
543 | } // of method setShuntConversion()
544 | const char *INA_Class::getDeviceName(const uint8_t deviceNumber) {
545 | /*! @brief returns character buffer with the name of the device specified in the input param
546 | @details See function definition for list of possible return values
547 | @param[in] deviceNumber to return the device name of
548 | @return device name */
549 | if (deviceNumber > _DeviceCount) return ("");
550 | readInafromEEPROM(deviceNumber); // Load EEPROM to ina structure
551 | switch (ina.type) {
552 | case INA219: return ("INA219");
553 | case INA226: return ("INA226");
554 | case INA228: return ("INA228");
555 | case INA230: return ("INA230");
556 | case INA231: return ("INA231");
557 | case INA260: return ("INA260");
558 | case INA3221_0:
559 | case INA3221_1:
560 | case INA3221_2: return ("INA3221");
561 | default: return ("UNKNOWN");
562 | } // of switch type
563 | } // of method getDeviceName()
564 | uint8_t INA_Class::getDeviceAddress(const uint8_t deviceNumber) {
565 | /*! @brief returns a I2C address of the device specified in the input parameter
566 | @details Return the I2C address of the specified device, if number is out of range return 0
567 | @param[in] deviceNumber to return the device name of
568 | @return I2C address of the device. Returns 0 if value is out-of-range
569 | */
570 | if (deviceNumber > _DeviceCount) return 0;
571 | readInafromEEPROM(deviceNumber); // Load EEPROM to ina structure
572 | return (ina.address);
573 | } // of method getDeviceAddress()
574 | uint16_t INA_Class::getBusMilliVolts(const uint8_t deviceNumber) {
575 | /*! @brief returns the bus voltage in millivolts
576 | @details The converted millivolt value is returned and if the device is in triggered mode
577 | the next conversion is started
578 | @param[in] deviceNumber to return the device bus millivolts for
579 | @return uint16_t unsigned integer for the bus millivoltage */
580 | uint32_t busVoltage = getBusRaw(deviceNumber); // Get raw voltage from device
581 | if (ina.type == INA228) {
582 | // The accuracy is 20bits and 195.3125uv is the LSB
583 | busVoltage = (uint64_t)busVoltage * 1953125 / 10000000; // conversion to get mV
584 | } else {
585 | busVoltage = busVoltage * ina.busVoltage_LSB / 100; // conversion to get mV
586 | } // if-then-else an INA228
587 | return (busVoltage);
588 | } // of method getBusMilliVolts()
589 | uint32_t INA_Class::getBusRaw(const uint8_t deviceNumber) {
590 | /*! @brief returns the raw unconverted bus voltage reading from the device
591 | @details The raw measured value is returned and if the device is in triggered mode the next
592 | conversion is started
593 | @param[in] deviceNumber to return the raw device bus voltage reading
594 | @return Raw bus measurement */
595 | readInafromEEPROM(deviceNumber); // Load EEPROM from EEPROM
596 | uint32_t raw{0}; // define the return variable
597 | if (ina.type == INA228) {
598 | raw = read3Bytes(ina.busVoltageRegister, ina.address); // Get the raw value from register
599 | raw = raw >> 4;
600 | } else {
601 | raw = readWord(ina.busVoltageRegister, ina.address); // Get the raw value from register
602 | if (ina.type == INA3221_0 || ina.type == INA3221_1 || ina.type == INA3221_2 ||
603 | ina.type == INA219) {
604 | raw = raw >> 3; // INA219 & INA3221 - the 3 LSB unused, so shift right
605 | } // of if-then an INA219 or INA3221
606 | } // if-then a 3byte bus voltage buffer
607 | if (!bitRead(ina.operatingMode, 2) && bitRead(ina.operatingMode, 1)) // Triggered & bus active
608 | {
609 | int16_t configRegister =
610 | readWord(INA_CONFIGURATION_REGISTER, ina.address); // Get current value
611 | writeWord(INA_CONFIGURATION_REGISTER, configRegister, ina.address); // Write to trigger next
612 | } // of if-then triggered mode enabled
613 | return (raw);
614 | } // of method getBusRaw()
615 | int32_t INA_Class::getShuntMicroVolts(const uint8_t deviceNumber) {
616 | /*! @brief returns the shunt reading converted to microvolts
617 | @details The computed microvolts value is returned and if the device is in triggered mode
618 | the next conversion is started
619 | @param[in] deviceNumber to return the value for
620 | @return int32_t signed integer for the shunt microvolts
621 | */
622 | int32_t shuntVoltage = getShuntRaw(deviceNumber);
623 | if (ina.type == INA260) // INA260 has a built-in shunt
624 | {
625 | int32_t busMicroAmps = getBusMicroAmps(deviceNumber); // Get the amps on the bus from device
626 | shuntVoltage = busMicroAmps / 200; // 2mOhm resistor, convert with Ohm's law
627 | } else {
628 | if (ina.type == INA228) {
629 | shuntVoltage = shuntVoltage * ina.shuntVoltage_LSB / 10; // Convert to microvolts
630 | } else {
631 | shuntVoltage = shuntVoltage * ina.shuntVoltage_LSB / 10; // Convert to microvolts
632 | } // if-then a INA228 with 20 bit accuracy
633 | } // of if-then-else an INA260
634 | return (shuntVoltage);
635 | } // of method getShuntMicroVolts()
636 | int32_t INA_Class::getShuntRaw(const uint8_t deviceNumber) {
637 | /*! @brief Returns the raw shunt reading
638 | @details The raw reading is returned and if the device is in triggered mode the next
639 | conversion is started
640 | @param[in] deviceNumber to return the value for
641 | @return Raw shunt reading */
642 | int32_t raw;
643 | readInafromEEPROM(deviceNumber); // Load EEPROM to ina structure
644 | if (ina.type == INA260) // INA260 has a built-in shunt
645 | {
646 | int32_t busMicroAmps = getBusMicroAmps(deviceNumber); // Get the amps on the bus
647 | raw = busMicroAmps / 200 / 1000; // 2mOhm resistor, apply Ohm's law
648 | } else {
649 | if (ina.type == INA228) // INA228 has 24 bit accuracy
650 | {
651 | raw = read3Bytes(ina.shuntVoltageRegister, ina.address); // Get the raw value from register
652 | // The number is two's complement, so if negative we need to pad when shifting //
653 | if (raw & 0x800000) {
654 | raw = (raw >> 4) | 0xFFF00000; // first 12 bits are "1"
655 | } else {
656 | raw = raw >> 4;
657 | } // if-then negative
658 | } else {
659 | raw = readWord(ina.shuntVoltageRegister, ina.address); // Get the raw value from register
660 | } // if-then a 24 bit register
661 | if (ina.type == INA3221_0 || ina.type == INA3221_1 ||
662 | ina.type == INA3221_2) // Doesn't use 3 LSB
663 | {
664 | raw = raw >> 3; // shift over 3 bits, datatype is "int" so shifts in sign bits
665 | } // of if-then we need to shift INA3221 reading over
666 | } // of if-then-else an INA260 with inbuilt shunt
667 | if (!bitRead(ina.operatingMode, 2) && bitRead(ina.operatingMode, 0)) // Triggered & shunt active
668 | {
669 | int16_t configRegister = readWord(INA_CONFIGURATION_REGISTER, ina.address); // Get current reg
670 | writeWord(INA_CONFIGURATION_REGISTER, configRegister, ina.address); // Write to trigger next
671 | } // of if-then triggered mode enabled
672 | return (raw);
673 | } // of method getShuntMicroVolts()
674 | int32_t INA_Class::getBusMicroAmps(const uint8_t deviceNumber) {
675 | /*! @brief Returns the computed microamps measured on the bus for the specified device
676 | @details The computed reading is returned and if the device is in triggered mode the next
677 | conversion is started
678 | @param[in] deviceNumber to return the value for
679 | @return int32_t signed integer for computed microamps on the bus */
680 | readInafromEEPROM(deviceNumber); // Load EEPROM to ina structure
681 | int32_t microAmps = 0;
682 | if (ina.type == INA3221_0 || ina.type == INA3221_1 ||
683 | ina.type == INA3221_2) // Doesn't compute Amps
684 | {
685 | microAmps =
686 | (int64_t)getShuntMicroVolts(deviceNumber) * ((int64_t)1000000 / (int64_t)ina.microOhmR);
687 | } else {
688 | microAmps = (int64_t)readWord(ina.currentRegister, ina.address) * (int64_t)ina.current_LSB /
689 | (int64_t)1000;
690 | } // of if-then-else an INA3221
691 | return (microAmps);
692 | } // of method getBusMicroAmps()
693 | int64_t INA_Class::getBusMicroWatts(const uint8_t deviceNumber) {
694 | /*!
695 | @brief returns the computed microwatts measured on the bus for the specified device
696 | @details The computed reading is returned and if the device is in triggered mode the next
697 | conversion is started
698 | @param[in] deviceNumber to return the value for
699 | @return int64_t signed integer for computed microwatts on the bus
700 | */
701 | int64_t microWatts = 0;
702 | readInafromEEPROM(deviceNumber); // Load EEPROM to ina structure
703 | if (ina.type == INA3221_0 || ina.type == INA3221_1 ||
704 | ina.type == INA3221_2) // Doesn't compute Amps
705 | {
706 | microWatts =
707 | ((int64_t)getShuntMicroVolts(deviceNumber) * (int64_t)1000000 / (int64_t)ina.microOhmR) *
708 | (int64_t)getBusMilliVolts(deviceNumber) / (int64_t)1000;
709 | } else {
710 | microWatts =
711 | (int64_t)readWord(INA_POWER_REGISTER, ina.address) * (int64_t)ina.power_LSB / (int64_t)1000;
712 | if (getShuntRaw(deviceNumber) < 0) microWatts *= -1; // Invert if negative voltage
713 | } // of if-then-else an INA3221
714 | return (microWatts);
715 | } // of method getBusMicroWatts()
716 | void INA_Class::reset(const uint8_t deviceNumber) {
717 | /*! @brief performs a software reset for the specified device
718 | @details If no device is specified, then all devices are reset
719 | @param[in] deviceNumber to reset */
720 | for (uint8_t i = 0; i < _DeviceCount; i++) // Loop for each device found
721 | {
722 | if (deviceNumber == UINT8_MAX ||
723 | deviceNumber % _DeviceCount == i) // If this device needs setting
724 | {
725 | readInafromEEPROM(i); // Load EEPROM to ina structure
726 | writeWord(INA_CONFIGURATION_REGISTER, INA_RESET_DEVICE, ina.address); // Set MSB to reset
727 | initDevice(i); // re-initialize device
728 | } // of if this device needs to be set
729 | } // for-next each device loop
730 | } // of method reset
731 | void INA_Class::setMode(const uint8_t mode, const uint8_t deviceNumber) {
732 | /*!
733 | @brief sets the operating mode from the list given in enum type "ina_Mode" for a device
734 | @details If no device is specified, then all devices are set to the given mode
735 | @param[in] mode Mode (see "ina_Mode" enumerated type for list of valid values
736 | @param[in] deviceNumber to reset (Optional, when not set then all devices are mode changed)
737 | */
738 | int16_t configRegister;
739 | for (uint8_t i = 0; i < _DeviceCount; i++) // Loop for each device found
740 | {
741 | if (deviceNumber == UINT8_MAX ||
742 | deviceNumber % _DeviceCount == i) // If this device needs setting
743 | {
744 | readInafromEEPROM(i); // Load EEPROM to ina structure
745 | configRegister = readWord(INA_CONFIGURATION_REGISTER, ina.address); // Get current config
746 | configRegister &= ~INA_CONFIG_MODE_MASK; // zero out mode bits
747 | ina.operatingMode = B00000111 & mode; // Mask off unused bits
748 | writeInatoEEPROM(i); // Store back to EEPROM
749 | configRegister |= ina.operatingMode; // shift mode settings
750 | writeWord(INA_CONFIGURATION_REGISTER, configRegister, ina.address); // Save new value
751 | } // if-then this device needs to be set
752 | } // for-next each device loop
753 | } // of method setMode()
754 | bool INA_Class::conversionFinished(const uint8_t deviceNumber) {
755 | /*!
756 | @brief Returns whether or not the conversion has completed
757 | @details The device's conversion ready bit is read and returned. "true" denotes finished
758 | conversion.
759 | @param[in] deviceNumber to check
760 | */
761 | if (_DeviceCount == 0) return false; // Return finished if invalid device. Issue #65
762 | readInafromEEPROM(deviceNumber % _DeviceCount); // Load EEPROM to ina structure
763 | uint16_t cvBits = 0;
764 | switch (ina.type) {
765 | case INA219:
766 | cvBits = readWord(INA_BUS_VOLTAGE_REGISTER, ina.address) & 2; // Bit 2 set denotes ready
767 | readWord(INA_POWER_REGISTER, ina.address); // Resets the "ready" bit
768 | break;
769 | case INA226:
770 | case INA230:
771 | case INA231:
772 | case INA260: cvBits = readWord(INA_MASK_ENABLE_REGISTER, ina.address) & (uint16_t)8; break;
773 | case INA3221_0:
774 | case INA3221_1:
775 | case INA3221_2: cvBits = readWord(INA3221_MASK_REGISTER, ina.address) & (uint16_t)1; break;
776 | default: cvBits = 1;
777 | } // of switch type
778 | if (cvBits != 0)
779 | return (true);
780 | else
781 | return (false);
782 | } // of method "conversionFinished()"
783 | void INA_Class::waitForConversion(const uint8_t deviceNumber) {
784 | /*!
785 | @brief will not return until the conversion for the specified device is finished
786 | @details if no device number is specified it will wait until all devices have finished their
787 | current conversion. If the conversion has completed already then the flag (and
788 | interrupt pin, if activated) is also reset.
789 | @param[in] deviceNumber to reset (Optional, when not set all devices have their mode changed)
790 | */
791 | uint16_t cvBits = 0;
792 | for (uint8_t i = 0; i < _DeviceCount; i++) // Loop for each device found
793 | {
794 | if (deviceNumber == UINT8_MAX ||
795 | deviceNumber % _DeviceCount == i) // If this device needs setting
796 | {
797 | readInafromEEPROM(i); // Load EEPROM to ina structure
798 | cvBits = 0;
799 | while (cvBits == 0) // Loop until the value is set
800 | {
801 | switch (ina.type) {
802 | case INA219:
803 | cvBits =
804 | readWord(INA_BUS_VOLTAGE_REGISTER, ina.address) & 2; // Bit 2 set denotes ready
805 | readWord(INA_POWER_REGISTER, ina.address); // Resets the "ready" bit
806 | break;
807 | case INA226:
808 | case INA230:
809 | case INA231:
810 | case INA260:
811 | cvBits = readWord(INA_MASK_ENABLE_REGISTER, ina.address) & (uint16_t)8;
812 | break;
813 | case INA3221_0:
814 | case INA3221_1:
815 | case INA3221_2:
816 | cvBits = readWord(INA3221_MASK_REGISTER, ina.address) & (uint16_t)1;
817 | break;
818 | default: cvBits = 1;
819 | } // of switch type
820 | } // of while the conversion hasn't finished
821 | } // of if this device needs to be set
822 | } // for-next each device loop
823 | } // of method waitForConversion()
824 | bool INA_Class::alertOnConversion(const bool alertState, const uint8_t deviceNumber) {
825 | /*!
826 | @brief configures the INA devices which support this functionality to pull the ALERT pin low
827 | when a conversion is complete
828 | @details This call is ignored and returns false when called for an invalid device as the INA219
829 | doesn't have this pin it won't work for that device.
830 | @param[in] alertState Boolean true or false to denote the requested setting
831 | @param[in] deviceNumber to reset (Optional, when not set all devices have their mode changed)
832 | @return Returns "true" on success, otherwise false
833 | */
834 | uint16_t alertRegister;
835 | bool returnCode = false; // Assume the worst
836 | for (uint8_t i = 0; i < _DeviceCount; i++) // Loop for each device found
837 | {
838 | if (deviceNumber == UINT8_MAX || deviceNumber == i) // If this device needs setting
839 | {
840 | readInafromEEPROM(i); // Load EEPROM to ina structure
841 | switch (ina.type) {
842 | case INA226:
843 | case INA230:
844 | case INA231:
845 | case INA260:
846 | alertRegister = readWord(INA_MASK_ENABLE_REGISTER, ina.address); // Get register
847 | alertRegister &= INA_ALERT_MASK; // Mask off all bits
848 | if (alertState) bitSet(alertRegister, INA_ALERT_CONVERSION_RDY_BIT); // Turn on the bit
849 | writeWord(INA_MASK_ENABLE_REGISTER, alertRegister, ina.address); // Write back
850 | returnCode = true;
851 | break;
852 | default: returnCode = false;
853 | } // of switch type
854 | } // of if this device needs to be set
855 | } // for-next each device loop
856 | return (returnCode);
857 | } // of method AlertOnConversion
858 | bool INA_Class::alertOnShuntOverVoltage(const bool alertState, const int32_t milliVolts,
859 | const uint8_t deviceNumber) {
860 | /*!
861 | @brief configures the INA devices which support this functionality to pull the ALERT pin low
862 | when the shunt current exceeds the value given in the parameter in millivolts
863 | @details This call is ignored and returns false when called for an invalid device
864 | @param[in] alertState Boolean true or false to denote the requested setting
865 | @param[in] milliVolts alert level at which to trigger the alarm
866 | @param[in] deviceNumber to reset (Optional, when not set all devices have their mode changed)
867 | @return Returns "true" on success, otherwise false
868 | */
869 | uint16_t alertRegister;
870 | bool returnCode = false; // Assume the worst
871 | for (uint8_t i = 0; i < _DeviceCount; i++) // Loop for each device found
872 | {
873 | if (deviceNumber == UINT8_MAX || deviceNumber == i) // If this device needs to be processed
874 | {
875 | readInafromEEPROM(i); // Load EEPROM to ina structure
876 | switch (ina.type) {
877 | case INA226:
878 | case INA230:
879 | case INA231:
880 | alertRegister = readWord(INA_MASK_ENABLE_REGISTER, ina.address); // Get current register
881 | alertRegister &= INA_ALERT_MASK; // Mask off all bits
882 | if (alertState) // If true, then also set threshold
883 | {
884 | bitSet(alertRegister, INA_ALERT_SHUNT_OVER_VOLT_BIT); // Turn on the bit
885 | uint16_t threshold = milliVolts * 1000 / ina.shuntVoltage_LSB; // Compute using LSB
886 | writeWord(INA_ALERT_LIMIT_REGISTER, threshold, ina.address); // Write register
887 | } // of if we are setting a value
888 | writeWord(INA_MASK_ENABLE_REGISTER, alertRegister, ina.address); // Write register back
889 | returnCode = true;
890 | break;
891 | default: returnCode = false;
892 | } // of switch type
893 | } // of if this device needs to be set
894 | } // for-next each device loop
895 | return (returnCode);
896 | } // of method AlertOnShuntOverVoltage
897 | bool INA_Class::alertOnShuntUnderVoltage(const bool alertState, const int32_t milliVolts,
898 | const uint8_t deviceNumber) {
899 | /*!
900 | @brief configures the INA devices which support this functionality to pull the ALERT pin low
901 | when the shunt current goes below the value given in the parameter in millivolts
902 | @details This call is ignored and returns false when called for an invalid device
903 | @param[in] alertState Boolean true or false to denote the requested setting
904 | @param[in] milliVolts alert level at which to trigger the alarm
905 | @param[in] deviceNumber to reset (Optional, when not set all devices have their alert changed)
906 | @return Returns "true" on success, otherwise false */
907 | uint16_t alertRegister;
908 | bool returnCode = true;
909 | for (uint8_t i = 0; i < _DeviceCount; i++) // Loop for each device found
910 | {
911 | if (deviceNumber == UINT8_MAX ||
912 | deviceNumber % _DeviceCount == i) // If this device needs setting
913 | {
914 | readInafromEEPROM(i); // Load EEPROM to ina structure
915 | switch (ina.type) {
916 | case INA226:
917 | case INA230:
918 | case INA231:
919 | alertRegister = readWord(INA_MASK_ENABLE_REGISTER, ina.address); // Get current register
920 | alertRegister &= INA_ALERT_MASK; // Mask off all bits
921 | if (alertState) // Also set threshold
922 | {
923 | bitSet(alertRegister, INA_ALERT_SHUNT_UNDER_VOLT_BIT); // Turn on the bit
924 | uint16_t threshold = milliVolts * 1000 / ina.shuntVoltage_LSB; // Compute using LSB
925 | writeWord(INA_ALERT_LIMIT_REGISTER, threshold, ina.address); // Write register
926 | } // of if we are setting a value
927 | writeWord(INA_MASK_ENABLE_REGISTER, alertRegister, ina.address); // Write register back
928 | break;
929 | default: returnCode = false;
930 | } // of switch type
931 | } // of if this device needs to be set
932 | } // for-next each device loop
933 | return (returnCode);
934 | } // of method AlertOnShuntUnderVoltage
935 | bool INA_Class::alertOnBusOverVoltage(const bool alertState, const int32_t milliVolts,
936 | const uint8_t deviceNumber) {
937 | /*!
938 | @brief configures the INA devices which support this functionality to pull the ALERT pin low
939 | when the bus voltage goes above the value given in the parameter in millivolts
940 | @details This call is ignored and returns false when called for an invalid device
941 | @param[in] alertState Boolean true or false to denote the requested setting
942 | @param[in] milliVolts alert level at which to trigger the alarm
943 | @param[in] deviceNumber to reset (Optional, when not set all devices have their alert changed)
944 | @return Returns "true" on success, otherwise false
945 | */
946 | uint16_t alertRegister;
947 | bool returnCode = true;
948 | for (uint8_t i = 0; i < _DeviceCount; i++) // Loop for each device found
949 | {
950 | if (deviceNumber == UINT8_MAX ||
951 | deviceNumber % _DeviceCount == i) // If this device needs setting
952 | {
953 | readInafromEEPROM(i); // Load EEPROM to ina structure
954 | switch (ina.type) {
955 | case INA226: // Devices that have an alert pin
956 | case INA230:
957 | case INA231:
958 | case INA260:
959 | alertRegister =
960 | readWord(INA_MASK_ENABLE_REGISTER, ina.address); // Get the current register
961 | alertRegister &= INA_ALERT_MASK; // Mask off all bits
962 | if (alertState) // Also set threshold
963 | {
964 | bitSet(alertRegister, INA_ALERT_BUS_OVER_VOLT_BIT); // Turn on the bit
965 | uint16_t threshold = milliVolts * 100 / ina.busVoltage_LSB; // Compute using LSB val
966 | writeWord(INA_ALERT_LIMIT_REGISTER, threshold, ina.address); // Write register
967 | } // of if we are setting a value
968 | writeWord(INA_MASK_ENABLE_REGISTER, alertRegister, ina.address); // Write register back
969 | break;
970 | default: returnCode = false;
971 | } // of switch type
972 | } // of if this device needs to be set
973 | } // for-next each device loop
974 | return (returnCode);
975 | } // of method AlertOnBusOverVoltageConversion
976 | bool INA_Class::alertOnBusUnderVoltage(const bool alertState, const int32_t milliVolts,
977 | const uint8_t deviceNumber) {
978 | /*!
979 | @brief configures the INA devices which support this functionality to pull the ALERT pin
980 | low when the bus current goes above the value given in the parameter in millivolts.
981 | @details This call is ignored and returns false when called for an invalid device
982 | @param[in] alertState Boolean true or false to denote the requested setting
983 | @param[in] milliVolts alert level at which to trigger the alarm
984 | @param[in] deviceNumber to reset (Optional, when not set then all devices have their alert
985 | changed)
986 | @return Returns "true" on success, otherwise false */
987 | uint16_t alertRegister;
988 | bool returnCode = true; // Assume success
989 | for (uint8_t i = 0; i < _DeviceCount; i++) // Loop for each device found
990 | {
991 | if (deviceNumber == UINT8_MAX ||
992 | deviceNumber % _DeviceCount == i) // If this device needs setting
993 | {
994 | readInafromEEPROM(i); // Load EEPROM to ina structure
995 | switch (ina.type) {
996 | case INA226: // Devices that have an alert pin
997 | case INA230:
998 | case INA231:
999 | case INA260:
1000 | alertRegister = readWord(INA_MASK_ENABLE_REGISTER, ina.address); // Get current register
1001 | alertRegister &= INA_ALERT_MASK; // Mask off all bits
1002 | if (alertState) // Also set threshold
1003 | {
1004 | bitSet(alertRegister, INA_ALERT_BUS_UNDER_VOLT_BIT); // Turn on the bit
1005 | uint16_t threshold = milliVolts * 100 / ina.busVoltage_LSB; // Compute using LSB val
1006 | writeWord(INA_ALERT_LIMIT_REGISTER, threshold, ina.address); // Write register
1007 | } // of if we are setting a value
1008 | writeWord(INA_MASK_ENABLE_REGISTER, alertRegister, ina.address); // Write register back
1009 | break;
1010 | default: returnCode = false;
1011 | } // of switch type
1012 | } // of if this device needs to be set
1013 | } // for-next each device loop
1014 | return (returnCode);
1015 | } // of method AlertOnBusUnderVoltage
1016 | bool INA_Class::alertOnPowerOverLimit(const bool alertState, const int32_t milliAmps,
1017 | const uint8_t deviceNumber) {
1018 | /*!
1019 | @brief configures the INA devices which support this functionality to pull the ALERT pin
1020 | low when the power exceeds the value set in the parameter in milliamps
1021 | @details This call is ignored and returns false when called for an invalid device
1022 | @param[in] alertState Boolean true or false to denote the requested setting
1023 | @param[in] milliAmps alert level at which to trigger the alarm
1024 | @param[in] deviceNumber to reset (Optional, when not set all devices have their alert changed)
1025 | @return Returns "true" on success, otherwise false
1026 | */
1027 | uint16_t alertRegister;
1028 | bool returnCode = true; // assume success
1029 | for (uint8_t i = 0; i < _DeviceCount; i++) // Loop for each device found
1030 | {
1031 | if (deviceNumber == UINT8_MAX ||
1032 | deviceNumber % _DeviceCount == i) // If this device needs setting
1033 | {
1034 | readInafromEEPROM(i); // Load EEPROM to ina structure
1035 | switch (ina.type) {
1036 | case INA226:
1037 | case INA230:
1038 | case INA231:
1039 | case INA260: // Devices with alert pin
1040 | alertRegister = readWord(INA_MASK_ENABLE_REGISTER, ina.address); // Get current register
1041 | alertRegister &= INA_ALERT_MASK; // Mask off all bits
1042 | if (alertState) // Also set threshold
1043 | {
1044 | bitSet(alertRegister, INA_ALERT_POWER_OVER_WATT_BIT); // Turn on the bit
1045 | uint16_t threshold = milliAmps * 1000000 / ina.power_LSB; // Compute using LSB val
1046 | writeWord(INA_ALERT_LIMIT_REGISTER, threshold, ina.address); // Write register
1047 | } // of if we are setting a value
1048 | writeWord(INA_MASK_ENABLE_REGISTER, alertRegister, ina.address); // Write register back
1049 | break;
1050 | default: returnCode = false;
1051 | } // of switch type
1052 | } // of if this device needs to be set
1053 | } // for-next each device loop
1054 | return (returnCode);
1055 | } // of method AlertOnPowerOverLimit
1056 | void INA_Class::setAveraging(const uint16_t averages, const uint8_t deviceNumber) {
1057 | /*!
1058 | @brief sets the hardware averaging for one or all devices
1059 | @details Out-of-Range averaging is brought down to the highest allowed value
1060 | @param[in] averages Number of averages to set (0-128)
1061 | @param[in] deviceNumber to reset (Optional, when not set all devices have their averaging changed)
1062 | */
1063 | uint16_t averageIndex;
1064 | int16_t configRegister;
1065 | for (uint8_t i = 0; i < _DeviceCount; i++) // Loop for each device found
1066 | {
1067 | if (deviceNumber == UINT8_MAX ||
1068 | deviceNumber % _DeviceCount == i) // If this device needs setting
1069 | {
1070 | readInafromEEPROM(i); // Load EEPROM to struct
1071 | configRegister = readWord(INA_CONFIGURATION_REGISTER, ina.address); // Get current register
1072 | switch (ina.type) {
1073 | case INA219:
1074 | if (averages >= 128)
1075 | averageIndex = 15;
1076 | else if (averages >= 64)
1077 | averageIndex = 14;
1078 | else if (averages >= 32)
1079 | averageIndex = 13;
1080 | else if (averages >= 16)
1081 | averageIndex = 12;
1082 | else if (averages >= 8)
1083 | averageIndex = 11;
1084 | else if (averages >= 4)
1085 | averageIndex = 10;
1086 | else if (averages >= 2)
1087 | averageIndex = 9;
1088 | else
1089 | averageIndex = 8;
1090 | configRegister &= ~INA219_CONFIG_AVG_MASK; // zero out the averages part
1091 | configRegister |= averageIndex << 3; // shift in the SADC averages
1092 | configRegister |= averageIndex << 7; // shift in the BADC averages
1093 | break;
1094 | case INA226:
1095 | case INA230:
1096 | case INA231:
1097 | case INA3221_0:
1098 | case INA3221_1:
1099 | case INA3221_2:
1100 | case INA260:
1101 | if (averages >= 1024)
1102 | averageIndex = 7;
1103 | else if (averages >= 512)
1104 | averageIndex = 6;
1105 | else if (averages >= 256)
1106 | averageIndex = 5;
1107 | else if (averages >= 128)
1108 | averageIndex = 4;
1109 | else if (averages >= 64)
1110 | averageIndex = 3;
1111 | else if (averages >= 16)
1112 | averageIndex = 2;
1113 | else if (averages >= 4)
1114 | averageIndex = 1;
1115 | else
1116 | averageIndex = 0;
1117 | configRegister &= ~INA226_CONFIG_AVG_MASK; // zero out the averages part
1118 | configRegister |= averageIndex << 9; // shift in the averages to reg
1119 | break;
1120 | } // of switch type
1121 | writeWord(INA_CONFIGURATION_REGISTER, configRegister, ina.address); // Save new value
1122 | } // of if this device needs to be set
1123 | } // for-next each device loop
1124 | } // of method setAveraging()
1125 |
--------------------------------------------------------------------------------
/src/INA.h:
--------------------------------------------------------------------------------
1 | // clang-format off
2 | /*!
3 | @file INA.h
4 |
5 | @brief INA Class library header file
6 |
7 | @mainpage Arduino library to support the INAxxx family of current sensors
8 |
9 | @section Library_intro_section Description
10 |
11 | Class definition header for the INA class. This library gives a common interface to various INA
12 | power monitor devices, see https://github.com/Zanduino/INA/wiki or the code below for a full
13 | list of currently supported devices. The INA devices have a 3-5V power supply and, depending
14 | upon the model, can measure voltages up to 26V or 36V. They are devices with High-Side / Low-Side
15 | Measurement, Bi-Directional Current and Power Monitor with I2C Compatible Interface. The device
16 | documentation can be found at the following location:\n
17 | http://www.ti.com/amplifier-circuit/current-sense/power-current-monitors/products.html\n\n
18 | Detailed library descriptions are on the INA GitHub Wiki pages at
19 | https://github.com/Zanduino/INA/wiki\n\n The INA devices, apart from the INA250 and INA260,
20 | require an external shunt of known resistance to be placed across the high-side or low-side
21 | supply or ground line and they use the small current generated by the shunt to compute the
22 | amperage passing across the circuit. This value, coupled with the voltage measurement, allows
23 | the amperage and wattage to be computed by the INA device and these values can be read from the
24 | devices using the industry standard I2C protocol.
25 |
26 | @section Style Programming
27 | @subsection Coding Coding and comments
28 | OK, I admit that I'm "old school" when it comes to programming style. I am used to using a full
29 | monitor and keyboard for development and testing, plus I like to heavily document code as it
30 | helps me remember what I did when I revisit code after several months (or years). I make use of
31 | the full width (which I've limited to 112 characters here) and put my comments at the end of
32 | lines. I prefer to use descriptive variable names, which means that they tend to be long.
33 |
34 | @subsection StyleGuide Style Guide
35 | Different languages have different coding styles. For the Arduino c++ language I've opted to go
36 | with one of the big players in the industry and have adopted the coding and style rules that
37 | Google recommends and which are documented at [Google c++ Style
38 | Guide](https://google.github.io/styleguide/cppguide.html). I have chosen to put braces on their
39 | own lines and include braces for even 1-liners. End braces are always commented so that
40 | convoluted code is more easily untangled.
41 |
42 | @subsection Documentation
43 | The comments have been formatted for use with [Doxygen](doxygen.nl), one of the leading
44 | documentation systems which is not only free but covers just about anything worth documenting.
45 | The Doxygen system parses the source files of a package and creates documentation. The default
46 | output is a set of HTML pages although it can produce single documents.
47 |
48 | @subsection comments Comment Format
49 | This package uses [Markdown](https://en.wikipedia.org/wiki/Markdown) syntax for formatting
50 | comments, which makes for easy reading directly in the source code and well-formatted
51 | pretty-print in postprocessing.
52 |
53 | @subsection ide IDE
54 | I've opted for using Microsoft Visual Studio (version 16.2.5) for development, the community
55 | version can be downloaded for free at [Microsoft
56 | Downloads](https://visualstudio.microsoft.com/downloads/) and I use the fantastic [Visual
57 | Micro](https://www.visualmicro.com/) package which give the Arduino IDE inside Visual Studio. The
58 | base version is free or becomes only slightly annoying nagware after 90 days, but the software is
59 | inexpensive and the price is well worth it for supporting continued development.
60 |
61 | @section doxygen doxygen configuration
62 |
63 | This library is built with the standard "Doxyfile", which is located at
64 | https://github.com/Zanduino/Common/blob/main/Doxygen. As described on that page, there are only 5
65 | environment variables used, and these are set in the project's actions file, located at
66 | https://github.com/Zanduino/INA/blob/master/.github/workflows/ci-doxygen.yml
67 | Edit this file and set the 5 variables - PRETTYNAME, PROJECT_NAME, PROJECT_NUMBER, PROJECT_BRIEF
68 | and PROJECT_LOGO so that these values are used in the doxygen documentation.
69 | The local copy of the doxyfile should be in the project's root directory in order to do local
70 | doxygen testing, but the file is ignored on upload to GitHub.
71 |
72 | @section clang-format
73 | Part of the GitHub actions for CI is running every source file through "clang-format" to ensure
74 | that coding formatting is done the same for all files. The configuration file ".clang-format" is
75 | located at https://github.com/Zanduino/Common/tree/main/clang-format and this is used for CI tests
76 | when pushing to GitHub. The local file, if present in the root directory, is ignored when
77 | committing and uploading.
78 |
79 | @section license GNU General Public License v3.0
80 |
81 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU
82 | General Public License as published by the Free Software Foundation, either version 3 of the
83 | License, or (at your option) any later version. This program is distributed in the hope that it
84 | will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
85 | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should
86 | have received a copy of the GNU General Public License along with this program. If not, see
87 | .
88 |
89 | @section author Author
90 |
91 | Written by Arnd at https://www.github.com/SV-Zanshin
92 |
93 | @section versions Changelog
94 |
95 | | Version | Date | Developer | Comments
96 | | ------- | ---------- | ----------- | --------
97 | | 1.1.2 | 2022-01-16 | Oleg-Sob | Issue #87. getBusMicroWatts() only returns positive values
98 | | 1.1.1 | 2021-03-12 | x3mEr | Issue #79. Documentation Update
99 | | 1.0.14 | 2020-12-01 | SV-Zanshin | Issue #72. Allow INA structures to be in memory rather than EEPROM
100 | | 1.0.14 | 2020-11-30 | johntaves | Issue #64. begin() does not set values on subsequent calls
101 | | 1.0.14 | 2020-11-29 | SV-Zanshin | Issue #71. Optimize library, cleanup source code
102 | | 1.0.14 | 2020-10-25 | gallium70 | Issue #66. Error in INA226/230/231 value for "power_LSB"
103 | | 1.0.13 | 2020-07-13 | fg89o | Issue #62. Added "_EEPROM_size" for ESP32 and ESP8266
104 | | 1.0.13 | 2020-07-13 | fg89o | Issue #62. Incorrect "_EEPROM_offset" computation
105 | | 1.0.12 | 2020-07-13 | SV-Zanshin | Issue #41. Added "_EEPROM_offset" variable
106 | | 1.0.12 | 2020-07-03 | sages | Issue #60. Possible Overflow getBus(MicroAmps,MicroWatts)
107 | | 1.0.11 | 2020-06-30 | SV-Zanshin | Issue #58, changed formatting to use clang-format
108 | | 1.0.11 | 2020-06-29 | SV-Zanshin | Issue #57. "Alert..." functions should be "alert..."
109 | | 1.0.11 | 2020-05-05 | oliverb68 | Issue #56. Limit of +/- 2kW on getBusMicroWatts
110 | | 1.0.10 | 2020-05-03 | we9v | Issue #54. Limit of 127A maximum current changed to 1022A
111 | | 1.0.10 | 2020-05-01 | nathancheek | Issue #53. Extraneous conversion on getShuntMicrovolts
112 | | 1.0.10 | 2020-03-24 | nathancheek | Issue #52. Search for all 16 possible devices
113 | | 1.0.10 | 2020-03-22 | alphaarea | Issue #50. Wiki fix for "begin()" - MaxBusAmps overflow
114 | | 1.0.9 | 2019-12-15 | Steamerzone | Issue #49. Added ifdef for STM32F1 device support
115 | | 1.0.9 | 2019-10-27 | SV-Zanshin | Cleaned up Doxygen formatting
116 | | 1.0.9 | 2019-10-17 | nathancheek | Issue #47. Added EEPROM support for teensy
117 | | 1.0.8 | 2019-09-03 | miky2k | Issue #43. Added new method "conversionFinished()"
118 | | 1.0.8 | 2019-05-23 | avaldebe | Issue #42. Restrict I2C scan to possible devices
119 | | 1.0.8 | 2019-03-24 | mattlogic | Issue #40. Corrected INA226_CONFIG_SADC_MASK value
120 | | 1.0.8 | 2019-03-17 | SV-Zanshin | Issue #19. Corrected 4 value ranges in bus/shunt conversion
121 | | 1.0.8 | 2019-02-16 | SV-Zanshin | Corrected and tested ESP32 implementation
122 | | 1.0.8 | 2019-02-10 | SV-Zanshin | Issue #39. Allow non-AVR processors without EEPROM to run
123 | | 1.0.8 | 2019-02-09 | SV-Zanshin | Cleaned up doxygen comment formatting in .h and .cpp files
124 | | 1.0.8 | 2019-02-09 | SV-Zanshin | Issue #38. Add getDeviceAddress() function
125 | | 1.0.7 | 2019-01-20 | SV-Zanshin | Issue #36&37. Changed for Travis-CI and automated doxygen
126 | | 1.0.7 | 2018-12-27 | SV-Zanshin | Issue #33. Change program documentation to doxygen format
127 | | 1.0.6 | 2018-12-13 | delboy711 | Issue #32. Incorrect ESP2866 rather than ESP8266
128 | | 1.0.6 | 2018-10-19 | SV-Zanshin | Issue #31. Use full 0-32V Range on INA219 all the time
129 | | 1.0.6 | 2018-10-19 | SV-Zanshin | Issue #30. Added TEENSY support & support large EEPROM
130 | | 1.0.6 | 2018-10-14 | SV-Zanshin | Added correct wire handling for ESP8266 and ESP32
131 | | 1.0.6 | 2018-10-07 | SV-Zanshin | Optimized getBusRaw() and getShuntRaw() functions
132 | | 1.0.5 | 2018-10-04 | SV-Zanshin | Added getBusRaw() and getShuntRaw() functions
133 | | 1.0.5 | 2018-09-29 | SV-Zanshin | Reformatted comments to different c++ coding style
134 | | 1.0.4 | 2018-09-22 | SV-Zanshin | Issue #27. EEPROM Calls don't work with ESP32
135 | | 1.0.4 | 2018-09-19 | SV-Zanshin | Issue #28. Ovef error when >31Amps specified in begin()
136 | | 1.0.3 | 2018-09-04 | delboy711 | Issue #26. Incorrect INA3221 negative current readings
137 | | 1.0.3 | 2018-08-18 | SV-Zanshin | Issue #22. Reduce EEPROM Footprint
138 | | 1.0.3 | 2018-08-18 | SV-Zanshin | Issue #21. Rename I2C Constants to avoid redefine STM32F1
139 | | 1.0.2 | 2018-07-22 | SV-Zanshin | Issue #11. Reduce EEPROM footprint. Removed "deviceName", 8B. Changed datatype in structure to bit-level length defs, saving additional 3 bytes
140 | | 1.0.2 | 2018-07-21 | avaldeve | Issue #12. Incorrect const datatype for I2C Speeds
141 | | 1.0.2 | 2018-07-12 | coelner | Issue #9. Esplora doesn't accept "Wire.begin()"
142 | | 1.0.2 | 2018-07-08 | SV-Zanshin | Issue #2. Finished testing INA3221 across all functions
143 | | 1.0.2 | 2018-07-07 | dnlwgnd | Issue #4. Guard code used incorrect label
144 | | 1.0.2 | 2018-06-30 | SV-Zanshin | Issue #3. Adding faster I2C bus support
145 | | 1.0.2 | 2018-06-29 | SV-Zanshin | Issue #2. Adding INA3221 support to library
146 | | 1.0.2 | 2018-06-29 | SV-Zanshin | Issue #2. Adding INA3221 support to library
147 | | 1.0.1 | 2018-06-24 | SV-Zanshin | Removed extraneous elements from ina struct, optimized code
148 | | 1.0.1b | 2018-06-23 | SV-Zanshin | Fixed error on multiple devices with ina structure contents
149 | | 1.0.1a | 2018-06-23 | SV-Zanshin | Removed debug mode and code
150 | | 1.0.0 | 2018-06-22 | SV-Zanshin | Initial release
151 | | 1.0.0b | 2018-06-17 | SV-Zanshin | Continued coding, tested on INA219 and INA226
152 | | 1.0.0a | 2018-06-10 | SV-Zanshin | Initial coding began
153 | */
154 | #ifndef ARDUINO
155 | /*! Define macro if not defined yet */
156 | #define ARDUINO 0
157 | #endif
158 | #if ARDUINO >= 100 /* Use old library if IDE is prior to V1.0 */
159 | #include "Arduino.h"
160 | #else
161 | #include "WProgram.h"
162 | #endif
163 |
164 | #ifndef INA__Class_h
165 | /*! Guard code definition to prevent multiple includes */
166 | #define INA__Class_h
167 | /*! typedef contains a packed bit-level defs of information stored per device */
168 | typedef struct {
169 | uint8_t type : 4; ///< 0-15 see enumerated "ina_Type" for details
170 | uint8_t operatingMode : 4; ///< 0-15 Default to continuous mode
171 | uint32_t address : 7; ///< 0-127 I2C Address of device
172 | uint32_t maxBusAmps : 10; ///< 0-1023 Store initialization value
173 | uint32_t microOhmR : 20; ///< 0-1,048,575 Store initialization value
174 | } inaEEPROM; // of structure
175 | /*! typedef contains a packed bit-level definition of information stored on a device */
176 | typedef struct inaDet : inaEEPROM {
177 | uint8_t busVoltageRegister : 3; ///< 0- 7, Bus Voltage Register
178 | uint8_t shuntVoltageRegister : 3; ///< 0- 7, Shunt Voltage Register
179 | uint8_t currentRegister : 3; ///< 0- 7, Current Register
180 | uint16_t shuntVoltage_LSB; ///< Device dependent LSB factor
181 | uint16_t busVoltage_LSB; ///< Device dependent LSB factor
182 | uint32_t current_LSB; ///< Amperage LSB
183 | uint32_t power_LSB; ///< Wattage LSB
184 | inaDet(); ///< struct constructor
185 | inaDet(inaEEPROM& inaEE); ///< for ina = inaEE; assignment
186 | } inaDet; // of structure
187 | /*! Enumerated list detailing the names of all supported INA devices. The INA3221 is stored
188 | as 3 distinct devices each with their own enumerated type. */
189 | enum ina_Type {
190 | INA219,
191 | INA226,
192 | INA228,
193 | INA230,
194 | INA231,
195 | INA260,
196 | INA3221_0,
197 | INA3221_1,
198 | INA3221_2,
199 | INA_UNKNOWN
200 | };
201 | /*! Enumerated list detailing the operating modes of a given device */
202 | enum ina_Mode {
203 | INA_MODE_SHUTDOWN, ///< Device powered down
204 | INA_MODE_TRIGGERED_SHUNT, ///< Triggered shunt, no bus
205 | INA_MODE_TRIGGERED_BUS, ///< Triggered bus, no shunt
206 | INA_MODE_TRIGGERED_BOTH, ///< Triggered bus and shunt
207 | INA_MODE_POWER_DOWN, ///< shutdown or power-down
208 | INA_MODE_CONTINUOUS_SHUNT, ///< Continuous shunt, no bus
209 | INA_MODE_CONTINUOUS_BUS, ///< Continuous bus, no shunt
210 | INA_MODE_CONTINUOUS_BOTH ///< Both continuous, default value
211 | }; // of enumerated type
212 | /************************************************************************************************
213 | ** Declare constants used in the class **
214 | ************************************************************************************************/
215 | #ifndef INA_I2C_MODES // I2C related constants
216 | #define INA_I2C_MODES ///< Guard code to prevent multiple defs
217 | const uint32_t INA_I2C_STANDARD_MODE{100000}; ///< Default normal I2C 100KHz speed
218 | const uint32_t INA_I2C_FAST_MODE{400000}; ///< Fast mode
219 | const uint32_t INA_I2C_FAST_MODE_PLUS{1000000}; ///< Really fast mode
220 | const uint32_t INA_I2C_HIGH_SPEED_MODE{3400000}; ///< Turbo mode
221 | #endif
222 | const uint8_t INA_CONFIGURATION_REGISTER{0}; ///< Configuration Register address
223 | const uint8_t INA_BUS_VOLTAGE_REGISTER{2}; ///< Bus Voltage Register address
224 | const uint8_t INA_POWER_REGISTER{3}; ///< Power Register address
225 | const uint8_t INA_CALIBRATION_REGISTER{5}; ///< Calibration Register address
226 | const uint8_t INA_MASK_ENABLE_REGISTER{6}; ///< Mask enable Register (some devices)
227 | const uint8_t INA_ALERT_LIMIT_REGISTER{7}; ///< Alert Limit Register (some devices)
228 | const uint8_t INA_MANUFACTURER_ID_REGISTER{0xFE}; ///< Mfgr ID Register (some devices)
229 | const uint8_t INA_DIE_ID_REGISTER{0xFF}; ///< Die ID Register (some devices)
230 | const uint16_t INA_RESET_DEVICE{0x8000}; ///< Write to config to reset device
231 | const uint16_t INA_CONVERSION_READY_MASK{0x0080}; ///< Bit 4
232 | const uint16_t INA_CONFIG_MODE_MASK{0x0007}; ///< Bits 0-3
233 | const uint16_t INA_ALERT_MASK{0x03FF}; ///< Mask off bits 0-9
234 | const uint8_t INA_ALERT_SHUNT_OVER_VOLT_BIT{15}; ///< Register bit
235 | const uint8_t INA_ALERT_SHUNT_UNDER_VOLT_BIT{14}; ///< Register bit
236 | const uint8_t INA_ALERT_BUS_OVER_VOLT_BIT{13}; ///< Register bit
237 | const uint8_t INA_ALERT_BUS_UNDER_VOLT_BIT{12}; ///< Register bit
238 | const uint8_t INA_ALERT_POWER_OVER_WATT_BIT{11}; ///< Register bit
239 | const uint8_t INA_ALERT_CONVERSION_RDY_BIT{10}; ///< Register bit
240 | const uint8_t INA_DEFAULT_OPERATING_MODE{B111}; ///< Default continuous mode
241 | const uint8_t INA219_SHUNT_VOLTAGE_REGISTER{1}; ///< INA219 Shunt Voltage Register
242 | const uint8_t INA219_CURRENT_REGISTER{4}; ///< INA219 Current Register
243 | const uint16_t INA219_BUS_VOLTAGE_LSB{400}; ///< INA219 LSB in uV *100 4.00mV
244 | const uint16_t INA219_SHUNT_VOLTAGE_LSB{100}; ///< INA219 LSB in uV *10 10.0uV
245 | const uint16_t INA219_CONFIG_AVG_MASK{0x07F8}; ///< INA219 Bits 3-6, 7-10
246 | const uint16_t INA219_CONFIG_PG_MASK{0xE7FF}; ///< INA219 Bits 11-12 masked
247 | const uint16_t INA219_CONFIG_BADC_MASK{0x0780}; ///< INA219 Bits 7-10 masked
248 | const uint16_t INA219_CONFIG_SADC_MASK{0x0038}; ///< INA219 Bits 3-5
249 | const uint8_t INA219_BRNG_BIT{13}; ///< INA219 Bit for BRNG in config reg
250 | const uint8_t INA219_PG_FIRST_BIT{11}; ///< INA219 1st bit of Programmable Gain
251 | const uint8_t INA226_SHUNT_VOLTAGE_REGISTER{1}; ///< INA226 Shunt Voltage Register
252 | const uint8_t INA226_CURRENT_REGISTER{4}; ///< INA226 Current Register
253 | const uint16_t INA226_BUS_VOLTAGE_LSB{125}; ///< INA226 LSB in uV *100 1.25mV
254 | const uint16_t INA226_SHUNT_VOLTAGE_LSB{25}; ///< INA226 LSB in uV *10 2.5uV
255 | const uint16_t INA226_CONFIG_AVG_MASK{0x0E00}; ///< INA226 Bits 9-11
256 | const uint16_t INA226_DIE_ID_VALUE{0x2260}; ///< INA226 Hard-coded Die ID for INA226
257 | const uint16_t INA226_CONFIG_BADC_MASK{0x01C0}; ///< INA226 Bits 6-8 masked
258 | const uint16_t INA226_CONFIG_SADC_MASK{0x0038}; ///< INA226 Bits 3-4
259 |
260 | const uint8_t INA228_DIE_ID_REGISTER{0x3F}; ///< INA228 Device_ID Register
261 | const uint16_t INA228_DIE_ID_VALUE{0x2280}; ///< INA228 Hard-coded Die ID for INA228
262 | const uint8_t INA228_BUS_VOLTAGE_REGISTER{0x5}; ///< INA228 Bus Voltage Register
263 | const uint16_t INA228_BUS_VOLTAGE_LSB{195}; ///< INA228 LSB in uV *100 1953125uV, extra code
264 | const uint8_t INA228_SHUNT_VOLTAGE_REGISTER{4}; ///< INA228 Shunt Voltage Register
265 | const uint8_t xINA228_CURRENT_REGISTER{4}; ///< INA228 Current Register
266 | const uint16_t xINA228_CONFIG_AVG_MASK{0x0E00}; ///< INA228 Bits 9-11
267 | const uint16_t xINA228_CONFIG_BADC_MASK{0x01C0}; ///< INA228 Bits 6-8 masked
268 | const uint16_t xINA228_CONFIG_SADC_MASK{0x0038}; ///< INA228 Bits 3-4
269 |
270 | const uint8_t INA260_SHUNT_VOLTAGE_REGISTER{0}; ///< INA260 Register doesn't exist
271 | const uint8_t INA260_CURRENT_REGISTER{1}; ///< INA260 Current Register
272 | const uint16_t INA260_BUS_VOLTAGE_LSB{125}; ///< INA260 LSB in uV *100 1.25mV
273 | const uint16_t INA260_CONFIG_BADC_MASK{0x01C0}; ///< INA260 Bits 6-8 masked
274 | const uint16_t INA260_CONFIG_SADC_MASK{0x0038}; ///< INA260 Bits 3-5 masked
275 | const uint8_t INA3221_SHUNT_VOLTAGE_REGISTER{1}; ///< INA3221 Register number 1
276 | const uint16_t INA3221_BUS_VOLTAGE_LSB{800}; ///< INA3221 LSB in uV *100 8mV
277 | const uint16_t INA3221_SHUNT_VOLTAGE_LSB{400}; ///< INA3221 LSB in uV *10 40uV
278 | const uint16_t INA3221_CONFIG_BADC_MASK{0x01C0}; ///< INA3221 Bits 7-10 masked
279 | const uint8_t INA3221_MASK_REGISTER{0xF}; ///< INA32219 Mask register
280 | const uint8_t I2C_DELAY{10}; ///< Microsecond delay on I2C writes
281 | // clang-format on
282 |
283 | class INA_Class {
284 | /*!
285 | * @class INA_Class
286 | * @brief Forward definitions for the INA_Class
287 | */
288 | public:
289 | INA_Class(uint8_t expectedDevices = 0);
290 | ~INA_Class();
291 | uint8_t begin(const uint16_t maxBusAmps, const uint32_t microOhmR,
292 | const uint8_t deviceNumber = UINT8_MAX);
293 | void setI2CSpeed(const uint32_t i2cSpeed = INA_I2C_STANDARD_MODE) const;
294 | void setMode(const uint8_t mode, const uint8_t deviceNumber = UINT8_MAX);
295 | void setAveraging(const uint16_t averages, const uint8_t deviceNumber = UINT8_MAX);
296 | void setBusConversion(const uint32_t convTime, const uint8_t deviceNumber = UINT8_MAX);
297 | void setShuntConversion(const uint32_t convTime, const uint8_t deviceNumber = UINT8_MAX);
298 | uint16_t getBusMilliVolts(const uint8_t deviceNumber = 0);
299 | uint32_t getBusRaw(const uint8_t deviceNumber = 0);
300 | int32_t getShuntMicroVolts(const uint8_t deviceNumber = 0);
301 | int32_t getShuntRaw(const uint8_t deviceNumber = 0);
302 | int32_t getBusMicroAmps(const uint8_t deviceNumber = 0);
303 | int64_t getBusMicroWatts(const uint8_t deviceNumber = 0);
304 | const char* getDeviceName(const uint8_t deviceNumber = 0);
305 | uint8_t getDeviceAddress(const uint8_t deviceNumber = 0);
306 | void reset(const uint8_t deviceNumber = 0);
307 | bool conversionFinished(const uint8_t deviceNumber = 0);
308 | void waitForConversion(const uint8_t deviceNumber = UINT8_MAX);
309 | bool alertOnConversion(const bool alertState, const uint8_t deviceNumber = UINT8_MAX);
310 | bool alertOnShuntOverVoltage(const bool alertState, const int32_t milliVolts,
311 | const uint8_t deviceNumber = UINT8_MAX);
312 | bool alertOnShuntUnderVoltage(const bool alertState, const int32_t milliVolts,
313 | const uint8_t deviceNumber = UINT8_MAX);
314 | bool alertOnBusOverVoltage(const bool alertState, const int32_t milliVolts,
315 | const uint8_t deviceNumber = UINT8_MAX);
316 | bool alertOnBusUnderVoltage(const bool alertState, const int32_t milliVolts,
317 | const uint8_t deviceNumber = UINT8_MAX);
318 | bool alertOnPowerOverLimit(const bool alertState, const int32_t milliAmps,
319 | const uint8_t deviceNumber = UINT8_MAX);
320 | uint16_t _EEPROM_offset = 0; ///< Offset to all EEPROM addresses, GitHub issue #41
321 | #if defined(ESP32) || defined(ESP8266)
322 | uint16_t _EEPROM_size = 512; ///< Default EEPROM reserved space for ESP32 and ESP8266
323 | #endif
324 | private:
325 | int16_t readWord(const uint8_t addr, const uint8_t deviceAddress) const;
326 | int32_t read3Bytes(const uint8_t addr, const uint8_t deviceAddress) const;
327 | void writeWord(const uint8_t addr, const uint16_t data, const uint8_t deviceAddress) const;
328 | void readInafromEEPROM(const uint8_t deviceNumber);
329 | void writeInatoEEPROM(const uint8_t deviceNumber);
330 | void initDevice(const uint8_t deviceNumber);
331 | uint8_t _DeviceCount{0}; ///< Total number of devices detected
332 | uint8_t _currentINA{UINT8_MAX}; ///< Stores current INA device number
333 | uint8_t _expectedDevices{0}; ///< If 0 use EEPROM, otherwise use RAM for INA structures
334 | inaEEPROM* _DeviceArray; ///< Pointer to dynamic array of devices if not using EEPROM
335 | inaEEPROM inaEE; ///< INA device structure
336 | inaDet ina; ///< INA device structure
337 | #if defined(__AVR__) || defined(CORE_TEENSY) || defined(ESP32) || defined(ESP8266) || \
338 | defined(__STM32F1__)
339 | #else
340 | inaEEPROM _EEPROMEmulation[32]; ///< Actual array of up to 32 devices
341 | #endif
342 | }; // of INA_Class definition
343 | #endif
344 |
--------------------------------------------------------------------------------