Merge branch 'arendst/development' into development

This commit is contained in:
reloxx13 2018-02-20 19:36:46 +01:00
commit a5b64335f9
49 changed files with 5457 additions and 723 deletions

674
lib/Joba_Tsl2561/COPYING Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

20
lib/Joba_Tsl2561/README Normal file
View File

@ -0,0 +1,20 @@
This is a library for the TSL2561 digital luminosity sensors from Ams (Taos).
Design goals:
* It is modularized so you can use only what you need if space/ram is constrained.
* It does not swallow error codes so you can react on them.
* It doesn't use floats as they are overkill for most IoT stuff.
Datasheet used:
http://ams.com/eng/Products/Light-Sensors/Ambient-Light-Sensors/TSL2561/TSL2560-TSL2561-Datasheet
http://ams.com/eng/content/download/250094/975485/file/TSL2560-61_DS000110_2-00.pdf
http://ams.com/eng/content/view/download/145438
http://ams.com/eng/content/view/download/181895
To use the library, just place the folder in your projects lib folder.
For usage, see the examples folder.
The library has 3 classes:
Tsl2561 All register access as described in the datasheet, except for interrupts
Tsl2561Util Convenience functions like lux calculation or automatic gain
Tsl2561Int TODO, Interrupt related stuff (not needed if int pin unconnected)

View File

