first commit
This commit is contained in:
504
libraries/Dimmable_Light_for_Arduino/LICENSE
Normal file
504
libraries/Dimmable_Light_for_Arduino/LICENSE
Normal file
@@ -0,0 +1,504 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 2.1, February 1999
|
||||
|
||||
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
[This is the first released version of the Lesser GPL. It also counts
|
||||
as the successor of the GNU Library Public License, version 2, hence
|
||||
the version number 2.1.]
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
Licenses are intended to guarantee your freedom to share and change
|
||||
free software--to make sure the software is free for all its users.
|
||||
|
||||
This license, the Lesser General Public License, applies to some
|
||||
specially designated software packages--typically libraries--of the
|
||||
Free Software Foundation and other authors who decide to use it. You
|
||||
can use it too, but we suggest you first think carefully about whether
|
||||
this license or the ordinary General Public License is the better
|
||||
strategy to use in any particular case, based on the explanations below.
|
||||
|
||||
When we speak of free software, we are referring to freedom of use,
|
||||
not price. Our General Public Licenses are designed to make sure that
|
||||
you have the freedom to distribute copies of free software (and charge
|
||||
for this service if you wish); that you receive source code or can get
|
||||
it if you want it; that you can change the software and use pieces of
|
||||
it in new free programs; and that you are informed that you can do
|
||||
these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
distributors to deny you these rights or to ask you to surrender these
|
||||
rights. These restrictions translate to certain responsibilities for
|
||||
you if you distribute copies of the library or if you modify it.
|
||||
|
||||
For example, if you distribute copies of the library, whether gratis
|
||||
or for a fee, you must give the recipients all the rights that we gave
|
||||
you. You must make sure that they, too, receive or can get the source
|
||||
code. If you link other code with the library, you must provide
|
||||
complete object files to the recipients, so that they can relink them
|
||||
with the library after making changes to the library and recompiling
|
||||
it. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with a two-step method: (1) we copyright the
|
||||
library, and (2) we offer you this license, which gives you legal
|
||||
permission to copy, distribute and/or modify the library.
|
||||
|
||||
To protect each distributor, we want to make it very clear that
|
||||
there is no warranty for the free library. Also, if the library is
|
||||
modified by someone else and passed on, the recipients should know
|
||||
that what they have is not the original version, so that the original
|
||||
author's reputation will not be affected by problems that might be
|
||||
introduced by others.
|
||||
|
||||
Finally, software patents pose a constant threat to the existence of
|
||||
any free program. We wish to make sure that a company cannot
|
||||
effectively restrict the users of a free program by obtaining a
|
||||
restrictive license from a patent holder. Therefore, we insist that
|
||||
any patent license obtained for a version of the library must be
|
||||
consistent with the full freedom of use specified in this license.
|
||||
|
||||
Most GNU software, including some libraries, is covered by the
|
||||
ordinary GNU General Public License. This license, the GNU Lesser
|
||||
General Public License, applies to certain designated libraries, and
|
||||
is quite different from the ordinary General Public License. We use
|
||||
this license for certain libraries in order to permit linking those
|
||||
libraries into non-free programs.
|
||||
|
||||
When a program is linked with a library, whether statically or using
|
||||
a shared library, the combination of the two is legally speaking a
|
||||
combined work, a derivative of the original library. The ordinary
|
||||
General Public License therefore permits such linking only if the
|
||||
entire combination fits its criteria of freedom. The Lesser General
|
||||
Public License permits more lax criteria for linking other code with
|
||||
the library.
|
||||
|
||||
We call this license the "Lesser" General Public License because it
|
||||
does Less to protect the user's freedom than the ordinary General
|
||||
Public License. It also provides other free software developers Less
|
||||
of an advantage over competing non-free programs. These disadvantages
|
||||
are the reason we use the ordinary General Public License for many
|
||||
libraries. However, the Lesser license provides advantages in certain
|
||||
special circumstances.
|
||||
|
||||
For example, on rare occasions, there may be a special need to
|
||||
encourage the widest possible use of a certain library, so that it becomes
|
||||
a de-facto standard. To achieve this, non-free programs must be
|
||||
allowed to use the library. A more frequent case is that a free
|
||||
library does the same job as widely used non-free libraries. In this
|
||||
case, there is little to gain by limiting the free library to free
|
||||
software only, so we use the Lesser General Public License.
|
||||
|
||||
In other cases, permission to use a particular library in non-free
|
||||
programs enables a greater number of people to use a large body of
|
||||
free software. For example, permission to use the GNU C Library in
|
||||
non-free programs enables many more people to use the whole GNU
|
||||
operating system, as well as its variant, the GNU/Linux operating
|
||||
system.
|
||||
|
||||
Although the Lesser General Public License is Less protective of the
|
||||
users' freedom, it does ensure that the user of a program that is
|
||||
linked with the Library has the freedom and the wherewithal to run
|
||||
that program using a modified version of the Library.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow. Pay close attention to the difference between a
|
||||
"work based on the library" and a "work that uses the library". The
|
||||
former contains code derived from the library, whereas the latter must
|
||||
be combined with the library in order to run.
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License Agreement applies to any software library or other
|
||||
program which contains a notice placed by the copyright holder or
|
||||
other authorized party saying it may be distributed under the terms of
|
||||
this Lesser General Public License (also called "this License").
|
||||
Each licensee is addressed as "you".
|
||||
|
||||
A "library" means a collection of software functions and/or data
|
||||
prepared so as to be conveniently linked with application programs
|
||||
(which use some of those functions and data) to form executables.
|
||||
|
||||
The "Library", below, refers to any such software library or work
|
||||
which has been distributed under these terms. A "work based on the
|
||||
Library" means either the Library or any derivative work under
|
||||
copyright law: that is to say, a work containing the Library or a
|
||||
portion of it, either verbatim or with modifications and/or translated
|
||||
straightforwardly into another language. (Hereinafter, translation is
|
||||
included without limitation in the term "modification".)
|
||||
|
||||
"Source code" for a work means the preferred form of the work for
|
||||
making modifications to it. For a library, complete source code means
|
||||
all the source code for all modules it contains, plus any associated
|
||||
interface definition files, plus the scripts used to control compilation
|
||||
and installation of the library.
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running a program using the Library is not restricted, and output from
|
||||
such a program is covered only if its contents constitute a work based
|
||||
on the Library (independent of the use of the Library in a tool for
|
||||
writing it). Whether that is true depends on what the Library does
|
||||
and what the program that uses the Library does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Library's
|
||||
complete source code as you receive it, in any medium, provided that
|
||||
you conspicuously and appropriately publish on each copy an
|
||||
appropriate copyright notice and disclaimer of warranty; keep intact
|
||||
all the notices that refer to this License and to the absence of any
|
||||
warranty; and distribute a copy of this License along with the
|
||||
Library.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy,
|
||||
and you may at your option offer warranty protection in exchange for a
|
||||
fee.
|
||||
|
||||
2. You may modify your copy or copies of the Library or any portion
|
||||
of it, thus forming a work based on the Library, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) The modified work must itself be a software library.
|
||||
|
||||
b) You must cause the files modified to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
c) You must cause the whole of the work to be licensed at no
|
||||
charge to all third parties under the terms of this License.
|
||||
|
||||
d) If a facility in the modified Library refers to a function or a
|
||||
table of data to be supplied by an application program that uses
|
||||
the facility, other than as an argument passed when the facility
|
||||
is invoked, then you must make a good faith effort to ensure that,
|
||||
in the event an application does not supply such function or
|
||||
table, the facility still operates, and performs whatever part of
|
||||
its purpose remains meaningful.
|
||||
|
||||
(For example, a function in a library to compute square roots has
|
||||
a purpose that is entirely well-defined independent of the
|
||||
application. Therefore, Subsection 2d requires that any
|
||||
application-supplied function or table used by this function must
|
||||
be optional: if the application does not supply it, the square
|
||||
root function must still compute square roots.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Library,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Library, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote
|
||||
it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Library.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Library
|
||||
with the Library (or with a work based on the Library) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may opt to apply the terms of the ordinary GNU General Public
|
||||
License instead of this License to a given copy of the Library. To do
|
||||
this, you must alter all the notices that refer to this License, so
|
||||
that they refer to the ordinary GNU General Public License, version 2,
|
||||
instead of to this License. (If a newer version than version 2 of the
|
||||
ordinary GNU General Public License has appeared, then you can specify
|
||||
that version instead if you wish.) Do not make any other change in
|
||||
these notices.
|
||||
|
||||
Once this change is made in a given copy, it is irreversible for
|
||||
that copy, so the ordinary GNU General Public License applies to all
|
||||
subsequent copies and derivative works made from that copy.
|
||||
|
||||
This option is useful when you wish to copy part of the code of
|
||||
the Library into a program that is not a library.
|
||||
|
||||
4. You may copy and distribute the Library (or a portion or
|
||||
derivative of it, under Section 2) in object code or executable form
|
||||
under the terms of Sections 1 and 2 above provided that you accompany
|
||||
it with the complete corresponding machine-readable source code, which
|
||||
must be distributed under the terms of Sections 1 and 2 above on a
|
||||
medium customarily used for software interchange.
|
||||
|
||||
If distribution of object code is made by offering access to copy
|
||||
from a designated place, then offering equivalent access to copy the
|
||||
source code from the same place satisfies the requirement to
|
||||
distribute the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
5. A program that contains no derivative of any portion of the
|
||||
Library, but is designed to work with the Library by being compiled or
|
||||
linked with it, is called a "work that uses the Library". Such a
|
||||
work, in isolation, is not a derivative work of the Library, and
|
||||
therefore falls outside the scope of this License.
|
||||
|
||||
However, linking a "work that uses the Library" with the Library
|
||||
creates an executable that is a derivative of the Library (because it
|
||||
contains portions of the Library), rather than a "work that uses the
|
||||
library". The executable is therefore covered by this License.
|
||||
Section 6 states terms for distribution of such executables.
|
||||
|
||||
When a "work that uses the Library" uses material from a header file
|
||||
that is part of the Library, the object code for the work may be a
|
||||
derivative work of the Library even though the source code is not.
|
||||
Whether this is true is especially significant if the work can be
|
||||
linked without the Library, or if the work is itself a library. The
|
||||
threshold for this to be true is not precisely defined by law.
|
||||
|
||||
If such an object file uses only numerical parameters, data
|
||||
structure layouts and accessors, and small macros and small inline
|
||||
functions (ten lines or less in length), then the use of the object
|
||||
file is unrestricted, regardless of whether it is legally a derivative
|
||||
work. (Executables containing this object code plus portions of the
|
||||
Library will still fall under Section 6.)
|
||||
|
||||
Otherwise, if the work is a derivative of the Library, you may
|
||||
distribute the object code for the work under the terms of Section 6.
|
||||
Any executables containing that work also fall under Section 6,
|
||||
whether or not they are linked directly with the Library itself.
|
||||
|
||||
6. As an exception to the Sections above, you may also combine or
|
||||
link a "work that uses the Library" with the Library to produce a
|
||||
work containing portions of the Library, and distribute that work
|
||||
under terms of your choice, provided that the terms permit
|
||||
modification of the work for the customer's own use and reverse
|
||||
engineering for debugging such modifications.
|
||||
|
||||
You must give prominent notice with each copy of the work that the
|
||||
Library is used in it and that the Library and its use are covered by
|
||||
this License. You must supply a copy of this License. If the work
|
||||
during execution displays copyright notices, you must include the
|
||||
copyright notice for the Library among them, as well as a reference
|
||||
directing the user to the copy of this License. Also, you must do one
|
||||
of these things:
|
||||
|
||||
a) Accompany the work with the complete corresponding
|
||||
machine-readable source code for the Library including whatever
|
||||
changes were used in the work (which must be distributed under
|
||||
Sections 1 and 2 above); and, if the work is an executable linked
|
||||
with the Library, with the complete machine-readable "work that
|
||||
uses the Library", as object code and/or source code, so that the
|
||||
user can modify the Library and then relink to produce a modified
|
||||
executable containing the modified Library. (It is understood
|
||||
that the user who changes the contents of definitions files in the
|
||||
Library will not necessarily be able to recompile the application
|
||||
to use the modified definitions.)
|
||||
|
||||
b) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (1) uses at run time a
|
||||
copy of the library already present on the user's computer system,
|
||||
rather than copying library functions into the executable, and (2)
|
||||
will operate properly with a modified version of the library, if
|
||||
the user installs one, as long as the modified version is
|
||||
interface-compatible with the version that the work was made with.
|
||||
|
||||
c) Accompany the work with a written offer, valid for at
|
||||
least three years, to give the same user the materials
|
||||
specified in Subsection 6a, above, for a charge no more
|
||||
than the cost of performing this distribution.
|
||||
|
||||
d) If distribution of the work is made by offering access to copy
|
||||
from a designated place, offer equivalent access to copy the above
|
||||
specified materials from the same place.
|
||||
|
||||
e) Verify that the user has already received a copy of these
|
||||
materials or that you have already sent this user a copy.
|
||||
|
||||
For an executable, the required form of the "work that uses the
|
||||
Library" must include any data and utility programs needed for
|
||||
reproducing the executable from it. However, as a special exception,
|
||||
the materials to be distributed need not include anything that is
|
||||
normally distributed (in either source or binary form) with the major
|
||||
components (compiler, kernel, and so on) of the operating system on
|
||||
which the executable runs, unless that component itself accompanies
|
||||
the executable.
|
||||
|
||||
It may happen that this requirement contradicts the license
|
||||
restrictions of other proprietary libraries that do not normally
|
||||
accompany the operating system. Such a contradiction means you cannot
|
||||
use both them and the Library together in an executable that you
|
||||
distribute.
|
||||
|
||||
7. You may place library facilities that are a work based on the
|
||||
Library side-by-side in a single library together with other library
|
||||
facilities not covered by this License, and distribute such a combined
|
||||
library, provided that the separate distribution of the work based on
|
||||
the Library and of the other library facilities is otherwise
|
||||
permitted, and provided that you do these two things:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work
|
||||
based on the Library, uncombined with any other library
|
||||
facilities. This must be distributed under the terms of the
|
||||
Sections above.
|
||||
|
||||
b) Give prominent notice with the combined library of the fact
|
||||
that part of it is a work based on the Library, and explaining
|
||||
where to find the accompanying uncombined form of the same work.
|
||||
|
||||
8. You may not copy, modify, sublicense, link with, or distribute
|
||||
the Library except as expressly provided under this License. Any
|
||||
attempt otherwise to copy, modify, sublicense, link with, or
|
||||
distribute the Library is void, and will automatically terminate your
|
||||
rights under this License. However, parties who have received copies,
|
||||
or rights, from you under this License will not have their licenses
|
||||
terminated so long as such parties remain in full compliance.
|
||||
|
||||
9. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Library or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Library (or any work based on the
|
||||
Library), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Library or works based on it.
|
||||
|
||||
10. Each time you redistribute the Library (or any work based on the
|
||||
Library), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute, link with or modify the Library
|
||||
subject to these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties with
|
||||
this License.
|
||||
|
||||
11. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Library at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Library by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Library.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any
|
||||
particular circumstance, the balance of the section is intended to apply,
|
||||
and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
12. If the distribution and/or use of the Library is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Library under this License may add
|
||||
an explicit geographical distribution limitation excluding those countries,
|
||||
so that distribution is permitted only in or among countries not thus
|
||||
excluded. In such case, this License incorporates the limitation as if
|
||||
written in the body of this License.
|
||||
|
||||
13. The Free Software Foundation may publish revised and/or new
|
||||
versions of the Lesser General Public License from time to time.
|
||||
Such new versions will be similar in spirit to the present version,
|
||||
but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Library
|
||||
specifies a version number of this License which applies to it and
|
||||
"any later version", you have the option of following the terms and
|
||||
conditions either of that version or of any later version published by
|
||||
the Free Software Foundation. If the Library does not specify a
|
||||
license version number, you may choose any version ever published by
|
||||
the Free Software Foundation.
|
||||
|
||||
14. If you wish to incorporate parts of the Library into other free
|
||||
programs whose distribution conditions are incompatible with these,
|
||||
write to the author to ask for permission. For software which is
|
||||
copyrighted by the Free Software Foundation, write to the Free
|
||||
Software Foundation; we sometimes make exceptions for this. Our
|
||||
decision will be guided by the two goals of preserving the free status
|
||||
of all derivatives of our free software and of promoting the sharing
|
||||
and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
|
||||
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
|
||||
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
|
||||
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
|
||||
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
|
||||
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
|
||||
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
|
||||
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
|
||||
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
|
||||
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
|
||||
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
|
||||
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
|
||||
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
|
||||
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
|
||||
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
|
||||
DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Libraries
|
||||
|
||||
If you develop a new library, and you want it to be of the greatest
|
||||
possible use to the public, we recommend making it free software that
|
||||
everyone can redistribute and change. You can do so by permitting
|
||||
redistribution under these terms (or, alternatively, under the terms of the
|
||||
ordinary General Public License).
|
||||
|
||||
To apply these terms, attach the following notices to the library. It is
|
||||
safest to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least the
|
||||
"copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the library's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
|
||||
USA
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the library, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the
|
||||
library `Frob' (a library for tweaking knobs) written by James Random
|
||||
Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1990
|
||||
Ty Coon, President of Vice
|
||||
|
||||
That's all there is to it!
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Before uploading this sketch, check and modify the following variables
|
||||
* accordingly to your hardware setup:
|
||||
* - syncPin, the pin listening for AC zero cross signal
|
||||
* - thyristorPin, the pin connected to the thyristor
|
||||
*/
|
||||
|
||||
#include <dimmable_light.h>
|
||||
|
||||
const int syncPin = 13;
|
||||
const int thyristorPin = 14;
|
||||
|
||||
DimmableLight light(thyristorPin);
|
||||
|
||||
// Delay between brightness increments, in milliseconds
|
||||
const int period = 50;
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
while (!Serial)
|
||||
;
|
||||
Serial.println();
|
||||
Serial.println("Dimmable Light for Arduino: first example");
|
||||
|
||||
Serial.print("Initializing DimmableLight library... ");
|
||||
DimmableLight::setSyncPin(syncPin);
|
||||
// VERY IMPORTANT: Call this method to activate the library
|
||||
DimmableLight::begin();
|
||||
Serial.println("Done!");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
for (int i = 0; i < 256; i++) {
|
||||
light.setBrightness(i);
|
||||
delay(period);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* An extension of the first example to demonstrate how easy is controlling multiple lights.
|
||||
*/
|
||||
#include <dimmable_light.h>
|
||||
|
||||
const int syncPin = 13;
|
||||
|
||||
DimmableLight light1(14);
|
||||
DimmableLight light2(12);
|
||||
|
||||
// Delay between brightness changes, in milliseconds
|
||||
const int period = 1000;
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
while (!Serial)
|
||||
;
|
||||
Serial.println();
|
||||
Serial.println("Dimmable Light for Arduino: second example");
|
||||
Serial.println();
|
||||
|
||||
Serial.print("Initializing the dimmable light class... ");
|
||||
DimmableLight::setSyncPin(syncPin);
|
||||
DimmableLight::begin();
|
||||
Serial.println("Done!");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
light1.setBrightness(0);
|
||||
light2.setBrightness(255);
|
||||
delay(period);
|
||||
|
||||
light1.setBrightness(128);
|
||||
light2.setBrightness(128);
|
||||
delay(period);
|
||||
|
||||
light1.setBrightness(255);
|
||||
light2.setBrightness(0);
|
||||
delay(period);
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
/**
|
||||
* In this example you can see a number of effects on indipendent lights.
|
||||
* To switch among the available effects, (un)comment the proper line in the setup() function.
|
||||
*
|
||||
* NOTE: compiles only for ESP8266 and ESP32 because the Ticker.h dependency.
|
||||
*/
|
||||
|
||||
#include <Ticker.h>
|
||||
#include <dimmable_light.h>
|
||||
|
||||
const int syncPin = 13;
|
||||
DimmableLight l1(5);
|
||||
DimmableLight l2(4);
|
||||
DimmableLight l3(14);
|
||||
DimmableLight l4(12);
|
||||
DimmableLight l5(15);
|
||||
|
||||
Ticker dim;
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
while (!Serial)
|
||||
;
|
||||
Serial.println();
|
||||
Serial.println("Dimmable Light for Arduino: third example");
|
||||
Serial.println();
|
||||
|
||||
Serial.print("Initializing the dimmable light class... ");
|
||||
DimmableLight::setSyncPin(syncPin);
|
||||
DimmableLight::begin();
|
||||
Serial.println("Done!");
|
||||
|
||||
Serial.println(String("Number of instantiated lights: ") + DimmableLight::getLightNumber());
|
||||
|
||||
// Uncomment one and only one among the following lines to see an effect
|
||||
// doEqual();
|
||||
// doEqualOnOff();
|
||||
// doDimSpecificStep();
|
||||
// doRangeLimit();
|
||||
// doNearValues();
|
||||
// doDimMixed();
|
||||
// doDimSweepEqual();
|
||||
// doInvertedDim();
|
||||
doCircularSwipe();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set particular values of brightness to every light.
|
||||
*/
|
||||
void doEqual() {
|
||||
const float period = 3;
|
||||
static int briLevels[] = { 0, 1, 2, 50, 100, 150, 254, 255 };
|
||||
static uint8_t brightnessStep = 0;
|
||||
Serial.println(String("Dimming at: ") + briLevels[brightnessStep] + "/255");
|
||||
l1.setBrightness(briLevels[brightnessStep]);
|
||||
l2.setBrightness(briLevels[brightnessStep]);
|
||||
l3.setBrightness(briLevels[brightnessStep]);
|
||||
l4.setBrightness(briLevels[brightnessStep]);
|
||||
l5.setBrightness(briLevels[brightnessStep]);
|
||||
|
||||
brightnessStep++;
|
||||
if (brightnessStep == sizeof(briLevels) / sizeof(briLevels[0])) { brightnessStep = 0; }
|
||||
dim.once(period, doEqual);
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn on and off simultaneously all the bulbs.
|
||||
*/
|
||||
void doEqualOnOff() {
|
||||
const float period = 3;
|
||||
static int briLevels[] = { 0, 255 };
|
||||
static uint8_t brightnessStep = 0;
|
||||
Serial.println(String("Dimming at: ") + briLevels[brightnessStep] + "/255");
|
||||
l1.setBrightness(briLevels[brightnessStep]);
|
||||
l2.setBrightness(briLevels[brightnessStep]);
|
||||
l3.setBrightness(briLevels[brightnessStep]);
|
||||
l4.setBrightness(briLevels[brightnessStep]);
|
||||
l5.setBrightness(briLevels[brightnessStep]);
|
||||
|
||||
brightnessStep++;
|
||||
if (brightnessStep == sizeof(briLevels) / sizeof(briLevels[0])) { brightnessStep = 0; }
|
||||
dim.once(period, doEqualOnOff);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set brightness to specific values.
|
||||
*/
|
||||
void doDimSpecificStep(void) {
|
||||
const float period = 3;
|
||||
static int briLevels1[] = { 40, 200 };
|
||||
static int briLevels2[] = { 60, 160 };
|
||||
static int briLevels3[] = { 80, 150 };
|
||||
static uint8_t brightnessStep = 0;
|
||||
Serial.println(String("Dimming at: ") + briLevels1[brightnessStep] + " and "
|
||||
+ briLevels2[brightnessStep] + " and " + briLevels3[brightnessStep] + " /255");
|
||||
l1.setBrightness(briLevels1[brightnessStep]);
|
||||
l2.setBrightness(briLevels2[brightnessStep]);
|
||||
l3.setBrightness(briLevels3[brightnessStep]);
|
||||
|
||||
brightnessStep++;
|
||||
if (brightnessStep == sizeof(briLevels1) / sizeof(briLevels1[0])) { brightnessStep = 0; }
|
||||
dim.once(period, doDimSpecificStep);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test a mixture between on, off and middle brightness.
|
||||
*/
|
||||
void doRangeLimit(void) {
|
||||
const float period = 5;
|
||||
static int briLevels1[] = { 0, 255 };
|
||||
static int briLevels2[] = { 255, 0 };
|
||||
static int briLevels3[] = { 100, 100 };
|
||||
static uint8_t brightnessStep = 0;
|
||||
Serial.println(String("Dimming at: ") + briLevels1[brightnessStep] + " and "
|
||||
+ briLevels2[brightnessStep] + " and " + briLevels3[brightnessStep] + " /255");
|
||||
l1.setBrightness(briLevels1[brightnessStep]);
|
||||
l2.setBrightness(briLevels2[brightnessStep]);
|
||||
l3.setBrightness(briLevels3[brightnessStep]);
|
||||
|
||||
brightnessStep++;
|
||||
if (brightnessStep == sizeof(briLevels1) / sizeof(briLevels1[0])) { brightnessStep = 0; }
|
||||
dim.once(period, doRangeLimit);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test your eyes sensitivity by switching between near values. Will you see any difference?
|
||||
*/
|
||||
void doNearValues(void) {
|
||||
const float period = 4;
|
||||
static int briLevels1[] = { 70, 70 };
|
||||
static int briLevels2[] = { 71, 71 };
|
||||
static int briLevels3[] = { 72, 73 };
|
||||
static uint8_t brightnessStep = 0;
|
||||
Serial.println(String("Dimming at: ") + briLevels1[brightnessStep] + " and "
|
||||
+ briLevels2[brightnessStep] + " and " + briLevels3[brightnessStep] + " /255");
|
||||
l1.setBrightness(briLevels1[brightnessStep]);
|
||||
l2.setBrightness(briLevels2[brightnessStep]);
|
||||
l3.setBrightness(briLevels3[brightnessStep]);
|
||||
|
||||
brightnessStep++;
|
||||
if (brightnessStep == sizeof(briLevels1) / sizeof(briLevels1[0])) { brightnessStep = 0; }
|
||||
dim.once(period, doNearValues);
|
||||
}
|
||||
|
||||
/**
|
||||
* The 1st the 5th are turned off, the 3rd is fixed to half brightness, and the 2nd and 4th sweep
|
||||
* in the opposite direction w.r.t. each other.
|
||||
*/
|
||||
void doDimMixed(void) {
|
||||
const float period = 0.05;
|
||||
static uint8_t brightnessStep = 1;
|
||||
static bool up = true;
|
||||
l1.setBrightness(brightnessStep);
|
||||
int b2 = 105;
|
||||
l2.setBrightness(b2);
|
||||
int b3 = -((int)brightnessStep - 255);
|
||||
l3.setBrightness(b3);
|
||||
Serial.println(String("Dimming at: ") + brightnessStep + " " + b2 + " " + b3 + "/255");
|
||||
|
||||
if (brightnessStep == 255 && up) {
|
||||
up = false;
|
||||
} else if (brightnessStep == 0 && !up) {
|
||||
up = true;
|
||||
} else {
|
||||
if (up) {
|
||||
brightnessStep++;
|
||||
} else {
|
||||
brightnessStep--;
|
||||
}
|
||||
// Jump some steps...
|
||||
// if(brightnessStep==6){
|
||||
// brightnessStep=249;
|
||||
// }
|
||||
}
|
||||
dim.once(period, doDimMixed);
|
||||
}
|
||||
|
||||
/**
|
||||
* All the lights simultaneously fade in and out.
|
||||
*/
|
||||
void doDimSweepEqual(void) {
|
||||
const float period = 0.05;
|
||||
static uint8_t brightnessStep = 1;
|
||||
static bool up = true;
|
||||
l1.setBrightness(brightnessStep);
|
||||
l2.setBrightness(brightnessStep);
|
||||
l3.setBrightness(brightnessStep);
|
||||
l4.setBrightness(brightnessStep);
|
||||
l5.setBrightness(brightnessStep);
|
||||
Serial.println(String("Dimming at: ") + brightnessStep + "/255");
|
||||
|
||||
if (brightnessStep == 255 && up) {
|
||||
up = false;
|
||||
} else if (brightnessStep == 0 && !up) {
|
||||
up = true;
|
||||
} else {
|
||||
if (up) {
|
||||
brightnessStep++;
|
||||
} else {
|
||||
brightnessStep--;
|
||||
}
|
||||
}
|
||||
dim.once(period, doDimSweepEqual);
|
||||
}
|
||||
|
||||
/**
|
||||
* The group formed by even bulbs sweep in the opposite direction w.r.t. the odd group.
|
||||
*/
|
||||
void doInvertedDim(void) {
|
||||
const float period = 0.05;
|
||||
static uint8_t brightnessStep = 1;
|
||||
static bool up = true;
|
||||
int oppositeBrightness = -((int)brightnessStep - 255);
|
||||
|
||||
l1.setBrightness(brightnessStep);
|
||||
l2.setBrightness(oppositeBrightness);
|
||||
l3.setBrightness(brightnessStep);
|
||||
l4.setBrightness(oppositeBrightness);
|
||||
l5.setBrightness(brightnessStep);
|
||||
Serial.println(String("Dimming at: ") + brightnessStep + " " + oppositeBrightness + "/255");
|
||||
|
||||
if (brightnessStep == 255 && up) {
|
||||
up = false;
|
||||
} else if (brightnessStep == 0 && !up) {
|
||||
up = true;
|
||||
} else {
|
||||
if (up) {
|
||||
brightnessStep++;
|
||||
} else {
|
||||
brightnessStep--;
|
||||
}
|
||||
}
|
||||
dim.once(period, doInvertedDim);
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn on the light with (255/nLights) steps offset between consecutive lights.
|
||||
*/
|
||||
void doCircularSwipe(void) {
|
||||
const float period = 0.01;
|
||||
|
||||
static uint16_t brightnessStep = 255;
|
||||
|
||||
// Alternatively, you can use the function conversionPow(..) instead conversion(..)
|
||||
l1.setBrightness(triangularFunction(module(brightnessStep + 0, 512)));
|
||||
l2.setBrightness(triangularFunction(module(brightnessStep + 51 * 1, 512)));
|
||||
l3.setBrightness(triangularFunction(module(brightnessStep + 51 * 2, 512)));
|
||||
l4.setBrightness(triangularFunction(module(brightnessStep + 51 * 3, 512)));
|
||||
l5.setBrightness(triangularFunction(module(brightnessStep + 51 * 4, 512)));
|
||||
|
||||
brightnessStep++;
|
||||
if (brightnessStep == 512) { brightnessStep = 0; }
|
||||
dim.once(period, doCircularSwipe);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the module of a non-negative number (optimized).
|
||||
*/
|
||||
unsigned int module(unsigned int value, unsigned int max) {
|
||||
if (value < max) { return value; }
|
||||
return value % max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a number in range [0; 512), return a triangular function [0;255].
|
||||
*/
|
||||
uint8_t triangularFunction(uint16_t value) {
|
||||
int simmetricValue = 0;
|
||||
if (value <= 255) { simmetricValue = value; }
|
||||
if (value >= 256 && value <= 511) { simmetricValue = -value + 511; }
|
||||
return simmetricValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a number in range [0; 512), return a "pow-ed" triangular function [0;255].
|
||||
*/
|
||||
uint8_t conversionPow(uint16_t value) {
|
||||
int simmetricValue = 0;
|
||||
if (value >= 256 && value <= 511) { simmetricValue = -value + 511; }
|
||||
if (value <= 255) { simmetricValue = value; }
|
||||
|
||||
if (simmetricValue < 150) { return 0; }
|
||||
int y = pow(simmetricValue - 150, 1.2);
|
||||
if (y > 255) { return 255; }
|
||||
return y;
|
||||
}
|
||||
|
||||
void loop() {}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* A simple example to show the usage of DimmableLightManager class.
|
||||
* This class helps you to give a name to each light, and using it
|
||||
* to control a light.
|
||||
*/
|
||||
#include <dimmable_light_manager.h>
|
||||
|
||||
const int N = 3;
|
||||
|
||||
#if defined(ARDUINO_ARCH_ESP8266)
|
||||
const int syncPin = 13;
|
||||
const int pins[N] = { 5, 4, 14 };
|
||||
#elif defined(ARDUINO_ARCH_ESP32)
|
||||
const int syncPin = 23;
|
||||
const int pins[N] = { 4, 16, 17 };
|
||||
#elif defined(ARDUINO_ARCH_AVR)
|
||||
const int syncPin = 2;
|
||||
const int pins[N] = { 3, 4, 5 };
|
||||
#elif defined(ARDUINO_ARCH_SAMD)
|
||||
const int syncPin = 2;
|
||||
const int pins[N] = { 3, 4, 5 };
|
||||
#elif (defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED))
|
||||
const int syncPin = 2;
|
||||
const int pins[N] = { 3, 4, 5 };
|
||||
#endif
|
||||
|
||||
DimmableLightManager dlm;
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
while (!Serial)
|
||||
;
|
||||
Serial.println();
|
||||
Serial.println("Dimmable Light for Arduino: fourth example");
|
||||
|
||||
Serial.println("Initializing the dimmable light class... ");
|
||||
|
||||
// Add all the lights you need
|
||||
for (int i = 0; i < N; i++) {
|
||||
if (dlm.add(String("light") + (i + 1), pins[i])) {
|
||||
Serial.println(String(" ") + (i + 1) + "-th light added correctly");
|
||||
} else {
|
||||
Serial.println(" Light isn't added, probably this name was already used...");
|
||||
}
|
||||
}
|
||||
|
||||
DimmableLight::setSyncPin(syncPin);
|
||||
DimmableLightManager::begin();
|
||||
|
||||
Serial.println("Done!");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
for (int b = 0; b < 255; b += 10) {
|
||||
for (int i = 0; i < dlm.getCount(); i++) {
|
||||
std::pair<String, DimmableLight*> p = dlm.get();
|
||||
String lightName = p.first;
|
||||
DimmableLight* dimLight = p.second;
|
||||
// Altervatively, you can require to the manager a specific light
|
||||
// DimmableLight* dimLight = dlm.get("light1");
|
||||
|
||||
Serial.println(String("Setting --") + lightName + "-- to brightness: " + b);
|
||||
dimLight->setBrightness(b);
|
||||
}
|
||||
delay(500);
|
||||
}
|
||||
Serial.println();
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* This advanced example shows how to use the DimmableLightManager
|
||||
* combined with Ticker class.
|
||||
*
|
||||
* In this case the friendly names are "light1", "light2" and so on...
|
||||
* Once your setup is ready (light, thyristor, wemos flashed with this sketch),
|
||||
* you should see a very simple effect: all the light will fade from
|
||||
* dark to maximum brightness simultaneously.
|
||||
*
|
||||
* NOTE: compiles only for ESP8266 and ESP32 because the Ticker.h dependency
|
||||
*/
|
||||
|
||||
#include <Ticker.h>
|
||||
#include <dimmable_light_manager.h>
|
||||
|
||||
#define N 5
|
||||
|
||||
const int syncPin = 13;
|
||||
int pins[N] = { 5, 4, 14, 12, 15 };
|
||||
|
||||
// This param modifies the effect speed. The value is the period between a
|
||||
// brightness value and the next one, in seconds
|
||||
const float period = 0.05;
|
||||
|
||||
Ticker dim;
|
||||
|
||||
DimmableLightManager dlm;
|
||||
|
||||
void doRaise(void) {
|
||||
static uint8_t brightnessStep = 0;
|
||||
|
||||
for (int i = 0; i < dlm.getCount(); i++) {
|
||||
DimmableLight* dimLight = dlm.get().second;
|
||||
dimLight->setBrightness(brightnessStep);
|
||||
}
|
||||
|
||||
if (brightnessStep == 255) {
|
||||
brightnessStep = 0;
|
||||
dim.attach(period, doLower);
|
||||
} else {
|
||||
brightnessStep++;
|
||||
}
|
||||
}
|
||||
|
||||
void doLower(void) {
|
||||
static uint8_t brightnessStep = 255;
|
||||
|
||||
for (int i = 0; i < dlm.getCount(); i++) {
|
||||
DimmableLight* dimLight = dlm.get().second;
|
||||
dimLight->setBrightness(brightnessStep);
|
||||
}
|
||||
|
||||
if (brightnessStep == 0) {
|
||||
brightnessStep = 255;
|
||||
dim.attach(period, doRaise);
|
||||
} else {
|
||||
brightnessStep--;
|
||||
}
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
while (!Serial)
|
||||
;
|
||||
Serial.println();
|
||||
Serial.println("Dimmable Light for Arduino: fifth example");
|
||||
|
||||
Serial.println("Initializing the dimmable light class... ");
|
||||
|
||||
// Add all the lights you need
|
||||
for (int i = 0; i < N; i++) {
|
||||
if (dlm.add(String("light") + (i + 1), pins[i])) {
|
||||
Serial.println(String(" ") + (i + 1) + "-th light added correctly");
|
||||
} else {
|
||||
Serial.println(" Light isn't added, probably this name was already used...");
|
||||
}
|
||||
}
|
||||
|
||||
DimmableLight::setSyncPin(syncPin);
|
||||
DimmableLightManager::begin();
|
||||
|
||||
Serial.println("Done!");
|
||||
|
||||
// This line starts the effect. In the meanwhile,
|
||||
// you can continue to execution your own code (thanks to Ticker library)
|
||||
dim.attach(period, doRaise);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// Print the light name and its actual brightness
|
||||
for (int i = 0; i < dlm.getCount(); i++) {
|
||||
std::pair<String, DimmableLight*> p = dlm.get();
|
||||
DimmableLight* dimLight = p.second;
|
||||
// Altervatively, you can require to the manager a specific light
|
||||
// DimmableLight* dimLight = dlm.get("light1");
|
||||
|
||||
Serial.println(String(p.first) + " brightness:" + dimLight->getBrightness());
|
||||
}
|
||||
Serial.println();
|
||||
|
||||
delay(500);
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* This examples provides some effects to test and demonstrate the potentiality of DimmableLight.
|
||||
* Once you can uploaded this sketch, you can select one effect through the serial port. Just
|
||||
* type the code's effect (values among ["e0"-"e12"]) and "stop" to stop the current effect.
|
||||
* Remember to select CRLF line ending in Arduino IDE serial console.
|
||||
*
|
||||
* NOTE: install https://github.com/kroimon/Arduino-SerialCommand
|
||||
*/
|
||||
#include "effect.h"
|
||||
|
||||
#include <SerialCommand.h>
|
||||
|
||||
SerialCommand serialCmd;
|
||||
|
||||
int effectSelected = -1;
|
||||
void unrecognized(const char* message) {
|
||||
Serial.println(String(message) + ": command not recognized");
|
||||
serialCmd.clearBuffer();
|
||||
}
|
||||
|
||||
void stopEffect() {
|
||||
offAllLights();
|
||||
|
||||
effectSelected = -1;
|
||||
effect = nullptr;
|
||||
}
|
||||
|
||||
void selectEffect(unsigned char effectId) {
|
||||
if (effectSelected != effectId) {
|
||||
effectSelected = effectId;
|
||||
|
||||
switch (effectSelected) {
|
||||
case 0:
|
||||
Serial.println("##New Effect Selected## Equal");
|
||||
doEqual();
|
||||
break;
|
||||
case 1:
|
||||
Serial.println("##New Effect Selected## Equal On Off");
|
||||
doEqualOnOff();
|
||||
break;
|
||||
case 2:
|
||||
Serial.println("##New Effect Selected## Dim Specific Step");
|
||||
doDimSpecificStep();
|
||||
break;
|
||||
case 3:
|
||||
Serial.println("##New Effect Selected## Range Limit");
|
||||
doRangeLimit();
|
||||
break;
|
||||
case 4:
|
||||
Serial.println("##New Effect Selected## Near Values");
|
||||
doNearValues();
|
||||
break;
|
||||
case 5:
|
||||
Serial.println("##New Effect Selected## Dim Mixed");
|
||||
doDimMixed();
|
||||
break;
|
||||
case 6:
|
||||
Serial.println("##New Effect Selected## Dim Sweep Equal");
|
||||
doDimSweepEqual();
|
||||
break;
|
||||
case 7:
|
||||
Serial.println("##New Effect Selected## On Off Sweep");
|
||||
doOnOffSweep();
|
||||
break;
|
||||
case 8:
|
||||
Serial.println("##New Effect Selected## Inverted Dim");
|
||||
doInvertedDim();
|
||||
break;
|
||||
case 9:
|
||||
Serial.println("##New Effect Selected## Circular Swipe");
|
||||
doCircularSwipe();
|
||||
break;
|
||||
case 10:
|
||||
Serial.println("##New Effect Selected## Random Bri");
|
||||
doRandomBri();
|
||||
break;
|
||||
case 11:
|
||||
Serial.println("##New Effect Selected## Random Bri Peephole");
|
||||
doRandomBriPeephole();
|
||||
break;
|
||||
case 12:
|
||||
Serial.println("##New Effect Selected## Random Push Extreme Values");
|
||||
doRandomPushExtremeValues();
|
||||
break;
|
||||
case 13:
|
||||
Serial.println("##New Effect Selected## Circular Swipe Regular");
|
||||
doCircularSwipeRegular();
|
||||
break;
|
||||
default: Serial.println("Effect ID not implemented");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
while (!Serial)
|
||||
;
|
||||
Serial.println();
|
||||
Serial.println("Dimmable Light for Arduino: sixth example");
|
||||
|
||||
initLights();
|
||||
|
||||
serialCmd.addCommand("stop", []() {
|
||||
stopEffect();
|
||||
});
|
||||
serialCmd.addCommand("e0", []() {
|
||||
selectEffect(0);
|
||||
});
|
||||
serialCmd.addCommand("e1", []() {
|
||||
selectEffect(1);
|
||||
});
|
||||
serialCmd.addCommand("e2", []() {
|
||||
selectEffect(2);
|
||||
});
|
||||
serialCmd.addCommand("e3", []() {
|
||||
selectEffect(3);
|
||||
});
|
||||
serialCmd.addCommand("e4", []() {
|
||||
selectEffect(4);
|
||||
});
|
||||
serialCmd.addCommand("e5", []() {
|
||||
selectEffect(5);
|
||||
});
|
||||
serialCmd.addCommand("e6", []() {
|
||||
selectEffect(6);
|
||||
});
|
||||
serialCmd.addCommand("e7", []() {
|
||||
selectEffect(7);
|
||||
});
|
||||
serialCmd.addCommand("e8", []() {
|
||||
selectEffect(8);
|
||||
});
|
||||
serialCmd.addCommand("e9", []() {
|
||||
selectEffect(9);
|
||||
});
|
||||
serialCmd.addCommand("e10", []() {
|
||||
selectEffect(10);
|
||||
});
|
||||
serialCmd.addCommand("e11", []() {
|
||||
selectEffect(11);
|
||||
});
|
||||
serialCmd.addCommand("e12", []() {
|
||||
selectEffect(12);
|
||||
});
|
||||
serialCmd.addCommand("e13", []() {
|
||||
selectEffect(13);
|
||||
});
|
||||
|
||||
serialCmd.setDefaultHandler(unrecognized);
|
||||
|
||||
Serial.println("Select one effect ranging between e0 and e13");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
serialCmd.readSerial();
|
||||
|
||||
uint32_t now = millis();
|
||||
if (effectSelected == -1) {
|
||||
delay(20);
|
||||
} else if (now - lastCall > period) {
|
||||
if (effect != nullptr) effect();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
#include "effect.h"
|
||||
|
||||
void (*effect)() = nullptr;
|
||||
// The period between a call and the next one in millisecond
|
||||
uint16_t period = 0;
|
||||
|
||||
uint32_t lastCall = 0;
|
||||
|
||||
// A complicated way to define objects to allow the testing of different
|
||||
// classes on different microcontrollers
|
||||
#if defined(RAW_VALUES)
|
||||
extern DimmableLight
|
||||
#elif defined(LINEARIZED_VALUES)
|
||||
extern DimmableLightLinearized
|
||||
#endif
|
||||
|
||||
#if defined(ESP8266)
|
||||
// Remember that GPIO0 (D3) and GPIO2 (D4) are "critical" since they control the boot phase.
|
||||
// I have to disconnect them to make it boot when using Krida's dimmers. If you want to
|
||||
// use those pins without disconnecting and connecting the wires, you need additional circuitry to
|
||||
// "protect" them.
|
||||
lights[N_LIGHTS] = { { 5 }, { 4 }, { 14 }, { 12 }, { 15 }, { 16 }, { 0 }, { 2 } };
|
||||
#elif defined(ESP32)
|
||||
lights[N_LIGHTS] = { { 4 }, { 16 }, { 17 }, { 5 }, { 18 }, { 19 }, { 21 }, { 22 } };
|
||||
#elif defined(AVR) // Arduino
|
||||
lights[N_LIGHTS] = { { 3 }, { 4 }, { 5 }, { 6 }, { 7 }, { 8 }, { 9 }, { 10 } };
|
||||
#elif defined(ARDUINO_ARCH_SAMD)
|
||||
lights[N_LIGHTS] = { { 3 }, { 4 }, { 5 }, { 6 }, { 7 }, { 8 }, { 9 }, { 10 } };
|
||||
#elif (defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED))
|
||||
lights[N_LIGHTS] = { { 3 }, { 4 }, { 5 }, { 6 }, { 7 }, { 8 }, { 9 }, { 10 } };
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Set particular values of brightness to every light.
|
||||
*/
|
||||
void doEqual() {
|
||||
const unsigned int period = 3000;
|
||||
static const uint8_t briLevels[] = { 0, 1, 2, 50, 100, 150, 254, 255 };
|
||||
static uint8_t brightnessStep = 0;
|
||||
Serial.println(String("Dimming at: ") + briLevels[brightnessStep] + "/255");
|
||||
for (int i = 0; i < N_LIGHTS; i++) { lights[i].setBrightness(briLevels[brightnessStep]); }
|
||||
|
||||
brightnessStep++;
|
||||
if (brightnessStep == sizeof(briLevels) / sizeof(briLevels[0])) { brightnessStep = 0; }
|
||||
|
||||
::period = period;
|
||||
lastCall = millis();
|
||||
effect = doEqual;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn on and off simultaneously all the bulbs.
|
||||
*/
|
||||
void doEqualOnOff() {
|
||||
const unsigned int period = 3000;
|
||||
static int briLevels[] = { 0, 255 };
|
||||
static uint8_t brightnessStep = 0;
|
||||
Serial.println(String("Dimming at: ") + briLevels[brightnessStep] + "/255");
|
||||
for (int i = 0; i < N_LIGHTS; i++) { lights[i].setBrightness(briLevels[brightnessStep]); }
|
||||
|
||||
brightnessStep++;
|
||||
if (brightnessStep == sizeof(briLevels) / sizeof(briLevels[0])) { brightnessStep = 0; }
|
||||
|
||||
::period = period;
|
||||
lastCall = millis();
|
||||
effect = doEqualOnOff;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set brightness to specific values.
|
||||
*/
|
||||
void doDimSpecificStep(void) {
|
||||
const unsigned int period = 3000;
|
||||
static const uint8_t briLevels1[] = { 40, 200 };
|
||||
static const uint8_t briLevels2[] = { 60, 160 };
|
||||
static const uint8_t briLevels3[] = { 80, 130 };
|
||||
static uint8_t brightnessStep = 0;
|
||||
Serial.println(String("Dimming at: ") + briLevels1[brightnessStep] + " and "
|
||||
+ briLevels2[brightnessStep] + " and " + briLevels3[brightnessStep] + " /255");
|
||||
lights[1].setBrightness(briLevels1[brightnessStep]);
|
||||
lights[2].setBrightness(briLevels2[brightnessStep]);
|
||||
lights[3].setBrightness(briLevels3[brightnessStep]);
|
||||
|
||||
brightnessStep++;
|
||||
if (brightnessStep == sizeof(briLevels1) / sizeof(briLevels1[0])) { brightnessStep = 0; }
|
||||
|
||||
::period = period;
|
||||
lastCall = millis();
|
||||
effect = doDimSpecificStep;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test a mixture between on, off and middle brightness.
|
||||
*/
|
||||
void doRangeLimit(void) {
|
||||
const unsigned int period = 5000;
|
||||
static const uint8_t briLevels1[] = { 0, 255 };
|
||||
static const uint8_t briLevels2[] = { 255, 0 };
|
||||
static const uint8_t briLevels3[] = { 100, 100 };
|
||||
static uint8_t brightnessStep = 0;
|
||||
Serial.println(String("Dimming at: ") + briLevels1[brightnessStep] + " and "
|
||||
+ briLevels2[brightnessStep] + " and " + briLevels3[brightnessStep] + " /255");
|
||||
lights[1].setBrightness(briLevels1[brightnessStep]);
|
||||
lights[2].setBrightness(briLevels2[brightnessStep]);
|
||||
lights[3].setBrightness(briLevels3[brightnessStep]);
|
||||
|
||||
brightnessStep++;
|
||||
if (brightnessStep == sizeof(briLevels1) / sizeof(briLevels1[0])) { brightnessStep = 0; }
|
||||
|
||||
::period = period;
|
||||
lastCall = millis();
|
||||
effect = doRangeLimit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test your eyes sensitivity by switching between near values. Will you see any difference?
|
||||
*/
|
||||
void doNearValues(void) {
|
||||
const unsigned int period = 3000;
|
||||
static const uint8_t avg = 80;
|
||||
static const uint8_t diff = 2;
|
||||
static const uint8_t briLevelsLamp1[] = { avg - diff, avg };
|
||||
static const uint8_t briLevelsLamp2[] = { avg, avg + diff };
|
||||
static const uint8_t briLevelsLamp3[] = { avg + diff, avg - diff };
|
||||
static uint8_t brightnessStep = 0;
|
||||
Serial.println(String("Dimming at: ") + briLevelsLamp1[brightnessStep] + " and "
|
||||
+ briLevelsLamp2[brightnessStep] + " and " + briLevelsLamp3[brightnessStep] + " /255");
|
||||
lights[1].setBrightness(briLevelsLamp1[brightnessStep]);
|
||||
lights[2].setBrightness(briLevelsLamp2[brightnessStep]);
|
||||
lights[3].setBrightness(briLevelsLamp3[brightnessStep]);
|
||||
|
||||
brightnessStep++;
|
||||
if (brightnessStep == sizeof(briLevelsLamp1) / sizeof(briLevelsLamp1[0])) { brightnessStep = 0; }
|
||||
|
||||
::period = period;
|
||||
lastCall = millis();
|
||||
effect = doNearValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* The 1st the 5th are turned off, the 3rd is fixed to half brightness, and the 2nd and 4th sweep
|
||||
* in the opposite direction w.r.t. each other.
|
||||
*/
|
||||
void doDimMixed(void) {
|
||||
const unsigned int period = 50;
|
||||
static uint8_t brightnessStep = 1;
|
||||
static bool up = true;
|
||||
|
||||
lights[1].setBrightness(brightnessStep);
|
||||
int b2 = 105;
|
||||
lights[2].setBrightness(b2);
|
||||
int b3 = -((int)brightnessStep - 255);
|
||||
lights[3].setBrightness(b3);
|
||||
Serial.println(String("Dimming at: ") + brightnessStep + " " + b2 + " " + b3 + "/255");
|
||||
|
||||
if (brightnessStep == 255 && up) {
|
||||
up = false;
|
||||
} else if (brightnessStep == 0 && !up) {
|
||||
up = true;
|
||||
} else {
|
||||
if (up) {
|
||||
brightnessStep++;
|
||||
} else {
|
||||
brightnessStep--;
|
||||
}
|
||||
// Jump some steps...
|
||||
// if(brightnessStep==6){
|
||||
// brightnessStep=249;
|
||||
// }
|
||||
}
|
||||
|
||||
::period = period;
|
||||
lastCall = millis();
|
||||
effect = doDimMixed;
|
||||
}
|
||||
|
||||
/**
|
||||
* All the lights simultaneously fade in and out.
|
||||
*/
|
||||
void doDimSweepEqual(void) {
|
||||
const unsigned int period = 50;
|
||||
static uint8_t brightnessStep = 1;
|
||||
static bool up = true;
|
||||
for (int i = 0; i < N_LIGHTS; i++) { lights[i].setBrightness(brightnessStep); }
|
||||
Serial.println(String("Dimming at: ") + brightnessStep + "/255");
|
||||
|
||||
if (brightnessStep == 255 && up) {
|
||||
up = false;
|
||||
} else if (brightnessStep == 0 && !up) {
|
||||
up = true;
|
||||
} else {
|
||||
if (up) {
|
||||
brightnessStep++;
|
||||
} else {
|
||||
brightnessStep--;
|
||||
}
|
||||
}
|
||||
|
||||
::period = period;
|
||||
lastCall = millis();
|
||||
effect = doDimSweepEqual;
|
||||
}
|
||||
|
||||
void doOnOffSweep() {
|
||||
const unsigned int period = 700;
|
||||
static int16_t step = 0;
|
||||
|
||||
for (int i = 0; i < N_LIGHTS; i++) {
|
||||
if (step == i) {
|
||||
lights[i].setBrightness(255);
|
||||
} else {
|
||||
lights[i].setBrightness(0);
|
||||
}
|
||||
}
|
||||
|
||||
step++;
|
||||
if (step == N_LIGHTS) { step = 0; }
|
||||
|
||||
::period = period;
|
||||
lastCall = millis();
|
||||
effect = doOnOffSweep;
|
||||
}
|
||||
|
||||
/**
|
||||
* The group formed by even bulbs sweep in the opposite direction w.r.t. the odd group.
|
||||
*/
|
||||
void doInvertedDim(void) {
|
||||
const unsigned int period = 50;
|
||||
static uint8_t brightnessStep = 1;
|
||||
static bool up = true;
|
||||
int oppositeBrightness = -((int)brightnessStep - 255);
|
||||
|
||||
Serial.println(String("Dimming at: ") + brightnessStep + " " + oppositeBrightness + "/255");
|
||||
for (int i = 0; i < N_LIGHTS; i++) {
|
||||
if (i % 2 == 0) {
|
||||
lights[i].setBrightness(brightnessStep);
|
||||
} else {
|
||||
lights[i].setBrightness(oppositeBrightness);
|
||||
}
|
||||
}
|
||||
|
||||
if (brightnessStep == 255 && up) {
|
||||
up = false;
|
||||
} else if (brightnessStep == 0 && !up) {
|
||||
up = true;
|
||||
} else {
|
||||
if (up) {
|
||||
brightnessStep++;
|
||||
} else {
|
||||
brightnessStep--;
|
||||
}
|
||||
}
|
||||
|
||||
::period = period;
|
||||
lastCall = millis();
|
||||
effect = doInvertedDim;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the module of a non-negative number (optimized).
|
||||
*/
|
||||
unsigned int module(unsigned int value, unsigned int max) {
|
||||
if (value < max) { return value; }
|
||||
return value % max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a number in range [0; 512), return a triangular function [0;255], if value is not in this
|
||||
* range, return 0.
|
||||
*/
|
||||
uint8_t triangularFunction(uint16_t value) {
|
||||
int simmetricValue = 0;
|
||||
if (value <= 255) { simmetricValue = value; }
|
||||
if (value >= 256 && value <= 511) { simmetricValue = -value + 511; }
|
||||
return simmetricValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a number in range [0; 512), return a "pow-ed" triangular function [0;255].
|
||||
*/
|
||||
uint8_t conversionPow(uint16_t value) {
|
||||
int simmetricValue = 0;
|
||||
if (value >= 256 && value <= 511) { simmetricValue = -value + 511; }
|
||||
if (value <= 255) { simmetricValue = value; }
|
||||
|
||||
if (simmetricValue < 150) { return 0; }
|
||||
int y = pow(simmetricValue - 150, 1.2);
|
||||
if (y > 255) { return 255; }
|
||||
return y;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn on the light with (255/nLights) steps offset between consecutive lights.
|
||||
*/
|
||||
void doCircularSwipe(void) {
|
||||
const unsigned int period = 50;
|
||||
|
||||
static uint16_t brightnessStep = 255;
|
||||
|
||||
// Alternatively, you can use the function conversionPow(..) instead conversion(..)
|
||||
for (int i = 0; i < N_LIGHTS; i++) {
|
||||
int brightness = triangularFunction(module(brightnessStep + 32 * i, 512));
|
||||
lights[i].setBrightness(brightness);
|
||||
}
|
||||
|
||||
brightnessStep++;
|
||||
if (brightnessStep == 512) { brightnessStep = 0; }
|
||||
|
||||
::period = period;
|
||||
lastCall = millis();
|
||||
effect = doCircularSwipe;
|
||||
}
|
||||
|
||||
void doRandomBri() {
|
||||
const unsigned int period = 700;
|
||||
|
||||
for (int i = 0; i < N_LIGHTS; i++) {
|
||||
int bri = random(0, 256);
|
||||
lights[i].setBrightness(bri);
|
||||
}
|
||||
|
||||
::period = period;
|
||||
lastCall = millis();
|
||||
effect = doRandomBri;
|
||||
}
|
||||
|
||||
/**
|
||||
* The variance of random number is restricted around the mean value step after step
|
||||
*/
|
||||
void doRandomBriPeephole() {
|
||||
const unsigned int period = 700;
|
||||
const uint16_t briStep = 10;
|
||||
const uint16_t totStep = 16;
|
||||
|
||||
static uint16_t iteration = 0;
|
||||
|
||||
for (int i = 0; i < N_LIGHTS; i++) {
|
||||
int bri;
|
||||
// The last 2 step are set to the same brightness
|
||||
if (iteration >= totStep - 3) {
|
||||
bri = 127;
|
||||
} else {
|
||||
bri = random(0 + briStep * iteration, 256 - briStep * iteration);
|
||||
}
|
||||
Serial.print(String(bri) + " ");
|
||||
lights[i].setBrightness(bri);
|
||||
}
|
||||
Serial.println();
|
||||
|
||||
iteration++;
|
||||
if (iteration == totStep) { iteration = 0; }
|
||||
|
||||
::period = period;
|
||||
lastCall = millis();
|
||||
effect = doRandomBriPeephole;
|
||||
}
|
||||
|
||||
/**
|
||||
* The variance of random number is restricted around the mean value step after step
|
||||
*/
|
||||
void doRandomPushExtremeValues() {
|
||||
const unsigned int period = 1000;
|
||||
const uint16_t briStep = 10;
|
||||
|
||||
for (int i = 0; i < N_LIGHTS; i++) {
|
||||
int bri = random(0, briStep * 2 + 1);
|
||||
if (bri < briStep) {
|
||||
bri = bri;
|
||||
} else {
|
||||
bri = 255 - (briStep * 2 - bri);
|
||||
}
|
||||
Serial.print(String(bri) + " ");
|
||||
lights[i].setBrightness(bri);
|
||||
}
|
||||
Serial.println();
|
||||
|
||||
::period = period;
|
||||
lastCall = millis();
|
||||
effect = doRandomPushExtremeValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform a brightness sweep all over the lights with a delay between each light of DELAY steps.
|
||||
* This effect is perfectly smooth and simmetric w.r.t. doCircularSwipe().
|
||||
*/
|
||||
void doCircularSwipeRegular(void) {
|
||||
const unsigned int period = 40;
|
||||
const int HALF_PERIOD = 255;
|
||||
const int DELAY = 96;
|
||||
|
||||
static int brightnessStep = 0;
|
||||
|
||||
for (int i = 0; i < N_LIGHTS; i++) {
|
||||
unsigned int x = brightnessStep - DELAY * i < 0 ? 0 : brightnessStep - DELAY * i;
|
||||
unsigned int brightness = triangularFunction(module(x, DELAY * N_LIGHTS));
|
||||
lights[i].setBrightness(brightness);
|
||||
}
|
||||
|
||||
brightnessStep++;
|
||||
|
||||
// Avoid any long-term overflow
|
||||
if (brightnessStep >= HALF_PERIOD + 2 * DELAY * N_LIGHTS) {
|
||||
brightnessStep = HALF_PERIOD + DELAY * N_LIGHTS;
|
||||
}
|
||||
|
||||
::period = period;
|
||||
lastCall = millis();
|
||||
effect = doCircularSwipeRegular;
|
||||
}
|
||||
|
||||
void offAllLights() {
|
||||
for (int i = 0; i < N_LIGHTS; i++) { lights[i].setBrightness(0); }
|
||||
}
|
||||
|
||||
void initLights() {
|
||||
Serial.print("Initializing the dimmable light class... ");
|
||||
|
||||
#if defined(RAW_VALUES)
|
||||
DimmableLight::setSyncPin(syncPin);
|
||||
DimmableLight::begin();
|
||||
#elif defined(LINEARIZED_VALUES)
|
||||
DimmableLightLinearized::setSyncPin(syncPin);
|
||||
DimmableLightLinearized::begin();
|
||||
#endif
|
||||
Serial.println("Done!");
|
||||
|
||||
#if defined(RAW_VALUES)
|
||||
Serial.println(String("Number of instantiated lights: ") + DimmableLight::getLightNumber());
|
||||
#elif defined(LINEARIZED_VALUES)
|
||||
Serial.println(String("Number of instantiated lights: ") + DimmableLightLinearized::getLightNumber());
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// Select ONLY ONE between these 2 options
|
||||
#define RAW_VALUES
|
||||
//#define LINEARIZED_VALUES
|
||||
|
||||
#if defined(RAW_VALUES)
|
||||
#include <dimmable_light.h>
|
||||
#elif defined(LINEARIZED_VALUES)
|
||||
#include <dimmable_light_linearized.h>
|
||||
#endif
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
const int N_LIGHTS = 8;
|
||||
|
||||
#if defined(ESP8266)
|
||||
const int syncPin = 13;
|
||||
#elif defined(ESP32)
|
||||
const int syncPin = 23;
|
||||
#elif defined(AVR)
|
||||
const int syncPin = 2;
|
||||
#elif defined(ARDUINO_ARCH_SAMD)
|
||||
const int syncPin = 2;
|
||||
#elif (defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED))
|
||||
const int syncPin = 2;
|
||||
#endif
|
||||
|
||||
#if defined(RAW_VALUES)
|
||||
extern DimmableLight lights[];
|
||||
#elif defined(LINEARIZED_VALUES)
|
||||
extern DimmableLightLinearized lights[];
|
||||
#endif
|
||||
|
||||
extern void (*effect)();
|
||||
// The period between a call and the next one in millisecond
|
||||
extern uint16_t period;
|
||||
extern uint32_t lastCall;
|
||||
|
||||
void doEqual();
|
||||
void doEqualOnOff();
|
||||
void doDimSpecificStep();
|
||||
void doRangeLimit();
|
||||
void doNearValues();
|
||||
void doDimMixed();
|
||||
void doDimSweepEqual();
|
||||
void doOnOffSweep();
|
||||
void doInvertedDim();
|
||||
void doCircularSwipe();
|
||||
void doRandomBri();
|
||||
void doRandomBriPeephole();
|
||||
void doRandomPushExtremeValues();
|
||||
void doCircularSwipeRegular();
|
||||
|
||||
void offAllLights();
|
||||
|
||||
void initLights();
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* The main parameters to configure this sketch accordingly to your hardware setup are:
|
||||
* - syncPin, that is the pin listening to AC zero cross signal
|
||||
* - light, the pin which is connected to the thyristor
|
||||
*/
|
||||
|
||||
#include <dimmable_light_linearized.h>
|
||||
|
||||
const int syncPin = 13;
|
||||
const int thyristorPin = 14;
|
||||
|
||||
DimmableLightLinearized light(thyristorPin);
|
||||
|
||||
// Delay between a brightness changement in millisecond
|
||||
const int period = 50;
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
while (!Serial)
|
||||
;
|
||||
Serial.println();
|
||||
Serial.println("Dimmable Light for Arduino: first example");
|
||||
|
||||
Serial.print("Initializing the dimmable light class... ");
|
||||
DimmableLightLinearized::setSyncPin(syncPin);
|
||||
// VERY IMPORTANT: Call this method to start internal light routine
|
||||
DimmableLightLinearized::begin();
|
||||
Serial.println("Done!");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
for (int i = 0; i < 256; i++) {
|
||||
light.setBrightness(i);
|
||||
delay(period);
|
||||
}
|
||||
|
||||
delay(2000);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* This examples shows how to dinamically set the network frequency,
|
||||
* so your device can adapt to 50Hz or 60Hz without changing firmware.
|
||||
*
|
||||
* You just need to activate the library, then wait a while to sample
|
||||
* the actual frequency and then set the correct frequency. Since the
|
||||
* detected value may be imprecise due to noise, it is up to you
|
||||
* to implement the logic to chose the proper frequency. The frequency
|
||||
* is calculated with a moving average (by default on the last 5 values)
|
||||
* and it is continuosly updated.
|
||||
*
|
||||
* NOTE: you have to select NETWORK_FREQ_RUNTIME and MONITOR_FREQUENCY
|
||||
* #defines in thyristor.h
|
||||
*/
|
||||
#include <dimmable_light.h>
|
||||
|
||||
const int syncPin = 13;
|
||||
const int thyristorPin = 14;
|
||||
|
||||
DimmableLight light(thyristorPin);
|
||||
|
||||
// Delay between brightness increments, in milliseconds
|
||||
const int period = 50;
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
while (!Serial)
|
||||
;
|
||||
Serial.println();
|
||||
Serial.println("Dimmable Light for Arduino: setting network frequency automatically");
|
||||
|
||||
Serial.print("Initializing DimmableLight library... ");
|
||||
DimmableLight::setSyncPin(syncPin);
|
||||
// VERY IMPORTANT: Call this method to activate the library
|
||||
DimmableLight::begin();
|
||||
|
||||
// A small delay to get some samples
|
||||
delay(50);
|
||||
|
||||
float f = DimmableLight::getDetectedFrequency();
|
||||
int frequency = round(f);
|
||||
if (frequency == 50) {
|
||||
Serial.print("Setting frequency to 50Hz... ");
|
||||
DimmableLight::setFrequency(50);
|
||||
Serial.println("Done!");
|
||||
} else if (frequency == 60) {
|
||||
Serial.print("Setting frequency to 60Hz... ");
|
||||
DimmableLight::setFrequency(60);
|
||||
Serial.println("Done!");
|
||||
} else {
|
||||
Serial.println(String("Unknown frequency detected: ") + f);
|
||||
while (1)
|
||||
;
|
||||
}
|
||||
|
||||
Serial.println("Light dimming...");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
for (int i = 0; i < 256; i++) {
|
||||
light.setBrightness(i);
|
||||
delay(period);
|
||||
}
|
||||
|
||||
// Remember that the frequency is continuously updated
|
||||
Serial.println(String("Updated frequency: ") + DimmableLight::getDetectedFrequency());
|
||||
}
|
||||
14
libraries/Dimmable_Light_for_Arduino/keywords.txt
Normal file
14
libraries/Dimmable_Light_for_Arduino/keywords.txt
Normal file
@@ -0,0 +1,14 @@
|
||||
DimmableLight KEYWORD1
|
||||
DimmableLightLinearized KEYWORD1
|
||||
DimmableLightManager KEYWORD1
|
||||
getBrightness KEYWORD2
|
||||
setBrightness KEYWORD2
|
||||
begin KEYWORD2
|
||||
get KEYWORD2
|
||||
add KEYWORD2
|
||||
getCount KEYWORD2
|
||||
turnOff KEYWORD2
|
||||
turnOn KEYWORD2
|
||||
setSyncPin KEYWORD2
|
||||
getFrequency KEYWORD2
|
||||
getLightNumber KEYWORD2
|
||||
101
libraries/Dimmable_Light_for_Arduino/library.json
Normal file
101
libraries/Dimmable_Light_for_Arduino/library.json
Normal file
@@ -0,0 +1,101 @@
|
||||
{
|
||||
"name": "Dimmable Light for Arduino",
|
||||
"version": "1.6.0",
|
||||
"authors": {
|
||||
"name": "Fabiano Riccardi",
|
||||
"email": "fabiano.riccardi@outlook.com"
|
||||
},
|
||||
"description": "This library allows to easily control dimmers (also known as thyristors).",
|
||||
"keywords": [
|
||||
"dimmer",
|
||||
"triac",
|
||||
"thyristor",
|
||||
"timer",
|
||||
"light",
|
||||
"arduino-library",
|
||||
"phase-fired control"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/fabianoriccardi/dimmable-light"
|
||||
},
|
||||
"licence": "LGPL-2.1-or-later",
|
||||
"frameworks": [
|
||||
"arduino"
|
||||
],
|
||||
"platforms": [
|
||||
"espressif8266",
|
||||
"espressif32",
|
||||
"atmelavr",
|
||||
"atmelsam",
|
||||
"raspberrypi"
|
||||
],
|
||||
"dependencies": [
|
||||
{
|
||||
"owner": "mike-matera",
|
||||
"name": "ArduinoSTL",
|
||||
"version": "^1.3.3",
|
||||
"platforms": [
|
||||
"atmelavr"
|
||||
]
|
||||
}
|
||||
],
|
||||
"examples": [
|
||||
{
|
||||
"name": "1_dimmable_light",
|
||||
"base": "examples/1_dimmable_light",
|
||||
"files": [
|
||||
"1_dimmable_light.ino"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "2_dimmable_lights",
|
||||
"base": "examples/2_dimmable_lights",
|
||||
"files": [
|
||||
"2_dimmable_lights.ino"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "3_dimmable_light_5_light",
|
||||
"base": "examples/3_dimmable_light_5_light",
|
||||
"files": [
|
||||
"3_dimmable_light_5_light.ino"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "4_lights_manager",
|
||||
"base": "examples/4_lights_manager",
|
||||
"files": [
|
||||
"4_lights_manager.ino"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "5_dimmable_manager_n_lights",
|
||||
"base": "examples/5_dimmable_manager_n_lights",
|
||||
"files": [
|
||||
"5_dimmable_manager_n_lights.ino"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "6_8_lights_effects",
|
||||
"base": "examples/6_8_lights_effects",
|
||||
"files": [
|
||||
"6_8_lights_effects.ino"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "7_linearized_dimmable_light",
|
||||
"base": "examples/7_linearized_dimmable_light",
|
||||
"files": [
|
||||
"7_linearized_dimmable_light.ino"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "8_set_frequency_automatically",
|
||||
"base": "examples/8_set_frequency_automatically",
|
||||
"files": [
|
||||
"8_set_frequency_automatically.ino"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
10
libraries/Dimmable_Light_for_Arduino/library.properties
Normal file
10
libraries/Dimmable_Light_for_Arduino/library.properties
Normal file
@@ -0,0 +1,10 @@
|
||||
name=Dimmable Light for Arduino
|
||||
version=1.6.0
|
||||
author=Fabiano Riccardi <fabiano.riccardi@outlook.com>
|
||||
maintainer=Fabiano Riccardi <fabiano.riccardi@outlook.com>
|
||||
sentence=This library allows to easily control dimmers (also known as thyristors).
|
||||
paragraph=This library was born to control dimmable light bulbs, but actually dimmers are fully compatible with other AC loads like electrical heaters and motors (be aware of what you are doing!). Actually it works on ESP8266, ESP32, AVR and SAMD.
|
||||
category=Device Control
|
||||
url=https://github.com/fabianoriccardi/dimmable-light
|
||||
architectures=esp8266,esp32,avr,samd,rp2040
|
||||
depends=ArduinoSTL
|
||||
57
libraries/Dimmable_Light_for_Arduino/platformio.ini
Normal file
57
libraries/Dimmable_Light_for_Arduino/platformio.ini
Normal file
@@ -0,0 +1,57 @@
|
||||
[env]
|
||||
monitor_speed = 115200
|
||||
upload_speed = 921600
|
||||
#upload_port = COM6
|
||||
build_flags = -Wall -Wextra
|
||||
lib_deps = kroimon/SerialCommand
|
||||
|
||||
[platformio]
|
||||
# Uncomment the example to need to compile
|
||||
src_dir = examples/1_dimmable_light
|
||||
#src_dir = examples/2_dimmable_lights
|
||||
#src_dir = examples/3_dimmable_light_5_light
|
||||
#src_dir = examples/4_lights_manager
|
||||
#src_dir = examples/5_dimmable_manager_n_lights
|
||||
#src_dir = examples/6_8_lights_effects
|
||||
#src_dir = examples/7_linearized_dimmable_light
|
||||
#src_dir = examples/8_set_frequency_automatically
|
||||
lib_dir = .
|
||||
|
||||
[env:esp8266]
|
||||
platform = espressif8266@4.2.1
|
||||
board = d1_mini
|
||||
framework = arduino
|
||||
|
||||
[env:esp32]
|
||||
platform = espressif32@6.4.0
|
||||
board = lolin32
|
||||
framework = arduino
|
||||
|
||||
[env:uno]
|
||||
platform = atmelavr@4.2.0
|
||||
board = uno
|
||||
framework = arduino
|
||||
lib_deps =
|
||||
${env.lib_deps}
|
||||
mike-matera/ArduinoSTL@^1.3.3
|
||||
upload_speed = 115200
|
||||
|
||||
[env:mega2560]
|
||||
platform = atmelavr@4.2.0
|
||||
board = megaatmega2560
|
||||
framework = arduino
|
||||
lib_deps =
|
||||
${env.lib_deps}
|
||||
mike-matera/ArduinoSTL@^1.3.3
|
||||
upload_speed = 115200
|
||||
|
||||
[env:nano_33_iot]
|
||||
platform = atmelsam@8.2.0
|
||||
board = nano_33_iot
|
||||
framework = arduino
|
||||
|
||||
[env:rpipico]
|
||||
platform = https://github.com/maxgerhardt/platform-raspberrypi.git
|
||||
board = pico
|
||||
framework = arduino
|
||||
board_build.core = earlephilhower
|
||||
91
libraries/Dimmable_Light_for_Arduino/readme.md
Normal file
91
libraries/Dimmable_Light_for_Arduino/readme.md
Normal file
@@ -0,0 +1,91 @@
|
||||
# Dimmable Light for Arduino
|
||||
|
||||
[](https://www.ardu-badge.com/Dimmable%20Light%20for%20Arduino) 
|
||||
|
||||
A library to manage thyristors (aka dimmer or triac) and phase-fired control (aka phase-cutting control) in Arduino environment.
|
||||
|
||||
## Motivations
|
||||
|
||||
At the very beginning, this library was born from the curiosity to experiment the performance and capabilities of hardware timer on ESP8266 and to control old-fashioned incandescence lights.
|
||||
In the second instance, I wanted to port the original piece of software to ESP32, and so I started to conceive a flexible software architecture that better adapts to different hardware platforms. Moreover, at the time there weren't multi-platform libraries to control thyristors, so I decided to publish, extend, and maintain this library over time.
|
||||
|
||||
### About the timers
|
||||
|
||||
Actually, it was interesting (and sometime frustrating) to discover that a *simple* peripheral such as timer can heavily vary among different platforms.
|
||||
For example, the ESP8266 is equipped with 2 timers, but only one is usable by the user since the other is reserved for Wi-Fi management. This can lead immediately to a complicate development if the user application needs the timer for multi purposes. For this reason, [ESP8266TimerInterrupt](https://github.com/khoih-prog/ESP8266TimerInterrupt) was born. Moreover, that timer hasn't "advanced" capabilities such as input compare, multiple output compare channels, a bidirectional counter, and it is only 23-bit. Another example is the ESP32, that is way better than its predecessor: it has 4 64-bit timers with up and down counters, but still no input capture and just 1 output compare channel per timer. Finally, I cannot avoid mentioning the AVR ATmega's timers: they have multiple full-featured 8-bit or 16-bit timers running at lower clock frequency than modern MCUs, which may reduce the overall resolution of dimmer control or lead to more complicated ISRs to handle multiple rollovers. At least, AVR MCUs, compared to ESP8266 and ESP32, are well-supported by C header files containing complete registers' specifications.
|
||||
This brief overview gives a glimpse of the variety of properties to consider while working with timers embedded in microcontrollers, and it highlights the importance of building an abstraction layer that hides all these differences and exposes the 2 primitives needed to control thyristors: one-shot timer activation and stop counting.
|
||||
|
||||
## Features
|
||||
|
||||
1. Control multiple thyristors using a single hardware timer
|
||||
2. Compatible with multiple platforms (ESP8266/ESP32/AVR/SAMD/RP2040)
|
||||
3. Interrupt optimization (trigger interrupts only if necessary, no periodic interrupt)
|
||||
4. Control the load by 2 measurement unit: gate activation time or linearized relative power
|
||||
5. Documented parameters to finely tune the library on your hardware and requirements
|
||||
|
||||
Here the comparison against 3 similar and popular libraries:
|
||||
|
||||
| | Dimmable Light for Arduino | [RobotDynOfficial/<br>RDBDimmer](https://github.com/RobotDynOfficial/RBDDimmer) | [circuitar/Dimmer](https://github.com/circuitar/Dimmer) | [AJMansfield/<br>TriacDimmer](https://github.com/AJMansfield/TriacDimmer) |
|
||||
|----------------------------------- |--------------------------------------------- |----------------------------------------------------- |---------------------------------- |---------------------------------- |
|
||||
| Multiple dimmers | yes | yes | yes | 2 |
|
||||
| Supported frequencies | 50/60Hz | 50Hz | 50/60Hz | 50/60Hz |
|
||||
| Supported architectures | AVR, SAMD, ESP8266, ESP32, RP2040 | AVR, SAMD, ESP8266, ESP32, STM32F1, STM32F4, SAM | AVR | AVR |
|
||||
| Control *effective* delivered power | yes, dynamic calculation | no | yes, static lookup table | no |
|
||||
| Predefined effects | no | yes, automatic fade to new value | yes, swipe effect | no |
|
||||
| Optional zero-crossing mode | no | no | yes | no |
|
||||
| Time resolution | 1us (2) | 1/100 of semi-period energy | 1/100 of semi-period length | 0.5us |
|
||||
| Smart interrupt management | yes, automatically activated only if needed | no | no | no |
|
||||
| Number of interrupts per semi-period (1) | number of instantiated dimmers + 1 | 100 | 100 | 3 |
|
||||
|
||||
(1) In the worst case, with default settings\
|
||||
(2) If the hardware timer allows it, otherwise it will be lower
|
||||
|
||||
## Installation
|
||||
|
||||
The latest version of Dimmable Light for Arduino is available on Arduino Library Manager and on [PlatformIO registry](https://registry.platformio.org/libraries/fabianoriccardi/Dimmable%20Light%20for%20Arduino).
|
||||
|
||||
On AVR boards such as Arduino/Genuino Uno, you also need [ArduinoSTL](https://github.com/mike-matera/ArduinoSTL) (available on Arduino Library Manager).
|
||||
If you want to compile the 6th example (the most complete), you also need [ArduinoSerialCommand](https://github.com/kroimon/Arduino-SerialCommand) library.
|
||||
|
||||
> 📝 *for AVR core*: use AVR Core v1.8.2 or lower. This is because an incompatibility between ArduinoSTL and new versions of AVR core.
|
||||
|
||||
> 📝 *for PlatformIO users*: in `platformio.ini` file it is recommeded to add in `env` section the setting `lib_compat_mode = strict` to avoid conflicts with the default STL included in all environments (but not in Arduino-AVR core) and ArduinoSTL.
|
||||
|
||||
## Usage
|
||||
|
||||
The main APIs are accessible through DimmableLight class. Instantiate one or more DimmableLight, specifying the corresponding activation pin.
|
||||
|
||||
DimmableLight dimmer(3);
|
||||
|
||||
Set the Zero Cross pin, calling the static method `setSyncPin`:
|
||||
|
||||
DimmableLight::setSyncPin(2);
|
||||
|
||||
Then call the static method `begin`:
|
||||
|
||||
DimmableLight::begin();
|
||||
|
||||
it enables the interrupt on Zero Cross Detection that checks if any thyristor must be activated. To set the activation time, call the method `setBrightness`:
|
||||
|
||||
dimmer.setBrightness(150);
|
||||
|
||||
the given value is the relative activation time w.r.t. the semi-period length. The method accepts values in range [0; 255].
|
||||
|
||||
If you encounter flickering problem due to noise on eletrical network, you can try to enable (uncomment) `#define FILTER_INT_PERIOD` at the begin of `thyristor.cpp` file.
|
||||
|
||||
If you have strict memory constrain, you can drop the functionalities provided by `dimmable_light_manager.h/cpp` (i.e. you can delete those files).
|
||||
|
||||
For ready-to-use code look in `examples` folder. For more details check the header files and the [Wiki](https://github.com/fabianoriccardi/dimmable-light/wiki).
|
||||
|
||||
## Examples
|
||||
|
||||
Along with the library, there are 8 examples. If you are a beginner, you should start from the first one. Note that examples 3 and 5 work only for ESP8266 and ESP32 because of their dependency on Ticker library. Example 7 shows how to control linearly the energy delivered to the load instead of controlling directly the gate activation time.
|
||||
|
||||
The example 6 demonstrates various fascinating luminous effects and requires 8 dimmers, each one to control a light. [Here](https://youtu.be/DRJcCIZw_Mw) you can find a brief video showing the 9th and 11th effect. I had used [this board](https://www.ebay.it/itm/124269741187), but you can find an equivalent one.
|
||||
In these images, you can see the full hardware setting:
|
||||
|
||||

|
||||
8 incandescence bulbs.
|
||||
|
||||

|
||||
Wemos D1 mini (v2.3.0) and a board equipped with 8 dimmers.
|
||||
74
libraries/Dimmable_Light_for_Arduino/src/circular_queue.h
Normal file
74
libraries/Dimmable_Light_for_Arduino/src/circular_queue.h
Normal file
@@ -0,0 +1,74 @@
|
||||
/******************************************************************************
|
||||
* This file is part of Dimmable Light for Arduino, a library to control *
|
||||
* dimmers. *
|
||||
* *
|
||||
* Copyright (C) 2018-2023 Fabiano Riccardi *
|
||||
* *
|
||||
* Dimmable Light for Arduino is free software; you can redistribute *
|
||||
* it and/or modify it under the terms of the GNU Lesser General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2.1 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public License *
|
||||
* along with this library; if not, see <http://www.gnu.org/licenses/>. *
|
||||
******************************************************************************/
|
||||
#ifndef CIRCULAR_QUEUE_H
|
||||
#define CIRCULAR_QUEUE_H
|
||||
|
||||
/*
|
||||
* A minimal static circular queue.
|
||||
* It supports only insertion, and older values are automatically overwritten.
|
||||
*/
|
||||
template<typename T, int N> class CircularQueue {
|
||||
public:
|
||||
/**
|
||||
* Construct a new Circular Queue object filling it with zeros or
|
||||
* using the default constructor of type T.
|
||||
*/
|
||||
CircularQueue() : arr{ 0 }, index(0), n(0){};
|
||||
|
||||
/**
|
||||
* Insert an element. If full, it returns the overwritten element.
|
||||
*/
|
||||
T insert(T value) {
|
||||
T ret = arr[index];
|
||||
arr[index] = value;
|
||||
index++;
|
||||
if (index == N) { index = 0; }
|
||||
if (n < N) { n++; }
|
||||
|
||||
return ret;
|
||||
};
|
||||
|
||||
/**
|
||||
* Empty the queue.
|
||||
*/
|
||||
void reset() {
|
||||
for (int i = 0; i < N; i++) { arr[i] = 0; }
|
||||
n = 0;
|
||||
index = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the number of stored elements.
|
||||
*/
|
||||
int getCount() const {
|
||||
return n;
|
||||
};
|
||||
|
||||
private:
|
||||
T arr[N];
|
||||
|
||||
// The position for the next element to be inserted
|
||||
int index;
|
||||
|
||||
// Number of elements currently stored
|
||||
int n;
|
||||
};
|
||||
|
||||
#endif // END CIRCULAR_QUEUE_H
|
||||
22
libraries/Dimmable_Light_for_Arduino/src/dimmable_light.cpp
Normal file
22
libraries/Dimmable_Light_for_Arduino/src/dimmable_light.cpp
Normal file
@@ -0,0 +1,22 @@
|
||||
/******************************************************************************
|
||||
* This file is part of Dimmable Light for Arduino, a library to control *
|
||||
* dimmers. *
|
||||
* *
|
||||
* Copyright (C) 2018-2023 Fabiano Riccardi *
|
||||
* *
|
||||
* Dimmable Light for Arduino is free software; you can redistribute *
|
||||
* it and/or modify it under the terms of the GNU Lesser General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2.1 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public License *
|
||||
* along with this library; if not, see <http://www.gnu.org/licenses/>. *
|
||||
******************************************************************************/
|
||||
#include "dimmable_light.h"
|
||||
|
||||
uint8_t DimmableLight::nLights = 0;
|
||||
156
libraries/Dimmable_Light_for_Arduino/src/dimmable_light.h
Normal file
156
libraries/Dimmable_Light_for_Arduino/src/dimmable_light.h
Normal file
@@ -0,0 +1,156 @@
|
||||
/******************************************************************************
|
||||
* This file is part of Dimmable Light for Arduino, a library to control *
|
||||
* dimmers. *
|
||||
* *
|
||||
* Copyright (C) 2018-2023 Fabiano Riccardi *
|
||||
* *
|
||||
* Dimmable Light for Arduino is free software; you can redistribute *
|
||||
* it and/or modify it under the terms of the GNU Lesser General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2.1 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public License *
|
||||
* along with this library; if not, see <http://www.gnu.org/licenses/>. *
|
||||
******************************************************************************/
|
||||
#ifndef DIMMABLE_LIGHT_H
|
||||
#define DIMMABLE_LIGHT_H
|
||||
|
||||
#include "thyristor.h"
|
||||
#include <Arduino.h>
|
||||
|
||||
/**
|
||||
* This is the user-oriented DimmableLight class, a wrapper on Thyristor class.
|
||||
* The measurement unit is relative to the semi-period length, and it assumes values
|
||||
* in [0;255] range.
|
||||
*/
|
||||
class DimmableLight {
|
||||
public:
|
||||
DimmableLight(int pin) : thyristor(pin), brightness(0) {
|
||||
if (nLights < N) {
|
||||
nLights++;
|
||||
} else {
|
||||
Serial.println("Max lights number reached, the light is not created!");
|
||||
// return error or exception
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the brightness, 0 to turn off the lamp
|
||||
*/
|
||||
void setBrightness(uint8_t bri) {
|
||||
brightness = bri;
|
||||
#ifdef NETWORK_FREQ_FIXED_50HZ
|
||||
uint16_t newDelay = 10000 - (uint16_t)(((uint32_t)bri * 10000) / 255);
|
||||
#elif defined(NETWORK_FREQ_FIXED_60HZ)
|
||||
uint16_t newDelay = 8333 - (uint16_t)(((uint32_t)bri * 8333) / 255);
|
||||
#elif defined(NETWORK_FREQ_RUNTIME)
|
||||
uint16_t newDelay =
|
||||
Thyristor::getSemiPeriod() - (uint16_t)(((uint32_t)bri * Thyristor::getSemiPeriod()) / 255);
|
||||
#endif
|
||||
thyristor.setDelay(newDelay);
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the current brightness
|
||||
*/
|
||||
uint8_t getBrightness() const {
|
||||
return brightness;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn on the light at full power.
|
||||
*/
|
||||
void turnOn() {
|
||||
setBrightness(255);
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn off the light.
|
||||
*/
|
||||
void turnOff() {
|
||||
setBrightness(0);
|
||||
}
|
||||
|
||||
static float getFrequency() {
|
||||
return Thyristor::getFrequency();
|
||||
}
|
||||
|
||||
#ifdef NETWORK_FREQ_RUNTIME
|
||||
static void setFrequency(float frequency) {
|
||||
Thyristor::setFrequency(frequency);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef MONITOR_FREQUENCY
|
||||
static float getDetectedFrequency() {
|
||||
return Thyristor::getDetectedFrequency();
|
||||
}
|
||||
|
||||
static bool isFrequencyMonitorAlwaysOn() {
|
||||
return Thyristor::isFrequencyMonitorAlwaysOn();
|
||||
}
|
||||
|
||||
static void frequencyMonitorAlwaysOn(bool enable) {
|
||||
Thyristor::frequencyMonitorAlwaysOn(enable);
|
||||
}
|
||||
#endif
|
||||
|
||||
~DimmableLight() {
|
||||
nLights--;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup the timer and the interrupt routine.
|
||||
*/
|
||||
static void begin() {
|
||||
Thyristor::begin();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the pin dedicated to receive the AC zero cross signal.
|
||||
*/
|
||||
static void setSyncPin(uint8_t pin) {
|
||||
Thyristor::setSyncPin(pin);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the pin direction (RISING (default), FALLING, CHANGE).
|
||||
*/
|
||||
static void setSyncDir(decltype(RISING) dir) {
|
||||
Thyristor::setSyncDir(dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the pin pullup (true = INPUT_PULLUP, false = INPUT). The internal pullup resistor is not
|
||||
* available for each platform and each pin.
|
||||
*/
|
||||
static void setSyncPullup(bool pullup) {
|
||||
Thyristor::setSyncPullup(pullup);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the number of instantiated lights.
|
||||
*/
|
||||
static uint8_t getLightNumber() {
|
||||
return nLights;
|
||||
};
|
||||
|
||||
private:
|
||||
static const uint8_t N = Thyristor::N;
|
||||
static uint8_t nLights;
|
||||
|
||||
Thyristor thyristor;
|
||||
|
||||
/**
|
||||
* Store the time to wait until turn on the light
|
||||
* 0-->255. That's is 1 unit is approx 40us@50Hz.
|
||||
*/
|
||||
uint8_t brightness;
|
||||
};
|
||||
|
||||
#endif // END DIMMABLE_LIGHT_H
|
||||
@@ -0,0 +1,22 @@
|
||||
/******************************************************************************
|
||||
* This file is part of Dimmable Light for Arduino, a library to control *
|
||||
* dimmers. *
|
||||
* *
|
||||
* Copyright (C) 2018-2023 Fabiano Riccardi *
|
||||
* *
|
||||
* Dimmable Light for Arduino is free software; you can redistribute *
|
||||
* it and/or modify it under the terms of the GNU Lesser General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2.1 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public License *
|
||||
* along with this library; if not, see <http://www.gnu.org/licenses/>. *
|
||||
******************************************************************************/
|
||||
#include "dimmable_light_linearized.h"
|
||||
|
||||
uint8_t DimmableLightLinearized::nLights = 0;
|
||||
@@ -0,0 +1,169 @@
|
||||
/******************************************************************************
|
||||
* This file is part of Dimmable Light for Arduino, a library to control *
|
||||
* dimmers. *
|
||||
* *
|
||||
* Copyright (C) 2018-2023 Fabiano Riccardi *
|
||||
* *
|
||||
* Dimmable Light for Arduino is free software; you can redistribute *
|
||||
* it and/or modify it under the terms of the GNU Lesser General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2.1 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public License *
|
||||
* along with this library; if not, see <http://www.gnu.org/licenses/>. *
|
||||
******************************************************************************/
|
||||
#ifndef DIMMABLE_LIGHT_LINEARIZED_H
|
||||
#define DIMMABLE_LIGHT_LINEARIZED_H
|
||||
|
||||
#include "thyristor.h"
|
||||
#include <Arduino.h>
|
||||
|
||||
/**
|
||||
* This is the user-oriented DimmableLightLinearized class,
|
||||
* a wrapper on Thyristor class. It differs from DimmableLight
|
||||
* "brightness" meaning: here the brightness it mapped linearly to
|
||||
* power delivered to your devices, in DimmableLight it is linearly mapped
|
||||
* to time point when thyristor is triggered.
|
||||
* The computation induced by this class may affect the performance of your MCU.
|
||||
*/
|
||||
class DimmableLightLinearized {
|
||||
public:
|
||||
DimmableLightLinearized(int pin) : thyristor(pin), brightness(0) {
|
||||
if (nLights < N) {
|
||||
nLights++;
|
||||
} else {
|
||||
Serial.println("Max lights number reached, the light is not created!");
|
||||
// return error or exception
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the brightness, 0 to turn off the lamp
|
||||
*/
|
||||
void setBrightness(uint8_t bri) {
|
||||
#ifdef NETWORK_FREQ_FIXED_50HZ
|
||||
double tempBrightness = -1.5034e-10 * pow(bri, 5) + 9.5843e-08 * pow(bri, 4)
|
||||
- 2.2953e-05 * pow(bri, 3) + 0.0025471 * pow(bri, 2) - 0.14965 * bri + 9.9846;
|
||||
#elif defined(NETWORK_FREQ_FIXED_60HZ)
|
||||
double tempBrightness = -1.2528e-10 * pow(bri, 5) + 7.9866e-08 * pow(bri, 4)
|
||||
- 1.9126e-05 * pow(bri, 3) + 0.0021225 * pow(bri, 2) - 0.12471 * bri + 8.3201;
|
||||
#elif defined(NETWORK_FREQ_RUNTIME)
|
||||
double tempBrightness;
|
||||
if (Thyristor::getFrequency() == 50) {
|
||||
tempBrightness = -1.5034e-10 * pow(bri, 5) + 9.5843e-08 * pow(bri, 4)
|
||||
- 2.2953e-05 * pow(bri, 3) + 0.0025471 * pow(bri, 2) - 0.14965 * bri + 9.9846;
|
||||
} else if (Thyristor::getFrequency() == 60) {
|
||||
tempBrightness = -1.2528e-10 * pow(bri, 5) + 7.9866e-08 * pow(bri, 4)
|
||||
- 1.9126e-05 * pow(bri, 3) + 0.0021225 * pow(bri, 2) - 0.12471 * bri + 8.3201;
|
||||
} else {
|
||||
// Only on and off
|
||||
if (bri > 0) {
|
||||
thyristor.turnOn();
|
||||
} else {
|
||||
thyristor.turnOff();
|
||||
}
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
tempBrightness *= 1000;
|
||||
|
||||
thyristor.setDelay(tempBrightness);
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the current brightness.
|
||||
*/
|
||||
uint8_t getBrightness() const {
|
||||
return brightness;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn off the light.
|
||||
*/
|
||||
void turnOff() {
|
||||
setBrightness(0);
|
||||
}
|
||||
|
||||
static float getFrequency() {
|
||||
return Thyristor::getFrequency();
|
||||
}
|
||||
|
||||
#ifdef NETWORK_FREQ_RUNTIME
|
||||
static void setFrequency(float frequency) {
|
||||
Thyristor::setFrequency(frequency);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef MONITOR_FREQUENCY
|
||||
static float getDetectedFrequency() {
|
||||
return Thyristor::getDetectedFrequency();
|
||||
}
|
||||
|
||||
static bool isFrequencyMonitorAlwaysOn() {
|
||||
return Thyristor::isFrequencyMonitorAlwaysOn();
|
||||
}
|
||||
|
||||
static void frequencyMonitorAlwaysOn(bool enable) {
|
||||
Thyristor::frequencyMonitorAlwaysOn(enable);
|
||||
}
|
||||
#endif
|
||||
|
||||
~DimmableLightLinearized() {
|
||||
nLights--;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup the timer and the interrupt routine.
|
||||
*/
|
||||
static void begin() {
|
||||
Thyristor::begin();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the pin dedicated to receive the AC zero cross signal.
|
||||
*/
|
||||
static void setSyncPin(uint8_t pin) {
|
||||
Thyristor::setSyncPin(pin);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the pin direction (RISING (default), FALLING, CHANGE).
|
||||
*/
|
||||
static void setSyncDir(decltype(RISING) dir) {
|
||||
Thyristor::setSyncDir(dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the pin pullup (true = INPUT_PULLUP, false = INPUT). The internal pullup resistor is not
|
||||
* available for each platform and each pin.
|
||||
*/
|
||||
static void setSyncPullup(bool pullup) {
|
||||
Thyristor::setSyncPullup(pullup);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the number of instantiated lights.
|
||||
*/
|
||||
static uint8_t getLightNumber() {
|
||||
return nLights;
|
||||
};
|
||||
|
||||
private:
|
||||
static const uint8_t N = 8;
|
||||
static uint8_t nLights;
|
||||
|
||||
Thyristor thyristor;
|
||||
|
||||
/**
|
||||
* Store the time to wait until turn on the light
|
||||
* 0-->255. That's is 1 unit is approx 40us@50Hz.
|
||||
*/
|
||||
uint8_t brightness;
|
||||
};
|
||||
|
||||
#endif // END DIMMABLE_LIGHT_LINEARIZED_H
|
||||
@@ -0,0 +1,64 @@
|
||||
/******************************************************************************
|
||||
* This file is part of Dimmable Light for Arduino, a library to control *
|
||||
* dimmers. *
|
||||
* *
|
||||
* Copyright (C) 2018-2023 Fabiano Riccardi *
|
||||
* *
|
||||
* Dimmable Light for Arduino is free software; you can redistribute *
|
||||
* it and/or modify it under the terms of the GNU Lesser General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2.1 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public License *
|
||||
* along with this library; if not, see <http://www.gnu.org/licenses/>. *
|
||||
******************************************************************************/
|
||||
#include "dimmable_light_manager.h"
|
||||
|
||||
bool DimmableLightManager::add(String lightName, uint8_t pin) {
|
||||
const char* temp = lightName.c_str();
|
||||
#if defined(ESP8266) || defined(ESP32) || defined(ARDUINO_ARCH_SAMD) || defined(ARDUINO_ARCH_RP2040)
|
||||
std::unordered_map<std::string, DimmableLight*>::const_iterator it = dla.find(temp);
|
||||
#elif defined(AVR)
|
||||
std::map<std::string, DimmableLight*>::const_iterator it = dla.find(temp);
|
||||
#endif
|
||||
if (it == dla.end()) {
|
||||
DimmableLight* pDimLight = new DimmableLight(pin);
|
||||
dla.insert({ lightName.c_str(), pDimLight });
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
DimmableLight* DimmableLightManager::get(String lightName) {
|
||||
const char* temp = lightName.c_str();
|
||||
#if defined(ESP8266) || defined(ESP32) || defined(ARDUINO_ARCH_SAMD) || defined(ARDUINO_ARCH_RP2040)
|
||||
std::unordered_map<std::string, DimmableLight*>::const_iterator it = dla.find(temp);
|
||||
#elif defined(AVR)
|
||||
std::map<std::string, DimmableLight*>::const_iterator it = dla.find(temp);
|
||||
#endif
|
||||
if (it != dla.end()) {
|
||||
return (it->second);
|
||||
} else {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
std::pair<String, DimmableLight*> DimmableLightManager::get() {
|
||||
#if defined(ESP8266) || defined(ESP32) || defined(ARDUINO_ARCH_SAMD) || defined(ARDUINO_ARCH_RP2040)
|
||||
static std::unordered_map<std::string, DimmableLight*>::const_iterator it = dla.begin();
|
||||
#elif defined(AVR)
|
||||
static std::map<std::string, DimmableLight*>::const_iterator it = dla.begin();
|
||||
#endif
|
||||
String name = it->first.c_str();
|
||||
std::pair<String, DimmableLight*> res(name, it->second);
|
||||
|
||||
it++;
|
||||
if (it == dla.end()) { it = dla.begin(); }
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/******************************************************************************
|
||||
* This file is part of Dimmable Light for Arduino, a library to control *
|
||||
* dimmers. *
|
||||
* *
|
||||
* Copyright (C) 2018-2023 Fabiano Riccardi *
|
||||
* *
|
||||
* Dimmable Light for Arduino is free software; you can redistribute *
|
||||
* it and/or modify it under the terms of the GNU Lesser General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2.1 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public License *
|
||||
* along with this library; if not, see <http://www.gnu.org/licenses/>. *
|
||||
******************************************************************************/
|
||||
#ifndef DIMMABLE_LIGHT_MANAGER_H
|
||||
#define DIMMABLE_LIGHT_MANAGER_H
|
||||
|
||||
#include "dimmable_light.h"
|
||||
|
||||
#if defined(ESP8266) || defined(ESP32) || defined(ARDUINO_ARCH_SAMD) || defined(ARDUINO_ARCH_RP2040)
|
||||
// Unfortunately Arduino defines max/min macros, those create conflicts with the one
|
||||
// defined by C++/STL environment
|
||||
#undef max
|
||||
#undef min
|
||||
#include <unordered_map>
|
||||
#elif defined(AVR)
|
||||
#include <ArduinoSTL.h>
|
||||
#include <map>
|
||||
#endif
|
||||
|
||||
#include <string>
|
||||
|
||||
/**
|
||||
* Class to store the mapping between a DimmableLight object and
|
||||
* a (friendly) name. This could be useful when developing APIs.
|
||||
*/
|
||||
class DimmableLightManager {
|
||||
public:
|
||||
/**
|
||||
* Create a new light with a given name
|
||||
*/
|
||||
bool add(String lightName, uint8_t pin);
|
||||
|
||||
/**
|
||||
* Get a light with a specific name, if any
|
||||
*/
|
||||
DimmableLight* get(String lightName);
|
||||
|
||||
/**
|
||||
* Get a light from from the contaniner.
|
||||
*
|
||||
* This method is "circular", that means once you get the last element
|
||||
* the nect call return the first one.
|
||||
*/
|
||||
std::pair<String, DimmableLight*> get();
|
||||
|
||||
int getCount() {
|
||||
return dla.size();
|
||||
}
|
||||
|
||||
static void begin() {
|
||||
DimmableLight::begin();
|
||||
}
|
||||
|
||||
private:
|
||||
#if defined(ESP8266) || defined(ESP32) || defined(ARDUINO_ARCH_SAMD) || defined(ARDUINO_ARCH_RP2040)
|
||||
std::unordered_map<std::string, DimmableLight*> dla;
|
||||
#elif defined(AVR)
|
||||
std::map<std::string, DimmableLight*> dla;
|
||||
#endif
|
||||
};
|
||||
|
||||
#endif
|
||||
179
libraries/Dimmable_Light_for_Arduino/src/hw_timer_avr.cpp
Normal file
179
libraries/Dimmable_Light_for_Arduino/src/hw_timer_avr.cpp
Normal file
@@ -0,0 +1,179 @@
|
||||
/******************************************************************************
|
||||
* This file is part of Dimmable Light for Arduino, a library to control *
|
||||
* dimmers. *
|
||||
* *
|
||||
* Copyright (C) 2018-2023 Fabiano Riccardi *
|
||||
* *
|
||||
* Dimmable Light for Arduino is free software; you can redistribute *
|
||||
* it and/or modify it under the terms of the GNU Lesser General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2.1 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public License *
|
||||
* along with this library; if not, see <http://www.gnu.org/licenses/>. *
|
||||
******************************************************************************/
|
||||
#ifdef AVR
|
||||
|
||||
#include "hw_timer_avr.h"
|
||||
#include <util/atomic.h>
|
||||
#include <Arduino.h>
|
||||
|
||||
/**
|
||||
* This parameter controls the timer used by this library. Timer0 is used by Arduino core, so you
|
||||
* shouldn't use it. The remaining timers are 8-bits or 16-bits. From my experience with
|
||||
* incandescence bulbs, I have observed sharp steps in brightness when using 8-bits timers, so I
|
||||
* decided to set as default the first available 16-bit timer: the *1*.
|
||||
*
|
||||
* Free timers ID:
|
||||
* - [1;2] on Arduino Uno (ATmega328P)
|
||||
* - [1;5] on Arduino Mega (ATmega2560)
|
||||
*/
|
||||
#define TIMER_ID 1
|
||||
|
||||
#if TIMER_ID == 0 || TIMER_ID == 2
|
||||
#define N_BIT_TIMER 8
|
||||
#else
|
||||
#define N_BIT_TIMER 16
|
||||
#endif
|
||||
|
||||
// Some helpful macros to support different timers
|
||||
#define _TCCRxA(X) TCCR##X##A
|
||||
#define TCCRxA(X) _TCCRxA(X)
|
||||
#define _TCCRxB(X) TCCR##X##B
|
||||
#define TCCRxB(X) _TCCRxB(X)
|
||||
#define _TIMSKx(X) TIMSK##X
|
||||
#define TIMSKx(X) _TIMSKx(X)
|
||||
#define _OCIExA(X) OCIE##X##A
|
||||
#define OCIExA(X) _OCIExA(X)
|
||||
#define _TCNTxL(X) TCNT##X##L
|
||||
#define TCNTxL(X) _TCNTxL(X)
|
||||
#define _TCNTxH(X) TCNT##X##H
|
||||
#define TCNTxH(X) _TCNTxH(X)
|
||||
#define _TCNTx(X) TCNT##X
|
||||
#define TCNTx(X) _TCNTx(X)
|
||||
#define _OCRxAH(X) OCR##X##AH
|
||||
#define OCRxAH(X) _OCRxAH(X)
|
||||
#define _OCRxAL(X) OCR##X##AL
|
||||
#define OCRxAL(X) _OCRxAL(X)
|
||||
#define _OCRxA(X) OCR##X##A
|
||||
#define OCRxA(X) _OCRxA(X)
|
||||
|
||||
#define _TIMER_COMPA_VECTOR(X) TIMER##X##_COMPA_vect
|
||||
#define TIMER_COMPA_VECTOR(X) _TIMER_COMPA_VECTOR(X)
|
||||
|
||||
static void (*timer_callback)() = nullptr;
|
||||
|
||||
ISR(TIMER_COMPA_VECTOR(TIMER_ID)) {
|
||||
// Disable interrupt of Output Compare A
|
||||
TIMSKx(TIMER_ID) &= 0b11111101;
|
||||
|
||||
if (timer_callback != nullptr) { timer_callback(); }
|
||||
}
|
||||
|
||||
uint16_t microsecond2Tick(uint16_t micro) {
|
||||
// a frequency value to match the conversion in MICROSECONDS
|
||||
static const uint32_t freq = F_CPU / 1000000;
|
||||
#if N_BIT_TIMER == 8
|
||||
static const uint16_t prescaler = 1024;
|
||||
#elif N_BIT_TIMER == 16
|
||||
static const uint16_t prescaler = 8;
|
||||
#endif
|
||||
static_assert((((uint32_t)1 << N_BIT_TIMER) - 1) / ((float)F_CPU / prescaler) * 1000000 > 10000,
|
||||
"the timer configuration has to allows to store a time value greater than 10000 "
|
||||
"(microseconds)");
|
||||
static const uint16_t shifterValue = F_CPU / prescaler < 1000000 ? prescaler / freq : freq / prescaler;
|
||||
|
||||
if (micro >= 32768) { return 0; }
|
||||
|
||||
// Optimized integer division(with rounding) and multiplication.
|
||||
uint16_t ticks;
|
||||
if (F_CPU / prescaler < 1000000) {
|
||||
ticks = micro / (shifterValue / 2);
|
||||
if (ticks & 0x0001) {
|
||||
// it must be ceiled
|
||||
return (ticks >> 1) + 1;
|
||||
} else {
|
||||
// it must be floored
|
||||
return ticks >> 1;
|
||||
}
|
||||
} else if (F_CPU / prescaler > 1000000) {
|
||||
return micro * shifterValue;
|
||||
} else {
|
||||
return micro;
|
||||
}
|
||||
}
|
||||
|
||||
void timerBegin() {
|
||||
// clean control registers TCCRxA and TCC2B registers
|
||||
TCCRxA(TIMER_ID) = 0;
|
||||
// Set CTC mode
|
||||
TCCRxB(TIMER_ID) = 0x08;
|
||||
|
||||
// Reset the counter
|
||||
// From the AVR datasheet: "To do a 16-bit write, the high byte must be written
|
||||
// before the low byte. For a 16-bit read, the low byte must be read
|
||||
// before the high byte".
|
||||
#if N_BIT_TIMER == 8
|
||||
TCNTx(TIMER_ID) = 0;
|
||||
#elif N_BIT_TIMER == 16
|
||||
TCNTxH(TIMER_ID) = 0;
|
||||
TCNTxL(TIMER_ID) = 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
void timerSetCallback(void (*f)()) {
|
||||
timer_callback = f;
|
||||
}
|
||||
|
||||
void timerStartAndTrigger(uint16_t tick) {
|
||||
timerStop();
|
||||
|
||||
#if N_BIT_TIMER == 8
|
||||
TCNTx(TIMER_ID) = 0;
|
||||
#elif N_BIT_TIMER == 16
|
||||
TCNTxH(TIMER_ID) = 0;
|
||||
TCNTxL(TIMER_ID) = 0;
|
||||
#endif
|
||||
|
||||
tick--;
|
||||
#if N_BIT_TIMER == 8
|
||||
OCRxA(TIMER_ID) = tick;
|
||||
#elif N_BIT_TIMER == 16
|
||||
OCRxAH(TIMER_ID) = tick >> 8;
|
||||
OCRxAL(TIMER_ID) = tick;
|
||||
#endif
|
||||
|
||||
#if N_BIT_TIMER == 8
|
||||
// 0x07: start counter with prescaler 1024
|
||||
TCCRxB(TIMER_ID) = 0x07;
|
||||
#elif N_BIT_TIMER == 16
|
||||
// 0x02: start counter with prescaler 8
|
||||
TCCRxB(TIMER_ID) |= 0x02;
|
||||
#endif
|
||||
|
||||
// enable interrupt of Output Compare A
|
||||
TIMSKx(TIMER_ID) = 1 << OCIExA(TIMER_ID);
|
||||
}
|
||||
|
||||
void timerSetAlarm(uint16_t tick) {
|
||||
#if N_BIT_TIMER == 8
|
||||
OCRxA(TIMER_ID) = tick;
|
||||
#elif N_BIT_TIMER == 16
|
||||
OCRxAH(TIMER_ID) = tick >> 8;
|
||||
OCRxAL(TIMER_ID) = tick;
|
||||
#endif
|
||||
|
||||
// enable interrupt of Output Compare A
|
||||
TIMSKx(TIMER_ID) = 1 << OCIExA(TIMER_ID);
|
||||
}
|
||||
|
||||
void timerStop() {
|
||||
TCCRxB(TIMER_ID) &= 0b11111000;
|
||||
}
|
||||
|
||||
#endif // END AVR
|
||||
64
libraries/Dimmable_Light_for_Arduino/src/hw_timer_avr.h
Normal file
64
libraries/Dimmable_Light_for_Arduino/src/hw_timer_avr.h
Normal file
@@ -0,0 +1,64 @@
|
||||
/******************************************************************************
|
||||
* This file is part of Dimmable Light for Arduino, a library to control *
|
||||
* dimmers. *
|
||||
* *
|
||||
* Copyright (C) 2018-2023 Fabiano Riccardi *
|
||||
* *
|
||||
* Dimmable Light for Arduino is free software; you can redistribute *
|
||||
* it and/or modify it under the terms of the GNU Lesser General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2.1 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public License *
|
||||
* along with this library; if not, see <http://www.gnu.org/licenses/>. *
|
||||
******************************************************************************/
|
||||
|
||||
/***********************************************************************************
|
||||
* Here there is specific AVR code. AVR is usually programmed at very low level
|
||||
* than respect ESP8266/ESP32, so this file is needed to provide a minimalistic
|
||||
* "HAL" to simplify timer usage.
|
||||
***********************************************************************************/
|
||||
#ifdef AVR
|
||||
|
||||
#ifndef HW_TIMER_ARDUINO_H
|
||||
#define HW_TIMER_ARDUINO_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
/**
|
||||
* convert microsecond to tick, max micro is 32767, otherwize it returns 0.
|
||||
*/
|
||||
uint16_t microsecond2Tick(uint16_t micro);
|
||||
|
||||
/**
|
||||
* Configure the timer to be started by timerStart()
|
||||
*/
|
||||
void timerBegin();
|
||||
|
||||
/**
|
||||
* Set callback function on timer triggers
|
||||
*/
|
||||
void timerSetCallback(void (*f)());
|
||||
|
||||
/**
|
||||
* Let's start the timer: it triggers after x ticks,
|
||||
* then it stops.
|
||||
* tick length depends on MCU clock and prescaler, please use
|
||||
* microsecond2Tick(..) to feed timerStart(..).
|
||||
*
|
||||
* NOTE: 0 or 1 values are not accepted
|
||||
*/
|
||||
void timerStartAndTrigger(uint16_t tick);
|
||||
|
||||
void timerSetAlarm(uint16_t tick);
|
||||
|
||||
void timerStop();
|
||||
|
||||
#endif // HW_TIMER_ARDUINO_H
|
||||
|
||||
#endif // END AVR
|
||||
58
libraries/Dimmable_Light_for_Arduino/src/hw_timer_esp32.cpp
Normal file
58
libraries/Dimmable_Light_for_Arduino/src/hw_timer_esp32.cpp
Normal file
@@ -0,0 +1,58 @@
|
||||
/******************************************************************************
|
||||
* This file is part of Dimmable Light for Arduino, a library to control *
|
||||
* dimmers. *
|
||||
* *
|
||||
* Copyright (C) 2018-2023 Fabiano Riccardi *
|
||||
* *
|
||||
* Dimmable Light for Arduino is free software; you can redistribute *
|
||||
* it and/or modify it under the terms of the GNU Lesser General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2.1 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public License *
|
||||
* along with this library; if not, see <http://www.gnu.org/licenses/>. *
|
||||
******************************************************************************/
|
||||
#ifdef ESP32
|
||||
|
||||
#include "hw_timer_esp32.h"
|
||||
|
||||
const static int TIMER_ID = 0;
|
||||
|
||||
static hw_timer_t* timer = nullptr;
|
||||
|
||||
void timerInit(void (*callback)()) {
|
||||
// Use 1st timer of 4 (counted from zero).
|
||||
// Set 80 divider for prescaler (see ESP32 Technical Reference Manual for more
|
||||
// info), count up. The counter starts to increase its value.
|
||||
timer = timerBegin(TIMER_ID, 80, true);
|
||||
timerStop(timer);
|
||||
timerWrite(timer, 0);
|
||||
|
||||
timerAttachInterrupt(timer, callback, false);
|
||||
}
|
||||
|
||||
void ARDUINO_ISR_ATTR startTimerAndTrigger(uint32_t delay) {
|
||||
timerWrite(timer, 0);
|
||||
timerAlarmWrite(timer, delay, false);
|
||||
timerAlarmEnable(timer);
|
||||
timerStart(timer);
|
||||
}
|
||||
|
||||
void ARDUINO_ISR_ATTR setAlarm(uint32_t delay) {
|
||||
timerAlarmWrite(timer, delay, false);
|
||||
|
||||
// On core v2.0.0-2.0.1, the timer alarm is automatically disabled after triggering,
|
||||
// so re-enable the alarm
|
||||
timerAlarmEnable(timer);
|
||||
}
|
||||
|
||||
void ARDUINO_ISR_ATTR stopTimer() {
|
||||
timerStop(timer);
|
||||
}
|
||||
|
||||
#endif // END ESP32
|
||||
38
libraries/Dimmable_Light_for_Arduino/src/hw_timer_esp32.h
Normal file
38
libraries/Dimmable_Light_for_Arduino/src/hw_timer_esp32.h
Normal file
@@ -0,0 +1,38 @@
|
||||
/******************************************************************************
|
||||
* This file is part of Dimmable Light for Arduino, a library to control *
|
||||
* dimmers. *
|
||||
* *
|
||||
* Copyright (C) 2018-2023 Fabiano Riccardi *
|
||||
* *
|
||||
* Dimmable Light for Arduino is free software; you can redistribute *
|
||||
* it and/or modify it under the terms of the GNU Lesser General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2.1 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public License *
|
||||
* along with this library; if not, see <http://www.gnu.org/licenses/>. *
|
||||
******************************************************************************/
|
||||
#ifndef HW_TIMER_ESP32_H
|
||||
#define HW_TIMER_ESP32_H
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
// This workaround is necessary to support compilation on ESP32-Arduino v1.0.x
|
||||
#ifndef ARDUINO_ISR_ATTR
|
||||
#define ARDUINO_ISR_ATTR
|
||||
#endif
|
||||
|
||||
void timerInit(void (*callback)());
|
||||
|
||||
void startTimerAndTrigger(uint32_t delay);
|
||||
|
||||
void setAlarm(uint32_t delay);
|
||||
|
||||
void stopTimer();
|
||||
|
||||
#endif // END HW_TIMER_ESP32_H
|
||||
121
libraries/Dimmable_Light_for_Arduino/src/hw_timer_esp8266.c
Normal file
121
libraries/Dimmable_Light_for_Arduino/src/hw_timer_esp8266.c
Normal file
@@ -0,0 +1,121 @@
|
||||
/******************************************************************************
|
||||
* Copyright 2013-2014 Espressif Systems (Wuxi)
|
||||
*
|
||||
* FileName: hw_timer.c
|
||||
*
|
||||
* Description: hw_timer driver
|
||||
*
|
||||
* Modification history:
|
||||
* 2014/5/1, v1.0 create this file.
|
||||
*******************************************************************************/
|
||||
#ifdef ESP8266
|
||||
//#include "c-types.h"
|
||||
typedef __SIZE_TYPE__ size_t;
|
||||
#include "ets_sys.h"
|
||||
#include "os_type.h"
|
||||
#include "osapi.h"
|
||||
|
||||
#include "hw_timer_esp8266.h"
|
||||
|
||||
|
||||
/******************************************************************************
|
||||
* FunctionName : hw_timer_arm
|
||||
* Description : set a trigger timer delay for this timer.
|
||||
* Parameters : uint32 val :
|
||||
in autoload mode
|
||||
50 ~ 0x7fffff; for FRC1 source.
|
||||
100 ~ 0x7fffff; for NMI source.
|
||||
in non autoload mode:
|
||||
10 ~ 0x7fffff;
|
||||
* Returns : NONE
|
||||
*******************************************************************************/
|
||||
void HW_TIMER_IRAM_ATTR hw_timer_arm(u32 val)
|
||||
{
|
||||
HW_TIMER_REG_WRITE(FRC1_LOAD_ADDRESS, US_TO_RTC_TIMER_TICKS(val));
|
||||
}
|
||||
|
||||
static void (* user_hw_timer_cb)(void) = NULL;
|
||||
/******************************************************************************
|
||||
* FunctionName : hw_timer_set_func
|
||||
* Description : set the func, when trigger timer is up.
|
||||
* Parameters : void (* user_hw_timer_cb_set)(void):
|
||||
timer callback function,
|
||||
* Returns : NONE
|
||||
*******************************************************************************/
|
||||
void HW_TIMER_IRAM_ATTR hw_timer_set_func(void (* user_hw_timer_cb_set)(void))
|
||||
{
|
||||
user_hw_timer_cb = user_hw_timer_cb_set;
|
||||
}
|
||||
|
||||
static HW_TIMER_IRAM_ATTR void hw_timer_isr_cb(void)
|
||||
{
|
||||
if (user_hw_timer_cb != NULL) {
|
||||
(*(user_hw_timer_cb))();
|
||||
}
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* FunctionName : hw_timer_init
|
||||
* Description : initilize the hardware isr timer
|
||||
* Parameters :
|
||||
FRC1_TIMER_SOURCE_TYPE source_type:
|
||||
FRC1_SOURCE, timer use frc1 isr as isr source.
|
||||
NMI_SOURCE, timer use nmi isr as isr source.
|
||||
u8 req:
|
||||
0, not autoload,
|
||||
1, autoload mode,
|
||||
* Returns : NONE
|
||||
*******************************************************************************/
|
||||
void HW_TIMER_IRAM_ATTR hw_timer_init(FRC1_TIMER_SOURCE_TYPE source_type, u8 req)
|
||||
{
|
||||
if (req == 1) {
|
||||
HW_TIMER_REG_WRITE(FRC1_CTRL_ADDRESS,
|
||||
FRC1_AUTO_LOAD | DIVDED_BY_16 | FRC1_ENABLE_TIMER | TM_EDGE_INT);
|
||||
} else {
|
||||
HW_TIMER_REG_WRITE(FRC1_CTRL_ADDRESS,
|
||||
DIVDED_BY_16 | FRC1_ENABLE_TIMER | TM_EDGE_INT);
|
||||
}
|
||||
|
||||
if (source_type == NMI_SOURCE) {
|
||||
ETS_FRC_TIMER1_NMI_INTR_ATTACH(hw_timer_isr_cb);
|
||||
} else {
|
||||
ETS_FRC_TIMER1_INTR_ATTACH(hw_timer_isr_cb, NULL);
|
||||
}
|
||||
|
||||
TM1_EDGE_INT_ENABLE();
|
||||
ETS_FRC1_INTR_ENABLE();
|
||||
}
|
||||
|
||||
//-------------------------------Test Code Below--------------------------------------
|
||||
#if 0
|
||||
void hw_test_timer_cb(void)
|
||||
{
|
||||
static uint16 j = 0;
|
||||
j++;
|
||||
|
||||
if ((WDEV_NOW() - tick_now2) >= 1000000) {
|
||||
static u32 idx = 1;
|
||||
tick_now2 = WDEV_NOW();
|
||||
os_printf("b%u:%d\n", idx++, j);
|
||||
j = 0;
|
||||
}
|
||||
|
||||
//hw_timer_arm(50);
|
||||
}
|
||||
|
||||
void ICACHE_FLASH_ATTR user_init(void)
|
||||
{
|
||||
hw_timer_init(FRC1_SOURCE, 1);
|
||||
hw_timer_set_func(hw_test_timer_cb);
|
||||
hw_timer_arm(100);
|
||||
}
|
||||
#endif
|
||||
/*
|
||||
NOTE:
|
||||
1 if use nmi source, for autoload timer , the timer setting val can't be less than 100.
|
||||
2 if use nmi source, this timer has highest priority, can interrupt other isr.
|
||||
3 if use frc1 source, this timer can't interrupt other isr.
|
||||
|
||||
*/
|
||||
|
||||
#endif // END ESP8266
|
||||
64
libraries/Dimmable_Light_for_Arduino/src/hw_timer_esp8266.h
Normal file
64
libraries/Dimmable_Light_for_Arduino/src/hw_timer_esp8266.h
Normal file
@@ -0,0 +1,64 @@
|
||||
#ifdef ESP8266
|
||||
|
||||
#ifndef HW_TIMER_H
|
||||
#define HW_TIMER_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define US_TO_RTC_TIMER_TICKS(t) \
|
||||
((t) ? \
|
||||
(((t) > 0x35A) ? \
|
||||
(((t)>>2) * ((APB_CLK_FREQ>>4)/250000) + ((t)&0x3) * ((APB_CLK_FREQ>>4)/1000000)) : \
|
||||
(((t) *(APB_CLK_FREQ>>4)) / 1000000)) : \
|
||||
0)
|
||||
|
||||
#define FRC1_ENABLE_TIMER BIT7
|
||||
#define FRC1_AUTO_LOAD BIT6
|
||||
|
||||
#ifdef IRAM_ATTR
|
||||
#define HW_TIMER_IRAM_ATTR IRAM_ATTR
|
||||
#else
|
||||
#define HW_TIMER_IRAM_ATTR ICACHE_RAM_ATTR
|
||||
#endif
|
||||
|
||||
#ifdef TIMER_REG_WRITE
|
||||
#define HW_TIMER_REG_WRITE TIMER_REG_WRITE
|
||||
#else
|
||||
#define HW_TIMER_REG_WRITE RTC_REG_WRITE
|
||||
#endif
|
||||
|
||||
//TIMER PREDIVED MODE
|
||||
typedef enum {
|
||||
DIVDED_BY_1 = 0, //timer clock
|
||||
DIVDED_BY_16 = 4, //divided by 16
|
||||
DIVDED_BY_256 = 8, //divided by 256
|
||||
} TIMER_PREDIVED_MODE;
|
||||
|
||||
typedef enum { //timer interrupt mode
|
||||
TM_LEVEL_INT = 1, // level interrupt
|
||||
TM_EDGE_INT = 0, //edge interrupt
|
||||
} TIMER_INT_MODE;
|
||||
|
||||
typedef enum {
|
||||
FRC1_SOURCE = 0,
|
||||
NMI_SOURCE = 1,
|
||||
} FRC1_TIMER_SOURCE_TYPE;
|
||||
|
||||
|
||||
void hw_timer_arm(u32 val);
|
||||
void hw_timer_set_func(void (* user_hw_timer_cb_set)(void));
|
||||
void hw_timer_init(FRC1_TIMER_SOURCE_TYPE source_type, u8 req);
|
||||
//void ICACHE_RAM_ATTR blink_gpio(void);
|
||||
//volatile bool state;
|
||||
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* HW_TIMER_H */
|
||||
|
||||
#endif // END ESP8266
|
||||
54
libraries/Dimmable_Light_for_Arduino/src/hw_timer_pico.cpp
Normal file
54
libraries/Dimmable_Light_for_Arduino/src/hw_timer_pico.cpp
Normal file
@@ -0,0 +1,54 @@
|
||||
/******************************************************************************
|
||||
* This file is part of Dimmable Light for Arduino, a library to control *
|
||||
* dimmers. *
|
||||
* *
|
||||
* Copyright (C) 2018-2023 Fabiano Riccardi *
|
||||
* *
|
||||
* Dimmable Light for Arduino is free software; you can redistribute *
|
||||
* it and/or modify it under the terms of the GNU Lesser General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2.1 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public License *
|
||||
* along with this library; if not, see <http://www.gnu.org/licenses/>. *
|
||||
******************************************************************************/
|
||||
|
||||
#if defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED)
|
||||
|
||||
#include "hw_timer_pico.h"
|
||||
#include <Arduino.h>
|
||||
|
||||
static void (*timer_callback)() = nullptr;
|
||||
static alarm_id_t alarm_id;
|
||||
static alarm_pool_t *alarm_pool;
|
||||
|
||||
void timerBegin() {
|
||||
alarm_pool = alarm_pool_get_default();
|
||||
}
|
||||
|
||||
void timerSetCallback(void (*callback)()) {
|
||||
timer_callback = callback;
|
||||
}
|
||||
|
||||
void timerStart(uint64_t t) {
|
||||
if (alarm_id) {
|
||||
cancel_alarm(alarm_id);
|
||||
alarm_id = 0;
|
||||
}
|
||||
|
||||
alarm_id = alarm_pool_add_alarm_in_us(
|
||||
alarm_pool, t,
|
||||
[](alarm_id_t, void *) -> int64_t {
|
||||
if (timer_callback != nullptr) { timer_callback(); }
|
||||
alarm_id = 0;
|
||||
return 0; // Do not reschedule alarm
|
||||
},
|
||||
NULL, true);
|
||||
}
|
||||
|
||||
#endif // END ARDUINO_ARCH_RP2040
|
||||
45
libraries/Dimmable_Light_for_Arduino/src/hw_timer_pico.h
Normal file
45
libraries/Dimmable_Light_for_Arduino/src/hw_timer_pico.h
Normal file
@@ -0,0 +1,45 @@
|
||||
/******************************************************************************
|
||||
* This file is part of Dimmable Light for Arduino, a library to control *
|
||||
* dimmers. *
|
||||
* *
|
||||
* Copyright (C) 2023 Adam Hoese *
|
||||
* *
|
||||
* Dimmable Light for Arduino is free software; you can redistribute *
|
||||
* it and/or modify it under the terms of the GNU Lesser General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2.1 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public License *
|
||||
* along with this library; if not, see <http://www.gnu.org/licenses/>. *
|
||||
******************************************************************************/
|
||||
|
||||
#if defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED)
|
||||
|
||||
#ifndef HW_TIMER_PICO_H
|
||||
#define HW_TIMER_PICO_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
/**
|
||||
* Initialize the timer.
|
||||
*/
|
||||
void timerBegin();
|
||||
|
||||
/**
|
||||
* Set callback function on timer triggers
|
||||
*/
|
||||
void timerSetCallback(void (*callback)());
|
||||
|
||||
/**
|
||||
* Start the timer to trigger after the specified number of microseconds.
|
||||
*/
|
||||
void timerStart(uint64_t t);
|
||||
|
||||
#endif // HW_TIMER_PICO_H
|
||||
|
||||
#endif // ARDUINO_ARCH_RP2040
|
||||
137
libraries/Dimmable_Light_for_Arduino/src/hw_timer_samd.cpp
Normal file
137
libraries/Dimmable_Light_for_Arduino/src/hw_timer_samd.cpp
Normal file
@@ -0,0 +1,137 @@
|
||||
/******************************************************************************
|
||||
* This file is part of Dimmable Light for Arduino, a library to control *
|
||||
* dimmers. *
|
||||
* *
|
||||
* Copyright (C) 2018-2023 Fabiano Riccardi *
|
||||
* *
|
||||
* Dimmable Light for Arduino is free software; you can redistribute *
|
||||
* it and/or modify it under the terms of the GNU Lesser General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2.1 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public License *
|
||||
* along with this library; if not, see <http://www.gnu.org/licenses/>. *
|
||||
******************************************************************************/
|
||||
|
||||
/***********************************************************************************
|
||||
* Here there is specific SAMD code. SAMD21 is usually programmed at register level
|
||||
* so this file is needed to provide a minimalistic "HAL" to simplify timer usage.
|
||||
***********************************************************************************/
|
||||
|
||||
#ifdef ARDUINO_ARCH_SAMD
|
||||
|
||||
#include "hw_timer_samd.h"
|
||||
#include <Arduino.h>
|
||||
|
||||
// Supported timer: 3,4,5,... (NOTE: the one named as TC and not TCC).
|
||||
// TC and TCC share the enumeration, where TCCs start from 0 and TCs
|
||||
// follow up
|
||||
#define TIMER_ID 3
|
||||
|
||||
#if TIMER_ID <= 2
|
||||
#error "TIMER_ID must be between [3;7]"
|
||||
#endif
|
||||
|
||||
// Some helpful macros to support different timers
|
||||
#define _TCx(X) TC##X
|
||||
#define TCx(X) _TCx(X)
|
||||
#define _TCx_Handler(X) TC##X##_Handler
|
||||
#define TCx_Handler(X) _TCx_Handler(X)
|
||||
#define _TCx_IRQn(X) TC##X##_IRQn
|
||||
#define TCx_IRQn(X) _TCx_IRQn(X)
|
||||
#define _TCx_(X) TC##X##_
|
||||
#define TCx_(X) _TCx_(X)
|
||||
|
||||
#if TIMER_ID == 3
|
||||
#define GCLK_CLKCTRL_ID_x GCLK_CLKCTRL_ID_TCC2_TC3
|
||||
#elif TIMER_ID == 4 || TIMER_ID == 5
|
||||
#define GCLK_CLKCTRL_ID_x GCLK_CLKCTRL_ID_TC4_TC5
|
||||
#elif TIMER_ID == 6 || TIMER_ID == 7
|
||||
#define GCLK_CLKCTRL_ID_x GCLK_CLKCTRL_ID_TC6_TC7
|
||||
#endif
|
||||
|
||||
static void (*timer_callback)() = nullptr;
|
||||
|
||||
void TCx_Handler(TIMER_ID)() {
|
||||
TCx(TIMER_ID)->COUNT16.CTRLA.bit.ENABLE = 0;
|
||||
// Wait until TC3 is enabled
|
||||
while (TCx(TIMER_ID)->COUNT16.STATUS.bit.SYNCBUSY == 1)
|
||||
;
|
||||
|
||||
TCx(TIMER_ID)->COUNT16.INTFLAG.bit.MC0 = 1;
|
||||
|
||||
timer_callback();
|
||||
}
|
||||
|
||||
uint16_t microsecond2Tick(uint16_t micro) {
|
||||
// Source clock / prescaler (NOTE that multiple prescaler can be chained)
|
||||
static const uint32_t OSC8M_FREQ = 8000000;
|
||||
static const uint32_t baseFreq = OSC8M_FREQ / 2;
|
||||
static const uint16_t baseFreqForMicro = baseFreq / 1000000;
|
||||
if (micro > 10000) { return 0; }
|
||||
return baseFreqForMicro * micro;
|
||||
}
|
||||
|
||||
void timerBegin() {
|
||||
// enable 8Mhz clock, prescaler to 0
|
||||
SYSCTRL->OSC8M.bit.PRESC = 0;
|
||||
SYSCTRL->OSC8M.reg |= SYSCTRL_OSC8M_ENABLE;
|
||||
|
||||
// Configure Generic Clock Controller
|
||||
// Configure asynchronous clock source
|
||||
GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID_x; // select TCx peripheral channel
|
||||
GCLK->CLKCTRL.reg |= GCLK_CLKCTRL_GEN_GCLK7; // select source GCLK_GEN[0]
|
||||
GCLK->CLKCTRL.bit.CLKEN = 1; // enable TCx generic clock
|
||||
|
||||
GCLK->GENCTRL.bit.SRC = GCLK_GENCTRL_SRC_OSC8M_Val; // 0x06 OSC8M oscillator output, High
|
||||
// accuracy 8Mhz clock
|
||||
GCLK->GENCTRL.bit.ID = 0x07; // select GCLK_GEN[7]
|
||||
GCLK->GENCTRL.bit.GENEN = 1; // enable generator
|
||||
|
||||
GCLK->GENDIV.bit.ID = 0x07; // select GCLK_GEN[7]
|
||||
GCLK->GENDIV.bit.DIV = 0; // write no prescaler
|
||||
|
||||
// Power Manager, usually peripheral are disabled on power reset!
|
||||
PM->APBCSEL.bit.APBCDIV = 0; // no prescaler
|
||||
PM->APBCMASK.bit.TCx_(TIMER_ID) = 1; // enable TCx interface
|
||||
|
||||
TCx(TIMER_ID)->COUNT16.CTRLA.bit.MODE = 0; // Configure Count Mode (16-bit)
|
||||
TCx(TIMER_ID)->COUNT16.CTRLA.bit.PRESCALER = TC_CTRLA_PRESCALER_DIV2_Val; // Configure Prescaler
|
||||
// for divide by 2
|
||||
TCx(TIMER_ID)->COUNT16.CTRLBCLR.bit.DIR = 1;
|
||||
|
||||
TCx(TIMER_ID)->COUNT16.CTRLC.bit.CPTEN0 = 0;
|
||||
TCx(TIMER_ID)->COUNT16.INTENSET.bit.MC0 = 1; // Enable TCx compare mode interrupt generation //
|
||||
// Enable match interrupts on compare channel 0
|
||||
TCx(TIMER_ID)->COUNT16.CC[0].reg = 0; // Initialize the compare register
|
||||
|
||||
NVIC_EnableIRQ(TCx_IRQn(TIMER_ID)); // Enable TCx NVIC Interrupt Line
|
||||
}
|
||||
|
||||
void timerSetCallback(void (*callback)()) {
|
||||
timer_callback = callback;
|
||||
}
|
||||
|
||||
void timerStart(uint16_t t) {
|
||||
if (t <= 1) { return; }
|
||||
|
||||
TCx(TIMER_ID)->COUNT16.COUNT.reg = 0;
|
||||
while (TCx(TIMER_ID)->COUNT16.STATUS.bit.SYNCBUSY == 1)
|
||||
;
|
||||
|
||||
TCx(TIMER_ID)->COUNT16.CC[0].reg = t;
|
||||
while (TCx(TIMER_ID)->COUNT16.STATUS.bit.SYNCBUSY == 1)
|
||||
;
|
||||
|
||||
TCx(TIMER_ID)->COUNT16.CTRLA.bit.ENABLE = 1;
|
||||
// Wait until Timer is enabled
|
||||
while (TCx(TIMER_ID)->COUNT16.STATUS.bit.SYNCBUSY == 1)
|
||||
;
|
||||
}
|
||||
|
||||
#endif // END ARDUINO_ARCH_SAMD
|
||||
57
libraries/Dimmable_Light_for_Arduino/src/hw_timer_samd.h
Normal file
57
libraries/Dimmable_Light_for_Arduino/src/hw_timer_samd.h
Normal file
@@ -0,0 +1,57 @@
|
||||
/******************************************************************************
|
||||
* This file is part of Dimmable Light for Arduino, a library to control *
|
||||
* dimmers. *
|
||||
* *
|
||||
* Copyright (C) 2018-2023 Fabiano Riccardi *
|
||||
* *
|
||||
* Dimmable Light for Arduino is free software; you can redistribute *
|
||||
* it and/or modify it under the terms of the GNU Lesser General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2.1 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public License *
|
||||
* along with this library; if not, see <http://www.gnu.org/licenses/>. *
|
||||
******************************************************************************/
|
||||
|
||||
/***********************************************************************************
|
||||
* Here there is specific SAMD code. SAMD21 is usually programmed at register level
|
||||
* so this file is needed to provide a minimalistic "HAL" to simplify timer usage.
|
||||
***********************************************************************************/
|
||||
#ifdef ARDUINO_ARCH_SAMD
|
||||
|
||||
#ifndef HW_TIMER_SAMD_H
|
||||
#define HW_TIMER_SAMD_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
/**
|
||||
* Convert from microsecond to tick.
|
||||
* Max microseconds value is 10000, for higher values it returns 0.
|
||||
*/
|
||||
uint16_t microsecond2Tick(uint16_t micro);
|
||||
|
||||
/**
|
||||
* Initialize the timer.
|
||||
*/
|
||||
void timerBegin();
|
||||
|
||||
/**
|
||||
* Set callback function on timer triggers
|
||||
*/
|
||||
void timerSetCallback(void (*callback)());
|
||||
|
||||
/**
|
||||
* Start the timer to trigger after the specified number of ticks.
|
||||
*
|
||||
* NOTE: 0 or 1 values are not accepted
|
||||
*/
|
||||
void timerStart(uint16_t tick);
|
||||
|
||||
#endif // HW_TIMER_SAMD_H
|
||||
|
||||
#endif // ARDUINO_ARCH_SAMD
|
||||
788
libraries/Dimmable_Light_for_Arduino/src/thyristor.cpp
Normal file
788
libraries/Dimmable_Light_for_Arduino/src/thyristor.cpp
Normal file
@@ -0,0 +1,788 @@
|
||||
/******************************************************************************
|
||||
* This file is part of Dimmable Light for Arduino, a library to control *
|
||||
* dimmers. *
|
||||
* *
|
||||
* Copyright (C) 2018-2023 Fabiano Riccardi *
|
||||
* *
|
||||
* Dimmable Light for Arduino is free software; you can redistribute *
|
||||
* it and/or modify it under the terms of the GNU Lesser General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2.1 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public License *
|
||||
* along with this library; if not, see <http://www.gnu.org/licenses/>. *
|
||||
******************************************************************************/
|
||||
#include "thyristor.h"
|
||||
#include "circular_queue.h"
|
||||
#include <Arduino.h>
|
||||
|
||||
#if defined(ARDUINO_ARCH_ESP8266)
|
||||
#include "hw_timer_esp8266.h"
|
||||
#elif defined(ARDUINO_ARCH_ESP32)
|
||||
#include "hw_timer_esp32.h"
|
||||
#elif defined(ARDUINO_ARCH_AVR)
|
||||
#include "hw_timer_avr.h"
|
||||
#elif defined(ARDUINO_ARCH_SAMD)
|
||||
#include "hw_timer_samd.h"
|
||||
#elif defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED)
|
||||
#include "hw_timer_pico.h"
|
||||
#else
|
||||
#error "only ESP8266, ESP32, AVR, SAMD & RP2040 (non-mbed) architectures are supported"
|
||||
#endif
|
||||
|
||||
// Ignore zero-cross interrupts when they occurs too early w.r.t semi-period ideal length.
|
||||
// The constant *semiPeriodShrinkMargin* defines the "too early" margin.
|
||||
// This filter affects the MONITOR_FREQUENCY measurement.
|
||||
//#define FILTER_INT_PERIOD
|
||||
|
||||
// FOR DEBUG PURPOSE ONLY. This option requires FILTER_INT_PERIOD enabled.
|
||||
// Print on serial port the time passed from the previous zero cross interrupt when the semi-period
|
||||
// length is exceed the interval defined by *semiPeriodShrinkMargin* and *semiPeriodExpandMargin*.
|
||||
//#define PRINT_INT_PERIOD
|
||||
|
||||
// FOR DEBUG PURPOSE ONLY.
|
||||
// Prints a char on the serial port if not all thyristors are managed in a semi-period.
|
||||
//#define CHECK_MANAGED_THYR
|
||||
|
||||
// Force the signal length of thyristor's gate. If not enabled, the signal to gate
|
||||
// is turned off through an interrupt just before the end of the period.
|
||||
// Look at gateTurnOffTime constant for more info.
|
||||
//#define PREDEFINED_PULSE_LENGTH
|
||||
|
||||
// In microseconds
|
||||
#ifdef NETWORK_FREQ_FIXED_50HZ
|
||||
static const uint16_t semiPeriodLength = 10000;
|
||||
#endif
|
||||
#ifdef NETWORK_FREQ_FIXED_60HZ
|
||||
static const uint16_t semiPeriodLength = 8333;
|
||||
#endif
|
||||
#ifdef NETWORK_FREQ_RUNTIME
|
||||
static uint16_t semiPeriodLength = 0;
|
||||
#endif
|
||||
|
||||
// These margins are precautions against noise, electrical spikes and frequency skew errors.
|
||||
// Activation delays lower than *startMargin* turn the thyristor fully ON.
|
||||
// Activation delays higher than *endMargin* turn the thyristor fully OFF.
|
||||
// Tune this parameters accordingly to your setup (electrical network, MCU, and ZC circuitry).
|
||||
// Values are expressed in microseconds.
|
||||
static const uint16_t startMargin = 200;
|
||||
static const uint16_t endMargin = 500;
|
||||
|
||||
// This parameter represents the time span in which 2 (or more) very near delays are merged (the
|
||||
// higher ones are merged in the smaller one). This could be necessary for 2 main reasons:
|
||||
// 1) Efficiency, in fact in some applications you will never seem differences between
|
||||
// near delays, hence raising many interrupts is useless.
|
||||
// 2) MCU inability to satisfy very tight "timer start".
|
||||
// After some experiments on incandescence light bulbs, I noted that even 50 microseconds
|
||||
// are not negligible, so I decided to set threshold lower than 20microsecond. Before lowering this
|
||||
// value, check the documentation of the specific MCU since some have limitations. For example,
|
||||
// ESP8266 API documentation suggests to set timer dealy higher than >10us. If you use 8-bit timers
|
||||
// on AVR, you should set a bigger mergePeriod (e.g. 100us).
|
||||
static const uint16_t mergePeriod = 20;
|
||||
|
||||
// Period in microseconds before the end of the semiperiod when an interrupt is triggered to
|
||||
// turn off all gate signals. This parameter doesn't have any effect if you enable
|
||||
// PREDEFINED_PULSE_LENGTH.
|
||||
static const uint16_t gateTurnOffTime = 300;
|
||||
|
||||
static_assert(endMargin - gateTurnOffTime > mergePeriod, "endMargin must be greater than "
|
||||
"(gateTurnOffTime + mergePeriod)");
|
||||
|
||||
#ifdef PREDEFINED_PULSE_LENGTH
|
||||
// Length of pulse on thyristor's gate pin. This parameter is not applied if thyristor is fully on
|
||||
// or off. This option is suitable only for very short pulses, since it blocks the ISR for the
|
||||
// specified amount of time.
|
||||
static uint8_t pulseWidth = 15;
|
||||
#endif
|
||||
|
||||
struct PinDelay {
|
||||
uint8_t pin;
|
||||
uint16_t delay;
|
||||
};
|
||||
|
||||
enum class INT_TYPE { ACTIVATE_THYRISTORS, TURN_OFF_GATES };
|
||||
|
||||
static INT_TYPE nextISR = INT_TYPE::ACTIVATE_THYRISTORS;
|
||||
|
||||
/**
|
||||
* Temporary struct manipulated by the ISR storing the timing information about each dimmer.
|
||||
*/
|
||||
static struct PinDelay pinDelay[Thyristor::N];
|
||||
|
||||
/**
|
||||
* Summary of thyristors' state used by ISR (concurrent-safe).
|
||||
*/
|
||||
static bool _allThyristorsOnOff = true;
|
||||
|
||||
/**
|
||||
* Tell if zero-cross interrupt is enabled.
|
||||
*/
|
||||
static bool interruptEnabled = false;
|
||||
|
||||
/**
|
||||
* Number of thyristors already managed in the current semi-period.
|
||||
*/
|
||||
static uint8_t thyristorManaged = 0;
|
||||
|
||||
/**
|
||||
* Number of thyristors FULLY on. The remaining ones must be turned
|
||||
* off by turn_off_gates_int at the end of the semi-period.
|
||||
*/
|
||||
static uint8_t alwaysOnCounter = 0;
|
||||
static uint8_t alwaysOffCounter = 0;
|
||||
|
||||
#if defined(ARDUINO_ARCH_ESP8266)
|
||||
void HW_TIMER_IRAM_ATTR turn_off_gates_int() {
|
||||
#elif defined(ARDUINO_ARCH_ESP32)
|
||||
void ARDUINO_ISR_ATTR turn_off_gates_int() {
|
||||
#else
|
||||
void turn_off_gates_int() {
|
||||
#endif
|
||||
for (int i = alwaysOnCounter; i < Thyristor::nThyristors; i++) {
|
||||
digitalWrite(pinDelay[i].pin, LOW);
|
||||
}
|
||||
|
||||
#if defined(ARDUINO_ARCH_AVR)
|
||||
timerStop();
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* Timer routine to turn on one or more thyristors. This function may be be called multiple times
|
||||
* per semi-period depending on the current thyristors configuration.
|
||||
*/
|
||||
#if defined(ARDUINO_ARCH_ESP8266)
|
||||
void HW_TIMER_IRAM_ATTR activate_thyristors() {
|
||||
#elif defined(ARDUINO_ARCH_ESP32)
|
||||
void ARDUINO_ISR_ATTR activate_thyristors() {
|
||||
#else
|
||||
void activate_thyristors() {
|
||||
#endif
|
||||
|
||||
const uint8_t firstToBeUpdated = thyristorManaged;
|
||||
|
||||
for (;
|
||||
// The last thyristor is managed outside the loop
|
||||
thyristorManaged < Thyristor::nThyristors - 1 &&
|
||||
// Consider the "near" thyristors
|
||||
pinDelay[thyristorManaged + 1].delay - pinDelay[firstToBeUpdated].delay < mergePeriod &&
|
||||
// Exclude the one who must remain totally off
|
||||
pinDelay[thyristorManaged].delay <= semiPeriodLength - endMargin;
|
||||
thyristorManaged++) {
|
||||
digitalWrite(pinDelay[thyristorManaged].pin, HIGH);
|
||||
}
|
||||
digitalWrite(pinDelay[thyristorManaged].pin, HIGH);
|
||||
thyristorManaged++;
|
||||
|
||||
// This while is dedicated to all those thyristors with delay == semiPeriodLength-margin; those
|
||||
// are the ones who shouldn't turn on, hence they can be skipped
|
||||
while (thyristorManaged < Thyristor::nThyristors && pinDelay[thyristorManaged].delay == semiPeriodLength) {
|
||||
thyristorManaged++;
|
||||
}
|
||||
|
||||
#ifdef PREDEFINED_PULSE_LENGTH
|
||||
delayMicroseconds(pulseWidth);
|
||||
|
||||
for (int i = firstToBeUpdated; i < thyristorManaged; i++) { digitalWrite(pinDelay[i].pin, LOW); }
|
||||
#endif
|
||||
|
||||
if (thyristorManaged < Thyristor::nThyristors) {
|
||||
int delayAbsolute = pinDelay[thyristorManaged].delay;
|
||||
|
||||
#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_SAMD) || (defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED))
|
||||
int delayRelative = delayAbsolute - pinDelay[firstToBeUpdated].delay;
|
||||
#endif
|
||||
|
||||
#if defined(ARDUINO_ARCH_ESP8266)
|
||||
timer1_write(US_TO_RTC_TIMER_TICKS(delayRelative));
|
||||
#elif defined(ARDUINO_ARCH_ESP32)
|
||||
setAlarm(delayAbsolute);
|
||||
#elif defined(ARDUINO_ARCH_AVR)
|
||||
timerSetAlarm(microsecond2Tick(delayRelative));
|
||||
#elif defined(ARDUINO_ARCH_SAMD)
|
||||
timerStart(microsecond2Tick(delayRelative));
|
||||
#elif defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED)
|
||||
timerStart(delayRelative);
|
||||
#else
|
||||
#error "Not implemented"
|
||||
#endif
|
||||
} else {
|
||||
|
||||
#ifdef PREDEFINED_PULSE_LENGTH
|
||||
// If there are not more thyristor to serve, I can stop timer. Energy saving?
|
||||
#if defined(ARDUINO_ARCH_ESP8266)
|
||||
// Given the Arduino HAL and esp8266 technical reference manual,
|
||||
// when timer triggers, the counter stops because it has reach zero
|
||||
// and no-autorealod was set (this timer can only down-count).
|
||||
#elif defined(ARDUINO_ARCH_ESP32)
|
||||
stopTimer();
|
||||
#elif defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_SAMD)
|
||||
// Given actual HAL, AVR and SAMD counter automatically stops on interrupt
|
||||
#elif defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED)
|
||||
// Timer callback is not rescheduled
|
||||
#endif
|
||||
#else
|
||||
// If there are not more thyristors to serve, set timer to turn off gates' signal
|
||||
uint16_t delayAbsolute = semiPeriodLength - gateTurnOffTime;
|
||||
|
||||
#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_SAMD) || (defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED))
|
||||
uint16_t delayRelative = delayAbsolute - pinDelay[firstToBeUpdated].delay;
|
||||
#endif
|
||||
|
||||
#if defined(ARDUINO_ARCH_ESP8266)
|
||||
timer1_attachInterrupt(turn_off_gates_int);
|
||||
timer1_write(US_TO_RTC_TIMER_TICKS(delayRelative));
|
||||
#elif defined(ARDUINO_ARCH_ESP32)
|
||||
nextISR = INT_TYPE::TURN_OFF_GATES;
|
||||
setAlarm(delayAbsolute);
|
||||
#elif defined(ARDUINO_ARCH_AVR)
|
||||
timerSetCallback(turn_off_gates_int);
|
||||
timerSetAlarm(microsecond2Tick(delayRelative));
|
||||
#elif defined(ARDUINO_ARCH_SAMD)
|
||||
timerSetCallback(turn_off_gates_int);
|
||||
timerStart(microsecond2Tick(delayRelative));
|
||||
#elif defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED)
|
||||
timerSetCallback(turn_off_gates_int);
|
||||
timerStart(delayRelative);
|
||||
#else
|
||||
#error "Not implemented"
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef FILTER_INT_PERIOD
|
||||
// In microsecond
|
||||
const static int semiPeriodShrinkMargin = 50;
|
||||
const static int semiPeriodExpandMargin = 50;
|
||||
#endif
|
||||
|
||||
#if defined(FILTER_INT_PERIOD) || defined(MONITOR_FREQUENCY)
|
||||
static uint32_t lastTime = 0;
|
||||
#endif
|
||||
|
||||
#ifdef MONITOR_FREQUENCY
|
||||
// Circular queue to compute the moving average
|
||||
static CircularQueue<uint32_t, 5> queue;
|
||||
static uint32_t total = 0;
|
||||
#endif
|
||||
|
||||
#if defined(ARDUINO_ARCH_ESP8266)
|
||||
void HW_TIMER_IRAM_ATTR zero_cross_int() {
|
||||
#elif defined(ARDUINO_ARCH_ESP32)
|
||||
void ARDUINO_ISR_ATTR zero_cross_int() {
|
||||
#else
|
||||
void zero_cross_int() {
|
||||
#endif
|
||||
|
||||
#if defined(FILTER_INT_PERIOD) || defined(MONITOR_FREQUENCY)
|
||||
if (!lastTime) {
|
||||
lastTime = micros();
|
||||
} else {
|
||||
uint32_t now = micros();
|
||||
|
||||
// "diff" is correct even when timer rolls back, because these values are unsigned
|
||||
uint32_t diff = now - lastTime;
|
||||
|
||||
#ifdef PRINT_INT_PERIOD
|
||||
if (diff < semiPeriodLength - semiPeriodShrinkMargin) {
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
ets_printf("B%d\n", diff);
|
||||
#else
|
||||
Serial.println(String('B') + diff);
|
||||
#endif
|
||||
}
|
||||
if (diff > semiPeriodLength + semiPeriodExpandMargin) {
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
ets_printf("A%d\n", diff);
|
||||
#else
|
||||
Serial.println(String('A') + diff);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef FILTER_INT_PERIOD
|
||||
// Filters out spurious interrupts. The effectiveness of this simple
|
||||
// filter could vary depending on noise on electrical networ.
|
||||
if (diff < semiPeriodLength - semiPeriodShrinkMargin) { return; }
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#if defined(ARDUINO_ARCH_AVR)
|
||||
// Early timer start, only for avr. This is necessary since the instructions executed in this
|
||||
// ISR take much time (more than 30us with only 4 dimmers). Before the end of this ISR, either
|
||||
// the timer is stop or the alarm time is properly set.
|
||||
timerStartAndTrigger(microsecond2Tick(15000));
|
||||
#endif
|
||||
|
||||
#if defined(FILTER_INT_PERIOD) || defined(MONITOR_FREQUENCY)
|
||||
#ifdef MONITOR_FREQUENCY
|
||||
// if diff is very very greater than the theoretical value, the electrical signal
|
||||
// can be considered as lost for a while and I must reset my moving average.
|
||||
// I decided to use "16" because is a power of 2, very fast to be computed.
|
||||
if (semiPeriodLength && diff > semiPeriodLength * 16) {
|
||||
queue.reset();
|
||||
total = 0;
|
||||
} else {
|
||||
// If filtering has passed, I can update the moving average
|
||||
uint32_t valueToRemove = queue.insert(diff);
|
||||
total += diff;
|
||||
total -= valueToRemove;
|
||||
}
|
||||
#endif
|
||||
|
||||
lastTime = now;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Turn OFF all the thyristors, even if always ON.
|
||||
// This is to speed up transitions between ON to OFF state:
|
||||
// If I don't turn OFF all those thyristors, I must wait
|
||||
// a semiperiod to turn off those one.
|
||||
for (int i = 0; i < Thyristor::nThyristors; i++) { digitalWrite(pinDelay[i].pin, LOW); }
|
||||
|
||||
#ifdef CHECK_MANAGED_THYR
|
||||
if (thyristorManaged != Thyristor::nThyristors) {
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
ets_printf("E%d\n", thyristorManaged);
|
||||
#else
|
||||
Serial.print("E");
|
||||
Serial.println(thyristorManaged);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
// Update the structures and set thresholds, if needed
|
||||
if (Thyristor::newDelayValues && !Thyristor::updatingStruct) {
|
||||
Thyristor::newDelayValues = false;
|
||||
alwaysOffCounter = 0;
|
||||
alwaysOnCounter = 0;
|
||||
for (int i = 0; i < Thyristor::nThyristors; i++) {
|
||||
pinDelay[i].pin = Thyristor::thyristors[i]->pin;
|
||||
// Rounding delays to avoid error and unexpected behavior due to
|
||||
// non-ideal thyristors and not perfect sine wave
|
||||
if (Thyristor::thyristors[i]->delay == 0) {
|
||||
alwaysOnCounter++;
|
||||
pinDelay[i].delay = 0;
|
||||
} else if (Thyristor::thyristors[i]->delay < startMargin) {
|
||||
alwaysOnCounter++;
|
||||
pinDelay[i].delay = 0;
|
||||
} else if (Thyristor::thyristors[i]->delay == semiPeriodLength) {
|
||||
alwaysOffCounter++;
|
||||
pinDelay[i].delay = semiPeriodLength;
|
||||
} else if (Thyristor::thyristors[i]->delay > semiPeriodLength - endMargin) {
|
||||
alwaysOffCounter++;
|
||||
pinDelay[i].delay = semiPeriodLength;
|
||||
} else {
|
||||
pinDelay[i].delay = Thyristor::thyristors[i]->delay;
|
||||
}
|
||||
}
|
||||
_allThyristorsOnOff = Thyristor::allThyristorsOnOff;
|
||||
}
|
||||
|
||||
thyristorManaged = 0;
|
||||
|
||||
// if all are on and off, I can disable the zero cross interrupt
|
||||
if (_allThyristorsOnOff) {
|
||||
for (int i = 0; i < Thyristor::nThyristors; i++) {
|
||||
if (pinDelay[i].delay == semiPeriodLength) {
|
||||
digitalWrite(pinDelay[i].pin, LOW);
|
||||
} else {
|
||||
digitalWrite(pinDelay[i].pin, HIGH);
|
||||
}
|
||||
thyristorManaged++;
|
||||
}
|
||||
|
||||
#if defined(MONITOR_FREQUENCY)
|
||||
if (!Thyristor::frequencyMonitorAlwaysEnabled) {
|
||||
interruptEnabled = false;
|
||||
detachInterrupt(digitalPinToInterrupt(Thyristor::syncPin));
|
||||
|
||||
queue.reset();
|
||||
total = 0;
|
||||
|
||||
lastTime = 0;
|
||||
}
|
||||
#elif defined(FILTER_INT_MONITOR)
|
||||
lastTime = 0;
|
||||
interruptEnabled = false;
|
||||
detachInterrupt(digitalPinToInterrupt(Thyristor::syncPin));
|
||||
#else
|
||||
interruptEnabled = false;
|
||||
detachInterrupt(digitalPinToInterrupt(Thyristor::syncPin));
|
||||
#endif
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Turn on thyristors with 0 delay (always on)
|
||||
while (thyristorManaged < Thyristor::nThyristors && pinDelay[thyristorManaged].delay == 0) {
|
||||
digitalWrite(pinDelay[thyristorManaged].pin, HIGH);
|
||||
thyristorManaged++;
|
||||
}
|
||||
|
||||
// This block of code is inteded to manage the case near to the next semi-period:
|
||||
// In this case we should avoid to trigger the timer, because the effective semiperiod
|
||||
// perceived by the esp8266 could be less than 10000microsecond. This could be due to
|
||||
// the relative time (there is no possibily to set the timer to an absolute time)
|
||||
// Moreover, it is impossible to disable an interrupt once it is armed, neither
|
||||
// change the callback function.
|
||||
// NOTE: don't know why, but the timer seem trigger even when it is not set...
|
||||
// so a provvisory solution if to set the relative callback to NULL!
|
||||
// NOTE 2: this improvement should be think even for multiple lamp!
|
||||
if (thyristorManaged < Thyristor::nThyristors && pinDelay[thyristorManaged].delay < semiPeriodLength) {
|
||||
uint16_t delayAbsolute = pinDelay[thyristorManaged].delay;
|
||||
#if defined(ARDUINO_ARCH_ESP8266)
|
||||
timer1_attachInterrupt(activate_thyristors);
|
||||
timer1_write(US_TO_RTC_TIMER_TICKS(delayAbsolute));
|
||||
#elif defined(ARDUINO_ARCH_ESP32)
|
||||
// setCallback(activate_thyristors);
|
||||
nextISR = INT_TYPE::ACTIVATE_THYRISTORS;
|
||||
startTimerAndTrigger(delayAbsolute);
|
||||
#elif defined(ARDUINO_ARCH_AVR)
|
||||
timerSetCallback(activate_thyristors);
|
||||
timerSetAlarm(microsecond2Tick(delayAbsolute));
|
||||
#elif defined(ARDUINO_ARCH_SAMD)
|
||||
timerSetCallback(activate_thyristors);
|
||||
timerStart(microsecond2Tick(delayAbsolute));
|
||||
#elif defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED)
|
||||
timerSetCallback(activate_thyristors);
|
||||
timerStart(pinDelay[thyristorManaged].delay);
|
||||
#else
|
||||
# error "Not implemented"
|
||||
#endif
|
||||
} else {
|
||||
|
||||
// This while is dedicated to all those thyristor wih delay == semiPeriodLength-margin; those
|
||||
// are the ones who shouldn't turn on, hence they can be skipped
|
||||
while (thyristorManaged < Thyristor::nThyristors && pinDelay[thyristorManaged].delay == semiPeriodLength) {
|
||||
thyristorManaged++;
|
||||
}
|
||||
|
||||
#if defined(ARDUINO_ARCH_ESP8266)
|
||||
// Given the Arduino HAL and esp8266 technical reference manual,
|
||||
// when timer triggers, the counter stops because it has reached zero
|
||||
// and no-autorealod was set (this timer can only down-count).
|
||||
#elif defined(ARDUINO_ARCH_ESP32)
|
||||
stopTimer();
|
||||
#elif defined(ARDUINO_ARCH_AVR)
|
||||
timerStop();
|
||||
#elif defined(ARDUINO_ARCH_SAMD)
|
||||
// Given actual HAL, and SAMD counter automatically stops on interrupt
|
||||
#elif defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED)
|
||||
// Timer callback is not rescheduled
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(ARDUINO_ARCH_ESP8266)
|
||||
void HW_TIMER_IRAM_ATTR isr_selector() {
|
||||
#elif defined(ARDUINO_ARCH_ESP32)
|
||||
void ARDUINO_ISR_ATTR isr_selector() {
|
||||
#else
|
||||
void isr_selector() {
|
||||
#endif
|
||||
if (nextISR == INT_TYPE::ACTIVATE_THYRISTORS) {
|
||||
activate_thyristors();
|
||||
} else if (nextISR == INT_TYPE::TURN_OFF_GATES) {
|
||||
turn_off_gates_int();
|
||||
}
|
||||
}
|
||||
|
||||
void Thyristor::setDelay(uint16_t newDelay) {
|
||||
if (verbosity > 2) {
|
||||
for (int i = 0; i < Thyristor::nThyristors; i++) {
|
||||
Serial.print(String("setB: ") + "posIntoArray:" + thyristors[i]->posIntoArray
|
||||
+ " pin:" + thyristors[i]->pin);
|
||||
Serial.print(" ");
|
||||
Serial.println(thyristors[i]->delay);
|
||||
}
|
||||
}
|
||||
|
||||
if (newDelay > semiPeriodLength) { newDelay = semiPeriodLength; }
|
||||
|
||||
// Reorder the array to speed up the interrupt.
|
||||
// This mini-algorithm works on a different memory area w.r.t. the ISR,
|
||||
// so it is concurrent-safe
|
||||
|
||||
updatingStruct = true;
|
||||
// Array example, it is always ordered, higher values means lower brightness levels
|
||||
// [45,678,5000,7500,9000]
|
||||
if (newDelay > delay) {
|
||||
if (verbosity > 2) Serial.println("\tlowering the light..");
|
||||
bool done = false;
|
||||
/////////////////////////////////////////////////////////////////
|
||||
// Let's find the new position
|
||||
int i = posIntoArray + 1;
|
||||
while (i < nThyristors && !done) {
|
||||
if (newDelay <= thyristors[i]->delay) {
|
||||
done = true;
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
// This could be due to 2 reasons:
|
||||
// 1) the light is already the lowest delay (i.e. turned off)
|
||||
// 2) the delay is not changed to overpass the neightbour
|
||||
if (posIntoArray + 1 == i) {
|
||||
if (verbosity > 2) Serial.println("No need to shift..");
|
||||
} else {
|
||||
int target;
|
||||
// Means that we have reached the end, the target i the last element
|
||||
if (i == nThyristors) {
|
||||
target = nThyristors - 1;
|
||||
} else {
|
||||
target = i - 1;
|
||||
}
|
||||
|
||||
// Let's shift
|
||||
for (int i = posIntoArray; i < target; i++) {
|
||||
thyristors[i] = thyristors[i + 1];
|
||||
thyristors[i]->posIntoArray = i;
|
||||
}
|
||||
thyristors[target] = this;
|
||||
this->posIntoArray = target;
|
||||
}
|
||||
} else if (newDelay < delay) {
|
||||
if (verbosity > 2) Serial.println("\traising the light..");
|
||||
bool done = false;
|
||||
int i = posIntoArray - 1;
|
||||
while (i >= 0 && !done) {
|
||||
if (newDelay >= thyristors[i]->delay) {
|
||||
done = true;
|
||||
} else {
|
||||
i--;
|
||||
}
|
||||
}
|
||||
if (posIntoArray - 1 == i) {
|
||||
if (verbosity > 2) Serial.println("No need to shift..");
|
||||
} else {
|
||||
int target;
|
||||
// Means that we have reached the start, the target is the first element
|
||||
if (!done) {
|
||||
target = 0;
|
||||
} else {
|
||||
target = i + 1;
|
||||
}
|
||||
|
||||
// Let's shift
|
||||
for (int i = posIntoArray; i > target; i--) {
|
||||
thyristors[i] = thyristors[i - 1];
|
||||
thyristors[i]->posIntoArray = i;
|
||||
}
|
||||
thyristors[target] = this;
|
||||
this->posIntoArray = target;
|
||||
}
|
||||
} else {
|
||||
if (verbosity > 2)
|
||||
Serial.println("Warning: you are setting the same delay as the previous one!");
|
||||
updatingStruct = false;
|
||||
return;
|
||||
}
|
||||
|
||||
delay = newDelay;
|
||||
bool enableInt = mustInterruptBeReEnabled(newDelay);
|
||||
newDelayValues = true;
|
||||
updatingStruct = false;
|
||||
if (enableInt) {
|
||||
if (verbosity > 2) Serial.println("Re-enabling interrupt");
|
||||
interruptEnabled = true;
|
||||
attachInterrupt(digitalPinToInterrupt(syncPin), zero_cross_int, syncDir);
|
||||
}
|
||||
|
||||
if (verbosity > 2) {
|
||||
for (int i = 0; i < Thyristor::nThyristors; i++) {
|
||||
Serial.print(String("\tsetB: ") + "posIntoArray:" + thyristors[i]->posIntoArray
|
||||
+ " pin:" + thyristors[i]->pin);
|
||||
Serial.print(" ");
|
||||
Serial.println(thyristors[i]->delay);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Thyristor::turnOn() {
|
||||
setDelay(semiPeriodLength);
|
||||
}
|
||||
|
||||
void Thyristor::begin() {
|
||||
pinMode(syncPin, syncPullup ? INPUT_PULLUP : INPUT);
|
||||
|
||||
#if defined(ARDUINO_ARCH_ESP8266)
|
||||
timer1_attachInterrupt(activate_thyristors);
|
||||
// These 2 registers assignments are the "unrolling" of:
|
||||
// timer1_enable(TIM_DIV16, TIM_EDGE, TIM_SINGLE);
|
||||
T1C = (1 << TCTE) | ((TIM_DIV16 & 3) << TCPD) | ((TIM_EDGE & 1) << TCIT) | ((TIM_SINGLE & 1) << TCAR);
|
||||
T1I = 0;
|
||||
#elif defined(ARDUINO_ARCH_ESP32)
|
||||
timerInit(isr_selector);
|
||||
#elif defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_SAMD) || (defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED))
|
||||
timerSetCallback(activate_thyristors);
|
||||
timerBegin();
|
||||
#else
|
||||
#error "Not implemented"
|
||||
#endif
|
||||
|
||||
#ifdef MONITOR_FREQUENCY
|
||||
// Starts immediately to sense the eletricity grid
|
||||
|
||||
interruptEnabled = true;
|
||||
attachInterrupt(digitalPinToInterrupt(syncPin), zero_cross_int, syncDir);
|
||||
#endif
|
||||
}
|
||||
|
||||
float Thyristor::getFrequency() {
|
||||
if (semiPeriodLength == 0) { return 0; }
|
||||
return 1000000 / 2 / (float)(semiPeriodLength);
|
||||
}
|
||||
|
||||
uint16_t Thyristor::getSemiPeriod() {
|
||||
return semiPeriodLength;
|
||||
}
|
||||
|
||||
#ifdef NETWORK_FREQ_RUNTIME
|
||||
void Thyristor::setFrequency(float frequency) {
|
||||
if (frequency < 0) { return; }
|
||||
|
||||
if (frequency == 0) {
|
||||
semiPeriodLength = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
semiPeriodLength = 1000000 / 2 / frequency;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef MONITOR_FREQUENCY
|
||||
float Thyristor::getDetectedFrequency() {
|
||||
int c;
|
||||
uint32_t tot;
|
||||
{
|
||||
// Stop interrupt to freeze variables modified or accessed in the interrupt
|
||||
noInterrupts();
|
||||
|
||||
// "diff" is correct even when rolling back, because all of them are unsigned
|
||||
uint32_t diff = micros() - lastTime;
|
||||
|
||||
// if diff is very very greater than the theoretical value, the electrical signal
|
||||
// can be considered as lost for a while.
|
||||
// I decided to use "16" because is a power of 2, very fast to be computed.
|
||||
if (semiPeriodLength && diff > semiPeriodLength * 16) {
|
||||
queue.reset();
|
||||
total = 0;
|
||||
}
|
||||
|
||||
c = queue.getCount();
|
||||
tot = total;
|
||||
interrupts();
|
||||
}
|
||||
|
||||
// We need at least a sample to return a value differnt from 0
|
||||
if (tot > 0) {
|
||||
// *1000000: us
|
||||
// /2: from semiperiod to full period
|
||||
float result = c * 1000000 / 2 / ((float)(tot));
|
||||
return result;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void Thyristor::frequencyMonitorAlwaysOn(bool enable) {
|
||||
{
|
||||
// Stop interrupt to freeze variables modified or accessed in the interrupt
|
||||
noInterrupts();
|
||||
|
||||
if (enable && !interruptEnabled) {
|
||||
interruptEnabled = true;
|
||||
attachInterrupt(digitalPinToInterrupt(syncPin), zero_cross_int, syncDir);
|
||||
}
|
||||
frequencyMonitorAlwaysEnabled = enable;
|
||||
|
||||
interrupts();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
Thyristor::Thyristor(int pin) : pin(pin), delay(semiPeriodLength) {
|
||||
if (nThyristors < N) {
|
||||
pinMode(pin, OUTPUT);
|
||||
|
||||
updatingStruct = true;
|
||||
|
||||
posIntoArray = nThyristors;
|
||||
nThyristors++;
|
||||
thyristors[posIntoArray] = this;
|
||||
|
||||
// Full reorder of the array
|
||||
for (int i = 0; i < nThyristors; i++) {
|
||||
for (int j = i + 1; j < nThyristors - 1; j++) {
|
||||
if (thyristors[i]->delay > thyristors[j]->delay) {
|
||||
Thyristor* temp = thyristors[i];
|
||||
thyristors[i] = thyristors[j];
|
||||
thyristors[j] = temp;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Set the posIntoArray with a "brutal" assignement to each Thyristor
|
||||
for (int i = 0; i < nThyristors; i++) { thyristors[i]->posIntoArray = i; }
|
||||
|
||||
newDelayValues = true;
|
||||
updatingStruct = false;
|
||||
} else {
|
||||
// TODO return error or exception
|
||||
}
|
||||
}
|
||||
|
||||
Thyristor::~Thyristor() {
|
||||
// Recompact the array
|
||||
updatingStruct = true;
|
||||
nThyristors--;
|
||||
// TODO remove light from the static pinDelay array, and shrink the array
|
||||
updatingStruct = false;
|
||||
}
|
||||
|
||||
bool Thyristor::areThyristorsOnOff() {
|
||||
bool allOnOff = true;
|
||||
int i = 0;
|
||||
while (i < nThyristors && allOnOff) {
|
||||
if (thyristors[i]->getDelay() != 0 && thyristors[i]->getDelay() != semiPeriodLength) {
|
||||
allOnOff = false;
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return allOnOff;
|
||||
}
|
||||
|
||||
bool Thyristor::mustInterruptBeReEnabled(uint16_t newDelay) {
|
||||
bool interruptMustBeEnabled = true;
|
||||
|
||||
// Temp values those are "commited" at the end of this method
|
||||
bool newAllThyristorsOnOff = allThyristorsOnOff;
|
||||
|
||||
if (newDelay == semiPeriodLength || newDelay == 0) {
|
||||
newAllThyristorsOnOff = areThyristorsOnOff();
|
||||
} else {
|
||||
// if newDelay is not optimizable i.e. a value between (0; semiPeriodLength)
|
||||
newAllThyristorsOnOff = false;
|
||||
}
|
||||
|
||||
allThyristorsOnOff = newAllThyristorsOnOff;
|
||||
if (verbosity > 1) Serial.println(String("allThyristorsOnOff: ") + allThyristorsOnOff);
|
||||
return !interruptEnabled && interruptMustBeEnabled;
|
||||
}
|
||||
|
||||
uint8_t Thyristor::nThyristors = 0;
|
||||
Thyristor* Thyristor::thyristors[Thyristor::N] = { nullptr };
|
||||
bool Thyristor::newDelayValues = false;
|
||||
bool Thyristor::updatingStruct = false;
|
||||
bool Thyristor::allThyristorsOnOff = true;
|
||||
uint8_t Thyristor::syncPin = 255;
|
||||
decltype(RISING) Thyristor::syncDir = RISING;
|
||||
bool Thyristor::syncPullup = false;
|
||||
bool Thyristor::frequencyMonitorAlwaysEnabled = true;
|
||||
277
libraries/Dimmable_Light_for_Arduino/src/thyristor.h
Normal file
277
libraries/Dimmable_Light_for_Arduino/src/thyristor.h
Normal file
@@ -0,0 +1,277 @@
|
||||
/******************************************************************************
|
||||
* This file is part of Dimmable Light for Arduino, a library to control *
|
||||
* dimmers. *
|
||||
* *
|
||||
* Copyright (C) 2018-2023 Fabiano Riccardi *
|
||||
* *
|
||||
* Dimmable Light for Arduino is free software; you can redistribute *
|
||||
* it and/or modify it under the terms of the GNU Lesser General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2.1 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public License *
|
||||
* along with this library; if not, see <http://www.gnu.org/licenses/>. *
|
||||
******************************************************************************/
|
||||
#ifndef THYRISTOR_H
|
||||
#define THYRISTOR_H
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
/**
|
||||
* These defines affect the declaration of this class and the relative wrappers.
|
||||
*/
|
||||
|
||||
// Set the network frequency.
|
||||
// The first 2 options fix the frequency to the common values (respectively to 50 and 60Hz) at
|
||||
// compile time. The third option allows you change network frequency at runtime. This option
|
||||
// automatically enables the setFrequency() method. The main drawback is that it requires a few more
|
||||
// resources w.r.t. the "fixed frequency" alternatives.
|
||||
// Select one and ONLY one among the following alternatives:
|
||||
//#define NETWORK_FREQ_FIXED_50HZ
|
||||
//#define NETWORK_FREQ_FIXED_60HZ
|
||||
//#define NETWORK_FREQ_RUNTIME
|
||||
|
||||
// Set the default value if no option is selected
|
||||
#if !defined(NETWORK_FREQ_FIXED_50HZ) && !defined(NETWORK_FREQ_FIXED_60HZ) && !defined(NETWORK_FREQ_RUNTIME)
|
||||
#define NETWORK_FREQ_FIXED_50HZ
|
||||
#endif
|
||||
|
||||
// If enabled, you can monitor the actual frequency of the electrical network.
|
||||
//#define MONITOR_FREQUENCY
|
||||
|
||||
/**
|
||||
* This is the core class of this library, that provides the finest control on thyristors.
|
||||
*
|
||||
* NOTE: Design Principle for this library: There are 2 main abstraction levels: the first one,
|
||||
* represented by Thyristor class, is agnostic about the controlled load (it doesn't assume a lamp,
|
||||
* a heater or a motor). The second one provides a simpler and more concrete interface, presenting
|
||||
* simplified APIs to the user as expected by an Arduino library, and it is exemplified by
|
||||
* DimmableLight class.
|
||||
* Now, I'm aware that this is positive because it allows to write very
|
||||
* readable code IF the appliance is a light, but it is limiting and weird if the user is going to
|
||||
* use another appliance.
|
||||
*
|
||||
* About this class, the "core" of the library, the name of the method to control a dimmer is
|
||||
* setDelay(..) and not, for example, setPower(..), setBrightness(..), ... This gives a precise idea
|
||||
* of what's happening at electrical level, that is controlling the activation time of the
|
||||
* thyristor. Secondly, the measurement unit is expressed in microseconds, allowing the finest and
|
||||
* feasible control reachable with almost any MCU avaialble on the market (including Arduino UNO
|
||||
* based on ATmega328p).
|
||||
*/
|
||||
class Thyristor {
|
||||
public:
|
||||
Thyristor(int pin);
|
||||
Thyristor(Thyristor const &) = delete;
|
||||
void operator=(Thyristor const &t) = delete;
|
||||
|
||||
/**
|
||||
* Set the delay, 10000 (ms, with 50Hz voltage) to turn off the thyristor
|
||||
*/
|
||||
void setDelay(uint16_t delay);
|
||||
|
||||
/**
|
||||
* Return the current delay.
|
||||
*/
|
||||
uint16_t getDelay() const {
|
||||
return delay;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn on the thyristor at full power.
|
||||
*/
|
||||
void turnOn();
|
||||
|
||||
/**
|
||||
* Turn off the thyristor.
|
||||
*/
|
||||
void turnOff() {
|
||||
setDelay(0);
|
||||
}
|
||||
|
||||
~Thyristor();
|
||||
|
||||
/**
|
||||
* Setup timer and interrupt routine.
|
||||
*/
|
||||
static void begin();
|
||||
|
||||
/**
|
||||
* Return the number of instantiated thyristors.
|
||||
*/
|
||||
static uint8_t getThyristorNumber() {
|
||||
return nThyristors;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set the pin dedicated to receive the AC zero cross signal.
|
||||
*/
|
||||
static void setSyncPin(uint8_t pin) {
|
||||
syncPin = pin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the pin direction (RISING (default), FALLING, CHANGE).
|
||||
*/
|
||||
static void setSyncDir(decltype(RISING) dir) {
|
||||
syncDir = dir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the pin pullup (true = INPUT_PULLUP, false = INPUT). The internal pullup resistor is not
|
||||
* available for each platform and each pin.
|
||||
*/
|
||||
static void setSyncPullup(bool pullup) {
|
||||
syncPullup = pullup;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get frequency.
|
||||
*/
|
||||
static float getFrequency();
|
||||
|
||||
/**
|
||||
* Get the semiperiod.
|
||||
*/
|
||||
static uint16_t getSemiPeriod();
|
||||
|
||||
#ifdef NETWORK_FREQ_RUNTIME
|
||||
/**
|
||||
* Set target frequency. Negative values are ignored;
|
||||
* zero set the semi-period to 0.
|
||||
*/
|
||||
static void setFrequency(float frequency);
|
||||
#endif
|
||||
|
||||
#ifdef MONITOR_FREQUENCY
|
||||
/**
|
||||
* Get the detected frequency on the electrical network, constantly updated.
|
||||
* Return 0 if there is no signal or while sampling the first periods.
|
||||
*
|
||||
* NOTE: when (re)starting, it will take a while before returning a value different from 0.
|
||||
*/
|
||||
static float getDetectedFrequency();
|
||||
|
||||
/**
|
||||
* Check if frequency monitor is always enabled.
|
||||
*/
|
||||
static bool isFrequencyMonitorAlwaysOn() {
|
||||
return frequencyMonitorAlwaysEnabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Control if the monitoring can be automatically stopped when
|
||||
* all lights are on and off. True to force the constant monitoring,
|
||||
* false to allow automatic stop. By default the monitoring is always active.
|
||||
*
|
||||
*/
|
||||
static void frequencyMonitorAlwaysOn(bool enable);
|
||||
#endif
|
||||
|
||||
static const uint8_t N = 8;
|
||||
|
||||
private:
|
||||
/**
|
||||
* Tell if interrupt must be re-enabled. This metohd affect allMixedOnOff variable.
|
||||
* This methods must be called every time a thyristor's delay is updated.
|
||||
*
|
||||
* NewDelay the new delay just set of this thyristor.
|
||||
* Return true if interrupt for zero cross detection should be re-enabled,
|
||||
* false do nothing.
|
||||
*/
|
||||
bool mustInterruptBeReEnabled(uint16_t newDelay);
|
||||
|
||||
/**
|
||||
* Search if all the values are only on and off.
|
||||
* Return true if all are on/off, false otherwise.
|
||||
*/
|
||||
bool areThyristorsOnOff();
|
||||
|
||||
/**
|
||||
* Number of instantiated thyristors.
|
||||
*/
|
||||
static uint8_t nThyristors;
|
||||
|
||||
/**
|
||||
* Vector of instatiated thyristors.
|
||||
*/
|
||||
static Thyristor *thyristors[];
|
||||
|
||||
/**
|
||||
* Variable to tell to interrupt routine to update its internal structures
|
||||
*/
|
||||
static bool newDelayValues;
|
||||
|
||||
/**
|
||||
* Variable to avoid concurrency problem between interrupt and threads.
|
||||
* In particular, this variable is used to prevent the copy of the memory used by
|
||||
* the array of struct during reordering (interrupt can continue because it
|
||||
* keeps its own copy of the array).
|
||||
* A condition variable does not make sense because interrupt routine cannot be
|
||||
* stopped.
|
||||
*/
|
||||
static bool updatingStruct;
|
||||
|
||||
/**
|
||||
* This variable tells if the thyristors are completely ON and OFF,
|
||||
* mixed configuration are included. If one thyristor has a value between
|
||||
* (0; semiPeriodLength), this variable is false. If true, this implies that
|
||||
* zero cross interrupt must be enabled to manage the thyristor activation.
|
||||
*/
|
||||
static bool allThyristorsOnOff;
|
||||
|
||||
/**
|
||||
* Pin receiving the external Zero Cross signal.
|
||||
*/
|
||||
static uint8_t syncPin;
|
||||
|
||||
/**
|
||||
* Pin direction (FALLING, RISING, CHANGE).
|
||||
*/
|
||||
static decltype(RISING) syncDir;
|
||||
|
||||
/**
|
||||
* Pin pullup active.
|
||||
*/
|
||||
static bool syncPullup;
|
||||
|
||||
/**
|
||||
* 0) no messages
|
||||
* 1) error messages
|
||||
* 2) debug messages
|
||||
* 3) info messages
|
||||
*/
|
||||
static const uint8_t verbosity = 1;
|
||||
|
||||
/**
|
||||
* True means the is always listeing, false means
|
||||
* auto-stop when all lights are on/off.
|
||||
*/
|
||||
static bool frequencyMonitorAlwaysEnabled;
|
||||
|
||||
/**
|
||||
* Pin used to control thyristor's gate.
|
||||
*/
|
||||
uint8_t pin;
|
||||
|
||||
/**
|
||||
* Position into the static array, this is used to speed up the research
|
||||
* operation while setting the new brightness value.
|
||||
*/
|
||||
uint8_t posIntoArray;
|
||||
|
||||
/**
|
||||
* Time to wait before turning on the thryristor.
|
||||
*/
|
||||
uint16_t delay;
|
||||
|
||||
friend void activate_thyristors();
|
||||
friend void zero_cross_int();
|
||||
friend void turn_off_gates_int();
|
||||
};
|
||||
|
||||
#endif // END THYRISTOR_H
|
||||
Reference in New Issue
Block a user