Merge branch 'development' into gateway-refactoring
Conflicts: libraries/MySensors/MyConfig.h libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino
This commit is contained in:
+1029
File diff suppressed because it is too large
Load Diff
+97
@@ -0,0 +1,97 @@
|
||||
/*--------------------------------------------------------------------
|
||||
This file is part of the Adafruit NeoPixel library.
|
||||
|
||||
NeoPixel is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as
|
||||
published by the Free Software Foundation, either version 3 of
|
||||
the License, or (at your option) any later version.
|
||||
|
||||
NeoPixel is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with NeoPixel. If not, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
--------------------------------------------------------------------*/
|
||||
|
||||
#ifndef ADAFRUIT_NEOPIXEL_H
|
||||
#define ADAFRUIT_NEOPIXEL_H
|
||||
|
||||
#if (ARDUINO >= 100)
|
||||
#include <Arduino.h>
|
||||
#else
|
||||
#include <WProgram.h>
|
||||
#include <pins_arduino.h>
|
||||
#endif
|
||||
|
||||
// 'type' flags for LED pixels (third parameter to constructor):
|
||||
#define NEO_RGB 0x00 // Wired for RGB data order
|
||||
#define NEO_GRB 0x01 // Wired for GRB data order
|
||||
#define NEO_BRG 0x04
|
||||
|
||||
#define NEO_COLMASK 0x01
|
||||
#define NEO_KHZ800 0x02 // 800 KHz datastream
|
||||
#define NEO_SPDMASK 0x02
|
||||
// Trinket flash space is tight, v1 NeoPixels aren't handled by default.
|
||||
// Remove the ifndef/endif to add support -- but code will be bigger.
|
||||
// Conversely, can comment out the #defines to save space on other MCUs.
|
||||
#ifndef __AVR_ATtiny85__
|
||||
#define NEO_KHZ400 0x00 // 400 KHz datastream
|
||||
#endif
|
||||
|
||||
class Adafruit_NeoPixel {
|
||||
|
||||
public:
|
||||
|
||||
// Constructor: number of LEDs, pin number, LED type
|
||||
Adafruit_NeoPixel(uint16_t n, uint8_t p=6, uint8_t t=NEO_GRB + NEO_KHZ800);
|
||||
~Adafruit_NeoPixel();
|
||||
|
||||
void
|
||||
begin(void),
|
||||
show(void),
|
||||
setPin(uint8_t p),
|
||||
setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b),
|
||||
setPixelColor(uint16_t n, uint32_t c),
|
||||
setBrightness(uint8_t),
|
||||
clear();
|
||||
uint8_t
|
||||
*getPixels(void) const,
|
||||
getBrightness(void) const;
|
||||
uint16_t
|
||||
numPixels(void) const;
|
||||
static uint32_t
|
||||
Color(uint8_t r, uint8_t g, uint8_t b);
|
||||
uint32_t
|
||||
getPixelColor(uint16_t n) const;
|
||||
inline bool
|
||||
canShow(void) { return (micros() - endTime) >= 50L; }
|
||||
|
||||
private:
|
||||
|
||||
const uint16_t
|
||||
numLEDs, // Number of RGB LEDs in strip
|
||||
numBytes; // Size of 'pixels' buffer below
|
||||
uint8_t
|
||||
pin, // Output pin number
|
||||
brightness,
|
||||
*pixels, // Holds LED color values (3 bytes each)
|
||||
rOffset, // Index of red byte within each 3-byte pixel
|
||||
gOffset, // Index of green byte
|
||||
bOffset; // Index of blue byte
|
||||
const uint8_t
|
||||
type; // Pixel flags (400 vs 800 KHz, RGB vs GRB color)
|
||||
uint32_t
|
||||
endTime; // Latch timing reference
|
||||
#ifdef __AVR__
|
||||
const volatile uint8_t
|
||||
*port; // Output PORT register
|
||||
uint8_t
|
||||
pinMask; // Output PORT bitmask
|
||||
#endif
|
||||
|
||||
};
|
||||
|
||||
#endif // ADAFRUIT_NEOPIXEL_H
|
||||
Executable
+794
@@ -0,0 +1,794 @@
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
|
||||
|
||||
LGPL ADDENDUM:
|
||||
|
||||
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
Executable
+12
@@ -0,0 +1,12 @@
|
||||
Adafruit NeoPixel library
|
||||
=========================
|
||||
|
||||
Arduino library for controlling single-wire-based LED pixels and strip such as the [Adafruit 60 LED/meter Digital LED strip][strip], the [Adafruit FLORA RGB Smart Pixel][flora], the [Adafruit Breadboard-friendly RGB Smart Pixel][pixel], the [Adafruit NeoPixel Stick][stick], and the [Adafruit NeoPixel Shield][shield].
|
||||
|
||||
After downloading, rename folder to 'Adafruit_NeoPixel' and install in Arduino Libraries folder. Restart Arduino IDE, then open File->Sketchbook->Library->Adafruit_NeoPixel->strandtest sketch.
|
||||
|
||||
[flora]: http://adafruit.com/products/1060
|
||||
[strip]: http://adafruit.com/products/1138
|
||||
[pixel]: http://adafruit.com/products/1312
|
||||
[stick]: http://adafruit.com/products/1426
|
||||
[shield]: http://adafruit.com/products/1430
|
||||
@@ -0,0 +1,165 @@
|
||||
// This is a demonstration on how to use an input device to trigger changes on your neo pixels.
|
||||
// You should wire a momentary push button to connect from ground to a digital IO pin. When you
|
||||
// press the button it will change to a new pixel animation. Note that you need to press the
|
||||
// button once to start the first animation!
|
||||
|
||||
#include <Adafruit_NeoPixel.h>
|
||||
|
||||
#define BUTTON_PIN 2 // Digital IO pin connected to the button. This will be
|
||||
// driven with a pull-up resistor so the switch should
|
||||
// pull the pin to ground momentarily. On a high -> low
|
||||
// transition the button press logic will execute.
|
||||
|
||||
#define PIXEL_PIN 6 // Digital IO pin connected to the NeoPixels.
|
||||
|
||||
#define PIXEL_COUNT 16
|
||||
|
||||
// Parameter 1 = number of pixels in strip, neopixel stick has 8
|
||||
// Parameter 2 = pin number (most are valid)
|
||||
// Parameter 3 = pixel type flags, add together as needed:
|
||||
// NEO_RGB Pixels are wired for RGB bitstream
|
||||
// NEO_GRB Pixels are wired for GRB bitstream, correct for neopixel stick
|
||||
// NEO_KHZ400 400 KHz bitstream (e.g. FLORA pixels)
|
||||
// NEO_KHZ800 800 KHz bitstream (e.g. High Density LED strip), correct for neopixel stick
|
||||
Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL_COUNT, PIXEL_PIN, NEO_GRB + NEO_KHZ800);
|
||||
|
||||
bool oldState = HIGH;
|
||||
int showType = 0;
|
||||
|
||||
void setup() {
|
||||
pinMode(BUTTON_PIN, INPUT_PULLUP);
|
||||
strip.begin();
|
||||
strip.show(); // Initialize all pixels to 'off'
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// Get current button state.
|
||||
bool newState = digitalRead(BUTTON_PIN);
|
||||
|
||||
// Check if state changed from high to low (button press).
|
||||
if (newState == LOW && oldState == HIGH) {
|
||||
// Short delay to debounce button.
|
||||
delay(20);
|
||||
// Check if button is still low after debounce.
|
||||
newState = digitalRead(BUTTON_PIN);
|
||||
if (newState == LOW) {
|
||||
showType++;
|
||||
if (showType > 9)
|
||||
showType=0;
|
||||
startShow(showType);
|
||||
}
|
||||
}
|
||||
|
||||
// Set the last button state to the old state.
|
||||
oldState = newState;
|
||||
}
|
||||
|
||||
void startShow(int i) {
|
||||
switch(i){
|
||||
case 0: colorWipe(strip.Color(0, 0, 0), 50); // Black/off
|
||||
break;
|
||||
case 1: colorWipe(strip.Color(255, 0, 0), 50); // Red
|
||||
break;
|
||||
case 2: colorWipe(strip.Color(0, 255, 0), 50); // Green
|
||||
break;
|
||||
case 3: colorWipe(strip.Color(0, 0, 255), 50); // Blue
|
||||
break;
|
||||
case 4: theaterChase(strip.Color(127, 127, 127), 50); // White
|
||||
break;
|
||||
case 5: theaterChase(strip.Color(127, 0, 0), 50); // Red
|
||||
break;
|
||||
case 6: theaterChase(strip.Color( 0, 0, 127), 50); // Blue
|
||||
break;
|
||||
case 7: rainbow(20);
|
||||
break;
|
||||
case 8: rainbowCycle(20);
|
||||
break;
|
||||
case 9: theaterChaseRainbow(50);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Fill the dots one after the other with a color
|
||||
void colorWipe(uint32_t c, uint8_t wait) {
|
||||
for(uint16_t i=0; i<strip.numPixels(); i++) {
|
||||
strip.setPixelColor(i, c);
|
||||
strip.show();
|
||||
delay(wait);
|
||||
}
|
||||
}
|
||||
|
||||
void rainbow(uint8_t wait) {
|
||||
uint16_t i, j;
|
||||
|
||||
for(j=0; j<256; j++) {
|
||||
for(i=0; i<strip.numPixels(); i++) {
|
||||
strip.setPixelColor(i, Wheel((i+j) & 255));
|
||||
}
|
||||
strip.show();
|
||||
delay(wait);
|
||||
}
|
||||
}
|
||||
|
||||
// Slightly different, this makes the rainbow equally distributed throughout
|
||||
void rainbowCycle(uint8_t wait) {
|
||||
uint16_t i, j;
|
||||
|
||||
for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
|
||||
for(i=0; i< strip.numPixels(); i++) {
|
||||
strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
|
||||
}
|
||||
strip.show();
|
||||
delay(wait);
|
||||
}
|
||||
}
|
||||
|
||||
//Theatre-style crawling lights.
|
||||
void theaterChase(uint32_t c, uint8_t wait) {
|
||||
for (int j=0; j<10; j++) { //do 10 cycles of chasing
|
||||
for (int q=0; q < 3; q++) {
|
||||
for (int i=0; i < strip.numPixels(); i=i+3) {
|
||||
strip.setPixelColor(i+q, c); //turn every third pixel on
|
||||
}
|
||||
strip.show();
|
||||
|
||||
delay(wait);
|
||||
|
||||
for (int i=0; i < strip.numPixels(); i=i+3) {
|
||||
strip.setPixelColor(i+q, 0); //turn every third pixel off
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Theatre-style crawling lights with rainbow effect
|
||||
void theaterChaseRainbow(uint8_t wait) {
|
||||
for (int j=0; j < 256; j++) { // cycle all 256 colors in the wheel
|
||||
for (int q=0; q < 3; q++) {
|
||||
for (int i=0; i < strip.numPixels(); i=i+3) {
|
||||
strip.setPixelColor(i+q, Wheel( (i+j) % 255)); //turn every third pixel on
|
||||
}
|
||||
strip.show();
|
||||
|
||||
delay(wait);
|
||||
|
||||
for (int i=0; i < strip.numPixels(); i=i+3) {
|
||||
strip.setPixelColor(i+q, 0); //turn every third pixel off
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Input a value 0 to 255 to get a color value.
|
||||
// The colours are a transition r - g - b - back to r.
|
||||
uint32_t Wheel(byte WheelPos) {
|
||||
WheelPos = 255 - WheelPos;
|
||||
if(WheelPos < 85) {
|
||||
return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
|
||||
} else if(WheelPos < 170) {
|
||||
WheelPos -= 85;
|
||||
return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
|
||||
} else {
|
||||
WheelPos -= 170;
|
||||
return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
// NeoPixel Ring simple sketch (c) 2013 Shae Erisson
|
||||
// released under the GPLv3 license to match the rest of the AdaFruit NeoPixel library
|
||||
|
||||
#include <Adafruit_NeoPixel.h>
|
||||
#include <avr/power.h>
|
||||
|
||||
// Which pin on the Arduino is connected to the NeoPixels?
|
||||
// On a Trinket or Gemma we suggest changing this to 1
|
||||
#define PIN 6
|
||||
|
||||
// How many NeoPixels are attached to the Arduino?
|
||||
#define NUMPIXELS 16
|
||||
|
||||
// When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
|
||||
// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
|
||||
// example for more information on possible values.
|
||||
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
|
||||
|
||||
int delayval = 500; // delay for half a second
|
||||
|
||||
void setup() {
|
||||
// This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
|
||||
#if defined (__AVR_ATtiny85__)
|
||||
if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
|
||||
#endif
|
||||
// End of trinket special code
|
||||
|
||||
pixels.begin(); // This initializes the NeoPixel library.
|
||||
}
|
||||
|
||||
void loop() {
|
||||
|
||||
// For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.
|
||||
|
||||
for(int i=0;i<NUMPIXELS;i++){
|
||||
|
||||
// pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
|
||||
pixels.setPixelColor(i, pixels.Color(0,150,0)); // Moderately bright green color.
|
||||
|
||||
pixels.show(); // This sends the updated pixel color to the hardware.
|
||||
|
||||
delay(delayval); // Delay for a period of time (in milliseconds).
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
#include <Adafruit_NeoPixel.h>
|
||||
#include <avr/power.h>
|
||||
|
||||
#define PIN 6
|
||||
|
||||
// Parameter 1 = number of pixels in strip
|
||||
// Parameter 2 = Arduino pin number (most are valid)
|
||||
// Parameter 3 = pixel type flags, add together as needed:
|
||||
// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
|
||||
// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
|
||||
// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products)
|
||||
// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
|
||||
Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, PIN, NEO_GRB + NEO_KHZ800);
|
||||
|
||||
// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
|
||||
// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input
|
||||
// and minimize distance between Arduino and first pixel. Avoid connecting
|
||||
// on a live circuit...if you must, connect GND first.
|
||||
|
||||
void setup() {
|
||||
// This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
|
||||
#if defined (__AVR_ATtiny85__)
|
||||
if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
|
||||
#endif
|
||||
// End of trinket special code
|
||||
|
||||
|
||||
strip.begin();
|
||||
strip.show(); // Initialize all pixels to 'off'
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// Some example procedures showing how to display to the pixels:
|
||||
colorWipe(strip.Color(255, 0, 0), 50); // Red
|
||||
colorWipe(strip.Color(0, 255, 0), 50); // Green
|
||||
colorWipe(strip.Color(0, 0, 255), 50); // Blue
|
||||
// Send a theater pixel chase in...
|
||||
theaterChase(strip.Color(127, 127, 127), 50); // White
|
||||
theaterChase(strip.Color(127, 0, 0), 50); // Red
|
||||
theaterChase(strip.Color( 0, 0, 127), 50); // Blue
|
||||
|
||||
rainbow(20);
|
||||
rainbowCycle(20);
|
||||
theaterChaseRainbow(50);
|
||||
}
|
||||
|
||||
// Fill the dots one after the other with a color
|
||||
void colorWipe(uint32_t c, uint8_t wait) {
|
||||
for(uint16_t i=0; i<strip.numPixels(); i++) {
|
||||
strip.setPixelColor(i, c);
|
||||
strip.show();
|
||||
delay(wait);
|
||||
}
|
||||
}
|
||||
|
||||
void rainbow(uint8_t wait) {
|
||||
uint16_t i, j;
|
||||
|
||||
for(j=0; j<256; j++) {
|
||||
for(i=0; i<strip.numPixels(); i++) {
|
||||
strip.setPixelColor(i, Wheel((i+j) & 255));
|
||||
}
|
||||
strip.show();
|
||||
delay(wait);
|
||||
}
|
||||
}
|
||||
|
||||
// Slightly different, this makes the rainbow equally distributed throughout
|
||||
void rainbowCycle(uint8_t wait) {
|
||||
uint16_t i, j;
|
||||
|
||||
for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
|
||||
for(i=0; i< strip.numPixels(); i++) {
|
||||
strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
|
||||
}
|
||||
strip.show();
|
||||
delay(wait);
|
||||
}
|
||||
}
|
||||
|
||||
//Theatre-style crawling lights.
|
||||
void theaterChase(uint32_t c, uint8_t wait) {
|
||||
for (int j=0; j<10; j++) { //do 10 cycles of chasing
|
||||
for (int q=0; q < 3; q++) {
|
||||
for (int i=0; i < strip.numPixels(); i=i+3) {
|
||||
strip.setPixelColor(i+q, c); //turn every third pixel on
|
||||
}
|
||||
strip.show();
|
||||
|
||||
delay(wait);
|
||||
|
||||
for (int i=0; i < strip.numPixels(); i=i+3) {
|
||||
strip.setPixelColor(i+q, 0); //turn every third pixel off
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Theatre-style crawling lights with rainbow effect
|
||||
void theaterChaseRainbow(uint8_t wait) {
|
||||
for (int j=0; j < 256; j++) { // cycle all 256 colors in the wheel
|
||||
for (int q=0; q < 3; q++) {
|
||||
for (int i=0; i < strip.numPixels(); i=i+3) {
|
||||
strip.setPixelColor(i+q, Wheel( (i+j) % 255)); //turn every third pixel on
|
||||
}
|
||||
strip.show();
|
||||
|
||||
delay(wait);
|
||||
|
||||
for (int i=0; i < strip.numPixels(); i=i+3) {
|
||||
strip.setPixelColor(i+q, 0); //turn every third pixel off
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Input a value 0 to 255 to get a color value.
|
||||
// The colours are a transition r - g - b - back to r.
|
||||
uint32_t Wheel(byte WheelPos) {
|
||||
WheelPos = 255 - WheelPos;
|
||||
if(WheelPos < 85) {
|
||||
return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
|
||||
} else if(WheelPos < 170) {
|
||||
WheelPos -= 85;
|
||||
return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
|
||||
} else {
|
||||
WheelPos -= 170;
|
||||
return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
|
||||
}
|
||||
}
|
||||
|
||||
Executable
+29
@@ -0,0 +1,29 @@
|
||||
#######################################
|
||||
# Syntax Coloring Map For Adafruit_NeoPixel
|
||||
#######################################
|
||||
# Class
|
||||
#######################################
|
||||
|
||||
Adafruit_NeoPixel KEYWORD1
|
||||
|
||||
#######################################
|
||||
# Methods and Functions
|
||||
#######################################
|
||||
|
||||
setPixelColor KEYWORD2
|
||||
setPin KEYWORD2
|
||||
setBrightness KEYWORD2
|
||||
numPixels KEYWORD2
|
||||
getPixelColor KEYWORD2
|
||||
Color KEYWORD2
|
||||
|
||||
#######################################
|
||||
# Constants
|
||||
#######################################
|
||||
|
||||
NEO_GRB LITERAL1
|
||||
NEO_COLMASK LITERAL1
|
||||
NEO_KHZ800 LITERAL1
|
||||
NEO_SPDMASK LITERAL1
|
||||
NEO_RGB LITERAL1
|
||||
NEO_KHZ400 LITERAL1
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
name=Adafruit NeoPixel
|
||||
version=1.0
|
||||
author=Adafruit
|
||||
maintainer=Adafruit <info@adafruit.com>
|
||||
sentence=Arduino library for controlling single-wire-based LED pixels and strip.
|
||||
paragraph=Arduino library for controlling single-wire-based LED pixels and strip.
|
||||
category=Display
|
||||
url=https://github.com/adafruit/Adafruit_NeoPixel
|
||||
architectures=*
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,8 @@
|
||||
#ifndef DallasTemperature_h
|
||||
#define DallasTemperature_h
|
||||
|
||||
#define DALLASTEMPLIBVERSION "3.7.2"
|
||||
|
||||
// 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
|
||||
@@ -20,9 +22,10 @@
|
||||
#include <OneWire.h>
|
||||
|
||||
// Model IDs
|
||||
#define DS18S20MODEL 0x10
|
||||
#define DS18S20MODEL 0x10 // also DS1820
|
||||
#define DS18B20MODEL 0x28
|
||||
#define DS1822MODEL 0x22
|
||||
#define DS1825MODEL 0x3B
|
||||
|
||||
// OneWire commands
|
||||
#define STARTCONVO 0x44 // Tells device to take a temperature reading and put it on the scratchpad
|
||||
@@ -51,7 +54,9 @@
|
||||
#define TEMP_12_BIT 0x7F // 12 bit
|
||||
|
||||
// Error Codes
|
||||
#define DEVICE_DISCONNECTED -127
|
||||
#define DEVICE_DISCONNECTED_C -127
|
||||
#define DEVICE_DISCONNECTED_F -196.6
|
||||
#define DEVICE_DISCONNECTED_RAW -7040
|
||||
|
||||
typedef uint8_t DeviceAddress[8];
|
||||
|
||||
@@ -61,54 +66,74 @@ class DallasTemperature
|
||||
|
||||
DallasTemperature(OneWire*);
|
||||
|
||||
// initalize bus
|
||||
// initialise bus
|
||||
void begin(void);
|
||||
|
||||
// returns the number of devices found on the bus
|
||||
uint8_t getDeviceCount(void);
|
||||
|
||||
// returns true if address is valid
|
||||
bool validAddress(uint8_t*);
|
||||
bool validAddress(const uint8_t*);
|
||||
|
||||
// finds an address at a given index on the bus
|
||||
bool getAddress(uint8_t*, const uint8_t);
|
||||
bool getAddress(uint8_t*, uint8_t);
|
||||
|
||||
// attempt to determine if the device at the given address is connected to the bus
|
||||
bool isConnected(uint8_t*);
|
||||
bool isConnected(const uint8_t*);
|
||||
|
||||
// attempt to determine if the device at the given address is connected to the bus
|
||||
// also allows for updating the read scratchpad
|
||||
bool isConnected(uint8_t*, uint8_t*);
|
||||
bool isConnected(const uint8_t*, uint8_t*);
|
||||
|
||||
// read device's scratchpad
|
||||
void readScratchPad(uint8_t*, uint8_t*);
|
||||
void readScratchPad(const uint8_t*, uint8_t*);
|
||||
|
||||
// write device's scratchpad
|
||||
void writeScratchPad(uint8_t*, const uint8_t*);
|
||||
void writeScratchPad(const uint8_t*, const uint8_t*);
|
||||
|
||||
// read device's power requirements
|
||||
bool readPowerSupply(uint8_t*);
|
||||
bool readPowerSupply(const uint8_t*);
|
||||
|
||||
// returns the current resolution, 9-12
|
||||
uint8_t getResolution(uint8_t*);
|
||||
// get global resolution
|
||||
uint8_t getResolution();
|
||||
|
||||
// set global resolution to 9, 10, 11, or 12 bits
|
||||
void setResolution(uint8_t);
|
||||
|
||||
// returns the device resolution: 9, 10, 11, or 12 bits
|
||||
uint8_t getResolution(const uint8_t*);
|
||||
|
||||
// set resolution of a device to 9, 10, 11, or 12 bits
|
||||
void setResolution(uint8_t*, uint8_t);
|
||||
|
||||
// sends command for all devices on the bus to perform a temperature conversion
|
||||
bool setResolution(const uint8_t*, uint8_t);
|
||||
|
||||
// sets/gets the waitForConversion flag
|
||||
void setWaitForConversion(bool);
|
||||
bool getWaitForConversion(void);
|
||||
|
||||
// sets/gets the checkForConversion flag
|
||||
void setCheckForConversion(bool);
|
||||
bool getCheckForConversion(void);
|
||||
|
||||
// sends command for all devices on the bus to perform a temperature conversion
|
||||
void requestTemperatures(void);
|
||||
|
||||
|
||||
// returns time to wait for a temperature conversion based on given resolution
|
||||
int16_t millisToWaitForConversion(uint8_t);
|
||||
|
||||
// sends command for one device to perform a temperature conversion by address
|
||||
void requestTemperaturesByAddress(uint8_t*);
|
||||
bool requestTemperaturesByAddress(const uint8_t*);
|
||||
|
||||
// sends command for one device to perform a temperature conversion by index
|
||||
void requestTemperaturesByIndex(uint8_t);
|
||||
bool requestTemperaturesByIndex(uint8_t);
|
||||
|
||||
// returns temperature raw value (12 bit integer of 1/16 degrees C)
|
||||
int16_t getTemp(const uint8_t*);
|
||||
|
||||
// returns temperature in degrees C
|
||||
float getTempC(uint8_t*);
|
||||
float getTempC(const uint8_t*);
|
||||
|
||||
// returns temperature in degrees F
|
||||
float getTempF(uint8_t*);
|
||||
float getTempF(const uint8_t*);
|
||||
|
||||
// Get temperature for device index (slow)
|
||||
float getTempCByIndex(uint8_t);
|
||||
@@ -118,26 +143,28 @@ class DallasTemperature
|
||||
|
||||
// returns true if the bus requires parasite power
|
||||
bool isParasitePowerMode(void);
|
||||
|
||||
bool isConversionAvailable(const uint8_t*);
|
||||
|
||||
#if REQUIRESALARMS
|
||||
|
||||
typedef void AlarmHandler(uint8_t*);
|
||||
typedef void AlarmHandler(const uint8_t*);
|
||||
|
||||
// sets the high alarm temperature for a device
|
||||
// accepts a char. valid range is -55C - 125C
|
||||
void setHighAlarmTemp(uint8_t*, const char);
|
||||
void setHighAlarmTemp(const uint8_t*, char);
|
||||
|
||||
// sets the low alarm temperature for a device
|
||||
// accepts a char. valid range is -55C - 125C
|
||||
void setLowAlarmTemp(uint8_t*, const char);
|
||||
void setLowAlarmTemp(const uint8_t*, char);
|
||||
|
||||
// returns a signed char with the current high alarm temperature for a device
|
||||
// in the range -55C - 125C
|
||||
char getHighAlarmTemp(uint8_t*);
|
||||
char getHighAlarmTemp(const uint8_t*);
|
||||
|
||||
// returns a signed char with the current low alarm temperature for a device
|
||||
// in the range -55C - 125C
|
||||
char getLowAlarmTemp(uint8_t*);
|
||||
char getLowAlarmTemp(const uint8_t*);
|
||||
|
||||
// resets internal variables used for the alarm search
|
||||
void resetAlarmSearch(void);
|
||||
@@ -146,7 +173,7 @@ class DallasTemperature
|
||||
bool alarmSearch(uint8_t*);
|
||||
|
||||
// returns true if ia specific device has an alarm
|
||||
bool hasAlarm(uint8_t*);
|
||||
bool hasAlarm(const uint8_t*);
|
||||
|
||||
// returns true if any device is reporting an alarm on the bus
|
||||
bool hasAlarm(void);
|
||||
@@ -155,22 +182,28 @@ class DallasTemperature
|
||||
void processAlarms(void);
|
||||
|
||||
// sets the alarm handler
|
||||
void setAlarmHandler(AlarmHandler *);
|
||||
void setAlarmHandler(const AlarmHandler *);
|
||||
|
||||
// The default alarm handler
|
||||
static void defaultAlarmHandler(uint8_t*);
|
||||
static void defaultAlarmHandler(const uint8_t*);
|
||||
|
||||
#endif
|
||||
|
||||
// convert from celcius to farenheit
|
||||
static float toFahrenheit(const float);
|
||||
// convert from Celsius to Fahrenheit
|
||||
static float toFahrenheit(float);
|
||||
|
||||
// convert from farenheit to celsius
|
||||
static float toCelsius(const float);
|
||||
// convert from Fahrenheit to Celsius
|
||||
static float toCelsius(float);
|
||||
|
||||
// convert from raw to Celsius
|
||||
static float rawToCelsius(int16_t);
|
||||
|
||||
// convert from raw to Fahrenheit
|
||||
static float rawToFahrenheit(int16_t);
|
||||
|
||||
#if REQUIRESNEW
|
||||
|
||||
// initalize memory area
|
||||
// initialize memory area
|
||||
void* operator new (unsigned int);
|
||||
|
||||
// delete memory reference
|
||||
@@ -186,16 +219,24 @@ class DallasTemperature
|
||||
|
||||
// used to determine the delay amount needed to allow for the
|
||||
// temperature conversion to take place
|
||||
int conversionDelay;
|
||||
|
||||
uint8_t bitResolution;
|
||||
|
||||
// used to requestTemperature with or without delay
|
||||
bool waitForConversion;
|
||||
|
||||
// used to requestTemperature to dynamically check if a conversion is complete
|
||||
bool checkForConversion;
|
||||
|
||||
// count of devices on the bus
|
||||
uint8_t devices;
|
||||
|
||||
// Take a pointer to one wire instance
|
||||
OneWire* _wire;
|
||||
|
||||
// reads scratchpad and returns the temperature in degrees C
|
||||
float calculateTemperature(uint8_t*, uint8_t*);
|
||||
// reads scratchpad and returns the raw temperature
|
||||
int16_t calculateTemperature(const uint8_t*, uint8_t*);
|
||||
|
||||
void blockTillConversionComplete(uint8_t, const uint8_t*);
|
||||
|
||||
#if REQUIRESALARMS
|
||||
|
||||
|
||||
@@ -4,10 +4,14 @@ Arduino Library for Dallas Temperature ICs
|
||||
Usage
|
||||
-----
|
||||
|
||||
This library supports the following devices:
|
||||
DS18B20
|
||||
DS18S20 - Please note there appears to be an issue with this series.
|
||||
DS1822
|
||||
This library supports the following devices :
|
||||
|
||||
|
||||
* DS18B20
|
||||
* DS18S20 - Please note there appears to be an issue with this series.
|
||||
* DS1822
|
||||
* DS1820
|
||||
|
||||
|
||||
You will need a pull-up resistor of about 5 KOhm between the 1-Wire data line
|
||||
and your 5V power. If you are using the DS18B20, ground pins 1 and 3. The
|
||||
@@ -15,7 +19,18 @@ centre pin is the data line '1-wire'.
|
||||
|
||||
We have included a "REQUIRESNEW" and "REQUIRESALARMS" definition. If you
|
||||
want to slim down the code feel free to use either of these by including
|
||||
#define REQUIRESNEW or #define REQUIRESALARMS a the top of DallasTemperature.h
|
||||
|
||||
|
||||
|
||||
#define REQUIRESNEW
|
||||
|
||||
or
|
||||
|
||||
#define REQUIRESALARMS
|
||||
|
||||
|
||||
at the top of DallasTemperature.h
|
||||
|
||||
|
||||
Credits
|
||||
-------
|
||||
@@ -26,6 +41,8 @@ Miles Burton <miles@mnetcs.com> originally developed this library.
|
||||
Tim Newsome <nuisance@casualhacker.net> added support for multiple sensors on
|
||||
the same bus.
|
||||
Guil Barros [gfbarros@bappos.com] added getTempByAddress (v3.5)
|
||||
Rob Tillaart [rob.tillaart@gmail.com] added async modus (v3.7.0)
|
||||
|
||||
|
||||
Website
|
||||
-------
|
||||
@@ -0,0 +1,85 @@
|
||||
|
||||
This file contains the change history of the Dallas Temperature Control Library.
|
||||
|
||||
VERSION 3.7.2 BETA
|
||||
===================
|
||||
DATE: 6 DEC 2011
|
||||
|
||||
- Jordan Hochenbaum [jhochenbaum@gmail.com] updated library for compatibility with Arduino 1.0.
|
||||
|
||||
VERSION 3.7.0 BETA
|
||||
===================
|
||||
DATE: 11 JAN 2011
|
||||
|
||||
- Rob Tillaart [rob.tillaart@gmail.com] added async modus (v3.7.0)
|
||||
The library is backwards compatible with version 3.6.0
|
||||
|
||||
MAJOR: async modus
|
||||
------------------
|
||||
- Added - private bool waitForConversion.
|
||||
This boolean is default set to true in the Constructor to keep the library backwards compatible. If this flag is true calls to requestTemperatures(), requestTemperaturesByAddress() et al, will be blocking with the appropiate time specified (in datasheet) for the resolution used. If the flag is set to false, requestTemperatures() et al, will return immediately after the conversion command is send over the 1-wire interface. The programmer is responsible to wait long enough before reading the temperature values. This enables the application to do other things while waiting for a new reading, like calculations, update LCD, read/write other IO lines etc. See examples.
|
||||
|
||||
- Added - void setWaitForConversion(bool);
|
||||
To set the flag to true or false, depending on the modus needed.
|
||||
|
||||
- Added - bool getWaitForConversion(void);
|
||||
To get the current value of the flag.
|
||||
|
||||
- Changed - void requestTemperatures(void);
|
||||
Added a test (false == waitForConversion) to return immediately after the conversion command instead of waiting until the conversion is ready.
|
||||
|
||||
- Changed - bool requestTemperaturesByAddress(uint8_t*);
|
||||
Added a test (false == waitForConversion) to return immediately after the conversion command instead of waiting until the conversion is ready.
|
||||
|
||||
|
||||
MINOR version number
|
||||
--------------------
|
||||
- Added - #define DALLASTEMPLIBVERSION "3.7.0"
|
||||
To indicate the version number in .h file
|
||||
|
||||
|
||||
MINOR internal var bitResolution
|
||||
----------------------------
|
||||
- Changed - private int conversionDelay - is renamed to - private int bitResolution
|
||||
As this variable holds the resolution. The delay for the conversion is derived from it.
|
||||
|
||||
- Changed - uint8_t getResolution(uint8_t* deviceAddress);
|
||||
If the device is not connected, it returns 0, otherwise it returns the resolution of the device.
|
||||
|
||||
- Changed - bool setResolution(uint8_t* deviceAddress, uint8_t newResolution);
|
||||
If the device is not connected, it returns FALSE (fail), otherwise it returns TRUE (succes).
|
||||
|
||||
- Added - uint8_t getResolution();
|
||||
Returns bitResolution.
|
||||
|
||||
- Added - void setResolution(uint8_t newResolution)
|
||||
Sets the internal variable bitResolution, and all devices to this value
|
||||
|
||||
|
||||
MINOR check connected state
|
||||
----------------------------
|
||||
- Changed - bool requestTemperaturesByIndex(deviceIndex)
|
||||
Changed return type from void to bool. The function returns false if the device identified with [deviceIndex] is not found on the bus and true otherwise.
|
||||
|
||||
- Changed - bool requestTemperaturesByAddress(deviceAddress)
|
||||
Changed return type from void to bool. The function returns false if the device identified with [deviceAddress] is not found on the bus and true otherwise.
|
||||
Added code to handle the DS18S20 which has a 9 bit resolution separately.
|
||||
Changed code so the blocking delay matches the bitResolution set in the device with deviceAddress.
|
||||
|
||||
- Changed - bool requestTemperaturesByIndex(uint8_t deviceIndex)
|
||||
Changed return type from void to bool. The function returns false if the device identified with [deviceIndex] is not found on the bus and true otherwise.
|
||||
|
||||
|
||||
|
||||
VERSION 3.6.0
|
||||
==============
|
||||
DATE: 2010-10-10
|
||||
|
||||
- no detailed change history known except:
|
||||
|
||||
- The OneWire code has been derived from
|
||||
http://www.arduino.cc/playground/Learning/OneWire.
|
||||
- Miles Burton <miles@mnetcs.com> originally developed this library.
|
||||
- Tim Newsome <nuisance@casualhacker.net> added support for multiple sensors on
|
||||
the same bus.
|
||||
- Guil Barros [gfbarros@bappos.com] added getTempByAddress (v3.5)
|
||||
@@ -2,7 +2,7 @@
|
||||
#include <DallasTemperature.h>
|
||||
|
||||
// Data wire is plugged into port 2 on the Arduino
|
||||
#define ONE_WIRE_BUS 3
|
||||
#define ONE_WIRE_BUS 2
|
||||
|
||||
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
|
||||
OneWire oneWire(ONE_WIRE_BUS);
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
#include <DallasTemperature.h>
|
||||
|
||||
// Data wire is plugged into port 2 on the Arduino
|
||||
#define ONE_WIRE_BUS 3
|
||||
#define TEMPERATURE_PRECISION 9
|
||||
#define ONE_WIRE_BUS 2
|
||||
|
||||
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
|
||||
OneWire oneWire(ONE_WIRE_BUS);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
#include <DallasTemperature.h>
|
||||
|
||||
// Data wire is plugged into port 2 on the Arduino
|
||||
#define ONE_WIRE_BUS 3
|
||||
#define ONE_WIRE_BUS 2
|
||||
#define TEMPERATURE_PRECISION 9
|
||||
|
||||
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
|
||||
@@ -74,8 +74,8 @@ void setup(void)
|
||||
Serial.println();
|
||||
|
||||
// set the resolution to 9 bit
|
||||
sensors.setResolution(insideThermometer, 9);
|
||||
sensors.setResolution(outsideThermometer, 9);
|
||||
sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION);
|
||||
sensors.setResolution(outsideThermometer, TEMPERATURE_PRECISION);
|
||||
|
||||
Serial.print("Device 0 Resolution: ");
|
||||
Serial.print(sensors.getResolution(insideThermometer), DEC);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
#include <DallasTemperature.h>
|
||||
|
||||
// Data wire is plugged into port 2 on the Arduino
|
||||
#define ONE_WIRE_BUS 3
|
||||
#define ONE_WIRE_BUS 2
|
||||
|
||||
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
|
||||
OneWire oneWire(ONE_WIRE_BUS);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
#include <DallasTemperature.h>
|
||||
|
||||
// Data wire is plugged into port 2 on the Arduino
|
||||
#define ONE_WIRE_BUS 3
|
||||
#define ONE_WIRE_BUS 2
|
||||
#define TEMPERATURE_PRECISION 9
|
||||
|
||||
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
|
||||
@@ -52,9 +52,9 @@ void setup(void)
|
||||
Serial.println();
|
||||
|
||||
Serial.print("Setting resolution to ");
|
||||
Serial.println(TEMPERATURE_PRECISION,DEC);
|
||||
Serial.println(TEMPERATURE_PRECISION, DEC);
|
||||
|
||||
// set the resolution to 9 bit (Each Dallas/Maxim device is capable of several different resolutions)
|
||||
// set the resolution to TEMPERATURE_PRECISION bit (Each Dallas/Maxim device is capable of several different resolutions)
|
||||
sensors.setResolution(tempDeviceAddress, TEMPERATURE_PRECISION);
|
||||
|
||||
Serial.print("Resolution actually set to: ");
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
#include <OneWire.h>
|
||||
#include <DallasTemperature.h>
|
||||
|
||||
// Data wire is plugged into port 2 on the Arduino
|
||||
#define ONE_WIRE_BUS 2
|
||||
|
||||
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
|
||||
OneWire oneWire(ONE_WIRE_BUS);
|
||||
|
||||
// Pass our oneWire reference to Dallas Temperature.
|
||||
DallasTemperature sensors(&oneWire);
|
||||
|
||||
void setup(void)
|
||||
{
|
||||
// start serial port
|
||||
Serial.begin(115200);
|
||||
Serial.println("Dallas Temperature Control Library - Async Demo");
|
||||
Serial.println("\nDemo shows the difference in length of the call\n\n");
|
||||
|
||||
// Start up the library
|
||||
sensors.begin();
|
||||
}
|
||||
|
||||
void loop(void)
|
||||
{
|
||||
// Request temperature conversion (traditional)
|
||||
Serial.println("Before blocking requestForConversion");
|
||||
unsigned long start = millis();
|
||||
|
||||
sensors.requestTemperatures();
|
||||
|
||||
unsigned long stop = millis();
|
||||
Serial.println("After blocking requestForConversion");
|
||||
Serial.print("Time used: ");
|
||||
Serial.println(stop - start);
|
||||
|
||||
// get temperature
|
||||
Serial.print("Temperature: ");
|
||||
Serial.println(sensors.getTempCByIndex(0));
|
||||
Serial.println("\n");
|
||||
|
||||
// Request temperature conversion - non-blocking / async
|
||||
Serial.println("Before NON-blocking/async requestForConversion");
|
||||
start = millis();
|
||||
sensors.setWaitForConversion(false); // makes it async
|
||||
sensors.requestTemperatures();
|
||||
sensors.setWaitForConversion(true);
|
||||
stop = millis();
|
||||
Serial.println("After NON-blocking/async requestForConversion");
|
||||
Serial.print("Time used: ");
|
||||
Serial.println(stop - start);
|
||||
|
||||
|
||||
// 9 bit resolution by default
|
||||
// Note the programmer is responsible for the right delay
|
||||
// we could do something usefull here instead of the delay
|
||||
int resolution = 9;
|
||||
delay(750/ (1 << (12-resolution)));
|
||||
|
||||
// get temperature
|
||||
Serial.print("Temperature: ");
|
||||
Serial.println(sensors.getTempCByIndex(0));
|
||||
Serial.println("\n\n\n\n");
|
||||
|
||||
delay(5000);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
//
|
||||
// Sample of using Async reading of Dallas Temperature Sensors
|
||||
//
|
||||
#include <OneWire.h>
|
||||
#include <DallasTemperature.h>
|
||||
|
||||
// Data wire is plugged into port 2 on the Arduino
|
||||
#define ONE_WIRE_BUS 2
|
||||
|
||||
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
|
||||
OneWire oneWire(ONE_WIRE_BUS);
|
||||
|
||||
// Pass our oneWire reference to Dallas Temperature.
|
||||
DallasTemperature sensors(&oneWire);
|
||||
|
||||
DeviceAddress tempDeviceAddress;
|
||||
|
||||
int resolution = 12;
|
||||
unsigned long lastTempRequest = 0;
|
||||
int delayInMillis = 0;
|
||||
float temperature = 0.0;
|
||||
int idle = 0;
|
||||
//
|
||||
// SETUP
|
||||
//
|
||||
void setup(void)
|
||||
{
|
||||
Serial.begin(115200);
|
||||
Serial.println("Dallas Temperature Control Library - Async Demo");
|
||||
Serial.print("Library Version: ");
|
||||
Serial.println(DALLASTEMPLIBVERSION);
|
||||
Serial.println("\n");
|
||||
|
||||
sensors.begin();
|
||||
sensors.getAddress(tempDeviceAddress, 0);
|
||||
sensors.setResolution(tempDeviceAddress, resolution);
|
||||
|
||||
sensors.setWaitForConversion(false);
|
||||
sensors.requestTemperatures();
|
||||
delayInMillis = 750 / (1 << (12 - resolution));
|
||||
lastTempRequest = millis();
|
||||
|
||||
pinMode(13, OUTPUT);
|
||||
}
|
||||
|
||||
void loop(void)
|
||||
{
|
||||
|
||||
if (millis() - lastTempRequest >= delayInMillis) // waited long enough??
|
||||
{
|
||||
digitalWrite(13, LOW);
|
||||
Serial.print(" Temperature: ");
|
||||
temperature = sensors.getTempCByIndex(0);
|
||||
Serial.println(temperature, resolution - 8);
|
||||
Serial.print(" Resolution: ");
|
||||
Serial.println(resolution);
|
||||
Serial.print("Idle counter: ");
|
||||
Serial.println(idle);
|
||||
Serial.println();
|
||||
|
||||
idle = 0;
|
||||
|
||||
// immediately after fetching the temperature we request a new sample
|
||||
// in the async modus
|
||||
// for the demo we let the resolution change to show differences
|
||||
resolution++;
|
||||
if (resolution > 12) resolution = 9;
|
||||
|
||||
sensors.setResolution(tempDeviceAddress, resolution);
|
||||
sensors.requestTemperatures();
|
||||
delayInMillis = 750 / (1 << (12 - resolution));
|
||||
lastTempRequest = millis();
|
||||
}
|
||||
|
||||
digitalWrite(13, HIGH);
|
||||
// we can do usefull things here
|
||||
// for the demo we just count the idle time in millis
|
||||
delay(1);
|
||||
idle++;
|
||||
}
|
||||
@@ -7,8 +7,8 @@
|
||||
#######################################
|
||||
DallasTemperature KEYWORD1
|
||||
OneWire KEYWORD1
|
||||
AlarmHandler KEYWORD1
|
||||
DeviceAddress KEYWORD1
|
||||
AlarmHandler KEYWORD1
|
||||
DeviceAddress KEYWORD1
|
||||
|
||||
#######################################
|
||||
# Methods and Functions (KEYWORD2)
|
||||
@@ -20,12 +20,14 @@ getTempC KEYWORD2
|
||||
toFahrenheit KEYWORD2
|
||||
getTempF KEYWORD2
|
||||
getTempCByIndex KEYWORD2
|
||||
getTempFByIndex KEYWORD2
|
||||
getTempFByIndex KEYWORD2
|
||||
setWaitForConversion KEYWORD2
|
||||
getWaitForConversion KEYWORD2
|
||||
requestTemperatures KEYWORD2
|
||||
requestTemperaturesByAddress KEYWORD2
|
||||
requestTemperaturesByIndex KEYWORD2
|
||||
requestTemperaturesByAddress KEYWORD2
|
||||
requestTemperaturesByIndex KEYWORD2
|
||||
isParasitePowerMode KEYWORD2
|
||||
begin KEYWORD2
|
||||
begin KEYWORD2
|
||||
getDeviceCount KEYWORD2
|
||||
getAddress KEYWORD2
|
||||
validAddress KEYWORD2
|
||||
@@ -45,6 +47,7 @@ processAlarmss KEYWORD2
|
||||
setAlarmHandlers KEYWORD2
|
||||
defaultAlarmHandler KEYWORD2
|
||||
calculateTemperature KEYWORD2
|
||||
millisToWaitForConversion KEYWORD2
|
||||
|
||||
#######################################
|
||||
# Constants (LITERAL1)
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"name": "DallasTemperature",
|
||||
"keywords": "onewire, 1-wire, bus, sensor, temperature",
|
||||
"description": "Arduino Library for Dallas Temperature ICs (DS18B20, DS18S20, DS1822, DS1820)",
|
||||
"repository":
|
||||
{
|
||||
"type": "git",
|
||||
"url": "https://github.com/milesburton/Arduino-Temperature-Control-Library.git"
|
||||
},
|
||||
"authors":
|
||||
[
|
||||
{
|
||||
"name": "Miles Burton",
|
||||
"email": "miles@mnetcs.com",
|
||||
"url": "http://www.milesburton.com",
|
||||
"maintainer": true
|
||||
},
|
||||
{
|
||||
"name": "Tim Newsome",
|
||||
"email": "nuisance@casualhacker.net"
|
||||
},
|
||||
{
|
||||
"name": "Guil Barros",
|
||||
"email": "gfbarros@bappos.com"
|
||||
},
|
||||
{
|
||||
"name": "Rob Tillaart",
|
||||
"email": "rob.tillaart@gmail.com"
|
||||
}
|
||||
],
|
||||
"dependencies":
|
||||
{
|
||||
"name": "OneWire",
|
||||
"authors": "Paul Stoffregen",
|
||||
"frameworks": "arduino"
|
||||
},
|
||||
"frameworks": "arduino",
|
||||
"platforms": "atmelavr"
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
|
||||
#include "Encoder.h"
|
||||
|
||||
// Yes, all the code is in the header file, to provide the user
|
||||
// configure options with #define (before they include it), and
|
||||
// to facilitate some crafty optimizations!
|
||||
|
||||
Encoder_internal_state_t * Encoder::interruptArgs[];
|
||||
|
||||
|
||||
@@ -0,0 +1,942 @@
|
||||
/* Encoder Library, for measuring quadrature encoded signals
|
||||
* http://www.pjrc.com/teensy/td_libs_Encoder.html
|
||||
* Copyright (c) 2011,2013 PJRC.COM, LLC - Paul Stoffregen <paul@pjrc.com>
|
||||
*
|
||||
* Version 1.2 - fix -2 bug in C-only code
|
||||
* Version 1.1 - expand to support boards with up to 60 interrupts
|
||||
* Version 1.0 - initial release
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
|
||||
#ifndef Encoder_h_
|
||||
#define Encoder_h_
|
||||
|
||||
#if defined(ARDUINO) && ARDUINO >= 100
|
||||
#include "Arduino.h"
|
||||
#elif defined(WIRING)
|
||||
#include "Wiring.h"
|
||||
#else
|
||||
#include "WProgram.h"
|
||||
#include "pins_arduino.h"
|
||||
#endif
|
||||
|
||||
#include "utility/direct_pin_read.h"
|
||||
|
||||
#if defined(ENCODER_USE_INTERRUPTS) || !defined(ENCODER_DO_NOT_USE_INTERRUPTS)
|
||||
#define ENCODER_USE_INTERRUPTS
|
||||
#define ENCODER_ARGLIST_SIZE CORE_NUM_INTERRUPT
|
||||
#include "utility/interrupt_pins.h"
|
||||
#ifdef ENCODER_OPTIMIZE_INTERRUPTS
|
||||
#include "utility/interrupt_config.h"
|
||||
#endif
|
||||
#else
|
||||
#define ENCODER_ARGLIST_SIZE 0
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
// All the data needed by interrupts is consolidated into this ugly struct
|
||||
// to facilitate assembly language optimizing of the speed critical update.
|
||||
// The assembly code uses auto-incrementing addressing modes, so the struct
|
||||
// must remain in exactly this order.
|
||||
typedef struct {
|
||||
volatile IO_REG_TYPE * pin1_register;
|
||||
volatile IO_REG_TYPE * pin2_register;
|
||||
IO_REG_TYPE pin1_bitmask;
|
||||
IO_REG_TYPE pin2_bitmask;
|
||||
uint8_t state;
|
||||
int32_t position;
|
||||
} Encoder_internal_state_t;
|
||||
|
||||
class Encoder
|
||||
{
|
||||
public:
|
||||
Encoder(uint8_t pin1, uint8_t pin2) {
|
||||
#ifdef INPUT_PULLUP
|
||||
pinMode(pin1, INPUT_PULLUP);
|
||||
pinMode(pin2, INPUT_PULLUP);
|
||||
#else
|
||||
pinMode(pin1, INPUT);
|
||||
digitalWrite(pin1, HIGH);
|
||||
pinMode(pin2, INPUT);
|
||||
digitalWrite(pin2, HIGH);
|
||||
#endif
|
||||
encoder.pin1_register = PIN_TO_BASEREG(pin1);
|
||||
encoder.pin1_bitmask = PIN_TO_BITMASK(pin1);
|
||||
encoder.pin2_register = PIN_TO_BASEREG(pin2);
|
||||
encoder.pin2_bitmask = PIN_TO_BITMASK(pin2);
|
||||
encoder.position = 0;
|
||||
// allow time for a passive R-C filter to charge
|
||||
// through the pullup resistors, before reading
|
||||
// the initial state
|
||||
delayMicroseconds(2000);
|
||||
uint8_t s = 0;
|
||||
if (DIRECT_PIN_READ(encoder.pin1_register, encoder.pin1_bitmask)) s |= 1;
|
||||
if (DIRECT_PIN_READ(encoder.pin2_register, encoder.pin2_bitmask)) s |= 2;
|
||||
encoder.state = s;
|
||||
#ifdef ENCODER_USE_INTERRUPTS
|
||||
interrupts_in_use = attach_interrupt(pin1, &encoder);
|
||||
interrupts_in_use += attach_interrupt(pin2, &encoder);
|
||||
#endif
|
||||
//update_finishup(); // to force linker to include the code (does not work)
|
||||
}
|
||||
|
||||
|
||||
#ifdef ENCODER_USE_INTERRUPTS
|
||||
inline int32_t read() {
|
||||
if (interrupts_in_use < 2) {
|
||||
noInterrupts();
|
||||
update(&encoder);
|
||||
} else {
|
||||
noInterrupts();
|
||||
}
|
||||
int32_t ret = encoder.position;
|
||||
interrupts();
|
||||
return ret;
|
||||
}
|
||||
inline void write(int32_t p) {
|
||||
noInterrupts();
|
||||
encoder.position = p;
|
||||
interrupts();
|
||||
}
|
||||
#else
|
||||
inline int32_t read() {
|
||||
update(&encoder);
|
||||
return encoder.position;
|
||||
}
|
||||
inline void write(int32_t p) {
|
||||
encoder.position = p;
|
||||
}
|
||||
#endif
|
||||
private:
|
||||
Encoder_internal_state_t encoder;
|
||||
#ifdef ENCODER_USE_INTERRUPTS
|
||||
uint8_t interrupts_in_use;
|
||||
#endif
|
||||
public:
|
||||
static Encoder_internal_state_t * interruptArgs[ENCODER_ARGLIST_SIZE];
|
||||
|
||||
// _______ _______
|
||||
// Pin1 ______| |_______| |______ Pin1
|
||||
// negative <--- _______ _______ __ --> positive
|
||||
// Pin2 __| |_______| |_______| Pin2
|
||||
|
||||
// new new old old
|
||||
// pin2 pin1 pin2 pin1 Result
|
||||
// ---- ---- ---- ---- ------
|
||||
// 0 0 0 0 no movement
|
||||
// 0 0 0 1 +1
|
||||
// 0 0 1 0 -1
|
||||
// 0 0 1 1 +2 (assume pin1 edges only)
|
||||
// 0 1 0 0 -1
|
||||
// 0 1 0 1 no movement
|
||||
// 0 1 1 0 -2 (assume pin1 edges only)
|
||||
// 0 1 1 1 +1
|
||||
// 1 0 0 0 +1
|
||||
// 1 0 0 1 -2 (assume pin1 edges only)
|
||||
// 1 0 1 0 no movement
|
||||
// 1 0 1 1 -1
|
||||
// 1 1 0 0 +2 (assume pin1 edges only)
|
||||
// 1 1 0 1 -1
|
||||
// 1 1 1 0 +1
|
||||
// 1 1 1 1 no movement
|
||||
/*
|
||||
// Simple, easy-to-read "documentation" version :-)
|
||||
//
|
||||
void update(void) {
|
||||
uint8_t s = state & 3;
|
||||
if (digitalRead(pin1)) s |= 4;
|
||||
if (digitalRead(pin2)) s |= 8;
|
||||
switch (s) {
|
||||
case 0: case 5: case 10: case 15:
|
||||
break;
|
||||
case 1: case 7: case 8: case 14:
|
||||
position++; break;
|
||||
case 2: case 4: case 11: case 13:
|
||||
position--; break;
|
||||
case 3: case 12:
|
||||
position += 2; break;
|
||||
default:
|
||||
position -= 2; break;
|
||||
}
|
||||
state = (s >> 2);
|
||||
}
|
||||
*/
|
||||
|
||||
private:
|
||||
static void update(Encoder_internal_state_t *arg) {
|
||||
#if defined(__AVR__)
|
||||
// The compiler believes this is just 1 line of code, so
|
||||
// it will inline this function into each interrupt
|
||||
// handler. That's a tiny bit faster, but grows the code.
|
||||
// Especially when used with ENCODER_OPTIMIZE_INTERRUPTS,
|
||||
// the inline nature allows the ISR prologue and epilogue
|
||||
// to only save/restore necessary registers, for very nice
|
||||
// speed increase.
|
||||
asm volatile (
|
||||
"ld r30, X+" "\n\t"
|
||||
"ld r31, X+" "\n\t"
|
||||
"ld r24, Z" "\n\t" // r24 = pin1 input
|
||||
"ld r30, X+" "\n\t"
|
||||
"ld r31, X+" "\n\t"
|
||||
"ld r25, Z" "\n\t" // r25 = pin2 input
|
||||
"ld r30, X+" "\n\t" // r30 = pin1 mask
|
||||
"ld r31, X+" "\n\t" // r31 = pin2 mask
|
||||
"ld r22, X" "\n\t" // r22 = state
|
||||
"andi r22, 3" "\n\t"
|
||||
"and r24, r30" "\n\t"
|
||||
"breq L%=1" "\n\t" // if (pin1)
|
||||
"ori r22, 4" "\n\t" // state |= 4
|
||||
"L%=1:" "and r25, r31" "\n\t"
|
||||
"breq L%=2" "\n\t" // if (pin2)
|
||||
"ori r22, 8" "\n\t" // state |= 8
|
||||
"L%=2:" "ldi r30, lo8(pm(L%=table))" "\n\t"
|
||||
"ldi r31, hi8(pm(L%=table))" "\n\t"
|
||||
"add r30, r22" "\n\t"
|
||||
"adc r31, __zero_reg__" "\n\t"
|
||||
"asr r22" "\n\t"
|
||||
"asr r22" "\n\t"
|
||||
"st X+, r22" "\n\t" // store new state
|
||||
"ld r22, X+" "\n\t"
|
||||
"ld r23, X+" "\n\t"
|
||||
"ld r24, X+" "\n\t"
|
||||
"ld r25, X+" "\n\t"
|
||||
"ijmp" "\n\t" // jumps to update_finishup()
|
||||
// TODO move this table to another static function,
|
||||
// so it doesn't get needlessly duplicated. Easier
|
||||
// said than done, due to linker issues and inlining
|
||||
"L%=table:" "\n\t"
|
||||
"rjmp L%=end" "\n\t" // 0
|
||||
"rjmp L%=plus1" "\n\t" // 1
|
||||
"rjmp L%=minus1" "\n\t" // 2
|
||||
"rjmp L%=plus2" "\n\t" // 3
|
||||
"rjmp L%=minus1" "\n\t" // 4
|
||||
"rjmp L%=end" "\n\t" // 5
|
||||
"rjmp L%=minus2" "\n\t" // 6
|
||||
"rjmp L%=plus1" "\n\t" // 7
|
||||
"rjmp L%=plus1" "\n\t" // 8
|
||||
"rjmp L%=minus2" "\n\t" // 9
|
||||
"rjmp L%=end" "\n\t" // 10
|
||||
"rjmp L%=minus1" "\n\t" // 11
|
||||
"rjmp L%=plus2" "\n\t" // 12
|
||||
"rjmp L%=minus1" "\n\t" // 13
|
||||
"rjmp L%=plus1" "\n\t" // 14
|
||||
"rjmp L%=end" "\n\t" // 15
|
||||
"L%=minus2:" "\n\t"
|
||||
"subi r22, 2" "\n\t"
|
||||
"sbci r23, 0" "\n\t"
|
||||
"sbci r24, 0" "\n\t"
|
||||
"sbci r25, 0" "\n\t"
|
||||
"rjmp L%=store" "\n\t"
|
||||
"L%=minus1:" "\n\t"
|
||||
"subi r22, 1" "\n\t"
|
||||
"sbci r23, 0" "\n\t"
|
||||
"sbci r24, 0" "\n\t"
|
||||
"sbci r25, 0" "\n\t"
|
||||
"rjmp L%=store" "\n\t"
|
||||
"L%=plus2:" "\n\t"
|
||||
"subi r22, 254" "\n\t"
|
||||
"rjmp L%=z" "\n\t"
|
||||
"L%=plus1:" "\n\t"
|
||||
"subi r22, 255" "\n\t"
|
||||
"L%=z:" "sbci r23, 255" "\n\t"
|
||||
"sbci r24, 255" "\n\t"
|
||||
"sbci r25, 255" "\n\t"
|
||||
"L%=store:" "\n\t"
|
||||
"st -X, r25" "\n\t"
|
||||
"st -X, r24" "\n\t"
|
||||
"st -X, r23" "\n\t"
|
||||
"st -X, r22" "\n\t"
|
||||
"L%=end:" "\n"
|
||||
: : "x" (arg) : "r22", "r23", "r24", "r25", "r30", "r31");
|
||||
#else
|
||||
uint8_t p1val = DIRECT_PIN_READ(arg->pin1_register, arg->pin1_bitmask);
|
||||
uint8_t p2val = DIRECT_PIN_READ(arg->pin2_register, arg->pin2_bitmask);
|
||||
uint8_t state = arg->state & 3;
|
||||
if (p1val) state |= 4;
|
||||
if (p2val) state |= 8;
|
||||
arg->state = (state >> 2);
|
||||
switch (state) {
|
||||
case 1: case 7: case 8: case 14:
|
||||
arg->position++;
|
||||
return;
|
||||
case 2: case 4: case 11: case 13:
|
||||
arg->position--;
|
||||
return;
|
||||
case 3: case 12:
|
||||
arg->position += 2;
|
||||
return;
|
||||
case 6: case 9:
|
||||
arg->position -= 2;
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
/*
|
||||
#if defined(__AVR__)
|
||||
// TODO: this must be a no inline function
|
||||
// even noinline does not seem to solve difficult
|
||||
// problems with this. Oh well, it was only meant
|
||||
// to shrink code size - there's no performance
|
||||
// improvement in this, only code size reduction.
|
||||
__attribute__((noinline)) void update_finishup(void) {
|
||||
asm volatile (
|
||||
"ldi r30, lo8(pm(Ltable))" "\n\t"
|
||||
"ldi r31, hi8(pm(Ltable))" "\n\t"
|
||||
"Ltable:" "\n\t"
|
||||
"rjmp L%=end" "\n\t" // 0
|
||||
"rjmp L%=plus1" "\n\t" // 1
|
||||
"rjmp L%=minus1" "\n\t" // 2
|
||||
"rjmp L%=plus2" "\n\t" // 3
|
||||
"rjmp L%=minus1" "\n\t" // 4
|
||||
"rjmp L%=end" "\n\t" // 5
|
||||
"rjmp L%=minus2" "\n\t" // 6
|
||||
"rjmp L%=plus1" "\n\t" // 7
|
||||
"rjmp L%=plus1" "\n\t" // 8
|
||||
"rjmp L%=minus2" "\n\t" // 9
|
||||
"rjmp L%=end" "\n\t" // 10
|
||||
"rjmp L%=minus1" "\n\t" // 11
|
||||
"rjmp L%=plus2" "\n\t" // 12
|
||||
"rjmp L%=minus1" "\n\t" // 13
|
||||
"rjmp L%=plus1" "\n\t" // 14
|
||||
"rjmp L%=end" "\n\t" // 15
|
||||
"L%=minus2:" "\n\t"
|
||||
"subi r22, 2" "\n\t"
|
||||
"sbci r23, 0" "\n\t"
|
||||
"sbci r24, 0" "\n\t"
|
||||
"sbci r25, 0" "\n\t"
|
||||
"rjmp L%=store" "\n\t"
|
||||
"L%=minus1:" "\n\t"
|
||||
"subi r22, 1" "\n\t"
|
||||
"sbci r23, 0" "\n\t"
|
||||
"sbci r24, 0" "\n\t"
|
||||
"sbci r25, 0" "\n\t"
|
||||
"rjmp L%=store" "\n\t"
|
||||
"L%=plus2:" "\n\t"
|
||||
"subi r22, 254" "\n\t"
|
||||
"rjmp L%=z" "\n\t"
|
||||
"L%=plus1:" "\n\t"
|
||||
"subi r22, 255" "\n\t"
|
||||
"L%=z:" "sbci r23, 255" "\n\t"
|
||||
"sbci r24, 255" "\n\t"
|
||||
"sbci r25, 255" "\n\t"
|
||||
"L%=store:" "\n\t"
|
||||
"st -X, r25" "\n\t"
|
||||
"st -X, r24" "\n\t"
|
||||
"st -X, r23" "\n\t"
|
||||
"st -X, r22" "\n\t"
|
||||
"L%=end:" "\n"
|
||||
: : : "r22", "r23", "r24", "r25", "r30", "r31");
|
||||
}
|
||||
#endif
|
||||
*/
|
||||
|
||||
|
||||
#ifdef ENCODER_USE_INTERRUPTS
|
||||
// this giant function is an unfortunate consequence of Arduino's
|
||||
// attachInterrupt function not supporting any way to pass a pointer
|
||||
// or other context to the attached function.
|
||||
static uint8_t attach_interrupt(uint8_t pin, Encoder_internal_state_t *state) {
|
||||
switch (pin) {
|
||||
#ifdef CORE_INT0_PIN
|
||||
case CORE_INT0_PIN:
|
||||
interruptArgs[0] = state;
|
||||
attachInterrupt(0, isr0, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT1_PIN
|
||||
case CORE_INT1_PIN:
|
||||
interruptArgs[1] = state;
|
||||
attachInterrupt(1, isr1, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT2_PIN
|
||||
case CORE_INT2_PIN:
|
||||
interruptArgs[2] = state;
|
||||
attachInterrupt(2, isr2, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT3_PIN
|
||||
case CORE_INT3_PIN:
|
||||
interruptArgs[3] = state;
|
||||
attachInterrupt(3, isr3, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT4_PIN
|
||||
case CORE_INT4_PIN:
|
||||
interruptArgs[4] = state;
|
||||
attachInterrupt(4, isr4, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT5_PIN
|
||||
case CORE_INT5_PIN:
|
||||
interruptArgs[5] = state;
|
||||
attachInterrupt(5, isr5, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT6_PIN
|
||||
case CORE_INT6_PIN:
|
||||
interruptArgs[6] = state;
|
||||
attachInterrupt(6, isr6, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT7_PIN
|
||||
case CORE_INT7_PIN:
|
||||
interruptArgs[7] = state;
|
||||
attachInterrupt(7, isr7, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT8_PIN
|
||||
case CORE_INT8_PIN:
|
||||
interruptArgs[8] = state;
|
||||
attachInterrupt(8, isr8, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT9_PIN
|
||||
case CORE_INT9_PIN:
|
||||
interruptArgs[9] = state;
|
||||
attachInterrupt(9, isr9, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT10_PIN
|
||||
case CORE_INT10_PIN:
|
||||
interruptArgs[10] = state;
|
||||
attachInterrupt(10, isr10, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT11_PIN
|
||||
case CORE_INT11_PIN:
|
||||
interruptArgs[11] = state;
|
||||
attachInterrupt(11, isr11, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT12_PIN
|
||||
case CORE_INT12_PIN:
|
||||
interruptArgs[12] = state;
|
||||
attachInterrupt(12, isr12, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT13_PIN
|
||||
case CORE_INT13_PIN:
|
||||
interruptArgs[13] = state;
|
||||
attachInterrupt(13, isr13, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT14_PIN
|
||||
case CORE_INT14_PIN:
|
||||
interruptArgs[14] = state;
|
||||
attachInterrupt(14, isr14, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT15_PIN
|
||||
case CORE_INT15_PIN:
|
||||
interruptArgs[15] = state;
|
||||
attachInterrupt(15, isr15, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT16_PIN
|
||||
case CORE_INT16_PIN:
|
||||
interruptArgs[16] = state;
|
||||
attachInterrupt(16, isr16, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT17_PIN
|
||||
case CORE_INT17_PIN:
|
||||
interruptArgs[17] = state;
|
||||
attachInterrupt(17, isr17, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT18_PIN
|
||||
case CORE_INT18_PIN:
|
||||
interruptArgs[18] = state;
|
||||
attachInterrupt(18, isr18, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT19_PIN
|
||||
case CORE_INT19_PIN:
|
||||
interruptArgs[19] = state;
|
||||
attachInterrupt(19, isr19, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT20_PIN
|
||||
case CORE_INT20_PIN:
|
||||
interruptArgs[20] = state;
|
||||
attachInterrupt(20, isr20, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT21_PIN
|
||||
case CORE_INT21_PIN:
|
||||
interruptArgs[21] = state;
|
||||
attachInterrupt(21, isr21, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT22_PIN
|
||||
case CORE_INT22_PIN:
|
||||
interruptArgs[22] = state;
|
||||
attachInterrupt(22, isr22, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT23_PIN
|
||||
case CORE_INT23_PIN:
|
||||
interruptArgs[23] = state;
|
||||
attachInterrupt(23, isr23, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT24_PIN
|
||||
case CORE_INT24_PIN:
|
||||
interruptArgs[24] = state;
|
||||
attachInterrupt(24, isr24, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT25_PIN
|
||||
case CORE_INT25_PIN:
|
||||
interruptArgs[25] = state;
|
||||
attachInterrupt(25, isr25, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT26_PIN
|
||||
case CORE_INT26_PIN:
|
||||
interruptArgs[26] = state;
|
||||
attachInterrupt(26, isr26, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT27_PIN
|
||||
case CORE_INT27_PIN:
|
||||
interruptArgs[27] = state;
|
||||
attachInterrupt(27, isr27, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT28_PIN
|
||||
case CORE_INT28_PIN:
|
||||
interruptArgs[28] = state;
|
||||
attachInterrupt(28, isr28, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT29_PIN
|
||||
case CORE_INT29_PIN:
|
||||
interruptArgs[29] = state;
|
||||
attachInterrupt(29, isr29, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
|
||||
#ifdef CORE_INT30_PIN
|
||||
case CORE_INT30_PIN:
|
||||
interruptArgs[30] = state;
|
||||
attachInterrupt(30, isr30, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT31_PIN
|
||||
case CORE_INT31_PIN:
|
||||
interruptArgs[31] = state;
|
||||
attachInterrupt(31, isr31, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT32_PIN
|
||||
case CORE_INT32_PIN:
|
||||
interruptArgs[32] = state;
|
||||
attachInterrupt(32, isr32, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT33_PIN
|
||||
case CORE_INT33_PIN:
|
||||
interruptArgs[33] = state;
|
||||
attachInterrupt(33, isr33, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT34_PIN
|
||||
case CORE_INT34_PIN:
|
||||
interruptArgs[34] = state;
|
||||
attachInterrupt(34, isr34, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT35_PIN
|
||||
case CORE_INT35_PIN:
|
||||
interruptArgs[35] = state;
|
||||
attachInterrupt(35, isr35, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT36_PIN
|
||||
case CORE_INT36_PIN:
|
||||
interruptArgs[36] = state;
|
||||
attachInterrupt(36, isr36, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT37_PIN
|
||||
case CORE_INT37_PIN:
|
||||
interruptArgs[37] = state;
|
||||
attachInterrupt(37, isr37, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT38_PIN
|
||||
case CORE_INT38_PIN:
|
||||
interruptArgs[38] = state;
|
||||
attachInterrupt(38, isr38, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT39_PIN
|
||||
case CORE_INT39_PIN:
|
||||
interruptArgs[39] = state;
|
||||
attachInterrupt(39, isr39, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT40_PIN
|
||||
case CORE_INT40_PIN:
|
||||
interruptArgs[40] = state;
|
||||
attachInterrupt(40, isr40, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT41_PIN
|
||||
case CORE_INT41_PIN:
|
||||
interruptArgs[41] = state;
|
||||
attachInterrupt(41, isr41, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT42_PIN
|
||||
case CORE_INT42_PIN:
|
||||
interruptArgs[42] = state;
|
||||
attachInterrupt(42, isr42, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT43_PIN
|
||||
case CORE_INT43_PIN:
|
||||
interruptArgs[43] = state;
|
||||
attachInterrupt(43, isr43, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT44_PIN
|
||||
case CORE_INT44_PIN:
|
||||
interruptArgs[44] = state;
|
||||
attachInterrupt(44, isr44, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT45_PIN
|
||||
case CORE_INT45_PIN:
|
||||
interruptArgs[45] = state;
|
||||
attachInterrupt(45, isr45, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT46_PIN
|
||||
case CORE_INT46_PIN:
|
||||
interruptArgs[46] = state;
|
||||
attachInterrupt(46, isr46, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT47_PIN
|
||||
case CORE_INT47_PIN:
|
||||
interruptArgs[47] = state;
|
||||
attachInterrupt(47, isr47, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT48_PIN
|
||||
case CORE_INT48_PIN:
|
||||
interruptArgs[48] = state;
|
||||
attachInterrupt(48, isr48, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT49_PIN
|
||||
case CORE_INT49_PIN:
|
||||
interruptArgs[49] = state;
|
||||
attachInterrupt(49, isr49, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT50_PIN
|
||||
case CORE_INT50_PIN:
|
||||
interruptArgs[50] = state;
|
||||
attachInterrupt(50, isr50, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT51_PIN
|
||||
case CORE_INT51_PIN:
|
||||
interruptArgs[51] = state;
|
||||
attachInterrupt(51, isr51, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT52_PIN
|
||||
case CORE_INT52_PIN:
|
||||
interruptArgs[52] = state;
|
||||
attachInterrupt(52, isr52, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT53_PIN
|
||||
case CORE_INT53_PIN:
|
||||
interruptArgs[53] = state;
|
||||
attachInterrupt(53, isr53, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT54_PIN
|
||||
case CORE_INT54_PIN:
|
||||
interruptArgs[54] = state;
|
||||
attachInterrupt(54, isr54, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT55_PIN
|
||||
case CORE_INT55_PIN:
|
||||
interruptArgs[55] = state;
|
||||
attachInterrupt(55, isr55, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT56_PIN
|
||||
case CORE_INT56_PIN:
|
||||
interruptArgs[56] = state;
|
||||
attachInterrupt(56, isr56, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT57_PIN
|
||||
case CORE_INT57_PIN:
|
||||
interruptArgs[57] = state;
|
||||
attachInterrupt(57, isr57, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT58_PIN
|
||||
case CORE_INT58_PIN:
|
||||
interruptArgs[58] = state;
|
||||
attachInterrupt(58, isr58, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
#ifdef CORE_INT59_PIN
|
||||
case CORE_INT59_PIN:
|
||||
interruptArgs[59] = state;
|
||||
attachInterrupt(59, isr59, CHANGE);
|
||||
break;
|
||||
#endif
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
#endif // ENCODER_USE_INTERRUPTS
|
||||
|
||||
|
||||
#if defined(ENCODER_USE_INTERRUPTS) && !defined(ENCODER_OPTIMIZE_INTERRUPTS)
|
||||
#ifdef CORE_INT0_PIN
|
||||
static void isr0(void) { update(interruptArgs[0]); }
|
||||
#endif
|
||||
#ifdef CORE_INT1_PIN
|
||||
static void isr1(void) { update(interruptArgs[1]); }
|
||||
#endif
|
||||
#ifdef CORE_INT2_PIN
|
||||
static void isr2(void) { update(interruptArgs[2]); }
|
||||
#endif
|
||||
#ifdef CORE_INT3_PIN
|
||||
static void isr3(void) { update(interruptArgs[3]); }
|
||||
#endif
|
||||
#ifdef CORE_INT4_PIN
|
||||
static void isr4(void) { update(interruptArgs[4]); }
|
||||
#endif
|
||||
#ifdef CORE_INT5_PIN
|
||||
static void isr5(void) { update(interruptArgs[5]); }
|
||||
#endif
|
||||
#ifdef CORE_INT6_PIN
|
||||
static void isr6(void) { update(interruptArgs[6]); }
|
||||
#endif
|
||||
#ifdef CORE_INT7_PIN
|
||||
static void isr7(void) { update(interruptArgs[7]); }
|
||||
#endif
|
||||
#ifdef CORE_INT8_PIN
|
||||
static void isr8(void) { update(interruptArgs[8]); }
|
||||
#endif
|
||||
#ifdef CORE_INT9_PIN
|
||||
static void isr9(void) { update(interruptArgs[9]); }
|
||||
#endif
|
||||
#ifdef CORE_INT10_PIN
|
||||
static void isr10(void) { update(interruptArgs[10]); }
|
||||
#endif
|
||||
#ifdef CORE_INT11_PIN
|
||||
static void isr11(void) { update(interruptArgs[11]); }
|
||||
#endif
|
||||
#ifdef CORE_INT12_PIN
|
||||
static void isr12(void) { update(interruptArgs[12]); }
|
||||
#endif
|
||||
#ifdef CORE_INT13_PIN
|
||||
static void isr13(void) { update(interruptArgs[13]); }
|
||||
#endif
|
||||
#ifdef CORE_INT14_PIN
|
||||
static void isr14(void) { update(interruptArgs[14]); }
|
||||
#endif
|
||||
#ifdef CORE_INT15_PIN
|
||||
static void isr15(void) { update(interruptArgs[15]); }
|
||||
#endif
|
||||
#ifdef CORE_INT16_PIN
|
||||
static void isr16(void) { update(interruptArgs[16]); }
|
||||
#endif
|
||||
#ifdef CORE_INT17_PIN
|
||||
static void isr17(void) { update(interruptArgs[17]); }
|
||||
#endif
|
||||
#ifdef CORE_INT18_PIN
|
||||
static void isr18(void) { update(interruptArgs[18]); }
|
||||
#endif
|
||||
#ifdef CORE_INT19_PIN
|
||||
static void isr19(void) { update(interruptArgs[19]); }
|
||||
#endif
|
||||
#ifdef CORE_INT20_PIN
|
||||
static void isr20(void) { update(interruptArgs[20]); }
|
||||
#endif
|
||||
#ifdef CORE_INT21_PIN
|
||||
static void isr21(void) { update(interruptArgs[21]); }
|
||||
#endif
|
||||
#ifdef CORE_INT22_PIN
|
||||
static void isr22(void) { update(interruptArgs[22]); }
|
||||
#endif
|
||||
#ifdef CORE_INT23_PIN
|
||||
static void isr23(void) { update(interruptArgs[23]); }
|
||||
#endif
|
||||
#ifdef CORE_INT24_PIN
|
||||
static void isr24(void) { update(interruptArgs[24]); }
|
||||
#endif
|
||||
#ifdef CORE_INT25_PIN
|
||||
static void isr25(void) { update(interruptArgs[25]); }
|
||||
#endif
|
||||
#ifdef CORE_INT26_PIN
|
||||
static void isr26(void) { update(interruptArgs[26]); }
|
||||
#endif
|
||||
#ifdef CORE_INT27_PIN
|
||||
static void isr27(void) { update(interruptArgs[27]); }
|
||||
#endif
|
||||
#ifdef CORE_INT28_PIN
|
||||
static void isr28(void) { update(interruptArgs[28]); }
|
||||
#endif
|
||||
#ifdef CORE_INT29_PIN
|
||||
static void isr29(void) { update(interruptArgs[29]); }
|
||||
#endif
|
||||
#ifdef CORE_INT30_PIN
|
||||
static void isr30(void) { update(interruptArgs[30]); }
|
||||
#endif
|
||||
#ifdef CORE_INT31_PIN
|
||||
static void isr31(void) { update(interruptArgs[31]); }
|
||||
#endif
|
||||
#ifdef CORE_INT32_PIN
|
||||
static void isr32(void) { update(interruptArgs[32]); }
|
||||
#endif
|
||||
#ifdef CORE_INT33_PIN
|
||||
static void isr33(void) { update(interruptArgs[33]); }
|
||||
#endif
|
||||
#ifdef CORE_INT34_PIN
|
||||
static void isr34(void) { update(interruptArgs[34]); }
|
||||
#endif
|
||||
#ifdef CORE_INT35_PIN
|
||||
static void isr35(void) { update(interruptArgs[35]); }
|
||||
#endif
|
||||
#ifdef CORE_INT36_PIN
|
||||
static void isr36(void) { update(interruptArgs[36]); }
|
||||
#endif
|
||||
#ifdef CORE_INT37_PIN
|
||||
static void isr37(void) { update(interruptArgs[37]); }
|
||||
#endif
|
||||
#ifdef CORE_INT38_PIN
|
||||
static void isr38(void) { update(interruptArgs[38]); }
|
||||
#endif
|
||||
#ifdef CORE_INT39_PIN
|
||||
static void isr39(void) { update(interruptArgs[39]); }
|
||||
#endif
|
||||
#ifdef CORE_INT40_PIN
|
||||
static void isr40(void) { update(interruptArgs[40]); }
|
||||
#endif
|
||||
#ifdef CORE_INT41_PIN
|
||||
static void isr41(void) { update(interruptArgs[41]); }
|
||||
#endif
|
||||
#ifdef CORE_INT42_PIN
|
||||
static void isr42(void) { update(interruptArgs[42]); }
|
||||
#endif
|
||||
#ifdef CORE_INT43_PIN
|
||||
static void isr43(void) { update(interruptArgs[43]); }
|
||||
#endif
|
||||
#ifdef CORE_INT44_PIN
|
||||
static void isr44(void) { update(interruptArgs[44]); }
|
||||
#endif
|
||||
#ifdef CORE_INT45_PIN
|
||||
static void isr45(void) { update(interruptArgs[45]); }
|
||||
#endif
|
||||
#ifdef CORE_INT46_PIN
|
||||
static void isr46(void) { update(interruptArgs[46]); }
|
||||
#endif
|
||||
#ifdef CORE_INT47_PIN
|
||||
static void isr47(void) { update(interruptArgs[47]); }
|
||||
#endif
|
||||
#ifdef CORE_INT48_PIN
|
||||
static void isr48(void) { update(interruptArgs[48]); }
|
||||
#endif
|
||||
#ifdef CORE_INT49_PIN
|
||||
static void isr49(void) { update(interruptArgs[49]); }
|
||||
#endif
|
||||
#ifdef CORE_INT50_PIN
|
||||
static void isr50(void) { update(interruptArgs[50]); }
|
||||
#endif
|
||||
#ifdef CORE_INT51_PIN
|
||||
static void isr51(void) { update(interruptArgs[51]); }
|
||||
#endif
|
||||
#ifdef CORE_INT52_PIN
|
||||
static void isr52(void) { update(interruptArgs[52]); }
|
||||
#endif
|
||||
#ifdef CORE_INT53_PIN
|
||||
static void isr53(void) { update(interruptArgs[53]); }
|
||||
#endif
|
||||
#ifdef CORE_INT54_PIN
|
||||
static void isr54(void) { update(interruptArgs[54]); }
|
||||
#endif
|
||||
#ifdef CORE_INT55_PIN
|
||||
static void isr55(void) { update(interruptArgs[55]); }
|
||||
#endif
|
||||
#ifdef CORE_INT56_PIN
|
||||
static void isr56(void) { update(interruptArgs[56]); }
|
||||
#endif
|
||||
#ifdef CORE_INT57_PIN
|
||||
static void isr57(void) { update(interruptArgs[57]); }
|
||||
#endif
|
||||
#ifdef CORE_INT58_PIN
|
||||
static void isr58(void) { update(interruptArgs[58]); }
|
||||
#endif
|
||||
#ifdef CORE_INT59_PIN
|
||||
static void isr59(void) { update(interruptArgs[59]); }
|
||||
#endif
|
||||
#endif
|
||||
};
|
||||
|
||||
#if defined(ENCODER_USE_INTERRUPTS) && defined(ENCODER_OPTIMIZE_INTERRUPTS)
|
||||
#if defined(__AVR__)
|
||||
#if defined(INT0_vect) && CORE_NUM_INTERRUPT > 0
|
||||
ISR(INT0_vect) { Encoder::update(Encoder::interruptArgs[SCRAMBLE_INT_ORDER(0)]); }
|
||||
#endif
|
||||
#if defined(INT1_vect) && CORE_NUM_INTERRUPT > 1
|
||||
ISR(INT1_vect) { Encoder::update(Encoder::interruptArgs[SCRAMBLE_INT_ORDER(1)]); }
|
||||
#endif
|
||||
#if defined(INT2_vect) && CORE_NUM_INTERRUPT > 2
|
||||
ISR(INT2_vect) { Encoder::update(Encoder::interruptArgs[SCRAMBLE_INT_ORDER(2)]); }
|
||||
#endif
|
||||
#if defined(INT3_vect) && CORE_NUM_INTERRUPT > 3
|
||||
ISR(INT3_vect) { Encoder::update(Encoder::interruptArgs[SCRAMBLE_INT_ORDER(3)]); }
|
||||
#endif
|
||||
#if defined(INT4_vect) && CORE_NUM_INTERRUPT > 4
|
||||
ISR(INT4_vect) { Encoder::update(Encoder::interruptArgs[SCRAMBLE_INT_ORDER(4)]); }
|
||||
#endif
|
||||
#if defined(INT5_vect) && CORE_NUM_INTERRUPT > 5
|
||||
ISR(INT5_vect) { Encoder::update(Encoder::interruptArgs[SCRAMBLE_INT_ORDER(5)]); }
|
||||
#endif
|
||||
#if defined(INT6_vect) && CORE_NUM_INTERRUPT > 6
|
||||
ISR(INT6_vect) { Encoder::update(Encoder::interruptArgs[SCRAMBLE_INT_ORDER(6)]); }
|
||||
#endif
|
||||
#if defined(INT7_vect) && CORE_NUM_INTERRUPT > 7
|
||||
ISR(INT7_vect) { Encoder::update(Encoder::interruptArgs[SCRAMBLE_INT_ORDER(7)]); }
|
||||
#endif
|
||||
#endif // AVR
|
||||
#endif // ENCODER_OPTIMIZE_INTERRUPTS
|
||||
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,29 @@
|
||||
/* Encoder Library - Basic Example
|
||||
* http://www.pjrc.com/teensy/td_libs_Encoder.html
|
||||
*
|
||||
* This example code is in the public domain.
|
||||
*/
|
||||
|
||||
#include <Encoder.h>
|
||||
|
||||
// Change these two numbers to the pins connected to your encoder.
|
||||
// Best Performance: both pins have interrupt capability
|
||||
// Good Performance: only the first pin has interrupt capability
|
||||
// Low Performance: neither pin has interrupt capability
|
||||
Encoder myEnc(5, 6);
|
||||
// avoid using pins with LEDs attached
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
Serial.println("Basic Encoder Test:");
|
||||
}
|
||||
|
||||
long oldPosition = -999;
|
||||
|
||||
void loop() {
|
||||
long newPosition = myEnc.read();
|
||||
if (newPosition != oldPosition) {
|
||||
oldPosition = newPosition;
|
||||
Serial.println(newPosition);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/* Encoder Library - NoInterrupts Example
|
||||
* http://www.pjrc.com/teensy/td_libs_Encoder.html
|
||||
*
|
||||
* This example code is in the public domain.
|
||||
*/
|
||||
|
||||
// If you define ENCODER_DO_NOT_USE_INTERRUPTS *before* including
|
||||
// Encoder, the library will never use interrupts. This is mainly
|
||||
// useful to reduce the size of the library when you are using it
|
||||
// with pins that do not support interrupts. Without interrupts,
|
||||
// your program must call the read() function rapidly, or risk
|
||||
// missing changes in position.
|
||||
#define ENCODER_DO_NOT_USE_INTERRUPTS
|
||||
#include <Encoder.h>
|
||||
|
||||
// Beware of Serial.print() speed. Without interrupts, if you
|
||||
// transmit too much data with Serial.print() it can slow your
|
||||
// reading from Encoder. Arduino 1.0 has improved transmit code.
|
||||
// Using the fastest baud rate also helps. Teensy has USB packet
|
||||
// buffering. But all boards can experience problems if you print
|
||||
// too much and fill up buffers.
|
||||
|
||||
// Change these two numbers to the pins connected to your encoder.
|
||||
// With ENCODER_DO_NOT_USE_INTERRUPTS, no interrupts are ever
|
||||
// used, even if the pin has interrupt capability
|
||||
Encoder myEnc(5, 6);
|
||||
// avoid using pins with LEDs attached
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
Serial.println("Basic NoInterrupts Test:");
|
||||
}
|
||||
|
||||
long position = -999;
|
||||
|
||||
void loop() {
|
||||
long newPos = myEnc.read();
|
||||
if (newPos != position) {
|
||||
position = newPos;
|
||||
Serial.println(position);
|
||||
}
|
||||
// With any substantial delay added, Encoder can only track
|
||||
// very slow motion. You may uncomment this line to see
|
||||
// how badly a delay affects your encoder.
|
||||
//delay(50);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/* Encoder Library - SpeedTest - for measuring maximum Encoder speed
|
||||
* http://www.pjrc.com/teensy/td_libs_Encoder.html
|
||||
*
|
||||
* This example code is in the public domain.
|
||||
*/
|
||||
|
||||
|
||||
// This SpeedTest example provides a simple way to verify how much
|
||||
// CPU time Encoder is consuming. Connect a DC voltmeter to the
|
||||
// output pin and measure the voltage while the encoder is stopped
|
||||
// or running at a very slow speed. Even though the pin is rapidly
|
||||
// pulsing, a DC voltmeter will show the average voltage. Due to
|
||||
// software timing, it will read a number much less than a steady
|
||||
// logic high, but this number will give you a baseline reading
|
||||
// for output with minimal interrupt overhead. Then increase the
|
||||
// encoder speed. The voltage will decrease as the processor spends
|
||||
// more time in Encoder's interrupt routines counting the pulses
|
||||
// and less time pulsing the output pin. When the voltage is
|
||||
// close to zero and will not decrease any farther, you have reached
|
||||
// the absolute speed limit. Or, if using a mechanical system where
|
||||
// you reach a speed limit imposed by your motors or other hardware,
|
||||
// the amount this voltage has decreased, compared to the baseline,
|
||||
// should give you a good approximation of the portion of available
|
||||
// CPU time Encoder is consuming at your maximum speed.
|
||||
|
||||
// Encoder requires low latency interrupt response. Available CPU
|
||||
// time does NOT necessarily prove or guarantee correct performance.
|
||||
// If another library, like NewSoftSerial, is disabling interrupts
|
||||
// for lengthy periods of time, Encoder can be prevented from
|
||||
// properly counting the intput signals while interrupt are disabled.
|
||||
|
||||
|
||||
// This optional setting causes Encoder to use more optimized code,
|
||||
// but the downside is a conflict if any other part of your sketch
|
||||
// or any other library you're using requires attachInterrupt().
|
||||
// It must be defined before Encoder.h is included.
|
||||
//#define ENCODER_OPTIMIZE_INTERRUPTS
|
||||
|
||||
#include <Encoder.h>
|
||||
#include "pins_arduino.h"
|
||||
|
||||
// Change these two numbers to the pins connected to your encoder
|
||||
// or shift register circuit which emulates a quadrature encoder
|
||||
// case 1: both pins are interrupts
|
||||
// case 2: only first pin used as interrupt
|
||||
Encoder myEnc(5, 6);
|
||||
|
||||
// Connect a DC voltmeter to this pin.
|
||||
const int outputPin = 12;
|
||||
|
||||
/* This simple circuit, using a Dual Flip-Flop chip, can emulate
|
||||
quadrature encoder signals. The clock can come from a fancy
|
||||
function generator or a cheap 555 timer chip. The clock
|
||||
frequency can be measured with another board running FreqCount
|
||||
http://www.pjrc.com/teensy/td_libs_FreqCount.html
|
||||
|
||||
+5V
|
||||
| Quadrature Encoder Signal Emulator
|
||||
Clock |
|
||||
Input o----*-------------------------- ---------------------------o Output1
|
||||
| |14 | |
|
||||
| _______|_______ | | _______________
|
||||
| | CD4013 | | | | CD4013 |
|
||||
| 5 | | 1 | | 9 | | 13
|
||||
---------| D Q |-----|----*----| D Q |------o Output2
|
||||
| | | | | | |
|
||||
| | 3 | | | 11 | |
|
||||
| ----|> Clk | ---------|> Clk |
|
||||
| | | | |
|
||||
| 6 | | 8 | |
|
||||
| ----| S | ----| S |
|
||||
| | | | | | |
|
||||
| | 4 | _ | 2 | 10 | _ | 12
|
||||
| *----| R Q |--- *----| R Q |----
|
||||
| | | | | | | |
|
||||
| | |_______________| | |_______________| |
|
||||
| | | | |
|
||||
| | | 7 | |
|
||||
| | | | |
|
||||
--------------------------------------------------------------
|
||||
| | |
|
||||
| | |
|
||||
----- ----- -----
|
||||
--- --- ---
|
||||
- - -
|
||||
*/
|
||||
|
||||
|
||||
void setup() {
|
||||
pinMode(outputPin, OUTPUT);
|
||||
}
|
||||
|
||||
#if defined(__AVR__)
|
||||
#define REGTYPE unsigned char
|
||||
#elif defined(__PIC32MX__)
|
||||
#define REGTYPE unsigned long
|
||||
#endif
|
||||
|
||||
void loop() {
|
||||
volatile int count = 0;
|
||||
volatile REGTYPE *reg = portOutputRegister(digitalPinToPort(outputPin));
|
||||
REGTYPE mask = digitalPinToBitMask(outputPin);
|
||||
|
||||
while (1) {
|
||||
myEnc.read(); // Read the encoder while interrupts are enabled.
|
||||
noInterrupts();
|
||||
*reg |= mask; // Pulse the pin high, while interrupts are disabled.
|
||||
count = count + 1;
|
||||
*reg &= ~mask;
|
||||
interrupts();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/* Encoder Library - TwoKnobs Example
|
||||
* http://www.pjrc.com/teensy/td_libs_Encoder.html
|
||||
*
|
||||
* This example code is in the public domain.
|
||||
*/
|
||||
|
||||
#include <Encoder.h>
|
||||
|
||||
// Change these pin numbers to the pins connected to your encoder.
|
||||
// Best Performance: both pins have interrupt capability
|
||||
// Good Performance: only the first pin has interrupt capability
|
||||
// Low Performance: neither pin has interrupt capability
|
||||
Encoder knobLeft(5, 6);
|
||||
Encoder knobRight(7, 8);
|
||||
// avoid using pins with LEDs attached
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
Serial.println("TwoKnobs Encoder Test:");
|
||||
}
|
||||
|
||||
long positionLeft = -999;
|
||||
long positionRight = -999;
|
||||
|
||||
void loop() {
|
||||
long newLeft, newRight;
|
||||
newLeft = knobLeft.read();
|
||||
newRight = knobRight.read();
|
||||
if (newLeft != positionLeft || newRight != positionRight) {
|
||||
Serial.print("Left = ");
|
||||
Serial.print(newLeft);
|
||||
Serial.print(", Right = ");
|
||||
Serial.print(newRight);
|
||||
Serial.println();
|
||||
positionLeft = newLeft;
|
||||
positionRight = newRight;
|
||||
}
|
||||
// if a character is sent from the serial monitor,
|
||||
// reset both back to zero.
|
||||
if (Serial.available()) {
|
||||
Serial.read();
|
||||
Serial.println("Reset both knobs to zero");
|
||||
knobLeft.write(0);
|
||||
knobRight.write(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
ENCODER_USE_INTERRUPTS LITERAL1
|
||||
ENCODER_OPTIMIZE_INTERRUPTS LITERAL1
|
||||
ENCODER_DO_NOT_USE_INTERRUPTS LITERAL1
|
||||
Encoder KEYWORD1
|
||||
@@ -0,0 +1,27 @@
|
||||
#ifndef direct_pin_read_h_
|
||||
#define direct_pin_read_h_
|
||||
|
||||
#if defined(__AVR__) || defined(__MK20DX128__) || defined(__MK20DX256__)
|
||||
|
||||
#define IO_REG_TYPE uint8_t
|
||||
#define PIN_TO_BASEREG(pin) (portInputRegister(digitalPinToPort(pin)))
|
||||
#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin))
|
||||
#define DIRECT_PIN_READ(base, mask) (((*(base)) & (mask)) ? 1 : 0)
|
||||
|
||||
#elif defined(__SAM3X8E__)
|
||||
|
||||
#define IO_REG_TYPE uint32_t
|
||||
#define PIN_TO_BASEREG(pin) (portInputRegister(digitalPinToPort(pin)))
|
||||
#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin))
|
||||
#define DIRECT_PIN_READ(base, mask) (((*(base)) & (mask)) ? 1 : 0)
|
||||
|
||||
#elif defined(__PIC32MX__)
|
||||
|
||||
#define IO_REG_TYPE uint32_t
|
||||
#define PIN_TO_BASEREG(pin) (portModeRegister(digitalPinToPort(pin)))
|
||||
#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin))
|
||||
#define DIRECT_PIN_READ(base, mask) (((*(base+4)) & (mask)) ? 1 : 0)
|
||||
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,87 @@
|
||||
#if defined(__AVR__)
|
||||
|
||||
#include <avr/io.h>
|
||||
#include <avr/interrupt.h>
|
||||
|
||||
#define attachInterrupt(num, func, mode) enableInterrupt(num)
|
||||
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
|
||||
#define SCRAMBLE_INT_ORDER(num) ((num < 4) ? num + 2 : ((num < 6) ? num - 4 : num))
|
||||
#define DESCRAMBLE_INT_ORDER(num) ((num < 2) ? num + 4 : ((num < 6) ? num - 2 : num))
|
||||
#else
|
||||
#define SCRAMBLE_INT_ORDER(num) (num)
|
||||
#define DESCRAMBLE_INT_ORDER(num) (num)
|
||||
#endif
|
||||
|
||||
static void enableInterrupt(uint8_t num)
|
||||
{
|
||||
switch (DESCRAMBLE_INT_ORDER(num)) {
|
||||
#if defined(EICRA) && defined(EIMSK)
|
||||
case 0:
|
||||
EICRA = (EICRA & 0xFC) | 0x01;
|
||||
EIMSK |= 0x01;
|
||||
return;
|
||||
case 1:
|
||||
EICRA = (EICRA & 0xF3) | 0x04;
|
||||
EIMSK |= 0x02;
|
||||
return;
|
||||
case 2:
|
||||
EICRA = (EICRA & 0xCF) | 0x10;
|
||||
EIMSK |= 0x04;
|
||||
return;
|
||||
case 3:
|
||||
EICRA = (EICRA & 0x3F) | 0x40;
|
||||
EIMSK |= 0x08;
|
||||
return;
|
||||
#elif defined(MCUCR) && defined(GICR)
|
||||
case 0:
|
||||
MCUCR = (MCUCR & ~((1 << ISC00) | (1 << ISC01))) | (mode << ISC00);
|
||||
GICR |= (1 << INT0);
|
||||
return;
|
||||
case 1:
|
||||
MCUCR = (MCUCR & ~((1 << ISC10) | (1 << ISC11))) | (mode << ISC10);
|
||||
GICR |= (1 << INT1);
|
||||
return;
|
||||
#elif defined(MCUCR) && defined(GIMSK)
|
||||
case 0:
|
||||
MCUCR = (MCUCR & ~((1 << ISC00) | (1 << ISC01))) | (mode << ISC00);
|
||||
GIMSK |= (1 << INT0);
|
||||
return;
|
||||
case 1:
|
||||
MCUCR = (MCUCR & ~((1 << ISC10) | (1 << ISC11))) | (mode << ISC10);
|
||||
GIMSK |= (1 << INT1);
|
||||
return;
|
||||
#endif
|
||||
#if defined(EICRB) && defined(EIMSK)
|
||||
case 4:
|
||||
EICRB = (EICRB & 0xFC) | 0x01;
|
||||
EIMSK |= 0x10;
|
||||
return;
|
||||
case 5:
|
||||
EICRB = (EICRB & 0xF3) | 0x04;
|
||||
EIMSK |= 0x20;
|
||||
return;
|
||||
case 6:
|
||||
EICRB = (EICRB & 0xCF) | 0x10;
|
||||
EIMSK |= 0x40;
|
||||
return;
|
||||
case 7:
|
||||
EICRB = (EICRB & 0x3F) | 0x40;
|
||||
EIMSK |= 0x80;
|
||||
return;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#elif defined(__PIC32MX__)
|
||||
|
||||
#ifdef ENCODER_OPTIMIZE_INTERRUPTS
|
||||
#undef ENCODER_OPTIMIZE_INTERRUPTS
|
||||
#endif
|
||||
|
||||
#else
|
||||
|
||||
#ifdef ENCODER_OPTIMIZE_INTERRUPTS
|
||||
#undef ENCODER_OPTIMIZE_INTERRUPTS
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,156 @@
|
||||
// interrupt pins for known boards
|
||||
|
||||
// Teensy (and maybe others) define these automatically
|
||||
#if !defined(CORE_NUM_INTERRUPT)
|
||||
|
||||
// Wiring boards
|
||||
#if defined(WIRING)
|
||||
#define CORE_NUM_INTERRUPT NUM_EXTERNAL_INTERRUPTS
|
||||
#if NUM_EXTERNAL_INTERRUPTS > 0
|
||||
#define CORE_INT0_PIN EI0
|
||||
#endif
|
||||
#if NUM_EXTERNAL_INTERRUPTS > 1
|
||||
#define CORE_INT1_PIN EI1
|
||||
#endif
|
||||
#if NUM_EXTERNAL_INTERRUPTS > 2
|
||||
#define CORE_INT2_PIN EI2
|
||||
#endif
|
||||
#if NUM_EXTERNAL_INTERRUPTS > 3
|
||||
#define CORE_INT3_PIN EI3
|
||||
#endif
|
||||
#if NUM_EXTERNAL_INTERRUPTS > 4
|
||||
#define CORE_INT4_PIN EI4
|
||||
#endif
|
||||
#if NUM_EXTERNAL_INTERRUPTS > 5
|
||||
#define CORE_INT5_PIN EI5
|
||||
#endif
|
||||
#if NUM_EXTERNAL_INTERRUPTS > 6
|
||||
#define CORE_INT6_PIN EI6
|
||||
#endif
|
||||
#if NUM_EXTERNAL_INTERRUPTS > 7
|
||||
#define CORE_INT7_PIN EI7
|
||||
#endif
|
||||
|
||||
// Arduino Uno, Duemilanove, Diecimila, LilyPad, Mini, Fio, etc...
|
||||
#elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega8__)
|
||||
#define CORE_NUM_INTERRUPT 2
|
||||
#define CORE_INT0_PIN 2
|
||||
#define CORE_INT1_PIN 3
|
||||
|
||||
// Arduino Mega
|
||||
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
|
||||
#define CORE_NUM_INTERRUPT 6
|
||||
#define CORE_INT0_PIN 2
|
||||
#define CORE_INT1_PIN 3
|
||||
#define CORE_INT2_PIN 21
|
||||
#define CORE_INT3_PIN 20
|
||||
#define CORE_INT4_PIN 19
|
||||
#define CORE_INT5_PIN 18
|
||||
|
||||
// Arduino Leonardo (untested)
|
||||
#elif defined(__AVR_ATmega32U4__) && !defined(CORE_TEENSY)
|
||||
#define CORE_NUM_INTERRUPT 4
|
||||
#define CORE_INT0_PIN 3
|
||||
#define CORE_INT1_PIN 2
|
||||
#define CORE_INT2_PIN 0
|
||||
#define CORE_INT3_PIN 1
|
||||
|
||||
// Sanguino (untested)
|
||||
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)
|
||||
#define CORE_NUM_INTERRUPT 3
|
||||
#define CORE_INT0_PIN 10
|
||||
#define CORE_INT1_PIN 11
|
||||
#define CORE_INT2_PIN 2
|
||||
|
||||
// Chipkit Uno32 - attachInterrupt may not support CHANGE option
|
||||
#elif defined(__PIC32MX__) && defined(_BOARD_UNO_)
|
||||
#define CORE_NUM_INTERRUPT 5
|
||||
#define CORE_INT0_PIN 38
|
||||
#define CORE_INT1_PIN 2
|
||||
#define CORE_INT2_PIN 7
|
||||
#define CORE_INT3_PIN 8
|
||||
#define CORE_INT4_PIN 35
|
||||
|
||||
// Chipkit Uno32 - attachInterrupt may not support CHANGE option
|
||||
#elif defined(__PIC32MX__) && defined(_BOARD_MEGA_)
|
||||
#define CORE_NUM_INTERRUPT 5
|
||||
#define CORE_INT0_PIN 3
|
||||
#define CORE_INT1_PIN 2
|
||||
#define CORE_INT2_PIN 7
|
||||
#define CORE_INT3_PIN 21
|
||||
#define CORE_INT4_PIN 20
|
||||
|
||||
// http://hlt.media.mit.edu/?p=1229
|
||||
#elif defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
|
||||
#define CORE_NUM_INTERRUPT 1
|
||||
#define CORE_INT0_PIN 2
|
||||
|
||||
// Arduino Due (untested)
|
||||
#elif defined(__SAM3X8E__)
|
||||
#define CORE_NUM_INTERRUPT 54
|
||||
#define CORE_INT0_PIN 0
|
||||
#define CORE_INT1_PIN 1
|
||||
#define CORE_INT2_PIN 2
|
||||
#define CORE_INT3_PIN 3
|
||||
#define CORE_INT4_PIN 4
|
||||
#define CORE_INT5_PIN 5
|
||||
#define CORE_INT6_PIN 6
|
||||
#define CORE_INT7_PIN 7
|
||||
#define CORE_INT8_PIN 8
|
||||
#define CORE_INT9_PIN 9
|
||||
#define CORE_INT10_PIN 10
|
||||
#define CORE_INT11_PIN 11
|
||||
#define CORE_INT12_PIN 12
|
||||
#define CORE_INT13_PIN 13
|
||||
#define CORE_INT14_PIN 14
|
||||
#define CORE_INT15_PIN 15
|
||||
#define CORE_INT16_PIN 16
|
||||
#define CORE_INT17_PIN 17
|
||||
#define CORE_INT18_PIN 18
|
||||
#define CORE_INT19_PIN 19
|
||||
#define CORE_INT20_PIN 20
|
||||
#define CORE_INT21_PIN 21
|
||||
#define CORE_INT22_PIN 22
|
||||
#define CORE_INT23_PIN 23
|
||||
#define CORE_INT24_PIN 24
|
||||
#define CORE_INT25_PIN 25
|
||||
#define CORE_INT26_PIN 26
|
||||
#define CORE_INT27_PIN 27
|
||||
#define CORE_INT28_PIN 28
|
||||
#define CORE_INT29_PIN 29
|
||||
#define CORE_INT30_PIN 30
|
||||
#define CORE_INT31_PIN 31
|
||||
#define CORE_INT32_PIN 32
|
||||
#define CORE_INT33_PIN 33
|
||||
#define CORE_INT34_PIN 34
|
||||
#define CORE_INT35_PIN 35
|
||||
#define CORE_INT36_PIN 36
|
||||
#define CORE_INT37_PIN 37
|
||||
#define CORE_INT38_PIN 38
|
||||
#define CORE_INT39_PIN 39
|
||||
#define CORE_INT40_PIN 40
|
||||
#define CORE_INT41_PIN 41
|
||||
#define CORE_INT42_PIN 42
|
||||
#define CORE_INT43_PIN 43
|
||||
#define CORE_INT44_PIN 44
|
||||
#define CORE_INT45_PIN 45
|
||||
#define CORE_INT46_PIN 46
|
||||
#define CORE_INT47_PIN 47
|
||||
#define CORE_INT48_PIN 48
|
||||
#define CORE_INT49_PIN 49
|
||||
#define CORE_INT50_PIN 50
|
||||
#define CORE_INT51_PIN 51
|
||||
#define CORE_INT52_PIN 52
|
||||
#define CORE_INT53_PIN 53
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if !defined(CORE_NUM_INTERRUPT)
|
||||
#error "Interrupts are unknown for this board, please add to this code"
|
||||
#endif
|
||||
#if CORE_NUM_INTERRUPT <= 0
|
||||
#error "Encoder requires interrupt pins, but this board does not have any :("
|
||||
#error "You could try defining ENCODER_DO_NOT_USE_INTERRUPTS as a kludge."
|
||||
#endif
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
#define DEBUG
|
||||
|
||||
// Serial output baud rate (for debug prints and serial gateway)
|
||||
#define BAUD_RATE 115200
|
||||
#define MY_BAUD_RATE 115200
|
||||
|
||||
|
||||
/**********************************
|
||||
@@ -53,7 +53,14 @@
|
||||
// but now can be used in any sensor node. Also the LEDs can now be
|
||||
// disabled in the gateway.
|
||||
|
||||
// #define MY_LEDS_BLINKING_FEATURE
|
||||
//#define MY_WITH_LEDS_BLINKING
|
||||
|
||||
// The following setting allows you to inverse the blinking feature WITH_LEDS_BLINKING
|
||||
// When WITH_LEDS_BLINKING_INVERSE is enabled LEDSs are normally turned on and switches
|
||||
// off when blinking
|
||||
|
||||
//#define WITH_LEDS_BLINKING_INVERSE
|
||||
|
||||
|
||||
// default LEDs blinking period in milliseconds
|
||||
#define MY_DEFAULT_LED_BLINK_PERIOD 300
|
||||
@@ -113,8 +120,7 @@
|
||||
#define MY_RANDOMSEED_PIN 7 // A7 - Pin used for random generation (do not connect anything to this)
|
||||
|
||||
// Key to use for HMAC calculation in MySigningAtsha204Soft (32 bytes)
|
||||
#define MY_HMAC_KEY 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\
|
||||
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
|
||||
#define MY_HMAC_KEY 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
|
||||
|
||||
|
||||
/**********************************
|
||||
|
||||
@@ -37,13 +37,41 @@
|
||||
#include <SPI.h>
|
||||
#endif
|
||||
|
||||
#if defined __AVR_ATmega328P__
|
||||
#ifndef sleep_bod_disable
|
||||
#define sleep_bod_disable() \
|
||||
do { \
|
||||
unsigned char tempreg; \
|
||||
__asm__ __volatile__("in %[tempreg], %[mcucr]" "\n\t" \
|
||||
"ori %[tempreg], %[bods_bodse]" "\n\t" \
|
||||
"out %[mcucr], %[tempreg]" "\n\t" \
|
||||
"andi %[tempreg], %[not_bodse]" "\n\t" \
|
||||
"out %[mcucr], %[tempreg]" \
|
||||
: [tempreg] "=&d" (tempreg) \
|
||||
: [mcucr] "I" _SFR_IO_ADDR(MCUCR), \
|
||||
[bods_bodse] "i" (_BV(BODS) | _BV(BODSE)), \
|
||||
[not_bodse] "i" (~_BV(BODSE))); \
|
||||
} while (0)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
// Define these as macros to save valuable space
|
||||
#define hw_init() Serial.begin(BAUD_RATE)
|
||||
|
||||
#define hw_digitalWrite(__pin, __value) (digitalWrite(__pin, __value))
|
||||
#define hw_init() Serial.begin(MY_BAUD_RATE)
|
||||
#define hw_watchdogReset() wdt_reset()
|
||||
#define hw_reboot() wdt_enable(WDTO_15MS); while (1)
|
||||
#define hw_millis() millis()
|
||||
#define hw_readConfig(__pos) (eeprom_read_byte((uint8_t*)(__pos)))
|
||||
#define hw_writeConfig(__pos, __value) (eeprom_update_byte((uint8_t*)(__pos), (__value)))
|
||||
|
||||
#ifndef eeprom_update_byte
|
||||
#define hw_writeConfig(loc, val) if((uint8_t)(val) != eeprom_read_byte((uint8_t*)(loc))) { eeprom_write_byte((uint8_t*)(loc), (val)); }
|
||||
#else
|
||||
#define hw_writeConfig(__pos, __value) (eeprom_update_byte((uint8_t*)(__pos), (__value)))
|
||||
#endif
|
||||
|
||||
//
|
||||
#define hw_readConfigBlock(__buf, __pos, __length) (eeprom_read_block((__buf), (void*)(__pos), (__length)))
|
||||
#define hw_writeConfigBlock(__pos, __buf, __length) (eeprom_write_block((void*)(__pos), (void*)__buf, (__length)))
|
||||
|
||||
|
||||
@@ -81,12 +81,11 @@ char* MyMessage::getStream(char *buffer) const {
|
||||
|
||||
char* MyMessage::getString(char *buffer) const {
|
||||
uint8_t payloadType = miGetPayloadType();
|
||||
if (payloadType == P_STRING) {
|
||||
strncpy(buffer, data, miGetLength());
|
||||
buffer[miGetLength()] = 0;
|
||||
return buffer;
|
||||
} else if (buffer != NULL) {
|
||||
if (payloadType == P_BYTE) {
|
||||
if (buffer != NULL) {
|
||||
if (payloadType == P_STRING) {
|
||||
strncpy(buffer, data, miGetLength());
|
||||
buffer[miGetLength()] = 0;
|
||||
} else if (payloadType == P_BYTE) {
|
||||
itoa(bValue, buffer, 10);
|
||||
} else if (payloadType == P_INT16) {
|
||||
itoa(iValue, buffer, 10);
|
||||
|
||||
@@ -41,12 +41,55 @@ typedef enum {
|
||||
C_STREAM = 4 // For Firmware and other larger chunks of data that need to be divided into pieces.
|
||||
} mysensor_command;
|
||||
|
||||
// Type of sensor (used when presenting sensors)
|
||||
typedef enum {
|
||||
S_DOOR, // Door sensor, V_TRIPPED, V_ARMED
|
||||
S_MOTION, // Motion sensor, V_TRIPPED, V_ARMED
|
||||
S_SMOKE, // Smoke sensor, V_TRIPPED, V_ARMED
|
||||
S_LIGHT, // Binary light or relay, V_STATUS (or V_LIGHT), V_WATT
|
||||
S_BINARY=3, // Binary light or relay, V_STATUS (or V_LIGHT), V_WATT (same as S_LIGHT)
|
||||
S_DIMMER, // Dimmable light or fan device, V_STATUS (on/off), V_DIMMER (dimmer level 0-100), V_WATT
|
||||
S_COVER, // Blinds or window cover, V_UP, V_DOWN, V_STOP, V_DIMMER (open/close to a percentage)
|
||||
S_TEMP, // Temperature sensor, V_TEMP
|
||||
S_HUM, // Humidity sensor, V_HUM
|
||||
S_BARO, // Barometer sensor, V_PRESSURE, V_FORECAST
|
||||
S_WIND, // Wind sensor, V_WIND, V_GUST
|
||||
S_RAIN, // Rain sensor, V_RAIN, V_RAINRATE
|
||||
S_UV, // Uv sensor, V_UV
|
||||
S_WEIGHT, // Personal scale sensor, V_WEIGHT, V_IMPEDANCE
|
||||
S_POWER, // Power meter, V_WATT, V_KWH
|
||||
S_HEATER, // Header device, V_HVAC_SETPOINT_HEAT, V_HVAC_FLOW_STATE
|
||||
S_DISTANCE, // Distance sensor, V_DISTANCE
|
||||
S_LIGHT_LEVEL, // Light level sensor, V_LIGHT_LEVEL (uncalibrated in percentage), V_LEVEL (light level in lux)
|
||||
S_ARDUINO_NODE, // Used (internally) for presenting a non-repeating Arduino node
|
||||
S_ARDUINO_REPEATER_NODE, // Used (internally) for presenting a repeating Arduino node
|
||||
S_LOCK, // Lock device, V_LOCK_STATUS
|
||||
S_IR, // Ir device, V_IR_SEND, V_IR_RECEIVE
|
||||
S_WATER, // Water meter, V_FLOW, V_VOLUME
|
||||
S_AIR_QUALITY, // Air quality sensor, V_LEVEL
|
||||
S_CUSTOM, // Custom sensor
|
||||
S_DUST, // Dust sensor, V_LEVEL
|
||||
S_SCENE_CONTROLLER, // Scene controller device, V_SCENE_ON, V_SCENE_OFF.
|
||||
S_RGB_LIGHT, // RGB light. Send color component data using V_RGB. Also supports V_WATT
|
||||
S_RGBW_LIGHT, // RGB light with an additional White component. Send data using V_RGBW. Also supports V_WATT
|
||||
S_COLOR_SENSOR, // Color sensor, send color information using V_RGB
|
||||
S_HVAC, // Thermostat/HVAC device. V_HVAC_SETPOINT_HEAT, V_HVAC_SETPOINT_COLD, V_HVAC_FLOW_STATE, V_HVAC_FLOW_MODE
|
||||
S_MULTIMETER, // Multimeter device, V_VOLTAGE, V_CURRENT, V_IMPEDANCE
|
||||
S_SPRINKLER, // Sprinkler, V_STATUS (turn on/off), V_TRIPPED (if fire detecting device)
|
||||
S_WATER_LEAK, // Water leak sensor, V_TRIPPED, V_ARMED
|
||||
S_SOUND, // Sound sensor, V_TRIPPED, V_ARMED, V_LEVEL (sound level in dB)
|
||||
S_VIBRATION, // Vibration sensor, V_TRIPPED, V_ARMED, V_LEVEL (vibration in Hz)
|
||||
S_MOISTURE, // Moisture sensor, V_TRIPPED, V_ARMED, V_LEVEL (water content or moisture in percentage?)
|
||||
} mysensor_sensor;
|
||||
|
||||
// Type of sensor data (for set/req/ack messages)
|
||||
typedef enum {
|
||||
V_TEMP, // S_TEMP
|
||||
V_HUM, // S_HUM
|
||||
V_LIGHT, // S_LIGHT (Light level in uncalibrated percentage)
|
||||
V_DIMMER, // S_DIMMER
|
||||
V_STATUS, // S_LIGHT, S_DIMMER, S_SPRINKLER, S_HVAC, S_HEATER. Used for setting binary (on/off) status. 1=on, 0=off
|
||||
V_LIGHT=2, // Same as V_STATUS
|
||||
V_PERCENTAGE, // S_DIMMER. Used for sending a percentage value (0-100).
|
||||
V_DIMMER=3, // S_DIMMER. Same as V_PERCENTAGE.
|
||||
V_PRESSURE, // S_BARO
|
||||
V_FORECAST, // S_BARO
|
||||
V_RAIN, // S_RAIN
|
||||
@@ -59,14 +102,15 @@ typedef enum {
|
||||
V_DISTANCE, // S_DISTANCE
|
||||
V_IMPEDANCE, // S_MULTIMETER, S_WEIGHT
|
||||
V_ARMED, // S_DOOR, S_MOTION, S_SMOKE, S_SPRINKLER
|
||||
V_TRIPPED, // S_DOOR, S_MOTION, S_SMOKE, S_SPRINKLER
|
||||
V_WATT, // S_POWER
|
||||
V_TRIPPED, // S_DOOR, S_MOTION, S_SMOKE, S_SPRINKLER (for sprinklers with fire detection)
|
||||
V_WATT, // S_POWER, S_LIGHT, S_DIMMER
|
||||
V_KWH, // S_POWER
|
||||
V_SCENE_ON, // S_SCENE_CONTROLLER
|
||||
V_SCENE_OFF, // S_SCENE_CONTROLLER
|
||||
V_HEATER, // S_HEATER
|
||||
V_HEATER_SW, // S_HEATER
|
||||
V_LIGHT_LEVEL, // S_LIGHT_LEVEL
|
||||
V_HEATER, // Deprecated. Use V_HVAC_FLOW_STATE instead.
|
||||
V_HVAC_FLOW_STATE=21, // HVAC flow state ("Off", "HeatOn", "CoolOn", or "AutoChangeOver"). S_HEATER, S_HVAC
|
||||
V_HVAC_SPEED, // HVAC/Heater fan speed ("Min", "Normal", "Max", "Auto")
|
||||
V_LIGHT_LEVEL, // Used for sending light level in uncalibrated percentage. See also V_LEVEL (light level in lux). S_LIGHT_LEVEL
|
||||
V_VAR1, V_VAR2, V_VAR3, V_VAR4, V_VAR5,
|
||||
V_UP, // S_COVER
|
||||
V_DOWN, // S_COVER
|
||||
@@ -76,72 +120,36 @@ typedef enum {
|
||||
V_FLOW, // S_WATER
|
||||
V_VOLUME, // S_WATER
|
||||
V_LOCK_STATUS, // S_LOCK
|
||||
V_DUST_LEVEL, // S_DUST
|
||||
V_LEVEL, // S_DUST, S_AIR_QUALITY, S_SOUND (dB), S_VIBRATION (hz), S_LIGHT_LEVEL (lux)
|
||||
V_VOLTAGE, // S_MULTIMETER
|
||||
V_CURRENT, // S_MULTIMETER
|
||||
V_RGB, // S_RGB_LIGHT, S_COLOR_SENSOR.
|
||||
// Used for sending color information for led lighting or color sensors.
|
||||
// Sent as ascii hex. RRGGBB (RR=red, GG=green, BB=blue component)
|
||||
V_RGBW, // S_RGB_LIGHT
|
||||
// Used for sending color information to led lighting.
|
||||
// Sent as ascii hex. RRGGBBWW (WW=while component)
|
||||
// Used for sending color information for multi color LED lighting or color sensors.
|
||||
// Sent as ASCII hex: RRGGBB (RR=red, GG=green, BB=blue component)
|
||||
V_RGBW, // S_RGBW_LIGHT
|
||||
// Used for sending color information to multi color LED lighting.
|
||||
// Sent as ASCII hex: RRGGBBWW (WW=while component)
|
||||
V_ID, // S_TEMP
|
||||
// Used for reporting the sensor internal ids (E.g. DS1820b).
|
||||
V_LIGHT_LEVEL_LUX, // S_LIGHT, Light level in lux
|
||||
// Used for sending in sensors hardware ids (i.e. OneWire DS1820b).
|
||||
V_UNIT_PREFIX, // Allows sensors to send in a string representing the
|
||||
// unit prefix to be displayed in GUI, not parsed! E.g. cm, m, km, inch.
|
||||
// Can be used for S_DISTANCE
|
||||
V_SOUND_DB, // S_SOUND sound level in db
|
||||
V_VIBRATION_HZ, // S_VIBRATION vibration i Hz
|
||||
V_ENCODER_VALUE, // S_ROTARY_ENCODER. Rotary encoder value.
|
||||
// unit prefix to be displayed in GUI, not parsed by controller! E.g. cm, m, km, inch.
|
||||
// Can be used for S_DISTANCE or gas concentration (S_DUST, S_AIR_QUALITY)
|
||||
V_HVAC_SETPOINT_COOL, // HVAC cool setpoint (Integer between 0-100). S_HVAC
|
||||
V_HVAC_SETPOINT_HEAT, // HVAC/Heater setpoint (Integer between 0-100). S_HEATER, S_HVAC
|
||||
V_HVAC_FLOW_MODE, // Flow mode for HVAC ("Auto", "ContinuousOn", "PeriodicOn"). S_HVAC
|
||||
|
||||
} mysensor_data;
|
||||
|
||||
|
||||
// Type of internal messages (for internal messages)
|
||||
typedef enum {
|
||||
I_BATTERY_LEVEL, I_TIME, I_VERSION, I_ID_REQUEST, I_ID_RESPONSE,
|
||||
I_INCLUSION_MODE, I_CONFIG, I_FIND_PARENT, I_FIND_PARENT_RESPONSE,
|
||||
I_LOG_MESSAGE, I_CHILDREN, I_SKETCH_NAME, I_SKETCH_VERSION,
|
||||
I_REBOOT, I_GATEWAY_READY, I_REQUEST_SIGNING, I_GET_NONCE, I_GET_NONCE_RESPONSE
|
||||
I_REBOOT, I_GATEWAY_READY, I_REQUEST_SIGNING, I_GET_NONCE, I_GET_NONCE_RESPONSE,
|
||||
I_HEARTBEAT
|
||||
} mysensor_internal;
|
||||
|
||||
// Type of sensor (for presentation message)
|
||||
typedef enum {
|
||||
S_DOOR, // V_TRIPPED, V_ARMED
|
||||
S_MOTION, // V_TRIPPED, V_ARMED
|
||||
S_SMOKE, // V_TRIPPED, V_ARMED
|
||||
S_LIGHT, // V_LIGHT, V_WATT
|
||||
S_DIMMER, // V_DIMMER, V_WATT
|
||||
S_COVER, // V_UP, V_DOWN, V_STOP
|
||||
S_TEMP, // V_TEMP
|
||||
S_HUM, // V_HUM
|
||||
S_BARO, // V_PRESSURE, V_FORECAST
|
||||
S_WIND, // V_WIND, V_GUST
|
||||
S_RAIN, // V_RAIN, V_RAINRATE
|
||||
S_UV, // V_UV
|
||||
S_WEIGHT, // V_WEIGHT, V_IMPEDANCE
|
||||
S_POWER, // V_WATT, V_KWH
|
||||
S_HEATER, // V_HEATER, V_HEATER_SW
|
||||
S_DISTANCE, // V_DISTANCE
|
||||
S_LIGHT_LEVEL, // V_LIGHT
|
||||
S_ARDUINO_NODE,
|
||||
S_ARDUINO_REPEATER_NODE,
|
||||
S_LOCK, // V_LOCK_STATUS
|
||||
S_IR, // V_IR_SEND, V_IR_RECEIVE
|
||||
S_WATER, // V_FLOW, V_VOLUME
|
||||
S_AIR_QUALITY, // V_VAR1
|
||||
S_CUSTOM,
|
||||
S_DUST, // V_DUST_LEVEL
|
||||
S_SCENE_CONTROLLER, // V_SCENE_ON, V_SCENE_OFF.
|
||||
S_RGB_LIGHT, // Send data using V_RGB or V_RGBW
|
||||
S_COLOR_SENSOR, // Send data using V_RGB
|
||||
S_MULTIMETER, // V_VOLTAGE, V_CURRENT, V_IMPEDANCE
|
||||
S_SPRINKLER, // V_TRIPPED, V_ARMED
|
||||
S_WATER_LEAK, // V_TRIPPED, V_ARMED
|
||||
S_SOUND, // V_TRIPPED, V_ARMED, V_SOUND_DB
|
||||
S_VIBRATION, // V_TRIPPED, V_ARMED, V_VIBRATION_HZ
|
||||
S_ROTARY_ENCODER, // V_ENCODER_VALUE
|
||||
} mysensor_sensor;
|
||||
|
||||
// Type of data stream (for streamed message)
|
||||
typedef enum {
|
||||
|
||||
@@ -74,24 +74,21 @@ MySensor::MySensor(MyTransport &_radio, MyHw &_hw
|
||||
|
||||
|
||||
#ifdef MY_OTA_FIRMWARE_FEATURE
|
||||
// do a crc16 on the whole received firmware
|
||||
bool MySensor::isValidFirmware() {
|
||||
void* ptr = 0;
|
||||
uint16_t crc = ~0;
|
||||
int j;
|
||||
|
||||
// do a crc16 on the whole received firmware
|
||||
bool MySensor::isValidFirmware() {
|
||||
// init crc
|
||||
uint16_t crc = ~0;
|
||||
for (uint16_t i = 0; i < fc.blocks * FIRMWARE_BLOCK_SIZE; ++i) {
|
||||
uint8_t a = flash.readByte((uint16_t) ptr + i + FIRMWARE_START_OFFSET);
|
||||
crc ^= a;
|
||||
for (j = 0; j < 8; ++j)
|
||||
{
|
||||
crc ^= flash.readByte(i + FIRMWARE_START_OFFSET);
|
||||
for (int8_t j = 0; j < 8; ++j) {
|
||||
if (crc & 1)
|
||||
crc = (crc >> 1) ^ 0xA001;
|
||||
else
|
||||
crc = (crc >> 1);
|
||||
}
|
||||
}
|
||||
return crc == fc.crc;
|
||||
}
|
||||
return crc == fc.crc;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -110,33 +107,33 @@ void MySensor::handleLedsBlinking() {
|
||||
// do the actual blinking
|
||||
if(countRx && countRx != 255) {
|
||||
// switch led on
|
||||
digitalWrite(pinRx, LOW);
|
||||
hw_digitalWrite(pinRx, LED_ON);
|
||||
}
|
||||
else if(!countRx) {
|
||||
// switching off
|
||||
digitalWrite(pinRx, HIGH);
|
||||
hw_digitalWrite(pinRx, LED_OFF);
|
||||
}
|
||||
if(countRx != 255)
|
||||
--countRx;
|
||||
|
||||
if(countTx && countTx != 255) {
|
||||
// switch led on
|
||||
digitalWrite(pinTx, LOW);
|
||||
hw_digitalWrite(pinTx, LED_ON);
|
||||
}
|
||||
else if(!countTx) {
|
||||
// switching off
|
||||
digitalWrite(pinTx, HIGH);
|
||||
hw_digitalWrite(pinTx, LED_OFF);
|
||||
}
|
||||
if(countTx != 255)
|
||||
--countTx;
|
||||
|
||||
if(countErr && countErr != 255) {
|
||||
// switch led on
|
||||
digitalWrite(pinEr, LOW);
|
||||
hw_digitalWrite(pinEr, LED_ON);
|
||||
}
|
||||
else if(!countErr) {
|
||||
// switching off
|
||||
digitalWrite(pinEr, HIGH);
|
||||
hw_digitalWrite(pinEr, LED_OFF);
|
||||
}
|
||||
if(countErr != 255)
|
||||
--countErr;
|
||||
@@ -182,9 +179,9 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b
|
||||
pinMode(pinEr, OUTPUT);
|
||||
|
||||
// Set initial state of leds
|
||||
digitalWrite(pinRx, HIGH);
|
||||
digitalWrite(pinTx, HIGH);
|
||||
digitalWrite(pinEr, HIGH);
|
||||
hw_digitalWrite(pinRx, LED_OFF);
|
||||
hw_digitalWrite(pinTx, LED_OFF);
|
||||
hw_digitalWrite(pinEr, LED_OFF);
|
||||
|
||||
// initialize counters
|
||||
countRx = 0;
|
||||
@@ -302,6 +299,12 @@ void MySensor::setupNode() {
|
||||
}
|
||||
|
||||
void MySensor::findParentNode() {
|
||||
static boolean findingParentNode = false;
|
||||
|
||||
if (findingParentNode)
|
||||
return;
|
||||
findingParentNode = true;
|
||||
|
||||
failedTransmissions = 0;
|
||||
|
||||
// Set distance to max
|
||||
@@ -316,6 +319,7 @@ void MySensor::findParentNode() {
|
||||
|
||||
// Wait for ping response.
|
||||
wait(2000);
|
||||
findingParentNode = false;
|
||||
}
|
||||
|
||||
boolean MySensor::sendRoute(MyMessage &message) {
|
||||
@@ -346,7 +350,7 @@ boolean MySensor::sendRoute(MyMessage &message) {
|
||||
|
||||
#ifdef MY_SIGNING_FEATURE
|
||||
// If destination is known to require signed messages and we are the sender, sign this message unless it is an ACK or a handshake message
|
||||
if (DO_SIGN(message.destination) && message.sender == nc.nodeId && !mGetAck(message) && mGetLength(msg) &&
|
||||
if (DO_SIGN(message.destination) && message.sender == nc.nodeId && !mGetAck(message) && mGetLength(message) &&
|
||||
(mGetCommand(message) != C_INTERNAL ||
|
||||
(message.type != I_GET_NONCE && message.type != I_GET_NONCE_RESPONSE && message.type != I_REQUEST_SIGNING &&
|
||||
message.type != I_ID_REQUEST && message.type != I_ID_RESPONSE &&
|
||||
@@ -483,8 +487,13 @@ void MySensor::sendBatteryLevel(uint8_t value, bool enableAck) {
|
||||
sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_BATTERY_LEVEL, enableAck).set(value));
|
||||
}
|
||||
|
||||
void MySensor::present(uint8_t childSensorId, uint8_t sensorType, bool enableAck) {
|
||||
sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, childSensorId, C_PRESENTATION, sensorType, enableAck).set(LIBRARY_VERSION));
|
||||
void MySensor::sendHeartbeat(void) {
|
||||
sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_HEARTBEAT, false).set(heartbeat++));
|
||||
|
||||
}
|
||||
|
||||
void MySensor::present(uint8_t childSensorId, uint8_t sensorType, const char *description, bool enableAck) {
|
||||
sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, childSensorId, C_PRESENTATION, sensorType, enableAck).set(childSensorId==NODE_SENSOR_ID?LIBRARY_VERSION:description));
|
||||
}
|
||||
|
||||
void MySensor::sendSketchInfo(const char *name, const char *version, bool enableAck) {
|
||||
@@ -518,7 +527,7 @@ boolean MySensor::process() {
|
||||
#ifdef MY_OTA_FIRMWARE_FEATURE
|
||||
unsigned long enter = hw_millis();
|
||||
if (fwUpdateOngoing && (enter - fwLastRequestTime > MY_OTA_RETRY_DELAY)) {
|
||||
if (fwRetry == 0) {
|
||||
if (!fwRetry) {
|
||||
debug(PSTR("fw upd fail\n"));
|
||||
// Give up. We have requested MY_OTA_RETRY times without any packet in return.
|
||||
fwUpdateOngoing = false;
|
||||
@@ -691,46 +700,61 @@ boolean MySensor::process() {
|
||||
// compare with current node configuration, if they differ, start fw fetch process
|
||||
if (memcmp(&fc,firmwareConfigResponse,sizeof(NodeFirmwareConfig))) {
|
||||
debug(PSTR("fw update\n"));
|
||||
fwUpdateOngoing = true;
|
||||
fwBlock = fc.blocks;
|
||||
// copy new FW config
|
||||
memcpy(&fc,firmwareConfigResponse,sizeof(NodeFirmwareConfig));
|
||||
// Init flash
|
||||
if (!flash.initialize()) {
|
||||
debug(PSTR("flash init fail\n"));
|
||||
}
|
||||
|
||||
}
|
||||
} else if (type == ST_FIRMWARE_RESPONSE) {
|
||||
// Save block to eeprom
|
||||
debug(PSTR("fw block %d\n"), fwBlock);
|
||||
|
||||
ReplyFWBlock *firmwareResponse = (ReplyFWBlock *)msg.data;
|
||||
// write to flash
|
||||
flash.writeBytes(((fwBlock-1)*FIRMWARE_BLOCK_SIZE) + FIRMWARE_START_OFFSET, firmwareResponse->data, FIRMWARE_BLOCK_SIZE);
|
||||
fwBlock--;
|
||||
if (fwBlock == 0) {
|
||||
// We're finished! Do a checksum and reboot.
|
||||
if (isValidFirmware()) {
|
||||
debug(PSTR("fw checksum ok\n"));
|
||||
// All seems ok, write size and signature to flash (DualOptiboot will pick this up and flash it)
|
||||
uint16_t fwsize = FIRMWARE_BLOCK_SIZE*fc.blocks;
|
||||
flash.writeBytes(0, "FLXIMG:", 7);
|
||||
flash.writeByte(7, fwsize >> 8);
|
||||
flash.writeByte(8, fwsize);
|
||||
flash.writeByte(9, ':');
|
||||
// Write the new firmware config to eeprom
|
||||
hw_writeConfigBlock((void*)&fc, (void*)EEPROM_FIRMWARE_TYPE_ADDRESS, sizeof(NodeFirmwareConfig));
|
||||
hw_reboot();
|
||||
fwUpdateOngoing = false;
|
||||
} else {
|
||||
debug(PSTR("fw checksum fail\n"));
|
||||
// erase lower 32K -> max flash size for ATMEGA328
|
||||
flash.blockErase32K(0);
|
||||
// wait until flash erased
|
||||
while ( flash.busy() );
|
||||
fwBlock = fc.blocks;
|
||||
fwUpdateOngoing = true;
|
||||
// reset flags
|
||||
fwRetry = MY_OTA_RETRY+1;
|
||||
fwLastRequestTime = 0;
|
||||
}
|
||||
return false;
|
||||
} else debug(PSTR("fw update skipped\n"));
|
||||
} else if (type == ST_FIRMWARE_RESPONSE) {
|
||||
if (fwUpdateOngoing) {
|
||||
// Save block to flash
|
||||
debug(PSTR("fw block %d\n"), fwBlock);
|
||||
// extract FW block
|
||||
ReplyFWBlock *firmwareResponse = (ReplyFWBlock *)msg.data;
|
||||
// write to flash
|
||||
flash.writeBytes( ((fwBlock - 1) * FIRMWARE_BLOCK_SIZE) + FIRMWARE_START_OFFSET, firmwareResponse->data, FIRMWARE_BLOCK_SIZE);
|
||||
// wait until flash written
|
||||
while ( flash.busy() );
|
||||
fwBlock--;
|
||||
if (!fwBlock) {
|
||||
// We're finished! Do a checksum and reboot.
|
||||
fwUpdateOngoing = false;
|
||||
if (isValidFirmware()) {
|
||||
debug(PSTR("fw checksum ok\n"));
|
||||
// All seems ok, write size and signature to flash (DualOptiboot will pick this up and flash it)
|
||||
uint16_t fwsize = FIRMWARE_BLOCK_SIZE * fc.blocks;
|
||||
uint8_t OTAbuffer[10] = {'F','L','X','I','M','G',':',(fwsize >> 8),fwsize,':'};
|
||||
flash.writeBytes(0, OTAbuffer, 10);
|
||||
// Write the new firmware config to eeprom
|
||||
hw_writeConfigBlock((void*)&fc, (void*)EEPROM_FIRMWARE_TYPE_ADDRESS, sizeof(NodeFirmwareConfig));
|
||||
hw_reboot();
|
||||
} else {
|
||||
debug(PSTR("fw checksum fail\n"));
|
||||
}
|
||||
}
|
||||
// reset flags
|
||||
fwRetry = MY_OTA_RETRY+1;
|
||||
fwLastRequestTime = 0;
|
||||
} else {
|
||||
debug(PSTR("No fw update ongoing\n"));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// Make sure packet request occurs next time process() is called by timing out requestTime.
|
||||
fwRetry = MY_OTA_RETRY+1;
|
||||
fwLastRequestTime = 0;
|
||||
return false;
|
||||
|
||||
}
|
||||
#endif
|
||||
// Call incoming message callback if available
|
||||
@@ -743,14 +767,17 @@ boolean MySensor::process() {
|
||||
// If this node have an id, relay the message
|
||||
|
||||
if (command == C_INTERNAL && type == I_FIND_PARENT) {
|
||||
if (nc.distance == DISTANCE_INVALID) {
|
||||
findParentNode();
|
||||
} else if (sender != nc.parentNodeId) {
|
||||
// Relaying nodes should always answer ping messages
|
||||
// Wait a random delay of 0-2 seconds to minimize collision
|
||||
// between ping ack messages from other relaying nodes
|
||||
wait(hw_millis() & 0x3ff);
|
||||
sendWrite(sender, build(msg, nc.nodeId, sender, NODE_SENSOR_ID, C_INTERNAL, I_FIND_PARENT_RESPONSE, false).set(nc.distance));
|
||||
if (sender != nc.parentNodeId) {
|
||||
if (nc.distance == DISTANCE_INVALID)
|
||||
findParentNode();
|
||||
|
||||
if (nc.distance != DISTANCE_INVALID) {
|
||||
// Relaying nodes should always answer ping messages
|
||||
// Wait a random delay of 0-2 seconds to minimize collision
|
||||
// between ping ack messages from other relaying nodes
|
||||
wait(hw_millis() & 0x3ff);
|
||||
sendWrite(sender, build(msg, nc.nodeId, sender, NODE_SENSOR_ID, C_INTERNAL, I_FIND_PARENT_RESPONSE, false).set(nc.distance));
|
||||
}
|
||||
}
|
||||
} else if (to == nc.nodeId) {
|
||||
// We should try to relay this message to another node
|
||||
|
||||
@@ -51,6 +51,14 @@ typedef MyHwATMega328 MyHwDriver;
|
||||
#define debug(x,...)
|
||||
#endif
|
||||
|
||||
#ifdef WITH_LEDS_BLINKING_INVERSE
|
||||
#define LED_ON 0x1
|
||||
#define LED_OFF 0x0
|
||||
#else
|
||||
#define LED_ON 0x0
|
||||
#define LED_OFF 0x1
|
||||
#endif
|
||||
|
||||
|
||||
// EEPROM start address for mysensors library data
|
||||
#define EEPROM_START 0
|
||||
@@ -176,9 +184,11 @@ class MySensor
|
||||
*
|
||||
* @param sensorId Select a unique sensor id for this sensor. Choose a number between 0-254.
|
||||
* @param sensorType The sensor type. See sensor typedef in MyMessage.h.
|
||||
* @param description A textual description of the sensor.
|
||||
* @param ack Set this to true if you want destination node to send ack back to this node. Default is not to request any ack.
|
||||
* @param description A textual description of the sensor.
|
||||
*/
|
||||
void present(uint8_t sensorId, uint8_t sensorType, bool ack=false);
|
||||
void present(uint8_t sensorId, uint8_t sensorType, const char *description="", bool ack=false);
|
||||
|
||||
/**
|
||||
* Sends sketch meta information to the gateway. Not mandatory but a nice thing to do.
|
||||
@@ -207,6 +217,12 @@ class MySensor
|
||||
*/
|
||||
void sendBatteryLevel(uint8_t level, bool ack=false);
|
||||
|
||||
/**
|
||||
* Send a heartbeat message (I'm alive!) to the gateway/controller.
|
||||
* The payload will be an incremental 16 bit integer value starting at 1 when sensor is powered on.
|
||||
*/
|
||||
void sendHeartbeat(void);
|
||||
|
||||
/**
|
||||
* Requests a value from gateway or some other sensor in the radio network.
|
||||
* Make sure to add callback-method in begin-method to handle request responses.
|
||||
@@ -362,6 +378,7 @@ class MySensor
|
||||
char convBuf[MAX_PAYLOAD*2+1];
|
||||
#endif
|
||||
uint8_t failedTransmissions;
|
||||
uint16_t heartbeat;
|
||||
void (*timeCallback)(unsigned long); // Callback for requested time messages
|
||||
void (*msgCallback)(const MyMessage &); // Callback for incoming messages from other nodes and gateway.
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ public:
|
||||
bool signMsg(MyMessage &msg);
|
||||
bool verifyMsg(MyMessage &msg);
|
||||
private:
|
||||
atsha204Class atsha204;
|
||||
ATSHA204Class atsha204;
|
||||
unsigned long timestamp;
|
||||
bool verification_ongoing;
|
||||
uint8_t current_nonce[NONCE_NUMIN_SIZE_PASSTHROUGH+SHA204_SERIAL_SZ+1];
|
||||
|
||||
@@ -61,6 +61,9 @@ static void DEBUG_SIGNING_PRINTBUF(const __FlashStringHelper* str, uint8_t* buf,
|
||||
#define DEBUG_SIGNING_PRINTBUF(str, buf, sz)
|
||||
#endif
|
||||
|
||||
// Initialize hmacKey from MyConfig.h (codebender didn't like static initialization in constructor)
|
||||
uint8_t MySigningAtsha204Soft::hmacKey[32] = { MY_HMAC_KEY };
|
||||
|
||||
MySigningAtsha204Soft::MySigningAtsha204Soft(bool requestSignatures,
|
||||
#ifdef MY_SECURE_NODE_WHITELISTING
|
||||
uint8_t nof_whitelist_entries, const whitelist_entry_t* the_whitelist,
|
||||
@@ -70,7 +73,6 @@ MySigningAtsha204Soft::MySigningAtsha204Soft(bool requestSignatures,
|
||||
:
|
||||
MySigning(requestSignatures),
|
||||
rndPin(randomseedPin),
|
||||
hmacKey({MY_HMAC_KEY}),
|
||||
#ifdef MY_SECURE_NODE_WHITELISTING
|
||||
whitlist_sz(nof_whitelist_entries),
|
||||
whitelist(the_whitelist),
|
||||
|
||||
@@ -73,7 +73,7 @@ private:
|
||||
bool verification_ongoing;
|
||||
uint8_t current_nonce[NONCE_NUMIN_SIZE_PASSTHROUGH];
|
||||
uint8_t temp_message[32];
|
||||
uint8_t hmacKey[32];
|
||||
static uint8_t hmacKey[32];
|
||||
uint8_t rndPin;
|
||||
uint8_t hmac[32];
|
||||
void calculateSignature(MyMessage &msg);
|
||||
|
||||
@@ -6,6 +6,6 @@
|
||||
#ifndef Version_h
|
||||
#define Version_h
|
||||
|
||||
#define LIBRARY_VERSION "1.5 b1"
|
||||
#define LIBRARY_VERSION "1.5"
|
||||
|
||||
#endif
|
||||
|
||||
@@ -77,7 +77,7 @@ float SmokeCurve[3] ={2.3,0.53,-0.44}; //two points are taken from
|
||||
|
||||
|
||||
MySensor gw;
|
||||
MyMessage msg(CHILD_ID_MQ, V_VAR1);
|
||||
MyMessage msg(CHILD_ID_MQ, V_LEVEL);
|
||||
|
||||
|
||||
void setup()
|
||||
|
||||
@@ -30,6 +30,8 @@
|
||||
#include <SPI.h>
|
||||
#include <MySensor.h>
|
||||
|
||||
#define DEBUG 1 // Debug enables Serial.print 1 = Yes 0 = No
|
||||
|
||||
int BATTERY_SENSE_PIN = A0; // select the input pin for the battery sense point
|
||||
|
||||
MySensor gw;
|
||||
@@ -50,7 +52,9 @@ void loop()
|
||||
{
|
||||
// get the battery Voltage
|
||||
int sensorValue = analogRead(BATTERY_SENSE_PIN);
|
||||
#if DEBUG > 0
|
||||
Serial.println(sensorValue);
|
||||
#endif
|
||||
|
||||
// 1M, 470K divider across battery and using internal ADC ref of 1.1V
|
||||
// Sense point is bypassed with 0.1 uF cap to reduce noise at that point
|
||||
@@ -59,6 +63,7 @@ void loop()
|
||||
float batteryV = sensorValue * 0.003363075;
|
||||
int batteryPcnt = sensorValue / 10;
|
||||
|
||||
#if DEBUG > 0
|
||||
Serial.print("Battery Voltage: ");
|
||||
Serial.print(batteryV);
|
||||
Serial.println(" V");
|
||||
@@ -66,6 +71,7 @@ void loop()
|
||||
Serial.print("Battery percent: ");
|
||||
Serial.print(batteryPcnt);
|
||||
Serial.println(" %");
|
||||
#endif
|
||||
|
||||
if (oldBatteryPcnt != batteryPcnt) {
|
||||
// Power up radio after sleep
|
||||
|
||||
@@ -29,11 +29,13 @@
|
||||
#include <DallasTemperature.h>
|
||||
#include <OneWire.h>
|
||||
|
||||
#define COMPARE_TEMP 1 // Send temperature only if changed? 1 = Yes 0 = No
|
||||
|
||||
#define ONE_WIRE_BUS 3 // Pin where dallase sensor is connected
|
||||
#define MAX_ATTACHED_DS18B20 16
|
||||
unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds)
|
||||
OneWire oneWire(ONE_WIRE_BUS);
|
||||
DallasTemperature sensors(&oneWire);
|
||||
OneWire oneWire(ONE_WIRE_BUS); // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
|
||||
DallasTemperature sensors(&oneWire); // Pass the oneWire reference to Dallas Temperature.
|
||||
MySensor gw;
|
||||
float lastTemperature[MAX_ATTACHED_DS18B20];
|
||||
int numSensors=0;
|
||||
@@ -44,14 +46,16 @@ MyMessage msg(0,V_TEMP);
|
||||
|
||||
void setup()
|
||||
{
|
||||
// Startup OneWire
|
||||
// Startup up the OneWire library
|
||||
sensors.begin();
|
||||
// requestTemperatures() will not block current thread
|
||||
sensors.setWaitForConversion(false);
|
||||
|
||||
// Startup and initialize MySensors library. Set callback for incoming messages.
|
||||
gw.begin();
|
||||
gw.begin();
|
||||
|
||||
// Send the sketch version information to the gateway and Controller
|
||||
gw.sendSketchInfo("Temperature Sensor", "1.0");
|
||||
gw.sendSketchInfo("Temperature Sensor", "1.1");
|
||||
|
||||
// Fetch the number of attached temperature sensors
|
||||
numSensors = sensors.getDeviceCount();
|
||||
@@ -69,7 +73,12 @@ void loop()
|
||||
gw.process();
|
||||
|
||||
// Fetch temperatures from Dallas sensors
|
||||
sensors.requestTemperatures();
|
||||
sensors.requestTemperatures();
|
||||
|
||||
// query conversion time and sleep until conversion completed
|
||||
int16_t conversionTime = sensors.millisToWaitForConversion(sensors.getResolution());
|
||||
// sleep() call can be replaced by wait() call if node need to process incoming messages (or if node is repeater)
|
||||
gw.sleep(conversionTime);
|
||||
|
||||
// Read temperatures and send them to controller
|
||||
for (int i=0; i<numSensors && i<MAX_ATTACHED_DS18B20; i++) {
|
||||
@@ -78,15 +87,17 @@ void loop()
|
||||
float temperature = static_cast<float>(static_cast<int>((gw.getConfig().isMetric?sensors.getTempCByIndex(i):sensors.getTempFByIndex(i)) * 10.)) / 10.;
|
||||
|
||||
// Only send data if temperature has changed and no error
|
||||
if (lastTemperature[i] != temperature && temperature != -127.00) {
|
||||
#if COMPARE_TEMP == 1
|
||||
if (lastTemperature[i] != temperature && temperature != -127.00 && temperature != 85.00) {
|
||||
#else
|
||||
if (temperature != -127.00 && temperature != 85.00) {
|
||||
#endif
|
||||
|
||||
// Send in the new temperature
|
||||
gw.send(msg.setSensor(i).set(temperature,1));
|
||||
// Save new temperatures for next compare
|
||||
lastTemperature[i]=temperature;
|
||||
}
|
||||
}
|
||||
gw.sleep(SLEEP_TIME);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
/**
|
||||
* The MySensors Arduino library handles the wireless radio link and protocol
|
||||
* between your home built sensors/actuators and HA controller of choice.
|
||||
* The sensors forms a self healing radio network with optional repeaters. Each
|
||||
* repeater and gateway builds a routing tables in EEPROM which keeps track of the
|
||||
* network topology allowing messages to be routed to nodes.
|
||||
*
|
||||
* Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
|
||||
* Copyright (C) 2013-2015 Sensnology AB
|
||||
* Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
|
||||
*
|
||||
* Documentation: http://www.mysensors.org
|
||||
* Support Forum: http://forum.mysensors.org
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU General Public License
|
||||
* version 2 as published by the Free Software Foundation.
|
||||
*
|
||||
*******************************
|
||||
*
|
||||
* REVISION HISTORY
|
||||
* Version 1.0 - Developed by Bruce Lacey and GizMoCuz (Domoticz)
|
||||
* Version 1.1 - Modified by hek to incorporate a rotary encode to adjust
|
||||
* light level locally at node
|
||||
*
|
||||
* DESCRIPTION
|
||||
* This sketch provides an example how to implement a dimmable led light node with a rotary
|
||||
* encoder connected for adjusting light level.
|
||||
* The encoder has a click button which turns on/off the light (and remembers last dim-level)
|
||||
* The sketch fades the light (non-blocking) to the desired level.
|
||||
*
|
||||
* Default MOSFET pin is 3
|
||||
*
|
||||
* Arduino Encoder module
|
||||
* ---------------------------
|
||||
* 5V 5V (+)
|
||||
* GND GND (-)
|
||||
* 4 CLK (or putput 1)
|
||||
* 5 DT (or output 1)
|
||||
* 6 SW (Switch/Click)
|
||||
*/
|
||||
|
||||
|
||||
#include <SPI.h>
|
||||
#include <Encoder.h>
|
||||
#include <MySensor.h>
|
||||
#include <Bounce2.h>
|
||||
|
||||
#define LED_PIN 3 // Arduino pin attached to MOSFET Gate pin
|
||||
#define KNOB_ENC_PIN_1 4 // Rotary encoder input pin 1
|
||||
#define KNOB_ENC_PIN_2 5 // Rotary encoder input pin 2
|
||||
#define KNOB_BUTTON_PIN 6 // Rotary encoder button pin
|
||||
#define FADE_DELAY 10 // Delay in ms for each percentage fade up/down (10ms = 1s full-range dim)
|
||||
#define SEND_THROTTLE_DELAY 400 // Number of milliseconds before sending after user stops turning knob
|
||||
#define SN "DimmableLED /w button"
|
||||
#define SV "1.2"
|
||||
|
||||
#define CHILD_ID_LIGHT 1
|
||||
|
||||
#define EEPROM_DIM_LEVEL_LAST 1
|
||||
#define EEPROM_DIM_LEVEL_SAVE 2
|
||||
|
||||
#define LIGHT_OFF 0
|
||||
#define LIGHT_ON 1
|
||||
|
||||
int dimValue;
|
||||
int fadeTo;
|
||||
int fadeDelta;
|
||||
byte oldButtonVal;
|
||||
bool changedByKnob=false;
|
||||
bool sendDimValue=false;
|
||||
unsigned long lastFadeStep;
|
||||
unsigned long sendDimTimeout;
|
||||
char convBuffer[10];
|
||||
|
||||
MySensor gw;
|
||||
MyMessage dimmerMsg(CHILD_ID_LIGHT, V_DIMMER);
|
||||
Encoder knob(KNOB_ENC_PIN_1, KNOB_ENC_PIN_2);
|
||||
Bounce debouncer = Bounce();
|
||||
|
||||
void setup()
|
||||
{
|
||||
// Set knob button pin as input (with debounce)
|
||||
pinMode(KNOB_BUTTON_PIN, INPUT);
|
||||
digitalWrite(KNOB_BUTTON_PIN, HIGH);
|
||||
debouncer.attach(KNOB_BUTTON_PIN);
|
||||
debouncer.interval(5);
|
||||
oldButtonVal = debouncer.read();
|
||||
|
||||
// Set analog led pin to off
|
||||
analogWrite( LED_PIN, 0);
|
||||
|
||||
// Init mysensors library
|
||||
gw.begin(incomingMessage, AUTO, false);
|
||||
|
||||
// Send the Sketch Version Information to the Gateway
|
||||
gw.present(CHILD_ID_LIGHT, S_DIMMER);
|
||||
gw.sendSketchInfo(SN, SV);
|
||||
|
||||
// Retreive our last dim levels from the eprom
|
||||
fadeTo = dimValue = 0;
|
||||
byte oldLevel = loadLevelState(EEPROM_DIM_LEVEL_LAST);
|
||||
Serial.print("Sending in last known light level to controller: ");
|
||||
Serial.println(oldLevel);
|
||||
gw.send(dimmerMsg.set(oldLevel), true);
|
||||
|
||||
Serial.println("Ready to receive messages...");
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
// Process incoming messages (like config and light state from controller)
|
||||
gw.process();
|
||||
|
||||
// Check if someone turned the rotary encode
|
||||
checkRotaryEncoder();
|
||||
|
||||
// Check if someone has pressed the knob button
|
||||
checkButtonClick();
|
||||
|
||||
// Fade light to new dim value
|
||||
fadeStep();
|
||||
}
|
||||
|
||||
void incomingMessage(const MyMessage &message)
|
||||
{
|
||||
if (message.type == V_LIGHT) {
|
||||
// Incoming on/off command sent from controller ("1" or "0")
|
||||
int lightState = message.getString()[0] == '1';
|
||||
int newLevel = 0;
|
||||
if (lightState==LIGHT_ON) {
|
||||
// Pick up last saved dimmer level from the eeprom
|
||||
newLevel = loadLevelState(EEPROM_DIM_LEVEL_SAVE);
|
||||
}
|
||||
// Send dimmer level back to controller with ack enabled
|
||||
gw.send(dimmerMsg.set(0), true);
|
||||
// We do not change any levels here until ack comes back from gateway
|
||||
return;
|
||||
} else if (message.type == V_DIMMER) {
|
||||
// Incoming dim-level command sent from controller (or ack message)
|
||||
fadeTo = atoi(message.getString(convBuffer));
|
||||
// Save received dim value to eeprom (unless turned off). Will be
|
||||
// retreived when a on command comes in
|
||||
if (fadeTo != 0)
|
||||
saveLevelState(EEPROM_DIM_LEVEL_SAVE, fadeTo);
|
||||
}
|
||||
saveLevelState(EEPROM_DIM_LEVEL_LAST, fadeTo);
|
||||
|
||||
Serial.print("New light level received: ");
|
||||
Serial.println(fadeTo);
|
||||
|
||||
if (!changedByKnob)
|
||||
knob.write(fadeTo);
|
||||
|
||||
// Cancel send if user turns knob while message comes in
|
||||
changedByKnob = false;
|
||||
sendDimValue = false;
|
||||
|
||||
// Stard fading to new light level
|
||||
startFade();
|
||||
}
|
||||
|
||||
|
||||
|
||||
void checkRotaryEncoder() {
|
||||
long encoderValue = knob.read();
|
||||
|
||||
if (encoderValue > 100) {
|
||||
encoderValue = 100;
|
||||
knob.write(100);
|
||||
} else if (encoderValue < 0) {
|
||||
encoderValue = 0;
|
||||
knob.write(0);
|
||||
}
|
||||
|
||||
if (encoderValue != fadeTo) {
|
||||
fadeTo = encoderValue;
|
||||
changedByKnob = true;
|
||||
startFade();
|
||||
}
|
||||
}
|
||||
|
||||
void checkButtonClick() {
|
||||
debouncer.update();
|
||||
byte buttonVal = debouncer.read();
|
||||
byte newLevel = 0;
|
||||
if (buttonVal != oldButtonVal && buttonVal == LOW) {
|
||||
if (dimValue==0) {
|
||||
// Turn on light. Set the level to last saved dim value
|
||||
int saved = loadLevelState(EEPROM_DIM_LEVEL_SAVE);
|
||||
newLevel = saved > 0 ? saved : 100;
|
||||
}
|
||||
gw.send(dimmerMsg.set(newLevel),true);
|
||||
}
|
||||
oldButtonVal = buttonVal;
|
||||
}
|
||||
|
||||
void startFade() {
|
||||
fadeDelta = ( fadeTo - dimValue ) < 0 ? -1 : 1;
|
||||
lastFadeStep = millis();
|
||||
}
|
||||
|
||||
// This method provides a graceful none-blocking fade up/down effect
|
||||
void fadeStep() {
|
||||
unsigned long currentTime = millis();
|
||||
if ( dimValue != fadeTo && currentTime > lastFadeStep + FADE_DELAY) {
|
||||
dimValue += fadeDelta;
|
||||
analogWrite( LED_PIN, (int)(dimValue / 100. * 255) );
|
||||
lastFadeStep = currentTime;
|
||||
|
||||
Serial.print("Fading level: ");
|
||||
Serial.println(dimValue);
|
||||
|
||||
if (fadeTo == dimValue && changedByKnob) {
|
||||
sendDimValue = true;
|
||||
sendDimTimeout = currentTime;
|
||||
}
|
||||
}
|
||||
// Wait a few millisecs before sending in new value (if user still turns the knob)
|
||||
if (sendDimValue && currentTime > sendDimTimeout + SEND_THROTTLE_DELAY) {
|
||||
// We're done fading.. send in new dim-value to controller.
|
||||
// Send in new dim value with ack (will be picked up in incomingMessage)
|
||||
gw.send(dimmerMsg.set(dimValue), true); // Send new dimmer value and request ack back
|
||||
sendDimValue = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Make sure only to store/fetch values in the range 0-100 from eeprom
|
||||
int loadLevelState(byte pos) {
|
||||
return min(max(gw.loadState(pos),0),100);
|
||||
}
|
||||
void saveLevelState(byte pos, byte data) {
|
||||
gw.saveState(pos,min(max(data,0),100));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ float calcVoltage = 0;
|
||||
float dustDensity = 0;
|
||||
|
||||
MySensor gw;
|
||||
MyMessage dustMsg(CHILD_ID_DUST, V_DUST_LEVEL);
|
||||
MyMessage dustMsg(CHILD_ID_DUST, V_LEVEL);
|
||||
|
||||
void setup()
|
||||
{
|
||||
|
||||
@@ -90,7 +90,7 @@ IPAddress myIp (192, 168, 178, 66); // Configure your static ip-address here
|
||||
#endif /* IP_ADDRESS_DHCP */
|
||||
|
||||
// NRFRF24L01 radio driver (set low transmit power by default)
|
||||
MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW);
|
||||
MyTransportNRF24 transport(RADIO_CE_PIN, RADIO_SPI_SS_PIN, RF24_PA_LEVEL_GW);
|
||||
//MyTransportRFM69 transport;
|
||||
|
||||
// Message signing driver (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h)
|
||||
@@ -101,7 +101,7 @@ MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW);
|
||||
// Hardware profile
|
||||
MyHwATMega328 hw;
|
||||
|
||||
// Controller protocol
|
||||
// Use default controller protocol
|
||||
MyProtocolDefault protocol;
|
||||
|
||||
// The MAC address can be anything you want but should be unique on your network.
|
||||
|
||||
@@ -0,0 +1,864 @@
|
||||
/*
|
||||
MySprinkler for MySensors
|
||||
|
||||
Arduino Multi-Zone Sprinkler Control
|
||||
|
||||
May 31, 2015
|
||||
|
||||
*** Version 2.0
|
||||
|
||||
*** Upgraded to http://MySensors.org version 1.4.1
|
||||
*** Expanded for up to 16 Valves
|
||||
*** Setup for active low relay board or comment out #define ACTIVE_LOW to switch to active high
|
||||
*** Switch to bitshift method vs byte arrays
|
||||
*** Changed RUN_ALL_ZONES Vera device to 0 (was highest valve)
|
||||
*** Added optional LCD display featuring remaining time, date last ran & current time
|
||||
*** Features 'raindrop' and 'clock' icons which indicate sensor is updating valve data and clock respectively
|
||||
*** Added single pushbutton menu to manually select which program to run (All Zones or a Single Zone)
|
||||
*** Added option of naming your Zones programmatically or with Vera (V_VAR3 used to store names)
|
||||
|
||||
Utilizing your Vera home automation controller and the MySensors.org gateway you can
|
||||
control up to a sixteen zone irrigation system with only three digital pins. This sketch
|
||||
will create NUMBER_OF_VALVES + 1 devices on your Vera controller
|
||||
|
||||
This sketch features the following:
|
||||
|
||||
* Allows you to cycle through All zones (RUN_ALL_ZONES) or individual zone (RUN_SINGLE_ZONE) control.
|
||||
* Use the 0th controller to activate RUN_ALL_ZONES (each zone in numeric sequence 1 to n)
|
||||
using Variable1 as the "ON" time in minutes in each of the vera devices created.
|
||||
* Use the individual zone controller to activate a single zone. This feature uses
|
||||
Variable2 as the "ON" time for each individual device/zone.
|
||||
* Connect according to pinout below and uses Shift Registers as to allow the MySensors
|
||||
standard radio configuration and still leave available digital pins
|
||||
* Turning on any zone will stop the current process and begin that particular process.
|
||||
* Turning off any zone will stop the current process and turn off all zones.
|
||||
* To push your new time intervals for your zones, simply change the variable on your Vera and
|
||||
your arduino will call to Vera once a minute and update accordingly. Variables will also be
|
||||
requested when the device is first powered on.
|
||||
* Pushbutton activation to RUN_ALL_ZONES, RUN_SINGLE_ZONE or halt the current program
|
||||
* LED status indicator
|
||||
|
||||
PARTS LIST:
|
||||
Available from the MySensors store - http://www.mysensors.org/store/
|
||||
* Relays (8 channel)
|
||||
* Female Pin Header Connector Strip
|
||||
* Prototype Universal Printed Circuit Boards (PCB)
|
||||
* NRF24L01 Radio
|
||||
* Arduino (I used a Pro Mini)
|
||||
* FTDI USB to TTL Serial Adapter
|
||||
* Capacitors (10uf and .1uf)
|
||||
* 3.3v voltage regulator
|
||||
* Resistors (270 & 10K)
|
||||
* Female Dupont Cables
|
||||
* 1602 LCD (with I2C Interface)
|
||||
* LED
|
||||
* Push button
|
||||
* Shift Register (SN74HC595)
|
||||
* 2 Pole 5mm Pitch PCB Mount Screw Terminal Block
|
||||
* 3 Pole 5mm Pitch PCB Mount Screw Terminal Block
|
||||
* 22-24 gauge wire or similar (I used Cat5/Cat6 cable)
|
||||
* 18 gauge wire (for relay)
|
||||
* Irrigation Power Supply (24-Volt/750 mA Transformer)
|
||||
|
||||
|
||||
INSTRUCTIONS:
|
||||
|
||||
* A step-by-step setup video is available here: http://youtu.be/l4GPRTsuHkI
|
||||
* After assembling your arduino, radio, decoupling capacitors, shift register(s), status LED, pushbutton LCD (I2C connected to
|
||||
A4 and A5) and relays, and load the sketch.
|
||||
* Following the instructions at https://MySensors.org include the device to your MySensors Gateway.
|
||||
* Verify that each new device has a Variable1, Variable2 and Variable3. Populate data accordingly with whole minutes for
|
||||
the RUN_ALL_ZONES routine (Variable1) and the RUN_SINGLE_ZONE routines (Variable 2). The values entered for times may be zero and
|
||||
you may use the defaulet zone names by leaving Variable3 blank.
|
||||
* Once you have entered values for each zone and each variable, save the settings by pressing the red save button on your Vera.
|
||||
* Restart your arduino; verify the settings are loaded into your arduino with the serial monitor; the array will be printed
|
||||
on the serial monitor.
|
||||
* Your arduino should slow-flash, indicating that it is in ready mode.
|
||||
* There are multiple debug serial prints that can be monitored to assure that it is operating properly.
|
||||
* ***THIS SHOULD NO LONGER BE NEEDED*** The standard MySensors library now works. https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads for the I2C library, or use yours
|
||||
|
||||
Contributed by Jim (BulldogLowell@gmail.com) with much contribution from Pete (pete.will@mysensors.org) and is released to the public domain
|
||||
*/
|
||||
//
|
||||
#include <Wire.h>
|
||||
#include <Time.h>
|
||||
#include <MySensor.h>
|
||||
#include <SPI.h>
|
||||
#include <LiquidCrystal.h>
|
||||
#include <LiquidCrystal_I2C.h>
|
||||
|
||||
|
||||
//
|
||||
#define NUMBER_OF_VALVES 8 // Change this to set your valve count up to 16.
|
||||
#define VALVE_RESET_TIME 7500UL // Change this (in milliseconds) for the time you need your valves to hydraulically reset and change state
|
||||
#define RADIO_ID AUTO // Change this to fix your Radio ID or use Auto
|
||||
|
||||
#define SKETCH_NAME "MySprinkler"
|
||||
#define SKETCH_VERSION "2.0"
|
||||
//
|
||||
#define CHILD_ID_SPRINKLER 0
|
||||
//
|
||||
#define ACTIVE_LOW // comment out this line if your relays are active high
|
||||
//
|
||||
#define DEBUG_ON // comment out to supress serial monitor output
|
||||
//
|
||||
#ifdef ACTIVE_LOW
|
||||
#define BITSHIFT_VALVE_NUMBER ~(1U << (valveNumber-1))
|
||||
#define ALL_VALVES_OFF 0xFFFF
|
||||
#else
|
||||
#define BITSHIFT_VALVE_NUMBER (1U << (valveNumber-1))
|
||||
#define ALL_VALVES_OFF 0U
|
||||
#endif
|
||||
//
|
||||
#ifdef DEBUG_ON
|
||||
#define DEBUG_PRINT(x) Serial.print(x)
|
||||
#define DEBUG_PRINTLN(x) Serial.println(x)
|
||||
#define SERIAL_START(x) Serial.begin(x)
|
||||
#else
|
||||
#define DEBUG_PRINT(x)
|
||||
#define DEBUG_PRINTLN(x)
|
||||
#define SERIAL_START(x)
|
||||
#endif
|
||||
//
|
||||
typedef enum {
|
||||
STAND_BY_ALL_OFF, RUN_SINGLE_ZONE, RUN_ALL_ZONES, CYCLE_COMPLETE, ZONE_SELECT_MENU
|
||||
}
|
||||
SprinklerStates;
|
||||
//
|
||||
SprinklerStates state = STAND_BY_ALL_OFF;
|
||||
SprinklerStates lastState;
|
||||
byte menuState = 0;
|
||||
unsigned long menuTimer;
|
||||
byte countDownTime = 10;
|
||||
//
|
||||
int allZoneTime [NUMBER_OF_VALVES + 1];
|
||||
int valveSoloTime [NUMBER_OF_VALVES + 1];
|
||||
int valveNumber;
|
||||
int lastValve;
|
||||
unsigned long startMillis;
|
||||
const int ledPin = 5;
|
||||
const int waterButtonPin = 3;
|
||||
boolean buttonPushed = false;
|
||||
boolean showTime = true;
|
||||
boolean clockUpdating = false;
|
||||
boolean recentUpdate = true;
|
||||
const char *dayOfWeek[] = {
|
||||
"Null", "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "
|
||||
};
|
||||
// Name your Zones here or use Vera to edit them by adding a name in Variable3...
|
||||
String valveNickName[17] = {
|
||||
"All Zones", "Zone 1", "Zone 2", "Zone 3", "Zone 4", "Zone 5", "Zone 6", "Zone 7", "Zone 8", "Zone 9", "Zone 10", "Zone 11", "Zone 12", "Zone 13", "Zone 14", "Zone 15", "Zone 16"
|
||||
};
|
||||
//
|
||||
time_t lastTimeRun = 0;
|
||||
//Setup Shift Register...
|
||||
const int latchPin = 8;
|
||||
const int clockPin = 4;
|
||||
const int dataPin = 7;
|
||||
//
|
||||
byte clock[8] = {0x0, 0xe, 0x15, 0x17, 0x11, 0xe, 0x0}; // fetching time indicator
|
||||
byte raindrop[8] = {0x4, 0x4, 0xA, 0xA, 0x11, 0xE, 0x0,}; // fetching Valve Data indicator
|
||||
// Set the pins on the I2C chip used for LCD connections:
|
||||
// addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
|
||||
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address to 0x27
|
||||
MySensor gw;
|
||||
//
|
||||
MyMessage msg1valve(CHILD_ID_SPRINKLER, V_LIGHT);
|
||||
MyMessage var1valve(CHILD_ID_SPRINKLER, V_VAR1);
|
||||
MyMessage var2valve(CHILD_ID_SPRINKLER, V_VAR2);
|
||||
//
|
||||
void setup()
|
||||
{
|
||||
SERIAL_START(115200);
|
||||
DEBUG_PRINTLN(F("Initialising..."));
|
||||
pinMode(latchPin, OUTPUT);
|
||||
pinMode(clockPin, OUTPUT);
|
||||
pinMode(dataPin, OUTPUT);
|
||||
pinMode(ledPin, OUTPUT);
|
||||
pinMode(waterButtonPin, INPUT_PULLUP);
|
||||
//pinMode(waterButtonPin, INPUT);
|
||||
attachInterrupt(1, PushButton, RISING); //May need to change for your Arduino model
|
||||
digitalWrite (ledPin, HIGH);
|
||||
DEBUG_PRINTLN(F("Turning All Valves Off..."));
|
||||
updateRelays(ALL_VALVES_OFF);
|
||||
//delay(5000);
|
||||
lcd.begin(16, 2); //(16 characters and 2 line display)
|
||||
lcd.clear();
|
||||
lcd.backlight();
|
||||
lcd.createChar(0, clock);
|
||||
lcd.createChar(1, raindrop);
|
||||
//
|
||||
//check for saved date in EEPROM
|
||||
DEBUG_PRINTLN(F("Checking EEPROM for stored date:"));
|
||||
delay(500);
|
||||
if (gw.loadState(0) == 0xFF); // EEPROM flag
|
||||
{
|
||||
DEBUG_PRINTLN(F("Retreiving last run time from EEPROM..."));
|
||||
for (int i = 0; i < 4 ; i++)
|
||||
{
|
||||
lastTimeRun = lastTimeRun << 8;
|
||||
lastTimeRun = lastTimeRun | gw.loadState(i + 1); // assemble 4 bytes into an ussigned long epoch timestamp
|
||||
}
|
||||
}
|
||||
gw.begin(getVariables, RADIO_ID, false); // Change 'false' to 'true' to create a Radio repeating node
|
||||
gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION);
|
||||
for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
|
||||
{
|
||||
gw.present(i, S_LIGHT);
|
||||
}
|
||||
DEBUG_PRINTLN(F("Sensor Presentation Complete"));
|
||||
//
|
||||
digitalWrite (ledPin, LOW);
|
||||
DEBUG_PRINTLN(F("Ready..."));
|
||||
//
|
||||
lcd.setCursor(0, 0);
|
||||
lcd.print(F(" Syncing Time "));
|
||||
lcd.setCursor(15, 0);
|
||||
lcd.write(byte(0));
|
||||
lcd.setCursor(0, 1);
|
||||
int clockCounter = 0;
|
||||
while (timeStatus() == timeNotSet && clockCounter < 21)
|
||||
{
|
||||
gw.process();
|
||||
gw.requestTime(receiveTime);
|
||||
DEBUG_PRINTLN(F("Requesting time from Gateway:"));
|
||||
delay(1000);
|
||||
lcd.print(".");
|
||||
clockCounter++;
|
||||
if (clockCounter > 16)
|
||||
{
|
||||
DEBUG_PRINTLN(F("Failed initial clock synchronization!"));
|
||||
lcd.clear();
|
||||
lcd.print(F(" Failed Clock "));
|
||||
lcd.setCursor(0, 1);
|
||||
lcd.print(F(" Syncronization "));
|
||||
delay(2000);
|
||||
break;
|
||||
}
|
||||
}
|
||||
//
|
||||
lcd.clear();
|
||||
//Update valve data when first powered on
|
||||
for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
|
||||
{
|
||||
lcd.print(F(" Updating "));
|
||||
lcd.setCursor(0, 1);
|
||||
lcd.print(F(" Valve Data: "));
|
||||
lcd.print(i);
|
||||
boolean flashIcon = false;
|
||||
DEBUG_PRINT(F("Calling for Valve "));
|
||||
DEBUG_PRINT(i);
|
||||
DEBUG_PRINTLN(F(" Data..."));
|
||||
while (gw.process() == false)
|
||||
{
|
||||
lcd.setCursor(15, 0);
|
||||
flashIcon = !flashIcon;
|
||||
flashIcon ? lcd.write(byte(1)) : lcd.print(F(" "));
|
||||
gw.request(i, V_VAR1);
|
||||
delay(100);
|
||||
}
|
||||
while (gw.process() == false)
|
||||
{
|
||||
lcd.setCursor(15, 0);
|
||||
flashIcon = !flashIcon;
|
||||
flashIcon ? lcd.write(byte(1)) : lcd.print(F(" "));
|
||||
gw.request(i, V_VAR2);
|
||||
delay(100);
|
||||
}
|
||||
while (gw.process() == false)
|
||||
{
|
||||
lcd.setCursor(15, 0);
|
||||
flashIcon = !flashIcon;
|
||||
flashIcon ? lcd.write(byte(1)) : lcd.print(F(" "));
|
||||
gw.request(i, V_VAR3);
|
||||
delay(100);
|
||||
}
|
||||
}
|
||||
lcd.clear();
|
||||
}
|
||||
//
|
||||
void loop()
|
||||
{
|
||||
gw.process();
|
||||
updateClock();
|
||||
updateDisplay();
|
||||
goGetValveTimes();
|
||||
//
|
||||
if (buttonPushed)
|
||||
{
|
||||
menuTimer = millis();
|
||||
DEBUG_PRINTLN(F("Button Pressed"));
|
||||
if (state == STAND_BY_ALL_OFF)
|
||||
{
|
||||
state = ZONE_SELECT_MENU;
|
||||
menuState = 0;
|
||||
}
|
||||
else if (state == ZONE_SELECT_MENU)
|
||||
{
|
||||
menuState++;
|
||||
if (menuState > NUMBER_OF_VALVES)
|
||||
{
|
||||
menuState = 0;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
state = STAND_BY_ALL_OFF;
|
||||
}
|
||||
buttonPushed = false;
|
||||
}
|
||||
if (state == STAND_BY_ALL_OFF)
|
||||
{
|
||||
slowToggleLED ();
|
||||
if (state != lastState)
|
||||
{
|
||||
updateRelays(ALL_VALVES_OFF);
|
||||
DEBUG_PRINTLN(F("State Changed... all Zones off"));
|
||||
for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
|
||||
{
|
||||
delay(50);
|
||||
gw.send(msg1valve.setSensor(i).set(false), false);
|
||||
}
|
||||
lcd.clear();
|
||||
lcd.setCursor(0,0);
|
||||
lcd.print(F("** Irrigation **"));
|
||||
lcd.setCursor(0,1);
|
||||
lcd.print(F("** Halted **"));
|
||||
delay(2000);
|
||||
lastValve = -1;
|
||||
}
|
||||
}
|
||||
//
|
||||
else if (state == RUN_ALL_ZONES)
|
||||
{
|
||||
if (lastValve != valveNumber)
|
||||
{
|
||||
for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
|
||||
{
|
||||
if (i == 0 || i == valveNumber)
|
||||
{
|
||||
gw.send(msg1valve.setSensor(i).set(true), false);
|
||||
}
|
||||
else
|
||||
{
|
||||
gw.send(msg1valve.setSensor(i).set(false), false);
|
||||
}
|
||||
}
|
||||
}
|
||||
lastValve = valveNumber;
|
||||
fastToggleLed();
|
||||
if (state != lastState)
|
||||
{
|
||||
valveNumber = 1;
|
||||
updateRelays(ALL_VALVES_OFF);
|
||||
DEBUG_PRINTLN(F("State Changed, Running All Zones..."));
|
||||
}
|
||||
unsigned long nowMillis = millis();
|
||||
if (nowMillis - startMillis < VALVE_RESET_TIME)
|
||||
{
|
||||
updateRelays(ALL_VALVES_OFF);
|
||||
}
|
||||
else if (nowMillis - startMillis < (allZoneTime[valveNumber] * 60000UL))
|
||||
{
|
||||
updateRelays(BITSHIFT_VALVE_NUMBER);
|
||||
}
|
||||
else
|
||||
{
|
||||
DEBUG_PRINTLN(F("Changing Valves..."));
|
||||
updateRelays(ALL_VALVES_OFF);
|
||||
startMillis = millis();
|
||||
valveNumber++;
|
||||
if (valveNumber > NUMBER_OF_VALVES)
|
||||
{
|
||||
state = CYCLE_COMPLETE;
|
||||
startMillis = millis();
|
||||
lastValve = -1;
|
||||
lastTimeRun = now();
|
||||
saveDateToEEPROM(lastTimeRun);
|
||||
for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
|
||||
{
|
||||
gw.send(msg1valve.setSensor(i).set(false), false);
|
||||
}
|
||||
DEBUG_PRINT(F("State = "));
|
||||
DEBUG_PRINTLN(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
//
|
||||
else if (state == RUN_SINGLE_ZONE)
|
||||
{
|
||||
fastToggleLed();
|
||||
if (state != lastState)
|
||||
{
|
||||
for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
|
||||
{
|
||||
if (i == 0 || i == valveNumber)
|
||||
{
|
||||
gw.send(msg1valve.setSensor(i).set(true), false);
|
||||
}
|
||||
else
|
||||
{
|
||||
gw.send(msg1valve.setSensor(i).set(false), false);
|
||||
}
|
||||
}
|
||||
DEBUG_PRINTLN(F("State Changed, Single Zone Running..."));
|
||||
DEBUG_PRINT(F("Zone: "));
|
||||
DEBUG_PRINTLN(valveNumber);
|
||||
}
|
||||
unsigned long nowMillis = millis();
|
||||
if (nowMillis - startMillis < VALVE_RESET_TIME)
|
||||
{
|
||||
updateRelays(ALL_VALVES_OFF);
|
||||
}
|
||||
else if (nowMillis - startMillis < (valveSoloTime [valveNumber] * 60000UL))
|
||||
{
|
||||
updateRelays(BITSHIFT_VALVE_NUMBER);
|
||||
}
|
||||
else
|
||||
{
|
||||
updateRelays(ALL_VALVES_OFF);
|
||||
for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
|
||||
{
|
||||
gw.send(msg1valve.setSensor(i).set(false), false);
|
||||
}
|
||||
state = CYCLE_COMPLETE;
|
||||
startMillis = millis();
|
||||
DEBUG_PRINT(F("State = "));
|
||||
DEBUG_PRINTLN(state);
|
||||
}
|
||||
lastTimeRun = now();
|
||||
}
|
||||
else if (state == CYCLE_COMPLETE)
|
||||
{
|
||||
if (millis() - startMillis < 30000UL)
|
||||
{
|
||||
fastToggleLed();
|
||||
}
|
||||
else
|
||||
{
|
||||
state = STAND_BY_ALL_OFF;
|
||||
}
|
||||
}
|
||||
else if (state = ZONE_SELECT_MENU)
|
||||
{
|
||||
displayMenu();
|
||||
}
|
||||
lastState = state;
|
||||
}
|
||||
//
|
||||
void displayMenu(void)
|
||||
{
|
||||
static byte lastMenuState = -1;
|
||||
static int lastSecond;
|
||||
if (menuState != lastMenuState)
|
||||
{
|
||||
lcd.clear();
|
||||
lcd.setCursor(0, 0);
|
||||
lcd.print(valveNickName[menuState]);
|
||||
lcd.setCursor(0, 1);
|
||||
lcd.print(F("Starting"));
|
||||
DEBUG_PRINT(valveNickName[menuState]);
|
||||
Serial.print(F(" Starting Shortly"));
|
||||
}
|
||||
int thisSecond = (millis() - menuTimer) / 1000UL;
|
||||
if (thisSecond != lastSecond && thisSecond < 8)
|
||||
{
|
||||
lcd.print(F("."));
|
||||
Serial.print(".");
|
||||
}
|
||||
lastSecond = thisSecond;
|
||||
if (millis() - menuTimer > 10000UL)
|
||||
{
|
||||
startMillis = millis();
|
||||
if (menuState == 0)
|
||||
{
|
||||
valveNumber = 1;
|
||||
state = RUN_ALL_ZONES;
|
||||
}
|
||||
else
|
||||
{
|
||||
valveNumber = menuState;
|
||||
state = RUN_SINGLE_ZONE;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
}
|
||||
lastMenuState = menuState;
|
||||
}
|
||||
//
|
||||
void updateRelays(int value)
|
||||
{
|
||||
digitalWrite(latchPin, LOW);
|
||||
shiftOut(dataPin, clockPin, MSBFIRST, highByte(value));
|
||||
shiftOut(dataPin, clockPin, MSBFIRST, lowByte(value));
|
||||
digitalWrite(latchPin, HIGH);
|
||||
}
|
||||
//
|
||||
void PushButton() //interrupt with debounce
|
||||
{
|
||||
static unsigned long last_interrupt_time = 0;
|
||||
unsigned long interrupt_time = millis();
|
||||
if (interrupt_time - last_interrupt_time > 200)
|
||||
{
|
||||
buttonPushed = true;
|
||||
}
|
||||
last_interrupt_time = interrupt_time;
|
||||
}
|
||||
//
|
||||
void fastToggleLed()
|
||||
{
|
||||
static unsigned long fastLedTimer;
|
||||
if (millis() - fastLedTimer >= 100UL)
|
||||
{
|
||||
digitalWrite(ledPin, !digitalRead(ledPin));
|
||||
fastLedTimer = millis ();
|
||||
}
|
||||
}
|
||||
//
|
||||
void slowToggleLED ()
|
||||
{
|
||||
static unsigned long slowLedTimer;
|
||||
if (millis() - slowLedTimer >= 1250UL)
|
||||
{
|
||||
digitalWrite(ledPin, !digitalRead(ledPin));
|
||||
slowLedTimer = millis ();
|
||||
}
|
||||
}
|
||||
//
|
||||
void getVariables(const MyMessage &message)
|
||||
{
|
||||
boolean zoneTimeUpdate = false;
|
||||
if (message.isAck())
|
||||
{
|
||||
DEBUG_PRINTLN(F("This is an ack from gateway"));
|
||||
}
|
||||
for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
|
||||
{
|
||||
if (message.sensor == i)
|
||||
{
|
||||
if (message.type == V_LIGHT)
|
||||
{
|
||||
int switchState = atoi(message.data);
|
||||
if (switchState == 0)
|
||||
{
|
||||
state = STAND_BY_ALL_OFF;
|
||||
DEBUG_PRINTLN(F("Recieved Instruction to Cancel..."));
|
||||
}
|
||||
else
|
||||
{
|
||||
if (i == 0)
|
||||
{
|
||||
state = RUN_ALL_ZONES;
|
||||
valveNumber = 1;
|
||||
DEBUG_PRINTLN(F("Recieved Instruction to Run All Zones..."));
|
||||
}
|
||||
else
|
||||
{
|
||||
state = RUN_SINGLE_ZONE;
|
||||
valveNumber = i;
|
||||
DEBUG_PRINT(F("Recieved Instruction to Activate Zone: "));
|
||||
DEBUG_PRINTLN(i);
|
||||
}
|
||||
}
|
||||
startMillis = millis();
|
||||
}
|
||||
else if (message.type == V_VAR1)
|
||||
{
|
||||
int variable1 = atoi(message.data);// RUN_ALL_ZONES time
|
||||
DEBUG_PRINT(F("Recieved variable1 valve:"));
|
||||
DEBUG_PRINT(i);
|
||||
DEBUG_PRINT(F(" = "));
|
||||
DEBUG_PRINTLN(variable1);
|
||||
if (variable1 != allZoneTime[i])
|
||||
{
|
||||
allZoneTime[i] = variable1;
|
||||
|
||||
zoneTimeUpdate = true;
|
||||
}
|
||||
}
|
||||
else if (message.type == V_VAR2)
|
||||
{
|
||||
int variable2 = atoi(message.data);// RUN_SINGLE_ZONE time
|
||||
DEBUG_PRINT(F("Recieved variable2 valve:"));
|
||||
DEBUG_PRINT(i);
|
||||
DEBUG_PRINT(F(" = "));
|
||||
DEBUG_PRINTLN(variable2);
|
||||
if (variable2 != valveSoloTime[i])
|
||||
{
|
||||
valveSoloTime[i] = variable2;
|
||||
zoneTimeUpdate = true;
|
||||
}
|
||||
}
|
||||
else if (message.type == V_VAR3)
|
||||
{
|
||||
String newMessage = String(message.data);
|
||||
if (newMessage.length() == 0)
|
||||
{
|
||||
DEBUG_PRINT(F("No Name Recieved for zone "));
|
||||
DEBUG_PRINTLN(i);
|
||||
break;
|
||||
}
|
||||
if (newMessage.length() > 16)
|
||||
{
|
||||
newMessage.substring(0, 16);
|
||||
}
|
||||
valveNickName[i] = "";
|
||||
valveNickName[i] += newMessage;
|
||||
DEBUG_PRINT(F("Recieved new name for zone "));
|
||||
DEBUG_PRINT(i);
|
||||
DEBUG_PRINT(F(" and it is now called: "));
|
||||
DEBUG_PRINTLN(valveNickName[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (zoneTimeUpdate)
|
||||
{
|
||||
//
|
||||
DEBUG_PRINTLN(F("New Zone Times Recieved..."));
|
||||
for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
|
||||
{
|
||||
if (i != 0)
|
||||
{
|
||||
DEBUG_PRINT(F("Zone "));
|
||||
DEBUG_PRINT(i);
|
||||
DEBUG_PRINT(F(" individual time: "));
|
||||
DEBUG_PRINT(valveSoloTime[i]);
|
||||
DEBUG_PRINT(F(" group time: "));
|
||||
DEBUG_PRINTLN(allZoneTime[i]);
|
||||
recentUpdate = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
recentUpdate = false;
|
||||
}
|
||||
}
|
||||
//
|
||||
void updateDisplay()
|
||||
{
|
||||
static unsigned long lastUpdateTime;
|
||||
static boolean displayToggle = false;
|
||||
//static byte toggleCounter = 0;
|
||||
static SprinklerStates lastDisplayState;
|
||||
if (state != lastDisplayState || millis() - lastUpdateTime >= 3000UL)
|
||||
{
|
||||
displayToggle = !displayToggle;
|
||||
switch (state) {
|
||||
case STAND_BY_ALL_OFF:
|
||||
//
|
||||
fastClear();
|
||||
lcd.setCursor(0, 0);
|
||||
if (displayToggle)
|
||||
{
|
||||
lcd.print(F(" System Ready "));
|
||||
if (clockUpdating)
|
||||
{
|
||||
lcd.setCursor(15, 0);
|
||||
lcd.write(byte(0));
|
||||
}
|
||||
lcd.setCursor(0, 1);
|
||||
lcd.print(hourFormat12() < 10 ? F(" ") : F(""));
|
||||
lcd.print(hourFormat12());
|
||||
lcd.print(minute() < 10 ? F(":0") : F(":"));
|
||||
lcd.print(minute());
|
||||
lcd.print(isAM() ? F("am") : F("pm"));
|
||||
lcd.print(month() < 10 ? F(" 0") : F(" "));
|
||||
lcd.print(month());
|
||||
lcd.print(day() < 10 ? F("/0") : F("/"));
|
||||
lcd.print(day());
|
||||
lcd.print(F("/"));
|
||||
lcd.print(year() % 100);
|
||||
}
|
||||
else
|
||||
{
|
||||
lcd.print(F(" Last Watered "));
|
||||
if (clockUpdating)
|
||||
{
|
||||
lcd.setCursor(15, 0);
|
||||
lcd.write(byte(0));
|
||||
}
|
||||
lcd.setCursor(0, 1);
|
||||
lcd.print(dayOfWeek[weekday(lastTimeRun)]);
|
||||
lcd.setCursor(11, 1);
|
||||
lcd.print(month(lastTimeRun) < 10 ? F(" ") : F(""));
|
||||
lcd.print(month(lastTimeRun));
|
||||
lcd.print(day(lastTimeRun) < 10 ? F("/0") : F("/"));
|
||||
lcd.print(day(lastTimeRun));
|
||||
}
|
||||
break;
|
||||
case RUN_SINGLE_ZONE:
|
||||
//
|
||||
fastClear();
|
||||
lcd.setCursor(0, 0);
|
||||
if (displayToggle)
|
||||
{
|
||||
lcd.print(F("Single Zone Mode"));
|
||||
lcd.setCursor(0, 1);
|
||||
lcd.print(F(" Zone:"));
|
||||
if (valveNumber < 10) lcd.print(F("0"));
|
||||
lcd.print(valveNumber);
|
||||
lcd.print(F(" Active"));
|
||||
}
|
||||
else
|
||||
{
|
||||
lcd.print(F(" Time Remaining "));
|
||||
lcd.setCursor(0, 1);
|
||||
if (valveSoloTime[valveNumber] == 0)
|
||||
{
|
||||
lcd.print(F(" No Valve Time "));
|
||||
}
|
||||
else
|
||||
{
|
||||
unsigned long timeRemaining = (valveSoloTime[valveNumber] * 60) - ((millis() - startMillis) / 1000);
|
||||
lcd.print(timeRemaining / 60 < 10 ? " 0" : " ");
|
||||
lcd.print(timeRemaining / 60);
|
||||
lcd.print("min");
|
||||
lcd.print(timeRemaining % 60 < 10 ? " 0" : " ");
|
||||
lcd.print(timeRemaining % 60);
|
||||
lcd.print("sec ");
|
||||
}
|
||||
}
|
||||
break;
|
||||
case RUN_ALL_ZONES:
|
||||
//
|
||||
fastClear();
|
||||
lcd.setCursor(0, 0);
|
||||
if (displayToggle)
|
||||
{
|
||||
lcd.print(F(" All-Zone Mode "));
|
||||
lcd.setCursor(0, 1);
|
||||
lcd.print(F(" Zone:"));
|
||||
if (valveNumber < 10) lcd.print(F("0"));
|
||||
lcd.print(valveNumber);
|
||||
lcd.print(F(" Active "));
|
||||
}
|
||||
else
|
||||
{
|
||||
lcd.print(F(" Time Remaining "));
|
||||
lcd.setCursor(0, 1);
|
||||
int timeRemaining = (allZoneTime[valveNumber] * 60) - ((millis() - startMillis) / 1000);
|
||||
lcd.print((timeRemaining / 60) < 10 ? " 0" : " ");
|
||||
lcd.print(timeRemaining / 60);
|
||||
lcd.print("min");
|
||||
lcd.print(timeRemaining % 60 < 10 ? " 0" : " ");
|
||||
lcd.print(timeRemaining % 60);
|
||||
lcd.print("sec ");
|
||||
}
|
||||
break;
|
||||
case CYCLE_COMPLETE:
|
||||
//
|
||||
if (displayToggle)
|
||||
{
|
||||
lcd.setCursor(0, 0);
|
||||
lcd.print(F(" Watering Cycle "));
|
||||
lcd.setCursor(0, 1);
|
||||
lcd.print(F(" Complete "));
|
||||
}
|
||||
else
|
||||
{
|
||||
int totalTimeRan = 0;
|
||||
for (int i = 1; i < NUMBER_OF_VALVES + 1; i++)
|
||||
{
|
||||
totalTimeRan += allZoneTime[i];
|
||||
}
|
||||
lcd.setCursor(0, 0);
|
||||
lcd.print(F(" Total Time Run "));
|
||||
lcd.setCursor(0, 1);
|
||||
lcd.print(totalTimeRan < 10 ? " 0" : " ");
|
||||
lcd.print(totalTimeRan);
|
||||
lcd.print(" Minutes ");
|
||||
}
|
||||
}
|
||||
lastUpdateTime = millis();
|
||||
}
|
||||
lastDisplayState = state;
|
||||
}
|
||||
void receiveTime(time_t newTime)
|
||||
{
|
||||
DEBUG_PRINTLN(F("Time value received and updated..."));
|
||||
int lastSecond = second();
|
||||
int lastMinute = minute();
|
||||
int lastHour = hour();
|
||||
setTime(newTime);
|
||||
if (((second() != lastSecond) || (minute() != lastMinute) || (hour() != lastHour)) || showTime)
|
||||
{
|
||||
DEBUG_PRINTLN(F("Clock updated...."));
|
||||
DEBUG_PRINT(F("Sensor's time currently set to:"));
|
||||
DEBUG_PRINT(hourFormat12() < 10 ? F(" 0") : F(" "));
|
||||
DEBUG_PRINT(hourFormat12());
|
||||
DEBUG_PRINT(minute() < 10 ? F(":0") : F(":"));
|
||||
DEBUG_PRINT(minute());
|
||||
DEBUG_PRINTLN(isAM() ? F("am") : F("pm"));
|
||||
DEBUG_PRINT(month());
|
||||
DEBUG_PRINT(F("/"));
|
||||
DEBUG_PRINT(day());
|
||||
DEBUG_PRINT(F("/"));
|
||||
DEBUG_PRINTLN(year());
|
||||
DEBUG_PRINTLN(dayOfWeek[weekday()]);
|
||||
showTime = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
DEBUG_PRINTLN(F("Sensor's time did NOT need adjustment greater than 1 second."));
|
||||
}
|
||||
clockUpdating = false;
|
||||
}
|
||||
void fastClear()
|
||||
{
|
||||
lcd.setCursor(0, 0);
|
||||
lcd.print(F(" "));
|
||||
lcd.setCursor(0, 1);
|
||||
lcd.print(F(" "));
|
||||
}
|
||||
//
|
||||
void updateClock()
|
||||
{
|
||||
static unsigned long lastVeraGetTime;
|
||||
if (millis() - lastVeraGetTime >= 3600000UL) // updates clock time and gets zone times from vera once every hour
|
||||
{
|
||||
DEBUG_PRINTLN(F("Requesting time and valve data from Gateway..."));
|
||||
lcd.setCursor(15, 0);
|
||||
lcd.write(byte(0));
|
||||
clockUpdating = true;
|
||||
gw.requestTime(receiveTime);
|
||||
lastVeraGetTime = millis();
|
||||
}
|
||||
}
|
||||
//
|
||||
void saveDateToEEPROM(unsigned long theDate)
|
||||
{
|
||||
DEBUG_PRINTLN(F("Saving Last Run date"));
|
||||
if (gw.loadState(0) != 0xFF)
|
||||
{
|
||||
gw.saveState(0, 0xFF); // EEPROM flag for last date saved stored in EEPROM (location zero)
|
||||
}
|
||||
//
|
||||
for (int i = 1; i < 5; i++)
|
||||
{
|
||||
gw.saveState(5 - i, byte(theDate >> 8 * (i - 1))); // store epoch datestamp in 4 bytes of EEPROM starting in location one
|
||||
}
|
||||
}
|
||||
//
|
||||
void goGetValveTimes()
|
||||
{
|
||||
static unsigned long valveUpdateTime;
|
||||
static byte valveIndex = 1;
|
||||
if (millis() - valveUpdateTime >= 300000UL / NUMBER_OF_VALVES)// update each valve once every 5 mins (distributes the traffic)
|
||||
{
|
||||
DEBUG_PRINTLN(F("Calling for Valve Data..."));
|
||||
lcd.setCursor(15, 0);
|
||||
lcd.write(byte(1)); //lcd.write(1);
|
||||
gw.request(valveIndex, V_VAR1);
|
||||
gw.request(valveIndex, V_VAR2);
|
||||
gw.request(valveIndex, V_VAR3);
|
||||
valveUpdateTime = millis();
|
||||
valveIndex++;
|
||||
if (valveIndex > NUMBER_OF_VALVES + 1)
|
||||
{
|
||||
valveIndex = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,12 +43,16 @@
|
||||
#include <Wire.h>
|
||||
|
||||
#define CHILD_ID_LIGHT 0
|
||||
#define LIGHT_SENSOR_ANALOG_PIN 0
|
||||
unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds)
|
||||
|
||||
BH1750 lightSensor;
|
||||
MySensor gw;
|
||||
MyMessage msg(CHILD_ID_LIGHT, V_LIGHT_LEVEL_LUX);
|
||||
|
||||
// V_LIGHT_LEVEL should only be used for uncalibrated light level 0-100%.
|
||||
// If your controller supports the new V_LEVEL variable, use this instead for
|
||||
// transmitting LUX light level.
|
||||
MyMessage msg(CHILD_ID_LIGHT, V_LIGHT_LEVEL);
|
||||
// MyMessage msg(CHILD_ID_LIGHT, V_LEVEL);
|
||||
uint16_t lastlux;
|
||||
|
||||
void setup()
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// This sketch is to integrate the Playing With Fusion AXS3935 Lightning Sensor Breakout Board
|
||||
// with the MySensors environment and is based on a sketch provided by Playing With Fusion
|
||||
// http://playingwithfusion.com/productview.php?pdid=22&catid=1001
|
||||
//
|
||||
#include "MySensor.h"
|
||||
// the lightning sensor can communicate via SPI or I2C. This sketch uses the SPI interface
|
||||
#include "SPI.h"
|
||||
// include Playing With Fusion AXS3935 libraries
|
||||
#include "PWFusion_AS3935.h"
|
||||
|
||||
// setup CS pins used for the connection with the lightning sensor
|
||||
// other connections are controlled by the SPI library)
|
||||
int8_t CS_PIN = 8;
|
||||
int8_t SI_PIN = 7;
|
||||
int8_t IRQ_PIN = 3;
|
||||
volatile int8_t AS3935_ISR_Trig = 0;
|
||||
|
||||
// #defines
|
||||
#define AS3935_INDOORS 1
|
||||
#define AS3935_OUTDOORS 0
|
||||
#define AS3935_DIST_DIS 0
|
||||
#define AS3935_DIST_EN 1
|
||||
#define AS3935_CAPACITANCE 96 // <-- SET THIS VALUE TO THE NUMBER LISTED ON YOUR BOARD
|
||||
// prototypes
|
||||
void AS3935_ISR();
|
||||
|
||||
PWF_AS3935 lightning0(CS_PIN, IRQ_PIN, SI_PIN);
|
||||
|
||||
#define CHILD_ID_DISTANCE 1
|
||||
#define CHILD_ID_INTENSITY 2
|
||||
MySensor gw;
|
||||
MyMessage msgDist(CHILD_ID_DISTANCE, V_DISTANCE);
|
||||
MyMessage msgInt(CHILD_ID_INTENSITY, V_VAR1);
|
||||
|
||||
void setup()
|
||||
{
|
||||
gw.begin();
|
||||
|
||||
// Send the sketch version information to the gateway and Controller
|
||||
gw.sendSketchInfo("Lightning Sensor", "1.1");
|
||||
|
||||
// Register all sensors to gw (they will be created as child devices)
|
||||
gw.present(CHILD_ID_DISTANCE, S_DISTANCE);
|
||||
gw.present(CHILD_ID_INTENSITY, S_CUSTOM);
|
||||
boolean metric = gw.getConfig().isMetric;
|
||||
|
||||
Serial.begin(115200);
|
||||
Serial.println("Playing With Fusion: AS3935 Lightning Sensor, SEN-39001");
|
||||
Serial.println("beginning boot procedure....");
|
||||
|
||||
// setup for the the SPI library:
|
||||
SPI.begin(); // begin SPI
|
||||
SPI.setClockDivider(SPI_CLOCK_DIV4); // SPI speed to SPI_CLOCK_DIV16/1MHz (max 2MHz, NEVER 500kHz!)
|
||||
SPI.setDataMode(SPI_MODE1); // MAX31855 is a Mode 1 device
|
||||
// --> clock starts low, read on rising edge
|
||||
SPI.setBitOrder(MSBFIRST); // data sent to chip MSb first
|
||||
|
||||
lightning0.AS3935_DefInit(); // set registers to default
|
||||
// now update sensor cal for your application and power up chip
|
||||
lightning0.AS3935_ManualCal(AS3935_CAPACITANCE, AS3935_OUTDOORS, AS3935_DIST_EN);
|
||||
// AS3935_ManualCal Parameters:
|
||||
// --> capacitance, in pF (marked on package)
|
||||
// --> indoors/outdoors (AS3935_INDOORS:0 / AS3935_OUTDOORS:1)
|
||||
// --> disturbers (AS3935_DIST_EN:1 / AS3935_DIST_DIS:2)
|
||||
// function also powers up the chip
|
||||
|
||||
// enable interrupt (hook IRQ pin to Arduino Uno/Mega interrupt input: 1 -> pin 3 )
|
||||
attachInterrupt(1, AS3935_ISR, RISING);
|
||||
// dump the registry data to the serial port for troubleshooting purposes
|
||||
lightning0.AS3935_PrintAllRegs();
|
||||
|
||||
// delay execution to allow chip to stabilize.
|
||||
delay(1000);
|
||||
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
|
||||
// This program only handles an AS3935 lightning sensor. It does nothing until
|
||||
// an interrupt is detected on the IRQ pin.
|
||||
while(0 == AS3935_ISR_Trig){}
|
||||
|
||||
// reset interrupt flag
|
||||
AS3935_ISR_Trig = 0;
|
||||
|
||||
// now get interrupt source
|
||||
uint8_t int_src = lightning0.AS3935_GetInterruptSrc();
|
||||
if(0 == int_src)
|
||||
{
|
||||
Serial.println("Unknown interrupt source");
|
||||
}
|
||||
else if(1 == int_src)
|
||||
{
|
||||
uint8_t lightning_dist_km = lightning0.AS3935_GetLightningDistKm();
|
||||
uint32_t lightning_intensity = lightning0.AS3935_GetStrikeEnergyRaw();
|
||||
|
||||
Serial.print("Lightning detected! Distance to strike: ");
|
||||
Serial.print(lightning_dist_km);
|
||||
Serial.println(" kilometers");
|
||||
Serial.print("Lightning detected! Lightning Intensity: ");
|
||||
Serial.println(lightning_intensity);
|
||||
gw.send(msgDist.set(lightning_dist_km));
|
||||
gw.send(msgInt.set(lightning_intensity));
|
||||
}
|
||||
else if(2 == int_src)
|
||||
{
|
||||
Serial.println("Disturber detected");
|
||||
}
|
||||
else if(3 == int_src)
|
||||
{
|
||||
Serial.println("Noise level too high");
|
||||
}
|
||||
}
|
||||
|
||||
// this is irq handler for AS3935 interrupts, has to return void and take no arguments
|
||||
// always make code in interrupt handlers fast and short
|
||||
void AS3935_ISR()
|
||||
{
|
||||
AS3935_ISR_Trig = 1;
|
||||
}␍
|
||||
@@ -118,7 +118,7 @@ byte TCP_MAC[] = { 0x02, 0xDE, 0xAD, 0x00, 0x00, 0x42 }; // Mac-address - You sh
|
||||
//////////////////////////////////////////////////////////////////
|
||||
|
||||
// NRFRF24L01 radio driver (set low transmit power by default)
|
||||
MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW);
|
||||
MyTransportNRF24 transport(RADIO_CE_PIN, RADIO_SPI_SS_PIN, RF24_PA_LEVEL_GW);
|
||||
//MyTransportRFM69 transport;
|
||||
|
||||
// Message signing driver (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,15 @@
|
||||
# MockMySensors
|
||||
Arduino sketch to fake sensor for the MySensors Library
|
||||
|
||||
This skecth is intended to crate fake sensors which register and respond to the controller
|
||||
|
||||
Barduino 2015
|
||||
-----------------
|
||||
|
||||
Comment/Uncomment the sensors you would like to test
|
||||
|
||||
Arduino Uno R3 can support about 12 sensors before it runs out of memory.
|
||||
You probably need to turn of the MySensor Lib debug to save some memory
|
||||
|
||||
Nest step will be to remove the read/write to the eprom
|
||||
and extend to support the v1.5 sensors
|
||||
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
* The MySensors Arduino library handles the wireless radio link and protocol
|
||||
* between your home built sensors/actuators and HA controller of choice.
|
||||
* The sensors forms a self healing radio network with optional repeaters. Each
|
||||
* repeater and gateway builds a routing tables in EEPROM which keeps track of the
|
||||
* network topology allowing messages to be routed to nodes.
|
||||
*
|
||||
* Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
|
||||
* Copyright (C) 2013-2015 Sensnology AB
|
||||
* Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
|
||||
*
|
||||
* Documentation: http://www.mysensors.org
|
||||
* Support Forum: http://forum.mysensors.org
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU General Public License
|
||||
* version 2 as published by the Free Software Foundation.
|
||||
*
|
||||
*******************************
|
||||
*
|
||||
* REVISION HISTORY
|
||||
* Version 1.0 - Created by Henrik Ekblad
|
||||
*
|
||||
* DESCRIPTION
|
||||
* Parking sensor using a neopixel led ring and distance sensor (HC-SR04).
|
||||
* Configure the digital pins used for distance sensor and neopixels below.
|
||||
* NOTE! Remeber to feed leds and distance sensor serparatly from your Arduino.
|
||||
* It will probably not survive feeding more than a couple of LEDs. You
|
||||
* can also adjust intesity below to reduce the power requirements.
|
||||
*
|
||||
* Sends parking status to the controller as a DOOR sensor if SEND_STATUS_TO_CONTROLLER
|
||||
* is defined below. You can also use this _standalone_ without any radio by
|
||||
* removing the SEND_STATUS_TO_CONTROLLER define.
|
||||
*/
|
||||
|
||||
#define SEND_STATUS_TO_CONTROLLER // Put a comment on this line for standalone mode
|
||||
|
||||
#include <Adafruit_NeoPixel.h>
|
||||
#include <NewPing.h>
|
||||
|
||||
#ifdef SEND_STATUS_TO_CONTROLLER
|
||||
#include <SPI.h>
|
||||
#include <MySensor.h>
|
||||
#endif
|
||||
|
||||
#define NEO_PIN 4 // NeoPixels input pin
|
||||
|
||||
#define TRIGGER_PIN 6 // Arduino pin tied to trigger pin on the ultrasonic sensor.
|
||||
#define ECHO_PIN 5 // Arduino pin tied to echo pin on the ultrasonic sensor.
|
||||
|
||||
#define NUMPIXELS 24 // Number of nexpixels in ring/strip
|
||||
#define MAX_INTESITY 20 // Intesity of leds (in percentage). Remeber more intesity requires more power.
|
||||
|
||||
// The maximum rated measuring range for the HC-SR04 is about 400-500cm.
|
||||
#define MAX_DISTANCE 100 // Max distance we want to start indicating green (in cm)
|
||||
#define PANIC_DISTANCE 5 // Mix distance we red warning indication should be active (in cm)
|
||||
#define PARKED_DISTANCE 20 // Distance when "parked signal" should be sent to controller (in cm)
|
||||
|
||||
// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
|
||||
// example for more information on possible values.
|
||||
|
||||
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, NEO_PIN, NEO_GRB + NEO_KHZ400);
|
||||
|
||||
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
|
||||
|
||||
#ifdef SEND_STATUS_TO_CONTROLLER
|
||||
#define CHILD_ID 1
|
||||
MySensor gw;
|
||||
MyMessage msg(CHILD_ID,V_TRIPPED);
|
||||
int oldParkedStatus=-1;
|
||||
int sendInterval = 5000; // Send park status at maximum every 5 second.
|
||||
unsigned long lastSend;
|
||||
#endif
|
||||
|
||||
int blinkInterval = 100; // blink interval (milliseconds)
|
||||
unsigned long lastBlinkPeriod;
|
||||
bool blinkColor = true;
|
||||
|
||||
// To make a fading motion on the led ring/tape we only move one pixel/distDebounce time
|
||||
int distDebounce = 30;
|
||||
unsigned long lastDebouncePeriod;
|
||||
int numLightPixels=0;
|
||||
int skipZero=0;
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
Serial.println("Starting distance sensor");
|
||||
pixels.begin(); // This initializes the NeoPixel library.
|
||||
Serial.println("Neopixels initialized");
|
||||
#ifdef SEND_STATUS_TO_CONTROLLER
|
||||
gw.begin();
|
||||
gw.sendSketchInfo("Parking Sensor", "1.0");
|
||||
gw.present(CHILD_ID, S_DOOR, "Parking Status");
|
||||
#endif
|
||||
}
|
||||
|
||||
void loop() {
|
||||
unsigned long now = millis();
|
||||
|
||||
int fullDist = sonar.ping_cm();
|
||||
// Serial.println(fullDist);
|
||||
int displayDist = min(fullDist, MAX_DISTANCE);
|
||||
if (displayDist == 0 && skipZero<10) {
|
||||
// Try to filter zero readings
|
||||
skipZero++;
|
||||
return;
|
||||
}
|
||||
// Check if it is time to alter the leds
|
||||
if (now-lastDebouncePeriod > distDebounce) {
|
||||
lastDebouncePeriod = now;
|
||||
|
||||
#ifdef SEND_STATUS_TO_CONTROLLER
|
||||
// Update parked status
|
||||
int parked = displayDist != 0 && displayDist<PARKED_DISTANCE;
|
||||
if (parked != oldParkedStatus && now-lastSend > sendInterval) {
|
||||
if (parked)
|
||||
Serial.println("Car Parked");
|
||||
else
|
||||
Serial.println("Car Gone");
|
||||
gw.send(msg.set(parked));
|
||||
oldParkedStatus = parked;
|
||||
lastSend = now;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (displayDist == 0) {
|
||||
// No reading from sensor, assume no object found
|
||||
numLightPixels--;
|
||||
} else {
|
||||
skipZero = 0;
|
||||
int newLightPixels = NUMPIXELS - (NUMPIXELS*(displayDist-PANIC_DISTANCE)/MAX_DISTANCE);
|
||||
if (newLightPixels>numLightPixels) {
|
||||
// Fast raise
|
||||
numLightPixels += max((newLightPixels - numLightPixels) / 2, 1);
|
||||
} else if (newLightPixels<numLightPixels) {
|
||||
// Slow decent
|
||||
numLightPixels--;
|
||||
}
|
||||
}
|
||||
|
||||
if (numLightPixels>=NUMPIXELS) {
|
||||
// Do some intense red blinking
|
||||
if (now-lastBlinkPeriod > blinkInterval) {
|
||||
blinkColor = !blinkColor;
|
||||
lastBlinkPeriod = now;
|
||||
}
|
||||
for(int i=0;i<numLightPixels;i++){
|
||||
pixels.setPixelColor(i, pixels.Color(blinkColor?255*MAX_INTESITY/100:0,0,0));
|
||||
}
|
||||
} else {
|
||||
for(int i=0;i<numLightPixels;i++){
|
||||
int r = 255 * i/NUMPIXELS;
|
||||
int g = 255 - r;
|
||||
// pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
|
||||
pixels.setPixelColor(i, pixels.Color(r*MAX_INTESITY/100,g*MAX_INTESITY/100,0));
|
||||
}
|
||||
// Turn off the rest
|
||||
for(int i=numLightPixels;i<NUMPIXELS;i++){
|
||||
pixels.setPixelColor(i, pixels.Color(0,0,0));
|
||||
}
|
||||
}
|
||||
pixels.show(); // This sends the updated pixel color to the hardware.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/****
|
||||
* Formatted logging to the Serial console.
|
||||
* Compiled in by setting LOGDEBUG
|
||||
*
|
||||
* 2015-05-25 Bruce Lacey V1.0
|
||||
*
|
||||
* Based upon Arduino Playground prior art and should be moved to
|
||||
* the MySensors library at some point as a common debug logging facility
|
||||
*/
|
||||
#ifndef MYSLog_h
|
||||
#define MYSLog_h
|
||||
|
||||
#define LOGDEBUG 1
|
||||
|
||||
#if defined ( LOGDEBUG )
|
||||
#define LOG(fmt, args... ) log( fmt, ## args );
|
||||
#else
|
||||
#define log(fmt, args... )
|
||||
#endif
|
||||
|
||||
void log(const char *fmt, ... ) {
|
||||
char buff[128];
|
||||
va_list args;
|
||||
va_start (args, fmt);
|
||||
vsnprintf(buff, sizeof(buff), fmt, args);
|
||||
va_end (args);
|
||||
buff[sizeof(buff)/sizeof(buff[0])-1]='\0';
|
||||
Serial.print(buff);
|
||||
}
|
||||
|
||||
void log(const __FlashStringHelper *fmt, ... ){
|
||||
char buf[128]; // resulting string limited to 128 chars
|
||||
va_list args;
|
||||
va_start (args, fmt);
|
||||
#ifdef __AVR__
|
||||
vsnprintf_P(buf, sizeof(buf), (const char *)fmt, args); // progmem for AVR
|
||||
#else
|
||||
vsnprintf(buf, sizeof(buf), (const char *)fmt, args); // for the rest of the world
|
||||
#endif
|
||||
va_end(args);
|
||||
Serial.print(buf);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,99 @@
|
||||
/***
|
||||
* This is a simple sketch used to demenstrate and test node-to-node MySensor's communication.
|
||||
* To use this sketch, assemble MySensors nodes - they need nothing more than a radio
|
||||
* 1. Flash each node with the same sketch, open the console and type either 0 or 1 to the respective nodes to set thei ID
|
||||
* 2. You only need to set the node id once, and restart the nodes
|
||||
* 3. To being a ping-pong test, simply type T in the console for one of the nodes.
|
||||
*
|
||||
* 2015-05-25 Bruce Lacey v1.0
|
||||
*/
|
||||
|
||||
#include <MySensor.h>
|
||||
#include <SPI.h>
|
||||
#include "MYSLog.h"
|
||||
|
||||
#define VSN "v1.0"
|
||||
|
||||
// Define two generic nodes with a single child
|
||||
#define YING 200
|
||||
#define YANG 201
|
||||
#define CHILD 1
|
||||
|
||||
// Sensor objects
|
||||
MySensor gw;
|
||||
|
||||
MyMessage mPing(CHILD, V_VAR1); //Ping message
|
||||
MyMessage mPong(CHILD, V_VAR2); //Pong message
|
||||
|
||||
void setup() {
|
||||
|
||||
Serial.begin(115200);
|
||||
|
||||
gw.begin(incomingMessage); // Node ids are written to EEPROM during sensor node configuration by entering a 0 or 1
|
||||
gw.present(CHILD, S_CUSTOM); //
|
||||
|
||||
gw.sendSketchInfo( nodeTypeAsCharRepresentation( gw.getNodeId() ), VSN );
|
||||
LOG(F("\n%sReady.\n"), nodeTypeAsCharRepresentation(gw.getNodeId()));
|
||||
}
|
||||
|
||||
void loop() {
|
||||
|
||||
// Interactive command and control
|
||||
// Entering a number from 0 or 1 will write the node 200 (YING) or 201 (YANG) to EEPROM
|
||||
// Entering T on either node will initiatve a ping-pong test.
|
||||
if (Serial.available()) {
|
||||
byte inChar = Serial.read();
|
||||
uint8_t node = gw.getNodeId();
|
||||
|
||||
// Manual Test Mode
|
||||
if (inChar == 'T' || inChar == 't') {
|
||||
LOG(F("T received - starting test...\n"));
|
||||
MyMessage msg = mPong;
|
||||
msg.sender = (node == YING ? YANG : YING);
|
||||
sendPingOrPongResponse( msg );
|
||||
}
|
||||
else if (inChar == '0' or inChar == '1') {
|
||||
byte nodeID = 200 + (inChar - '0');
|
||||
setNodeId(nodeID);
|
||||
}
|
||||
else {
|
||||
LOG("Invalid input\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Process sensor messages
|
||||
gw.process();
|
||||
}
|
||||
|
||||
void incomingMessage(const MyMessage &message) {
|
||||
|
||||
LOG(F("Received %s from %s\n"), msgTypeAsCharRepresentation((mysensor_data)message.type), nodeTypeAsCharRepresentation(message.sender));
|
||||
|
||||
delay(250);
|
||||
sendPingOrPongResponse( message );
|
||||
}
|
||||
|
||||
void sendPingOrPongResponse( MyMessage msg ) {
|
||||
|
||||
MyMessage response = (msg.type == V_VAR1 ? mPong : mPing);
|
||||
|
||||
LOG(F("Sending %s to %s\n"), msgTypeAsCharRepresentation( (mysensor_data)response.type ), nodeTypeAsCharRepresentation(msg.sender));
|
||||
|
||||
// Set payload to current time in millis to ensure each message is unique
|
||||
response.set( millis() );
|
||||
response.setDestination(msg.sender);
|
||||
gw.send(response);
|
||||
}
|
||||
|
||||
void setNodeId(byte nodeID) {
|
||||
LOG(F("Setting node id to: %i.\n***Please restart the node for changes to take effect.\n"), nodeID);
|
||||
eeprom_write_byte((uint8_t*)EEPROM_NODE_ID_ADDRESS, (byte)nodeID);
|
||||
}
|
||||
|
||||
const char * msgTypeAsCharRepresentation( mysensor_data mType ) {
|
||||
return mType == V_VAR1 ? "Ping" : "Pong";
|
||||
}
|
||||
|
||||
const char * nodeTypeAsCharRepresentation( uint8_t node ) {
|
||||
return node == YING ? "Ying Node" : "Yang Node";
|
||||
}
|
||||
@@ -35,7 +35,21 @@
|
||||
#define BARO_CHILD 0
|
||||
#define TEMP_CHILD 1
|
||||
|
||||
unsigned long SLEEP_TIME = 60000; // Sleep time between reads (in seconds)
|
||||
const float ALTITUDE = 688; // <-- adapt this value to your own location's altitude.
|
||||
|
||||
// Sleep time between reads (in seconds). Do not change this value as the forecast algorithm needs a sample every minute.
|
||||
const unsigned long SLEEP_TIME = 60000;
|
||||
|
||||
const char *weather[] = { "stable", "sunny", "cloudy", "unstable", "thunderstorm", "unknown" };
|
||||
enum FORECAST
|
||||
{
|
||||
STABLE = 0, // "Stable Weather Pattern"
|
||||
SUNNY = 1, // "Slowly rising Good Weather", "Clear/Sunny "
|
||||
CLOUDY = 2, // "Slowly falling L-Pressure ", "Cloudy/Rain "
|
||||
UNSTABLE = 3, // "Quickly rising H-Press", "Not Stable"
|
||||
THUNDERSTORM = 4, // "Quickly falling L-Press", "Thunderstorm"
|
||||
UNKNOWN = 5 // "Unknown (More Time needed)
|
||||
};
|
||||
|
||||
Adafruit_BMP085 bmp = Adafruit_BMP085(); // Digital Pressure Sensor
|
||||
MySensor gw;
|
||||
@@ -43,206 +57,243 @@ MySensor gw;
|
||||
float lastPressure = -1;
|
||||
float lastTemp = -1;
|
||||
int lastForecast = -1;
|
||||
const char *weather[] = {"stable","sunny","cloudy","unstable","thunderstorm","unknown"};
|
||||
int minutes;
|
||||
float pressureSamples[7][6];
|
||||
|
||||
const int LAST_SAMPLES_COUNT = 5;
|
||||
float lastPressureSamples[LAST_SAMPLES_COUNT];
|
||||
|
||||
// this CONVERSION_FACTOR is used to convert from Pa to kPa in forecast algorithm
|
||||
// get kPa/h be dividing hPa by 10
|
||||
#define CONVERSION_FACTOR (1.0/10.0)
|
||||
|
||||
int minuteCount = 0;
|
||||
bool firstRound = true;
|
||||
float pressureAvg[7];
|
||||
// average value is used in forecast algorithm.
|
||||
float pressureAvg;
|
||||
// average after 2 hours is used as reference value for the next iteration.
|
||||
float pressureAvg2;
|
||||
|
||||
float dP_dt;
|
||||
boolean metric;
|
||||
boolean metric;
|
||||
MyMessage tempMsg(TEMP_CHILD, V_TEMP);
|
||||
MyMessage pressureMsg(BARO_CHILD, V_PRESSURE);
|
||||
MyMessage forecastMsg(BARO_CHILD, V_FORECAST);
|
||||
|
||||
void setup() {
|
||||
gw.begin();
|
||||
|
||||
// Send the sketch version information to the gateway and Controller
|
||||
gw.sendSketchInfo("Pressure Sensor", "1.0");
|
||||
void setup()
|
||||
{
|
||||
gw.begin();
|
||||
|
||||
if (!bmp.begin()) {
|
||||
Serial.println("Could not find a valid BMP085 sensor, check wiring!");
|
||||
while (1) { }
|
||||
}
|
||||
// Send the sketch version information to the gateway and Controller
|
||||
gw.sendSketchInfo("Pressure Sensor", "1.1");
|
||||
|
||||
// Register sensors to gw (they will be created as child devices)
|
||||
gw.present(BARO_CHILD, S_BARO);
|
||||
gw.present(TEMP_CHILD, S_TEMP);
|
||||
metric = gw.getConfig().isMetric;
|
||||
if (!bmp.begin())
|
||||
{
|
||||
Serial.println("Could not find a valid BMP085 sensor, check wiring!");
|
||||
while (1) {}
|
||||
}
|
||||
|
||||
// Register sensors to gw (they will be created as child devices)
|
||||
gw.present(BARO_CHILD, S_BARO);
|
||||
gw.present(TEMP_CHILD, S_TEMP);
|
||||
metric = gw.getConfig().isMetric;
|
||||
}
|
||||
|
||||
void loop() {
|
||||
float pressure = bmp.readSealevelPressure(205)/100; // 205 meters above sealevel
|
||||
float temperature = bmp.readTemperature();
|
||||
|
||||
if (!metric) {
|
||||
// Convert to fahrenheit
|
||||
temperature = temperature * 9.0 / 5.0 + 32.0;
|
||||
}
|
||||
|
||||
int forecast = sample(pressure);
|
||||
void loop()
|
||||
{
|
||||
float pressure = bmp.readSealevelPressure(ALTITUDE) / 100.0;
|
||||
float temperature = bmp.readTemperature();
|
||||
|
||||
Serial.print("Temperature = ");
|
||||
Serial.print(temperature);
|
||||
Serial.println(metric?" *C":" *F");
|
||||
Serial.print("Pressure = ");
|
||||
Serial.print(pressure);
|
||||
Serial.println(" Pa");
|
||||
Serial.println(weather[forecast]);
|
||||
if (!metric)
|
||||
{
|
||||
// Convert to fahrenheit
|
||||
temperature = temperature * 9.0 / 5.0 + 32.0;
|
||||
}
|
||||
|
||||
int forecast = sample(pressure);
|
||||
|
||||
Serial.print("Temperature = ");
|
||||
Serial.print(temperature);
|
||||
Serial.println(metric ? " *C" : " *F");
|
||||
Serial.print("Pressure = ");
|
||||
Serial.print(pressure);
|
||||
Serial.println(" hPa");
|
||||
Serial.print("Forecast = ");
|
||||
Serial.println(weather[forecast]);
|
||||
|
||||
|
||||
if (temperature != lastTemp) {
|
||||
gw.send(tempMsg.set(temperature,1));
|
||||
lastTemp = temperature;
|
||||
}
|
||||
if (temperature != lastTemp)
|
||||
{
|
||||
gw.send(tempMsg.set(temperature, 1));
|
||||
lastTemp = temperature;
|
||||
}
|
||||
|
||||
if (pressure != lastPressure) {
|
||||
gw.send(pressureMsg.set(pressure, 0));
|
||||
lastPressure = pressure;
|
||||
}
|
||||
if (pressure != lastPressure)
|
||||
{
|
||||
gw.send(pressureMsg.set(pressure, 0));
|
||||
lastPressure = pressure;
|
||||
}
|
||||
|
||||
if (forecast != lastForecast) {
|
||||
gw.send(forecastMsg.set(weather[forecast]));
|
||||
lastForecast = forecast;
|
||||
}
|
||||
|
||||
/*
|
||||
DP/Dt explanation
|
||||
if (forecast != lastForecast)
|
||||
{
|
||||
gw.send(forecastMsg.set(weather[forecast]));
|
||||
lastForecast = forecast;
|
||||
}
|
||||
|
||||
0 = "Stable Weather Pattern"
|
||||
1 = "Slowly rising Good Weather", "Clear/Sunny "
|
||||
2 = "Slowly falling L-Pressure ", "Cloudy/Rain "
|
||||
3 = "Quickly rising H-Press", "Not Stable"
|
||||
4 = "Quickly falling L-Press", "Thunderstorm"
|
||||
5 = "Unknown (More Time needed)
|
||||
*/
|
||||
|
||||
gw.sleep(SLEEP_TIME);
|
||||
gw.sleep(SLEEP_TIME);
|
||||
}
|
||||
|
||||
int sample(float pressure) {
|
||||
// Algorithm found here
|
||||
// http://www.freescale.com/files/sensors/doc/app_note/AN3914.pdf
|
||||
if (minuteCount == 180)
|
||||
minuteCount = 5;
|
||||
|
||||
//From 0 to 5 min.
|
||||
if (minuteCount <= 5){
|
||||
pressureSamples[0][minuteCount] = pressure;
|
||||
}
|
||||
//From 30 to 35 min.
|
||||
if ((minuteCount <= 30) && (minuteCount >= 35)){
|
||||
pressureSamples[1][minuteCount - 30] = pressure;
|
||||
}
|
||||
//From 55 to 60 min.
|
||||
if ((minuteCount <= 55) && (minuteCount >= 60)){
|
||||
pressureSamples[2][minuteCount - 55] = pressure;
|
||||
}
|
||||
//From 90 to 95 min.
|
||||
if ((minuteCount <= 90) && (minuteCount >= 95)){
|
||||
pressureSamples[3][minuteCount - 90] = pressure;
|
||||
}
|
||||
//From 115 to 119 min.
|
||||
if ((minuteCount <= 115) && (minuteCount >= 120)){
|
||||
pressureSamples[4][minuteCount - 115] = pressure;
|
||||
}
|
||||
//From 150 to 155 min.
|
||||
if ((minuteCount <= 150) && (minuteCount >= 155)){
|
||||
pressureSamples[5][minuteCount - 150] = pressure;
|
||||
}
|
||||
//From 175 to 180 min.
|
||||
if ((minuteCount <= 175) && (minuteCount >= 180)){
|
||||
pressureSamples[6][minuteCount - 175] = pressure;
|
||||
}
|
||||
|
||||
float getLastPressureSamplesAverage()
|
||||
{
|
||||
float lastPressureSamplesAverage = 0;
|
||||
for (int i = 0; i < LAST_SAMPLES_COUNT; i++)
|
||||
{
|
||||
lastPressureSamplesAverage += lastPressureSamples[i];
|
||||
}
|
||||
lastPressureSamplesAverage /= LAST_SAMPLES_COUNT;
|
||||
|
||||
return lastPressureSamplesAverage;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Algorithm found here
|
||||
// http://www.freescale.com/files/sensors/doc/app_note/AN3914.pdf
|
||||
// Pressure in hPa --> forecast done by calculating kPa/h
|
||||
int sample(float pressure)
|
||||
{
|
||||
// Calculate the average of the last n minutes.
|
||||
int index = minuteCount % LAST_SAMPLES_COUNT;
|
||||
lastPressureSamples[index] = pressure;
|
||||
|
||||
minuteCount++;
|
||||
if (minuteCount > 185)
|
||||
{
|
||||
minuteCount = 6;
|
||||
}
|
||||
|
||||
if (minuteCount == 5) {
|
||||
// Avg pressure in first 5 min, value averaged from 0 to 5 min.
|
||||
pressureAvg[0] = ((pressureSamples[0][0] + pressureSamples[0][1]
|
||||
+ pressureSamples[0][2] + pressureSamples[0][3]
|
||||
+ pressureSamples[0][4] + pressureSamples[0][5]) / 6);
|
||||
} else if (minuteCount == 35) {
|
||||
// Avg pressure in 30 min, value averaged from 0 to 5 min.
|
||||
pressureAvg[1] = ((pressureSamples[1][0] + pressureSamples[1][1]
|
||||
+ pressureSamples[1][2] + pressureSamples[1][3]
|
||||
+ pressureSamples[1][4] + pressureSamples[1][5]) / 6);
|
||||
float change = (pressureAvg[1] - pressureAvg[0]);
|
||||
if (minuteCount == 5)
|
||||
{
|
||||
pressureAvg = getLastPressureSamplesAverage();
|
||||
}
|
||||
else if (minuteCount == 35)
|
||||
{
|
||||
float lastPressureAvg = getLastPressureSamplesAverage();
|
||||
float change = (lastPressureAvg - pressureAvg) * CONVERSION_FACTOR;
|
||||
if (firstRound) // first time initial 3 hour
|
||||
dP_dt = ((65.0 / 1023.0) * 2 * change); // note this is for t = 0.5hour
|
||||
{
|
||||
dP_dt = change * 2; // note this is for t = 0.5hour
|
||||
}
|
||||
else
|
||||
dP_dt = (((65.0 / 1023.0) * change) / 1.5); // divide by 1.5 as this is the difference in time from 0 value.
|
||||
} else if (minuteCount == 60) {
|
||||
// Avg pressure at end of the hour, value averaged from 0 to 5 min.
|
||||
pressureAvg[2] = ((pressureSamples[2][0] + pressureSamples[2][1]
|
||||
+ pressureSamples[2][2] + pressureSamples[2][3]
|
||||
+ pressureSamples[2][4] + pressureSamples[2][5]) / 6);
|
||||
float change = (pressureAvg[2] - pressureAvg[0]);
|
||||
{
|
||||
dP_dt = change / 1.5; // divide by 1.5 as this is the difference in time from 0 value.
|
||||
}
|
||||
}
|
||||
else if (minuteCount == 65)
|
||||
{
|
||||
float lastPressureAvg = getLastPressureSamplesAverage();
|
||||
float change = (lastPressureAvg - pressureAvg) * CONVERSION_FACTOR;
|
||||
if (firstRound) //first time initial 3 hour
|
||||
dP_dt = ((65.0 / 1023.0) * change); //note this is for t = 1 hour
|
||||
{
|
||||
dP_dt = change; //note this is for t = 1 hour
|
||||
}
|
||||
else
|
||||
dP_dt = (((65.0 / 1023.0) * change) / 2); //divide by 2 as this is the difference in time from 0 value
|
||||
} else if (minuteCount == 95) {
|
||||
// Avg pressure at end of the hour, value averaged from 0 to 5 min.
|
||||
pressureAvg[3] = ((pressureSamples[3][0] + pressureSamples[3][1]
|
||||
+ pressureSamples[3][2] + pressureSamples[3][3]
|
||||
+ pressureSamples[3][4] + pressureSamples[3][5]) / 6);
|
||||
float change = (pressureAvg[3] - pressureAvg[0]);
|
||||
{
|
||||
dP_dt = change / 2; //divide by 2 as this is the difference in time from 0 value
|
||||
}
|
||||
}
|
||||
else if (minuteCount == 95)
|
||||
{
|
||||
float lastPressureAvg = getLastPressureSamplesAverage();
|
||||
float change = (lastPressureAvg - pressureAvg) * CONVERSION_FACTOR;
|
||||
if (firstRound) // first time initial 3 hour
|
||||
dP_dt = (((65.0 / 1023.0) * change) / 1.5); // note this is for t = 1.5 hour
|
||||
{
|
||||
dP_dt = change / 1.5; // note this is for t = 1.5 hour
|
||||
}
|
||||
else
|
||||
dP_dt = (((65.0 / 1023.0) * change) / 2.5); // divide by 2.5 as this is the difference in time from 0 value
|
||||
} else if (minuteCount == 120) {
|
||||
// Avg pressure at end of the hour, value averaged from 0 to 5 min.
|
||||
pressureAvg[4] = ((pressureSamples[4][0] + pressureSamples[4][1]
|
||||
+ pressureSamples[4][2] + pressureSamples[4][3]
|
||||
+ pressureSamples[4][4] + pressureSamples[4][5]) / 6);
|
||||
float change = (pressureAvg[4] - pressureAvg[0]);
|
||||
{
|
||||
dP_dt = change / 2.5; // divide by 2.5 as this is the difference in time from 0 value
|
||||
}
|
||||
}
|
||||
else if (minuteCount == 125)
|
||||
{
|
||||
float lastPressureAvg = getLastPressureSamplesAverage();
|
||||
pressureAvg2 = lastPressureAvg; // store for later use.
|
||||
float change = (lastPressureAvg - pressureAvg) * CONVERSION_FACTOR;
|
||||
if (firstRound) // first time initial 3 hour
|
||||
dP_dt = (((65.0 / 1023.0) * change) / 2); // note this is for t = 2 hour
|
||||
{
|
||||
dP_dt = change / 2; // note this is for t = 2 hour
|
||||
}
|
||||
else
|
||||
dP_dt = (((65.0 / 1023.0) * change) / 3); // divide by 3 as this is the difference in time from 0 value
|
||||
} else if (minuteCount == 155) {
|
||||
// Avg pressure at end of the hour, value averaged from 0 to 5 min.
|
||||
pressureAvg[5] = ((pressureSamples[5][0] + pressureSamples[5][1]
|
||||
+ pressureSamples[5][2] + pressureSamples[5][3]
|
||||
+ pressureSamples[5][4] + pressureSamples[5][5]) / 6);
|
||||
float change = (pressureAvg[5] - pressureAvg[0]);
|
||||
{
|
||||
dP_dt = change / 3; // divide by 3 as this is the difference in time from 0 value
|
||||
}
|
||||
}
|
||||
else if (minuteCount == 155)
|
||||
{
|
||||
float lastPressureAvg = getLastPressureSamplesAverage();
|
||||
float change = (lastPressureAvg - pressureAvg) * CONVERSION_FACTOR;
|
||||
if (firstRound) // first time initial 3 hour
|
||||
dP_dt = (((65.0 / 1023.0) * change) / 2.5); // note this is for t = 2.5 hour
|
||||
{
|
||||
dP_dt = change / 2.5; // note this is for t = 2.5 hour
|
||||
}
|
||||
else
|
||||
dP_dt = (((65.0 / 1023.0) * change) / 3.5); // divide by 3.5 as this is the difference in time from 0 value
|
||||
} else if (minuteCount == 180) {
|
||||
// Avg pressure at end of the hour, value averaged from 0 to 5 min.
|
||||
pressureAvg[6] = ((pressureSamples[6][0] + pressureSamples[6][1]
|
||||
+ pressureSamples[6][2] + pressureSamples[6][3]
|
||||
+ pressureSamples[6][4] + pressureSamples[6][5]) / 6);
|
||||
float change = (pressureAvg[6] - pressureAvg[0]);
|
||||
{
|
||||
dP_dt = change / 3.5; // divide by 3.5 as this is the difference in time from 0 value
|
||||
}
|
||||
}
|
||||
else if (minuteCount == 185)
|
||||
{
|
||||
float lastPressureAvg = getLastPressureSamplesAverage();
|
||||
float change = (lastPressureAvg - pressureAvg) * CONVERSION_FACTOR;
|
||||
if (firstRound) // first time initial 3 hour
|
||||
dP_dt = (((65.0 / 1023.0) * change) / 3); // note this is for t = 3 hour
|
||||
{
|
||||
dP_dt = change / 3; // note this is for t = 3 hour
|
||||
}
|
||||
else
|
||||
dP_dt = (((65.0 / 1023.0) * change) / 4); // divide by 4 as this is the difference in time from 0 value
|
||||
pressureAvg[0] = pressureAvg[5]; // Equating the pressure at 0 to the pressure at 2 hour after 3 hours have past.
|
||||
{
|
||||
dP_dt = change / 4; // divide by 4 as this is the difference in time from 0 value
|
||||
}
|
||||
pressureAvg = pressureAvg2; // Equating the pressure at 0 to the pressure at 2 hour after 3 hours have past.
|
||||
firstRound = false; // flag to let you know that this is on the past 3 hour mark. Initialized to 0 outside main loop.
|
||||
}
|
||||
|
||||
int forecast = UNKNOWN;
|
||||
if (minuteCount < 35 && firstRound) //if time is less than 35 min on the first 3 hour interval.
|
||||
return 5; // Unknown, more time needed
|
||||
{
|
||||
forecast = UNKNOWN;
|
||||
}
|
||||
else if (dP_dt < (-0.25))
|
||||
return 4; // Quickly falling LP, Thunderstorm, not stable
|
||||
{
|
||||
forecast = THUNDERSTORM;
|
||||
}
|
||||
else if (dP_dt > 0.25)
|
||||
return 3; // Quickly rising HP, not stable weather
|
||||
{
|
||||
forecast = UNSTABLE;
|
||||
}
|
||||
else if ((dP_dt > (-0.25)) && (dP_dt < (-0.05)))
|
||||
return 2; // Slowly falling Low Pressure System, stable rainy weather
|
||||
{
|
||||
forecast = CLOUDY;
|
||||
}
|
||||
else if ((dP_dt > 0.05) && (dP_dt < 0.25))
|
||||
return 1; // Slowly rising HP stable good weather
|
||||
else if ((dP_dt > (-0.05)) && (dP_dt < 0.05))
|
||||
return 0; // Stable weather
|
||||
{
|
||||
forecast = SUNNY;
|
||||
}
|
||||
else if ((dP_dt >(-0.05)) && (dP_dt < 0.05))
|
||||
{
|
||||
forecast = STABLE;
|
||||
}
|
||||
else
|
||||
return 5; // Unknown
|
||||
{
|
||||
forecast = UNKNOWN;
|
||||
}
|
||||
|
||||
// uncomment when debugging
|
||||
//Serial.print(F("Forecast at minute "));
|
||||
//Serial.print(minuteCount);
|
||||
//Serial.print(F(" dP/dt = "));
|
||||
//Serial.print(dP_dt);
|
||||
//Serial.print(F("kPa/h --> "));
|
||||
//Serial.println(weather[forecast]);
|
||||
|
||||
return forecast;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,594 @@
|
||||
/*
|
||||
Arduino Tipping Bucket Rain Gauge
|
||||
|
||||
April 26, 2015
|
||||
|
||||
Version 1.4.1 alpha
|
||||
|
||||
Arduino Tipping Bucket Rain Gauge
|
||||
|
||||
Utilizing a tipping bucket sensor, your Vera home automation controller and the MySensors.org
|
||||
gateway you can measure and sense local rain. This sketch will create two devices on your
|
||||
Vera controller. One will display your total precipitation for the last 5 days. The other,
|
||||
a sensor that changes state if there is recent rain (up to last 120 hours) above a threshold.
|
||||
Both these settings are user definable.
|
||||
|
||||
There is a build overview video here: https://youtu.be/1eMfKQaLROo
|
||||
|
||||
This sketch features the following:
|
||||
|
||||
* Allows you to set the rain threshold in mm
|
||||
* Allows you to determine the tripped indicator window up to 120 hours.
|
||||
* Displays the last 5 days of rain in Variable1 through Variable5
|
||||
of the Rain Sensor device
|
||||
* Configuration changes to Sensor device updated every hour
|
||||
* Should run on any Arduino
|
||||
* Will retain Tripped/Not Tripped status and data in a power interruption, saving small amount
|
||||
of data to EEPROM (Circular Buffer to maximize life of EEPROM)
|
||||
* LED status indicator
|
||||
* Optional Temp/Humidity (DHT-22 or DHT-11) and Light LUX (BH1750) sensors. To use, uncomment
|
||||
#define DHT_ON and/or #define LUX_ON
|
||||
* Optionally send total accumulation of each day's rainfall or send only individual days rainfall totals.
|
||||
Comment out #define USE_DAILY to display individual daily rainfall.
|
||||
|
||||
by @BulldogLowell and @PeteWill for free public use
|
||||
|
||||
*/
|
||||
#include <SPI.h>
|
||||
#include <MySensor.h>
|
||||
#include <math.h>
|
||||
#include <Time.h>
|
||||
|
||||
#define NODE_ID 24 //or AUTO to let controller assign
|
||||
#define SKETCH_NAME "Rain Gauge"
|
||||
#define SKETCH_VERSION "1.4.1a"
|
||||
|
||||
#define DWELL_TIME 125 // this allows for radio to come back to power after a transmission, ideally 0
|
||||
|
||||
//#define DEBUG_ON // comment out this line to disable serial debug
|
||||
#define DHT_ON // uncomment out this line to enable DHT sensor
|
||||
#define LUX_ON // uncomment out this line to enable BH1750 sensor
|
||||
//#define USE_DAILY // displays each time segment as an accumulation of prior periods inclusive. Comment out to display individual daily rainfall totals in the variables sent to your controller.
|
||||
|
||||
#define CALIBRATE_FACTOR 60 // amount of rain per rain bucket tip e.g. 5 is .05mm
|
||||
#define DHT_LUX_DELAY 300000 //Delay in milliseconds that the DHT and LUX sensors will wait before sending data
|
||||
|
||||
#define CHILD_ID_RAIN_LOG 3 // Keeps track of accumulated rainfall
|
||||
#define CHILD_ID_TRIPPED_INDICATOR 4 // Indicates Tripped when rain detected
|
||||
#define EEPROM_BUFFER_LOCATION 0 // location of the EEPROM circular buffer
|
||||
#define E_BUFFER_LENGTH 240
|
||||
#define RAIN_BUCKET_SIZE 120
|
||||
|
||||
#ifdef DEBUG_ON
|
||||
#define DEBUG_PRINT(x) Serial.print(x)
|
||||
#define DEBUG_PRINTLN(x) Serial.println(x)
|
||||
#define SERIAL_START(x) Serial.begin(x)
|
||||
#else
|
||||
#define DEBUG_PRINT(x)
|
||||
#define DEBUG_PRINTLN(x)
|
||||
#define SERIAL_START(x)
|
||||
#endif
|
||||
//
|
||||
MySensor gw;
|
||||
//
|
||||
MyMessage msgRainRate(CHILD_ID_RAIN_LOG, V_RAINRATE);
|
||||
MyMessage msgRain(CHILD_ID_RAIN_LOG, V_RAIN);
|
||||
//
|
||||
MyMessage msgRainVAR1(CHILD_ID_RAIN_LOG, V_VAR1);
|
||||
MyMessage msgRainVAR2(CHILD_ID_RAIN_LOG, V_VAR2);
|
||||
MyMessage msgRainVAR3(CHILD_ID_RAIN_LOG, V_VAR3);
|
||||
MyMessage msgRainVAR4(CHILD_ID_RAIN_LOG, V_VAR4);
|
||||
MyMessage msgRainVAR5(CHILD_ID_RAIN_LOG, V_VAR5);
|
||||
//
|
||||
MyMessage msgTripped(CHILD_ID_TRIPPED_INDICATOR, V_TRIPPED);
|
||||
MyMessage msgTrippedVar1(CHILD_ID_TRIPPED_INDICATOR, V_VAR1);
|
||||
MyMessage msgTrippedVar2(CHILD_ID_TRIPPED_INDICATOR, V_VAR2);
|
||||
//
|
||||
#ifdef DHT_ON
|
||||
#include <DHT.h>
|
||||
#define CHILD_ID_HUM 0
|
||||
#define CHILD_ID_TEMP 1
|
||||
#define HUMIDITY_SENSOR_DIGITAL_PIN 8
|
||||
DHT dht;
|
||||
float lastTemp;
|
||||
float lastHum;
|
||||
boolean metric = true;
|
||||
MyMessage msgHum(CHILD_ID_HUM, V_HUM);
|
||||
MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
|
||||
#endif
|
||||
//
|
||||
#ifdef LUX_ON
|
||||
//BH1750 is connected to SCL (analog input A5) and SDA (analog input A4)
|
||||
#include <BH1750.h>
|
||||
#include <Wire.h>
|
||||
#define CHILD_ID_LIGHT 2
|
||||
BH1750 lightSensor;
|
||||
MyMessage msg(CHILD_ID_LIGHT, V_LIGHT_LEVEL);
|
||||
unsigned int lastlux;
|
||||
byte heartbeat = 10; //Used to send the light lux to gateway as soon as the device is restarted and after the DHT_LUX_DELAY has happened 10 times
|
||||
#endif
|
||||
unsigned long sensorPreviousMillis;
|
||||
int eepromIndex;
|
||||
int tipSensorPin = 3; // Pin the tipping bucket is connected to. Must be interrupt capable pin
|
||||
int ledPin = 5; // Pin the LED is connected to. PWM capable pin required
|
||||
unsigned long dataMillis;
|
||||
unsigned long serialInterval = 600000UL;
|
||||
const unsigned long oneHour = 3600000UL;
|
||||
unsigned long lastTipTime;
|
||||
unsigned long lastRainTime; //Used for rainRate calculation
|
||||
unsigned int rainBucket [RAIN_BUCKET_SIZE] ; /* 24 hours x 5 Days = 120 hours */
|
||||
unsigned int rainRate = 0;
|
||||
byte rainWindow = 72; //default rain window in hours. Will be overwritten with msgTrippedVar1.
|
||||
volatile int wasTippedBuffer = 0;
|
||||
int rainSensorThreshold = 50; //default rain sensor sensitivity in hundredths. Will be overwritten with msgTrippedVar2.
|
||||
byte state = 0;
|
||||
byte oldState = -1;
|
||||
int lastRainRate = 0;
|
||||
int lastMeasure = 0;
|
||||
boolean gotTime = false;
|
||||
byte lastHour;
|
||||
byte currentHour;
|
||||
//
|
||||
void setup()
|
||||
{
|
||||
SERIAL_START(115200);
|
||||
//
|
||||
// Set up the IO
|
||||
pinMode(tipSensorPin, INPUT_PULLUP);
|
||||
attachInterrupt (1, sensorTipped, FALLING); // depending on location of the hall effect sensor may need CHANGE
|
||||
pinMode(ledPin, OUTPUT);
|
||||
digitalWrite(ledPin, HIGH);
|
||||
//
|
||||
//Let's get the controller talking to the Arduino
|
||||
gw.begin(getVariables, NODE_ID);
|
||||
gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION);
|
||||
gw.wait(DWELL_TIME);
|
||||
gw.present(CHILD_ID_RAIN_LOG, S_RAIN);
|
||||
gw.wait(DWELL_TIME);
|
||||
gw.present(CHILD_ID_TRIPPED_INDICATOR, S_MOTION);
|
||||
gw.wait(DWELL_TIME);
|
||||
DEBUG_PRINTLN(F("Sensor Presentation Complete"));
|
||||
//
|
||||
//Sync time with the server, this will be called hourly in order to keep time from creeping with the crystal
|
||||
//
|
||||
unsigned long functionTimeout = millis();
|
||||
while (timeStatus() == timeNotSet && millis() - functionTimeout < 30000UL)
|
||||
{
|
||||
gw.process();
|
||||
gw.requestTime(receiveTime);
|
||||
DEBUG_PRINTLN(F("Getting Time"));
|
||||
gw.wait(1000); // call once per second
|
||||
DEBUG_PRINTLN(F("."));
|
||||
}
|
||||
currentHour = hour();
|
||||
lastHour = hour();
|
||||
//
|
||||
//retrieve from EEPROM stored values on a power cycle.
|
||||
//
|
||||
boolean isDataOnEeprom = false;
|
||||
for (int i = 0; i < E_BUFFER_LENGTH; i++)
|
||||
{
|
||||
byte locator = gw.loadState(EEPROM_BUFFER_LOCATION + i);
|
||||
if (locator == 0xFE) // found the EEPROM circular buffer index
|
||||
{
|
||||
eepromIndex = EEPROM_BUFFER_LOCATION + i;
|
||||
DEBUG_PRINT(F("EEPROM Index "));
|
||||
DEBUG_PRINTLN(eepromIndex);
|
||||
//Now that we have the buffer index let's populate the rainBucket[] with data from eeprom
|
||||
loadRainArray(eepromIndex);
|
||||
isDataOnEeprom = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
//
|
||||
if (!isDataOnEeprom) // Added for the first time it is run on a new Arduino
|
||||
{
|
||||
DEBUG_PRINTLN(F("I didn't find valid EEPROM Index, so I'm writing one to location 0"));
|
||||
eepromIndex = EEPROM_BUFFER_LOCATION;
|
||||
gw.saveState(eepromIndex, 0xFE);
|
||||
gw.saveState(eepromIndex + 1, 0xFE);
|
||||
//then I will clear out any bad data
|
||||
for (int i = 2; i <= E_BUFFER_LENGTH; i++)
|
||||
{
|
||||
gw.saveState(i, 0x00);
|
||||
}
|
||||
}
|
||||
dataMillis = millis();
|
||||
lastTipTime = millis() - oneHour; //why is this -oneHour?? Doesn't millis() start at 0 when first powered on?
|
||||
//
|
||||
gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR1);
|
||||
gw.wait(DWELL_TIME);
|
||||
gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR2);
|
||||
gw.wait(DWELL_TIME);
|
||||
//
|
||||
#ifdef DHT_ON
|
||||
dht.setup(HUMIDITY_SENSOR_DIGITAL_PIN);
|
||||
// Register all sensors to gw (they will be created as child devices)
|
||||
gw.present(CHILD_ID_HUM, S_HUM);
|
||||
gw.wait(DWELL_TIME);
|
||||
gw.present(CHILD_ID_TEMP, S_TEMP);
|
||||
gw.wait(DWELL_TIME);
|
||||
metric = gw.getConfig().isMetric;
|
||||
gw.wait(DWELL_TIME);
|
||||
#endif
|
||||
//
|
||||
#ifdef LUX_ON
|
||||
gw.present(CHILD_ID_LIGHT, S_LIGHT_LEVEL);
|
||||
gw.wait(DWELL_TIME);
|
||||
lightSensor.begin();
|
||||
#endif
|
||||
//
|
||||
DEBUG_PRINTLN(F("Radio Setup Complete!"));
|
||||
transmitRainData();
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
gw.process();
|
||||
if (state)
|
||||
{
|
||||
prettyFade(); // breathe if tripped
|
||||
}
|
||||
else
|
||||
{
|
||||
slowFlash(); // blink if not tripped
|
||||
}
|
||||
#ifdef DEBUG_ON // Serial Debug Block
|
||||
if ( (millis() - dataMillis) >= serialInterval)
|
||||
{
|
||||
for (int i = 24; i <= 120; i = i + 24)
|
||||
{
|
||||
updateSerialData(i);
|
||||
}
|
||||
dataMillis = millis();
|
||||
}
|
||||
#endif
|
||||
//
|
||||
// let's constantly check to see if the rain in the past rainWindow hours is greater than rainSensorThreshold
|
||||
//
|
||||
int measure = 0; // Check to see if we need to show sensor tripped in this block
|
||||
for (int i = 0; i < rainWindow; i++)
|
||||
{
|
||||
measure += rainBucket [i];
|
||||
if (measure != lastMeasure)
|
||||
{
|
||||
// DEBUG_PRINT(F("measure value (total rainBucket within rainWindow): "));
|
||||
// DEBUG_PRINTLN(measure);
|
||||
lastMeasure = measure;
|
||||
}
|
||||
}
|
||||
//
|
||||
state = (measure >= (rainSensorThreshold * 100));
|
||||
if (state != oldState)
|
||||
{
|
||||
gw.send(msgTripped.set(state));
|
||||
gw.wait(DWELL_TIME);
|
||||
DEBUG_PRINT(F("New Sensor State... Sensor: "));
|
||||
DEBUG_PRINTLN(state ? "Tripped" : "Not Tripped");
|
||||
oldState = state;
|
||||
}
|
||||
//
|
||||
unsigned long tipDelay = millis() - lastRainTime;
|
||||
if (wasTippedBuffer) // if was tipped, then update the 24hour total and transmit to Vera
|
||||
{
|
||||
DEBUG_PRINTLN(F("Sensor Tipped"));
|
||||
DEBUG_PRINT(F("rainBucket [0] value: "));
|
||||
DEBUG_PRINTLN(rainBucket [0]);
|
||||
gw.send(msgRain.set((float)rainTotal(currentHour) / 100, 1)); //Calculate the total rain for the day
|
||||
gw.wait(DWELL_TIME);
|
||||
wasTippedBuffer--;
|
||||
rainRate = ((oneHour) / tipDelay);
|
||||
if (rainRate != lastRainRate)
|
||||
{
|
||||
gw.send(msgRainRate.set(rainRate, 1));
|
||||
gw.wait(DWELL_TIME);
|
||||
DEBUG_PRINT(F("RainRate= "));
|
||||
DEBUG_PRINTLN(rainRate);
|
||||
lastRainRate = rainRate;
|
||||
}
|
||||
lastRainTime = lastTipTime;
|
||||
}
|
||||
//
|
||||
currentHour = hour();
|
||||
if (currentHour != lastHour)
|
||||
{
|
||||
DEBUG_PRINTLN(F("One hour elapsed."));
|
||||
gw.send(msgRain.set((float)rainTotal(currentHour) / 100, 1)); // send today's rainfall
|
||||
gw.wait(DWELL_TIME);
|
||||
gw.saveState(eepromIndex, highByte(rainBucket[0]));
|
||||
gw.saveState(eepromIndex + 1, lowByte(rainBucket[0]));
|
||||
DEBUG_PRINT(F("Saving rainBucket[0] to eeprom. rainBucket[0] = "));
|
||||
DEBUG_PRINTLN(rainBucket[0]);
|
||||
for (int i = RAIN_BUCKET_SIZE - 1; i >= 0; i--)//cascade an hour of values back into the array
|
||||
{
|
||||
rainBucket [i + 1] = rainBucket [i];
|
||||
}
|
||||
gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR1);
|
||||
gw.wait(DWELL_TIME);
|
||||
gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR2);
|
||||
gw.wait(DWELL_TIME);
|
||||
rainBucket[0] = 0;
|
||||
eepromIndex = eepromIndex + 2;
|
||||
if (eepromIndex > EEPROM_BUFFER_LOCATION + E_BUFFER_LENGTH)
|
||||
{
|
||||
eepromIndex = EEPROM_BUFFER_LOCATION;
|
||||
}
|
||||
DEBUG_PRINT(F("Writing to EEPROM. Index: "));
|
||||
DEBUG_PRINTLN(eepromIndex);
|
||||
gw.saveState(eepromIndex, 0xFE);
|
||||
gw.saveState(eepromIndex + 1, 0xFE);
|
||||
gw.requestTime(receiveTime); // sync the time every hour
|
||||
gw.wait(DWELL_TIME);
|
||||
transmitRainData();
|
||||
rainRate = 0;
|
||||
gw.send(msgRainRate.set(rainRate, 1));
|
||||
gw.wait(DWELL_TIME);
|
||||
DEBUG_PRINTLN(F("Sending rainRate is 0 to controller"));
|
||||
lastHour = currentHour;
|
||||
}
|
||||
if (millis() - sensorPreviousMillis > DHT_LUX_DELAY)
|
||||
{
|
||||
#ifdef DHT_ON //DHT Code
|
||||
doDHT();
|
||||
#endif
|
||||
#ifdef LUX_ON
|
||||
doLUX();
|
||||
#endif
|
||||
sensorPreviousMillis = millis();
|
||||
}
|
||||
}
|
||||
//
|
||||
#ifdef DHT_ON
|
||||
void doDHT(void)
|
||||
{
|
||||
float temperature = dht.getTemperature();
|
||||
if (isnan(temperature))
|
||||
{
|
||||
DEBUG_PRINTLN(F("Failed reading temperature from DHT"));
|
||||
} else if (temperature != lastTemp)
|
||||
{
|
||||
lastTemp = temperature;
|
||||
if (!metric)
|
||||
{
|
||||
temperature = dht.toFahrenheit(temperature);
|
||||
}
|
||||
gw.send(msgTemp.set(temperature, 1));
|
||||
gw.wait(DWELL_TIME);
|
||||
DEBUG_PRINT(F("Temperature is: "));
|
||||
DEBUG_PRINTLN(temperature);
|
||||
}
|
||||
float humidity = dht.getHumidity();;
|
||||
if (isnan(humidity))
|
||||
{
|
||||
DEBUG_PRINTLN(F("Failed reading humidity from DHT"));
|
||||
} else if (humidity != lastHum)
|
||||
{
|
||||
lastHum = humidity;
|
||||
gw.send(msgHum.set(humidity, 1));
|
||||
gw.wait(DWELL_TIME);
|
||||
DEBUG_PRINT(F("Humidity is: "));
|
||||
DEBUG_PRINTLN(humidity);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
//
|
||||
#ifdef LUX_ON
|
||||
void doLUX(void)
|
||||
{
|
||||
unsigned int lux = lightSensor.readLightLevel();// Get Lux value
|
||||
DEBUG_PRINT(F("Current LUX Level: "));
|
||||
DEBUG_PRINTLN(lux);
|
||||
heartbeat++;
|
||||
if (lux != lastlux || heartbeat > 10)
|
||||
{
|
||||
gw.send(msg.set(lux));
|
||||
lastlux = lux;
|
||||
}
|
||||
if (heartbeat > 10)
|
||||
{
|
||||
heartbeat = 0;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
//
|
||||
void sensorTipped()
|
||||
{
|
||||
unsigned long thisTipTime = millis();
|
||||
if (thisTipTime - lastTipTime > 100UL)
|
||||
{
|
||||
rainBucket[0] += CALIBRATE_FACTOR; // adds CALIBRATE_FACTOR hundredths of unit each tip
|
||||
wasTippedBuffer++;
|
||||
}
|
||||
lastTipTime = thisTipTime;
|
||||
}
|
||||
//
|
||||
int rainTotal(int hours)
|
||||
{
|
||||
int total = 0;
|
||||
for ( int i = 0; i <= hours; i++)
|
||||
{
|
||||
total += rainBucket [i];
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
void updateSerialData(int x)
|
||||
{
|
||||
DEBUG_PRINT(F("Rain last "));
|
||||
DEBUG_PRINT(x);
|
||||
DEBUG_PRINTLN(F(" hours: "));
|
||||
float tipCount = 0;
|
||||
for (int i = 0; i < x; i++)
|
||||
{
|
||||
tipCount = tipCount + rainBucket [i];
|
||||
}
|
||||
tipCount = tipCount / 100;
|
||||
DEBUG_PRINTLN(tipCount);
|
||||
}
|
||||
|
||||
void loadRainArray(int value) // retrieve stored rain array from EEPROM on powerup
|
||||
{
|
||||
for (int i = 0; i < RAIN_BUCKET_SIZE; i++)
|
||||
{
|
||||
value = value - 2;
|
||||
if (value < EEPROM_BUFFER_LOCATION)
|
||||
{
|
||||
value = EEPROM_BUFFER_LOCATION + E_BUFFER_LENGTH;
|
||||
}
|
||||
DEBUG_PRINT(F("EEPROM location: "));
|
||||
DEBUG_PRINTLN(value);
|
||||
byte rainValueHigh = gw.loadState(value);
|
||||
byte rainValueLow = gw.loadState(value + 1);
|
||||
unsigned int rainValue = rainValueHigh << 8;
|
||||
rainValue |= rainValueLow;
|
||||
rainBucket[i + 1] = rainValue;
|
||||
//
|
||||
DEBUG_PRINT(F("rainBucket[ value: "));
|
||||
DEBUG_PRINT(i + 1);
|
||||
DEBUG_PRINT(F("] value: "));
|
||||
DEBUG_PRINTLN(rainBucket[i + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
void transmitRainData(void)
|
||||
{
|
||||
DEBUG_PRINT(F("In transmitRainData. currentHour = "));
|
||||
DEBUG_PRINTLN(currentHour);
|
||||
int rainUpdateTotal = 0;
|
||||
for (int i = currentHour; i >= 0; i--)
|
||||
{
|
||||
rainUpdateTotal += rainBucket[i];
|
||||
DEBUG_PRINT(F("Adding rainBucket["));
|
||||
DEBUG_PRINT(i);
|
||||
DEBUG_PRINTLN(F("] to rainUpdateTotal."));
|
||||
}
|
||||
DEBUG_PRINT(F("TX Day 1: rainUpdateTotal = "));
|
||||
DEBUG_PRINTLN((float)rainUpdateTotal / 100.0);
|
||||
gw.send(msgRainVAR1.set((float)rainUpdateTotal / 100.0, 1)); //Send current day rain totals (resets at midnight)
|
||||
gw.wait(DWELL_TIME);
|
||||
#ifdef USE_DAILY
|
||||
rainUpdateTotal = 0;
|
||||
#endif
|
||||
for (int i = currentHour + 24; i > currentHour; i--)
|
||||
{
|
||||
rainUpdateTotal += rainBucket[i];
|
||||
DEBUG_PRINT(F("Adding rainBucket["));
|
||||
DEBUG_PRINT(i);
|
||||
DEBUG_PRINTLN(F("] to rainUpdateTotal."));
|
||||
}
|
||||
DEBUG_PRINT(F("TX Day 2: rainUpdateTotal = "));
|
||||
DEBUG_PRINTLN((float)rainUpdateTotal / 100.0);
|
||||
gw.send(msgRainVAR2.set((float)rainUpdateTotal / 100.0, 1));
|
||||
gw.wait(DWELL_TIME);
|
||||
#ifdef USE_DAILY
|
||||
rainUpdateTotal = 0;
|
||||
#endif
|
||||
for (int i = currentHour + 48; i > currentHour + 24; i--)
|
||||
{
|
||||
rainUpdateTotal += rainBucket[i];
|
||||
DEBUG_PRINT(F("Adding rainBucket["));
|
||||
DEBUG_PRINT(i);
|
||||
DEBUG_PRINTLN(F("] to rainUpdateTotal."));
|
||||
}
|
||||
DEBUG_PRINT(F("TX Day 3: rainUpdateTotal = "));
|
||||
DEBUG_PRINTLN((float)rainUpdateTotal / 100.0);
|
||||
gw.send(msgRainVAR3.set((float)rainUpdateTotal / 100.0, 1));
|
||||
gw.wait(DWELL_TIME);
|
||||
#ifdef USE_DAILY
|
||||
rainUpdateTotal = 0;
|
||||
#endif
|
||||
for (int i = currentHour + 72; i > currentHour + 48; i--)
|
||||
{
|
||||
rainUpdateTotal += rainBucket[i];
|
||||
DEBUG_PRINT(F("Adding rainBucket["));
|
||||
DEBUG_PRINT(i);
|
||||
DEBUG_PRINTLN(F("] to rainUpdateTotal."));
|
||||
}
|
||||
DEBUG_PRINT(F("TX Day 4: rainUpdateTotal = "));
|
||||
DEBUG_PRINTLN((float)rainUpdateTotal / 100.0);
|
||||
gw.send(msgRainVAR4.set((float)rainUpdateTotal / 100.0, 1));
|
||||
gw.wait(DWELL_TIME);
|
||||
#ifdef USE_DAILY
|
||||
rainUpdateTotal = 0;
|
||||
#endif
|
||||
for (int i = currentHour + 96; i > currentHour + 72; i--)
|
||||
{
|
||||
rainUpdateTotal += rainBucket[i];
|
||||
DEBUG_PRINT(F("Adding rainBucket["));
|
||||
DEBUG_PRINT(i);
|
||||
DEBUG_PRINTLN(F("] to rainUpdateTotal."));
|
||||
}
|
||||
DEBUG_PRINT(F("TX Day 5: rainUpdateTotal = "));
|
||||
DEBUG_PRINTLN((float)rainUpdateTotal / 100.0);
|
||||
gw.send(msgRainVAR5.set((float)rainUpdateTotal / 100.0, 1));
|
||||
gw.wait(DWELL_TIME);
|
||||
}
|
||||
|
||||
void getVariables(const MyMessage &message)
|
||||
{
|
||||
if (message.sensor == CHILD_ID_RAIN_LOG)
|
||||
{
|
||||
// nothing to do here
|
||||
}
|
||||
else if (message.sensor == CHILD_ID_TRIPPED_INDICATOR)
|
||||
{
|
||||
if (message.type == V_VAR1)
|
||||
{
|
||||
rainWindow = atoi(message.data);
|
||||
if (rainWindow > 120)
|
||||
{
|
||||
rainWindow = 120;
|
||||
}
|
||||
else if (rainWindow < 1)
|
||||
{
|
||||
rainWindow = 1;
|
||||
}
|
||||
if (rainWindow != atoi(message.data)) // if I changed the value back inside the boundries, push that number back to Vera
|
||||
{
|
||||
gw.send(msgTrippedVar1.set(rainWindow));
|
||||
}
|
||||
}
|
||||
else if (message.type == V_VAR2)
|
||||
{
|
||||
rainSensorThreshold = atoi(message.data);
|
||||
if (rainSensorThreshold > 10000)
|
||||
{
|
||||
rainSensorThreshold = 10000;
|
||||
}
|
||||
else if (rainSensorThreshold < 1)
|
||||
{
|
||||
rainSensorThreshold = 1;
|
||||
}
|
||||
if (rainSensorThreshold != atoi(message.data)) // if I changed the value back inside the boundries, push that number back to Vera
|
||||
{
|
||||
gw.send(msgTrippedVar2.set(rainSensorThreshold));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void prettyFade(void)
|
||||
{
|
||||
float val = (exp(sin(millis() / 2000.0 * PI)) - 0.36787944) * 108.0;
|
||||
analogWrite(ledPin, val);
|
||||
}
|
||||
|
||||
void slowFlash(void)
|
||||
{
|
||||
static boolean ledState = true;
|
||||
static unsigned long pulseStart = millis();
|
||||
if (millis() - pulseStart < 100UL)
|
||||
{
|
||||
digitalWrite(ledPin, !ledState);
|
||||
pulseStart = millis();
|
||||
}
|
||||
}
|
||||
|
||||
void receiveTime(unsigned long time)
|
||||
{
|
||||
DEBUG_PRINTLN(F("Time received..."));
|
||||
setTime(time);
|
||||
char theTime[6];
|
||||
sprintf(theTime, "%d:%2d", hour(), minute());
|
||||
DEBUG_PRINTLN(theTime);
|
||||
}
|
||||
+162
-59
@@ -22,45 +22,67 @@
|
||||
* Version 1.0 - Thomas Bowman Mørch
|
||||
*
|
||||
* DESCRIPTION
|
||||
* Default sensor sketch for MySensor Sensebender Micro module
|
||||
* Default sensor sketch for Sensebender Micro module
|
||||
* Act as a temperature / humidity sensor by default.
|
||||
*
|
||||
* If A0 is held low while powering on, it will enter testmode, which verifies all on-board peripherals
|
||||
*
|
||||
* Battery voltage is repported as child sensorId 199, as well as battery percentage
|
||||
*
|
||||
* Battery voltage is as battery percentage (Internal message), and optionally as a sensor value (See defines below)
|
||||
*
|
||||
*
|
||||
* Version 1.3 - Thomas Bowman Mørch
|
||||
* Improved transmission logic, eliminating spurious transmissions (when temperatuere / humidity fluctuates 1 up and down between measurements)
|
||||
*
|
||||
* Added OTA boot mode, need to hold A1 low while applying power. (uses slightly more power as it's waiting for bootloader messages)
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
|
||||
#include <MySensor.h>
|
||||
#include <Wire.h>
|
||||
#include <SI7021.h>
|
||||
#include <SPI.h>
|
||||
#include <SPIFlash.h>
|
||||
#include "utility/SPIFlash.h"
|
||||
#include <EEPROM.h>
|
||||
#include <sha204_lib_return_codes.h>
|
||||
#include <sha204_library.h>
|
||||
#include <RunningAverage.h>
|
||||
//#include <avr/power.h>
|
||||
|
||||
// Define a static node address, remove if you want auto address assignment
|
||||
//#define NODE_ADDRESS 3
|
||||
|
||||
// Uncomment the line below, to transmit battery voltage as a normal sensor value
|
||||
//#define BATT_SENSOR 199
|
||||
|
||||
#define RELEASE "1.3"
|
||||
|
||||
#define AVERAGES 2
|
||||
|
||||
// Child sensor ID's
|
||||
#define CHILD_ID_TEMP 1
|
||||
#define CHILD_ID_HUM 2
|
||||
#define CHILD_ID_BATT 199
|
||||
|
||||
// How many milli seconds between each measurement
|
||||
#define MEASURE_INTERVAL 60000
|
||||
|
||||
// How many milli seconds should we wait for OTA?
|
||||
#define OTA_WAIT_PERIOD 300
|
||||
|
||||
// FORCE_TRANSMIT_INTERVAL, this number of times of wakeup, the sensor is forced to report all values to the controller
|
||||
#define FORCE_TRANSMIT_INTERVAL 30
|
||||
|
||||
// When MEASURE_INTERVAL is 60000 and FORCE_TRANSMIT_INTERVAL is 30, we force a transmission every 30 minutes.
|
||||
// Between the forced transmissions a tranmission will only occur if the measured value differs from the previous measurement
|
||||
|
||||
//Pin definitions
|
||||
// HUMI_TRANSMIT_THRESHOLD tells how much the humidity should have changed since last time it was transmitted. Likewise with
|
||||
// TEMP_TRANSMIT_THRESHOLD for temperature threshold.
|
||||
#define HUMI_TRANSMIT_THRESHOLD 0.5
|
||||
#define TEMP_TRANSMIT_THRESHOLD 0.5
|
||||
|
||||
// Pin definitions
|
||||
#define TEST_PIN A0
|
||||
#define OTA_ENABLE A1
|
||||
#define LED_PIN A2
|
||||
#define ATSHA204_PIN 17 // A3
|
||||
|
||||
@@ -75,120 +97,209 @@ MySensor gw;
|
||||
// Sensor messages
|
||||
MyMessage msgHum(CHILD_ID_HUM, V_HUM);
|
||||
MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
|
||||
MyMessage msgBattery(CHILD_ID_BATT, V_VOLTAGE);
|
||||
|
||||
#ifdef BATT_SENSOR
|
||||
MyMessage msgBatt(BATT_SENSOR, V_VOLTAGE);
|
||||
#endif
|
||||
|
||||
// Global settings
|
||||
int measureCount = 0;
|
||||
int sendBattery = 0;
|
||||
boolean isMetric = true;
|
||||
boolean highfreq = true;
|
||||
boolean ota_enabled = false;
|
||||
boolean transmission_occured = false;
|
||||
|
||||
// Storage of old measurements
|
||||
float lastTemperature = -100;
|
||||
int lastHumidity = -100;
|
||||
long lastBattery = -100;
|
||||
|
||||
RunningAverage raHum(AVERAGES);
|
||||
|
||||
/****************************************************
|
||||
*
|
||||
* Setup code
|
||||
*
|
||||
****************************************************/
|
||||
void setup() {
|
||||
|
||||
|
||||
pinMode(LED_PIN, OUTPUT);
|
||||
digitalWrite(LED_PIN, LOW);
|
||||
|
||||
Serial.begin(115200);
|
||||
Serial.print(F("Sensebender Micro FW "));
|
||||
Serial.print(RELEASE);
|
||||
Serial.flush();
|
||||
|
||||
// First check if we should boot into test mode
|
||||
|
||||
pinMode(TEST_PIN,INPUT);
|
||||
digitalWrite(TEST_PIN, HIGH); // Enable pullup
|
||||
if (!digitalRead(TEST_PIN)) testMode();
|
||||
|
||||
pinMode(OTA_ENABLE, INPUT);
|
||||
digitalWrite(OTA_ENABLE, HIGH);
|
||||
if (!digitalRead(OTA_ENABLE)) {
|
||||
ota_enabled = true;
|
||||
}
|
||||
|
||||
// Make sure that ATSHA204 is not floating
|
||||
pinMode(ATSHA204_PIN, INPUT);
|
||||
digitalWrite(ATSHA204_PIN, HIGH);
|
||||
|
||||
digitalWrite(TEST_PIN,LOW);
|
||||
digitalWrite(LED_PIN, HIGH);
|
||||
digitalWrite(OTA_ENABLE, LOW); // remove pullup, save some power.
|
||||
|
||||
digitalWrite(LED_PIN, HIGH);
|
||||
|
||||
#ifdef NODE_ADDRESS
|
||||
gw.begin(NULL, NODE_ADDRESS, false);
|
||||
#else
|
||||
gw.begin(NULL,AUTO,false);
|
||||
#endif
|
||||
|
||||
humiditySensor.begin();
|
||||
|
||||
digitalWrite(LED_PIN, LOW);
|
||||
|
||||
humiditySensor.begin();
|
||||
|
||||
gw.sendSketchInfo("MysensorMicro", "1.0");
|
||||
Serial.flush();
|
||||
Serial.println(F(" - Online!"));
|
||||
gw.sendSketchInfo("Sensebender Micro", RELEASE);
|
||||
|
||||
gw.present(CHILD_ID_TEMP,S_TEMP);
|
||||
gw.present(CHILD_ID_HUM,S_HUM);
|
||||
|
||||
gw.present(CHILD_ID_BATT, S_POWER);
|
||||
switchClock(1<<CLKPS2); // Switch to 1Mhz for the reminder of the sketch, save power.
|
||||
#ifdef BATT_SENSOR
|
||||
gw.present(BATT_SENSOR, S_POWER);
|
||||
#endif
|
||||
|
||||
|
||||
isMetric = gw.getConfig().isMetric;
|
||||
Serial.print(F("isMetric: ")); Serial.println(isMetric);
|
||||
raHum.clear();
|
||||
sendTempHumidityMeasurements(false);
|
||||
sendBattLevel(false);
|
||||
if (ota_enabled) Serial.println("OTA FW update enabled");
|
||||
|
||||
}
|
||||
|
||||
|
||||
// Main loop function
|
||||
/***********************************************
|
||||
*
|
||||
* Main loop function
|
||||
*
|
||||
***********************************************/
|
||||
void loop() {
|
||||
measureCount ++;
|
||||
bool forceTransmit = false;
|
||||
|
||||
if (measureCount > FORCE_TRANSMIT_INTERVAL
|
||||
) { // force a transmission
|
||||
measureCount ++;
|
||||
sendBattery ++;
|
||||
bool forceTransmit = false;
|
||||
transmission_occured = false;
|
||||
if ((measureCount == 5) && highfreq)
|
||||
{
|
||||
if (!ota_enabled) clock_prescale_set(clock_div_8); // Switch to 1Mhz for the reminder of the sketch, save power.
|
||||
highfreq = false;
|
||||
}
|
||||
|
||||
if (measureCount > FORCE_TRANSMIT_INTERVAL) { // force a transmission
|
||||
forceTransmit = true;
|
||||
measureCount = 0;
|
||||
}
|
||||
|
||||
|
||||
gw.process();
|
||||
sendBattLevel(forceTransmit);
|
||||
|
||||
sendTempHumidityMeasurements(forceTransmit);
|
||||
|
||||
if (sendBattery > 60)
|
||||
{
|
||||
sendBattLevel(forceTransmit); // Not needed to send battery info that often
|
||||
sendBattery = 0;
|
||||
}
|
||||
|
||||
if (ota_enabled & transmission_occured) {
|
||||
gw.wait(OTA_WAIT_PERIOD);
|
||||
}
|
||||
|
||||
gw.sleep(MEASURE_INTERVAL);
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
/*********************************************
|
||||
*
|
||||
* Sends temperature and humidity from Si7021 sensor
|
||||
*
|
||||
* Parameters
|
||||
* - force : Forces transmission of a value (even if it's the same as previous measurement)
|
||||
*/
|
||||
*
|
||||
*********************************************/
|
||||
void sendTempHumidityMeasurements(bool force)
|
||||
{
|
||||
if (force) {
|
||||
lastHumidity = -100;
|
||||
lastTemperature = -100;
|
||||
}
|
||||
|
||||
bool tx = force;
|
||||
|
||||
si7021_env data = humiditySensor.getHumidityAndTemperature();
|
||||
|
||||
float temperature = data.celsiusHundredths/100;
|
||||
|
||||
int humidity = data.humidityPercent;
|
||||
raHum.addValue(data.humidityPercent);
|
||||
|
||||
float diffTemp = abs(lastTemperature - (isMetric ? data.celsiusHundredths : data.fahrenheitHundredths)/100);
|
||||
float diffHum = abs(lastHumidity - raHum.getAverage());
|
||||
|
||||
if (lastTemperature != temperature) {
|
||||
Serial.print(F("TempDiff :"));Serial.println(diffTemp);
|
||||
Serial.print(F("HumDiff :"));Serial.println(diffHum);
|
||||
|
||||
if (isnan(diffHum)) tx = true;
|
||||
if (diffTemp > TEMP_TRANSMIT_THRESHOLD) tx = true;
|
||||
if (diffHum > HUMI_TRANSMIT_THRESHOLD) tx = true;
|
||||
|
||||
if (tx) {
|
||||
measureCount = 0;
|
||||
float temperature = (isMetric ? data.celsiusHundredths : data.fahrenheitHundredths) / 100.0;
|
||||
|
||||
int humidity = data.humidityPercent;
|
||||
Serial.print("T: ");Serial.println(temperature);
|
||||
Serial.print("H: ");Serial.println(humidity);
|
||||
|
||||
gw.send(msgTemp.set(temperature,1));
|
||||
lastTemperature = temperature;
|
||||
}
|
||||
if (lastHumidity != humidity) {
|
||||
gw.send(msgHum.set(humidity));
|
||||
lastTemperature = temperature;
|
||||
lastHumidity = humidity;
|
||||
transmission_occured = true;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Sends battery information (both voltage, and battery percentage)
|
||||
/********************************************
|
||||
*
|
||||
* Sends battery information (battery percentage)
|
||||
*
|
||||
* Parameters
|
||||
* - force : Forces transmission of a value
|
||||
*/
|
||||
*
|
||||
*******************************************/
|
||||
void sendBattLevel(bool force)
|
||||
{
|
||||
if (force) lastBattery = -1;
|
||||
long vcc = readVcc();
|
||||
if (vcc != lastBattery) {
|
||||
lastBattery = vcc;
|
||||
|
||||
#ifdef BATT_SENSOR
|
||||
gw.send(msgBatt.set(vcc));
|
||||
#endif
|
||||
|
||||
// Calculate percentage
|
||||
gw.send(msgBattery.set(vcc));
|
||||
|
||||
vcc = vcc - 1900; // subtract 1.9V from vcc, as this is the lowest voltage we will operate at
|
||||
|
||||
long percent = vcc / 14;
|
||||
long percent = vcc / 14.0;
|
||||
gw.sendBatteryLevel(percent);
|
||||
transmission_occured = true;
|
||||
}
|
||||
}
|
||||
|
||||
/*******************************************
|
||||
*
|
||||
* Internal battery ADC measuring
|
||||
*
|
||||
*******************************************/
|
||||
long readVcc() {
|
||||
// Read 1.1V reference against AVcc
|
||||
// set the reference to Vcc and the measurement to the internal 1.1V reference
|
||||
@@ -213,19 +324,14 @@ long readVcc() {
|
||||
|
||||
result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
|
||||
return result; // Vcc in millivolts
|
||||
|
||||
}
|
||||
|
||||
void switchClock(unsigned char clk)
|
||||
{
|
||||
cli();
|
||||
|
||||
CLKPR = 1<<CLKPCE; // Set CLKPCE to enable clk switching
|
||||
CLKPR = clk;
|
||||
sei();
|
||||
}
|
||||
|
||||
|
||||
// Verify all peripherals, and signal via the LED if any problems.
|
||||
/****************************************************
|
||||
*
|
||||
* Verify all peripherals, and signal via the LED if any problems.
|
||||
*
|
||||
****************************************************/
|
||||
void testMode()
|
||||
{
|
||||
uint8_t rx_buffer[SHA204_RSP_SIZE_MAX];
|
||||
@@ -233,7 +339,7 @@ void testMode()
|
||||
byte tests = 0;
|
||||
|
||||
digitalWrite(LED_PIN, HIGH); // Turn on LED.
|
||||
|
||||
Serial.println(F(" - TestMode"));
|
||||
Serial.println(F("Testing peripherals!"));
|
||||
Serial.flush();
|
||||
Serial.print(F("-> SI7021 : "));
|
||||
@@ -305,7 +411,7 @@ void testMode()
|
||||
while (1) // Blink OK pattern!
|
||||
{
|
||||
digitalWrite(LED_PIN, HIGH);
|
||||
delay(800);
|
||||
delay(200);
|
||||
digitalWrite(LED_PIN, LOW);
|
||||
delay(200);
|
||||
}
|
||||
@@ -315,10 +421,7 @@ void testMode()
|
||||
Serial.println(F("----> Selftest failed!"));
|
||||
while (1) // Blink FAILED pattern! Rappidly blinking..
|
||||
{
|
||||
digitalWrite(LED_PIN, HIGH);
|
||||
delay(100);
|
||||
digitalWrite(LED_PIN, LOW);
|
||||
delay(100);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// Feed this function the Arduino-ized pin number you want to assign to the ATSHA204's SDA pin
|
||||
// This will find the DDRX, PORTX, and PINX registrs it'll need to point to to control that pin
|
||||
// As well as the bit value for each of those registers
|
||||
atsha204Class::atsha204Class(uint8_t pin)
|
||||
ATSHA204Class::ATSHA204Class(uint8_t pin)
|
||||
{
|
||||
device_pin = digitalPinToBitMask(pin); // Find the bit value of the pin
|
||||
uint8_t port = digitalPinToPort(pin); // temoporarily used to get the next three registers
|
||||
@@ -18,7 +18,7 @@ atsha204Class::atsha204Class(uint8_t pin)
|
||||
device_port_IN = portInputRegister(port);
|
||||
}
|
||||
|
||||
void atsha204Class::getSerialNumber(uint8_t * response)
|
||||
void ATSHA204Class::getSerialNumber(uint8_t * response)
|
||||
{
|
||||
uint8_t readCommand[READ_COUNT];
|
||||
uint8_t readResponse[READ_4_RSP_SIZE];
|
||||
@@ -48,7 +48,7 @@ void atsha204Class::getSerialNumber(uint8_t * response)
|
||||
|
||||
/* SWI bit bang functions */
|
||||
|
||||
void atsha204Class::swi_set_signal_pin(uint8_t is_high)
|
||||
void ATSHA204Class::swi_set_signal_pin(uint8_t is_high)
|
||||
{
|
||||
*device_port_DDR |= device_pin;
|
||||
|
||||
@@ -58,7 +58,7 @@ void atsha204Class::swi_set_signal_pin(uint8_t is_high)
|
||||
*device_port_OUT &= ~device_pin;
|
||||
}
|
||||
|
||||
uint8_t atsha204Class::swi_send_bytes(uint8_t count, uint8_t *buffer)
|
||||
uint8_t ATSHA204Class::swi_send_bytes(uint8_t count, uint8_t *buffer)
|
||||
{
|
||||
uint8_t i, bit_mask;
|
||||
|
||||
@@ -101,12 +101,12 @@ uint8_t atsha204Class::swi_send_bytes(uint8_t count, uint8_t *buffer)
|
||||
return SWI_FUNCTION_RETCODE_SUCCESS;
|
||||
}
|
||||
|
||||
uint8_t atsha204Class::swi_send_byte(uint8_t value)
|
||||
uint8_t ATSHA204Class::swi_send_byte(uint8_t value)
|
||||
{
|
||||
return swi_send_bytes(1, &value);
|
||||
}
|
||||
|
||||
uint8_t atsha204Class::swi_receive_bytes(uint8_t count, uint8_t *buffer)
|
||||
uint8_t ATSHA204Class::swi_receive_bytes(uint8_t count, uint8_t *buffer)
|
||||
{
|
||||
uint8_t status = SWI_FUNCTION_RETCODE_SUCCESS;
|
||||
uint8_t i;
|
||||
@@ -212,12 +212,12 @@ uint8_t atsha204Class::swi_receive_bytes(uint8_t count, uint8_t *buffer)
|
||||
|
||||
/* Physical functions */
|
||||
|
||||
void atsha204Class::sha204c_sleep()
|
||||
void ATSHA204Class::sha204c_sleep()
|
||||
{
|
||||
swi_send_byte(SHA204_SWI_FLAG_SLEEP);
|
||||
}
|
||||
|
||||
uint8_t atsha204Class::sha204p_receive_response(uint8_t size, uint8_t *response)
|
||||
uint8_t ATSHA204Class::sha204p_receive_response(uint8_t size, uint8_t *response)
|
||||
{
|
||||
uint8_t count_byte;
|
||||
uint8_t i;
|
||||
@@ -249,7 +249,7 @@ uint8_t atsha204Class::sha204p_receive_response(uint8_t size, uint8_t *response)
|
||||
|
||||
/* Communication functions */
|
||||
|
||||
uint8_t atsha204Class::sha204c_wakeup(uint8_t *response)
|
||||
uint8_t ATSHA204Class::sha204c_wakeup(uint8_t *response)
|
||||
{
|
||||
swi_set_signal_pin(0);
|
||||
delayMicroseconds(10*SHA204_WAKEUP_PULSE_WIDTH);
|
||||
@@ -277,7 +277,7 @@ uint8_t atsha204Class::sha204c_wakeup(uint8_t *response)
|
||||
return ret_code;
|
||||
}
|
||||
|
||||
uint8_t atsha204Class::sha204c_resync(uint8_t size, uint8_t *response)
|
||||
uint8_t ATSHA204Class::sha204c_resync(uint8_t size, uint8_t *response)
|
||||
{
|
||||
// Try to re-synchronize without sending a Wake token
|
||||
// (step 1 of the re-synchronization process).
|
||||
@@ -298,7 +298,7 @@ uint8_t atsha204Class::sha204c_resync(uint8_t size, uint8_t *response)
|
||||
return (ret_code == SHA204_SUCCESS ? SHA204_RESYNC_WITH_WAKEUP : ret_code);
|
||||
}
|
||||
|
||||
uint8_t atsha204Class::sha204c_send_and_receive(uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer, uint8_t execution_delay, uint8_t execution_timeout)
|
||||
uint8_t ATSHA204Class::sha204c_send_and_receive(uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer, uint8_t execution_delay, uint8_t execution_timeout)
|
||||
{
|
||||
uint8_t ret_code = SHA204_FUNC_FAIL;
|
||||
uint8_t ret_code_resync;
|
||||
@@ -440,7 +440,7 @@ uint8_t atsha204Class::sha204c_send_and_receive(uint8_t *tx_buffer, uint8_t rx_s
|
||||
|
||||
|
||||
/* Marshaling functions */
|
||||
uint8_t atsha204Class::sha204m_read(uint8_t *tx_buffer, uint8_t *rx_buffer, uint8_t zone, uint16_t address)
|
||||
uint8_t ATSHA204Class::sha204m_read(uint8_t *tx_buffer, uint8_t *rx_buffer, uint8_t zone, uint16_t address)
|
||||
{
|
||||
uint8_t rx_size;
|
||||
|
||||
@@ -457,7 +457,7 @@ uint8_t atsha204Class::sha204m_read(uint8_t *tx_buffer, uint8_t *rx_buffer, uint
|
||||
return sha204c_send_and_receive(&tx_buffer[0], rx_size, &rx_buffer[0], READ_DELAY, READ_EXEC_MAX - READ_DELAY);
|
||||
}
|
||||
|
||||
uint8_t atsha204Class::sha204m_execute(uint8_t op_code, uint8_t param1, uint16_t param2,
|
||||
uint8_t ATSHA204Class::sha204m_execute(uint8_t op_code, uint8_t param1, uint16_t param2,
|
||||
uint8_t datalen1, uint8_t *data1, uint8_t tx_size, uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer)
|
||||
{
|
||||
uint8_t poll_delay, poll_timeout, response_size;
|
||||
@@ -534,7 +534,7 @@ uint8_t atsha204Class::sha204m_execute(uint8_t op_code, uint8_t param1, uint16_t
|
||||
|
||||
/* CRC Calculator and Checker */
|
||||
|
||||
void atsha204Class::sha204c_calculate_crc(uint8_t length, uint8_t *data, uint8_t *crc)
|
||||
void ATSHA204Class::sha204c_calculate_crc(uint8_t length, uint8_t *data, uint8_t *crc)
|
||||
{
|
||||
uint8_t counter;
|
||||
uint16_t crc_register = 0;
|
||||
@@ -560,7 +560,7 @@ void atsha204Class::sha204c_calculate_crc(uint8_t length, uint8_t *data, uint8_t
|
||||
crc[1] = (uint8_t) (crc_register >> 8);
|
||||
}
|
||||
|
||||
uint8_t atsha204Class::sha204c_check_crc(uint8_t *response)
|
||||
uint8_t ATSHA204Class::sha204c_check_crc(uint8_t *response)
|
||||
{
|
||||
uint8_t crc[SHA204_CRC_SIZE];
|
||||
uint8_t count = response[SHA204_BUFFER_POS_COUNT];
|
||||
@@ -570,4 +570,4 @@ uint8_t atsha204Class::sha204c_check_crc(uint8_t *response)
|
||||
|
||||
return (crc[0] == response[count] && crc[1] == response[count + 1])
|
||||
? SHA204_SUCCESS : SHA204_BAD_CRC;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,7 +220,7 @@
|
||||
|
||||
#define SHA204_SERIAL_SZ 9 // The number of bytes the serial number consists of
|
||||
|
||||
class atsha204Class
|
||||
class ATSHA204Class
|
||||
{
|
||||
private:
|
||||
uint8_t device_pin;
|
||||
@@ -237,7 +237,7 @@ private:
|
||||
uint8_t sha204c_resync(uint8_t size, uint8_t *response);
|
||||
uint8_t sha204c_send_and_receive(uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer, uint8_t execution_delay, uint8_t execution_timeout);
|
||||
public:
|
||||
atsha204Class(uint8_t pin); // Constructor
|
||||
ATSHA204Class(uint8_t pin); // Constructor
|
||||
void sha204c_sleep();
|
||||
uint8_t sha204m_execute(uint8_t op_code, uint8_t param1, uint16_t param2,
|
||||
uint8_t datalen1, uint8_t *data1, uint8_t tx_size, uint8_t *tx_buffer, uint8_t rx_size, uint8_t *rx_buffer);
|
||||
|
||||
@@ -36,13 +36,19 @@
|
||||
#define RF69_MAX_DATA_LEN 61 // to take advantage of the built in AES/CRC we want to limit the frame size to the internal FIFO size (66 bytes - 3 bytes overhead)
|
||||
#define RF69_SPI_CS SS // SS is the SPI slave select pin, for instance D10 on atmega328
|
||||
|
||||
// INT0 on AVRs should be connected to RFM69's DIO0 (ex on Atmega328 it's D2, on Atmega644/1284 it's D2)
|
||||
#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega88) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega88__) || defined(__AVR_ATmega32U4__)
|
||||
// INT0 on AVRs should be connected to RFM69's DIO0 (ex on ATmega328 it's D2, on ATmega644/1284 it's D2)
|
||||
#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega88) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega88__)
|
||||
#define RF69_IRQ_PIN 2
|
||||
#define RF69_IRQ_NUM 0
|
||||
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega1284P__)
|
||||
#define RF69_IRQ_PIN 2
|
||||
#define RF69_IRQ_NUM 2
|
||||
#elif defined(__AVR_ATmega32U4__)
|
||||
#define RF69_IRQ_PIN 3
|
||||
#define RF69_IRQ_NUM 0
|
||||
#else
|
||||
#define RF69_IRQ_PIN 2
|
||||
#define RF69_IRQ_NUM 0
|
||||
#endif
|
||||
|
||||
#define CSMA_LIMIT -90 // upper RX signal sensitivity threshold in dBm for carrier sense access
|
||||
|
||||
@@ -1,20 +1,40 @@
|
||||
/*
|
||||
* Copyright (c) 2013 by Felix Rusu <felix@lowpowerlab.com>
|
||||
* SPI Flash memory library for arduino/moteino.
|
||||
* This works with 256byte/page SPI flash memory
|
||||
* For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes)
|
||||
* Minimal modifications should allow chips that have different page size but modifications
|
||||
* DEPENDS ON: Arduino SPI library
|
||||
*
|
||||
* This file is free software; you can redistribute it and/or modify
|
||||
* it under the terms of either the GNU General Public License version 2
|
||||
* or the GNU Lesser General Public License version 2.1, both as
|
||||
* published by the Free Software Foundation.
|
||||
*/
|
||||
// Copyright (c) 2013-2015 by Felix Rusu, LowPowerLab.com
|
||||
// SPI Flash memory library for arduino/moteino.
|
||||
// This works with 256byte/page SPI flash memory
|
||||
// For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes)
|
||||
// Minimal modifications should allow chips that have different page size but modifications
|
||||
// DEPENDS ON: Arduino SPI library
|
||||
// > Updated Jan. 5, 2015, TomWS1, modified writeBytes to allow blocks > 256 bytes and handle page misalignment.
|
||||
// > Updated Feb. 26, 2015 TomWS1, added support for SPI Transactions (Arduino 1.5.8 and above)
|
||||
// > Selective merge by Felix after testing in IDE 1.0.6, 1.6.4
|
||||
// **********************************************************************************
|
||||
// License
|
||||
// **********************************************************************************
|
||||
// This program is free software; you can redistribute it
|
||||
// and/or modify it under the terms of the GNU General
|
||||
// Public License as published by the Free Software
|
||||
// Foundation; either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will
|
||||
// be useful, but WITHOUT ANY WARRANTY; without even the
|
||||
// implied warranty of MERCHANTABILITY or FITNESS FOR A
|
||||
// PARTICULAR PURPOSE. See the GNU General Public
|
||||
// License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General
|
||||
// Public License along with this program.
|
||||
// If not, see <http://www.gnu.org/licenses/>.
|
||||
//
|
||||
// Licence can be viewed at
|
||||
// http://www.gnu.org/licenses/gpl-3.0.txt
|
||||
//
|
||||
// Please maintain this license information along with authorship
|
||||
// and copyright notices in any redistribution of this code
|
||||
|
||||
#include <SPIFlash.h>
|
||||
|
||||
byte SPIFlash::UNIQUEID[8];
|
||||
uint8_t SPIFlash::UNIQUEID[8];
|
||||
|
||||
/// IMPORTANT: NAND FLASH memory requires erase before write, because
|
||||
/// it can only transition from 1s to 0s and only the erase command can reset all 0s to 1s
|
||||
@@ -32,15 +52,22 @@ SPIFlash::SPIFlash(uint8_t slaveSelectPin, uint16_t jedecID) {
|
||||
|
||||
/// Select the flash chip
|
||||
void SPIFlash::select() {
|
||||
noInterrupts();
|
||||
//save current SPI settings
|
||||
#ifndef SPI_HAS_TRANSACTION
|
||||
noInterrupts();
|
||||
#endif
|
||||
_SPCR = SPCR;
|
||||
_SPSR = SPSR;
|
||||
//set FLASH chip SPI settings
|
||||
|
||||
#ifdef SPI_HAS_TRANSACTION
|
||||
SPI.beginTransaction(_settings);
|
||||
#else
|
||||
// set FLASH SPI settings
|
||||
SPI.setDataMode(SPI_MODE0);
|
||||
SPI.setBitOrder(MSBFIRST);
|
||||
SPI.setClockDivider(SPI_CLOCK_DIV4); //decided to slow down from DIV2 after SPI stalling in some instances, especially visible on mega1284p when RFM69 and FLASH chip both present
|
||||
SPI.begin();
|
||||
#endif
|
||||
digitalWrite(_slaveSelectPin, LOW);
|
||||
}
|
||||
|
||||
@@ -48,9 +75,13 @@ void SPIFlash::select() {
|
||||
void SPIFlash::unselect() {
|
||||
digitalWrite(_slaveSelectPin, HIGH);
|
||||
//restore SPI settings to what they were before talking to the FLASH chip
|
||||
#ifdef SPI_HAS_TRANSACTION
|
||||
SPI.endTransaction();
|
||||
#else
|
||||
interrupts();
|
||||
#endif
|
||||
SPCR = _SPCR;
|
||||
SPSR = _SPSR;
|
||||
interrupts();
|
||||
}
|
||||
|
||||
/// setup SPI, read device ID etc...
|
||||
@@ -59,6 +90,10 @@ boolean SPIFlash::initialize()
|
||||
_SPCR = SPCR;
|
||||
_SPSR = SPSR;
|
||||
pinMode(_slaveSelectPin, OUTPUT);
|
||||
#ifdef SPI_HAS_TRANSACTION
|
||||
_settings = SPISettings(4000000, MSBFIRST, SPI_MODE0);
|
||||
#endif
|
||||
|
||||
unselect();
|
||||
wakeup();
|
||||
|
||||
@@ -72,7 +107,7 @@ boolean SPIFlash::initialize()
|
||||
}
|
||||
|
||||
/// Get the manufacturer and device ID bytes (as a short word)
|
||||
word SPIFlash::readDeviceId()
|
||||
uint16_t SPIFlash::readDeviceId()
|
||||
{
|
||||
#if defined(__AVR_ATmega32U4__) // Arduino Leonardo, MoteinoLeo
|
||||
command(SPIFLASH_IDREAD); // Read JEDEC ID
|
||||
@@ -80,7 +115,7 @@ word SPIFlash::readDeviceId()
|
||||
select();
|
||||
SPI.transfer(SPIFLASH_IDREAD);
|
||||
#endif
|
||||
word jedecid = SPI.transfer(0) << 8;
|
||||
uint16_t jedecid = SPI.transfer(0) << 8;
|
||||
jedecid |= SPI.transfer(0);
|
||||
unselect();
|
||||
return jedecid;
|
||||
@@ -89,47 +124,47 @@ word SPIFlash::readDeviceId()
|
||||
/// Get the 64 bit unique identifier, stores it in UNIQUEID[8]. Only needs to be called once, ie after initialize
|
||||
/// Returns the byte pointer to the UNIQUEID byte array
|
||||
/// Read UNIQUEID like this:
|
||||
/// flash.readUniqueId(); for (byte i=0;i<8;i++) { Serial.print(flash.UNIQUEID[i], HEX); Serial.print(' '); }
|
||||
/// flash.readUniqueId(); for (uint8_t i=0;i<8;i++) { Serial.print(flash.UNIQUEID[i], HEX); Serial.print(' '); }
|
||||
/// or like this:
|
||||
/// flash.readUniqueId(); byte* MAC = flash.readUniqueId(); for (byte i=0;i<8;i++) { Serial.print(MAC[i], HEX); Serial.print(' '); }
|
||||
byte* SPIFlash::readUniqueId()
|
||||
/// flash.readUniqueId(); uint8_t* MAC = flash.readUniqueId(); for (uint8_t i=0;i<8;i++) { Serial.print(MAC[i], HEX); Serial.print(' '); }
|
||||
uint8_t* SPIFlash::readUniqueId()
|
||||
{
|
||||
command(SPIFLASH_MACREAD);
|
||||
SPI.transfer(0);
|
||||
SPI.transfer(0);
|
||||
SPI.transfer(0);
|
||||
SPI.transfer(0);
|
||||
for (byte i=0;i<8;i++)
|
||||
for (uint8_t i=0;i<8;i++)
|
||||
UNIQUEID[i] = SPI.transfer(0);
|
||||
unselect();
|
||||
return UNIQUEID;
|
||||
}
|
||||
|
||||
/// read 1 byte from flash memory
|
||||
byte SPIFlash::readByte(long addr) {
|
||||
uint8_t SPIFlash::readByte(uint32_t addr) {
|
||||
command(SPIFLASH_ARRAYREADLOWFREQ);
|
||||
SPI.transfer(addr >> 16);
|
||||
SPI.transfer(addr >> 8);
|
||||
SPI.transfer(addr);
|
||||
byte result = SPI.transfer(0);
|
||||
uint8_t result = SPI.transfer(0);
|
||||
unselect();
|
||||
return result;
|
||||
}
|
||||
|
||||
/// read unlimited # of bytes
|
||||
void SPIFlash::readBytes(long addr, void* buf, word len) {
|
||||
void SPIFlash::readBytes(uint32_t addr, void* buf, uint16_t len) {
|
||||
command(SPIFLASH_ARRAYREAD);
|
||||
SPI.transfer(addr >> 16);
|
||||
SPI.transfer(addr >> 8);
|
||||
SPI.transfer(addr);
|
||||
SPI.transfer(0); //"dont care"
|
||||
for (word i = 0; i < len; ++i)
|
||||
((byte*) buf)[i] = SPI.transfer(0);
|
||||
for (uint16_t i = 0; i < len; ++i)
|
||||
((uint8_t*) buf)[i] = SPI.transfer(0);
|
||||
unselect();
|
||||
}
|
||||
|
||||
/// Send a command to the flash chip, pass TRUE for isWrite when its a write command
|
||||
void SPIFlash::command(byte cmd, boolean isWrite){
|
||||
void SPIFlash::command(uint8_t cmd, boolean isWrite){
|
||||
#if defined(__AVR_ATmega32U4__) // Arduino Leonardo, MoteinoLeo
|
||||
DDRB |= B00000001; // Make sure the SS pin (PB0 - used by RFM12B on MoteinoLeo R1) is set as output HIGH!
|
||||
PORTB |= B00000001;
|
||||
@@ -155,7 +190,7 @@ boolean SPIFlash::busy()
|
||||
/*
|
||||
select();
|
||||
SPI.transfer(SPIFLASH_STATUSREAD);
|
||||
byte status = SPI.transfer(0);
|
||||
uint8_t status = SPI.transfer(0);
|
||||
unselect();
|
||||
return status & 1;
|
||||
*/
|
||||
@@ -163,11 +198,11 @@ boolean SPIFlash::busy()
|
||||
}
|
||||
|
||||
/// return the STATUS register
|
||||
byte SPIFlash::readStatus()
|
||||
uint8_t SPIFlash::readStatus()
|
||||
{
|
||||
select();
|
||||
SPI.transfer(SPIFLASH_STATUSREAD);
|
||||
byte status = SPI.transfer(0);
|
||||
uint8_t status = SPI.transfer(0);
|
||||
unselect();
|
||||
return status;
|
||||
}
|
||||
@@ -176,7 +211,7 @@ byte SPIFlash::readStatus()
|
||||
/// Write 1 byte to flash memory
|
||||
/// WARNING: you can only write to previously erased memory locations (see datasheet)
|
||||
/// use the block erase commands to first clear memory (write 0xFFs)
|
||||
void SPIFlash::writeByte(long addr, uint8_t byt) {
|
||||
void SPIFlash::writeByte(uint32_t addr, uint8_t byt) {
|
||||
command(SPIFLASH_BYTEPAGEPROGRAM, true); // Byte/Page Program
|
||||
SPI.transfer(addr >> 16);
|
||||
SPI.transfer(addr >> 8);
|
||||
@@ -185,20 +220,32 @@ void SPIFlash::writeByte(long addr, uint8_t byt) {
|
||||
unselect();
|
||||
}
|
||||
|
||||
/// write 1-256 bytes to flash memory
|
||||
/// write multiple bytes to flash memory (up to 64K)
|
||||
/// WARNING: you can only write to previously erased memory locations (see datasheet)
|
||||
/// use the block erase commands to first clear memory (write 0xFFs)
|
||||
/// WARNING: if you write beyond a page boundary (or more than 256bytes),
|
||||
/// the bytes will wrap around and start overwriting at the beginning of that same page
|
||||
/// see datasheet for more details
|
||||
void SPIFlash::writeBytes(long addr, const void* buf, uint16_t len) {
|
||||
command(SPIFLASH_BYTEPAGEPROGRAM, true); // Byte/Page Program
|
||||
SPI.transfer(addr >> 16);
|
||||
SPI.transfer(addr >> 8);
|
||||
SPI.transfer(addr);
|
||||
for (uint16_t i = 0; i < len; i++)
|
||||
SPI.transfer(((byte*) buf)[i]);
|
||||
unselect();
|
||||
/// This version handles both page alignment and data blocks larger than 256 bytes.
|
||||
///
|
||||
void SPIFlash::writeBytes(uint32_t addr, const void* buf, uint16_t len) {
|
||||
uint16_t n;
|
||||
uint16_t maxBytes = 256-(addr%256); // force the first set of bytes to stay within the first page
|
||||
uint16_t offset = 0;
|
||||
while (len>0)
|
||||
{
|
||||
n = (len<=maxBytes) ? len : maxBytes;
|
||||
command(SPIFLASH_BYTEPAGEPROGRAM, true); // Byte/Page Program
|
||||
SPI.transfer(addr >> 16);
|
||||
SPI.transfer(addr >> 8);
|
||||
SPI.transfer(addr);
|
||||
|
||||
for (uint16_t i = 0; i < n; i++)
|
||||
SPI.transfer(((uint8_t*) buf)[offset + i]);
|
||||
unselect();
|
||||
|
||||
addr+=n; // adjust the addresses and remaining bytes by what we've just transferred.
|
||||
offset +=n;
|
||||
len -= n;
|
||||
maxBytes = 256; // now we can do up to 256 bytes per loop
|
||||
}
|
||||
}
|
||||
|
||||
/// erase entire flash memory array
|
||||
@@ -213,7 +260,7 @@ void SPIFlash::chipErase() {
|
||||
}
|
||||
|
||||
/// erase a 4Kbyte block
|
||||
void SPIFlash::blockErase4K(long addr) {
|
||||
void SPIFlash::blockErase4K(uint32_t addr) {
|
||||
command(SPIFLASH_BLOCKERASE_4K, true); // Block Erase
|
||||
SPI.transfer(addr >> 16);
|
||||
SPI.transfer(addr >> 8);
|
||||
@@ -222,7 +269,7 @@ void SPIFlash::blockErase4K(long addr) {
|
||||
}
|
||||
|
||||
/// erase a 32Kbyte block
|
||||
void SPIFlash::blockErase32K(long addr) {
|
||||
void SPIFlash::blockErase32K(uint32_t addr) {
|
||||
command(SPIFLASH_BLOCKERASE_32K, true); // Block Erase
|
||||
SPI.transfer(addr >> 16);
|
||||
SPI.transfer(addr >> 8);
|
||||
|
||||
@@ -1,16 +1,36 @@
|
||||
/*
|
||||
* Copyright (c) 2013 by Felix Rusu <felix@lowpowerlab.com>
|
||||
* SPI Flash memory library for arduino/moteino.
|
||||
* This works with 256byte/page SPI flash memory
|
||||
* For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes)
|
||||
* Minimal modifications should allow chips that have different page size but modifications
|
||||
* DEPENDS ON: Arduino SPI library
|
||||
*
|
||||
* This file is free software; you can redistribute it and/or modify
|
||||
* it under the terms of either the GNU General Public License version 2
|
||||
* or the GNU Lesser General Public License version 2.1, both as
|
||||
* published by the Free Software Foundation.
|
||||
*/
|
||||
// Copyright (c) 2013-2015 by Felix Rusu, LowPowerLab.com
|
||||
// SPI Flash memory library for arduino/moteino.
|
||||
// This works with 256byte/page SPI flash memory
|
||||
// For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes)
|
||||
// Minimal modifications should allow chips that have different page size but modifications
|
||||
// DEPENDS ON: Arduino SPI library
|
||||
// > Updated Jan. 5, 2015, TomWS1, modified writeBytes to allow blocks > 256 bytes and handle page misalignment.
|
||||
// > Updated Feb. 26, 2015 TomWS1, added support for SPI Transactions (Arduino 1.5.8 and above)
|
||||
// > Selective merge by Felix after testing in IDE 1.0.6, 1.6.4
|
||||
// **********************************************************************************
|
||||
// License
|
||||
// **********************************************************************************
|
||||
// This program is free software; you can redistribute it
|
||||
// and/or modify it under the terms of the GNU General
|
||||
// Public License as published by the Free Software
|
||||
// Foundation; either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will
|
||||
// be useful, but WITHOUT ANY WARRANTY; without even the
|
||||
// implied warranty of MERCHANTABILITY or FITNESS FOR A
|
||||
// PARTICULAR PURPOSE. See the GNU General Public
|
||||
// License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General
|
||||
// Public License along with this program.
|
||||
// If not, see <http://www.gnu.org/licenses/>.
|
||||
//
|
||||
// Licence can be viewed at
|
||||
// http://www.gnu.org/licenses/gpl-3.0.txt
|
||||
//
|
||||
// Please maintain this license information along with authorship
|
||||
// and copyright notices in any redistribution of this code
|
||||
|
||||
#ifndef _SPIFLASH_H_
|
||||
#define _SPIFLASH_H_
|
||||
@@ -33,19 +53,19 @@
|
||||
/// Assuming the WP pin is pulled up (to disable hardware write protection)
|
||||
/// To use any write commands the WEL bit in the status register must be set to 1.
|
||||
/// This is accomplished by sending a 0x06 command before any such write/erase command.
|
||||
/// The WEL bit in the status register resets to the logical “0” state after a
|
||||
/// device power-up or reset. In addition, the WEL bit will be reset to the logical “0” state automatically under the following conditions:
|
||||
/// • Write Disable operation completes successfully
|
||||
/// • Write Status Register operation completes successfully or aborts
|
||||
/// • Protect Sector operation completes successfully or aborts
|
||||
/// • Unprotect Sector operation completes successfully or aborts
|
||||
/// • Byte/Page Program operation completes successfully or aborts
|
||||
/// • Sequential Program Mode reaches highest unprotected memory location
|
||||
/// • Sequential Program Mode reaches the end of the memory array
|
||||
/// • Sequential Program Mode aborts
|
||||
/// • Block Erase operation completes successfully or aborts
|
||||
/// • Chip Erase operation completes successfully or aborts
|
||||
/// • Hold condition aborts
|
||||
/// The WEL bit in the status register resets to the logical ?0? state after a
|
||||
/// device power-up or reset. In addition, the WEL bit will be reset to the logical ?0? state automatically under the following conditions:
|
||||
/// ? Write Disable operation completes successfully
|
||||
/// ? Write Status Register operation completes successfully or aborts
|
||||
/// ? Protect Sector operation completes successfully or aborts
|
||||
/// ? Unprotect Sector operation completes successfully or aborts
|
||||
/// ? Byte/Page Program operation completes successfully or aborts
|
||||
/// ? Sequential Program Mode reaches highest unprotected memory location
|
||||
/// ? Sequential Program Mode reaches the end of the memory array
|
||||
/// ? Sequential Program Mode aborts
|
||||
/// ? Block Erase operation completes successfully or aborts
|
||||
/// ? Chip Erase operation completes successfully or aborts
|
||||
/// ? Hold condition aborts
|
||||
#define SPIFLASH_WRITEENABLE 0x06 // write enable
|
||||
#define SPIFLASH_WRITEDISABLE 0x04 // write disable
|
||||
|
||||
@@ -69,21 +89,21 @@
|
||||
|
||||
class SPIFlash {
|
||||
public:
|
||||
static byte UNIQUEID[8];
|
||||
SPIFlash(byte slaveSelectPin, uint16_t jedecID=0);
|
||||
static uint8_t UNIQUEID[8];
|
||||
SPIFlash(uint8_t slaveSelectPin, uint16_t jedecID=0);
|
||||
boolean initialize();
|
||||
void command(byte cmd, boolean isWrite=false);
|
||||
byte readStatus();
|
||||
byte readByte(long addr);
|
||||
void readBytes(long addr, void* buf, word len);
|
||||
void writeByte(long addr, byte byt);
|
||||
void writeBytes(long addr, const void* buf, uint16_t len);
|
||||
void command(uint8_t cmd, boolean isWrite=false);
|
||||
uint8_t readStatus();
|
||||
uint8_t readByte(uint32_t addr);
|
||||
void readBytes(uint32_t addr, void* buf, uint16_t len);
|
||||
void writeByte(uint32_t addr, uint8_t byt);
|
||||
void writeBytes(uint32_t addr, const void* buf, uint16_t len);
|
||||
boolean busy();
|
||||
void chipErase();
|
||||
void blockErase4K(long address);
|
||||
void blockErase32K(long address);
|
||||
word readDeviceId();
|
||||
byte* readUniqueId();
|
||||
void blockErase4K(uint32_t address);
|
||||
void blockErase32K(uint32_t address);
|
||||
uint16_t readDeviceId();
|
||||
uint8_t* readUniqueId();
|
||||
|
||||
void sleep();
|
||||
void wakeup();
|
||||
@@ -91,10 +111,13 @@ public:
|
||||
protected:
|
||||
void select();
|
||||
void unselect();
|
||||
byte _slaveSelectPin;
|
||||
uint8_t _slaveSelectPin;
|
||||
uint16_t _jedecID;
|
||||
byte _SPCR;
|
||||
byte _SPSR;
|
||||
uint8_t _SPCR;
|
||||
uint8_t _SPSR;
|
||||
#ifdef SPI_HAS_TRANSACTION
|
||||
SPISettings _settings;
|
||||
#endif
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -4,6 +4,24 @@ Copyright (c) 2007, Jim Studt (original old version - many contributors since)
|
||||
The latest version of this library may be found at:
|
||||
http://www.pjrc.com/teensy/td_libs_OneWire.html
|
||||
|
||||
OneWire has been maintained by Paul Stoffregen (paul@pjrc.com) since
|
||||
January 2010. At the time, it was in need of many bug fixes, but had
|
||||
been abandoned the original author (Jim Studt). None of the known
|
||||
contributors were interested in maintaining OneWire. Paul typically
|
||||
works on OneWire every 6 to 12 months. Patches usually wait that
|
||||
long. If anyone is interested in more actively maintaining OneWire,
|
||||
please contact Paul.
|
||||
|
||||
Version 2.2:
|
||||
Teensy 3.0 compatibility, Paul Stoffregen, paul@pjrc.com
|
||||
Arduino Due compatibility, http://arduino.cc/forum/index.php?topic=141030
|
||||
Fix DS18B20 example negative temperature
|
||||
Fix DS18B20 example's low res modes, Ken Butcher
|
||||
Improve reset timing, Mark Tillotson
|
||||
Add const qualifiers, Bertrik Sikken
|
||||
Add initial value input to crc16, Bertrik Sikken
|
||||
Add target_search() function, Scott Roberts
|
||||
|
||||
Version 2.1:
|
||||
Arduino 1.0 compatibility, Paul Stoffregen
|
||||
Improve temperature example, Paul Stoffregen
|
||||
@@ -136,13 +154,13 @@ uint8_t OneWire::reset(void)
|
||||
DIRECT_WRITE_LOW(reg, mask);
|
||||
DIRECT_MODE_OUTPUT(reg, mask); // drive output low
|
||||
interrupts();
|
||||
delayMicroseconds(500);
|
||||
delayMicroseconds(480);
|
||||
noInterrupts();
|
||||
DIRECT_MODE_INPUT(reg, mask); // allow it to float
|
||||
delayMicroseconds(80);
|
||||
delayMicroseconds(70);
|
||||
r = !DIRECT_READ(reg, mask);
|
||||
interrupts();
|
||||
delayMicroseconds(420);
|
||||
delayMicroseconds(410);
|
||||
return r;
|
||||
}
|
||||
|
||||
@@ -249,13 +267,13 @@ void OneWire::read_bytes(uint8_t *buf, uint16_t count) {
|
||||
//
|
||||
// Do a ROM select
|
||||
//
|
||||
void OneWire::select( uint8_t rom[8])
|
||||
void OneWire::select(const uint8_t rom[8])
|
||||
{
|
||||
int i;
|
||||
uint8_t i;
|
||||
|
||||
write(0x55); // Choose ROM
|
||||
|
||||
for( i = 0; i < 8; i++) write(rom[i]);
|
||||
for (i = 0; i < 8; i++) write(rom[i]);
|
||||
}
|
||||
|
||||
//
|
||||
@@ -280,17 +298,30 @@ void OneWire::depower()
|
||||
// You do not need to do it for the first search, though you could.
|
||||
//
|
||||
void OneWire::reset_search()
|
||||
{
|
||||
{
|
||||
// reset the search state
|
||||
LastDiscrepancy = 0;
|
||||
LastDeviceFlag = FALSE;
|
||||
LastFamilyDiscrepancy = 0;
|
||||
for(int i = 7; ; i--)
|
||||
{
|
||||
for(int i = 7; ; i--) {
|
||||
ROM_NO[i] = 0;
|
||||
if ( i == 0) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Setup the search to find the device type 'family_code' on the next call
|
||||
// to search(*newAddr) if it is present.
|
||||
//
|
||||
void OneWire::target_search(uint8_t family_code)
|
||||
{
|
||||
// set the search state to find SearchFamily type devices
|
||||
ROM_NO[0] = family_code;
|
||||
for (uint8_t i = 1; i < 8; i++)
|
||||
ROM_NO[i] = 0;
|
||||
LastDiscrepancy = 64;
|
||||
LastFamilyDiscrepancy = 0;
|
||||
LastDeviceFlag = FALSE;
|
||||
}
|
||||
|
||||
//
|
||||
// Perform a search. If this function returns a '1' then it has
|
||||
@@ -461,7 +492,7 @@ static const uint8_t PROGMEM dscrc_table[] = {
|
||||
// compared to all those delayMicrosecond() calls. But I got
|
||||
// confused, so I use this table from the examples.)
|
||||
//
|
||||
uint8_t OneWire::crc8( uint8_t *addr, uint8_t len)
|
||||
uint8_t OneWire::crc8(const uint8_t *addr, uint8_t len)
|
||||
{
|
||||
uint8_t crc = 0;
|
||||
|
||||
@@ -475,7 +506,7 @@ uint8_t OneWire::crc8( uint8_t *addr, uint8_t len)
|
||||
// Compute a Dallas Semiconductor 8 bit CRC directly.
|
||||
// this is much slower, but much smaller, than the lookup table.
|
||||
//
|
||||
uint8_t OneWire::crc8( uint8_t *addr, uint8_t len)
|
||||
uint8_t OneWire::crc8(const uint8_t *addr, uint8_t len)
|
||||
{
|
||||
uint8_t crc = 0;
|
||||
|
||||
@@ -493,23 +524,22 @@ uint8_t OneWire::crc8( uint8_t *addr, uint8_t len)
|
||||
#endif
|
||||
|
||||
#if ONEWIRE_CRC16
|
||||
bool OneWire::check_crc16(uint8_t* input, uint16_t len, uint8_t* inverted_crc)
|
||||
bool OneWire::check_crc16(const uint8_t* input, uint16_t len, const uint8_t* inverted_crc, uint16_t crc)
|
||||
{
|
||||
uint16_t crc = ~crc16(input, len);
|
||||
crc = ~crc16(input, len, crc);
|
||||
return (crc & 0xFF) == inverted_crc[0] && (crc >> 8) == inverted_crc[1];
|
||||
}
|
||||
|
||||
uint16_t OneWire::crc16(uint8_t* input, uint16_t len)
|
||||
uint16_t OneWire::crc16(const uint8_t* input, uint16_t len, uint16_t crc)
|
||||
{
|
||||
static const uint8_t oddparity[16] =
|
||||
{ 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 };
|
||||
uint16_t crc = 0; // Starting seed is zero.
|
||||
|
||||
for (uint16_t i = 0 ; i < len ; i++) {
|
||||
// Even though we're just copying a byte from the input,
|
||||
// we'll be doing 16-bit computation with it.
|
||||
uint16_t cdata = input[i];
|
||||
cdata = (cdata ^ (crc & 0xff)) & 0xff;
|
||||
cdata = (cdata ^ crc) & 0xff;
|
||||
crc >>= 8;
|
||||
|
||||
if (oddparity[cdata & 0x0F] ^ oddparity[cdata >> 4])
|
||||
|
||||
@@ -56,13 +56,44 @@
|
||||
#define IO_REG_TYPE uint8_t
|
||||
#define IO_REG_ASM asm("r30")
|
||||
#define DIRECT_READ(base, mask) (((*(base)) & (mask)) ? 1 : 0)
|
||||
#define DIRECT_MODE_INPUT(base, mask) ((*(base+1)) &= ~(mask))
|
||||
#define DIRECT_MODE_OUTPUT(base, mask) ((*(base+1)) |= (mask))
|
||||
#define DIRECT_WRITE_LOW(base, mask) ((*(base+2)) &= ~(mask))
|
||||
#define DIRECT_WRITE_HIGH(base, mask) ((*(base+2)) |= (mask))
|
||||
#define DIRECT_MODE_INPUT(base, mask) ((*((base)+1)) &= ~(mask))
|
||||
#define DIRECT_MODE_OUTPUT(base, mask) ((*((base)+1)) |= (mask))
|
||||
#define DIRECT_WRITE_LOW(base, mask) ((*((base)+2)) &= ~(mask))
|
||||
#define DIRECT_WRITE_HIGH(base, mask) ((*((base)+2)) |= (mask))
|
||||
|
||||
#elif defined(__MK20DX128__)
|
||||
#define PIN_TO_BASEREG(pin) (portOutputRegister(pin))
|
||||
#define PIN_TO_BITMASK(pin) (1)
|
||||
#define IO_REG_TYPE uint8_t
|
||||
#define IO_REG_ASM
|
||||
#define DIRECT_READ(base, mask) (*((base)+512))
|
||||
#define DIRECT_MODE_INPUT(base, mask) (*((base)+640) = 0)
|
||||
#define DIRECT_MODE_OUTPUT(base, mask) (*((base)+640) = 1)
|
||||
#define DIRECT_WRITE_LOW(base, mask) (*((base)+256) = 1)
|
||||
#define DIRECT_WRITE_HIGH(base, mask) (*((base)+128) = 1)
|
||||
|
||||
#elif defined(__SAM3X8E__)
|
||||
// Arduino 1.5.1 may have a bug in delayMicroseconds() on Arduino Due.
|
||||
// http://arduino.cc/forum/index.php/topic,141030.msg1076268.html#msg1076268
|
||||
// If you have trouble with OneWire on Arduino Due, please check the
|
||||
// status of delayMicroseconds() before reporting a bug in OneWire!
|
||||
#define PIN_TO_BASEREG(pin) (&(digitalPinToPort(pin)->PIO_PER))
|
||||
#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin))
|
||||
#define IO_REG_TYPE uint32_t
|
||||
#define IO_REG_ASM
|
||||
#define DIRECT_READ(base, mask) (((*((base)+15)) & (mask)) ? 1 : 0)
|
||||
#define DIRECT_MODE_INPUT(base, mask) ((*((base)+5)) = (mask))
|
||||
#define DIRECT_MODE_OUTPUT(base, mask) ((*((base)+4)) = (mask))
|
||||
#define DIRECT_WRITE_LOW(base, mask) ((*((base)+13)) = (mask))
|
||||
#define DIRECT_WRITE_HIGH(base, mask) ((*((base)+12)) = (mask))
|
||||
#ifndef PROGMEM
|
||||
#define PROGMEM
|
||||
#endif
|
||||
#ifndef pgm_read_byte
|
||||
#define pgm_read_byte(addr) (*(const uint8_t *)(addr))
|
||||
#endif
|
||||
|
||||
#elif defined(__PIC32MX__)
|
||||
#include <plib.h> // is this necessary?
|
||||
#define PIN_TO_BASEREG(pin) (portModeRegister(digitalPinToPort(pin)))
|
||||
#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin))
|
||||
#define IO_REG_TYPE uint32_t
|
||||
@@ -101,7 +132,7 @@ class OneWire
|
||||
uint8_t reset(void);
|
||||
|
||||
// Issue a 1-Wire rom select command, you do the reset first.
|
||||
void select( uint8_t rom[8]);
|
||||
void select(const uint8_t rom[8]);
|
||||
|
||||
// Issue a 1-Wire rom skip command, to address all on bus.
|
||||
void skip(void);
|
||||
@@ -137,6 +168,10 @@ class OneWire
|
||||
// Clear the search state so that if will start from the beginning again.
|
||||
void reset_search();
|
||||
|
||||
// Setup the search to find the device type 'family_code' on the next call
|
||||
// to search(*newAddr) if it is present.
|
||||
void target_search(uint8_t family_code);
|
||||
|
||||
// Look for the next device. Returns 1 if a new address has been
|
||||
// returned. A zero might mean that the bus is shorted, there are
|
||||
// no devices, or you have already retrieved all of them. It
|
||||
@@ -149,7 +184,7 @@ class OneWire
|
||||
#if ONEWIRE_CRC
|
||||
// Compute a Dallas Semiconductor 8 bit CRC, these are used in the
|
||||
// ROM and scratchpad registers.
|
||||
static uint8_t crc8( uint8_t *addr, uint8_t len);
|
||||
static uint8_t crc8(const uint8_t *addr, uint8_t len);
|
||||
|
||||
#if ONEWIRE_CRC16
|
||||
// Compute the 1-Wire CRC16 and compare it against the received CRC.
|
||||
@@ -170,8 +205,9 @@ class OneWire
|
||||
// @param inverted_crc - The two CRC16 bytes in the received data.
|
||||
// This should just point into the received data,
|
||||
// *not* at a 16-bit integer.
|
||||
// @param crc - The crc starting value (optional)
|
||||
// @return True, iff the CRC matches.
|
||||
static bool check_crc16(uint8_t* input, uint16_t len, uint8_t* inverted_crc);
|
||||
static bool check_crc16(const uint8_t* input, uint16_t len, const uint8_t* inverted_crc, uint16_t crc = 0);
|
||||
|
||||
// Compute a Dallas Semiconductor 16 bit CRC. This is required to check
|
||||
// the integrity of data received from many 1-Wire devices. Note that the
|
||||
@@ -183,8 +219,9 @@ class OneWire
|
||||
// byte order than the two bytes you get from 1-Wire.
|
||||
// @param input - Array of bytes to checksum.
|
||||
// @param len - How many bytes to use.
|
||||
// @param crc - The crc starting value (optional)
|
||||
// @return The CRC16, as defined by Dallas Semiconductor.
|
||||
static uint16_t crc16(uint8_t* input, uint16_t len);
|
||||
static uint16_t crc16(const uint8_t* input, uint16_t len, uint16_t crc = 0);
|
||||
#endif
|
||||
#endif
|
||||
};
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
// The DallasTemperature library can do all this work for you!
|
||||
// http://milesburton.com/Dallas_Temperature_Control_Library
|
||||
|
||||
OneWire ds(10); // on pin 10
|
||||
OneWire ds(10); // on pin 10 (a 4.7K resistor is necessary)
|
||||
|
||||
void setup(void) {
|
||||
Serial.begin(9600);
|
||||
@@ -62,7 +62,7 @@ void loop(void) {
|
||||
|
||||
ds.reset();
|
||||
ds.select(addr);
|
||||
ds.write(0x44,1); // start conversion, with parasite power on at the end
|
||||
ds.write(0x44, 1); // start conversion, with parasite power on at the end
|
||||
|
||||
delay(1000); // maybe 750ms is enough, maybe not
|
||||
// we might do a ds.depower() here, but the reset will take care of it.
|
||||
@@ -72,7 +72,7 @@ void loop(void) {
|
||||
ds.write(0xBE); // Read Scratchpad
|
||||
|
||||
Serial.print(" Data = ");
|
||||
Serial.print(present,HEX);
|
||||
Serial.print(present, HEX);
|
||||
Serial.print(" ");
|
||||
for ( i = 0; i < 9; i++) { // we need 9 bytes
|
||||
data[i] = ds.read();
|
||||
@@ -83,21 +83,24 @@ void loop(void) {
|
||||
Serial.print(OneWire::crc8(data, 8), HEX);
|
||||
Serial.println();
|
||||
|
||||
// convert the data to actual temperature
|
||||
|
||||
unsigned int raw = (data[1] << 8) | data[0];
|
||||
// Convert the data to actual temperature
|
||||
// because the result is a 16 bit signed integer, it should
|
||||
// be stored to an "int16_t" type, which is always 16 bits
|
||||
// even when compiled on a 32 bit processor.
|
||||
int16_t raw = (data[1] << 8) | data[0];
|
||||
if (type_s) {
|
||||
raw = raw << 3; // 9 bit resolution default
|
||||
if (data[7] == 0x10) {
|
||||
// count remain gives full 12 bit resolution
|
||||
// "count remain" gives full 12 bit resolution
|
||||
raw = (raw & 0xFFF0) + 12 - data[6];
|
||||
}
|
||||
} else {
|
||||
byte cfg = (data[4] & 0x60);
|
||||
if (cfg == 0x00) raw = raw << 3; // 9 bit resolution, 93.75 ms
|
||||
else if (cfg == 0x20) raw = raw << 2; // 10 bit res, 187.5 ms
|
||||
else if (cfg == 0x40) raw = raw << 1; // 11 bit res, 375 ms
|
||||
// default is 12 bit resolution, 750 ms conversion time
|
||||
// at lower res, the low bits are undefined, so let's zero them
|
||||
if (cfg == 0x00) raw = raw & ~7; // 9 bit resolution, 93.75 ms
|
||||
else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
|
||||
else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
|
||||
//// default is 12 bit resolution, 750 ms conversion time
|
||||
}
|
||||
celsius = (float)raw / 16.0;
|
||||
fahrenheit = celsius * 1.8 + 32.0;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
Notes from AS3935 datasheet:
|
||||
Register Map: Page 11, detailed version on Page 12
|
||||
|
||||
Max clock freq for SPI = 2MHz
|
||||
|
||||
SPI command Structure: Page14
|
||||
To activate this SPI, the CS has to be set to low. A SPI command consists of two bytes serial command and the data are sampled on the falling
|
||||
edge of SCLK (CPHA=1). The next table shows command structure, from the MSB (B15) to LSB (B0). The command stream has to be sent to
|
||||
the SPI from the MSB (B15) to the LSB (B0).
|
||||
|
||||
@@ -0,0 +1,421 @@
|
||||
/***************************************************************************
|
||||
* File Name: PWFusion_AS3935.h
|
||||
* Processor/Platform: Arduino Uno R3 (tested)
|
||||
* Development Environment: Arduino 1.0.5
|
||||
*
|
||||
* Designed for use with with Playing With Fusion AS3935 Lightning Sensor
|
||||
* Breakout: SEN-39001.
|
||||
*
|
||||
* SEN-39001 (universal applications)
|
||||
* ---> http://www.playingwithfusion.com/productview.php?pdid=22
|
||||
*
|
||||
* Copyright © 2014 Playing With Fusion, Inc.
|
||||
* SOFTWARE LICENSE AGREEMENT: This code is released under the MIT License.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
* DEALINGS IN THE SOFTWARE.
|
||||
* **************************************************************************
|
||||
* REVISION HISTORY:
|
||||
* Author Date Comments
|
||||
* J. Steinlage 2014Aug20 Original version
|
||||
*
|
||||
* Playing With Fusion, Inc. invests time and resources developing open-source
|
||||
* code. Please support Playing With Fusion and continued open-source
|
||||
* development by buying products from Playing With Fusion!
|
||||
*
|
||||
* **************************************************************************
|
||||
* ADDITIONAL NOTES:
|
||||
* This file contains functions to interface with the AS3935 Franklin
|
||||
* Lightning Sensor manufactured by AMS. Originally designed for application
|
||||
* on the Arduino Uno platform.
|
||||
**************************************************************************/
|
||||
#include "PWFusion_AS3935.h"
|
||||
|
||||
PWF_AS3935::PWF_AS3935(int8_t CSx, int8_t IRQx, int8_t SIx)
|
||||
{
|
||||
_cs = CSx;
|
||||
_si = SIx;
|
||||
_irq = IRQx;
|
||||
|
||||
// initalize the chip select pins
|
||||
pinMode(_cs, OUTPUT);
|
||||
pinMode(_si, OUTPUT);
|
||||
pinMode(_irq, INPUT);
|
||||
|
||||
digitalWrite(_cs, HIGH); // set pin high to initialize/clear SPI bus
|
||||
digitalWrite(_si, LOW); // set pin low for SPI mode
|
||||
|
||||
}
|
||||
|
||||
uint8_t PWF_AS3935::_sing_reg_read(uint8_t RegAdd)
|
||||
{
|
||||
digitalWrite(_cs, LOW); // set pin low to start talking to IC
|
||||
// next pack command byte, send AS3935.... structure is shown below
|
||||
// MODE Register Address/Direct Cmd
|
||||
// B15-14 B13------------------8
|
||||
// 15 is always 0; B14, 0: Write/Direct Command, 1: Read
|
||||
SPI.transfer((RegAdd & 0x3F) | 0x40); // simple write, nothing to read back
|
||||
uint8_t RegData = SPI.transfer(0x00); // read register data from IC
|
||||
digitalWrite(_cs, HIGH); // set pin high to end SPI session
|
||||
|
||||
return RegData;
|
||||
}
|
||||
|
||||
void PWF_AS3935::_sing_reg_write(uint8_t RegAdd, uint8_t DataMask, uint8_t RegData)
|
||||
{
|
||||
// start by reading original register data (only modifying what we need to)
|
||||
uint8_t OrigRegData = _sing_reg_read(RegAdd);
|
||||
|
||||
// calculate new register data... 'delete' old targeted data, replace with new data
|
||||
// note: 'DataMask' must be bits targeted for replacement
|
||||
// add'l note: this function does NOT shift values into the proper place... they need to be there already
|
||||
uint8_t NewRegData = ((OrigRegData & ~DataMask) | (RegData & DataMask));
|
||||
|
||||
// now configure and write the updated register value
|
||||
digitalWrite(_cs, LOW); // set pin low to start talking to IC
|
||||
// next pack command byte, send AS3935.... structure is shown below
|
||||
// MODE Register Address/Direct Cmd
|
||||
// B15-14 B13------------------8
|
||||
// 15 is always 0; B14, 0: Write/Direct Command, 1: Read
|
||||
SPI.transfer((RegAdd & 0x3F)); // simple write, nothing to read back
|
||||
SPI.transfer(RegData); // write register data to IC
|
||||
digitalWrite(_cs, HIGH); // set pin high to end SPI session
|
||||
}
|
||||
|
||||
void PWF_AS3935::AS3935_DefInit()
|
||||
{
|
||||
_AS3935_Reset(); // reset registers to default
|
||||
}
|
||||
|
||||
void PWF_AS3935::_AS3935_Reset()
|
||||
{
|
||||
// run PRESET_DEFAULT Direct Command to set all registers in default state
|
||||
digitalWrite(_cs, LOW); // begin transfer
|
||||
SPI.transfer(0x3C); // send first byte (write, PRESET_DEFAULT register)
|
||||
SPI.transfer(0x96); // send second byte (direct command)
|
||||
digitalWrite(_cs, HIGH); // end transfer
|
||||
delay(2); // wait 2ms to complete
|
||||
}
|
||||
|
||||
void PWF_AS3935::_CalRCO()
|
||||
{
|
||||
// run ALIB_RCO Direct Command to cal internal RCO
|
||||
digitalWrite(_cs, LOW); // begin transfer
|
||||
SPI.transfer(0x3D); // send first byte (write, CALIB_RCO register)
|
||||
SPI.transfer(0x96); // send second byte (direct command)
|
||||
digitalWrite(_cs, HIGH); // end transfer
|
||||
delay(3); // wait 3ms to complete
|
||||
}
|
||||
|
||||
void PWF_AS3935::AS3935_PowerUp(void)
|
||||
{
|
||||
// power-up sequence based on datasheet, pg 23/27
|
||||
// register 0x00, PWD bit: 0 (clears PWD)
|
||||
_sing_reg_write(0x00, 0x01, 0x00);
|
||||
_CalRCO(); // run RCO cal cmd
|
||||
_sing_reg_write(0x08, 0x20, 0x20); // set DISP_SRCO to 1
|
||||
delay(2);
|
||||
_sing_reg_write(0x08, 0x20, 0x00); // set DISP_SRCO to 0
|
||||
|
||||
}
|
||||
|
||||
void PWF_AS3935::AS3935_PowerDown(void)
|
||||
{
|
||||
// register 0x00, PWD bit: 0 (sets PWD)
|
||||
_sing_reg_write(0x00, 0x01, 0x01);
|
||||
Serial.println("AS3935 powered down");
|
||||
}
|
||||
|
||||
void PWF_AS3935::AS3935_DisturberEn(void)
|
||||
{
|
||||
// register 0x03, PWD bit: 5 (sets MASK_DIST)
|
||||
_sing_reg_write(0x03, 0x20, 0x00);
|
||||
Serial.println("disturber detection enabled");
|
||||
}
|
||||
|
||||
void PWF_AS3935::AS3935_DisturberDis(void)
|
||||
{
|
||||
// register 0x03, PWD bit: 5 (sets MASK_DIST)
|
||||
_sing_reg_write(0x03, 0x20, 0x20);
|
||||
}
|
||||
|
||||
void PWF_AS3935::AS3935_SetIRQ_Output_Source(uint8_t irq_select)
|
||||
{
|
||||
// set interrupt source - what to displlay on IRQ pin
|
||||
// reg 0x08, bits 5 (TRCO), 6 (SRCO), 7 (LCO)
|
||||
// only one should be set at once, I think
|
||||
// 0 = NONE, 1 = TRCO, 2 = SRCO, 3 = LCO
|
||||
|
||||
if(1 == irq_select)
|
||||
{
|
||||
_sing_reg_write(0x08, 0xE0, 0x20); // set only TRCO bit
|
||||
}
|
||||
else if(2 == irq_select)
|
||||
{
|
||||
_sing_reg_write(0x08, 0xE0, 0x40); // set only SRCO bit
|
||||
}
|
||||
else if(3 == irq_select)
|
||||
{
|
||||
_sing_reg_write(0x08, 0xE0, 0x80); // set only LCO bit
|
||||
}
|
||||
else // assume 0
|
||||
{
|
||||
_sing_reg_write(0x08, 0xE0, 0x00); // clear IRQ pin display bits
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void PWF_AS3935::AS3935_SetTuningCaps(uint8_t cap_val)
|
||||
{
|
||||
// Assume only numbers divisible by 8 (because that's all the chip supports)
|
||||
if(120 < cap_val) // cap_value out of range, assume highest capacitance
|
||||
{
|
||||
_sing_reg_write(0x08, 0x0F, 0x0F); // set capacitance bits to maximum
|
||||
}
|
||||
else
|
||||
{
|
||||
_sing_reg_write(0x08, 0x0F, (cap_val>>3)); // set capacitance bits
|
||||
}
|
||||
Serial.print("capacitance set to 8x");
|
||||
Serial.println((_sing_reg_read(0x08) & 0x0F));
|
||||
}
|
||||
|
||||
uint8_t PWF_AS3935::AS3935_GetInterruptSrc(void)
|
||||
{
|
||||
// definition of interrupt data on table 18 of datasheet
|
||||
// for this function:
|
||||
// 0 = unknown src, 1 = lightning detected, 2 = disturber, 3 = Noise level too high
|
||||
delay(10); // wait 10ms before reading (2ms per pg 22 of datasheet)
|
||||
uint8_t int_src = (_sing_reg_read(0x03) & 0x0F); // read register, get rid of non-interrupt data
|
||||
if(0x08 == int_src)
|
||||
{
|
||||
return 1; // lightning caused interrupt
|
||||
}
|
||||
else if(0x04 == int_src)
|
||||
{
|
||||
return 2; // disturber detected
|
||||
}
|
||||
else if(0x01 == int_src)
|
||||
{
|
||||
return 3; // Noise level too high
|
||||
}
|
||||
else{return 0;} // interrupt result not expected
|
||||
|
||||
}
|
||||
|
||||
uint8_t PWF_AS3935::AS3935_GetLightningDistKm(void)
|
||||
{
|
||||
uint8_t strike_dist = (_sing_reg_read(0x07) & 0x3F); // read register, get rid of non-distance data
|
||||
return strike_dist;
|
||||
}
|
||||
|
||||
uint32_t PWF_AS3935::AS3935_GetStrikeEnergyRaw(void)
|
||||
{
|
||||
uint32_t nrgy_raw = ((_sing_reg_read(0x06) & 0x1F) << 8); // MMSB, shift 8 bits left, make room for MSB
|
||||
nrgy_raw |= _sing_reg_read(0x05); // read MSB
|
||||
nrgy_raw <= 8; // shift 8 bits left, make room for LSB
|
||||
nrgy_raw |= _sing_reg_read(0x04); // read LSB, add to others
|
||||
|
||||
return nrgy_raw;
|
||||
}
|
||||
|
||||
uint8_t PWF_AS3935::AS3935_SetMinStrikes(uint8_t min_strk)
|
||||
{
|
||||
// This function sets min strikes to the closest available number, rounding to the floor,
|
||||
// where necessary, then returns the physical value that was set. Options are 1, 5, 9 or 16 strikes.
|
||||
// see pg 22 of the datasheet for more info (#strikes in 17 min)
|
||||
if(5 > min_strk)
|
||||
{
|
||||
_sing_reg_write(0x02, 0x30, 0x00);
|
||||
return 1;
|
||||
}
|
||||
else if(9 > min_strk)
|
||||
{
|
||||
_sing_reg_write(0x02, 0x30, 0x10);
|
||||
return 5;
|
||||
}
|
||||
else if(16 > min_strk)
|
||||
{
|
||||
_sing_reg_write(0x02, 0x30, 0x20);
|
||||
return 9;
|
||||
}
|
||||
else
|
||||
{
|
||||
_sing_reg_write(0x02, 0x30, 0x30);
|
||||
return 16;
|
||||
}
|
||||
}
|
||||
|
||||
void PWF_AS3935::AS3935_SetIndoors(void)
|
||||
{
|
||||
// AFE settings addres 0x00, bits 5:1 (10010, based on datasheet, pg 19, table 15)
|
||||
// this is the default setting at power-up (AS3935 datasheet, table 9)
|
||||
_sing_reg_write(0x00, 0x3E, 0x24);
|
||||
Serial.println("set up for indoor operation");
|
||||
}
|
||||
|
||||
void PWF_AS3935::AS3935_SetOutdoors(void)
|
||||
{
|
||||
// AFE settings addres 0x00, bits 5:1 (01110, based on datasheet, pg 19, table 15)
|
||||
_sing_reg_write(0x00, 0x3E, 0x1C);
|
||||
Serial.println("set up for outdoor operation");
|
||||
}
|
||||
|
||||
void PWF_AS3935::AS3935_ClearStatistics(void)
|
||||
{
|
||||
// clear is accomplished by toggling CL_STAT bit 'high-low-high' (then set low to move on)
|
||||
_sing_reg_write(0x02, 0x40, 0x40); // high
|
||||
_sing_reg_write(0x02, 0x40, 0x00); // low
|
||||
_sing_reg_write(0x02, 0x40, 0x40); // high
|
||||
}
|
||||
|
||||
uint8_t PWF_AS3935::AS3935_GetNoiseFloorLvl(void)
|
||||
{
|
||||
// NF settings addres 0x01, bits 6:4
|
||||
// default setting of 010 at startup (datasheet, table 9)
|
||||
uint8_t reg_raw = _sing_reg_read(0x01); // read register 0x01
|
||||
return ((reg_raw & 0x70)>>4); // should return value from 0-7, see table 16 for info
|
||||
}
|
||||
|
||||
void PWF_AS3935::AS3935_SetNoiseFloorLvl(uint8_t nf_sel)
|
||||
{
|
||||
// NF settings addres 0x01, bits 6:4
|
||||
// default setting of 010 at startup (datasheet, table 9)
|
||||
if(7 >= nf_sel) // nf_sel within expected range
|
||||
{
|
||||
_sing_reg_write(0x01, 0x70, ((nf_sel & 0x07)<<4));
|
||||
}
|
||||
else
|
||||
{ // out of range, set to default (power-up value 010)
|
||||
_sing_reg_write(0x01, 0x70, 0x20);
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t PWF_AS3935::AS3935_GetWatchdogThreshold(void)
|
||||
{
|
||||
// This function is used to read WDTH. It is used to increase robustness to disturbers,
|
||||
// though will make detection less efficient (see page 19, Fig 20 of datasheet)
|
||||
// WDTH register: add 0x01, bits 3:0
|
||||
// default value of 0001
|
||||
// values should only be between 0x00 and 0x0F (0 and 7)
|
||||
uint8_t reg_raw = _sing_reg_read(0x01);
|
||||
return (reg_raw & 0x0F);
|
||||
}
|
||||
|
||||
void PWF_AS3935::AS3935_SetWatchdogThreshold(uint8_t wdth)
|
||||
{
|
||||
// This function is used to modify WDTH. It is used to increase robustness to disturbers,
|
||||
// though will make detection less efficient (see page 19, Fig 20 of datasheet)
|
||||
// WDTH register: add 0x01, bits 3:0
|
||||
// default value of 0001
|
||||
// values should only be between 0x00 and 0x0F (0 and 7)
|
||||
_sing_reg_write(0x01, 0x0F, (wdth & 0x0F));
|
||||
}
|
||||
|
||||
uint8_t PWF_AS3935::AS3935_GetSpikeRejection(void)
|
||||
{
|
||||
// This function is used to read SREJ (spike rejection). Similar to the Watchdog threshold,
|
||||
// it is used to make the system more robust to disturbers, though will make general detection
|
||||
// less efficient (see page 20-21, especially Fig 21 of datasheet)
|
||||
// SREJ register: add 0x02, bits 3:0
|
||||
// default value of 0010
|
||||
// values should only be between 0x00 and 0x0F (0 and 7)
|
||||
uint8_t reg_raw = _sing_reg_read(0x02);
|
||||
return (reg_raw & 0x0F);
|
||||
}
|
||||
|
||||
void PWF_AS3935::AS3935_SetSpikeRejection(uint8_t srej)
|
||||
{
|
||||
// This function is used to modify SREJ (spike rejection). Similar to the Watchdog threshold,
|
||||
// it is used to make the system more robust to disturbers, though will make general detection
|
||||
// less efficient (see page 20-21, especially Fig 21 of datasheet)
|
||||
// WDTH register: add 0x02, bits 3:0
|
||||
// default value of 0010
|
||||
// values should only be between 0x00 and 0x0F (0 and 7)
|
||||
_sing_reg_write(0x02, 0x0F, (srej & 0x0F));
|
||||
}
|
||||
|
||||
void PWF_AS3935::AS3935_SetLCO_FDIV(uint8_t fdiv)
|
||||
{
|
||||
// This function sets LCO_FDIV register. This is useful in the tuning of the antenna
|
||||
// LCO_FDIV register: add 0x03, bits 7:6
|
||||
// default value: 00
|
||||
// set 0, 1, 2 or 3 for ratios of 16, 32, 64 and 128, respectively.
|
||||
// See pg 23, Table 20 for more info.
|
||||
_sing_reg_write(0x03, 0xC0, ((fdiv & 0x03) << 5));
|
||||
}
|
||||
|
||||
void PWF_AS3935::AS3935_PrintAllRegs(void)
|
||||
{
|
||||
Serial.print("Reg 0x00: ");
|
||||
Serial.println(_sing_reg_read(0x00));
|
||||
Serial.print("Reg 0x01: ");
|
||||
Serial.println(_sing_reg_read(0x01));
|
||||
Serial.print("Reg 0x02: ");
|
||||
Serial.println(_sing_reg_read(0x02));
|
||||
Serial.print("Reg 0x03: ");
|
||||
Serial.println(_sing_reg_read(0x03));
|
||||
Serial.print("Reg 0x04: ");
|
||||
Serial.println(_sing_reg_read(0x04));
|
||||
Serial.print("Reg 0x05: ");
|
||||
Serial.println(_sing_reg_read(0x05));
|
||||
Serial.print("Reg 0x06: ");
|
||||
Serial.println(_sing_reg_read(0x06));
|
||||
Serial.print("Reg 0x07: ");
|
||||
Serial.println(_sing_reg_read(0x07));
|
||||
Serial.print("Reg 0x08: ");
|
||||
Serial.println(_sing_reg_read(0x08));
|
||||
uint32_t nrgy_val = AS3935_GetStrikeEnergyRaw();
|
||||
Serial.println(nrgy_val);
|
||||
}
|
||||
|
||||
void PWF_AS3935::AS3935_ManualCal(uint8_t capacitance, uint8_t location, uint8_t disturber)
|
||||
{
|
||||
// start by powering up
|
||||
AS3935_PowerUp();
|
||||
|
||||
// indoors/outdoors next...
|
||||
if(1 == location) // set outdoors if 1
|
||||
{
|
||||
AS3935_SetOutdoors();
|
||||
}
|
||||
else // set indoors if anything but 1
|
||||
{
|
||||
AS3935_SetIndoors();
|
||||
}
|
||||
|
||||
// disturber cal
|
||||
if(0 == disturber) // disabled if 0
|
||||
{
|
||||
AS3935_DisturberDis();
|
||||
}
|
||||
else // enabled if anything but 0
|
||||
{
|
||||
AS3935_DisturberEn();
|
||||
}
|
||||
|
||||
AS3935_SetIRQ_Output_Source(0);
|
||||
|
||||
delay(500);
|
||||
// capacitance first... directly write value here
|
||||
AS3935_SetTuningCaps(capacitance);
|
||||
|
||||
Serial.println("AS3935 manual cal complete");
|
||||
}
|
||||
// a nice function would be to read the last 'x' strike data values....
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
/***************************************************************************
|
||||
* File Name: PWFusion_AS3935.h
|
||||
* Processor/Platform: Arduino Uno R3 (tested)
|
||||
* Development Environment: Arduino 1.0.5
|
||||
*
|
||||
* Designed for use with with Playing With Fusion AS3935 Lightning Sensor
|
||||
* Breakout: SEN-39001.
|
||||
*
|
||||
* SEN-39001 (universal applications)
|
||||
* ---> http://www.playingwithfusion.com/productview.php?pdid=22
|
||||
*
|
||||
* Copyright © 2014 Playing With Fusion, Inc.
|
||||
* SOFTWARE LICENSE AGREEMENT: This code is released under the MIT License.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
* DEALINGS IN THE SOFTWARE.
|
||||
* **************************************************************************
|
||||
* REVISION HISTORY:
|
||||
* Author Date Comments
|
||||
* J. Steinlage 2014Aug20 Original version
|
||||
*
|
||||
* Playing With Fusion, Inc. invests time and resources developing open-source
|
||||
* code. Please support Playing With Fusion and continued open-source
|
||||
* development by buying products from Playing With Fusion!
|
||||
*
|
||||
* **************************************************************************
|
||||
* ADDITIONAL NOTES:
|
||||
* This file contains functions to interface with the AS3935 Franklin
|
||||
* Lightning Sensor manufactured by AMS. Originally designed for application
|
||||
* on the Arduino Uno platform.
|
||||
**************************************************************************/
|
||||
#ifndef PWF_AS3935_h
|
||||
#define PWF_AS3935_h
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "avr/pgmspace.h"
|
||||
#include "util/delay.h"
|
||||
#include "stdlib.h"
|
||||
#include "SPI.h"
|
||||
|
||||
class PWF_AS3935
|
||||
{
|
||||
public:
|
||||
PWF_AS3935(int8_t CSx, int8_t IRQx, int8_t SIx);
|
||||
void AS3935_ManualCal(uint8_t capacitance, uint8_t location, uint8_t disturber);
|
||||
void AS3935_DefInit(void);
|
||||
void AS3935_PowerUp(void);
|
||||
void AS3935_PowerDown(void);
|
||||
void AS3935_DisturberEn(void);
|
||||
void AS3935_DisturberDis(void);
|
||||
void AS3935_SetIRQ_Output_Source(uint8_t irq_select);
|
||||
void AS3935_SetTuningCaps(uint8_t cap_val);
|
||||
uint8_t AS3935_GetInterruptSrc(void);
|
||||
uint8_t AS3935_GetLightningDistKm(void);
|
||||
uint32_t AS3935_GetStrikeEnergyRaw(void);
|
||||
uint8_t AS3935_SetMinStrikes(uint8_t min_strk);
|
||||
void AS3935_ClearStatistics(void);
|
||||
void AS3935_SetIndoors(void);
|
||||
void AS3935_SetOutdoors(void);
|
||||
uint8_t AS3935_GetNoiseFloorLvl(void);
|
||||
void AS3935_SetNoiseFloorLvl(uint8_t nf_sel);
|
||||
uint8_t AS3935_GetWatchdogThreshold(void);
|
||||
void AS3935_SetWatchdogThreshold(uint8_t wdth);
|
||||
uint8_t AS3935_GetSpikeRejection(void);
|
||||
void AS3935_SetSpikeRejection(uint8_t srej);
|
||||
void AS3935_SetLCO_FDIV(uint8_t fdiv);
|
||||
void AS3935_PrintAllRegs(void);
|
||||
|
||||
private:
|
||||
int8_t _cs, _irq, _si;
|
||||
uint8_t _sing_reg_read(uint8_t RegAdd);
|
||||
void _sing_reg_write(uint8_t RegAdd, uint8_t DataMask, uint8_t RegData);
|
||||
void _AS3935_Reset(void);
|
||||
void _CalRCO(void);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
//
|
||||
// FILE: RunningAverage.cpp
|
||||
// AUTHOR: Rob Tillaart
|
||||
// VERSION: 0.2.08
|
||||
// DATE: 2015-apr-10
|
||||
// PURPOSE: RunningAverage library for Arduino
|
||||
//
|
||||
// The library stores N individual values in a circular buffer,
|
||||
// to calculate the running average.
|
||||
//
|
||||
// HISTORY:
|
||||
// 0.1.00 - 2011-01-30 initial version
|
||||
// 0.1.01 - 2011-02-28 fixed missing destructor in .h
|
||||
// 0.2.00 - 2012-??-?? Yuval Naveh added trimValue (found on web)
|
||||
// http://stromputer.googlecode.com/svn-history/r74/trunk/Arduino/Libraries/RunningAverage/RunningAverage.cpp
|
||||
// 0.2.01 - 2012-11-21 refactored
|
||||
// 0.2.02 - 2012-12-30 refactored trimValue -> fillValue
|
||||
// 0.2.03 - 2013-11-31 getElement
|
||||
// 0.2.04 - 2014-07-03 added memory protection
|
||||
// 0.2.05 - 2014-12-16 changed float -> double
|
||||
// 0.2.06 - 2015-03-07 all size uint8_t
|
||||
// 0.2.07 - 2015-03-16 added getMin() and getMax() functions (Eric Mulder)
|
||||
// 0.2.08 - 2015-04-10 refactored getMin() and getMax() implementation
|
||||
//
|
||||
// Released to the public domain
|
||||
//
|
||||
|
||||
#include "RunningAverage.h"
|
||||
#include <stdlib.h>
|
||||
|
||||
RunningAverage::RunningAverage(uint8_t size)
|
||||
{
|
||||
_size = size;
|
||||
_ar = (double*) malloc(_size * sizeof(double));
|
||||
if (_ar == NULL) _size = 0;
|
||||
clear();
|
||||
}
|
||||
|
||||
RunningAverage::~RunningAverage()
|
||||
{
|
||||
if (_ar != NULL) free(_ar);
|
||||
}
|
||||
|
||||
// resets all counters
|
||||
void RunningAverage::clear()
|
||||
{
|
||||
_cnt = 0;
|
||||
_idx = 0;
|
||||
_sum = 0.0;
|
||||
_min = NAN;
|
||||
_max = NAN;
|
||||
for (uint8_t i = 0; i < _size; i++)
|
||||
{
|
||||
_ar[i] = 0.0; // keeps addValue simple
|
||||
}
|
||||
}
|
||||
|
||||
// adds a new value to the data-set
|
||||
void RunningAverage::addValue(double value)
|
||||
{
|
||||
if (_ar == NULL) return; // allocation error
|
||||
_sum -= _ar[_idx];
|
||||
_ar[_idx] = value;
|
||||
_sum += _ar[_idx];
|
||||
_idx++;
|
||||
if (_idx == _size) _idx = 0; // faster than %
|
||||
// handle min max
|
||||
if (_cnt == 0) _min = _max = value;
|
||||
else if (value < _min) _min = value;
|
||||
else if (value > _max) _max = value;
|
||||
// update count as last otherwise if( _cnt == 0) above will fail
|
||||
if (_cnt < _size) _cnt++;
|
||||
}
|
||||
|
||||
// returns the average of the data-set added sofar
|
||||
double RunningAverage::getAverage()
|
||||
{
|
||||
if (_cnt == 0) return NAN;
|
||||
return _sum / _cnt;
|
||||
}
|
||||
|
||||
// returns the value of an element if exist, NAN otherwise
|
||||
double RunningAverage::getElement(uint8_t idx)
|
||||
{
|
||||
if (idx >=_cnt ) return NAN;
|
||||
return _ar[idx];
|
||||
}
|
||||
|
||||
// fill the average with a value
|
||||
// the param number determines how often value is added (weight)
|
||||
// number should preferably be between 1 and size
|
||||
void RunningAverage::fillValue(double value, uint8_t number)
|
||||
{
|
||||
clear(); // TODO conditional? if (clr) clear();
|
||||
|
||||
for (uint8_t i = 0; i < number; i++)
|
||||
{
|
||||
addValue(value);
|
||||
}
|
||||
}
|
||||
// END OF FILE
|
||||
@@ -0,0 +1,56 @@
|
||||
//
|
||||
// FILE: RunningAverage.h
|
||||
// AUTHOR: Rob dot Tillaart at gmail dot com
|
||||
// VERSION: 0.2.08
|
||||
// DATE: 2015-apr-10
|
||||
// PURPOSE: RunningAverage library for Arduino
|
||||
// URL: http://arduino.cc/playground/Main/RunningAverage
|
||||
// HISTORY: See RunningAverage.cpp
|
||||
//
|
||||
// Released to the public domain
|
||||
//
|
||||
// backwards compatibility
|
||||
// clr() clear()
|
||||
// add(x) addValue(x)
|
||||
// avg() getAverage()
|
||||
|
||||
#ifndef RunningAverage_h
|
||||
#define RunningAverage_h
|
||||
|
||||
#define RUNNINGAVERAGE_LIB_VERSION "0.2.08"
|
||||
|
||||
#include "Arduino.h"
|
||||
|
||||
class RunningAverage
|
||||
{
|
||||
public:
|
||||
RunningAverage(void);
|
||||
RunningAverage(uint8_t);
|
||||
~RunningAverage();
|
||||
|
||||
void clear();
|
||||
void addValue(double);
|
||||
void fillValue(double, uint8_t);
|
||||
|
||||
double getAverage();
|
||||
// returns lowest value added to the data-set since last clear
|
||||
double getMin() { return _min; };
|
||||
// returns highest value added to the data-set since last clear
|
||||
double getMax() { return _max; };
|
||||
|
||||
double getElement(uint8_t idx);
|
||||
uint8_t getSize() { return _size; }
|
||||
uint8_t getCount() { return _cnt; }
|
||||
|
||||
protected:
|
||||
uint8_t _size;
|
||||
uint8_t _cnt;
|
||||
uint8_t _idx;
|
||||
double _sum;
|
||||
double * _ar;
|
||||
double _min;
|
||||
double _max;
|
||||
};
|
||||
|
||||
#endif
|
||||
// END OF FILE
|
||||
@@ -0,0 +1,38 @@
|
||||
//
|
||||
// FILE: fillValue.pde
|
||||
// AUTHOR: Rob Tillaart
|
||||
// DATE: 2012-12-30
|
||||
//
|
||||
// PUPROSE: show working of fillValue
|
||||
//
|
||||
|
||||
#include "RunningAverage.h"
|
||||
|
||||
RunningAverage myRA(10);
|
||||
int samples = 0;
|
||||
|
||||
void setup(void)
|
||||
{
|
||||
Serial.begin(115200);
|
||||
Serial.print("Demo RunningAverage lib - fillValue ");
|
||||
Serial.print("Version: ");
|
||||
Serial.println(RUNNINGAVERAGE_LIB_VERSION);
|
||||
|
||||
myRA.fillValue(100,5);
|
||||
}
|
||||
|
||||
void loop(void)
|
||||
{
|
||||
long rn = random(0, 100);
|
||||
myRA.addValue(rn/100.0);
|
||||
samples++;
|
||||
Serial.print("Running Average: ");
|
||||
Serial.println(myRA.getAverage(), 4);
|
||||
|
||||
if (samples == 300)
|
||||
{
|
||||
samples = 0;
|
||||
myRA.fillValue(100, 10);
|
||||
}
|
||||
delay(100);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
//
|
||||
// FILE: runningAverageMinMaxTest.ino
|
||||
// AUTHOR: Rob Tillaart
|
||||
// VERSION: 0.1.00
|
||||
// DATE: 2015-apr-10
|
||||
//
|
||||
// PUPROSE: demo
|
||||
//
|
||||
|
||||
#include "RunningAverage.h"
|
||||
|
||||
RunningAverage myRA(10);
|
||||
int samples = 0;
|
||||
|
||||
void setup(void)
|
||||
{
|
||||
Serial.begin(115200);
|
||||
Serial.println("\nDemo runningAverageMinMaxTest");
|
||||
Serial.print("Version: ");
|
||||
Serial.println(RUNNINGAVERAGE_LIB_VERSION);
|
||||
myRA.clear(); // explicitly start clean
|
||||
|
||||
Serial.println("\nCNT\tMIN\tAVG\tMAX");
|
||||
}
|
||||
|
||||
void loop(void)
|
||||
{
|
||||
long rn = random(0, 1000);
|
||||
myRA.addValue(rn * 0.001);
|
||||
samples++;
|
||||
Serial.print(samples);
|
||||
Serial.print("\t");
|
||||
Serial.print(myRA.getMin(), 3);
|
||||
Serial.print("\t");
|
||||
Serial.print(myRA.getAverage(), 3);
|
||||
Serial.print("\t");
|
||||
Serial.println(myRA.getMax(), 3);
|
||||
|
||||
if (samples == 100)
|
||||
{
|
||||
samples = 0;
|
||||
myRA.clear();
|
||||
Serial.println("\nCNT\tMIN\tAVG\tMAX");
|
||||
}
|
||||
delay(10);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//
|
||||
// FILE: runningAverageHour.pde
|
||||
// AUTHOR: Rob Tillaart
|
||||
// DATE: 2012-12-30
|
||||
//
|
||||
// PUPROSE: show working of runningAverage per hour
|
||||
// in 2 steps - last minute + last hour
|
||||
// 3 or more steps also possible
|
||||
//
|
||||
|
||||
#include "RunningAverage.h"
|
||||
|
||||
RunningAverage raMinute(60);
|
||||
RunningAverage raHour(60);
|
||||
|
||||
int samples = 0;
|
||||
|
||||
void setup(void)
|
||||
{
|
||||
Serial.begin(115200);
|
||||
Serial.println("Demo RunningAverage lib - average per minute & hour");
|
||||
Serial.print("Version: ");
|
||||
Serial.println(RUNNINGAVERAGE_LIB_VERSION);
|
||||
raHour.clear();
|
||||
raMinute.clear();
|
||||
}
|
||||
|
||||
void loop(void)
|
||||
{
|
||||
long rn = random(0, 100);
|
||||
raMinute.addValue(rn);
|
||||
samples++;
|
||||
|
||||
if (samples % 60 == 0) raHour.addValue(raMinute.getAverage());
|
||||
|
||||
Serial.print(" raMinute: ");
|
||||
Serial.print(raMinute.getAverage(), 4);
|
||||
Serial.print(" raHour: ");
|
||||
Serial.println(raHour.getAverage(), 4);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//
|
||||
// FILE: runningAverageTest.pde
|
||||
// AUTHOR: Rob Tillaart
|
||||
// VERSION: 0.1.01
|
||||
// DATE: 2012-12-30
|
||||
//
|
||||
// PUPROSE: show working of runningAverage
|
||||
//
|
||||
|
||||
#include "RunningAverage.h"
|
||||
|
||||
RunningAverage myRA(10);
|
||||
int samples = 0;
|
||||
|
||||
void setup(void)
|
||||
{
|
||||
Serial.begin(115200);
|
||||
Serial.println("Demo RunningAverage lib");
|
||||
Serial.print("Version: ");
|
||||
Serial.println(RUNNINGAVERAGE_LIB_VERSION);
|
||||
myRA.clear(); // explicitly start clean
|
||||
}
|
||||
|
||||
void loop(void)
|
||||
{
|
||||
long rn = random(0, 1000);
|
||||
myRA.addValue(rn * 0.001);
|
||||
samples++;
|
||||
Serial.print(samples);
|
||||
Serial.print("\t Running Average: ");
|
||||
Serial.println(myRA.getAverage(), 3);
|
||||
|
||||
if (samples == 300)
|
||||
{
|
||||
samples = 0;
|
||||
myRA.clear();
|
||||
Serial.println();
|
||||
}
|
||||
delay(10);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
#######################################
|
||||
# Syntax Coloring Map For RunningAverage
|
||||
#######################################
|
||||
|
||||
#######################################
|
||||
# Datatypes (KEYWORD1)
|
||||
#######################################
|
||||
|
||||
RunningAverage KEYWORD1
|
||||
|
||||
#######################################
|
||||
# Methods and Functions (KEYWORD2)
|
||||
#######################################
|
||||
|
||||
clear KEYWORD2
|
||||
addValue KEYWORD2
|
||||
getAverage KEYWORD2
|
||||
getMin KEYWORD2
|
||||
getMax KEYWORD2
|
||||
fillValue KEYWORD2
|
||||
getElement KEYWORD2
|
||||
getSize KEYWORD2
|
||||
getCount KEYWORD2
|
||||
|
||||
#######################################
|
||||
# Instances (KEYWORD2)
|
||||
#######################################
|
||||
|
||||
|
||||
#######################################
|
||||
# Constants (LITERAL1)
|
||||
#######################################
|
||||
Reference in New Issue
Block a user