@ -0,0 +1,65 @@
/*
Autogain tests for Tsl2561Util namespace.
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Tsl2561Util.h>
Tsl2561 Tsl(Wire);
uint8_t id;
void setup() {
Serial.begin(115200);
Wire.begin();
while( !Tsl.begin() )
; // wait until chip detected or wdt reset
Serial.println("\nStarting Tsl2561Util autogain loop");
Tsl.on();
Tsl.id(id);
}
void loop() {
uint16_t scaledFull = ~0, scaledIr = ~0;
uint32_t full = ~0, ir = ~0, milliLux = ~0;
bool gain = false;
Tsl2561::exposure_t exposure = Tsl2561::EXP_OFF;
if( Tsl2561Util::autoGain(Tsl, gain, exposure, scaledFull, scaledIr) ) {
if( Tsl2561Util::normalizedLuminosity(gain, exposure, full = scaledFull, ir = scaledIr) ) {
if( Tsl2561Util::milliLux(full, ir, milliLux, Tsl2561::packageCS(id)) ) {
Serial.printf("Tsl2561 addr: 0x%02x, id: 0x%02x, sfull: %5u, sir: %5u, full: %5u, ir: %5u, gain: %d, exp: %d, lux: %5u.%03u\n",
Tsl.address(), id, scaledFull, scaledIr, full, ir, gain, exposure, milliLux/1000, milliLux%1000);
}
else {
Serial.printf("Tsl2561Util::milliLux(full=%u, ir=%u) error\n", full, ir);
}
}
else {
Serial.printf("Tsl2561Util::normalizedLuminosity(gain=%u, exposure=%u, sfull=%u, sir=%u, full=%u, ir=%u) error\n",
gain, exposure, scaledFull, scaledIr, full, ir);
}
}
else {
Serial.printf("Tsl2561Util::autoGain(gain=%u, exposure=%u, sfull=%u, sir=%u) error\n",
gain, exposure, scaledFull, scaledIr);
}
delay(1000);
}

View File

@ -0,0 +1,56 @@
/*
Simple tests for Tsl2561 class. No error checking is done.
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Tsl2561.h>
Tsl2561 Tsl(Wire);
void setup() {
Serial.begin(115200);
Wire.begin();
Serial.println("\nStarting Tsl2561 simple loop");
}
void loop() {
Tsl.begin();
if( Tsl.available() ) {
Tsl.on();
Tsl.setSensitivity(true, Tsl2561::EXP_14);
delay(16);
uint8_t id;
uint16_t full, ir;
Tsl.id(id);
Tsl.fullLuminosity(full);
Tsl.irLuminosity(ir);
Serial.printf("Tsl2561 at 0x%02x(id=0x%02x) luminosity is %5u (full) and %5u (ir)\n", Tsl.address(), id, full, ir);
Tsl.off();
}
else {
Serial.println("No Tsl2561 found. Check wiring.");
}
delay(5000);
}

View File

@ -0,0 +1,163 @@
/*
Tests for the Tsl2561 class.
It shows how to use every available method.
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Tsl2561.h>
Tsl2561 Tsl(Wire);
void showError( Tsl2561 &tsl ) {
Tsl2561::status_t status = tsl.status();
Serial.printf("Error was %u: ", status);
switch( status ) {
case Tsl2561::ERR_OK: Serial.println("None"); break;
case Tsl2561::ERR_RW: Serial.println("Read/Write"); break;
case Tsl2561::ERR_BUSY: Serial.println("Busy"); break;
case Tsl2561::ERR_GONE: Serial.println("Gone"); break;
case Tsl2561::ERR_GENERAL: Serial.println("General"); break;
default: Serial.println("Unknown"); break;
}
}
void testSensitivity( Tsl2561 &tsl, bool newGain, Tsl2561::exposure_t newExp ) {
if( tsl.on() ) {
uint32_t start = millis();
Serial.printf("Chip powered on at %u\n", start);
bool chipGain;
Tsl2561::exposure_t chipExp;
bool change = true;
if( tsl.getSensitivity(chipGain, chipExp) ) {
if( chipGain == newGain && chipExp == newExp ) {
change = false;
}
}
else {
Serial.print("getSensitivity failed. ");
showError(tsl);
}
bool check = true;
if( change ) {
if( tsl.setSensitivity(newGain, newExp) ) {
Serial.printf("New gain = %d, exposure = 0x%02x\n", newGain, newExp);
}
else {
check = false;
Serial.print("setSensitivity failed. ");
showError(tsl);
}
}
if( check ) {
uint16_t ir, full = 0;
while( !full && millis() - start < 1000 ) {
if( !tsl.fullLuminosity(full) ) {
Serial.print("Check full luminosity failed. ");
showError(tsl);
}
if( full ) {
if( !tsl.irLuminosity(ir) ) {
Serial.print("Check ir luminosity failed. ");
showError(tsl);
}
}
else {
delay(10);
}
}
if( !full ) {
Serial.println("No luminosity reading after 1s. Too dark?");
}
else {
Serial.printf("Got luminosity after %d ms. Full spectrum is %d and IR only is %d\n", millis() - start, full, ir);
}
}
if( !tsl.off() ) {
Serial.print("Power off failed. ");
showError(tsl);
}
}
else {
Serial.print("Power on failed. ");
showError(tsl);
}
}
bool testPackage( Tsl2561 &tsl ) {
uint8_t id;
if( tsl.id(id) ) {
Serial.printf("Chip has type %02x and revision %x\n", Tsl2561::type(id), Tsl2561::revision(id) );
if( Tsl2561::packageT_FN_CL(id) ) {
Serial.println("Chip is a T, FN or CL type package");
}
else if( Tsl2561::packageCS(id) ) {
Serial.println("Chip is a CS type package");
}
else {
Serial.println("Chip is an unknown package");
}
return true;
}
else {
Serial.print("Get Chip ID failed. ");
showError(tsl);
}
return false;
}
void test( Tsl2561 &tsl ) {
bool ok = tsl.available();
Serial.printf("\nTesting Tsl2561 at address %02x: %sfound\n", tsl.address(), ok ? "" : "NOT ");
if( ok ) {
if( testPackage(tsl) ) {
testSensitivity(tsl, Tsl2561::GAIN_OFF, Tsl2561::EXP_402);
testSensitivity(tsl, Tsl2561::GAIN_ON, Tsl2561::EXP_402);
testSensitivity(tsl, Tsl2561::GAIN_OFF, Tsl2561::EXP_101);
testSensitivity(tsl, Tsl2561::GAIN_ON, Tsl2561::EXP_101);
testSensitivity(tsl, Tsl2561::GAIN_OFF, Tsl2561::EXP_14);
testSensitivity(tsl, Tsl2561::GAIN_ON, Tsl2561::EXP_14);
}
}
else {
showError(tsl);
}
}
void setup() {
Serial.begin(115200);
Wire.begin();
Serial.println("\nStarting Tsl2561 testing loop");
}
void loop() {
Tsl.begin(Tsl2561::ADDR_GND);
test(Tsl);
Tsl.begin(Tsl2561::ADDR_FLOAT);
test(Tsl);
Tsl.begin(Tsl2561::ADDR_VDD);
test(Tsl);
Serial.println("\nNext test in 5s\n");
delay(5000);
}

View File

@ -0,0 +1,87 @@
/*
Simple tests for Tsl2561Util namespace.
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Tsl2561Util.h>
Tsl2561::address_t addr[] = { Tsl2561::ADDR_GND, Tsl2561::ADDR_FLOAT, Tsl2561::ADDR_VDD };
Tsl2561 Tsl(Wire);
void setup() {
Serial.begin(115200);
Wire.begin();
Serial.println("\nStarting Tsl2561Util loop");
}
void loop() {
bool found = false;
for( uint8_t i = 0; i < sizeof(addr)/sizeof(addr[0]); i++ ) {
if( Tsl.begin(addr[i]) ) {
found = true;
Serial.println();
uint16_t scaledFull = 0, scaledIr;
uint32_t full, ir, milliLux;
uint8_t id;
bool gain;
Tsl2561::exposure_t exposure;
for( uint8_t g=0; g<2; g++ ) {
gain = g;
for( uint8_t e=0; e<3; e++ ) {
exposure = (Tsl2561::exposure_t)e;
Tsl.on();
Tsl.setSensitivity(gain, exposure);
Tsl2561Util::waitNext(exposure);
Tsl.id(id);
Tsl.getSensitivity(gain, exposure);
Tsl.fullLuminosity(scaledFull);
Tsl.irLuminosity(scaledIr);
Serial.printf("Tsl2561 addr: 0x%02x, id: 0x%02x, sfull: %5u, sir: %5u, gain: %d, exp: %d", addr[i], id, scaledFull, scaledIr, gain, exposure);
if( Tsl2561Util::normalizedLuminosity(gain, exposure, full = scaledFull, ir = scaledIr) ) {
if( Tsl2561Util::milliLux(full, ir, milliLux, Tsl2561::packageCS(id)) ) {
Serial.printf(", full: %5u, ir: %5u, lux: %5u.%03u\n", full, ir, milliLux/1000, milliLux%1000);
}
else {
Serial.printf(", full: %5u, ir: %5u: Tsl2561Util::milliLux() error\n", full, ir);
}
}
else {
Serial.printf(", full: %5u, ir: %5u: Tsl2561Util::normalizedLuminosity() error\n", full, ir);
}
Tsl.off();
}
}
}
}
if( !found ) {
Serial.println("No Tsl2561 found. Check wiring.");
}
delay(5000);
}

View File

@ -0,0 +1,13 @@
{
"name": "Joba_Tsl2561",
"version": "2.0.1",
"keywords": "twowire, i2c, bus, sensor, luminosity, illuminance, lux",
"description": "Arduino Library for ams (taos) luminance chip Tsl2561 with autogain",
"repository":
{
"type": "git",
"url": "https://github.com/joba-1/Joba_Tsl2561.git"
},
"frameworks": "arduino",
"platforms": "*"
}

View File

@ -0,0 +1,9 @@
name=Joba Tsl2561 Library
version=2.0.1
author=joba-1
maintainer=joba-1 <joban123.psn@gmail.com>
sentence=IoT library for using the Tsl2561 luminosity sensor
paragraph=Luminosity measurement in lux with autogain
category=Sensors
url=https://github.com/joba-1/Joba_Tsl2561
architectures=*

View File

@ -0,0 +1,134 @@
/*
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Tsl2561.h"
Tsl2561::Tsl2561( TwoWire &wire ) : _addr(ADDR_NONE), _wire(wire), _status(ERR_OK) {
}
bool Tsl2561::available() {
_wire.beginTransmission(_addr);
return (_status = static_cast<status_t>(_wire.endTransmission())) == ERR_OK;
}
bool Tsl2561::begin( address_t addr ) {
_addr = addr;
return available();
}
bool Tsl2561::begin() {
static address_t addr[] = { ADDR_GND, ADDR_FLOAT, ADDR_VDD };
for( uint8_t i=0; i<sizeof(addr)/sizeof(addr[0]); i++ ) {
if( begin(addr[i]) ) {
return true;
}
}
_addr = ADDR_NONE;
return false;
}
bool Tsl2561::readByte( register_t reg, uint8_t &val ) {
_wire.beginTransmission(_addr);
_wire.write(reg | CONTROL_CMD);
if( _wire.endTransmission(false) == ERR_OK ) {
if( _wire.requestFrom(_addr, 1) ) {
val = static_cast<uint8_t>(_wire.read());
}
}
return (_status = static_cast<status_t>(_wire.endTransmission())) == ERR_OK;
}
bool Tsl2561::readWord( register_t reg, uint16_t &val ) {
_wire.beginTransmission(_addr);
_wire.write(reg | CONTROL_CMD);
if( _wire.endTransmission(false) == ERR_OK ) {
if( _wire.requestFrom(_addr, 2) ) {
val = (uint16_t)_wire.read() & 0xff;
val |= ((uint16_t)_wire.read() & 0xff) << 8;
}
}
return (_status = static_cast<status_t>(_wire.endTransmission())) == ERR_OK;
}
bool Tsl2561::writeByte( register_t reg, uint8_t val ) {
_wire.beginTransmission(_addr);
_wire.write(reg | CONTROL_CMD);
_wire.write(val);
return (_status = static_cast<status_t>(_wire.endTransmission())) == ERR_OK;
}
Tsl2561::status_t Tsl2561::status() const {
return _status;
}
Tsl2561::address_t Tsl2561::address() const {
return _addr;
}
bool Tsl2561::id( uint8_t &id ) {
return readByte(REG_ID, id);
}
uint8_t Tsl2561::type( uint8_t id ) {
return id & PKG_ID;
}
uint8_t Tsl2561::revision( uint8_t id ) {
return id & PKG_REV;
}
bool Tsl2561::packageCS( uint8_t id ) {
return type(id) == PKG_CS;
}
bool Tsl2561::packageT_FN_CL( uint8_t id ) {
return type(id) == PKG_T_FN_CL;
}
bool Tsl2561::on() {
return writeByte(REG_CONTROL, POWER_ON);
}
bool Tsl2561::off() {
return writeByte(REG_CONTROL, POWER_OFF);
}
bool Tsl2561::setSensitivity( bool gain, exposure_t exposure ) {
return writeByte(REG_TIMING, (gain ? GAIN_ON : GAIN_OFF) | exposure);
}
bool Tsl2561::getSensitivity( bool &gain, exposure_t &exposure )
{
uint8_t val;
if( readByte(REG_TIMING, val) ) {
gain = val & GAIN_ON;
exposure = static_cast<exposure_t>(val & EXP_ON);
}
return _status == ERR_OK;
}
bool Tsl2561::fullLuminosity( uint16_t &luminosity ) {
return readWord(REG_DATA0LOW, luminosity);
}
bool Tsl2561::irLuminosity( uint16_t &luminosity ) {
return readWord(REG_DATA1LOW, luminosity);
}

View File

@ -0,0 +1,133 @@
/*
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef Tsl2561_H
#define Tsl2561_H
#include <Arduino.h>
#include <Wire.h>
class Tsl2561 {
public:
typedef enum {
ADDR_NONE = 0b0000000,
ADDR_GND = 0b0101001,
ADDR_FLOAT = 0b0111001,
ADDR_VDD = 0b1001001
} address_t;
typedef enum {
REG_CONTROL, // Control of basic functions
REG_TIMING, // Integration time/gain control
REG_THRESHLOWLOW, // Low byte of low interrupt threshold
REG_THRESHLOWHIGH, // High byte of low interrupt threshold
REG_THRESHHIGHLOW, // Low byte of high interrupt threshold
REG_THRESHHIGHHIGH, // High byte of high interrupt threshold
REG_INTERRUPT, // Interrupt control
REG_RESERVED1,
REG_CRC, // Factory test - not a user register
REG_RESERVED2,
REG_ID, // Part number/Rev ID
REG_RESERVED3,
REG_DATA0LOW, // Low byte of ADC channel 0
REG_DATA0HIGH, // High byte of ADC channel 0
REG_DATA1LOW, // Low byte of ADC channel 1
REG_DATA1HIGH // High byte of ADC channel 1
} register_t;
enum {
CONTROL_CMD = 0b10000000,
CONTROL_CLEAR = 0b01000000,
CONTROL_WORD = 0b00100000, // SPI only?
CONTROL_BLOCK = 0b00010000, // SPI only?
CONTROL_ADDRESS = 0b00001111
};
enum {
POWER_OFF,
POWER_ON = 0b11,
};
enum {
GAIN_OFF,
GAIN_ON = 0b00010000
};
typedef enum {
EXP_ON = 0b00001011,
EXP_OFF = 0b00000011,
EXP_14 = 0b00000000,
EXP_101 = 0b00000001,
EXP_402 = 0b00000010
} exposure_t;
enum {
PKG_ID = 0b11110000,
PKG_REV = 0b00001111,
PKG_CS = 0b00010000,
PKG_T_FN_CL = 0b01010000
};
typedef enum {
ERR_OK = 0,
ERR_GENERAL = 1,
ERR_GONE = 2,
ERR_RW = 3,
ERR_BUSY = 4
} status_t;
Tsl2561( TwoWire &wire );
bool begin( address_t addr );
bool begin();
bool available();
status_t status() const;
address_t address() const;
bool id( uint8_t &id );
static uint8_t type( uint8_t id );
static uint8_t revision( uint8_t id );
static bool packageCS( uint8_t id );
static bool packageT_FN_CL( uint8_t id );
bool on();
bool off();
bool setSensitivity( bool gain, exposure_t exposure );
bool getSensitivity( bool &gain, exposure_t &exposure );
bool fullLuminosity( uint16_t &luminosity );
bool irLuminosity( uint16_t &luminosity );
protected:
bool readByte( register_t reg, uint8_t &val );
bool readWord( register_t reg, uint16_t &val );
bool writeByte( register_t reg, uint8_t val );
private:
Tsl2561();
Tsl2561( Tsl2561 & );
address_t _addr;
TwoWire &_wire;
status_t _status;
};
#endif

View File

@ -0,0 +1,193 @@
/*
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Tsl2561Util.h"
namespace Tsl2561Util {
// Tsl2561Util::normalizedLuminosity returncode false can mean:
// - saturation: full and/or ir have value ~0 (aka -1)
// - manual exposure time: full and ir are corrected only for gain
// If true, full and ir have values as if exposure was 402 and gain 16.
bool normalizedLuminosity( bool gain, Tsl2561::exposure_t exposure, uint32_t &full, uint32_t &ir ) {
uint16_t scaledFull = (uint16_t)full;
uint16_t scaledIr = (uint16_t)ir;
if( scaledFull ) {
if( ! gain ) {
full <<= 4;
ir <<= 4;
}
switch( exposure ) {
case Tsl2561::EXP_14:
full = (scaledFull >= 5047/4*3) ? ~0 : ((full + 5) * 322) / 11;
ir = (scaledIr >= 5047/4*3) ? ~0 : ((ir + 5) * 322) / 11;
break;
case Tsl2561::EXP_101:
full = (scaledFull >= 37177/4*3) ? ~0 : ((full + 40) * 322) / 81;
ir = (scaledIr >= 37177/4*3) ? ~0 : ((ir + 40) * 322) / 81;
break;
case Tsl2561::EXP_402:
if( scaledFull >= 65535/4*3 ) full = ~0;
if( scaledIr >= 65535/4*3 ) ir = ~0;
break;
default:
return false;
}
return full != ~0U && ir != ~0U;
}
return false;
}
// Return upper saturation limit upto which chip returns accurate data
uint16_t getLimit( Tsl2561::exposure_t exposure ) {
switch( exposure ) {
case Tsl2561::EXP_14: return 5047/4*3;
case Tsl2561::EXP_101: return 37177/4*3;
default: return 65535/4*3;
}
}
// Wait for one measurement interval plus some empirically tested extra millis
void waitNext( Tsl2561::exposure_t exposure ) {
switch( exposure ) {
case Tsl2561::EXP_14: delay(16); break;
case Tsl2561::EXP_101: delay(103); break;
default: delay(408); break;
}
}
// Wait for next sample, read luminosity and adjust sensitivity, if needed and possible
bool autoGain( Tsl2561 &tsl, bool &gain, Tsl2561::exposure_t &exposure, uint16_t &full, uint16_t &ir ) {
static const struct {
bool gain;
Tsl2561::exposure_t exposure;
} sensitivity[] = {
{ false, Tsl2561::EXP_14, }, // min
{ false, Tsl2561::EXP_101 },
{ true, Tsl2561::EXP_14 },
{ false, Tsl2561::EXP_402 },
{ true, Tsl2561::EXP_101 },
{ true, Tsl2561::EXP_402 } // max
};
// get current sensitivity
if( !tsl.getSensitivity(gain, exposure) ) {
return false;
}
// find index of current sensitivity
uint8_t curr = 0;
while( curr < sizeof(sensitivity)/sizeof(sensitivity[0]) ) {
if( sensitivity[curr].gain == gain && sensitivity[curr].exposure == exposure ) {
break;
}
curr++;
}
if( curr == sizeof(sensitivity)/sizeof(sensitivity[0]) ) {
return false; // should not happen...
}
// in a loop wait for next sample, get values and adjust sensitivity if needed
while( true ) {
waitNext(exposure);
if( !tsl.fullLuminosity(full) || !tsl.irLuminosity(ir) ) {
return false;
}
uint16_t limit = getLimit(exposure);
if( full >= 1000 && full <= limit ) {
return true; // new value within limits
}
if( (full < 1000 && ++curr < sizeof(sensitivity)/sizeof(sensitivity[0]))
|| (full > limit && curr-- > 0) ) {
if( !tsl.setSensitivity(sensitivity[curr].gain, sensitivity[curr].exposure) ) {
return false;
}
gain = sensitivity[curr].gain;
exposure = sensitivity[curr].exposure;
}
else {
return true; // saturated, but best we can do
}
}
}
// Measurement is up to 20% too high for temperatures above 25°C. Compensate for that.
bool compensateTemperature( int16_t centiCelsius, uint32_t &full, uint32_t &ir ) {
// assume linear gradient 0% at 25°C to +20% at 70°C
if( centiCelsius >= -3000 && centiCelsius <= 7000 ) {
full -= (full * (centiCelsius - 2500) * 20) / (100 * (7000 - 2500));
ir -= (ir * (centiCelsius - 2500) * 20) / (100 * (7000 - 2500));
return true;
}
return false;
}
// Calculate lux from raw luminosity values
bool milliLux( uint32_t full, uint32_t ir, uint32_t &mLux, bool csType ) {
if( !full ) {
mLux = 0;
return true;
}
uint32_t milliRatio = ir * 1000 / full;
if( csType ) {
if( milliRatio < 130 ) { mLux = 1000 * full - 840 * ir; }
else if ( milliRatio < 260 ) { mLux = 1080 * full - 1380 * ir; }
else if ( milliRatio < 390 ) { mLux = 1160 * full - 1690 * ir; }
else if ( milliRatio < 520 ) { mLux = 1260 * full - 1940 * ir; }
else if ( milliRatio < 650 ) { mLux = 730 * full - 930 * ir; }
else if ( milliRatio < 800 ) { mLux = 500 * full - 575 * ir; }
else if ( milliRatio < 1300 ) { mLux = 110 * full - 85 * ir; }
else {
mLux = 0;
return false;
}
mLux /= 400 * 16 / 200; // 32 = counts/lux (cpl)
}
else {
if( milliRatio < 125 ) { mLux = 1000 * full - 895 * ir; }
else if ( milliRatio < 250 ) { mLux = 1070 * full - 1045 * ir; }
else if ( milliRatio < 375 ) { mLux = 1150 * full - 1790 * ir; }
else if ( milliRatio < 500 ) { mLux = 1260 * full - 2050 * ir; }
else if ( milliRatio < 610 ) { mLux = 740 * full - 1020 * ir; }
else if ( milliRatio < 800 ) { mLux = 420 * full - 500 * ir; }
else if ( milliRatio < 1300 ) { mLux = 48 * full - 37 * ir; }
else {
mLux = 0;
return false;
}
mLux /= 400 * 16 / 193; // 33 = counts/lux (cpl)
}
return true;
}
} // namespace Tsl2561Util

View File

@ -0,0 +1,48 @@
/*
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef Tsl2561Util_H
#define Tsl2561Util_H
#include <Tsl2561.h>
namespace Tsl2561Util {
// delay until next sample is available
void waitNext( Tsl2561::exposure_t exposure );
// get saturation limit for given exposure time
uint16_t getLimit( Tsl2561::exposure_t exposure );
// in a loop wait for a sample, get it, check if within thresholds,
// until luminosity is either valid or at upper or lower saturation limit
bool autoGain( Tsl2561 &tsl, bool &gain, Tsl2561::exposure_t &exposure, uint16_t &full, uint16_t &ir );
// adjust luminosity as if measured with maximum exposure time and maximum gain
bool normalizedLuminosity( bool gain, Tsl2561::exposure_t exposure, uint32_t &full, uint32_t &ir );
// adjust luminosity according to sensor temperature (max +/-20% from 25°C)
bool compensateTemperature( int16_t centiCelsius, uint32_t &full, uint32_t &ir );
// calculate lux from normalized (and optionally temperature adjusted) luminosity
bool milliLux( uint32_t full, uint32_t ir, uint32_t &milliLux, bool csType = false );
};
#endif

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 Seeed Technology Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,45 @@
# Mutichannel_Gas_Sensor
This Arduino library is used for driving "Xadow - Mutichannel Gas Sensor" and "Grove - Mutichanel Gas Sensor"
## Usage:
mutichannelGasSensor.begin(0x04);
mutichannelGasSensor.powerOn();
then read the concentration of the specific gas you want to measure:
mutichannelGasSensor.measure_NH3();
mutichannelGasSensor.measure_CO();
mutichannelGasSensor.measure_NO2();
mutichannelGasSensor.measure_C3H8();
mutichannelGasSensor.measure_C4H10();
mutichannelGasSensor.measure_CH4();
mutichannelGasSensor.measure_H2();
mutichannelGasSensor.measure_C2H5OH();
For details please move to [wiki page](http://www.seeedstudio.com/wiki/Grove_-_Multichannel_Gas_Sensor).
----
This software is written by Jacky Zhang (![](http://www.seeedstudio.com/wiki/images/8/8f/Email_addr_of_jacky_zhang.png)) from [Seeed Technology Inc.](http://www.seeed.cc) and is licensed under [The MIT License](http://opensource.org/licenses/mit-license.php). Check License.txt/LICENSE for the details of MIT license.<br>
Contributing to this software is warmly welcomed. You can do this basically by<br>
[forking](https://help.github.com/articles/fork-a-repo), committing modifications and then [pulling requests](https://help.github.com/articles/using-pull-requests) (follow the links above<br>
for operating guide). Adding change log and your contact into file header is encouraged.<br>
Thanks for your contribution.
Seeed is a hardware innovation platform for makers to grow inspirations into differentiating products. By working closely with technology providers of all scale, Seeed provides accessible technologies with quality, speed and supply chain knowledge. When prototypes are ready to iterate, Seeed helps productize 1 to 1,000 pcs using in-house engineering, supply chain management and agile manufacture forces. Seeed also team up with incubators, Chinese tech ecosystem, investors and distribution channels to portal Maker startups beyond.
[![Analytics](https://ga-beacon.appspot.com/UA-46589105-3/Mutichannel_Gas_Sensor)](https://github.com/igrigorik/ga-beacon)

View File

@ -0,0 +1,20 @@
// Get firmware version of Grove Multichannel Gas Sensor
#include <Wire.h>
#include "MutichannelGasSensor.h"
#define SENSOR_ADDR 0X04 // default to 0x04
void setup()
{
Serial.begin(115200);
gas.begin(SENSOR_ADDR);
unsigned char version = gas.getVersion();
Serial.print("Version = ");
Serial.println(version);
}
void loop()
{
// nothing to do
}

View File

@ -0,0 +1,25 @@
// change i2c address
// Loovee
// 2016-11-10
#include <Wire.h>
#include "MutichannelGasSensor.h"
#define SENSOR_ADDR_OLD 0x04 // default to 0x04
#define SENSOR_ADDR_NEW 0x19 // change i2c address to 0x19
void setup()
{
Serial.begin(115200);
gas.begin(SENSOR_ADDR_OLD); //
gas.change_i2c_address(SENSOR_ADDR_NEW);
Serial.print("I2C ADDRESS SET TO 0X");;
Serial.println(SENSOR_ADDR_NEW, HEX);
}
void loop()
{
}
// END FILE

View File

@ -0,0 +1,57 @@
// get RAW data from the sensor
// Loovee
// 2016-11-10
#include <Wire.h>
#include "MutichannelGasSensor.h"
#define SENSOR_ADDR 0X04 // default to 0x04
void setup()
{
Serial.begin(115200);
gas.begin(SENSOR_ADDR); //
}
void loop()
{
float R0_NH3, R0_CO, R0_NO2;
float Rs_NH3, Rs_CO, Rs_NO2;
float ratio_NH3, ratio_CO, ratio_NO2;
R0_NH3 = gas.getR0(0);
R0_CO = gas.getR0(1);
R0_NO2 = gas.getR0(2);
Rs_NH3 = gas.getRs(0);
Rs_CO = gas.getRs(1);
Rs_NO2 = gas.getRs(2);
ratio_NH3 = Rs_NH3/R0_NH3;
ratio_CO = Rs_CO/R0_CO;
ratio_NO2 = Rs_NH3/R0_NO2;
Serial.println("R0:");
Serial.print(R0_NH3);
Serial.print('\t');
Serial.print(R0_CO);
Serial.print('\t');
Serial.println(R0_NO2);
Serial.println("Rs:");
Serial.print(Rs_NH3);
Serial.print('\t');
Serial.print(Rs_CO);
Serial.print('\t');
Serial.println(Rs_NO2);
Serial.println("ratio:");
Serial.print(ratio_NH3);
Serial.print('\t');
Serial.print(ratio_CO);
Serial.print('\t');
Serial.println(ratio_NO2);
Serial.println("------------------------");
delay(1000);
}

View File

@ -0,0 +1,81 @@
/*
This is a demo to test gas library
This code is running on Xadow-mainboard, and the I2C slave is Xadow-gas
There is a ATmega168PA on Xadow-gas, it get sensors output and feed back to master.
the data is raw ADC value, algorithm should be realized on master.
please feel free to write email to me if there is any question
Jacky Zhang, Embedded Software Engineer
qi.zhang@seeed.cc
17,mar,2015
*/
#include <Wire.h>
#include "MutichannelGasSensor.h"
void setup()
{
Serial.begin(115200); // start serial for output
Serial.println("power on!");
gas.begin(0x04);//the default I2C address of the slave is 0x04
gas.powerOn();
Serial.print("Firmware Version = ");
Serial.println(gas.getVersion());
}
void loop()
{
float c;
c = gas.measure_NH3();
Serial.print("The concentration of NH3 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_CO();
Serial.print("The concentration of CO is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_NO2();
Serial.print("The concentration of NO2 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_C3H8();
Serial.print("The concentration of C3H8 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_C4H10();
Serial.print("The concentration of C4H10 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_CH4();
Serial.print("The concentration of CH4 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_H2();
Serial.print("The concentration of H2 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_C2H5OH();
Serial.print("The concentration of C2H5OH is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
delay(1000);
Serial.println("...");
}

View File

@ -0,0 +1,89 @@
/*
This is a demo to test gas library
This code is running on Xadow-mainboard, and the I2C slave is Xadow-gas
There is a ATmega168PA on Xadow-gas, it get sensors output and feed back to master.
the data is raw ADC value, algorithm should be realized on master.
please feel free to write email to me if there is any question
Jacky Zhang, Embedded Software Engineer
qi.zhang@seeed.cc
17,mar,2015
*/
#include "xadow.h"
#include <Wire.h>
#include "MutichannelGasSensor.h"
void setup()
{
Xadow.init();
Serial.begin(9600); // start serial for output
Serial.println("power on!");
gas.begin(0x04);//the default I2C address of the slave is 0x04
//gas.changeI2cAddr(0x10);
//gas.doCalibrate();
gas.powerOn();
}
void loop()
{
float c;
c = gas.measure_NH3();
Serial.print("The concentration of NH3 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_CO();
Serial.print("The concentration of CO is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_NO2();
Serial.print("The concentration of NO2 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_C3H8();
Serial.print("The concentration of C3H8 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_C4H10();
Serial.print("The concentration of C4H10 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_CH4();
Serial.print("The concentration of CH4 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_H2();
Serial.print("The concentration of H2 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_C2H5OH();
Serial.print("The concentration of C2H5OH is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
Xadow.greenLed(LEDON);
delay(500);
Xadow.greenLed(LEDOFF);
delay(500);
Serial.println("...");
}

Binary file not shown.

View File

@ -0,0 +1,513 @@
// Atmega chip programmer
// Author: Nick Gammon
// Date: 22nd May 2012
// Version: 1.17
// Version 1.1: Reset foundSig to -1 each time around the loop.
// Version 1.2: Put hex bootloader data into separate files
// Version 1.3: Added verify, and MD5 sums
// Version 1.4: Added signatures for ATmeag8U2/16U2/32U2 (7 May 2012)
// Version 1.5: Added signature for ATmega1284P (8 May 2012)
// Version 1.6: Allow sketches to read bootloader area (lockbyte: 0x2F)
// Version 1.7: Added choice of bootloaders for the Atmega328P (8 MHz or 16 MHz)
// Version 1.8: Output an 8 MHz clock on pin 9
// Version 1.9: Added support for Atmega1284P, and fixed some bugs
// Version 1.10: Corrected flash size for Atmega1284P.
// Version 1.11: Added support for Atmega1280. Removed MD5SUM stuff to make room.
// Version 1.12: Added signatures for ATtiny2313A, ATtiny4313, ATtiny13
// Version 1.13: Added signature for Atmega8A
// Version 1.14: Added bootloader for Atmega8
// Version 1.15: Removed extraneous 0xFF from some files
// Version 1.16: Added signature for Atmega328
// Version 1.17: Allowed for running on the Leonardo, Micro, etc.
/*
Copyright 2012 Nick Gammon.
PERMISSION TO DISTRIBUTE
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
LIMITATION OF LIABILITY
The software is provided "as is", without warranty of any kind, express or implied,
including but not limited to the warranties of merchantability, fitness for a particular
purpose and noninfringement. In no event shall the authors or copyright holders be liable
for any claim, damages or other liability, whether in an action of contract,
tort or otherwise, arising from, out of or in connection with the software
or the use or other dealings in the software.
*/
#include <SPI.h>
#include <avr/pgmspace.h>
const unsigned long BAUD_RATE = 115200;
const byte CLOCKOUT = 9;
const byte RESET = 10; // --> goes to reset on the target board
#if ARDUINO < 100
const byte SCK = 13; // SPI clock
#endif
// number of items in an array
#define NUMITEMS(arg) ((unsigned int) (sizeof (arg) / sizeof (arg [0])))
// programming commands to send via SPI to the chip
enum {
progamEnable = 0xAC,
// writes are preceded by progamEnable
chipErase = 0x80,
writeLockByte = 0xE0,
writeLowFuseByte = 0xA0,
writeHighFuseByte = 0xA8,
writeExtendedFuseByte = 0xA4,
pollReady = 0xF0,
programAcknowledge = 0x53,
readSignatureByte = 0x30,
readCalibrationByte = 0x38,
readLowFuseByte = 0x50, readLowFuseByteArg2 = 0x00,
readExtendedFuseByte = 0x50, readExtendedFuseByteArg2 = 0x08,
readHighFuseByte = 0x58, readHighFuseByteArg2 = 0x08,
readLockByte = 0x58, readLockByteArg2 = 0x00,
readProgramMemory = 0x20,
writeProgramMemory = 0x4C,
loadExtendedAddressByte = 0x4D,
loadProgramMemory = 0x40,
}; // end of enum
// structure to hold signature and other relevant data about each chip
typedef struct {
byte sig [3];
char * desc;
unsigned long flashSize;
unsigned int baseBootSize;
const byte * bootloader;
unsigned long loaderStart; // bytes
unsigned int loaderLength; // bytes
unsigned long pageSize; // bytes
byte lowFuse, highFuse, extFuse, lockByte;
} signatureType;
const unsigned long kb = 1024;
// hex bootloader data
#include "bootloader_atmega168.h"
// see Atmega328 datasheet page 298
signatureType signatures [] =
{
// signature description flash size bootloader size
// Attiny84 family
{ { 0x1E, 0x91, 0x0B }, "ATtiny24", 2 * kb, 0 },
{ { 0x1E, 0x92, 0x07 }, "ATtiny44", 4 * kb, 0 },
{ { 0x1E, 0x93, 0x0C }, "ATtiny84", 8 * kb, 0 },
// Attiny85 family
{ { 0x1E, 0x91, 0x08 }, "ATtiny25", 2 * kb, 0 },
{ { 0x1E, 0x92, 0x06 }, "ATtiny45", 4 * kb, 0 },
{ { 0x1E, 0x93, 0x0B }, "ATtiny85", 8 * kb, 0 },
// Atmega328 family
{ { 0x1E, 0x92, 0x0A }, "ATmega48PA", 4 * kb, 0 },
{ { 0x1E, 0x93, 0x0F }, "ATmega88PA", 8 * kb, 256 },
{ { 0x1E, 0x94, 0x0B }, "ATmega168PA", 16 * kb, 256,
atmega168_optiboot, // loader image
//0x3E00, // start address
0x0,
sizeof atmega168_optiboot,
128, // page size (for committing)
0xC6, // fuse low byte: external full-swing crystal
0xde, // fuse high byte: SPI enable, brown-out detection at 2.7V
0xf8, // fuse extended byte: boot into bootloader, 512 byte bootloader
0xcf }, // lock bits: SPM is not allowed to write to the Boot Loader section.
}; // end of signatures
// if signature found in above table, this is its index
int foundSig = -1;
byte lastAddressMSB = 0;
// execute one programming instruction ... b1 is command, b2, b3, b4 are arguments
// processor may return a result on the 4th transfer, this is returned.
byte program (const byte b1, const byte b2 = 0, const byte b3 = 0, const byte b4 = 0)
{
SPI.transfer (b1);
SPI.transfer (b2);
SPI.transfer (b3);
return SPI.transfer (b4);
} // end of program
// read a byte from flash memory
byte readFlash (unsigned long addr)
{
byte high = (addr & 1) ? 0x08 : 0; // set if high byte wanted
addr >>= 1; // turn into word address
// set the extended (most significant) address byte if necessary
byte MSB = (addr >> 16) & 0xFF;
if (MSB != lastAddressMSB)
{
program (loadExtendedAddressByte, 0, MSB);
lastAddressMSB = MSB;
} // end if different MSB
return program (readProgramMemory | high, highByte (addr), lowByte (addr));
} // end of readFlash
// write a byte to the flash memory buffer (ready for committing)
byte writeFlash (unsigned long addr, const byte data)
{
byte high = (addr & 1) ? 0x08 : 0; // set if high byte wanted
addr >>= 1; // turn into word address
program (loadProgramMemory | high, 0, lowByte (addr), data);
} // end of writeFlash
// show a byte in hex with leading zero and optional newline
void showHex (const byte b, const boolean newline = false, const boolean show0x = true)
{
if (show0x)
Serial.print (F("0x"));
// try to avoid using sprintf
char buf [4] = { ((b >> 4) & 0x0F) | '0', (b & 0x0F) | '0', ' ' , 0 };
if (buf [0] > '9')
buf [0] += 7;
if (buf [1] > '9')
buf [1] += 7;
Serial.print (buf);
if (newline)
Serial.println ();
} // end of showHex
// convert a boolean to Yes/No
void showYesNo (const boolean b, const boolean newline = false)
{
if (b)
Serial.print (F("Yes"));
else
Serial.print (F("No"));
if (newline)
Serial.println ();
} // end of showYesNo
// poll the target device until it is ready to be programmed
void pollUntilReady ()
{
while ((program (pollReady) & 1) == 1)
{} // wait till ready
} // end of pollUntilReady
// commit page
void commitPage (unsigned long addr)
{
//Serial.print (F("Committing page starting at 0x"));
//Serial.println (addr, HEX);
addr >>= 1; // turn into word address
// set the extended (most significant) address byte if necessary
byte MSB = (addr >> 16) & 0xFF;
if (MSB != lastAddressMSB)
{
program (loadExtendedAddressByte, 0, MSB);
lastAddressMSB = MSB;
} // end if different MSB
program (writeProgramMemory, highByte (addr), lowByte (addr));
pollUntilReady ();
} // end of commitPage
// write specified value to specified fuse/lock byte
void writeFuse (const byte newValue, const byte instruction)
{
if (newValue == 0)
return; // ignore
program (progamEnable, instruction, 0, newValue);
pollUntilReady ();
} // end of writeFuse
void getFuseBytes ()
{
Serial.print (F("LFuse = "));
showHex (program (readLowFuseByte, readLowFuseByteArg2), true);
Serial.print (F("HFuse = "));
showHex (program (readHighFuseByte, readHighFuseByteArg2), true);
Serial.print (F("EFuse = "));
showHex (program (readExtendedFuseByte, readExtendedFuseByteArg2), true);
Serial.print (F("Lock byte = "));
showHex (program (readLockByte, readLockByteArg2), true);
Serial.print ("Clock calibration = ");
showHex (program (readCalibrationByte), true);
} // end of getFuseBytes
// burn the bootloader to the target device
void writeBootloader ()
{
if (signatures [foundSig].bootloader == 0)
{
Serial.println (F("No bootloader support for this device."));
return;
} // end if
int i;
byte lFuse = program (readLowFuseByte, readLowFuseByteArg2);
byte newlFuse = signatures [foundSig].lowFuse;
byte newhFuse = signatures [foundSig].highFuse;
byte newextFuse = signatures [foundSig].extFuse;
byte newlockByte = signatures [foundSig].lockByte;
unsigned long addr = signatures [foundSig].loaderStart;
unsigned int len = signatures [foundSig].loaderLength;
unsigned long pagesize = signatures [foundSig].pageSize;
unsigned long pagemask = ~(pagesize - 1);
const byte * bootloader = signatures [foundSig].bootloader;
Serial.print (F("Bootloader address = 0x"));
Serial.println (addr, HEX);
Serial.print (F("Bootloader length = "));
Serial.print (len);
Serial.println (F(" bytes."));
byte subcommand = 'U';
// Atmega328P or Atmega328
if (signatures [foundSig].sig [0] == 0x1E &&
signatures [foundSig].sig [1] == 0x95 &&
(signatures [foundSig].sig [2] == 0x0F || signatures [foundSig].sig [2] == 0x14)
)
{
Serial.println (F("Type 'L' to use Lilypad (8 MHz) loader, or 'U' for Uno (16 MHz) loader ..."));
do
{
subcommand = toupper (Serial.read ());
} while (subcommand != 'L' && subcommand != 'U');
if (subcommand == 'L') // use internal 8 MHz clock
{
Serial.println (F("Using Lilypad 8 MHz loader."));
bootloader = atmega168_optiboot;
newlFuse = 0xE2; // internal 8 MHz oscillator
newhFuse = 0xDA; // 2048 byte bootloader, SPI enabled
addr = 0x7800;
len = sizeof atmega168_optiboot;
} // end of using the 8 MHz clock
else
Serial.println (F("Using Uno Optiboot 16 MHz loader."));
} // end of being Atmega328P
unsigned long oldPage = addr & pagemask;
Serial.println (F("Type 'V' to verify, or 'G' to program the chip with the bootloader ..."));
char command;
do
{
command = toupper (Serial.read ());
} while (command != 'G' && command != 'V');
if (command == 'G')
{
Serial.println (F("Erasing chip ..."));
program (progamEnable, chipErase); // erase it
pollUntilReady ();
Serial.println (F("Writing bootloader ..."));
for (i = 0; i < len; i += 2)
{
unsigned long thisPage = (addr + i) & pagemask;
// page changed? commit old one
if (thisPage != oldPage)
{
commitPage (oldPage);
oldPage = thisPage;
}
unsigned char c1 = pgm_read_byte(bootloader + i);
unsigned char c2 = pgm_read_byte(bootloader + i+1);
writeFlash (addr + i, c1);
writeFlash (addr + i + 1, c2);
} // end while doing each word
Serial.println();
// commit final page
commitPage (oldPage);
Serial.println ("Written.");
} // end if programming
Serial.println (F("Verifying ..."));
// count errors
unsigned int errors = 0;
// check each byte
for (i = 0; i < signatures [foundSig].loaderLength; i++)
{
//if(i==0)Serial.print(" ");
byte found = readFlash (addr + i);
byte expected = pgm_read_byte(bootloader + i);
if (found != expected)
{
if (errors <= 100)
{
Serial.print (F("Verification error at address "));
Serial.print (addr + i, HEX);
Serial.print (F(". Got: "));
showHex (found);
Serial.print (F(" Expected: "));
showHex (expected, true);
} // end of haven't shown 100 errors yet
errors++;
} // end if error
} // end of for
Serial.println("\r\n");
if (errors == 0)
Serial.println (F("No errors found."));
else
{
Serial.print (errors, DEC);
Serial.println (F(" verification error(s)."));
if (errors > 100)
Serial.println (F("First 100 shown."));
return; // don't change fuses if errors
} // end if
if (command == 'G')
{
Serial.println (F("Writing fuses ..."));
writeFuse (newlFuse, writeLowFuseByte);
writeFuse (newhFuse, writeHighFuseByte);
writeFuse (newextFuse, writeExtendedFuseByte);
writeFuse (newlockByte, writeLockByte);
// confirm them
getFuseBytes ();
} // end if programming
Serial.println (F("Done."));
} // end of writeBootloader
void startProgramming ()
{
byte confirm;
pinMode (RESET, OUTPUT);
pinMode (SCK, OUTPUT);
// we are in sync if we get back programAcknowledge on the third byte
do
{
delay (100);
// ensure SCK low
digitalWrite (SCK, LOW);
// then pulse reset, see page 309 of datasheet
digitalWrite (RESET, HIGH);
delay (1); // pulse for at least 2 clock cycles
digitalWrite (RESET, LOW);
delay (25); // wait at least 20 mS
SPI.transfer (progamEnable);
SPI.transfer (programAcknowledge);
confirm = SPI.transfer (0);
SPI.transfer (0);
} while (confirm != programAcknowledge);
Serial.println (F("Entered programming mode OK."));
} // end of startProgramming
void getSignature ()
{
foundSig = -1;
lastAddressMSB = 0;
byte sig [3];
Serial.print (F("Signature = "));
for (byte i = 0; i < 3; i++)
{
sig [i] = program (readSignatureByte, 0, i);
showHex (sig [i]);
} // end for each signature byte
Serial.println ();
for (int j = 0; j < NUMITEMS (signatures); j++)
{
if (memcmp (sig, signatures [j].sig, sizeof sig) == 0)
{
foundSig = j;
Serial.print (F("Processor = "));
Serial.println (signatures [j].desc);
Serial.print (F("Flash memory size = "));
Serial.print (signatures [j].flashSize, DEC);
Serial.println (F(" bytes."));
return;
} // end of signature found
} // end of for each signature
Serial.println (F("Unrecogized signature."));
} // end of getSignature
void setup ()
{
Serial.begin (BAUD_RATE);
while (!Serial) ; // for Leonardo, Micro etc.
Serial.println ();
Serial.println (F("Atmega chip programmer."));
Serial.println (F("Written by Nick Gammon."));
digitalWrite (RESET, HIGH); // ensure SS stays high for now
SPI.begin ();
// slow down SPI for benefit of slower processors like the Attiny
SPI.setClockDivider (SPI_CLOCK_DIV64);
pinMode (CLOCKOUT, OUTPUT);
// set up Timer 1
TCCR1A = _BV (COM1A0); // toggle OC1A on Compare Match
TCCR1B = _BV(WGM12) | _BV(CS10); // CTC, no prescaling
OCR1A = 0; // output every cycle
} // end of setup
void loop ()
{
startProgramming ();
getSignature ();
getFuseBytes ();
// if we found a signature try to write a bootloader
if (foundSig != -1)
writeBootloader ();
// release reset
digitalWrite (RESET, HIGH);
Serial.println (F("Type 'C' when ready to continue with another chip ..."));
while (toupper (Serial.read ()) != 'C')
{}
} // end of loop

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@ -0,0 +1,35 @@
// Calibration code for Grove - Multichannel Gas Sensor
// Note that it need 10 minutes pre-heat before calibration
// This code is writen by Loovee@2016-5-18
#include <Wire.h>
#include "MutichannelGasSensor.h"
#define SENSOR_ADDR 0X04 // default to 0x04
#define PRE_HEAT_TIME 0 // pre-heat time, 10-30 minutes is recommended
void setup()
{
Serial.begin(115200);
gas.begin(SENSOR_ADDR); //
Serial.println("power on, and pre-heat");
for(int i=60*PRE_HEAT_TIME; i>=0; i--)
{
Serial.print(i/60);
Serial.print(":");
Serial.println(i%60);
delay(1000);
}
Serial.println("Begin to calibrate...");
gas.doCalibrate();
Serial.println("Calibration ok");
gas.display_eeprom();
}
void loop()
{
}

View File

@ -0,0 +1,36 @@
// factory setting
// Loovee
// 2016-11-10
#include <Wire.h>
#include "MutichannelGasSensor.h"
#define SENSOR_ADDR 0X04 // default to 0x04
void setup()
{
Serial.begin(115200);
Serial.println("Please input something to continue");
while(!Serial.available());
gas.begin(SENSOR_ADDR); //
Serial.println("FACTORY SETTING OK");
float R0_NH3, R0_CO, R0_NO2;
R0_NH3 = gas.getR0(0);
R0_CO = gas.getR0(1);
R0_NO2 = gas.getR0(2);
Serial.print("R0_NH3 = ");
Serial.println(R0_NH3);
Serial.print("R0_CO = ");
Serial.println(R0_CO);
Serial.print("R0_NO2 = ");
Serial.println(R0_NO2);
}
void loop()
{
}

View File

@ -0,0 +1,272 @@
/*firmware of multichannel gas sensor v2.0*3
write by loovee
2016-11-6
Factory adc value of 3 channels:
NH3 = 860
CO = 950
NO2 = 155
Default address is 0x04
*/
#include <Wire.h>
#include <EEPROM.h>
#define DEFAULT_I2C_ADDR 0x04
#define DBG 1
// EEPROM ADDRESS
#define ADDR_IS_SET 0 // if this is the first time to run, if 1126, set
#define ADDR_FACTORY_ADC_NH3 2
#define ADDR_FACTORY_ADC_CO 4
#define ADDR_FACTORY_ADC_NO2 6
#define ADDR_USER_ADC_HN3 8
#define ADDR_USER_ADC_CO 10
#define ADDR_USER_ADC_NO2 12
#define ADDR_IF_CALI 14 // IF USER HAD CALI
#define ADDR_I2C_ADDRESS 20
// I2C COMMAND
#define CMD_ADC_RES0 1 // NH3
#define CMD_ADC_RES1 2 // CO
#define CMD_ADC_RES2 3 // NO2
#define CMD_ADC_RESALL 4 // ALL CHANNEL
#define CMD_CHANGE_I2C 5 // CHANGE I2C
#define CMD_READ_EEPROM 6 // READ EEPROM VALUE, RETURN UNSIGNED INT
#define CMD_SET_R0_ADC 7 // SET R0 ADC VALUE
#define CMD_GET_R0_ADC 8 // GET R0 ADC VALUE
#define CMD_GET_R0_ADC_FACTORY 9 // GET FACTORY R0 ADC VALUE
#define CMD_CONTROL_LED 10
#define CMD_CONTROL_PWR 11
// EEPROM READ AND WRITE - UNSIGNED INT
void eeprom_write(int addr, unsigned int value)
{
EEPROM.write(addr, value>>8);
EEPROM.write(addr+1, value&0xff);
}
unsigned int eeprom_read(int addr)
{
unsigned int r = EEPROM.read(addr);
r <<= 8;
r+= EEPROM.read(addr+1);
return r;
}
const int pin_pwr = 8;
const int pin_led = 9;
const int pin_NH3 = A0; // RES0
const int pin_CO = A1; // RES1
const int pin_NO2 = A2; // RES2
unsigned char i2c_address = 0;
#define LED_ON() digitalWrite(pin_led, LOW)
#define LED_OFF() digitalWrite(pin_led, HIGH)
void factory_init()
{
#if DBG
Serial.print("FACTORY: ");
#endif
if(1126 != eeprom_read(ADDR_IS_SET)) // IF FACTORY SET
{
#if DBG
Serial.println("YES");
#endif
eeprom_write(ADDR_IS_SET, 1126);
eeprom_write(ADDR_FACTORY_ADC_NH3, 860);
eeprom_write(ADDR_FACTORY_ADC_CO, 950);
eeprom_write(ADDR_FACTORY_ADC_NO2, 155);
eeprom_write(ADDR_USER_ADC_HN3, 860);
eeprom_write(ADDR_USER_ADC_CO, 950);
eeprom_write(ADDR_USER_ADC_NO2, 155);
eeprom_write(ADDR_IF_CALI, 0);
eeprom_write(ADDR_I2C_ADDRESS, DEFAULT_I2C_ADDR);
}
#if DBG
else Serial.println("NO");
#endif
}
int getAnalog(int pin)
{
long sum = 0;
for(int i=0; i<64; i++)
{
sum += analogRead(pin);
}
return sum>>6;
}
unsigned int ADC_RES0 = 0;
unsigned int ADC_RES1 = 0;
unsigned int ADC_RES2 = 0;
unsigned char raw_adc[6];
void updateValue()
{
static unsigned long timer_s = millis();
if(millis()-timer_s < 1000)return;
timer_s = millis();
ADC_RES0 = getAnalog(pin_NH3);
ADC_RES1 = getAnalog(pin_CO);
ADC_RES2 = getAnalog(pin_NO2);
raw_adc[0] = ADC_RES0>>8;
raw_adc[1] = ADC_RES0;
raw_adc[2] = ADC_RES1>>8;
raw_adc[3] = ADC_RES1;
raw_adc[4] = ADC_RES2>>8;
raw_adc[5] = ADC_RES2;
}
void setup()
{
#if DBG
Serial.begin(115200);
#endif
pinMode(pin_pwr, OUTPUT);
digitalWrite(pin_pwr, HIGH);
pinMode(pin_led, OUTPUT);
factory_init();
i2c_address = eeprom_read(ADDR_I2C_ADDRESS);
#if DBG
Serial.print("i2d address = 0x");
Serial.println(i2c_address, HEX);
#endif
for(int i=0; i<5; i++)
{
digitalWrite(pin_led, LOW);
delay(100);
digitalWrite(pin_led, HIGH);
delay(100);
}
Wire.begin(i2c_address); // join i2c bus with address
Wire.onReceive(receiveCallback); // register receive callback
Wire.onRequest(requestCallback); // register request callback
}
void loop()
{
updateValue();
}
unsigned char recvCmd = 0;
unsigned char recvDta = 0;
unsigned char recvDtaStr[10];
void receiveCallback(int dtaCount)
{
if(dtaCount == 1)
{
recvCmd = Wire.read();
}
else if(dtaCount == 2) // set i2c address
{
recvCmd = Wire.read();
recvDta = Wire.read();
if(CMD_CHANGE_I2C == recvCmd)
{
i2c_address = recvDta;
eeprom_write(ADDR_I2C_ADDRESS, i2c_address);
Wire.begin(i2c_address);
}
else if(CMD_CONTROL_LED == recvCmd)
{
if(0 == recvDta)LED_OFF();
else if(1 == recvDta)LED_ON();
}
else if(CMD_CONTROL_PWR == recvCmd)
{
if(0 == recvDta)digitalWrite(pin_pwr, LOW);
else if(1 == recvDta)digitalWrite(pin_pwr, HIGH);
}
}
else if(dtaCount == 7) // set ADC value
{
recvCmd = Wire.read();
unsigned int dta[3];
for(int i=0; i<3; i++)
{
dta[i] = Wire.read();
dta[i] <<= 8;
dta[i] += Wire.read();
}
if(recvCmd == CMD_SET_R0_ADC)
{
eeprom_write(ADDR_USER_ADC_HN3, dta[0]);
eeprom_write(ADDR_USER_ADC_CO, dta[1]);
eeprom_write(ADDR_USER_ADC_NO2, dta[2]);
}
}
}
unsigned char rcDta[10];
void requestCallback()
{
switch(recvCmd)
{
case CMD_ADC_RES0: // NH3
Wire.write(&raw_adc[0], 2); // HIGH FIRST
break;
case CMD_ADC_RES1: // CO
Wire.write(&raw_adc[2], 2); // HIGH FIRST
break;
case CMD_ADC_RES2: // NO2
Wire.write(&raw_adc[4], 2); // HIGH FIRST
break;
case CMD_ADC_RESALL:
Wire.write(raw_adc, 6);
break;
case CMD_READ_EEPROM:
rcDta[0] = EEPROM.read(recvDta);
rcDta[1] = EEPROM.read(recvDta+1);
Wire.write(rcDta, 2);
break;
case CMD_GET_R0_ADC:
rcDta[0] = EEPROM.read(ADDR_USER_ADC_HN3);
rcDta[1] = EEPROM.read(ADDR_USER_ADC_HN3+1);
rcDta[2] = EEPROM.read(ADDR_USER_ADC_CO);
rcDta[3] = EEPROM.read(ADDR_USER_ADC_CO+1);
rcDta[4] = EEPROM.read(ADDR_USER_ADC_NO2);
rcDta[5] = EEPROM.read(ADDR_USER_ADC_NO2+1);
Wire.write(rcDta, 6);
break;
case CMD_GET_R0_ADC_FACTORY:
rcDta[0] = EEPROM.read(ADDR_FACTORY_ADC_NH3);
rcDta[1] = EEPROM.read(ADDR_FACTORY_ADC_NH3+1);
rcDta[2] = EEPROM.read(ADDR_FACTORY_ADC_CO);
rcDta[3] = EEPROM.read(ADDR_FACTORY_ADC_CO+1);
rcDta[4] = EEPROM.read(ADDR_FACTORY_ADC_NO2);
rcDta[5] = EEPROM.read(ADDR_FACTORY_ADC_NO2+1);
Wire.write(rcDta, 6);
break;
default:;
}
}
// END FILE

View File

@ -0,0 +1,14 @@
{
"name": "Mutichannel_Gas_Sensor",
"keywords": "Gas Sensor",
"description": "Grove - Multichannel Gas Sensor",
"homepage": "http://wiki.seeed.cc/Grove-Multichannel_Gas_Sensor/",
"repository":
{
"type": "git",
"url": "https://github.com/Seeed-Studio/Mutichannel_Gas_Sensor.git"
},
"version": "0.0.1",
"frameworks": "arduino",
"platforms": "*"
}

View File

@ -0,0 +1,9 @@
name=Grove - Multichannel Gas Sensor
version=0.0.1
author=WEMOS.CC <support@wemos.cc>
maintainer=WEMOS.CC
sentence=Library for the <a href="http://wiki.seeed.cc/Grove-Multichannel_Gas_Sensor/"> Grove - Multichannel Gas Sensor</a>.
paragraph=Library for the Grove - Multichannel Gas Sensor.
category=Device Control
url=https://github.com/Seeed-Studio/Mutichannel_Gas_Sensor.git
architectures=*

View File

@ -0,0 +1,729 @@
/*
MutichannelGasSensor.cpp
2015 Copyright (c) Seeed Technology Inc. All right reserved.
Author: Jacky Zhang
2015-3-17
http://www.seeed.cc/
modi by Jack, 2015-8
The MIT License (MIT)
Copyright (c) 2015 Seeed Technology Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <math.h>
#include <Wire.h>
#include <Arduino.h>
#include "MutichannelGasSensor.h"
/*********************************************************************************************************
** Function name: begin
** Descriptions: initialize I2C
*********************************************************************************************************/
void MutichannelGasSensor::begin(int address)
{
__version = 1; // version 1/2
r0_inited = false;
Wire.begin();
i2cAddress = address;
__send_error = false;
__version = getVersion();
}
bool MutichannelGasSensor::isError()
{
return __send_error;
}
unsigned char MutichannelGasSensor::getVersion()
{
if(get_addr_dta(CMD_READ_EEPROM, ADDR_IS_SET) == 1126) // get version
{
__version = 2;
return __version;
}
if (!__send_error) {
__version = 1;
}
else {
__version = -1;
}
return __version;
}
void MutichannelGasSensor::begin()
{
begin(DEFAULT_I2C_ADDR);
}
/*********************************************************************************************************
** Function name: sendI2C
** Descriptions: send one byte to I2C Wire
*********************************************************************************************************/
void MutichannelGasSensor::sendI2C(unsigned char dta)
{
__send_error = false;
Wire.beginTransmission(i2cAddress); // transmit to device #4
Wire.write(dta); // sends one byte
if (Wire.endTransmission()) { // stop transmitting
__send_error = true;
}
}
unsigned int MutichannelGasSensor::get_addr_dta(unsigned char addr_reg)
{
int trys = 0;
START:
__send_error = false;
Wire.beginTransmission(i2cAddress);
Wire.write(addr_reg);
if (Wire.endTransmission()) { // stop transmitting
trys++;
__send_error = true;
if (trys > 3) {
return 0;
}
}
Wire.requestFrom(i2cAddress, (uint8_t)2);
unsigned int dta = 0;
unsigned char raw[10];
int cnt = 0;
while(Wire.available())
{
raw[cnt++] = Wire.read();
}
if(cnt == 0)goto START;
dta = raw[0];
dta <<= 8;
dta += raw[1];
switch(addr_reg)
{
case CH_VALUE_NH3:
if(dta > 0)
{
adcValueR0_NH3_Buf = dta;
}
else
{
dta = adcValueR0_NH3_Buf;
}
break;
case CH_VALUE_CO:
if(dta > 0)
{
adcValueR0_CO_Buf = dta;
}
else
{
dta = adcValueR0_CO_Buf;
}
break;
case CH_VALUE_NO2:
if(dta > 0)
{
adcValueR0_NO2_Buf = dta;
}
else
{
dta = adcValueR0_NO2_Buf;
}
break;
default:;
}
return dta;
}
unsigned int MutichannelGasSensor::get_addr_dta(unsigned char addr_reg, unsigned char __dta)
{
int trys = 0;
START:
__send_error = false;
Wire.beginTransmission(i2cAddress);
Wire.write(addr_reg);
Wire.write(__dta);
if (Wire.endTransmission()) { // stop transmitting
trys++;
__send_error = true;
if (trys > 3) {
return 0;
}
}
Wire.requestFrom(i2cAddress, (uint8_t)2);
unsigned int dta = 0;
unsigned char raw[10];
int cnt = 0;
while(Wire.available())
{
raw[cnt++] = Wire.read();
}
if(cnt == 0)goto START;
dta = raw[0];
dta <<= 8;
dta += raw[1];
return dta;
}
void MutichannelGasSensor::write_i2c(unsigned char addr, unsigned char *dta, unsigned char dta_len)
{
__send_error = false;
Wire.beginTransmission(addr);
for(int i=0; i<dta_len; i++)
{
Wire.write(dta[i]);
}
if (Wire.endTransmission()) {
__send_error = true;
}
}
/*********************************************************************************************************
** Function name: readData
** Descriptions: read 4 bytes from I2C slave
*********************************************************************************************************/
int16_t MutichannelGasSensor::readData(uint8_t cmd)
{
uint16_t timeout = 0;
uint8_t buffer[4];
uint8_t checksum = 0;
int16_t rtnData = 0;
//send command
sendI2C(cmd);
//wait for a while
delay(2);
//get response
Wire.requestFrom(i2cAddress, (uint8_t)4); // request 4 bytes from slave device
while(Wire.available() == 0)
{
if(timeout++ > 100)
return -2;//time out
delay(2);
}
if(Wire.available() != 4)
return -3;//rtnData length wrong
buffer[0] = Wire.read();
buffer[1] = Wire.read();
buffer[2] = Wire.read();
buffer[3] = Wire.read();
checksum = (uint8_t)(buffer[0] + buffer[1] + buffer[2]);
if(checksum != buffer[3])
return -4;//checksum wrong
rtnData = ((buffer[1] << 8) + buffer[2]);
return rtnData;//successful
}
/*********************************************************************************************************
** Function name: readR0
** Descriptions: read R0 stored in slave MCU
*********************************************************************************************************/
int16_t MutichannelGasSensor::readR0(void)
{
int16_t rtnData = 0;
rtnData = readData(0x11);
if(rtnData > 0)
res0[0] = rtnData;
else
return rtnData; //unsuccessful
rtnData = readData(0x12);
if(rtnData > 0)
res0[1] = rtnData;
else
return rtnData; //unsuccessful
rtnData = readData(0x13);
if(rtnData > 0)
res0[2] = rtnData;
else
return rtnData; //unsuccessful
return 1;//successful
}
/*********************************************************************************************************
** Function name: readR
** Descriptions: read resistance value of each channel from slave MCU
*********************************************************************************************************/
int16_t MutichannelGasSensor::readR(void)
{
int16_t rtnData = 0;
rtnData = readData(0x01);
if(rtnData >= 0)
res[0] = rtnData;
else
return rtnData;//unsuccessful
rtnData = readData(0x02);
if(rtnData >= 0)
res[1] = rtnData;
else
return rtnData;//unsuccessful
rtnData = readData(0x03);
if(rtnData >= 0)
res[2] = rtnData;
else
return rtnData;//unsuccessful
return 0;//successful
}
/*********************************************************************************************************
** Function name: readR
** Descriptions: calculate gas concentration of each channel from slave MCU
** Parameters:
gas - gas type
** Returns:
float value - concentration of the gas
*********************************************************************************************************/
float MutichannelGasSensor::calcGas(int gas)
{
float ratio0, ratio1, ratio2;
if(1 == __version)
{
if(!r0_inited)
{
if(readR0() >= 0) r0_inited = true;
else return -1.0f;
}
if(readR() < 0)
return -2.0f;
ratio0 = (float)res[0] / res0[0];
ratio1 = (float)res[1] / res0[1];
ratio2 = (float)res[2] / res0[2];
}
else if(2 == __version)
{
// how to calc ratio/123
ledOn();
int A0_0 = get_addr_dta(6, ADDR_USER_ADC_HN3);
int A0_1 = get_addr_dta(6, ADDR_USER_ADC_CO);
int A0_2 = get_addr_dta(6, ADDR_USER_ADC_NO2);
int An_0 = get_addr_dta(CH_VALUE_NH3);
int An_1 = get_addr_dta(CH_VALUE_CO);
int An_2 = get_addr_dta(CH_VALUE_NO2);
ratio0 = (float)An_0/(float)A0_0*(1023.0-A0_0)/(1023.0-An_0);
ratio1 = (float)An_1/(float)A0_1*(1023.0-A0_1)/(1023.0-An_1);
ratio2 = (float)An_2/(float)A0_2*(1023.0-A0_2)/(1023.0-An_2);
}
float c = 0;
switch(gas)
{
case CO:
{
c = pow(ratio1, -1.179)*4.385; //mod by jack
break;
}
case NO2:
{
c = pow(ratio2, 1.007)/6.855; //mod by jack
break;
}
case NH3:
{
c = pow(ratio0, -1.67)/1.47; //modi by jack
break;
}
case C3H8: //add by jack
{
c = pow(ratio0, -2.518)*570.164;
break;
}
case C4H10: //add by jack
{
c = pow(ratio0, -2.138)*398.107;
break;
}
case GAS_CH4: //add by jack
{
c = pow(ratio1, -4.363)*630.957;
break;
}
case H2: //add by jack
{
c = pow(ratio1, -1.8)*0.73;
break;
}
case C2H5OH: //add by jack
{
c = pow(ratio1, -1.552)*1.622;
break;
}
default:
break;
}
if(2==__version)ledOff();
return isnan(c)?-3:c;
}
/*********************************************************************************************************
** Function name: changeI2cAddr
** Descriptions: change I2C address of the slave MCU, and this address will be stored in EEPROM of slave MCU
*********************************************************************************************************/
void MutichannelGasSensor::changeI2cAddr(uint8_t newAddr)
{
Wire.beginTransmission(i2cAddress); // transmit to device
Wire.write(0x23); // sends one byte
Wire.write(newAddr); // sends one byte
if (Wire.endTransmission()){ // stop transmitting
__send_error = true;
} else {
i2cAddress = newAddr;
}
}
/*********************************************************************************************************
** Function name: doCalibrate
** Descriptions: tell slave to do a calibration, it will take about 8s
after the calibration, must reread the R0 values
*********************************************************************************************************/
void MutichannelGasSensor::doCalibrate(void)
{
if(1 == __version)
{
START:
sendI2C(0x22);
if(readR0() > 0)
{
for(int i=0; i<3; i++)
{
Serial.print(res0[i]);
Serial.print('\t');
}
}
else
{
delay(5000);
Serial.println("continue...");
for(int i=0; i<3; i++)
{
Serial.print(res0[i]);
Serial.print('\t');
}
Serial.println();
goto START;
}
}
else if(2 == __version)
{
unsigned int i, a0, a1, a2;
while(1)
{
a0 = get_addr_dta(CH_VALUE_NH3);
a1 = get_addr_dta(CH_VALUE_CO);
a2 = get_addr_dta(CH_VALUE_NO2);
Serial.print(a0);
Serial.print('\t');
Serial.print(a1);
Serial.print('\t');
Serial.print(a2);
Serial.println('\t');
ledOn();
int cnt = 0;
for(i=0; i<20; i++)
{
if((a0 - get_addr_dta(CH_VALUE_NH3)) > 2 || (get_addr_dta(CH_VALUE_NH3) - a0) > 2)cnt++;
if((a1 - get_addr_dta(CH_VALUE_CO)) > 2 || (get_addr_dta(CH_VALUE_CO) - a1) > 2)cnt++;
if((a2 - get_addr_dta(CH_VALUE_NO2)) > 2 || (get_addr_dta(CH_VALUE_NO2) - a2) > 2)cnt++;
if(cnt>5)
{
break;
}
delay(1000);
}
ledOff();
if(cnt <= 5)break;
delay(200);
}
Serial.print("write user adc value: ");
Serial.print(a0);Serial.print('\t');
Serial.print(a1);Serial.print('\t');
Serial.print(a2);Serial.println('\t');
unsigned char tmp[7];
tmp[0] = 7;
tmp[1] = a0>>8;
tmp[2] = a0&0xff;
tmp[3] = a1>>8;
tmp[4] = a1&0xff;
tmp[5] = a2>>8;
tmp[6] = a2&0xff;
write_i2c(i2cAddress, tmp, 7);
}
}
/*********************************************************************************************************
** Function name: powerOn
** Descriptions: power on sensor heater
*********************************************************************************************************/
void MutichannelGasSensor::powerOn(void)
{
if(__version == 1)
sendI2C(0x21);
else if(__version == 2)
{
dta_test[0] = 11;
dta_test[1] = 1;
write_i2c(i2cAddress, dta_test, 2);
}
}
/*********************************************************************************************************
** Function name: powerOff
** Descriptions: power off sensor heater
*********************************************************************************************************/
void MutichannelGasSensor::powerOff(void)
{
if(__version == 1)
sendI2C(0x20);
else if(__version == 2)
{
dta_test[0] = 11;
dta_test[1] = 0;
write_i2c(i2cAddress, dta_test, 2);
}
}
void MutichannelGasSensor::display_eeprom()
{
if(__version == 1)
{
Serial.println("ERROR: display_eeprom() is NOT support by V1 firmware.");
return ;
}
Serial.print("ADDR_IS_SET = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_IS_SET));
Serial.print("ADDR_FACTORY_ADC_NH3 = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_NH3));
Serial.print("ADDR_FACTORY_ADC_CO = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_CO));
Serial.print("ADDR_FACTORY_ADC_NO2 = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_NO2));
Serial.print("ADDR_USER_ADC_HN3 = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_HN3));
Serial.print("ADDR_USER_ADC_CO = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_CO));
Serial.print("ADDR_USER_ADC_NO2 = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_NO2));
Serial.print("ADDR_I2C_ADDRESS = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_I2C_ADDRESS));
}
float MutichannelGasSensor::getR0(unsigned char ch) // 0:CH3, 1:CO, 2:NO2
{
if(__version == 1)
{
Serial.println("ERROR: getR0() is NOT support by V1 firmware.");
return -1;
}
int a = 0;
switch(ch)
{
case 0: // CH3
a = get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_HN3);
Serial.print("a_ch3 = ");
Serial.println(a);
break;
case 1: // CO
a = get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_CO);
Serial.print("a_co = ");
Serial.println(a);
break;
case 2: // NO2
a = get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_NO2);
Serial.print("a_no2 = ");
Serial.println(a);
break;
default:;
}
float r = 56.0*(float)a/(1023.0-(float)a);
return r;
}
float MutichannelGasSensor::getRs(unsigned char ch) // 0:CH3, 1:CO, 2:NO2
{
if(__version == 1)
{
Serial.println("ERROR: getRs() is NOT support by V1 firmware.");
return -1;
}
int a = 0;
switch(ch)
{
case 0: // NH3
a = get_addr_dta(1);
break;
case 1: // CO
a = get_addr_dta(2);
break;
case 2: // NO2
a = get_addr_dta(3);
break;
default:;
}
float r = 56.0*(float)a/(1023.0-(float)a);
return r;
}
// 1. change i2c address to 0x04
// 2. change adc value of R0 to default
void MutichannelGasSensor::factory_setting()
{
unsigned char tmp[7];
unsigned char error;
unsigned char address = 0;
for(address = 1; address < 127; address++ )
{
// The i2c_scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
// change i2c to 0x04
Serial.print("I2C address is: 0x");
Serial.println(address, HEX);
Serial.println("Change I2C address to 0x04");
dta_test[0] = CMD_CHANGE_I2C;
dta_test[1] = 0x04;
write_i2c(address, dta_test, 2);
i2cAddress = 0x04;
delay(100);
getVersion();
break;
}
}
unsigned int a0 = get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_NH3);
unsigned int a1 = get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_CO);
unsigned int a2 = get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_NO2);
tmp[0] = 7;
tmp[1] = a0>>8;
tmp[2] = a0&0xff;
tmp[3] = a1>>8;
tmp[4] = a1&0xff;
tmp[5] = a2>>8;
tmp[6] = a2&0xff;
delay(100);
write_i2c(i2cAddress, tmp, 7);
delay(100);
}
void MutichannelGasSensor::change_i2c_address(unsigned char addr)
{
dta_test[0] = CMD_CHANGE_I2C;
dta_test[1] = addr;
write_i2c(i2cAddress, dta_test, 2);
Serial.print("FUNCTION: CHANGE I2C ADDRESS: 0X");
Serial.print(i2cAddress, HEX);
Serial.print(" > 0x");
Serial.println(addr, HEX);
i2cAddress = addr;
}
void MutichannelGasSensor::ledOn()
{
dta_test[0] = CMD_CONTROL_LED;
dta_test[1] = 1;
write_i2c(i2cAddress, dta_test, 2);
}
void MutichannelGasSensor::ledOff()
{
dta_test[0] = CMD_CONTROL_LED;
dta_test[1] = 0;
write_i2c(i2cAddress, dta_test, 2);
}
MutichannelGasSensor gas;
/*********************************************************************************************************
END FILE
*********************************************************************************************************/

View File

@ -0,0 +1,140 @@
/*
MutichannelGasSensor.h
2015 Copyright (c) Seeed Technology Inc. All right reserved.
Author: Jacky Zhang
2015-3-17
http://www.seeed.cc/
modi by Jack, 2015-8
V2 by Loovee
2016-11-11
The MIT License (MIT)
Copyright (c) 2015 Seeed Technology Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef __MUTICHANNELGASSENSOR_H__
#define __MUTICHANNELGASSENSOR_H__
#define DEFAULT_I2C_ADDR 0x04
#define ADDR_IS_SET 0 // if this is the first time to run, if 1126, set
#define ADDR_FACTORY_ADC_NH3 2
#define ADDR_FACTORY_ADC_CO 4
#define ADDR_FACTORY_ADC_NO2 6
#define ADDR_USER_ADC_HN3 8
#define ADDR_USER_ADC_CO 10
#define ADDR_USER_ADC_NO2 12
#define ADDR_IF_CALI 14 // IF USER HAD CALI
#define ADDR_I2C_ADDRESS 20
#define CH_VALUE_NH3 1
#define CH_VALUE_CO 2
#define CH_VALUE_NO2 3
#define CMD_ADC_RES0 1 // NH3
#define CMD_ADC_RES1 2 // CO
#define CMD_ADC_RES2 3 // NO2
#define CMD_ADC_RESALL 4 // ALL CHANNEL
#define CMD_CHANGE_I2C 5 // CHANGE I2C
#define CMD_READ_EEPROM 6 // READ EEPROM VALUE, RETURN UNSIGNED INT
#define CMD_SET_R0_ADC 7 // SET R0 ADC VALUE
#define CMD_GET_R0_ADC 8 // GET R0 ADC VALUE
#define CMD_GET_R0_ADC_FACTORY 9 // GET FACTORY R0 ADC VALUE
#define CMD_CONTROL_LED 10
#define CMD_CONTROL_PWR 11
enum{CO, NO2, NH3, C3H8, C4H10, GAS_CH4, H2, C2H5OH};
class MutichannelGasSensor{
private:
int __version;
int __send_error;
unsigned char dta_test[20];
unsigned int readChAdcValue(int ch);
unsigned int adcValueR0_NH3_Buf;
unsigned int adcValueR0_CO_Buf;
unsigned int adcValueR0_NO2_Buf;
public:
uint8_t i2cAddress; //I2C address of this MCU
uint16_t res0[3]; //sensors res0
uint16_t res[3]; //sensors res
bool r0_inited;
inline unsigned int get_addr_dta(unsigned char addr_reg);
inline unsigned int get_addr_dta(unsigned char addr_reg, unsigned char __dta);
inline void write_i2c(unsigned char addr, unsigned char *dta, unsigned char dta_len);
void sendI2C(unsigned char dta);
int16_t readData(uint8_t cmd);
int16_t readR0(void);
int16_t readR(void);
float calcGas(int gas);
public:
void begin(int address);
void begin();
void changeI2cAddr(uint8_t newAddr);
void powerOn(void);
void powerOff(void);
void doCalibrate(void);
//get gas concentration, unit: ppm
float measure_CO(){return calcGas(CO);}
float measure_NO2(){return calcGas(NO2);}
float measure_NH3(){return calcGas(NH3);}
float measure_C3H8(){return calcGas(C3H8);}
float measure_C4H10(){return calcGas(C4H10);}
float measure_CH4(){return calcGas(GAS_CH4);}
float measure_H2(){return calcGas(H2);}
float measure_C2H5OH(){return calcGas(C2H5OH);}
float getR0(unsigned char ch); // 0:CH3, 1:CO, 2:NO2
float getRs(unsigned char ch); // 0:CH3, 1:CO, 2:NO2
public:
bool isError();
void ledOn();
void ledOff();
void display_eeprom();
void factory_setting();
void change_i2c_address(unsigned char addr);
unsigned char getVersion();
};
extern MutichannelGasSensor gas;
#endif
/*********************************************************************************************************
END FILE
*********************************************************************************************************/

View File

@ -1,46 +0,0 @@
Thank you for opening an issue on an Adafruit Arduino library repository. To
improve the speed of resolution please review the following guidelines and
common troubleshooting steps below before creating the issue:
- **Do not use GitHub issues for troubleshooting projects and issues.** Instead use
the forums at http://forums.adafruit.com to ask questions and troubleshoot why
something isn't working as expected. In many cases the problem is a common issue
that you will more quickly receive help from the forum community. GitHub issues
are meant for known defects in the code. If you don't know if there is a defect
in the code then start with troubleshooting on the forum first.
- **If following a tutorial or guide be sure you didn't miss a step.** Carefully
check all of the steps and commands to run have been followed. Consult the
forum if you're unsure or have questions about steps in a guide/tutorial.
- **For Arduino projects check these very common issues to ensure they don't apply**:
- For uploading sketches or communicating with the board make sure you're using
a **USB data cable** and **not** a **USB charge-only cable**. It is sometimes
very hard to tell the difference between a data and charge cable! Try using the
cable with other devices or swapping to another cable to confirm it is not
the problem.
- **Be sure you are supplying adequate power to the board.** Check the specs of
your board and plug in an external power supply. In many cases just
plugging a board into your computer is not enough to power it and other
peripherals.
- **Double check all soldering joints and connections.** Flakey connections
cause many mysterious problems. See the [guide to excellent soldering](https://learn.adafruit.com/adafruit-guide-excellent-soldering/tools) for examples of good solder joints.
- **Ensure you are using an official Arduino or Adafruit board.** We can't
guarantee a clone board will have the same functionality and work as expected
with this code and don't support them.
If you're sure this issue is a defect in the code and checked the steps above
please fill in the following fields to provide enough troubleshooting information.
You may delete the guideline and text above to just leave the following details:
- Arduino board: **INSERT ARDUINO BOARD NAME/TYPE HERE**
- Arduino IDE version (found in Arduino -> About Arduino menu): **INSERT ARDUINO
VERSION HERE**
- List the steps to reproduce the problem below (if possible attach a sketch or
copy the sketch code in too): **LIST REPRO STEPS BELOW**

View File

@ -1,26 +0,0 @@
Thank you for creating a pull request to contribute to Adafruit's GitHub code!
Before you open the request please review the following guidelines and tips to
help it be more easily integrated:
- **Describe the scope of your change--i.e. what the change does and what parts
of the code were modified.** This will help us understand any risks of integrating
the code.
- **Describe any known limitations with your change.** For example if the change
doesn't apply to a supported platform of the library please mention it.
- **Please run any tests or examples that can exercise your modified code.** We
strive to not break users of the code and running tests/examples helps with this
process.
Thank you again for contributing! We will try to test and integrate the change
as soon as we can, but be aware we have many GitHub repositories to manage and
can't immediately respond to every request. There is no need to bump or check in
on a pull request (it will clutter the discussion of the request).
Also don't be worried if the request is closed or not integrated--sometimes the
priorities of Adafruit's GitHub code (education, ease of use) might not match the
priorities of the pull request. Don't fret, the open source community thrives on
forks and GitHub makes it easy to keep your changes in a forked repo.
After reviewing the guidelines above you can delete this text from the pull request.

View File

@ -1,7 +0,0 @@
This is an Arduino library for the TSL2561 digital luminosity (light) sensors.
Pick one up at http://www.adafruit.com/products/439
To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder TSL2561. Check that the TSL2561 folder contains TSL2561.cpp and TSL2561.h
Place the TSL2561 library folder your <arduinosketchfolder>/libraries/ folder. You may need to create the libraries subfolder if its your first library. Restart the IDE.

View File

@ -1,301 +0,0 @@
/**************************************************************************/
/*!
@file tsl2561.c
@author K. Townsend (microBuilder.eu / adafruit.com)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2010, microBuilder SARL, Adafruit Industries
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#if defined ( ESP8266 )
#include <pgmspace.h>
#else
#include <avr/pgmspace.h>
#include <util/delay.h>
#endif
#include <stdlib.h>
#include "TSL2561.h"
TSL2561::TSL2561(uint8_t addr) {
_addr = addr;
_initialized = false;
_integration = TSL2561_INTEGRATIONTIME_13MS;
_gain = TSL2561_GAIN_16X;
// we cant do wire initialization till later, because we havent loaded Wire yet
}
boolean TSL2561::begin(void) {
Wire.begin();
// Initialise I2C
Wire.beginTransmission(_addr);
#if ARDUINO >= 100
Wire.write(TSL2561_REGISTER_ID);
#else
Wire.send(TSL2561_REGISTER_ID);
#endif
Wire.endTransmission();
Wire.requestFrom(_addr, 1);
#if ARDUINO >= 100
int x = Wire.read();
#else
int x = Wire.receive();
#endif
//Serial.print("0x"); Serial.println(x, HEX);
if (x & 0x0A ) {
//Serial.println("Found TSL2561");
} else {
return false;
}
_initialized = true;
// Set default integration time and gain
setTiming(_integration);
setGain(_gain);
// Note: by default, the device is in power down mode on bootup
disable();
return true;
}
void TSL2561::enable(void)
{
if (!_initialized) begin();
// Enable the device by setting the control bit to 0x03
write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_CONTROL, TSL2561_CONTROL_POWERON);
}
void TSL2561::disable(void)
{
if (!_initialized) begin();
// Disable the device by setting the control bit to 0x03
write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_CONTROL, TSL2561_CONTROL_POWEROFF);
}
void TSL2561::setGain(tsl2561Gain_t gain) {
if (!_initialized) begin();
enable();
_gain = gain;
write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_TIMING, _integration | _gain);
disable();
}
void TSL2561::setTiming(tsl2561IntegrationTime_t integration)
{
if (!_initialized) begin();
enable();
_integration = integration;
write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_TIMING, _integration | _gain);
disable();
}
uint32_t TSL2561::calculateLux(uint16_t ch0, uint16_t ch1)
{
unsigned long chScale;
unsigned long channel1;
unsigned long channel0;
switch (_integration)
{
case TSL2561_INTEGRATIONTIME_13MS:
chScale = TSL2561_LUX_CHSCALE_TINT0;
break;
case TSL2561_INTEGRATIONTIME_101MS:
chScale = TSL2561_LUX_CHSCALE_TINT1;
break;
default: // No scaling ... integration time = 402ms
chScale = (1 << TSL2561_LUX_CHSCALE);
break;
}
// Scale for gain (1x or 16x)
if (!_gain) chScale = chScale << 4;
// scale the channel values
channel0 = (ch0 * chScale) >> TSL2561_LUX_CHSCALE;
channel1 = (ch1 * chScale) >> TSL2561_LUX_CHSCALE;
// find the ratio of the channel values (Channel1/Channel0)
unsigned long ratio1 = 0;
if (channel0 != 0) ratio1 = (channel1 << (TSL2561_LUX_RATIOSCALE+1)) / channel0;
// round the ratio value
unsigned long ratio = (ratio1 + 1) >> 1;
unsigned int b, m;
#ifdef TSL2561_PACKAGE_CS
if ((ratio >= 0) && (ratio <= TSL2561_LUX_K1C))
{b=TSL2561_LUX_B1C; m=TSL2561_LUX_M1C;}
else if (ratio <= TSL2561_LUX_K2C)
{b=TSL2561_LUX_B2C; m=TSL2561_LUX_M2C;}
else if (ratio <= TSL2561_LUX_K3C)
{b=TSL2561_LUX_B3C; m=TSL2561_LUX_M3C;}
else if (ratio <= TSL2561_LUX_K4C)
{b=TSL2561_LUX_B4C; m=TSL2561_LUX_M4C;}
else if (ratio <= TSL2561_LUX_K5C)
{b=TSL2561_LUX_B5C; m=TSL2561_LUX_M5C;}
else if (ratio <= TSL2561_LUX_K6C)
{b=TSL2561_LUX_B6C; m=TSL2561_LUX_M6C;}
else if (ratio <= TSL2561_LUX_K7C)
{b=TSL2561_LUX_B7C; m=TSL2561_LUX_M7C;}
else if (ratio > TSL2561_LUX_K8C)
{b=TSL2561_LUX_B8C; m=TSL2561_LUX_M8C;}
#else
if ((ratio >= 0) && (ratio <= TSL2561_LUX_K1T))
{b=TSL2561_LUX_B1T; m=TSL2561_LUX_M1T;}
else if (ratio <= TSL2561_LUX_K2T)
{b=TSL2561_LUX_B2T; m=TSL2561_LUX_M2T;}
else if (ratio <= TSL2561_LUX_K3T)
{b=TSL2561_LUX_B3T; m=TSL2561_LUX_M3T;}
else if (ratio <= TSL2561_LUX_K4T)
{b=TSL2561_LUX_B4T; m=TSL2561_LUX_M4T;}
else if (ratio <= TSL2561_LUX_K5T)
{b=TSL2561_LUX_B5T; m=TSL2561_LUX_M5T;}
else if (ratio <= TSL2561_LUX_K6T)
{b=TSL2561_LUX_B6T; m=TSL2561_LUX_M6T;}
else if (ratio <= TSL2561_LUX_K7T)
{b=TSL2561_LUX_B7T; m=TSL2561_LUX_M7T;}
else if (ratio > TSL2561_LUX_K8T)
{b=TSL2561_LUX_B8T; m=TSL2561_LUX_M8T;}
#endif
unsigned long temp;
temp = ((channel0 * b) - (channel1 * m));
// do not allow negative lux value
if (temp < 0) temp = 0;
// round lsb (2^(LUX_SCALE-1))
temp += (1 << (TSL2561_LUX_LUXSCALE-1));
// strip off fractional portion
uint32_t lux = temp >> TSL2561_LUX_LUXSCALE;
// Signal I2C had no errors
return lux;
}
uint32_t TSL2561::getFullLuminosity (void)
{
if (!_initialized) begin();
// Enable the device by setting the control bit to 0x03
enable();
// Wait x ms for ADC to complete
switch (_integration)
{
case TSL2561_INTEGRATIONTIME_13MS:
delay(14);
break;
case TSL2561_INTEGRATIONTIME_101MS:
delay(102);
break;
default:
delay(403);
break;
}
uint32_t x;
x = read16(TSL2561_COMMAND_BIT | TSL2561_WORD_BIT | TSL2561_REGISTER_CHAN1_LOW);
x <<= 16;
x |= read16(TSL2561_COMMAND_BIT | TSL2561_WORD_BIT | TSL2561_REGISTER_CHAN0_LOW);
disable();
return x;
}
uint16_t TSL2561::getLuminosity (uint8_t channel) {
uint32_t x = getFullLuminosity();
if (channel == 0) {
// Reads two byte value from channel 0 (visible + infrared)
return (x & 0xFFFF);
} else if (channel == 1) {
// Reads two byte value from channel 1 (infrared)
return (x >> 16);
} else if (channel == 2) {
// Reads all and subtracts out just the visible!
return ( (x & 0xFFFF) - (x >> 16));
}
// unknown channel!
return 0;
}
uint16_t TSL2561::read16(uint8_t reg)
{
uint16_t x; uint16_t t;
Wire.beginTransmission(_addr);
#if ARDUINO >= 100
Wire.write(reg);
#else
Wire.send(reg);
#endif
Wire.endTransmission();
Wire.requestFrom(_addr, 2);
#if ARDUINO >= 100
t = Wire.read();
x = Wire.read();
#else
t = Wire.receive();
x = Wire.receive();
#endif
x <<= 8;
x |= t;
return x;
}
void TSL2561::write8 (uint8_t reg, uint8_t value)
{
Wire.beginTransmission(_addr);
#if ARDUINO >= 100
Wire.write(reg);
Wire.write(value);
#else
Wire.send(reg);
Wire.send(value);
#endif
Wire.endTransmission();
}

View File

@ -1,184 +0,0 @@
/**************************************************************************/
/*!
@file tsl2561.h
@author K. Townsend (microBuilder.eu)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2010, microBuilder SARL
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#ifndef _TSL2561_H_
#define _TSL2561_H_
#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
#include <Wire.h>
#define TSL2561_VISIBLE 2 // channel 0 - channel 1
#define TSL2561_INFRARED 1 // channel 1
#define TSL2561_FULLSPECTRUM 0 // channel 0
// 3 i2c address options!
#define TSL2561_ADDR_LOW 0x29
#define TSL2561_ADDR_FLOAT 0x39
#define TSL2561_ADDR_HIGH 0x49
// Lux calculations differ slightly for CS package
//#define TSL2561_PACKAGE_CS
#define TSL2561_PACKAGE_T_FN_CL
#define TSL2561_READBIT (0x01)
#define TSL2561_COMMAND_BIT (0x80) // Must be 1
#define TSL2561_CLEAR_BIT (0x40) // Clears any pending interrupt (write 1 to clear)
#define TSL2561_WORD_BIT (0x20) // 1 = read/write word (rather than byte)
#define TSL2561_BLOCK_BIT (0x10) // 1 = using block read/write
#define TSL2561_CONTROL_POWERON (0x03)
#define TSL2561_CONTROL_POWEROFF (0x00)
#define TSL2561_LUX_LUXSCALE (14) // Scale by 2^14
#define TSL2561_LUX_RATIOSCALE (9) // Scale ratio by 2^9
#define TSL2561_LUX_CHSCALE (10) // Scale channel values by 2^10
#define TSL2561_LUX_CHSCALE_TINT0 (0x7517) // 322/11 * 2^TSL2561_LUX_CHSCALE
#define TSL2561_LUX_CHSCALE_TINT1 (0x0FE7) // 322/81 * 2^TSL2561_LUX_CHSCALE
// T, FN and CL package values
#define TSL2561_LUX_K1T (0x0040) // 0.125 * 2^RATIO_SCALE
#define TSL2561_LUX_B1T (0x01f2) // 0.0304 * 2^LUX_SCALE
#define TSL2561_LUX_M1T (0x01be) // 0.0272 * 2^LUX_SCALE
#define TSL2561_LUX_K2T (0x0080) // 0.250 * 2^RATIO_SCALE
#define TSL2561_LUX_B2T (0x0214) // 0.0325 * 2^LUX_SCALE
#define TSL2561_LUX_M2T (0x02d1) // 0.0440 * 2^LUX_SCALE
#define TSL2561_LUX_K3T (0x00c0) // 0.375 * 2^RATIO_SCALE
#define TSL2561_LUX_B3T (0x023f) // 0.0351 * 2^LUX_SCALE
#define TSL2561_LUX_M3T (0x037b) // 0.0544 * 2^LUX_SCALE
#define TSL2561_LUX_K4T (0x0100) // 0.50 * 2^RATIO_SCALE
#define TSL2561_LUX_B4T (0x0270) // 0.0381 * 2^LUX_SCALE
#define TSL2561_LUX_M4T (0x03fe) // 0.0624 * 2^LUX_SCALE
#define TSL2561_LUX_K5T (0x0138) // 0.61 * 2^RATIO_SCALE
#define TSL2561_LUX_B5T (0x016f) // 0.0224 * 2^LUX_SCALE
#define TSL2561_LUX_M5T (0x01fc) // 0.0310 * 2^LUX_SCALE
#define TSL2561_LUX_K6T (0x019a) // 0.80 * 2^RATIO_SCALE
#define TSL2561_LUX_B6T (0x00d2) // 0.0128 * 2^LUX_SCALE
#define TSL2561_LUX_M6T (0x00fb) // 0.0153 * 2^LUX_SCALE
#define TSL2561_LUX_K7T (0x029a) // 1.3 * 2^RATIO_SCALE
#define TSL2561_LUX_B7T (0x0018) // 0.00146 * 2^LUX_SCALE
#define TSL2561_LUX_M7T (0x0012) // 0.00112 * 2^LUX_SCALE
#define TSL2561_LUX_K8T (0x029a) // 1.3 * 2^RATIO_SCALE
#define TSL2561_LUX_B8T (0x0000) // 0.000 * 2^LUX_SCALE
#define TSL2561_LUX_M8T (0x0000) // 0.000 * 2^LUX_SCALE
// CS package values
#define TSL2561_LUX_K1C (0x0043) // 0.130 * 2^RATIO_SCALE
#define TSL2561_LUX_B1C (0x0204) // 0.0315 * 2^LUX_SCALE
#define TSL2561_LUX_M1C (0x01ad) // 0.0262 * 2^LUX_SCALE
#define TSL2561_LUX_K2C (0x0085) // 0.260 * 2^RATIO_SCALE
#define TSL2561_LUX_B2C (0x0228) // 0.0337 * 2^LUX_SCALE
#define TSL2561_LUX_M2C (0x02c1) // 0.0430 * 2^LUX_SCALE
#define TSL2561_LUX_K3C (0x00c8) // 0.390 * 2^RATIO_SCALE
#define TSL2561_LUX_B3C (0x0253) // 0.0363 * 2^LUX_SCALE
#define TSL2561_LUX_M3C (0x0363) // 0.0529 * 2^LUX_SCALE
#define TSL2561_LUX_K4C (0x010a) // 0.520 * 2^RATIO_SCALE
#define TSL2561_LUX_B4C (0x0282) // 0.0392 * 2^LUX_SCALE
#define TSL2561_LUX_M4C (0x03df) // 0.0605 * 2^LUX_SCALE
#define TSL2561_LUX_K5C (0x014d) // 0.65 * 2^RATIO_SCALE
#define TSL2561_LUX_B5C (0x0177) // 0.0229 * 2^LUX_SCALE
#define TSL2561_LUX_M5C (0x01dd) // 0.0291 * 2^LUX_SCALE
#define TSL2561_LUX_K6C (0x019a) // 0.80 * 2^RATIO_SCALE
#define TSL2561_LUX_B6C (0x0101) // 0.0157 * 2^LUX_SCALE
#define TSL2561_LUX_M6C (0x0127) // 0.0180 * 2^LUX_SCALE
#define TSL2561_LUX_K7C (0x029a) // 1.3 * 2^RATIO_SCALE
#define TSL2561_LUX_B7C (0x0037) // 0.00338 * 2^LUX_SCALE
#define TSL2561_LUX_M7C (0x002b) // 0.00260 * 2^LUX_SCALE
#define TSL2561_LUX_K8C (0x029a) // 1.3 * 2^RATIO_SCALE
#define TSL2561_LUX_B8C (0x0000) // 0.000 * 2^LUX_SCALE
#define TSL2561_LUX_M8C (0x0000) // 0.000 * 2^LUX_SCALE
enum
{
TSL2561_REGISTER_CONTROL = 0x00,
TSL2561_REGISTER_TIMING = 0x01,
TSL2561_REGISTER_THRESHHOLDL_LOW = 0x02,
TSL2561_REGISTER_THRESHHOLDL_HIGH = 0x03,
TSL2561_REGISTER_THRESHHOLDH_LOW = 0x04,
TSL2561_REGISTER_THRESHHOLDH_HIGH = 0x05,
TSL2561_REGISTER_INTERRUPT = 0x06,
TSL2561_REGISTER_CRC = 0x08,
TSL2561_REGISTER_ID = 0x0A,
TSL2561_REGISTER_CHAN0_LOW = 0x0C,
TSL2561_REGISTER_CHAN0_HIGH = 0x0D,
TSL2561_REGISTER_CHAN1_LOW = 0x0E,
TSL2561_REGISTER_CHAN1_HIGH = 0x0F
};
typedef enum
{
TSL2561_INTEGRATIONTIME_13MS = 0x00, // 13.7ms
TSL2561_INTEGRATIONTIME_101MS = 0x01, // 101ms
TSL2561_INTEGRATIONTIME_402MS = 0x02 // 402ms
}
tsl2561IntegrationTime_t;
typedef enum
{
TSL2561_GAIN_0X = 0x00, // No gain
TSL2561_GAIN_16X = 0x10, // 16x gain
}
tsl2561Gain_t;
class TSL2561 {
public:
TSL2561(uint8_t addr);
boolean begin(void);
void enable(void);
void disable(void);
void write8(uint8_t r, uint8_t v);
uint16_t read16(uint8_t reg);
uint32_t calculateLux(uint16_t ch0, uint16_t ch1);
void setTiming(tsl2561IntegrationTime_t integration);
void setGain(tsl2561Gain_t gain);
uint16_t getLuminosity (uint8_t channel);
uint32_t getFullLuminosity ();
private:
int8_t _addr;
tsl2561IntegrationTime_t _integration;
tsl2561Gain_t _gain;
boolean _initialized;
};
#endif

View File

@ -1,63 +0,0 @@
#include <Wire.h>
#include "TSL2561.h"
// Example for demonstrating the TSL2561 library - public domain!
// connect SCL to analog 5
// connect SDA to analog 4
// connect VDD to 3.3V DC
// connect GROUND to common ground
// ADDR can be connected to ground, or vdd or left floating to change the i2c address
// The address will be different depending on whether you let
// the ADDR pin float (addr 0x39), or tie it to ground or vcc. In those cases
// use TSL2561_ADDR_LOW (0x29) or TSL2561_ADDR_HIGH (0x49) respectively
TSL2561 tsl(TSL2561_ADDR_FLOAT);
void setup(void) {
Serial.begin(9600);
if (tsl.begin()) {
Serial.println("Found sensor");
} else {
Serial.println("No sensor?");
while (1);
}
// You can change the gain on the fly, to adapt to brighter/dimmer light situations
//tsl.setGain(TSL2561_GAIN_0X); // set no gain (for bright situtations)
tsl.setGain(TSL2561_GAIN_16X); // set 16x gain (for dim situations)
// Changing the integration time gives you a longer time over which to sense light
// longer timelines are slower, but are good in very low light situtations!
tsl.setTiming(TSL2561_INTEGRATIONTIME_13MS); // shortest integration time (bright light)
//tsl.setTiming(TSL2561_INTEGRATIONTIME_101MS); // medium integration time (medium light)
//tsl.setTiming(TSL2561_INTEGRATIONTIME_402MS); // longest integration time (dim light)
// Now we're ready to get readings!
}
void loop(void) {
// Simple data read example. Just read the infrared, fullspecrtrum diode
// or 'visible' (difference between the two) channels.
// This can take 13-402 milliseconds! Uncomment whichever of the following you want to read
uint16_t x = tsl.getLuminosity(TSL2561_VISIBLE);
//uint16_t x = tsl.getLuminosity(TSL2561_FULLSPECTRUM);
//uint16_t x = tsl.getLuminosity(TSL2561_INFRARED);
Serial.println(x, DEC);
// More advanced data read example. Read 32 bits with top 16 bits IR, bottom 16 bits full spectrum
// That way you can do whatever math and comparisons you want!
uint32_t lum = tsl.getFullLuminosity();
uint16_t ir, full;
ir = lum >> 16;
full = lum & 0xFFFF;
Serial.print("IR: "); Serial.print(ir); Serial.print("\t\t");
Serial.print("Full: "); Serial.print(full); Serial.print("\t");
Serial.print("Visible: "); Serial.print(full - ir); Serial.print("\t");
Serial.print("Lux: "); Serial.println(tsl.calculateLux(full, ir));
delay(100);
}

View File

@ -1,9 +0,0 @@
name=TSL2561 Arduino Library
version=1.0.0
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=Arduino library for using the TSL2561 Luminosity sensor
paragraph=Arduino library for using the TSL2561 Luminosity sensor
category=Sensors
url=https://github.com/adafruit/TSL2561-Arduino-Library
architectures=*

View File

@ -1,20 +1,28 @@
/* 5.12.0b
/* 5.12.0c
* Fix intermittent exception when dns lookup is used while sleep is enabled
*
* 5.12.0b
* Add serial debug info
* Add Multichannel Gas sensor using MultiChannel_Gas_Sensor library (#1245)
* Add optional usage of %d or %X suffices in MQTT client to append chipid (#1871)
* Add optional usage of %d or %X suffices in MQTT topic to append chipid (#1871)
* Add optional usage of %d or %04d in ota url to be replaced with chipid (#1871)
* Add Sonoff Bridge command RfKey<x> 5 to show current RF key values either default or learned (#1884)
* Add user configurable serial GPIOs to MagicHome and Arilux modules (#1887)
* Add Russian language file (#1909)
* Add Webserver upload preflight request support (#1927)
* Add Home Assistant clear other device (#1931)
* Add Restart time to Status 1 (#1938)
* Change TSL2561 driver to joba library and delete Adafruit library (#1644)
* Change Sonoff SC JSON format (#1939)
* Fix compile error when define HOME_ASSISTANT_DISCOVERY_ENABLE is not set (#1937)
* Add optional TSL2561 driver using library Joba_Tsl2561 to be enabled in user_config.h with define USE_TSL2561_JOBA (#1951)
* Add support for sensor SHTC3 (#1967)
*
* 5.12.0a
* Change platformio option sonoff-ds18x20 to sonoff-xxl enabling ds18x20 and all other sensors in one image
* Fix providing web page configuratin option for Friendly Name when no device (relay or light) is configured (#1850)
* Change default paremeters in user_config.h to undefined for easy installation (#1851)
* Change default parameters in user_config.h to undefined for easy installation (#1851)
* Change max user configurable hold time from 10 to 25 seconds (#1851)
*
* 5.12.0 20180209

View File

@ -449,7 +449,7 @@ const char HTTP_SNS_SEAPRESSURE[] PROGMEM = "%s{s}%s " D_PRESSUREATSEALEVEL "{m}
const char HTTP_SNS_ANALOG[] PROGMEM = "%s{s}%s " D_ANALOG_INPUT "%d{m}%d{e}"; // {s} = <tr><th>, {m} = </th><td>, {e} = </td></tr>
#if defined(USE_MHZ19) || defined(USE_SENSEAIR)
const char HTTP_SNS_CO2[] PROGMEM = "%s{s}%s " D_CO2 "{m}%d " D_UNIT_PARTS_PER_MILLION "{e}"; // {s} = <tr><th>, {m} = </th><td>, {e} = </td></tr>
const char HTTP_SNS_CO2[] PROGMEM = "%s{s}%s " D_CO2 "{m}%d " D_UNIT_PARTS_PER_MILLION "{e}"; // {s} = <tr><th>, {m} = </th><td>, {e} = </td></tr>
#endif // USE_WEBSERVER
const char S_MAIN_MENU[] PROGMEM = D_MAIN_MENU;

View File

@ -210,18 +210,18 @@
#define D_SECONDS "секунд"
#define D_DEVICE_WILL_RESTART "Устройство будет перезапущено через несколько секунд"
#define D_BUTTON_TOGGLE "Переключить"
#define D_CONFIGURATION "Кофигурация"
#define D_CONFIGURATION "Конфигурация"
#define D_INFORMATION "Информация"
#define D_FIRMWARE_UPGRADE "Обновление прошивки"
#define D_CONSOLE "Консоль"
#define D_CONFIRM_RESTART "Подтвердить перезагрузку"
#define D_CONFIGURE_MODULE "Кофигурация Модуля"
#define D_CONFIGURE_WIFI "Кофигурация WiFi"
#define D_CONFIGURE_MQTT "Кофигурация MQTT"
#define D_CONFIGURE_DOMOTICZ "Кофигурация Domoticz"
#define D_CONFIGURE_LOGGING "Кофигурация Logging"
#define D_CONFIGURE_OTHER "Кофигурация прочее"
#define D_CONFIGURE_MODULE "Конфигурация Модуля"
#define D_CONFIGURE_WIFI "Конфигурация WiFi"
#define D_CONFIGURE_MQTT "Конфигурация MQTT"
#define D_CONFIGURE_DOMOTICZ "Конфигурация Domoticz"
#define D_CONFIGURE_LOGGING "Конфигурация Logging"
#define D_CONFIGURE_OTHER "Конфигурация прочее"
#define D_CONFIRM_RESET_CONFIGURATION "Подтвердить Сброс Конфигурации"
#define D_RESET_CONFIGURATION "Сброс Конфигурации"
#define D_BACKUP_CONFIGURATION "Резервное копирование Конфигурации"
@ -293,7 +293,7 @@
#define D_ESP_CHIP_ID "ID чипа ESP"
#define D_FLASH_CHIP_ID "ID чипа Flash памяти"
#define D_FLASH_CHIP_SIZE "Размер Flash памяти"
#define D_FREE_PROGRAM_SPACE "Свободное пространство программы"
#define D_FREE_PROGRAM_SPACE "Свободное пространство программ"
#define D_UPGRADE_BY_WEBSERVER "Обновление через Веб-сервер"
#define D_OTA_URL "OTA Url"
@ -428,7 +428,7 @@
#define D_UNIT_SECTORS "секторов"
#define D_UNIT_VOLT "В"
#define D_UNIT_WATT "Вт"
#define D_UNIT_WATTHOUR "Вт"
#define D_UNIT_WATTHOUR "ВтЧ"
// Log message prefix
#define D_LOG_APPLICATION "APP: " // Application

View File

@ -25,7 +25,7 @@
- Select IDE Tools - Flash Size: "1M (no SPIFFS)"
====================================================*/
#define VERSION 0x050C0002 // 5.12.0b
#define VERSION 0x050C0003 // 5.12.0c
// Location specific includes
#include <core_version.h> // Arduino_Esp8266 version information (ARDUINO_ESP8266_RELEASE and ARDUINO_ESP8266_RELEASE_2_3_0)

View File

@ -49,8 +49,9 @@ void WifiWpsStatusCallback(wps_cb_status status);
#define USE_VEML6070 // Add I2C code for VEML6070 sensor (+0k5 code)
#define USE_TSL2561 // Add I2C code for TSL2561 sensor using library Adafruit TSL2561 Arduino (+1k2 code)
#define USE_ADS1115 // Add I2C code for ADS1115 16 bit A/D converter based on Adafruit ADS1x15 library (no library needed) (+0k7 code)
// #define USE_ADS1115_I2CDEV // Add I2C code for ADS1115 16 bit A/D converter using library i2cdevlib-Core and i2cdevlib-ADS1115 (+2k code)
//#define USE_ADS1115_I2CDEV // Add I2C code for ADS1115 16 bit A/D converter using library i2cdevlib-Core and i2cdevlib-ADS1115 (+2k code)
#define USE_INA219 // Add I2C code for INA219 Low voltage and current sensor (+1k code)
#define USE_MGS // Add I2C code for Xadow and Grove Mutichannel Gas sensor using library Multichannel_Gas_Sensor (+10k code)
#define USE_MHZ19 // Add support for MH-Z19 CO2 sensor (+2k code)
#define USE_SENSEAIR // Add support for SenseAir K30, K70 and S8 CO2 sensor (+2k3 code)
#ifndef CO2_LOW

View File

@ -17,8 +17,8 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
IPAddress syslog_host_addr; // Syslog host IP address
unsigned long syslog_host_refresh = 0;
IPAddress syslog_host_addr; // Syslog host IP address
uint32_t syslog_host_hash = 0; // Syslog host name hash
/*********************************************************************************************\
* Watchdog extension (https://github.com/esp8266/Arduino/issues/1532)
@ -414,6 +414,15 @@ void SetSerialBaudrate(int baudrate)
}
}
uint32_t GetHash(const char *buffer, size_t size)
{
uint32_t hash = 0;
for (uint16_t i = 0; i <= size; i++) {
hash += (uint8_t)*buffer++ * (i +1);
}
return hash;
}
/*********************************************************************************************\
* Wifi
\*********************************************************************************************/
@ -1245,7 +1254,7 @@ void RtcSecond()
uint32_t dstoffset;
TIME_T tmpTime;
if ((ntp_sync_minute > 59) && (3 == RtcTime.minute)) ntp_sync_minute = 1; // If sync prepare for a new cycle
if ((ntp_sync_minute > 59) && (RtcTime.minute > 2)) ntp_sync_minute = 1; // If sync prepare for a new cycle
uint8_t offset = (uptime < 30) ? RtcTime.second : (((ESP.getChipId() & 0xF) * 3) + 3) ; // First try ASAP to sync. If fails try once every 60 seconds based on chip id
if ((WL_CONNECTED == WiFi.status()) && (offset == RtcTime.second) && ((RtcTime.year < 2016) || (ntp_sync_minute == RtcTime.minute))) {
ntp_time = sntp_get_current_timestamp();
@ -1396,9 +1405,9 @@ void Syslog()
// Destroys log_data
char syslog_preamble[64]; // Hostname + Id
if ((static_cast<uint32_t>(syslog_host_addr) == 0) || ((millis() - syslog_host_refresh) > 60000)) {
WiFi.hostByName(Settings.syslog_host, syslog_host_addr);
syslog_host_refresh = millis();
if (syslog_host_hash != GetHash(Settings.syslog_host, strlen(Settings.syslog_host))) {
syslog_host_hash = GetHash(Settings.syslog_host, strlen(Settings.syslog_host));
WiFi.hostByName(Settings.syslog_host, syslog_host_addr); // If sleep enabled this might result in exception so try to do it once using hash
}
if (PortUdp.beginPacket(syslog_host_addr, Settings.syslog_port)) {
snprintf_P(syslog_preamble, sizeof(syslog_preamble), PSTR("%s ESP-"), my_hostname);

View File

@ -183,16 +183,18 @@
#define USE_I2C // I2C using library wire (+10k code, 0k2 mem, 124 iram)
#ifdef USE_I2C
#define USE_SHT // Add I2C emulating code for SHT1X sensor (+1k4 code)
#define USE_SHT3X // Add I2C code for SHT3x sensor (+0k6 code)
#define USE_SHT3X // Add I2C code for SHT3x or SHTC3 sensor (+0k7 code)
#define USE_HTU // Add I2C code for HTU21/SI7013/SI7020/SI7021 sensor (+1k5 code)
#define USE_BMP // Add I2C code for BMP085/BMP180/BMP280/BME280 sensor (+4k code)
// #define USE_BME680 // Add additional support for BME680 sensor using Adafruit Sensor and BME680 libraries (+6k code)
#define USE_BH1750 // Add I2C code for BH1750 sensor (+0k5 code)
// #define USE_VEML6070 // Add I2C code for VEML6070 sensor (+0k5 code)
// #define USE_TSL2561 // Add I2C code for TSL2561 sensor using library Adafruit TSL2561 Arduino (+1k2 code)
// #define USE_TSL2561 // Add I2C code for TSL2561 sensor using library Joba_Tsl2561 (+2k3 code)
// #define USE_ADS1115 // Add I2C code for ADS1115 16 bit A/D converter based on Adafruit ADS1x15 library (no library needed) (+0k7 code)
// #define USE_ADS1115_I2CDEV // Add I2C code for ADS1115 16 bit A/D converter using library i2cdevlib-Core and i2cdevlib-ADS1115 (+2k code)
// #define USE_INA219 // Add I2C code for INA219 Low voltage and current sensor (+1k code)
// #define USE_MGS // Add I2C code for Xadow and Grove Mutichannel Gas sensor using library Multichannel_Gas_Sensor (+10k code)
#define MGS_SENSOR_ADDR 0x04 // Default Mutichannel Gas sensor i2c address
#endif // USE_I2C
// -- Serial sensors ------------------------------

View File

@ -109,15 +109,15 @@ boolean SonoffBridgeSerialInput()
{
// iTead Rf Universal Transceiver Module Serial Protocol Version 1.0 (20170420)
if (sonoff_bridge_receive_flag) {
if (!((serial_in_byte_counter == 0) && (serial_in_byte == 0))) { // Skip leading 0
if (!serial_in_byte_counter) {
if (!((0 == serial_in_byte_counter) && (0 == serial_in_byte))) { // Skip leading 0
if (0 == serial_in_byte_counter) {
sonoff_bridge_expected_bytes = 2; // 0xA0, 0xA1, 0xA2
if (serial_in_byte >= 0xA3) {
sonoff_bridge_expected_bytes = 11; // 0xA3, 0xA4, 0xA5
}
}
serial_in_buffer[serial_in_byte_counter++] = serial_in_byte;
if ((sonoff_bridge_expected_bytes == serial_in_byte_counter) && (0x55 == serial_in_byte)) { // 0x55 - End of text
if ((sonoff_bridge_expected_bytes == serial_in_byte_counter) && (0x55 == serial_in_byte)) { // 0x55 - End of text
SonoffBridgeReceived();
sonoff_bridge_receive_flag = 0;
return 1;
@ -252,7 +252,7 @@ boolean SonoffBridgeCommand()
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, XdrvMailbox.index, D_JSON_START_LEARNING);
}
else if (3 == XdrvMailbox.payload) { // Unlearn RF data
Settings.rf_code[XdrvMailbox.index][0] = 0;
Settings.rf_code[XdrvMailbox.index][0] = 0; // Reset sync_time MSB
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, XdrvMailbox.index, D_JSON_SET_TO_DEFAULT);
}
else if (4 == XdrvMailbox.payload) { // Save RF data provided by RFSync, RfLow, RfHigh and last RfCode
@ -263,8 +263,23 @@ boolean SonoffBridgeCommand()
Settings.rf_code[XdrvMailbox.index][7] = (sonoff_bridge_last_send_code >> 8) & 0xff;
Settings.rf_code[XdrvMailbox.index][8] = sonoff_bridge_last_send_code & 0xff;
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, XdrvMailbox.index, D_JSON_SAVED);
} else if (5 == XdrvMailbox.payload) { // Show default or learned RF data
uint8_t key = XdrvMailbox.index;
uint8_t index = (0 == Settings.rf_code[key][0]) ? 0 : key; // Use default if sync_time MSB = 0
uint16_t sync_time = (Settings.rf_code[index][0] << 8) | Settings.rf_code[index][1];
uint16_t low_time = (Settings.rf_code[index][2] << 8) | Settings.rf_code[index][3];
uint16_t high_time = (Settings.rf_code[index][4] << 8) | Settings.rf_code[index][5];
uint32_t code = (Settings.rf_code[index][6] << 16) | (Settings.rf_code[index][7] << 8);
if (0 == index) {
key--;
code |= (uint8_t)((0x10 << (key >> 2)) | (1 << (key & 3)));
} else {
code |= Settings.rf_code[index][8];
}
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"%s%d\":{\"" D_JSON_SYNC "\":%d,\"" D_JSON_LOW "\":%d,\"" D_JSON_HIGH "\":%d,\"" D_JSON_DATA "\":\"%06X\"}}"),
command, XdrvMailbox.index, sync_time, low_time, high_time, code);
} else {
if ((1 == XdrvMailbox.payload) || (0 == Settings.rf_code[XdrvMailbox.index][0])) {
if ((1 == XdrvMailbox.payload) || (0 == Settings.rf_code[XdrvMailbox.index][0])) { // Test sync_time MSB
SonoffBridgeSend(0, XdrvMailbox.index); // Send default RF data
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, XdrvMailbox.index, D_JSON_DEFAULT_SENT);
} else {

View File

@ -20,17 +20,21 @@
#ifdef USE_I2C
#ifdef USE_SHT3X
/*********************************************************************************************\
* SHT3X - Temperature and Humidy
* SHT3X and SHTC3 - Temperature and Humidy
*
* I2C Address: 0x44 or 0x45
* I2C Address: 0x44, 0x45 or 0x70 (SHTC3)
\*********************************************************************************************/
#define SHT3X_ADDR_GND 0x44 // address pin low (GND)
#define SHT3X_ADDR_VDD 0x45 // address pin high (VDD)
#define SHTC3_ADDR 0x70 // address for shtc3 sensor
const char kShtTypes[] PROGMEM = "SHT3X|SHT3X|SHTC3";
uint8_t sht3x_type = 0;
uint8_t sht3x_address;
uint8_t sht3x_addresses[] = { SHT3X_ADDR_GND, SHT3X_ADDR_VDD };
uint8_t sht3x_addresses[] = { SHT3X_ADDR_GND, SHT3X_ADDR_VDD, SHTC3_ADDR };
char sht3x_types[6];
bool Sht3xRead(float &t, float &h)
{
@ -40,8 +44,17 @@ bool Sht3xRead(float &t, float &h)
h = NAN;
Wire.beginTransmission(sht3x_address);
Wire.write(0x2C); // Enable clock stretching
Wire.write(0x06); // High repeatability
if (SHTC3_ADDR == sht3x_address) {
Wire.write(0x35); // Wake from
Wire.write(0x17); // sleep
Wire.endTransmission();
Wire.beginTransmission(sht3x_address);
Wire.write(0x78); // Dissable clock stretching ( I don't think that wire library support clock stretching )
Wire.write(0x66); // High resolution
} else {
Wire.write(0x2C); // Enable clock stretching
Wire.write(0x06); // High repeatability
}
if (Wire.endTransmission() != 0) { // Stop I2C transmission
return false;
}
@ -69,7 +82,8 @@ void Sht3xDetect()
for (byte i = 0; i < sizeof(sht3x_addresses); i++) {
sht3x_address = sht3x_addresses[i];
if (Sht3xRead(t, h)) {
snprintf_P(log_data, sizeof(log_data), S_LOG_I2C_FOUND_AT, "SHT3X", sht3x_address);
GetTextIndexed(sht3x_types, sizeof(sht3x_types), i, kShtTypes);
snprintf_P(log_data, sizeof(log_data), S_LOG_I2C_FOUND_AT, sht3x_types, htu_address);
AddLog(LOG_LEVEL_DEBUG);
return;
}
@ -89,14 +103,14 @@ void Sht3xShow(boolean json)
dtostrfd(h, Settings.flag2.humidity_resolution, humidity);
if (json) {
snprintf_P(mqtt_data, sizeof(mqtt_data), JSON_SNS_TEMPHUM, mqtt_data, "SHT3X", temperature, humidity);
snprintf_P(mqtt_data, sizeof(mqtt_data), JSON_SNS_TEMPHUM, mqtt_data, sht3x_types, temperature, humidity);
#ifdef USE_DOMOTICZ
DomoticzTempHumSensor(temperature, humidity);
#endif // USE_DOMOTICZ
#ifdef USE_WEBSERVER
} else {
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_TEMP, mqtt_data, "SHT3X", temperature, TempUnit());
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_HUM, mqtt_data, "SHT3X", humidity);
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_TEMP, mqtt_data, sht3x_types, temperature, TempUnit());
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_HUM, mqtt_data, sht3x_types, humidity);
#endif // USE_WEBSERVER
}
}

View File

@ -1,7 +1,7 @@
/*
xsns_16_tsl2561.ino - TSL2561 light sensor support for Sonoff-Tasmota
Copyright (C) 2018 Theo Arends
Copyright (C) 2018 Theo Arends and Joachim Banzhaf
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@ -24,75 +24,62 @@
*
* I2C Addresses: 0x29 (low), 0x39 (float) or 0x49 (high)
*
* Using library https://github.com/adafruit/TSL2561-Arduino-Library
* Using library https://github.com/joba-1/Joba_Tsl2561
\*********************************************************************************************/
#include <TSL2561.h>
#include <Tsl2561Util.h>
uint8_t tsl2561_address;
uint8_t tsl2561_addresses[] = { TSL2561_ADDR_LOW, TSL2561_ADDR_FLOAT, TSL2561_ADDR_HIGH };
//TSL2561 tsl(TSL2561_ADDR_FLOAT);
TSL2561 *tsl = 0;
Tsl2561 Tsl(Wire);
void Tsl2561Detect()
{
if (tsl) {
return;
}
for (byte i = 0; i < sizeof(tsl2561_addresses); i++) {
tsl2561_address = tsl2561_addresses[i];
if (I2cDevice(tsl2561_address)) {
tsl = new TSL2561(tsl2561_address);
if (tsl->begin()) {
tsl->setGain(TSL2561_GAIN_16X);
tsl->setTiming(TSL2561_INTEGRATIONTIME_101MS);
snprintf_P(log_data, sizeof(log_data), S_LOG_I2C_FOUND_AT, "TSL2561", tsl2561_address);
AddLog(LOG_LEVEL_DEBUG);
break;
} else {
delete tsl;
tsl = 0;
}
if (!Tsl.available()) {
Tsl.begin();
if (Tsl.available()) {
snprintf_P(log_data, sizeof(log_data), S_LOG_I2C_FOUND_AT, "TSL2561", Tsl.address());
AddLog(LOG_LEVEL_DEBUG);
}
}
}
#ifdef USE_WEBSERVER
const char HTTP_SNS_TSL2561[] PROGMEM =
"%s{s}TSL2561 " D_ILLUMINANCE "{m}%d " D_UNIT_LUX "{e}"; // {s} = <tr><th>, {m} = </th><td>, {e} = </td></tr>
"%s{s}TSL2561 " D_ILLUMINANCE "{m}%u.%03u " D_UNIT_LUX "{e}"; // {s} = <tr><th>, {m} = </th><td>, {e} = </td></tr>
#endif // USE_WEBSERVER
void Tsl2561Show(boolean json)
{
if (tsl) {
union {
uint32_t full;
struct { uint16_t both, ir; };
} light;
light.full = tsl->getFullLuminosity();
uint32_t illuminance = 0;
if ((light.full == 0 || light.full == 0xffffffff)) {
if (!I2cDevice(tsl2561_address)) {
delete tsl;
tsl = 0;
}
} else {
illuminance = tsl->calculateLux(light.both, light.ir);
}
snprintf(log_data, sizeof(log_data), PSTR(D_ILLUMINANCE " 0x%08lx = b 0x%04x, i 0x%04x -> %lu " D_UNIT_LUX), light.full, light.both, light.ir, illuminance);
AddLog(LOG_LEVEL_DEBUG);
uint8_t id;
bool gain;
Tsl2561::exposure_t exposure;
uint16_t scaledFull, scaledIr;
uint32_t full, ir;
uint32_t milliLux;
if (json) {
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"TSL2561\":{\"" D_JSON_ILLUMINANCE "\":%d}"), mqtt_data, illuminance);
if (Tsl.available()) {
if (Tsl.on()) {
if( Tsl.id(id)
&& Tsl2561Util::autoGain(Tsl, gain, exposure, scaledFull, scaledIr)
&& Tsl2561Util::normalizedLuminosity(gain, exposure, full = scaledFull, ir = scaledIr)
&& Tsl2561Util::milliLux(full, ir, milliLux, Tsl2561::packageCS(id))) {
snprintf_P(log_data, sizeof(log_data), PSTR(D_ILLUMINANCE " g:%d, e:%d, f:%u, i:%u -> %u.%03u " D_UNIT_LUX),
gain, exposure, full, ir, milliLux/1000, milliLux%1000);
AddLog(LOG_LEVEL_DEBUG);
if (json) {
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"TSL2561\":{\"" D_JSON_ILLUMINANCE "\":%u.%03u}"),
mqtt_data, milliLux/1000, milliLux%1000);
#ifdef USE_DOMOTICZ
DomoticzSensor(DZ_ILLUMINANCE, illuminance);
DomoticzSensor(DZ_ILLUMINANCE, (milliLux+500)/1000);
#endif // USE_DOMOTICZ
#ifdef USE_WEBSERVER
} else {
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_TSL2561, mqtt_data, illuminance);
} else {
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_TSL2561, mqtt_data, milliLux/1000, milliLux%1000);
#endif // USE_WEBSERVER
}
}
Tsl.off();
}
}
}
@ -125,5 +112,5 @@ boolean Xsns16(byte function)
return result;
}
#endif // USE_TSL2561
#endif // USE_I2C
#endif // USE_TSL2561_JOBA
#endif // USE_I2C

121
sonoff/xsns_19_mgs.ino Normal file
View File

@ -0,0 +1,121 @@
/*
xsns_19_mgs.ino - Xadow and Grove Mutichannel Gas sensor support for Sonoff-Tasmota
Copyright (C) 2018 Palich2000 and Theo Arends
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef USE_I2C
#ifdef USE_MGS
/*********************************************************************************************\
* Grove - Multichannel Gas Sensor
* http://wiki.seeed.cc/Grove-Multichannel_Gas_Sensor/
*
* https://github.com/Seeed-Studio/Mutichannel_Gas_Sensor.git
\*********************************************************************************************/
#ifndef MGS_SENSOR_ADDR
#define MGS_SENSOR_ADDR 0x04 // Default Mutichannel Gas sensor i2c address
#endif
#include "MutichannelGasSensor.h"
void MGSInit() {
gas.begin(MGS_SENSOR_ADDR);
}
boolean MGSPrepare()
{
gas.begin(MGS_SENSOR_ADDR);
if (!gas.isError()) {
snprintf_P(log_data, sizeof(log_data), S_LOG_I2C_FOUND_AT, "MultiGasSensor", MGS_SENSOR_ADDR);
AddLog(LOG_LEVEL_DEBUG);
return true;
} else {
return false;
}
}
char* measure_gas(int gas_type, char* buffer)
{
float f = gas.calcGas(gas_type);
dtostrfd(f, 2, buffer);
return buffer;
}
#ifdef USE_WEBSERVER
const char HTTP_MGS_GAS[] PROGMEM = "%s{s}MGS %s{m}%s " D_UNIT_PARTS_PER_MILLION "{e}"; // {s} = <tr><th>, {m} = </th><td>, {e} = </td></tr>
#endif // USE_WEBSERVER
void MGSShow(boolean json)
{
char buffer[25];
if (json) {
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"MGS\":{\"NH3\":%s"), mqtt_data, measure_gas(NH3, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"CO\":%s"), mqtt_data, measure_gas(CO, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"NO2\":%s"), mqtt_data, measure_gas(NO2, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"C3H8\":%s"), mqtt_data, measure_gas(C3H8, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"C4H10\":%s"), mqtt_data, measure_gas(C4H10, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"CH4\":%s"), mqtt_data, measure_gas(GAS_CH4, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"H2\":%s"), mqtt_data, measure_gas(H2, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"C2H5OH\":%s}"), mqtt_data, measure_gas(C2H5OH, buffer));
#ifdef USE_WEBSERVER
} else {
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "NH3", measure_gas(NH3, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "CO", measure_gas(CO, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "NO2", measure_gas(NO2, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "C3H8", measure_gas(C3H8, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "C4H10", measure_gas(C4H10, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "CH4", measure_gas(GAS_CH4, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "H2", measure_gas(H2, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "C2H5OH", measure_gas(C2H5OH, buffer));
#endif // USE_WEBSERVER
}
}
/*********************************************************************************************\
* Interface
\*********************************************************************************************/
#define XSNS_19
boolean Xsns19(byte function)
{
boolean result = false;
static int detected = false;
if (i2c_flg) {
switch (function) {
case FUNC_INIT:
// MGSInit();
break;
case FUNC_PREP_BEFORE_TELEPERIOD:
detected = MGSPrepare();
break;
case FUNC_JSON_APPEND:
if (detected) MGSShow(1);
break;
#ifdef USE_WEBSERVER
case FUNC_WEB_APPEND:
if (detected) MGSShow(0);
break;
#endif // USE_WEBSERVER
}
}
return result;
}
#endif // USE_MGS
#endif // USE_I2C