pax_global_header 0000666 0000000 0000000 00000000064 14206137734 0014521 g ustar 00root root 0000000 0000000 52 comment=86f353e8dc0c66015e18cf5a40c25dc7fc347a7a
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ 0000775 0000000 0000000 00000000000 14206137734 0021513 5 ustar 00root root 0000000 0000000 ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/.gitignore 0000664 0000000 0000000 00000000157 14206137734 0023506 0 ustar 00root root 0000000 0000000 .pioenvs
.pio/libdeps
.pio/build
.vscode
*.ino.cpp
config.h
config.hftstuttgart.h
.project
.cproject
.settings
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/.gitlab-ci.yml 0000664 0000000 0000000 00000000477 14206137734 0024157 0 ustar 00root root 0000000 0000000 image: python:3.6
stages:
- build
before_script:
- "pip install -U platformio"
- "cp ampel-firmware/config.public.h ampel-firmware/config.h"
job:
stage: build
script: "platformio run"
artifacts:
paths:
- .pio/build/esp32/firmware.bin
- .pio/build/esp8266/firmware.bin
expire_in: never
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/CHANGELOG.md 0000664 0000000 0000000 00000001773 14206137734 0023334 0 ustar 00root root 0000000 0000000 # Change Log
## [v0.2.2](https://transfer.hft-stuttgart.de/gitlab/co2ampel/ampel-firmware/-/releases/v0.2.2) 2021/10/01
* MAC address is now shown at startup and via HTTP
## [v0.2.1](https://transfer.hft-stuttgart.de/gitlab/co2ampel/ampel-firmware/-/releases/v0.2.1) 2021/06/06
* BUGFIX: Sensor would keep on calibrating after successful calibration.
## [v0.2.0](https://transfer.hft-stuttgart.de/gitlab/co2ampel/ampel-firmware/-/releases/v0.2.0) 2021/06/06
* BUGFIX: Calibration was not applied correctly (Thanks Michael Käppler for bug finding & fixing!)
* MQTT works again for ESP32 (board needs to be updated in Arduino IDE/PlaftormIO)
## [v0.1.0](https://transfer.hft-stuttgart.de/gitlab/co2ampel/ampel-firmware/-/releases/v0.1.0) 2021/05/19
* More stable calibration, with 10s timestep
* Allow commands from Serial/MQTT/Webserver
* Many bugfixes
## [v0.0.9](https://transfer.hft-stuttgart.de/gitlab/co2ampel/ampel-firmware/-/releases/v0.0.9) 2020/12/15
* First CO2 Ampel release.
* Basic functionality
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/LICENSE 0000664 0000000 0000000 00000104515 14206137734 0022526 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
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.
Copyright (C)
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 .
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:
Copyright (C)
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
.
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
.
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/Makefile 0000664 0000000 0000000 00000000447 14206137734 0023160 0 ustar 00root root 0000000 0000000 all:
pio -f -c vim run
upload:
pio -f -c vim run --target upload -e $(board)
clean:
pio -f -c vim run --target clean
program:
pio -f -c vim run --target program
uploadfs:
pio -f -c vim run --target uploadfs
update:
pio -f -c vim update
monitor:
pio device monitor --filter colorize
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/README.md 0000664 0000000 0000000 00000015437 14206137734 0023004 0 ustar 00root root 0000000 0000000 # CO2 Ampel
*CO2 Ampel* is an open-source project, written in C++ for [ESP8266](https://en.wikipedia.org/wiki/ESP8266) or [ESP32](https://en.wikipedia.org/wiki/ESP32).
It measures the current CO2 concentration (in ppm), and displays it on an LED ring.
The room should be ventilated as soon as one LED turns red.
## Ampel web-conf
Ampel-firmware + [IotWebConf](https://github.com/prampec/IotWebConf).
This is beta software, and bugs are expected! There is not much free RAM left on ESP8266, so the ESP might crash randomly. :-/
* You probably need to update `config.h`. There's a new template in `config.public.h`.
* Every parameter can be set in the web-configuration, so you don't have to modify `config.h` once it's been updated.
* Flash
* Start the *Ampel*
* It should blink turquoise, to indicate *Access Point* mode
* Connect with a laptop/smartphone to ESPxxxxxx WiFi.
* Open a browser, it should bring you to the *Ampel* web-page.
* The usual web-page will be shown. You can click on "Configuration".
* You'll have to set an *Ampel* password with at least 8 characters.
* You can set WiFi SSID + Password if you want. It will then try to connect if you disconnect from the *Access Point*.
* If you don't specify SSID + Password, the *Ampel* will simply stay in *Access Point* mode.
* The *Ampel* password will be required if a connection fails, and the *Access Point* starts again.
* The *Ampel* password will be needed (with user 'admin') to connect to the web-page once the *Ampel* is connected to WiFi.
* It might be necessary to reset the *Ampel* after changing important parameters.
* You can rename the *Ampel*. This name will be used instead of ESPxxxxxx for CSV files and the mDNS address. You'll get a new CSV file after renaming, which can be convenient, e.g. to indicate at which location the measurements were made.
* If you forgot the password, you can send `reset_config` as command, and `reset` the ampel.
* If you disabled WiFi, you can enable it again with `wifi 1`.
* It's also possible to specify WiFi SSID and password in the console, with `ssid wifi_ssid_here` and `pwd wifi_password_here` commands.
* You can enable CSV by clicking on "+CSV", or disable it by clicking on "Disable CSV".
* The same applies to MQTT and LoRaWAN.
* If you disable a set, the parameters are still saved, and will appear again once the service is enabled.
## Features
The *CO2 Ampel* can:
* Display CO2 concentration on LED ring.
* Allow calibration.
* Get current time over [NTP](https://en.wikipedia.org/wiki/Network_Time_Protocol)
* Send data over [MQTT](https://en.wikipedia.org/wiki/MQTT).
* Send data over [LoRaWAN](https://en.wikipedia.org/wiki/LoRa#LoRaWAN).
* Display measurements and configuration on a small website.
* Log data to a [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) file, directly on the ESP flash memory.
* Accept many interactive commands.
## Hardware Requirements
* [ESP8266](https://en.wikipedia.org/wiki/ESP8266) or [ESP32](https://en.wikipedia.org/wiki/ESP32) microcontroller (this project has been tested with *ESP8266 ESP-12 WIFI* and *TTGO ESP32 SX1276 LoRa*)
* [Sensirion SCD30](https://www.sensirion.com/en/environmental-sensors/carbon-dioxide-sensors/carbon-dioxide-sensors-co2/) "Sensor Module for HVAC and Indoor Air Quality Applications"
* [NeoPixel Ring - 12](https://www.adafruit.com/product/1643), or [NeoPixel Ring - 16](https://www.adafruit.com/product/1463) (experimental)
See the [documentation](https://transfer.hft-stuttgart.de/gitlab/co2ampel/ampel-documentation) for more info.
## Software Requirements
* [PlatformIO](https://platformio.org/)
or
* [Arduino IDE](https://www.arduino.cc/en/software)
## Installation
* If `config.h` does not exist, copy it from `config.public.h`
* Modify `config.h`, e.g. for measurement time-steps, WiFi access, MQTT, NTP and web-server.
### PlatformIO
PlatformIO can be run from [VSCODE](https://platformio.org/install/ide?install=vscode), [Eclipse CDT](https://www.eclipse.org/cdt/) or console:
```bash
make upload board=esp8266 && make monitor # For ESP8266
```
```bash
make upload board=esp32 && make monitor # For ESP32
```
### Arduino IDE
* All the libraries are included in this repository. No need to install anything via *Library Manager*.
* Add your board to the [board manager](https://github.com/esp8266/Arduino#installing-with-boards-manager). Either ESP8266:
http://arduino.esp8266.com/stable/package_esp8266com_index.json
or ESP32:
https://dl.espressif.com/dl/package_esp32_index.json
* Choose the correct board in *Tools > Board > ...*
* Choose the correct *Flash size* (e.g. "Flash Size : 4MB (1MB FS, OTA:~1019kB)" for *ESP8266 ESP-12 WIFI*)
* *Verify*
* *Upload*
* *Tools > Serial Monitor*
## Available commands
In Arduino IDE *Serial Monitor* or PlatformIO *Monitor*, type `help` + Enter in order to list the available commands:
* `ap 0/1` (Disables/enables access point).
* `auto_calibrate 0/1` (Disables/enables autocalibration).
* `calibrate 600` (Starts calibration process, to given ppm).
* `calibrate` (Starts calibration process).
* `calibrate! 600` (Calibrates right now, to given ppm).
* `co2 1500` (Sets CO2 level, for debugging).
* `color 0xFF0015` (Shows color, specified as RGB, for debugging).
* `csv 60` (Sets CSV writing interval, in s).
* `format_filesystem` (Deletes the whole filesystem).
* `free` (Displays available heap space).
* `led 0/1` (Turns LEDs on/off).
* `local_ip` (Displays local IP and current SSID).
* `lora 300` (Sets LoRaWAN sending interval, in s).
* `mqtt 60` (Sets MQTT sending interval, in s).
* `pwd abc` (Sets WiFi password to 'abc').
* `reset` (Restarts the ESP).
* `reset_config` (Resets the complete IotWeb config).
* `reset_scd` (Resets SCD30).
* `save_config` (Saves the config to EEPROM).
* `send_local_ip` (Sends local IP and SSID via MQTT. Can be useful to find sensor).
* `set_time 1618829570` (Sets time to the given UNIX time).
* `show_csv` (Displays the complete CSV file on Serial).
* `ssid name` (Sets SSID to 'name').
* `timer 30` (Sets measurement interval, in s).
* `wifi 0/1` (Turns Wifi on/off).
* `wifi_scan` (Scans available WiFi networks).
The commands can be sent via the Serial interface, from the webpage or via MQTT.
## Authors
* Eric Duminil (HfT Stuttgart)
* Robert Otto (HfT Stuttgart)
* Myriam Guedey (HfT Stuttgart)
* Tobias Gabriel Erhart (HfT Stuttgart)
* Jonas Stave (HfT Stuttgart)
* Michael Käppler
## Contributing
* Merge requests are welcome, and should be based on the `develop` branch.
* The `develop` branch gets merged into the `master` once it has been sufficiently tested.
* For major changes, please open an issue first to discuss what you would like to change.
## License
Copyright © 2021, [HfT Stuttgart](https://www.hft-stuttgart.de/)
[GPLv3](https://choosealicense.com/licenses/gpl-3.0/)
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/ 0000775 0000000 0000000 00000000000 14206137734 0024423 5 ustar 00root root 0000000 0000000 ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/ampel-firmware.h 0000664 0000000 0000000 00000001266 14206137734 0027511 0 ustar 00root root 0000000 0000000 #ifndef AMPEL_H_INCLUDED
#define AMPEL_H_INCLUDED
/*****************************************************************
* Libraries *
*****************************************************************/
//NOTE: Too many headers. Move them to include/ folder?
#include "web_config.h" // Needed for offline config too.
#include "csv_writer.h"
#include "wifi_util.h"
#include "mqtt.h"
#include "web_server.h"
#include "lorawan.h"
#include "util.h"
#include "ntp.h"
#include "sensor_console.h"
#include "co2_sensor.h"
#include "led_effects.h"
void wifiConnected();
void wifiFailed();
void keepServicesAlive();
void checkFlashButton();
#endif
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/ampel-firmware.ino 0000664 0000000 0000000 00000017431 14206137734 0030050 0 ustar 00root root 0000000 0000000 /***
* ____ ___ ____ _ _
* / ___/ _ \___ \ / \ _ __ ___ _ __ ___| |
* | | | | | |__) | / _ \ | '_ ` _ \| '_ \ / _ \ |
* | |__| |_| / __/ / ___ \| | | | | | |_) | __/ |
* \____\___/_____| /_/__ \_\_| |_| |_| .__/ \___|_| _
* | | | |/ _|_ _| / ___|| |_ _ _| |_| |_ __ _ __ _ _ __| |_
* | |_| | |_ | | \___ \| __| | | | __| __/ _` |/ _` | '__| __|
* | _ | _| | | ___) | |_| |_| | |_| || (_| | (_| | | | |_
* |_| |_|_| |_| |____/ \__|\__,_|\__|\__\__, |\__,_|_| \__|
* |___/
*/
#include "ampel-firmware.h"
/*****************************************************************
* GPL License *
*****************************************************************/
/*
* This file is part of the "CO2 Ampel" project ( https://transfer.hft-stuttgart.de/gitlab/co2ampel and
* https://transfer.hft-stuttgart.de/gitlab/co2ampel/ampel-firmware )
* Copyright (c) 2020 HfT Stuttgart.
*
* 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, version 3.
*
* 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 .
*/
/*****************************************************************
* Authors *
*****************************************************************/
/*
* Eric Duminil
* Robert Otto
* Myriam Guedey
* Tobias Gabriel Erhart
* Jonas Stave
* Michael Käppler
*/
/*****************************************************************
* Configuration *
*****************************************************************/
/*
* Please define settings in 'config.h'.
* There's an example config file called 'config.example.h'.
* You can copy 'config.public.h' (stored in Git) to 'config.h' (not stored in Git),
* and define your credentials and parameters in 'config.h'.
*/
/*****************************************************************
* Setup *
*****************************************************************/
void setup() {
led_effects::setupOnBoardLED();
led_effects::onBoardLEDOff();
Serial.begin(config::bauds);
web_config::initialize();
web_config::setWifiConnectionCallback(wifiConnected);
web_config::setWifiFailCallback(wifiFailed);
pinMode(0, INPUT); // Flash button (used for forced calibration)
Serial.println();
Serial.print(F("Sensor ID: "));
Serial.println(ampel.sensorId);
Serial.print(F("Name : "));
Serial.println(config::ampel_name());
Serial.print(F("MAC : "));
Serial.println(ampel.macAddress);
Serial.print(F("Board : "));
Serial.println(ampel.board);
Serial.print(F("Firmware : "));
Serial.println(ampel.version);
led_effects::setupRing();
sensor::initialize();
csv_writer::initialize(config::ampel_name());
ntp::initialize();
if (config::is_wifi_on) {
wifi::defineCommands();
web_server::definePages();
wifi::tryConnection();
}
#if defined(ESP32)
if (config::is_lorawan_active()) {
lorawan::initialize();
}
#endif
}
/*****************************************************************
* Main loop *
*****************************************************************/
void loop() {
#if defined(ESP32)
if (config::is_lorawan_active()) {
//LMIC Library seems to be very sensitive to timing issues, so run it first.
lorawan::process();
if (lorawan::waiting_for_confirmation) {
// If node is waiting for join confirmation from Gateway, nothing else should run.
return;
}
}
#endif
//NOTE: Loop should never take more than 1000ms. Split in smaller methods and logic if needed.
//NOTE: Only use millis() for duration comparison, not timestamps comparison. Otherwise, problems happen when millis roll over.
uint32_t t0 = millis();
keepServicesAlive();
// Short press for night mode, Long press for calibration.
checkFlashButton();
sensor_console::checkSerialInput();
if (sensor::processData()) {
if (config::is_csv_active()) {
csv_writer::logIfTimeHasCome(sensor::timestamp, sensor::co2, sensor::temperature, sensor::humidity);
}
if (config::is_wifi_on && config::is_mqtt_active()) {
mqtt::publishIfTimeHasCome(sensor::timestamp, sensor::co2, sensor::temperature, sensor::humidity);
}
#if defined(ESP32)
if (config::is_lorawan_active()) {
lorawan::preparePayloadIfTimeHasCome(sensor::co2, sensor::temperature, sensor::humidity);
}
#endif
}
uint32_t duration = millis() - t0;
if (duration > ampel.max_loop_duration) {
ampel.max_loop_duration = duration;
Serial.print(F("Debug - Max loop duration : "));
Serial.print(ampel.max_loop_duration);
Serial.println(F(" ms."));
}
}
/*****************************************************************
* Callbacks *
*****************************************************************/
void wifiConnected() {
led_effects::showKITTWheel(color::green);
Serial.println();
Serial.print(F("WiFi - Connected to "));
Serial.print(WiFi.SSID());
Serial.print(F(", IP address: "));
IPAddress address = WiFi.localIP();
snprintf(wifi::local_ip, sizeof(wifi::local_ip), "%d.%d.%d.%d", address[0], address[1], address[2], address[3]);
Serial.println(wifi::local_ip);
ntp::connect();
if (config::is_mqtt_active()) {
mqtt::initialize(ampel.sensorId);
}
Serial.print(F("You can access this sensor via http://"));
Serial.print(config::ampel_name());
Serial.print(F(".local (might be unstable) or http://"));
Serial.println(WiFi.localIP());
}
void wifiFailed() {
// Ampel will go back to Access Point mode for AP_TIMEOUT seconds, and try connection again after
Serial.print(F("WiFi - Could not connect to "));
Serial.println(config::selected_ssid());
led_effects::showKITTWheel(color::red);
}
/*****************************************************************
* Helper functions *
*****************************************************************/
/**
* Checks if flash button has been pressed:
* If not, do nothing.
* If short press, toggle LED display.
* If long press, start calibration process.
*/
void checkFlashButton() {
if (!digitalRead(0)) { // Button has been pressed
led_effects::onBoardLEDOn();
delay(300);
if (digitalRead(0)) {
Serial.println(F("Flash has been pressed for a short time. Should toggle night mode."));
led_effects::toggleNightMode();
//NOTE: Start Access Point instead?
} else {
Serial.println(F("Flash has been pressed for a long time. Keep it pressed for calibration."));
if (led_effects::countdownToZero()) {
Serial.println(F("You can now release the button."));
sensor::startCalibrationProcess();
led_effects::showKITTWheel(color::red, 2);
}
}
led_effects::onBoardLEDOff();
}
}
void keepServicesAlive() {
if (config::is_wifi_on) {
web_config::update();
if (wifi::connected()) {
ntp::update(); // NTP client has its own timer. It will connect to NTP server every 60s.
if (config::is_mqtt_active()) {
mqtt::keepConnection(); // MQTT client has its own timer. It will keep alive every 15s.
}
}
}
}
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/co2_sensor.cpp 0000664 0000000 0000000 00000031060 14206137734 0027203 0 ustar 00root root 0000000 0000000 #include "co2_sensor.h"
#include "web_config.h"
#include "ntp.h"
#include "led_effects.h"
#include "sensor_console.h"
#include
// The SCD30 from Sensirion is a high quality Nondispersive Infrared (NDIR) based CO₂ sensor capable of detecting 400 to 10000ppm with an accuracy of ±(30ppm+3%).
// https://github.com/sparkfun/SparkFun_SCD30_Arduino_Library
#include "src/lib/SparkFun_SCD30_Arduino_Library/src/SparkFun_SCD30_Arduino_Library.h" // From: http://librarymanager/All#SparkFun_SCD30
namespace config {
const uint16_t measurement_timestep_bootup = 5; // [s] Measurement timestep during acclimatization.
const uint8_t max_deviation_during_bootup = 20; // [%]
const int8_t max_deviation_during_calibration = 30; // [ppm]
const int16_t timestep_during_calibration = 10; // [s] WARNING: Measurements can be unreliable for timesteps shorter than 10s.
const int8_t stable_measurements_before_calibration = 120 / timestep_during_calibration; // [-] Stable measurements during at least 2 minutes.
const uint16_t co2_alert_threshold = 2000; // [ppm] Display a flashing led ring, if concentration exceeds this value
const bool debug_sensor_states = false; // If true, log state transitions over serial console
}
namespace sensor {
SCD30 scd30;
uint16_t co2 = 0;
float temperature = 0;
float humidity = 0;
char timestamp[23];
int16_t stable_measurements = 0;
/**
* Define sensor states
* BOOTUP -> initial state, until first >0 ppm values are returned
* READY -> sensor does output valid information (> 0 ppm) and no other condition takes place
* NEEDS_CALIBRATION -> sensor measurements are too low (< 250 ppm)
* PREPARE_CALIBRATION_UNSTABLE -> forced calibration was initiated, last measurements were too far apart
* PREPARE_CALIBRATION_STABLE -> forced calibration was initiated, last measurements were close to each others
*/
enum state {
BOOTUP,
READY,
NEEDS_CALIBRATION,
PREPARE_CALIBRATION_UNSTABLE,
PREPARE_CALIBRATION_STABLE
};
const char *state_names[] = {
"BOOTUP",
"READY",
"NEEDS_CALIBRATION",
"PREPARE_CALIBRATION_UNSTABLE",
"PREPARE_CALIBRATION_STABLE" };
state current_state = BOOTUP;
void switchState(state);
void initialize() {
#if defined(ESP8266)
Wire.begin(12, 14); // ESP8266 - D6, D5;
#endif
#if defined(ESP32)
Wire.begin(21, 22); // ESP32
/**
* SCD30 ESP32
* VCC --- 3V3
* GND --- GND
* SCL --- SCL (GPIO22) //NOTE: GPIO3 Would be more convenient (right next to GND)
* SDA --- SDA (GPIO21) //NOTE: GPIO1 would be more convenient (right next to GPO3)
*/
#endif
Serial.println();
scd30.enableDebugging(); // Prints firmware version in the console.
if (!scd30.begin(config::auto_calibrate_sensor)) {
Serial.println(F("ERROR - CO2 sensor not detected. Please check wiring!"));
led_effects::showKITTWheel(color::red, 30);
ESP.restart();
}
// Changes of the SCD30's measurement timestep do not come into effect
// before the next measurement takes place. That means that after a hard reset
// of the ESP the SCD30 sometimes needs a long time until switching back to 2 s
// for acclimatization. Resetting it after startup seems to fix this behaviour.
scd30.reset();
Serial.print(F("Setting temperature offset to -"));
Serial.print(abs(config::temperature_offset));
Serial.println(F(" K."));
scd30.setTemperatureOffset(abs(config::temperature_offset)); // setTemperatureOffset only accepts positive numbers, but shifts the temperature down.
delay(100);
Serial.print(F("Temperature offset is : -"));
Serial.print(scd30.getTemperatureOffset());
Serial.println(F(" K"));
Serial.print(F("Auto-calibration is "));
Serial.println(config::auto_calibrate_sensor ? "ON." : "OFF.");
// SCD30 has its own timer.
//NOTE: The timer seems to be inaccurate, though, possibly depending on voltage. Should it be offset?
Serial.println();
Serial.print(F("Setting SCD30 timestep to "));
Serial.print(config::measurement_timestep_bootup);
Serial.println(F(" s during acclimatization."));
scd30.setMeasurementInterval(config::measurement_timestep_bootup); // [s]
sensor_console::defineIntCommand("co2", setCO2forDebugging, F("1500 (Sets co2 level, for debugging)"));
sensor_console::defineIntCommand("timer", setTimer, F("30 (Sets measurement interval, in s)"));
sensor_console::defineCommand("calibrate", startCalibrationProcess, F("(Starts calibration process)"));
sensor_console::defineIntCommand("calibrate", calibrateSensorToSpecificPPM,
F("600 (Starts calibration process, to given ppm)"));
sensor_console::defineIntCommand("calibrate!", calibrateSensorRightNow,
F("600 (Calibrates right now, to given ppm)"));
sensor_console::defineIntCommand("auto_calibrate", setAutoCalibration, F("0/1 (Disables/enables autocalibration)"));
sensor_console::defineCommand("reset_scd", resetSCD, F("(Resets SCD30)"));
}
bool hasSensorSettled() {
static uint16_t last_co2 = 0;
uint16_t delta;
delta = abs(co2 - last_co2);
last_co2 = co2;
// We assume the sensor has acclimated to the environment if measurements
// change less than a specified percentage of the current value.
return (co2 > 0 && delta < ((uint32_t) co2 * config::max_deviation_during_bootup / 100));
}
bool enoughStableMeasurements() {
static int16_t previous_co2 = 0;
if (co2 > (previous_co2 - config::max_deviation_during_calibration)
&& co2 < (previous_co2 + config::max_deviation_during_calibration)) {
stable_measurements++;
Serial.print(F("Number of stable measurements : "));
Serial.print(stable_measurements);
Serial.print(F(" / "));
Serial.println(config::stable_measurements_before_calibration);
switchState(PREPARE_CALIBRATION_STABLE);
} else {
stable_measurements = 0;
switchState(PREPARE_CALIBRATION_UNSTABLE);
}
previous_co2 = co2;
return (stable_measurements == config::stable_measurements_before_calibration);
}
void startCalibrationProcess() {
/** From the sensor documentation:
* Before applying FRC, SCD30 needs to be operated for 2 minutes with the desired measurement period in continuous mode.
*/
Serial.print(F("Setting SCD30 timestep to "));
Serial.print(config::timestep_during_calibration);
Serial.println(F("s, prior to calibration."));
scd30.setMeasurementInterval(config::timestep_during_calibration); // [s] The change will only take effect after next measurement.
Serial.println(F("Waiting until the measurements are stable for at least 2 minutes."));
Serial.println(F("It could take a very long time."));
switchState(PREPARE_CALIBRATION_UNSTABLE);
}
void calibrate() {
Serial.print(F("Calibrating SCD30 now..."));
scd30.setAltitudeCompensation(config::altitude_above_sea_level);
scd30.setForcedRecalibrationFactor(config::co2_calibration_level);
Serial.println(F(" Done!"));
Serial.println(F("Sensor calibrated."));
switchState(BOOTUP); // In order to stop the calibration and select the desired timestep.
//WARNING: Do not reset the ampel or the SCD30!
//At least one measurement needs to happen in order for the calibration to be correctly applied.
}
void logToSerial() {
Serial.print(timestamp);
Serial.print(F(" - co2(ppm): "));
Serial.print(co2);
Serial.print(F(" temp(C): "));
Serial.print(temperature, 1);
Serial.print(F(" humidity(%): "));
Serial.println(humidity, 1);
}
void switchState(state new_state) {
if (new_state == current_state) {
return;
}
if (config::debug_sensor_states) {
Serial.print(F("Changing sensor state: "));
Serial.print(state_names[current_state]);
Serial.print(F(" -> "));
Serial.println(state_names[new_state]);
}
current_state = new_state;
}
void switchStateForCurrentPPM() {
if (current_state == BOOTUP) {
if (!hasSensorSettled()) {
return;
}
switchState(READY);
Serial.println(F("Sensor acclimatization finished."));
Serial.print(F("Setting SCD30 timestep to "));
Serial.print(config::measurement_timestep);
Serial.println(F(" s."));
if (config::measurement_timestep < 10) {
Serial.println(F("WARNING: Timesteps shorter than 10s can lead to unreliable measurements!"));
}
scd30.setMeasurementInterval(config::measurement_timestep); // [s]
}
// Check for pre-calibration states first, because we do not want to
// leave them before calibration is done.
if ((current_state == PREPARE_CALIBRATION_UNSTABLE) || (current_state == PREPARE_CALIBRATION_STABLE)) {
if (enoughStableMeasurements()) {
calibrate();
}
} else if (co2 < 250) {
// Sensor should be calibrated.
switchState(NEEDS_CALIBRATION);
} else {
switchState(READY);
}
}
void displayCO2OnLedRing() {
/**
* Display data, even if it's "old" (with breathing).
* A short delay is required in order to let background tasks run on the ESP8266.
* see https://github.com/esp8266/Arduino/issues/3241#issuecomment-301290392
*/
if (co2 < config::co2_alert_threshold) {
led_effects::displayCO2color(co2);
delay(100);
} else {
// Display a flashing led ring, if concentration exceeds a specific value
led_effects::alert(color::red);
}
}
void showState() {
switch (current_state) {
case BOOTUP:
led_effects::showWaitingLED(color::blue);
break;
case READY:
displayCO2OnLedRing();
break;
case NEEDS_CALIBRATION:
led_effects::showWaitingLED(color::magenta);
break;
case PREPARE_CALIBRATION_UNSTABLE:
led_effects::showWaitingLED(color::red);
break;
case PREPARE_CALIBRATION_STABLE:
led_effects::showWaitingLED(color::green);
break;
default:
Serial.println(F("Encountered unknown sensor state")); // This should not happen.
}
}
/** Gets fresh data if available, checks calibration status, displays CO2 levels.
* Returns true if fresh data is available, for further processing (e.g. MQTT, CSV or LoRa)
*/
bool processData() {
bool freshData = scd30.dataAvailable();
if (freshData) {
ntp::getLocalTime(timestamp);
co2 = scd30.getCO2();
temperature = scd30.getTemperature();
humidity = scd30.getHumidity();
switchStateForCurrentPPM();
// Log every time fresh data is available.
logToSerial();
}
showState();
// Report data for further processing only if the data is reliable
// (state 'READY') or manual calibration is necessary (state 'NEEDS_CALIBRATION').
return freshData && (current_state == READY || current_state == NEEDS_CALIBRATION);
}
/*****************************************************************
* Callbacks for sensor commands *
*****************************************************************/
void setCO2forDebugging(int32_t fakeCo2) {
Serial.print(F("DEBUG. Setting CO2 to "));
co2 = fakeCo2;
Serial.println(co2);
switchStateForCurrentPPM();
}
void setAutoCalibration(int32_t autoCalibration) {
config::auto_calibrate_sensor = autoCalibration;
scd30.setAutoSelfCalibration(autoCalibration);
Serial.print(F("Setting auto-calibration to : "));
Serial.println(autoCalibration ? F("On.") : F("Off."));
}
void setTimer(int32_t timestep) {
if (timestep >= 2 && timestep <= 1800) {
Serial.print(F("Setting Measurement Interval to : "));
Serial.print(timestep);
Serial.println(F("s (change will only be applied after next measurement)."));
scd30.setMeasurementInterval(timestep);
config::measurement_timestep = timestep;
led_effects::showKITTWheel(color::green, 1);
}
}
void calibrateSensorToSpecificPPM(int32_t calibrationLevel) {
if (calibrationLevel >= 400 && calibrationLevel <= 2000) {
Serial.print(F("Force calibration, at "));
config::co2_calibration_level = calibrationLevel;
Serial.print(config::co2_calibration_level);
Serial.println(F(" ppm."));
startCalibrationProcess();
}
}
void calibrateSensorRightNow(int32_t calibrationLevel) {
if (calibrationLevel >= 400 && calibrationLevel <= 2000) {
Serial.print(F("Force calibration, right now, at "));
config::co2_calibration_level = calibrationLevel;
Serial.print(config::co2_calibration_level);
Serial.println(F(" ppm."));
calibrate();
}
}
void resetSCD() {
Serial.print(F("Resetting SCD30..."));
scd30.reset();
Serial.println(F("done."));
}
}
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/co2_sensor.h 0000664 0000000 0000000 00000001063 14206137734 0026650 0 ustar 00root root 0000000 0000000 #ifndef CO2_SENSOR_H_
#define CO2_SENSOR_H_
#include // For uint16_t
namespace sensor {
extern uint16_t co2;
extern float temperature;
extern float humidity;
extern char timestamp[];
void initialize();
bool processData();
void startCalibrationProcess();
void setCO2forDebugging(int32_t fakeCo2);
void setTimer(int32_t timestep);
void calibrateSensorToSpecificPPM(int32_t calibrationLevel);
void calibrateSensorRightNow(int32_t calibrationLevel);
void setAutoCalibration(int32_t autoCalibration);
void resetSCD();
}
#endif
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/config.public.h 0000664 0000000 0000000 00000021765 14206137734 0027331 0 ustar 00root root 0000000 0000000 #ifndef CONFIG_H_INCLUDED
# define CONFIG_H_INCLUDED
/*** _ _
* / \ _ __ ___ _ __ ___| |
* / _ \ | '_ ` _ \| '_ \ / _ \ |
* / ___ \| | | | | | |_) | __/ |
* /_/ __\_\_| |_| |_| .__/_\___|_|
* / ___|___ _ __|_/ _(_) __ _
* | | / _ \| '_ \| |_| |/ _` |
* | |__| (_) | | | | _| | (_| |
* \____\___/|_| |_|_| |_|\__, |
* |___/
***/
// This file is a config template, and can be copied to config.h.
// Please don't save any important password in this template.
// IMPORTANT: Parameters defined in config.h are only default values, and are applied if:
// * the ampel is flashed for the first time
// * or 'reset_config' command is called
// * or AMPEL_CONFIG_VERSION has been changed.
// Once those default values have been applied, uploading the firmware with a modified config.h will not update the ampel configuration!
// Every parameter can be modified and saved later via the web-config.
// Some of those parameters can also be modified via commands in the Serial monitor :
// e.g. 'wifi 0' to turn WiFi off, or 'csv 60' to log data in csv every minute.
/***
* AMPEL
*/
// You can rename the Ampel if you want.
// This name will be used for CSV files and the mDNS address.
// You'll get a new CSV file after renaming, which can be convenient, e.g. after moving
// the ampel to another room.
// If left empty, the name will be ESPxxxxxx, where xxxxxx represent the last half of the MAC address.
# define AMPEL_NAME ""
// This password will be used for Access Point (without username), and for web-server available at http://local_ip with user 'admin', without quotes.
// If left empty, the password will have to be set during the first configuration, via access point.
// In order to be set successfully, it should have at least 8 characters.
# define AMPEL_PASSWORD ""
// AMPEL_CONFIG_VERSION should be defined, and have exactly 3 characters.
// If you modify this string, every parameter saved on the Ampel will be replaced by the ones in config.h.
// AMPEL_CONFIG_VERSION should also be updated if the configuration structure is modified.
// The structure of the Ampel configuration has been modified 10 times, so it's called "a10" for now.
# define AMPEL_CONFIG_VERSION "a10"
/**
* SERVICES
*/
// Define the default for corresponding services. They can be enabled/disabled later in the web-config.
# define AMPEL_WIFI true // Should ESP connect to WiFi? Web configuration will not be available when set to false. Use "wifi 1" command to set to true.
# define AMPEL_MQTT true // Should data be sent over MQTT? (AMPEL_WIFI should be enabled too)
# define AMPEL_CSV true // Should data be logged as CSV, on the ESP flash memory?
# define AMPEL_LORAWAN false // Should data be sent over LoRaWAN? (Requires ESP32 + LoRa modem, and "MCCI LoRaWAN LMIC library")
/**
* WIFI
*/
// SSID and PASSWORD need to be defined, but can be empty.
# define WIFI_SSID ""
# define WIFI_PASSWORD ""
// How long should the Ampel try to connect to WIFI_SSID?
# define WIFI_TIMEOUT 30 // [s]
// If the Ampel cannot connect to WIFI_SSID, it will start an Access Point for ACCESS_POINT_TIMEOUT seconds.
// If someone connects to this Access Point, the Ampel will stay in this mode until everybody logs out.
// If nobody connects to the Access Point before ACCESS_POINT_TIMEOUT seconds, the Ampel will try to connect WIFI_SSID again.
# define ACCESS_POINT_TIMEOUT 60 // [s]
/**
* Sensor
*/
// How often should measurement be performed, and displayed?
//WARNING: On some sensors, measurements become very unreliable when timestep is set to 2s.
//NOTE: 10s or longer should be fine in order to get reliable results.
//NOTE: SCD30 timer does not seem to be very precise. Time variations may occur.
# define MEASUREMENT_TIMESTEP 60 // [s] Value between 2 and 1800 (range for SCD30 sensor)
// How often should measurements be appended to CSV ?
// Set to 0 if you want to send values after each measurement
// WARNING: Writing too often might damage the ESP memory
# define CSV_INTERVAL 300 // [s]
// Residual heat from CO2 sensor seems to be high enough to change the temperature reading. How much should it be offset?
// NOTE: Sign isn't relevant. The returned temperature will always be shifted down.
# define TEMPERATURE_OFFSET -3 // [K]
// Altitude above sea level
// Used for CO2 calibration
// here: Stuttgart, Schellingstr. 24. (Source: Google Earth)
# define ALTITUDE_ABOVE_SEA_LEVEL 260 // [m]
// The reference CO2 concentration has to be within the range 400 ppm ≤ cref(CO2) ≤ 2000 ppm.
// Used for CO2 calibration
// here : measured concentration in Stuttgart
# define ATMOSPHERIC_CO2_CONCENTRATION 425 // [ppm]
// Should the sensor try to calibrate itself?
// Sensirion recommends 7 days of continuous readings with at least 1 hour a day of 'fresh air' for self-calibration to complete.
# define AUTO_CALIBRATE_SENSOR false // [true / false]
/**
* LEDs
*/
// LED brightness, which can vary between min and max brightness ("LED breathing")
// MAX_BRIGHTNESS must be defined, and should be between 0 and 255.
# define MAX_BRIGHTNESS 255
// MIN_BRIGHTNESS, if defined, should be between 0 and MAX_BRIGHTNESS - 1
// If MIN_BRIGHTNESS is set to MAX_BRIGHTNESS, breathing is disabled.
# define MIN_BRIGHTNESS 60
// How many LEDs in the ring? 12 and 16 are currently supported.
# define LED_COUNT 12
/**
* MQTT
*/
/*
* If AMPEL_MQTT is enabled, co2ampel will publish data every MQTT_SENDING_INTERVAL seconds.
* An MQTT subscriber can then get the data from the corresponding broker, either encrypted or unencrypted:
*
* ❯ mosquitto_sub -h 'test.mosquitto.org' -p 8883 -t 'CO2sensors/#' --cafile mosquitto.org.crt -v
* CO2sensors/ESPd03cc5 {"time":"2020-12-13 13:14:37+01", "co2":571, "temp":18.9, "rh":50.9}
* CO2sensors/ESPd03cc5 {"time":"2020-12-13 13:14:48+01", "co2":573, "temp":18.9, "rh":50.2}
* ...
*
* ❯ mosquitto_sub -h 'test.mosquitto.org' -t 'CO2sensors/#' -v
* CO2sensors/ESPd03cc5 {"time":"2020-12-13 13:15:09+01", "co2":568, "temp":18.9, "rh":50.1}
* CO2sensors/ESPd03cc5 {"time":"2020-12-13 13:15:20+01", "co2":572, "temp":18.9, "rh":50.3}
* ...
*/
/*
* Allow sensor to be configured over MQTT? Very useful for debugging. For example:
* mosquitto_pub -h 'test.mosquitto.org' -t 'CO2sensors/ESPe08dc9/control' -m 'timer 30'
* mosquitto_pub -h 'test.mosquitto.org' -t 'CO2sensors/ESPe08dc9/control' -m 'calibrate'
* mosquitto_pub -h 'test.mosquitto.org' -t 'CO2sensors/ESPe08dc9/control' -m 'reset'
*/
# define ALLOW_MQTT_COMMANDS false
// How often should measurements be sent to MQTT server?
// Set to 0 if you want to send values after each measurement
// # define MQTT_SENDING_INTERVAL MEASUREMENT_TIMESTEP * 5 // [s]
# define MQTT_SENDING_INTERVAL 300 // [s]
# define MQTT_SERVER "test.mosquitto.org" // MQTT server URL or IP address
# define MQTT_PORT 8883
# define MQTT_ENCRYPTED true // Set to false for unencrypted MQTT (e.g. with port 1883).
# define MQTT_USER ""
# define MQTT_PASSWORD ""
/**
* LoRaWAN
*/
// 1) Requires "MCCI LoRaWAN LMIC library", which will be automatically used with PlatformIO but should be added in "Arduino IDE".
// 2) Region and transceiver type should be specified in:
// * Arduino/libraries/MCCI_LoRaWAN_LMIC_library/project_config/lmic_project_config.h for Arduino IDE
// * platformio.ini for PlatformIO
// See https://github.com/mcci-catena/arduino-lmic#configuration for more information
// 3) It has been tested with "TTGO ESP32 SX1276 LoRa 868" and will only work with an ESP32 + LoRa modem
// 4) In order to use LoRaWAN, a gateway should be close to the co2ampel, and an account, an application and a device should be registered,
// e.g. on https://www.thethingsindustries.com/docs/integrations/
// 5) The corresponding keys should be defined in LORAWAN_DEVICE_EUI, LORAWAN_APPLICATION_EUI and LORAWAN_APPLICATION_KEY
// How often should measurements be sent over LoRaWAN?
# define LORAWAN_SENDING_INTERVAL 300 // [s] This value should not be too low. See https://www.thethingsnetwork.org/docs/lorawan/duty-cycle.html#maximum-duty-cycle
// WARNING: If AMPEL_LORAWAN is true, you need to modify the 3 following constants
// They are written as hexadecimal strings, and will be parsed in the correct order.
// This EUI must be in big-endian format, so most-significant-byte first.
// You can copy the string from TheThingsNetwork as-is, without reversing the bytes.
// For TheThingsNetwork issued EUIs the string should start with "70B3D5..."
# define LORAWAN_DEVICE_EUI "70B3D57ED004CB17"
// This should also be in big-endian format, and can be copied as is from TheThingsNetwork.
# define LORAWAN_APPLICATION_EUI "0102030405060708"
// This should also be in big-endian format, and can be copied as is from TheThingsNetwork.
# define LORAWAN_APPLICATION_KEY "9D06308E20B974919DA6404E063BE01D"
/**
* NTP
*/
# define NTP_SERVER "pool.ntp.org"
# define UTC_OFFSET 1 // [h] +1 for Paris/Berlin, -5 for NYC
# define DAYLIGHT_SAVING_TIME false // true in summer, false in winter
#endif
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/csv_writer.cpp 0000664 0000000 0000000 00000012366 14206137734 0027326 0 ustar 00root root 0000000 0000000 #include "csv_writer.h"
#include "web_config.h"
#include "ntp.h"
#include "led_effects.h"
#include "sensor_console.h"
namespace csv_writer {
unsigned long last_written_at = 0;
char last_successful_write[23];
#if defined(ESP8266)
/**
* SPECIFIC FUNCTIONS FOR LITTLEFS
*/
FSInfo fs_info;
bool mountFS() {
return LittleFS.begin(); // format if needed.
}
void updateFsInfo() {
FS_LIB.info(fs_info);
}
int getTotalSpace() {
return fs_info.totalBytes;
}
int getUsedSpace() {
return fs_info.usedBytes;
}
void showFilesystemContent() {
Dir dir = FS_LIB.openDir("/");
while (dir.next()) {
Serial.print(" ");
Serial.print(dir.fileName());
Serial.print(" - ");
if (dir.fileSize()) {
File f = dir.openFile("r");
Serial.println(f.size());
f.close();
} else {
Serial.println("0");
}
}
}
#elif defined(ESP32)
/**
* SPECIFIC FUNCTIONS FOR SPIFFS
*/
bool mountFS() {
return SPIFFS.begin(true); // format if needed.
}
void updateFsInfo() {
// Nothing to do.
}
int getTotalSpace() {
return SPIFFS.totalBytes();
}
int getUsedSpace() {
return SPIFFS.usedBytes();
}
void showFilesystemContent() {
File root = SPIFFS.open("/");
File file = root.openNextFile();
while (file) {
Serial.print(" ");
Serial.print(file.name());
Serial.print(" - ");
Serial.println(file.size());
file = root.openNextFile();
}
}
#endif
char filename[20]; // e.g. "/ESPxxxxxx.csv\0"
int getAvailableSpace() {
return getTotalSpace() - getUsedSpace();
}
void initialize(const char *basename) {
snprintf(filename, sizeof(filename), "/%.14s.csv", basename);
Serial.println();
Serial.print(F("Initializing FS..."));
if (mountFS()) {
Serial.println(F("done."));
} else {
Serial.println(F("fail."));
return;
}
updateFsInfo();
Serial.println(F("File system info:"));
Serial.print(F(" Total space : "));
Serial.print(getTotalSpace() / 1024);
Serial.println("kB");
Serial.print(F(" Used space : "));
Serial.print(getUsedSpace() / 1024);
Serial.println("kB");
Serial.print(F(" Available space: "));
Serial.print(getAvailableSpace() / 1024);
Serial.println("kB");
Serial.println();
// Open dir folder
Serial.println(F("Filesystem content:"));
showFilesystemContent();
Serial.println();
sensor_console::defineIntCommand("csv", setCSVinterval, F("60 (Sets CSV writing interval, in s)"));
sensor_console::defineCommand("format_filesystem", formatFilesystem, F("(Deletes the whole filesystem)"));
sensor_console::defineCommand("show_csv", showCSVContent, F("(Displays the complete CSV file on Serial)"));
}
File openOrCreate() {
File csv_file;
if (FS_LIB.exists(filename)) {
csv_file = FS_LIB.open(filename, "a+");
} else {
csv_file = FS_LIB.open(filename, "w");
csv_file.print(F("Sensor time;CO2 concentration;Temperature;Humidity\r\n"));
csv_file.print(F("YYYY-MM-DD HH:MM:SS+ZZ;ppm;degC;%\r\n"));
}
return csv_file;
}
void log(const char *timestamp, const int16_t &co2, const float &temperature, const float &humidity) {
led_effects::onBoardLEDOn();
File csv_file = openOrCreate();
char csv_line[42];
snprintf(csv_line, sizeof(csv_line), "%s;%d;%.1f;%.1f\r\n", timestamp, co2, temperature, humidity);
if (csv_file) {
size_t written_bytes = csv_file.print(csv_line);
csv_file.close();
if (written_bytes == 0) {
Serial.println(F("Nothing written. Disk full?"));
} else {
Serial.print(F("CSV - Wrote : "));
Serial.print(csv_line);
ntp::getLocalTime(last_successful_write);
}
updateFsInfo();
delay(50);
} else {
//NOTE: Can it ever happen that outfile is false?
Serial.println(F("Problem on create file!"));
}
led_effects::onBoardLEDOff();
}
void logIfTimeHasCome(const char *timeStamp, const int16_t &co2, const float &temperature, const float &humidity) {
unsigned long now = seconds();
if (now - last_written_at > config::csv_interval) {
last_written_at = now;
log(timeStamp, co2, temperature, humidity);
}
}
/*****************************************************************
* Callbacks for sensor commands *
*****************************************************************/
void setCSVinterval(int32_t csv_interval) {
config::csv_interval = csv_interval;
Serial.print(F("Setting CSV Interval to : "));
Serial.print(config::csv_interval);
Serial.println("s.");
led_effects::showKITTWheel(color::green, 1);
}
void showCSVContent() {
//TODO: Now that ampel_name can be set, should show the content of every csv
Serial.print(F("### "));
Serial.print(filename);
Serial.println(F(" ###"));
File csv_file;
if (FS_LIB.exists(filename)) {
csv_file = FS_LIB.open(filename, "r");
while (csv_file.available()) {
Serial.write(csv_file.read());
}
csv_file.close();
}
Serial.println(F("######################"));
}
void formatFilesystem() {
FS_LIB.format();
led_effects::showKITTWheel(color::blue, 2);
}
}
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/csv_writer.h 0000664 0000000 0000000 00000001261 14206137734 0026763 0 ustar 00root root 0000000 0000000 #ifndef CSV_WRITER_H_
#define CSV_WRITER_H_
#if defined(ESP8266)
# include
# define FS_LIB LittleFS
#elif defined(ESP32)
# include
# define FS_LIB SPIFFS
#else
# error Board should be either ESP8266 or ESP832
#endif
//NOTE: LittleFS will be available for Arduino esp32 core v2
namespace csv_writer {
extern char last_successful_write[];
void initialize(const char *basename);
void logIfTimeHasCome(const char *timestamp, const int16_t &co2, const float &temperature, const float &humidity);
int getAvailableSpace();
extern char filename[];
void setCSVinterval(int32_t csv_interval);
void showCSVContent();
void formatFilesystem();
}
#endif
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/led_effects.cpp 0000664 0000000 0000000 00000022747 14206137734 0027406 0 ustar 00root root 0000000 0000000 #include "led_effects.h"
#include "web_config.h"
#include "sensor_console.h"
// Adafruit NeoPixel (Arduino library for controlling single-wire-based LED pixels and strip)
// https://github.com/adafruit/Adafruit_NeoPixel
// Documentation : http://adafruit.github.io/Adafruit_NeoPixel/html/class_adafruit___neo_pixel.html
#include "src/lib/Adafruit_NeoPixel/Adafruit_NeoPixel.h"
/*****************************************************************
* Configuration *
*****************************************************************/
namespace config {
const int kitt_tail = 3; // How many dimmer LEDs follow in K.I.T.T. wheel
const uint16_t poor_air_quality_ppm = 1600; // Above this threshold, LED breathing effect is faster.
bool display_led = true; // Will be set to false during "night mode".
//NOTE: One value has been prepended, to make calculations easier and avoid out of bounds index.
uint16_t co2_ticks[16 + 1] = { 0, 500, 600, 700, 800, 900, 1000 }; // rest will be filled later
// For a given LED, which color should be displayed? First LED will be pure green (hue angle 120°),
// LEDs >= 1600ppm will be pure red (hue angle 0°), LEDs in-between will be yellowish.
uint16_t led_hues[16];
}
#if defined(ESP8266)
// NeoPixels on GPIO05, aka D1 on ESP8266.
const int NEOPIXELS_PIN = 5;
#elif defined(ESP32)
// NeoPixels on GPIO23 on ESP32. To avoid conflict with LoRa_SCK on TTGO.
const int NEOPIXELS_PIN = 23;
#endif
// config::led_count is not yet known, will be set later.
Adafruit_NeoPixel pixels(0, NEOPIXELS_PIN, NEO_GRB + NEO_KHZ800);
namespace led_effects {
//On-board LED on D4, aka GPIO02
const int ONBOARD_LED_PIN = 2;
void setupOnBoardLED() {
pinMode(ONBOARD_LED_PIN, OUTPUT);
}
void onBoardLEDOff() {
//NOTE: OFF is LOW on ESP32 and HIGH on ESP8266 :-/
#ifdef ESP8266
digitalWrite(ONBOARD_LED_PIN, HIGH);
#else
digitalWrite(ONBOARD_LED_PIN, LOW);
#endif
}
void onBoardLEDOn() {
#ifdef ESP8266
digitalWrite(ONBOARD_LED_PIN, LOW);
#else
digitalWrite(ONBOARD_LED_PIN, HIGH);
#endif
}
void LEDsOff() {
pixels.clear();
pixels.show();
onBoardLEDOff();
}
void showColor(int32_t color) {
config::display_led = false; // In order to avoid overwriting the desired color next time CO2 is displayed
pixels.setBrightness(255);
pixels.fill(color);
pixels.show();
}
void setupRing() {
Serial.print(F("Ring : "));
Serial.print(config::led_count);
Serial.println(F(" LEDs."));
pixels.updateLength(config::led_count);
if (config::led_count == 12) {
config::co2_ticks[7] = 1200;
config::co2_ticks[8] = 1400;
config::co2_ticks[9] = 1600;
config::co2_ticks[10] = 1800;
config::co2_ticks[11] = 2000;
config::co2_ticks[12] = 2200;
config::led_hues[0] = 21845U;
config::led_hues[1] = 19114U;
config::led_hues[2] = 16383U;
config::led_hues[3] = 13653U;
config::led_hues[4] = 10922U;
config::led_hues[5] = 8191U;
config::led_hues[6] = 5461U;
config::led_hues[7] = 2730U;
config::led_hues[8] = 0;
config::led_hues[9] = 0;
config::led_hues[10] = 0;
config::led_hues[11] = 0;
} else if (config::led_count == 16) {
config::co2_ticks[7] = 1100;
config::co2_ticks[8] = 1200;
config::co2_ticks[9] = 1300;
config::co2_ticks[10] = 1400;
config::co2_ticks[11] = 1500;
config::co2_ticks[12] = 1600;
config::co2_ticks[13] = 1700;
config::co2_ticks[14] = 1800;
config::co2_ticks[15] = 2000;
config::co2_ticks[16] = 2200;
config::led_hues[0] = 21845U;
config::led_hues[1] = 19859U;
config::led_hues[2] = 17873U;
config::led_hues[3] = 15887U;
config::led_hues[4] = 13901U;
config::led_hues[5] = 11915U;
config::led_hues[6] = 9929U;
config::led_hues[7] = 7943U;
config::led_hues[8] = 5957U;
config::led_hues[9] = 3971U;
config::led_hues[10] = 1985U;
config::led_hues[11] = 0;
config::led_hues[12] = 0;
config::led_hues[13] = 0;
config::led_hues[14] = 0;
config::led_hues[15] = 0;
} else {
// "Only 12 and 16 LEDs rings are currently supported."
config::display_led = false;
}
pixels.begin();
pixels.setBrightness(config::max_brightness);
LEDsOff();
sensor_console::defineIntCommand("led", turnLEDsOnOff, F("0/1 (Turns LEDs on/off)"));
sensor_console::defineIntCommand("color", showColor, F("0xFF0015 (Shows color, specified as RGB, for debugging)"));
}
void toggleNightMode() {
turnLEDsOnOff(!config::display_led);
}
void turnLEDsOnOff(int32_t display_led) {
config::display_led = display_led;
if (config::display_led) {
Serial.println(F("LEDs are on!"));
} else {
Serial.println(F("Night mode!"));
LEDsOff();
}
}
//NOTE: basically one iteration of KITT wheel
void showWaitingLED(uint32_t color) {
using namespace config;
delay(80);
if (!display_led) {
return;
}
static uint16_t kitt_offset = 0;
pixels.clear();
for (int j = kitt_tail; j >= 0; j--) {
int ledNumber = abs((kitt_offset - j + led_count) % (2 * led_count) - led_count) % led_count; // Triangular function
pixels.setPixelColor(ledNumber, color * pixels.gamma8(255 - j * 76) / 255);
}
pixels.show();
kitt_offset++;
}
// Start K.I.T.T. led effect. Red color as default.
// Simulate a moving LED with tail. First LED starts at 0, and moves along a triangular function. The tail follows, with decreasing brightness.
// Takes approximately 1s for each direction.
void showKITTWheel(uint32_t color, uint16_t duration_s) {
pixels.setBrightness(config::max_brightness);
for (int i = 0; i < duration_s * config::led_count; ++i) {
showWaitingLED(color);
}
}
/*
* For a given CO2 level and ledId, which brightness should be displayed? 0 for off, 255 for on. Something in-between for partial LED.
* For example, for 1500ppm, every LED between 0 and 7 (500 -> 1400ppm) should be on, LED at 8 (1600ppm) should be half-on.
*/
uint8_t getLedBrightness(uint16_t co2, int ledId) {
if (co2 >= config::co2_ticks[ledId + 1]) {
return 255;
} else {
if (2 * co2 >= config::co2_ticks[ledId] + config::co2_ticks[ledId + 1]) {
// Show partial LED if co2 more than halfway between ticks.
return 27; // Brightness isn't linear, so 27 / 255 looks much brighter than 10%
} else {
// LED off because co2 below previous tick
return 0;
}
}
}
/**
* If enabled, slowly varies the brightness between MAX_BRIGHTNESS & MIN_BRIGHTNESS.
*/
void breathe(int16_t co2) {
static uint8_t breathing_offset = 0;
uint8_t brightness_amplitude = config::max_brightness - config::min_brightness;
uint16_t brightness = config::min_brightness + pixels.sine8(breathing_offset) * brightness_amplitude / 255;
pixels.setBrightness(brightness);
pixels.show();
breathing_offset += co2 > config::poor_air_quality_ppm ? 6 : 3; // breathing speed. +3 looks like slow human breathing.
}
/**
* Fills the whole ring with green, yellow, orange or black, depending on co2 input and CO2_TICKS.
*/
void displayCO2color(uint16_t co2) {
if (!config::display_led) {
return;
}
pixels.setBrightness(config::max_brightness);
for (int ledId = 0; ledId < config::led_count; ++ledId) {
uint8_t brightness = getLedBrightness(co2, ledId);
pixels.setPixelColor(ledId, pixels.ColorHSV(config::led_hues[ledId], 255, brightness));
}
pixels.show();
if (config::max_brightness > config::min_brightness) {
breathe(co2);
}
}
void showRainbowWheel(uint16_t duration_ms) {
if (!config::display_led) {
return;
}
static uint16_t wheel_offset = 0;
static uint16_t sine_offset = 0;
unsigned long t0 = millis();
pixels.setBrightness(config::max_brightness);
while (millis() - t0 < duration_ms) {
for (int i = 0; i < config::led_count; i++) {
pixels.setPixelColor(i, pixels.ColorHSV(i * 65535 / config::led_count + wheel_offset));
wheel_offset += (pixels.sine8(sine_offset++ / 50) - 127) / 2;
}
pixels.show();
delay(10);
}
}
void alert(uint32_t color) {
if (!config::display_led) {
onBoardLEDOn();
delay(500);
onBoardLEDOff();
delay(500);
return;
}
for (int i = 0; i < 10; i++) {
pixels.setBrightness(static_cast(config::max_brightness * (1 - i * 0.1)));
delay(50);
pixels.fill(color);
pixels.show();
}
}
/**
* Displays a complete blue circle, and starts removing LEDs one by one.
* Does nothing in night mode and returns false then. Returns true if
* the countdown has finished. Can be used for calibration, e.g. when countdown is 0.
* NOTE: This function is blocking and returns only after the button has
* been released or after every LED has been turned off.
*/
bool countdownToZero() {
if (!config::display_led) {
Serial.println(F("Night mode. Not doing anything."));
delay(1000); // Wait for a while, to avoid coming back to this function too many times when button is pressed.
return false;
}
pixels.fill(color::blue);
pixels.show();
int countdown;
for (countdown = config::led_count; countdown >= 0 && !digitalRead(0); countdown--) {
pixels.setPixelColor(countdown, color::black);
pixels.show();
Serial.println(countdown);
delay(500);
}
return countdown < 0;
}
}
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/led_effects.h 0000664 0000000 0000000 00000001353 14206137734 0027041 0 ustar 00root root 0000000 0000000 #ifndef LED_EFFECTS_H_INCLUDED
#define LED_EFFECTS_H_INCLUDED
#include // For uint32_t
namespace color {
const uint32_t red = 0xFF0000;
const uint32_t green = 0x00FF00;
const uint32_t blue = 0x0000FF;
const uint32_t black = 0x000000;
const uint32_t magenta = 0xFF00FF;
}
namespace led_effects {
void setupOnBoardLED();
void onBoardLEDOff();
void onBoardLEDOn();
void toggleNightMode();
void turnLEDsOnOff(int32_t);
void LEDsOff();
void setupRing();
void alert(uint32_t color);
bool countdownToZero();
void showWaitingLED(uint32_t color);
void showKITTWheel(uint32_t color, uint16_t duration_s = 2);
void showRainbowWheel(uint16_t duration_ms = 1000);
void displayCO2color(uint16_t co2);
}
#endif
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/lorawan.cpp 0000664 0000000 0000000 00000023574 14206137734 0026605 0 ustar 00root root 0000000 0000000 #include "lorawan.h"
#if defined(ESP32)
#include "web_config.h"
#include "led_effects.h"
#include "sensor_console.h"
#include "util.h"
#include "ntp.h"
// Requires "MCCI LoRaWAN LMIC library", which will be automatically used with PlatformIO but should be added in "Arduino IDE"
// Tested successfully with v3.2.0 and connected to a thethingsnetwork.org app.
#include
#include
#include
#include
namespace config {
#if defined(CFG_eu868)
const char *lorawan_frequency_plan = "Europe 868";
#elif defined(CFG_us915)
const char *lorawan_frequency_plan = "US 915";
#elif defined(CFG_au915)
const char *lorawan_frequency_plan = "Australia 915";
#elif defined(CFG_as923)
const char *lorawan_frequency_plan = "Asia 923";
#elif defined(CFG_kr920)
const char *lorawan_frequency_plan = "Korea 920";
#elif defined(CFG_in866)
const char *lorawan_frequency_plan = "India 866";
#else
# error "Region should be specified"
#endif
}
// Payloads will be automatically sent via MQTT by TheThingsNetwork, and can be seen with:
// mosquitto_sub -h eu.thethings.network -t '+/devices/+/up' -u 'APPLICATION-NAME' -P 'ttn-account-v2.4xxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxx' -v
// or encrypted:
// mosquitto_sub -h eu.thethings.network -t '+/devices/+/up' -u 'APPLICATION-NAME' -P 'ttn-account-v2.4xxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxx' -v --cafile mqtt-ca.pem -p 8883
// ->
// co2ampel-test/devices/esp3a7c94/up {"app_id":"co2ampel-test","dev_id":"esp3a7c94","hardware_serial":"00xxxxxxxx","port":1,"counter":5,"payload_raw":"TJd7","payload_fields":{"co2":760,"rh":61.5,"temp":20.2},"metadata":{"time":"2020-12-23T23:00:51.44020438Z","frequency":867.5,"modulation":"LORA","data_rate":"SF7BW125","airtime":51456000,"coding_rate":"4/5","gateways":[{"gtw_id":"eui-xxxxxxxxxxxxxxxxxx","timestamp":1765406908,"time":"2020-12-23T23:00:51.402519Z","channel":5,"rssi":-64,"snr":7.5,"rf_chain":0,"latitude":22.7,"longitude":114.24,"altitude":450}]}}
// More info : https://www.thethingsnetwork.org/docs/applications/mqtt/quick-start.html
namespace lorawan {
bool waiting_for_confirmation = false;
bool connected = false;
char last_transmission[23] = "";
void initialize() {
Serial.print(F("Starting LoRaWAN. Frequency plan : "));
Serial.print(config::lorawan_frequency_plan);
Serial.println(F(" MHz."));
// More info about pin mapping : https://github.com/mcci-catena/arduino-lmic#pin-mapping
// Has been tested successfully with ESP32 TTGO LoRa32 V1, and might work with other ESP32+LoRa boards.
const lmic_pinmap *pPinMap = Arduino_LMIC::GetPinmap_ThisBoard();
// LMIC init.
os_init_ex(pPinMap);
// Reset the MAC state. Session and pending data transfers will be discarded.
LMIC_reset();
// Join, but don't send anything yet.
LMIC_startJoining();
sensor_console::defineIntCommand("lora", setLoRaInterval, F("300 (Sets LoRaWAN sending interval, in s)"));
}
// Checks if OTAA is connected, or if payload should be sent.
// NOTE: while a transaction is in process (i.e. until the TXcomplete event has been received), no blocking code (e.g. delay loops etc.) are allowed, otherwise the LMIC/OS code might miss the event.
// If this rule is not followed, a typical symptom is that the first send is ok and all following ones end with the 'TX not complete' failure.
void process() {
os_runloop_once();
}
void printHex2(unsigned v) {
v &= 0xff;
if (v < 16)
Serial.print('0');
Serial.print(v, HEX);
}
void onEvent(ev_t ev) {
char current_time[23];
ntp::getLocalTime(current_time);
Serial.print(F("LoRa - "));
Serial.print(current_time);
Serial.print(F(" - "));
switch (ev) {
case EV_JOINING:
Serial.println(F("EV_JOINING"));
break;
case EV_JOINED:
waiting_for_confirmation = false;
connected = true;
led_effects::onBoardLEDOff();
Serial.println(F("EV_JOINED"));
{
u4_t netid = 0;
devaddr_t devaddr = 0;
u1_t nwkKey[16];
u1_t artKey[16];
LMIC_getSessionKeys(&netid, &devaddr, nwkKey, artKey);
//NOTE: Saving session to EEPROM seems like a good idea at first, but unfortunately: too much info is needed, and a counter would need to be save every single time data is sent.
Serial.print(F(" netid: "));
Serial.println(netid, DEC);
Serial.print(F(" devaddr: "));
Serial.println(devaddr, HEX);
Serial.print(F(" AppSKey: "));
for (size_t i = 0; i < sizeof(artKey); ++i) {
if (i != 0)
Serial.print("-");
printHex2(artKey[i]);
}
Serial.println();
Serial.print(F(" NwkSKey: "));
for (size_t i = 0; i < sizeof(nwkKey); ++i) {
if (i != 0)
Serial.print("-");
printHex2(nwkKey[i]);
}
Serial.println();
}
Serial.println(F("Other services may resume, and will not be frozen anymore."));
// Disable link check validation (automatically enabled during join)
LMIC_setLinkCheckMode(0);
break;
case EV_JOIN_FAILED:
Serial.println(F("EV_JOIN_FAILED"));
break;
case EV_REJOIN_FAILED:
Serial.println(F("EV_REJOIN_FAILED"));
break;
case EV_TXCOMPLETE:
ntp::getLocalTime(last_transmission);
Serial.println(F("EV_TXCOMPLETE"));
break;
case EV_TXSTART:
waiting_for_confirmation = !connected;
Serial.println(F("EV_TXSTART"));
break;
case EV_TXCANCELED:
waiting_for_confirmation = false;
led_effects::onBoardLEDOff();
Serial.println(F("EV_TXCANCELED"));
break;
case EV_JOIN_TXCOMPLETE:
waiting_for_confirmation = false;
led_effects::onBoardLEDOff();
Serial.println(F("EV_JOIN_TXCOMPLETE: no JoinAccept."));
Serial.println(F("Other services may resume."));
break;
default:
Serial.print(F("LoRa event: "));
Serial.println((unsigned) ev);
break;
}
if (waiting_for_confirmation) {
led_effects::onBoardLEDOn();
Serial.println(F("LoRa - waiting for OTAA confirmation. Freezing every other service!"));
}
}
void preparePayload(int16_t co2, float temperature, float humidity) {
// Check if there is not a current TX/RX job running
if (LMIC.opmode & OP_TXRXPEND) {
Serial.println(F("OP_TXRXPEND, not sending"));
} else {
uint8_t buff[3];
// Mapping CO2 from 0ppm to 5100ppm to [0, 255], with 20ppm increments.
buff[0] = (util::min(util::max(co2, 0), 5100) + 10) / 20;
// Mapping temperatures from [-10°C, 41°C] to [0, 255], with 0.2°C increment
buff[1] = static_cast((util::min(util::max(temperature, -10), 41) + 10.1f) * 5);
// Mapping humidity from [0%, 100%] to [0, 200], with 0.5°C increment (0.4°C would also be possible)
buff[2] = static_cast(util::min(util::max(humidity, 0) + 0.25f, 100) * 2);
Serial.print(F("LoRa - Payload : '"));
printHex2(buff[0]);
Serial.print(" ");
printHex2(buff[1]);
Serial.print(" ");
printHex2(buff[2]);
Serial.print(F("', "));
Serial.print(buff[0] * 20);
Serial.print(F(" ppm, "));
Serial.print(buff[1] * 0.2 - 10);
Serial.print(F(" °C, "));
Serial.print(buff[2] * 0.5);
Serial.println(F(" %."));
// Prepare upstream data transmission at the next possible time.
LMIC_setTxData2(1, buff, sizeof(buff), 0);
//NOTE: To decode in TheThingsNetwork:
// function decodeUplink(input) {
// return {
// data: {
// co2: input.bytes[0] * 20,
// temp: input.bytes[1] / 5.0 - 10,
// rh: input.bytes[2] / 2.0
// },
// warnings: [],
// errors: []
// };
// }
}
}
void preparePayloadIfTimeHasCome(const int16_t &co2, const float &temperature, const float &humidity) {
static unsigned long last_sent_at = 0;
unsigned long now = seconds();
if (connected && (now - last_sent_at > config::lorawan_sending_interval)) {
last_sent_at = now;
preparePayload(co2, temperature, humidity);
}
}
/*****************************************************************
* Callbacks for sensor commands *
*****************************************************************/
void setLoRaInterval(int32_t sending_interval) {
config::lorawan_sending_interval = sending_interval;
Serial.print(F("Setting LoRa sending interval to : "));
Serial.print(config::lorawan_sending_interval);
Serial.println("s.");
led_effects::showKITTWheel(color::green, 1);
}
}
void onEvent(ev_t ev) {
lorawan::onEvent(ev);
}
// 'A' -> 10, 'F' -> 15, 'f' -> 15, 'z' -> -1
int8_t hexCharToInt(char c) {
int8_t v = -1;
if ((c >= '0') && (c <= '9')) {
v = (c - '0');
} else if ((c >= 'A') && (c <= 'F')) {
v = (c - 'A' + 10);
} else if ((c >= 'a') && (c <= 'f')) {
v = (c - 'a' + 10);
}
return v;
}
/**
* Parses hex string and saves the corresponding bytes in buf.
* msb is true for most-significant-byte, false for least-significant-byte.
*
* "112233" will be loaded into {0x11, 0x22, 0x33} in MSB, {0x33, 0x22, 0x11} in LSB.
*/
void hexStringToByteArray(uint8_t *buf, const char *hex, uint max_n, bool msb) {
int n = util::min(strlen(hex) / 2, max_n);
for (int i = 0; i < n; i++) {
int j;
if (msb) {
j = i;
} else {
j = n - 1 - i;
}
uint8_t r = hexCharToInt(hex[j * 2]) * 16 + hexCharToInt(hex[j * 2 + 1]);
buf[i] = r;
}
}
// Load config into LMIC byte arrays.
void os_getArtEui(u1_t *buf) {
hexStringToByteArray(buf, config::lorawan_app_eui, 8, false);
}
void os_getDevEui(u1_t *buf) {
hexStringToByteArray(buf, config::lorawan_device_eui, 8, false);
}
void os_getDevKey(u1_t *buf) {
hexStringToByteArray(buf, config::lorawan_app_key, 16, true);
}
#endif
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/lorawan.h 0000664 0000000 0000000 00000001023 14206137734 0026233 0 ustar 00root root 0000000 0000000 #ifndef AMPEL_LORAWAN_H_
#define AMPEL_LORAWAN_H_
# if defined(ESP32)
#include // For uint32_t & uint16_t
namespace config {
extern const char *lorawan_frequency_plan; // e.g. "Europe 868"
}
namespace lorawan {
extern bool waiting_for_confirmation;
extern bool connected;
extern char last_transmission[];
void initialize();
void process();
void preparePayloadIfTimeHasCome(const int16_t &co2, const float &temp, const float &hum);
void setLoRaInterval(int32_t sending_interval);
}
# endif
#endif
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/mqtt.cpp 0000664 0000000 0000000 00000016744 14206137734 0026130 0 ustar 00root root 0000000 0000000 #include "mqtt.h"
#include "web_config.h"
#include "led_effects.h"
#include "sensor_console.h"
#include "wifi_util.h"
#include "ntp.h"
#include "src/lib/PubSubClient/src/PubSubClient.h"
#if defined(ESP8266)
# include
#elif defined(ESP32)
# include
#endif
namespace config {
// Values should be defined in config.h or over webconfig
//INFO: Listen to every CO2 sensor which is connected to the server:
// mosquitto_sub -h MQTT_SERVER -t 'CO2sensors/#' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -v
const unsigned long wait_after_fail = 900; // [s] Wait 15 minutes after an MQTT connection fail, before trying again.
}
#if defined(ESP32)
# include
#endif
WiFiClient *espClient;
PubSubClient mqttClient;
namespace mqtt {
unsigned long last_sent_at = 0;
unsigned long last_failed_at = 0;
bool connected = false;
char publish_topic[21]; // e.g. "CO2sensors/ESPxxxxxx\0"
const char *json_sensor_format;
char last_successful_publish[23] = "";
void initialize(const char *sensorId) {
json_sensor_format = PSTR("{\"time\":\"%s\", \"co2\":%d, \"temp\":%.1f, \"rh\":%.1f}");
snprintf(publish_topic, sizeof(publish_topic), "CO2sensors/%s", sensorId);
if (config::mqtt_encryption) {
// The sensor doesn't check the fingerprint of the MQTT broker, because otherwise this fingerprint should be updated
// on the sensor every 3 months. The connection can still be encrypted, though:
WiFiClientSecure *secureClient = new WiFiClientSecure();
secureClient->setInsecure();
espClient = secureClient;
} else {
espClient = new WiFiClient();
}
mqttClient.setClient(*espClient);
mqttClient.setServer(config::mqtt_server, config::mqtt_port);
sensor_console::defineIntCommand("mqtt", setMQTTinterval, F("60 (Sets MQTT sending interval, in s)"));
sensor_console::defineCommand("send_local_ip", sendInfoAboutLocalNetwork,
F("(Sends local IP and SSID via MQTT. Can be useful to find sensor)"));
}
void publish(const char *timestamp, int16_t co2, float temperature, float humidity) {
if (wifi::connected() && mqttClient.connected()) {
led_effects::onBoardLEDOn();
Serial.print(F("MQTT - Publishing message ... "));
char payload[75]; // Should be enough for json...
snprintf(payload, sizeof(payload), json_sensor_format, timestamp, co2, temperature, humidity);
// Topic is the same as clientID. e.g. 'CO2sensors/ESP3d03da'
if (mqttClient.publish(publish_topic, payload)) {
Serial.println(F("OK"));
ntp::getLocalTime(last_successful_publish);
} else {
Serial.println(F("Failed."));
}
led_effects::onBoardLEDOff();
}
}
/**
* Allows sensor to be controlled by commands over MQTT
*
* mosquitto_pub -h MQTT_SERVER -t 'CO2sensors/SENSOR_ID/control' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -m "reset"
* mosquitto_pub -h MQTT_SERVER -t 'CO2sensors/SENSOR_ID/control' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -m "timer 30"
* mosquitto_pub -h MQTT_SERVER -t 'CO2sensors/SENSOR_ID/control' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -m "mqtt 900"
* mosquitto_pub -h MQTT_SERVER -t 'CO2sensors/SENSOR_ID/control' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -m "calibrate 700"
*/
void controlSensorCallback(char *sub_topic, byte *message, unsigned int length) {
if (length == 0) {
return;
}
led_effects::onBoardLEDOn();
Serial.print(F("Message arrived on topic: "));
Serial.println(sub_topic);
char command[length + 1];
for (unsigned int i = 0; i < length; i++) {
command[i] = message[i];
}
command[length] = 0;
sensor_console::execute(command);
led_effects::onBoardLEDOff();
}
void reconnect() {
if (last_failed_at > 0 && (seconds() - last_failed_at < config::wait_after_fail)) {
// It failed less than wait_after_fail ago. Not even trying.
return;
}
if (!wifi::connected()) { //NOTE: Sadly, WiFi.status is sometimes WL_CONNECTED even though it's really not
// No WIFI
return;
}
Serial.print(F("MQTT - Attempting connection to "));
Serial.print(config::mqtt_server);
Serial.print(config::mqtt_encryption ? F(" (Encrypted") : F(" (Unencrypted"));
Serial.print(F(", port "));
Serial.print(config::mqtt_port);
Serial.print(F(") "));
Serial.print(F("User:'"));
Serial.print(config::mqtt_user);
Serial.print(F("' ..."));
led_effects::onBoardLEDOn();
// Wait for connection, at most 15s (default)
mqttClient.connect(publish_topic, config::mqtt_user, config::mqtt_password);
led_effects::onBoardLEDOff();
connected = mqttClient.connected();
if (connected) {
if (config::allow_mqtt_commands) {
char control_topic[60]; // Should be enough for "CO2sensors/ESPd03cc5/control"
snprintf(control_topic, sizeof(control_topic), "%s/control", publish_topic);
mqttClient.subscribe(control_topic);
mqttClient.setCallback(controlSensorCallback);
}
Serial.println(F(" Connected."));
last_failed_at = 0;
} else {
// As defined in PubSubClient, between -4 and 5
const __FlashStringHelper *mqtt_statuses[] = { F("Connection timeout"), F("Connection lost"), F(
"Connection failed"), F("Disconnected"), F("Connected"), F("Bad protocol"), F("Bad client ID"), F(
"Unavailable"), F("Bad credentials"), F("Unauthorized") };
last_failed_at = seconds();
Serial.print(mqtt_statuses[mqttClient.state() + 4]);
Serial.print("! (Code=");
Serial.print(mqttClient.state());
Serial.print(F("). Will try again in "));
Serial.print(config::wait_after_fail);
Serial.println("s.");
}
}
void publishIfTimeHasCome(const char *timestamp, const int16_t &co2, const float &temp, const float &hum) {
// Send message via MQTT according to sending interval
unsigned long now = seconds();
if (now - last_sent_at > config::mqtt_sending_interval) {
last_sent_at = now;
publish(timestamp, co2, temp, hum);
}
}
void keepConnection() {
// Keep MQTT connection
if (!mqttClient.connected()) {
reconnect();
}
mqttClient.loop();
}
/*****************************************************************
* Callbacks for sensor commands *
*****************************************************************/
void setMQTTinterval(int32_t sending_interval) {
config::mqtt_sending_interval = sending_interval;
Serial.print(F("Setting MQTT sending interval to : "));
Serial.print(config::mqtt_sending_interval);
Serial.println(F("s."));
led_effects::showKITTWheel(color::green, 1);
}
// It can be hard to find the local IP of a sensor if it isn't connected to Serial port, and if mDNS is disabled.
// If the sensor can be reach by MQTT, it can answer with info about local_ip and ssid.
// The sensor will send the info to "CO2sensors/ESP123456/info".
void sendInfoAboutLocalNetwork() {
char info_topic[60]; // Should be enough for "CO2sensors/ESP123456/info"
snprintf(info_topic, sizeof(info_topic), "%s/info", publish_topic);
char payload[75]; // Should be enough for info json...
const char *json_info_format = PSTR("{\"local_ip\":\"%s\", \"ssid\":\"%s\"}");
snprintf(payload, sizeof(payload), json_info_format, wifi::local_ip, config::selected_ssid());
mqttClient.publish(info_topic, payload);
}
}
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/mqtt.h 0000664 0000000 0000000 00000000703 14206137734 0025561 0 ustar 00root root 0000000 0000000 #ifndef MQTT_H_INCLUDED
#define MQTT_H_INCLUDED
#include // For uint32_t & uint16_t
namespace mqtt {
extern char last_successful_publish[];
extern bool connected;
void initialize(const char *sensorId);
void keepConnection();
void publishIfTimeHasCome(const char *timestamp, const int16_t &co2, const float &temp, const float &hum);
void setMQTTinterval(int32_t sending_interval);
void sendInfoAboutLocalNetwork();
}
#endif
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/ntp.cpp 0000664 0000000 0000000 00000003252 14206137734 0025732 0 ustar 00root root 0000000 0000000 #include "ntp.h"
#include "sensor_console.h"
#include "web_config.h"
#include // required for NTP
#include "src/lib/NTPClient/NTPClient.h" // NTP
//NOTE: ESP32 sometimes couldn't access the NTP server, and every loop would take +1000ms
// ifdefs could be used to define functions specific to ESP32, e.g. with configTime
namespace ntp {
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
bool connected_at_least_once = false;
void setLocalTime(int32_t unix_seconds);
// Should be defined, even offline
void initialize() {
timeClient.setTimeOffset((config::time_zone + config::daylight_saving_time) * 3600);
sensor_console::defineIntCommand("set_time", ntp::setLocalTime, F("1618829570 (Sets time to the given UNIX time)"));
}
void connect(){
timeClient.setPoolServerName(config::ntp_server);
timeClient.setUpdateInterval(60000UL);
Serial.print("NTP - Trying to connect to : ");
Serial.println(config::ntp_server);
timeClient.begin();
}
void update() {
connected_at_least_once |= timeClient.update();
}
void getLocalTime(char *timestamp) {
timeClient.getFormattedDate(timestamp);
}
void setLocalTime(int32_t unix_seconds) {
char time[23];
timeClient.getFormattedDate(time);
Serial.print(F("Current time : "));
Serial.println(time);
if (connected_at_least_once) {
Serial.println(F("NTP update already happened. Not changing anything."));
return;
}
Serial.print(F("Setting UNIX time to : "));
Serial.println(unix_seconds);
timeClient.setEpochTime(unix_seconds - seconds());
timeClient.getFormattedDate(time);
Serial.print(F("Current time : "));
Serial.println(time);
}
}
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/ntp.h 0000664 0000000 0000000 00000000604 14206137734 0025375 0 ustar 00root root 0000000 0000000 #ifndef AMPEL_TIME_H_INCLUDED
#define AMPEL_TIME_H_INCLUDED
namespace ntp {
extern bool connected_at_least_once;
void initialize();
void connect();
void update();
void getLocalTime(char *timestamp);
}
//NOTE: Only use seconds() for duration comparison, not timestamps comparison. Otherwise, problems happen when millis roll over.
#define seconds() (millis() / 1000UL)
#endif
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/sensor_console.cpp 0000664 0000000 0000000 00000013047 14206137734 0030167 0 ustar 00root root 0000000 0000000 #include "sensor_console.h"
namespace sensor_console {
const uint8_t MAX_COMMANDS = 26;
const uint8_t MAX_COMMAND_SIZE = 40;
uint8_t commands_count = 0;
enum input_type {
NONE,
INT32,
STRING
};
struct Command {
const char *name;
union {
void (*voidFunction)();
void (*intFunction)(int32_t);
void (*strFunction)(char*);
};
const char *doc;
input_type parameter_type;
};
struct CommandLine {
char function_name[MAX_COMMAND_SIZE];
input_type argument_type;
int32_t int_argument;
char str_argument[MAX_COMMAND_SIZE];
};
Command commands[MAX_COMMANDS];
bool addCommand(const char *name, const __FlashStringHelper *doc_fstring) {
if (commands_count < MAX_COMMANDS) {
commands[commands_count].name = name;
commands[commands_count].doc = (const char*) doc_fstring;
return true;
} else {
Serial.println(F("Too many commands have been defined."));
return false;
}
}
void defineCommand(const char *name, void (*function)(), const __FlashStringHelper *doc_fstring) {
if (addCommand(name, doc_fstring)) {
commands[commands_count].voidFunction = function;
commands[commands_count++].parameter_type = NONE;
}
}
void defineIntCommand(const char *name, void (*function)(int32_t), const __FlashStringHelper *doc_fstring) {
if (addCommand(name, doc_fstring)) {
commands[commands_count].intFunction = function;
commands[commands_count++].parameter_type = INT32;
}
}
void defineStringCommand(const char *name, void (*function)(char*), const __FlashStringHelper *doc_fstring) {
if (addCommand(name, doc_fstring)) {
commands[commands_count].strFunction = function;
commands[commands_count++].parameter_type = STRING;
}
}
/*
* Tries to split a string command (e.g. 'mqtt 60' or 'show_csv') into
* a CommandLine struct (function_name, argument_type and argument)
*/
void parseCommand(const char *command, CommandLine &command_line) {
if (strlen(command) == 0) {
Serial.println(F("Received empty command"));
command_line.argument_type = NONE;
return;
}
char *first_space;
first_space = strchr(command, ' ');
if (first_space == NULL) {
command_line.argument_type = NONE;
strlcpy(command_line.function_name, command, MAX_COMMAND_SIZE);
return;
}
strlcpy(command_line.function_name, command, first_space - command + 1);
strlcpy(command_line.str_argument, first_space + 1, MAX_COMMAND_SIZE - (first_space - command) - 1);
char *end;
command_line.int_argument = strtol(command_line.str_argument, &end, 0); // Accepts 123 or 0xFF00FF
if (*end) {
command_line.argument_type = STRING;
} else {
command_line.argument_type = INT32;
}
}
int compareCommandNames(const void *s1, const void *s2) {
struct Command *c1 = (struct Command*) s1;
struct Command *c2 = (struct Command*) s2;
return strcmp(c1->name, c2->name);
}
void listAvailableCommands() {
qsort(commands, commands_count, sizeof(commands[0]), compareCommandNames);
for (uint8_t i = 0; i < commands_count; i++) {
Serial.print(F(" "));
Serial.print(commands[i].name);
Serial.print(F(" "));
Serial.print(commands[i].doc);
Serial.println(F("."));
}
}
/*
* Saves bytes from Serial.read() until enter is pressed, and tries to run the corresponding command.
* http://www.gammon.com.au/serial
*/
void processSerialInput(const byte input_byte) {
static char input_line[MAX_COMMAND_SIZE];
static unsigned int input_pos = 0;
switch (input_byte) {
case '\n': // end of text
Serial.println();
input_line[input_pos] = 0;
execute(input_line);
input_pos = 0;
break;
case '\r': // discard carriage return
break;
case '\b': // backspace
if (input_pos > 0) {
input_pos--;
Serial.print(F("\b \b"));
}
break;
default:
if (input_pos == 0) {
Serial.print(F("> "));
}
// keep adding if not full ... allow for terminating null byte
if (input_pos < (MAX_COMMAND_SIZE - 1)) {
input_line[input_pos++] = input_byte;
Serial.print((char) input_byte);
}
break;
}
}
void checkSerialInput() {
while (Serial.available() > 0) {
sensor_console::processSerialInput(Serial.read());
}
}
/*
* Tries to find the corresponding callback for a given command. Name and parameter type should fit.
*/
void execute(const char *command_str) {
CommandLine input;
parseCommand(command_str, input);
for (uint8_t i = 0; i < commands_count; i++) {
if (!strcmp(input.function_name, commands[i].name) && input.argument_type == commands[i].parameter_type) {
Serial.print(F("Calling : "));
Serial.print(input.function_name);
switch (input.argument_type) {
case NONE:
Serial.println(F("()"));
commands[i].voidFunction();
return;
case INT32:
Serial.print(F("("));
Serial.print(input.int_argument);
Serial.println(F(")"));
commands[i].intFunction(input.int_argument);
return;
case STRING:
Serial.print(F("('"));
Serial.print(input.str_argument);
Serial.println(F("')"));
commands[i].strFunction(input.str_argument);
return;
}
}
}
Serial.print(F("'"));
Serial.print(command_str);
Serial.println(F("' not supported. Available commands :"));
listAvailableCommands();
}
}
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/sensor_console.h 0000664 0000000 0000000 00000001474 14206137734 0027635 0 ustar 00root root 0000000 0000000 #ifndef SENSOR_CONSOLE_H_INCLUDED
#define SENSOR_CONSOLE_H_INCLUDED
#include // For Flash strings, uint8_t and int32_t
/** Other scripts can use this namespace, in order to define commands, via callbacks.
* Those callbacks can then be used to send commands to the sensor (reset, calibrate, led on/off, ...)
* The callbacks can either have no parameter, or one int32_t parameter.
*/
namespace sensor_console {
void defineCommand(const char *name, void (*function)(), const __FlashStringHelper *doc_fstring);
void defineIntCommand(const char *name, void (*function)(int32_t), const __FlashStringHelper *doc_fstring);
void defineStringCommand(const char *name, void (*function)(char*), const __FlashStringHelper *doc_fstring);
void checkSerialInput();
void execute(const char *command_line);
}
#endif
ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/src/ 0000775 0000000 0000000 00000000000 14206137734 0025212 5 ustar 00root root 0000000 0000000 ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/src/lib/ 0000775 0000000 0000000 00000000000 14206137734 0025760 5 ustar 00root root 0000000 0000000 ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/src/lib/Adafruit_NeoPixel/ 0000775 0000000 0000000 00000000000 14206137734 0031322 5 ustar 00root root 0000000 0000000 Adafruit_NeoPixel.cpp 0000664 0000000 0000000 00000352444 14206137734 0035325 0 ustar 00root root 0000000 0000000 ampel-firmware-86f353e8dc0c66015e18cf5a40c25dc7fc347a7a/ampel-firmware/src/lib/Adafruit_NeoPixel /*!
* @file Adafruit_NeoPixel.cpp
*
* @mainpage Arduino Library for driving Adafruit NeoPixel addressable LEDs,
* FLORA RGB Smart Pixels and compatible devicess -- WS2811, WS2812, WS2812B,
* SK6812, etc.
*
* @section intro_sec Introduction
*
* This is the documentation for Adafruit's NeoPixel library for the
* Arduino platform, allowing a broad range of microcontroller boards
* (most AVR boards, many ARM devices, ESP8266 and ESP32, among others)
* to control Adafruit NeoPixels, FLORA RGB Smart Pixels and compatible
* devices -- WS2811, WS2812, WS2812B, SK6812, etc.
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing products
* from Adafruit!
*
* @section author Author
*
* Written by Phil "Paint Your Dragon" Burgess for Adafruit Industries,
* with contributions by PJRC, Michael Miller and other members of the
* open source community.
*
* @section license License
*
* This file is part of the Adafruit_NeoPixel library.
*
* Adafruit_NeoPixel 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.
*
* Adafruit_NeoPixel is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with NeoPixel. If not, see
* .
*
*/
#include "Adafruit_NeoPixel.h"
#if defined(TARGET_LPC1768)
#include
#endif
#if defined(NRF52) || defined(NRF52_SERIES)
#include "nrf.h"
// Interrupt is only disabled if there is no PWM device available
// Note: Adafruit Bluefruit nrf52 does not use this option
//#define NRF52_DISABLE_INT
#endif
#if defined(ARDUINO_ARCH_NRF52840)
#if defined __has_include
#if __has_include()
#include
#endif
#endif
#endif
/*!
@brief NeoPixel constructor when length, pin and pixel type are known
at compile-time.
@param n Number of NeoPixels in strand.
@param p Arduino pin number which will drive the NeoPixel data in.
@param t Pixel type -- add together NEO_* constants defined in
Adafruit_NeoPixel.h, for example NEO_GRB+NEO_KHZ800 for
NeoPixels expecting an 800 KHz (vs 400 KHz) data stream
with color bytes expressed in green, red, blue order per
pixel.
@return Adafruit_NeoPixel object. Call the begin() function before use.
*/
Adafruit_NeoPixel::Adafruit_NeoPixel(uint16_t n, int16_t p, neoPixelType t)
: begun(false), brightness(0), pixels(NULL), endTime(0) {
updateType(t);
updateLength(n);
setPin(p);
#if defined(ARDUINO_ARCH_RP2040)
// Find a free SM on one of the PIO's
sm = pio_claim_unused_sm(pio, false); // don't panic
// Try pio1 if SM not found
if (sm < 0) {
pio = pio1;
sm = pio_claim_unused_sm(pio, true); // panic if no SM is free
}
init = true;
#endif
}
/*!
@brief "Empty" NeoPixel constructor when length, pin and/or pixel type
are not known at compile-time, and must be initialized later with
updateType(), updateLength() and setPin().
@return Adafruit_NeoPixel object. Call the begin() function before use.
@note This function is deprecated, here only for old projects that
may still be calling it. New projects should instead use the
'new' keyword with the first constructor syntax (length, pin,
type).
*/
Adafruit_NeoPixel::Adafruit_NeoPixel()
:
#if defined(NEO_KHZ400)
is800KHz(true),
#endif
begun(false), numLEDs(0), numBytes(0), pin(-1), brightness(0),
pixels(NULL), rOffset(1), gOffset(0), bOffset(2), wOffset(1), endTime(0) {
}
/*!
@brief Deallocate Adafruit_NeoPixel object, set data pin back to INPUT.
*/
Adafruit_NeoPixel::~Adafruit_NeoPixel() {
free(pixels);
if (pin >= 0)
pinMode(pin, INPUT);
}
/*!
@brief Configure NeoPixel pin for output.
*/
void Adafruit_NeoPixel::begin(void) {
if (pin >= 0) {
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
}
begun = true;
}
/*!
@brief Change the length of a previously-declared Adafruit_NeoPixel
strip object. Old data is deallocated and new data is cleared.
Pin number and pixel format are unchanged.
@param n New length of strip, in pixels.
@note This function is deprecated, here only for old projects that
may still be calling it. New projects should instead use the
'new' keyword with the first constructor syntax (length, pin,
type).
*/
void Adafruit_NeoPixel::updateLength(uint16_t n) {
free(pixels); // Free existing data (if any)
// Allocate new data -- note: ALL PIXELS ARE CLEARED
numBytes = n * ((wOffset == rOffset) ? 3 : 4);
if ((pixels = (uint8_t *)malloc(numBytes))) {
memset(pixels, 0, numBytes);
numLEDs = n;
} else {
numLEDs = numBytes = 0;
}
}
/*!
@brief Change the pixel format of a previously-declared
Adafruit_NeoPixel strip object. If format changes from one of
the RGB variants to an RGBW variant (or RGBW to RGB), the old
data will be deallocated and new data is cleared. Otherwise,
the old data will remain in RAM and is not reordered to the
new format, so it's advisable to follow up with clear().
@param t Pixel type -- add together NEO_* constants defined in
Adafruit_NeoPixel.h, for example NEO_GRB+NEO_KHZ800 for
NeoPixels expecting an 800 KHz (vs 400 KHz) data stream
with color bytes expressed in green, red, blue order per
pixel.
@note This function is deprecated, here only for old projects that
may still be calling it. New projects should instead use the
'new' keyword with the first constructor syntax
(length, pin, type).
*/
void Adafruit_NeoPixel::updateType(neoPixelType t) {
bool oldThreeBytesPerPixel = (wOffset == rOffset); // false if RGBW
wOffset = (t >> 6) & 0b11; // See notes in header file
rOffset = (t >> 4) & 0b11; // regarding R/G/B/W offsets
gOffset = (t >> 2) & 0b11;
bOffset = t & 0b11;
#if defined(NEO_KHZ400)
is800KHz = (t < 256); // 400 KHz flag is 1<<8
#endif
// If bytes-per-pixel has changed (and pixel data was previously
// allocated), re-allocate to new size. Will clear any data.
if (pixels) {
bool newThreeBytesPerPixel = (wOffset == rOffset);
if (newThreeBytesPerPixel != oldThreeBytesPerPixel)
updateLength(numLEDs);
}
}
// RP2040 specific driver
#if defined(ARDUINO_ARCH_RP2040)
void Adafruit_NeoPixel::rp2040Init(uint8_t pin, bool is800KHz)
{
uint offset = pio_add_program(pio, &ws2812_program);
if (is800KHz)
{
// 800kHz, 8 bit transfers
ws2812_program_init(pio, sm, offset, pin, 800000, 8);
}
else
{
// 400kHz, 8 bit transfers
ws2812_program_init(pio, sm, offset, pin, 400000, 8);
}
}
// Not a user API
void Adafruit_NeoPixel::rp2040Show(uint8_t pin, uint8_t *pixels, uint32_t numBytes, bool is800KHz)
{
if (this->init)
{
// On first pass through initialise the PIO
rp2040Init(pin, is800KHz);
this->init = false;
}
while(numBytes--)
// Bits for transmission must be shifted to top 8 bits
pio_sm_put_blocking(pio, sm, ((uint32_t)*pixels++)<< 24);
}
#endif
#if defined(ESP8266)
// ESP8266 show() is external to enforce ICACHE_RAM_ATTR execution
extern "C" IRAM_ATTR void espShow(uint16_t pin, uint8_t *pixels,
uint32_t numBytes, uint8_t type);
#elif defined(ESP32)
extern "C" void espShow(uint16_t pin, uint8_t *pixels, uint32_t numBytes,
uint8_t type);
#endif // ESP8266
#if defined(K210)
#define KENDRYTE_K210 1
#endif
#if defined(KENDRYTE_K210)
extern "C" void k210Show(uint8_t pin, uint8_t *pixels, uint32_t numBytes,
boolean is800KHz);
#endif // KENDRYTE_K210
/*!
@brief Transmit pixel data in RAM to NeoPixels.
@note On most architectures, interrupts are temporarily disabled in
order to achieve the correct NeoPixel signal timing. This means
that the Arduino millis() and micros() functions, which require
interrupts, will lose small intervals of time whenever this
function is called (about 30 microseconds per RGB pixel, 40 for
RGBW pixels). There's no easy fix for this, but a few
specialized alternative or companion libraries exist that use
very device-specific peripherals to work around it.
*/
void Adafruit_NeoPixel::show(void) {
if (!pixels)
return;
// Data latch = 300+ microsecond pause in the output stream. Rather than
// put a delay at the end of the function, the ending time is noted and
// the function will simply hold off (if needed) on issuing the
// subsequent round of data until the latch time has elapsed. This
// allows the mainline code to start generating the next frame of data
// rather than stalling for the latch.
while (!canShow())
;
// endTime is a private member (rather than global var) so that multiple
// instances on different pins can be quickly issued in succession (each
// instance doesn't delay the next).
// In order to make this code runtime-configurable to work with any pin,
// SBI/CBI instructions are eschewed in favor of full PORT writes via the
// OUT or ST instructions. It relies on two facts: that peripheral
// functions (such as PWM) take precedence on output pins, so our PORT-
// wide writes won't interfere, and that interrupts are globally disabled
// while data is being issued to the LEDs, so no other code will be
// accessing the PORT. The code takes an initial 'snapshot' of the PORT
// state, computes 'pin high' and 'pin low' values, and writes these back
// to the PORT register as needed.
// NRF52 may use PWM + DMA (if available), may not need to disable interrupt
#if !(defined(NRF52) || defined(NRF52_SERIES))
noInterrupts(); // Need 100% focus on instruction timing
#endif
#if defined(__AVR__)
// AVR MCUs -- ATmega & ATtiny (no XMEGA) ---------------------------------
volatile uint16_t i = numBytes; // Loop counter
volatile uint8_t *ptr = pixels, // Pointer to next byte
b = *ptr++, // Current byte value
hi, // PORT w/output bit set high
lo; // PORT w/output bit set low
// Hand-tuned assembly code issues data to the LED drivers at a specific
// rate. There's separate code for different CPU speeds (8, 12, 16 MHz)
// for both the WS2811 (400 KHz) and WS2812 (800 KHz) drivers. The
// datastream timing for the LED drivers allows a little wiggle room each
// way (listed in the datasheets), so the conditions for compiling each
// case are set up for a range of frequencies rather than just the exact
// 8, 12 or 16 MHz values, permitting use with some close-but-not-spot-on
// devices (e.g. 16.5 MHz DigiSpark). The ranges were arrived at based
// on the datasheet figures and have not been extensively tested outside
// the canonical 8/12/16 MHz speeds; there's no guarantee these will work
// close to the extremes (or possibly they could be pushed further).
// Keep in mind only one CPU speed case actually gets compiled; the
// resulting program isn't as massive as it might look from source here.
// 8 MHz(ish) AVR ---------------------------------------------------------
#if (F_CPU >= 7400000UL) && (F_CPU <= 9500000UL)
#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled
if (is800KHz) {
#endif
volatile uint8_t n1, n2 = 0; // First, next bits out
// Squeezing an 800 KHz stream out of an 8 MHz chip requires code
// specific to each PORT register.
// 10 instruction clocks per bit: HHxxxxxLLL
// OUT instructions: ^ ^ ^ (T=0,2,7)
// PORTD OUTPUT ----------------------------------------------------
#if defined(PORTD)
#if defined(PORTB) || defined(PORTC) || defined(PORTF)
if (port == &PORTD) {
#endif // defined(PORTB/C/F)
hi = PORTD | pinMask;
lo = PORTD & ~pinMask;
n1 = lo;
if (b & 0x80)
n1 = hi;
// Dirty trick: RJMPs proceeding to the next instruction are used
// to delay two clock cycles in one instruction word (rather than
// using two NOPs). This was necessary in order to squeeze the
// loop down to exactly 64 words -- the maximum possible for a
// relative branch.
asm volatile(
"headD:"
"\n\t" // Clk Pseudocode
// Bit 7:
"out %[port] , %[hi]"
"\n\t" // 1 PORT = hi
"mov %[n2] , %[lo]"
"\n\t" // 1 n2 = lo
"out %[port] , %[n1]"
"\n\t" // 1 PORT = n1
"rjmp .+0"
"\n\t" // 2 nop nop
"sbrc %[byte] , 6"
"\n\t" // 1-2 if(b & 0x40)
"mov %[n2] , %[hi]"
"\n\t" // 0-1 n2 = hi
"out %[port] , %[lo]"
"\n\t" // 1 PORT = lo
"rjmp .+0"
"\n\t" // 2 nop nop
// Bit 6:
"out %[port] , %[hi]"
"\n\t" // 1 PORT = hi
"mov %[n1] , %[lo]"
"\n\t" // 1 n1 = lo
"out %[port] , %[n2]"
"\n\t" // 1 PORT = n2
"rjmp .+0"
"\n\t" // 2 nop nop
"sbrc %[byte] , 5"
"\n\t" // 1-2 if(b & 0x20)
"mov %[n1] , %[hi]"
"\n\t" // 0-1 n1 = hi
"out %[port] , %[lo]"
"\n\t" // 1 PORT = lo
"rjmp .+0"
"\n\t" // 2 nop nop
// Bit 5:
"out %[port] , %[hi]"
"\n\t" // 1 PORT = hi
"mov %[n2] , %[lo]"
"\n\t" // 1 n2 = lo
"out %[port] , %[n1]"
"\n\t" // 1 PORT = n1
"rjmp .+0"
"\n\t" // 2 nop nop
"sbrc %[byte] , 4"
"\n\t" // 1-2 if(b & 0x10)
"mov %[n2] , %[hi]"
"\n\t" // 0-1 n2 = hi
"out %[port] , %[lo]"
"\n\t" // 1 PORT = lo
"rjmp .+0"
"\n\t" // 2 nop nop
// Bit 4:
"out %[port] , %[hi]"
"\n\t" // 1 PORT = hi
"mov %[n1] , %[lo]"
"\n\t" // 1 n1 = lo
"out %[port] , %[n2]"
"\n\t" // 1 PORT = n2
"rjmp .+0"
"\n\t" // 2 nop nop
"sbrc %[byte] , 3"
"\n\t" // 1-2 if(b & 0x08)
"mov %[n1] , %[hi]"
"\n\t" // 0-1 n1 = hi
"out %[port] , %[lo]"
"\n\t" // 1 PORT = lo
"rjmp .+0"
"\n\t" // 2 nop nop
// Bit 3:
"out %[port] , %[hi]"
"\n\t" // 1 PORT = hi
"mov %[n2] , %[lo]"
"\n\t" // 1 n2 = lo
"out %[port] , %[n1]"
"\n\t" // 1 PORT = n1
"rjmp .+0"
"\n\t" // 2 nop nop
"sbrc %[byte] , 2"
"\n\t" // 1-2 if(b & 0x04)
"mov %[n2] , %[hi]"
"\n\t" // 0-1 n2 = hi
"out %[port] , %[lo]"
"\n\t" // 1 PORT = lo
"rjmp .+0"
"\n\t" // 2 nop nop
// Bit 2:
"out %[port] , %[hi]"
"\n\t" // 1 PORT = hi
"mov %[n1] , %[lo]"
"\n\t" // 1 n1 = lo
"out %[port] , %[n2]"
"\n\t" // 1 PORT = n2
"rjmp .+0"
"\n\t" // 2 nop nop
"sbrc %[byte] , 1"
"\n\t" // 1-2 if(b & 0x02)
"mov %[n1] , %[hi]"
"\n\t" // 0-1 n1 = hi
"out %[port] , %[lo]"
"\n\t" // 1 PORT = lo
"rjmp .+0"
"\n\t" // 2 nop nop
// Bit 1:
"out %[port] , %[hi]"
"\n\t" // 1 PORT = hi
"mov %[n2] , %[lo]"
"\n\t" // 1 n2 = lo
"out %[port] , %[n1]"
"\n\t" // 1 PORT = n1
"rjmp .+0"
"\n\t" // 2 nop nop
"sbrc %[byte] , 0"
"\n\t" // 1-2 if(b & 0x01)
"mov %[n2] , %[hi]"
"\n\t" // 0-1 n2 = hi
"out %[port] , %[lo]"
"\n\t" // 1 PORT = lo
"sbiw %[count], 1"
"\n\t" // 2 i-- (don't act on Z flag yet)
// Bit 0:
"out %[port] , %[hi]"
"\n\t" // 1 PORT = hi
"mov %[n1] , %[lo]"
"\n\t" // 1 n1 = lo
"out %[port] , %[n2]"
"\n\t" // 1 PORT = n2
"ld %[byte] , %a[ptr]+"
"\n\t" // 2 b = *ptr++
"sbrc %[byte] , 7"
"\n\t" // 1-2 if(b & 0x80)
"mov %[n1] , %[hi]"
"\n\t" // 0-1 n1 = hi
"out %[port] , %[lo]"
"\n\t" // 1 PORT = lo
"brne headD"
"\n" // 2 while(i) (Z flag set above)
: [byte] "+r"(b), [n1] "+r"(n1), [n2] "+r"(n2), [count] "+w"(i)
: [port] "I"(_SFR_IO_ADDR(PORTD)), [ptr] "e"(ptr), [hi] "r"(hi),
[lo] "r"(lo));
#if defined(PORTB) || defined(PORTC) || defined(PORTF)
} else // other PORT(s)
#endif // defined(PORTB/C/F)
#endif // defined(PORTD)
// PORTB OUTPUT ----------------------------------------------------
#if defined(PORTB)
#if defined(PORTD) || defined(PORTC) || defined(PORTF)
if (port == &PORTB) {
#endif // defined(PORTD/C/F)
// Same as above, just switched to PORTB and stripped of comments.
hi = PORTB | pinMask;
lo = PORTB & ~pinMask;
n1 = lo;
if (b & 0x80)
n1 = hi;
asm volatile(
"headB:"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n2] , %[lo]"
"\n\t"
"out %[port] , %[n1]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 6"
"\n\t"
"mov %[n2] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"rjmp .+0"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n1] , %[lo]"
"\n\t"
"out %[port] , %[n2]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 5"
"\n\t"
"mov %[n1] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"rjmp .+0"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n2] , %[lo]"
"\n\t"
"out %[port] , %[n1]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 4"
"\n\t"
"mov %[n2] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"rjmp .+0"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n1] , %[lo]"
"\n\t"
"out %[port] , %[n2]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 3"
"\n\t"
"mov %[n1] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"rjmp .+0"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n2] , %[lo]"
"\n\t"
"out %[port] , %[n1]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 2"
"\n\t"
"mov %[n2] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"rjmp .+0"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n1] , %[lo]"
"\n\t"
"out %[port] , %[n2]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 1"
"\n\t"
"mov %[n1] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"rjmp .+0"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n2] , %[lo]"
"\n\t"
"out %[port] , %[n1]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 0"
"\n\t"
"mov %[n2] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"sbiw %[count], 1"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n1] , %[lo]"
"\n\t"
"out %[port] , %[n2]"
"\n\t"
"ld %[byte] , %a[ptr]+"
"\n\t"
"sbrc %[byte] , 7"
"\n\t"
"mov %[n1] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"brne headB"
"\n"
: [byte] "+r"(b), [n1] "+r"(n1), [n2] "+r"(n2), [count] "+w"(i)
: [port] "I"(_SFR_IO_ADDR(PORTB)), [ptr] "e"(ptr), [hi] "r"(hi),
[lo] "r"(lo));
#if defined(PORTD) || defined(PORTC) || defined(PORTF)
}
#endif
#if defined(PORTC) || defined(PORTF)
else
#endif // defined(PORTC/F)
#endif // defined(PORTB)
// PORTC OUTPUT ----------------------------------------------------
#if defined(PORTC)
#if defined(PORTD) || defined(PORTB) || defined(PORTF)
if (port == &PORTC) {
#endif // defined(PORTD/B/F)
// Same as above, just switched to PORTC and stripped of comments.
hi = PORTC | pinMask;
lo = PORTC & ~pinMask;
n1 = lo;
if (b & 0x80)
n1 = hi;
asm volatile(
"headC:"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n2] , %[lo]"
"\n\t"
"out %[port] , %[n1]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 6"
"\n\t"
"mov %[n2] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"rjmp .+0"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n1] , %[lo]"
"\n\t"
"out %[port] , %[n2]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 5"
"\n\t"
"mov %[n1] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"rjmp .+0"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n2] , %[lo]"
"\n\t"
"out %[port] , %[n1]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 4"
"\n\t"
"mov %[n2] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"rjmp .+0"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n1] , %[lo]"
"\n\t"
"out %[port] , %[n2]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 3"
"\n\t"
"mov %[n1] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"rjmp .+0"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n2] , %[lo]"
"\n\t"
"out %[port] , %[n1]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 2"
"\n\t"
"mov %[n2] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"rjmp .+0"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n1] , %[lo]"
"\n\t"
"out %[port] , %[n2]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 1"
"\n\t"
"mov %[n1] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"rjmp .+0"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n2] , %[lo]"
"\n\t"
"out %[port] , %[n1]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 0"
"\n\t"
"mov %[n2] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"sbiw %[count], 1"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n1] , %[lo]"
"\n\t"
"out %[port] , %[n2]"
"\n\t"
"ld %[byte] , %a[ptr]+"
"\n\t"
"sbrc %[byte] , 7"
"\n\t"
"mov %[n1] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"brne headC"
"\n"
: [byte] "+r"(b), [n1] "+r"(n1), [n2] "+r"(n2), [count] "+w"(i)
: [port] "I"(_SFR_IO_ADDR(PORTC)), [ptr] "e"(ptr), [hi] "r"(hi),
[lo] "r"(lo));
#if defined(PORTD) || defined(PORTB) || defined(PORTF)
}
#endif // defined(PORTD/B/F)
#if defined(PORTF)
else
#endif
#endif // defined(PORTC)
// PORTF OUTPUT ----------------------------------------------------
#if defined(PORTF)
#if defined(PORTD) || defined(PORTB) || defined(PORTC)
if (port == &PORTF) {
#endif // defined(PORTD/B/C)
hi = PORTF | pinMask;
lo = PORTF & ~pinMask;
n1 = lo;
if (b & 0x80)
n1 = hi;
asm volatile(
"headF:"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n2] , %[lo]"
"\n\t"
"out %[port] , %[n1]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 6"
"\n\t"
"mov %[n2] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"rjmp .+0"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n1] , %[lo]"
"\n\t"
"out %[port] , %[n2]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 5"
"\n\t"
"mov %[n1] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"rjmp .+0"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n2] , %[lo]"
"\n\t"
"out %[port] , %[n1]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 4"
"\n\t"
"mov %[n2] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"rjmp .+0"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n1] , %[lo]"
"\n\t"
"out %[port] , %[n2]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 3"
"\n\t"
"mov %[n1] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"rjmp .+0"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n2] , %[lo]"
"\n\t"
"out %[port] , %[n1]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 2"
"\n\t"
"mov %[n2] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"rjmp .+0"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n1] , %[lo]"
"\n\t"
"out %[port] , %[n2]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 1"
"\n\t"
"mov %[n1] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"rjmp .+0"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n2] , %[lo]"
"\n\t"
"out %[port] , %[n1]"
"\n\t"
"rjmp .+0"
"\n\t"
"sbrc %[byte] , 0"
"\n\t"
"mov %[n2] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"sbiw %[count], 1"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"mov %[n1] , %[lo]"
"\n\t"
"out %[port] , %[n2]"
"\n\t"
"ld %[byte] , %a[ptr]+"
"\n\t"
"sbrc %[byte] , 7"
"\n\t"
"mov %[n1] , %[hi]"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"brne headF"
"\n"
: [byte] "+r"(b), [n1] "+r"(n1), [n2] "+r"(n2), [count] "+w"(i)
: [port] "I"(_SFR_IO_ADDR(PORTF)), [ptr] "e"(ptr), [hi] "r"(hi),
[lo] "r"(lo));
#if defined(PORTD) || defined(PORTB) || defined(PORTC)
}
#endif // defined(PORTD/B/C)
#endif // defined(PORTF)
#if defined(NEO_KHZ400)
} else { // end 800 KHz, do 400 KHz
// Timing is more relaxed; unrolling the inner loop for each bit is
// not necessary. Still using the peculiar RJMPs as 2X NOPs, not out
// of need but just to trim the code size down a little.
// This 400-KHz-datastream-on-8-MHz-CPU code is not quite identical
// to the 800-on-16 code later -- the hi/lo timing between WS2811 and
// WS2812 is not simply a 2:1 scale!
// 20 inst. clocks per bit: HHHHxxxxxxLLLLLLLLLL
// ST instructions: ^ ^ ^ (T=0,4,10)
volatile uint8_t next, bit;
hi = *port | pinMask;
lo = *port & ~pinMask;
next = lo;
bit = 8;
asm volatile("head20:"
"\n\t" // Clk Pseudocode (T = 0)
"st %a[port], %[hi]"
"\n\t" // 2 PORT = hi (T = 2)
"sbrc %[byte] , 7"
"\n\t" // 1-2 if(b & 128)
"mov %[next], %[hi]"
"\n\t" // 0-1 next = hi (T = 4)
"st %a[port], %[next]"
"\n\t" // 2 PORT = next (T = 6)
"mov %[next] , %[lo]"
"\n\t" // 1 next = lo (T = 7)
"dec %[bit]"
"\n\t" // 1 bit-- (T = 8)
"breq nextbyte20"
"\n\t" // 1-2 if(bit == 0)
"rol %[byte]"
"\n\t" // 1 b <<= 1 (T = 10)
"st %a[port], %[lo]"
"\n\t" // 2 PORT = lo (T = 12)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 14)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 16)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 18)
"rjmp head20"
"\n\t" // 2 -> head20 (next bit out)
"nextbyte20:"
"\n\t" // (T = 10)
"st %a[port], %[lo]"
"\n\t" // 2 PORT = lo (T = 12)
"nop"
"\n\t" // 1 nop (T = 13)
"ldi %[bit] , 8"
"\n\t" // 1 bit = 8 (T = 14)
"ld %[byte] , %a[ptr]+"
"\n\t" // 2 b = *ptr++ (T = 16)
"sbiw %[count], 1"
"\n\t" // 2 i-- (T = 18)
"brne head20"
"\n" // 2 if(i != 0) -> (next byte)
: [port] "+e"(port), [byte] "+r"(b), [bit] "+r"(bit),
[next] "+r"(next), [count] "+w"(i)
: [hi] "r"(hi), [lo] "r"(lo), [ptr] "e"(ptr));
}
#endif // NEO_KHZ400
// 12 MHz(ish) AVR --------------------------------------------------------
#elif (F_CPU >= 11100000UL) && (F_CPU <= 14300000UL)
#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled
if (is800KHz) {
#endif
// In the 12 MHz case, an optimized 800 KHz datastream (no dead time
// between bytes) requires a PORT-specific loop similar to the 8 MHz
// code (but a little more relaxed in this case).
// 15 instruction clocks per bit: HHHHxxxxxxLLLLL
// OUT instructions: ^ ^ ^ (T=0,4,10)
volatile uint8_t next;
// PORTD OUTPUT ----------------------------------------------------
#if defined(PORTD)
#if defined(PORTB) || defined(PORTC) || defined(PORTF)
if (port == &PORTD) {
#endif // defined(PORTB/C/F)
hi = PORTD | pinMask;
lo = PORTD & ~pinMask;
next = lo;
if (b & 0x80)
next = hi;
// Don't "optimize" the OUT calls into the bitTime subroutine;
// we're exploiting the RCALL and RET as 3- and 4-cycle NOPs!
asm volatile("headD:"
"\n\t" // (T = 0)
"out %[port], %[hi]"
"\n\t" // (T = 1)
"rcall bitTimeD"
"\n\t" // Bit 7 (T = 15)
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeD"
"\n\t" // Bit 6
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeD"
"\n\t" // Bit 5
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeD"
"\n\t" // Bit 4
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeD"
"\n\t" // Bit 3
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeD"
"\n\t" // Bit 2
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeD"
"\n\t" // Bit 1
// Bit 0:
"out %[port] , %[hi]"
"\n\t" // 1 PORT = hi (T = 1)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 3)
"ld %[byte] , %a[ptr]+"
"\n\t" // 2 b = *ptr++ (T = 5)
"out %[port] , %[next]"
"\n\t" // 1 PORT = next (T = 6)
"mov %[next] , %[lo]"
"\n\t" // 1 next = lo (T = 7)
"sbrc %[byte] , 7"
"\n\t" // 1-2 if(b & 0x80) (T = 8)
"mov %[next] , %[hi]"
"\n\t" // 0-1 next = hi (T = 9)
"nop"
"\n\t" // 1 (T = 10)
"out %[port] , %[lo]"
"\n\t" // 1 PORT = lo (T = 11)
"sbiw %[count], 1"
"\n\t" // 2 i-- (T = 13)
"brne headD"
"\n\t" // 2 if(i != 0) -> (next byte)
"rjmp doneD"
"\n\t"
"bitTimeD:"
"\n\t" // nop nop nop (T = 4)
"out %[port], %[next]"
"\n\t" // 1 PORT = next (T = 5)
"mov %[next], %[lo]"
"\n\t" // 1 next = lo (T = 6)
"rol %[byte]"
"\n\t" // 1 b <<= 1 (T = 7)
"sbrc %[byte], 7"
"\n\t" // 1-2 if(b & 0x80) (T = 8)
"mov %[next], %[hi]"
"\n\t" // 0-1 next = hi (T = 9)
"nop"
"\n\t" // 1 (T = 10)
"out %[port], %[lo]"
"\n\t" // 1 PORT = lo (T = 11)
"ret"
"\n\t" // 4 nop nop nop nop (T = 15)
"doneD:"
"\n"
: [byte] "+r"(b), [next] "+r"(next), [count] "+w"(i)
: [port] "I"(_SFR_IO_ADDR(PORTD)), [ptr] "e"(ptr),
[hi] "r"(hi), [lo] "r"(lo));
#if defined(PORTB) || defined(PORTC) || defined(PORTF)
} else // other PORT(s)
#endif // defined(PORTB/C/F)
#endif // defined(PORTD)
// PORTB OUTPUT ----------------------------------------------------
#if defined(PORTB)
#if defined(PORTD) || defined(PORTC) || defined(PORTF)
if (port == &PORTB) {
#endif // defined(PORTD/C/F)
hi = PORTB | pinMask;
lo = PORTB & ~pinMask;
next = lo;
if (b & 0x80)
next = hi;
// Same as above, just set for PORTB & stripped of comments
asm volatile("headB:"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeB"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeB"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeB"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeB"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeB"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeB"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeB"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"rjmp .+0"
"\n\t"
"ld %[byte] , %a[ptr]+"
"\n\t"
"out %[port] , %[next]"
"\n\t"
"mov %[next] , %[lo]"
"\n\t"
"sbrc %[byte] , 7"
"\n\t"
"mov %[next] , %[hi]"
"\n\t"
"nop"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"sbiw %[count], 1"
"\n\t"
"brne headB"
"\n\t"
"rjmp doneB"
"\n\t"
"bitTimeB:"
"\n\t"
"out %[port], %[next]"
"\n\t"
"mov %[next], %[lo]"
"\n\t"
"rol %[byte]"
"\n\t"
"sbrc %[byte], 7"
"\n\t"
"mov %[next], %[hi]"
"\n\t"
"nop"
"\n\t"
"out %[port], %[lo]"
"\n\t"
"ret"
"\n\t"
"doneB:"
"\n"
: [byte] "+r"(b), [next] "+r"(next), [count] "+w"(i)
: [port] "I"(_SFR_IO_ADDR(PORTB)), [ptr] "e"(ptr),
[hi] "r"(hi), [lo] "r"(lo));
#if defined(PORTD) || defined(PORTC) || defined(PORTF)
}
#endif
#if defined(PORTC) || defined(PORTF)
else
#endif // defined(PORTC/F)
#endif // defined(PORTB)
// PORTC OUTPUT ----------------------------------------------------
#if defined(PORTC)
#if defined(PORTD) || defined(PORTB) || defined(PORTF)
if (port == &PORTC) {
#endif // defined(PORTD/B/F)
hi = PORTC | pinMask;
lo = PORTC & ~pinMask;
next = lo;
if (b & 0x80)
next = hi;
// Same as above, just set for PORTC & stripped of comments
asm volatile("headC:"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeC"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeC"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeC"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeC"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeC"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeC"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeC"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"rjmp .+0"
"\n\t"
"ld %[byte] , %a[ptr]+"
"\n\t"
"out %[port] , %[next]"
"\n\t"
"mov %[next] , %[lo]"
"\n\t"
"sbrc %[byte] , 7"
"\n\t"
"mov %[next] , %[hi]"
"\n\t"
"nop"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"sbiw %[count], 1"
"\n\t"
"brne headC"
"\n\t"
"rjmp doneC"
"\n\t"
"bitTimeC:"
"\n\t"
"out %[port], %[next]"
"\n\t"
"mov %[next], %[lo]"
"\n\t"
"rol %[byte]"
"\n\t"
"sbrc %[byte], 7"
"\n\t"
"mov %[next], %[hi]"
"\n\t"
"nop"
"\n\t"
"out %[port], %[lo]"
"\n\t"
"ret"
"\n\t"
"doneC:"
"\n"
: [byte] "+r"(b), [next] "+r"(next), [count] "+w"(i)
: [port] "I"(_SFR_IO_ADDR(PORTC)), [ptr] "e"(ptr),
[hi] "r"(hi), [lo] "r"(lo));
#if defined(PORTD) || defined(PORTB) || defined(PORTF)
}
#endif // defined(PORTD/B/F)
#if defined(PORTF)
else
#endif
#endif // defined(PORTC)
// PORTF OUTPUT ----------------------------------------------------
#if defined(PORTF)
#if defined(PORTD) || defined(PORTB) || defined(PORTC)
if (port == &PORTF) {
#endif // defined(PORTD/B/C)
hi = PORTF | pinMask;
lo = PORTF & ~pinMask;
next = lo;
if (b & 0x80)
next = hi;
// Same as above, just set for PORTF & stripped of comments
asm volatile("headF:"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeC"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeC"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeC"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeC"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeC"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeC"
"\n\t"
"out %[port], %[hi]"
"\n\t"
"rcall bitTimeC"
"\n\t"
"out %[port] , %[hi]"
"\n\t"
"rjmp .+0"
"\n\t"
"ld %[byte] , %a[ptr]+"
"\n\t"
"out %[port] , %[next]"
"\n\t"
"mov %[next] , %[lo]"
"\n\t"
"sbrc %[byte] , 7"
"\n\t"
"mov %[next] , %[hi]"
"\n\t"
"nop"
"\n\t"
"out %[port] , %[lo]"
"\n\t"
"sbiw %[count], 1"
"\n\t"
"brne headF"
"\n\t"
"rjmp doneC"
"\n\t"
"bitTimeC:"
"\n\t"
"out %[port], %[next]"
"\n\t"
"mov %[next], %[lo]"
"\n\t"
"rol %[byte]"
"\n\t"
"sbrc %[byte], 7"
"\n\t"
"mov %[next], %[hi]"
"\n\t"
"nop"
"\n\t"
"out %[port], %[lo]"
"\n\t"
"ret"
"\n\t"
"doneC:"
"\n"
: [byte] "+r"(b), [next] "+r"(next), [count] "+w"(i)
: [port] "I"(_SFR_IO_ADDR(PORTF)), [ptr] "e"(ptr),
[hi] "r"(hi), [lo] "r"(lo));
#if defined(PORTD) || defined(PORTB) || defined(PORTC)
}
#endif // defined(PORTD/B/C)
#endif // defined(PORTF)
#if defined(NEO_KHZ400)
} else { // 400 KHz
// 30 instruction clocks per bit: HHHHHHxxxxxxxxxLLLLLLLLLLLLLLL
// ST instructions: ^ ^ ^ (T=0,6,15)
volatile uint8_t next, bit;
hi = *port | pinMask;
lo = *port & ~pinMask;
next = lo;
bit = 8;
asm volatile("head30:"
"\n\t" // Clk Pseudocode (T = 0)
"st %a[port], %[hi]"
"\n\t" // 2 PORT = hi (T = 2)
"sbrc %[byte] , 7"
"\n\t" // 1-2 if(b & 128)
"mov %[next], %[hi]"
"\n\t" // 0-1 next = hi (T = 4)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 6)
"st %a[port], %[next]"
"\n\t" // 2 PORT = next (T = 8)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 10)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 12)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 14)
"nop"
"\n\t" // 1 nop (T = 15)
"st %a[port], %[lo]"
"\n\t" // 2 PORT = lo (T = 17)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 19)
"dec %[bit]"
"\n\t" // 1 bit-- (T = 20)
"breq nextbyte30"
"\n\t" // 1-2 if(bit == 0)
"rol %[byte]"
"\n\t" // 1 b <<= 1 (T = 22)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 24)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 26)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 28)
"rjmp head30"
"\n\t" // 2 -> head30 (next bit out)
"nextbyte30:"
"\n\t" // (T = 22)
"nop"
"\n\t" // 1 nop (T = 23)
"ldi %[bit] , 8"
"\n\t" // 1 bit = 8 (T = 24)
"ld %[byte] , %a[ptr]+"
"\n\t" // 2 b = *ptr++ (T = 26)
"sbiw %[count], 1"
"\n\t" // 2 i-- (T = 28)
"brne head30"
"\n" // 1-2 if(i != 0) -> (next byte)
: [port] "+e"(port), [byte] "+r"(b), [bit] "+r"(bit),
[next] "+r"(next), [count] "+w"(i)
: [hi] "r"(hi), [lo] "r"(lo), [ptr] "e"(ptr));
}
#endif // NEO_KHZ400
// 16 MHz(ish) AVR --------------------------------------------------------
#elif (F_CPU >= 15400000UL) && (F_CPU <= 19000000L)
#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled
if (is800KHz) {
#endif
// WS2811 and WS2812 have different hi/lo duty cycles; this is
// similar but NOT an exact copy of the prior 400-on-8 code.
// 20 inst. clocks per bit: HHHHHxxxxxxxxLLLLLLL
// ST instructions: ^ ^ ^ (T=0,5,13)
volatile uint8_t next, bit;
hi = *port | pinMask;
lo = *port & ~pinMask;
next = lo;
bit = 8;
asm volatile("head20:"
"\n\t" // Clk Pseudocode (T = 0)
"st %a[port], %[hi]"
"\n\t" // 2 PORT = hi (T = 2)
"sbrc %[byte], 7"
"\n\t" // 1-2 if(b & 128)
"mov %[next], %[hi]"
"\n\t" // 0-1 next = hi (T = 4)
"dec %[bit]"
"\n\t" // 1 bit-- (T = 5)
"st %a[port], %[next]"
"\n\t" // 2 PORT = next (T = 7)
"mov %[next] , %[lo]"
"\n\t" // 1 next = lo (T = 8)
"breq nextbyte20"
"\n\t" // 1-2 if(bit == 0) (from dec above)
"rol %[byte]"
"\n\t" // 1 b <<= 1 (T = 10)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 12)
"nop"
"\n\t" // 1 nop (T = 13)
"st %a[port], %[lo]"
"\n\t" // 2 PORT = lo (T = 15)
"nop"
"\n\t" // 1 nop (T = 16)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 18)
"rjmp head20"
"\n\t" // 2 -> head20 (next bit out)
"nextbyte20:"
"\n\t" // (T = 10)
"ldi %[bit] , 8"
"\n\t" // 1 bit = 8 (T = 11)
"ld %[byte] , %a[ptr]+"
"\n\t" // 2 b = *ptr++ (T = 13)
"st %a[port], %[lo]"
"\n\t" // 2 PORT = lo (T = 15)
"nop"
"\n\t" // 1 nop (T = 16)
"sbiw %[count], 1"
"\n\t" // 2 i-- (T = 18)
"brne head20"
"\n" // 2 if(i != 0) -> (next byte)
: [port] "+e"(port), [byte] "+r"(b), [bit] "+r"(bit),
[next] "+r"(next), [count] "+w"(i)
: [ptr] "e"(ptr), [hi] "r"(hi), [lo] "r"(lo));
#if defined(NEO_KHZ400)
} else { // 400 KHz
// The 400 KHz clock on 16 MHz MCU is the most 'relaxed' version.
// 40 inst. clocks per bit: HHHHHHHHxxxxxxxxxxxxLLLLLLLLLLLLLLLLLLLL
// ST instructions: ^ ^ ^ (T=0,8,20)
volatile uint8_t next, bit;
hi = *port | pinMask;
lo = *port & ~pinMask;
next = lo;
bit = 8;
asm volatile("head40:"
"\n\t" // Clk Pseudocode (T = 0)
"st %a[port], %[hi]"
"\n\t" // 2 PORT = hi (T = 2)
"sbrc %[byte] , 7"
"\n\t" // 1-2 if(b & 128)
"mov %[next] , %[hi]"
"\n\t" // 0-1 next = hi (T = 4)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 6)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 8)
"st %a[port], %[next]"
"\n\t" // 2 PORT = next (T = 10)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 12)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 14)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 16)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 18)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 20)
"st %a[port], %[lo]"
"\n\t" // 2 PORT = lo (T = 22)
"nop"
"\n\t" // 1 nop (T = 23)
"mov %[next] , %[lo]"
"\n\t" // 1 next = lo (T = 24)
"dec %[bit]"
"\n\t" // 1 bit-- (T = 25)
"breq nextbyte40"
"\n\t" // 1-2 if(bit == 0)
"rol %[byte]"
"\n\t" // 1 b <<= 1 (T = 27)
"nop"
"\n\t" // 1 nop (T = 28)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 30)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 32)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 34)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 36)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 38)
"rjmp head40"
"\n\t" // 2 -> head40 (next bit out)
"nextbyte40:"
"\n\t" // (T = 27)
"ldi %[bit] , 8"
"\n\t" // 1 bit = 8 (T = 28)
"ld %[byte] , %a[ptr]+"
"\n\t" // 2 b = *ptr++ (T = 30)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 32)
"st %a[port], %[lo]"
"\n\t" // 2 PORT = lo (T = 34)
"rjmp .+0"
"\n\t" // 2 nop nop (T = 36)
"sbiw %[count], 1"
"\n\t" // 2 i-- (T = 38)
"brne head40"
"\n" // 1-2 if(i != 0) -> (next byte)
: [port] "+e"(port), [byte] "+r"(b), [bit] "+r"(bit),
[next] "+r"(next), [count] "+w"(i)
: [ptr] "e"(ptr), [hi] "r"(hi), [lo] "r"(lo));
}
#endif // NEO_KHZ400
#else
#error "CPU SPEED NOT SUPPORTED"
#endif // end F_CPU ifdefs on __AVR__
// END AVR ----------------------------------------------------------------
#elif defined(__arm__)
// ARM MCUs -- Teensy 3.0, 3.1, LC, Arduino Due, RP2040 -------------------
#if defined(ARDUINO_ARCH_RP2040)
// Use PIO
rp2040Show(pin, pixels, numBytes, is800KHz);
#elif defined(TEENSYDUINO) && \
defined(KINETISK) // Teensy 3.0, 3.1, 3.2, 3.5, 3.6
#define CYCLES_800_T0H (F_CPU / 4000000)
#define CYCLES_800_T1H (F_CPU / 1250000)
#define CYCLES_800 (F_CPU / 800000)
#define CYCLES_400_T0H (F_CPU / 2000000)
#define CYCLES_400_T1H (F_CPU / 833333)
#define CYCLES_400 (F_CPU / 400000)
uint8_t *p = pixels, *end = p + numBytes, pix, mask;
volatile uint8_t *set = portSetRegister(pin), *clr = portClearRegister(pin);
uint32_t cyc;
ARM_DEMCR |= ARM_DEMCR_TRCENA;
ARM_DWT_CTRL |= ARM_DWT_CTRL_CYCCNTENA;
#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled
if (is800KHz) {
#endif
cyc = ARM_DWT_CYCCNT + CYCLES_800;
while (p < end) {
pix = *p++;
for (mask = 0x80; mask; mask >>= 1) {
while (ARM_DWT_CYCCNT - cyc < CYCLES_800)
;
cyc = ARM_DWT_CYCCNT;
*set = 1;
if (pix & mask) {
while (ARM_DWT_CYCCNT - cyc < CYCLES_800_T1H)
;
} else {
while (ARM_DWT_CYCCNT - cyc < CYCLES_800_T0H)
;
}
*clr = 1;
}
}
while (ARM_DWT_CYCCNT - cyc < CYCLES_800)
;
#if defined(NEO_KHZ400)
} else { // 400 kHz bitstream
cyc = ARM_DWT_CYCCNT + CYCLES_400;
while (p < end) {
pix = *p++;
for (mask = 0x80; mask; mask >>= 1) {
while (ARM_DWT_CYCCNT - cyc < CYCLES_400)
;
cyc = ARM_DWT_CYCCNT;
*set = 1;
if (pix & mask) {
while (ARM_DWT_CYCCNT - cyc < CYCLES_400_T1H)
;
} else {
while (ARM_DWT_CYCCNT - cyc < CYCLES_400_T0H)
;
}
*clr = 1;
}
}
while (ARM_DWT_CYCCNT - cyc < CYCLES_400)
;
}
#endif // NEO_KHZ400
#elif defined(TEENSYDUINO) && (defined(__IMXRT1052__) || defined(__IMXRT1062__))
#define CYCLES_800_T0H (F_CPU_ACTUAL / 4000000)
#define CYCLES_800_T1H (F_CPU_ACTUAL / 1250000)
#define CYCLES_800 (F_CPU_ACTUAL / 800000)
#define CYCLES_400_T0H (F_CPU_ACTUAL / 2000000)
#define CYCLES_400_T1H (F_CPU_ACTUAL / 833333)
#define CYCLES_400 (F_CPU_ACTUAL / 400000)
uint8_t *p = pixels, *end = p + numBytes, pix, mask;
volatile uint32_t *set = portSetRegister(pin), *clr = portClearRegister(pin);
uint32_t cyc, msk = digitalPinToBitMask(pin);
ARM_DEMCR |= ARM_DEMCR_TRCENA;
ARM_DWT_CTRL |= ARM_DWT_CTRL_CYCCNTENA;
#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled
if (is800KHz) {
#endif
cyc = ARM_DWT_CYCCNT + CYCLES_800;
while (p < end) {
pix = *p++;
for (mask = 0x80; mask; mask >>= 1) {
while (ARM_DWT_CYCCNT - cyc < CYCLES_800)
;
cyc = ARM_DWT_CYCCNT;
*set = msk;
if (pix & mask) {
while (ARM_DWT_CYCCNT - cyc < CYCLES_800_T1H)
;
} else {
while (ARM_DWT_CYCCNT - cyc < CYCLES_800_T0H)
;
}
*clr = msk;
}
}
while (ARM_DWT_CYCCNT - cyc < CYCLES_800)
;
#if defined(NEO_KHZ400)
} else { // 400 kHz bitstream
cyc = ARM_DWT_CYCCNT + CYCLES_400;
while (p < end) {
pix = *p++;
for (mask = 0x80; mask; mask >>= 1) {
while (ARM_DWT_CYCCNT - cyc < CYCLES_400)
;
cyc = ARM_DWT_CYCCNT;
*set = msk;
if (pix & mask) {
while (ARM_DWT_CYCCNT - cyc < CYCLES_400_T1H)
;
} else {
while (ARM_DWT_CYCCNT - cyc < CYCLES_400_T0H)
;
}
*clr = msk;
}
}
while (ARM_DWT_CYCCNT - cyc < CYCLES_400)
;
}
#endif // NEO_KHZ400
#elif defined(TEENSYDUINO) && defined(__MKL26Z64__) // Teensy-LC
#if F_CPU == 48000000
uint8_t *p = pixels, pix, count, dly, bitmask = digitalPinToBitMask(pin);
volatile uint8_t *reg = portSetRegister(pin);
uint32_t num = numBytes;
asm volatile("L%=_begin:"
"\n\t"
"ldrb %[pix], [%[p], #0]"
"\n\t"
"lsl %[pix], #24"
"\n\t"
"movs %[count], #7"
"\n\t"
"L%=_loop:"
"\n\t"
"lsl %[pix], #1"
"\n\t"
"bcs L%=_loop_one"
"\n\t"
"L%=_loop_zero:"
"\n\t"
"strb %[bitmask], [%[reg], #0]"
"\n\t"
"movs %[dly], #4"
"\n\t"
"L%=_loop_delay_T0H:"
"\n\t"
"sub %[dly], #1"
"\n\t"
"bne L%=_loop_delay_T0H"
"\n\t"
"strb %[bitmask], [%[reg], #4]"
"\n\t"
"movs %[dly], #13"
"\n\t"
"L%=_loop_delay_T0L:"
"\n\t"
"sub %[dly], #1"
"\n\t"
"bne L%=_loop_delay_T0L"
"\n\t"
"b L%=_next"
"\n\t"
"L%=_loop_one:"
"\n\t"
"strb %[bitmask], [%[reg], #0]"
"\n\t"
"movs %[dly], #13"
"\n\t"
"L%=_loop_delay_T1H:"
"\n\t"
"sub %[dly], #1"
"\n\t"
"bne L%=_loop_delay_T1H"
"\n\t"
"strb %[bitmask], [%[reg], #4]"
"\n\t"
"movs %[dly], #4"
"\n\t"
"L%=_loop_delay_T1L:"
"\n\t"
"sub %[dly], #1"
"\n\t"
"bne L%=_loop_delay_T1L"
"\n\t"
"nop"
"\n\t"
"L%=_next:"
"\n\t"
"sub %[count], #1"
"\n\t"
"bne L%=_loop"
"\n\t"
"lsl %[pix], #1"
"\n\t"
"bcs L%=_last_one"
"\n\t"
"L%=_last_zero:"
"\n\t"
"strb %[bitmask], [%[reg], #0]"
"\n\t"
"movs %[dly], #4"
"\n\t"
"L%=_last_delay_T0H:"
"\n\t"
"sub %[dly], #1"
"\n\t"
"bne L%=_last_delay_T0H"
"\n\t"
"strb %[bitmask], [%[reg], #4]"
"\n\t"
"movs %[dly], #10"
"\n\t"
"L%=_last_delay_T0L:"
"\n\t"
"sub %[dly], #1"
"\n\t"
"bne L%=_last_delay_T0L"
"\n\t"
"b L%=_repeat"
"\n\t"
"L%=_last_one:"
"\n\t"
"strb %[bitmask], [%[reg], #0]"
"\n\t"
"movs %[dly], #13"
"\n\t"
"L%=_last_delay_T1H:"
"\n\t"
"sub %[dly], #1"
"\n\t"
"bne L%=_last_delay_T1H"
"\n\t"
"strb %[bitmask], [%[reg], #4]"
"\n\t"
"movs %[dly], #1"
"\n\t"
"L%=_last_delay_T1L:"
"\n\t"
"sub %[dly], #1"
"\n\t"
"bne L%=_last_delay_T1L"
"\n\t"
"nop"
"\n\t"
"L%=_repeat:"
"\n\t"
"add %[p], #1"
"\n\t"
"sub %[num], #1"
"\n\t"
"bne L%=_begin"
"\n\t"
"L%=_done:"
"\n\t"
: [p] "+r"(p), [pix] "=&r"(pix), [count] "=&r"(count),
[dly] "=&r"(dly), [num] "+r"(num)
: [bitmask] "r"(bitmask), [reg] "r"(reg));
#else
#error "Sorry, only 48 MHz is supported, please set Tools > CPU Speed to 48 MHz"
#endif // F_CPU == 48000000
// Begin of support for nRF52 based boards -------------------------
#elif defined(NRF52) || defined(NRF52_SERIES)
// [[[Begin of the Neopixel NRF52 EasyDMA implementation
// by the Hackerspace San Salvador]]]
// This technique uses the PWM peripheral on the NRF52. The PWM uses the
// EasyDMA feature included on the chip. This technique loads the duty
// cycle configuration for each cycle when the PWM is enabled. For this
// to work we need to store a 16 bit configuration for each bit of the
// RGB(W) values in the pixel buffer.
// Comparator values for the PWM were hand picked and are guaranteed to
// be 100% organic to preserve freshness and high accuracy. Current
// parameters are:
// * PWM Clock: 16Mhz
// * Minimum step time: 62.5ns
// * Time for zero in high (T0H): 0.31ms
// * Time for one in high (T1H): 0.75ms
// * Cycle time: 1.25us
// * Frequency: 800Khz
// For 400Khz we just double the calculated times.
// ---------- BEGIN Constants for the EasyDMA implementation -----------
// The PWM starts the duty cycle in LOW. To start with HIGH we
// need to set the 15th bit on each register.
// WS2812 (rev A) timing is 0.35 and 0.7us
//#define MAGIC_T0H 5UL | (0x8000) // 0.3125us
//#define MAGIC_T1H 12UL | (0x8000) // 0.75us
// WS2812B (rev B) timing is 0.4 and 0.8 us
#define MAGIC_T0H 6UL | (0x8000) // 0.375us
#define MAGIC_T1H 13UL | (0x8000) // 0.8125us
// WS2811 (400 khz) timing is 0.5 and 1.2
#define MAGIC_T0H_400KHz 8UL | (0x8000) // 0.5us
#define MAGIC_T1H_400KHz 19UL | (0x8000) // 1.1875us
// For 400Khz, we double value of CTOPVAL
#define CTOPVAL 20UL // 1.25us
#define CTOPVAL_400KHz 40UL // 2.5us
// ---------- END Constants for the EasyDMA implementation -------------
//
// If there is no device available an alternative cycle-counter
// implementation is tried.
// The nRF52 runs with a fixed clock of 64Mhz. The alternative
// implementation is the same as the one used for the Teensy 3.0/1/2 but
// with the Nordic SDK HAL & registers syntax.
// The number of cycles was hand picked and is guaranteed to be 100%
// organic to preserve freshness and high accuracy.
// ---------- BEGIN Constants for cycle counter implementation ---------
#define CYCLES_800_T0H 18 // ~0.36 uS
#define CYCLES_800_T1H 41 // ~0.76 uS
#define CYCLES_800 71 // ~1.25 uS
#define CYCLES_400_T0H 26 // ~0.50 uS
#define CYCLES_400_T1H 70 // ~1.26 uS
#define CYCLES_400 156 // ~2.50 uS
// ---------- END of Constants for cycle counter implementation --------
// To support both the SoftDevice + Neopixels we use the EasyDMA
// feature from the NRF25. However this technique implies to
// generate a pattern and store it on the memory. The actual
// memory used in bytes corresponds to the following formula:
// totalMem = numBytes*8*2+(2*2)
// The two additional bytes at the end are needed to reset the
// sequence.
//
// If there is not enough memory, we will fall back to cycle counter
// using DWT
uint32_t pattern_size =
numBytes * 8 * sizeof(uint16_t) + 2 * sizeof(uint16_t);
uint16_t *pixels_pattern = NULL;
NRF_PWM_Type *pwm = NULL;
// Try to find a free PWM device, which is not enabled
// and has no connected pins
NRF_PWM_Type *PWM[] = {
NRF_PWM0,
NRF_PWM1,
NRF_PWM2
#if defined(NRF_PWM3)
,
NRF_PWM3
#endif
};
for (unsigned int device = 0; device < (sizeof(PWM) / sizeof(PWM[0]));
device++) {
if ((PWM[device]->ENABLE == 0) &&
(PWM[device]->PSEL.OUT[0] & PWM_PSEL_OUT_CONNECT_Msk) &&
(PWM[device]->PSEL.OUT[1] & PWM_PSEL_OUT_CONNECT_Msk) &&
(PWM[device]->PSEL.OUT[2] & PWM_PSEL_OUT_CONNECT_Msk) &&
(PWM[device]->PSEL.OUT[3] & PWM_PSEL_OUT_CONNECT_Msk)) {
pwm = PWM[device];
break;
}
}
// only malloc if there is PWM device available
if (pwm != NULL) {
#if defined(ARDUINO_NRF52_ADAFRUIT) // use thread-safe malloc
pixels_pattern = (uint16_t *)rtos_malloc(pattern_size);
#else
pixels_pattern = (uint16_t *)malloc(pattern_size);
#endif
}
// Use the identified device to choose the implementation
// If a PWM device is available use DMA
if ((pixels_pattern != NULL) && (pwm != NULL)) {
uint16_t pos = 0; // bit position
for (uint16_t n = 0; n < numBytes; n++) {
uint8_t pix = pixels[n];
for (uint8_t mask = 0x80; mask > 0; mask >>= 1) {
#if defined(NEO_KHZ400)
if (!is800KHz) {
pixels_pattern[pos] =
(pix & mask) ? MAGIC_T1H_400KHz : MAGIC_T0H_400KHz;
} else
#endif
{
pixels_pattern[pos] = (pix & mask) ? MAGIC_T1H : MAGIC_T0H;
}
pos++;
}
}
// Zero padding to indicate the end of que sequence
pixels_pattern[pos++] = 0 | (0x8000); // Seq end
pixels_pattern[pos++] = 0 | (0x8000); // Seq end
// Set the wave mode to count UP
pwm->MODE = (PWM_MODE_UPDOWN_Up << PWM_MODE_UPDOWN_Pos);
// Set the PWM to use the 16MHz clock
pwm->PRESCALER =
(PWM_PRESCALER_PRESCALER_DIV_1 << PWM_PRESCALER_PRESCALER_Pos);
// Setting of the maximum count
// but keeping it on 16Mhz allows for more granularity just
// in case someone wants to do more fine-tuning of the timing.
#if defined(NEO_KHZ400)
if (!is800KHz) {
pwm->COUNTERTOP = (CTOPVAL_400KHz << PWM_COUNTERTOP_COUNTERTOP_Pos);
} else
#endif
{
pwm->COUNTERTOP = (CTOPVAL << PWM_COUNTERTOP_COUNTERTOP_Pos);
}
// Disable loops, we want the sequence to repeat only once
pwm->LOOP = (PWM_LOOP_CNT_Disabled << PWM_LOOP_CNT_Pos);
// On the "Common" setting the PWM uses the same pattern for the
// for supported sequences. The pattern is stored on half-word
// of 16bits
pwm->DECODER = (PWM_DECODER_LOAD_Common << PWM_DECODER_LOAD_Pos) |
(PWM_DECODER_MODE_RefreshCount << PWM_DECODER_MODE_Pos);
// Pointer to the memory storing the patter
pwm->SEQ[0].PTR = (uint32_t)(pixels_pattern) << PWM_SEQ_PTR_PTR_Pos;
// Calculation of the number of steps loaded from memory.
pwm->SEQ[0].CNT = (pattern_size / sizeof(uint16_t)) << PWM_SEQ_CNT_CNT_Pos;
// The following settings are ignored with the current config.
pwm->SEQ[0].REFRESH = 0;
pwm->SEQ[0].ENDDELAY = 0;
// The Neopixel implementation is a blocking algorithm. DMA
// allows for non-blocking operation. To "simulate" a blocking
// operation we enable the interruption for the end of sequence
// and block the execution thread until the event flag is set by
// the peripheral.
// pwm->INTEN |= (PWM_INTEN_SEQEND0_Enabled<PSEL.OUT[0] = g_APinDescription[pin].name;
#else
pwm->PSEL.OUT[0] = g_ADigitalPinMap[pin];
#endif
// Enable the PWM
pwm->ENABLE = 1;
// After all of this and many hours of reading the documentation
// we are ready to start the sequence...
pwm->EVENTS_SEQEND[0] = 0;
pwm->TASKS_SEQSTART[0] = 1;
// But we have to wait for the flag to be set.
while (!pwm->EVENTS_SEQEND[0]) {
#if defined(ARDUINO_NRF52_ADAFRUIT) || defined(ARDUINO_ARCH_NRF52840)
yield();
#endif
}
// Before leave we clear the flag for the event.
pwm->EVENTS_SEQEND[0] = 0;
// We need to disable the device and disconnect
// all the outputs before leave or the device will not
// be selected on the next call.
// TODO: Check if disabling the device causes performance issues.
pwm->ENABLE = 0;
pwm->PSEL.OUT[0] = 0xFFFFFFFFUL;
#if defined(ARDUINO_NRF52_ADAFRUIT) // use thread-safe free
rtos_free(pixels_pattern);
#else
free(pixels_pattern);
#endif
} // End of DMA implementation
// ---------------------------------------------------------------------
else {
#ifndef ARDUINO_ARCH_NRF52840
// Fall back to DWT
#if defined(ARDUINO_NRF52_ADAFRUIT)
// Bluefruit Feather 52 uses freeRTOS
// Critical Section is used since it does not block SoftDevice execution
taskENTER_CRITICAL();
#elif defined(NRF52_DISABLE_INT)
// If you are using the Bluetooth SoftDevice we advise you to not disable
// the interrupts. Disabling the interrupts even for short periods of time
// causes the SoftDevice to stop working.
// Disable the interrupts only in cases where you need high performance for
// the LEDs and if you are not using the EasyDMA feature.
__disable_irq();
#endif
NRF_GPIO_Type *nrf_port = (NRF_GPIO_Type *)digitalPinToPort(pin);
uint32_t pinMask = digitalPinToBitMask(pin);
uint32_t CYCLES_X00 = CYCLES_800;
uint32_t CYCLES_X00_T1H = CYCLES_800_T1H;
uint32_t CYCLES_X00_T0H = CYCLES_800_T0H;
#if defined(NEO_KHZ400)
if (!is800KHz) {
CYCLES_X00 = CYCLES_400;
CYCLES_X00_T1H = CYCLES_400_T1H;
CYCLES_X00_T0H = CYCLES_400_T0H;
}
#endif
// Enable DWT in debug core
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
// Tries to re-send the frame if is interrupted by the SoftDevice.
while (1) {
uint8_t *p = pixels;
uint32_t cycStart = DWT->CYCCNT;
uint32_t cyc = 0;
for (uint16_t n = 0; n < numBytes; n++) {
uint8_t pix = *p++;
for (uint8_t mask = 0x80; mask; mask >>= 1) {
while (DWT->CYCCNT - cyc < CYCLES_X00)
;
cyc = DWT->CYCCNT;
nrf_port->OUTSET |= pinMask;
if (pix & mask) {
while (DWT->CYCCNT - cyc < CYCLES_X00_T1H)
;
} else {
while (DWT->CYCCNT - cyc < CYCLES_X00_T0H)
;
}
nrf_port->OUTCLR |= pinMask;
}
}
while (DWT->CYCCNT - cyc < CYCLES_X00)
;
// If total time longer than 25%, resend the whole data.
// Since we are likely to be interrupted by SoftDevice
if ((DWT->CYCCNT - cycStart) < (8 * numBytes * ((CYCLES_X00 * 5) / 4))) {
break;
}
// re-send need 300us delay
delayMicroseconds(300);
}
// Enable interrupts again
#if defined(ARDUINO_NRF52_ADAFRUIT)
taskEXIT_CRITICAL();
#elif defined(NRF52_DISABLE_INT)
__enable_irq();
#endif
#endif
}
// END of NRF52 implementation
#elif defined(__SAMD21E17A__) || defined(__SAMD21G18A__) || \
defined(__SAMD21E18A__) || defined(__SAMD21J18A__) || \
defined (__SAMD11C14A__)
// Arduino Zero, Gemma/Trinket M0, SODAQ Autonomo
// and others
// Tried this with a timer/counter, couldn't quite get adequate
// resolution. So yay, you get a load of goofball NOPs...
uint8_t *ptr, *end, p, bitMask, portNum;
uint32_t pinMask;
portNum = g_APinDescription[pin].ulPort;
pinMask = 1ul << g_APinDescription[pin].ulPin;
ptr = pixels;
end = ptr + numBytes;
p = *ptr++;
bitMask = 0x80;
volatile uint32_t *set = &(PORT->Group[portNum].OUTSET.reg),
*clr = &(PORT->Group[portNum].OUTCLR.reg);
#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled
if (is800KHz) {
#endif
for (;;) {
*set = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop;");
if (p & bitMask) {
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop;");
*clr = pinMask;
} else {
*clr = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop;");
}
if (bitMask >>= 1) {
asm("nop; nop; nop; nop; nop; nop; nop; nop; nop;");
} else {
if (ptr >= end)
break;
p = *ptr++;
bitMask = 0x80;
}
}
#if defined(NEO_KHZ400)
} else { // 400 KHz bitstream
for (;;) {
*set = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop; nop; nop; nop;");
if (p & bitMask) {
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop;");
*clr = pinMask;
} else {
*clr = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop;");
}
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;");
if (bitMask >>= 1) {
asm("nop; nop; nop; nop; nop; nop; nop;");
} else {
if (ptr >= end)
break;
p = *ptr++;
bitMask = 0x80;
}
}
}
#endif
//----
#elif defined(XMC1100_XMC2GO) || defined(XMC1100_H_BRIDGE2GO) || defined(XMC1100_Boot_Kit) || defined(XMC1300_Boot_Kit)
// XMC1100/1200/1300 with ARM Cortex M0 are running with 32MHz, XMC1400 runs with 48MHz so may not work
// Tried this with a timer/counter, couldn't quite get adequate
// resolution. So yay, you get a load of goofball NOPs...
uint8_t *ptr, *end, p, bitMask, portNum;
uint32_t pinMask;
ptr = pixels;
end = ptr + numBytes;
p = *ptr++;
bitMask = 0x80;
XMC_GPIO_PORT_t* XMC_port = mapping_port_pin[ pin ].port;
uint8_t XMC_pin = mapping_port_pin[ pin ].pin;
uint32_t omrhigh = (uint32_t)XMC_GPIO_OUTPUT_LEVEL_HIGH << XMC_pin;
uint32_t omrlow = (uint32_t)XMC_GPIO_OUTPUT_LEVEL_LOW << XMC_pin;
#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled
if(is800KHz) {
#endif
for(;;) {
XMC_port->OMR = omrhigh;
asm("nop; nop; nop; nop;");
if(p & bitMask) {
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop;");
XMC_port->OMR = omrlow;
} else {
XMC_port->OMR = omrlow;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop;");
}
if(bitMask >>= 1) {
asm("nop; nop; nop; nop; nop;");
} else {
if(ptr >= end) break;
p = *ptr++;
bitMask = 0x80;
}
}
#ifdef NEO_KHZ400 // untested code
} else { // 400 KHz bitstream
for(;;) {
XMC_port->OMR = omrhigh;
asm("nop; nop; nop; nop; nop;");
if(p & bitMask) {
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop;");
XMC_port->OMR = omrlow;
} else {
XMC_port->OMR = omrlow;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop;");
}
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;");
if(bitMask >>= 1) {
asm("nop; nop; nop;");
} else {
if(ptr >= end) break;
p = *ptr++;
bitMask = 0x80;
}
}
}
#endif
//----
//----
#elif defined(XMC4700_Relax_Kit) || defined(XMC4800_Relax_Kit)
// XMC4700 and XMC4800 with ARM Cortex M4 are running with 144MHz
// Tried this with a timer/counter, couldn't quite get adequate
// resolution. So yay, you get a load of goofball NOPs...
uint8_t *ptr, *end, p, bitMask, portNum;
uint32_t pinMask;
ptr = pixels;
end = ptr + numBytes;
p = *ptr++;
bitMask = 0x80;
XMC_GPIO_PORT_t* XMC_port = mapping_port_pin[ pin ].port;
uint8_t XMC_pin = mapping_port_pin[ pin ].pin;
uint32_t omrhigh = (uint32_t)XMC_GPIO_OUTPUT_LEVEL_HIGH << XMC_pin;
uint32_t omrlow = (uint32_t)XMC_GPIO_OUTPUT_LEVEL_LOW << XMC_pin;
#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled
if(is800KHz) {
#endif
for(;;) {
XMC_port->OMR = omrhigh;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop;");
if(p & bitMask) {
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;");
XMC_port->OMR = omrlow;
} else {
XMC_port->OMR = omrlow;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;");
}
if(bitMask >>= 1) {
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;");
} else {
if(ptr >= end) break;
p = *ptr++;
bitMask = 0x80;
}
}
#ifdef NEO_KHZ400
} else { // 400 KHz bitstream
// ToDo!
}
#endif
//----
#elif defined(__SAMD51__) // M4
uint8_t *ptr, *end, p, bitMask, portNum, bit;
uint32_t pinMask;
portNum = g_APinDescription[pin].ulPort;
pinMask = 1ul << g_APinDescription[pin].ulPin;
ptr = pixels;
end = ptr + numBytes;
p = *ptr++;
bitMask = 0x80;
volatile uint32_t *set = &(PORT->Group[portNum].OUTSET.reg),
*clr = &(PORT->Group[portNum].OUTCLR.reg);
// SAMD51 overclock-compatible timing is only a mild abomination.
// It uses SysTick for a consistent clock reference regardless of
// optimization / cache settings. That's the good news. The bad news,
// since SysTick->VAL is a volatile type it's slow to access...and then,
// with the SysTick interval that Arduino sets up (1 ms), this would
// require a subtract and MOD operation for gauging elapsed time, and
// all taken in combination that lacks adequate temporal resolution
// for NeoPixel timing. So a kind of horrible thing is done here...
// since interrupts are turned off anyway and it's generally accepted
// by now that we're gonna lose track of time in the NeoPixel lib,
// the SysTick timer is reconfigured for a period matching the NeoPixel
// bit timing (either 800 or 400 KHz) and we watch SysTick->VAL very
// closely (just a threshold, no subtract or MOD or anything) and that
// seems to work just well enough. When finished, the SysTick
// peripheral is set back to its original state.
uint32_t t0, t1, top, ticks, saveLoad = SysTick->LOAD, saveVal = SysTick->VAL;
#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled
if (is800KHz) {
#endif
top = (uint32_t)(F_CPU * 0.00000125); // Bit hi + lo = 1.25 uS
t0 = top - (uint32_t)(F_CPU * 0.00000040); // 0 = 0.4 uS hi
t1 = top - (uint32_t)(F_CPU * 0.00000080); // 1 = 0.8 uS hi
#if defined(NEO_KHZ400)
} else { // 400 KHz bitstream
top = (uint32_t)(F_CPU * 0.00000250); // Bit hi + lo = 2.5 uS
t0 = top - (uint32_t)(F_CPU * 0.00000050); // 0 = 0.5 uS hi
t1 = top - (uint32_t)(F_CPU * 0.00000120); // 1 = 1.2 uS hi
}
#endif
SysTick->LOAD = top; // Config SysTick for NeoPixel bit freq
SysTick->VAL = top; // Set to start value (counts down)
(void)SysTick->VAL; // Dummy read helps sync up 1st bit
for (;;) {
*set = pinMask; // Set output high
ticks = (p & bitMask) ? t1 : t0; // SysTick threshold,
while (SysTick->VAL > ticks)
; // wait for it
*clr = pinMask; // Set output low
if (!(bitMask >>= 1)) { // Next bit for this byte...done?
if (ptr >= end)
break; // If last byte sent, exit loop
p = *ptr++; // Fetch next byte
bitMask = 0x80; // Reset bitmask
}
while (SysTick->VAL <= ticks)
; // Wait for rollover to 'top'
}
SysTick->LOAD = saveLoad; // Restore SysTick rollover to 1 ms
SysTick->VAL = saveVal; // Restore SysTick value
#elif defined(ARDUINO_STM32_FEATHER) // FEATHER WICED (120MHz)
// Tried this with a timer/counter, couldn't quite get adequate
// resolution. So yay, you get a load of goofball NOPs...
uint8_t *ptr, *end, p, bitMask;
uint32_t pinMask;
pinMask = BIT(PIN_MAP[pin].gpio_bit);
ptr = pixels;
end = ptr + numBytes;
p = *ptr++;
bitMask = 0x80;
volatile uint16_t *set = &(PIN_MAP[pin].gpio_device->regs->BSRRL);
volatile uint16_t *clr = &(PIN_MAP[pin].gpio_device->regs->BSRRH);
#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled
if (is800KHz) {
#endif
for (;;) {
if (p & bitMask) { // ONE
// High 800ns
*set = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop;");
// Low 450ns
*clr = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop;");
} else { // ZERO
// High 400ns
*set = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop;");
// Low 850ns
*clr = pinMask;
asm("nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop; nop; nop; nop; nop;"
"nop; nop; nop; nop;");
}
if (bitMask >>= 1) {
// Move on to the next pixel
asm("nop;");
} else {
if (ptr >= end)
break;
p = *ptr++;
bitMask = 0x80;
}
}
#if defined(NEO_KHZ400)
} else { // 400 KHz bitstream
// ToDo!
}
#endif
#elif defined(TARGET_LPC1768)
uint8_t *ptr, *end, p, bitMask;
ptr = pixels;
end = ptr + numBytes;
p = *ptr++;
bitMask = 0x80;
#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled
if (is800KHz) {
#endif
for (;;) {
if (p & bitMask) {
// data ONE high
// min: 550 typ: 700 max: 5,500
gpio_set(pin);
time::delay_ns(550);
// min: 450 typ: 600 max: 5,000
gpio_clear(pin);
time::delay_ns(450);
} else {
// data ZERO high
// min: 200 typ: 350 max: 500
gpio_set(pin);
time::delay_ns(200);
// data low
// min: 450 typ: 600 max: 5,000
gpio_clear(pin);
time::delay_ns(450);
}
if (bitMask >>= 1) {
// Move on to the next pixel
asm("nop;");
} else {
if (ptr >= end)
break;
p = *ptr++;
bitMask = 0x80;
}
}
#if defined(NEO_KHZ400)
} else { // 400 KHz bitstream
// ToDo!
}
#endif
#elif defined(ARDUINO_ARCH_STM32) || defined(ARDUINO_ARCH_ARDUINO_CORE_STM32)
uint8_t *p = pixels, *end = p + numBytes, pix = *p++, mask = 0x80;
uint32_t cyc;
uint32_t saveLoad = SysTick->LOAD, saveVal = SysTick->VAL;
#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled
if (is800KHz) {
#endif
uint32_t top = (F_CPU / 800000); // 1.25µs
uint32_t t0 = top - (F_CPU / 2500000); // 0.4µs
uint32_t t1 = top - (F_CPU / 1250000); // 0.8µs
SysTick->LOAD = top - 1; // Config SysTick for NeoPixel bit freq
SysTick->VAL = 0; // Set to start value
for (;;) {
LL_GPIO_SetOutputPin(gpioPort, gpioPin);
cyc = (pix & mask) ? t1 : t0;
while (SysTick->VAL > cyc)
;
LL_GPIO_ResetOutputPin(gpioPort, gpioPin);
if (!(mask >>= 1)) {
if (p >= end)
break;
pix = *p++;
mask = 0x80;
}
while (SysTick->VAL <= cyc)
;
}
#if defined(NEO_KHZ400)
} else { // 400 kHz bitstream
uint32_t top = (F_CPU / 400000); // 2.5µs
uint32_t t0 = top - (F_CPU / 2000000); // 0.5µs
uint32_t t1 = top - (F_CPU / 833333); // 1.2µs
SysTick->LOAD = top - 1; // Config SysTick for NeoPixel bit freq
SysTick->VAL = 0; // Set to start value
for (;;) {
LL_GPIO_SetOutputPin(gpioPort, gpioPin);
cyc = (pix & mask) ? t1 : t0;
while (SysTick->VAL > cyc)
;
LL_GPIO_ResetOutputPin(gpioPort, gpioPin);
if (!(mask >>= 1)) {
if (p >= end)
break;
pix = *p++;
mask = 0x80;
}
while (SysTick->VAL <= cyc)
;
}
}
#endif // NEO_KHZ400
SysTick->LOAD = saveLoad; // Restore SysTick rollover to 1 ms
SysTick->VAL = saveVal; // Restore SysTick value
#elif defined(NRF51)
uint8_t *p = pixels, pix, count, mask;
int32_t num = numBytes;
unsigned int bitmask = (1 << g_ADigitalPinMap[pin]);
// https://github.com/sandeepmistry/arduino-nRF5/blob/dc53980c8bac27898fca90d8ecb268e11111edc1/variants/BBCmicrobit/variant.cpp
volatile unsigned int *reg = (unsigned int *)(0x50000000UL + 0x508);
// https://github.com/sandeepmistry/arduino-nRF5/blob/dc53980c8bac27898fca90d8ecb268e11111edc1/cores/nRF5/SDK/components/device/nrf51.h
// http://www.iot-programmer.com/index.php/books/27-micro-bit-iot-in-c/chapters-micro-bit-iot-in-c/47-micro-bit-iot-in-c-fast-memory-mapped-gpio?showall=1
// https://github.com/Microsoft/pxt-neopixel/blob/master/sendbuffer.asm
asm volatile(
// "cpsid i" ; disable irq
// b .start
"b L%=_start"
"\n\t"
// .nextbit: ; C0
"L%=_nextbit:"
"\n\t" //; C0
// str r1, [r3, #0] ; pin := hi C2
"strb %[bitmask], [%[reg], #0]"
"\n\t" //; pin := hi C2
// tst r6, r0 ; C3
"tst %[mask], %[pix]"
"\n\t" // ; C3
// bne .islate ; C4
"bne L%=_islate"
"\n\t" //; C4
// str r1, [r2, #0] ; pin := lo C6
"strb %[bitmask], [%[reg], #4]"
"\n\t" //; pin := lo C6
// .islate:
"L%=_islate:"
"\n\t"
// lsrs r6, r6, #1 ; r6 >>= 1 C7
"lsr %[mask], %[mask], #1"
"\n\t" //; r6 >>= 1 C7
// bne .justbit ; C8
"bne L%=_justbit"
"\n\t" //; C8
// ; not just a bit - need new byte
// adds r4, #1 ; r4++ C9
"add %[p], #1"
"\n\t" //; r4++ C9
// subs r5, #1 ; r5-- C10
"sub %[num], #1"
"\n\t" //; r5-- C10
// bcc .stop ; if (r5<0) goto .stop C11
"bcc L%=_stop"
"\n\t" //; if (r5<0) goto .stop C11
// .start:
"L%=_start:"
// movs r6, #0x80 ; reset mask C12
"movs %[mask], #0x80"
"\n\t" //; reset mask C12
// nop ; C13
"nop"
"\n\t" //; C13
// .common: ; C13
"L%=_common:"
"\n\t" //; C13
// str r1, [r2, #0] ; pin := lo C15
"strb %[bitmask], [%[reg], #4]"
"\n\t" //; pin := lo C15
// ; always re-load byte - it just fits with the cycles better this way
// ldrb r0, [r4, #0] ; r0 := *r4 C17
"ldrb %[pix], [%[p], #0]"
"\n\t" //; r0 := *r4 C17
// b .nextbit ; C20
"b L%=_nextbit"
"\n\t" //; C20
// .justbit: ; C10
"L%=_justbit:"
"\n\t" //; C10
// ; no nops, branch taken is already 3 cycles
// b .common ; C13
"b L%=_common"
"\n\t" //; C13
// .stop:
"L%=_stop:"
"\n\t"
// str r1, [r2, #0] ; pin := lo
"strb %[bitmask], [%[reg], #4]"
"\n\t" //; pin := lo
// cpsie i ; enable irq
: [p] "+r"(p), [pix] "=&r"(pix), [count] "=&r"(count), [mask] "=&r"(mask),
[num] "+r"(num)
: [bitmask] "r"(bitmask), [reg] "r"(reg));
#elif defined(__SAM3X8E__) // Arduino Due
#define SCALE VARIANT_MCK / 2UL / 1000000UL
#define INST (2UL * F_CPU / VARIANT_MCK)
#define TIME_800_0 ((int)(0.40 * SCALE + 0.5) - (5 * INST))
#define TIME_800_1 ((int)(0.80 * SCALE + 0.5) - (5 * INST))
#define PERIOD_800 ((int)(1.25 * SCALE + 0.5) - (5 * INST))
#define TIME_400_0 ((int)(0.50 * SCALE + 0.5) - (5 * INST))
#define TIME_400_1 ((int)(1.20 * SCALE + 0.5) - (5 * INST))
#define PERIOD_400 ((int)(2.50 * SCALE + 0.5) - (5 * INST))
int pinMask, time0, time1, period, t;
Pio *port;
volatile WoReg *portSet, *portClear, *timeValue, *timeReset;
uint8_t *p, *end, pix, mask;
pmc_set_writeprotect(false);
pmc_enable_periph_clk((uint32_t)TC3_IRQn);
TC_Configure(TC1, 0,
TC_CMR_WAVE | TC_CMR_WAVSEL_UP | TC_CMR_TCCLKS_TIMER_CLOCK1);
TC_Start(TC1, 0);
pinMask = g_APinDescription[pin].ulPin; // Don't 'optimize' these into
port = g_APinDescription[pin].pPort; // declarations above. Want to
portSet = &(port->PIO_SODR); // burn a few cycles after
portClear = &(port->PIO_CODR); // starting timer to minimize
timeValue = &(TC1->TC_CHANNEL[0].TC_CV); // the initial 'while'.
timeReset = &(TC1->TC_CHANNEL[0].TC_CCR);
p = pixels;
end = p + numBytes;
pix = *p++;
mask = 0x80;
#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled
if (is800KHz) {
#endif
time0 = TIME_800_0;
time1 = TIME_800_1;
period = PERIOD_800;
#if defined(NEO_KHZ400)
} else { // 400 KHz bitstream
time0 = TIME_400_0;
time1 = TIME_400_1;
period = PERIOD_400;
}
#endif
for (t = time0;; t = time0) {
if (pix & mask)
t = time1;
while (*timeValue < (unsigned)period)
;
*portSet = pinMask;
*timeReset = TC_CCR_CLKEN | TC_CCR_SWTRG;
while (*timeValue < (unsigned)t)
;
*portClear = pinMask;
if (!(mask >>= 1)) { // This 'inside-out' loop logic utilizes
if (p >= end)
break; // idle time to minimize inter-byte delays.
pix = *p++;
mask = 0x80;
}
}
while (*timeValue < (unsigned)period)
; // Wait for last bit
TC_Stop(TC1, 0);
#endif // end Due
// END ARM ----------------------------------------------------------------
#elif defined(ESP8266) || defined(ESP32)
// ESP8266 ----------------------------------------------------------------
// ESP8266 show() is external to enforce ICACHE_RAM_ATTR execution
espShow(pin, pixels, numBytes, is800KHz);
#elif defined(KENDRYTE_K210)
k210Show(pin, pixels, numBytes, is800KHz);
#elif defined(__ARDUINO_ARC__)
// Arduino 101 -----------------------------------------------------------
#define NOPx7 \
{ \
__builtin_arc_nop(); \
__builtin_arc_nop(); \
__builtin_arc_nop(); \
__builtin_arc_nop(); \
__builtin_arc_nop(); \
__builtin_arc_nop(); \
__builtin_arc_nop(); \
}
PinDescription *pindesc = &g_APinDescription[pin];
register uint32_t loop =
8 * numBytes; // one loop to handle all bytes and all bits
register uint8_t *p = pixels;
register uint32_t currByte = (uint32_t)(*p);
register uint32_t currBit = 0x80 & currByte;
register uint32_t bitCounter = 0;
register uint32_t first = 1;
// The loop is unusual. Very first iteration puts all the way LOW to the wire
// - constant LOW does not affect NEOPIXEL, so there is no visible effect
// displayed. During that very first iteration CPU caches instructions in the
// loop. Because of the caching process, "CPU slows down". NEOPIXEL pulse is
// very time sensitive that's why we let the CPU cache first and we start
// regular pulse from 2nd iteration
if (pindesc->ulGPIOType == SS_GPIO) {
register uint32_t reg = pindesc->ulGPIOBase + SS_GPIO_SWPORTA_DR;
uint32_t reg_val = __builtin_arc_lr((volatile uint32_t)reg);
register uint32_t reg_bit_high = reg_val | (1 << pindesc->ulGPIOId);
register uint32_t reg_bit_low = reg_val & ~(1 << pindesc->ulGPIOId);
loop += 1; // include first, special iteration
while (loop--) {
if (!first) {
currByte <<= 1;
bitCounter++;
}
// 1 is >550ns high and >450ns low; 0 is 200..500ns high and >450ns low
__builtin_arc_sr(first ? reg_bit_low : reg_bit_high,
(volatile uint32_t)reg);
if (currBit) { // ~400ns HIGH (740ns overall)
NOPx7 NOPx7
}
// ~340ns HIGH
NOPx7 __builtin_arc_nop();
// 820ns LOW; per spec, max allowed low here is 5000ns */
__builtin_arc_sr(reg_bit_low, (volatile uint32_t)reg);
NOPx7 NOPx7
if (bitCounter >= 8) {
bitCounter = 0;
currByte = (uint32_t)(*++p);
}
currBit = 0x80 & currByte;
first = 0;
}
} else if (pindesc->ulGPIOType == SOC_GPIO) {
register uint32_t reg = pindesc->ulGPIOBase + SOC_GPIO_SWPORTA_DR;
uint32_t reg_val = MMIO_REG_VAL(reg);
register uint32_t reg_bit_high = reg_val | (1 << pindesc->ulGPIOId);
register uint32_t reg_bit_low = reg_val & ~(1 << pindesc->ulGPIOId);
loop += 1; // include first, special iteration
while (loop--) {
if (!first) {
currByte <<= 1;
bitCounter++;
}
MMIO_REG_VAL(reg) = first ? reg_bit_low : reg_bit_high;
if (currBit) { // ~430ns HIGH (740ns overall)
NOPx7 NOPx7 __builtin_arc_nop();
}
// ~310ns HIGH
NOPx7
// 850ns LOW; per spec, max allowed low here is 5000ns */
MMIO_REG_VAL(reg) = reg_bit_low;
NOPx7 NOPx7
if (bitCounter >= 8) {
bitCounter = 0;
currByte = (uint32_t)(*++p);
}
currBit = 0x80 & currByte;
first = 0;
}
}
#else
#error Architecture not supported
#endif
// END ARCHITECTURE SELECT ------------------------------------------------
#if !(defined(NRF52) || defined(NRF52_SERIES))
interrupts();
#endif
endTime = micros(); // Save EOD time for latch on next call
}
/*!
@brief Set/change the NeoPixel output pin number. Previous pin,
if any, is set to INPUT and the new pin is set to OUTPUT.
@param p Arduino pin number (-1 = no pin).
*/
void Adafruit_NeoPixel::setPin(int16_t p) {
if (begun && (pin >= 0))
pinMode(pin, INPUT); // Disable existing out pin
pin = p;
if (begun) {
pinMode(p, OUTPUT);
digitalWrite(p, LOW);
}
#if defined(__AVR__)
port = portOutputRegister(digitalPinToPort(p));
pinMask = digitalPinToBitMask(p);
#endif
#if defined(ARDUINO_ARCH_STM32) || defined(ARDUINO_ARCH_ARDUINO_CORE_STM32)
gpioPort = digitalPinToPort(p);
gpioPin = STM_LL_GPIO_PIN(digitalPinToPinName(p));
#endif
}
/*!
@brief Set a pixel's color using separate red, green and blue
components. If using RGBW pixels, white will be set to 0.
@param n Pixel index, starting from 0.
@param r Red brightness, 0 = minimum (off), 255 = maximum.
@param g Green brightness, 0 = minimum (off), 255 = maximum.
@param b Blue brightness, 0 = minimum (off), 255 = maximum.
*/
void Adafruit_NeoPixel::setPixelColor(uint16_t n, uint8_t r, uint8_t g,
uint8_t b) {
if (n < numLEDs) {
if (brightness) { // See notes in setBrightness()
r = (r * brightness) >> 8;
g = (g * brightness) >> 8;
b = (b * brightness) >> 8;
}
uint8_t *p;
if (wOffset == rOffset) { // Is an RGB-type strip
p = &pixels[n * 3]; // 3 bytes per pixel
} else { // Is a WRGB-type strip
p = &pixels[n * 4]; // 4 bytes per pixel
p[wOffset] = 0; // But only R,G,B passed -- set W to 0
}
p[rOffset] = r; // R,G,B always stored
p[gOffset] = g;
p[bOffset] = b;
}
}
/*!
@brief Set a pixel's color using separate red, green, blue and white
components (for RGBW NeoPixels only).
@param n Pixel index, starting from 0.
@param r Red brightness, 0 = minimum (off), 255 = maximum.
@param g Green brightness, 0 = minimum (off), 255 = maximum.
@param b Blue brightness, 0 = minimum (off), 255 = maximum.
@param w White brightness, 0 = minimum (off), 255 = maximum, ignored
if using RGB pixels.
*/
void Adafruit_NeoPixel::setPixelColor(uint16_t n, uint8_t r, uint8_t g,
uint8_t b, uint8_t w) {
if (n < numLEDs) {
if (brightness) { // See notes in setBrightness()
r = (r * brightness) >> 8;
g = (g * brightness) >> 8;
b = (b * brightness) >> 8;
w = (w * brightness) >> 8;
}
uint8_t *p;
if (wOffset == rOffset) { // Is an RGB-type strip
p = &pixels[n * 3]; // 3 bytes per pixel (ignore W)
} else { // Is a WRGB-type strip
p = &pixels[n * 4]; // 4 bytes per pixel
p[wOffset] = w; // Store W
}
p[rOffset] = r; // Store R,G,B
p[gOffset] = g;
p[bOffset] = b;
}
}
/*!
@brief Set a pixel's color using a 32-bit 'packed' RGB or RGBW value.
@param n Pixel index, starting from 0.
@param c 32-bit color value. Most significant byte is white (for RGBW
pixels) or ignored (for RGB pixels), next is red, then green,
and least significant byte is blue.
*/
void Adafruit_NeoPixel::setPixelColor(uint16_t n, uint32_t c) {
if (n < numLEDs) {
uint8_t *p, r = (uint8_t)(c >> 16), g = (uint8_t)(c >> 8), b = (uint8_t)c;
if (brightness) { // See notes in setBrightness()
r = (r * brightness) >> 8;
g = (g * brightness) >> 8;
b = (b * brightness) >> 8;
}
if (wOffset == rOffset) {
p = &pixels[n * 3];
} else {
p = &pixels[n * 4];
uint8_t w = (uint8_t)(c >> 24);
p[wOffset] = brightness ? ((w * brightness) >> 8) : w;
}
p[rOffset] = r;
p[gOffset] = g;
p[bOffset] = b;
}
}
/*!
@brief Fill all or part of the NeoPixel strip with a color.
@param c 32-bit color value. Most significant byte is white (for
RGBW pixels) or ignored (for RGB pixels), next is red,
then green, and least significant byte is blue. If all
arguments are unspecified, this will be 0 (off).
@param first Index of first pixel to fill, starting from 0. Must be
in-bounds, no clipping is performed. 0 if unspecified.
@param count Number of pixels to fill, as a positive value. Passing
0 or leaving unspecified will fill to end of strip.
*/
void Adafruit_NeoPixel::fill(uint32_t c, uint16_t first, uint16_t count) {
uint16_t i, end;
if (first >= numLEDs) {
return; // If first LED is past end of strip, nothing to do
}
// Calculate the index ONE AFTER the last pixel to fill
if (count == 0) {
// Fill to end of strip
end = numLEDs;
} else {
// Ensure that the loop won't go past the last pixel
end = first + count;
if (end > numLEDs)
end = numLEDs;
}
for (i = first; i < end; i++) {
this->setPixelColor(i, c);
}
}
/*!
@brief Convert hue, saturation and value into a packed 32-bit RGB color
that can be passed to setPixelColor() or other RGB-compatible
functions.
@param hue An unsigned 16-bit value, 0 to 65535, representing one full
loop of the color wheel, which allows 16-bit hues to "roll
over" while still doing the expected thing (and allowing
more precision than the wheel() function that was common to
prior NeoPixel examples).
@param sat Saturation, 8-bit value, 0 (min or pure grayscale) to 255
(max or pure hue). Default of 255 if unspecified.
@param val Value (brightness), 8-bit value, 0 (min / black / off) to
255 (max or full brightness). Default of 255 if unspecified.
@return Packed 32-bit RGB with the most significant byte set to 0 -- the
white element of WRGB pixels is NOT utilized. Result is linearly
but not perceptually correct, so you may want to pass the result
through the gamma32() function (or your own gamma-correction
operation) else colors may appear washed out. This is not done
automatically by this function because coders may desire a more
refined gamma-correction function than the simplified
one-size-fits-all operation of gamma32(). Diffusing the LEDs also
really seems to help when using low-saturation colors.
*/
uint32_t Adafruit_NeoPixel::ColorHSV(uint16_t hue, uint8_t sat, uint8_t val) {
uint8_t r, g, b;
// Remap 0-65535 to 0-1529. Pure red is CENTERED on the 64K rollover;
// 0 is not the start of pure red, but the midpoint...a few values above
// zero and a few below 65536 all yield pure red (similarly, 32768 is the
// midpoint, not start, of pure cyan). The 8-bit RGB hexcone (256 values
// each for red, green, blue) really only allows for 1530 distinct hues
// (not 1536, more on that below), but the full unsigned 16-bit type was
// chosen for hue so that one's code can easily handle a contiguous color
// wheel by allowing hue to roll over in either direction.
hue = (hue * 1530L + 32768) / 65536;
// Because red is centered on the rollover point (the +32768 above,
// essentially a fixed-point +0.5), the above actually yields 0 to 1530,
// where 0 and 1530 would yield the same thing. Rather than apply a
// costly modulo operator, 1530 is handled as a special case below.
// So you'd think that the color "hexcone" (the thing that ramps from
// pure red, to pure yellow, to pure green and so forth back to red,
// yielding six slices), and with each color component having 256
// possible values (0-255), might have 1536 possible items (6*256),
// but in reality there's 1530. This is because the last element in
// each 256-element slice is equal to the first element of the next
// slice, and keeping those in there this would create small
// discontinuities in the color wheel. So the last element of each
// slice is dropped...we regard only elements 0-254, with item 255
// being picked up as element 0 of the next slice. Like this:
// Red to not-quite-pure-yellow is: 255, 0, 0 to 255, 254, 0
// Pure yellow to not-quite-pure-green is: 255, 255, 0 to 1, 255, 0
// Pure green to not-quite-pure-cyan is: 0, 255, 0 to 0, 255, 254
// and so forth. Hence, 1530 distinct hues (0 to 1529), and hence why
// the constants below are not the multiples of 256 you might expect.
// Convert hue to R,G,B (nested ifs faster than divide+mod+switch):
if (hue < 510) { // Red to Green-1
b = 0;
if (hue < 255) { // Red to Yellow-1
r = 255;
g = hue; // g = 0 to 254
} else { // Yellow to Green-1
r = 510 - hue; // r = 255 to 1
g = 255;
}
} else if (hue < 1020) { // Green to Blue-1
r = 0;
if (hue < 765) { // Green to Cyan-1
g = 255;
b = hue - 510; // b = 0 to 254
} else { // Cyan to Blue-1
g = 1020 - hue; // g = 255 to 1
b = 255;
}
} else if (hue < 1530) { // Blue to Red-1
g = 0;
if (hue < 1275) { // Blue to Magenta-1
r = hue - 1020; // r = 0 to 254
b = 255;
} else { // Magenta to Red-1
r = 255;
b = 1530 - hue; // b = 255 to 1
}
} else { // Last 0.5 Red (quicker than % operator)
r = 255;
g = b = 0;
}
// Apply saturation and value to R,G,B, pack into 32-bit result:
uint32_t v1 = 1 + val; // 1 to 256; allows >>8 instead of /255
uint16_t s1 = 1 + sat; // 1 to 256; same reason
uint8_t s2 = 255 - sat; // 255 to 0
return ((((((r * s1) >> 8) + s2) * v1) & 0xff00) << 8) |
(((((g * s1) >> 8) + s2) * v1) & 0xff00) |
(((((b * s1) >> 8) + s2) * v1) >> 8);
}
/*!
@brief Query the color of a previously-set pixel.
@param n Index of pixel to read (0 = first).
@return 'Packed' 32-bit RGB or WRGB value. Most significant byte is white
(for RGBW pixels) or 0 (for RGB pixels), next is red, then green,
and least significant byte is blue.
@note If the strip brightness has been changed from the default value
of 255, the color read from a pixel may not exactly match what
was previously written with one of the setPixelColor() functions.
This gets more pronounced at lower brightness levels.
*/
uint32_t Adafruit_NeoPixel::getPixelColor(uint16_t n) const {
if (n >= numLEDs)
return 0; // Out of bounds, return no color.
uint8_t *p;
if (wOffset == rOffset) { // Is RGB-type device
p = &pixels[n * 3];
if (brightness) {
// Stored color was decimated by setBrightness(). Returned value
// attempts to scale back to an approximation of the original 24-bit
// value used when setting the pixel color, but there will always be
// some error -- those bits are simply gone. Issue is most
// pronounced at low brightness levels.
return (((uint32_t)(p[rOffset] << 8) / brightness) << 16) |
(((uint32_t)(p[gOffset] << 8) / brightness) << 8) |
((uint32_t)(p[bOffset] << 8) / brightness);
} else {
// No brightness adjustment has been made -- return 'raw' color
return ((uint32_t)p[rOffset] << 16) | ((uint32_t)p[gOffset] << 8) |
(uint32_t)p[bOffset];
}
} else { // Is RGBW-type device
p = &pixels[n * 4];
if (brightness) { // Return scaled color
return (((uint32_t)(p[wOffset] << 8) / brightness) << 24) |
(((uint32_t)(p[rOffset] << 8) / brightness) << 16) |
(((uint32_t)(p[gOffset] << 8) / brightness) << 8) |
((uint32_t)(p[bOffset] << 8) / brightness);
} else { // Return raw color
return ((uint32_t)p[wOffset] << 24) | ((uint32_t)p[rOffset] << 16) |
((uint32_t)p[gOffset] << 8) | (uint32_t)p[bOffset];
}
}
}
/*!
@brief Adjust output brightness. Does not immediately affect what's
currently displayed on the LEDs. The next call to show() will
refresh the LEDs at this level.
@param b Brightness setting, 0=minimum (off), 255=brightest.
@note This was intended for one-time use in one's setup() function,
not as an animation effect in itself. Because of the way this
library "pre-multiplies" LED colors in RAM, changing the
brightness is often a "lossy" operation -- what you write to
pixels isn't necessary the same as what you'll read back.
Repeated brightness changes using this function exacerbate the
problem. Smart programs therefore treat the strip as a
write-only resource, maintaining their own state to render each
frame of an animation, not relying on read-modify-write.
*/
void Adafruit_NeoPixel::setBrightness(uint8_t b) {
// Stored brightness value is different than what's passed.
// This simplifies the actual scaling math later, allowing a fast
// 8x8-bit multiply and taking the MSB. 'brightness' is a uint8_t,
// adding 1 here may (intentionally) roll over...so 0 = max brightness
// (color values are interpreted literally; no scaling), 1 = min
// brightness (off), 255 = just below max brightness.
uint8_t newBrightness = b + 1;
if (newBrightness != brightness) { // Compare against prior value
// Brightness has changed -- re-scale existing data in RAM,
// This process is potentially "lossy," especially when increasing
// brightness. The tight timing in the WS2811/WS2812 code means there
// aren't enough free cycles to perform this scaling on the fly as data
// is issued. So we make a pass through the existing color data in RAM
// and scale it (subsequent graphics commands also work at this
// brightness level). If there's a significant step up in brightness,
// the limited number of steps (quantization) in the old data will be
// quite visible in the re-scaled version. For a non-destructive
// change, you'll need to re-render the full strip data. C'est la vie.
uint8_t c, *ptr = pixels,
oldBrightness = brightness - 1; // De-wrap old brightness value
uint16_t scale;
if (oldBrightness == 0)
scale = 0; // Avoid /0
else if (b == 255)
scale = 65535 / oldBrightness;
else
scale = (((uint16_t)newBrightness << 8) - 1) / oldBrightness;
for (uint16_t i = 0; i < numBytes; i++) {
c = *ptr;
*ptr++ = (c * scale) >> 8;
}
brightness = newBrightness;
}
}
/*!
@brief Retrieve the last-set brightness value for the strip.
@return Brightness value: 0 = minimum (off), 255 = maximum.
*/
uint8_t Adafruit_NeoPixel::getBrightness(void) const { return brightness - 1; }
/*!
@brief Fill the whole NeoPixel strip with 0 / black / off.
*/
void Adafruit_NeoPixel::clear(void) { memset(pixels, 0, numBytes); }
// A 32-bit variant of gamma8() that applies the same function
// to all components of a packed RGB or WRGB value.
uint32_t Adafruit_NeoPixel::gamma32(uint32_t x) {
uint8_t *y = (uint8_t *)&x;
// All four bytes of a 32-bit value are filtered even if RGB (not WRGB),
// to avoid a bunch of shifting and masking that would be necessary for
// properly handling different endianisms (and each byte is a fairly
// trivial operation, so it might not even be wasting cycles vs a check
// and branch for the RGB case). In theory this might cause trouble *if*
// someone's storing information in the unused most significant byte
// of an RGB value, but this seems exceedingly rare and if it's
// encountered in reality they can mask values going in or coming out.
for (uint8_t i = 0; i < 4; i++)
y[i] = gamma8(y[i]);
return x; // Packed 32-bit return
}
/*!
@brief Fill NeoPixel strip with one or more cycles of hues.
Everyone loves the rainbow swirl so much, now it's canon!
@param first_hue Hue of first pixel, 0-65535, representing one full
cycle of the color wheel. Each subsequent pixel will
be offset to complete one or more cycles over the
length of the strip.
@param reps Number of cycles of the color wheel over the length
of the strip. Default is 1. Negative values can be
used to reverse the hue order.
@param saturation Saturation (optional), 0-255 = gray to pure hue,
default = 255.
@param brightness Brightness/value (optional), 0-255 = off to max,
default = 255. This is distinct and in combination
with any configured global strip brightness.
@param gammify If true (default), apply gamma correction to colors
for better appearance.
*/
void Adafruit_NeoPixel::rainbow(uint16_t first_hue, int8_t reps,
uint8_t saturation, uint8_t brightness, bool gammify) {
for (uint16_t i=0; i