diff --git a/AVR/lib/RF24/Doxyfile b/AVR/lib/RF24/Doxyfile deleted file mode 100644 index 4604afc..0000000 --- a/AVR/lib/RF24/Doxyfile +++ /dev/null @@ -1,1551 +0,0 @@ -# Doxyfile 1.6.3 - -# This file describes the settings to be used by the documentation system -# doxygen (www.doxygen.org) for a project -# -# All text after a hash (#) is considered a comment and will be ignored -# The format is: -# TAG = value [value, ...] -# For lists items can also be appended using: -# TAG += value [value, ...] -# Values that contain spaces should be placed between quotes (" ") - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- - -# This tag specifies the encoding used for all characters in the config file -# that follow. The default is UTF-8 which is also the encoding used for all -# text before the first occurrence of this tag. Doxygen uses libiconv (or the -# iconv built into libc) for the transcoding. See -# http://www.gnu.org/software/libiconv for the list of possible encodings. - -DOXYFILE_ENCODING = UTF-8 - -# The PROJECT_NAME tag is a single word (or a sequence of words surrounded -# by quotes) that should identify the project. - -PROJECT_NAME = RF24 - -# The PROJECT_NUMBER tag can be used to enter a project or revision number. -# This could be handy for archiving the generated documentation or -# if some version control system is used. - -PROJECT_NUMBER = v1 - -# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) -# base path where the generated documentation will be put. -# If a relative path is entered, it will be relative to the location -# where doxygen was started. If left blank the current directory will be used. - -OUTPUT_DIRECTORY = docs - -# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create -# 4096 sub-directories (in 2 levels) under the output directory of each output -# format and will distribute the generated files over these directories. -# Enabling this option can be useful when feeding doxygen a huge amount of -# source files, where putting all generated files in the same directory would -# otherwise cause performance problems for the file system. - -CREATE_SUBDIRS = NO - -# The OUTPUT_LANGUAGE tag is used to specify the language in which all -# documentation generated by doxygen is written. Doxygen will use this -# information to generate all constant output in the proper language. -# The default language is English, other supported languages are: -# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, -# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, -# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English -# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, -# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak, -# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. - -OUTPUT_LANGUAGE = English - -# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will -# include brief member descriptions after the members that are listed in -# the file and class documentation (similar to JavaDoc). -# Set to NO to disable this. - -BRIEF_MEMBER_DESC = YES - -# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend -# the brief description of a member or function before the detailed description. -# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the -# brief descriptions will be completely suppressed. - -REPEAT_BRIEF = YES - -# This tag implements a quasi-intelligent brief description abbreviator -# that is used to form the text in various listings. Each string -# in this list, if found as the leading text of the brief description, will be -# stripped from the text and the result after processing the whole list, is -# used as the annotated text. Otherwise, the brief description is used as-is. -# If left blank, the following values are used ("$name" is automatically -# replaced with the name of the entity): "The $name class" "The $name widget" -# "The $name file" "is" "provides" "specifies" "contains" -# "represents" "a" "an" "the" - -ABBREVIATE_BRIEF = - -# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then -# Doxygen will generate a detailed section even if there is only a brief -# description. - -ALWAYS_DETAILED_SEC = NO - -# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all -# inherited members of a class in the documentation of that class as if those -# members were ordinary class members. Constructors, destructors and assignment -# operators of the base classes will not be shown. - -INLINE_INHERITED_MEMB = NO - -# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full -# path before files name in the file list and in the header files. If set -# to NO the shortest path that makes the file name unique will be used. - -FULL_PATH_NAMES = YES - -# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag -# can be used to strip a user-defined part of the path. Stripping is -# only done if one of the specified strings matches the left-hand part of -# the path. The tag can be used to show relative paths in the file list. -# If left blank the directory from which doxygen is run is used as the -# path to strip. - -STRIP_FROM_PATH = - -# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of -# the path mentioned in the documentation of a class, which tells -# the reader which header file to include in order to use a class. -# If left blank only the name of the header file containing the class -# definition is used. Otherwise one should specify the include paths that -# are normally passed to the compiler using the -I flag. - -STRIP_FROM_INC_PATH = - -# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter -# (but less readable) file names. This can be useful is your file systems -# doesn't support long names like on DOS, Mac, or CD-ROM. - -SHORT_NAMES = NO - -# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen -# will interpret the first line (until the first dot) of a JavaDoc-style -# comment as the brief description. If set to NO, the JavaDoc -# comments will behave just like regular Qt-style comments -# (thus requiring an explicit @brief command for a brief description.) - -JAVADOC_AUTOBRIEF = YES - -# If the QT_AUTOBRIEF tag is set to YES then Doxygen will -# interpret the first line (until the first dot) of a Qt-style -# comment as the brief description. If set to NO, the comments -# will behave just like regular Qt-style comments (thus requiring -# an explicit \brief command for a brief description.) - -QT_AUTOBRIEF = YES - -# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen -# treat a multi-line C++ special comment block (i.e. a block of //! or /// -# comments) as a brief description. This used to be the default behaviour. -# The new default is to treat a multi-line C++ comment block as a detailed -# description. Set this tag to YES if you prefer the old behaviour instead. - -MULTILINE_CPP_IS_BRIEF = NO - -# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented -# member inherits the documentation from any documented member that it -# re-implements. - -INHERIT_DOCS = YES - -# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce -# a new page for each member. If set to NO, the documentation of a member will -# be part of the file/class/namespace that contains it. - -SEPARATE_MEMBER_PAGES = NO - -# The TAB_SIZE tag can be used to set the number of spaces in a tab. -# Doxygen uses this value to replace tabs by spaces in code fragments. - -TAB_SIZE = 8 - -# This tag can be used to specify a number of aliases that acts -# as commands in the documentation. An alias has the form "name=value". -# For example adding "sideeffect=\par Side Effects:\n" will allow you to -# put the command \sideeffect (or @sideeffect) in the documentation, which -# will result in a user-defined paragraph with heading "Side Effects:". -# You can put \n's in the value part of an alias to insert newlines. - -ALIASES = - -# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C -# sources only. Doxygen will then generate output that is more tailored for C. -# For instance, some of the names that are used will be different. The list -# of all members will be omitted, etc. - -OPTIMIZE_OUTPUT_FOR_C = NO - -# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java -# sources only. Doxygen will then generate output that is more tailored for -# Java. For instance, namespaces will be presented as packages, qualified -# scopes will look different, etc. - -OPTIMIZE_OUTPUT_JAVA = NO - -# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran -# sources only. Doxygen will then generate output that is more tailored for -# Fortran. - -OPTIMIZE_FOR_FORTRAN = NO - -# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL -# sources. Doxygen will then generate output that is tailored for -# VHDL. - -OPTIMIZE_OUTPUT_VHDL = NO - -# Doxygen selects the parser to use depending on the extension of the files it parses. -# With this tag you can assign which parser to use for a given extension. -# Doxygen has a built-in mapping, but you can override or extend it using this tag. -# The format is ext=language, where ext is a file extension, and language is one of -# the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP, -# Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat -# .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran), -# use: inc=Fortran f=C. Note that for custom extensions you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. - -EXTENSION_MAPPING = - -# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want -# to include (a tag file for) the STL sources as input, then you should -# set this tag to YES in order to let doxygen match functions declarations and -# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. -# func(std::string) {}). This also make the inheritance and collaboration -# diagrams that involve STL classes more complete and accurate. - -BUILTIN_STL_SUPPORT = NO - -# If you use Microsoft's C++/CLI language, you should set this option to YES to -# enable parsing support. - -CPP_CLI_SUPPORT = NO - -# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. -# Doxygen will parse them like normal C++ but will assume all classes use public -# instead of private inheritance when no explicit protection keyword is present. - -SIP_SUPPORT = NO - -# For Microsoft's IDL there are propget and propput attributes to indicate getter -# and setter methods for a property. Setting this option to YES (the default) -# will make doxygen to replace the get and set methods by a property in the -# documentation. This will only work if the methods are indeed getting or -# setting a simple type. If this is not the case, or you want to show the -# methods anyway, you should set this option to NO. - -IDL_PROPERTY_SUPPORT = YES - -# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC -# tag is set to YES, then doxygen will reuse the documentation of the first -# member in the group (if any) for the other members of the group. By default -# all members of a group must be documented explicitly. - -DISTRIBUTE_GROUP_DOC = NO - -# Set the SUBGROUPING tag to YES (the default) to allow class member groups of -# the same type (for instance a group of public functions) to be put as a -# subgroup of that type (e.g. under the Public Functions section). Set it to -# NO to prevent subgrouping. Alternatively, this can be done per class using -# the \nosubgrouping command. - -SUBGROUPING = YES - -# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum -# is documented as struct, union, or enum with the name of the typedef. So -# typedef struct TypeS {} TypeT, will appear in the documentation as a struct -# with name TypeT. When disabled the typedef will appear as a member of a file, -# namespace, or class. And the struct will be named TypeS. This can typically -# be useful for C code in case the coding convention dictates that all compound -# types are typedef'ed and only the typedef is referenced, never the tag name. - -TYPEDEF_HIDES_STRUCT = NO - -# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to -# determine which symbols to keep in memory and which to flush to disk. -# When the cache is full, less often used symbols will be written to disk. -# For small to medium size projects (<1000 input files) the default value is -# probably good enough. For larger projects a too small cache size can cause -# doxygen to be busy swapping symbols to and from disk most of the time -# causing a significant performance penality. -# If the system has enough physical memory increasing the cache will improve the -# performance by keeping more symbols in memory. Note that the value works on -# a logarithmic scale so increasing the size by one will rougly double the -# memory usage. The cache size is given by this formula: -# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, -# corresponding to a cache size of 2^16 = 65536 symbols - -SYMBOL_CACHE_SIZE = 0 - -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- - -# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in -# documentation are documented, even if no documentation was available. -# Private class members and static file members will be hidden unless -# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES - -EXTRACT_ALL = NO - -# If the EXTRACT_PRIVATE tag is set to YES all private members of a class -# will be included in the documentation. - -EXTRACT_PRIVATE = NO - -# If the EXTRACT_STATIC tag is set to YES all static members of a file -# will be included in the documentation. - -EXTRACT_STATIC = NO - -# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) -# defined locally in source files will be included in the documentation. -# If set to NO only classes defined in header files are included. - -EXTRACT_LOCAL_CLASSES = YES - -# This flag is only useful for Objective-C code. When set to YES local -# methods, which are defined in the implementation section but not in -# the interface are included in the documentation. -# If set to NO (the default) only methods in the interface are included. - -EXTRACT_LOCAL_METHODS = NO - -# If this flag is set to YES, the members of anonymous namespaces will be -# extracted and appear in the documentation as a namespace called -# 'anonymous_namespace{file}', where file will be replaced with the base -# name of the file that contains the anonymous namespace. By default -# anonymous namespace are hidden. - -EXTRACT_ANON_NSPACES = NO - -# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all -# undocumented members of documented classes, files or namespaces. -# If set to NO (the default) these members will be included in the -# various overviews, but no documentation section is generated. -# This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_MEMBERS = NO - -# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all -# undocumented classes that are normally visible in the class hierarchy. -# If set to NO (the default) these classes will be included in the various -# overviews. This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_CLASSES = NO - -# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all -# friend (class|struct|union) declarations. -# If set to NO (the default) these declarations will be included in the -# documentation. - -HIDE_FRIEND_COMPOUNDS = NO - -# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any -# documentation blocks found inside the body of a function. -# If set to NO (the default) these blocks will be appended to the -# function's detailed documentation block. - -HIDE_IN_BODY_DOCS = NO - -# The INTERNAL_DOCS tag determines if documentation -# that is typed after a \internal command is included. If the tag is set -# to NO (the default) then the documentation will be excluded. -# Set it to YES to include the internal documentation. - -INTERNAL_DOCS = NO - -# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate -# file names in lower-case letters. If set to YES upper-case letters are also -# allowed. This is useful if you have classes or files whose names only differ -# in case and if your file system supports case sensitive file names. Windows -# and Mac users are advised to set this option to NO. - -CASE_SENSE_NAMES = YES - -# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen -# will show members with their full class and namespace scopes in the -# documentation. If set to YES the scope will be hidden. - -HIDE_SCOPE_NAMES = NO - -# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen -# will put a list of the files that are included by a file in the documentation -# of that file. - -SHOW_INCLUDE_FILES = YES - -# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen -# will list include files with double quotes in the documentation -# rather than with sharp brackets. - -FORCE_LOCAL_INCLUDES = NO - -# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] -# is inserted in the documentation for inline members. - -INLINE_INFO = YES - -# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen -# will sort the (detailed) documentation of file and class members -# alphabetically by member name. If set to NO the members will appear in -# declaration order. - -SORT_MEMBER_DOCS = YES - -# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the -# brief documentation of file, namespace and class members alphabetically -# by member name. If set to NO (the default) the members will appear in -# declaration order. - -SORT_BRIEF_DOCS = NO - -# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the (brief and detailed) documentation of class members so that constructors and destructors are listed first. If set to NO (the default) the constructors will appear in the respective orders defined by SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. - -SORT_MEMBERS_CTORS_1ST = NO - -# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the -# hierarchy of group names into alphabetical order. If set to NO (the default) -# the group names will appear in their defined order. - -SORT_GROUP_NAMES = NO - -# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be -# sorted by fully-qualified names, including namespaces. If set to -# NO (the default), the class list will be sorted only by class name, -# not including the namespace part. -# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. -# Note: This option applies only to the class list, not to the -# alphabetical list. - -SORT_BY_SCOPE_NAME = NO - -# The GENERATE_TODOLIST tag can be used to enable (YES) or -# disable (NO) the todo list. This list is created by putting \todo -# commands in the documentation. - -GENERATE_TODOLIST = YES - -# The GENERATE_TESTLIST tag can be used to enable (YES) or -# disable (NO) the test list. This list is created by putting \test -# commands in the documentation. - -GENERATE_TESTLIST = YES - -# The GENERATE_BUGLIST tag can be used to enable (YES) or -# disable (NO) the bug list. This list is created by putting \bug -# commands in the documentation. - -GENERATE_BUGLIST = YES - -# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or -# disable (NO) the deprecated list. This list is created by putting -# \deprecated commands in the documentation. - -GENERATE_DEPRECATEDLIST= YES - -# The ENABLED_SECTIONS tag can be used to enable conditional -# documentation sections, marked by \if sectionname ... \endif. - -ENABLED_SECTIONS = - -# The MAX_INITIALIZER_LINES tag determines the maximum number of lines -# the initial value of a variable or define consists of for it to appear in -# the documentation. If the initializer consists of more lines than specified -# here it will be hidden. Use a value of 0 to hide initializers completely. -# The appearance of the initializer of individual variables and defines in the -# documentation can be controlled using \showinitializer or \hideinitializer -# command in the documentation regardless of this setting. - -MAX_INITIALIZER_LINES = 30 - -# Set the SHOW_USED_FILES tag to NO to disable the list of files generated -# at the bottom of the documentation of classes and structs. If set to YES the -# list will mention the files that were used to generate the documentation. - -SHOW_USED_FILES = YES - -# If the sources in your project are distributed over multiple directories -# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy -# in the documentation. The default is NO. - -SHOW_DIRECTORIES = NO - -# Set the SHOW_FILES tag to NO to disable the generation of the Files page. -# This will remove the Files entry from the Quick Index and from the -# Folder Tree View (if specified). The default is YES. - -SHOW_FILES = YES - -# Set the SHOW_NAMESPACES tag to NO to disable the generation of the -# Namespaces page. -# This will remove the Namespaces entry from the Quick Index -# and from the Folder Tree View (if specified). The default is YES. - -SHOW_NAMESPACES = YES - -# The FILE_VERSION_FILTER tag can be used to specify a program or script that -# doxygen should invoke to get the current version for each file (typically from -# the version control system). Doxygen will invoke the program by executing (via -# popen()) the command , where is the value of -# the FILE_VERSION_FILTER tag, and is the name of an input file -# provided by doxygen. Whatever the program writes to standard output -# is used as the file version. See the manual for examples. - -FILE_VERSION_FILTER = - -# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by -# doxygen. The layout file controls the global structure of the generated output files -# in an output format independent way. The create the layout file that represents -# doxygen's defaults, run doxygen with the -l option. You can optionally specify a -# file name after the option, if omitted DoxygenLayout.xml will be used as the name -# of the layout file. - -LAYOUT_FILE = - -#--------------------------------------------------------------------------- -# configuration options related to warning and progress messages -#--------------------------------------------------------------------------- - -# The QUIET tag can be used to turn on/off the messages that are generated -# by doxygen. Possible values are YES and NO. If left blank NO is used. - -QUIET = NO - -# The WARNINGS tag can be used to turn on/off the warning messages that are -# generated by doxygen. Possible values are YES and NO. If left blank -# NO is used. - -WARNINGS = YES - -# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings -# for undocumented members. If EXTRACT_ALL is set to YES then this flag will -# automatically be disabled. - -WARN_IF_UNDOCUMENTED = YES - -# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for -# potential errors in the documentation, such as not documenting some -# parameters in a documented function, or documenting parameters that -# don't exist or using markup commands wrongly. - -WARN_IF_DOC_ERROR = YES - -# This WARN_NO_PARAMDOC option can be abled to get warnings for -# functions that are documented, but have no documentation for their parameters -# or return value. If set to NO (the default) doxygen will only warn about -# wrong or incomplete parameter documentation, but not about the absence of -# documentation. - -WARN_NO_PARAMDOC = NO - -# The WARN_FORMAT tag determines the format of the warning messages that -# doxygen can produce. The string should contain the $file, $line, and $text -# tags, which will be replaced by the file and line number from which the -# warning originated and the warning text. Optionally the format may contain -# $version, which will be replaced by the version of the file (if it could -# be obtained via FILE_VERSION_FILTER) - -WARN_FORMAT = "$file:$line: $text" - -# The WARN_LOGFILE tag can be used to specify a file to which warning -# and error messages should be written. If left blank the output is written -# to stderr. - -WARN_LOGFILE = - -#--------------------------------------------------------------------------- -# configuration options related to the input files -#--------------------------------------------------------------------------- - -# The INPUT tag can be used to specify the files and/or directories that contain -# documented source files. You may enter file names like "myfile.cpp" or -# directories like "/usr/src/myproject". Separate the files or directories -# with spaces. - -INPUT = . - -# This tag can be used to specify the character encoding of the source files -# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is -# also the default input encoding. Doxygen uses libiconv (or the iconv built -# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for -# the list of possible encodings. - -INPUT_ENCODING = UTF-8 - -# If the value of the INPUT tag contains directories, you can use the -# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp -# and *.h) to filter out the source-files in the directories. If left -# blank the following patterns are tested: -# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx -# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90 - -FILE_PATTERNS = *.h FAQ - -# The RECURSIVE tag can be used to turn specify whether or not subdirectories -# should be searched for input files as well. Possible values are YES and NO. -# If left blank NO is used. - -RECURSIVE = NO - -# The EXCLUDE tag can be used to specify files and/or directories that should -# excluded from the INPUT source files. This way you can easily exclude a -# subdirectory from a directory tree whose root is specified with the INPUT tag. - -EXCLUDE = - -# The EXCLUDE_SYMLINKS tag can be used select whether or not files or -# directories that are symbolic links (a Unix filesystem feature) are excluded -# from the input. - -EXCLUDE_SYMLINKS = NO - -# If the value of the INPUT tag contains directories, you can use the -# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude -# certain files from those directories. Note that the wildcards are matched -# against the file with absolute path, so to exclude all test directories -# for example use the pattern */test/* - -EXCLUDE_PATTERNS = - -# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names -# (namespaces, classes, functions, etc.) that should be excluded from the -# output. The symbol name can be a fully qualified name, a word, or if the -# wildcard * is used, a substring. Examples: ANamespace, AClass, -# AClass::ANamespace, ANamespace::*Test - -EXCLUDE_SYMBOLS = - -# The EXAMPLE_PATH tag can be used to specify one or more files or -# directories that contain example code fragments that are included (see -# the \include command). - -EXAMPLE_PATH = examples - -# If the value of the EXAMPLE_PATH tag contains directories, you can use the -# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp -# and *.h) to filter out the source-files in the directories. If left -# blank all files are included. - -EXAMPLE_PATTERNS = - -# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be -# searched for input files to be used with the \include or \dontinclude -# commands irrespective of the value of the RECURSIVE tag. -# Possible values are YES and NO. If left blank NO is used. - -EXAMPLE_RECURSIVE = YES - -# The IMAGE_PATH tag can be used to specify one or more files or -# directories that contain image that are included in the documentation (see -# the \image command). - -IMAGE_PATH = - -# The INPUT_FILTER tag can be used to specify a program that doxygen should -# invoke to filter for each input file. Doxygen will invoke the filter program -# by executing (via popen()) the command , where -# is the value of the INPUT_FILTER tag, and is the name of an -# input file. Doxygen will then use the output that the filter program writes -# to standard output. -# If FILTER_PATTERNS is specified, this tag will be -# ignored. - -INPUT_FILTER = - -# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern -# basis. -# Doxygen will compare the file name with each pattern and apply the -# filter if there is a match. -# The filters are a list of the form: -# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further -# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER -# is applied to all files. - -FILTER_PATTERNS = - -# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using -# INPUT_FILTER) will be used to filter the input files when producing source -# files to browse (i.e. when SOURCE_BROWSER is set to YES). - -FILTER_SOURCE_FILES = NO - -#--------------------------------------------------------------------------- -# configuration options related to source browsing -#--------------------------------------------------------------------------- - -# If the SOURCE_BROWSER tag is set to YES then a list of source files will -# be generated. Documented entities will be cross-referenced with these sources. -# Note: To get rid of all source code in the generated output, make sure also -# VERBATIM_HEADERS is set to NO. - -SOURCE_BROWSER = NO - -# Setting the INLINE_SOURCES tag to YES will include the body -# of functions and classes directly in the documentation. - -INLINE_SOURCES = NO - -# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct -# doxygen to hide any special comment blocks from generated source code -# fragments. Normal C and C++ comments will always remain visible. - -STRIP_CODE_COMMENTS = YES - -# If the REFERENCED_BY_RELATION tag is set to YES -# then for each documented function all documented -# functions referencing it will be listed. - -REFERENCED_BY_RELATION = NO - -# If the REFERENCES_RELATION tag is set to YES -# then for each documented function all documented entities -# called/used by that function will be listed. - -REFERENCES_RELATION = NO - -# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) -# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from -# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will -# link to the source code. -# Otherwise they will link to the documentation. - -REFERENCES_LINK_SOURCE = NO - -# If the USE_HTAGS tag is set to YES then the references to source code -# will point to the HTML generated by the htags(1) tool instead of doxygen -# built-in source browser. The htags tool is part of GNU's global source -# tagging system (see http://www.gnu.org/software/global/global.html). You -# will need version 4.8.6 or higher. - -USE_HTAGS = NO - -# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen -# will generate a verbatim copy of the header file for each class for -# which an include is specified. Set to NO to disable this. - -VERBATIM_HEADERS = YES - -#--------------------------------------------------------------------------- -# configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- - -# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index -# of all compounds will be generated. Enable this if the project -# contains a lot of classes, structs, unions or interfaces. - -ALPHABETICAL_INDEX = NO - -# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then -# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns -# in which this list will be split (can be a number in the range [1..20]) - -COLS_IN_ALPHA_INDEX = 5 - -# In case all classes in a project start with a common prefix, all -# classes will be put under the same header in the alphabetical index. -# The IGNORE_PREFIX tag can be used to specify one or more prefixes that -# should be ignored while generating the index headers. - -IGNORE_PREFIX = - -#--------------------------------------------------------------------------- -# configuration options related to the HTML output -#--------------------------------------------------------------------------- - -# If the GENERATE_HTML tag is set to YES (the default) Doxygen will -# generate HTML output. - -GENERATE_HTML = YES - -# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `html' will be used as the default path. - -HTML_OUTPUT = html - -# The HTML_FILE_EXTENSION tag can be used to specify the file extension for -# each generated HTML page (for example: .htm,.php,.asp). If it is left blank -# doxygen will generate files with .html extension. - -HTML_FILE_EXTENSION = .html - -# The HTML_HEADER tag can be used to specify a personal HTML header for -# each generated HTML page. If it is left blank doxygen will generate a -# standard header. - -HTML_HEADER = - -# The HTML_FOOTER tag can be used to specify a personal HTML footer for -# each generated HTML page. If it is left blank doxygen will generate a -# standard footer. - -HTML_FOOTER = - -# The HTML_STYLESHEET tag can be used to specify a user-defined cascading -# style sheet that is used by each HTML page. It can be used to -# fine-tune the look of the HTML output. If the tag is left blank doxygen -# will generate a default style sheet. Note that doxygen will try to copy -# the style sheet file to the HTML output directory, so don't put your own -# stylesheet in the HTML output directory as well, or it will be erased! - -HTML_STYLESHEET = doxygen-custom.css - -# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML -# page will contain the date and time when the page was generated. Setting -# this to NO can help when comparing the output of multiple runs. - -HTML_TIMESTAMP = YES - -# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, -# files or namespaces will be aligned in HTML using tables. If set to -# NO a bullet list will be used. - -HTML_ALIGN_MEMBERS = YES - -# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML -# documentation will contain sections that can be hidden and shown after the -# page has loaded. For this to work a browser that supports -# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox -# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). - -HTML_DYNAMIC_SECTIONS = NO - -# If the GENERATE_DOCSET tag is set to YES, additional index files -# will be generated that can be used as input for Apple's Xcode 3 -# integrated development environment, introduced with OSX 10.5 (Leopard). -# To create a documentation set, doxygen will generate a Makefile in the -# HTML output directory. Running make will produce the docset in that -# directory and running "make install" will install the docset in -# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find -# it at startup. -# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information. - -GENERATE_DOCSET = NO - -# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the -# feed. A documentation feed provides an umbrella under which multiple -# documentation sets from a single provider (such as a company or product suite) -# can be grouped. - -DOCSET_FEEDNAME = "Doxygen generated docs" - -# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that -# should uniquely identify the documentation set bundle. This should be a -# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen -# will append .docset to the name. - -DOCSET_BUNDLE_ID = org.doxygen.Project - -# If the GENERATE_HTMLHELP tag is set to YES, additional index files -# will be generated that can be used as input for tools like the -# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) -# of the generated HTML documentation. - -GENERATE_HTMLHELP = NO - -# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can -# be used to specify the file name of the resulting .chm file. You -# can add a path in front of the file if the result should not be -# written to the html output directory. - -CHM_FILE = - -# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can -# be used to specify the location (absolute path including file name) of -# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run -# the HTML help compiler on the generated index.hhp. - -HHC_LOCATION = - -# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag -# controls if a separate .chi index file is generated (YES) or that -# it should be included in the master .chm file (NO). - -GENERATE_CHI = NO - -# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING -# is used to encode HtmlHelp index (hhk), content (hhc) and project file -# content. - -CHM_INDEX_ENCODING = - -# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag -# controls whether a binary table of contents is generated (YES) or a -# normal table of contents (NO) in the .chm file. - -BINARY_TOC = NO - -# The TOC_EXPAND flag can be set to YES to add extra items for group members -# to the contents of the HTML help documentation and to the tree view. - -TOC_EXPAND = NO - -# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER -# are set, an additional index file will be generated that can be used as input for -# Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated -# HTML documentation. - -GENERATE_QHP = NO - -# If the QHG_LOCATION tag is specified, the QCH_FILE tag can -# be used to specify the file name of the resulting .qch file. -# The path specified is relative to the HTML output folder. - -QCH_FILE = - -# The QHP_NAMESPACE tag specifies the namespace to use when generating -# Qt Help Project output. For more information please see -# http://doc.trolltech.com/qthelpproject.html#namespace - -QHP_NAMESPACE = org.doxygen.Project - -# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating -# Qt Help Project output. For more information please see -# http://doc.trolltech.com/qthelpproject.html#virtual-folders - -QHP_VIRTUAL_FOLDER = doc - -# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add. -# For more information please see -# http://doc.trolltech.com/qthelpproject.html#custom-filters - -QHP_CUST_FILTER_NAME = - -# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see -# Qt Help Project / Custom Filters. - -QHP_CUST_FILTER_ATTRS = - -# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's -# filter section matches. -# Qt Help Project / Filter Attributes. - -QHP_SECT_FILTER_ATTRS = - -# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can -# be used to specify the location of Qt's qhelpgenerator. -# If non-empty doxygen will try to run qhelpgenerator on the generated -# .qhp file. - -QHG_LOCATION = - -# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files -# will be generated, which together with the HTML files, form an Eclipse help -# plugin. To install this plugin and make it available under the help contents -# menu in Eclipse, the contents of the directory containing the HTML and XML -# files needs to be copied into the plugins directory of eclipse. The name of -# the directory within the plugins directory should be the same as -# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before the help appears. - -GENERATE_ECLIPSEHELP = NO - -# A unique identifier for the eclipse help plugin. When installing the plugin -# the directory name containing the HTML and XML files should also have -# this name. - -ECLIPSE_DOC_ID = org.doxygen.Project - -# The DISABLE_INDEX tag can be used to turn on/off the condensed index at -# top of each HTML page. The value NO (the default) enables the index and -# the value YES disables it. - -DISABLE_INDEX = NO - -# This tag can be used to set the number of enum values (range [1..20]) -# that doxygen will group on one line in the generated HTML documentation. - -ENUM_VALUES_PER_LINE = 4 - -# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index -# structure should be generated to display hierarchical information. -# If the tag value is set to YES, a side panel will be generated -# containing a tree-like index structure (just like the one that -# is generated for HTML Help). For this to work a browser that supports -# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). -# Windows users are probably better off using the HTML help feature. - -GENERATE_TREEVIEW = NO - -# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, -# and Class Hierarchy pages using a tree view instead of an ordered list. - -USE_INLINE_TREES = NO - -# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be -# used to set the initial width (in pixels) of the frame in which the tree -# is shown. - -TREEVIEW_WIDTH = 250 - -# Use this tag to change the font size of Latex formulas included -# as images in the HTML documentation. The default is 10. Note that -# when you change the font size after a successful doxygen run you need -# to manually remove any form_*.png images from the HTML output directory -# to force them to be regenerated. - -FORMULA_FONTSIZE = 10 - -# When the SEARCHENGINE tag is enabled doxygen will generate a search box for the HTML output. The underlying search engine uses javascript -# and DHTML and should work on any modern browser. Note that when using HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) there is already a search function so this one should -# typically be disabled. For large projects the javascript based search engine -# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. - -SEARCHENGINE = YES - -# When the SERVER_BASED_SEARCH tag is enabled the search engine will be implemented using a PHP enabled web server instead of at the web client using Javascript. Doxygen will generate the search PHP script and index -# file to put on the web server. The advantage of the server based approach is that it scales better to large projects and allows full text search. The disadvances is that it is more difficult to setup -# and does not have live searching capabilities. - -SERVER_BASED_SEARCH = NO - -#--------------------------------------------------------------------------- -# configuration options related to the LaTeX output -#--------------------------------------------------------------------------- - -# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will -# generate Latex output. - -GENERATE_LATEX = NO - -# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `latex' will be used as the default path. - -LATEX_OUTPUT = latex - -# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be -# invoked. If left blank `latex' will be used as the default command name. -# Note that when enabling USE_PDFLATEX this option is only used for -# generating bitmaps for formulas in the HTML output, but not in the -# Makefile that is written to the output directory. - -LATEX_CMD_NAME = latex - -# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to -# generate index for LaTeX. If left blank `makeindex' will be used as the -# default command name. - -MAKEINDEX_CMD_NAME = makeindex - -# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact -# LaTeX documents. This may be useful for small projects and may help to -# save some trees in general. - -COMPACT_LATEX = NO - -# The PAPER_TYPE tag can be used to set the paper type that is used -# by the printer. Possible values are: a4, a4wide, letter, legal and -# executive. If left blank a4wide will be used. - -PAPER_TYPE = a4wide - -# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX -# packages that should be included in the LaTeX output. - -EXTRA_PACKAGES = - -# The LATEX_HEADER tag can be used to specify a personal LaTeX header for -# the generated latex document. The header should contain everything until -# the first chapter. If it is left blank doxygen will generate a -# standard header. Notice: only use this tag if you know what you are doing! - -LATEX_HEADER = - -# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated -# is prepared for conversion to pdf (using ps2pdf). The pdf file will -# contain links (just like the HTML output) instead of page references -# This makes the output suitable for online browsing using a pdf viewer. - -PDF_HYPERLINKS = YES - -# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of -# plain latex in the generated Makefile. Set this option to YES to get a -# higher quality PDF documentation. - -USE_PDFLATEX = YES - -# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. -# command to the generated LaTeX files. This will instruct LaTeX to keep -# running if errors occur, instead of asking the user for help. -# This option is also used when generating formulas in HTML. - -LATEX_BATCHMODE = NO - -# If LATEX_HIDE_INDICES is set to YES then doxygen will not -# include the index chapters (such as File Index, Compound Index, etc.) -# in the output. - -LATEX_HIDE_INDICES = NO - -# If LATEX_SOURCE_CODE is set to YES then doxygen will include source code with syntax highlighting in the LaTeX output. Note that which sources are shown also depends on other settings such as SOURCE_BROWSER. - -LATEX_SOURCE_CODE = NO - -#--------------------------------------------------------------------------- -# configuration options related to the RTF output -#--------------------------------------------------------------------------- - -# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output -# The RTF output is optimized for Word 97 and may not look very pretty with -# other RTF readers or editors. - -GENERATE_RTF = NO - -# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `rtf' will be used as the default path. - -RTF_OUTPUT = rtf - -# If the COMPACT_RTF tag is set to YES Doxygen generates more compact -# RTF documents. This may be useful for small projects and may help to -# save some trees in general. - -COMPACT_RTF = NO - -# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated -# will contain hyperlink fields. The RTF file will -# contain links (just like the HTML output) instead of page references. -# This makes the output suitable for online browsing using WORD or other -# programs which support those fields. -# Note: wordpad (write) and others do not support links. - -RTF_HYPERLINKS = NO - -# Load stylesheet definitions from file. Syntax is similar to doxygen's -# config file, i.e. a series of assignments. You only have to provide -# replacements, missing definitions are set to their default value. - -RTF_STYLESHEET_FILE = - -# Set optional variables used in the generation of an rtf document. -# Syntax is similar to doxygen's config file. - -RTF_EXTENSIONS_FILE = - -#--------------------------------------------------------------------------- -# configuration options related to the man page output -#--------------------------------------------------------------------------- - -# If the GENERATE_MAN tag is set to YES (the default) Doxygen will -# generate man pages - -GENERATE_MAN = NO - -# The MAN_OUTPUT tag is used to specify where the man pages will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `man' will be used as the default path. - -MAN_OUTPUT = man - -# The MAN_EXTENSION tag determines the extension that is added to -# the generated man pages (default is the subroutine's section .3) - -MAN_EXTENSION = .3 - -# If the MAN_LINKS tag is set to YES and Doxygen generates man output, -# then it will generate one additional man file for each entity -# documented in the real man page(s). These additional files -# only source the real man page, but without them the man command -# would be unable to find the correct page. The default is NO. - -MAN_LINKS = NO - -#--------------------------------------------------------------------------- -# configuration options related to the XML output -#--------------------------------------------------------------------------- - -# If the GENERATE_XML tag is set to YES Doxygen will -# generate an XML file that captures the structure of -# the code including all documentation. - -GENERATE_XML = YES - -# The XML_OUTPUT tag is used to specify where the XML pages will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `xml' will be used as the default path. - -XML_OUTPUT = xml - -# The XML_SCHEMA tag can be used to specify an XML schema, -# which can be used by a validating XML parser to check the -# syntax of the XML files. - -XML_SCHEMA = - -# The XML_DTD tag can be used to specify an XML DTD, -# which can be used by a validating XML parser to check the -# syntax of the XML files. - -XML_DTD = - -# If the XML_PROGRAMLISTING tag is set to YES Doxygen will -# dump the program listings (including syntax highlighting -# and cross-referencing information) to the XML output. Note that -# enabling this will significantly increase the size of the XML output. - -XML_PROGRAMLISTING = NO - -#--------------------------------------------------------------------------- -# configuration options for the AutoGen Definitions output -#--------------------------------------------------------------------------- - -# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will -# generate an AutoGen Definitions (see autogen.sf.net) file -# that captures the structure of the code including all -# documentation. Note that this feature is still experimental -# and incomplete at the moment. - -GENERATE_AUTOGEN_DEF = NO - -#--------------------------------------------------------------------------- -# configuration options related to the Perl module output -#--------------------------------------------------------------------------- - -# If the GENERATE_PERLMOD tag is set to YES Doxygen will -# generate a Perl module file that captures the structure of -# the code including all documentation. Note that this -# feature is still experimental and incomplete at the -# moment. - -GENERATE_PERLMOD = NO - -# If the PERLMOD_LATEX tag is set to YES Doxygen will generate -# the necessary Makefile rules, Perl scripts and LaTeX code to be able -# to generate PDF and DVI output from the Perl module output. - -PERLMOD_LATEX = NO - -# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be -# nicely formatted so it can be parsed by a human reader. -# This is useful -# if you want to understand what is going on. -# On the other hand, if this -# tag is set to NO the size of the Perl module output will be much smaller -# and Perl will parse it just the same. - -PERLMOD_PRETTY = YES - -# The names of the make variables in the generated doxyrules.make file -# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. -# This is useful so different doxyrules.make files included by the same -# Makefile don't overwrite each other's variables. - -PERLMOD_MAKEVAR_PREFIX = - -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- - -# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will -# evaluate all C-preprocessor directives found in the sources and include -# files. - -ENABLE_PREPROCESSING = YES - -# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro -# names in the source code. If set to NO (the default) only conditional -# compilation will be performed. Macro expansion can be done in a controlled -# way by setting EXPAND_ONLY_PREDEF to YES. - -MACRO_EXPANSION = NO - -# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES -# then the macro expansion is limited to the macros specified with the -# PREDEFINED and EXPAND_AS_DEFINED tags. - -EXPAND_ONLY_PREDEF = NO - -# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files -# in the INCLUDE_PATH (see below) will be search if a #include is found. - -SEARCH_INCLUDES = YES - -# The INCLUDE_PATH tag can be used to specify one or more directories that -# contain include files that are not input files but should be processed by -# the preprocessor. - -INCLUDE_PATH = - -# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard -# patterns (like *.h and *.hpp) to filter out the header-files in the -# directories. If left blank, the patterns specified with FILE_PATTERNS will -# be used. - -INCLUDE_FILE_PATTERNS = - -# The PREDEFINED tag can be used to specify one or more macro names that -# are defined before the preprocessor is started (similar to the -D option of -# gcc). The argument of the tag is a list of macros of the form: name -# or name=definition (no spaces). If the definition and the = are -# omitted =1 is assumed. To prevent a macro definition from being -# undefined via #undef or recursively expanded use the := operator -# instead of the = operator. - -PREDEFINED = - -# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then -# this tag can be used to specify a list of macro names that should be expanded. -# The macro definition that is found in the sources will be used. -# Use the PREDEFINED tag if you want to use a different macro definition. - -EXPAND_AS_DEFINED = - -# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then -# doxygen's preprocessor will remove all function-like macros that are alone -# on a line, have an all uppercase name, and do not end with a semicolon. Such -# function macros are typically used for boiler-plate code, and will confuse -# the parser if not removed. - -SKIP_FUNCTION_MACROS = YES - -#--------------------------------------------------------------------------- -# Configuration::additions related to external references -#--------------------------------------------------------------------------- - -# The TAGFILES option can be used to specify one or more tagfiles. -# Optionally an initial location of the external documentation -# can be added for each tagfile. The format of a tag file without -# this location is as follows: -# -# TAGFILES = file1 file2 ... -# Adding location for the tag files is done as follows: -# -# TAGFILES = file1=loc1 "file2 = loc2" ... -# where "loc1" and "loc2" can be relative or absolute paths or -# URLs. If a location is present for each tag, the installdox tool -# does not have to be run to correct the links. -# Note that each tag file must have a unique name -# (where the name does NOT include the path) -# If a tag file is not located in the directory in which doxygen -# is run, you must also specify the path to the tagfile here. - -TAGFILES = - -# When a file name is specified after GENERATE_TAGFILE, doxygen will create -# a tag file that is based on the input files it reads. - -GENERATE_TAGFILE = - -# If the ALLEXTERNALS tag is set to YES all external classes will be listed -# in the class index. If set to NO only the inherited external classes -# will be listed. - -ALLEXTERNALS = NO - -# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed -# in the modules index. If set to NO, only the current project's groups will -# be listed. - -EXTERNAL_GROUPS = YES - -# The PERL_PATH should be the absolute path and name of the perl script -# interpreter (i.e. the result of `which perl'). - -PERL_PATH = /usr/bin/perl - -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- - -# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will -# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base -# or super classes. Setting the tag to NO turns the diagrams off. Note that -# this option is superseded by the HAVE_DOT option below. This is only a -# fallback. It is recommended to install and use dot, since it yields more -# powerful graphs. - -CLASS_DIAGRAMS = YES - -# You can define message sequence charts within doxygen comments using the \msc -# command. Doxygen will then run the mscgen tool (see -# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the -# documentation. The MSCGEN_PATH tag allows you to specify the directory where -# the mscgen tool resides. If left empty the tool is assumed to be found in the -# default search path. - -MSCGEN_PATH = - -# If set to YES, the inheritance and collaboration graphs will hide -# inheritance and usage relations if the target is undocumented -# or is not a class. - -HIDE_UNDOC_RELATIONS = YES - -# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is -# available from the path. This tool is part of Graphviz, a graph visualization -# toolkit from AT&T and Lucent Bell Labs. The other options in this section -# have no effect if this option is set to NO (the default) - -HAVE_DOT = NO - -# By default doxygen will write a font called FreeSans.ttf to the output -# directory and reference it in all dot files that doxygen generates. This -# font does not include all possible unicode characters however, so when you need -# these (or just want a differently looking font) you can specify the font name -# using DOT_FONTNAME. You need need to make sure dot is able to find the font, -# which can be done by putting it in a standard location or by setting the -# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory -# containing the font. - -DOT_FONTNAME = FreeSans - -# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. -# The default size is 10pt. - -DOT_FONTSIZE = 10 - -# By default doxygen will tell dot to use the output directory to look for the -# FreeSans.ttf font (which doxygen will put there itself). If you specify a -# different font using DOT_FONTNAME you can set the path where dot -# can find it using this tag. - -DOT_FONTPATH = - -# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for each documented class showing the direct and -# indirect inheritance relations. Setting this tag to YES will force the -# the CLASS_DIAGRAMS tag to NO. - -CLASS_GRAPH = YES - -# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for each documented class showing the direct and -# indirect implementation dependencies (inheritance, containment, and -# class references variables) of the class with other documented classes. - -COLLABORATION_GRAPH = YES - -# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for groups, showing the direct groups dependencies - -GROUP_GRAPHS = YES - -# If the UML_LOOK tag is set to YES doxygen will generate inheritance and -# collaboration diagrams in a style similar to the OMG's Unified Modeling -# Language. - -UML_LOOK = NO - -# If set to YES, the inheritance and collaboration graphs will show the -# relations between templates and their instances. - -TEMPLATE_RELATIONS = NO - -# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT -# tags are set to YES then doxygen will generate a graph for each documented -# file showing the direct and indirect include dependencies of the file with -# other documented files. - -INCLUDE_GRAPH = YES - -# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and -# HAVE_DOT tags are set to YES then doxygen will generate a graph for each -# documented header file showing the documented files that directly or -# indirectly include this file. - -INCLUDED_BY_GRAPH = YES - -# If the CALL_GRAPH and HAVE_DOT options are set to YES then -# doxygen will generate a call dependency graph for every global function -# or class method. Note that enabling this option will significantly increase -# the time of a run. So in most cases it will be better to enable call graphs -# for selected functions only using the \callgraph command. - -CALL_GRAPH = NO - -# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then -# doxygen will generate a caller dependency graph for every global function -# or class method. Note that enabling this option will significantly increase -# the time of a run. So in most cases it will be better to enable caller -# graphs for selected functions only using the \callergraph command. - -CALLER_GRAPH = NO - -# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen -# will graphical hierarchy of all classes instead of a textual one. - -GRAPHICAL_HIERARCHY = YES - -# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES -# then doxygen will show the dependencies a directory has on other directories -# in a graphical way. The dependency relations are determined by the #include -# relations between the files in the directories. - -DIRECTORY_GRAPH = YES - -# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images -# generated by dot. Possible values are png, jpg, or gif -# If left blank png will be used. - -DOT_IMAGE_FORMAT = png - -# The tag DOT_PATH can be used to specify the path where the dot tool can be -# found. If left blank, it is assumed the dot tool can be found in the path. - -DOT_PATH = - -# The DOTFILE_DIRS tag can be used to specify one or more directories that -# contain dot files that are included in the documentation (see the -# \dotfile command). - -DOTFILE_DIRS = - -# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of -# nodes that will be shown in the graph. If the number of nodes in a graph -# becomes larger than this value, doxygen will truncate the graph, which is -# visualized by representing a node as a red box. Note that doxygen if the -# number of direct children of the root node in a graph is already larger than -# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note -# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. - -DOT_GRAPH_MAX_NODES = 50 - -# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the -# graphs generated by dot. A depth value of 3 means that only nodes reachable -# from the root by following a path via at most 3 edges will be shown. Nodes -# that lay further from the root node will be omitted. Note that setting this -# option to 1 or 2 may greatly reduce the computation time needed for large -# code bases. Also note that the size of a graph can be further restricted by -# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. - -MAX_DOT_GRAPH_DEPTH = 0 - -# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent -# background. This is disabled by default, because dot on Windows does not -# seem to support this out of the box. Warning: Depending on the platform used, -# enabling this option may lead to badly anti-aliased labels on the edges of -# a graph (i.e. they become hard to read). - -DOT_TRANSPARENT = NO - -# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output -# files in one run (i.e. multiple -o and -T options on the command line). This -# makes dot run faster, but since only newer versions of dot (>1.8.10) -# support this, this feature is disabled by default. - -DOT_MULTI_TARGETS = YES - -# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will -# generate a legend page explaining the meaning of the various boxes and -# arrows in the dot generated graphs. - -GENERATE_LEGEND = YES - -# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will -# remove the intermediate dot files that are used to generate -# the various graphs. - -DOT_CLEANUP = YES diff --git a/AVR/lib/RF24/FAQ b/AVR/lib/RF24/FAQ deleted file mode 100644 index eccd03a..0000000 --- a/AVR/lib/RF24/FAQ +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @page FAQ Frequently Asked Questions - * - * @ref starting - * - * @ref hardware - * - * @ref range - * - * @ref issues - * - * @ref ram - * - * @ref tests - * - * @section starting Where do I start? - * - * See my blog post: - * Getting Started with nRF24L01+ on Arduino - * - * @section hardware Where can I buy some hardware? - * - * @li iTeadStudio sells the basic 2.4G Wireless nRF24L01+ Module for $4. Such a deal! - * @li MDfly.com sells the same unit, 2.4Ghz Wireless nRF24L01+ Transceiver Module for $6.95, but it ships from the US so it gets there a lot faster. Great place to get a few units and get started quickly. - * @li MDfly.com also has the nRF24L01 2.4GHz Transceiver Module w/ Power Amplifier for $13.95, which increases range dramatically and uses a chip antenna - * @li MDfly.com also has the 2.4GHz Transceiver Module w/ Power Amplifier with an external antenna for $19.95 - * - * @section range What is the range of these units? - * - * Here are some results from measurements I have taken, using the basic $4 iTeadStudio units. - * I recommend that everyone take their own measurements in their particular circumstances. - * - * @li non-plus unit, 2MBps (worst case), 41+ ft line of sight indoors, immediate dropoff with any deviation from LOS. (41 ft is as far as I can go in my house without turning a corner) - * @li Plus unit, 250kbps (best case), 46 ft around two corners indoors, 49 ft around one corner. More importantly, at 250k, packet loss is almost negligible through almost all of that range. - * @li Both units at 1MBps, plus unit gets about 10% range improvement over non-plus in almost all situations. - * - * @section issues What should I do if I find a problem? - * - * Please open an issue on github if you find any problems using it with any version of Arduino or Maple. - * - * @section ram What is the RAM footprint of this library? - * - * 16 bytes. A single radio object consumes 16 bytes of RAM, and the library - * does not use any other RAM statically. - * - * @section tests Why are the examples in the 'tests' directory failing? - * - * The sketches in the 'tests' directory are not for general use. - * Please use the examples in the 'examples' directory instead. - * - * The 'tests' directory is only for people making changes to the library - * to ensure that their changes do not break anything. - */ diff --git a/AVR/lib/RF24/README.md b/AVR/lib/RF24/README.md deleted file mode 100644 index c0e71c0..0000000 --- a/AVR/lib/RF24/README.md +++ /dev/null @@ -1,20 +0,0 @@ -# Arduino driver for nRF24L01 2.4GHz Wireless Transceiver - -Design Goals: This library is designed to be... - -* Maximally compliant with the intended operation of the chip -* Easy for beginners to use -* Consumed with a public interface that's similiar to other Arduino standard libraries -* Built against the standard SPI library. - -Please refer to: - -* [Documentation Main Page](http://maniacbug.github.com/RF24) -* [RF24 Class Documentation](http://maniacbug.github.com/RF24/classRF24.html) -* [Source Code](https://github.com/maniacbug/RF24) -* [Downloads](https://github.com/maniacbug/RF24/archives/master) -* [Chip Datasheet](http://www.nordicsemi.com/files/Product/data_sheet/nRF24L01_Product_Specification_v2_0.pdf) - -This chip uses the SPI bus, plus two chip control pins. Remember that pin 10 must still remain an output, or -the SPI hardware will go into 'slave' mode. - diff --git a/AVR/lib/RF24/RF24.c b/AVR/lib/RF24/RF24.c deleted file mode 100644 index 6543f63..0000000 --- a/AVR/lib/RF24/RF24.c +++ /dev/null @@ -1,1027 +0,0 @@ -/* - Copyright (C) 2011,2012 J. Coliz , jaseg - - 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. - */ - -#include "nRF24L01.h" -#include "RF24_config.h" -#include "RF24.h" - -#ifndef RF24_NOUART -#include "uart.h" -#endif - -#include "util.h" - -#include -#include -#include -#include -#include -#include -#include - -#include - -#undef SERIAL_DEBUG -#ifdef SERIAL_DEBUG -#define IF_SERIAL_DEBUG(x) ({x;}) -#else -#define IF_SERIAL_DEBUG(x) -#endif - - -//Global status variables -uint8_t nrf24_wide_band = TRUE; /* 2Mbs data rate in use? */ -uint8_t nrf24_p_variant = FALSE; /* False for RF24L01 and TRUE for RF24L01P */ -uint8_t nrf24_payload_size = 32; /**< Fixed size of payloads */ -uint8_t nrf24_ack_payload_available = FALSE; /**< Whether there is an ack payload waiting */ -uint8_t nrf24_dynamic_payloads_enabled = FALSE; /**< Whether dynamic payloads are enabled. */ -uint8_t nrf24_ack_payload_length; /**< Dynamic size of pending ack payload. */ -uint64_t nrf24_pipe0_reading_address = 0; /**< Last address set on pipe 0 for reading. */ - - -inline void nrf24_csn(int mode) -{ - // Minimum ideal SPI bus speed is 2x data rate - // If we assume 2Mbs data rate and 16Mhz clock, a - // divider of 4 is the minimum we want. - // CLK:BUS 8Mhz:2Mhz, 16Mhz:4Mhz, or 20Mhz:5Mhz - // CHANGED!!! - setup_spi(SPI_MODE_0, SPI_MSB, SPI_NO_INTERRUPT, SPI_MSTR_CLK4); - RF24_CSN_PORT &= ~_BV(RF24_CSN_PIN); - RF24_CSN_PORT |= mode<> RX_P_NO) & 0x7); - uart_puts_p(PSTR("TX_FULL=")); - uart_putc((status & _BV(TX_FULL))?'1':'0'); - uart_putc('\n'); -} - -void nrf24_print_observe_tx(uint8_t value) -{ - uart_puts_p(PSTR("RF24 OBSERVE_TX=")); - uart_puthex(value); - uart_puts_p(PSTR(": POLS_CNT=")); - uart_puthex((value >> PLOS_CNT) & 0xF); - uart_puts_p(PSTR("ARC_CNT=")); - uart_puthex((value >> ARC_CNT) & 0xF); - uart_putc('\n'); -} - -void nrf24_print_byte_register(const char* name, uint8_t reg, uint8_t qty) -{ - if(!qty){ - qty = 1; - } - uart_puts_p(PSTR("RF24 ")); - uart_puts(name); - uart_putc('\t'); - if(strlen_P(name) < 8){ - uart_putc('\t'); - } - uart_putc(' '); - uart_putc('='); - while (qty--){ - uart_putc(' '); - uart_putc('0'); - uart_putc('x'); - uart_puthex(nrf24_read_register(reg++)); - } - uart_putc('\n'); -} - -void nrf24_print_address_register(const char* name, uint8_t reg, uint8_t qty) -{ - if(!qty){ - qty = 1; - } - uart_puts_p(PSTR("RF24 ")); - uart_puts(name); - uart_putc('\t'); - if(strlen_P(name) < 8){ - uart_putc('\t'); - } - uart_putc(' '); - uart_putc('='); - while (qty--) - { - uint8_t buffer[5]; - nrf24_read_register_buf(reg++,buffer,sizeof(buffer)); - uart_putc(' '); - uart_putc('0'); - uart_putc('x'); - uint8_t* bufptr = buffer + sizeof(buffer); - while( --bufptr >= buffer ){ - uart_puthex(*bufptr); - } - } - uart_putc('\n'); -} -#endif - - -void nrf24_setChannel(uint8_t channel) -{ - // TODO: This method could take advantage of the 'wide_band' calculation - // done in nrf24_setChannel() to require nrf24_certain channel spacing. - - nrf24_write_register(RF_CH,min(channel,127)); -} - - - -void nrf24_setPayloadSize(uint8_t size) -{ - nrf24_payload_size = min(size,MAX_PAYLOAD_SIZE); -} - - - -uint8_t nrf24_getPayloadSize(void) -{ - return nrf24_payload_size; -} - - - -static const char rf24_datarate_e_str_0[] PROGMEM = "1MBPS"; -static const char rf24_datarate_e_str_1[] PROGMEM = "2MBPS"; -static const char rf24_datarate_e_str_2[] PROGMEM = "250KBPS"; -static const char * const rf24_datarate_e_str_P[] PROGMEM = { - rf24_datarate_e_str_0, - rf24_datarate_e_str_1, - rf24_datarate_e_str_2, -}; -static const char rf24_model_e_str_0[] PROGMEM = "nRF24L01"; -static const char rf24_model_e_str_1[] PROGMEM = "nRF24L01+"; -static const char * const rf24_model_e_str_P[] PROGMEM = { - rf24_model_e_str_0, - rf24_model_e_str_1, -}; -static const char rf24_crclength_e_str_0[] PROGMEM = "Disabled"; -static const char rf24_crclength_e_str_1[] PROGMEM = "8 bits"; -static const char rf24_crclength_e_str_2[] PROGMEM = "16 bits" ; -static const char * const rf24_crclength_e_str_P[] PROGMEM = { - rf24_crclength_e_str_0, - rf24_crclength_e_str_1, - rf24_crclength_e_str_2, -}; -static const char rf24_pa_dbm_e_str_0[] PROGMEM = "PA_MIN"; -static const char rf24_pa_dbm_e_str_1[] PROGMEM = "PA_LOW"; -static const char rf24_pa_dbm_e_str_2[] PROGMEM = "LA_MED"; -static const char rf24_pa_dbm_e_str_3[] PROGMEM = "PA_HIGH"; -static const char * const rf24_pa_dbm_e_str_P[] PROGMEM = { - rf24_pa_dbm_e_str_0, - rf24_pa_dbm_e_str_1, - rf24_pa_dbm_e_str_2, - rf24_pa_dbm_e_str_3, -}; - -#ifndef RF24_NOUART -void nrf24_printDetails(void) -{ - nrf24_print_status(nrf24_get_status()); - - nrf24_print_address_register(PSTR("RX_ADDR_P0-1"),RX_ADDR_P0,2); - nrf24_print_byte_register(PSTR("RX_ADDR_P2-5"),RX_ADDR_P2,4); - nrf24_print_address_register(PSTR("TX_ADDR"),TX_ADDR,1); - - nrf24_print_byte_register(PSTR("RX_PW_P0-6"),RX_PW_P0,6); - nrf24_print_byte_register(PSTR("EN_AA"),EN_AA,1); - nrf24_print_byte_register(PSTR("EN_RXADDR"),EN_RXADDR,1); - nrf24_print_byte_register(PSTR("RF_CH"),RF_CH,1); - nrf24_print_byte_register(PSTR("RF_SETUP"),RF_SETUP,1); - nrf24_print_byte_register(PSTR("CONFIG"),CONFIG,1); - nrf24_print_byte_register(PSTR("DYNPD/FEATURE"),DYNPD,2); - - uart_puts_p(PSTR("RF24 Data Rate\t = ")); - uart_puts_p((const char*)pgm_read_word(&rf24_datarate_e_str_P[nrf24_getDataRate()])); - uart_putc('\n'); - uart_puts_p(PSTR("RF24 Model\t\t = ")); - uart_puts_p((const char*)pgm_read_word(&rf24_model_e_str_P[nrf24_isPVariant()])); - uart_putc('\n'); - uart_puts_p(PSTR("RF24 CRC Length\t = ")); - uart_puts_p((const char*)pgm_read_word(&rf24_crclength_e_str_P[nrf24_getCRCLength()])); - uart_putc('\n'); - uart_puts_p(PSTR("RF24 PA Power\t = ")); - uart_puts_p((const char*)pgm_read_word(&rf24_pa_dbm_e_str_P[nrf24_getPALevel()])); - uart_putc('\n'); -} -#endif - - -void nrf24_begin(void) -{ - // Initialize pins - RF24_CE_DDR |= _BV(RF24_CE_PIN); - RF24_CSN_DDR |= _BV(RF24_CSN_PIN); - - // Initialize SPI bus -// spi_init(); - - nrf24_ce(LOW); - nrf24_csn(HIGH); - - // Must allow the radio time to settle else configuration bits will not necessarily stick. - // This is actually only required following power up but some settling time also appears to - // be required after resets too. For full coverage, we'll always assume the worst. - // Enabling 16b CRC is by far the most obvious case if the wrong timing is used - or skipped. - // Technically we require 4.5ms + 14us as a worst case. We'll just call it 5ms for good measure. - // WARNING: Delay is based on P-variant whereby non-P *may* require different timing. - _delay_ms( 5 ) ; - - // Set 1500uS (minimum for 32B payload in ESB@250KBPS) timeouts, to make testing a little easier - // WARNING: If this is ever lowered, either 250KBS mode with AA is broken or maximum packet - // sizes must never be used. See documentation for a more complete explanation. - nrf24_write_register(SETUP_RETR,(0x4 << ARD) | (0xF << ARC)); - - // Restore our default PA level - nrf24_setPALevel( RF24_PA_MAX ) ; - - // Determine if this is a p or non-p RF24 module and then - // reset our data rate back to default value. This works - // because a non-P variant won't allow the data rate to - // be set to 250Kbps. - if( nrf24_setDataRate( RF24_250KBPS ) ) - { - nrf24_p_variant = TRUE ; - } - - // Then set the data rate to the slowest (and most reliable) speed supported by all - // hardware. - nrf24_setDataRate( RF24_1MBPS ) ; - - // Initialize CRC and request 2-byte (16bit) CRC - nrf24_setCRCLength( RF24_CRC_16 ) ; - - // Disable dynamic payloads, to match dynamic_payloads_enabled setting - nrf24_write_register(DYNPD,0); - - // Reset current status - // Notice reset and nrf24_flush is the last thing we do - nrf24_write_register(STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); - - // Set up default configuration. Callers can always change it later. - // This channel should be universally safe and not bleed over into adjacent - // spectrum. - nrf24_setChannel(76); - - // Flush buffers - nrf24_flush_rx(); - nrf24_flush_tx(); -} - - - -void nrf24_startListening(void) -{ - nrf24_write_register(CONFIG, nrf24_read_register(CONFIG) | _BV(PWR_UP) | _BV(PRIM_RX)); - nrf24_write_register(STATUS, _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); - - // Restore the pipe0 adddress, if exists - if (nrf24_pipe0_reading_address) - nrf24_write_register_buf(RX_ADDR_P0, (const uint8_t*)(&nrf24_pipe0_reading_address), 5); - - // Flush buffers -// nrf24_flush_rx(); -// nrf24_flush_tx(); - - // Go! - nrf24_ce(HIGH); - - // wait for the radio to come up (130us actually only needed) - _delay_us(130); -} - - - -void nrf24_stopListening(void) -{ - nrf24_ce(LOW); - nrf24_flush_tx(); - nrf24_flush_rx(); -} - - - -void nrf24_powerDown(void) -{ - nrf24_write_register(CONFIG,nrf24_read_register(CONFIG) & ~_BV(PWR_UP)); -} - - - -void nrf24_powerUp(void) -{ - nrf24_write_register(CONFIG,nrf24_read_register(CONFIG) | _BV(PWR_UP)); -} - - - -uint8_t nrf24_write( const void* buf, uint8_t len ) -{ - uint8_t result = FALSE; - - // Begin the write - nrf24_startWrite(buf,len); - - // ------------ - // At this point we could return from a non-blocking write, and then call - // the rest after an interrupt - // FIXME - - // Instead, we are going to block here until we get TX_DS (transmission completed and ack'd) - // or MAX_RT (maximum retries, transmission failed). Also, we'll timeout in case the radio - // is flaky and we get neither. - - // IN the end, the send should be blocking. It comes back in 60ms worst case, or much faster - // if I tighted up the retry logic. (Default settings will be 1500us. - // Monitor the send - uint8_t observe_tx; - uint8_t status; - const uint32_t timeout = 500000; //ms to wait for timeout - uint32_t cycles = 0; - do - { - status = nrf24_read_register_buf(OBSERVE_TX,&observe_tx,1); - IF_SERIAL_DEBUG(uart_puthex(observe_tx)); - cycles++; - } - while( ! ( status & ( _BV(TX_DS) | _BV(MAX_RT) ) ) && ( cycles < timeout ) ); - - // The part above is what you could recreate with your own interrupt handler, - // and then call this when you got an interrupt - // ------------ - - // Call this when you get an interrupt - // The status tells us three things - // * The send was successful (TX_DS) - // * The send failed, too many retries (MAX_RT) - // * There is an ack packet waiting (RX_DR) - uint8_t tx_ok=0, tx_fail=0; - nrf24_whatHappened(&tx_ok,&tx_fail,&nrf24_ack_payload_available); - - //printf("%u%u%u\r\n",tx_ok,tx_fail,ack_payload_available); - - result = tx_ok; - IF_SERIAL_DEBUG(uart_puts(result?"...OK.":"...Failed")); - - // Handle the ack packet - if ( nrf24_ack_payload_available ) - { - nrf24_ack_payload_length = nrf24_getDynamicPayloadSize(); -#ifdef SERIAL_DEBUG - uart_puts_p(PSTR("RF24 [AckPacket]/")); - uart_putdec(uart_ack_payload_length); - uart_putc('\n'); -#endif//SERIAL_DEBUG - } - - // Yay, we are done. - - // Power down - nrf24_powerDown(); - - // Flush buffers (Is this a relic of past experimentation, and not needed anymore??) - nrf24_flush_tx(); - - return result; -} - - -void nrf24_startWrite( const void* buf, uint8_t len ) -{ - // Transmitter power-up - nrf24_write_register(CONFIG, ( nrf24_read_register(CONFIG) | _BV(PWR_UP) ) & ~_BV(PRIM_RX) ); - _delay_us(150); - - // Send the payload - nrf24_write_payload( buf, len ); - - // Allons! - nrf24_ce(HIGH); - _delay_us(15); - nrf24_ce(LOW); -} - - - -uint8_t nrf24_getDynamicPayloadSize(void) -{ - uint8_t result = 0; - - nrf24_csn(LOW); - send_spi( R_RX_PL_WID ); - result = send_spi(0xff); - nrf24_csn(HIGH); - - return result; -} - - - -uint8_t nrf24_available(void) -{ - return nrf24_available_pipe(NULL); -} - - - -uint8_t nrf24_available_pipe(uint8_t* pipe_num) -{ - uint8_t status = nrf24_get_status(); - - // Too noisy, enable if you really want lots o data!! - //IF_SERIAL_DEBUG(print_status(status)); - - uint8_t result = ( status & _BV(RX_DR) ); - - if (result) - { - // If the caller wants the pipe number, include that - if ( pipe_num ) - *pipe_num = ( status >> RX_P_NO ) & 7; - - // Clear the status bit - - // ??? Should this REALLY be cleared now? Or wait until we - // actually READ the payload? - - nrf24_write_register(STATUS,_BV(RX_DR) ); - - // Handle ack payload receipt - if ( status & _BV(TX_DS) ) - { - nrf24_write_register(STATUS,_BV(TX_DS)); - } - } - - return result; -} - - - -uint8_t nrf24_read( void* buf, uint8_t len ) -{ - // Fetch the payload - nrf24_read_payload( buf, len ); - - // was this the last of the data available? - return nrf24_read_register(FIFO_STATUS) & _BV(RX_EMPTY); -} - - - -void nrf24_whatHappened(uint8_t *tx_ok, uint8_t *tx_fail, uint8_t *rx_ready) -{ - // Read the status & reset the status in one easy call - // Or is that such a good idea? - uint8_t status = nrf24_write_register(STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); - - // Report to the user what happened - *tx_ok = status & _BV(TX_DS); - *tx_fail = status & _BV(MAX_RT); - *rx_ready = status & _BV(RX_DR); -} - - - -void nrf24_openWritingPipe(uint64_t value) -{ - // Note that AVR 8-bit uC's store this LSB first, and the NRF24L01(+) - // expects it LSB first too, so we're good. - - nrf24_write_register_buf(RX_ADDR_P0, (uint8_t*)(&value), 5); - nrf24_write_register_buf(TX_ADDR, (uint8_t*)(&value), 5); - - nrf24_write_register(RX_PW_P0,min(nrf24_payload_size,MAX_PAYLOAD_SIZE)); -} - - - -static const uint8_t child_pipe[] PROGMEM = -{ - RX_ADDR_P0, RX_ADDR_P1, RX_ADDR_P2, RX_ADDR_P3, RX_ADDR_P4, RX_ADDR_P5 -}; -static const uint8_t child_payload_size[] PROGMEM = -{ - RX_PW_P0, RX_PW_P1, RX_PW_P2, RX_PW_P3, RX_PW_P4, RX_PW_P5 -}; -static const uint8_t child_pipe_enable[] PROGMEM = -{ - ERX_P0, ERX_P1, ERX_P2, ERX_P3, ERX_P4, ERX_P5 -}; - -void nrf24_openReadingPipe(uint8_t child, uint64_t address) -{ - // If this is pipe 0, cache the address. This is needed because - // openWritingPipe() will overwrite the pipe 0 address, so - // startListening() will have to restore it. - if (child == 0) - nrf24_pipe0_reading_address = address; - - if (child <= 6) - { - // For pipes 2-5, only write the LSB - if ( child < 2 ) - nrf24_write_register_buf(pgm_read_byte(&child_pipe[child]), (const uint8_t*)(&address), 5); - else - nrf24_write_register_buf(pgm_read_byte(&child_pipe[child]), (const uint8_t*)(&address), 1); - - nrf24_write_register(pgm_read_byte(&child_payload_size[child]), nrf24_payload_size); - - // Note it would be more efficient to set all of the bits for all open - // pipes at once. However, I thought it would make the calling code - // more simple to do it this way. - nrf24_write_register(EN_RXADDR,nrf24_read_register(EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[child]))); - } -} - - - -void nrf24_toggle_features(void) -{ - nrf24_csn(LOW); - send_spi( ACTIVATE ); - send_spi( 0x73 ); - nrf24_csn(HIGH); -} - - - -void nrf24_enableDynamicPayloads(void) -{ - // Enable dynamic payload throughout the system - nrf24_write_register(FEATURE,nrf24_read_register(FEATURE) | _BV(EN_DPL) ); - - // If it didn't work, the features are not enabled - if ( ! nrf24_read_register(FEATURE) ) - { - // So enable them and try again - nrf24_toggle_features(); - nrf24_write_register(FEATURE,nrf24_read_register(FEATURE) | _BV(EN_DPL) ); - } - -#ifdef SERIAL_DEBUG - uart_puts_p(PSTR("RF24 FEATURE=")); - uart_putdec(read_register(FEATURE)); - uart_putc('\n'); -#endif//SERIAL_DEBUG - - // Enable dynamic payload on all pipes - // - // Not sure the use case of only having dynamic payload on nrf24_certain - // pipes, so the library does not support it. - nrf24_write_register(DYNPD,nrf24_read_register(DYNPD) | _BV(DPL_P5) | _BV(DPL_P4) | _BV(DPL_P3) | _BV(DPL_P2) | _BV(DPL_P1) | _BV(DPL_P0)); - - nrf24_dynamic_payloads_enabled = TRUE; -} - - - -void nrf24_enableAckPayload(void) -{ - // - // enable ack payload and dynamic payload features - // - - nrf24_write_register(FEATURE,nrf24_read_register(FEATURE) | _BV(EN_ACK_PAY) | _BV(EN_DPL) ); - - // If it didn't work, the features are not enabled - if ( ! nrf24_read_register(FEATURE) ) - { - // So enable them and try again - nrf24_toggle_features(); - nrf24_write_register(FEATURE,nrf24_read_register(FEATURE) | _BV(EN_ACK_PAY) | _BV(EN_DPL) ); - } - -#ifdef SERIAL_DEBUG - uart_puts_p(PSTR("RF24 FEATURE=")); - uart_putdec(read_register(FEATURE)); - uart_putc('\n'); -#endif - - // - // Enable dynamic payload on pipes 0 & 1 - // - - nrf24_write_register(DYNPD,nrf24_read_register(DYNPD) | _BV(DPL_P1) | _BV(DPL_P0)); -} - - - -void nrf24_writeAckPayload(uint8_t pipe, const void* buf, uint8_t len) -{ - const uint8_t* current = (const uint8_t*)(buf); - - nrf24_csn(LOW); - send_spi( W_ACK_PAYLOAD | ( pipe & 7 ) ); - uint8_t data_len = min(len,MAX_PAYLOAD_SIZE); - while ( data_len-- ) - send_spi(*current++); - - nrf24_csn(HIGH); -} - - - -uint8_t nrf24_isAckPayloadAvailable(void) -{ - uint8_t result = nrf24_ack_payload_available; - nrf24_ack_payload_available = FALSE; - return result; -} - - - -uint8_t nrf24_isPVariant(void) -{ - return nrf24_p_variant ; -} - - - -void nrf24_setAutoAck(uint8_t enable) -{ - if ( enable ) - nrf24_write_register(EN_AA, 0x3F); - else - nrf24_write_register(EN_AA, 0); -} - - - -void nrf24_setAutoAck_pipe( uint8_t pipe, uint8_t enable ) -{ - if ( pipe <= 6 ) - { - uint8_t en_aa = nrf24_read_register( EN_AA ) ; - if( enable ) - { - en_aa |= _BV(pipe) ; - } - else - { - en_aa &= ~_BV(pipe) ; - } - nrf24_write_register( EN_AA, en_aa ) ; - } -} - - - -uint8_t nrf24_testCarrier(void) -{ - return ( nrf24_read_register(CD) & 1 ); -} - - - -uint8_t nrf24_testRPD(void) -{ - return ( nrf24_read_register(RPD) & 1 ) ; -} - - - -void nrf24_setPALevel(rf24_pa_dbm_e level) -{ - uint8_t setup = nrf24_read_register(RF_SETUP) ; - setup &= ~(_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ; - - // switch uses RAM (evil!) - if ( level == RF24_PA_MAX ) - { - setup |= (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ; - } - else if ( level == RF24_PA_HIGH ) - { - setup |= _BV(RF_PWR_HIGH) ; - } - else if ( level == RF24_PA_LOW ) - { - setup |= _BV(RF_PWR_LOW); - } - else if ( level == RF24_PA_MIN ) - { - // nothing - } - else if ( level == RF24_PA_ERROR ) - { - // On error, go to maximum PA - setup |= (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ; - } - - nrf24_write_register( RF_SETUP, setup ) ; -} - - - -rf24_pa_dbm_e nrf24_getPALevel(void) -{ - rf24_pa_dbm_e result = RF24_PA_ERROR ; - uint8_t power = nrf24_read_register(RF_SETUP) & (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ; - - // switch uses RAM (evil!) - if ( power == (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ) - { - result = RF24_PA_MAX ; - } - else if ( power == _BV(RF_PWR_HIGH) ) - { - result = RF24_PA_HIGH ; - } - else if ( power == _BV(RF_PWR_LOW) ) - { - result = RF24_PA_LOW ; - } - else - { - result = RF24_PA_MIN ; - } - - return result ; -} - - - -uint8_t nrf24_setDataRate(rf24_datarate_e speed) -{ - uint8_t setup = nrf24_read_register(RF_SETUP) ; - - // HIGH and LOW '00' is 1Mbs - our default - nrf24_wide_band = FALSE ; - setup &= ~(_BV(RF_DR_LOW) | _BV(RF_DR_HIGH)) ; - if( speed == RF24_250KBPS ) - { - // Must set the RF_DR_LOW to 1; RF_DR_HIGH (used to be RF_DR) is already 0 - // Making it '10'. - nrf24_wide_band = FALSE ; - setup |= _BV( RF_DR_LOW ) ; - } - else - { - // Set 2Mbs, RF_DR (RF_DR_HIGH) is set 1 - // Making it '01' - if ( speed == RF24_2MBPS ) - { - nrf24_wide_band = TRUE ; - setup |= _BV(RF_DR_HIGH); - } - else - { - // 1Mbs - nrf24_wide_band = FALSE ; - } - } - nrf24_write_register(RF_SETUP,setup); - - // Verify our result - if ( nrf24_read_register(RF_SETUP) == setup ){ - return TRUE; - } - else{ - nrf24_wide_band = FALSE; - } - return FALSE; -} - - - -rf24_datarate_e nrf24_getDataRate( void ) -{ - rf24_datarate_e result ; - uint8_t dr = nrf24_read_register(RF_SETUP) & (_BV(RF_DR_LOW) | _BV(RF_DR_HIGH)); - - // switch uses RAM (evil!) - // Order matters in our case below - if ( dr == _BV(RF_DR_LOW) ) - { - // '10' = 250KBPS - result = RF24_250KBPS ; - } - else if ( dr == _BV(RF_DR_HIGH) ) - { - // '01' = 2MBPS - result = RF24_2MBPS ; - } - else - { - // '00' = 1MBPS - result = RF24_1MBPS ; - } - return result ; -} - - - -void nrf24_setCRCLength(rf24_crclength_e length) -{ - uint8_t config = nrf24_read_register(CONFIG) & ~( _BV(CRCO) | _BV(EN_CRC)) ; - - // switch uses RAM (evil!) - if ( length == RF24_CRC_DISABLED ) - { - // Do nothing, we turned it off above. - } - else if ( length == RF24_CRC_8 ) - { - config |= _BV(EN_CRC); - } - else - { - config |= _BV(EN_CRC); - config |= _BV( CRCO ); - } - nrf24_write_register( CONFIG, config ) ; -} - - - -rf24_crclength_e nrf24_getCRCLength(void) -{ - rf24_crclength_e result = RF24_CRC_DISABLED; - uint8_t config = nrf24_read_register(CONFIG) & ( _BV(CRCO) | _BV(EN_CRC)) ; - - if ( config & _BV(EN_CRC ) ) - { - if ( config & _BV(CRCO) ) - result = RF24_CRC_16; - else - result = RF24_CRC_8; - } - - return result; -} - - - -void nrf24_disableCRC( void ) -{ - uint8_t disable = nrf24_read_register(CONFIG) & ~_BV(EN_CRC) ; - nrf24_write_register( CONFIG, disable ) ; -} - - -void nrf24_setRetries(uint8_t delay, uint8_t count) -{ - nrf24_write_register(SETUP_RETR,(delay&0xf)< - - 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. - */ - -#include "nRF24L01.h" -#include "RF24_config.h" -#include "RF24.h" - -inline void nrf24_csn(int mode) -{ - // Minimum ideal SPI bus speed is 2x data rate - // If we assume 2Mbs data rate and 16Mhz clock, a - // divider of 4 is the minimum we want. - // CLK:BUS 8Mhz:2Mhz, 16Mhz:4Mhz, or 20Mhz:5Mhz - spi_setup(SPI_MSBFIRST | SPI_MODE0 | SPI_CLOCK_DIV4); - CSN_PORT &= ~_BV(CSN_PIN); - CSN_PORT |= mode<> RX_P_NO) & 0x7); - uart_puts_p(PSTR("TX_FULL=")); - uart_putc((status & _BV(TX_FULL))?'1':'0'); - uart_putc('\n'); - -} - -void nrf24_print_observe_tx(uint8_t value) -{ - uart_puts_p(PSTR("RF24 OBSERVE_TX=")); - uart_puthex(value); - uart_puts_p(PSTR(": POLS_CNT=")); - uart_puthex((value >> PLOS_CNT) & 0xF); - uart_puts_p(PSTR("ARC_CNT=")); - uart_puthex((value >> ARC_CNT) & 0xF); - uart_putc('\n'); -} - - - -void nrf24_print_byte_register(const char* name, uint8_t reg, uint8_t qty) -{ - uart_puts_p("RF24 "); - uart_puts(name); - uart_putc('\t'); - if(strlen_P(name) < 8){ - uart_putc('\t'); - } - uart_putc(' '); - uart_putc('='); - while (qty--){ - uart_putc(' '); - uart_putc('0'); - uart_putc('x'); - uart_puthex(read_register(reg++)); - } - uart_putc('\n'); -} - - - -void nrf24_print_address_register(const char* name, uint8_t reg, uint8_t qty) -{ - uart_puts_p("RF24 "); - uart_puts(name); - uart_putc('\t'); - if(strlen_P(name) < 8){ - uart_putc('\t'); - } - uart_putc(' '); - uart_putc('='); - while (qty--) - { - uint8_t buffer[5]; - read_register(reg++,buffer,sizeof(buffer)); - uart_putc(' '); - uart_putc('0'); - uart_putc('x'); - uint8_t* bufptr = buffer + sizeof(buffer); - while( --bufptr >= buffer ){ - uart_puthex(*bufptr); - } - } - uart_putc('\n'); -} - - - -void nrf24_setChannel(uint8_t channel) -{ - // TODO: This method could take advantage of the 'wide_band' calculation - // done in setChannel() to require certain channel spacing. - - const uint8_t max_channel = 127; - write_register(RF_CH,min(channel,max_channel)); -} - - - -void nrf24_setPayloadSize(uint8_t size) -{ - const uint8_t max_payload_size = 32; - payload_size = min(size,max_payload_size); -} - - - -uint8_t nrf24_getPayloadSize(void) -{ - return payload_size; -} - - - -static const char rf24_datarate_e_str_0[] PROGMEM = "1MBPS"; -static const char rf24_datarate_e_str_1[] PROGMEM = "2MBPS"; -static const char rf24_datarate_e_str_2[] PROGMEM = "250KBPS"; -static const char * const rf24_datarate_e_str_P[] PROGMEM = { - rf24_datarate_e_str_0, - rf24_datarate_e_str_1, - rf24_datarate_e_str_2, -}; -static const char rf24_model_e_str_0[] PROGMEM = "nRF24L01"; -static const char rf24_model_e_str_1[] PROGMEM = "nRF24L01+"; -static const char * const rf24_model_e_str_P[] PROGMEM = { - rf24_model_e_str_0, - rf24_model_e_str_1, -}; -static const char rf24_crclength_e_str_0[] PROGMEM = "Disabled"; -static const char rf24_crclength_e_str_1[] PROGMEM = "8 bits"; -static const char rf24_crclength_e_str_2[] PROGMEM = "16 bits" ; -static const char * const rf24_crclength_e_str_P[] PROGMEM = { - rf24_crclength_e_str_0, - rf24_crclength_e_str_1, - rf24_crclength_e_str_2, -}; -static const char rf24_pa_dbm_e_str_0[] PROGMEM = "PA_MIN"; -static const char rf24_pa_dbm_e_str_1[] PROGMEM = "PA_LOW"; -static const char rf24_pa_dbm_e_str_2[] PROGMEM = "LA_MED"; -static const char rf24_pa_dbm_e_str_3[] PROGMEM = "PA_HIGH"; -static const char * const rf24_pa_dbm_e_str_P[] PROGMEM = { - rf24_pa_dbm_e_str_0, - rf24_pa_dbm_e_str_1, - rf24_pa_dbm_e_str_2, - rf24_pa_dbm_e_str_3, -}; - -void nrf24_printDetails(void) -{ - print_status(get_status()); - - print_address_register(PSTR("RX_ADDR_P0-1"),RX_ADDR_P0,2); - print_byte_register(PSTR("RX_ADDR_P2-5"),RX_ADDR_P2,4); - print_address_register(PSTR("TX_ADDR"),TX_ADDR); - - print_byte_register(PSTR("RX_PW_P0-6"),RX_PW_P0,6); - print_byte_register(PSTR("EN_AA"),EN_AA); - print_byte_register(PSTR("EN_RXADDR"),EN_RXADDR); - print_byte_register(PSTR("RF_CH"),RF_CH); - print_byte_register(PSTR("RF_SETUP"),RF_SETUP); - print_byte_register(PSTR("CONFIG"),CONFIG); - print_byte_register(PSTR("DYNPD/FEATURE"),DYNPD,2); - - uart_puts_p(PSTR("RF24 Data Rate\t = ")); - uart_puts(pgm_read_word(&rf24_datarate_e_str_P[getDataRate()])); - uart_putc('\n'); - uart_puts_p(PSTR("RF24 Model\t\t = ")); - uart_puts(pgm_read_word(&rf24_model_e_str_P[isPVariant()])); - uart_putc('\n'); - uart_puts_p(PSTR("RF24 CRC Length\t = ")); - uart_puts(pgm_read_word(&rf24_crclength_e_str_P[getCRCLength()])); - uart_putc('\n'); - uart_puts_p(PSTR("RF24 PA Power\t = ")); - uart_puts(pgm_read_word(&rf24_pa_dbm_e_str_P[getPALevel()])); - uart_putc('\n'); -} - - - -void nrf24_begin(void) -{ - // Initialize pins - CE_DDR |= _BV(CE_PIN); - CSN_DDR |= _BV(CSN_PIN); - - // Initialize SPI bus - spi_begin(); - - ce(LOW); - csn(HIGH); - - // Must allow the radio time to settle else configuration bits will not necessarily stick. - // This is actually only required following power up but some settling time also appears to - // be required after resets too. For full coverage, we'll always assume the worst. - // Enabling 16b CRC is by far the most obvious case if the wrong timing is used - or skipped. - // Technically we require 4.5ms + 14us as a worst case. We'll just call it 5ms for good measure. - // WARNING: Delay is based on P-variant whereby non-P *may* require different timing. - delay( 5 ) ; - - // Set 1500uS (minimum for 32B payload in ESB@250KBPS) timeouts, to make testing a little easier - // WARNING: If this is ever lowered, either 250KBS mode with AA is broken or maximum packet - // sizes must never be used. See documentation for a more complete explanation. - write_register(SETUP_RETR,(B0100 << ARD) | (B1111 << ARC)); - - // Restore our default PA level - setPALevel( RF24_PA_MAX ) ; - - // Determine if this is a p or non-p RF24 module and then - // reset our data rate back to default value. This works - // because a non-P variant won't allow the data rate to - // be set to 250Kbps. - if( setDataRate( RF24_250KBPS ) ) - { - p_variant = true ; - } - - // Then set the data rate to the slowest (and most reliable) speed supported by all - // hardware. - setDataRate( RF24_1MBPS ) ; - - // Initialize CRC and request 2-byte (16bit) CRC - setCRCLength( RF24_CRC_16 ) ; - - // Disable dynamic payloads, to match dynamic_payloads_enabled setting - write_register(DYNPD,0); - - // Reset current status - // Notice reset and flush is the last thing we do - write_register(STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); - - // Set up default configuration. Callers can always change it later. - // This channel should be universally safe and not bleed over into adjacent - // spectrum. - setChannel(76); - - // Flush buffers - flush_rx(); - flush_tx(); -} - - - -void nrf24_startListening(void) -{ - write_register(CONFIG, read_register(CONFIG) | _BV(PWR_UP) | _BV(PRIM_RX)); - write_register(STATUS, _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); - - // Restore the pipe0 adddress, if exists - if (pipe0_reading_address) - write_register(RX_ADDR_P0, (const uint8_t*)(pipe0_reading_address), 5); - - // Flush buffers - flush_rx(); - flush_tx(); - - // Go! - ce(HIGH); - - // wait for the radio to come up (130us actually only needed) - delayMicroseconds(130); -} - - - -void nrf24_stopListening(void) -{ - ce(LOW); - flush_tx(); - flush_rx(); -} - - - -void nrf24_powerDown(void) -{ - write_register(CONFIG,read_register(CONFIG) & ~_BV(PWR_UP)); -} - - - -void nrf24_powerUp(void) -{ - write_register(CONFIG,read_register(CONFIG) | _BV(PWR_UP)); -} - - - -bool nrf24_write( const void* buf, uint8_t len ) -{ - bool result = false; - - // Begin the write - startWrite(buf,len); - - // ------------ - // At this point we could return from a non-blocking write, and then call - // the rest after an interrupt - - // Instead, we are going to block here until we get TX_DS (transmission completed and ack'd) - // or MAX_RT (maximum retries, transmission failed). Also, we'll timeout in case the radio - // is flaky and we get neither. - - // IN the end, the send should be blocking. It comes back in 60ms worst case, or much faster - // if I tighted up the retry logic. (Default settings will be 1500us. - // Monitor the send - uint8_t observe_tx; - uint8_t status; - uint32_t sent_at = millis(); - const uint32_t timeout = 500; //ms to wait for timeout - do - { - status = read_register(OBSERVE_TX,&observe_tx,1); - IF_SERIAL_DEBUG(uart_puthex(observe_tx)); - } - while( ! ( status & ( _BV(TX_DS) | _BV(MAX_RT) ) ) && ( millis() - sent_at < timeout ) ); - - // The part above is what you could recreate with your own interrupt handler, - // and then call this when you got an interrupt - // ------------ - - // Call this when you get an interrupt - // The status tells us three things - // * The send was successful (TX_DS) - // * The send failed, too many retries (MAX_RT) - // * There is an ack packet waiting (RX_DR) - bool tx_ok, tx_fail; - whatHappened(tx_ok,tx_fail,ack_payload_available); - - //printf("%u%u%u\r\n",tx_ok,tx_fail,ack_payload_available); - - result = tx_ok; - IF_SERIAL_DEBUG(uart_puts(result?"...OK.":"...Failed")); - - // Handle the ack packet - if ( ack_payload_available ) - { - ack_payload_length = getDynamicPayloadSize(); -#ifdef SERIAL_DEBUG - uart_puts_p(PSTR("RF24 [AckPacket]/")); - uart_putdec(uart_ack_payload_length); - uart_putc('\n'); -#endif//SERIAL_DEBUG - } - - // Yay, we are done. - - // Power down - powerDown(); - - // Flush buffers (Is this a relic of past experimentation, and not needed anymore??) - flush_tx(); - - return result; -} - - -void nrf24_startWrite( const void* buf, uint8_t len ) -{ - // Transmitter power-up - write_register(CONFIG, ( read_register(CONFIG) | _BV(PWR_UP) ) & ~_BV(PRIM_RX) ); - delayMicroseconds(150); - - // Send the payload - write_payload( buf, len ); - - // Allons! - ce(HIGH); - delayMicroseconds(15); - ce(LOW); -} - - - -uint8_t nrf24_getDynamicPayloadSize(void) -{ - uint8_t result = 0; - - csn(LOW); - spi_transfer( R_RX_PL_WID ); - result = spi_transfer(0xff); - csn(HIGH); - - return result; -} - - - -bool nrf24_available(void) -{ - return available(NULL); -} - - - -bool nrf24_available(uint8_t* pipe_num) -{ - uint8_t status = get_status(); - - // Too noisy, enable if you really want lots o data!! - //IF_SERIAL_DEBUG(print_status(status)); - - bool result = ( status & _BV(RX_DR) ); - - if (result) - { - // If the caller wants the pipe number, include that - if ( pipe_num ) - *pipe_num = ( status >> RX_P_NO ) & B111; - - // Clear the status bit - - // ??? Should this REALLY be cleared now? Or wait until we - // actually READ the payload? - - write_register(STATUS,_BV(RX_DR) ); - - // Handle ack payload receipt - if ( status & _BV(TX_DS) ) - { - write_register(STATUS,_BV(TX_DS)); - } - } - - return result; -} - - - -bool nrf24_read( void* buf, uint8_t len ) -{ - // Fetch the payload - read_payload( buf, len ); - - // was this the last of the data available? - return read_register(FIFO_STATUS) & _BV(RX_EMPTY); -} - - - -void nrf24_whatHappened(bool& tx_ok,bool& tx_fail,bool& rx_ready) -{ - // Read the status & reset the status in one easy call - // Or is that such a good idea? - uint8_t status = write_register(STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); - - // Report to the user what happened - tx_ok = status & _BV(TX_DS); - tx_fail = status & _BV(MAX_RT); - rx_ready = status & _BV(RX_DR); -} - - - -void nrf24_openWritingPipe(uint64_t value) -{ - // Note that AVR 8-bit uC's store this LSB first, and the NRF24L01(+) - // expects it LSB first too, so we're good. - - write_register(RX_ADDR_P0, (uint8_t*)(&value), 5); - write_register(TX_ADDR, (uint8_t*)(&value), 5); - - const uint8_t max_payload_size = 32; - write_register(RX_PW_P0,min(payload_size,max_payload_size)); -} - - - -static const uint8_t child_pipe[] PROGMEM = -{ - RX_ADDR_P0, RX_ADDR_P1, RX_ADDR_P2, RX_ADDR_P3, RX_ADDR_P4, RX_ADDR_P5 -}; -static const uint8_t child_payload_size[] PROGMEM = -{ - RX_PW_P0, RX_PW_P1, RX_PW_P2, RX_PW_P3, RX_PW_P4, RX_PW_P5 -}; -static const uint8_t child_pipe_enable[] PROGMEM = -{ - ERX_P0, ERX_P1, ERX_P2, ERX_P3, ERX_P4, ERX_P5 -}; - -void nrf24_openReadingPipe(uint8_t child, uint64_t address) -{ - // If this is pipe 0, cache the address. This is needed because - // openWritingPipe() will overwrite the pipe 0 address, so - // startListening() will have to restore it. - if (child == 0) - pipe0_reading_address = address; - - if (child <= 6) - { - // For pipes 2-5, only write the LSB - if ( child < 2 ) - write_register(pgm_read_byte(&child_pipe[child]), (const uint8_t*)(&address), 5); - else - write_register(pgm_read_byte(&child_pipe[child]), (const uint8_t*)(&address), 1); - - write_register(pgm_read_byte(&child_payload_size[child]),payload_size); - - // Note it would be more efficient to set all of the bits for all open - // pipes at once. However, I thought it would make the calling code - // more simple to do it this way. - write_register(EN_RXADDR,read_register(EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[child]))); - } -} - - - -void nrf24_toggle_features(void) -{ - csn(LOW); - spi_transfer( ACTIVATE ); - spi_transfer( 0x73 ); - csn(HIGH); -} - - - -void nrf24_enableDynamicPayloads(void) -{ - // Enable dynamic payload throughout the system - write_register(FEATURE,read_register(FEATURE) | _BV(EN_DPL) ); - - // If it didn't work, the features are not enabled - if ( ! read_register(FEATURE) ) - { - // So enable them and try again - toggle_features(); - write_register(FEATURE,read_register(FEATURE) | _BV(EN_DPL) ); - } - -#ifdef SERIAL_DEBUG - uart_puts_p(PSTR("RF24 FEATURE=")); - uart_putdec(read_register(FEATURE)); - uart_putc('\n'); -#endif//SERIAL_DEBUG - - // Enable dynamic payload on all pipes - // - // Not sure the use case of only having dynamic payload on certain - // pipes, so the library does not support it. - write_register(DYNPD,read_register(DYNPD) | _BV(DPL_P5) | _BV(DPL_P4) | _BV(DPL_P3) | _BV(DPL_P2) | _BV(DPL_P1) | _BV(DPL_P0)); - - dynamic_payloads_enabled = true; -} - - - -void nrf24_enableAckPayload(void) -{ - // - // enable ack payload and dynamic payload features - // - - write_register(FEATURE,read_register(FEATURE) | _BV(EN_ACK_PAY) | _BV(EN_DPL) ); - - // If it didn't work, the features are not enabled - if ( ! read_register(FEATURE) ) - { - // So enable them and try again - toggle_features(); - write_register(FEATURE,read_register(FEATURE) | _BV(EN_ACK_PAY) | _BV(EN_DPL) ); - } - -#ifdef SERIAL_DEBUG - uart_puts_p(PSTR("RF24 FEATURE=")); - uart_putdec(read_register(FEATURE)); - uart_putc('\n'); -#endif - - // - // Enable dynamic payload on pipes 0 & 1 - // - - write_register(DYNPD,read_register(DYNPD) | _BV(DPL_P1) | _BV(DPL_P0)); -} - - - -void nrf24_writeAckPayload(uint8_t pipe, const void* buf, uint8_t len) -{ - const uint8_t* current = (const uint8_t*)(buf); - - csn(LOW); - spi_transfer( W_ACK_PAYLOAD | ( pipe & B111 ) ); - const uint8_t max_payload_size = 32; - uint8_t data_len = min(len,max_payload_size); - while ( data_len-- ) - spi_transfer(*current++); - - csn(HIGH); -} - - - -bool nrf24_isAckPayloadAvailable(void) -{ - bool result = ack_payload_available; - ack_payload_available = false; - return result; -} - - - -bool nrf24_isPVariant(void) -{ - return p_variant ; -} - - - -void nrf24_setAutoAck(bool enable) -{ - if ( enable ) - write_register(EN_AA, 0x3F); - else - write_register(EN_AA, 0); -} - - - -void nrf24_setAutoAck( uint8_t pipe, bool enable ) -{ - if ( pipe <= 6 ) - { - uint8_t en_aa = read_register( EN_AA ) ; - if( enable ) - { - en_aa |= _BV(pipe) ; - } - else - { - en_aa &= ~_BV(pipe) ; - } - write_register( EN_AA, en_aa ) ; - } -} - - - -bool nrf24_testCarrier(void) -{ - return ( read_register(CD) & 1 ); -} - - - -bool nrf24_testRPD(void) -{ - return ( read_register(RPD) & 1 ) ; -} - - - -void nrf24_setPALevel(rf24_pa_dbm_e level) -{ - uint8_t setup = read_register(RF_SETUP) ; - setup &= ~(_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ; - - // switch uses RAM (evil!) - if ( level == RF24_PA_MAX ) - { - setup |= (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ; - } - else if ( level == RF24_PA_HIGH ) - { - setup |= _BV(RF_PWR_HIGH) ; - } - else if ( level == RF24_PA_LOW ) - { - setup |= _BV(RF_PWR_LOW); - } - else if ( level == RF24_PA_MIN ) - { - // nothing - } - else if ( level == RF24_PA_ERROR ) - { - // On error, go to maximum PA - setup |= (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ; - } - - write_register( RF_SETUP, setup ) ; -} - - - -rf24_pa_dbm_e nrf24_getPALevel(void) -{ - rf24_pa_dbm_e result = RF24_PA_ERROR ; - uint8_t power = read_register(RF_SETUP) & (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ; - - // switch uses RAM (evil!) - if ( power == (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ) - { - result = RF24_PA_MAX ; - } - else if ( power == _BV(RF_PWR_HIGH) ) - { - result = RF24_PA_HIGH ; - } - else if ( power == _BV(RF_PWR_LOW) ) - { - result = RF24_PA_LOW ; - } - else - { - result = RF24_PA_MIN ; - } - - return result ; -} - - - -bool nrf24_setDataRate(rf24_datarate_e speed) -{ - bool result = false; - uint8_t setup = read_register(RF_SETUP) ; - - // HIGH and LOW '00' is 1Mbs - our default - wide_band = false ; - setup &= ~(_BV(RF_DR_LOW) | _BV(RF_DR_HIGH)) ; - if( speed == RF24_250KBPS ) - { - // Must set the RF_DR_LOW to 1; RF_DR_HIGH (used to be RF_DR) is already 0 - // Making it '10'. - wide_band = false ; - setup |= _BV( RF_DR_LOW ) ; - } - else - { - // Set 2Mbs, RF_DR (RF_DR_HIGH) is set 1 - // Making it '01' - if ( speed == RF24_2MBPS ) - { - wide_band = true ; - setup |= _BV(RF_DR_HIGH); - } - else - { - // 1Mbs - wide_band = false ; - } - } - write_register(RF_SETUP,setup); - - // Verify our result - if ( read_register(RF_SETUP) == setup ) - { - result = true; - } - else - { - wide_band = false; - } - - return result; -} - - - -rf24_datarate_e nrf24_getDataRate( void ) -{ - rf24_datarate_e result ; - uint8_t dr = read_register(RF_SETUP) & (_BV(RF_DR_LOW) | _BV(RF_DR_HIGH)); - - // switch uses RAM (evil!) - // Order matters in our case below - if ( dr == _BV(RF_DR_LOW) ) - { - // '10' = 250KBPS - result = RF24_250KBPS ; - } - else if ( dr == _BV(RF_DR_HIGH) ) - { - // '01' = 2MBPS - result = RF24_2MBPS ; - } - else - { - // '00' = 1MBPS - result = RF24_1MBPS ; - } - return result ; -} - - - -void nrf24_setCRCLength(rf24_crclength_e length) -{ - uint8_t config = read_register(CONFIG) & ~( _BV(CRCO) | _BV(EN_CRC)) ; - - // switch uses RAM (evil!) - if ( length == RF24_CRC_DISABLED ) - { - // Do nothing, we turned it off above. - } - else if ( length == RF24_CRC_8 ) - { - config |= _BV(EN_CRC); - } - else - { - config |= _BV(EN_CRC); - config |= _BV( CRCO ); - } - write_register( CONFIG, config ) ; -} - - - -rf24_crclength_e nrf24_getCRCLength(void) -{ - rf24_crclength_e result = RF24_CRC_DISABLED; - uint8_t config = read_register(CONFIG) & ( _BV(CRCO) | _BV(EN_CRC)) ; - - if ( config & _BV(EN_CRC ) ) - { - if ( config & _BV(CRCO) ) - result = RF24_CRC_16; - else - result = RF24_CRC_8; - } - - return result; -} - - - -void nrf24_disableCRC( void ) -{ - uint8_t disable = read_register(CONFIG) & ~_BV(EN_CRC) ; - write_register( CONFIG, disable ) ; -} - - -void nrf24_setRetries(uint8_t delay, uint8_t count) -{ - write_register(SETUP_RETR,(delay&0xf)<, jaseg - - 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. - */ - -/** - * @file RF24.h - * - * Class declaration for RF24 and helper enums - */ - -#ifndef __RF24_H__ -#define __RF24_H__ - -//#include - -#define HIGH 1 -#define LOW 0 - -#define TRUE 1 -#define FALSE 0 - -/** - * Power Amplifier level. - * - * For use with setPALevel() - */ -typedef enum { RF24_PA_MIN = 0,RF24_PA_LOW, RF24_PA_HIGH, RF24_PA_MAX, RF24_PA_ERROR } rf24_pa_dbm_e ; - -/** - * Data rate. How fast data moves through the air. - * - * For use with setDataRate() - */ -typedef enum { RF24_1MBPS = 0, RF24_2MBPS, RF24_250KBPS } rf24_datarate_e; - -/** - * CRC Length. How big (if any) of a CRC is included. - * - * For use with setCRCLength() - */ -typedef enum { RF24_CRC_DISABLED = 0, RF24_CRC_8, RF24_CRC_16 } rf24_crclength_e; - -/** - * Driver for nRF24L01(+) 2.4GHz Wireless Transceiver - */ - -/** - * @name Low-level internal interface. - * - * Protected methods that address the chip directly. Regular users cannot - * ever call these. They are documented for completeness and for developers who - * may want to extend this class. - */ -/**@{*/ - -/** - * Set chip select pin - * - * Running SPI bus at PI_CLOCK_DIV2 so we don't waste time transferring data - * and best of all, we make use of the radio's FIFO buffers. A lower speed - * means we're less likely to effectively leverage our FIFOs and pay a higher - * AVR runtime cost as toll. - * - * @param mode HIGH to take this unit off the SPI bus, LOW to put it on - */ -void nrf24_csn(int mode); - -/** - * Set chip enable - * - * @param level HIGH to actively begin transmission or LOW to put in standby. Please see data sheet - * for a much more detailed description of this pin. - */ -void nrf24_ce(int level); - -/** - * Read a chunk of data in from a register - * - * @param reg Which register. Use constants from nRF24L01.h - * @param buf Where to put the data - * @param len How many bytes of data to transfer - * @return Current value of status register - */ -uint8_t nrf24_read_register_buf(uint8_t reg, uint8_t* buf, uint8_t len); - -/** - * Read single byte from a register - * - * @param reg Which register. Use constants from nRF24L01.h - * @return Current value of register @p reg - */ -uint8_t nrf24_read_register(uint8_t reg); - -/** - * Write a chunk of data to a register - * - * @param reg Which register. Use constants from nRF24L01.h - * @param buf Where to get the data - * @param len How many bytes of data to transfer - * @return Current value of status register - */ -uint8_t nrf24_write_register_buf(uint8_t reg, const uint8_t* buf, uint8_t len); - -/** - * Write a single byte to a register - * - * @param reg Which register. Use constants from nRF24L01.h - * @param value The new value to write - * @return Current value of status register - */ -uint8_t nrf24_write_register(uint8_t reg, uint8_t value); - -/** - * Write the transmit payload - * - * The size of data written is the fixed payload size, see getPayloadSize() - * - * @param buf Where to get the data - * @param len Number of bytes to be sent - * @return Current value of status register - */ -uint8_t nrf24_write_payload(const void* buf, uint8_t len); - -/** - * Read the receive payload - * - * The size of data read is the fixed payload size, see getPayloadSize() - * - * @param buf Where to put the data - * @param len Maximum number of bytes to read - * @return Current value of status register - */ -uint8_t nrf24_read_payload(void* buf, uint8_t len); - -/** - * Empty the receive buffer - * - * @return Current value of status register - */ -uint8_t nrf24_flush_rx(void); - -/** - * Empty the transmit buffer - * - * @return Current value of status register - */ -uint8_t nrf24_flush_tx(void); - -/** - * Retrieve the current status of the chip - * - * @return Current value of status register - */ -uint8_t nrf24_get_status(void); - -/** - * Decode and print the given status to stdout - * - * @param status Status value to print - * - * @warning Does nothing if stdout is not defined. See fdevopen in stdio.h - */ -void nrf24_print_status(uint8_t status); - -/** - * Decode and print the given 'observe_tx' value to stdout - * - * @param value The observe_tx value to print - * - * @warning Does nothing if stdout is not defined. See fdevopen in stdio.h - */ -void nrf24_print_observe_tx(uint8_t value); - -/** - * Print the name and value of an 8-bit register to stdout - * - * Optionally it can print some quantity of successive - * registers on the same line. This is useful for printing a group - * of related registers on one line. - * - * @param name Name of the register - * @param reg Which register. Use constants from nRF24L01.h - * @param qty How many successive registers to print - */ -void nrf24_print_byte_register(const char* name, uint8_t reg, uint8_t qty); - -/** - * Print the name and value of a 40-bit address register to stdout - * - * Optionally it can print some quantity of successive - * registers on the same line. This is useful for printing a group - * of related registers on one line. - * - * @param name Name of the register - * @param reg Which register. Use constants from nRF24L01.h - * @param qty How many successive registers to print - */ -void nrf24_print_address_register(const char* name, uint8_t reg, uint8_t qty); - -/** - * Turn on or off the special features of the chip - * - * The chip has certain 'features' which are only available when the 'features' - * are enabled. See the datasheet for details. - */ -void nrf24_toggle_features(void); -/**@}*/ - -/** - * @name Primary public interface - * - * These are the main methods you need to operate the chip - */ -/**@{*/ - -/** - * Begin operation of the chip - * - * Call this in setup(), before calling any other methods. - */ -void nrf24_begin(void); - -/** - * Start listening on the pipes opened for reading. - * - * Be sure to call openReadingPipe() first. Do not call write() while - * in this mode, without first calling stopListening(). Call - * isAvailable() to check for incoming traffic, and read() to get it. - */ -void nrf24_startListening(void); - -/** - * Stop listening for incoming messages - * - * Do this before calling write(). - */ -void nrf24_stopListening(void); - -/** - * Write to the open writing pipe - * - * Be sure to call openWritingPipe() first to set the destination - * of where to write to. - * - * This blocks until the message is successfully acknowledged by - * the receiver or the timeout/retransmit maxima are reached. In - * the current configuration, the max delay here is 60ms. - * - * The maximum size of data written is the fixed payload size, see - * getPayloadSize(). However, you can write less, and the remainder - * will just be filled with zeroes. - * - * @param buf Pointer to the data to be sent - * @param len Number of bytes to be sent - * @return True if the payload was delivered successfully FALSE if not - */ -uint8_t nrf24_write( const void* buf, uint8_t len ); - -/** - * Test whether there are bytes available to be read - * - * @return True if there is a payload available, FALSE if none is - */ -uint8_t nrf24_available(void); - -/** - * Read the payload - * - * Return the last payload received - * - * The size of data read is the fixed payload size, see getPayloadSize() - * - * @note I specifically chose 'void*' as a data type to make it easier - * for beginners to use. No casting needed. - * - * @param buf Pointer to a buffer where the data should be written - * @param len Maximum number of bytes to read into the buffer - * @return True if the payload was delivered successfully FALSE if not - */ -uint8_t nrf24_read( void* buf, uint8_t len ); - -/** - * Open a pipe for writing - * - * Only one pipe can be open at once, but you can change the pipe - * you'll listen to. Do not call this while actively listening. - * Remember to stopListening() first. - * - * Addresses are 40-bit hex values, e.g.: - * - * @code - * openWritingPipe(0xF0F0F0F0F0); - * @endcode - * - * @param address The 40-bit address of the pipe to open. This can be - * any value whatsoever, as long as you are the only one writing to it - * and only one other radio is listening to it. Coordinate these pipe - * addresses amongst nodes on the network. - */ -void nrf24_openWritingPipe(uint64_t address); - -/** - * Open a pipe for reading - * - * Up to 6 pipes can be open for reading at once. Open all the - * reading pipes, and then call startListening(). - * - * @see openWritingPipe - * - * @warning Pipes 1-5 should share the first 32 bits. - * Only the least significant byte should be unique, e.g. - * @code - * openReadingPipe(1,0xF0F0F0F0AA); - * openReadingPipe(2,0xF0F0F0F066); - * @endcode - * - * @warning Pipe 0 is also used by the writing pipe. So if you open - * pipe 0 for reading, and then startListening(), it will overwrite the - * writing pipe. Ergo, do an openWritingPipe() again before write(). - * - * @todo Enforce the restriction that pipes 1-5 must share the top 32 bits - * - * @param number Which pipe# to open, 0-5. - * @param address The 40-bit address of the pipe to open. - */ -void nrf24_openReadingPipe(uint8_t number, uint64_t address); - -/**@}*/ -/** - * @name Optional Configurators - * - * Methods you can use to get or set the configuration of the chip. - * None are required. Calling begin() sets up a reasonable set of - * defaults. - */ -/**@{*/ -/** - * Set the number and delay of retries upon failed submit - * - * @param delay How long to wait between each retry, in multiples of 250us, - * max is 15. 0 means 250us, 15 means 4000us. - * @param count How many retries before giving up, max 15 - */ -void nrf24_setRetries(uint8_t delay, uint8_t count); - -/** - * Set RF communication channel - * - * @param channel Which RF channel to communicate on, 0-127 - */ -void nrf24_setChannel(uint8_t channel); - -/** - * Set Static Payload Size - * - * This implementation uses a pre-stablished fixed payload size for all - * transmissions. If this method is never called, the driver will always - * transmit the maximum payload size (32 bytes), no matter how much - * was sent to write(). - * - * @todo Implement variable-sized payloads feature - * - * @param size The number of bytes in the payload - */ -void nrf24_setPayloadSize(uint8_t size); - -/** - * Get Static Payload Size - * - * @see setPayloadSize() - * - * @return The number of bytes in the payload - */ -uint8_t nrf24_getPayloadSize(void); - -/** - * Get Dynamic Payload Size - * - * For dynamic payloads, this pulls the size of the payload off - * the chip - * - * @return Payload length of last-received dynamic payload - */ -uint8_t nrf24_getDynamicPayloadSize(void); - -/** - * Enable custom payloads on the acknowledge packets - * - * Ack payloads are a handy way to return data back to senders without - * manually changing the radio modes on both units. - * - * @see examples/pingpair_pl/pingpair_pl.pde - */ -void nrf24_enableAckPayload(void); - -/** - * Enable dynamically-sized payloads - * - * This way you don't always have to send large packets just to send them - * once in a while. This enables dynamic payloads on ALL pipes. - * - * @see examples/pingpair_pl/pingpair_dyn.pde - */ -void nrf24_enableDynamicPayloads(void); - -/** - * Determine whether the hardware is an nRF24L01+ or not. - * - * @return TRUE if the hardware is nRF24L01+ (or compatible) and FALSE - * if its not. - */ -uint8_t nrf24_isPVariant(void) ; - -/** - * Enable or disable auto-acknowlede packets - * - * This is enabled by default, so it's only needed if you want to turn - * it off for some reason. - * - * @param enable Whether to enable (TRUE) or disable (FALSE) auto-acks - */ -void nrf24_setAutoAck(uint8_t enable); - -/** - * Enable or disable auto-acknowlede packets on a per pipeline basis. - * - * AA is enabled by default, so it's only needed if you want to turn - * it off/on for some reason on a per pipeline basis. - * - * @param pipe Which pipeline to modify - * @param enable Whether to enable (TRUE) or disable (FALSE) auto-acks - */ -void nrf24_setAutoAck_pipe( uint8_t pipe, uint8_t enable ) ; - -/** - * Set Power Amplifier (PA) level to one of four levels. - * Relative mnemonics have been used to allow for future PA level - * changes. According to 6.5 of the nRF24L01+ specification sheet, - * they translate to: RF24_PA_MIN=-18dBm, RF24_PA_LOW=-12dBm, - * RF24_PA_MED=-6dBM, and RF24_PA_HIGH=0dBm. - * - * @param level Desired PA level. - */ -void nrf24_setPALevel( rf24_pa_dbm_e level ) ; - -/** - * Fetches the current PA level. - * - * @return Returns a value from the rf24_pa_dbm_e enum describing - * the current PA setting. Please remember, all values represented - * by the enum mnemonics are negative dBm. See setPALevel for - * return value descriptions. - */ -rf24_pa_dbm_e nrf24_getPALevel( void ) ; - -/** - * Set the transmission data rate - * - * @warning setting RF24_250KBPS will fail for non-plus units - * - * @param speed RF24_250KBPS for 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS for 2Mbps - * @return TRUE if the change was successful - */ -uint8_t nrf24_setDataRate(rf24_datarate_e speed); - -/** - * Fetches the transmission data rate - * - * @return Returns the hardware's currently configured datarate. The value - * is one of 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS, as defined in the - * rf24_datarate_e enum. - */ -rf24_datarate_e nrf24_getDataRate( void ) ; - -/** - * Set the CRC length - * - * @param length RF24_CRC_8 for 8-bit or RF24_CRC_16 for 16-bit - */ -void nrf24_setCRCLength(rf24_crclength_e length); - -/** - * Get the CRC length - * - * @return RF24_DISABLED if disabled or RF24_CRC_8 for 8-bit or RF24_CRC_16 for 16-bit - */ -rf24_crclength_e nrf24_getCRCLength(void); - -/** - * Disable CRC validation - * - */ -void nrf24_disableCRC( void ) ; - -/**@}*/ -/** - * @name Advanced Operation - * - * Methods you can use to drive the chip in more advanced ways - */ -/**@{*/ - -/** - * Print a giant block of debugging information to stdout - * - * @warning Does nothing if stdout is not defined. See fdevopen in stdio.h - */ -void nrf24_printDetails(void); - -/** - * Enter low-power mode - * - * To return to normal power mode, either write() some data or - * startListening, or powerUp(). - */ -void nrf24_powerDown(void); - -/** - * Leave low-power mode - making radio more responsive - * - * To return to low power mode, call powerDown(). - */ -void nrf24_powerUp(void) ; - -/** - * Test whether there are bytes available to be read - * - * Use this version to discover on which pipe the message - * arrived. - * - * @param[out] pipe_num Which pipe has the payload available - * @return True if there is a payload available, FALSE if none is - */ -uint8_t nrf24_available_pipe(uint8_t* pipe_num); - -/** - * Non-blocking write to the open writing pipe - * - * Just like write(), but it returns immediately. To find out what happened - * to the send, catch the IRQ and then call whatHappened(). - * - * @see write() - * @see whatHappened() - * - * @param buf Pointer to the data to be sent - * @param len Number of bytes to be sent - * @return True if the payload was delivered successfully FALSE if not - */ -void nrf24_startWrite( const void* buf, uint8_t len ); - -/** - * Write an ack payload for the specified pipe - * - * The next time a message is received on @p pipe, the data in @p buf will - * be sent back in the acknowledgement. - * - * @warning According to the data sheet, only three of these can be pending - * at any time. I have not tested this. - * - * @param pipe Which pipe# (typically 1-5) will get this response. - * @param buf Pointer to data that is sent - * @param len Length of the data to send, up to 32 bytes max. Not affected - * by the static payload set by setPayloadSize(). - */ -void nrf24_writeAckPayload(uint8_t pipe, const void* buf, uint8_t len); - -/** - * Determine if an ack payload was received in the most recent call to - * write(). - * - * Call read() to retrieve the ack payload. - * - * @warning Calling this function clears the internal flag which indicates - * a payload is available. If it returns TRUE, you must read the packet - * out as the very next interaction with the radio, or the results are - * undefined. - * - * @return True if an ack payload is available. - */ -uint8_t nrf24_isAckPayloadAvailable(void); - -/** - * Call this when you get an interrupt to find out why - * - * Tells you what caused the interrupt, and clears the state of - * interrupts. - * - * @param[out] tx_ok The send was successful (TX_DS) - * @param[out] tx_fail The send failed, too many retries (MAX_RT) - * @param[out] rx_ready There is a message waiting to be read (RX_DS) - */ -void nrf24_whatHappened(uint8_t *tx_ok,uint8_t *tx_fail,uint8_t *rx_ready); - -/** - * Test whether there was a carrier on the line for the - * previous listening period. - * - * Useful to check for interference on the current channel. - * - * @return TRUE if was carrier, FALSE if not - */ -uint8_t nrf24_testCarrier(void); - -/** - * Test whether a signal (carrier or otherwise) greater than - * or equal to -64dBm is present on the channel. Valid only - * on nRF24L01P (+) hardware. On nRF24L01, use testCarrier(). - * - * Useful to check for interference on the current channel and - * channel hopping strategies. - * - * @return TRUE if signal => -64dBm, FALSE if not - */ -uint8_t nrf24_testRPD(void) ; - -/**@}*/ - -/** - * @example GettingStarted.pde - * - * This is an example which corresponds to my "Getting Started" blog post: - * Getting Started with nRF24L01+ on Arduino. - * - * It is an example of how to use the RF24 class. Write this sketch to two - * different nodes. Put one of the nodes into 'transmit' mode by connecting - * with the serial monitor and sending a 'T'. The ping node sends the current - * time to the pong node, which responds by sending the value back. The ping - * node can then see how long the whole cycle took. - */ - -/** - * @example nordic_fob.pde - * - * This is an example of how to use the RF24 class to receive signals from the - * Sparkfun Nordic FOB. See http://www.sparkfun.com/products/8602 . - * Thanks to Kirk Mower for providing test hardware. - */ - -/** - * @example led_remote.pde - * - * This is an example of how to use the RF24 class to control a remote - * bank of LED's using buttons on a remote control. - * - * Every time the buttons change on the remote, the entire state of - * buttons is send to the led board, which displays the state. - */ - -/** - * @example pingpair.pde - * - * This is an example of how to use the RF24 class. Write this sketch to two - * different nodes, connect the role_pin to ground on one. The ping node sends - * the current time to the pong node, which responds by sending the value back. - * The ping node can then see how long the whole cycle took. - */ - -/** - * @example pingpair_maple.pde - * - * This is an example of how to use the RF24 class on the Maple. For a more - * detailed explanation, see my blog post: - * nRF24L01+ Running on Maple - * - * It will communicate well to an Arduino-based unit as well, so it's not for only Maple-to-Maple communication. - * - * Write this sketch to two different nodes, - * connect the role_pin to ground on one. The ping node sends the current time to the pong node, - * which responds by sending the value back. The ping node can then see how long the whole cycle - * took. - */ - -/** - * @example starping.pde - * - * This sketch is a more complex example of using the RF24 library for Arduino. - * Deploy this on up to six nodes. Set one as the 'pong receiver' by tying the - * role_pin low, and the others will be 'ping transmit' units. The ping units - * unit will send out the value of millis() once a second. The pong unit will - * respond back with a copy of the value. Each ping unit can get that response - * back, and determine how long the whole cycle took. - * - * This example requires a bit more complexity to determine which unit is which. - * The pong receiver is identified by having its role_pin tied to ground. - * The ping senders are further differentiated by a byte in eeprom. - */ - -/** - * @example pingpair_pl.pde - * - * This is an example of how to do two-way communication without changing - * transmit/receive modes. Here, a payload is set to the transmitter within - * the Ack packet of each transmission. Note that the payload is set BEFORE - * the sender's message arrives. - */ - -/** - * @example pingpair_irq.pde - * - * This is an example of how to user interrupts to interact with the radio. - * It builds on the pingpair_pl example, and uses ack payloads. - */ - -/** - * @example pingpair_sleepy.pde - * - * This is an example of how to use the RF24 class to create a battery- - * efficient system. It is just like the pingpair.pde example, but the - * ping node powers down the radio and sleeps the MCU after every - * ping/pong cycle. - */ - -/** - * @example scanner.pde - * - * Example to detect interference on the various channels available. - * This is a good diagnostic tool to check whether you're picking a - * good channel for your application. - * - * Inspired by cpixip. - * See http://arduino.cc/forum/index.php/topic,54795.0.html - */ - -/** - * @mainpage Driver for nRF24L01(+) 2.4GHz Wireless Transceiver - * - * @section Goals Design Goals - * - * This library is designed to be... - * @li Maximally compliant with the intended operation of the chip - * @li Easy for beginners to use - * @li Consumed with a public interface that's similiar to other Arduino standard libraries - * - * @section News News - * - * NOW COMPATIBLE WITH ARDUINO 1.0 - The 'master' branch and all examples work with both Arduino 1.0 and earlier versions. - * Please open an issue if you find any problems using it with any version of Arduino. - * - * NOW COMPATIBLE WITH MAPLE - RF24 has been tested with the - * Maple Native, - * and should work with any Maple board. See the pingpair_maple example. - * Note that only the pingpair_maple example has been tested on Maple, although - * the others can certainly be adapted. - * - * @section Useful Useful References - * - * Please refer to: - * - * @li Documentation Main Page - * @li RF24 Class Documentation - * @li Source Code - * @li Downloads Page - * @li Chip Datasheet - * - * This chip uses the SPI bus, plus two chip control pins. Remember that pin 10 must still remain an output, or - * the SPI hardware will go into 'slave' mode. - * - * @section More More Information - * - * @subpage FAQ - * - * @section Projects Projects - * - * Stuff I have built with RF24 - * - * RF24 Getting Started - Finished Product - * - * Getting Started with nRF24L01+ on Arduino - * - * Nordic FOB and nRF24L01+ - * - * Using the Sparkfun Nordic FOB - * - * RF Duinode V3 (2V4) - * - * Low-Power Wireless Sensor Node - * - * nRF24L01+ connected to Leaf Labs Maple Native - * - * nRF24L01+ Running on Maple - */ - - -#include "RF24.c" - -#endif // __RF24_H__ -// vim:ai:cin:sts=2 sw=2 ft=cpp - diff --git a/AVR/lib/RF24/RF24_config.h b/AVR/lib/RF24/RF24_config.h deleted file mode 100644 index 6b49201..0000000 --- a/AVR/lib/RF24/RF24_config.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - Copyright (C) 2011,2012 J. Coliz , jaseg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - version 3 as published by the Free Software Foundation. - */ - -/*#ifndef __RF24_CONFIG_H__ -#define __RF24_CONFIG_H__ - -#define CE_PORT PORTB -#define CE_DDR DDRB -#define CE_PIN 0 - -#define CSN_PORT PORTL -#define CSN_DDR DDRL -#define CSN_PIN 0 - -#define MAX_PAYLOAD_SIZE 32 - -//typedef char const char; - -#endif // __RF24_CONFIG_H__ -*/ \ No newline at end of file diff --git a/AVR/lib/RF24/doxygen-custom.css b/AVR/lib/RF24/doxygen-custom.css deleted file mode 100644 index d7d0e12..0000000 --- a/AVR/lib/RF24/doxygen-custom.css +++ /dev/null @@ -1,835 +0,0 @@ -/* The standard CSS for doxygen */ - -body, table, div, p, dl { - font-family: Lucida Grande, Verdana, Geneva, Arial, sans-serif; - font-size: 12px; -} - -/* @group Heading Levels */ - -h1 { - font-size: 150%; -} - -.title { - font-size: 150%; - font-weight: bold; - margin: 10px 2px; -} - -h2 { - font-size: 120%; -} - -h3 { - font-size: 100%; -} - -dt { - font-weight: bold; -} - -div.multicol { - -moz-column-gap: 1em; - -webkit-column-gap: 1em; - -moz-column-count: 3; - -webkit-column-count: 3; -} - -p.startli, p.startdd, p.starttd { - margin-top: 2px; -} - -p.endli { - margin-bottom: 0px; -} - -p.enddd { - margin-bottom: 4px; -} - -p.endtd { - margin-bottom: 2px; -} - -/* @end */ - -caption { - font-weight: bold; -} - -span.legend { - font-size: 70%; - text-align: center; -} - -h3.version { - font-size: 90%; - text-align: center; -} - -div.qindex, div.navtab{ - background-color: #EBEFF6; - border: 1px solid #A3B4D7; - text-align: center; - margin: 2px; - padding: 2px; -} - -div.qindex, div.navpath { - width: 100%; - line-height: 140%; -} - -div.navtab { - margin-right: 15px; -} - -/* @group Link Styling */ - -a { - color: #3D578C; - font-weight: normal; - text-decoration: none; -} - -.contents a:visited { - color: #4665A2; -} - -a:hover { - text-decoration: underline; -} - -a.qindex { - font-weight: bold; -} - -a.qindexHL { - font-weight: bold; - background-color: #9CAFD4; - color: #ffffff; - border: 1px double #869DCA; -} - -.contents a.qindexHL:visited { - color: #ffffff; -} - -a.el { - font-weight: bold; -} - -a.elRef { -} - -a.code { - color: #4665A2; -} - -a.codeRef { - color: #4665A2; -} - -/* @end */ - -dl.el { - margin-left: -1cm; -} - -.fragment { - font-family: monospace, fixed; - font-size: 105%; -} - -pre.fragment { - border: 1px solid #C4CFE5; - background-color: #FBFCFD; - padding: 4px 6px; - margin: 4px 8px 4px 2px; - overflow: auto; - word-wrap: break-word; - font-size: 9pt; - line-height: 125%; -} - -div.ah { - background-color: black; - font-weight: bold; - color: #ffffff; - margin-bottom: 3px; - margin-top: 3px; - padding: 0.2em; - border: solid thin #333; - border-radius: 0.5em; - -webkit-border-radius: .5em; - -moz-border-radius: .5em; - box-shadow: 2px 2px 3px #999; - -webkit-box-shadow: 2px 2px 3px #999; - -moz-box-shadow: rgba(0, 0, 0, 0.15) 2px 2px 2px; - background-image: -webkit-gradient(linear, left top, left bottom, from(#eee), to(#000),color-stop(0.3, #444)); - background-image: -moz-linear-gradient(center top, #eee 0%, #444 40%, #000); -} - -div.groupHeader { - margin-left: 16px; - margin-top: 12px; - font-weight: bold; -} - -div.groupText { - margin-left: 16px; - font-style: italic; -} - -body { - background: white; - color: black; - margin: 0; -} - -div.contents { - margin-top: 10px; - margin-left: 10px; - margin-right: 5px; -} - -td.indexkey { - background-color: #EBEFF6; - font-weight: bold; - border: 1px solid #C4CFE5; - margin: 2px 0px 2px 0; - padding: 2px 10px; -} - -td.indexvalue { - background-color: #EBEFF6; - border: 1px solid #C4CFE5; - padding: 2px 10px; - margin: 2px 0px; -} - -tr.memlist { - background-color: #EEF1F7; -} - -p.formulaDsp { - text-align: center; -} - -img.formulaDsp { - -} - -img.formulaInl { - vertical-align: middle; -} - -div.center { - text-align: center; - margin-top: 0px; - margin-bottom: 0px; - padding: 0px; -} - -div.center img { - border: 0px; -} - -address.footer { - text-align: right; - padding-right: 12px; -} - -img.footer { - border: 0px; - vertical-align: middle; -} - -/* @group Code Colorization */ - -span.keyword { - color: #008000 -} - -span.keywordtype { - color: #604020 -} - -span.keywordflow { - color: #e08000 -} - -span.comment { - color: #800000 -} - -span.preprocessor { - color: #806020 -} - -span.stringliteral { - color: #002080 -} - -span.charliteral { - color: #008080 -} - -span.vhdldigit { - color: #ff00ff -} - -span.vhdlchar { - color: #000000 -} - -span.vhdlkeyword { - color: #700070 -} - -span.vhdllogic { - color: #ff0000 -} - -/* @end */ - -/* -.search { - color: #003399; - font-weight: bold; -} - -form.search { - margin-bottom: 0px; - margin-top: 0px; -} - -input.search { - font-size: 75%; - color: #000080; - font-weight: normal; - background-color: #e8eef2; -} -*/ - -td.tiny { - font-size: 75%; -} - -.dirtab { - padding: 4px; - border-collapse: collapse; - border: 1px solid #A3B4D7; -} - -th.dirtab { - background: #EBEFF6; - font-weight: bold; -} - -hr { - height: 0px; - border: none; - border-top: 1px solid #4A6AAA; -} - -hr.footer { - height: 1px; -} - -/* @group Member Descriptions */ - -table.memberdecls { - border-spacing: 0px; - padding: 0px; -} - -.mdescLeft, .mdescRight, -.memItemLeft, .memItemRight, -.memTemplItemLeft, .memTemplItemRight, .memTemplParams { - background-color: #F9FAFC; - border: none; - margin: 4px; - padding: 1px 0 0 8px; -} - -.mdescLeft, .mdescRight { - padding: 0px 8px 4px 8px; - color: #555; -} - -.memItemLeft, .memItemRight, .memTemplParams { - border-top: 1px solid #C4CFE5; -} - -.memItemLeft, .memTemplItemLeft { - white-space: nowrap; -} - -.memItemRight { - width: 100%; -} - -.memTemplParams { - color: #4665A2; - white-space: nowrap; -} - -/* @end */ - -/* @group Member Details */ - -/* Styles for detailed member documentation */ - -.memtemplate { - font-size: 80%; - color: #4665A2; - font-weight: normal; - margin-left: 9px; -} - -.memnav { - background-color: #EBEFF6; - border: 1px solid #A3B4D7; - text-align: center; - margin: 2px; - margin-right: 15px; - padding: 2px; -} - -.mempage { - width: 100%; -} - -.memitem { - padding: 0; - margin-bottom: 10px; - margin-right: 5px; -} - -.memname { - white-space: nowrap; - font-weight: bold; - margin-left: 6px; -} - -.memproto { - border-top: 1px solid #A8B8D9; - border-left: 1px solid #A8B8D9; - border-right: 1px solid #A8B8D9; - padding: 6px 0px 6px 0px; - color: #253555; - font-weight: bold; - text-shadow: 0px 1px 1px rgba(255, 255, 255, 0.9); - /* opera specific markup */ - box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); - border-top-right-radius: 8px; - border-top-left-radius: 8px; - /* firefox specific markup */ - -moz-box-shadow: rgba(0, 0, 0, 0.15) 5px 5px 5px; - -moz-border-radius-topright: 8px; - -moz-border-radius-topleft: 8px; - /* webkit specific markup */ - -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); - -webkit-border-top-right-radius: 8px; - -webkit-border-top-left-radius: 8px; - background-image:url('nav_f.png'); - background-repeat:repeat-x; - background-color: #E2E8F2; - -} - -.memdoc { - border-bottom: 1px solid #A8B8D9; - border-left: 1px solid #A8B8D9; - border-right: 1px solid #A8B8D9; - padding: 2px 5px; - background-color: #FBFCFD; - border-top-width: 0; - /* opera specific markup */ - border-bottom-left-radius: 8px; - border-bottom-right-radius: 8px; - box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); - /* firefox specific markup */ - -moz-border-radius-bottomleft: 8px; - -moz-border-radius-bottomright: 8px; - -moz-box-shadow: rgba(0, 0, 0, 0.15) 5px 5px 5px; - background-image: -moz-linear-gradient(center top, #FFFFFF 0%, #FFFFFF 60%, #F7F8FB 95%, #EEF1F7); - /* webkit specific markup */ - -webkit-border-bottom-left-radius: 8px; - -webkit-border-bottom-right-radius: 8px; - -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); - background-image: -webkit-gradient(linear,center top,center bottom,from(#FFFFFF), color-stop(0.6,#FFFFFF), color-stop(0.60,#FFFFFF), color-stop(0.95,#F7F8FB), to(#EEF1F7)); -} - -.paramkey { - text-align: right; -} - -.paramtype { - white-space: nowrap; -} - -.paramname { - color: #602020; - white-space: nowrap; -} -.paramname em { - font-style: normal; -} - -.params, .retval, .exception, .tparams { - border-spacing: 6px 2px; -} - -.params .paramname, .retval .paramname { - font-weight: bold; - vertical-align: top; -} - -.params .paramtype { - font-style: italic; - vertical-align: top; -} - -.params .paramdir { - font-family: "courier new",courier,monospace; - vertical-align: top; -} - - - - -/* @end */ - -/* @group Directory (tree) */ - -/* for the tree view */ - -.ftvtree { - font-family: sans-serif; - margin: 0px; -} - -/* these are for tree view when used as main index */ - -.directory { - font-size: 9pt; - font-weight: bold; - margin: 5px; -} - -.directory h3 { - margin: 0px; - margin-top: 1em; - font-size: 11pt; -} - -/* -The following two styles can be used to replace the root node title -with an image of your choice. Simply uncomment the next two styles, -specify the name of your image and be sure to set 'height' to the -proper pixel height of your image. -*/ - -/* -.directory h3.swap { - height: 61px; - background-repeat: no-repeat; - background-image: url("yourimage.gif"); -} -.directory h3.swap span { - display: none; -} -*/ - -.directory > h3 { - margin-top: 0; -} - -.directory p { - margin: 0px; - white-space: nowrap; -} - -.directory div { - display: none; - margin: 0px; -} - -.directory img { - vertical-align: -30%; -} - -/* these are for tree view when not used as main index */ - -.directory-alt { - font-size: 100%; - font-weight: bold; -} - -.directory-alt h3 { - margin: 0px; - margin-top: 1em; - font-size: 11pt; -} - -.directory-alt > h3 { - margin-top: 0; -} - -.directory-alt p { - margin: 0px; - white-space: nowrap; -} - -.directory-alt div { - display: none; - margin: 0px; -} - -.directory-alt img { - vertical-align: -30%; -} - -/* @end */ - -div.dynheader { - margin-top: 8px; -} - -address { - font-style: normal; - color: #2A3D61; -} - -table.doxtable { - border-collapse:collapse; -} - -table.doxtable td, table.doxtable th { - border: 1px solid #2D4068; - padding: 3px 7px 2px; -} - -table.doxtable th { - background-color: #374F7F; - color: #FFFFFF; - font-size: 110%; - padding-bottom: 4px; - padding-top: 5px; - text-align:left; -} - -.tabsearch { - top: 0px; - left: 10px; - height: 36px; - background-image: url('tab_b.png'); - z-index: 101; - overflow: hidden; - font-size: 13px; -} - -.navpath ul -{ - font-size: 11px; - background-image:url('tab_b.png'); - background-repeat:repeat-x; - height:30px; - line-height:30px; - color:#8AA0CC; - border:solid 1px #C2CDE4; - overflow:hidden; - margin:0px; - padding:0px; -} - -.navpath li -{ - list-style-type:none; - float:left; - padding-left:10px; - padding-right:15px; - background-image:url('bc_s.png'); - background-repeat:no-repeat; - background-position:right; - color:#364D7C; -} - -.navpath li.navelem a -{ - height:32px; - display:block; - text-decoration: none; - outline: none; -} - -.navpath li.navelem a:hover -{ - color:#6884BD; -} - -.navpath li.footer -{ - list-style-type:none; - float:right; - padding-left:10px; - padding-right:15px; - background-image:none; - background-repeat:no-repeat; - background-position:right; - color:#364D7C; - font-size: 8pt; -} - - -div.summary -{ - float: right; - font-size: 8pt; - padding-right: 5px; - width: 50%; - text-align: right; -} - -div.summary a -{ - white-space: nowrap; -} - -div.ingroups -{ - font-size: 8pt; - padding-left: 5px; - width: 50%; - text-align: left; -} - -div.ingroups a -{ - white-space: nowrap; -} - -div.header -{ - background-image:url('nav_h.png'); - background-repeat:repeat-x; - background-color: #F9FAFC; - margin: 0px; - border-bottom: 1px solid #C4CFE5; -} - -div.headertitle -{ - padding: 5px 5px 5px 10px; -} - -dl -{ - padding: 0 0 0 10px; -} - -dl.note, dl.warning, dl.attention, dl.pre, dl.post, dl.invariant, dl.deprecated, dl.todo, dl.test, dl.bug -{ - border-left:4px solid; - padding: 0 0 0 6px; -} - -dl.note -{ - border-color: #D0C000; -} - -dl.warning, dl.attention -{ - border-color: #FF0000; -} - -dl.pre, dl.post, dl.invariant -{ - border-color: #00D000; -} - -dl.deprecated -{ - border-color: #505050; -} - -dl.todo -{ - border-color: #00C0E0; -} - -dl.test -{ - border-color: #3030E0; -} - -dl.bug -{ - border-color: #C08050; -} - -#projectlogo -{ - text-align: center; - vertical-align: bottom; - border-collapse: separate; -} - -#projectlogo img -{ - border: 0px none; -} - -#projectname -{ - font: 300% Tahoma, Arial,sans-serif; - margin: 0px; - padding: 2px 0px; -} - -#projectbrief -{ - font: 120% Tahoma, Arial,sans-serif; - margin: 0px; - padding: 0px; -} - -#projectnumber -{ - font: 50% Tahoma, Arial,sans-serif; - margin: 0px; - padding: 0px; -} - -#titlearea -{ - padding: 0px; - margin: 0px; - width: 100%; - border-bottom: 1px solid #5373B4; -} - -.image -{ - text-align: left; -} - -.dotgraph -{ - text-align: center; -} - -.mscgraph -{ - text-align: center; -} - -.caption -{ - font-weight: bold; -} - diff --git a/AVR/lib/RF24/examples/GettingStarted/GettingStarted.pde b/AVR/lib/RF24/examples/GettingStarted/GettingStarted.pde deleted file mode 100644 index 3cb32d5..0000000 --- a/AVR/lib/RF24/examples/GettingStarted/GettingStarted.pde +++ /dev/null @@ -1,227 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * Example for Getting Started with nRF24L01+ radios. - * - * This is an example of how to use the RF24 class. Write this sketch to two - * different nodes. Put one of the nodes into 'transmit' mode by connecting - * with the serial monitor and sending a 'T'. The ping node sends the current - * time to the pong node, which responds by sending the value back. The ping - * node can then see how long the whole cycle took. - */ - -#include -#include "nRF24L01.h" -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 9 & 10 - -RF24 radio(9,10); - -// -// Topology -// - -// Radio pipe addresses for the 2 nodes to communicate. -const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL }; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes -// in this system. Doing so greatly simplifies testing. -// - -// The various roles supported by this sketch -typedef enum { role_ping_out = 1, role_pong_back } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"}; - -// The role of the current running sketch -role_e role = role_pong_back; - -void setup(void) -{ - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/GettingStarted/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - printf("*** PRESS 'T' to begin transmitting to the other node\n\r"); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // optionally, increase the delay between retries & # of retries - radio.setRetries(15,15); - - // optionally, reduce the payload size. seems to - // improve reliability - radio.setPayloadSize(8); - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens two pipes for these two nodes to communicate - // back and forth. - // Open 'our' pipe for writing - // Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading) - - if ( role == role_ping_out ) - { - radio.openWritingPipe(pipes[0]); - radio.openReadingPipe(1,pipes[1]); - } - else - { - radio.openWritingPipe(pipes[1]); - radio.openReadingPipe(1,pipes[0]); - } - - // - // Start listening - // - - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); -} - -void loop(void) -{ - // - // Ping out role. Repeatedly send the current time - // - - if (role == role_ping_out) - { - // First, stop listening so we can talk. - radio.stopListening(); - - // Take the time, and send it. This will block until complete - unsigned long time = millis(); - printf("Now sending %lu...",time); - bool ok = radio.write( &time, sizeof(unsigned long) ); - - if (ok) - printf("ok..."); - else - printf("failed.\n\r"); - - // Now, continue listening - radio.startListening(); - - // Wait here until we get a response, or timeout (250ms) - unsigned long started_waiting_at = millis(); - bool timeout = false; - while ( ! radio.available() && ! timeout ) - if (millis() - started_waiting_at > 200 ) - timeout = true; - - // Describe the results - if ( timeout ) - { - printf("Failed, response timed out.\n\r"); - } - else - { - // Grab the response, compare, and send to debugging spew - unsigned long got_time; - radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got response %lu, round-trip delay: %lu\n\r",got_time,millis()-got_time); - } - - // Try again 1s later - delay(1000); - } - - // - // Pong back role. Receive each packet, dump it out, and send it back - // - - if ( role == role_pong_back ) - { - // if there is data ready - if ( radio.available() ) - { - // Dump the payloads until we've gotten everything - unsigned long got_time; - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - done = radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got payload %lu...",got_time); - - // Delay just a little bit to let the other unit - // make the transition to receiver - delay(20); - } - - // First, stop listening so we can talk - radio.stopListening(); - - // Send the final one back. - radio.write( &got_time, sizeof(unsigned long) ); - printf("Sent response.\n\r"); - - // Now, resume listening so we catch the next packets. - radio.startListening(); - } - } - - // - // Change roles - // - - if ( Serial.available() ) - { - char c = toupper(Serial.read()); - if ( c == 'T' && role == role_pong_back ) - { - printf("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK\n\r"); - - // Become the primary transmitter (ping out) - role = role_ping_out; - radio.openWritingPipe(pipes[0]); - radio.openReadingPipe(1,pipes[1]); - } - else if ( c == 'R' && role == role_ping_out ) - { - printf("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK\n\r"); - - // Become the primary receiver (pong back) - role = role_pong_back; - radio.openWritingPipe(pipes[1]); - radio.openReadingPipe(1,pipes[0]); - } - } -} -// vim:cin:ai:sts=2 sw=2 ft=cpp diff --git a/AVR/lib/RF24/examples/GettingStarted/Jamfile b/AVR/lib/RF24/examples/GettingStarted/Jamfile deleted file mode 100644 index 6a2499a..0000000 --- a/AVR/lib/RF24/examples/GettingStarted/Jamfile +++ /dev/null @@ -1,210 +0,0 @@ -# (1) Project Information - -PROJECT_LIBS = SPI RF24 ; - -# (2) Board Information - -UPLOAD_PROTOCOL ?= stk500v1 ; -UPLOAD_SPEED ?= 57600 ; -MCU ?= atmega328p ; -F_CPU ?= 16000000 ; -CORE ?= arduino ; -VARIANT ?= standard ; -ARDUINO_VERSION ?= 100 ; - -# (3) USB Ports - -PORTS = p4 p6 p9 u0 u1 u2 ; -PORT_p6 = /dev/tty.usbserial-A600eHIs ; -PORT_p4 = /dev/tty.usbserial-A40081RP ; -PORT_p9 = /dev/tty.usbserial-A9007LmI ; -PORT_u0 = /dev/ttyUSB0 ; -PORT_u1 = /dev/ttyUSB1 ; -PORT_u2 = /dev/ttyUSB2 ; - -# (4) Location of AVR tools -# -# This configuration assumes using avr-tools that were obtained separate from the Arduino -# distribution. - -if $(OS) = MACOSX -{ - AVR_BIN = /usr/local/avrtools/bin ; - AVR_ETC = /usr/local/avrtools/etc ; - AVR_INCLUDE = /usr/local/avrtools/include ; -} -else -{ - AVR_BIN = /usr/bin ; - AVR_INCLUDE = /usr/lib/avr/include ; - AVR_ETC = /etc ; -} - -# (5) Directories where Arduino core and libraries are located - -ARDUINO_DIR ?= /opt/Arduino ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/$(CORE) $(ARDUINO_DIR)/hardware/arduino/variants/$(VARIANT) ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; - -# -# -------------------------------------------------- -# Below this line usually never needs to be modified -# - -# Tool locations - -CC = $(AVR_BIN)/avr-gcc ; -C++ = $(AVR_BIN)/avr-g++ ; -LINK = $(AVR_BIN)/avr-gcc ; -OBJCOPY = $(AVR_BIN)/avr-objcopy ; -AVRDUDE = $(AVR_BIN)/avrdude ; - -# Flags - -DEFINES += F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -OPTIM = -Os ; -CCFLAGS = -Wall -Wextra -mmcu=$(MCU) -ffunction-sections -fdata-sections ; -C++FLAGS = $(CCFLAGS) -fno-exceptions -fno-strict-aliasing ; -LINKFLAGS = $(OPTIM) -lm -Wl,--gc-sections -mmcu=$(MCU) ; -AVRDUDEFLAGS = -V -F -D -C $(AVR_ETC)/avrdude.conf -p $(MCU) -c $(UPLOAD_PROTOCOL) -b $(UPLOAD_SPEED) ; - -# Search everywhere for headers - -HDRS = $(PWD) $(AVR_INCLUDE) $(ARDUINO_CORE) $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) ; - -# Output locations - -LOCATE_TARGET = $(F_CPU) ; -LOCATE_SOURCE = $(F_CPU) ; - -# -# Custom rules -# - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule Pde -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_SOURCE) ; - Clean clean : $(<) ; -} - -if ( $(ARDUINO_VERSION) < 100 ) -{ - ARDUINO_H = WProgram.h ; -} -else -{ - ARDUINO_H = Arduino.h ; -} - -actions Pde -{ - echo "#include <$(ARDUINO_H)>" > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule C++Pde -{ - local _CPP = $(>:B).cpp ; - Pde $(_CPP) : $(>) ; - C++ $(<) : $(_CPP) ; -} - -rule UserObject -{ - switch $(>:S) - { - case .ino : C++Pde $(<) : $(>) ; - case .pde : C++Pde $(<) : $(>) ; - } -} - -rule Objects -{ - local _i ; - - for _i in [ FGristFiles $(<) ] - { - local _b = $(_i:B)$(SUFOBJ) ; - local _o = $(_b:G=$(SOURCE_GRIST:E)) ; - Object $(_o) : $(_i) ; - Depends obj : $(_o) ; - } -} - -rule Main -{ - MainFromObjects $(<) : $(>:B)$(SUFOBJ) ; - Objects $(>) ; -} - -rule Hex -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_TARGET) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions Hex -{ - $(OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule Upload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - UploadAction $(2) : $(3) ; -} - -actions UploadAction -{ - $(AVRDUDE) $(AVRDUDEFLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -# -# Targets -# - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp *.c ] ; - -# Grab everything from the current dir -PROJECT_MODULES += [ GLOB $(PWD) : *.c *.cpp *.pde *.ino ] ; - -# Main output executable -MAIN = $(PWD:B).elf ; - -Main $(MAIN) : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -Hex $(MAIN:B).hex : $(MAIN) ; - -# Upload targets -for _p in $(PORTS) -{ - Upload $(_p) : $(PORT_$(_p)) : $(MAIN:B).hex ; -} diff --git a/AVR/lib/RF24/examples/GettingStarted/printf.h b/AVR/lib/RF24/examples/GettingStarted/printf.h deleted file mode 100644 index b2efd56..0000000 --- a/AVR/lib/RF24/examples/GettingStarted/printf.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -#ifdef ARDUINO - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#else -#error This example is only for use on Arduino. -#endif // ARDUINO - -#endif // __PRINTF_H__ diff --git a/AVR/lib/RF24/examples/led_remote/Jamfile b/AVR/lib/RF24/examples/led_remote/Jamfile deleted file mode 100644 index 901f8da..0000000 --- a/AVR/lib/RF24/examples/led_remote/Jamfile +++ /dev/null @@ -1,206 +0,0 @@ -PROJECT_NAME = $(PWD:B) ; -PROJECT_DIR = . ; -PROJECT_LIBS = SPI RF24 ; - -OUT_DIR = ojam ; -F_CPU = 16000000 ; -MCU = atmega328p ; -PORTS = /dev/tty.usbserial-A600eHIs /dev/tty.usbserial-A40081RP /dev/tty.usbserial-A9007LmI ; - -UPLOAD_RATE = 57600 ; -AVRDUDE_PROTOCOL = stk500v1 ; -COM = 33 ; - -# Host-specific overrides for locations -if $(OS) = MACOSX -{ -ARDUINO_VERSION = 22 ; -OLD_DIR = /opt/arduino-0021 ; -AVR_TOOLS_PATH = $(OLD_DIR)/hardware/tools/avr/bin ; -AVRDUDECONFIG_PATH = $(OLD_DIR)/hardware/tools/avr/etc ; -ARDUINO_DIR = /opt/Arduino ; -ARDUINO_AVR = /usr/lib/avr/include ; -} - -# Where is everything? -ARDUINO_VERSION ?= 22 ; -AVR_TOOLS_PATH ?= /usr/bin ; -ARDUINO_DIR ?= /opt/arduino-00$(ARDUINO_VERSION) ; -ARDUINO_AVR ?= $(ARDUINO_DIR)/hardware/tools/avr/avr/include/avr ; -AVRDUDECONFIG_PATH ?= $(ARDUINO_DIR)/hardware/tools ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; -AVR_CC = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_CXX = $(AVR_TOOLS_PATH)/avr-g++ ; -AVR_LD = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_OBJCOPY = $(AVR_TOOLS_PATH)/avr-objcopy ; -AVRDUDE = $(AVR_TOOLS_PATH)/avrdude ; - -DEFINES = F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -CTUNING = -ffunction-sections -fdata-sections ; -CXXTUNING = -fno-exceptions -fno-strict-aliasing ; -CFLAGS = -Os -Wall -Wextra -mmcu=$(MCU) $(CTUNING) ; -CXXFLAGS = $(CFLAGS) $(CXXTUNING) ; -LDFLAGS = -Os -lm -Wl,--gc-sections -mmcu=atmega328p ; - -# Search everywhere for headers -HDRS = $(PROJECT_DIR) $(ARDUINO_AVR) $(ARDUINO_CORE) [ GLOB $(ARDUINO_LIB) $(SKETCH_LIB) : [^.]* ] ; - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp ] ; - -# In addition to explicitly-specified program modules, pick up anything from the current -# dir. -PROJECT_MODULES += [ GLOB $(PROJECT_DIR) : *.c *.cpp *.pde ] ; - -# Shortcut for the out files -OUT = $(OUT_DIR)/$(PROJECT_NAME) ; - -# AvrDude setup -AVRDUDE_FLAGS = -V -F -D -C $(AVRDUDECONFIG_PATH)/avrdude.conf -p $(MCU) -c $(AVRDUDE_PROTOCOL) -b $(UPLOAD_RATE) ; - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule AvrCc -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrCc -{ - $(AVR_CC) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CFLAGS) $(>) -} - -rule AvrC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrC++ -{ - $(AVR_CXX) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule Pde -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - -} - -actions Pde -{ - echo "#include " > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule AvrPde -{ - local _CPP = $(OUT_DIR)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - AvrC++ $(<) : $(_CPP) ; -} - -rule AvrObject -{ - switch $(>:S) - { - case .c : AvrCc $(<) : $(>) ; - case .cpp : AvrC++ $(<) : $(>) ; - case .pde : AvrPde $(<) : $(>) ; - } -} - -rule AvrObjects -{ - for _I in $(<) - { - AvrObject $(OUT_DIR)/$(_I:B).o : $(_I) ; - } -} - -rule AvrMainFromObjects -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - MkDir $(<:D) ; - Depends all : $(<) ; - Clean clean : $(<) ; -} - -actions AvrMainFromObjects -{ - $(AVR_LD) $(LDFLAGS) -o $(<) $(>) -} - -rule AvrMain -{ - AvrMainFromObjects $(<) : $(OUT_DIR)/$(>:B).o ; - AvrObjects $(>) ; -} - -rule AvrHex -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions AvrHex -{ - $(AVR_OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule AvrUpload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - AvrUploadAction $(2) : $(3) ; -} - -actions AvrUploadAction -{ - $(AVRDUDE) $(AVRDUDE_FLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -AvrMain $(OUT).elf : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -AvrHex $(OUT).hex : $(OUT).elf ; - -AvrUpload p6 : /dev/tty.usbserial-A600eHIs : $(OUT).hex ; -AvrUpload p4 : /dev/tty.usbserial-A40081RP : $(OUT).hex ; -AvrUpload p9 : /dev/tty.usbserial-A9007LmI : $(OUT).hex ; - diff --git a/AVR/lib/RF24/examples/led_remote/led_remote.pde b/AVR/lib/RF24/examples/led_remote/led_remote.pde deleted file mode 100644 index 7aeeb3b..0000000 --- a/AVR/lib/RF24/examples/led_remote/led_remote.pde +++ /dev/null @@ -1,255 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * Example LED Remote - * - * This is an example of how to use the RF24 class to control a remote - * bank of LED's using buttons on a remote control. - * - * On the 'remote', connect any number of buttons or switches from - * an arduino pin to ground. Update 'button_pins' to reflect the - * pins used. - * - * On the 'led' board, connect the same number of LED's from an - * arduino pin to a resistor to ground. Update 'led_pins' to reflect - * the pins used. Also connect a separate pin to ground and change - * the 'role_pin'. This tells the sketch it's running on the LED board. - * - * Every time the buttons change on the remote, the entire state of - * buttons is send to the led board, which displays the state. - */ - -#include -#include "nRF24L01.h" -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 9 & 10 - -RF24 radio(9,10); - -// sets the role of this unit in hardware. Connect to GND to be the 'led' board receiver -// Leave open to be the 'remote' transmitter -const int role_pin = A4; - -// Pins on the remote for buttons -const uint8_t button_pins[] = { 2,3,4,5,6,7 }; -const uint8_t num_button_pins = sizeof(button_pins); - -// Pins on the LED board for LED's -const uint8_t led_pins[] = { 2,3,4,5,6,7 }; -const uint8_t num_led_pins = sizeof(led_pins); - -// -// Topology -// - -// Single radio pipe address for the 2 nodes to communicate. -const uint64_t pipe = 0xE8E8F0F0E1LL; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes in this -// system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_remote = 1, role_led } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Remote", "LED Board"}; - -// The role of the current running sketch -role_e role; - -// -// Payload -// - -uint8_t button_states[num_button_pins]; -uint8_t led_states[num_led_pins]; - -// -// Setup -// - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_remote; - else - role = role_led; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/led_remote/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens a single pipes for these two nodes to communicate - // back and forth. One listens on it, the other talks to it. - - if ( role == role_remote ) - { - radio.openWritingPipe(pipe); - } - else - { - radio.openReadingPipe(1,pipe); - } - - // - // Start listening - // - - if ( role == role_led ) - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); - - // - // Set up buttons / LED's - // - - // Set pull-up resistors for all buttons - if ( role == role_remote ) - { - int i = num_button_pins; - while(i--) - { - pinMode(button_pins[i],INPUT); - digitalWrite(button_pins[i],HIGH); - } - } - - // Turn LED's ON until we start getting keys - if ( role == role_led ) - { - int i = num_led_pins; - while(i--) - { - pinMode(button_pins[i],OUTPUT); - led_states[i] = HIGH; - digitalWrite(led_pins[i],led_states[i]); - } - } - -} - -// -// Loop -// - -void loop(void) -{ - // - // Remote role. If the state of any button has changed, send the whole state of - // all buttons. - // - - if ( role == role_remote ) - { - // Get the current state of buttons, and - // Test if the current state is different from the last state we sent - int i = num_button_pins; - bool different = false; - while(i--) - { - uint8_t state = ! digitalRead(button_pins[i]); - if ( state != button_states[i] ) - { - different = true; - button_states[i] = state; - } - } - - // Send the state of the buttons to the LED board - if ( different ) - { - printf("Now sending..."); - bool ok = radio.write( button_states, num_button_pins ); - if (ok) - printf("ok\n\r"); - else - printf("failed\n\r"); - } - - // Try again in a short while - delay(20); - } - - // - // LED role. Receive the state of all buttons, and reflect that in the LEDs - // - - if ( role == role_led ) - { - // if there is data ready - if ( radio.available() ) - { - // Dump the payloads until we've gotten everything - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - done = radio.read( button_states, num_button_pins ); - - // Spew it - printf("Got buttons\n\r"); - - // For each button, if the button now on, then toggle the LED - int i = num_led_pins; - while(i--) - { - if ( button_states[i] ) - { - led_states[i] ^= HIGH; - digitalWrite(led_pins[i],led_states[i]); - } - } - } - } - } -} -// vim:ai:cin:sts=2 sw=2 ft=cpp diff --git a/AVR/lib/RF24/examples/led_remote/printf.h b/AVR/lib/RF24/examples/led_remote/printf.h deleted file mode 100644 index b2efd56..0000000 --- a/AVR/lib/RF24/examples/led_remote/printf.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -#ifdef ARDUINO - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#else -#error This example is only for use on Arduino. -#endif // ARDUINO - -#endif // __PRINTF_H__ diff --git a/AVR/lib/RF24/examples/nordic_fob/Jamfile b/AVR/lib/RF24/examples/nordic_fob/Jamfile deleted file mode 100644 index ec519f7..0000000 --- a/AVR/lib/RF24/examples/nordic_fob/Jamfile +++ /dev/null @@ -1,219 +0,0 @@ -# (1) Project Information - -PROJECT_LIBS = RF24 SPI ; -PROJECT_DIRS = $(PWD) ; - -# (2) Board Information - -UPLOAD_PROTOCOL ?= stk500v1 ; -UPLOAD_SPEED ?= 115200 ; -MCU ?= atmega328p ; -F_CPU ?= 16000000 ; -CORE ?= arduino ; -VARIANT ?= standard ; -ARDUINO_VERSION ?= 100 ; - -# (3) USB Ports - -PORTS = p4 p6 p9 u0 u1 u2 ; -PORT_p6 = /dev/tty.usbserial-A600eHIs ; -PORT_p4 = /dev/tty.usbserial-A40081RP ; -PORT_p9 = /dev/tty.usbserial-A9007LmI ; -PORT_u0 = /dev/ttyUSB0 ; -PORT_u1 = /dev/ttyUSB1 ; -PORT_u2 = /dev/ttyUSB2 ; - -# (4) Location of AVR tools -# -# This configuration assumes using avr-tools that were obtained separate from the Arduino -# distribution. - -if $(OS) = MACOSX -{ - AVR_BIN = /usr/local/avrtools/bin ; - AVR_ETC = /usr/local/avrtools/etc ; - AVR_INCLUDE = /usr/local/avrtools/include ; -} -else -{ - AVR_BIN = /usr/bin ; - AVR_INCLUDE = /usr/lib/avr/include ; - AVR_ETC = /etc ; -} - -# (5) Directories where Arduino core and libraries are located - -ARDUINO_DIR ?= /opt/Arduino ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/$(CORE) $(ARDUINO_DIR)/hardware/arduino/variants/$(VARIANT) ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; - -# -# -------------------------------------------------- -# Below this line usually never needs to be modified -# - -# Tool locations - -CC = $(AVR_BIN)/avr-gcc ; -C++ = $(AVR_BIN)/avr-g++ ; -LINK = $(AVR_BIN)/avr-gcc ; -AR = $(AVR_BIN)/avr-ar rcs ; -RANLIB = ; -OBJCOPY = $(AVR_BIN)/avr-objcopy ; -AVRDUDE = $(AVR_BIN)/avrdude ; - -# Flags - -DEFINES += F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -OPTIM = -Os ; -CCFLAGS = -Wall -Wextra -Wno-strict-aliasing -mmcu=$(MCU) -ffunction-sections -fdata-sections ; -C++FLAGS = $(CCFLAGS) -fno-exceptions -fno-strict-aliasing ; -LINKFLAGS = $(OPTIM) -lm -Wl,--gc-sections -mmcu=$(MCU) ; -AVRDUDEFLAGS = -V -F -D -C $(AVR_ETC)/avrdude.conf -p $(MCU) -c $(UPLOAD_PROTOCOL) -b $(UPLOAD_SPEED) ; - -# Search everywhere for headers - -HDRS = $(PROJECT_DIRS) $(AVR_INCLUDE) $(ARDUINO_CORE) $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) ; - -# Output locations - -LOCATE_TARGET = $(F_CPU) ; -LOCATE_SOURCE = $(F_CPU) ; - -# -# Custom rules -# - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule Pde -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_SOURCE) ; - Clean clean : $(<) ; -} - -if ( $(ARDUINO_VERSION) < 100 ) -{ - ARDUINO_H = WProgram.h ; -} -else -{ - ARDUINO_H = Arduino.h ; -} - -actions Pde -{ - echo "#include <$(ARDUINO_H)>" > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule C++Pde -{ - local _CPP = $(>:B).cpp ; - Pde $(_CPP) : $(>) ; - C++ $(<) : $(_CPP) ; -} - -rule UserObject -{ - switch $(>:S) - { - case .ino : C++Pde $(<) : $(>) ; - case .pde : C++Pde $(<) : $(>) ; - } -} - -rule Objects -{ - local _i ; - - for _i in [ FGristFiles $(<) ] - { - local _b = $(_i:B)$(SUFOBJ) ; - local _o = $(_b:G=$(SOURCE_GRIST:E)) ; - Object $(_o) : $(_i) ; - Depends obj : $(_o) ; - } -} - -rule Library -{ - LibraryFromObjects $(<) : $(>:B)$(SUFOBJ) ; - Objects $(>) ; -} - -rule Main -{ - MainFromObjects $(<) : $(>:B)$(SUFOBJ) ; - Objects $(>) ; -} - -rule Hex -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_TARGET) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions Hex -{ - $(OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule Upload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - UploadAction $(2) : $(3) ; -} - -actions UploadAction -{ - $(AVRDUDE) $(AVRDUDEFLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -rule Arduino -{ - LINKFLAGS on $(<) = $(LINKFLAGS) -Wl,-Map=$(LOCATE_TARGET)/$(<:B).map ; - Main $(<) : $(>) ; - LinkLibraries $(<) : libs core ; - Hex $(<:B).hex : $(<) ; - for _p in $(PORTS) - { - Upload $(_p) : $(PORT_$(_p)) : $(<:B).hex ; - } -} - -# -# Targets -# - -# Grab everything from the core directory -Library core : [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -Library libs : [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp *.c ] ; - -# Main output executable -Arduino $(PWD:B).elf : $(PROJECT_MODULES) [ GLOB $(PROJECT_DIRS) : *.c *.cpp *.pde *.ino ] ; diff --git a/AVR/lib/RF24/examples/nordic_fob/nordic_fob.pde b/AVR/lib/RF24/examples/nordic_fob/nordic_fob.pde deleted file mode 100644 index 5a316a0..0000000 --- a/AVR/lib/RF24/examples/nordic_fob/nordic_fob.pde +++ /dev/null @@ -1,142 +0,0 @@ -/* - Copyright (C) 2012 J. Coliz - - 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. - */ - -/** - * Example Nordic FOB Receiver - * - * This is an example of how to use the RF24 class to receive signals from the - * Sparkfun Nordic FOB. Thanks to Kirk Mower for providing test hardware. - * - * See blog post at http://maniacbug.wordpress.com/2012/01/08/nordic-fob/ - */ - -#include -#include -#include "nRF24L01.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 9 & 10 - -RF24 radio(9,10); - -// -// Payload -// - -struct payload_t -{ - uint8_t buttons; - uint16_t id; - uint8_t empty; -}; - -const char* button_names[] = { "Up", "Down", "Left", "Right", "Center" }; -const int num_buttons = 5; - -// -// Forward declarations -// - -uint16_t flip_endian(uint16_t in); - -// -// Setup -// - -void setup(void) -{ - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\r\nRF24/examples/nordic_fob/\r\n"); - - // - // Setup and configure rf radio according to the built-in parameters - // of the FOB. - // - - radio.begin(); - radio.setChannel(2); - radio.setPayloadSize(4); - radio.setAutoAck(false); - radio.setCRCLength(RF24_CRC_8); - radio.openReadingPipe(1,0xE7E7E7E7E7LL); - - // - // Start listening - // - - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); -} - -// -// Loop -// - -void loop(void) -{ - // - // Receive each packet, dump it out - // - - // if there is data ready - if ( radio.available() ) - { - // Get the packet from the radio - payload_t payload; - radio.read( &payload, sizeof(payload) ); - - // Print the ID of this message. Note that the message - // is sent 'big-endian', so we have to flip it. - printf("#%05u Buttons ",flip_endian(payload.id)); - - // Print the name of each button - int i = num_buttons; - while (i--) - { - if ( ! ( payload.buttons & _BV(i) ) ) - { - printf("%s ",button_names[i]); - } - } - - // If no buttons, print None - if ( payload.buttons == _BV(num_buttons) - 1 ) - printf("None"); - - printf("\r\n"); - } -} - -// -// Helper functions -// - -// Change a big-endian word into a little-endian -uint16_t flip_endian(uint16_t in) -{ - uint16_t low = in >> 8; - uint16_t high = in << 8; - - return high | low; -} - -// vim:cin:ai:sts=2 sw=2 ft=cpp diff --git a/AVR/lib/RF24/examples/nordic_fob/printf.h b/AVR/lib/RF24/examples/nordic_fob/printf.h deleted file mode 100644 index b2efd56..0000000 --- a/AVR/lib/RF24/examples/nordic_fob/printf.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -#ifdef ARDUINO - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#else -#error This example is only for use on Arduino. -#endif // ARDUINO - -#endif // __PRINTF_H__ diff --git a/AVR/lib/RF24/examples/pingpair/Jamfile b/AVR/lib/RF24/examples/pingpair/Jamfile deleted file mode 100644 index 18244ec..0000000 --- a/AVR/lib/RF24/examples/pingpair/Jamfile +++ /dev/null @@ -1,219 +0,0 @@ -# (1) Project Information - -PROJECT_LIBS = SPI RF24 ; -PROJECT_DIRS = $(PWD) ; - -# (2) Board Information - -UPLOAD_PROTOCOL ?= arduino ; -UPLOAD_SPEED ?= 115200 ; -MCU ?= atmega328p ; -F_CPU ?= 16000000 ; -CORE ?= arduino ; -VARIANT ?= standard ; -ARDUINO_VERSION ?= 100 ; - -# (3) USB Ports - -PORTS = p4 p6 p9 u0 u1 u2 ; -PORT_p6 = /dev/tty.usbserial-A600eHIs ; -PORT_p4 = /dev/tty.usbserial-A40081RP ; -PORT_p9 = /dev/tty.usbserial-A9007LmI ; -PORT_u0 = /dev/ttyUSB0 ; -PORT_u1 = /dev/ttyUSB1 ; -PORT_u2 = /dev/ttyUSB2 ; - -# (4) Location of AVR tools -# -# This configuration assumes using avr-tools that were obtained separate from the Arduino -# distribution. - -if $(OS) = MACOSX -{ - AVR_BIN ?= /usr/local/avrtools/bin ; - AVR_ETC = /usr/local/avrtools/etc ; - AVR_INCLUDE = /usr/local/avrtools/include ; -} -else -{ - AVR_BIN ?= /usr/bin ; - AVR_INCLUDE = /usr/lib/avr/include ; - AVR_ETC = /etc ; -} - -# (5) Directories where Arduino core and libraries are located - -ARDUINO_DIR ?= /opt/Arduino ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/$(CORE) $(ARDUINO_DIR)/hardware/arduino/variants/$(VARIANT) ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; - -# -# -------------------------------------------------- -# Below this line usually never needs to be modified -# - -# Tool locations - -CC = $(AVR_BIN)/avr-gcc ; -C++ = $(AVR_BIN)/avr-g++ ; -LINK = $(AVR_BIN)/avr-gcc ; -AR = $(AVR_BIN)/avr-ar rcs ; -RANLIB = ; -OBJCOPY = $(AVR_BIN)/avr-objcopy ; -AVRDUDE ?= $(AVR_BIN)/avrdude ; - -# Flags - -DEFINES += F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -OPTIM = -Os ; -CCFLAGS = -Wall -Wextra -Wno-strict-aliasing -mmcu=$(MCU) -ffunction-sections -fdata-sections ; -C++FLAGS = $(CCFLAGS) -fno-exceptions -fno-strict-aliasing ; -LINKFLAGS = $(OPTIM) -lm -Wl,--gc-sections -mmcu=$(MCU) ; -AVRDUDEFLAGS = -V -F -D -C $(AVR_ETC)/avrdude.conf -p $(MCU) -c $(UPLOAD_PROTOCOL) -b $(UPLOAD_SPEED) ; - -# Search everywhere for headers - -HDRS = $(PROJECT_DIRS) $(AVR_INCLUDE) $(ARDUINO_CORE) $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) ; - -# Output locations - -LOCATE_TARGET = $(F_CPU) ; -LOCATE_SOURCE = $(F_CPU) ; - -# -# Custom rules -# - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule Pde -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_SOURCE) ; - Clean clean : $(<) ; -} - -if ( $(ARDUINO_VERSION) < 100 ) -{ - ARDUINO_H = WProgram.h ; -} -else -{ - ARDUINO_H = Arduino.h ; -} - -actions Pde -{ - echo "#include <$(ARDUINO_H)>" > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule C++Pde -{ - local _CPP = $(>:B).cpp ; - Pde $(_CPP) : $(>) ; - C++ $(<) : $(_CPP) ; -} - -rule UserObject -{ - switch $(>:S) - { - case .ino : C++Pde $(<) : $(>) ; - case .pde : C++Pde $(<) : $(>) ; - } -} - -rule Objects -{ - local _i ; - - for _i in [ FGristFiles $(<) ] - { - local _b = $(_i:B)$(SUFOBJ) ; - local _o = $(_b:G=$(SOURCE_GRIST:E)) ; - Object $(_o) : $(_i) ; - Depends obj : $(_o) ; - } -} - -rule Library -{ - LibraryFromObjects $(<) : $(>:B)$(SUFOBJ) ; - Objects $(>) ; -} - -rule Main -{ - MainFromObjects $(<) : $(>:B)$(SUFOBJ) ; - Objects $(>) ; -} - -rule Hex -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_TARGET) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions Hex -{ - $(OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule Upload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - UploadAction $(2) : $(3) ; -} - -actions UploadAction -{ - $(AVRDUDE) $(AVRDUDEFLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -rule Arduino -{ - LINKFLAGS on $(<) = $(LINKFLAGS) -Wl,-Map=$(LOCATE_TARGET)/$(<:B).map ; - Main $(<) : $(>) ; - LinkLibraries $(<) : core libs ; - Hex $(<:B).hex : $(<) ; - for _p in $(PORTS) - { - Upload $(_p) : $(PORT_$(_p)) : $(<:B).hex ; - } -} - -# -# Targets -# - -# Grab everything from the core directory -Library core : [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -Library libs : [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp *.c ] ; - -# Main output executable -Arduino $(PWD:B).elf : $(PROJECT_MODULES) [ GLOB $(PROJECT_DIRS) : *.c *.cpp *.pde *.ino ] ; diff --git a/AVR/lib/RF24/examples/pingpair/pingpair.pde b/AVR/lib/RF24/examples/pingpair/pingpair.pde deleted file mode 100644 index 3a57a67..0000000 --- a/AVR/lib/RF24/examples/pingpair/pingpair.pde +++ /dev/null @@ -1,220 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * Example RF Radio Ping Pair - * - * This is an example of how to use the RF24 class. Write this sketch to two different nodes, - * connect the role_pin to ground on one. The ping node sends the current time to the pong node, - * which responds by sending the value back. The ping node can then see how long the whole cycle - * took. - */ - -#include -#include "nRF24L01.h" -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 9 & 10 - -RF24 radio(9,10); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const int role_pin = 7; - -// -// Topology -// - -// Radio pipe addresses for the 2 nodes to communicate. -const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL }; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes -// in this system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_ping_out = 1, role_pong_back } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"}; - -// The role of the current running sketch -role_e role; - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( ! digitalRead(role_pin) ) - role = role_ping_out; - else - role = role_pong_back; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/pingpair/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // optionally, increase the delay between retries & # of retries - radio.setRetries(15,15); - - // optionally, reduce the payload size. seems to - // improve reliability - radio.setPayloadSize(8); - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens two pipes for these two nodes to communicate - // back and forth. - // Open 'our' pipe for writing - // Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading) - - if ( role == role_ping_out ) - { - radio.openWritingPipe(pipes[0]); - radio.openReadingPipe(1,pipes[1]); - } - else - { - radio.openWritingPipe(pipes[1]); - radio.openReadingPipe(1,pipes[0]); - } - - // - // Start listening - // - - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); -} - -void loop(void) -{ - // - // Ping out role. Repeatedly send the current time - // - - if (role == role_ping_out) - { - // First, stop listening so we can talk. - radio.stopListening(); - - // Take the time, and send it. This will block until complete - unsigned long time = millis(); - printf("Now sending %lu...",time); - bool ok = radio.write( &time, sizeof(unsigned long) ); - - if (ok) - printf("ok..."); - else - printf("failed.\n\r"); - - // Now, continue listening - radio.startListening(); - - // Wait here until we get a response, or timeout (250ms) - unsigned long started_waiting_at = millis(); - bool timeout = false; - while ( ! radio.available() && ! timeout ) - if (millis() - started_waiting_at > 200 ) - timeout = true; - - // Describe the results - if ( timeout ) - { - printf("Failed, response timed out.\n\r"); - } - else - { - // Grab the response, compare, and send to debugging spew - unsigned long got_time; - radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got response %lu, round-trip delay: %lu\n\r",got_time,millis()-got_time); - } - - // Try again 1s later - delay(1000); - } - - // - // Pong back role. Receive each packet, dump it out, and send it back - // - - if ( role == role_pong_back ) - { - // if there is data ready - if ( radio.available() ) - { - // Dump the payloads until we've gotten everything - unsigned long got_time; - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - done = radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got payload %lu...",got_time); - - // Delay just a little bit to let the other unit - // make the transition to receiver - delay(20); - } - - // First, stop listening so we can talk - radio.stopListening(); - - // Send the final one back. - radio.write( &got_time, sizeof(unsigned long) ); - printf("Sent response.\n\r"); - - // Now, resume listening so we catch the next packets. - radio.startListening(); - } - } -} -// vim:cin:ai:sts=2 sw=2 ft=cpp diff --git a/AVR/lib/RF24/examples/pingpair/printf.h b/AVR/lib/RF24/examples/pingpair/printf.h deleted file mode 100644 index b2efd56..0000000 --- a/AVR/lib/RF24/examples/pingpair/printf.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -#ifdef ARDUINO - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#else -#error This example is only for use on Arduino. -#endif // ARDUINO - -#endif // __PRINTF_H__ diff --git a/AVR/lib/RF24/examples/pingpair_dyn/Jamfile b/AVR/lib/RF24/examples/pingpair_dyn/Jamfile deleted file mode 100644 index 901f8da..0000000 --- a/AVR/lib/RF24/examples/pingpair_dyn/Jamfile +++ /dev/null @@ -1,206 +0,0 @@ -PROJECT_NAME = $(PWD:B) ; -PROJECT_DIR = . ; -PROJECT_LIBS = SPI RF24 ; - -OUT_DIR = ojam ; -F_CPU = 16000000 ; -MCU = atmega328p ; -PORTS = /dev/tty.usbserial-A600eHIs /dev/tty.usbserial-A40081RP /dev/tty.usbserial-A9007LmI ; - -UPLOAD_RATE = 57600 ; -AVRDUDE_PROTOCOL = stk500v1 ; -COM = 33 ; - -# Host-specific overrides for locations -if $(OS) = MACOSX -{ -ARDUINO_VERSION = 22 ; -OLD_DIR = /opt/arduino-0021 ; -AVR_TOOLS_PATH = $(OLD_DIR)/hardware/tools/avr/bin ; -AVRDUDECONFIG_PATH = $(OLD_DIR)/hardware/tools/avr/etc ; -ARDUINO_DIR = /opt/Arduino ; -ARDUINO_AVR = /usr/lib/avr/include ; -} - -# Where is everything? -ARDUINO_VERSION ?= 22 ; -AVR_TOOLS_PATH ?= /usr/bin ; -ARDUINO_DIR ?= /opt/arduino-00$(ARDUINO_VERSION) ; -ARDUINO_AVR ?= $(ARDUINO_DIR)/hardware/tools/avr/avr/include/avr ; -AVRDUDECONFIG_PATH ?= $(ARDUINO_DIR)/hardware/tools ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; -AVR_CC = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_CXX = $(AVR_TOOLS_PATH)/avr-g++ ; -AVR_LD = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_OBJCOPY = $(AVR_TOOLS_PATH)/avr-objcopy ; -AVRDUDE = $(AVR_TOOLS_PATH)/avrdude ; - -DEFINES = F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -CTUNING = -ffunction-sections -fdata-sections ; -CXXTUNING = -fno-exceptions -fno-strict-aliasing ; -CFLAGS = -Os -Wall -Wextra -mmcu=$(MCU) $(CTUNING) ; -CXXFLAGS = $(CFLAGS) $(CXXTUNING) ; -LDFLAGS = -Os -lm -Wl,--gc-sections -mmcu=atmega328p ; - -# Search everywhere for headers -HDRS = $(PROJECT_DIR) $(ARDUINO_AVR) $(ARDUINO_CORE) [ GLOB $(ARDUINO_LIB) $(SKETCH_LIB) : [^.]* ] ; - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp ] ; - -# In addition to explicitly-specified program modules, pick up anything from the current -# dir. -PROJECT_MODULES += [ GLOB $(PROJECT_DIR) : *.c *.cpp *.pde ] ; - -# Shortcut for the out files -OUT = $(OUT_DIR)/$(PROJECT_NAME) ; - -# AvrDude setup -AVRDUDE_FLAGS = -V -F -D -C $(AVRDUDECONFIG_PATH)/avrdude.conf -p $(MCU) -c $(AVRDUDE_PROTOCOL) -b $(UPLOAD_RATE) ; - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule AvrCc -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrCc -{ - $(AVR_CC) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CFLAGS) $(>) -} - -rule AvrC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrC++ -{ - $(AVR_CXX) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule Pde -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - -} - -actions Pde -{ - echo "#include " > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule AvrPde -{ - local _CPP = $(OUT_DIR)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - AvrC++ $(<) : $(_CPP) ; -} - -rule AvrObject -{ - switch $(>:S) - { - case .c : AvrCc $(<) : $(>) ; - case .cpp : AvrC++ $(<) : $(>) ; - case .pde : AvrPde $(<) : $(>) ; - } -} - -rule AvrObjects -{ - for _I in $(<) - { - AvrObject $(OUT_DIR)/$(_I:B).o : $(_I) ; - } -} - -rule AvrMainFromObjects -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - MkDir $(<:D) ; - Depends all : $(<) ; - Clean clean : $(<) ; -} - -actions AvrMainFromObjects -{ - $(AVR_LD) $(LDFLAGS) -o $(<) $(>) -} - -rule AvrMain -{ - AvrMainFromObjects $(<) : $(OUT_DIR)/$(>:B).o ; - AvrObjects $(>) ; -} - -rule AvrHex -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions AvrHex -{ - $(AVR_OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule AvrUpload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - AvrUploadAction $(2) : $(3) ; -} - -actions AvrUploadAction -{ - $(AVRDUDE) $(AVRDUDE_FLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -AvrMain $(OUT).elf : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -AvrHex $(OUT).hex : $(OUT).elf ; - -AvrUpload p6 : /dev/tty.usbserial-A600eHIs : $(OUT).hex ; -AvrUpload p4 : /dev/tty.usbserial-A40081RP : $(OUT).hex ; -AvrUpload p9 : /dev/tty.usbserial-A9007LmI : $(OUT).hex ; - diff --git a/AVR/lib/RF24/examples/pingpair_dyn/pingpair_dyn.pde b/AVR/lib/RF24/examples/pingpair_dyn/pingpair_dyn.pde deleted file mode 100644 index 7108f3b..0000000 --- a/AVR/lib/RF24/examples/pingpair_dyn/pingpair_dyn.pde +++ /dev/null @@ -1,232 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * Example using Dynamic Payloads - * - * This is an example of how to use payloads of a varying (dynamic) size. - */ - -#include -#include "nRF24L01.h" -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 9 & 10 - -RF24 radio(9,10); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const int role_pin = 7; - -// -// Topology -// - -// Radio pipe addresses for the 2 nodes to communicate. -const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL }; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes -// in this system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_ping_out = 1, role_pong_back } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"}; - -// The role of the current running sketch -role_e role; - -// -// Payload -// - -const int min_payload_size = 4; -const int max_payload_size = 32; -const int payload_size_increments_by = 2; -int next_payload_size = min_payload_size; - -char receive_payload[max_payload_size+1]; // +1 to allow room for a terminating NULL char - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_ping_out; - else - role = role_pong_back; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/pingpair_dyn/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // enable dynamic payloads - radio.enableDynamicPayloads(); - - // optionally, increase the delay between retries & # of retries - radio.setRetries(15,15); - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens two pipes for these two nodes to communicate - // back and forth. - // Open 'our' pipe for writing - // Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading) - - if ( role == role_ping_out ) - { - radio.openWritingPipe(pipes[0]); - radio.openReadingPipe(1,pipes[1]); - } - else - { - radio.openWritingPipe(pipes[1]); - radio.openReadingPipe(1,pipes[0]); - } - - // - // Start listening - // - - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); -} - -void loop(void) -{ - // - // Ping out role. Repeatedly send the current time - // - - if (role == role_ping_out) - { - // The payload will always be the same, what will change is how much of it we send. - static char send_payload[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ789012"; - - // First, stop listening so we can talk. - radio.stopListening(); - - // Take the time, and send it. This will block until complete - printf("Now sending length %i...",next_payload_size); - radio.write( send_payload, next_payload_size ); - - // Now, continue listening - radio.startListening(); - - // Wait here until we get a response, or timeout - unsigned long started_waiting_at = millis(); - bool timeout = false; - while ( ! radio.available() && ! timeout ) - if (millis() - started_waiting_at > 500 ) - timeout = true; - - // Describe the results - if ( timeout ) - { - printf("Failed, response timed out.\n\r"); - } - else - { - // Grab the response, compare, and send to debugging spew - uint8_t len = radio.getDynamicPayloadSize(); - radio.read( receive_payload, len ); - - // Put a zero at the end for easy printing - receive_payload[len] = 0; - - // Spew it - printf("Got response size=%i value=%s\n\r",len,receive_payload); - } - - // Update size for next time. - next_payload_size += payload_size_increments_by; - if ( next_payload_size > max_payload_size ) - next_payload_size = min_payload_size; - - // Try again 1s later - delay(1000); - } - - // - // Pong back role. Receive each packet, dump it out, and send it back - // - - if ( role == role_pong_back ) - { - // if there is data ready - if ( radio.available() ) - { - // Dump the payloads until we've gotten everything - uint8_t len; - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - len = radio.getDynamicPayloadSize(); - done = radio.read( receive_payload, len ); - - // Put a zero at the end for easy printing - receive_payload[len] = 0; - - // Spew it - printf("Got payload size=%i value=%s\n\r",len,receive_payload); - } - - // First, stop listening so we can talk - radio.stopListening(); - - // Send the final one back. - radio.write( receive_payload, len ); - printf("Sent response.\n\r"); - - // Now, resume listening so we catch the next packets. - radio.startListening(); - } - } -} -// vim:cin:ai:sts=2 sw=2 ft=cpp diff --git a/AVR/lib/RF24/examples/pingpair_dyn/printf.h b/AVR/lib/RF24/examples/pingpair_dyn/printf.h deleted file mode 100644 index b2efd56..0000000 --- a/AVR/lib/RF24/examples/pingpair_dyn/printf.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -#ifdef ARDUINO - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#else -#error This example is only for use on Arduino. -#endif // ARDUINO - -#endif // __PRINTF_H__ diff --git a/AVR/lib/RF24/examples/pingpair_irq/Jamfile b/AVR/lib/RF24/examples/pingpair_irq/Jamfile deleted file mode 100644 index 18244ec..0000000 --- a/AVR/lib/RF24/examples/pingpair_irq/Jamfile +++ /dev/null @@ -1,219 +0,0 @@ -# (1) Project Information - -PROJECT_LIBS = SPI RF24 ; -PROJECT_DIRS = $(PWD) ; - -# (2) Board Information - -UPLOAD_PROTOCOL ?= arduino ; -UPLOAD_SPEED ?= 115200 ; -MCU ?= atmega328p ; -F_CPU ?= 16000000 ; -CORE ?= arduino ; -VARIANT ?= standard ; -ARDUINO_VERSION ?= 100 ; - -# (3) USB Ports - -PORTS = p4 p6 p9 u0 u1 u2 ; -PORT_p6 = /dev/tty.usbserial-A600eHIs ; -PORT_p4 = /dev/tty.usbserial-A40081RP ; -PORT_p9 = /dev/tty.usbserial-A9007LmI ; -PORT_u0 = /dev/ttyUSB0 ; -PORT_u1 = /dev/ttyUSB1 ; -PORT_u2 = /dev/ttyUSB2 ; - -# (4) Location of AVR tools -# -# This configuration assumes using avr-tools that were obtained separate from the Arduino -# distribution. - -if $(OS) = MACOSX -{ - AVR_BIN ?= /usr/local/avrtools/bin ; - AVR_ETC = /usr/local/avrtools/etc ; - AVR_INCLUDE = /usr/local/avrtools/include ; -} -else -{ - AVR_BIN ?= /usr/bin ; - AVR_INCLUDE = /usr/lib/avr/include ; - AVR_ETC = /etc ; -} - -# (5) Directories where Arduino core and libraries are located - -ARDUINO_DIR ?= /opt/Arduino ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/$(CORE) $(ARDUINO_DIR)/hardware/arduino/variants/$(VARIANT) ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; - -# -# -------------------------------------------------- -# Below this line usually never needs to be modified -# - -# Tool locations - -CC = $(AVR_BIN)/avr-gcc ; -C++ = $(AVR_BIN)/avr-g++ ; -LINK = $(AVR_BIN)/avr-gcc ; -AR = $(AVR_BIN)/avr-ar rcs ; -RANLIB = ; -OBJCOPY = $(AVR_BIN)/avr-objcopy ; -AVRDUDE ?= $(AVR_BIN)/avrdude ; - -# Flags - -DEFINES += F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -OPTIM = -Os ; -CCFLAGS = -Wall -Wextra -Wno-strict-aliasing -mmcu=$(MCU) -ffunction-sections -fdata-sections ; -C++FLAGS = $(CCFLAGS) -fno-exceptions -fno-strict-aliasing ; -LINKFLAGS = $(OPTIM) -lm -Wl,--gc-sections -mmcu=$(MCU) ; -AVRDUDEFLAGS = -V -F -D -C $(AVR_ETC)/avrdude.conf -p $(MCU) -c $(UPLOAD_PROTOCOL) -b $(UPLOAD_SPEED) ; - -# Search everywhere for headers - -HDRS = $(PROJECT_DIRS) $(AVR_INCLUDE) $(ARDUINO_CORE) $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) ; - -# Output locations - -LOCATE_TARGET = $(F_CPU) ; -LOCATE_SOURCE = $(F_CPU) ; - -# -# Custom rules -# - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule Pde -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_SOURCE) ; - Clean clean : $(<) ; -} - -if ( $(ARDUINO_VERSION) < 100 ) -{ - ARDUINO_H = WProgram.h ; -} -else -{ - ARDUINO_H = Arduino.h ; -} - -actions Pde -{ - echo "#include <$(ARDUINO_H)>" > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule C++Pde -{ - local _CPP = $(>:B).cpp ; - Pde $(_CPP) : $(>) ; - C++ $(<) : $(_CPP) ; -} - -rule UserObject -{ - switch $(>:S) - { - case .ino : C++Pde $(<) : $(>) ; - case .pde : C++Pde $(<) : $(>) ; - } -} - -rule Objects -{ - local _i ; - - for _i in [ FGristFiles $(<) ] - { - local _b = $(_i:B)$(SUFOBJ) ; - local _o = $(_b:G=$(SOURCE_GRIST:E)) ; - Object $(_o) : $(_i) ; - Depends obj : $(_o) ; - } -} - -rule Library -{ - LibraryFromObjects $(<) : $(>:B)$(SUFOBJ) ; - Objects $(>) ; -} - -rule Main -{ - MainFromObjects $(<) : $(>:B)$(SUFOBJ) ; - Objects $(>) ; -} - -rule Hex -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_TARGET) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions Hex -{ - $(OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule Upload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - UploadAction $(2) : $(3) ; -} - -actions UploadAction -{ - $(AVRDUDE) $(AVRDUDEFLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -rule Arduino -{ - LINKFLAGS on $(<) = $(LINKFLAGS) -Wl,-Map=$(LOCATE_TARGET)/$(<:B).map ; - Main $(<) : $(>) ; - LinkLibraries $(<) : core libs ; - Hex $(<:B).hex : $(<) ; - for _p in $(PORTS) - { - Upload $(_p) : $(PORT_$(_p)) : $(<:B).hex ; - } -} - -# -# Targets -# - -# Grab everything from the core directory -Library core : [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -Library libs : [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp *.c ] ; - -# Main output executable -Arduino $(PWD:B).elf : $(PROJECT_MODULES) [ GLOB $(PROJECT_DIRS) : *.c *.cpp *.pde *.ino ] ; diff --git a/AVR/lib/RF24/examples/pingpair_irq/pingpair_irq.pde b/AVR/lib/RF24/examples/pingpair_irq/pingpair_irq.pde deleted file mode 100644 index 47084a1..0000000 --- a/AVR/lib/RF24/examples/pingpair_irq/pingpair_irq.pde +++ /dev/null @@ -1,216 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * Example of using interrupts - * - * This is an example of how to user interrupts to interact with the radio. - * It builds on the pingpair_pl example, and uses ack payloads. - */ - -#include -#include "nRF24L01.h" -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 9 & 10 - -RF24 radio(8,9); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const short role_pin = 7; - -// -// Topology -// - -// Single radio pipe address for the 2 nodes to communicate. -const uint64_t pipe = 0xE8E8F0F0E1LL; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes in this -// system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_sender = 1, role_receiver } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Sender", "Receiver"}; - -// The role of the current running sketch -role_e role; - -// Interrupt handler, check the radio because we got an IRQ -void check_radio(void); - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_sender; - else - role = role_receiver; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/pingpair_irq/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // We will be using the Ack Payload feature, so please enable it - radio.enableAckPayload(); - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens a single pipe for these two nodes to communicate - // back and forth. One listens on it, the other talks to it. - - if ( role == role_sender ) - { - radio.openWritingPipe(pipe); - } - else - { - radio.openReadingPipe(1,pipe); - } - - // - // Start listening - // - - if ( role == role_receiver ) - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); - - // - // Attach interrupt handler to interrupt #0 (using pin 2) - // on BOTH the sender and receiver - // - - attachInterrupt(0, check_radio, FALLING); -} - -static uint32_t message_count = 0; - -void loop(void) -{ - // - // Sender role. Repeatedly send the current time - // - - if (role == role_sender) - { - // Take the time, and send it. - unsigned long time = millis(); - printf("Now sending %lu\n\r",time); - radio.startWrite( &time, sizeof(unsigned long) ); - - // Try again soon - delay(2000); - } - - // - // Receiver role: Does nothing! All the work is in IRQ - // - -} - -void check_radio(void) -{ - // What happened? - bool tx,fail,rx; - radio.whatHappened(tx,fail,rx); - - // Have we successfully transmitted? - if ( tx ) - { - if ( role == role_sender ) - printf("Send:OK\n\r"); - - if ( role == role_receiver ) - printf("Ack Payload:Sent\n\r"); - } - - // Have we failed to transmit? - if ( fail ) - { - if ( role == role_sender ) - printf("Send:Failed\n\r"); - - if ( role == role_receiver ) - printf("Ack Payload:Failed\n\r"); - } - - // Transmitter can power down for now, because - // the transmission is done. - if ( ( tx || fail ) && ( role == role_sender ) ) - radio.powerDown(); - - // Did we receive a message? - if ( rx ) - { - // If we're the sender, we've received an ack payload - if ( role == role_sender ) - { - radio.read(&message_count,sizeof(message_count)); - printf("Ack:%lu\n\r",message_count); - } - - // If we're the receiver, we've received a time message - if ( role == role_receiver ) - { - // Get this payload and dump it - static unsigned long got_time; - radio.read( &got_time, sizeof(got_time) ); - printf("Got payload %lu\n\r",got_time); - - // Add an ack packet for the next time around. This is a simple - // packet counter - radio.writeAckPayload( 1, &message_count, sizeof(message_count) ); - ++message_count; - } - } -} - -// vim:ai:cin:sts=2 sw=2 ft=cpp diff --git a/AVR/lib/RF24/examples/pingpair_irq/printf.h b/AVR/lib/RF24/examples/pingpair_irq/printf.h deleted file mode 100644 index b2efd56..0000000 --- a/AVR/lib/RF24/examples/pingpair_irq/printf.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -#ifdef ARDUINO - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#else -#error This example is only for use on Arduino. -#endif // ARDUINO - -#endif // __PRINTF_H__ diff --git a/AVR/lib/RF24/examples/pingpair_maple/Jamfile b/AVR/lib/RF24/examples/pingpair_maple/Jamfile deleted file mode 100644 index 798096c..0000000 --- a/AVR/lib/RF24/examples/pingpair_maple/Jamfile +++ /dev/null @@ -1,182 +0,0 @@ -MCU = cortex-m3 ; -CHIP = STM32F103ZE ; -BOARD = maple_native ; - -#CHIP = at91sam3u4 ; -#BOARD = sam3u-ek ; - -if ! $(TOOLSET) -{ - TOOLSET = devkit ; - Echo "Assuming TOOLSET=devkit" ; -} - -if $(TOOLSET) = yagarto -{ - TOOLS_PATH = ~/Source/yagarto-4.6.2/bin ; - TOOLS_ARCH = arm-none-eabi- ; -} -if $(TOOLSET) = yagarto-install -{ - TOOLS_PATH = ~/Source/yagarto/install/bin ; - TOOLS_ARCH = arm-none-eabi- ; -} -else if $(TOOLSET) = devkit -{ - TOOLS_PATH = /opt/devkitARM/bin ; - TOOLS_ARCH = arm-eabi- ; -} -else if $(TOOLSET) = maple -{ - TOOLS_PATH = /opt/Maple/Resources/Java/hardware/tools/arm/bin ; - TOOLS_ARCH = arm-none-eabi- ; -} -else if $(TOOLSET) = ports -{ - TOOLS_PATH = /opt/local/bin ; - TOOLS_ARCH = arm-none-eabi- ; -} - -CC = $(TOOLS_PATH)/$(TOOLS_ARCH)gcc ; -C++ = $(TOOLS_PATH)/$(TOOLS_ARCH)g++ ; -AS = $(TOOLS_PATH)/$(TOOLS_ARCH)gcc -c ; -LINK = $(TOOLS_PATH)/$(TOOLS_ARCH)g++ ; -OBJCOPY = $(TOOLS_PATH)/$(TOOLS_ARCH)objcopy ; -DFU = dfu-util ; - -DEFINES += VECT_TAB_FLASH BOARD_$(BOARD) MCU_$(CHIP) ERROR_LED_PORT=GPIOC ERROR_LED_PIN=15 STM32_HIGH_DENSITY MAPLE_IDE ; -OPTIM = -Os ; -MFLAGS = cpu=$(MCU) thumb arch=armv7-m ; -CCFLAGS = -Wall -m$(MFLAGS) -g -nostdlib -ffunction-sections -fdata-sections -Wl,--gc-sections ; -C++FLAGS = $(CCFLAGS) -fno-rtti -fno-exceptions ; -LINKFLAGS += -m$(MFLAGS) -Xlinker --gc-sections ; -DFUFLAGS = -a1 -d 0x1eaf:0x0003 -R ; - -MAPLE_DIR = $(HOME)/Source/SAM3U/libmaple ; -MAPLE_LIBS = Servo LiquidCrystal Wire FreeRTOS ; -MAPLE_SUBDIRS = wirish wirish/comm wirish/boards libmaple libmaple/usb libmaple/usb/usb_lib ; - -SKETCH_DIR = $(HOME)/Source/Arduino ; -SKETCH_LIBS = RF24 ; - -MODULE_DIRS = . $(MAPLE_DIR)/$(MAPLE_SUBDIRS) $(MAPLE_DIR)/libraries/$(MAPLE_LIBS) $(SKETCH_DIR)/libraries/$(SKETCH_LIBS) ; -HDRS = $(MODULE_DIRS) ; -LOCATE_TARGET = out/$(TOOLSET) ; -LOCATE_SOURCE = $(LOCATE_TARGET) ; - -rule Pde -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_SOURCE) ; - Clean clean : $(<) ; -} - -if ( $(ARDUINO_VERSION) < 100 ) -{ - ARDUINO_H = WProgram.h ; -} -else -{ - ARDUINO_H = Arduino.h ; -} - -actions Pde -{ - echo "#include <$(ARDUINO_H)>" > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule C++Pde -{ - local _CPP = $(>:B).cpp ; - Pde $(_CPP) : $(>) ; - C++ $(<) : $(_CPP) ; -} - -rule Hex -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_TARGET) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions Hex -{ - $(OBJCOPY) -O ihex $(>) $(<) -} - -rule Binary -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_TARGET) ; - Depends binary : $(<) ; - Clean clean : $(<) ; -} - -actions Binary -{ - $(OBJCOPY) -O binary $(>) $(<) -} - -rule UserObject -{ - switch $(>:S) - { - case .S : As $(<) : $(>) ; - case .ino : C++Pde $(<) : $(>) ; - case .pde : C++Pde $(<) : $(>) ; - } -} - -rule Upload -{ - Depends up : $(<) ; - NotFile up ; - Always $(<) ; - Always up ; -} - -actions Upload -{ - $(DFU) $(DFUFLAGS) -D $(<) -} - -# Override base objects rule, so all output can go in the output dir -rule Objects -{ - local _i ; - - for _i in [ FGristFiles $(<) ] - { - local _b = $(_i:B)$(SUFOBJ) ; - local _o = $(_b:G=$(SOURCE_GRIST:E)) ; - Object $(_o) : $(_i) ; - Depends obj : $(_o) ; - } -} - -# Override base main rule, so all output can go in the output dir -rule Main -{ - MainFromObjects $(<) : $(>:B)$(SUFOBJ) ; - Objects $(>) ; -} - -# Modules -MODULES = [ GLOB $(MODULE_DIRS) : *.pde *.c *.cpp *.S ] ; - -# Main output executable -MAIN = $(PWD:B).elf ; - -# Linker script -LINK_DIR = $(MAPLE_DIR)/support/ld ; -LINKSCRIPT = $(LINK_DIR)/$(BOARD)/flash.ld ; - -# Bring in the map and link script -LINKFLAGS += -Wl,-Map=$(LOCATE_TARGET)/$(MAIN:B).map -T$(LINKSCRIPT) -L$(LINK_DIR) ; - -Main $(MAIN) : $(MODULES) ; -Binary $(MAIN:B).bin : $(MAIN) ; -Upload $(MAIN:B).bin ; diff --git a/AVR/lib/RF24/examples/pingpair_maple/main.cpp b/AVR/lib/RF24/examples/pingpair_maple/main.cpp deleted file mode 100644 index b4f976d..0000000 --- a/AVR/lib/RF24/examples/pingpair_maple/main.cpp +++ /dev/null @@ -1,87 +0,0 @@ -#ifdef MAPLE_IDE - -#include -#include "wirish.h" - -extern void setup(void); -extern void loop(void); - -void board_start(const char* program_name) -{ - // Set up the LED to steady on - pinMode(BOARD_LED_PIN, OUTPUT); - digitalWrite(BOARD_LED_PIN, HIGH); - - // Setup the button as input - pinMode(BOARD_BUTTON_PIN, INPUT); - digitalWrite(BOARD_BUTTON_PIN, HIGH); - - SerialUSB.begin(); - SerialUSB.println("Press BUT"); - - // Wait for button press - while ( !isButtonPressed() ) - { - } - - SerialUSB.println("Welcome!"); - SerialUSB.println(program_name); - - int i = 11; - while (i--) - { - toggleLED(); - delay(50); - } -} - -/** - * Custom version of _write, which will print to the USB. - * In order to use it you MUST ADD __attribute__((weak)) - * to _write in libmaple/syscalls.c -*/ -extern "C" int _write (int file, char * ptr, int len) -{ - if ( (file != 1) && (file != 2) ) - return 0; - else - SerialUSB.write(ptr,len); - return len; -} - -/** - * Re-entrant version of _write. Yagarto and Devkit now use - * the re-entrant newlib, so these get called instead of the - * non_r versions. - */ -extern "C" int _write_r (void*, int file, char * ptr, int len) -{ - return _write( file, ptr, len); -} - -__attribute__((constructor)) __attribute__ ((weak)) void premain() -{ - init(); -} - -__attribute__((weak)) void setup(void) -{ - board_start("No program defined"); -} - -__attribute__((weak)) void loop(void) -{ -} - -__attribute__((weak)) int main(void) -{ - setup(); - - while (true) - { - loop(); - } - return 0; -} -#endif // ifdef MAPLE_IDE -// vim:cin:ai:sts=2 sw=2 ft=cpp diff --git a/AVR/lib/RF24/examples/pingpair_maple/pingpair_maple.pde b/AVR/lib/RF24/examples/pingpair_maple/pingpair_maple.pde deleted file mode 100644 index 2d3925b..0000000 --- a/AVR/lib/RF24/examples/pingpair_maple/pingpair_maple.pde +++ /dev/null @@ -1,242 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * Example RF Radio Ping Pair ... for Maple - * - * This is an example of how to use the RF24 class. Write this sketch to two different nodes, - * connect the role_pin to ground on one. The ping node sends the current time to the pong node, - * which responds by sending the value back. The ping node can then see how long the whole cycle - * took. - */ - -#include "WProgram.h" -#include -#include "nRF24L01.h" -#include "RF24.h" - -// -// Maple specific setup. Other than this section, the sketch is the same on Maple as on -// Arduino -// - -#ifdef MAPLE_IDE - -// External startup function -extern void board_start(const char* program_name); - -// Use SPI #2. -HardwareSPI SPI(2); - -#else -#define board_startup printf -#define toggleLED(x) (x) -#endif - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 7 & 6 -// (This works for the Getting Started board plugged into the -// Maple Native backwards.) - -RF24 radio(7,6); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const int role_pin = 10; - -// -// Topology -// - -// Radio pipe addresses for the 2 nodes to communicate. -const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL }; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes -// in this system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_ping_out = 1, role_pong_back } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"}; - -// The role of the current running sketch -role_e role; - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_ping_out; - else - role = role_pong_back; - - // - // Print preamble - // - - board_start("\n\rRF24/examples/pingpair/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // optionally, increase the delay between retries & # of retries - radio.setRetries(15,15); - - // optionally, reduce the payload size. seems to - // improve reliability - radio.setPayloadSize(8); - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens two pipes for these two nodes to communicate - // back and forth. - // Open 'our' pipe for writing - // Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading) - - if ( role == role_ping_out ) - { - radio.openWritingPipe(pipes[0]); - radio.openReadingPipe(1,pipes[1]); - } - else - { - radio.openWritingPipe(pipes[1]); - radio.openReadingPipe(1,pipes[0]); - } - - // - // Start listening - // - - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); -} - -void loop(void) -{ - // - // Ping out role. Repeatedly send the current time - // - - if (role == role_ping_out) - { - toggleLED(); - - // First, stop listening so we can talk. - radio.stopListening(); - - // Take the time, and send it. This will block until complete - unsigned long time = millis(); - printf("Now sending %lu...",time); - bool ok = radio.write( &time, sizeof(unsigned long) ); - - if (ok) - printf("ok...\r\n"); - else - printf("failed.\r\n"); - - // Now, continue listening - radio.startListening(); - - // Wait here until we get a response, or timeout (250ms) - unsigned long started_waiting_at = millis(); - bool timeout = false; - while ( ! radio.available() && ! timeout ) - if (millis() - started_waiting_at > 200 ) - timeout = true; - - // Describe the results - if ( timeout ) - { - printf("Failed, response timed out.\r\n"); - } - else - { - // Grab the response, compare, and send to debugging spew - unsigned long got_time; - radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got response %lu, round-trip delay: %lu\r\n",got_time,millis()-got_time); - } - - toggleLED(); - - // Try again 1s later - delay(1000); - } - - // - // Pong back role. Receive each packet, dump it out, and send it back - // - - if ( role == role_pong_back ) - { - // if there is data ready - if ( radio.available() ) - { - // Dump the payloads until we've gotten everything - unsigned long got_time; - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - done = radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got payload %lu...",got_time); - - // Delay just a little bit to let the other unit - // make the transition to receiver - delay(20); - } - - // First, stop listening so we can talk - radio.stopListening(); - - // Send the final one back. - radio.write( &got_time, sizeof(unsigned long) ); - printf("Sent response.\r\n"); - - // Now, resume listening so we catch the next packets. - radio.startListening(); - } - } -} -// vim:cin:ai:sts=2 sw=2 ft=cpp diff --git a/AVR/lib/RF24/examples/pingpair_pl/Jamfile b/AVR/lib/RF24/examples/pingpair_pl/Jamfile deleted file mode 100644 index 901f8da..0000000 --- a/AVR/lib/RF24/examples/pingpair_pl/Jamfile +++ /dev/null @@ -1,206 +0,0 @@ -PROJECT_NAME = $(PWD:B) ; -PROJECT_DIR = . ; -PROJECT_LIBS = SPI RF24 ; - -OUT_DIR = ojam ; -F_CPU = 16000000 ; -MCU = atmega328p ; -PORTS = /dev/tty.usbserial-A600eHIs /dev/tty.usbserial-A40081RP /dev/tty.usbserial-A9007LmI ; - -UPLOAD_RATE = 57600 ; -AVRDUDE_PROTOCOL = stk500v1 ; -COM = 33 ; - -# Host-specific overrides for locations -if $(OS) = MACOSX -{ -ARDUINO_VERSION = 22 ; -OLD_DIR = /opt/arduino-0021 ; -AVR_TOOLS_PATH = $(OLD_DIR)/hardware/tools/avr/bin ; -AVRDUDECONFIG_PATH = $(OLD_DIR)/hardware/tools/avr/etc ; -ARDUINO_DIR = /opt/Arduino ; -ARDUINO_AVR = /usr/lib/avr/include ; -} - -# Where is everything? -ARDUINO_VERSION ?= 22 ; -AVR_TOOLS_PATH ?= /usr/bin ; -ARDUINO_DIR ?= /opt/arduino-00$(ARDUINO_VERSION) ; -ARDUINO_AVR ?= $(ARDUINO_DIR)/hardware/tools/avr/avr/include/avr ; -AVRDUDECONFIG_PATH ?= $(ARDUINO_DIR)/hardware/tools ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; -AVR_CC = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_CXX = $(AVR_TOOLS_PATH)/avr-g++ ; -AVR_LD = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_OBJCOPY = $(AVR_TOOLS_PATH)/avr-objcopy ; -AVRDUDE = $(AVR_TOOLS_PATH)/avrdude ; - -DEFINES = F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -CTUNING = -ffunction-sections -fdata-sections ; -CXXTUNING = -fno-exceptions -fno-strict-aliasing ; -CFLAGS = -Os -Wall -Wextra -mmcu=$(MCU) $(CTUNING) ; -CXXFLAGS = $(CFLAGS) $(CXXTUNING) ; -LDFLAGS = -Os -lm -Wl,--gc-sections -mmcu=atmega328p ; - -# Search everywhere for headers -HDRS = $(PROJECT_DIR) $(ARDUINO_AVR) $(ARDUINO_CORE) [ GLOB $(ARDUINO_LIB) $(SKETCH_LIB) : [^.]* ] ; - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp ] ; - -# In addition to explicitly-specified program modules, pick up anything from the current -# dir. -PROJECT_MODULES += [ GLOB $(PROJECT_DIR) : *.c *.cpp *.pde ] ; - -# Shortcut for the out files -OUT = $(OUT_DIR)/$(PROJECT_NAME) ; - -# AvrDude setup -AVRDUDE_FLAGS = -V -F -D -C $(AVRDUDECONFIG_PATH)/avrdude.conf -p $(MCU) -c $(AVRDUDE_PROTOCOL) -b $(UPLOAD_RATE) ; - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule AvrCc -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrCc -{ - $(AVR_CC) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CFLAGS) $(>) -} - -rule AvrC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrC++ -{ - $(AVR_CXX) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule Pde -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - -} - -actions Pde -{ - echo "#include " > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule AvrPde -{ - local _CPP = $(OUT_DIR)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - AvrC++ $(<) : $(_CPP) ; -} - -rule AvrObject -{ - switch $(>:S) - { - case .c : AvrCc $(<) : $(>) ; - case .cpp : AvrC++ $(<) : $(>) ; - case .pde : AvrPde $(<) : $(>) ; - } -} - -rule AvrObjects -{ - for _I in $(<) - { - AvrObject $(OUT_DIR)/$(_I:B).o : $(_I) ; - } -} - -rule AvrMainFromObjects -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - MkDir $(<:D) ; - Depends all : $(<) ; - Clean clean : $(<) ; -} - -actions AvrMainFromObjects -{ - $(AVR_LD) $(LDFLAGS) -o $(<) $(>) -} - -rule AvrMain -{ - AvrMainFromObjects $(<) : $(OUT_DIR)/$(>:B).o ; - AvrObjects $(>) ; -} - -rule AvrHex -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions AvrHex -{ - $(AVR_OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule AvrUpload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - AvrUploadAction $(2) : $(3) ; -} - -actions AvrUploadAction -{ - $(AVRDUDE) $(AVRDUDE_FLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -AvrMain $(OUT).elf : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -AvrHex $(OUT).hex : $(OUT).elf ; - -AvrUpload p6 : /dev/tty.usbserial-A600eHIs : $(OUT).hex ; -AvrUpload p4 : /dev/tty.usbserial-A40081RP : $(OUT).hex ; -AvrUpload p9 : /dev/tty.usbserial-A9007LmI : $(OUT).hex ; - diff --git a/AVR/lib/RF24/examples/pingpair_pl/pingpair_pl.pde b/AVR/lib/RF24/examples/pingpair_pl/pingpair_pl.pde deleted file mode 100644 index 70aed6e..0000000 --- a/AVR/lib/RF24/examples/pingpair_pl/pingpair_pl.pde +++ /dev/null @@ -1,180 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * Example of using Ack Payloads - * - * This is an example of how to do two-way communication without changing - * transmit/receive modes. Here, a payload is set to the transmitter within - * the Ack packet of each transmission. Note that the payload is set BEFORE - * the sender's message arrives. - */ - -#include -#include "nRF24L01.h" -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 9 & 10 - -RF24 radio(9,10); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const short role_pin = 7; - -// -// Topology -// - -// Single radio pipe address for the 2 nodes to communicate. -const uint64_t pipe = 0xE8E8F0F0E1LL; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes in this -// system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_sender = 1, role_receiver } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Sender", "Receiver"}; - -// The role of the current running sketch -role_e role; - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_sender; - else - role = role_receiver; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/pingpair_pl/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // We will be using the Ack Payload feature, so please enable it - radio.enableAckPayload(); - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens a single pipes for these two nodes to communicate - // back and forth. One listens on it, the other talks to it. - - if ( role == role_sender ) - { - radio.openWritingPipe(pipe); - } - else - { - radio.openReadingPipe(1,pipe); - } - - // - // Start listening - // - - if ( role == role_receiver ) - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); -} - -void loop(void) -{ - static uint32_t message_count = 0; - - // - // Sender role. Repeatedly send the current time - // - - if (role == role_sender) - { - // Take the time, and send it. This will block until complete - unsigned long time = millis(); - printf("Now sending %lu...",time); - radio.write( &time, sizeof(unsigned long) ); - - if ( radio.isAckPayloadAvailable() ) - { - radio.read(&message_count,sizeof(message_count)); - printf("Ack: [%lu] ",message_count); - } - printf("OK\n\r"); - - // Try again soon - delay(2000); - } - - // - // Receiver role. Receive each packet, dump it out, add ack payload for next time - // - - if ( role == role_receiver ) - { - // if there is data ready - if ( radio.available() ) - { - // Dump the payloads until we've gotten everything - static unsigned long got_time; - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - done = radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got payload %lu\n",got_time); - } - - // Add an ack packet for the next time around. This is a simple - // packet counter - radio.writeAckPayload( 1, &message_count, sizeof(message_count) ); - ++message_count; - } - } -} -// vim:ai:cin:sts=2 sw=2 ft=cpp diff --git a/AVR/lib/RF24/examples/pingpair_pl/printf.h b/AVR/lib/RF24/examples/pingpair_pl/printf.h deleted file mode 100644 index b2efd56..0000000 --- a/AVR/lib/RF24/examples/pingpair_pl/printf.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -#ifdef ARDUINO - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#else -#error This example is only for use on Arduino. -#endif // ARDUINO - -#endif // __PRINTF_H__ diff --git a/AVR/lib/RF24/examples/pingpair_sleepy/Jamfile b/AVR/lib/RF24/examples/pingpair_sleepy/Jamfile deleted file mode 100644 index 901f8da..0000000 --- a/AVR/lib/RF24/examples/pingpair_sleepy/Jamfile +++ /dev/null @@ -1,206 +0,0 @@ -PROJECT_NAME = $(PWD:B) ; -PROJECT_DIR = . ; -PROJECT_LIBS = SPI RF24 ; - -OUT_DIR = ojam ; -F_CPU = 16000000 ; -MCU = atmega328p ; -PORTS = /dev/tty.usbserial-A600eHIs /dev/tty.usbserial-A40081RP /dev/tty.usbserial-A9007LmI ; - -UPLOAD_RATE = 57600 ; -AVRDUDE_PROTOCOL = stk500v1 ; -COM = 33 ; - -# Host-specific overrides for locations -if $(OS) = MACOSX -{ -ARDUINO_VERSION = 22 ; -OLD_DIR = /opt/arduino-0021 ; -AVR_TOOLS_PATH = $(OLD_DIR)/hardware/tools/avr/bin ; -AVRDUDECONFIG_PATH = $(OLD_DIR)/hardware/tools/avr/etc ; -ARDUINO_DIR = /opt/Arduino ; -ARDUINO_AVR = /usr/lib/avr/include ; -} - -# Where is everything? -ARDUINO_VERSION ?= 22 ; -AVR_TOOLS_PATH ?= /usr/bin ; -ARDUINO_DIR ?= /opt/arduino-00$(ARDUINO_VERSION) ; -ARDUINO_AVR ?= $(ARDUINO_DIR)/hardware/tools/avr/avr/include/avr ; -AVRDUDECONFIG_PATH ?= $(ARDUINO_DIR)/hardware/tools ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; -AVR_CC = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_CXX = $(AVR_TOOLS_PATH)/avr-g++ ; -AVR_LD = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_OBJCOPY = $(AVR_TOOLS_PATH)/avr-objcopy ; -AVRDUDE = $(AVR_TOOLS_PATH)/avrdude ; - -DEFINES = F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -CTUNING = -ffunction-sections -fdata-sections ; -CXXTUNING = -fno-exceptions -fno-strict-aliasing ; -CFLAGS = -Os -Wall -Wextra -mmcu=$(MCU) $(CTUNING) ; -CXXFLAGS = $(CFLAGS) $(CXXTUNING) ; -LDFLAGS = -Os -lm -Wl,--gc-sections -mmcu=atmega328p ; - -# Search everywhere for headers -HDRS = $(PROJECT_DIR) $(ARDUINO_AVR) $(ARDUINO_CORE) [ GLOB $(ARDUINO_LIB) $(SKETCH_LIB) : [^.]* ] ; - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp ] ; - -# In addition to explicitly-specified program modules, pick up anything from the current -# dir. -PROJECT_MODULES += [ GLOB $(PROJECT_DIR) : *.c *.cpp *.pde ] ; - -# Shortcut for the out files -OUT = $(OUT_DIR)/$(PROJECT_NAME) ; - -# AvrDude setup -AVRDUDE_FLAGS = -V -F -D -C $(AVRDUDECONFIG_PATH)/avrdude.conf -p $(MCU) -c $(AVRDUDE_PROTOCOL) -b $(UPLOAD_RATE) ; - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule AvrCc -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrCc -{ - $(AVR_CC) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CFLAGS) $(>) -} - -rule AvrC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrC++ -{ - $(AVR_CXX) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule Pde -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - -} - -actions Pde -{ - echo "#include " > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule AvrPde -{ - local _CPP = $(OUT_DIR)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - AvrC++ $(<) : $(_CPP) ; -} - -rule AvrObject -{ - switch $(>:S) - { - case .c : AvrCc $(<) : $(>) ; - case .cpp : AvrC++ $(<) : $(>) ; - case .pde : AvrPde $(<) : $(>) ; - } -} - -rule AvrObjects -{ - for _I in $(<) - { - AvrObject $(OUT_DIR)/$(_I:B).o : $(_I) ; - } -} - -rule AvrMainFromObjects -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - MkDir $(<:D) ; - Depends all : $(<) ; - Clean clean : $(<) ; -} - -actions AvrMainFromObjects -{ - $(AVR_LD) $(LDFLAGS) -o $(<) $(>) -} - -rule AvrMain -{ - AvrMainFromObjects $(<) : $(OUT_DIR)/$(>:B).o ; - AvrObjects $(>) ; -} - -rule AvrHex -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions AvrHex -{ - $(AVR_OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule AvrUpload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - AvrUploadAction $(2) : $(3) ; -} - -actions AvrUploadAction -{ - $(AVRDUDE) $(AVRDUDE_FLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -AvrMain $(OUT).elf : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -AvrHex $(OUT).hex : $(OUT).elf ; - -AvrUpload p6 : /dev/tty.usbserial-A600eHIs : $(OUT).hex ; -AvrUpload p4 : /dev/tty.usbserial-A40081RP : $(OUT).hex ; -AvrUpload p9 : /dev/tty.usbserial-A9007LmI : $(OUT).hex ; - diff --git a/AVR/lib/RF24/examples/pingpair_sleepy/pingpair_sleepy.pde b/AVR/lib/RF24/examples/pingpair_sleepy/pingpair_sleepy.pde deleted file mode 100644 index 49daa69..0000000 --- a/AVR/lib/RF24/examples/pingpair_sleepy/pingpair_sleepy.pde +++ /dev/null @@ -1,288 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * Example RF Radio Ping Pair which Sleeps between Sends - * - * This is an example of how to use the RF24 class to create a battery- - * efficient system. It is just like the pingpair.pde example, but the - * ping node powers down the radio and sleeps the MCU after every - * ping/pong cycle. - * - * As with the pingpair.pde example, write this sketch to two different nodes, - * connect the role_pin to ground on one. The ping node sends the current - * time to the pong node, which responds by sending the value back. The ping - * node can then see how long the whole cycle took. - */ - -#include -#include -#include -#include "nRF24L01.h" -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 9 & 10 - -RF24 radio(9,10); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const int role_pin = 7; - -// -// Topology -// - -// Radio pipe addresses for the 2 nodes to communicate. -const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL }; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes -// in this system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_ping_out = 1, role_pong_back } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"}; - -// The role of the current running sketch -role_e role; - -// -// Sleep declarations -// - -typedef enum { wdt_16ms = 0, wdt_32ms, wdt_64ms, wdt_128ms, wdt_250ms, wdt_500ms, wdt_1s, wdt_2s, wdt_4s, wdt_8s } wdt_prescalar_e; - -void setup_watchdog(uint8_t prescalar); -void do_sleep(void); - -const short sleep_cycles_per_transmission = 4; -volatile short sleep_cycles_remaining = sleep_cycles_per_transmission; - -// -// Normal operation -// - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_ping_out; - else - role = role_pong_back; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/pingpair_sleepy/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // Prepare sleep parameters - // - - // Only the ping out role sleeps. Wake up every 4s to send a ping - if ( role == role_ping_out ) - setup_watchdog(wdt_1s); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens two pipes for these two nodes to communicate - // back and forth. - // Open 'our' pipe for writing - // Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading) - - if ( role == role_ping_out ) - { - radio.openWritingPipe(pipes[0]); - radio.openReadingPipe(1,pipes[1]); - } - else - { - radio.openWritingPipe(pipes[1]); - radio.openReadingPipe(1,pipes[0]); - } - - // - // Start listening - // - - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); -} - -void loop(void) -{ - // - // Ping out role. Repeatedly send the current time - // - - if (role == role_ping_out) - { - // First, stop listening so we can talk. - radio.stopListening(); - - // Take the time, and send it. This will block until complete - unsigned long time = millis(); - printf("Now sending %lu...",time); - radio.write( &time, sizeof(unsigned long) ); - - // Now, continue listening - radio.startListening(); - - // Wait here until we get a response, or timeout (250ms) - unsigned long started_waiting_at = millis(); - bool timeout = false; - while ( ! radio.available() && ! timeout ) - if (millis() - started_waiting_at > 250 ) - timeout = true; - - // Describe the results - if ( timeout ) - { - printf("Failed, response timed out.\n\r"); - } - else - { - // Grab the response, compare, and send to debugging spew - unsigned long got_time; - radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got response %lu, round-trip delay: %lu\n\r",got_time,millis()-got_time); - } - - // - // Shut down the system - // - - // Experiment with some delay here to see if it has an effect - delay(500); - - // Power down the radio. Note that the radio will get powered back up - // on the next write() call. - radio.powerDown(); - - // Sleep the MCU. The watchdog timer will awaken in a short while, and - // continue execution here. - while( sleep_cycles_remaining ) - do_sleep(); - - sleep_cycles_remaining = sleep_cycles_per_transmission; - } - - // - // Pong back role. Receive each packet, dump it out, and send it back - // - // This is untouched from the pingpair example. - // - - if ( role == role_pong_back ) - { - // if there is data ready - if ( radio.available() ) - { - // Dump the payloads until we've gotten everything - unsigned long got_time; - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - done = radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it. Include our time, because the ping_out millis counter is unreliable - // due to it sleeping - printf("Got payload %lu @ %lu...",got_time,millis()); - } - - // First, stop listening so we can talk - radio.stopListening(); - - // Send the final one back. - radio.write( &got_time, sizeof(unsigned long) ); - printf("Sent response.\n\r"); - - // Now, resume listening so we catch the next packets. - radio.startListening(); - } - } -} - -// -// Sleep helpers -// - -// 0=16ms, 1=32ms,2=64ms,3=125ms,4=250ms,5=500ms -// 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec - -void setup_watchdog(uint8_t prescalar) -{ - prescalar = min(9,prescalar); - uint8_t wdtcsr = prescalar & 7; - if ( prescalar & 8 ) - wdtcsr |= _BV(WDP3); - - MCUSR &= ~_BV(WDRF); - WDTCSR = _BV(WDCE) | _BV(WDE); - WDTCSR = _BV(WDCE) | wdtcsr | _BV(WDIE); -} - -ISR(WDT_vect) -{ - --sleep_cycles_remaining; -} - -void do_sleep(void) -{ - set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here - sleep_enable(); - - sleep_mode(); // System sleeps here - - sleep_disable(); // System continues execution here when watchdog timed out -} - -// vim:ai:cin:sts=2 sw=2 ft=cpp diff --git a/AVR/lib/RF24/examples/pingpair_sleepy/printf.h b/AVR/lib/RF24/examples/pingpair_sleepy/printf.h deleted file mode 100644 index b2efd56..0000000 --- a/AVR/lib/RF24/examples/pingpair_sleepy/printf.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -#ifdef ARDUINO - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#else -#error This example is only for use on Arduino. -#endif // ARDUINO - -#endif // __PRINTF_H__ diff --git a/AVR/lib/RF24/examples/scanner/Jamfile b/AVR/lib/RF24/examples/scanner/Jamfile deleted file mode 100644 index 1bf541e..0000000 --- a/AVR/lib/RF24/examples/scanner/Jamfile +++ /dev/null @@ -1,210 +0,0 @@ -# (1) Project Information - -PROJECT_LIBS = SPI RF24 ; - -# (2) Board Information - -UPLOAD_PROTOCOL ?= stk500v1 ; -UPLOAD_SPEED ?= 57600 ; -MCU ?= atmega328p ; -F_CPU ?= 16000000 ; -CORE ?= arduino ; -VARIANT ?= standard ; -ARDUINO_VERSION ?= 100 ; - -# (3) USB Ports - -PORTS = p4 p6 p9 u0 u1 u2 ; -PORT_p6 = /dev/tty.usbserial-A600eHIs ; -PORT_p4 = /dev/tty.usbserial-A40081RP ; -PORT_p9 = /dev/tty.usbserial-A9007LmI ; -PORT_u0 = /dev/ttyUSB0 ; -PORT_u1 = /dev/ttyUSB1 ; -PORT_u2 = /dev/ttyUSB2 ; - -# (4) Location of AVR tools -# -# This configuration assumes using avr-tools that were obtained separate from the Arduino -# distribution. - -if $(OS) = MACOSX -{ - AVR_BIN = /usr/local/avrtools/bin ; - AVR_ETC = /usr/local/avrtools/etc ; - AVR_INCLUDE = /usr/local/avrtools/include ; -} -else -{ - AVR_BIN = /usr/bin ; - AVR_INCLUDE = /usr/lib/avr/include ; - AVR_ETC = /etc ; -} - -# (5) Directories where Arduino core and libraries are located - -ARDUINO_DIR ?= /opt/Arduino ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/$(CORE) $(ARDUINO_DIR)/hardware/arduino/variants/$(VARIANT) ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; - -# -# -------------------------------------------------- -# Below this line usually never needs to be modified -# - -# Tool locations - -CC = $(AVR_BIN)/avr-gcc ; -C++ = $(AVR_BIN)/avr-g++ ; -LINK = $(AVR_BIN)/avr-gcc ; -OBJCOPY = $(AVR_BIN)/avr-objcopy ; -AVRDUDE = $(AVR_BIN)/avrdude ; - -# Flags - -DEFINES += F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -OPTIM = -Os ; -CCFLAGS = -Wall -Wextra -mmcu=$(MCU) -ffunction-sections -fdata-sections ; -C++FLAGS = $(CCFLAGS) -fno-exceptions -fno-strict-aliasing ; -LINKFLAGS = $(OPTIM) -lm -Wl,--gc-sections -mmcu=$(MCU) ; -AVRDUDEFLAGS = -V -F -D -C $(AVR_ETC)/avrdude.conf -p $(MCU) -c $(UPLOAD_PROTOCOL) -b $(UPLOAD_SPEED) ; - -# Search everywhere for headers - -HDRS = $(PWD) $(AVR_INCLUDE) $(ARDUINO_CORE) $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) ; - -# Output locations - -LOCATE_TARGET = $(F_CPU) ; -LOCATE_SOURCE = $(F_CPU) ; - -# -# Custom rules -# - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule Pde -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_SOURCE) ; - Clean clean : $(<) ; -} - -if ( $(ARDUINO_VERSION) < 100 ) -{ - ARDUINO_H = WProgram.h ; -} -else -{ - ARDUINO_H = Arduino.h ; -} - -actions Pde -{ - echo "#include <$(ARDUINO_H)>" > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule C++Pde -{ - local _CPP = $(>:B).cpp ; - Pde $(_CPP) : $(>) ; - C++ $(<) : $(_CPP) ; -} - -rule UserObject -{ - switch $(>:S) - { - case .ino : C++Pde $(<) : $(>) ; - case .pde : C++Pde $(<) : $(>) ; - } -} - -rule Objects -{ - local _i ; - - for _i in [ FGristFiles $(<) ] - { - local _b = $(_i:B)$(SUFOBJ) ; - local _o = $(_b:G=$(SOURCE_GRIST:E)) ; - Object $(_o) : $(_i) ; - Depends obj : $(_o) ; - } -} - -rule Main -{ - MainFromObjects $(<) : $(>:B)$(SUFOBJ) ; - Objects $(>) ; -} - -rule Hex -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_TARGET) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions Hex -{ - $(OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule Upload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - UploadAction $(2) : $(3) ; -} - -actions UploadAction -{ - $(AVRDUDE) $(AVRDUDEFLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -# -# Targets -# - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp *.c ] ; - -# Grab everything from the current dir -PROJECT_MODULES += [ GLOB $(PWD) : *.c *.cpp *.pde *.ino ] ; - -# Main output executable -MAIN = $(PWD:B).elf ; - -Main $(MAIN) : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -Hex $(MAIN:B).hex : $(MAIN) ; - -# Upload targets -for _p in $(PORTS) -{ - Upload $(_p) : $(PORT_$(_p)) : $(MAIN:B).hex ; -} diff --git a/AVR/lib/RF24/examples/scanner/output/core.a b/AVR/lib/RF24/examples/scanner/output/core.a deleted file mode 100644 index 6ae105d..0000000 Binary files a/AVR/lib/RF24/examples/scanner/output/core.a and /dev/null differ diff --git a/AVR/lib/RF24/examples/scanner/output/scanner.cpp b/AVR/lib/RF24/examples/scanner/output/scanner.cpp deleted file mode 100644 index 5eb1627..0000000 --- a/AVR/lib/RF24/examples/scanner/output/scanner.cpp +++ /dev/null @@ -1,128 +0,0 @@ -#include -#line 1 "scanner.pde" - -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * Channel scanner - * - * Example to detect interference on the various channels available. - * This is a good diagnostic tool to check whether you're picking a - * good channel for your application. - * - * Inspired by cpixip. - * See http://arduino.cc/forum/index.php/topic,54795.0.html - */ - -#include -#include "nRF24L01.h" -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 8 & 9 - -RF24 radio(8,9); - -// -// Channel info -// - -const short num_channels = 128; -short values[num_channels]; - -// -// Setup -// - -void setup(void) -{ - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/scanner/\n\r"); - - // - // Setup and configure rf radio - // - - radio.begin(); - radio.setAutoAck(false); - - // Get into standby mode - radio.startListening(); - radio.stopListening(); - - // Print out header, high then low digit - int i = 0; - while ( i < num_channels ) - { - printf("%x",i>>4); - ++i; - } - printf("\n\r"); - i = 0; - while ( i < num_channels ) - { - printf("%x",i&0xf); - ++i; - } - printf("\n\r"); -} - -// -// Loop -// - -const short num_reps = 100; - -void loop(void) -{ - // Clear measurement values - memset(values,0,num_channels); - - // Scan all channels num_reps times - int rep_counter = num_reps; - while (rep_counter--) - { - int i = num_channels; - while (i--) - { - // Select this channel - radio.setChannel(i); - - // Listen for a little - radio.startListening(); - delayMicroseconds(128); - radio.stopListening(); - - // Did we get a carrier? - if ( radio.testCarrier() ) - ++values[i]; - } - } - - // Print out channel measurements, clamped to a single hex digit - int i = 0; - while ( i < num_channels ) - { - printf("%x",min(0xf,values[i]&0xf)); - ++i; - } - printf("\n\r"); -} - - -// vim:ai:cin:sts=2 sw=2 ft=cpp diff --git a/AVR/lib/RF24/examples/scanner/output/scanner.elf b/AVR/lib/RF24/examples/scanner/output/scanner.elf deleted file mode 100644 index 5e0f4b1..0000000 Binary files a/AVR/lib/RF24/examples/scanner/output/scanner.elf and /dev/null differ diff --git a/AVR/lib/RF24/examples/scanner/output/scanner.hex b/AVR/lib/RF24/examples/scanner/output/scanner.hex deleted file mode 100644 index 45c37db..0000000 --- a/AVR/lib/RF24/examples/scanner/output/scanner.hex +++ /dev/null @@ -1,325 +0,0 @@ -:100000000C9463000C948B000C948B000C948B006C -:100010000C948B000C948B000C948B000C948B0034 -:100020000C948B000C948B000C948B000C948B0024 -:100030000C948B000C948B000C948B000C948B0014 -:100040000C948F050C948B000C9423060C948B005D -:100050000C948B000C948B000C948B000C948B00F4 -:100060000C948B000C948B000000000024002700EF -:100070002A0000000000250028002B0000000000DE -:1000800023002600290004040404040404040202DA -:100090000202020203030303030301020408102007 -:1000A0004080010204081020010204081020000012 -:1000B0000007000201000003040600000000000029 -:1000C000000090043B0711241FBECFEFD8E0DEBF35 -:1000D000CDBF11E0A0E0B1E0E6EFF3E102C0059092 -:1000E0000D92AA33B107D9F712E0AAE3B1E001C03B -:1000F0001D92A13FB107E1F710E0C6ECD0E004C0CB -:100100002297FE010E94F509C23CD107C9F70E945F -:100110001C060C94F9090C9400000F931F93CF93C5 -:10012000DF938C01EB01009731F46115710519F42F -:1001300020E030E038C081E090E06EE070E00E94A6 -:10014000CB02FC019C01009771F180E8838320972A -:1001500071F0D387C28781E883838091E702909111 -:10016000E802892B21F4F093E802E093E7020115FD -:100170001105C9F011870087838182608383809194 -:10018000E9029091EA02892B71F4F093EA02E0937C -:10019000E9028091EB029091EC02892B21F4F0931B -:1001A000EC02E093EB02C901DF91CF911F910F9117 -:1001B0000895A0E0B0E0EFEDF0E00C94CC09FE0172 -:1001C0003596619171918091E9029091EA02AF01B7 -:1001D0000E94EE002096E2E00C94E809ABE0B0E06B -:1001E000E4EFF0E00C94BC093C012B015A01FC0146 -:1001F00017821682838181FD03C06FEF7FEFC6C136 -:100200009AE0892E1E010894211C311CF3012381E0 -:10021000F20123FD859123FF81912F01882309F4A9 -:10022000B2C1853239F423FD859123FF81912F01DD -:10023000853229F490E0B3010E940604E7CF982F9D -:10024000FF24EE249924FFE1FF15D0F09B3269F0E2 -:100250009C3228F4903259F0933291F40EC09D32C2 -:1002600049F0903369F441E024C052E0F52A84E07B -:10027000F82A28C098E0F92A25C0E0E1FE2A22C029 -:10028000F7FC29C0892F80538A3070F4F6FE05C030 -:10029000989C902C1124980E15C0E89CE02C1124F9 -:1002A000E80EF0E2FF2A0EC09E3229F4F6FC6BC184 -:1002B00040E4F42A07C09C3619F450E8F52A02C03D -:1002C000983649F4F20123FD959123FF91912F0176 -:1002D000992309F0B8CF892F8554833018F08052C4 -:1002E000833038F444E050E0A40EB51E5FE3598338 -:1002F0000FC0933631F0933779F0933509F056C03B -:1003000020C0F5018081898342E050E0A40EB51E33 -:10031000610101E010E012C0F501C080D180F6FC5F -:1003200003C06FEF7FEF02C0692D70E042E050E044 -:10033000A40EB51EC6010E94FB038C015FE7F522E7 -:1003400014C0F501C080D180F6FC03C06FEF7FEFD1 -:1003500002C0692D70E042E050E0A40EB51EC60157 -:100360000E94E9038C0150E8F52AF3FE07C01AC089 -:1003700080E290E0B3010E940604EA948E2D90E0A2 -:1003800008171907A8F30EC0F601F7FC8591F7FED0 -:1003900081916F0190E0B3010E940604E110EA949C -:1003A000015010400115110579F7EAC0943611F09B -:1003B000993669F5F7FE08C0F50120813181428147 -:1003C000538184E090E00AC0F501808191819C0115 -:1003D000442737FD4095542F82E090E0A80EB91EC7 -:1003E0009FE6F92257FF09C0509540953095219519 -:1003F0003F4F4F4F5F4FE0E8FE2ACA01B901A1010C -:100400002AE030E00E943204D82ED21840C095373E -:1004100029F41F2D1F7E2AE030E01DC01F2D197FFB -:100420009F3661F0903720F4983509F0ACC00FC0CA -:10043000903739F0983709F0A6C004C028E030E0C2 -:100440000AC0106114FD146020E130E004C014FD06 -:10045000166020E132E017FF08C0F501608171816C -:100460008281938144E050E008C0F5018081918150 -:10047000BC0180E090E042E050E0A40EB51EA10176 -:100480000E943204D82ED2188FE7F82EF122F6FE01 -:100490000BC05EEFF522D91438F4F4FE07C0F2FC6D -:1004A00005C08FEEF82202C01D2D01C0192DF4FEEB -:1004B0000DC0FE01ED0DF11D8081803319F499EE20 -:1004C000F92208C01F5FF2FE05C003C08F2D867899 -:1004D00009F01F5F0F2DF3FC14C0F0FE0FC01E15B6 -:1004E00010F09D2C0BC09D2C9E0C911A1E2D06C049 -:1004F00080E290E0B3010E9406041F5F1E15C0F366 -:1005000004C01E1510F4E11A01C0EE2404FF0FC050 -:1005100080E390E0B3010E94060402FF1DC001FDCC -:1005200003C088E790E00EC088E590E00BC0802F04 -:10053000867891F001FF02C08BE201C080E2F7FCF7 -:100540008DE290E0B3010E94060406C080E390E0D3 -:10055000B3010E9406049A94D914C0F3DA94F1010D -:10056000ED0DF11D808190E0B3010E940604DD20B5 -:10057000A9F706C080E290E0B3010E940604EA9465 -:10058000EE20C1F743CEF30166817781CB012B9634 -:10059000E2E10C94D8090F931F93CF93DF93689FE8 -:1005A0008001699F100D789F100D1124C8010E94D1 -:1005B000E702EC01009729F060E070E0A8010E94DA -:1005C000F403CE01DF91CF911F910F910895CF9346 -:1005D000DF93BC018230910510F462E070E0A091DD -:1005E000EF02B091F002ED01E0E0F0E040E050E019 -:1005F00021C0888199818617970769F48A819B8138 -:10060000309719F09383828304C09093F002809313 -:10061000EF02FE0134C06817790738F4411551051F -:1006200019F08417950708F4AC01FE018A819B81BB -:100630009C01E9012097E9F641155105A9F1CA018C -:10064000861B970B049708F4BA01E0E0F0E02AC09B -:100650008D919C91119784179507F9F4641775078C -:1006600081F412968D919C911397309719F0938392 -:10067000828304C09093F0028093EF02FD013296D2 -:100680004CC0CA01861B970BFD01E80FF91F61934F -:10069000719302978D939C9340C0FD018281938159 -:1006A0009C01D9011097A1F68091ED029091EE0284 -:1006B000892B41F480912301909124019093EE02C3 -:1006C0008093ED024091250150912601411551057D -:1006D00041F44DB75EB78091210190912201481BF2 -:1006E000590B2091ED023091EE02CA01821B930B4F -:1006F0008617970780F0AB014E5F5F4F8417950711 -:1007000050F0420F531F5093EE024093ED02F90157 -:100710006193719302C0E0E0F0E0CF01DF91CF91EF -:100720000895CF93DF93009709F450C0EC0122970E -:100730001B821A82A091EF02B091F002109709F18A -:1007400040E050E0AC17BD0708F1BB83AA83FE016F -:1007500021913191E20FF31FAE17BF0779F48D910C -:100760009C911197280F391F2E5F3F4F39832883A3 -:1007700012968D919C9113979B838A834115510505 -:1007800071F4D093F002C093EF0220C012968D91C5 -:100790009C911397AD01009711F0DC01D3CFFA01C2 -:1007A000D383C28321913191E20FF31FCE17DF076C -:1007B00069F488819981280F391F2E5F3F4FFA0114 -:1007C000318320838A819B8193838283DF91CF91C0 -:1007D0000895FC010590615070400110D8F7809594 -:1007E00090958E0F9F1F0895DC0101C06D934150BD -:1007F0005040E0F70895FC016150704001900110F5 -:10080000D8F7809590958E0F9F1F08950F931F9393 -:10081000CF93DF938C01EB018B8181FF1BC082FFA3 -:100820000DC02E813F818C819D812817390764F48A -:10083000E881F9810193F983E88306C0E885F985A9 -:10084000802F0995892B31F48E819F8101969F839A -:100850008E8302C00FEF1FEFC801DF91CF911F9170 -:100860000F910895FA01AA27283051F1203181F122 -:10087000E8946F936E7F6E5F7F4F8F4F9F4FAF4FA8 -:10088000B1E03ED0B4E03CD0670F781F891F9A1FBB -:10089000A11D680F791F8A1F911DA11D6A0F711D6F -:1008A000811D911DA11D20D009F468943F912AE07B -:1008B000269F11243019305D3193DEF6CF01089563 -:1008C000462F4770405D4193B3E00FD0C9F7F6CF94 -:1008D000462F4F70405D4A3318F0495D31FD40525C -:1008E000419302D0A9F7EACFB4E0A69597958795F2 -:1008F00077956795BA95C9F70097610571050895D1 -:100900009B01AC010A2E069457954795379527957C -:10091000BA95C9F7620F731F841F951FA01D089514 -:100920008AE391E068E049E00E9475070895FF922C -:100930000F931F93CF93DF9380E8E7E4F1E0DF01AB -:100940001D928A95E9F704E610E021C08AE391E060 -:100950006F2D0E94F2078AE391E00E94840880E8EC -:1009600090E00E94D7058AE391E00E947C078AE329 -:1009700091E00E944608882329F088819981019698 -:10098000998388832297FA94BFEFFB16F9F60150FA -:100990001040EFEF0F3F1E0729F0C5E4D2E08FE7CC -:1009A000F82ED4CFC7E4D1E000E011E000D000D0B1 -:1009B000ADB7BEB712961C930E931197899199917A -:1009C0008F70907014969C938E9313970E94D90009 -:1009D0000F900F900F900F90B2E0C734DB0731F704 -:1009E00000D083E091E0EDB7FEB7928381830E944F -:1009F000D9000F900F90DF91CF911F910F91FF9031 -:100A0000089580E895E060E070E00E948D00089510 -:100A10000F931F93CF93DF9384ED92E040E051EE6C -:100A200060E070E00E9454060E94010500D086E05C -:100A300091E0EDB7FEB7928381830E94D9000F90B9 -:100A40000F908AE391E00E944B088AE391E060E016 -:100A50000E94E8078AE391E00E9484088AE391E01B -:100A60000E947C07C0E0D0E000E011E000D000D0A0 -:100A7000EDB7FEB712830183CE0124E095958795EB -:100A80002A95E1F7948383830E94D90021960F90E1 -:100A90000F900F900F90C038D10541F700D083E040 -:100AA00091E0EDB7FEB7928381830E94D900C0E048 -:100AB000D0E00F900F9000D000D0EDB7FEB70183CB -:100AC0001283CE018F709070948383830E94D9002B -:100AD00021960F900F900F900F90C038D10559F7C5 -:100AE00000D083E091E0EDB7FEB7928381830E944E -:100AF000D9000F900F90DF91CF911F910F91089522 -:100B00000F931F93082F84ED92E0602F0E94280717 -:100B1000112707FD1095C8011F910F9108951F928D -:100B20000F920FB60F9211242F933F938F939F93A1 -:100B3000AF93BF9380914B0290914C02A0914D02D4 -:100B4000B0914E0230914F020196A11DB11D232F8D -:100B50002D5F2D3720F02D570196A11DB11D20933B -:100B60004F0280934B0290934C02A0934D02B0939E -:100B70004E028091470290914802A0914902B091A3 -:100B80004A020196A11DB11D80934702909348022D -:100B9000A0934902B0934A02BF91AF919F918F9168 -:100BA0003F912F910F900FBE0F901F9018950197B6 -:100BB00039F0880F991F880F991F02970197F1F755 -:100BC0000895789484B5826084BD84B5816084BDC5 -:100BD00085B5826085BD85B5816085BDEEE6F0E0B6 -:100BE000808181608083E1E8F0E010828081826012 -:100BF0008083808181608083E0E8F0E08081816093 -:100C00008083E1EBF0E0808184608083E0EBF0E0C2 -:100C1000808181608083EAE7F0E080818460808366 -:100C20008081826080838081816080838081806810 -:100C300080831092C10008950E94E1050E9408057A -:100C40000E949704FDCF1F920F920FB60F921124AE -:100C50002F933F934F938F939F93EF93FF934091E5 -:100C6000C600E091D002F091D10231969F012F771A -:100C7000307031978091D2029091D30228173907B2 -:100C800039F0E05BFD4F40833093D1022093D002D6 -:100C9000FF91EF919F918F914F913F912F910F90E5 -:100CA0000FBE0F901F901895AF92BF92DF92EF92F8 -:100CB000FF920F931F93CF93DF93EC017A018B0187 -:100CC000DD24403081EE580780E0680780E0780737 -:100CD00011F0DD24D39491E0A92EB12CE885F9859B -:100CE000DD2069F0C5010A8802C0880F991F0A94A7 -:100CF000E2F7808360E079E08DE390E005C0108248 -:100D000060E874E88EE190E0A80197010E949A09DA -:100D10002150304040405040569547953795279593 -:100D200080E12030380720F0DD2011F0DD24D6CF1F -:100D3000EC81FD813083EE81FF812083EA85FB8594 -:100D4000208141E050E0CA010E8402C0880F991F43 -:100D50000A94E2F7282B2083EA85FB852081CA01CB -:100D60000F8402C0880F991F0A94E2F7282B208372 -:100D7000EA85FB858081088802C0440F551F0A94CC -:100D8000E2F7842B8083DF91CF911F910F91FF9029 -:100D9000EF90DF90BF90AF900895DC011296ED9137 -:100DA000FC911397E058FF4F2191319180819181FF -:100DB000281B390B2F773070C9010895DC0112967A -:100DC000ED91FC911397EE57FF4F20813181929165 -:100DD0008291E058F0408217930719F42FEF3FEF0C -:100DE00005C0E20FF31F8081282F30E0C90108956C -:100DF000DC011296ED91FC911397DF01AE57BF4FC6 -:100E00002D913C911197E058FF4F80819181E058DE -:100E1000F0408217930719F42FEF3FEF0BC0E20F5A -:100E2000F31F80812F5F3F4F2F7730702D933C93BE -:100E3000282F30E0C9010895DC011296ED91FC9154 -:100E40001397EE57FF4F808191819293829308957B -:100E5000FC01A085B18521898C9190E0022E02C011 -:100E6000959587950A94E2F780FFF6CF0484F5857F -:100E7000E02D608308958BE291E09093D5028093FA -:100E8000D40280E592E09093D7028093D60285EC5D -:100E900090E09093D9028093D80284EC90E09093F4 -:100EA000DB028093DA0280EC90E09093DD02809385 -:100EB000DC0281EC90E09093DF028093DE0286EC0E -:100EC00090E09093E1028093E00284E08093E2025C -:100ED00083E08093E30287E08093E40285E08093DF -:100EE000E50281E08093E6020895FC01608341837E -:100EF00080E2828313820895FC01808160E00E9479 -:100F0000CD080895FF920F931F938C01F62E80E079 -:100F10000E94650985E00E946A09F80181816F2DB0 -:100F20000E94CD081F910F91FF9008951F93CF93BA -:100F3000DF93EC0160E070E00E94820781EE8EBDDD -:100F40000DB407FEFDCF1EB5CE0161E070E00E943A -:100F50008207812FDF91CF911F9108951F93CF9327 -:100F6000DF93EC0160E070E00E94820782EE8EBDAC -:100F70000DB407FEFDCF1EB5CE0161E070E00E940A -:100F80008207812FDF91CF911F9108950F931F93B7 -:100F9000CF93DF93EC01162F042F60E070E00E94E6 -:100FA00082071F7110621EBD0DB407FEFDCF1EB576 -:100FB0000EBD0DB407FEFDCF8EB5CE0161E070E031 -:100FC0000E948207812FDF91CF911F910F91089589 -:100FD000662319F061E04FE302C061E040E00E9447 -:100FE000C6070895462F603808F04FE765E00E9475 -:100FF000C6070895EF92FF920F931F93CF93DF934D -:101000007C01162FEA01022F60E070E00E94820747 -:101010001F7110621EBD0DB407FEFDCF1EB508C0C6 -:1010200088818EBD0DB407FEFDCF21968EB501508F -:101030000023B1F7C70161E070E00E948207812FB1 -:10104000DF91CF911F910F91FF90EF9008951F9323 -:10105000CF93DF93EC01162F60E070E00E948207CF -:101060001F711EBD0DB407FEFDCF8EB58FEF8EBD77 -:101070000DB407FEFDCF1EB5CE0161E070E00E9409 -:101080008207812FDF91CF911F91089569E00E941F -:101090002708817008950F931F938C01FC018081B4 -:1010A00061E00E94A708F801818161E00E94A70821 -:1010B000F801808160E00E94CD08C80161E070E025 -:1010C0000E9482070E947B0981E00E945C0980E007 -:1010D0000E94650985E00E946A09C80164E04FEF3B -:1010E0000E94C607C80167E040E70E94C607C80122 -:1010F0000E94AE07C8010E949607C80161E00E94E5 -:10110000F2071F910F9108950F931F938C0160E0D8 -:101110004BE00E94C607C80167E040E70E94C6078F -:10112000A8014B5F5F4FC8016AE025E00E94FA0703 -:10113000C8010E94AE07F801808161E00E94CD08DD -:1011400082E890E00E94D7051F910F910895482FE3 -:1011500050E0CA0186569F4FFC0124914A575F4FC9 -:10116000FA0184918823C1F0E82FF0E0EE0FFF1F11 -:10117000E859FF4FA591B491662341F49FB7F894C5 -:101180008C91209582238C939FBF08959FB7F894EC -:101190008C91822B8C939FBF0895482F50E0CA01F9 -:1011A00082559F4FFC012491CA0186569F4FFC0136 -:1011B00034914A575F4FFA019491992309F444C03E -:1011C000222351F1233071F0243028F42130A1F092 -:1011D000223011F514C02630B1F02730C1F0243090 -:1011E000D9F404C0809180008F7703C08091800083 -:1011F0008F7D8093800010C084B58F7702C084B546 -:101200008F7D84BD09C08091B0008F7703C080912D -:10121000B0008F7D8093B000E92FF0E0EE0FFF1F4C -:10122000EE58FF4FA591B491662341F49FB7F8940F -:101230008C91309583238C939FBF08959FB7F8942A -:101240008C91832B8C939FBF08950F931F93CF9303 -:10125000DF938C01EB0109C02196D801ED91FC913F -:101260000190F081E02DC801099568816623A1F7FE -:10127000DF91CF911F910F910895EF92FF920F93FD -:101280001F93CF93DF938C017B01EA010CC0D70140 -:101290006D917D01D801ED91FC910190F081E02DDF -:1012A000C80109952197209791F7DF91CF911F9160 -:1012B0000F91FF90EF900895882319F48CB5806208 -:1012C00002C08CB58F7D8CBD08959CB5937F982B03 -:1012D0009CBD08952CB5382F33702C7F322B3CBD2C -:1012E0002DB590E0959587959595879581702E7F82 -:1012F000822B8DBD08958DE061E00E94A7088BE0F0 -:1013000061E00E94A7088AE061E00E94A7088DE0E2 -:1013100060E00E94CD088BE060E00E94CD088AE08A -:1013200061E00E94CD088CB580618CBD8CB5806475 -:101330008CBD0895A1E21A2EAA1BBB1BFD010DC096 -:10134000AA1FBB1FEE1FFF1FA217B307E407F50775 -:1013500020F0A21BB30BE40BF50B661F771F881F51 -:10136000991F1A9469F760957095809590959B01E7 -:10137000AC01BD01CF0108952F923F924F925F9231 -:101380006F927F928F929F92AF92BF92CF92DF9295 -:10139000EF92FF920F931F93CF93DF93CDB7DEB7FA -:1013A000CA1BDB0B0FB6F894DEBF0FBECDBF09948E -:1013B0002A88398848885F846E847D848C849B84E5 -:1013C000AA84B984C884DF80EE80FD800C811B81F3 -:1013D000AA81B981CE0FD11D0FB6F894DEBF0FBE22 -:1013E000CDBFED010895EE0FFF1F0590F491E02DA4 -:0613F0000994F894FFCF00 -:1013F6002578000A0D000A0D524632342F657861B1 -:101406006D706C65732F7363616E6E65722F0A0D56 -:10141600002000F102000000000000280725093D19 -:0A14260009CD06F806DE061C0700DB -:00000001FF diff --git a/AVR/lib/RF24/examples/scanner/printf.h b/AVR/lib/RF24/examples/scanner/printf.h deleted file mode 100644 index 66f6438..0000000 --- a/AVR/lib/RF24/examples/scanner/printf.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#endif // __PRINTF_H__ diff --git a/AVR/lib/RF24/examples/scanner/scanner.pde b/AVR/lib/RF24/examples/scanner/scanner.pde deleted file mode 100644 index 1a43d72..0000000 --- a/AVR/lib/RF24/examples/scanner/scanner.pde +++ /dev/null @@ -1,124 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * Channel scanner - * - * Example to detect interference on the various channels available. - * This is a good diagnostic tool to check whether you're picking a - * good channel for your application. - * - * Inspired by cpixip. - * See http://arduino.cc/forum/index.php/topic,54795.0.html - */ - -#include -#include "nRF24L01.h" -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 9 & 10 - -RF24 radio(9,10); - -// -// Channel info -// - -const uint8_t num_channels = 128; -uint8_t values[num_channels]; - -// -// Setup -// - -void setup(void) -{ - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/scanner/\n\r"); - - // - // Setup and configure rf radio - // - - radio.begin(); - radio.setAutoAck(false); - - // Get into standby mode - radio.startListening(); - radio.stopListening(); - - // Print out header, high then low digit - int i = 0; - while ( i < num_channels ) - { - printf("%x",i>>4); - ++i; - } - printf("\n\r"); - i = 0; - while ( i < num_channels ) - { - printf("%x",i&0xf); - ++i; - } - printf("\n\r"); -} - -// -// Loop -// - -const int num_reps = 100; - -void loop(void) -{ - // Clear measurement values - memset(values,0,sizeof(values)); - - // Scan all channels num_reps times - int rep_counter = num_reps; - while (rep_counter--) - { - int i = num_channels; - while (i--) - { - // Select this channel - radio.setChannel(i); - - // Listen for a little - radio.startListening(); - delayMicroseconds(128); - radio.stopListening(); - - // Did we get a carrier? - if ( radio.testCarrier() ) - ++values[i]; - } - } - - // Print out channel measurements, clamped to a single hex digit - int i = 0; - while ( i < num_channels ) - { - printf("%x",min(0xf,values[i]&0xf)); - ++i; - } - printf("\n\r"); -} - -// vim:ai:cin:sts=2 sw=2 ft=cpp diff --git a/AVR/lib/RF24/examples/starping/Jamfile b/AVR/lib/RF24/examples/starping/Jamfile deleted file mode 100644 index de9b1f6..0000000 --- a/AVR/lib/RF24/examples/starping/Jamfile +++ /dev/null @@ -1,206 +0,0 @@ -PROJECT_NAME = $(PWD:B) ; -PROJECT_DIR = . ; -PROJECT_LIBS = EEPROM SPI RF24 ; - -OUT_DIR = ojam ; -F_CPU = 16000000 ; -MCU = atmega328p ; -PORTS = /dev/tty.usbserial-A600eHIs /dev/tty.usbserial-A40081RP /dev/tty.usbserial-A9007LmI ; - -UPLOAD_RATE = 57600 ; -AVRDUDE_PROTOCOL = stk500v1 ; -COM = 33 ; - -# Host-specific overrides for locations -if $(OS) = MACOSX -{ -ARDUINO_VERSION = 22 ; -OLD_DIR = /opt/arduino-0021 ; -AVR_TOOLS_PATH = $(OLD_DIR)/hardware/tools/avr/bin ; -AVRDUDECONFIG_PATH = $(OLD_DIR)/hardware/tools/avr/etc ; -ARDUINO_DIR = /opt/Arduino ; -ARDUINO_AVR = /usr/lib/avr/include ; -} - -# Where is everything? -ARDUINO_VERSION ?= 22 ; -AVR_TOOLS_PATH ?= /usr/bin ; -ARDUINO_DIR ?= /opt/arduino-00$(ARDUINO_VERSION) ; -ARDUINO_AVR ?= $(ARDUINO_DIR)/hardware/tools/avr/avr/include/avr ; -AVRDUDECONFIG_PATH ?= $(ARDUINO_DIR)/hardware/tools ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; -AVR_CC = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_CXX = $(AVR_TOOLS_PATH)/avr-g++ ; -AVR_LD = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_OBJCOPY = $(AVR_TOOLS_PATH)/avr-objcopy ; -AVRDUDE = $(AVR_TOOLS_PATH)/avrdude ; - -DEFINES = F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -CTUNING = -ffunction-sections -fdata-sections ; -CXXTUNING = -fno-exceptions -fno-strict-aliasing ; -CFLAGS = -Os -Wall -Wextra -mmcu=$(MCU) $(CTUNING) ; -CXXFLAGS = $(CFLAGS) $(CXXTUNING) ; -LDFLAGS = -Os -lm -Wl,--gc-sections -mmcu=atmega328p ; - -# Search everywhere for headers -HDRS = $(PROJECT_DIR) $(ARDUINO_AVR) $(ARDUINO_CORE) [ GLOB $(ARDUINO_LIB) $(SKETCH_LIB) : [^.]* ] ; - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp ] ; - -# In addition to explicitly-specified program modules, pick up anything from the current -# dir. -PROJECT_MODULES += [ GLOB $(PROJECT_DIR) : *.c *.cpp *.pde ] ; - -# Shortcut for the out files -OUT = $(OUT_DIR)/$(PROJECT_NAME) ; - -# AvrDude setup -AVRDUDE_FLAGS = -V -F -D -C $(AVRDUDECONFIG_PATH)/avrdude.conf -p $(MCU) -c $(AVRDUDE_PROTOCOL) -b $(UPLOAD_RATE) ; - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule AvrCc -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrCc -{ - $(AVR_CC) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CFLAGS) $(>) -} - -rule AvrC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrC++ -{ - $(AVR_CXX) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule Pde -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - -} - -actions Pde -{ - echo "#include " > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule AvrPde -{ - local _CPP = $(OUT_DIR)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - AvrC++ $(<) : $(_CPP) ; -} - -rule AvrObject -{ - switch $(>:S) - { - case .c : AvrCc $(<) : $(>) ; - case .cpp : AvrC++ $(<) : $(>) ; - case .pde : AvrPde $(<) : $(>) ; - } -} - -rule AvrObjects -{ - for _I in $(<) - { - AvrObject $(OUT_DIR)/$(_I:B).o : $(_I) ; - } -} - -rule AvrMainFromObjects -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - MkDir $(<:D) ; - Depends all : $(<) ; - Clean clean : $(<) ; -} - -actions AvrMainFromObjects -{ - $(AVR_LD) $(LDFLAGS) -o $(<) $(>) -} - -rule AvrMain -{ - AvrMainFromObjects $(<) : $(OUT_DIR)/$(>:B).o ; - AvrObjects $(>) ; -} - -rule AvrHex -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions AvrHex -{ - $(AVR_OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule AvrUpload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - AvrUploadAction $(2) : $(3) ; -} - -actions AvrUploadAction -{ - $(AVRDUDE) $(AVRDUDE_FLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -AvrMain $(OUT).elf : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -AvrHex $(OUT).hex : $(OUT).elf ; - -AvrUpload p6 : /dev/tty.usbserial-A600eHIs : $(OUT).hex ; -AvrUpload p4 : /dev/tty.usbserial-A40081RP : $(OUT).hex ; -AvrUpload p9 : /dev/tty.usbserial-A9007LmI : $(OUT).hex ; - diff --git a/AVR/lib/RF24/examples/starping/printf.h b/AVR/lib/RF24/examples/starping/printf.h deleted file mode 100644 index b2efd56..0000000 --- a/AVR/lib/RF24/examples/starping/printf.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -#ifdef ARDUINO - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#else -#error This example is only for use on Arduino. -#endif // ARDUINO - -#endif // __PRINTF_H__ diff --git a/AVR/lib/RF24/examples/starping/starping.pde b/AVR/lib/RF24/examples/starping/starping.pde deleted file mode 100644 index 4813a77..0000000 --- a/AVR/lib/RF24/examples/starping/starping.pde +++ /dev/null @@ -1,293 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * Example RF Radio Ping Star Group - * - * This sketch is a more complex example of using the RF24 library for Arduino. - * Deploy this on up to six nodes. Set one as the 'pong receiver' by tying the - * role_pin low, and the others will be 'ping transmit' units. The ping units - * unit will send out the value of millis() once a second. The pong unit will - * respond back with a copy of the value. Each ping unit can get that response - * back, and determine how long the whole cycle took. - * - * This example requires a bit more complexity to determine which unit is which. - * The pong receiver is identified by having its role_pin tied to ground. - * The ping senders are further differentiated by a byte in eeprom. - */ - -#include -#include -#include "nRF24L01.h" -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 9 & 10 - -RF24 radio(9,10); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'pong' receiver. -const int role_pin = 7; - -// -// Topology -// - -// Radio pipe addresses for the nodes to communicate. Only ping nodes need -// dedicated pipes in this topology. Each ping node has a talking pipe -// that it will ping into, and a listening pipe that it will listen for -// the pong. The pong node listens on all the ping node talking pipes -// and sends the pong back on the sending node's specific listening pipe. - -const uint64_t talking_pipes[5] = { 0xF0F0F0F0D2LL, 0xF0F0F0F0C3LL, 0xF0F0F0F0B4LL, 0xF0F0F0F0A5LL, 0xF0F0F0F096LL }; -const uint64_t listening_pipes[5] = { 0x3A3A3A3AD2LL, 0x3A3A3A3AC3LL, 0x3A3A3A3AB4LL, 0x3A3A3A3AA5LL, 0x3A3A3A3A96LL }; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes -// in this system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_invalid = 0, role_ping_out, role_pong_back } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"}; - -// The role of the current running sketch -role_e role; - -// -// Address management -// - -// Where in EEPROM is the address stored? -const uint8_t address_at_eeprom_location = 0; - -// What is our address (SRAM cache of the address from EEPROM) -// Note that zero is an INVALID address. The pong back unit takes address -// 1, and the rest are 2-6 -uint8_t node_address; - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_ping_out; - else - role = role_pong_back; - - // - // Address - // - - if ( role == role_pong_back ) - node_address = 1; - else - { - // Read the address from EEPROM - uint8_t reading = EEPROM.read(address_at_eeprom_location); - - // If it is in a valid range for node addresses, it is our - // address. - if ( reading >= 2 && reading <= 6 ) - node_address = reading; - - // Otherwise, it is invalid, so set our address AND ROLE to 'invalid' - else - { - node_address = 0; - role = role_invalid; - } - } - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/starping/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - printf("ADDRESS: %i\n\r",node_address); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // - // Open pipes to other nodes for communication - // - - // The pong node listens on all the ping node talking pipes - // and sends the pong back on the sending node's specific listening pipe. - if ( role == role_pong_back ) - { - radio.openReadingPipe(1,talking_pipes[0]); - radio.openReadingPipe(2,talking_pipes[1]); - radio.openReadingPipe(3,talking_pipes[2]); - radio.openReadingPipe(4,talking_pipes[3]); - radio.openReadingPipe(5,talking_pipes[4]); - } - - // Each ping node has a talking pipe that it will ping into, and a listening - // pipe that it will listen for the pong. - if ( role == role_ping_out ) - { - // Write on our talking pipe - radio.openWritingPipe(talking_pipes[node_address-2]); - // Listen on our listening pipe - radio.openReadingPipe(1,listening_pipes[node_address-2]); - } - - // - // Start listening - // - - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); - - // - // Prompt the user to assign a node address if we don't have one - // - - if ( role == role_invalid ) - { - printf("\n\r*** NO NODE ADDRESS ASSIGNED *** Send 1 through 6 to assign an address\n\r"); - } -} - -void loop(void) -{ - // - // Ping out role. Repeatedly send the current time - // - - if (role == role_ping_out) - { - // First, stop listening so we can talk. - radio.stopListening(); - - // Take the time, and send it. This will block until complete - unsigned long time = millis(); - printf("Now sending %lu...",time); - radio.write( &time, sizeof(unsigned long) ); - - // Now, continue listening - radio.startListening(); - - // Wait here until we get a response, or timeout (250ms) - unsigned long started_waiting_at = millis(); - bool timeout = false; - while ( ! radio.available() && ! timeout ) - if (millis() - started_waiting_at > 250 ) - timeout = true; - - // Describe the results - if ( timeout ) - { - printf("Failed, response timed out.\n\r"); - } - else - { - // Grab the response, compare, and send to debugging spew - unsigned long got_time; - radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got response %lu, round-trip delay: %lu\n\r",got_time,millis()-got_time); - } - - // Try again 1s later - delay(1000); - } - - // - // Pong back role. Receive each packet, dump it out, and send it back - // - - if ( role == role_pong_back ) - { - // if there is data ready - uint8_t pipe_num; - if ( radio.available(&pipe_num) ) - { - // Dump the payloads until we've gotten everything - unsigned long got_time; - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - done = radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got payload %lu from node %i...",got_time,pipe_num+1); - } - - // First, stop listening so we can talk - radio.stopListening(); - - // Open the correct pipe for writing - radio.openWritingPipe(listening_pipes[pipe_num-1]); - - // Retain the low 2 bytes to identify the pipe for the spew - uint16_t pipe_id = listening_pipes[pipe_num-1] & 0xffff; - - // Send the final one back. - radio.write( &got_time, sizeof(unsigned long) ); - printf("Sent response to %04x.\n\r",pipe_id); - - // Now, resume listening so we catch the next packets. - radio.startListening(); - } - } - - // - // Listen for serial input, which is how we set the address - // - if (Serial.available()) - { - // If the character on serial input is in a valid range... - char c = Serial.read(); - if ( c >= '1' && c <= '6' ) - { - // It is our address - EEPROM.write(address_at_eeprom_location,c-'0'); - - // And we are done right now (no easy way to soft reset) - printf("\n\rManually reset address to: %c\n\rPress RESET to continue!",c); - while(1) ; - } - } -} -// vim:ai:ci sts=2 sw=2 ft=cpp diff --git a/AVR/lib/RF24/keywords.txt b/AVR/lib/RF24/keywords.txt deleted file mode 100644 index d0bd557..0000000 --- a/AVR/lib/RF24/keywords.txt +++ /dev/null @@ -1,13 +0,0 @@ - RF24 KEYWORD1 - begin KEYWORD2 - setChannel KEYWORD2 - setPayloadSize KEYWORD2 - getPayloadSize KEYWORD2 - print_details KEYWORD2 - startListening KEYWORD2 - stopListening KEYWORD2 - write KEYWORD2 - available KEYWORD2 - read KEYWORD2 - openWritingPipe KEYWORD2 - openReadingPipe KEYWORD2 \ No newline at end of file diff --git a/AVR/lib/RF24/tests/README b/AVR/lib/RF24/tests/README deleted file mode 100644 index 43ceaf5..0000000 --- a/AVR/lib/RF24/tests/README +++ /dev/null @@ -1,7 +0,0 @@ -The sketches in this directory are intended to be checkin tests. -No code should be pushed to github without these tests passing. - -See "runtests.sh" script inside each sketch dir. This script is fully compatible with -git bisest. - -Note that this requires python and py-serial diff --git a/AVR/lib/RF24/tests/native/Jamfile b/AVR/lib/RF24/tests/native/Jamfile deleted file mode 100644 index 10d0336..0000000 --- a/AVR/lib/RF24/tests/native/Jamfile +++ /dev/null @@ -1,300 +0,0 @@ -PROJECT_NAME = $(PWD:B) ; -PROJECT_DIR = . ; -PROJECT_LIBS = RF24 ; - -OUT_DIR = ojam ; -F_CPU = 16000000 ; -MCU = atmega328p ; -PORTS = /dev/tty.usbserial-A600eHIs /dev/tty.usbserial-A40081RP /dev/tty.usbserial-A9007LmI ; - -UPLOAD_RATE = 57600 ; -AVRDUDE_PROTOCOL = stk500v1 ; -COM = 33 ; - -# Host-specific overrides for locations -if $(OS) = MACOSX -{ -ARDUINO_VERSION = 22 ; -OLD_DIR = /opt/arduino-0021 ; -AVR_TOOLS_PATH = $(OLD_DIR)/hardware/tools/avr/bin ; -AVRDUDECONFIG_PATH = $(OLD_DIR)/hardware/tools/avr/etc ; -ARDUINO_DIR = /opt/Arduino ; -ARDUINO_AVR = /usr/lib/avr/include ; -} - -# Where is everything? -ARDUINO_VERSION ?= 22 ; -SKETCH_DIR = $(HOME)/Source/Arduino ; -AVR_TOOLS_PATH ?= /usr/bin ; -ARDUINO_DIR ?= /opt/arduino-00$(ARDUINO_VERSION) ; -ARDUINO_AVR ?= $(ARDUINO_DIR)/hardware/tools/avr/avr/include/avr ; -AVRDUDECONFIG_PATH ?= $(ARDUINO_DIR)/hardware/tools ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(SKETCH_DIR)/libraries ; -AVR_AS = $(AVR_TOOLS_PATH)/avr-as ; -AVR_CC = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_CXX = $(AVR_TOOLS_PATH)/avr-g++ ; -AVR_LD = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_OBJCOPY = $(AVR_TOOLS_PATH)/avr-objcopy ; -AVRDUDE = $(AVR_TOOLS_PATH)/avrdude ; - -DEFINES = F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H HAL=1 ; -CTUNING = -ffunction-sections -fdata-sections ; -CXXTUNING = -fno-exceptions -fno-strict-aliasing ; -ASFLAGS = -mmcu=$(MCU) ; -CFLAGS = -Os -Wall -Wextra $(ASFLAGS) $(CTUNING) ; -CXXFLAGS = $(CFLAGS) $(CXXTUNING) ; -LDFLAGS = -Os -lm -Wl,--gc-sections -mmcu=atmega328p ; - -# Search everywhere for headers -HDRS = $(PROJECT_DIR) $(ARDUINO_AVR) $(ARDUINO_CORE) [ GLOB $(ARDUINO_LIB) $(SKETCH_LIB) : [^.]* ] ; -HDRS += [ GLOB $(HDRS) : utility ] ; - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp *.c ] ; - -# In addition to explicitly-specified program modules, pick up anything from the current -# dir. -PROJECT_MODULES += [ GLOB $(PROJECT_DIR) : *.c *.cpp *.pde ] ; - -# Shortcut for the out files -OUT = $(OUT_DIR)/$(PROJECT_NAME) ; - -# AvrDude setup -AVRDUDE_FLAGS = -V -F -D -C $(AVRDUDECONFIG_PATH)/avrdude.conf -p $(MCU) -c $(AVRDUDE_PROTOCOL) -b $(UPLOAD_RATE) ; - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -# GitVersion version.h ; - -rule AvrAsm -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrAsm -{ - $(AVR_AS) $(ASFLAGS) -o $(<) $(>) -} - -rule AvrCc -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrCc -{ - $(AVR_CC) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CFLAGS) $(>) -} - -rule AvrC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrC++ -{ - $(AVR_CXX) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule AvrAsmFromC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrAsmFromC++ -{ - $(AVR_CXX) -S -fverbose-asm -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule Pde -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; -} - -actions Pde -{ - echo "#include " > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule AvrPde -{ - local _CPP = $(OUT_DIR)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - AvrC++ $(<) : $(_CPP) ; -} - -rule AvrObject -{ - switch $(>:S) - { - case .S : AvrAsm $(<) : $(>) ; - case .c : AvrCc $(<) : $(>) ; - case .cpp : AvrC++ $(<) : $(>) ; - case .pde : AvrPde $(<) : $(>) ; - } -} - -rule AvrObjects -{ - for _I in $(<) - { - AvrObject $(OUT_DIR)/$(_I:B).o : $(_I) ; - } -} - -rule AvrMainFromObjects -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - MkDir $(<:D) ; - Depends all : $(<) ; - Clean clean : $(<) ; -} - -actions AvrMainFromObjects -{ - $(AVR_LD) $(LDFLAGS) -o $(<) $(>) -} - -rule AvrMain -{ - AvrMainFromObjects $(<) : $(OUT_DIR)/$(>:B).o ; - AvrObjects $(>) ; -} - -rule AvrHex -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions AvrHex -{ - $(AVR_OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule AvrUpload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - AvrUploadAction $(2) : $(3) ; -} - -actions AvrUploadAction -{ - $(AVRDUDE) $(AVRDUDE_FLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -AvrMain $(OUT).elf : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) -AvrHex $(OUT).hex : $(OUT).elf ; - -AvrUpload p6 : /dev/tty.usbserial-A600eHIs : $(OUT).hex ; -AvrUpload p4 : /dev/tty.usbserial-A40081RP : $(OUT).hex ; -AvrUpload p9 : /dev/tty.usbserial-A9007LmI : $(OUT).hex ; - -# -# Native -# - -OUT_DIR_NATIVE = out_native ; -OUT_NATIVE = $(OUT_DIR_NATIVE)/$(PROJECT_NAME) ; -NATIVE_CORE = $(SKETCH_DIR)/hardware/native ; -HDRS = $(NATIVE_CORE) $(HDRS) ; -NATIVE_CORE_MODULES = [ GLOB $(NATIVE_CORE) : *.c *.cpp ] ; -NATIVE_MODULES = ; -DEFINES += NATIVE ; - -rule NativePde -{ - local _CPP = $(OUT_DIR_NATIVE)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - C++ $(<) : $(_CPP) ; -} - -rule UserObject -{ - switch $(>) - { - case *.pde : NativePde $(<) : $(>) ; - } -} - -rule Objects -{ - for _I in $(<) - { - local _O = $(OUT_DIR_NATIVE)/$(_I:B).o ; - Object $(_O) : $(_I) ; - } -} - -rule Main -{ - MainFromObjects $(<) : $(OUT_DIR_NATIVE)/$(>:B).o ; - Objects $(>) ; -} - -actions C++ -{ - c++ -c -o $(<) $(CCHDRS) $(CCDEFS) $(>) -} - -actions Link -{ - c++ -o $(<) $(>) -} - - - -MkDir $(OUT_DIR_NATIVE) ; -Depends $(OUT_NATIVE) : $(OUT_DIR_NATIVE) ; -Main $(OUT_NATIVE) : $(NATIVE_CORE_MODULES) $(NATIVE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; - -Depends native : $(OUT_NATIVE) ; - diff --git a/AVR/lib/RF24/tests/native/pingpair_irq.pde b/AVR/lib/RF24/tests/native/pingpair_irq.pde deleted file mode 100644 index 99c2cdf..0000000 --- a/AVR/lib/RF24/tests/native/pingpair_irq.pde +++ /dev/null @@ -1,223 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * Interrupt-driven test for native target - * - * This example is the friendliest for the native target because it doesn't do - * any polling. Made a slight change to call done() at the end of setup. - */ - -#include -#include "nRF24L01.h" -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 8 & 9 - -RF24 radio(8,9); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const short role_pin = 7; - -// -// Topology -// - -// Single radio pipe address for the 2 nodes to communicate. -const uint64_t pipe = 0xE8E8F0F0E1LL; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes in this -// system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_sender = 1, role_receiver } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Sender", "Receiver"}; - -// The role of the current running sketch -role_e role; - -// Interrupt handler, check the radio because we got an IRQ -void check_radio(void); - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_sender; - else - role = role_receiver; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/pingpair_irq/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // We will be using the Ack Payload feature, so please enable it - radio.enableAckPayload(); - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens a single pipe for these two nodes to communicate - // back and forth. One listens on it, the other talks to it. - - if ( role == role_sender ) - { - radio.openWritingPipe(pipe); - } - else - { - radio.openReadingPipe(1,pipe); - } - - // - // Start listening - // - - if ( role == role_receiver ) - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); - - // - // Attach interrupt handler to interrupt #0 (using pin 2) - // on BOTH the sender and receiver - // - - attachInterrupt(0, check_radio, FALLING); - - // - // On the native target, this is as far as we get - // -#if NATIVE - done(); -#endif -} - -static uint32_t message_count = 0; - -void loop(void) -{ - // - // Sender role. Repeatedly send the current time - // - - if (role == role_sender) - { - // Take the time, and send it. - unsigned long time = millis(); - printf("Now sending %lu\n\r",time); - radio.startWrite( &time, sizeof(unsigned long) ); - - // Try again soon - delay(2000); - } - - // - // Receiver role: Does nothing! All the work is in IRQ - // - -} - -void check_radio(void) -{ - // What happened? - bool tx,fail,rx; - radio.whatHappened(tx,fail,rx); - - // Have we successfully transmitted? - if ( tx ) - { - if ( role == role_sender ) - printf("Send:OK\n\r"); - - if ( role == role_receiver ) - printf("Ack Payload:Sent\n\r"); - } - - // Have we failed to transmit? - if ( fail ) - { - if ( role == role_sender ) - printf("Send:Failed\n\r"); - - if ( role == role_receiver ) - printf("Ack Payload:Failed\n\r"); - } - - // Transmitter can power down for now, because - // the transmission is done. - if ( ( tx || fail ) && ( role == role_sender ) ) - radio.powerDown(); - - // Did we receive a message? - if ( rx ) - { - // If we're the sender, we've received an ack payload - if ( role == role_sender ) - { - radio.read(&message_count,sizeof(message_count)); - printf("Ack:%lu\n\r",(unsigned long)message_count); - } - - // If we're the receiver, we've received a time message - if ( role == role_receiver ) - { - // Get this payload and dump it - static unsigned long got_time; - radio.read( &got_time, sizeof(got_time) ); - printf("Got payload %lu\n\r",got_time); - - // Add an ack packet for the next time around. This is a simple - // packet counter - radio.writeAckPayload( 1, &message_count, sizeof(message_count) ); - ++message_count; - } - } -} - -// vim:ai:cin:sts=2 sw=2 ft=cpp diff --git a/AVR/lib/RF24/tests/native/printf.h b/AVR/lib/RF24/tests/native/printf.h deleted file mode 100644 index df6c46a..0000000 --- a/AVR/lib/RF24/tests/native/printf.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -#include "WProgram.h" - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#endif // __PRINTF_H__ diff --git a/AVR/lib/RF24/tests/pingpair_blocking/Jamfile b/AVR/lib/RF24/tests/pingpair_blocking/Jamfile deleted file mode 100644 index 18244ec..0000000 --- a/AVR/lib/RF24/tests/pingpair_blocking/Jamfile +++ /dev/null @@ -1,219 +0,0 @@ -# (1) Project Information - -PROJECT_LIBS = SPI RF24 ; -PROJECT_DIRS = $(PWD) ; - -# (2) Board Information - -UPLOAD_PROTOCOL ?= arduino ; -UPLOAD_SPEED ?= 115200 ; -MCU ?= atmega328p ; -F_CPU ?= 16000000 ; -CORE ?= arduino ; -VARIANT ?= standard ; -ARDUINO_VERSION ?= 100 ; - -# (3) USB Ports - -PORTS = p4 p6 p9 u0 u1 u2 ; -PORT_p6 = /dev/tty.usbserial-A600eHIs ; -PORT_p4 = /dev/tty.usbserial-A40081RP ; -PORT_p9 = /dev/tty.usbserial-A9007LmI ; -PORT_u0 = /dev/ttyUSB0 ; -PORT_u1 = /dev/ttyUSB1 ; -PORT_u2 = /dev/ttyUSB2 ; - -# (4) Location of AVR tools -# -# This configuration assumes using avr-tools that were obtained separate from the Arduino -# distribution. - -if $(OS) = MACOSX -{ - AVR_BIN ?= /usr/local/avrtools/bin ; - AVR_ETC = /usr/local/avrtools/etc ; - AVR_INCLUDE = /usr/local/avrtools/include ; -} -else -{ - AVR_BIN ?= /usr/bin ; - AVR_INCLUDE = /usr/lib/avr/include ; - AVR_ETC = /etc ; -} - -# (5) Directories where Arduino core and libraries are located - -ARDUINO_DIR ?= /opt/Arduino ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/$(CORE) $(ARDUINO_DIR)/hardware/arduino/variants/$(VARIANT) ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; - -# -# -------------------------------------------------- -# Below this line usually never needs to be modified -# - -# Tool locations - -CC = $(AVR_BIN)/avr-gcc ; -C++ = $(AVR_BIN)/avr-g++ ; -LINK = $(AVR_BIN)/avr-gcc ; -AR = $(AVR_BIN)/avr-ar rcs ; -RANLIB = ; -OBJCOPY = $(AVR_BIN)/avr-objcopy ; -AVRDUDE ?= $(AVR_BIN)/avrdude ; - -# Flags - -DEFINES += F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -OPTIM = -Os ; -CCFLAGS = -Wall -Wextra -Wno-strict-aliasing -mmcu=$(MCU) -ffunction-sections -fdata-sections ; -C++FLAGS = $(CCFLAGS) -fno-exceptions -fno-strict-aliasing ; -LINKFLAGS = $(OPTIM) -lm -Wl,--gc-sections -mmcu=$(MCU) ; -AVRDUDEFLAGS = -V -F -D -C $(AVR_ETC)/avrdude.conf -p $(MCU) -c $(UPLOAD_PROTOCOL) -b $(UPLOAD_SPEED) ; - -# Search everywhere for headers - -HDRS = $(PROJECT_DIRS) $(AVR_INCLUDE) $(ARDUINO_CORE) $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) ; - -# Output locations - -LOCATE_TARGET = $(F_CPU) ; -LOCATE_SOURCE = $(F_CPU) ; - -# -# Custom rules -# - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule Pde -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_SOURCE) ; - Clean clean : $(<) ; -} - -if ( $(ARDUINO_VERSION) < 100 ) -{ - ARDUINO_H = WProgram.h ; -} -else -{ - ARDUINO_H = Arduino.h ; -} - -actions Pde -{ - echo "#include <$(ARDUINO_H)>" > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule C++Pde -{ - local _CPP = $(>:B).cpp ; - Pde $(_CPP) : $(>) ; - C++ $(<) : $(_CPP) ; -} - -rule UserObject -{ - switch $(>:S) - { - case .ino : C++Pde $(<) : $(>) ; - case .pde : C++Pde $(<) : $(>) ; - } -} - -rule Objects -{ - local _i ; - - for _i in [ FGristFiles $(<) ] - { - local _b = $(_i:B)$(SUFOBJ) ; - local _o = $(_b:G=$(SOURCE_GRIST:E)) ; - Object $(_o) : $(_i) ; - Depends obj : $(_o) ; - } -} - -rule Library -{ - LibraryFromObjects $(<) : $(>:B)$(SUFOBJ) ; - Objects $(>) ; -} - -rule Main -{ - MainFromObjects $(<) : $(>:B)$(SUFOBJ) ; - Objects $(>) ; -} - -rule Hex -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_TARGET) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions Hex -{ - $(OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule Upload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - UploadAction $(2) : $(3) ; -} - -actions UploadAction -{ - $(AVRDUDE) $(AVRDUDEFLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -rule Arduino -{ - LINKFLAGS on $(<) = $(LINKFLAGS) -Wl,-Map=$(LOCATE_TARGET)/$(<:B).map ; - Main $(<) : $(>) ; - LinkLibraries $(<) : core libs ; - Hex $(<:B).hex : $(<) ; - for _p in $(PORTS) - { - Upload $(_p) : $(PORT_$(_p)) : $(<:B).hex ; - } -} - -# -# Targets -# - -# Grab everything from the core directory -Library core : [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -Library libs : [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp *.c ] ; - -# Main output executable -Arduino $(PWD:B).elf : $(PROJECT_MODULES) [ GLOB $(PROJECT_DIRS) : *.c *.cpp *.pde *.ino ] ; diff --git a/AVR/lib/RF24/tests/pingpair_blocking/pingpair_blocking.pde b/AVR/lib/RF24/tests/pingpair_blocking/pingpair_blocking.pde deleted file mode 100644 index 1501d37..0000000 --- a/AVR/lib/RF24/tests/pingpair_blocking/pingpair_blocking.pde +++ /dev/null @@ -1,273 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -#include -#include "nRF24L01.h" -#include "RF24.h" -#include "printf.h" - -// -// Test version of RF24, exposes some protected interface -// - -class RF24Test: public RF24 -{ -public: RF24Test(int a, int b): RF24(a,b) {} -}; - - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 8 & 9 - -RF24Test radio(8,9); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const int role_pin = 7; - -// -// Topology -// - -// Radio pipe addresses for the 2 nodes to communicate. -const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL }; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes -// in this system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_ping_out = 1, role_pong_back } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"}; - -// The role of the current running sketch -role_e role; - -// -// Test state -// - -bool done; //*< Are we done with the test? */ -bool passed; //*< Have we passed the test? */ -bool notified; //*< Have we notified the user we're done? */ -const int num_needed = 10; //*< How many success/failures until we're done? */ -int receives_remaining = num_needed; //*< How many ack packets until we declare victory? */ -int failures_remaining = num_needed; //*< How many more failed sends until we declare failure? */ -const int interval = 100; //*< ms to wait between sends */ - -char configuration = '1'; //*< Configuration key, one char sent in by the test framework to tell us how to configure, this is the default */ - -void one_ok(void) -{ - // Have we received enough yet? - if ( ! --receives_remaining ) - { - done = true; - passed = true; - } -} - -void one_failed(void) -{ - // Have we failed enough yet? - if ( ! --failures_remaining ) - { - done = true; - passed = false; - } -} - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_ping_out; - else - role = role_pong_back; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/tests/pingpair_blocking/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // get test config - // - - printf("+READY press any key to start\n\r\n\r"); - - while (! Serial.available() ) {} - configuration = Serial.read(); - printf("Configuration\t = %c\n\r",configuration); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens two pipes for these two nodes to communicate - // back and forth. - // Open 'our' pipe for writing - // Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading) - - if ( role == role_ping_out ) - { - radio.openWritingPipe(pipes[0]); - radio.openReadingPipe(1,pipes[1]); - } - else - { - radio.openWritingPipe(pipes[1]); - radio.openReadingPipe(1,pipes[0]); - } - - // - // Start listening - // - - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); - - if ( role == role_pong_back ) - printf("\n\r+OK "); -} - -void loop(void) -{ - // - // Ping out role. Repeatedly send the current time - // - - if (role == role_ping_out) - { - // First, stop listening so we can talk. - radio.stopListening(); - - // Take the time, and send it. This will block until complete - unsigned long time = millis(); - printf("Now sending %lu...",time); - radio.write( &time, sizeof(unsigned long) ); - - // Now, continue listening - radio.startListening(); - - // Wait here until we get a response, or timeout (250ms) - unsigned long started_waiting_at = millis(); - bool timeout = false; - while ( ! radio.available() && ! timeout ) - if (millis() - started_waiting_at > 200 ) - timeout = true; - - // Describe the results - if ( timeout ) - { - printf("Failed, response timed out.\n\r"); - one_failed(); - } - else - { - // Grab the response, compare, and send to debugging spew - unsigned long got_time; - radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got response %lu, round-trip delay: %lu\n\r",got_time,millis()-got_time); - one_ok(); - } - - // Try again later - delay(250); - } - - // - // Pong back role. Receive each packet, dump it out, and send it back - // - - if ( role == role_pong_back ) - { - // if there is data ready - if ( radio.available() ) - { - // Dump the payloads until we've gotten everything - unsigned long got_time; - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - done = radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got payload %lu...",got_time); - - // Delay just a little bit to let the other unit - // make the transition to receiver - delay(20); - } - - // First, stop listening so we can talk - radio.stopListening(); - - // Send the final one back. - radio.write( &got_time, sizeof(unsigned long) ); - printf("Sent response.\n\r"); - - // Now, resume listening so we catch the next packets. - radio.startListening(); - - } - } - - // - // Stop the test if we're done and report results - // - if ( done && ! notified ) - { - notified = true; - - printf("\n\r+OK "); - if ( passed ) - printf("PASS\n\r\n\r"); - else - printf("FAIL\n\r\n\r"); - } -} -// vim:cin:ai:sts=2 sw=2 ft=cpp diff --git a/AVR/lib/RF24/tests/pingpair_blocking/printf.h b/AVR/lib/RF24/tests/pingpair_blocking/printf.h deleted file mode 100644 index b2efd56..0000000 --- a/AVR/lib/RF24/tests/pingpair_blocking/printf.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -#ifdef ARDUINO - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#else -#error This example is only for use on Arduino. -#endif // ARDUINO - -#endif // __PRINTF_H__ diff --git a/AVR/lib/RF24/tests/pingpair_blocking/runtest.py b/AVR/lib/RF24/tests/pingpair_blocking/runtest.py deleted file mode 100644 index 0772f95..0000000 --- a/AVR/lib/RF24/tests/pingpair_blocking/runtest.py +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/python - -import sys,serial - -def read_until(token): - while 1: - line = ser.readline(None) - sys.stdout.write(line) - - if (line.startswith(token)): - break - return line - - -ser = serial.Serial(sys.argv[1], 57600, timeout=5, dsrdtr=False, rtscts=False) - -read_until("+READY") -ser.write(sys.argv[2]) - -line = read_until("+OK") -ser.close() -if (line.find("PASS") != -1): - sys.exit(0) -else: - sys.exit(1) diff --git a/AVR/lib/RF24/tests/pingpair_blocking/runtests.sh b/AVR/lib/RF24/tests/pingpair_blocking/runtests.sh deleted file mode 100644 index e106448..0000000 --- a/AVR/lib/RF24/tests/pingpair_blocking/runtests.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/sh - -# Connect u0 to receiver, u1 to sender - -jam u0 u1 && expect test.ex diff --git a/AVR/lib/RF24/tests/pingpair_blocking/test.ex b/AVR/lib/RF24/tests/pingpair_blocking/test.ex deleted file mode 100644 index ea992ad..0000000 --- a/AVR/lib/RF24/tests/pingpair_blocking/test.ex +++ /dev/null @@ -1,11 +0,0 @@ -#/usr/bin/expect - -set timeout 100 -spawn picocom -b 57600 /dev/ttyUSB0 -expect "+READY" -send "1" -expect "+OK" -spawn picocom -b 57600 /dev/ttyUSB1 -expect "+READY" -send "1" -expect "+OK" diff --git a/AVR/lib/RF24/tests/pingpair_test/Jamfile b/AVR/lib/RF24/tests/pingpair_test/Jamfile deleted file mode 100644 index 18244ec..0000000 --- a/AVR/lib/RF24/tests/pingpair_test/Jamfile +++ /dev/null @@ -1,219 +0,0 @@ -# (1) Project Information - -PROJECT_LIBS = SPI RF24 ; -PROJECT_DIRS = $(PWD) ; - -# (2) Board Information - -UPLOAD_PROTOCOL ?= arduino ; -UPLOAD_SPEED ?= 115200 ; -MCU ?= atmega328p ; -F_CPU ?= 16000000 ; -CORE ?= arduino ; -VARIANT ?= standard ; -ARDUINO_VERSION ?= 100 ; - -# (3) USB Ports - -PORTS = p4 p6 p9 u0 u1 u2 ; -PORT_p6 = /dev/tty.usbserial-A600eHIs ; -PORT_p4 = /dev/tty.usbserial-A40081RP ; -PORT_p9 = /dev/tty.usbserial-A9007LmI ; -PORT_u0 = /dev/ttyUSB0 ; -PORT_u1 = /dev/ttyUSB1 ; -PORT_u2 = /dev/ttyUSB2 ; - -# (4) Location of AVR tools -# -# This configuration assumes using avr-tools that were obtained separate from the Arduino -# distribution. - -if $(OS) = MACOSX -{ - AVR_BIN ?= /usr/local/avrtools/bin ; - AVR_ETC = /usr/local/avrtools/etc ; - AVR_INCLUDE = /usr/local/avrtools/include ; -} -else -{ - AVR_BIN ?= /usr/bin ; - AVR_INCLUDE = /usr/lib/avr/include ; - AVR_ETC = /etc ; -} - -# (5) Directories where Arduino core and libraries are located - -ARDUINO_DIR ?= /opt/Arduino ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/$(CORE) $(ARDUINO_DIR)/hardware/arduino/variants/$(VARIANT) ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; - -# -# -------------------------------------------------- -# Below this line usually never needs to be modified -# - -# Tool locations - -CC = $(AVR_BIN)/avr-gcc ; -C++ = $(AVR_BIN)/avr-g++ ; -LINK = $(AVR_BIN)/avr-gcc ; -AR = $(AVR_BIN)/avr-ar rcs ; -RANLIB = ; -OBJCOPY = $(AVR_BIN)/avr-objcopy ; -AVRDUDE ?= $(AVR_BIN)/avrdude ; - -# Flags - -DEFINES += F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -OPTIM = -Os ; -CCFLAGS = -Wall -Wextra -Wno-strict-aliasing -mmcu=$(MCU) -ffunction-sections -fdata-sections ; -C++FLAGS = $(CCFLAGS) -fno-exceptions -fno-strict-aliasing ; -LINKFLAGS = $(OPTIM) -lm -Wl,--gc-sections -mmcu=$(MCU) ; -AVRDUDEFLAGS = -V -F -D -C $(AVR_ETC)/avrdude.conf -p $(MCU) -c $(UPLOAD_PROTOCOL) -b $(UPLOAD_SPEED) ; - -# Search everywhere for headers - -HDRS = $(PROJECT_DIRS) $(AVR_INCLUDE) $(ARDUINO_CORE) $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) ; - -# Output locations - -LOCATE_TARGET = $(F_CPU) ; -LOCATE_SOURCE = $(F_CPU) ; - -# -# Custom rules -# - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule Pde -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_SOURCE) ; - Clean clean : $(<) ; -} - -if ( $(ARDUINO_VERSION) < 100 ) -{ - ARDUINO_H = WProgram.h ; -} -else -{ - ARDUINO_H = Arduino.h ; -} - -actions Pde -{ - echo "#include <$(ARDUINO_H)>" > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule C++Pde -{ - local _CPP = $(>:B).cpp ; - Pde $(_CPP) : $(>) ; - C++ $(<) : $(_CPP) ; -} - -rule UserObject -{ - switch $(>:S) - { - case .ino : C++Pde $(<) : $(>) ; - case .pde : C++Pde $(<) : $(>) ; - } -} - -rule Objects -{ - local _i ; - - for _i in [ FGristFiles $(<) ] - { - local _b = $(_i:B)$(SUFOBJ) ; - local _o = $(_b:G=$(SOURCE_GRIST:E)) ; - Object $(_o) : $(_i) ; - Depends obj : $(_o) ; - } -} - -rule Library -{ - LibraryFromObjects $(<) : $(>:B)$(SUFOBJ) ; - Objects $(>) ; -} - -rule Main -{ - MainFromObjects $(<) : $(>:B)$(SUFOBJ) ; - Objects $(>) ; -} - -rule Hex -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_TARGET) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions Hex -{ - $(OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule Upload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - UploadAction $(2) : $(3) ; -} - -actions UploadAction -{ - $(AVRDUDE) $(AVRDUDEFLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -rule Arduino -{ - LINKFLAGS on $(<) = $(LINKFLAGS) -Wl,-Map=$(LOCATE_TARGET)/$(<:B).map ; - Main $(<) : $(>) ; - LinkLibraries $(<) : core libs ; - Hex $(<:B).hex : $(<) ; - for _p in $(PORTS) - { - Upload $(_p) : $(PORT_$(_p)) : $(<:B).hex ; - } -} - -# -# Targets -# - -# Grab everything from the core directory -Library core : [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -Library libs : [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp *.c ] ; - -# Main output executable -Arduino $(PWD:B).elf : $(PROJECT_MODULES) [ GLOB $(PROJECT_DIRS) : *.c *.cpp *.pde *.ino ] ; diff --git a/AVR/lib/RF24/tests/pingpair_test/pingpair_test.pde b/AVR/lib/RF24/tests/pingpair_test/pingpair_test.pde deleted file mode 100644 index 6acbf51..0000000 --- a/AVR/lib/RF24/tests/pingpair_test/pingpair_test.pde +++ /dev/null @@ -1,435 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * Full test on single RF pair - * - * This sketches uses as many RF24 methods as possible in a single test. - * - * To operate: - * Upload this sketch on two nodes, each with IRQ -> pin 2 - * One node needs pin 7 -> GND, the other NC. That's the receiving node - * Monitor the sending node's serial output - * Look for "+OK PASS" or "+OK FAIL" - */ - -#include -#include "nRF24L01.h" -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 8 & 9 - -RF24 radio(8,9); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const short role_pin = 7; - -// -// Topology -// - -// Single radio pipe address for the 2 nodes to communicate. -const uint64_t pipe = 0xE8E8F0F0E1LL; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes in this -// system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_sender = 1, role_receiver } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Sender", "Receiver"}; - -// The role of the current running sketch -role_e role; - -// Interrupt handler, check the radio because we got an IRQ -void check_radio(void); - -// -// Payload -// - -const int min_payload_size = 4; -const int max_payload_size = 32; -int payload_size_increments_by = 2; -int next_payload_size = min_payload_size; - -char receive_payload[max_payload_size+1]; // +1 to allow room for a terminating NULL char - -// -// Test state -// - -bool done; //*< Are we done with the test? */ -bool passed; //*< Have we passed the test? */ -bool notified; //*< Have we notified the user we're done? */ -const int num_needed = 10; //*< How many success/failures until we're done? */ -int receives_remaining = num_needed; //*< How many ack packets until we declare victory? */ -int failures_remaining = num_needed; //*< How many more failed sends until we declare failure? */ -const int interval = 100; //*< ms to wait between sends */ - -char configuration = '1'; //*< Configuration key, one char sent in by the test framework to tell us how to configure, this is the default */ - -uint8_t pipe_number = 1; // Which pipe to send on. - -void one_ok(void) -{ - // Have we received enough yet? - if ( ! --receives_remaining ) - { - done = true; - passed = true; - } -} - -void one_failed(void) -{ - // Have we failed enough yet? - if ( ! --failures_remaining ) - { - done = true; - passed = false; - } -} - -// -// Setup -// - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_sender; - else - role = role_receiver; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/tests/pingpair_test/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // Read configuration from serial - // - // It would be a much better test if this program could accept configuration - // from the serial port. Then it would be possible to run the same test under - // lots of different circumstances. - // - // The idea is that we will print "+READY" at this point. The python script - // will wait for it, and then send down a configuration script that we - // execute here and then run with. - // - // The test controller will need to configure the receiver first, then go run - // the test on the sender. - // - - printf("+READY press any key to start\n\r\n\r"); - - while (! Serial.available() ) {} - configuration = Serial.read(); - printf("Configuration\t = %c\n\r",configuration); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // We will be using the Ack Payload feature, so please enable it - radio.enableAckPayload(); - - // Config 2 is special radio config - if (configuration=='2') - { - radio.setCRCLength(RF24_CRC_8); - radio.setDataRate(RF24_250KBPS); - radio.setChannel(10); - } - else - { - //Otherwise, default radio config - - // Optional: Increase CRC length for improved reliability - radio.setCRCLength(RF24_CRC_16); - - // Optional: Decrease data rate for improved reliability - radio.setDataRate(RF24_1MBPS); - - // Optional: Pick a high channel - radio.setChannel(90); - } - - // Config 3 is static payloads only - if (configuration == '3') - { - next_payload_size = 16; - payload_size_increments_by = 0; - radio.setPayloadSize(next_payload_size); - } - else - { - // enable dynamic payloads - radio.enableDynamicPayloads(); - } - - // Config 4 tests out a higher pipe ## - if (configuration == '4' && role == role_sender) - { - // Set top 4 bytes of the address in pipe 1 - radio.openReadingPipe(1,pipe & 0xFFFFFFFF00ULL); - - // indicate the pipe to use - pipe_number = 5; - } - else if ( role == role_sender ) - { - radio.openReadingPipe(5,0); - } - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens a single pipe for these two nodes to communicate - // back and forth. One listens on it, the other talks to it. - - if ( role == role_sender ) - { - radio.openWritingPipe(pipe); - } - else - { - radio.openReadingPipe(pipe_number,pipe); - } - - // - // Start listening - // - - if ( role == role_receiver ) - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); - - // - // Attach interrupt handler to interrupt #0 (using pin 2) - // on BOTH the sender and receiver - // - - attachInterrupt(0, check_radio, FALLING); - - if ( role == role_receiver ) - printf("\n\r+OK "); -} - -// -// Print buffer -// -// Printing from the interrupt handler is a bad idea, so we print from there -// to this intermediate buffer -// - -char prbuf[1000]; -char *prbuf_end = prbuf + sizeof(prbuf); -char *prbuf_in = prbuf; -char *prbuf_out = prbuf; - -// -// Loop -// - -static uint32_t message_count = 0; -static uint32_t last_message_count = 0; - -void loop(void) -{ - // - // Sender role. Repeatedly send the current time - // - - if (role == role_sender && !done) - { - // The payload will always be the same, what will change is how much of it we send. - static char send_payload[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ789012"; - - // First, stop listening so we can talk. - radio.stopListening(); - - // Send it. This will block until complete - printf("\n\rNow sending length %i...",next_payload_size); - radio.startWrite( send_payload, next_payload_size ); - - // Update size for next time. - next_payload_size += payload_size_increments_by; - if ( next_payload_size > max_payload_size ) - next_payload_size = min_payload_size; - - // Try again soon - delay(interval); - - // Timeout if we have not received anything back ever - if ( ! last_message_count && millis() > interval * 100 ) - { - printf("No responses received. Are interrupts connected??\n\r"); - done = true; - } - } - - // - // Receiver role: Does nothing! All the work is in IRQ - // - - // - // Spew print buffer - // - - size_t write_length = prbuf_in - prbuf_out; - if ( write_length ) - { - Serial.write(reinterpret_cast(prbuf_out),write_length); - prbuf_out += write_length; - } - - // - // Stop the test if we're done and report results - // - if ( done && ! notified ) - { - notified = true; - - printf("\n\r+OK "); - if ( passed ) - printf("PASS\n\r\n\r"); - else - printf("FAIL\n\r\n\r"); - } - -} - -void check_radio(void) -{ - // What happened? - bool tx,fail,rx; - radio.whatHappened(tx,fail,rx); - - // Have we successfully transmitted? - if ( tx ) - { - if ( role == role_sender ) - prbuf_in += sprintf(prbuf_in,"Send:OK "); - - if ( role == role_receiver ) - prbuf_in += sprintf(prbuf_in,"Ack Payload:Sent\n\r"); - } - - // Have we failed to transmit? - if ( fail ) - { - if ( role == role_sender ) - { - prbuf_in += sprintf(prbuf_in,"Send:Failed "); - - // log status of this line - one_failed(); - } - - if ( role == role_receiver ) - prbuf_in += sprintf(prbuf_in,"Ack Payload:Failed\n\r"); - } - - // Transmitter can power down for now, because - // the transmission is done. - if ( ( tx || fail ) && ( role == role_sender ) ) - radio.powerDown(); - - // Did we receive a message? - if ( rx ) - { - // If we're the sender, we've received an ack payload - if ( role == role_sender ) - { - radio.read(&message_count,sizeof(message_count)); - prbuf_in += sprintf(prbuf_in,"Ack:%lu ",message_count); - - // is this ack what we were expecting? to account - // for failures, we simply want to make sure we get a - // DIFFERENT ack every time. - if ( ( message_count != last_message_count ) || ( configuration=='3' && message_count == 16 ) ) - { - prbuf_in += sprintf(prbuf_in,"OK "); - one_ok(); - } - else - { - prbuf_in += sprintf(prbuf_in,"FAILED "); - one_failed(); - } - last_message_count = message_count; - } - - // If we're the receiver, we've received a time message - if ( role == role_receiver ) - { - // Get this payload and dump it - size_t len = max_payload_size; - memset(receive_payload,0,max_payload_size); - - if ( configuration == '3' ) - len = next_payload_size; - else - len = radio.getDynamicPayloadSize(); - - radio.read( receive_payload, len ); - - // Put a zero at the end for easy printing - receive_payload[len] = 0; - - // Spew it - prbuf_in += sprintf(prbuf_in,"Recv size=%i val=%s len=%u\n\r",len,receive_payload,strlen(receive_payload)); - - // Add an ack packet for the next time around. - // Here we will report back how many bytes we got this time. - radio.writeAckPayload( pipe_number, &len, sizeof(len) ); - ++message_count; - } - } -} - -// vim:ai:cin:sts=2 sw=2 ft=cpp diff --git a/AVR/lib/RF24/tests/pingpair_test/printf.h b/AVR/lib/RF24/tests/pingpair_test/printf.h deleted file mode 100644 index b2efd56..0000000 --- a/AVR/lib/RF24/tests/pingpair_test/printf.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -#ifdef ARDUINO - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#else -#error This example is only for use on Arduino. -#endif // ARDUINO - -#endif // __PRINTF_H__ diff --git a/AVR/lib/RF24/tests/pingpair_test/runtest.py b/AVR/lib/RF24/tests/pingpair_test/runtest.py deleted file mode 100644 index 45fb65c..0000000 --- a/AVR/lib/RF24/tests/pingpair_test/runtest.py +++ /dev/null @@ -1,25 +0,0 @@ -#!/opt/local/bin/python - -import sys,serial - -def read_until(token): - while 1: - line = ser.readline(None,"\r") - sys.stdout.write(line) - - if (line.startswith(token)): - break - return line - - -ser = serial.Serial(sys.argv[1], 57600, timeout=5, dsrdtr=False, rtscts=False) - -read_until("+READY") -ser.write(sys.argv[2]) - -line = read_until("+OK") -ser.close() -if (line.find("PASS") != -1): - sys.exit(0) -else: - sys.exit(1) diff --git a/AVR/lib/RF24/tests/pingpair_test/runtests.sh b/AVR/lib/RF24/tests/pingpair_test/runtests.sh deleted file mode 100644 index 4d02310..0000000 --- a/AVR/lib/RF24/tests/pingpair_test/runtests.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/sh - -# Connect u0 to receiver, u0 to sender -# WARNING: Test config 2 only works with PLUS units. - -jam u0 u1 && expect test.ex 1 -sleep 1 -stty 57600 raw ignbrk hup < /dev/ttyUSB0 -sleep 1 -stty 57600 raw ignbrk hup < /dev/ttyUSB1 -expect test.ex 2 -sleep 1 -stty 57600 raw ignbrk hup < /dev/ttyUSB0 -sleep 1 -stty 57600 raw ignbrk hup < /dev/ttyUSB1 -expect test.ex 3 -sleep 1 -stty 57600 raw ignbrk hup < /dev/ttyUSB0 -sleep 1 -stty 57600 raw ignbrk hup < /dev/ttyUSB1 -expect test.ex 4 diff --git a/AVR/lib/RF24/tests/pingpair_test/test.ex b/AVR/lib/RF24/tests/pingpair_test/test.ex deleted file mode 100644 index a14ffef..0000000 --- a/AVR/lib/RF24/tests/pingpair_test/test.ex +++ /dev/null @@ -1,11 +0,0 @@ -#/usr/bin/expect - -set timeout 100 -spawn picocom -b 57600 /dev/ttyUSB0 -expect "+READY" -send [lindex $argv 0] -expect "+OK" -spawn picocom -b 57600 /dev/ttyUSB1 -expect "+READY" -send [lindex $argv 0] -expect "+OK" diff --git a/AVR/lib/RF24/uart.c b/AVR/lib/RF24/uart.c deleted file mode 100644 index 3bf2b42..0000000 --- a/AVR/lib/RF24/uart.c +++ /dev/null @@ -1,651 +0,0 @@ -/************************************************************************* -Title: Interrupt UART library with receive/transmit circular buffers -Author: Peter Fleury http://jump.to/fleury -File: $Id: uart.c,v 1.6.2.2 2009/11/29 08:56:12 Peter Exp $ -Software: AVR-GCC 4.1, AVR Libc 1.4.6 or higher -Hardware: any AVR with built-in UART, -License: GNU General Public License - -DESCRIPTION: - An interrupt is generated when the UART has finished transmitting or - receiving a byte. The interrupt handling routines use circular buffers - for buffering received and transmitted data. - - The UART_RX_BUFFER_SIZE and UART_TX_BUFFER_SIZE variables define - the buffer size in bytes. Note that these variables must be a - power of 2. - -USAGE: - Refere to the header file uart.h for a description of the routines. - See also example test_uart.c. - -NOTES: - Based on Atmel Application Note AVR306 - -LICENSE: - Copyright (C) 2006 Peter Fleury - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - 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. - -*************************************************************************/ -#include -#include -#include -#include "uart.h" - - -/* - * constants and macros - */ - -/* size of RX/TX buffers */ -#define UART_RX_BUFFER_MASK ( UART_RX_BUFFER_SIZE - 1) -#define UART_TX_BUFFER_MASK ( UART_TX_BUFFER_SIZE - 1) - -#if ( UART_RX_BUFFER_SIZE & UART_RX_BUFFER_MASK ) -#error RX buffer size is not a power of 2 -#endif -#if ( UART_TX_BUFFER_SIZE & UART_TX_BUFFER_MASK ) -#error TX buffer size is not a power of 2 -#endif - -#if defined(__AVR_AT90S2313__) \ - || defined(__AVR_AT90S4414__) || defined(__AVR_AT90S4434__) \ - || defined(__AVR_AT90S8515__) || defined(__AVR_AT90S8535__) \ - || defined(__AVR_ATmega103__) - /* old AVR classic or ATmega103 with one UART */ - #define AT90_UART - #define UART0_RECEIVE_INTERRUPT SIG_UART_RECV - #define UART0_TRANSMIT_INTERRUPT SIG_UART_DATA - #define UART0_STATUS USR - #define UART0_CONTROL UCR - #define UART0_DATA UDR - #define UART0_UDRIE UDRIE -#elif defined(__AVR_AT90S2333__) || defined(__AVR_AT90S4433__) - /* old AVR classic with one UART */ - #define AT90_UART - #define UART0_RECEIVE_INTERRUPT SIG_UART_RECV - #define UART0_TRANSMIT_INTERRUPT SIG_UART_DATA - #define UART0_STATUS UCSRA - #define UART0_CONTROL UCSRB - #define UART0_DATA UDR - #define UART0_UDRIE UDRIE -#elif defined(__AVR_ATmega8__) || defined(__AVR_ATmega16__) || defined(__AVR_ATmega32__) \ - || defined(__AVR_ATmega8515__) || defined(__AVR_ATmega8535__) \ - || defined(__AVR_ATmega323__) - /* ATmega with one USART */ - #define ATMEGA_USART - #define UART0_RECEIVE_INTERRUPT SIG_UART_RECV - #define UART0_TRANSMIT_INTERRUPT SIG_UART_DATA - #define UART0_STATUS UCSRA - #define UART0_CONTROL UCSRB - #define UART0_DATA UDR - #define UART0_UDRIE UDRIE -#elif defined(__AVR_ATmega163__) - /* ATmega163 with one UART */ - #define ATMEGA_UART - #define UART0_RECEIVE_INTERRUPT SIG_UART_RECV - #define UART0_TRANSMIT_INTERRUPT SIG_UART_DATA - #define UART0_STATUS UCSRA - #define UART0_CONTROL UCSRB - #define UART0_DATA UDR - #define UART0_UDRIE UDRIE -#elif defined(__AVR_ATmega162__) - /* ATmega with two USART */ - #define ATMEGA_USART0 - #define ATMEGA_USART1 - #define UART0_RECEIVE_INTERRUPT SIG_USART0_RECV - #define UART1_RECEIVE_INTERRUPT SIG_USART1_RECV - #define UART0_TRANSMIT_INTERRUPT SIG_USART0_DATA - #define UART1_TRANSMIT_INTERRUPT SIG_USART1_DATA - #define UART0_STATUS UCSR0A - #define UART0_CONTROL UCSR0B - #define UART0_DATA UDR0 - #define UART0_UDRIE UDRIE0 - #define UART1_STATUS UCSR1A - #define UART1_CONTROL UCSR1B - #define UART1_DATA UDR1 - #define UART1_UDRIE UDRIE1 -#elif defined(__AVR_ATmega64__) || defined(__AVR_ATmega128__) - /* ATmega with two USART */ - #define ATMEGA_USART0 - #define ATMEGA_USART1 - #define UART0_RECEIVE_INTERRUPT SIG_UART0_RECV - #define UART1_RECEIVE_INTERRUPT SIG_UART1_RECV - #define UART0_TRANSMIT_INTERRUPT SIG_UART0_DATA - #define UART1_TRANSMIT_INTERRUPT SIG_UART1_DATA - #define UART0_STATUS UCSR0A - #define UART0_CONTROL UCSR0B - #define UART0_DATA UDR0 - #define UART0_UDRIE UDRIE0 - #define UART1_STATUS UCSR1A - #define UART1_CONTROL UCSR1B - #define UART1_DATA UDR1 - #define UART1_UDRIE UDRIE1 -#elif defined(__AVR_ATmega161__) - /* ATmega with UART */ - #error "AVR ATmega161 currently not supported by this libaray !" -#elif defined(__AVR_ATmega169__) - /* ATmega with one USART */ - #define ATMEGA_USART - #define UART0_RECEIVE_INTERRUPT SIG_USART_RECV - #define UART0_TRANSMIT_INTERRUPT SIG_USART_DATA - #define UART0_STATUS UCSRA - #define UART0_CONTROL UCSRB - #define UART0_DATA UDR - #define UART0_UDRIE UDRIE -#elif defined(__AVR_ATmega48__) ||defined(__AVR_ATmega88__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega48P__) || defined(__AVR_ATmega88P__) || defined(__AVR_ATmega168P__) || defined(__AVR_ATmega328P__) - /* ATmega with one USART */ - #define ATMEGA_USART0 - #define UART0_RECEIVE_INTERRUPT USART_RX_vect - #define UART0_TRANSMIT_INTERRUPT USART_TX_vect - #define UART0_STATUS UCSR0A - #define UART0_CONTROL UCSR0B - #define UART0_DATA UDR0 - #define UART0_UDRIE UDRIE0 -#elif defined(__AVR_ATtiny2313__) - #define ATMEGA_USART - #define UART0_RECEIVE_INTERRUPT SIG_USART0_RX - #define UART0_TRANSMIT_INTERRUPT SIG_USART0_UDRE - #define UART0_STATUS UCSRA - #define UART0_CONTROL UCSRB - #define UART0_DATA UDR - #define UART0_UDRIE UDRIE -#elif defined(__AVR_ATmega329__) ||defined(__AVR_ATmega3290__) ||\ - defined(__AVR_ATmega649__) ||defined(__AVR_ATmega6490__) ||\ - defined(__AVR_ATmega325__) ||defined(__AVR_ATmega3250__) ||\ - defined(__AVR_ATmega645__) ||defined(__AVR_ATmega6450__) - /* ATmega with one USART */ - #define ATMEGA_USART0 - #define UART0_RECEIVE_INTERRUPT SIG_UART_RECV - #define UART0_TRANSMIT_INTERRUPT SIG_UART_DATA - #define UART0_STATUS UCSR0A - #define UART0_CONTROL UCSR0B - #define UART0_DATA UDR0 - #define UART0_UDRIE UDRIE0 -#elif defined(__AVR_ATmega2560__) || defined(__AVR_ATmega2561__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega1281__) || defined(__AVR_ATmega640__) -/* ATmega with two USART */ - #define ATMEGA_USART0 - #define ATMEGA_USART1 - #define UART0_RECEIVE_INTERRUPT SIG_USART0_RECV - #define UART1_RECEIVE_INTERRUPT SIG_USART1_RECV - #define UART0_TRANSMIT_INTERRUPT SIG_USART0_DATA - #define UART1_TRANSMIT_INTERRUPT SIG_USART1_DATA - #define UART0_STATUS UCSR0A - #define UART0_CONTROL UCSR0B - #define UART0_DATA UDR0 - #define UART0_UDRIE UDRIE0 - #define UART1_STATUS UCSR1A - #define UART1_CONTROL UCSR1B - #define UART1_DATA UDR1 - #define UART1_UDRIE UDRIE1 -#elif defined(__AVR_ATmega644__) - /* ATmega with one USART */ - #define ATMEGA_USART0 - #define UART0_RECEIVE_INTERRUPT SIG_USART_RECV - #define UART0_TRANSMIT_INTERRUPT SIG_USART_DATA - #define UART0_STATUS UCSR0A - #define UART0_CONTROL UCSR0B - #define UART0_DATA UDR0 - #define UART0_UDRIE UDRIE0 -#elif defined(__AVR_ATmega164P__) || defined(__AVR_ATmega324P__) || defined(__AVR_ATmega644P__) - /* ATmega with two USART */ - #define ATMEGA_USART0 - #define ATMEGA_USART1 - #define UART0_RECEIVE_INTERRUPT SIG_USART_RECV - #define UART1_RECEIVE_INTERRUPT SIG_USART1_RECV - #define UART0_TRANSMIT_INTERRUPT SIG_USART_DATA - #define UART1_TRANSMIT_INTERRUPT SIG_USART1_DATA - #define UART0_STATUS UCSR0A - #define UART0_CONTROL UCSR0B - #define UART0_DATA UDR0 - #define UART0_UDRIE UDRIE0 - #define UART1_STATUS UCSR1A - #define UART1_CONTROL UCSR1B - #define UART1_DATA UDR1 - #define UART1_UDRIE UDRIE1 -#else - #error "no UART definition for MCU available" -#endif - - -/* - * module global variables - */ -static volatile unsigned char UART_TxBuf[UART_TX_BUFFER_SIZE]; -static volatile unsigned char UART_RxBuf[UART_RX_BUFFER_SIZE]; -static volatile unsigned char UART_TxHead; -static volatile unsigned char UART_TxTail; -static volatile unsigned char UART_RxHead; -static volatile unsigned char UART_RxTail; -static volatile unsigned char UART_LastRxError; - -#if defined( ATMEGA_USART1 ) -static volatile unsigned char UART1_TxBuf[UART_TX_BUFFER_SIZE]; -static volatile unsigned char UART1_RxBuf[UART_RX_BUFFER_SIZE]; -static volatile unsigned char UART1_TxHead; -static volatile unsigned char UART1_TxTail; -static volatile unsigned char UART1_RxHead; -static volatile unsigned char UART1_RxTail; -static volatile unsigned char UART1_LastRxError; -#endif - - - -ISR(UART0_RECEIVE_INTERRUPT) -/************************************************************************* -Function: UART Receive Complete interrupt -Purpose: called when the UART has received a character -**************************************************************************/ -{ - unsigned char tmphead; - unsigned char data; - unsigned char usr; - unsigned char lastRxError; - - - /* read UART status register and UART data register */ - usr = UART0_STATUS; - data = UART0_DATA; - - /* */ -#if defined( AT90_UART ) - lastRxError = (usr & (_BV(FE)|_BV(DOR)) ); -#elif defined( ATMEGA_USART ) - lastRxError = (usr & (_BV(FE)|_BV(DOR)) ); -#elif defined( ATMEGA_USART0 ) - lastRxError = (usr & (_BV(FE0)|_BV(DOR0)) ); -#elif defined ( ATMEGA_UART ) - lastRxError = (usr & (_BV(FE)|_BV(DOR)) ); -#endif - - /* calculate buffer index */ - tmphead = ( UART_RxHead + 1) & UART_RX_BUFFER_MASK; - - if ( tmphead == UART_RxTail ) { - /* error: receive buffer overflow */ - lastRxError = UART_BUFFER_OVERFLOW >> 8; - }else{ - /* store new index */ - UART_RxHead = tmphead; - /* store received data in buffer */ - UART_RxBuf[tmphead] = data; - } - UART_LastRxError = lastRxError; -} - - -ISR(UART0_TRANSMIT_INTERRUPT) -/************************************************************************* -Function: UART Data Register Empty interrupt -Purpose: called when the UART is ready to transmit the next byte -**************************************************************************/ -{ - unsigned char tmptail; - - - if ( UART_TxHead != UART_TxTail) { - /* calculate and store new buffer index */ - tmptail = (UART_TxTail + 1) & UART_TX_BUFFER_MASK; - UART_TxTail = tmptail; - /* get one byte from buffer and write it to UART */ - UART0_DATA = UART_TxBuf[tmptail]; /* start transmission */ - }else{ - /* tx buffer empty, disable UDRE interrupt */ - UART0_CONTROL &= ~_BV(UART0_UDRIE); - } -} - - -/************************************************************************* -Function: uart_init() -Purpose: initialize UART and set baudrate -Input: baudrate using macro UART_BAUD_SELECT() -Returns: none -**************************************************************************/ -void uart_init(unsigned int baudrate) -{ - UART_TxHead = 0; - UART_TxTail = 0; - UART_RxHead = 0; - UART_RxTail = 0; - -#if defined( AT90_UART ) - /* set baud rate */ - UBRR = (unsigned char)baudrate; - - /* enable UART receiver and transmmitter and receive complete interrupt */ - UART0_CONTROL = _BV(RXCIE)|_BV(RXEN)|_BV(TXEN); - -#elif defined (ATMEGA_USART) - /* Set baud rate */ - if ( baudrate & 0x8000 ) - { - UART0_STATUS = (1<>8); - UBRRL = (unsigned char) baudrate; - - /* Enable USART receiver and transmitter and receive complete interrupt */ - UART0_CONTROL = _BV(RXCIE)|(1<>8); - UBRR0L = (unsigned char) baudrate; - - /* Enable USART receiver and transmitter and receive complete interrupt */ - UART0_CONTROL = _BV(RXCIE0)|(1<>8); - UBRR = (unsigned char) baudrate; - - /* Enable UART receiver and transmitter and receive complete interrupt */ - UART0_CONTROL = _BV(RXCIE)|(1<> 8; - }else{ - /* store new index */ - UART1_RxHead = tmphead; - /* store received data in buffer */ - UART1_RxBuf[tmphead] = data; - } - UART1_LastRxError = lastRxError; -} - - -ISR(UART1_TRANSMIT_INTERRUPT) -/************************************************************************* -Function: UART1 Data Register Empty interrupt -Purpose: called when the UART1 is ready to transmit the next byte -**************************************************************************/ -{ - unsigned char tmptail; - - - if ( UART1_TxHead != UART1_TxTail) { - /* calculate and store new buffer index */ - tmptail = (UART1_TxTail + 1) & UART_TX_BUFFER_MASK; - UART1_TxTail = tmptail; - /* get one byte from buffer and write it to UART */ - UART1_DATA = UART1_TxBuf[tmptail]; /* start transmission */ - }else{ - /* tx buffer empty, disable UDRE interrupt */ - UART1_CONTROL &= ~_BV(UART1_UDRIE); - } -} - - -/************************************************************************* -Function: uart1_init() -Purpose: initialize UART1 and set baudrate -Input: baudrate using macro UART_BAUD_SELECT() -Returns: none -**************************************************************************/ -void uart1_init(unsigned int baudrate) -{ - UART1_TxHead = 0; - UART1_TxTail = 0; - UART1_RxHead = 0; - UART1_RxTail = 0; - - - /* Set baud rate */ - if ( baudrate & 0x8000 ) - { - UART1_STATUS = (1<>8); - UBRR1L = (unsigned char) baudrate; - - /* Enable USART receiver and transmitter and receive complete interrupt */ - UART1_CONTROL = _BV(RXCIE1)|(1< http://jump.to/fleury -File: $Id: uart.h,v 1.8.2.1 2007/07/01 11:14:38 peter Exp $ -Software: AVR-GCC 4.1, AVR Libc 1.4 -Hardware: any AVR with built-in UART, tested on AT90S8515 & ATmega8 at 4 Mhz -License: GNU General Public License -Usage: see Doxygen manual - -LICENSE: - Copyright (C) 2006 Peter Fleury - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - 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. - -************************************************************************/ - -/** - * @defgroup pfleury_uart UART Library - * @code #include @endcode - * - * @brief Interrupt UART library using the built-in UART with transmit and receive circular buffers. - * - * This library can be used to transmit and receive data through the built in UART. - * - * An interrupt is generated when the UART has finished transmitting or - * receiving a byte. The interrupt handling routines use circular buffers - * for buffering received and transmitted data. - * - * The UART_RX_BUFFER_SIZE and UART_TX_BUFFER_SIZE constants define - * the size of the circular buffers in bytes. Note that these constants must be a power of 2. - * You may need to adapt this constants to your target and your application by adding - * CDEFS += -DUART_RX_BUFFER_SIZE=nn -DUART_RX_BUFFER_SIZE=nn to your Makefile. - * - * @note Based on Atmel Application Note AVR306 - * @author Peter Fleury pfleury@gmx.ch http://jump.to/fleury - */ - -/**@{*/ - - -#if (__GNUC__ * 100 + __GNUC_MINOR__) < 304 -#error "This library requires AVR-GCC 3.4 or later, update to newer AVR-GCC compiler !" -#endif - - -/* -** constants and macros -*/ - -/** @brief UART Baudrate Expression - * @param xtalcpu system clock in Mhz, e.g. 4000000L for 4Mhz - * @param baudrate baudrate in bps, e.g. 1200, 2400, 9600 - */ -#define UART_BAUD_SELECT(baudRate,xtalCpu) ((xtalCpu)/((baudRate)*16l)-1) - -/** @brief UART Baudrate Expression for ATmega double speed mode - * @param xtalcpu system clock in Mhz, e.g. 4000000L for 4Mhz - * @param baudrate baudrate in bps, e.g. 1200, 2400, 9600 - */ -#define UART_BAUD_SELECT_DOUBLE_SPEED(baudRate,xtalCpu) (((xtalCpu)/((baudRate)*8l)-1)|0x8000) - - -/** Size of the circular receive buffer, must be power of 2 */ -#ifndef UART_RX_BUFFER_SIZE -#define UART_RX_BUFFER_SIZE 32 -#endif -/** Size of the circular transmit buffer, must be power of 2 */ -#ifndef UART_TX_BUFFER_SIZE -#define UART_TX_BUFFER_SIZE 32 -#endif - -/* test if the size of the circular buffers fits into SRAM */ -#if ( (UART_RX_BUFFER_SIZE+UART_TX_BUFFER_SIZE) >= (RAMEND-0x60 ) ) -#error "size of UART_RX_BUFFER_SIZE + UART_TX_BUFFER_SIZE larger than size of SRAM" -#endif - -/* -** high byte error return code of uart_getc() -*/ -#define UART_FRAME_ERROR 0x0800 /* Framing Error by UART */ -#define UART_OVERRUN_ERROR 0x0400 /* Overrun condition by UART */ -#define UART_BUFFER_OVERFLOW 0x0200 /* receive ringbuffer overflow */ -#define UART_NO_DATA 0x0100 /* no receive data available */ - - -/* -** function prototypes -*/ - -/** - @brief Initialize UART and set baudrate - @param baudrate Specify baudrate using macro UART_BAUD_SELECT() - @return none -*/ -extern void uart_init(unsigned int baudrate); - - -/** - * @brief Get received byte from ringbuffer - * - * Returns in the lower byte the received character and in the - * higher byte the last receive error. - * UART_NO_DATA is returned when no data is available. - * - * @param void - * @return lower byte: received byte from ringbuffer - * @return higher byte: last receive status - * - \b 0 successfully received data from UART - * - \b UART_NO_DATA - *
no receive data available - * - \b UART_BUFFER_OVERFLOW - *
Receive ringbuffer overflow. - * We are not reading the receive buffer fast enough, - * one or more received character have been dropped - * - \b UART_OVERRUN_ERROR - *
Overrun condition by UART. - * A character already present in the UART UDR register was - * not read by the interrupt handler before the next character arrived, - * one or more received characters have been dropped. - * - \b UART_FRAME_ERROR - *
Framing Error by UART - */ -extern unsigned int uart_getc(void); - - -/** - * @brief Put byte to ringbuffer for transmitting via UART - * @param data byte to be transmitted - * @return none - */ -extern void uart_putc(unsigned char data); - - -/** - * @brief Put string to ringbuffer for transmitting via UART - * - * The string is buffered by the uart library in a circular buffer - * and one character at a time is transmitted to the UART using interrupts. - * Blocks if it can not write the whole string into the circular buffer. - * - * @param s string to be transmitted - * @return none - */ -extern void uart_puts(const char *s ); - - -/** - * @brief Put string from program memory to ringbuffer for transmitting via UART. - * - * The string is buffered by the uart library in a circular buffer - * and one character at a time is transmitted to the UART using interrupts. - * Blocks if it can not write the whole string into the circular buffer. - * - * @param s program memory string to be transmitted - * @return none - * @see uart_puts_P - */ -extern void uart_puts_p(const char *s ); - -/** - * @brief Macro to automatically put a string constant into program memory - */ -#define uart_puts_P(__s) uart_puts_p(PSTR(__s)) - - - -/** @brief Initialize USART1 (only available on selected ATmegas) @see uart_init */ -extern void uart1_init(unsigned int baudrate); -/** @brief Get received byte of USART1 from ringbuffer. (only available on selected ATmega) @see uart_getc */ -extern unsigned int uart1_getc(void); -/** @brief Put byte to ringbuffer for transmitting via USART1 (only available on selected ATmega) @see uart_putc */ -extern void uart1_putc(unsigned char data); -/** @brief Put string to ringbuffer for transmitting via USART1 (only available on selected ATmega) @see uart_puts */ -extern void uart1_puts(const char *s ); -/** @brief Put string from program memory to ringbuffer for transmitting via USART1 (only available on selected ATmega) @see uart_puts_p */ -extern void uart1_puts_p(const char *s ); -/** @brief Macro to automatically put a string constant into program memory */ -#define uart1_puts_P(__s) uart1_puts_p(PSTR(__s)) - -/**@}*/ - -#include "uart.c" -#endif // UART_H - diff --git a/AVR/lib/RF24/util.c b/AVR/lib/RF24/util.c deleted file mode 100644 index 39bbd1e..0000000 --- a/AVR/lib/RF24/util.c +++ /dev/null @@ -1,62 +0,0 @@ -/* - Copyright (C) 2012 jaseg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - version 3 as published by the Free Software Foundation. - */ - -#include "util.h" -#include "uart.h" - -void uart_puthex_nibble(uint8_t nibble){ - if(nibble < 0xA) - uart_putc('0'+nibble); - else - uart_putc('A'+nibble-0xA); -} - -void uart_puthex(uint8_t data){ - uart_puthex_nibble(data>4); - uart_puthex_nibble(data&0xF); -} - -void uart_puthex_16(uint16_t data){ - uart_puthex(data>>8); - uart_puthex(data&0xFF); -} - -void uart_puthex_flip_16(uint16_t data){ - uart_puthex(data&0xFF); - uart_puthex(data>>8); -} - -void uart_puthex_32(uint32_t data){ - uint16_t high = data>>16; - uart_puthex_16(high); - uint16_t low = data&0xFFFF; - uart_puthex_16(low); -} - -void uart_puthex_flip_32(uint32_t data){ - uint16_t low = data&0xFFFF; - uart_puthex_flip_16(low); - uint16_t high = data>>16; - uart_puthex_flip_16(high); -} - -void uart_putdec(uint8_t data){ - if(data >= 100){ - if(data >= 200){ - uart_putc('2'); - data -= 200; - }else{ - uart_putc('1'); - data -= 100; - } - } - uint8_t d2 = data/10; - data %= 10; - uart_putc('0'+d2); - uart_putc('0'+data); -} diff --git a/AVR/lib/RF24/util.h b/AVR/lib/RF24/util.h deleted file mode 100644 index d54e8a1..0000000 --- a/AVR/lib/RF24/util.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - Copyright (C) 2012 jaseg - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - version 3 as published by the Free Software Foundation. - */ - -#ifndef __UTIL_H__ -#define __UTIL_H__ -#include - -void uart_puthex_nibble(uint8_t nibble); -void uart_puthex(uint8_t data); -void uart_puthex_16(uint16_t data); -void uart_puthex_32(uint32_t data); -void uart_puthex_flip_16(uint16_t data); -void uart_puthex_flip_32(uint32_t data); -void uart_putdec(uint8_t data); -inline uint8_t min(uint8_t a, uint8_t b){ - return a>b?b:a; -} - -#endif//__UTIL_H__ diff --git a/AVR/lib/RF24/wikidoc.xslt b/AVR/lib/RF24/wikidoc.xslt deleted file mode 100644 index b94d3ef..0000000 --- a/AVR/lib/RF24/wikidoc.xslt +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - === === - - - - - '''' - -Parameters: - - - - * '''': - - - - - -Returns: - -* - - -Warning: - - - - <pre> </pre> - - - - - - - diff --git a/AVR/lib/Vera/VeraAVR.c b/AVR/lib/Vera/VeraAVR.c deleted file mode 100644 index 564cf05..0000000 --- a/AVR/lib/Vera/VeraAVR.c +++ /dev/null @@ -1,252 +0,0 @@ -/* - Vera Arduino library is used to communicate sensor data to your Vera receiver sketch using RF24 library. - The maximum amount of transferrable data is 336 characters from a sensor to receiver. - - Created by Henrik Ekblad - Version 1.0 - - 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. - - modification by axillent@gmail.com to run on pure AVR - */ - -#include "VeraAVR.h" -#include -#include -#include - -uint8_t ee_radio_id EEMEM = 255; - -struct { - uint16_t radioId; - uint16_t relayId; - message_s msg; // Buffer for incoming messages. - char convBuffer[20]; -} _veraavr_data; - -/*uint8_t VeraAVR_eeprom_radioid() { - return eeprom_read_byte(&ee_radio_id); -}*/ -/*static void VeraAVR_delay_ms(uint16_t delay) { - for(; delay >= 50; delay -= 50) { - _delay_ms(50); - wdt_reset(); - } - wdt_reset(); -}*/ - -void VeraAVR_begin(uint16_t _radioId) { - VeraAVR_begin2(_radioId, GATEWAY_ADDRESS); -} - -void VeraAVR_begin2(uint16_t _radioId, uint16_t _relayId) { - _veraavr_data.radioId = _radioId; - _veraavr_data.relayId = _relayId; - // Start up the radio library - nrf24_begin(); - nrf24_enableDynamicPayloads(); - nrf24_setAutoAck(1) ; - nrf24_setRetries(15, 15); - nrf24_setChannel(VERA_CHANNEL); - nrf24_setDataRate(RF24_1MBPS); - nrf24_setCRCLength(RF24_CRC_16); - if (_veraavr_data.radioId == GATEWAY_ADDRESS) { - nrf24_openReadingPipe(1, BASE_RADIO_ID); - } else { - if (_veraavr_data.radioId == AUTO) { - _veraavr_data.radioId = eeprom_read_byte(&ee_radio_id); - if (_veraavr_data.radioId == 0xFFF || _veraavr_data.radioId == 0x00) { - // No radio id has been fetched yet. EEPROM is unwritten. - // Request new id from Vera. Use radio address 255 temporarily. - //nrf24_openReadingPipe(0,0); // Don't listen to other nodes - nrf24_openReadingPipe(1, BASE_RADIO_ID+_veraavr_data.radioId); - nrf24_openWritingPipe(BASE_RADIO_ID); - _veraavr_data.radioId = atoi(VeraAVR_getConfiguration(V_REQUEST_ID)); - // Write id to EEPROM - if (_veraavr_data.radioId == AUTO) { // Vera will return 255 if all sensor id are taken - // wait a minute before possible wdt reset - for(uint8_t i=0; i < 120; i++) { - wdt_reset(); - _delay_ms(500); - } - // wait for a while ot until wdt reset - while (1) {} - } else { - eeprom_write_byte(&ee_radio_id, _veraavr_data.radioId); - } - } - } - //eeprom_write_byte(&ee_radio_id, _veraavr_data.radioId); - nrf24_openReadingPipe(1, BASE_RADIO_ID+_veraavr_data.radioId); - } - nrf24_startListening(); - wdt_reset(); -} - -uint8_t VeraAVR_sendDataGW(uint8_t childId, messageType messageType, uint8_t type, const char *data) { - return VeraAVR_sendData(_veraavr_data.radioId, _veraavr_data.relayId, GATEWAY_ADDRESS, childId, messageType, type, data); -} - -uint8_t VeraAVR_sendData(uint16_t from, uint16_t next, uint16_t to, uint8_t childId, messageType messageType, uint8_t type, const char *data) { - uint8_t ok = 0; - if (strlen(data) < sizeof(_veraavr_data.msg.data)) { - _veraavr_data.msg.header.version = PROTOCOL_VERSION; - _veraavr_data.msg.header.binary = 0; - _veraavr_data.msg.header.from = from; - _veraavr_data.msg.header.to = to; - _veraavr_data.msg.header.childId = childId; - _veraavr_data.msg.header.messageType = messageType; - _veraavr_data.msg.header.type = type; - - strncpy(_veraavr_data.msg.data, data, sizeof(_veraavr_data.msg.data)-1); - _veraavr_data.msg.header.crc = VeraAVR_crc8Message(_veraavr_data.msg); - - - nrf24_stopListening(); - nrf24_openWritingPipe(BASE_RADIO_ID + next); - uint8_t retry = 5; - do { - ok = nrf24_write(&_veraavr_data.msg, min(MAX_MESSAGE_LENGTH, sizeof(_veraavr_data.msg.header) + strlen(_veraavr_data.msg.data) + 1)); - wdt_reset(); - } - while ( !ok && --retry ); - nrf24_startListening(); - } - return ok; -} - -void VeraAVR_sendVariable_char(uint8_t childId, uint8_t variableType, - const char *value) { - VeraAVR_sendDataGW(childId, M_VARIABLE, variableType, value); -} - -void VeraAVR_sendVariable_float(uint8_t childId, uint8_t variableType, float value, int decimals) { - VeraAVR_sendVariable_char(childId, variableType, dtostrf(value,2,decimals,_veraavr_data.convBuffer)); -} - -void VeraAVR_sendVariable_int(uint8_t childId, uint8_t variableType, int value) { - VeraAVR_sendVariable_char(childId, variableType, itoa(value, _veraavr_data.convBuffer, 10)); -} -void VeraAVR_sendVariable_long(uint8_t childId, uint8_t variableType, long value) { - VeraAVR_sendVariable_char(childId, variableType, ltoa(value, _veraavr_data.convBuffer, 10)); -} - -void VeraAVR_requestStatus(uint8_t childId, uint8_t variableType) { - VeraAVR_sendDataGW(childId, M_STATUS, variableType, ""); -} - -char* VeraAVR_getStatus(uint8_t childId, uint8_t variableType) { - while (1) { - VeraAVR_requestStatus(childId, variableType); - uint8_t i = 0; - while (i < 100) { // 5 seconds timeout before re-sending status request - while (VeraAVR_messageAvailable()) { - // Check that it is right type of message and not a routing message - if ((_veraavr_data.msg.header.messageType == M_REQUEST_STATUS_RESPONSE) && - (_veraavr_data.msg.header.type == variableType) && - (_veraavr_data.msg.header.to == childId)) { - return _veraavr_data.msg.data; - } - } - _delay_ms(50); - wdt_reset(); - i++; - } - } - return NULL; -} - -void VeraAVR_requestConfiguration(uint8_t variableType) { - VeraAVR_requestStatus(NODE_CHILD_ID, variableType); -} - -char* VeraAVR_getConfiguration(uint8_t variableType) { - return VeraAVR_getStatus(NODE_CHILD_ID, variableType); -} - -unsigned long VeraAVR_getTime() { - return atol(VeraAVR_getConfiguration(V_TIME)); -} - -void VeraAVR_sendSensorPresentation(uint8_t childId, uint8_t sensorType) { - VeraAVR_sendDataGW(childId, M_PRESENTATION, sensorType, LIBRARY_VERSION); -} - - -uint8_t VeraAVR_messageAvailable() { - while (nrf24_available()) { - VeraAVR_readMessage(); - // Check that message was addressed for me. Could be a message from some other sensor - // as we«re automatically listening to pipe 0 (our writing pipe) where all sensors - // send their data - if (_veraavr_data.msg.header.to == _veraavr_data.radioId && VeraAVR_validate() == VALIDATE_OK) - return 1; - wdt_reset(); - } - return 0; -} - - -message_s VeraAVR_waitForMessage() { - while (1) { - if (VeraAVR_messageAvailable()) { - return _veraavr_data.msg; - } - wdt_reset(); - } -} - -message_s VeraAVR_getMessage() { - return _veraavr_data.msg; -} - - -message_s VeraAVR_readMessage() { - uint8_t len = nrf24_getDynamicPayloadSize(); - //uint8_t done = - nrf24_read(&_veraavr_data.msg, len); - // Make sure string gets terminated ok. - _veraavr_data.msg.data[sizeof(_veraavr_data.msg.data)-1] = '\0'; - return _veraavr_data.msg; -} - -/* - * calculate CRC8 on message_s data taking care of data structure and protocol version - */ -uint8_t VeraAVR_crc8Message(message_s var_msg) { - struct { - message_s msg; - uint8_t protocol_version; - } crc_data; - memcpy(&crc_data, &var_msg, sizeof(var_msg)); - crc_data.protocol_version = PROTOCOL_VERSION; - // some clean up needed for repeated result - crc_data.msg.header.crc = 0; - // fill unused space by zeroes for string data only - if(!crc_data.msg.header.binary) { - uint8_t len = strlen(crc_data.msg.data); - if(len < sizeof(crc_data.msg.data)-1) { - memset(&crc_data.msg.data[len], 0, sizeof(crc_data.msg.data) - 1 - len); - } - } - return crc8((uint8_t*)&crc_data, (uint8_t)sizeof(crc_data)); -} -/* - * true if message is consistent * - */ -uint8_t VeraAVR_checkCRCMessage(message_s var_msg) { - return (var_msg.header.crc == VeraAVR_crc8Message(var_msg))?1:0; -} -uint8_t VeraAVR_checkCRC() { - return VeraAVR_checkCRCMessage(_veraavr_data.msg); -} - -uint8_t VeraAVR_validate() { - uint8_t crc_check = VeraAVR_checkCRC(); - uint8_t version_check = (_veraavr_data.msg.header.version == PROTOCOL_VERSION); - if(crc_check && version_check) return VALIDATE_OK; - if(!crc_check) return VALIDATE_BAD_CRC; - return VALIDATE_BAD_VERSION; -} diff --git a/AVR/lib/Vera/VeraAVR.h b/AVR/lib/Vera/VeraAVR.h deleted file mode 100644 index f6fb3a9..0000000 --- a/AVR/lib/Vera/VeraAVR.h +++ /dev/null @@ -1,157 +0,0 @@ -/* - Vera Arduino library is used to communicate sensor data to your Vera receiver sketch using RF24 library. - - Created by Henrik Ekblad - Version 1.0 - - 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. - - modification by axillent@gmail.com to run on pure AVR - - before running this you need to configure properly RF24-avrlib -*/ - -#ifndef Vera_h -#define Vera_h - -#include -#include -#include -#include - -#define LIBRARY_VERSION "1.2+" -#define PROTOCOL_VERSION 1 -#define BAUD_RATE 115200 -#define AUTO 0xFFF // Id 4095 is reserved for auto initialization of radioId. -#define NODE_CHILD_ID 0xFF // Node child id is always created for when a new sensor is detected - -#define VERA_CHANNEL 76 - -// This is the radioId for Vera receiver sketch (where all sensors should send their data). -// This is also act as base value for sensor radioId -#define BASE_RADIO_ID 0xABCDABC000LL -#define GATEWAY_ADDRESS ((uint16_t)0) - -#define MAX_MESSAGE_LENGTH 32 - -#define CRC8INIT 0x00 -#define CRC8POLY 0x18 //0X18 = X^8+X^5+X^4+X^0 - -typedef enum { M_PRESENTATION = 0, M_VARIABLE, M_STATUS, M_CUSTOM, M_GATEWAY_MESSAGE, M_REQUEST_STATUS_RESPONSE } messageType; - -// Adding new variable- and device types should be done at the end of enum -typedef enum { V_TEMP,V_HUM, V_LIGHT, V_DIMMER, V_PRESSURE, V_FORECAST, V_RAIN, V_RAINRATE, V_WIND, V_GUST, - V_DIRECTION, V_UV, V_WEIGHT, V_DISTANCE, V_IMPEDANCE, V_BATTERY_LEVEL, V_BATTERY_DATE, - V_ARMED, V_TRIPPED, V_LAST_TRIP, V_WATT, V_KWH, V_SCENE_ON, V_SCENE_OFF, V_HEATER, - V_HEATER_SW, V_LIGHT_LEVEL, V_VAR1, V_VAR2, V_VAR3, V_VAR4, V_VAR5, V_TIME, V_VERSION, - V_REQUEST_ID, V_INCLUSION_MODE, V_INCLUSION_COUNT, V_INCLUSION_RESULT, V_NEIGHBORS, - V_RELAY_MODE, V_LAST_UPDATE} variable; - -typedef enum { S_DOOR, S_MOTION, S_SMOKE, S_LIGHT, S_DIMMER, S_COVER, S_TEMP, S_HUM, S_BARO, S_WIND, - S_RAIN, S_UV, S_WEIGHT, S_POWER, S_HEATER, S_DISTANCE, S_LIGHT_LEVEL, S_ARDUINO_NODE} senosr; - -// result of validate() -enum { VALIDATE_OK=0, VALIDATE_BAD_CRC, VALIDATE_BAD_VERSION }; - - -typedef struct { - uint8_t crc : 8; // 8 bits crc - uint8_t version : 3; // 3 bits protocol version - uint8_t binary : 1; // 1 bit. Data is binary and should be encoded when sent to vera - uint16_t from : 12; // 12 bits. RadioId of sender node - uint16_t to : 12; // 12 bits. RadioId of destination node - uint8_t childId : 8; // 1 byte. Up to MAX_CHILD_DEVICES child sensors per radioId - uint8_t messageType : 4; // 4 bits. Type of message. See messageType - uint8_t type : 8; // 8 bits. variableType or deviceType depending on messageType -} header_s; - -typedef struct { - header_s header; - char data[MAX_MESSAGE_LENGTH - sizeof(header_s) + 1]; // Each message can transfer a payload. Add one extra byte for \0 -} message_s; - - - -/** -* Begin operation of the vera library -* -* Call this in setup(), before calling any other vera library methods. -*/ -void VeraAVR_begin(uint16_t _radioId); -void VeraAVR_begin2(uint16_t _radioId, uint16_t _relayId); - -/** -* Sends a variable change to vera -* -* @param childId The child id for which to update variable. Value can be 0-127. -* @param variableType The variableType to update -* @param value New value of the variable -*/ -void VeraAVR_sendVariable_char (uint8_t childId, uint8_t variableType, const char *value); -void VeraAVR_sendVariable_float (uint8_t childId, uint8_t variableType, float value, int decimals); -void VeraAVR_sendVariable_long(uint8_t childId, uint8_t variableType, long value); -void VeraAVR_sendVariable_int(uint8_t childId, uint8_t variableType, int value); - -/** -* Requests status for a vera variable (sent from an actuator) -* -* @param childId The unique child id for the different sensors connected to this arduino. 0-127. -* @param variableType The variableType to update -*/ -void VeraAVR_requestStatus (uint8_t childId, uint8_t variableType); - -/** -* Requests configuration parameter -* -* @param variableType The variableType to fetch -*/ -void VeraAVR_requestConfiguration(uint8_t variableType); -char * VeraAVR_getConfiguration(uint8_t variableType); -/** - * Fetches time from vera - */ -unsigned long VeraAVR_getTime(); -/* -* The arduino must send a presentation of all the sensors connected before any variable changes will be registrered on Vera side. -* Usually it's good to present all sensors when Arduino starts up (setup). -* Waits until all data has been transmitted and acknowledged by Vera receiver (retries RESEND_PRESENTATION times). -* -* @param childId The unique child id for the different sensors connected to this arduino. 0-254. -* @param sensorType Sensor types to create. They will be numbered from 0 up to 127. -*/ -void VeraAVR_sendSensorPresentation (uint8_t childId, uint8_t sensorType); - -/** -* Registers this arduino device as a relay. This requires this node to call -* api methods regularly to relay messages that could be passing this node and -* answer to any neighbor-discovery messages. -* Basically all api methods relays messages (waitForMessage, messageAvailable, ..) -* When this method is called vera will be informed that this node acts as relay. -*/ -void VeraAVR_registerNodeAsRelay(); -/** -* Busy waits until there is a message available to be read (used for actuators, like relays) -*/ -message_s VeraAVR_waitForVeraMessage(void); -/** -* Returns true if there is a message addressed for this node is available to be read (used by VeraGateway) -*/ -uint8_t VeraAVR_messageAvailable(); - /** - * Returns the last received message - */ -message_s VeraAVR_getMessage(); -uint8_t sendData(uint16_t from, uint16_t next, uint16_t to, uint8_t childId, messageType messageType, uint8_t type, const char *data); -uint8_t VeraAVR_validate(); -uint8_t VeraAVR_crc8Message(message_s); -uint8_t VeraAVR_checkCRCMessage(message_s); -uint8_t VeraAVR_checkCRC(); -message_s VeraAVR_readMessage(void); -uint8_t VeraAVR_sendDataGW(uint8_t childId, messageType messageType, uint8_t type, const char *data); -uint8_t VeraAVR_sendData(uint16_t from, uint16_t next, uint16_t to, uint8_t childId, messageType messageType, uint8_t type, const char *data); - -#include "VeraAVR.c" - -#endif diff --git a/AVR/lib/crc8/crc8.c b/AVR/lib/crc8/crc8.c deleted file mode 100644 index 6a0fc00..0000000 --- a/AVR/lib/crc8/crc8.c +++ /dev/null @@ -1,63 +0,0 @@ -/* please read copyright-notice at EOF */ - -#include - -#define CRC8INIT 0x00 -#define CRC8POLY 0x18 //0X18 = X^8+X^5+X^4+X^0 - -uint8_t crc8( uint8_t *data, uint16_t number_of_bytes_in_data ) -{ - uint8_t crc; - uint16_t loop_count; - uint8_t bit_counter; - uint8_t b; - uint8_t feedback_bit; - - crc = CRC8INIT; - - for (loop_count = 0; loop_count != number_of_bytes_in_data; loop_count++) - { - b = data[loop_count]; - - bit_counter = 8; - do { - feedback_bit = (crc ^ b) & 0x01; - - if ( feedback_bit == 0x01 ) { - crc = crc ^ CRC8POLY; - } - crc = (crc >> 1) & 0x7F; - if ( feedback_bit == 0x01 ) { - crc = crc | 0x80; - } - - b = b >> 1; - bit_counter--; - - } while (bit_counter > 0); - } - - return crc; -} - -/* -This code is from Colin O'Flynn - Copyright (c) 2002 -only minor changes by M.Thomas 9/2004 - -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. -*/ diff --git a/AVR/lib/crc8/crc8.h b/AVR/lib/crc8/crc8.h deleted file mode 100644 index 1b27cd4..0000000 --- a/AVR/lib/crc8/crc8.h +++ /dev/null @@ -1,42 +0,0 @@ -#ifndef CRC8_H_ -#define CRC8_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -uint8_t crc8( uint8_t* data, uint16_t number_of_bytes_in_data ); - -#ifdef __cplusplus -} -#endif - -#include "crc8.c" - -#endif - -/* -This is based on code from : - -Copyright (c) 2002 Colin O'Flynn - -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. -*/ - diff --git a/AVR/lib/spi/Arduino/DS1305/ds1305.c b/AVR/lib/spi/Arduino/DS1305/ds1305.c deleted file mode 100644 index fbafeb4..0000000 --- a/AVR/lib/spi/Arduino/DS1305/ds1305.c +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2009 Andrew Smallbone - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include - -#ifdef __cplusplus -extern "C"{ -#endif - -unsigned char ds1305_transfer(unsigned char address, unsigned char data) -{ - select_ds1305(); - send_spi(address); - unsigned char out = send_spi(data); - deselect_ds1305(); - return out; -} - -void ds1305_write_block(unsigned char address, unsigned char *data, int length) -{ - select_ds1305(); - send_spi(address+DS1305_WRITE); - int i; - for (i=0; i - * - * 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 _ds1305_h__ -#define _ds1305_h__ - -#include - -#ifdef __cplusplus -extern "C"{ -#endif - -// these should be defined to the operation used to select/deselect the DS1305 -void select_ds1305(void); -void deselect_ds1305(void); - -#define DS1305_WRITE 0x80 -#define DS1305_TIME 0x00 -#define DS1305_ALARM0 0x07 -#define DS1305_ALARM1 0x0B -#define DS1305_CONTROL 0x0F -#define DS1305_STATUS 0x010 -#define DS1305_CHARGER 0x11 -#define DS1305_USERRAM 0x20 - -#define DS1305_ALARM_SET 0x80 - -// send the address and a byte and returns the byte returned by the DS1305 -unsigned char ds1305_transfer(unsigned char address, unsigned char data); -// write a block of bytes - will add 0x80 to the address -void ds1305_write_block(unsigned char address, unsigned char *data, int length); -// read a block of bytes -void ds1305_read_block(unsigned char address, unsigned char *data, int length); - -typedef struct _DS1305_DATETIME -{ - unsigned char seconds; - unsigned char minutes; - unsigned char hours; - unsigned char dayofweek; - unsigned char date; - unsigned char month; - unsigned char year; -} DS1305_DATETIME; - -/* set/get the current time/date passed the address of a DS1305_DATETIME struct - To set the current time/date to "20:11:32 Sunday 29/07/2009" - DS1305_DATETIME current = {0x32, 0x11, 0x20, 0x01, 0x29, 0x05, 0x09}; - set_time(¤t); -*/ -#define set_time(datetime) ds1305_write_block(DS1305_TIME, (unsigned char *)datetime, 7) -#define get_time(datetime) ds1305_read_block(DS1305_TIME, (unsigned char *)datetime, 7) - -/* set/get the time of alarm0/alarm1 passed the address of a DS1305_DATETIME struct, - although only the seconds/minutes/hours/dayofweek are sent/received -*/ -#define set_alarm0(time) ds1305_write_block(DS1305_ALARM0, (unsigned char *)time, 4) -#define get_alarm0(time) ds1305_read_block(DS1305_ALARM0, (unsigned char *)time, 4) -#define set_alarm1(time) ds1305_write_block(DS1305_ALARM1, (unsigned char *)time, 4) -#define get_alarm1(time) ds1305_read_block(DS1305_ALARM1, (unsigned char *)time, 4) - -// flags used in set_control/get_control -#define DS1305_EOSC 0x80 // enable oscillator, note this is inverse of ^EOSC bit value on chip -#define DS1305_WP 0x40 // write protect -#define DS1305_INTCN 0x04 // enable interrupts -#define DS1305_AIE1 0x02 // alarm0 interrupt enable -#define DS1305_AIE0 0x01 // alarm1 interrupt enable - -/* get/set the control register. To enable the oscillator, turn on write protection - and enable all interrupts the following would be used: - set_control(DS1305_EOSC | DS1305_WP | DS1305_INTCN | DS1305_AIE1 | DS1305_AIE0); -*/ -#define set_control(data) ds1305_transfer(DS1305_CONTROL+DS1305_WRITE, (data) ^ DS1305_EOSC) -#define get_control(data) (ds1305_transfer(DS1305_CONTROL, 0xFF) ^ DS1305_EOSC) - -// flags used in get_status -#define DS1305_IRQF0 0x01 // interrupt 0 request flag - current time has matched alarm 0 -#define DS1305_IRQF1 0x02 // interrupt 1 request flag - current time has matched alarm 1 -#define get_status(data) ds1305_transfer(DS1305_STATUS, 0xFF) - -// flags used in set_charger/get_charger -#define DS1305_CHARGER_OFF 0x5C // no charge - don't combine with other values -#define DS1305_CHARGER_1D2K 0xA5 // 1 diode 2K resistor -#define DS1305_CHARGER_1D4K 0xA6 // 1 diode 4K resistor -#define DS1305_CHARGER_1D8K 0xA7 // 1 diode 8K resistor -#define DS1305_CHARGER_2D2K 0xA1 // 2 diode 2K resistor -#define DS1305_CHARGER_2D4K 0xA2 // 2 diode 4K resistor -#define DS1305_CHARGER_2D8K 0xA3 // 2 diode 8K resistor -/* get/set the charger register */ -#define set_charger(data) ds1305_transfer(DS1305_CHARGE+DS1305_WRITE, data) -#define get_charger(data) ds1305_transfer(DS1305_CHARGE, 0xFF) - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif diff --git a/AVR/lib/spi/Arduino/DS1305/keywords.txt b/AVR/lib/spi/Arduino/DS1305/keywords.txt deleted file mode 100644 index bfaf490..0000000 --- a/AVR/lib/spi/Arduino/DS1305/keywords.txt +++ /dev/null @@ -1,53 +0,0 @@ -####################################### -# Syntax Coloring Map For SPI -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### -DS1305_DATETIME KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -select_ds1305 KEYWORD2 -deselect_ds1305 KEYWORD2 -set_time KEYWORD2 -get_time KEYWORD2 -set_control KEYWORD2 -get_control KEYWORD2 -set_charger KEYWORD2 -get_charger KEYWORD2 -get_alarm0 KEYWORD2 -set_alarm1 KEYWORD2 -get_alarm1 KEYWORD2 -get_status KEYWORD2 - -####################################### -# Constants KEYWORD2 -####################################### -DS1305_WRITE LITERAL1 -DS1305_TIME LITERAL1 -DS1305_ALARM0 LITERAL1 -DS1305_ALARM1 LITERAL1 -DS1305_CONTROL LITERAL1 -DS1305_STATUS LITERAL1 -DS1305_CHARGER LITERAL1 -DS1305_USERRAM LITERAL1 -DS1305_ALARM_SET LITERAL1 -DS1305_EOSC LITERAL1 -DS1305_WP LITERAL1 -DS1305_INTCN LITERAL1 -DS1305_AIE1 LITERAL1 -DS1305_AIE0 LITERAL1 -DS1305_IRQF0 LITERAL1 -DS1305_IRQF1 LITERAL1 -DS1305_CHARGER_OFF LITERAL1 -DS1305_CHARGER_1D2K LITERAL1 -DS1305_CHARGER_1D4K LITERAL1 -DS1305_CHARGER_1D8K LITERAL1 -DS1305_CHARGER_2D2K LITERAL1 -DS1305_CHARGER_2D4K LITERAL1 -DS1305_CHARGER_2D8K LITERAL1 - diff --git a/AVR/lib/spi/Arduino/SPI/examples/DS1305_Alarm/DS1305_Alarm.pde b/AVR/lib/spi/Arduino/SPI/examples/DS1305_Alarm/DS1305_Alarm.pde deleted file mode 100644 index 601672a..0000000 --- a/AVR/lib/spi/Arduino/SPI/examples/DS1305_Alarm/DS1305_Alarm.pde +++ /dev/null @@ -1,79 +0,0 @@ -#include -#include - -#define DS1305_PIN 4 -#define LED_PIN 3 - -// following two methods required by DS1305 library to select/deselect device -void select_ds1305(void) -{ - digitalWrite(DS1305_PIN, HIGH); -} - -void deselect_ds1305(void) -{ - digitalWrite(DS1305_PIN, LOW); -} - -// flash led that's connected to pin 3 -void flash_led(void) -{ - pinMode(LED_PIN, OUTPUT); - for (int i=0; i<10; i++) { - digitalWrite(LED_PIN, i%2==0); - delay(50); - } -} - -// called when pin INT0 goes from 1 to 0 -ISR(INT0_vect) -{ - // get alarm value to clear alarm interrupt flag on DS1305 - DS1305_DATETIME alarm; - get_alarm0(&alarm); - flash_led(); -} - -void setup() -{ - // flash LED at start to indicate were about to start - flash_led(); - flash_led(); - - // pin used to enable DS1305 - pinMode(DS1305_PIN, OUTPUT); - - // Make sure ADC is unselected and setup spi - deselect_ds1305(); - setup_spi(SPI_MODE_1, SPI_MSB, SPI_NO_INTERRUPT, SPI_MSTR_CLK16); - set_control(0); - - // set current date/time to Thursday 06/05/09 20:32:30 - DS1305_DATETIME current = {0x30, 0x32, 0x20, 0x05, 0x06, 0x05, 0x09}; - set_time(¤t); - - // change the value of alarm to the required time/granularity: - // raise alarm every day (at 20:32:00): - // DS1305_DATETIME alarm = {0x00, 0x32, 0x20, 0x00 | DS1305_ALARM_SET}; - // raise alarm every minute (when seconds = 00): - // DS1305_DATETIME alarm = {0x00, 0x32 | DS1305_ALARM_SET, - // 0x20 | DS1305_ALARM_SET, 0x05 | DS1305_ALARM_SET}; - // raise alarm every second: - DS1305_DATETIME alarm = {0x55 | DS1305_ALARM_SET, 0x32 | DS1305_ALARM_SET, - 0x20 | DS1305_ALARM_SET, 0x05 | DS1305_ALARM_SET}; - set_alarm0(&alarm); - // turn on timer and make alarm0 lower INT0 pin when alarm is triggered - set_control(DS1305_EOSC | DS1305_INTCN | DS1305_AIE0); - - // raise interrupt when INT0 pin falls (pin PD0 at AT90usbXXX, pin PD2 on ATmegaXXX (arduino pin 2)) - // the code in ISR(INT0_vect) above will be called - EICRA = (1< - -// MAX6675 connected to pin D9 -#define MAX6675_SELECT_PIN 8 -#define DESELECT_MAX6675 digitalWrite(MAX6675_SELECT_PIN, HIGH) -#define SELECT_MAX6675 digitalWrite(MAX6675_SELECT_PIN, LOW) - -void setup() -{ - pinMode(MAX6675_SELECT_PIN, OUTPUT); - DESELECT_MAX6675; - setup_spi(SPI_MODE_1, SPI_MSB, SPI_NO_INTERRUPT, SPI_MSTR_CLK8); - Serial.begin(19200); -} - -void loop() -{ - delay(500); - - // select the device, wait > 100nS, read two bytes, deselect - SELECT_MAX6675; - delayMicroseconds(1); - unsigned char highByte = send_spi(0); - unsigned char lowByte = send_spi(0); - DESELECT_MAX6675; - - // if bit 3 is high thermocouple is unconnected - if (lowByte & (1<<2)) { - Serial.print("Not connected "); - Serial.print(highByte, HEX); Serial.print(" "); - Serial.println(lowByte, HEX); - } else { - // temperature value is in bits 6-0 of highByte and 7-2 of lowByte - short value = (highByte << 5 | lowByte>>3); - // 1 bit is 0.25 degree 'divide' by 4 to show degrees - Serial.print(value/4); Serial.print("."); Serial.println(value%4 *25); - } -} diff --git a/AVR/lib/spi/Arduino/SPI/examples/MCP3201_ADC/MCP3201_ADC.pde b/AVR/lib/spi/Arduino/SPI/examples/MCP3201_ADC/MCP3201_ADC.pde deleted file mode 100644 index 2380dfb..0000000 --- a/AVR/lib/spi/Arduino/SPI/examples/MCP3201_ADC/MCP3201_ADC.pde +++ /dev/null @@ -1,32 +0,0 @@ -#include - -#define SELECT_ADC digitalWrite(8, LOW); -#define DESELECT_ADC digitalWrite(8, HIGH); - -unsigned short read_adc(void) -{ - // select ADC wait 100microseconds then read two bytes - SELECT_ADC; - unsigned char one = send_spi(0xFF); - unsigned char two = send_spi(0xFF); - DESELECT_ADC; - // 12 bits of ADC value is bottom 5 bits of first - // byte and top 7 bits of second, move into 16 bit int - return ((0x1F & one) << 7) | (two >> 1); -} - -void setup() -{ - pinMode(8, OUTPUT); - Serial.begin(19200); - // make sure ADC is not selected and setup spi - DESELECT_ADC; - setup_spi(SPI_MODE_0, SPI_MSB, SPI_NO_INTERRUPT, SPI_MSTR_CLK16); -} - -void loop() -{ - unsigned short num = read_adc(); - Serial.println(num); - delay(1000); -} diff --git a/AVR/lib/spi/Arduino/SPI/examples/MasterSlave/MasterSlave.pde b/AVR/lib/spi/Arduino/SPI/examples/MasterSlave/MasterSlave.pde deleted file mode 100644 index 6c3ca03..0000000 --- a/AVR/lib/spi/Arduino/SPI/examples/MasterSlave/MasterSlave.pde +++ /dev/null @@ -1,91 +0,0 @@ -#include -#include - -#define BUTTON_PIN 2 -#define LED_PIN 3 -#define FLASH_LED_COMMAND 0x01 - -#define OTHER_SELECT_PIN 7 -#define SELECT_OTHER digitalWrite(OTHER_SELECT_PIN, LOW); -#define DESELECT_OTHER digitalWrite(OTHER_SELECT_PIN, HIGH); - -#define BUFSIZE 20 -volatile unsigned char incoming[BUFSIZE]; -volatile short int received=0; - -// flash led that's connected to pin PD7 -void flash_led(int count) -{ - pinMode(LED_PIN, OUTPUT); - for (int i=0; i - -void reportError(int line, char *message, uint8_t expected, uint8_t actual) -{ - Serial.print("Test "); Serial.print(message); - Serial.print(" failed at line "); Serial.print(line-3); - Serial.print(", expected="); Serial.print(expected, BIN); - Serial.print(", actual="); Serial.println(actual, BIN); -} - -#define assertEquals(message, expected, actual) \ - if (expected != actual) { reportError(__LINE__, message, expected, actual); return; } - - -#define test_setup_spi(message, eSPCR, eSPSR, mode, dord, interrupt, clock) \ - setup_spi(mode, dord, interrupt, clock); \ - assertEquals(message, eSPCR, SPCR); \ - assertEquals(message, eSPSR, SPSR & 0x01); - - -void test_registers() -{ - // top 4 bits of SPCR - enabled, interrupt, lsb/msb, master/slave - disable_spi(); - assertEquals("0", 0x00, SPCR); - - test_setup_spi("1", 0xE0, 0x00, SPI_MODE_0, SPI_LSB, SPI_INTERRUPT, SPI_SLAVE); - test_setup_spi("2", 0x60, 0x00, SPI_MODE_0, SPI_LSB, SPI_NO_INTERRUPT, SPI_SLAVE); - test_setup_spi("3", 0x40, 0x00, SPI_MODE_0, SPI_MSB, SPI_NO_INTERRUPT, SPI_SLAVE); - - // CPOL/CPHA bits - timing mode - test_setup_spi("4", 0x40, 0x00, SPI_MODE_0, SPI_MSB, SPI_NO_INTERRUPT, SPI_SLAVE); - test_setup_spi("5", 0x44, 0x00, SPI_MODE_1, SPI_MSB, SPI_NO_INTERRUPT, SPI_SLAVE); - test_setup_spi("6", 0x48, 0x00, SPI_MODE_2, SPI_MSB, SPI_NO_INTERRUPT, SPI_SLAVE); - test_setup_spi("7", 0x4C, 0x00, SPI_MODE_3, SPI_MSB, SPI_NO_INTERRUPT, SPI_SLAVE); - - // clock - test_setup_spi("9", 0xE0, 1, SPI_MODE_0, SPI_LSB, SPI_INTERRUPT, SPI_MSTR_CLK2); - test_setup_spi("10", 0xE0, 0, SPI_MODE_0, SPI_LSB, SPI_INTERRUPT, SPI_MSTR_CLK4); - test_setup_spi("11", 0xE1, 1, SPI_MODE_0, SPI_LSB, SPI_INTERRUPT, SPI_MSTR_CLK8); - test_setup_spi("12", 0xE1, 0, SPI_MODE_0, SPI_LSB, SPI_INTERRUPT, SPI_MSTR_CLK16); - test_setup_spi("13", 0xE2, 1, SPI_MODE_0, SPI_LSB, SPI_INTERRUPT, SPI_MSTR_CLK32); - test_setup_spi("14", 0xE2, 0, SPI_MODE_0, SPI_LSB, SPI_INTERRUPT, SPI_MSTR_CLK64); - test_setup_spi("15", 0xE3, 0, SPI_MODE_0, SPI_LSB, SPI_INTERRUPT, SPI_MSTR_CLK128); -} - -void setup() -{ - Serial.begin(19200); -} - -void loop() -{ - delay(5000); - Serial.println("Running tests"); - test_registers(); - Serial.println("Run tests"); - while(true); -} diff --git a/AVR/lib/spi/Arduino/SPI/keywords.txt b/AVR/lib/spi/Arduino/SPI/keywords.txt deleted file mode 100644 index 96faa4c..0000000 --- a/AVR/lib/spi/Arduino/SPI/keywords.txt +++ /dev/null @@ -1,39 +0,0 @@ -####################################### -# Syntax Coloring Map For SPI -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -setup_spi KEYWORD2 -disable_spi KEYWORD2 -send_spi KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### -SPI_SS_PIN LITERAL1 -SPI_SCK_PIN LITERAL1 -SPI_MOSI_PIN LITERAL1 -SPI_MISO_PIN LITERAL1 -SPI_MODE_0 LITERAL1 -SPI_MODE_1 LITERAL1 -SPI_MODE_2 LITERAL1 -SPI_MODE_3 LITERAL1 -SPI_LSB LITERAL1 -SPI_MSB LITERAL1 -SPI_NO_INTERRUPT LITERAL1 -SPI_INTERRUPT LITERAL1 -SPI_SLAVE LITERAL1 -SPI_MSTR_CLK2 LITERAL1 -SPI_MSTR_CLK4 LITERAL1 -SPI_MSTR_CLK8 LITERAL1 -SPI_MSTR_CLK16 LITERAL1 -SPI_MSTR_CLK32 LITERAL1 -SPI_MSTR_CLK64 LITERAL1 -SPI_MSTR_CLK128 LITERAL1 diff --git a/AVR/lib/spi/Arduino/SPI/spi.c b/AVR/lib/spi/Arduino/SPI/spi.c deleted file mode 100644 index 27b0518..0000000 --- a/AVR/lib/spi/Arduino/SPI/spi.c +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2009 Andrew Smallbone - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include - -#ifdef __cplusplus -extern "C"{ -#endif - -#ifdef __ARDUINO__ -#include -#endif - -void setup_spi(uint8_t mode, int dord, int interrupt, uint8_t clock) -{ - // specify pin directions for SPI pins on port B - if (clock == SPI_SLAVE) { // if slave SS and SCK is input - DDRB &= ~(1< - * - * 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 _spi_h__ -#define _spi_h__ - -#include - -#ifdef __cplusplus -extern "C"{ -#endif - -// create alias for the different SPI chip pins - code assumes all on port B -#if (defined(__AVR_AT90USB82__) || defined(__AVR_AT90USB162__)) - #define SPI_SS_PIN PORTB0 - #define SPI_SCK_PIN PORTB1 - #define SPI_MOSI_PIN PORTB2 - #define SPI_MISO_PIN PORTB3 -#elif (defined(__AVR_ATmega48__) || defined(_AVR_ATmega88__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega328__) || defined(__AVR_ATmega328P__)) - #define SPI_SS_PIN PORTB2 - #define SPI_SCK_PIN PORTB5 - #define SPI_MOSI_PIN PORTB3 - #define SPI_MISO_PIN PORTB4 -#else - #error unknown processor - add to spi.h -#endif - -// SPI clock modes -#define SPI_MODE_0 0x00 /* Sample (Rising) Setup (Falling) CPOL=0, CPHA=0 */ -#define SPI_MODE_1 0x01 /* Setup (Rising) Sample (Falling) CPOL=0, CPHA=1 */ -#define SPI_MODE_2 0x02 /* Sample (Falling) Setup (Rising) CPOL=1, CPHA=0 */ -#define SPI_MODE_3 0x03 /* Setup (Falling) Sample (Rising) CPOL=1, CPHA=1 */ - -// data direction -#define SPI_LSB 1 /* send least significant bit (bit 0) first */ -#define SPI_MSB 0 /* send most significant bit (bit 7) first */ - -// whether to raise interrupt when data received (SPIF bit received) -#define SPI_NO_INTERRUPT 0 -#define SPI_INTERRUPT 1 - -// slave or master with clock diviser -#define SPI_SLAVE 0xF0 -#define SPI_MSTR_CLK4 0x00 /* chip clock/4 */ -#define SPI_MSTR_CLK16 0x01 /* chip clock/16 */ -#define SPI_MSTR_CLK64 0x02 /* chip clock/64 */ -#define SPI_MSTR_CLK128 0x03 /* chip clock/128 */ -#define SPI_MSTR_CLK2 0x04 /* chip clock/2 */ -#define SPI_MSTR_CLK8 0x05 /* chip clock/8 */ -#define SPI_MSTR_CLK32 0x06 /* chip clock/32 */ - - - -// setup spi -void setup_spi(uint8_t mode, // timing mode SPI_MODE[0-4] - int dord, // data direction SPI_LSB|SPI_MSB - int interrupt, // whether to raise interrupt on recieve - uint8_t clock); // clock diviser - -// disable spi -void disable_spi(void); - -// send and receive a byte of data (master mode) -uint8_t send_spi(uint8_t out); - -// receive the byte of data waiting on the SPI buffer and -// set the next byte to transfer - for use in slave mode -// when interrupts are enabled. -uint8_t received_from_spi(uint8_t out); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif - diff --git a/AVR/lib/spi/Makefile b/AVR/lib/spi/Makefile deleted file mode 100644 index 69e620d..0000000 --- a/AVR/lib/spi/Makefile +++ /dev/null @@ -1,17 +0,0 @@ -# -*- makefile -*- - -#TARGET = spi-test-adc -#TARGET = spi-test-rtc -TARGET = spi-test-masterslave - -OBJECTS = $(TARGET).o spi.o -CFLAGS = -I../libs -include ./Makefile.mf - -DEVICE = at90usb162 -CLOCK = 16000000 - -examples: - make -k TARGET=spi-test-adc clean all - make -k TARGET=spi-test-rtc OBJECTS="spi-test-rtc.o spi.o ds1305.o" clean all - make -k TARGET=spi-test-masterslave clean all \ No newline at end of file diff --git a/AVR/lib/spi/Makefile.mf b/AVR/lib/spi/Makefile.mf deleted file mode 100644 index aeb6d4e..0000000 --- a/AVR/lib/spi/Makefile.mf +++ /dev/null @@ -1,109 +0,0 @@ -# Name: Makefile - -# This is a prototype Makefile. Modify it according to your needs. -# You should at least check the settings for -# DEVICE ....... The AVR device you compile for -# CLOCK ........ Target AVR clock rate in Hertz -# OBJECTS ...... The object files created from your source files. This list is -# usually the same as the list of source files with suffix ".o". -# PROGRAMMER ... Options to avrdude which define the hardware you use for -# uploading to the AVR and the interface where this hardware -# is connected. -# FUSES ........ Parameters for avrdude to flash the fuses appropriately. - -DEVICE = at90usb162 -CLOCK = 16000000 -PROGRAMMER = -c stk500v2 -P avrdoper -#OBJECTS = $(TARGET).o -FUSES = -U hfuse:w:0xd9:m -U lfuse:w:0x24:m -# ATMega8 fuse bits (fuse bits for other devices are different!): -# Example for 8 MHz internal oscillator -# Fuse high byte: -# 0xd9 = 1 1 0 1 1 0 0 1 <-- BOOTRST (boot reset vector at 0x0000) -# ^ ^ ^ ^ ^ ^ ^------ BOOTSZ0 -# | | | | | +-------- BOOTSZ1 -# | | | | +---------- EESAVE (set to 0 to preserve EEPROM over chip erase) -# | | | +-------------- CKOPT (clock option, depends on oscillator type) -# | | +---------------- SPIEN (if set to 1, serial programming is disabled) -# | +------------------ WDTON (if set to 0, watchdog is always on) -# +-------------------- RSTDISBL (if set to 0, RESET pin is disabled) -# Fuse low byte: -# 0x24 = 0 0 1 0 0 1 0 0 -# ^ ^ \ / \--+--/ -# | | | +------- CKSEL 3..0 (8M internal RC) -# | | +--------------- SUT 1..0 (slowly rising power) -# | +------------------ BODEN (if 0, brown-out detector is enabled) -# +-------------------- BODLEVEL (if 0: 4V, if 1: 2.7V) - -# Example for 12 MHz external crystal: -# Fuse high byte: -# 0xc9 = 1 1 0 0 1 0 0 1 <-- BOOTRST (boot reset vector at 0x0000) -# ^ ^ ^ ^ ^ ^ ^------ BOOTSZ0 -# | | | | | +-------- BOOTSZ1 -# | | | | +---------- EESAVE (set to 0 to preserve EEPROM over chip erase) -# | | | +-------------- CKOPT (clock option, depends on oscillator type) -# | | +---------------- SPIEN (if set to 1, serial programming is disabled) -# | +------------------ WDTON (if set to 0, watchdog is always on) -# +-------------------- RSTDISBL (if set to 0, RESET pin is disabled) -# Fuse low byte: -# 0x9f = 1 0 0 1 1 1 1 1 -# ^ ^ \ / \--+--/ -# | | | +------- CKSEL 3..0 (external >8M crystal) -# | | +--------------- SUT 1..0 (crystal osc, BOD enabled) -# | +------------------ BODEN (if 0, brown-out detector is enabled) -# +-------------------- BODLEVEL (if 0: 4V, if 1: 2.7V) - - -# Tune the lines below only if you know what you are doing: - -AVRDUDE = avrdude $(PROGRAMMER) -p $(DEVICE) -COMPILE = avr-gcc $(CFLAGS) -Wall -std=gnu99 -funsigned-char -funsigned-bitfields -ffunction-sections -fpack-struct -fshort-enums -I. -Os -DF_CPU=$(CLOCK) -mmcu=$(DEVICE) - -# symbolic targets: -all: $(TARGET).hex - -.c.o: - $(COMPILE) -c $< -o $@ - -.S.o: - $(COMPILE) -x assembler-with-cpp -c $< -o $@ -# "-x assembler-with-cpp" should not be necessary since this is the default -# file type for the .S (with capital S) extension. However, upper case -# characters are not always preserved on Windows. To ensure WinAVR -# compatibility define the file type manually. - -.c.s: - $(COMPILE) -S $< -o $@ - -flash: all - $(AVRDUDE) -U flash:w:$(TARGET).hex:i - -fuse: - $(AVRDUDE) $(FUSES) - -# Xcode uses the Makefile targets "", "clean" and "install" -install: flash fuse - -# if you use a bootloader, change the command below appropriately: -load: all - bootloadHID $(TARGET).hex - -clean: - rm -f $(TARGET).hex $(TARGET).elf $(OBJECTS) - -# file targets: -$(TARGET).elf: $(OBJECTS) - $(COMPILE) -o $(TARGET).elf $(OBJECTS) - -$(TARGET).hex: $(TARGET).elf - rm -f $(TARGET).hex - avr-objcopy -j .text -j .data -O ihex $(TARGET).elf $(TARGET).hex -# If you have an EEPROM section, you must also create a hex file for the -# EEPROM and add it to the "flash" target. - -# Targets for code debugging and analysis: -disasm: $(TARGET).elf - avr-objdump -d $(TARGET).elf - -cpp: - $(COMPILE) -E $(TARGET).c diff --git a/AVR/lib/spi/ds1305.c b/AVR/lib/spi/ds1305.c deleted file mode 100644 index fbafeb4..0000000 --- a/AVR/lib/spi/ds1305.c +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2009 Andrew Smallbone - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include - -#ifdef __cplusplus -extern "C"{ -#endif - -unsigned char ds1305_transfer(unsigned char address, unsigned char data) -{ - select_ds1305(); - send_spi(address); - unsigned char out = send_spi(data); - deselect_ds1305(); - return out; -} - -void ds1305_write_block(unsigned char address, unsigned char *data, int length) -{ - select_ds1305(); - send_spi(address+DS1305_WRITE); - int i; - for (i=0; i - * - * 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 _ds1305_h__ -#define _ds1305_h__ - -#include - -#ifdef __cplusplus -extern "C"{ -#endif - -// these should be defined to the operation used to select/deselect the DS1305 -void select_ds1305(void); -void deselect_ds1305(void); - -#define DS1305_WRITE 0x80 -#define DS1305_TIME 0x00 -#define DS1305_ALARM0 0x07 -#define DS1305_ALARM1 0x0B -#define DS1305_CONTROL 0x0F -#define DS1305_STATUS 0x010 -#define DS1305_CHARGER 0x11 -#define DS1305_USERRAM 0x20 - -#define DS1305_ALARM_SET 0x80 - -// send the address and a byte and returns the byte returned by the DS1305 -unsigned char ds1305_transfer(unsigned char address, unsigned char data); -// write a block of bytes - will add 0x80 to the address -void ds1305_write_block(unsigned char address, unsigned char *data, int length); -// read a block of bytes -void ds1305_read_block(unsigned char address, unsigned char *data, int length); - -typedef struct _DS1305_DATETIME -{ - unsigned char seconds; - unsigned char minutes; - unsigned char hours; - unsigned char dayofweek; - unsigned char date; - unsigned char month; - unsigned char year; -} DS1305_DATETIME; - -/* set/get the current time/date passed the address of a DS1305_DATETIME struct - To set the current time/date to "20:11:32 Sunday 29/07/2009" - DS1305_DATETIME current = {0x32, 0x11, 0x20, 0x01, 0x29, 0x05, 0x09}; - set_time(¤t); -*/ -#define set_time(datetime) ds1305_write_block(DS1305_TIME, (unsigned char *)datetime, 7) -#define get_time(datetime) ds1305_read_block(DS1305_TIME, (unsigned char *)datetime, 7) - -/* set/get the time of alarm0/alarm1 passed the address of a DS1305_DATETIME struct, - although only the seconds/minutes/hours/dayofweek are sent/received -*/ -#define set_alarm0(time) ds1305_write_block(DS1305_ALARM0, (unsigned char *)time, 4) -#define get_alarm0(time) ds1305_read_block(DS1305_ALARM0, (unsigned char *)time, 4) -#define set_alarm1(time) ds1305_write_block(DS1305_ALARM1, (unsigned char *)time, 4) -#define get_alarm1(time) ds1305_read_block(DS1305_ALARM1, (unsigned char *)time, 4) - -// flags used in set_control/get_control -#define DS1305_EOSC 0x80 // enable oscillator, note this is inverse of ^EOSC bit value on chip -#define DS1305_WP 0x40 // write protect -#define DS1305_INTCN 0x04 // enable interrupts -#define DS1305_AIE1 0x02 // alarm0 interrupt enable -#define DS1305_AIE0 0x01 // alarm1 interrupt enable - -/* get/set the control register. To enable the oscillator, turn on write protection - and enable all interrupts the following would be used: - set_control(DS1305_EOSC | DS1305_WP | DS1305_INTCN | DS1305_AIE1 | DS1305_AIE0); -*/ -#define set_control(data) ds1305_transfer(DS1305_CONTROL+DS1305_WRITE, (data) ^ DS1305_EOSC) -#define get_control(data) (ds1305_transfer(DS1305_CONTROL, 0xFF) ^ DS1305_EOSC) - -// flags used in get_status -#define DS1305_IRQF0 0x01 // interrupt 0 request flag - current time has matched alarm 0 -#define DS1305_IRQF1 0x02 // interrupt 1 request flag - current time has matched alarm 1 -#define get_status(data) ds1305_transfer(DS1305_STATUS, 0xFF) - -// flags used in set_charger/get_charger -#define DS1305_CHARGER_OFF 0x5C // no charge - don't combine with other values -#define DS1305_CHARGER_1D2K 0xA5 // 1 diode 2K resistor -#define DS1305_CHARGER_1D4K 0xA6 // 1 diode 4K resistor -#define DS1305_CHARGER_1D8K 0xA7 // 1 diode 8K resistor -#define DS1305_CHARGER_2D2K 0xA1 // 2 diode 2K resistor -#define DS1305_CHARGER_2D4K 0xA2 // 2 diode 4K resistor -#define DS1305_CHARGER_2D8K 0xA3 // 2 diode 8K resistor -/* get/set the charger register */ -#define set_charger(data) ds1305_transfer(DS1305_CHARGE+DS1305_WRITE, data) -#define get_charger(data) ds1305_transfer(DS1305_CHARGE, 0xFF) - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif diff --git a/AVR/lib/spi/readme.txt b/AVR/lib/spi/readme.txt deleted file mode 100644 index 350bbe3..0000000 --- a/AVR/lib/spi/readme.txt +++ /dev/null @@ -1,111 +0,0 @@ -This directory contains a simple AVR spi helper library that should -run on most AVR microcontrollers which support SPI. - -The code is further described at: -http://www.rocketnumbernine.com/2009/04/26/using-spi-on-an-avr-1/ (basics & ADC) -http://www.rocketnumbernine.com/2009/05/12/using-spi-on-an-avr-2/ (RTC) - -Any comments/questions to - -Make sure viewing this text in a fixed width font for the tables and diagrams - - ----------------------------------- -Arduino ----------------------------------- -The Arduino Directory contains all code required to run on the Arduino. -Simply copy the Arduino/SPI and Arduino/DS1305 directories to the -"hardware/libraries" directory of your Arduino IDE installation and -restart the Arduino IDE. Once restarted there should be -"Sketch->Import Library->SPI" and "Sketch->Import Library->DS1305" menu -entries which can be used to include the spi header files into your project. -"File->Sketchbook->Examples->Library SPI" contains 3 example projects - - ----------------------------------- -AVR GCC ----------------------------------- -To use, just copy spi.h and spi.c (and ds1305.c and ds1305.h if using -the DS1305 Real Time Clock chip) to your own project and compile. - -Makefile.mf - 'standard' generated make file from AVR GCC -Makefile - Makefile "make examples" will make example programs below: - -spi-test-adc.c MC3201 Analogue to Digital convertor example -spi-test-rtc.c DS1305 - Real-Time-Clock/Alarm example -spi-test-masterslave.c Master/Slave communication example - - ----------------------------------- -PINS ----------------------------------- -Following are the AVR pins used in the circuits below - - ATmegaXXX Arduino AT90usbXXX -MISO PB4 12 PB3 -MOSI PB3 11 PB2 -SCK PB5 13 PB1 -SS PB2 10 PB0 - -INT0 PD2 2 PD0 - - ----------------------------------- -MC3201 12-bit ADC Circuit ----------------------------------- -See http://ww1.microchip.com/downloads/en/DeviceDoc/21290D.pdf for full details. - - +-----------------+ - | MC3201 | - +5V [| Vref Vdd |] +5V - | | -Analogue In [| IN+ CLK |] AVR SCK - | | - Ground [| IN- Dout |] AVR MOSI - | | - Ground [| Vss ^CS |] AVR CE - +-----------------+ - - -For testing purposes "Analogue In" can be connected to the middle wire -of a potentiometer with one outer wire being connected to +5 and the -other to Ground. A 1uF Capacitor should be placed between the analogue -input and ground, and +5V and ground as close to the chip as possible, -but in a pinch the circuit will likely work without. - - -MOSI/SLCK/CE to the relevant pin on the AVR (MISO is not used) - see above. - ----------------------------------- -DS1305 Real Time Clock Circuit ----------------------------------- -See http://datasheets.maxim-ic.com/en/ds/DS1305.pdf for full details. - -Without a battery the following connections can be used: - - +-----------------+ - | DS1305 | - Ground [| Vcc2 Vcc1 |] +5V - | | - Ground [| Vbat ^PF |] Not Connected - | | - Crystal [| X1 Vccif |] +5V - | | - Crystal [| X2 SDO |] AVR MISO - | | - Not Connected [| N.C. SDI |] AVR MOSI - | | - AVR INT0 [| INT0 SLCK |] AVR SLCK - | | - Not Connected [| INT1 CE |] AVR CE - | | - Ground [| GND SERMODE |] +5V - +-----------------+ - - -MISO/MOSI/SLCK/CE/INT0 to the relevant pin on the AVR - see above. - - - - - diff --git a/AVR/lib/spi/spi-test-adc.c b/AVR/lib/spi/spi-test-adc.c deleted file mode 100644 index a68bfb7..0000000 --- a/AVR/lib/spi/spi-test-adc.c +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2009 Andrew Smallbone - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include -#include -#include - -#define SELECT_ADC PORTB &= ~(1<> 1); -} - -int main(void) -{ - DDRB |= (1<> 9)); // use the top 3 bytes to turn on LED - _delay_ms(1); - } -} - diff --git a/AVR/lib/spi/spi-test-masterslave.c b/AVR/lib/spi/spi-test-masterslave.c deleted file mode 100644 index 21a7dbe..0000000 --- a/AVR/lib/spi/spi-test-masterslave.c +++ /dev/null @@ -1,88 +0,0 @@ -#include -#include -#include - -#define FLASH_LED_COMMAND 0x01 -#define OTHER_SELECT_PIN PB6 -#define SELECT_OTHER PORTB &= ~(1<= BUFSIZE || incoming[received-1] == 0x00) { - parse_message(); - received = 0; - } -} - -int main(void) -{ - // make sure other device is unselected (pin is HIGH) and setup spi - DESELECT_OTHER; - DDRB |= (1< - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include -#include -#include -#include - -#include - -// following two methods required by DS1305 library to select/deselect device -void select_ds1305(void) -{ - PORTD |= (1< - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include "spi.h" - -#ifdef __cplusplus -extern "C"{ -#endif - -#ifdef __ARDUINO__ -#include -#endif - -#ifndef SPI_SOFT_DRIVER - -// hardware driver - -void setup_spi(uint8_t mode, int dord, int interrupt, uint8_t clock) -{ - // specify pin directions for SPI pins on port B - if (clock == SPI_SLAVE) { // if slave SS and SCK is input - DDRB &= ~(1< - * - * 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 _spi_h__ -#define _spi_h__ - -#include - -#ifdef __cplusplus -extern "C"{ -#endif - - -// create alias for the different SPI chip pins - code assumes all on port B -#if (defined(__AVR_AT90USB82__) || defined(__AVR_AT90USB162__)) - #define SPI_SS_PIN PORTB0 - #define SPI_SCK_PIN PORTB1 - #define SPI_MOSI_PIN PORTB2 - #define SPI_MISO_PIN PORTB3 -#elif (defined(__AVR_ATmega48__) || defined(_AVR_ATmega88__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega328__) || defined(__AVR_ATmega328P__)) \ - || defined(__AVR_ATmega168PA__) || defined(__AVR_ATmega8A__) - #define SPI_PORT PORTB - #define SPI_PIN PINB - #define SPI_DDR DDRB - #define SPI_SS_PIN PORTB2 - #define SPI_SCK_PIN PORTB5 - #define SPI_MOSI_PIN PORTB3 - #define SPI_MISO_PIN PORTB4 -#else - #error unknown processor - add to spi.h -#endif - -// SPI clock modes -#define SPI_MODE_0 0x00 /* Sample (Rising) Setup (Falling) CPOL=0, CPHA=0 */ -#define SPI_MODE_1 0x01 /* Setup (Rising) Sample (Falling) CPOL=0, CPHA=1 */ -#define SPI_MODE_2 0x02 /* Sample (Falling) Setup (Rising) CPOL=1, CPHA=0 */ -#define SPI_MODE_3 0x03 /* Setup (Falling) Sample (Rising) CPOL=1, CPHA=1 */ - -// data direction -#define SPI_LSB 1 /* send least significant bit (bit 0) first */ -#define SPI_MSB 0 /* send most significant bit (bit 7) first */ - -// whether to raise interrupt when data received (SPIF bit received) -#define SPI_NO_INTERRUPT 0 -#define SPI_INTERRUPT 1 - -// slave or master with clock diviser -#define SPI_SLAVE 0xF0 -#define SPI_MSTR_CLK4 0x00 /* chip clock/4 */ -#define SPI_MSTR_CLK16 0x01 /* chip clock/16 */ -#define SPI_MSTR_CLK64 0x02 /* chip clock/64 */ -#define SPI_MSTR_CLK128 0x03 /* chip clock/128 */ -#define SPI_MSTR_CLK2 0x04 /* chip clock/2 */ -#define SPI_MSTR_CLK8 0x05 /* chip clock/8 */ -#define SPI_MSTR_CLK32 0x06 /* chip clock/32 */ - - - -// setup spi -void setup_spi(uint8_t mode, // timing mode SPI_MODE[0-4] - int dord, // data direction SPI_LSB|SPI_MSB - int interrupt, // whether to raise interrupt on recieve - uint8_t clock); // clock diviser - -// disable spi -void disable_spi(void); - -// send and receive a byte of data (master mode) -uint8_t send_spi(uint8_t out); - -// receive the byte of data waiting on the SPI buffer and -// set the next byte to transfer - for use in slave mode -// when interrupts are enabled. -uint8_t received_from_spi(uint8_t out); - -#ifdef __cplusplus -} // extern "C" -#endif - -#include "spi.c" - -#endif - diff --git a/Bootloader/.gitignore b/Bootloader/.gitignore new file mode 100644 index 0000000..71c9880 --- /dev/null +++ b/Bootloader/.gitignore @@ -0,0 +1,2 @@ +*.o +*.elf \ No newline at end of file diff --git a/Bootloader/Makefile b/Bootloader/Makefile new file mode 100644 index 0000000..72cf373 --- /dev/null +++ b/Bootloader/Makefile @@ -0,0 +1,66 @@ +PROJECT = MyOtaBootloader +INCLUDES = ../libraries/MySensors + +MCU = atmega328p +CLK = 16000000L + +ISP_PORT = com5 +ISP_SPEED = 115200 +ISP_PROTOCOL = stk500v2 +ISP_MCU = m328p +# HFUSE = D8 - 4096 byte boot +ISP_HFUSE = D8 +# LFUSE = 4E - Low power resonator (16MHz), fast start, clkdiv/8 +ISP_LFUSE = FF +# EFUSE = 06 - 1.8V brownout +ISP_EFUSE = 06 +ISP_ARGS = -c$(ISP_PROTOCOL) -P$(ISP_PORT) -b$(ISP_SPEED) -p$(ISP_MCU) + +ifeq ($(OS),Windows_NT) + BINPATH = C:/Program Files (x86)/Arduino/hardware/tools/avr/bin/ + JAVAPATH = C:/Program Files/Java/jdk1.7.0_40/bin/ + JAVAC = $(JAVAPATH)javac.exe + JAVA = $(JAVAPATH)java.exe +else + UNAME_S := $(shell uname -s) + UNAME_P := $(shell uname -p) + UNAME_M := $(shell uname -m) + ifeq ($(UNAME_S),Linux) + ifeq ($(UNAME_P),x86_64) + BINPATH = ../arduino/bin-linux64/bin/ + else ifneq ($(filter %86,$(UNAME_P)),) + BINPATH = ../arduino/bin-linux32/bin/ + else ifneq ($(filter arm%,$(UNAME_M)),) + BINPATH = /usr/bin/ + endif + endif +endif + +CFLAGS = -c -g -Os -fno-inline-small-functions -fno-split-wide-types -mshort-calls -Wall -mmcu=$(MCU) -DF_CPU=$(CLK) -std=gnu99 +LDFLAGS = -Os -Wl,--section-start=.text=0x7000 -nostartfiles -mmcu=$(MCU) + +all: clean out + +clean: + - rm *.o + - rm *.elf + - rm *.hex + +$(PROJECT).o: $(PROJECT).c + "$(BINPATH)avr-gcc" $(CFLAGS) -I$(INCLUDES) $< -o $@ + +$(PROJECT).elf: $(PROJECT).o + "$(BINPATH)avr-gcc" $(LDFLAGS) -o $@ $< -lm + +$(PROJECT).hex: $(PROJECT).elf + "$(BINPATH)avr-objcopy" -O ihex -R .eeprom $< $@ + +out: $(PROJECT).hex + "$(BINPATH)avr-size" $(PROJECT).elf + +load: clean out isp + +isp: $(PROJECT).hex + "$(BINPATH)avrdude" $(ISP_ARGS) -e -u -Ulock:w:0x3f:m -qq -Uefuse:w:0x$(ISP_EFUSE):m -Uhfuse:w:0x$(ISP_HFUSE):m -Ulfuse:w:0x$(ISP_LFUSE):m -Ulock:w:0x0f:m + "$(BINPATH)avrdude" $(ISP_ARGS) -V -q -s -Uflash:w:$(PROJECT).hex + "$(BINPATH)avrdude" $(ISP_ARGS) diff --git a/Bootloader/MyOtaBootloader.c b/Bootloader/MyOtaBootloader.c new file mode 100644 index 0000000..cd58712 --- /dev/null +++ b/Bootloader/MyOtaBootloader.c @@ -0,0 +1,207 @@ +#include "MyOtaBootloader.h" + +int main(void) __attribute__ ((naked)) __attribute__ ((section (".init9"))); + +volatile char dummy; + +EMPTY_INTERRUPT(WDT_vect); + +static uint16_t calcCRCrom (const void* ptr, uint16_t len) { + uint16_t crc = ~0; + for (uint16_t i = 0; i < len; ++i) + crc = _crc16_update(crc, pgm_read_byte((uint16_t) ptr + i)); + return crc; +} + +static uint8_t validFirmware () { + return calcCRCrom(0, fc.blocks * FIRMWARE_BLOCK_SIZE) == fc.crc; +} + +static void reboot() { + wdt_enable(WDTO_15MS); + for (;;); +} + +static void startup() { + if (validFirmware()) { + wdt_disable(); + clock_prescale_set(orgClockDiv); + ((void(*)()) 0)(); + } else + reboot(); +} + +static void boot_program_page(uint32_t page, uint8_t *buf) { + uint8_t sreg = SREG; + cli(); + eeprom_busy_wait(); + boot_page_erase(page); + boot_spm_busy_wait(); + for (uint16_t i = 0; i < SPM_PAGESIZE; i += 2) { + uint16_t w = *buf++; + w += (*buf++) << 8; + boot_page_fill(page + i, w); + } + boot_page_write(page); + boot_spm_busy_wait(); + boot_rww_enable(); + SREG = sreg; +} + +static boolean sendWrite(MyMessage message) { + return write(nc.parentNodeId, message.array, HEADER_SIZE + mGetLength(message), (message.destination == BROADCAST_ADDRESS)); +} + +static uint8_t sendAndWait(uint8_t reqType, uint8_t resType) { + msg.type = reqType; + for (uint8_t i = 0; i < 10; i++) { + sendWrite(msg); + for (uint16_t j = 0; j < 20; j++) { + wdt_reset(); + for (uint16_t j = 0; j < 100; j++) { + wdt_reset(); + uint8_t pipe; + boolean avail = available(&pipe); + if (avail && pipe<=6) { + read(rmsg.array,pipe); + if(!(mGetVersion(rmsg) == PROTOCOL_VERSION)) + continue; + if (rmsg.destination == nc.nodeId) { + if (mGetCommand(rmsg) == C_INTERNAL) { + if (rmsg.type == I_FIND_PARENT_RESPONSE) { + if (rmsg.data[0] < nc.distance - 1) { + nc.distance = rmsg.data[0] + 1; + nc.parentNodeId = rmsg.sender; + eeprom_write_byte((uint8_t*)EEPROM_PARENT_NODE_ID_ADDRESS, nc.parentNodeId); + eeprom_write_byte((uint8_t*)EEPROM_DISTANCE_ADDRESS, nc.distance); + } + } + } + if ((mGetCommand(rmsg) == mGetCommand(msg)) && (rmsg.type == resType)) + return 1; + } + } + delaym(1); + } + } + } + return 0; +} + +int main () { + asm volatile ("clr __zero_reg__"); + // switch to 4 MHz + orgClockDiv = clock_prescale_get(); + clock_prescale_set(F_CPU_DIV); + MCUSR = 0; + // enable watchdog to avoid deadlock + wdt_enable(WDTO_8S); + +#ifdef LED_DEBUG + // enable LEDs for debugging and blink once as visual "bootloader started" sign + led_init(); + blink(LED_MBOTH, 250); +#endif +#ifdef UART_DEBUG + // enable UART for debugging and send start message + uart_init(); + uart_puts("Go\n"); +#endif + + wdt_reset(); + // initialize RF module + begin(); + wdt_reset(); + // Read settings from EEPROM + eeprom_read_block((void*)&nc, (void*)EEPROM_NODE_ID_ADDRESS, sizeof(struct NodeConfig)); + wdt_reset(); + + msg.sender = nc.nodeId; + msg.last = nc.nodeId; + address(nc.nodeId); + + msg.sensor = NODE_SENSOR_ID; + mSetLength(msg, 0); + mSetPayloadType(msg, P_STRING); + mSetAck(msg,false); + mSetVersion(msg, PROTOCOL_VERSION); + + nc.distance = 255; + mSetCommand(msg, C_INTERNAL); + msg.destination = BROADCAST_ADDRESS; + if (!sendAndWait(I_FIND_PARENT, I_FIND_PARENT_RESPONSE)) +// starting existing firmware if no parent responds (if firmware is valid) +// reboot(); + startup(); + + msg.destination = GATEWAY_ADDRESS; + + if (nc.nodeId == AUTO) { + openReadingPipe(CURRENT_NODE_PIPE, TO_ADDR(nc.nodeId)); + if (!sendAndWait(I_ID_REQUEST, I_ID_RESPONSE)) + reboot(); + if (mGetPayloadType(rmsg) == P_BYTE) + nc.nodeId = rmsg.data[0]; + else if (mGetPayloadType(rmsg) == P_STRING) + nc.nodeId = atoi(rmsg.data); + if (nc.nodeId == AUTO) + reboot(); + eeprom_write_byte((uint8_t*)EEPROM_NODE_ID_ADDRESS, nc.nodeId); + msg.sender = nc.nodeId; + msg.last = nc.nodeId; + address(nc.nodeId); + } + + // Read settings from EEPROM + eeprom_read_block((void*)&fc, (void*)EEPROM_FIRMWARE_TYPE_ADDRESS, sizeof(struct FirmwareConfig)); + + mSetPayloadType(msg,P_CUSTOM); + + FirmwareConfigRequest *firmwareConfigRequest = (FirmwareConfigRequest *)msg.data; + mSetLength(msg, sizeof(FirmwareConfigRequest)); + mSetCommand(msg, C_STREAM); + firmwareConfigRequest->type = fc.type; + firmwareConfigRequest->version = fc.version; + if (!sendAndWait(ST_FIRMWARE_CONFIG_REQUEST, ST_FIRMWARE_CONFIG_RESPONSE)) +// starting existing firmware if no firmware config response (if firmware is valid) +// reboot(); + startup(); + FirmwareConfigResponse *firmwareConfigResponse = (FirmwareConfigResponse *)rmsg.data; + if (firmwareConfigResponse->version == fc.version) + if (firmwareConfigResponse->blocks == fc.blocks) + if (firmwareConfigResponse->crc == fc.crc) + if (validFirmware()) + startup(); + fc.type = firmwareConfigResponse->type; + fc.version = firmwareConfigResponse->version; + fc.blocks = firmwareConfigResponse->blocks; + fc.crc = firmwareConfigResponse->crc; + + FirmwareRequest *firmwareRequest = (FirmwareRequest *)msg.data; + mSetLength(msg, sizeof(FirmwareRequest)); + firmwareRequest->type = fc.type; + firmwareRequest->version = fc.version; + for (uint16_t block = 0; block < fc.blocks; block++) { + firmwareRequest->block = block; + if (!sendAndWait(ST_FIRMWARE_REQUEST, ST_FIRMWARE_RESPONSE)) + reboot(); + FirmwareResponse *firmwareResponse = (FirmwareResponse *)rmsg.data; + uint8_t offset = (block * FIRMWARE_BLOCK_SIZE) % SPM_PAGESIZE; + memcpy(progBuf + offset, firmwareResponse->data, FIRMWARE_BLOCK_SIZE); + if (offset == SPM_PAGESIZE - FIRMWARE_BLOCK_SIZE) + boot_program_page((block * FIRMWARE_BLOCK_SIZE) - offset, progBuf); + } + + wdt_reset(); + + if (validFirmware()) { + eeprom_write_block((void*)&fc, (void*)EEPROM_FIRMWARE_TYPE_ADDRESS, sizeof(struct FirmwareConfig)); +#ifdef UART_DEBUG + uart_puts("fw ok\n"); + } else { + uart_puts("fw nok\n"); +#endif + } + + reboot(); +} diff --git a/Bootloader/MyOtaBootloader.h b/Bootloader/MyOtaBootloader.h new file mode 100644 index 0000000..d906370 --- /dev/null +++ b/Bootloader/MyOtaBootloader.h @@ -0,0 +1,67 @@ +#ifndef MyOtaBootloader_H +#define MyOtaBootloader_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "MyMessage.h" +#include "MySensor.h" +#include "MyOtaBootloaderRF24.h" + +#define FIRMWARE_BLOCK_SIZE 16 + +struct FirmwareConfig +{ + uint16_t type; + uint16_t version; + uint16_t blocks; + uint16_t crc; +}; + +typedef struct +{ + uint16_t type; + uint16_t version; +} FirmwareConfigRequest; + +typedef struct +{ + uint16_t type; + uint16_t version; + uint16_t blocks; + uint16_t crc; +} FirmwareConfigResponse; + +typedef struct +{ + uint16_t type; + uint16_t version; + uint16_t block; +} FirmwareRequest; + +typedef struct +{ + uint16_t type; + uint16_t version; + uint16_t block; + uint8_t data[FIRMWARE_BLOCK_SIZE]; +} FirmwareResponse; + +static struct NodeConfig nc; +static struct FirmwareConfig fc; +static MyMessage msg; +static MyMessage rmsg; + +static clock_div_t orgClockDiv = 0; + +static uint8_t progBuf[SPM_PAGESIZE]; + +#endif // MyOtaBootloader_H diff --git a/Bootloader/MyOtaBootloader.hex b/Bootloader/MyOtaBootloader.hex new file mode 100644 index 0000000..6fd8c58 --- /dev/null +++ b/Bootloader/MyOtaBootloader.hex @@ -0,0 +1,214 @@ +:1070000011E0A0E0B1E0E0E4FDE702C005900D92E0 +:10701000A030B107D9F711E0A0E0B1E001C01D92A6 +:10702000A83DB107E1F711248091610090E08F70D5 +:107030009070909301018093000182E090E020E83D +:107040000FB6F89420936100809361000FBE14BEC8 +:1070500029E288E190E00FB6F894A895809360004B +:107060000FBE20936000A8951092CF011092D0011E +:107070001092D1011092D2011092D3011092D4013A +:107080001092D5011092D60184B18E6284B92498F1 +:1070900085B1857D85B92A9A8AE090E0B3D184E0F4 +:1070A0006FE520D281E06BE31DD285E06CE41AD25B +:1070B00086E0E5D1682F607D676286E013D280E0CC +:1070C000DED1682F6C6080E00DD287E060E70AD2E5 +:1070D0002A9881E090E096D180E5A6D183E7A4D1FB +:1070E0002A9A81E090E08ED18DE1C9D1682F666047 +:1070F0008DE1F8D18CE1C3D1682F6F638CE1F2D1BF +:1071000082EEADD181EEABD104D280E0B8D1682F50 +:107110006E7F80E0E7D182E00FEF1CEF21EE38EACE +:1071200048EA50E060E070E002D2A89582E091E089 +:1071300060E070E043E050E02DEE39E38AD5A89599 +:107140008091020180930E0180930D014FD22FEFA9 +:10715000209313018091110192E0909310012093EC +:107160000401887083608093110120930F0187E0F0 +:1071700068E04AD3882309F42AD310920F01809142 +:1071800002018F3F09F038C081E00FEF1CEF21EEC4 +:1071900038EA48EA50E060E070E0C9D183E064E09A +:1071A00033D3882309F407D38091320182958695E1 +:1071B0008770813019F48091350105C0882329F446 +:1071C00085E391E028D580930201809102018F3FF1 +:1071D00009F4F1D280910201F999FECF1FBA12BCD5 +:1071E00011BC80BD0FB6F894FA9AF99A0FBE80933D +:1071F0000E0180930D01FAD185E091E06BE171E021 +:1072000048E050E02DEE39E324D5909111019871BA +:10721000809110018770806280931001946C90932C +:1072200011018091050190910601909315018093C1 +:1072300014018091070190910801909317018093A8 +:10724000160180E061E0E0D2882309F4C0D22091E9 +:10725000370130913801809107019091080128177A +:107260003907C9F42091390130913A01809109011F +:1072700090910A012817390771F420913B01309150 +:107280003C0180910B0190910C012817390719F4EA +:107290005DD281119CD240913501509136015093BD +:1072A0000601409305012091370130913801309358 +:1072B0000801209307018091390190913A01909340 +:1072C0000A018093090180913B0190913C019093C8 +:1072D0000C0180930B01F4E1EF2EF1E0FF2E809181 +:1072E00010018770806380931001509315014093C3 +:1072F00014013093170120931601C0E0D0E000E99B +:107300001FEFBB24B394E5E0CE2E71E1D72E4DC024 +:10731000F701D583C48382E063E076D2882309F441 +:107320004AD2902F90599F77E92FF0E0E15BFE4F12 +:10733000ABE3B1E080E10D9001928150E1F790372D +:1073400009F030C03FB7F894F999FECF83E0F80117 +:1073500080935700E89507B600FCFDCFA801AFE485 +:10736000B1E02C9111968C91119790E0982F88277D +:10737000820F911D1296FA010C01B0925700E89508 +:1073800011244E5F5F4FF1E0AF3CBF0751F7F801AA +:10739000C0925700E89507B600FCFDCFD092570089 +:1073A000E8953FBF2196005F1F4F809109019091A2 +:1073B0000A01C817D90708F4ABCFA895C7D188230D +:1073C00049F08BE191E065E071E048E050E024EFA6 +:1073D00039E35BD4F0D180E090E0F999FECF92BD23 +:1073E00081BDF89A80B50895F999FECF1FBA92BD74 +:1073F00081BD60BD0FB6F894FA9AF99A0FBE089550 +:107400000000089540E050E00BC020E030E00000B4 +:107410002F5F3F4F61E0243F3607C9F74F5F5F4F53 +:107420004817590790F308950F931F93182F00E002 +:10743000E7DF17FD02C02B9801C02B9AE1DF2D9AE0 +:1074400083B1110F82958170182BDADF2D98D8DF68 +:107450000F5F083069F7812F1F910F9108951F93D7 +:10746000182F2A9881E090E0CDDF812FDDDF182FE3 +:107470002A9A81E090E0C6DF812F1F9108951F9323 +:10748000182F2A9881E090E0BDDF812F8F71CCDF2B +:107490008FEFCADF182F2A9A81E090E0B3DF812FA7 +:1074A0001F9108950F931F93CF93DF93182FEB0134 +:1074B000042F2A9881E090E0A5DF1F71812F806260 +:1074C000B3DF182F03C08991AFDF01500023D9F734 +:1074D0002A9A81E090E096DF812FDF91CF911F9172 +:1074E0000F9108950F931F93182F062F2A9881E06C +:1074F00090E088DF1F71812F806296DF182F802F28 +:1075000093DF2A9A81E090E07DDF812F1F910F9118 +:10751000089580E0B4DF81FD09C080E0B0DF682F0E +:10752000626080E0DFDF85E090E06CDF08957F92AD +:107530008F929F92AF92BF92CF92DF92EF92FF9283 +:107540000F931F93DF93CF93CDB7DEB728970FB676 +:10755000F894DEBF0FBECDBF782E480159016A01F5 +:107560007B01882381F40093CF019092D001209376 +:10757000D101B092D2014093D301D092D401609353 +:10758000D501F092D60189829A82AB82BC82CD82EB +:10759000DE82EF82F88681E0871538F0872D865FDE +:1075A000BE016F5F7F4F45E07DDF82E068DF21E055 +:1075B00030E002C0220F331F7A94E2F7682F622B6B +:1075C00082E090DF28960FB6F894DEBF0FBECDBFE5 +:1075D000CF91DF911F910F91FF90EF90DF90CF90AF +:1075E000BF90AF909F908F907F9008957F928F92E1 +:1075F0009F92AF92BF92CF92DF92EF92FF920F9342 +:107600001F93DF93CF93CDB7DEB728970FB6F894CB +:10761000DEBF0FBECDBF8F3F09F483C0082F10E03F +:1076200020E030E040E050E060E070E089831A83C1 +:107630002B833C834D835E836F83788788243CEF64 +:10764000932E21EEA22E98EAB92E88EAC82EDD24C8 +:10765000EE24FF24080D81E09981091708F080E0ED +:10766000192D91E0AA819A1608F090E0E82FE10F19 +:1076700081E0E11708F080E0982B1E2F2A2D772457 +:107680007394BB81AB1608F07724920F81E09217B8 +:1076900008F080E0782A292F3B2D91E0EC81BE167E +:1076A00008F090E0E72DE30F81E0E31708F080E0B9 +:1076B000982B3E2F4C2D77247394FD81CF1608F024 +:1076C0007724940F81E0941708F080E0782A492FFE +:1076D0005D2D91E08E81D81608F090E0E72DE50F42 +:1076E00081E0E51708F080E0982B5E2F6E2D77245F +:1076F0007394AF81EA1608F07724960F81E096170D +:1077000008F080E0782A692F7F0C772D59016A01F3 +:10771000E92E80E00CDF81E09501A6016E2D772D2A +:1077200006DF28960FB6F894DEBF0FBECDBFCF910F +:10773000DF911F910F91FF90EF90DF90CF90BF905E +:10774000AF909F908F907F90089518954091090178 +:1077500050910A0164E0440F551F6A95E1F7E0E09B +:10776000F0E02FEF3FEF19C084912827822F8295F8 +:107770008227082E869586958025082E8695802559 +:107780008770022E232F869507948795302D282702 +:1077900006948795302528273196E417F50720F3BE +:1077A00040E080910B0190910C012817390709F4F2 +:1077B00041E0842F089528E088E190E00FB6F89426 +:1077C000A895809360000FBE20936000FFCFBEDFBE +:1077D0008823C1F088E10FB6F8948093600010927E +:1077E00060000FBE809100019091010120E80FB66A +:1077F000F89420936100809361000FBEE0E0F0E018 +:1078000009950895D8DF08952F923F924F925F9285 +:107810006F927F928F929F92AF92BF92CF92DF92A0 +:10782000EF92FF920F931F93DF93CF93CDB7DEB705 +:10783000E3970FB6F894DEBF0FBECDBF6BA7809362 +:1078400012016624B9E02B2E312C2C0E3D1E2E0188 +:107850000894411C511CD101EDE0F1E081E201905E +:107860000D928150E1F7109103017C842B852AA7AA +:1078700050DE299881E090E0C5DD81EEF0DD82EEFA +:10788000EEDD80E0FCDD682F6E7F80E02BDE30E0F7 +:1078900040E050E060E070E080E090E01CA73DA791 +:1078A0004EA75FA768AB79AB8AAB9BAB8824ACEFE4 +:1078B0009A2EF1EEAF2EE8EABE2E78EAC72EDD242E +:1078C000EE24FF24012F080D81E0011708F080E06D +:1078D000192D91E0EDA59E1608F090E0E82FE10F3C +:1078E00081E0E11708F080E0982B1E2F2A2DE1E0BF +:1078F000FEA5AF1608F0E0E0920F81E0921708F0C5 +:1079000080E0E82B292F3B2D91E08FA5B81608F0D9 +:1079100090E0E30F81E0E31708F080E0982B3E2F22 +:107920004C2DE1E0F8A9CF1608F0E0E0940F81E0DB +:10793000941708F080E0E82B492F5D2D91E089A98C +:10794000D81608F090E0E50F81E0E51708F080E038 +:10795000982B5E2F6E2D81E0EAA9EE1608F080E0EC +:10796000E92FE60F91E0E61708F090E0892B8F0DE4 +:1079700009831A832B833C834D835E83EF8388873F +:107980008AE0B20145E08EDD80E1B20145E08ADDAA +:10799000FAA5FF3F11F010EA01C010EB769476943F +:1079A000769427E0720E2A9881E090E02BDD812FFB +:1079B0003BDD81017101E70CF11C04C0F8018191EC +:1079C0008F0132DD0E151F05C9F72A9A81E090E07C +:1079D00019DD299A81E090E015DD299881E090E099 +:1079E00011DD8FEF3CDD8073E1F387E060E77ADD46 +:1079F00084FF02C081EE33DD8CDD80E040DD682F46 +:107A0000616080E06FDD87E060E76CDD0091CF01B1 +:107A10001091D0012091D1013091D2014091D30138 +:107A20005091D4016091D5017091D601802F812BA6 +:107A3000822B832B842B852B862B872B61F009834C +:107A40001A832B833C834D835E836F8378878AE020 +:107A5000B20145E027DD82EE02DD81EE00DD299AEC +:107A600081E090E0CFDCAA24BB24A895CC24DD24BF +:107A7000A89587E104DD80FD9CC08FEFF0DCE82E47 +:107A8000E694F7E0EF22EF1609F493C02A9881E01C +:107A900090E0B8DC80E6C8DC8FEFC6DCF82E2A9ACE +:107AA00081E090E0AFDC20E22F1518F482EED7DC05 +:107AB000FF242A9881E090E0A5DC81E6B5DC0EE2A7 +:107AC00011E006C08FEFB0DCF80181938F01FA94CA +:107AD000FF20C1F72A9A81E090E094DC87E060E71C +:107AE00001DD2A9881E090E08DDC8E2D886A9CDC97 +:107AF0008E2D9ADC2A9A81E090E084DC809131011D +:107B00008770823009F058C0909130018091020155 +:107B1000981709F04EC080913201682F70E0CB01B8 +:107B200087709070039709F034C0809133018830DA +:107B300009F02FC040913501242F332727FD3095C0 +:107B40008091040190E001972817390714F5242F3C +:107B50002F5F2093040140912F0140930301F99975 +:107B6000FECF1FBA81E090E092BD81BD40BD0FB64F +:107B7000F894FA9AF99A0FBEF999FECF1FBA42E02B +:107B800050E052BD41BD20BD0FB6F894FA9AF99A63 +:107B90000FBE8091110190E0862797278770907023 +:107BA000892B39F4809133015BA5851711F481E0AD +:107BB00019C081E090E026DC0894C11CD11C64E669 +:107BC000C616D10409F054CF0894A11CB11C74E16D +:107BD000A716B10409F049CF63948AE0681609F04A +:107BE0003ACE80E0E3960FB6F894DEBF0FBECDBF6D +:107BF000CF91DF911F910F91FF90EF90DF90CF9089 +:107C0000BF90AF909F908F907F906F905F904F90BC +:107C10003F902F900895FC0188279927E89421919F +:107C20002032E9F3293010F02E30C8F32B3241F026 +:107C30002D3239F4689404C00E94613E820F911D78 +:107C4000219120532A30C0F31EF4909581959F4FC7 +:107C50000895A0E0B0E0EFE2FEE30C94733E7C01F7 +:107C6000EB018A01690109C0CE012196F60109954F +:107C7000F70181937F010150104001151105A1F713 +:107C8000CDB7DEB7E8E00C948F3EA0E0B0E0EBE4C7 +:107C9000FEE30C94733EEC017B018A01690109C08B +:107CA000CE012196F70161917F01F60109950150FE +:107CB000104001151105A1F7CDB7DEB7E8E00C942F +:107CC0008F3E7AE0979F902D879F802D910D1124F4 +:107CD00008952F923F924F925F926F927F928F9270 +:107CE0009F92AF92BF92CF92DF92EF92FF920F934B +:107CF0001F93CF93DF93CDB7DEB7CA1BDB0B0FB655 +:107D0000F894DEBF0FBECDBF09942A883988488811 +:107D10005F846E847D848C849B84AA84B984C884A7 +:107D2000DF80EE80FD800C811B81AA81B981CE0F9E +:107D3000D11D0FB6F894DEBF0FBECDBFED01089583 +:040000030000700089 +:00000001FF diff --git a/Bootloader/MyOtaBootloaderHW.h b/Bootloader/MyOtaBootloaderHW.h new file mode 100644 index 0000000..2eec57b --- /dev/null +++ b/Bootloader/MyOtaBootloaderHW.h @@ -0,0 +1,154 @@ +#ifndef MyOtaBootloaderHW_H +#define MyOtaBootloaderHW_H + +#include +#include + +//#define LED_DEBUG +//#define UART_DEBUG + +// hardware +// ******** + +#define F_CPU_DIV clock_div_4 +#define F_CPU_REAL F_CPU / (1 << F_CPU_DIV) +#define UART_BAUD 9600UL +#define DELAY_M 125 * (1 << F_CPU_DIV) + +// boolean definition +// ****************** + +typedef uint8_t bool; +typedef uint8_t boolean; +#define false 0x0 +#define true 0x1 +#define LOW 0x0 +#define HIGH 0x1 + +// delay +// ***** + +static void delayu() { + asm("nop"); +} + +static void delaym(uint16_t t) { + uint16_t d, a; + for (d = 0; d < t; d++) + for (a = 0; a < DELAY_M; a++) + asm("nop"); +} + +// LED debug +// ********* + +#ifdef LED_DEBUG +#define LED_DDR DDRD +#define LED_PORT PORTD +#define LED_RED 6 // Arduino Pin 6 <-> Bit 6 of port D +#define LED_GREEN 7 // Arduino Pin 7 <-> Bit 7 of port D +#define LED_MRED (1 << LED_RED) +#define LED_MGREEN (1 << LED_GREEN) +#define LED_MBOTH (LED_MRED | LED_MGREEN) + +static void led_init() { + LED_DDR |= LED_MBOTH; + LED_PORT &= ~LED_MBOTH; +} + +static void blink(uint8_t mask, uint16_t time) { + LED_PORT |= mask; + if (time > 0) + { + delaym(time); + LED_PORT &= ~mask; + delaym(time); + } +} +#endif + +// UART debug +// ********** + +#ifdef UART_DEBUG +static void uart_init() +{ + UCSR0A = _BV(U2X0); //Double speed mode USART0 + UCSR0B = _BV(RXEN0) | _BV(TXEN0); + UCSR0C = _BV(UCSZ00) | _BV(UCSZ01); + UBRR0L = (uint8_t)( (F_CPU_REAL + UART_BAUD * 4L) / (UART_BAUD * 8L) - 1 ); +} + +static void uart_putc(char ch) { + while (!(UCSR0A & _BV(UDRE0))); + UDR0 = ch; +} + +static void uart_puts(char *s) +{ + while (*s) + uart_putc(*s++); +} + +static void uart_puti(uint8_t i) +{ + char s[5]; + itoa( i, s, 10 ); + uart_puts( s ); +} +#endif + +// SPI communication +// ***************** + +#define SPI_DDR DDRB +#define SPI_PORT PORTB +#define SPI_PIN PINB +#define SPI_SCLK 5 // Arduino Pin 13 <-> Bit 5 of port B +#define SPI_MISO 4 // Arduino Pin 12 <-> Bit 4 of port B +#define SPI_MOSI 3 // Arduino Pin 11 <-> Bit 3 of port B +#define SPI_CSN 2 // Arduino Pin 10 <-> Bit 2 of port B +#define SPI_CE 1 // Arduino Pin 9 <-> Bit 1 of port B + +#define csnlow() SPI_PORT &= ~(1<> SPI_MISO) & 0x01); // capture current MISO bit + delayu(); + SPI_PORT &= ~(1 << SPI_SCLK); + delayu(); + } + return value; +} + +static uint8_t spiTrans(uint8_t cmd){ + uint8_t status; + csnlow(); + status = SPItransfer( cmd ); + csnhigh(); + return status; +} + +#endif // MyOtaBootloaderHW_H diff --git a/Bootloader/MyOtaBootloaderRF24.h b/Bootloader/MyOtaBootloaderRF24.h new file mode 100644 index 0000000..fa2495c --- /dev/null +++ b/Bootloader/MyOtaBootloaderRF24.h @@ -0,0 +1,253 @@ +#ifndef MyOtaBootloaderRF24_H +#define MyOtaBootloaderRF24_H + +#include "MyOtaBootloaderHW.h" +#include "../libraries/MySensors/utility/nRF24L01.h" + +#include + +// hardware-agnostic interface to transceiver +// ****************************************** +// static void begin() +// static void address(uint8_t addr) +// static boolean write(uint8_t next, uint8_t* packet, uint8_t length, boolean multicast) +// static bool available(uint8_t* pipe_num) +// static void read(uint8_t* buf, uint8_t pipe) + +typedef enum { RF24_PA_MIN = 0,RF24_PA_LOW, RF24_PA_HIGH, RF24_PA_MAX, RF24_PA_ERROR } rf24_pa_dbm_e ; +typedef enum { RF24_1MBPS = 0, RF24_2MBPS, RF24_250KBPS } rf24_datarate_e; + +uint64_t pipe0_reading_address; /**< Last address set on pipe 0 for reading. */ + +static uint8_t read_register(uint8_t reg) +{ + csnlow(); + SPItransfer( R_REGISTER | ( REGISTER_MASK & reg ) ); + uint8_t result = SPItransfer(0xff); + csnhigh(); + return result; +} + +static uint8_t write_registers(uint8_t reg, const uint8_t* buf, uint8_t len) +{ + uint8_t status; + csnlow(); + status = SPItransfer( W_REGISTER | ( REGISTER_MASK & reg ) ); + while ( len-- ) + SPItransfer(*buf++); + csnhigh(); + return status; +} + +static uint8_t write_register(uint8_t reg, uint8_t value) +{ + uint8_t status; + csnlow(); + status = SPItransfer( W_REGISTER | ( REGISTER_MASK & reg ) ); + SPItransfer(value); + csnhigh(); + return status; +} + +static uint8_t read_payload(uint8_t* buf, uint8_t data_len) +{ +#ifdef UART_DEBUG + uart_puts("-> "); +#endif + uint8_t status; + uint8_t* current = buf; + csnlow(); + status = SPItransfer( R_RX_PAYLOAD ); + while ( data_len-- ) { + *current = SPItransfer(0xFF); +#ifdef UART_DEBUG + uart_puti(*current); + uart_putc(','); +#endif + current++; + } + csnhigh(); +#ifdef UART_DEBUG + uart_putc('\n'); +#endif + return status; +} + +#define get_status() spiTrans(NOP) + +static void powerUp(void) +{ + if (!(read_register(CONFIG) & _BV(PWR_UP))){ + write_register(CONFIG,read_register(CONFIG) | _BV(PWR_UP)); + delaym(5); + } +} + +#define convert_64_bit_to_byte_array(value, data) ((*(uint64_t *)(data)) = (uint64_t)(value)) + +static void startListening(void) +{ + powerUp(); + write_register(CONFIG, read_register(CONFIG) | _BV(PRIM_RX)); + write_register(STATUS, _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); + if (pipe0_reading_address){ + uint8_t addressa[8]; + convert_64_bit_to_byte_array(pipe0_reading_address, addressa); + write_registers(RX_ADDR_P0, addressa, 5); + } + spiTrans(FLUSH_RX); + spiTrans(FLUSH_TX); + cehigh(); +} + +static void stopListening(void) +{ + celow(); + spiTrans(FLUSH_TX); + spiTrans(FLUSH_RX); + write_register(CONFIG, read_register(CONFIG) & ~_BV(PRIM_RX)); +} + +static void write_payload(const uint8_t* buf, uint8_t data_len, const uint8_t writeType) +{ +#ifdef UART_DEBUG + uart_puts("<- "); +#endif + const uint8_t* current = buf; + csnlow(); + SPItransfer(writeType); + while ( data_len-- ) { +#ifdef UART_DEBUG + uart_puti(*current); + uart_putc(','); +#endif + SPItransfer(*current++); + } + csnhigh(); +#ifdef UART_DEBUG + uart_putc('\n'); +#endif +} + +static bool writem( const uint8_t* buf, uint8_t len, const bool multicast ) +{ + write_payload( buf, len, multicast ? W_TX_PAYLOAD_NO_ACK : W_TX_PAYLOAD) ; + cehigh(); + celow(); + while( ! ( get_status() & ( _BV(TX_DS) | _BV(MAX_RT) ))) { } + uint8_t status = write_register(STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); + if( status & _BV(MAX_RT)){ + spiTrans(FLUSH_TX); + return 0; + } + return 1; +} + +static uint8_t getDynamicPayloadSize(void) +{ + uint8_t result = 0; + csnlow(); + SPItransfer( R_RX_PL_WID ); + result = SPItransfer(0xff); + csnhigh(); + if(result > 32) { + spiTrans(FLUSH_RX); + return 0; + } + return result; +} + +static bool available(uint8_t* pipe_num) +{ + if (!(read_register(FIFO_STATUS) & _BV(RX_EMPTY) )){ + if (pipe_num) { + uint8_t status = get_status(); + *pipe_num = ( status >> RX_P_NO ) & 0b111; + } + return 1; + } + return 0; +} + +static void writeAckPayload(uint8_t pipe, const uint8_t* buf, uint8_t len) +{ + const uint8_t* current = buf; + uint8_t data_len = len; + csnlow(); + SPItransfer(W_ACK_PAYLOAD | ( pipe & 0b111 ) ); + while ( data_len-- ) + SPItransfer(*current++); + csnhigh(); +} + +static void read( uint8_t* buf, uint8_t pipe ){ + read_payload(buf, getDynamicPayloadSize()); + write_register(STATUS,_BV(RX_DR) | _BV(MAX_RT) | _BV(TX_DS)); + writeAckPayload(pipe,&pipe, 1 ); +} + +static void openWritingPipe(uint64_t value) +{ + uint8_t valuea[8]; + convert_64_bit_to_byte_array(value, valuea); + write_registers(RX_ADDR_P0, valuea, 5); + write_registers(TX_ADDR, valuea, 5); +} + +static void openReadingPipe(uint8_t child, uint64_t address) +{ + if (child == 0) + pipe0_reading_address = address; + uint8_t addressa[8]; + convert_64_bit_to_byte_array(address, addressa); + if ( child < 2 ) + write_registers(RX_ADDR_P0 + child, addressa, 5); + write_register(EN_RXADDR,read_register(EN_RXADDR) | _BV(ERX_P0 + child)); +} + +static boolean write(uint8_t next, uint8_t* packet, uint8_t length, boolean multicast) { + powerUp(); + stopListening(); + openWritingPipe(TO_ADDR(next)); + bool ok = writem(packet, length, multicast); + startListening(); + return ok; +} + +static void address(uint8_t addr) +{ + if (addr != BROADCAST_ADDRESS) { + openReadingPipe(WRITE_PIPE, TO_ADDR(addr)); + openReadingPipe(CURRENT_NODE_PIPE, TO_ADDR(addr)); + } +} + +static void begin(void) +{ + pipe0_reading_address = 0; + + SPIinit(); + delaym( 10 ) ; + + write_register(SETUP_RETR, 5 << ARD | 15 << ARC); + write_register(EN_AA, 0b00111111 & ~_BV(BROADCAST_PIPE)) ; + write_register(RF_CH, RF24_CHANNEL); + write_register(RF_SETUP, (read_register(RF_SETUP) & 0b11010000) | ((RF24_PA_LEVEL << 1) + 1) | ((RF24_DATARATE & 0b00000010 ) << 4) | ((RF24_DATARATE & 0b00000001 ) << 3)); + write_register(CONFIG, read_register(CONFIG) | _BV(CRCO) | _BV(EN_CRC)) ; + write_register(STATUS, _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT)); + + csnlow(); + SPItransfer(ACTIVATE); + SPItransfer(0x73); + csnhigh(); + write_register(FEATURE, read_register(FEATURE) | _BV(EN_ACK_PAY) | _BV(EN_DPL) ); + write_register(DYNPD, read_register(DYNPD) | _BV(DPL_P5) | _BV(DPL_P4) | _BV(DPL_P3) | _BV(DPL_P2) | _BV(DPL_P1) | _BV(DPL_P0)); + + spiTrans(FLUSH_RX); + spiTrans(FLUSH_TX); + + powerUp(); //Power up by default when begin() is called + write_register(CONFIG, read_register(CONFIG) & ~_BV(PRIM_RX)); + openReadingPipe(BROADCAST_PIPE, TO_ADDR(BROADCAST_ADDRESS)); +} +#endif // MyOtaBootloaderRF24_H diff --git a/Bootloader/Readme.md b/Bootloader/Readme.md new file mode 100644 index 0000000..b6d7e33 --- /dev/null +++ b/Bootloader/Readme.md @@ -0,0 +1,47 @@ +See NodeJsController/Readme.md for usage instructions... + +

Technical details to write your own controller

+All initialization the bootloader does (finding parent / requesting nodeId on first start) uses the same packets as a normal MySensors sketch. There is no need for the controller to distinguish between packets from the bootloader and packets from normal sketch execution. The controller only needs to care about two additional request/response communications. All communication is binary. +

FirmwareConfig

+
    +
  • the bootloader sends a FirmwareConfigRequest packet to the gateway to request information about the firmware it should execute: +

    +typedef struct
    +{
    + uint16_t type;
    + uint16_t version;
    +} FirmwareConfigRequest; +

    +
  • the gateway (the controller) responds with a FirmwareConfigResponse including details about the firmware the sensor should execute: +

    +typedef struct
    +{
    + uint16_t type;
    + uint16_t version;
    + uint16_t blocks;
    + uint16_t crc;
    +} FirmwareConfigResponse; +

    +
+

Firmware

+
    +
  • the bootloader sends a FirmwareRequest packet to the gateway to request a specific subset (block) of the compiled firmware: +

    +typedef struct
    +{
    + uint16_t type;
    + uint16_t version;
    + uint16_t block;
    +} FirmwareRequest; +

    +
  • the gateway (the controller) responds with a FirmwareResponse including the specific block of the compiled firmware: +
+

+typedef struct
+{
+ uint16_t type;
+ uint16_t version;
+ uint16_t block;
+ uint8_t data[FIRMWARE_BLOCK_SIZE];
+} FirmwareResponse; +

diff --git a/NodeJsController/DropDb.js b/NodeJsController/DropDb.js new file mode 100644 index 0000000..128168b --- /dev/null +++ b/NodeJsController/DropDb.js @@ -0,0 +1,17 @@ +const dbAddress = '127.0.0.1'; +const dbPort = 27017; +const dbName = 'MySensorsDb'; + +var dbc = require('mongodb').MongoClient; +dbc.connect('mongodb://' + dbAddress + ':' + dbPort + '/' + dbName, function(err, db) { + if (err) { + console.log('Error connecting to database at mongodb://' + dbAddress + ':' + dbPort + '/' + dbName); + } else { + db.dropDatabase(function(err, result) { + if (err) + console.log('Error dropping database at mongodb://' + dbAddress + ':' + dbPort + '/' + dbName); + else + console.log('Successfully dropped database at mongodb://' + dbAddress + ':' + dbPort + '/' + dbName); + }); + } +}); diff --git a/NodeJsController/MySensors.sh b/NodeJsController/MySensors.sh new file mode 100644 index 0000000..99bf500 --- /dev/null +++ b/NodeJsController/MySensors.sh @@ -0,0 +1,8 @@ +#!/bin/sh +# pidfile must be first argument +PIDFILE=$1 +mkdir -p /home/pi/logs +cd /home/pi/Arduino/NodeJsController +/opt/node/bin/node NodeJsController.js >>/home/pi/logs/NodeJsController.log 2>&1 $PIDFILE diff --git a/NodeJsController/MySensorsInitScript.sh b/NodeJsController/MySensorsInitScript.sh new file mode 100644 index 0000000..38a9feb --- /dev/null +++ b/NodeJsController/MySensorsInitScript.sh @@ -0,0 +1,160 @@ +#! /bin/sh +### BEGIN INIT INFO +# Provides: mysensors +# Required-Start: $remote_fs $syslog $mongodb +# Required-Stop: $remote_fs $syslog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: MySensors NodeJs Controller +# Description: MySensors NodeJs Controller +### END INIT INFO + +# Author: Foo Bar +# +# Please remove the "Author" lines above and replace them +# with your own name if you copy and modify this script. + +# Do NOT "set -e" + +# PATH should only include /usr/* if it runs after the mountnfs.sh script +PATH=/sbin:/usr/sbin:/bin:/usr/bin +DESC="MySensors NodeJs Controller" +NAME="MySensors.sh" +PIDFILE="/usr/local/var/run/$NAME.pid" +DAEMON="/home/pi/Arduino/NodeJsController/$NAME" +DAEMON_ARGS="$PIDFILE" +DAEMON_USER="pi" +SCRIPTNAME=/etc/init.d/$NAME + +# Exit if the package is not installed +[ -x "$DAEMON" ] || exit 0 + +# Read configuration variable file if it is present +[ -r /etc/default/$NAME ] && . /etc/default/$NAME + +# Load the VERBOSE setting and other rcS variables +. /lib/init/vars.sh + +# Define LSB log_* functions. +# Depend on lsb-base (>= 3.2-14) to ensure that this file is present +# and status_of_proc is working. +. /lib/lsb/init-functions + +# +# Function that starts the daemon/service +# +do_start() +{ + # Return + # 0 if daemon has been started + # 1 if daemon was already running + # 2 if daemon could not be started + start-stop-daemon --start --quiet --chuid $DAEMON_USER --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \ + || return 1 + start-stop-daemon --start --quiet --chuid $DAEMON_USER --pidfile $PIDFILE --exec $DAEMON -- \ + $DAEMON_ARGS \ + || return 2 + # Add code here, if necessary, that waits for the process to be ready + # to handle requests from services started subsequently which depend + # on this one. As a last resort, sleep for some time. +} + +# +# Function that stops the daemon/service +# +do_stop() +{ + # Return + # 0 if daemon has been stopped + # 1 if daemon was already stopped + # 2 if daemon could not be stopped + # other if a failure occurred + start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME + RETVAL="$?" + [ "$RETVAL" = 2 ] && return 2 + # Wait for children to finish too if this is a daemon that forks + # and if the daemon is only ever run from this initscript. + # If the above conditions are not satisfied then add some other code + # that waits for the process to drop all resources that could be + # needed by services started subsequently. A last resort is to + # sleep for some time. + start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON + [ "$?" = 2 ] && return 2 + # Many daemons don't delete their pidfiles when they exit. + rm -f $PIDFILE + return "$RETVAL" +} + +# +# Function that sends a SIGHUP to the daemon/service +# +do_reload() { + # + # If the daemon can reload its configuration without + # restarting (for example, when it is sent a SIGHUP), + # then implement that here. + # + start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME + return 0 +} + +case "$1" in + start) + [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME" + do_start + case "$?" in + 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; + 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; + esac + ;; + stop) + [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME" + do_stop + case "$?" in + 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; + 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; + esac + ;; + status) + status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $? + ;; + #reload|force-reload) + # + # If do_reload() is not implemented then leave this commented out + # and leave 'force-reload' as an alias for 'restart'. + # + #log_daemon_msg "Reloading $DESC" "$NAME" + #do_reload + #log_end_msg $? + #;; + restart|force-reload) + # + # If the "reload" option is implemented then remove the + # 'force-reload' alias + # + log_daemon_msg "Restarting $DESC" "$NAME" + do_stop + case "$?" in + 0|1) + do_start + case "$?" in + 0) log_end_msg 0 ;; + 1) log_end_msg 1 ;; # Old process is still running + *) log_end_msg 1 ;; # Failed to start + esac + ;; + *) + # Failed to stop + log_end_msg 1 + ;; + esac + ;; + *) + #echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2 + echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2 + exit 3 + ;; +esac + +: + diff --git a/NodeJsController/NodeJsController.js b/NodeJsController/NodeJsController.js new file mode 100644 index 0000000..8bb67da --- /dev/null +++ b/NodeJsController/NodeJsController.js @@ -0,0 +1,710 @@ +//const gwType = 'Ethernet'; +//const gwAddress = '10.0.1.99'; +//const gwPort = 9999; + +const gwType = 'Serial'; +//const gwPort = 'COM4'; +const gwPort = '/dev/ttyAMA0'; +const gwBaud = 115200; + +const dbAddress = '127.0.0.1'; +const dbPort = 27017; +const dbName = 'MySensorsDb'; + +const fwSketches = [ ]; +const fwDefaultType = 0xFFFF; // index of hex file from array above (0xFFFF + +const FIRMWARE_BLOCK_SIZE = 16; +const BROADCAST_ADDRESS = 255; +const NODE_SENSOR_ID = 255; + +const C_PRESENTATION = 0; +const C_SET = 1; +const C_REQ = 2; +const C_INTERNAL = 3; +const C_STREAM = 4; + +const V_TEMP = 0; +const V_HUM = 1; +const V_LIGHT = 2; +const V_DIMMER = 3; +const V_PRESSURE = 4; +const V_FORECAST = 5; +const V_RAIN = 6; +const V_RAINRATE = 7; +const V_WIND = 8; +const V_GUST = 9; +const V_DIRECTION = 10; +const V_UV = 11; +const V_WEIGHT = 12; +const V_DISTANCE = 13; +const V_IMPEDANCE = 14; +const V_ARMED = 15; +const V_TRIPPED = 16; +const V_WATT = 17; +const V_KWH = 18; +const V_SCENE_ON = 19; +const V_SCENE_OFF = 20; +const V_HEATER = 21; +const V_HEATER_SW = 22; +const V_LIGHT_LEVEL = 23; +const V_VAR1 = 24; +const V_VAR2 = 25; +const V_VAR3 = 26; +const V_VAR4 = 27; +const V_VAR5 = 28; +const V_UP = 29; +const V_DOWN = 30; +const V_STOP = 31; +const V_IR_SEND = 32; +const V_IR_RECEIVE = 33; +const V_FLOW = 34; +const V_VOLUME = 35; +const V_LOCK_STATUS = 36; + +const I_BATTERY_LEVEL = 0; +const I_TIME = 1; +const I_VERSION = 2; +const I_ID_REQUEST = 3; +const I_ID_RESPONSE = 4; +const I_INCLUSION_MODE = 5; +const I_CONFIG = 6; +const I_PING = 7; +const I_PING_ACK = 8; +const I_LOG_MESSAGE = 9; +const I_CHILDREN = 10; +const I_SKETCH_NAME = 11; +const I_SKETCH_VERSION = 12; +const I_REBOOT = 13; + +const S_DOOR = 0; +const S_MOTION = 1; +const S_SMOKE = 2; +const S_LIGHT = 3; +const S_DIMMER = 4; +const S_COVER = 5; +const S_TEMP = 6; +const S_HUM = 7; +const S_BARO = 8; +const S_WIND = 9; +const S_RAIN = 10; +const S_UV = 11; +const S_WEIGHT = 12; +const S_POWER = 13; +const S_HEATER = 14; +const S_DISTANCE = 15; +const S_LIGHT_LEVEL = 16; +const S_ARDUINO_NODE = 17; +const S_ARDUINO_REPEATER_NODE = 18; +const S_LOCK = 19; +const S_IR = 20; +const S_WATER = 21; +const S_AIR_QUALITY = 22; + +const ST_FIRMWARE_CONFIG_REQUEST = 0; +const ST_FIRMWARE_CONFIG_RESPONSE = 1; +const ST_FIRMWARE_REQUEST = 2; +const ST_FIRMWARE_RESPONSE = 3; +const ST_SOUND = 4; +const ST_IMAGE = 5; + +const P_STRING = 0; +const P_BYTE = 1; +const P_INT16 = 2; +const P_UINT16 = 3; +const P_LONG32 = 4; +const P_ULONG32 = 5; +const P_CUSTOM = 6; + +var fs = require('fs'); +var path = require('path'); +var requestify = require('requestify'); +var appendedString=""; + +function crcUpdate(old, value) { + var c = old ^ value; + for (var i = 0; i < 8; ++i) { + if ((c & 1) > 0) + c = ((c >> 1) ^ 0xA001); + else + c = (c >> 1); + } + return c; +} + +function pullWord(arr, pos) { + return arr[pos] + 256 * arr[pos + 1]; +} + +function pushWord(arr, val) { + arr.push(val & 0x00FF); + arr.push((val >> 8) & 0x00FF); +} + +function pushDWord(arr, val) { + arr.push(val & 0x000000FF); + arr.push((val >> 8) & 0x000000FF); + arr.push((val >> 16) & 0x000000FF); + arr.push((val >> 24) & 0x000000FF); +} + +function loadFirmware(fwtype, fwversion, sketch, db) { + var filename = path.basename(sketch); + console.log("compiling firmware: " + filename); + var req = { + files: [{ + filename: filename, + content: fs.readFileSync(sketch).toString() + }], + format: "hex", + version: "105", + build: { + mcu: "atmega328p", + f_cpu: "16000000L", + core: "arduino", + variant: "standard" + } + }; + requestify.post('https://codebender.cc/utilities/compile/', req).then(function(res) { + var body = JSON.parse(res.getBody()); + if (body.success) { + console.log("loading firmware: " + filename); + fwdata = []; + var start = 0; + var end = 0; + var pos = 0; + var hex = body.output.split("\n"); + for(l in hex) { + line = hex[l].trim(); + if (line.length > 0) { + while (line.substring(0, 1) != ":") + line = line.substring(1); + var reclen = parseInt(line.substring(1, 3), 16); + var offset = parseInt(line.substring(3, 7), 16); + var rectype = parseInt(line.substring(7, 9), 16); + var data = line.substring(9, 9 + 2 * reclen); + var chksum = parseInt(line.substring(9 + (2 * reclen), 9 + (2 * reclen) + 2), 16); + if (rectype == 0) { + if ((start == 0) && (end == 0)) { + if (offset % 128 > 0) + throw new Error("error loading hex file - offset can't be devided by 128"); + start = offset; + end = offset; + } + if (offset < end) + throw new Error("error loading hex file - offset lower than end"); + while (offset > end) { + fwdata.push(255); + pos++; + end++; + } + for (var i = 0; i < reclen; i++) { + fwdata.push(parseInt(data.substring(i * 2, (i * 2) + 2), 16)); + pos++; + } + end += reclen; + } + } + } + var pad = end % 128; // ATMega328 has 64 words per page / 128 bytes per page + for (var i = 0; i < 128 - pad; i++) { + fwdata.push(255); + pos++; + end++; + } + var blocks = (end - start) / FIRMWARE_BLOCK_SIZE; + var crc = 0xFFFF; + for (var i = 0; i < blocks * FIRMWARE_BLOCK_SIZE; ++i) { + var v = crc; + crc = crcUpdate(crc, fwdata[i]); + } + db.collection('firmware', function(err, c) { + c.update({ + 'type': fwtype, + 'version': fwversion + }, { + $set: { + 'filename': filename, + 'blocks': blocks, + 'crc': crc, + 'data': fwdata + } + }, { + upsert: true + }, function(err, result) { + if (err) + console.log('Error writing firmware to database'); + }); + }); + console.log("loading firmware done. blocks: " + blocks + " / crc: " + crc); + } else { + console.log("error: %j", res.body); + } + }); +} + +/* +function decode(msg) { + var msgs = msg.toString().split(";"); + rsender = +msgs[0]; + rsensor = +msgs[1]; + rcommand = +msgs[2]; + rtype = +msgs[3]; + var pl = msgs[4].trim(); + rpayload = []; + for (var i = 0; i < pl.length; i+=2) { + var b = parseInt(pl.substring(i, i + 2), 16); + rpayload.push(b); + } +} +*/ + +function encode(destination, sensor, command, acknowledge, type, payload) { + var msg = destination.toString(10) + ";" + sensor.toString(10) + ";" + command.toString(10) + ";" + acknowledge.toString(10) + ";" + type.toString(10) + ";"; + if (command == 4) { + for (var i = 0; i < payload.length; i++) { + if (payload[i] < 16) + msg += "0"; + msg += payload[i].toString(16); + } + } else { + msg += payload; + } + msg += '\n'; + return msg.toString(); +} + +function saveProtocol(sender, payload, db) { + db.collection('node', function(err, c) { + c.update({ + 'id': sender + }, { + $set: { + 'protocol': payload + } + }, { + upsert: true + }, function(err, result) { + if (err) + console.log("Error writing protocol to database"); + }); + }); +} + +function saveSensor(sender, sensor, type, db) { + db.collection('node', function(err, c) { + c.update({ + 'id': sender + }, { + $addToSet: { + sensor: type + } + }, function(err, result) { + if (err) + console.log("Error writing sensor to database"); + }); + }); +} + +function saveValue(sender, sensor, type, payload, db) { + var cn = "Value-" + sender.toString() + "-" + sensor.toString(); + db.createCollection(cn, function(err, c) { + c.save({ + 'timestamp': new Date().getTime(), + 'type': type, + 'value': payload + }, function(err, result) { + if (err) + console.log("Error writing value to database"); + }); + }); +} + +function saveBatteryLevel(sender, payload, db) { + var cn = "BatteryLevel-" + sender.toString(); + db.createCollection(cn, function(err, c) { + c.save({ + 'timestamp': new Date().getTime(), + 'value': payload + }, function(err, result) { + if (err) + console.log("Error writing battery level to database"); + }); + }); +} + +function saveSketchName(sender, payload, db) { + db.collection('node', function(err, c) { + c.update({ + 'id': sender + }, { + $set: { + 'sketchName': payload + } + }, function(err, result) { + if (err) + console.log("Error writing sketch name to database"); + }); + }); +} + +function saveSketchVersion(sender, payload, db) { + db.collection('node', function(err, c) { + c.update({ + 'id': sender + }, { + $set: { + 'sketchVersion': payload + } + }, function(err, result) { + if (err) + console.log("Error writing sketch version to database"); + }); + }); +} + +function sendTime(destination, sensor, gw) { + var payload = new Date().getTime(); + var command = C_INTERNAL; + var acknowledge = 0; // no ack + var type = I_TIME; + var td = encode(destination, sensor, command, acknowledge, type, payload); + console.log('-> ' + td.toString()); + gw.write(td); +} + +function sendNextAvailableSensorId(db, gw) { + db.collection('node', function(err, c) { + c.find({ + $query: { }, + $orderby: { + 'id': 1 + } + }).toArray(function(err, results) { + if (err) + console.log('Error finding nodes'); + var id = 1; + for (var i = 0; i < results.length; i++) + if (results[i].id > i + 1) { + id = i + 1; + break; + } + if (id < 255) { + c.save({ + 'id': id + }, function(err, result) { + if (err) + console.log('Error writing node to database'); + var destination = BROADCAST_ADDRESS; + var sensor = NODE_SENSOR_ID; + var command = C_INTERNAL; + var acknowledge = 0; // no ack + var type = I_ID_RESPONSE; + var payload = id; + var td = encode(destination, sensor, command, acknowledge, type, payload); + console.log('-> ' + td.toString()); + gw.write(td); + }); + } + }); + }); +} + +function sendConfig(destination, gw) { + var payload = "M"; + var sensor = NODE_SENSOR_ID; + var command = C_INTERNAL; + var acknowledge = 0; // no ack + var type = I_CONFIG; + var td = encode(destination, sensor, command, acknowledge, type, payload); + console.log('-> ' + td.toString()); + gw.write(td); +} + +function sendFirmwareConfigResponse(destination, fwtype, fwversion, db, gw) { + // keep track of type/versin info for each node + // at the same time update the last modified date + // could be used to remove nodes not seen for a long time etc. + db.collection('node', function(err, c) { + c.update({ + 'id': destination + }, { + $set: { + 'type': fwtype, + 'version': fwversion, + 'reboot': 0 + } + }, { + upsert: true + }, function(err, result) { + if (err) + console.log("Error writing node type and version to database"); + }); + }); + if (fwtype == 0xFFFF) { + // sensor does not know which type / blank EEPROM + // take predefined type (ideally selected in UI prior to connection of new sensor) + if (fwDefaultType == 0xFFFF) + throw new Error('No default sensor type defined'); + fwtype = fwDefaultType; + } + db.collection('firmware', function(err, c) { + c.findOne({ + $query: { + 'type': fwtype + }, + $orderby: { + 'version': -1 + } + }, function(err, result) { + if (err) + console.log('Error finding firmware for type ' + fwtype); + else if (!result) + console.log('No firmware found for type ' + fwtype); + else { + var payload = []; + pushWord(payload, result.type); + pushWord(payload, result.version); + pushWord(payload, result.blocks); + pushWord(payload, result.crc); + var sensor = NODE_SENSOR_ID; + var command = C_STREAM; + var acknowledge = 0; // no ack + var type = ST_FIRMWARE_CONFIG_RESPONSE; + var td = encode(destination, sensor, command, acknowledge, type, payload); + console.log('-> ' + td.toString()); + gw.write(td); + } + }); + }); +} + +function sendFirmwareResponse(destination, fwtype, fwversion, fwblock, db, gw) { + db.collection('firmware', function(err, c) { + c.findOne({ + 'type': fwtype, + 'version': fwversion + }, function(err, result) { + if (err) + console.log('Error finding firmware version ' + fwversion + ' for type ' + fwtype); + var payload = []; + pushWord(payload, result.type); + pushWord(payload, result.version); + pushWord(payload, fwblock); + for (var i = 0; i < FIRMWARE_BLOCK_SIZE; i++) + payload.push(result.data[fwblock * FIRMWARE_BLOCK_SIZE + i]); + var sensor = NODE_SENSOR_ID; + var command = C_STREAM; + var acknowledge = 0; // no ack + var type = ST_FIRMWARE_RESPONSE; + var td = encode(destination, sensor, command, acknowledge, type, payload); + console.log('-> ' + td.toString()); + gw.write(td); + }); + }); +} + +function saveRebootRequest(destination, db) { + db.collection('node', function(err, c) { + c.update({ + 'id': destination + }, { + $set: { + 'reboot': 1 + } + }, function(err, result) { + if (err) + console.log("Error writing reboot request to database"); + }); + }); +} + +function checkRebootRequest(destination, db, gw) { + db.collection('node', function(err, c) { + c.find({ + 'id': destination + }, function(err, item) { + if (err) + console.log('Error checking reboot request'); + else if (item.reboot == 1) + sendRebootMessage(destination, gw); + }); + }); +} + +function sendRebootMessage(destination, gw) { + var sensor = NODE_SENSOR_ID; + var command = C_INTERNAL; + var acknowledge = 0; // no ack + var type = I_REBOOT; + var payload = ""; + var td = encode(destination, sensor, command, acknowledge, type, payload); + console.log('-> ' + td.toString()); + gw.write(td); +} + + +function appendData(str, db, gw) { + pos=0; + while (str.charAt(pos) != '\n' && pos < str.length) { + appendedString=appendedString+str.charAt(pos); + pos++; + } + if (str.charAt(pos) == '\n') { + rfReceived(appendedString.trim(), db, gw); + appendedString=""; + } + if (pos < str.length) { + appendData(str.substr(pos+1,str.length-pos-1), db, gw); + } +} + +function rfReceived(data, db, gw) { + if ((data != null) && (data != "")) { + console.log('<- ' + data); + // decoding message + var datas = data.toString().split(";"); + var sender = +datas[0]; + var sensor = +datas[1]; + var command = +datas[2]; + var ack = +datas[3]; + var type = +datas[4]; + var rawpayload=""; + if (datas[5]) { + rawpayload = datas[5].trim(); + } + var payload; + if (command == C_STREAM) { + payload = []; + for (var i = 0; i < rawpayload.length; i+=2) + payload.push(parseInt(rawpayload.substring(i, i + 2), 16)); + } else { + payload = rawpayload; + } + // decision on appropriate response + switch (command) { + case C_PRESENTATION: + if (sensor == NODE_SENSOR_ID) + saveProtocol(sender, payload, db); + saveSensor(sender, sensor, type, db); + break; + case C_SET: + saveValue(sender, sensor, type, payload, db); + break; + case C_REQ: + break; + case C_INTERNAL: + switch (type) { + case I_BATTERY_LEVEL: + saveBatteryLevel(sender, payload, db); + break; + case I_TIME: + sendTime(sender, sensor, gw); + break; + case I_VERSION: + break; + case I_ID_REQUEST: + sendNextAvailableSensorId(db, gw); + break; + case I_ID_RESPONSE: + break; + case I_INCLUSION_MODE: + break; + case I_CONFIG: + sendConfig(sender, gw); + break; + case I_PING: + break; + case I_PING_ACK: + break; + case I_LOG_MESSAGE: + break; + case I_CHILDREN: + break; + case I_SKETCH_NAME: + saveSketchName(sender, payload, db); + break; + case I_SKETCH_VERSION: + saveSketchVersion(sender, payload, db); + break; + case I_REBOOT: + break; + } + break; + case C_STREAM: + switch (type) { + case ST_FIRMWARE_CONFIG_REQUEST: + var fwtype = pullWord(payload, 0); + var fwversion = pullWord(payload, 2); + sendFirmwareConfigResponse(sender, fwtype, fwversion, db, gw); + break; + case ST_FIRMWARE_CONFIG_RESPONSE: + break; + case ST_FIRMWARE_REQUEST: + var fwtype = pullWord(payload, 0); + var fwversion = pullWord(payload, 2); + var fwblock = pullWord(payload, 4); + sendFirmwareResponse(sender, fwtype, fwversion, fwblock, db, gw); + break; + case ST_FIRMWARE_RESPONSE: + break; + case ST_SOUND: + break; + case ST_IMAGE: + break; + } + break; + } + checkRebootRequest(sender, db, gw); + } +} + +var dbc = require('mongodb').MongoClient; +dbc.connect('mongodb://' + dbAddress + ':' + dbPort + '/' + dbName, function(err, db) { + if(err) { + console.log('Error connecting to database at mongodb://' + dbAddress + ':' + dbPort + '/' + dbName); + return; + } + console.log('Connected to database at mongodb://' + dbAddress + ':' + dbPort + '/' + dbName); + db.createCollection('node', function(err, collection) { }); + db.createCollection('firmware', function(err, collection) { }); + + // ToDo : check for new hex files / only load if new / get type and version from filename + for (var i = 0; i < fwSketches.length; i++) + loadFirmware(i, 1, fwSketches[i], db); + + var gw; + if (gwType == 'Ethernet') { + gw = require('net').Socket(); + gw.connect(gwPort, gwAddress); + gw.setEncoding('ascii'); + gw.on('connect', function() { + console.log('connected to ethernet gateway at ' + gwAddress + ":" + gwPort); + }).on('data', function(rd) { + appendData(rd.toString(), db, gw); + }).on('end', function() { + console.log('disconnected from gateway'); + }).on('error', function() { + console.log('connection error - trying to reconnect'); + gw.connect(gwPort, gwAddress); + gw.setEncoding('ascii'); + }); + } else if (gwType == 'Serial') { + var SerialPort = require('serialport').SerialPort; + gw = new SerialPort(gwPort, { baudrate: gwBaud }); + gw.open(); + gw.on('open', function() { + console.log('connected to serial gateway at ' + gwPort); + }).on('data', function(rd) { + appendData(rd.toString(), db, gw); + }).on('end', function() { + console.log('disconnected from gateway'); + }).on('error', function() { + console.log('connection error - trying to reconnect'); + gw.open(); + }); + } else { + throw new Error('unknown Gateway type'); + } +}); + diff --git a/NodeJsController/Readme.md b/NodeJsController/Readme.md new file mode 100644 index 0000000..d8b364b --- /dev/null +++ b/NodeJsController/Readme.md @@ -0,0 +1,306 @@ +

MySensors with NodeJS Controller and OTA bootloader on RPi

+

Hardware

+

Headless Raspberry Pi model B with wired Ethernet

+

I'm connecting a monitor only for first time boot to get the IP address and then connect via Putty/xRDP

+

Download and install latest Raspbian version on a fresh SD-Card

+

Tutorials for this task are available on the internet (download, copy to SD)

+

Setup base parameters

+

(adjust to your needs - here: RPi-IP: 10.0.1.5 / Router-IP: 10.0.1.1 / password: test / timezone: Europe,Berlin / hostname: mysensors)

+
    +
  • login as pi / raspberry +
  • sudo nano /etc/network/interfaces +

    #iface eth0 inet dhcp
    +iface eth0 inet static
    +address 10.0.1.5
    +netmask 255.255.255.0
    +gateway 10.0.1.1
    +nameserver 10.0.1.1

    +
  • sudo raspi-config +
      +
    • 1. Expand Filesystem +
    • 2. Change User Password
      +

      test

      +
    • 4. Internationalisation Options +
        +
      • I2. Change Timezone +

        Europe / Berlin

        +
      +
    • 8. Advanced Options +
        +
      • A2. Hostname +

        mysensors

        +
      • A3. Memory Split +

        16

        +
      +
    +
  • Finish +
  • Reboot +
+

Install latest updates

+
    +
  • login as pi / test +
  • sudo apt-get update +
  • sudo apt-get upgrade +
  • sudo reboot +
+ +

Install NodeJS (here: latest stable version available for RPi: 0.10.28)

+
    +
  • login as pi / test +
  • sudo mkdir /opt/node +
  • wget http://nodejs.org/dist/v0.10.28/node-v0.10.28-linux-arm-pi.tar.gz +
  • tar xvzf node-v0.10.28-linux-arm-pi.tar.gz +
  • rm node-v0.10.28-linux-arm-pi.tar.gz +
  • sudo cp -r node-v0.10.28-linux-arm-pi/* /opt/node +
  • rm -rf node-v0.10.28-linux-arm-pi/ +
  • sudo nano /etc/profile +

    NODE_JS_HOME="/opt/node"
    +PATH="$PATH:$NODE_JS_HOME/bin"

    +export PATH

    +
  • sudo reboot +
  • to confirm it's working as expected login as pi/test and run "node -v" which should return the installed node version (here: v0.10.28) +
+

Install MongoDB

+
    +
  • login as pi / test +
  • sudo useradd -c mongodb -d /home/mongodb -m -U mongodb +
  • sudo mkdir -p /opt/mongo/bin +
  • sudo mkdir /var/lib/mongodb +
  • sudo chown mongodb:nogroup /var/lib/mongodb +
  • sudo mkdir /var/log/mongodb +
  • sudo chown mongodb:nogroup /var/log/mongodb +
  • wget https://github.com/brice-morin/ArduPi/raw/master/mongodb-rpi/mongo/bin/mongo +
  • wget https://github.com/brice-morin/ArduPi/raw/master/mongodb-rpi/mongo/bin/mongod +
  • wget https://github.com/brice-morin/ArduPi/raw/master/mongodb-rpi/mongo/bin/mongodump +
  • wget https://github.com/brice-morin/ArduPi/raw/master/mongodb-rpi/mongo/bin/bsondump +
  • sudo mv mongo /opt/mongo/bin/ +
  • sudo mv mongod /opt/mongo/bin/ +
  • sudo mv mongodump /opt/mongo/bin/ +
  • sudo mv bsondump /opt/mongo/bin/ +
  • sudo chmod -R 775 /opt/mongo/bin +
  • sudo ln -s /opt/mongo/bin/mongod /usr/bin/mongod +
  • wget https://raw.githubusercontent.com/skrabban/mongo-nonx86/master/debian/mongodb.conf +
  • wget https://raw.githubusercontent.com/skrabban/mongo-nonx86/master/debian/init.d +
  • sudo mv mongodb.conf /etc/mongodb.conf +
  • sudo mv init.d /etc/init.d/mongodb +
  • sudo chmod 755 /etc/init.d/mongodb +
  • sudo update-rc.d mongodb defaults +
  • sudo reboot +
  • to confirm it's working as expected login as pi/test and run "/opt/mongo/bin/mongo" which should start the mongo shell (type "exit" to close the shell again) +
  • if the RPi loses power without proper shutdown while mongod is running, you can't restart without manually removing the pid file first. To do so run “sudo rm /var/lib/mongodb/mongod.lock” +
+ +

Install MySensors from Git branch development (here: password: test)

+
    +
  • login as pi / test +
  • git clone https://github.com/mysensors/Arduino.git +
  • cd Arduino +
  • git checkout development +
  • cd NodeJsController +
  • npm install +
  • to confirm that the NodeJsController is working as expected and connects to the local mongo DB: "node NodeJsController.js" which should start the controller, connect to the database and run into an error connecting to the gateway. Stop node again via Ctrl-c +
+

Start NodeJsController on boot

+
    +
  • cd ~/Arduino/NodeJsController +
  • chmod 755 *.sh +
  • sudo cp MySensorsInitScript.sh /etc/init.d/mysensors +
  • sudo mkdir -p /usr/local/var/run +
  • sudo chmod -R 777 /usr/local/var/run +
  • sudo update-rc.d mysensors defaults +
  • sudo reboot +
  • to confirm that NodeJsController is starting at boot, check the log file /home/pi/logs/NodeJsController.log +
+ + +

Serial Gateway

+

Hardware

+
    +
  • as described for the standard Serial Gateway - using the standard Serial Gateway sketch with DEBUG (in MyConfig.h) disabled +
  • I'm using the version with inclusion mode button and LEDs based on no Arduino but a plain ATmega328p on a breadboard +
  • Connect directly to the serial GPIO pins of the RPi: +

    Arduino GND <-> Raspberry Pi GND (pin 6)
    +Arduino RX <-> Raspberry Pi TX (pin 8)
    +Arduino TX <-> Raspberry Pi RX (pin 10)
    +Arduino RESET <-> Raspberry Pi GPIO22 (pin 15)

    +
  • Right now I'm using a separate power supply for the serial gateway instead of the 3.3V or 5V pins of the RPi because I ran in some issues with power consumption during programming +
+

Disable default use of RPi serial port

+
    +
  • sudo nano /etc/inittab +

    #T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100

    +
  • sudo nano /boot/cmdline.txt - remove part of the file: +

    console=ttyAMA0,115200

    +
  • cd /dev +
  • sudo ln -s ttyAMA0 ttyUSB9 +
  • sudo apt-get install minicom +
  • sudo reboot +
+ +

Setup NodeJsController

+
    +
  • nano ~/Arduino/NodeJsController/NodeJsController.js +

    //const gwType = 'Ethernet';
    +//const gwAddress = '10.0.1.99';
    +//const gwPort = 9999;
    +//const gwType = 'Serial';
    +//const gwPort = '/dev/ttyAMA0';
    +//const gwBaud = 115200;

    +
  • sudo service mysensors restart (at this point stop/restart doesn't work. use "sudo killall node" followed by "sudo service mysensors start" instead) +
+ +

Ethernet Gateway

+

Hardware

+
    +
  • as described for the standard Ethernet Gateway - using the standard Ethernet Gateway sketch with DEBUG (in MyConfig.h) disabled +
  • I'm using the version with inclusion mode button and LEDs based on no Arduino but a plain ATmega328p on a breadboard and the ENC28J60 Ethernet module +
  • here: 10.0.1.99 / port: 9999 +
+ +

Setup NodeJsController

+
    +
  • nano ~/Arduino/NodeJsController/NodeJsController.js +

    const gwAddress = '10.0.1.99';

    +
  • sudo service mysensors restart (at this point stop/restart doesn't work. use "sudo killall node" followed by "sudo service mysensors start" instead) +
+ +

Sensor Node Bootloader

+

Hardware

+
    +
  • as described for a simple Sensor Node +
  • here: no Arduino but a plain ATmega328p on a breadboard +
  • using DallasTemperature example (one sensor connected to pin 3) +
+

Compile Bootloader (can be skipped but good to see if everything is working)

+
    +
  • cd ~/Arduino/Bootloader +
  • make +
  • this should compile the bootloader and produce three files in the same directory: MyOtaBootloader.o / MyOtaBootloader.elf / MyOtaBootloader.hex +
+

Flash Bootloader

+
    +
  • cd ~/Arduino/Bootloader +
  • nano Makefile +
  • adjust avrdude settings to the available programmer. In my case (mySmartUSB MK3 programmer temporarily connected to RPi USB port): +

    ISP_PORT = /dev/ttyUSB0
    +ISP_SPEED = 115200
    +ISP_PROTOCOL = stk500v2
    +ISP_MCU = m328p

    +
  • make load +
+ +

End-to-End Test

+

Add Firmware to Controller (here: DallasTemperatureSensor)

+
    +
  • nano ~/Arduino/NodeJsController/NodeJsController.js +

    const fwHexFiles = [ '../libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino' ];
    +const fwDefaultType = 0;

    +
  • sudo service mysensors restart (at this point stop/restart doesn't work. use "sudo killall node" followed by "sudo service mysensors start" instead) +
+

Flash Firmware OTA

+
    +
  • tail -f ~/logs/NodeJsController.log +
  • Power up sensor node with OTA bootloader +
+

Check functionality

+
    +
  • in addition to watching the log file (tail command above) you can connect to the mongo db using a client (e.g. Robomongo) and check if new values are written to the database as a real end-to-end test once the bootloader finished uploading the firmware +
diff --git a/NodeJsController/Reboot.js b/NodeJsController/Reboot.js new file mode 100644 index 0000000..2afb2b9 --- /dev/null +++ b/NodeJsController/Reboot.js @@ -0,0 +1,28 @@ +var NodeIdToReboot = 1; + +const dbAddress = '127.0.0.1'; +const dbPort = 27017; +const dbName = 'MySensorsDb'; + +var dbc = require('mongodb').MongoClient; +dbc.connect('mongodb://' + dbAddress + ':' + dbPort + '/' + dbName, function(err, db) { + if (err) { + console.log('Error connecting to database at mongodb://' + dbAddress + ':' + dbPort + '/' + dbName); + } else { + db.collection('node', function(err, c) { + c.update({ + 'id': NodeIdToReboot + }, { + $set: { + 'reboot': 1 + } + }, function(err, result) { + if (err) + console.log("Error writing reboot request to database"); + else + console.log("Reboot request saved to database"); + }); + }); + } +}); + diff --git a/NodeJsController/package.json b/NodeJsController/package.json new file mode 100644 index 0000000..eaffa4a --- /dev/null +++ b/NodeJsController/package.json @@ -0,0 +1,11 @@ +{ + "name": "NodeJsController", + "version": "0.0.1", + "description": "MySensors Controller based on Node JS", + "dependencies": { + "mongodb": "~1.4.7", + "net": "~1.0.2", + "requestify": "^0.1.16", + "serialport": "^1.4.5" + } +} diff --git a/README.md b/README.md index 4df7c40..ebb4f31 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ Arduino ======= -MySensors Arduino Library +MySensors Arduino Library v1.4 Please visit www.mysensors.org for more information diff --git a/libraries/EmonLib/EmonLib.cpp b/libraries/EmonLib/EmonLib.cpp new file mode 100644 index 0000000..1a1fd29 --- /dev/null +++ b/libraries/EmonLib/EmonLib.cpp @@ -0,0 +1,259 @@ +/* + Emon.cpp - Library for openenergymonitor + Created by Trystan Lea, April 27 2010 + GNU GPL + modified to use up to 12 bits ADC resolution (ex. Arduino Due) + by boredman@boredomprojects.net 26.12.2013 +*/ + +//#include "WProgram.h" un-comment for use on older versions of Arduino IDE +#include "EmonLib.h" + +#if defined(ARDUINO) && ARDUINO >= 100 + +#include "Arduino.h" + +#else + +#include "WProgram.h" + +#endif + +//-------------------------------------------------------------------------------------- +// Sets the pins to be used for voltage and current sensors +//-------------------------------------------------------------------------------------- +void EnergyMonitor::voltage(int _inPinV, double _VCAL, double _PHASECAL) +{ + inPinV = _inPinV; + VCAL = _VCAL; + PHASECAL = _PHASECAL; +} + +void EnergyMonitor::current(int _inPinI, double _ICAL) +{ + inPinI = _inPinI; + ICAL = _ICAL; +} + +//-------------------------------------------------------------------------------------- +// Sets the pins to be used for voltage and current sensors based on emontx pin map +//-------------------------------------------------------------------------------------- +void EnergyMonitor::voltageTX(double _VCAL, double _PHASECAL) +{ + inPinV = 2; + VCAL = _VCAL; + PHASECAL = _PHASECAL; +} + +void EnergyMonitor::currentTX(int _channel, double _ICAL) +{ + if (_channel == 1) inPinI = 3; + if (_channel == 2) inPinI = 0; + if (_channel == 3) inPinI = 1; + ICAL = _ICAL; +} + +//-------------------------------------------------------------------------------------- +// emon_calc procedure +// Calculates realPower,apparentPower,powerFactor,Vrms,Irms,kwh increment +// From a sample window of the mains AC voltage and current. +// The Sample window length is defined by the number of half wavelengths or crossings we choose to measure. +//-------------------------------------------------------------------------------------- +void EnergyMonitor::calcVI(int crossings, int timeout) +{ + #if defined emonTxV3 + int SUPPLYVOLTAGE=3300; + #else + int SUPPLYVOLTAGE = readVcc(); + #endif + + int crossCount = 0; //Used to measure number of times threshold is crossed. + int numberOfSamples = 0; //This is now incremented + + //------------------------------------------------------------------------------------------------------------------------- + // 1) Waits for the waveform to be close to 'zero' (500 adc) part in sin curve. + //------------------------------------------------------------------------------------------------------------------------- + boolean st=false; //an indicator to exit the while loop + + unsigned long start = millis(); //millis()-start makes sure it doesnt get stuck in the loop if there is an error. + + while(st==false) //the while loop... + { + startV = analogRead(inPinV); //using the voltage waveform + if ((startV < (ADC_COUNTS/2+50)) && (startV > (ADC_COUNTS/2-50))) st=true; //check its within range + if ((millis()-start)>timeout) st = true; + } + + //------------------------------------------------------------------------------------------------------------------------- + // 2) Main measurment loop + //------------------------------------------------------------------------------------------------------------------------- + start = millis(); + + while ((crossCount < crossings) && ((millis()-start) startV) checkVCross = true; + else checkVCross = false; + if (numberOfSamples==1) lastVCross = checkVCross; + + if (lastVCross != checkVCross) crossCount++; + } + + //------------------------------------------------------------------------------------------------------------------------- + // 3) Post loop calculations + //------------------------------------------------------------------------------------------------------------------------- + //Calculation of the root of the mean of the voltage and current squared (rms) + //Calibration coeficients applied. + + double V_RATIO = VCAL *((SUPPLYVOLTAGE/1000.0) / (ADC_COUNTS)); + Vrms = V_RATIO * sqrt(sumV / numberOfSamples); + + double I_RATIO = ICAL *((SUPPLYVOLTAGE/1000.0) / (ADC_COUNTS)); + Irms = I_RATIO * sqrt(sumI / numberOfSamples); + + //Calculation power values + realPower = V_RATIO * I_RATIO * sumP / numberOfSamples; + apparentPower = Vrms * Irms; + powerFactor=realPower / apparentPower; + + //Reset accumulators + sumV = 0; + sumI = 0; + sumP = 0; +//-------------------------------------------------------------------------------------- +} + +//-------------------------------------------------------------------------------------- +double EnergyMonitor::calcIrms(int NUMBER_OF_SAMPLES) +{ + + #if defined emonTxV3 + int SUPPLYVOLTAGE=3300; + #else + int SUPPLYVOLTAGE = readVcc(); + #endif + + + for (int n = 0; n < NUMBER_OF_SAMPLES; n++) + { + lastSampleI = sampleI; + sampleI = analogRead(inPinI); + lastFilteredI = filteredI; + filteredI = 0.996*(lastFilteredI+sampleI-lastSampleI); + + // Root-mean-square method current + // 1) square current values + sqI = filteredI * filteredI; + // 2) sum + sumI += sqI; + } + + double I_RATIO = ICAL *((SUPPLYVOLTAGE/1000.0) / (ADC_COUNTS)); + Irms = I_RATIO * sqrt(sumI / NUMBER_OF_SAMPLES); + + //Reset accumulators + sumI = 0; +//-------------------------------------------------------------------------------------- + + return Irms; +} + +void EnergyMonitor::serialprint() +{ + Serial.print(realPower); + Serial.print(' '); + Serial.print(apparentPower); + Serial.print(' '); + Serial.print(Vrms); + Serial.print(' '); + Serial.print(Irms); + Serial.print(' '); + Serial.print(powerFactor); + Serial.println(' '); + delay(100); +} + +//thanks to http://hacking.majenko.co.uk/making-accurate-adc-readings-on-arduino +//and Jérôme who alerted us to http://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/ + +long EnergyMonitor::readVcc() { + long result; + + //not used on emonTx V3 - as Vcc is always 3.3V - eliminates bandgap error and need for calibration http://harizanov.com/2013/09/thoughts-on-avr-adc-accuracy/ + + #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328__) || defined (__AVR_ATmega328P__) + ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); + #elif defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_AT90USB1286__) + ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); + ADCSRB &= ~_BV(MUX5); // Without this the function always returns -1 on the ATmega2560 http://openenergymonitor.org/emon/node/2253#comment-11432 + #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) + ADMUX = _BV(MUX5) | _BV(MUX0); + #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) + ADMUX = _BV(MUX3) | _BV(MUX2); + + #endif + + + #if defined(__AVR__) + delay(2); // Wait for Vref to settle + ADCSRA |= _BV(ADSC); // Convert + while (bit_is_set(ADCSRA,ADSC)); + result = ADCL; + result |= ADCH<<8; + result = 1126400L / result; //1100mV*1024 ADC steps http://openenergymonitor.org/emon/node/1186 + return result; + #elif defined(__arm__) + return (3300); //Arduino Due + #else + return (3300); //Guess that other un-supported architectures will be running a 3.3V! + #endif +} + diff --git a/libraries/EmonLib/EmonLib.h b/libraries/EmonLib/EmonLib.h new file mode 100644 index 0000000..41cafcb --- /dev/null +++ b/libraries/EmonLib/EmonLib.h @@ -0,0 +1,89 @@ +/* + Emon.h - Library for openenergymonitor + Created by Trystan Lea, April 27 2010 + GNU GPL + modified to use up to 12 bits ADC resolution (ex. Arduino Due) + by boredman@boredomprojects.net 26.12.2013 +*/ + +#ifndef EmonLib_h +#define EmonLib_h + +#if defined(ARDUINO) && ARDUINO >= 100 + +#include "Arduino.h" + +#else + +#include "WProgram.h" + +#endif + +// to enable 12-bit ADC resolution on Arduino Due, +// include the following line in main sketch inside setup() function: +// analogReadResolution(ADC_BITS); +// otherwise will default to 10 bits, as in regular Arduino-based boards. +#if defined(__arm__) +#define ADC_BITS 12 +#else +#define ADC_BITS 10 +#endif + +#define ADC_COUNTS (1< +#include +#include +#include +#include "LowPower.h" + +// Only Pico Power devices can change BOD settings through software +#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 lowPowerBodOn(mode) \ +do { \ + set_sleep_mode(mode); \ + cli(); \ + sleep_enable(); \ + sei(); \ + sleep_cpu(); \ + sleep_disable(); \ + sei(); \ +} while (0); + +// Only Pico Power devices can change BOD settings through software +#if defined __AVR_ATmega328P__ +#define lowPowerBodOff(mode)\ +do { \ + set_sleep_mode(mode); \ + cli(); \ + sleep_enable(); \ + sleep_bod_disable(); \ + sei(); \ + sleep_cpu(); \ + sleep_disable(); \ + sei(); \ +} while (0); +#endif + +// Some macros is still missing from AVR GCC distribution for ATmega32U4 +#if defined __AVR_ATmega32U4__ + // Timer 4 PRR bit is currently not defined in iom32u4.h + #ifndef PRTIM4 + #define PRTIM4 4 + #endif + + // Timer 4 power reduction macro is not defined currently in power.h + #ifndef power_timer4_disable + #define power_timer4_disable() (PRR1 |= (uint8_t)(1 << PRTIM4)) + #endif + + #ifndef power_timer4_enable + #define power_timer4_enable() (PRR1 &= (uint8_t)~(1 << PRTIM4)) + #endif +#endif + +/******************************************************************************* +* Name: idle +* Description: Putting ATmega328P/168 into idle state. Please make sure you +* understand the implication and result of disabling module. +* +* Argument Description +* ========= =========== +* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake +* up resource: +* (a) SLEEP_15MS - 15 ms sleep +* (b) SLEEP_30MS - 30 ms sleep +* (c) SLEEP_60MS - 60 ms sleep +* (d) SLEEP_120MS - 120 ms sleep +* (e) SLEEP_250MS - 250 ms sleep +* (f) SLEEP_500MS - 500 ms sleep +* (g) SLEEP_1S - 1 s sleep +* (h) SLEEP_2S - 2 s sleep +* (i) SLEEP_4S - 4 s sleep +* (j) SLEEP_8S - 8 s sleep +* (k) SLEEP_FOREVER - Sleep without waking up through WDT +* +* 2. adc ADC module disable control: +* (a) ADC_OFF - Turn off ADC module +* (b) ADC_ON - Leave ADC module in its default state +* +* 3. timer2 Timer 2 module disable control: +* (a) TIMER2_OFF - Turn off Timer 2 module +* (b) TIMER2_ON - Leave Timer 2 module in its default state +* +* 4. timer1 Timer 1 module disable control: +* (a) TIMER1_OFF - Turn off Timer 1 module +* (b) TIMER1_ON - Leave Timer 1 module in its default state +* +* 5. timer0 Timer 0 module disable control: +* (a) TIMER0_OFF - Turn off Timer 0 module +* (b) TIMER0_ON - Leave Timer 0 module in its default state +* +* 6. spi SPI module disable control: +* (a) SPI_OFF - Turn off SPI module +* (b) SPI_ON - Leave SPI module in its default state +* +* 7. usart0 USART0 module disable control: +* (a) USART0_OFF - Turn off USART0 module +* (b) USART0_ON - Leave USART0 module in its default state +* +* 8. twi TWI module disable control: +* (a) TWI_OFF - Turn off TWI module +* (b) TWI_ON - Leave TWI module in its default state +* +*******************************************************************************/ +#if defined (__AVR_ATmega328P__) || defined (__AVR_ATmega168__) +void LowPowerClass::idle(period_t period, adc_t adc, timer2_t timer2, + timer1_t timer1, timer0_t timer0, + spi_t spi, usart0_t usart0, twi_t twi) +{ + // Temporary clock source variable + unsigned char clockSource = 0; + + if (timer2 == TIMER2_OFF) + { + if (TCCR2B & CS22) clockSource |= (1 << CS22); + if (TCCR2B & CS21) clockSource |= (1 << CS21); + if (TCCR2B & CS20) clockSource |= (1 << CS20); + + // Remove the clock source to shutdown Timer2 + TCCR2B &= ~(1 << CS22); + TCCR2B &= ~(1 << CS21); + TCCR2B &= ~(1 << CS20); + + power_timer2_disable(); + } + + if (adc == ADC_OFF) + { + ADCSRA &= ~(1 << ADEN); + power_adc_disable(); + } + + if (timer1 == TIMER1_OFF) power_timer1_disable(); + if (timer0 == TIMER0_OFF) power_timer0_disable(); + if (spi == SPI_OFF) power_spi_disable(); + if (usart0 == USART0_OFF) power_usart0_disable(); + if (twi == TWI_OFF) power_twi_disable(); + + if (period != SLEEP_FOREVER) + { + wdt_enable(period); + WDTCSR |= (1 << WDIE); + } + + lowPowerBodOn(SLEEP_MODE_IDLE); + + if (adc == ADC_OFF) + { + power_adc_enable(); + ADCSRA |= (1 << ADEN); + } + + if (timer2 == TIMER2_OFF) + { + if (clockSource & CS22) TCCR2B |= (1 << CS22); + if (clockSource & CS21) TCCR2B |= (1 << CS21); + if (clockSource & CS20) TCCR2B |= (1 << CS20); + + power_timer2_enable(); + } + + if (timer1 == TIMER1_OFF) power_timer1_enable(); + if (timer0 == TIMER0_OFF) power_timer0_enable(); + if (spi == SPI_OFF) power_spi_enable(); + if (usart0 == USART0_OFF) power_usart0_enable(); + if (twi == TWI_OFF) power_twi_enable(); +} +#endif + +/******************************************************************************* +* Name: idle +* Description: Putting ATmega32U4 into idle state. Please make sure you +* understand the implication and result of disabling module. +* Take note that Timer 2 is not available and USART0 +* is replaced with USART1 on ATmega32U4. +* +* Argument Description +* ========= =========== +* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake +* up resource: +* (a) SLEEP_15MS - 15 ms sleep +* (b) SLEEP_30MS - 30 ms sleep +* (c) SLEEP_60MS - 60 ms sleep +* (d) SLEEP_120MS - 120 ms sleep +* (e) SLEEP_250MS - 250 ms sleep +* (f) SLEEP_500MS - 500 ms sleep +* (g) SLEEP_1S - 1 s sleep +* (h) SLEEP_2S - 2 s sleep +* (i) SLEEP_4S - 4 s sleep +* (j) SLEEP_8S - 8 s sleep +* (k) SLEEP_FOREVER - Sleep without waking up through WDT +* +* 2. adc ADC module disable control: +* (a) ADC_OFF - Turn off ADC module +* (b) ADC_ON - Leave ADC module in its default state +* +* 3. timer4 Timer 4 module disable control: +* (a) TIMER4_OFF - Turn off Timer 4 module +* (b) TIMER4_ON - Leave Timer 4 module in its default state +* +* 4. timer3 Timer 3 module disable control: +* (a) TIMER3_OFF - Turn off Timer 3 module +* (b) TIMER3_ON - Leave Timer 3 module in its default state +* +* 5. timer1 Timer 1 module disable control: +* (a) TIMER1_OFF - Turn off Timer 1 module +* (b) TIMER1_ON - Leave Timer 1 module in its default state +* +* 6. timer0 Timer 0 module disable control: +* (a) TIMER0_OFF - Turn off Timer 0 module +* (b) TIMER0_ON - Leave Timer 0 module in its default state +* +* 7. spi SPI module disable control: +* (a) SPI_OFF - Turn off SPI module +* (b) SPI_ON - Leave SPI module in its default state +* +* 8. usart1 USART1 module disable control: +* (a) USART1_OFF - Turn off USART1 module +* (b) USART1_ON - Leave USART1 module in its default state +* +* 9. twi TWI module disable control: +* (a) TWI_OFF - Turn off TWI module +* (b) TWI_ON - Leave TWI module in its default state +* +* 10.usb USB module disable control: +* (a) USB_OFF - Turn off USB module +* (b) USB_ON - Leave USB module in its default state +*******************************************************************************/ +#if defined __AVR_ATmega32U4__ +void LowPowerClass::idle(period_t period, adc_t adc, + timer4_t timer4, timer3_t timer3, + timer1_t timer1, timer0_t timer0, + spi_t spi, usart1_t usart1, twi_t twi, usb_t usb) +{ + if (adc == ADC_OFF) + { + ADCSRA &= ~(1 << ADEN); + power_adc_disable(); + } + + if (timer4 == TIMER4_OFF) power_timer4_disable(); + if (timer3 == TIMER3_OFF) power_timer3_disable(); + if (timer1 == TIMER1_OFF) power_timer1_disable(); + if (timer0 == TIMER0_OFF) power_timer0_disable(); + if (spi == SPI_OFF) power_spi_disable(); + if (usart1 == USART1_OFF) power_usart1_disable(); + if (twi == TWI_OFF) power_twi_disable(); + if (usb == USB_OFF) power_usb_disable(); + + if (period != SLEEP_FOREVER) + { + wdt_enable(period); + WDTCSR |= (1 << WDIE); + } + + lowPowerBodOn(SLEEP_MODE_IDLE); + + if (adc == ADC_OFF) + { + power_adc_enable(); + ADCSRA |= (1 << ADEN); + } + + if (timer4 == TIMER4_OFF) power_timer4_enable(); + if (timer3 == TIMER3_OFF) power_timer3_enable(); + if (timer1 == TIMER1_OFF) power_timer1_enable(); + if (timer0 == TIMER0_OFF) power_timer0_enable(); + if (spi == SPI_OFF) power_spi_enable(); + if (usart1 == USART1_OFF) power_usart1_enable(); + if (twi == TWI_OFF) power_twi_enable(); + if (usb == USB_OFF) power_usb_enable(); +} +#endif + +/******************************************************************************* +* Name: idle +* Description: Putting ATmega2560 & ATmega1280 into idle state. Please make sure +* you understand the implication and result of disabling module. +* Take note that extra Timer 5, 4, 3 compared to an ATmega328P/168. +* Also take note that extra USART 3, 2, 1 compared to an +* ATmega328P/168. +* +* Argument Description +* ========= =========== +* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake +* up resource: +* (a) SLEEP_15MS - 15 ms sleep +* (b) SLEEP_30MS - 30 ms sleep +* (c) SLEEP_60MS - 60 ms sleep +* (d) SLEEP_120MS - 120 ms sleep +* (e) SLEEP_250MS - 250 ms sleep +* (f) SLEEP_500MS - 500 ms sleep +* (g) SLEEP_1S - 1 s sleep +* (h) SLEEP_2S - 2 s sleep +* (i) SLEEP_4S - 4 s sleep +* (j) SLEEP_8S - 8 s sleep +* (k) SLEEP_FOREVER - Sleep without waking up through WDT +* +* 2. adc ADC module disable control: +* (a) ADC_OFF - Turn off ADC module +* (b) ADC_ON - Leave ADC module in its default state +* +* 3. timer5 Timer 5 module disable control: +* (a) TIMER5_OFF - Turn off Timer 5 module +* (b) TIMER5_ON - Leave Timer 5 module in its default state +* +* 4. timer4 Timer 4 module disable control: +* (a) TIMER4_OFF - Turn off Timer 4 module +* (b) TIMER4_ON - Leave Timer 4 module in its default state +* +* 5. timer3 Timer 3 module disable control: +* (a) TIMER3_OFF - Turn off Timer 3 module +* (b) TIMER3_ON - Leave Timer 3 module in its default state +* +* 6. timer2 Timer 2 module disable control: +* (a) TIMER2_OFF - Turn off Timer 2 module +* (b) TIMER2_ON - Leave Timer 2 module in its default state +* +* 7. timer1 Timer 1 module disable control: +* (a) TIMER1_OFF - Turn off Timer 1 module +* (b) TIMER1_ON - Leave Timer 1 module in its default state +* +* 8. timer0 Timer 0 module disable control: +* (a) TIMER0_OFF - Turn off Timer 0 module +* (b) TIMER0_ON - Leave Timer 0 module in its default state +* +* 9. spi SPI module disable control: +* (a) SPI_OFF - Turn off SPI module +* (b) SPI_ON - Leave SPI module in its default state +* +* 10.usart3 USART3 module disable control: +* (a) USART3_OFF - Turn off USART3 module +* (b) USART3_ON - Leave USART3 module in its default state +* +* 11.usart2 USART2 module disable control: +* (a) USART2_OFF - Turn off USART2 module +* (b) USART2_ON - Leave USART2 module in its default state +* +* 12.usart1 USART1 module disable control: +* (a) USART1_OFF - Turn off USART1 module +* (b) USART1_ON - Leave USART1 module in its default state +* +* 13.usart0 USART0 module disable control: +* (a) USART0_OFF - Turn off USART0 module +* (b) USART0_ON - Leave USART0 module in its default state +* +* 14.twi TWI module disable control: +* (a) TWI_OFF - Turn off TWI module +* (b) TWI_ON - Leave TWI module in its default state +* +*******************************************************************************/ +#if defined (__AVR_ATmega2560__) || defined (__AVR_ATmega1280__) +void LowPowerClass::idle(period_t period, adc_t adc, timer5_t timer5, + timer4_t timer4, timer3_t timer3, timer2_t timer2, + timer1_t timer1, timer0_t timer0, spi_t spi, + usart3_t usart3, usart2_t usart2, usart1_t usart1, + usart0_t usart0, twi_t twi) +{ + // Temporary clock source variable + unsigned char clockSource = 0; + + if (timer2 == TIMER2_OFF) + { + if (TCCR2B & CS22) clockSource |= (1 << CS22); + if (TCCR2B & CS21) clockSource |= (1 << CS21); + if (TCCR2B & CS20) clockSource |= (1 << CS20); + + // Remove the clock source to shutdown Timer2 + TCCR2B &= ~(1 << CS22); + TCCR2B &= ~(1 << CS21); + TCCR2B &= ~(1 << CS20); + + power_timer2_disable(); + } + + if (adc == ADC_OFF) + { + ADCSRA &= ~(1 << ADEN); + power_adc_disable(); + } + + if (timer5 == TIMER5_OFF) power_timer5_disable(); + if (timer4 == TIMER4_OFF) power_timer4_disable(); + if (timer3 == TIMER3_OFF) power_timer3_disable(); + if (timer1 == TIMER1_OFF) power_timer1_disable(); + if (timer0 == TIMER0_OFF) power_timer0_disable(); + if (spi == SPI_OFF) power_spi_disable(); + if (usart3 == USART3_OFF) power_usart3_disable(); + if (usart2 == USART2_OFF) power_usart2_disable(); + if (usart1 == USART1_OFF) power_usart1_disable(); + if (usart0 == USART0_OFF) power_usart0_disable(); + if (twi == TWI_OFF) power_twi_disable(); + + if (period != SLEEP_FOREVER) + { + wdt_enable(period); + WDTCSR |= (1 << WDIE); + } + + lowPowerBodOn(SLEEP_MODE_IDLE); + + if (adc == ADC_OFF) + { + power_adc_enable(); + ADCSRA |= (1 << ADEN); + } + + if (timer2 == TIMER2_OFF) + { + if (clockSource & CS22) TCCR2B |= (1 << CS22); + if (clockSource & CS21) TCCR2B |= (1 << CS21); + if (clockSource & CS20) TCCR2B |= (1 << CS20); + + power_timer2_enable(); + } + + if (timer5 == TIMER5_OFF) power_timer5_enable(); + if (timer4 == TIMER4_OFF) power_timer4_enable(); + if (timer3 == TIMER3_OFF) power_timer3_enable(); + if (timer1 == TIMER1_OFF) power_timer1_enable(); + if (timer0 == TIMER0_OFF) power_timer0_enable(); + if (spi == SPI_OFF) power_spi_enable(); + if (usart3 == USART3_OFF) power_usart3_enable(); + if (usart2 == USART2_OFF) power_usart2_enable(); + if (usart1 == USART1_OFF) power_usart1_enable(); + if (usart0 == USART0_OFF) power_usart0_enable(); + if (twi == TWI_OFF) power_twi_enable(); +} +#endif + +/******************************************************************************* +* Name: adcNoiseReduction +* Description: Putting microcontroller into ADC noise reduction state. This is +* a very useful state when using the ADC to achieve best and low +* noise signal. +* +* Argument Description +* ========= =========== +* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake +* up resource: +* (a) SLEEP_15MS - 15 ms sleep +* (b) SLEEP_30MS - 30 ms sleep +* (c) SLEEP_60MS - 60 ms sleep +* (d) SLEEP_120MS - 120 ms sleep +* (e) SLEEP_250MS - 250 ms sleep +* (f) SLEEP_500MS - 500 ms sleep +* (g) SLEEP_1S - 1 s sleep +* (h) SLEEP_2S - 2 s sleep +* (i) SLEEP_4S - 4 s sleep +* (j) SLEEP_8S - 8 s sleep +* (k) SLEEP_FOREVER - Sleep without waking up through WDT +* +* 2. adc ADC module disable control. Turning off the ADC module is +* basically removing the purpose of this low power mode. +* (a) ADC_OFF - Turn off ADC module +* (b) ADC_ON - Leave ADC module in its default state +* +* 3. timer2 Timer 2 module disable control: +* (a) TIMER2_OFF - Turn off Timer 2 module +* (b) TIMER2_ON - Leave Timer 2 module in its default state +* +*******************************************************************************/ +void LowPowerClass::adcNoiseReduction(period_t period, adc_t adc, + timer2_t timer2) +{ + // Temporary clock source variable + unsigned char clockSource = 0; + + #if !defined(__AVR_ATmega32U4__) + if (timer2 == TIMER2_OFF) + { + if (TCCR2B & CS22) clockSource |= (1 << CS22); + if (TCCR2B & CS21) clockSource |= (1 << CS21); + if (TCCR2B & CS20) clockSource |= (1 << CS20); + + // Remove the clock source to shutdown Timer2 + TCCR2B &= ~(1 << CS22); + TCCR2B &= ~(1 << CS21); + TCCR2B &= ~(1 << CS20); + } + #endif + + if (adc == ADC_OFF) ADCSRA &= ~(1 << ADEN); + + if (period != SLEEP_FOREVER) + { + wdt_enable(period); + WDTCSR |= (1 << WDIE); + } + + lowPowerBodOn(SLEEP_MODE_ADC); + + if (adc == ADC_OFF) ADCSRA |= (1 << ADEN); + + #if !defined(__AVR_ATmega32U4__) + if (timer2 == TIMER2_OFF) + { + if (clockSource & CS22) TCCR2B |= (1 << CS22); + if (clockSource & CS21) TCCR2B |= (1 << CS21); + if (clockSource & CS20) TCCR2B |= (1 << CS20); + + } + #endif +} + +/******************************************************************************* +* Name: powerDown +* Description: Putting microcontroller into power down state. This is +* the lowest current consumption state. Use this together with +* external pin interrupt to wake up through external event +* triggering (example: RTC clockout pin, SD card detect pin). +* +* Argument Description +* ========= =========== +* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake +* up resource: +* (a) SLEEP_15MS - 15 ms sleep +* (b) SLEEP_30MS - 30 ms sleep +* (c) SLEEP_60MS - 60 ms sleep +* (d) SLEEP_120MS - 120 ms sleep +* (e) SLEEP_250MS - 250 ms sleep +* (f) SLEEP_500MS - 500 ms sleep +* (g) SLEEP_1S - 1 s sleep +* (h) SLEEP_2S - 2 s sleep +* (i) SLEEP_4S - 4 s sleep +* (j) SLEEP_8S - 8 s sleep +* (k) SLEEP_FOREVER - Sleep without waking up through WDT +* +* 2. adc ADC module disable control. Turning off the ADC module is +* basically removing the purpose of this low power mode. +* (a) ADC_OFF - Turn off ADC module +* (b) ADC_ON - Leave ADC module in its default state +* +* 3. bod Brown Out Detector (BOD) module disable control: +* (a) BOD_OFF - Turn off BOD module +* (b) BOD_ON - Leave BOD module in its default state +* +*******************************************************************************/ +void LowPowerClass::powerDown(period_t period, adc_t adc, bod_t bod) +{ + if (adc == ADC_OFF) ADCSRA &= ~(1 << ADEN); + + if (period != SLEEP_FOREVER) + { + wdt_enable(period); + WDTCSR |= (1 << WDIE); + } + if (bod == BOD_OFF) + { + #if defined __AVR_ATmega328P__ + lowPowerBodOff(SLEEP_MODE_PWR_DOWN); + #else + lowPowerBodOn(SLEEP_MODE_PWR_DOWN); + #endif + } + else + { + lowPowerBodOn(SLEEP_MODE_PWR_DOWN); + } + + if (adc == ADC_OFF) ADCSRA |= (1 << ADEN); +} + +/******************************************************************************* +* Name: powerSave +* Description: Putting microcontroller into power save state. This is +* the lowest current consumption state after power down. +* Use this state together with an external 32.768 kHz crystal (but +* 8/16 MHz crystal/resonator need to be removed) to provide an +* asynchronous clock source to Timer 2. Please take note that +* Timer 2 is also used by the Arduino core for PWM operation. +* Please refer to wiring.c for explanation. Removal of the external +* 8/16 MHz crystal/resonator requires the microcontroller to run +* on its internal RC oscillator which is not so accurate for time +* critical operation. +* +* Argument Description +* ========= =========== +* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake +* up resource: +* (a) SLEEP_15MS - 15 ms sleep +* (b) SLEEP_30MS - 30 ms sleep +* (c) SLEEP_60MS - 60 ms sleep +* (d) SLEEP_120MS - 120 ms sleep +* (e) SLEEP_250MS - 250 ms sleep +* (f) SLEEP_500MS - 500 ms sleep +* (g) SLEEP_1S - 1 s sleep +* (h) SLEEP_2S - 2 s sleep +* (i) SLEEP_4S - 4 s sleep +* (j) SLEEP_8S - 8 s sleep +* (k) SLEEP_FOREVER - Sleep without waking up through WDT +* +* 2. adc ADC module disable control. Turning off the ADC module is +* basically removing the purpose of this low power mode. +* (a) ADC_OFF - Turn off ADC module +* (b) ADC_ON - Leave ADC module in its default state +* +* 3. bod Brown Out Detector (BOD) module disable control: +* (a) BOD_OFF - Turn off BOD module +* (b) BOD_ON - Leave BOD module in its default state +* +* 4. timer2 Timer 2 module disable control: +* (a) TIMER2_OFF - Turn off Timer 2 module +* (b) TIMER2_ON - Leave Timer 2 module in its default state +* +*******************************************************************************/ +void LowPowerClass::powerSave(period_t period, adc_t adc, bod_t bod, + timer2_t timer2) +{ + // Temporary clock source variable + unsigned char clockSource = 0; + + #if !defined(__AVR_ATmega32U4__) + if (timer2 == TIMER2_OFF) + { + if (TCCR2B & CS22) clockSource |= (1 << CS22); + if (TCCR2B & CS21) clockSource |= (1 << CS21); + if (TCCR2B & CS20) clockSource |= (1 << CS20); + + // Remove the clock source to shutdown Timer2 + TCCR2B &= ~(1 << CS22); + TCCR2B &= ~(1 << CS21); + TCCR2B &= ~(1 << CS20); + } + #endif + + if (adc == ADC_OFF) ADCSRA &= ~(1 << ADEN); + + if (period != SLEEP_FOREVER) + { + wdt_enable(period); + WDTCSR |= (1 << WDIE); + } + + if (bod == BOD_OFF) + { + #if defined __AVR_ATmega328P__ + lowPowerBodOff(SLEEP_MODE_PWR_SAVE); + #else + lowPowerBodOn(SLEEP_MODE_PWR_SAVE); + #endif + } + else + { + lowPowerBodOn(SLEEP_MODE_PWR_SAVE); + } + + if (adc == ADC_OFF) ADCSRA |= (1 << ADEN); + + #if !defined(__AVR_ATmega32U4__) + if (timer2 == TIMER2_OFF) + { + if (clockSource & CS22) TCCR2B |= (1 << CS22); + if (clockSource & CS21) TCCR2B |= (1 << CS21); + if (clockSource & CS20) TCCR2B |= (1 << CS20); + } + #endif +} + +/******************************************************************************* +* Name: powerStandby +* Description: Putting microcontroller into power standby state. +* +* Argument Description +* ========= =========== +* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake +* up resource: +* (a) SLEEP_15MS - 15 ms sleep +* (b) SLEEP_30MS - 30 ms sleep +* (c) SLEEP_60MS - 60 ms sleep +* (d) SLEEP_120MS - 120 ms sleep +* (e) SLEEP_250MS - 250 ms sleep +* (f) SLEEP_500MS - 500 ms sleep +* (g) SLEEP_1S - 1 s sleep +* (h) SLEEP_2S - 2 s sleep +* (i) SLEEP_4S - 4 s sleep +* (j) SLEEP_8S - 8 s sleep +* (k) SLEEP_FOREVER - Sleep without waking up through WDT +* +* 2. adc ADC module disable control. Turning off the ADC module is +* basically removing the purpose of this low power mode. +* (a) ADC_OFF - Turn off ADC module +* (b) ADC_ON - Leave ADC module in its default state +* +* 3. bod Brown Out Detector (BOD) module disable control: +* (a) BOD_OFF - Turn off BOD module +* (b) BOD_ON - Leave BOD module in its default state +* +*******************************************************************************/ +void LowPowerClass::powerStandby(period_t period, adc_t adc, bod_t bod) +{ + if (adc == ADC_OFF) ADCSRA &= ~(1 << ADEN); + + if (period != SLEEP_FOREVER) + { + wdt_enable(period); + WDTCSR |= (1 << WDIE); + } + + if (bod == BOD_OFF) + { + #if defined __AVR_ATmega328P__ + lowPowerBodOff(SLEEP_MODE_STANDBY); + #else + lowPowerBodOn(SLEEP_MODE_STANDBY); + #endif + } + else + { + lowPowerBodOn(SLEEP_MODE_STANDBY); + } + + if (adc == ADC_OFF) ADCSRA |= (1 << ADEN); +} + +/******************************************************************************* +* Name: powerExtStandby +* Description: Putting microcontroller into power extended standby state. This +* is different from the power standby state as it has the +* capability to run Timer 2 asynchronously. +* +* Argument Description +* ========= =========== +* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake +* up resource: +* (a) SLEEP_15MS - 15 ms sleep +* (b) SLEEP_30MS - 30 ms sleep +* (c) SLEEP_60MS - 60 ms sleep +* (d) SLEEP_120MS - 120 ms sleep +* (e) SLEEP_250MS - 250 ms sleep +* (f) SLEEP_500MS - 500 ms sleep +* (g) SLEEP_1S - 1 s sleep +* (h) SLEEP_2S - 2 s sleep +* (i) SLEEP_4S - 4 s sleep +* (j) SLEEP_8S - 8 s sleep +* (k) SLEEP_FOREVER - Sleep without waking up through WDT +* +* 2. adc ADC module disable control. +* (a) ADC_OFF - Turn off ADC module +* (b) ADC_ON - Leave ADC module in its default state +* +* 3. bod Brown Out Detector (BOD) module disable control: +* (a) BOD_OFF - Turn off BOD module +* (b) BOD_ON - Leave BOD module in its default state +* +* 4. timer2 Timer 2 module disable control: +* (a) TIMER2_OFF - Turn off Timer 2 module +* (b) TIMER2_ON - Leave Timer 2 module in its default state +* +*******************************************************************************/ +void LowPowerClass::powerExtStandby(period_t period, adc_t adc, bod_t bod, + timer2_t timer2) +{ + // Temporary clock source variable + unsigned char clockSource = 0; + + #if !defined(__AVR_ATmega32U4__) + if (timer2 == TIMER2_OFF) + { + if (TCCR2B & CS22) clockSource |= (1 << CS22); + if (TCCR2B & CS21) clockSource |= (1 << CS21); + if (TCCR2B & CS20) clockSource |= (1 << CS20); + + // Remove the clock source to shutdown Timer2 + TCCR2B &= ~(1 << CS22); + TCCR2B &= ~(1 << CS21); + TCCR2B &= ~(1 << CS20); + } + #endif + + if (adc == ADC_OFF) ADCSRA &= ~(1 << ADEN); + + if (period != SLEEP_FOREVER) + { + wdt_enable(period); + WDTCSR |= (1 << WDIE); + } + if (bod == BOD_OFF) + { + #if defined __AVR_ATmega328P__ + lowPowerBodOff(SLEEP_MODE_EXT_STANDBY); + #else + lowPowerBodOn(SLEEP_MODE_EXT_STANDBY); + #endif + } + else + { + lowPowerBodOn(SLEEP_MODE_EXT_STANDBY); + } + + if (adc == ADC_OFF) ADCSRA |= (1 << ADEN); + + #if !defined(__AVR_ATmega32U4__) + if (timer2 == TIMER2_OFF) + { + if (clockSource & CS22) TCCR2B |= (1 << CS22); + if (clockSource & CS21) TCCR2B |= (1 << CS21); + if (clockSource & CS20) TCCR2B |= (1 << CS20); + } + #endif +} + +/******************************************************************************* +* Name: ISR (WDT_vect) +* Description: Watchdog Timer interrupt service routine. This routine is +* required to allow automatic WDIF and WDIE bit clearance in +* hardware. +* +*******************************************************************************/ +ISR (WDT_vect) +{ + // WDIE & WDIF is cleared in hardware upon entering this ISR + wdt_disable(); +} + +LowPowerClass LowPower; \ No newline at end of file diff --git a/libraries/LowPower/LowPower.h b/libraries/LowPower/LowPower.h new file mode 100644 index 0000000..ef05901 --- /dev/null +++ b/libraries/LowPower/LowPower.h @@ -0,0 +1,137 @@ +#ifndef LowPower_h +#define LowPower_h + +enum period_t +{ + SLEEP_15Ms, + SLEEP_30MS, + SLEEP_60MS, + SLEEP_120MS, + SLEEP_250MS, + SLEEP_500MS, + SLEEP_1S, + SLEEP_2S, + SLEEP_4S, + SLEEP_8S, + SLEEP_FOREVER +}; + +enum bod_t +{ + BOD_OFF, + BOD_ON +}; + +enum adc_t +{ + ADC_OFF, + ADC_ON +}; + +enum timer5_t +{ + TIMER5_OFF, + TIMER5_ON +}; + +enum timer4_t +{ + TIMER4_OFF, + TIMER4_ON +}; + +enum timer3_t +{ + TIMER3_OFF, + TIMER3_ON +}; + +enum timer2_t +{ + TIMER2_OFF, + TIMER2_ON +}; + +enum timer1_t +{ + TIMER1_OFF, + TIMER1_ON +}; + +enum timer0_t +{ + TIMER0_OFF, + TIMER0_ON +}; + +enum spi_t +{ + SPI_OFF, + SPI_ON +}; + +enum usart0_t +{ + USART0_OFF, + USART0_ON +}; + +enum usart1_t +{ + USART1_OFF, + USART1_ON +}; + +enum usart2_t +{ + USART2_OFF, + USART2_ON +}; + +enum usart3_t +{ + USART3_OFF, + USART3_ON +}; + +enum twi_t +{ + TWI_OFF, + TWI_ON +}; + +enum usb_t +{ + USB_OFF, + USB_ON +}; + +class LowPowerClass +{ + public: + #if defined (__AVR_ATmega328P__) || defined (__AVR_ATmega168__) + void idle(period_t period, adc_t adc, timer2_t timer2, + timer1_t timer1, timer0_t timer0, spi_t spi, + usart0_t usart0, twi_t twi); + #elif defined __AVR_ATmega2560__ + void idle(period_t period, adc_t adc, timer5_t timer5, + timer4_t timer4, timer3_t timer3, timer2_t timer2, + timer1_t timer1, timer0_t timer0, spi_t spi, + usart3_t usart3, usart2_t usart2, usart1_t usart1, + usart0_t usart0, twi_t twi); + #elif defined __AVR_ATmega32U4__ + void idle(period_t period, adc_t adc, timer4_t timer4, timer3_t timer3, + timer1_t timer1, timer0_t timer0, spi_t spi, + usart1_t usart1, twi_t twi, usb_t usb); + #else + #error "Please ensure chosen MCU is either 328P, 32U4 or 2560." + #endif + void adcNoiseReduction(period_t period, adc_t adc, timer2_t timer2); + void powerDown(period_t period, adc_t adc, bod_t bod); + void powerSave(period_t period, adc_t adc, bod_t bod, timer2_t timer2); + void powerStandby(period_t period, adc_t adc, bod_t bod); + void powerExtStandby(period_t period, adc_t adc, bod_t bod, timer2_t timer2); +}; + +extern LowPowerClass LowPower; +#endif \ No newline at end of file diff --git a/libraries/LowPower/keywords.txt b/libraries/LowPower/keywords.txt new file mode 100644 index 0000000..ef2461c --- /dev/null +++ b/libraries/LowPower/keywords.txt @@ -0,0 +1,68 @@ +####################################### +# Syntax Coloring Map LowPower +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +idle KEYWORD2 +adcNoiseReduction KEYWORD2 +powerDown KEYWORD2 +powerSave KEYWORD2 +powerStandby KEYWORD2 +powerExtStandby KEYWORD2 + +####################################### +# Instances (KEYWORD2) +####################################### + +LowPower KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + +SLEEP_15MS LITERAL1 +SLEEP_30MS LITERAL1 +SLEEP_60MS LITERAL1 +SLEEP_120MS LITERAL1 +SLEEP_250MS LITERAL1 +SLEEP_500MS LITERAL1 +SLEEP_1S LITERAL1 +SLEEP_2S LITERAL1 +SLEEP_4S LITERAL1 +SLEEP_8S LITERAL1 +SLEEP_FOREVER LITERAL1 +ADC_OFF LITERAL1 +ADC_ON LITERAL1 +BOD_OFF LITERAL1 +BOD_ON LITERAL1 +TIMER4_OFF LITERAL1 +TIMER4_ON LITERAL1 +TIMER3_OFF LITERAL1 +TIMER3_ON LITERAL1 +TIMER2_OFF LITERAL1 +TIMER2_ON LITERAL1 +TIMER1_OFF LITERAL1 +TIMER1_ON LITERAL1 +TIMER0_OFF LITERAL1 +TIMER0_ON LITERAL1 +USART3_OFF LITERAL1 +USART3_ON LITERAL1 +USART2_OFF LITERAL1 +USART2_ON LITERAL1 +USART1_OFF LITERAL1 +USART1_ON LITERAL1 +USART0_OFF LITERAL1 +USART0_ON LITERAL1 +SPI_OFF LITERAL1 +SPI_ON LITERAL1 +TWI_OFF LITERAL1 +TWI_ON LITERAL1 +USB_OFF LITERAL1 +USB_ON LITERAL1 \ No newline at end of file diff --git a/libraries/MsTimer2/examples/FlashLed/FlashLed.pde b/libraries/MsTimer2/examples/FlashLed/FlashLed.pde deleted file mode 100644 index 4d04496..0000000 --- a/libraries/MsTimer2/examples/FlashLed/FlashLed.pde +++ /dev/null @@ -1,42 +0,0 @@ -char dummyvar; // to get Arduinoi IDE to include core headers properly - -/* - MsTimer2 is a small and very easy to use library to interface Timer2 with - humans. It's called MsTimer2 because it "hardcodes" a resolution of 1 - millisecond on timer2 - For Details see: http://www.arduino.cc/playground/Main/MsTimer2 -*/ -#include - -// Switch on LED on and off each half second - -#if defined(ARDUINO) && ARDUINO >= 100 -const int led_pin = LED_BUILTIN; // 1.0 built in LED pin var -#else -#if defined(CORE_LED0_PIN) -const int led_pin = CORE_LED0_PIN; // 3rd party LED pin define -#else -const int led_pin = 13; // default to pin 13 -#endif -#endif - - -void flash() -{ - static boolean output = HIGH; - - digitalWrite(led_pin, output); - output = !output; -} - -void setup() -{ - pinMode(led_pin, OUTPUT); - - MsTimer2::set(500, flash); // 500ms period - MsTimer2::start(); -} - -void loop() -{ -} diff --git a/libraries/MsTimer2/keywords.txt b/libraries/MsTimer2/keywords.txt deleted file mode 100644 index 8b4fff7..0000000 --- a/libraries/MsTimer2/keywords.txt +++ /dev/null @@ -1,4 +0,0 @@ -MsTimer2 KEYWORD1 -set KEYWORD2 -start KEYWORD2 -stop KEYWORD2 diff --git a/libraries/MySensors/Config.h b/libraries/MySensors/Config.h deleted file mode 100644 index 49270d4..0000000 --- a/libraries/MySensors/Config.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef Config_h -#define Config_h - -/*** - * Configure Sensor Network - */ -#define RF24_CHANNEL 76 //RF channel for the sensor net, 0-127 -#define RF24_DATARATE RF24_2MBPS //RF24_250KBPS for 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS for 2Mbps -#define RF24_PA_LEVEL RF24_PA_MAX //Senor PA Level == RF24_PA_MIN=-18dBm, RF24_PA_LOW=-12dBm, RF24_PA_HIGH=-6dBM, and RF24_PA_MAX=0dBm -#define RF24_PA_LEVEL_GW RF24_PA_LEVEL //Gateway PA Level, defaults to Sensor net PA Level. Tune here if using an amplified nRF2401+ in your gateway. - -/*** - * Enable/Disable debug logging - */ -//#define DEBUG - -#endif diff --git a/libraries/MySensors/Gateway.cpp b/libraries/MySensors/Gateway.cpp deleted file mode 100644 index 2470fe5..0000000 --- a/libraries/MySensors/Gateway.cpp +++ /dev/null @@ -1,260 +0,0 @@ -/* - The MySensors Arduino library adds a new layer on top of the RF24 library. - It handles radio network routing, relaying and ids. - - Created by Henrik Ekblad - - 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. -*/ - -#include "Gateway.h" - -Gateway::Gateway(uint8_t _cepin, uint8_t _cspin, uint8_t _inclusion_time) : Relay(_cepin, _cspin) { - ledMode = false; - isRelay = true; - inclusionTime = _inclusion_time; -} - -Gateway::Gateway(uint8_t _cepin, uint8_t _cspin, uint8_t _inclusion_time, uint8_t _inclusion_pin, uint8_t _rx, uint8_t _tx, uint8_t _er) : Relay(_cepin, _cspin) { - ledMode = true; - isRelay = true; - pinInclusion = _inclusion_pin; - inclusionTime = _inclusion_time; - pinRx = _rx; - pinTx = _tx; - pinEr = _er; -} - -void Gateway::begin(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate, void (*inDataCallback)(char *)) { - Serial.begin(BAUD_RATE); - - if (inDataCallback != NULL) { - useWriteCallback = true; - dataCallback = inDataCallback; - } else { - useWriteCallback = false; - } - - radioId = 0; - distance = 0; - inclusionMode = 0; - buttonTriggeredInclusion = false; - countRx = 0; - countTx = 0; - countErr = 0; - - if (ledMode) { - // Setup led pins - pinMode(pinRx, OUTPUT); - pinMode(pinTx, OUTPUT); - pinMode(pinEr, OUTPUT); - digitalWrite(pinRx, LOW); - digitalWrite(pinTx, LOW); - digitalWrite(pinEr, LOW); - - // Setup digital in that triggers inclusion mode - pinMode(pinInclusion, INPUT); - digitalWrite(pinInclusion, HIGH); - - // Set initial state of leds - digitalWrite(pinRx, HIGH); - digitalWrite(pinTx, HIGH); - digitalWrite(pinEr, HIGH); - - } - - // Start up the radio library - setupRadio(paLevel, channel, dataRate); - RF24::openReadingPipe(CURRENT_NODE_PIPE, BASE_RADIO_ID); - RF24::startListening(); - - // Send startup log message on serial - serial(PSTR("0;0;%d;%d;Arduino startup complete.\n"), M_INTERNAL, I_LOG_MESSAGE); - -} - - -boolean Gateway::isLedMode() { - return ledMode; -} - -void Gateway::startInclusionInterrupt() { - buttonTriggeredInclusion = true; -} - - -void Gateway::checkButtonTriggeredInclusion() { - if (buttonTriggeredInclusion) { - // Ok, someone pressed the inclusion button on the gateway - // start inclusion mode for 1 munute. - serial(PSTR("0;0;%d;%d;Inclusion started by button.\n"), M_INTERNAL, I_LOG_MESSAGE); - buttonTriggeredInclusion = false; - setInclusionMode(true); - -#ifdef DEBUG - sendChildren(); -#endif - - } -} - -void Gateway::checkInclusionFinished() { - if (inclusionMode && millis()-inclusionStartTime>60000UL*inclusionTime) { - // inclusionTimeInMinutes minute(s) has passed.. stop inclusion mode - setInclusionMode(false); - } -} - - -void Gateway::parseAndSend(char *commandBuffer) { - boolean ok = false; - char *str, *p, *value=NULL; - int i = 0; - uint16_t sensorRadioId = 0; - uint8_t childId = 0; - uint8_t messageType = 0; - uint8_t type = 0; - - // Extract command data coming on serial line - for (str = strtok_r(commandBuffer, ";", &p); // split using semicolon - str && i < 5; // loop while str is not null an max 5 times - str = strtok_r(NULL, ";", &p) // get subsequent tokens - ) { - switch (i) { - case 0: // Radioid (destination) - sensorRadioId = atoi(str); - break; - case 1: // Childid - childId = atoi(str); - break; - case 2: // Message type - messageType = atoi(str); - break; - case 3: // Data type - type = atoi(str); - break; - case 4: // Variable value - value = str; - break; - } - i++; - } - - if (sensorRadioId==GATEWAY_ADDRESS && messageType==M_INTERNAL) { - // Handle messages directed to gateway - if (type == I_VERSION) { - // Request for version - serial(PSTR("0;0;%d;%d;%s\n"),M_INTERNAL, I_VERSION, LIBRARY_VERSION); - } else if (type == I_INCLUSION_MODE) { - // Request to change inclusion mode - setInclusionMode(atoi(value) == 1); - } - } else { - txBlink(1); - - ok = sendData(GATEWAY_ADDRESS, sensorRadioId, childId, messageType, type, value, strlen(value), false); - if (!ok) { - errBlink(1); - } - } -} - - -void Gateway::setInclusionMode(boolean newMode) { - if (newMode != inclusionMode) - inclusionMode = newMode; - // Send back mode change on serial line to ack command - serial(PSTR("0;0;%d;%d;%d\n"), M_INTERNAL, I_INCLUSION_MODE, inclusionMode?1:0); - - if (inclusionMode) { - inclusionStartTime = millis(); - } -} - - -// Override normal validate to add error blink if crc check fails -uint8_t Gateway::validate(uint8_t length) { - uint8_t res = Sensor::validate(length); - if (res == VALIDATE_BAD_CRC) { - errBlink(1); - } - return res; -} - -void Gateway::processRadioMessage() { - if (messageAvailable()) { - // A new message was received from one of the sensors - message_s msg = getMessage(); - if (msg.header.messageType == M_PRESENTATION && inclusionMode) { - rxBlink(3); - } else { - rxBlink(1); - } - // Pass along the message from sensors to serial line - serial(msg); - } - - checkButtonTriggeredInclusion(); - checkInclusionFinished(); -} - -void Gateway::serial(const char *fmt, ... ) { - va_list args; - va_start (args, fmt ); - vsnprintf_P(serialBuffer, MAX_SEND_LENGTH, fmt, args); - va_end (args); - Serial.print(serialBuffer); - if (useWriteCallback) { - // We have a registered write callback (probably Ethernet) - dataCallback(serialBuffer); - } -} - -void Gateway::serial(message_s msg) { - serial(PSTR("%d;%d;%d;%d;%s\n"),msg.header.from, msg.header.childId, msg.header.messageType, msg.header.type, msg.data); -} - - -void Gateway::ledTimersInterrupt() { - if(countRx && countRx != 255) { - // switch led on - digitalWrite(pinRx, LOW); - } else if(!countRx) { - // switching off - digitalWrite(pinRx, HIGH); - } - if(countRx != 255) { countRx--; } - - if(countTx && countTx != 255) { - // switch led on - digitalWrite(pinTx, LOW); - } else if(!countTx) { - // switching off - digitalWrite(pinTx, HIGH); - } - if(countTx != 255) { countTx--; } - else if(inclusionMode) { countTx = 8; } - - if(countErr && countErr != 255) { - // switch led on - digitalWrite(pinEr, LOW); - } else if(!countErr) { - // switching off - digitalWrite(pinEr, HIGH); - } - if(countErr != 255) { countErr--; } - -} - -void Gateway::rxBlink(uint8_t cnt) { - if(countRx == 255) { countRx = cnt; } -} -void Gateway::txBlink(uint8_t cnt) { - if(countTx == 255 && !inclusionMode) { countTx = cnt; } -} -void Gateway::errBlink(uint8_t cnt) { - if(countErr == 255) { countErr = cnt; } -} - diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h new file mode 100644 index 0000000..aedf051 --- /dev/null +++ b/libraries/MySensors/MyConfig.h @@ -0,0 +1,23 @@ +#ifndef MyConfig_h +#define MyConfig_h + +/*** + * Configure Sensor Network + */ +#define RF24_CHANNEL 76 //RF channel for the sensor net, 0-127 +#define RF24_DATARATE RF24_250KBPS //RF24_250KBPS for 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS for 2Mbps +#define RF24_PA_LEVEL RF24_PA_MAX //Sensor PA Level == RF24_PA_MIN=-18dBm, RF24_PA_LOW=-12dBm, RF24_PA_HIGH=-6dBM, and RF24_PA_MAX=0dBm +#define RF24_PA_LEVEL_GW RF24_PA_LEVEL //Gateway PA Level, defaults to Sensor net PA Level. Tune here if using an amplified nRF2401+ in your gateway. +#define BASE_RADIO_ID ((uint64_t)0xA8A8E1FC00LL) // This is also act as base value for sensor nodeId addresses. Change this (or channel) if you have more than one sensor network. + +// MySensors online examples defaults +#define DEFAULT_CE_PIN 9 +#define DEFAULT_CS_PIN 10 + + +/*** + * Enable/Disable debug logging + */ +#define DEBUG + +#endif diff --git a/libraries/MySensors/MyGateway.cpp b/libraries/MySensors/MyGateway.cpp new file mode 100644 index 0000000..c8848cf --- /dev/null +++ b/libraries/MySensors/MyGateway.cpp @@ -0,0 +1,294 @@ +/* + The MySensors library adds a new layer on top of the RF24 library. + It handles radio network routing, relaying and ids. + + Created by Henrik Ekblad + + 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. +*/ + +#include "MyGateway.h" +#include "utility/MsTimer2.h" +#include "utility/PinChangeInt.h" + + +uint8_t pinRx; +uint8_t pinTx; +uint8_t pinEr; +boolean buttonTriggeredInclusion; +volatile uint8_t countRx; +volatile uint8_t countTx; +volatile uint8_t countErr; +boolean inclusionMode; // Keeps track on inclusion mode + + +MyGateway::MyGateway(uint8_t _cepin, uint8_t _cspin, uint8_t _inclusion_time, uint8_t _inclusion_pin, uint8_t _rx, uint8_t _tx, uint8_t _er) : MySensor(_cepin, _cspin) { + pinInclusion = _inclusion_pin; + inclusionTime = _inclusion_time; + pinRx = _rx; + pinTx = _tx; + pinEr = _er; +} + + +void MyGateway::begin(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate, void (*inDataCallback)(char *)) { + Serial.begin(BAUD_RATE); + repeaterMode = true; + isGateway = true; + setupRepeaterMode(); + + if (inDataCallback != NULL) { + useWriteCallback = true; + dataCallback = inDataCallback; + } else { + useWriteCallback = false; + } + + nc.nodeId = 0; + nc.distance = 0; + inclusionMode = 0; + buttonTriggeredInclusion = false; + countRx = 0; + countTx = 0; + countErr = 0; + + // Setup led pins + pinMode(pinRx, OUTPUT); + pinMode(pinTx, OUTPUT); + pinMode(pinEr, OUTPUT); + digitalWrite(pinRx, LOW); + digitalWrite(pinTx, LOW); + digitalWrite(pinEr, LOW); + + // Setup digital in that triggers inclusion mode + pinMode(pinInclusion, INPUT); + digitalWrite(pinInclusion, HIGH); + + // Set initial state of leds + digitalWrite(pinRx, HIGH); + digitalWrite(pinTx, HIGH); + digitalWrite(pinEr, HIGH); + + + // Start up the radio library + setupRadio(paLevel, channel, dataRate); + RF24::openReadingPipe(WRITE_PIPE, BASE_RADIO_ID); + RF24::openReadingPipe(CURRENT_NODE_PIPE, BASE_RADIO_ID); + RF24::startListening(); + + // Add led timer interrupt + MsTimer2::set(300, ledTimersInterrupt); + MsTimer2::start(); + + // Add interrupt for inclusion button to pin + PCintPort::attachInterrupt(pinInclusion, startInclusionInterrupt, RISING); + + // Send startup log message on serial + serial(PSTR("0;0;%d;0;%d;Gateway startup complete.\n"), C_INTERNAL, I_GATEWAY_READY); +} + + +void startInclusionInterrupt() { + buttonTriggeredInclusion = true; +} + + + +void MyGateway::checkButtonTriggeredInclusion() { + if (buttonTriggeredInclusion) { + // Ok, someone pressed the inclusion button on the gateway + // start inclusion mode for 1 munute. + serial(PSTR("0;0;%d;0;%d;Inclusion started by button.\n"), C_INTERNAL, I_LOG_MESSAGE); + buttonTriggeredInclusion = false; + setInclusionMode(true); + } +} + +void MyGateway::checkInclusionFinished() { + if (inclusionMode && millis()-inclusionStartTime>60000UL*inclusionTime) { + // inclusionTimeInMinutes minute(s) has passed.. stop inclusion mode + setInclusionMode(false); + } +} + +uint8_t MyGateway::h2i(char c) { + uint8_t i = 0; + if (c <= '9') + i += c - '0'; + else if (c >= 'a') + i += c - 'a' + 10; + else + i += c - 'A' + 10; + return i; +} + +void MyGateway::parseAndSend(char *commandBuffer) { + boolean ok = false; + char *str, *p, *value=NULL; + uint8_t bvalue[MAX_PAYLOAD]; + uint8_t blen = 0; + int i = 0; + uint16_t destination = 0; + uint8_t sensor = 0; + uint8_t command = 0; + uint8_t type = 0; + uint8_t ack = 0; + + // Extract command data coming on serial line + for (str = strtok_r(commandBuffer, ";", &p); // split using semicolon + str && i < 6; // loop while str is not null an max 5 times + str = strtok_r(NULL, ";", &p) // get subsequent tokens + ) { + switch (i) { + case 0: // Radioid (destination) + destination = atoi(str); + break; + case 1: // Childid + sensor = atoi(str); + break; + case 2: // Message type + command = atoi(str); + break; + case 3: // Should we request ack from destination? + ack = atoi(str); + break; + case 4: // Data type + type = atoi(str); + break; + case 5: // Variable value + if (command == C_STREAM) { + blen = 0; + uint8_t val; + while (*str) { + val = h2i(*str++) << 4; + val += h2i(*str++); + bvalue[blen] = val; + blen++; + } + } else { + value = str; + } + break; + } + i++; + } + + if (destination==GATEWAY_ADDRESS && command==C_INTERNAL) { + // Handle messages directed to gateway + if (type == I_VERSION) { + // Request for version + serial(PSTR("0;0;%d;0;%d;%s\n"),C_INTERNAL, I_VERSION, LIBRARY_VERSION); + } else if (type == I_INCLUSION_MODE) { + // Request to change inclusion mode + setInclusionMode(atoi(value) == 1); + } + } else { + txBlink(1); + msg.sender = GATEWAY_ADDRESS; + msg.destination = destination; + msg.sensor = sensor; + msg.type = type; + mSetCommand(msg,command); + mSetRequestAck(msg,ack?1:0); + mSetAck(msg,false); + msg.set(value); + if (command == C_STREAM) + msg.set(bvalue, blen); + else + msg.set(value); + ok = sendRoute(msg); + if (!ok) { + errBlink(1); + } + } +} + + +void MyGateway::setInclusionMode(boolean newMode) { + if (newMode != inclusionMode) + inclusionMode = newMode; + // Send back mode change on serial line to ack command + serial(PSTR("0;0;%d;0;%d;%d\n"), C_INTERNAL, I_INCLUSION_MODE, inclusionMode?1:0); + + if (inclusionMode) { + inclusionStartTime = millis(); + } +} + +void MyGateway::processRadioMessage() { + if (process()) { + // A new message was received from one of the sensors + MyMessage message = getLastMessage(); + if (mGetCommand(message) == C_PRESENTATION && inclusionMode) { + rxBlink(3); + } else { + rxBlink(1); + } + // Pass along the message from sensors to serial line + serial(message); + } + + checkButtonTriggeredInclusion(); + checkInclusionFinished(); +} + +void MyGateway::serial(const char *fmt, ... ) { + va_list args; + va_start (args, fmt ); + vsnprintf_P(serialBuffer, MAX_SEND_LENGTH, fmt, args); + va_end (args); + Serial.print(serialBuffer); + if (useWriteCallback) { + // We have a registered write callback (probably Ethernet) + dataCallback(serialBuffer); + } +} + +void MyGateway::serial(MyMessage &msg) { + serial(PSTR("%d;%d;%d;%d;%d;%s\n"),msg.sender, msg.sensor, mGetCommand(msg), mGetAck(msg), msg.type, msg.getString(convBuf)); +} + + +void ledTimersInterrupt() { + if(countRx && countRx != 255) { + // switch led on + digitalWrite(pinRx, LOW); + } else if(!countRx) { + // switching off + digitalWrite(pinRx, HIGH); + } + if(countRx != 255) { countRx--; } + + if(countTx && countTx != 255) { + // switch led on + digitalWrite(pinTx, LOW); + } else if(!countTx) { + // switching off + digitalWrite(pinTx, HIGH); + } + if(countTx != 255) { countTx--; } + else if(inclusionMode) { countTx = 8; } + + if(countErr && countErr != 255) { + // switch led on + digitalWrite(pinEr, LOW); + } else if(!countErr) { + // switching off + digitalWrite(pinEr, HIGH); + } + if(countErr != 255) { countErr--; } + +} + +void MyGateway::rxBlink(uint8_t cnt) { + if(countRx == 255) { countRx = cnt; } +} +void MyGateway::txBlink(uint8_t cnt) { + if(countTx == 255 && !inclusionMode) { countTx = cnt; } +} +void MyGateway::errBlink(uint8_t cnt) { + if(countErr == 255) { countErr = cnt; } +} + diff --git a/libraries/MySensors/Gateway.h b/libraries/MySensors/MyGateway.h similarity index 67% rename from libraries/MySensors/Gateway.h rename to libraries/MySensors/MyGateway.h index 692997f..21a93d6 100644 --- a/libraries/MySensors/Gateway.h +++ b/libraries/MySensors/MyGateway.h @@ -1,5 +1,5 @@ /* - The MySensors Arduino library adds a new layer on top of the RF24 library. + The MySensors library adds a new layer on top of the RF24 library. It handles radio network routing, relaying and ids. Created by Henrik Ekblad @@ -9,21 +9,21 @@ version 2 as published by the Free Software Foundation. */ -#ifndef Gateway_h -#define Gateway_h +#ifndef MyGateway_h +#define MyGateway_h -#include "Relay.h" +#include "MySensor.h" -#define MAX_RECEIVE_LENGTH 100 // Max buffersize needed for messages coming from vera -#define MAX_SEND_LENGTH 120 // Max buffersize needed for messages coming from vera +#define MAX_RECEIVE_LENGTH 100 // Max buffersize needed for messages coming from controller +#define MAX_SEND_LENGTH 120 // Max buffersize needed for messages destined for controller -class Gateway : public Relay +class MyGateway : public MySensor { public: /** * Constructor * - * Creates a new instance of Gateway class. + * Creates a new instance of MyGateway class. * If you don't use status leds and/or inclusion mode button on your arduino gateway * you can disable this functionality by calling the 2 argument constructor. * @@ -36,41 +36,27 @@ class Gateway : public Relay * @param _er Digital pin for error led * */ - Gateway(uint8_t _cepin=9, uint8_t _cspin=10, uint8_t _inclusion_time = 1); - Gateway(uint8_t _cepin, uint8_t _cspin, uint8_t _inclusion_time, uint8_t _inclusion_pin, uint8_t _rx, uint8_t _tx, uint8_t _er); + MyGateway(uint8_t _cepin=DEFAULT_CE_PIN, uint8_t _cspin=DEFAULT_CS_PIN, uint8_t _inclusion_time = 1, uint8_t _inclusion_pin = 3, uint8_t _rx=6, uint8_t _tx=5, uint8_t _er=4); /* Use this and pass a function that should be called when you want to process commands that arrive from radio network */ void begin(rf24_pa_dbm_e paLevel=RF24_PA_LEVEL_GW, uint8_t channel=RF24_CHANNEL, rf24_datarate_e dataRate=RF24_DATARATE, void (*dataCallback)(char *)=NULL); void processRadioMessage(); void parseAndSend(char *inputString); - boolean isLedMode(); - void ledTimersInterrupt(); - void startInclusionInterrupt(); private: + char convBuf[MAX_PAYLOAD*2+1]; char serialBuffer[MAX_SEND_LENGTH]; // Buffer for building string when sending data to vera unsigned long inclusionStartTime; - boolean inclusionMode; // Keeps track on inclusion mode - boolean buttonTriggeredInclusion; - volatile uint8_t countRx; - volatile uint8_t countTx; - volatile uint8_t countErr; - boolean ledMode; boolean useWriteCallback; void (*dataCallback)(char *); - - uint8_t pinInclusion; uint8_t inclusionTime; - uint8_t pinRx; - uint8_t pinTx; - uint8_t pinEr; + + uint8_t h2i(char c); void serial(const char *fmt, ... ); - uint8_t validate(uint8_t length); - void serial(message_s msg); - void interruptStartInclusion(); + void serial(MyMessage &msg); void checkButtonTriggeredInclusion(); void setInclusionMode(boolean newMode); void checkInclusionFinished(); @@ -80,6 +66,7 @@ class Gateway : public Relay void errBlink(uint8_t cnt); }; - +void ledTimersInterrupt(); +void startInclusionInterrupt(); #endif diff --git a/libraries/MySensors/MyMQTT.cpp b/libraries/MySensors/MyMQTT.cpp new file mode 100755 index 0000000..610414e --- /dev/null +++ b/libraries/MySensors/MyMQTT.cpp @@ -0,0 +1,326 @@ +/* +The MySensors library adds a new layer on top of the RF24 library. +It handles radio network routing, relaying and ids. + +Created by Henrik Ekblad +Modified by Daniel Wiegert +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. +*/ + +#include "MyMQTT.h" +#include "utility/MsTimer2.h" + +char V_0[] PROGMEM = "TEMP"; //V_TEMP +char V_1[] PROGMEM = "HUM"; //V_HUM +char V_2[] PROGMEM = "LIGHT"; //V_LIGHT +char V_3[] PROGMEM = "DIMMER"; //V_DIMMER +char V_4[] PROGMEM = "PRESSURE"; //V_PRESSURE +char V_5[] PROGMEM = "FORECAST"; //V_FORECAST +char V_6[] PROGMEM = "RAIN"; //V_RAIN +char V_7[] PROGMEM = "RAINRATE"; //V_RAINRATE +char V_8[] PROGMEM = "WIND"; //V_WIND +char V_9[] PROGMEM = "GUST"; //V_GUST +char V_10[] PROGMEM = "DIRECTON"; //V_DIRECTON +char V_11[] PROGMEM = "UV"; //V_UV +char V_12[] PROGMEM = "WEIGHT"; //V_WEIGHT +char V_13[] PROGMEM = "DISTANCE"; //V_DISTANCE +char V_14[] PROGMEM = "IMPEDANCE"; //V_IMPEDANCE +char V_15[] PROGMEM = "ARMED"; //V_ARMED +char V_16[] PROGMEM = "TRIPPED"; //V_TRIPPED +char V_17[] PROGMEM = "WATT"; //V_WATT +char V_18[] PROGMEM = "KWH"; //V_KWH +char V_19[] PROGMEM = "SCENE_ON"; //V_SCENE_ON +char V_20[] PROGMEM = "SCENE_OFF"; //V_SCENE_OFF +char V_21[] PROGMEM = "HEATER"; //V_HEATER +char V_22[] PROGMEM = "HEATER_SW"; //V_HEATER_SW +char V_23[] PROGMEM = "LIGHT_LEVEL"; //V_LIGHT_LEVEL +char V_24[] PROGMEM = "VAR1"; //V_VAR1 +char V_25[] PROGMEM = "VAR2"; //V_VAR2 +char V_26[] PROGMEM = "VAR3"; //V_VAR3 +char V_27[] PROGMEM = "VAR4"; //V_VAR4 +char V_28[] PROGMEM = "VAR5"; //V_VAR5 +char V_29[] PROGMEM = "UP"; //V_UP +char V_30[] PROGMEM = "DOWN"; //V_DOWN +char V_31[] PROGMEM = "STOP"; //V_STOP +char V_32[] PROGMEM = "IR_SEND"; //V_IR_SEND +char V_33[] PROGMEM = "IR_RECEIVE"; //V_IR_RECEIVE +char V_34[] PROGMEM = "FLOW"; //V_FLOW +char V_35[] PROGMEM = "VOLUME"; //V_VOLUME +char V_36[] PROGMEM = "LOCK_STATUS"; //V_LOCK_STATUS +char V_37[] PROGMEM = "DUST_LEVEL"; //V_DUST_LEVEL +char V_38[] PROGMEM = "VOLTAGE"; //V_VOLTAGE +char V_39[] PROGMEM = "CURRENT"; //V_CURRENT +char V_40[] PROGMEM = ""; // +char V_41[] PROGMEM = ""; // +char V_42[] PROGMEM = ""; // +char V_43[] PROGMEM = ""; // +char V_44[] PROGMEM = ""; // +char V_45[] PROGMEM = ""; // +char V_46[] PROGMEM = ""; // +char V_47[] PROGMEM = ""; // +char V_48[] PROGMEM = ""; // +char V_49[] PROGMEM = ""; // +char V_50[] PROGMEM = ""; // +char V_51[] PROGMEM = ""; // +char V_52[] PROGMEM = ""; // +char V_53[] PROGMEM = ""; // +char V_54[] PROGMEM = ""; // +char V_55[] PROGMEM = ""; // +char V_56[] PROGMEM = ""; // +char V_57[] PROGMEM = ""; // +char V_58[] PROGMEM = ""; // +char V_59[] PROGMEM = ""; // +char V_60[] PROGMEM = "Started!\n"; //Custom for MQTTGateway +char V_61[] PROGMEM = "SKETCH_NAME"; //Custom for MQTTGateway +char V_62[] PROGMEM = "SKETCH_VERSION"; //Custom for MQTTGateway +char V_63[] PROGMEM = "UNKNOWN"; //Custom for MQTTGateway + +////////////////////////////////////////////////////////////////// + +PROGMEM const char *vType[] = { + V_0, V_1, V_2, V_3, V_4, V_5, V_6, V_7, V_8, V_9, V_10, + V_11, V_12, V_13, V_14, V_15, V_16, V_17, V_18, V_19, V_20, + V_21, V_22, V_23, V_24, V_25, V_26, V_27, V_28, V_29, V_30, + V_31, V_32, V_33, V_34, V_35, V_36, V_37, V_38, V_39, V_40, + V_41, V_42, V_43, V_44, V_45, V_46, V_47, V_48, V_49, V_50, + V_51, V_52, V_53, V_54, V_55, V_56, V_57, V_58, V_59, V_60, + V_61, V_62, V_63 +}; + + +char broker[] PROGMEM = MQTT_BROKER_PREFIX; + +#define S_FIRSTCUSTOM 60 +#define TYPEMAXLEN 20 +#define V_TOTAL (sizeof(vType)/sizeof(char *))-1 + +extern volatile uint8_t countRx; +extern volatile uint8_t countTx; +extern volatile uint8_t countErr; +extern uint8_t pinRx; +extern uint8_t pinTx; +extern uint8_t pinEr; + +MyMQTT::MyMQTT(uint8_t _cepin, uint8_t _cspin) : +MySensor(_cepin, _cspin) { + +} + +inline MyMessage& build (MyMessage &msg, uint8_t sender, uint8_t destination, uint8_t sensor, uint8_t command, uint8_t type, bool enableAck) { + msg.destination = destination; + msg.sender = sender; + msg.sensor = sensor; + msg.type = type; + mSetCommand(msg,command); + mSetRequestAck(msg,enableAck); + mSetAck(msg,false); + return msg; +} + +char *MyMQTT::getType(char *b, const char **index) { + char *q = b; + char *p = (char *)pgm_read_word(index); + while (*q++ = pgm_read_byte(p++)); + *q=0; + return b; +} + +void MyMQTT::begin(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate, void (*inDataCallback) + (const char *, uint8_t *), uint8_t _rx, uint8_t _tx, uint8_t _er) { + Serial.begin(BAUD_RATE); + repeaterMode = true; + isGateway = true; + MQTTClientConnected = false; + + setupRepeaterMode(); + dataCallback = inDataCallback; + + nc.nodeId = 0; + nc.distance = 0; + + // Start up the radio library + setupRadio(paLevel, channel, dataRate); + RF24::openReadingPipe(WRITE_PIPE, BASE_RADIO_ID); + RF24::openReadingPipe(CURRENT_NODE_PIPE, BASE_RADIO_ID); + RF24::startListening(); + + pinRx = _rx; + pinMode(pinRx, OUTPUT); + pinTx = _tx; + pinMode(pinTx, OUTPUT); + pinEr = _er; + pinMode(pinEr, OUTPUT); + + MsTimer2::set(200, ledTimersInterrupt); + MsTimer2::start(); + + Serial.print(getType(convBuf, &vType[S_FIRSTCUSTOM])); +} + +void MyMQTT::processRadioMessage() { + if (process()) { + // A new message was received from one of the sensors + MyMessage message = getLastMessage(); + // Pass along the message from sensors to serial line + rxBlink(1); + SendMQTT(message); + } + +} + +void MyMQTT::processMQTTMessage(char *inputString, uint8_t inputPos) { + char *str, *p; + uint8_t i = 0; + buffer[0]= 0; + buffsize = 0; + + if ((uint8_t)inputString[0] >> 4 == MQTTCONNECT) { + buffer[buffsize++] = MQTTCONNACK << 4; + buffer[buffsize++] = 0x02; // Remaining length + buffer[buffsize++] = 0x00; // Connection accepted + buffer[buffsize++] = 0x00; // Reserved + MQTTClientConnected=true; // We have connection! + } + if ((uint8_t)inputString[0] >> 4 == MQTTPINGREQ) { + buffer[buffsize++] = MQTTPINGRESP << 4; + buffer[buffsize++] = 0x00; + } + if ((uint8_t)inputString[0] >> 4 == MQTTSUBSCRIBE) { + buffer[buffsize++] = MQTTSUBACK << 4; // Just ack everything, we actually dont really care! + buffer[buffsize++] = 0x03; // Remaining length + buffer[buffsize++] = (uint8_t)inputString[2]; // Message ID MSB + buffer[buffsize++] = (uint8_t)inputString[3]; // Message ID LSB + buffer[buffsize++] = MQTTQOS0; // QOS level + } + if ((uint8_t)inputString[0] >> 4 == MQTTUNSUBSCRIBE) { + buffer[buffsize++] = MQTTUNSUBACK << 4; + buffer[buffsize++] = 0x02; // Remaining length + buffer[buffsize++] = (uint8_t)inputString[2]; // Message ID MSB + buffer[buffsize++] = (uint8_t)inputString[3]; // Message ID LSB + } + if ((uint8_t)inputString[0] >> 4 == MQTTDISCONNECT) { + MQTTClientConnected=false; // We lost connection! + } + if (buffsize > 0) { + dataCallback(buffer,&buffsize); + } + + // We publish everything we get, we dont care if its subscribed or not! + if ((uint8_t)inputString[0] >> 4 == MQTTPUBLISH || (MQTT_SEND_SUBSCRIPTION && (uint8_t)inputString[0] >> 4 == MQTTSUBSCRIBE)) { + buffer[0]= 0; + buffsize = 0; + // Cut out address and payload depending on message type. + if ((uint8_t)inputString[0] >> 4 == MQTTSUBSCRIBE) { + strncat(buffer,inputString+6,inputString[5]); + } else { + strncat(buffer,inputString+4,inputString[3]); + } + + // TODO: Check if we should send ack or not. + for (str = strtok_r(buffer,"/",&p) ; str && i<4 ; str = strtok_r(NULL,"/",&p)) { + if (i == 0) { + if (strcmp_P(str,broker)!=0) { //look for MQTT_BROKER_PREFIX + return; //Message not for us or malformatted! + } + } else if (i==1) { + msg.destination = atoi(str); //NodeID + } else if (i==2) { + msg.sensor = atoi(str); //SensorID + } else if (i==3) { + char match=0; //SensorType + //strcpy(str,(char*)&str[2]); //Strip V_ + + for (uint8_t j=0; strcpy_P(convBuf, (char*)pgm_read_word(&(vType[j]))) ; j++) { + if (strcmp((char*)&str[2],convBuf)==0) { //Strip V_ and compare + match=j; + break; + } + if (j >= V_TOTAL) { // No match found! + match=V_TOTAL; // last item. + break; + } + } + msg.type = match; + } + i++; + } //Check if packge has payload + if ((uint8_t)inputString[1] > (uint8_t)(inputString[3]+2) && !((uint8_t)inputString[0] >> 4 == MQTTSUBSCRIBE)) { + strcpy(convBuf,inputString+(inputString[3]+4)); + msg.set(convBuf); //Payload + } else { + msg.set(""); //No payload + } + txBlink(1); + if (!sendRoute(build(msg, GATEWAY_ADDRESS, msg.destination, msg.sensor, C_SET, msg.type, 0))) errBlink(1); + + } +} + +void MyMQTT::SendMQTT(MyMessage &msg) { + buffsize = 0; + if (!MQTTClientConnected) return; //We have no connections - return + if (msg.isAck()) { + Serial.println("msg is ack!"); + if (msg.sender==255 && mGetCommand(msg)==C_INTERNAL && msg.type==I_ID_REQUEST) { + // TODO: sending ACK request on id_response fucks node up. doesn't work. + // The idea was to confirm id and save to EEPROM_LATEST_NODE_ADDRESS. + } + } else { + // we have to check every message if its a newly assigned id or not. + // Ack on I_ID_RESPONSE does not work, and checking on C_PRESENTATION isn't reliable. + uint8_t newNodeID = loadState(EEPROM_LATEST_NODE_ADDRESS)+1; + if (newNodeID <= MQTT_FIRST_SENSORID) newNodeID = MQTT_FIRST_SENSORID; + if (msg.sender==newNodeID) { + saveState(EEPROM_LATEST_NODE_ADDRESS,newNodeID); + } + if (mGetCommand(msg)==C_INTERNAL) { + if (msg.type==I_CONFIG) { + txBlink(1); + if (!sendRoute(build(msg, GATEWAY_ADDRESS, msg.sender, 255, C_INTERNAL, I_CONFIG, 0).set("M"))) errBlink(1); + } else if (msg.type==I_ID_REQUEST && msg.sender==255) { + uint8_t newNodeID = loadState(EEPROM_LATEST_NODE_ADDRESS)+1; + if (newNodeID <= MQTT_FIRST_SENSORID) newNodeID = MQTT_FIRST_SENSORID; + if (newNodeID >= MQTT_LAST_SENSORID) return; // Sorry no more id's left :( + txBlink(1); + if (!sendRoute(build(msg, GATEWAY_ADDRESS, msg.sender, 255, C_INTERNAL, I_ID_RESPONSE, 0).set(newNodeID))) errBlink(1); + } + } else if (mGetCommand(msg)!=0) { + if (mGetCommand(msg)==3) msg.type=msg.type+(S_FIRSTCUSTOM-10); //Special message + + buffer[buffsize++] = MQTTPUBLISH << 4; // 0: + buffer[buffsize++] = 0x09; // 1: Remaining length with no payload, we'll set this later to correct value, buffsize -2 + buffer[buffsize++] = 0x00; // 2: Length MSB (Remaing length can never exceed ff,so MSB must be 0!) + buffer[buffsize++] = 0x08; // 3: Length LSB (ADDR), We'll set this later + if (msg.type > V_TOTAL) msg.type=V_TOTAL;// If type > defined types set to unknown. + strcpy_P(buffer+4, broker); + buffsize+=strlen_P(broker); + buffsize+=sprintf(&buffer[buffsize],"/%i/%i/V_%s",msg.sender,msg.sensor,getType(convBuf, &vType[msg.type])); + buffer[3]=buffsize-4; // Set correct address length on byte 4. +#ifdef DEBUG + Serial.println((char*)&buffer[4]); +#endif + msg.getString(convBuf); + for (uint8_t a=0; a +Modified by Daniel Wiegert +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. +*/ + +#ifndef MyMQTT_h +#define MyMQTT_h + +#include "MySensor.h" + + +////////////////////////////////////////////////////////////////// + +#ifdef DEBUG +#define TCPDUMP // Dump TCP packages. +#endif + +#define MQTT_FIRST_SENSORID 20 // If you want manually configured nodes below this value. 255 = Disable +#define MQTT_LAST_SENSORID 254 // 254 is max! 255 reserved. +#define MQTT_BROKER_PREFIX "MyMQTT" // First prefix in MQTT tree, keep short! +#define MQTT_SEND_SUBSCRIPTION 1 // Send empty payload (request) to node upon MQTT client subscribe request. +// NOTE above : Beware to check if there is any length on payload in your incommingMessage code: +// Example: if (msg.type==V_LIGHT && strlen(msg.getString())>0) otherwise the code might do strange things. + +////////////////////////////////////////////////////////////////// + +#define EEPROM_LATEST_NODE_ADDRESS ((uint8_t)EEPROM_LOCAL_CONFIG_ADDRESS) +#define MQTT_MAX_PACKET_SIZE 100 + +#define MQTTPROTOCOLVERSION 3 +#define MQTTCONNECT 1 // Client request to connect to Server +#define MQTTCONNACK 2 // Connect Acknowledgment +#define MQTTPUBLISH 3 // Publish message +#define MQTTPUBACK 4 // Publish Acknowledgment +#define MQTTPUBREC 5 // Publish Received (assured delivery part 1) +#define MQTTPUBREL 6 // Publish Release (assured delivery part 2) +#define MQTTPUBCOMP 7 // Publish Complete (assured delivery part 3) +#define MQTTSUBSCRIBE 8 // Client Subscribe request +#define MQTTSUBACK 9 // Subscribe Acknowledgment +#define MQTTUNSUBSCRIBE 10 // Client Unsubscribe request +#define MQTTUNSUBACK 11 // Unsubscribe Acknowledgment +#define MQTTPINGREQ 12 // PING Request +#define MQTTPINGRESP 13 // PING Response +#define MQTTDISCONNECT 14 // Client is Disconnecting +#define MQTTReserved 15 // Reserved + +#define MQTTQOS0 (0 << 1) +#define MQTTQOS1 (1 << 1) +#define MQTTQOS2 (2 << 1) + +class MyMQTT : +public MySensor { + +public: + MyMQTT(uint8_t _cepin=5, uint8_t _cspin=6); + void begin(rf24_pa_dbm_e paLevel=RF24_PA_LEVEL_GW, uint8_t channel=RF24_CHANNEL, rf24_datarate_e dataRate=RF24_DATARATE, void (*dataCallback) + (const char *, uint8_t *)=NULL, uint8_t _rx=6, uint8_t _tx=5, uint8_t _er=4 ); + void processRadioMessage(); + void processMQTTMessage(char *inputString, uint8_t inputPos); +private: + void (*dataCallback)(const char *, uint8_t *); + void SendMQTT(MyMessage &msg); + void ledTimers(); + void rxBlink(uint8_t cnt); + void txBlink(uint8_t cnt); + void errBlink(uint8_t cnt); + + bool MQTTClientConnected; + char buffer[MQTT_MAX_PACKET_SIZE]; + char convBuf[MAX_PAYLOAD*2+1]; + uint8_t buffsize; + char *getType(char *b, const char **index); +}; + +extern void ledTimersInterrupt(); + +#endif diff --git a/libraries/MySensors/MyMessage.cpp b/libraries/MySensors/MyMessage.cpp new file mode 100755 index 0000000..286b111 --- /dev/null +++ b/libraries/MySensors/MyMessage.cpp @@ -0,0 +1,231 @@ +#include "MyMessage.h" +#include +#include + + +MyMessage::MyMessage() { + destination = 0; // Gateway is default destination +} + +MyMessage::MyMessage(uint8_t _sensor, uint8_t _type) { + destination = 0; // Gateway is default destination + sensor = _sensor; + type = _type; +} + + +bool MyMessage::isAck() const { + return miGetAck(); +} + + +/* Getters for payload converted to desired form */ +void* MyMessage::getCustom() const { + return (void *)data; +} + +const char* MyMessage::getString() const { + uint8_t payloadType = miGetPayloadType(); + if (payloadType == P_STRING) { + return data; + } else { + return NULL; + } +} + +// handles single character hex (0 - 15) +char MyMessage::i2h(uint8_t i) const { + uint8_t k = i & 0x0F; + if (k <= 9) + return '0' + k; + else + return 'A' + k - 10; +} + +char* MyMessage::getStream(char *buffer) const { + uint8_t cmd = miGetCommand(); + if ((cmd == C_STREAM) && (buffer != NULL)) { + for (uint8_t i = 0; i < miGetLength(); i++) + { + buffer[i * 2] = i2h(data[i] >> 4); + buffer[(i * 2) + 1] = i2h(data[i]); + } + buffer[miGetLength() * 2] = '\0'; + return buffer; + } else { + return NULL; + } +} + +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) { + itoa(bValue, buffer, 10); + } else if (payloadType == P_INT16) { + itoa(iValue, buffer, 10); + } else if (payloadType == P_UINT16) { + utoa(uiValue, buffer, 10); + } else if (payloadType == P_LONG32) { + ltoa(lValue, buffer, 10); + } else if (payloadType == P_ULONG32) { + + ultoa(ulValue, buffer, 10); + } else if (payloadType == P_FLOAT32) { + dtostrf(fValue,2,fPrecision,buffer); + } else if (payloadType == P_CUSTOM) { + return getStream(buffer); + } + return buffer; + } else { + return NULL; + } +} + +uint8_t MyMessage::getByte() const { + if (miGetPayloadType() == P_BYTE) { + return data[0]; + } else if (miGetPayloadType() == P_STRING) { + return atoi(data); + } else { + return 0; + } +} + +bool MyMessage::getBool() const { + return getInt(); +} + +float MyMessage::getFloat() const { + if (miGetPayloadType() == P_FLOAT32) { + return fValue; + } else if (miGetPayloadType() == P_STRING) { + return atof(data); + } else { + return 0; + } +} + +long MyMessage::getLong() const { + if (miGetPayloadType() == P_LONG32) { + return lValue; + } else if (miGetPayloadType() == P_STRING) { + return atol(data); + } else { + return 0; + } +} + +unsigned long MyMessage::getULong() const { + if (miGetPayloadType() == P_ULONG32) { + return ulValue; + } else if (miGetPayloadType() == P_STRING) { + return atol(data); + } else { + return 0; + } +} + +int MyMessage::getInt() const { + if (miGetPayloadType() == P_INT16) { + return iValue; + } else if (miGetPayloadType() == P_STRING) { + return atoi(data); + } else { + return 0; + } +} + +unsigned int MyMessage::getUInt() const { + if (miGetPayloadType() == P_UINT16) { + return uiValue; + } else if (miGetPayloadType() == P_STRING) { + return atoi(data); + } else { + return 0; + } + +} + + +MyMessage& MyMessage::setType(uint8_t _type) { + type = _type; + return *this; +} + +MyMessage& MyMessage::setSensor(uint8_t _sensor) { + sensor = _sensor; + return *this; +} + +MyMessage& MyMessage::setDestination(uint8_t _destination) { + destination = _destination; + return *this; +} + +// Set payload +MyMessage& MyMessage::set(void* value, uint8_t length) { + miSetPayloadType(P_CUSTOM); + miSetLength(length); + memcpy(data, value, min(length, MAX_PAYLOAD)); + return *this; +} + + +MyMessage& MyMessage::set(const char* value) { + uint8_t length = strlen(value); + miSetLength(length); + miSetPayloadType(P_STRING); + strncpy(data, value, min(length, MAX_PAYLOAD)); + return *this; +} + +MyMessage& MyMessage::set(uint8_t value) { + miSetLength(1); + miSetPayloadType(P_BYTE); + data[0] = value; + return *this; +} + + +MyMessage& MyMessage::set(float value, uint8_t decimals) { + miSetLength(5); // 32 bit float + persi + miSetPayloadType(P_FLOAT32); + fValue=value; + fPrecision = decimals; + return *this; +} + +MyMessage& MyMessage::set(unsigned long value) { + miSetPayloadType(P_ULONG32); + miSetLength(4); + ulValue = value; + return *this; +} + +MyMessage& MyMessage::set(long value) { + miSetPayloadType(P_LONG32); + miSetLength(4); + lValue = value; + return *this; +} + +MyMessage& MyMessage::set(unsigned int value) { + miSetPayloadType(P_UINT16); + miSetLength(2); + uiValue = value; + return *this; +} + +MyMessage& MyMessage::set(int value) { + miSetPayloadType(P_INT16); + miSetLength(2); + iValue = value; + return *this; +} + + diff --git a/libraries/MySensors/MyMessage.h b/libraries/MySensors/MyMessage.h new file mode 100644 index 0000000..bc7a086 --- /dev/null +++ b/libraries/MySensors/MyMessage.h @@ -0,0 +1,215 @@ +/* + The MySensors library adds a new layer on top of the RF24 library. + It handles radio network routing, relaying and ids. + + Created by Henrik Ekblad + + 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. + */ + +#ifndef MyMessage_h +#define MyMessage_h + +#ifdef __cplusplus +#include +#include +#include +#endif + +#define PROTOCOL_VERSION 2 +#define MAX_MESSAGE_LENGTH 32 +#define HEADER_SIZE 7 +#define MAX_PAYLOAD (MAX_MESSAGE_LENGTH - HEADER_SIZE) + +// Message types +typedef enum { + C_PRESENTATION = 0, + C_SET = 1, + C_REQ = 2, + C_INTERNAL = 3, + C_STREAM = 4 // For Firmware and other larger chunks of data that need to be divided into pieces. +} command; + +// Type of sensor data (for set/req/ack messages) +typedef enum { + V_TEMP,V_HUM, V_LIGHT, V_DIMMER, V_PRESSURE, V_FORECAST, V_RAIN, + V_RAINRATE, V_WIND, V_GUST, V_DIRECTION, V_UV, V_WEIGHT, V_DISTANCE, + V_IMPEDANCE, V_ARMED, V_TRIPPED, V_WATT, V_KWH, V_SCENE_ON, V_SCENE_OFF, + V_HEATER, V_HEATER_SW, V_LIGHT_LEVEL, V_VAR1, V_VAR2, V_VAR3, V_VAR4, V_VAR5, + V_UP, V_DOWN, V_STOP, V_IR_SEND, V_IR_RECEIVE, V_FLOW, V_VOLUME, V_LOCK_STATUS, + V_DUST_LEVEL, V_VOLTAGE, V_CURRENT +} 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 +} internal; + +// Type of sensor (for presentation message) +typedef enum { + S_DOOR, S_MOTION, S_SMOKE, S_LIGHT, S_DIMMER, S_COVER, S_TEMP, S_HUM, S_BARO, S_WIND, + S_RAIN, S_UV, S_WEIGHT, S_POWER, S_HEATER, S_DISTANCE, S_LIGHT_LEVEL, S_ARDUINO_NODE, + S_ARDUINO_REPEATER_NODE, S_LOCK, S_IR, S_WATER, S_AIR_QUALITY, S_CUSTOM, S_DUST, + S_SCENE_CONTROLLER +} sensor; + +// Type of data stream (for streamed message) +typedef enum { + ST_FIRMWARE_CONFIG_REQUEST, ST_FIRMWARE_CONFIG_RESPONSE, ST_FIRMWARE_REQUEST, ST_FIRMWARE_RESPONSE, + ST_SOUND, ST_IMAGE +} stream; + +typedef enum { + P_STRING, P_BYTE, P_INT16, P_UINT16, P_LONG32, P_ULONG32, P_CUSTOM, P_FLOAT32 +} payload; + + + +#define BIT(n) ( 1<<(n) ) +// Create a bitmask of length len. +#define BIT_MASK(len) ( BIT(len)-1 ) +// Create a bitfield mask of length starting at bit 'start'. +#define BF_MASK(start, len) ( BIT_MASK(len)<<(start) ) + +// Prepare a bitmask for insertion or combining. +#define BF_PREP(x, start, len) ( ((x)&BIT_MASK(len)) << (start) ) +// Extract a bitfield of length len starting at bit 'start' from y. +#define BF_GET(y, start, len) ( ((y)>>(start)) & BIT_MASK(len) ) +// Insert a new bitfield value x into y. +#define BF_SET(y, x, start, len) ( y= ((y) &~ BF_MASK(start, len)) | BF_PREP(x, start, len) ) + +// Getters/setters for special bit fields in header +#define mSetVersion(_msg,_version) BF_SET(_msg.version_length, _version, 0, 3) +#define mGetVersion(_msg) BF_GET(_msg.version_length, 0, 3) + +#define mSetLength(_msg,_length) BF_SET(_msg.version_length, _length, 3, 5) +#define mGetLength(_msg) BF_GET(_msg.version_length, 3, 5) + +#define mSetCommand(_msg,_command) BF_SET(_msg.command_ack_payload, _command, 0, 3) +#define mGetCommand(_msg) BF_GET(_msg.command_ack_payload, 0, 3) + +#define mSetRequestAck(_msg,_rack) BF_SET(_msg.command_ack_payload, _rack, 3, 1) +#define mGetRequestAck(_msg) BF_GET(_msg.command_ack_payload, 3, 1) + +#define mSetAck(_msg,_ackMsg) BF_SET(_msg.command_ack_payload, _ackMsg, 4, 1) +#define mGetAck(_msg) BF_GET(_msg.command_ack_payload, 4, 1) + +#define mSetPayloadType(_msg, _pt) BF_SET(_msg.command_ack_payload, _pt, 5, 3) +#define mGetPayloadType(_msg) BF_GET(_msg.command_ack_payload, 5, 3) + + +// internal access for special fields +#define miGetCommand() BF_GET(command_ack_payload, 0, 3) + +#define miSetLength(_length) BF_SET(version_length, _length, 3, 5) +#define miGetLength() BF_GET(version_length, 3, 5) + +#define miSetRequestAck(_rack) BF_SET(command_ack_payload, _rack, 3, 1) +#define miGetRequestAck() BF_GET(command_ack_payload, 3, 1) + +#define miSetAck(_ack) BF_SET(command_ack_payload, _ack, 4, 1) +#define miGetAck() BF_GET(command_ack_payload, 4, 1) + +#define miSetPayloadType(_pt) BF_SET(command_ack_payload, _pt, 5, 3) +#define miGetPayloadType() BF_GET(command_ack_payload, 5, 3) + + +#ifdef __cplusplus +class MyMessage +{ +public: + // Constructors + MyMessage(); + + MyMessage(uint8_t sensor, uint8_t type); + + char i2h(uint8_t i) const; + + /** + * If payload is something else than P_STRING you can have the payload value converted + * into string representation by supplying a buffer with the minimum size of + * 2*MAX_PAYLOAD+1. This is to be able to fit hex-conversion of a full binary payload. + */ + char* getStream(char *buffer) const; + char* getString(char *buffer) const; + const char* getString() const; + void* getCustom() const; + uint8_t getByte() const; + bool getBool() const; + float getFloat() const; + long getLong() const; + unsigned long getULong() const; + int getInt() const; + unsigned int getUInt() const; + + // Getter for ack-flag. True if this is an ack message. + bool isAck() const; + + // Setters for building message "on the fly" + MyMessage& setType(uint8_t type); + MyMessage& setSensor(uint8_t sensor); + MyMessage& setDestination(uint8_t destination); + + // Setters for payload + MyMessage& set(void* payload, uint8_t length); + MyMessage& set(const char* value); + MyMessage& set(uint8_t value); + MyMessage& set(float value, uint8_t decimals); + MyMessage& set(unsigned long value); + MyMessage& set(long value); + MyMessage& set(unsigned int value); + MyMessage& set(int value); + +#else + +typedef union { +struct +{ + +#endif + uint8_t last; // 8 bit - Id of last node this message passed + uint8_t sender; // 8 bit - Id of sender node (origin) + uint8_t destination; // 8 bit - Id of destination node + + uint8_t version_length; // 3 bit - Protocol version + // 5 bit - Length of payload + uint8_t command_ack_payload; // 3 bit - Command type + // 1 bit - Request an ack - Indicator that receiver should send an ack back. + // 1 bit - Is ack messsage - Indicator that this is the actual ack message. + // 3 bit - Payload data type + uint8_t type; // 8 bit - Type varies depending on command + uint8_t sensor; // 8 bit - Id of sensor that this message concerns. + + // Each message can transfer a payload. We add one extra byte for string + // terminator \0 to be "printable" this is not transferred OTA + // This union is used to simplify the construction of the binary data types transferred. + union { + uint8_t bValue; + unsigned long ulValue; + long lValue; + unsigned int uiValue; + int iValue; + struct { // Float messages + float fValue; + uint8_t fPrecision; // Number of decimals when serializing + }; + struct { // Presentation messages + uint8_t version; // Library version + uint8_t sensorType; // Sensor type hint for controller, see table above + }; + char data[MAX_PAYLOAD + 1]; + } __attribute__((packed)); +#ifdef __cplusplus +} __attribute__((packed)); +#else +}; +uint8_t array[HEADER_SIZE + MAX_PAYLOAD + 1]; +} __attribute__((packed)) MyMessage; +#endif + +#endif diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp new file mode 100755 index 0000000..55b15ee --- /dev/null +++ b/libraries/MySensors/MySensor.cpp @@ -0,0 +1,549 @@ + /* + The MySensors library adds a new layer on top of the RF24 library. + It handles radio network routing, relaying and ids. + + Created by Henrik Ekblad + + 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. + */ + +#include "MySensor.h" +#include "utility/LowPower.h" +#include "utility/RF24.h" +#include "utility/RF24_config.h" + + +// Inline function and macros +inline MyMessage& build (MyMessage &msg, uint8_t sender, uint8_t destination, uint8_t sensor, uint8_t command, uint8_t type, bool enableAck) { + msg.sender = sender; + msg.destination = destination; + msg.sensor = sensor; + msg.type = type; + mSetCommand(msg,command); + mSetRequestAck(msg,enableAck); + mSetAck(msg,false); + return msg; +} + + +MySensor::MySensor(uint8_t _cepin, uint8_t _cspin) : RF24(_cepin, _cspin) { +} + + +void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, boolean _repeaterMode, uint8_t _parentNodeId, rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate) { + Serial.begin(BAUD_RATE); + isGateway = false; + repeaterMode = _repeaterMode; + msgCallback = _msgCallback; + + if (repeaterMode) { + setupRepeaterMode(); + } + setupRadio(paLevel, channel, dataRate); + + // Read settings from EEPROM + eeprom_read_block((void*)&nc, (void*)EEPROM_NODE_ID_ADDRESS, sizeof(NodeConfig)); + // Read latest received controller configuration from EEPROM + eeprom_read_block((void*)&cc, (void*)EEPROM_LOCAL_CONFIG_ADDRESS, sizeof(ControllerConfig)); + if (cc.isMetric == 0xff) { + // Eeprom empty, set default to metric + cc.isMetric = 0x01; + } + + if (_parentNodeId != AUTO) { + nc.parentNodeId = _parentNodeId; + autoFindParent = false; + } else { + autoFindParent = true; + } + + if (_nodeId != AUTO) { + // Set static id + nc.nodeId = _nodeId; + } + + // If no parent was found in eeprom. Try to find one. + if (autoFindParent && nc.parentNodeId == 0xff) { + findParentNode(); + } + + // Try to fetch node-id from gateway + if (nc.nodeId == AUTO) { + requestNodeId(); + } + + debug(PSTR("%s started, id %d\n"), repeaterMode?"repeater":"sensor", nc.nodeId); + + // Open reading pipe for messages directed to this node (set write pipe to same) + RF24::openReadingPipe(WRITE_PIPE, TO_ADDR(nc.nodeId)); + RF24::openReadingPipe(CURRENT_NODE_PIPE, TO_ADDR(nc.nodeId)); + + // Send presentation for this radio node (attach + present(NODE_SENSOR_ID, repeaterMode? S_ARDUINO_REPEATER_NODE : S_ARDUINO_NODE); + + // Send a configuration exchange request to controller + // Node sends parent node. Controller answers with latest node configuration + // which is picked up in process() + sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_CONFIG, false).set(nc.parentNodeId)); + + // Wait configuration reply. + waitForReply(); +} + +void MySensor::setupRadio(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate) { + failedTransmissions = 0; + + // Start up the radio library + RF24::begin(); + + if (!RF24::isPVariant()) { + debug(PSTR("check wires\n")); + while(1); + } + RF24::setAutoAck(1); + RF24::setAutoAck(BROADCAST_PIPE,false); // Turn off auto ack for broadcast + RF24::enableAckPayload(); + RF24::setChannel(channel); + RF24::setPALevel(paLevel); + RF24::setDataRate(dataRate); + RF24::setRetries(5,15); + RF24::setCRCLength(RF24_CRC_16); + RF24::enableDynamicPayloads(); + + // All nodes listen to broadcast pipe (for FIND_PARENT_RESPONSE messages) + RF24::openReadingPipe(BROADCAST_PIPE, TO_ADDR(BROADCAST_ADDRESS)); +} + +void MySensor::setupRepeaterMode(){ + childNodeTable = new uint8_t[256]; + eeprom_read_block((void*)childNodeTable, (void*)EEPROM_ROUTES_ADDRESS, 256); +} + + +uint8_t MySensor::getNodeId() { + return nc.nodeId; +} + +ControllerConfig MySensor::getConfig() { + return cc; +} + +void MySensor::requestNodeId() { + debug(PSTR("req node id\n")); + RF24::openReadingPipe(CURRENT_NODE_PIPE, TO_ADDR(nc.nodeId)); + sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_ID_REQUEST, false).set("")); + waitForReply(); +} + + +void MySensor::findParentNode() { + failedTransmissions = 0; + + // Set distance to max + nc.distance = 255; + + // Send ping message to BROADCAST_ADDRESS (to which all relaying nodes and gateway listens and should reply to) + build(msg, nc.nodeId, BROADCAST_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_FIND_PARENT, false).set(""); + sendWrite(BROADCAST_ADDRESS, msg, true); + + // Wait for ping response. + waitForReply(); +} + +void MySensor::waitForReply() { + unsigned long enter = millis(); + // Wait a couple of seconds for response + while (millis() - enter < 2000) { + process(); + } +} + +boolean MySensor::sendRoute(MyMessage &message) { + // Make sure to process any incoming messages before sending (could this end up in recursive loop?) + // process(); + bool isInternal = mGetCommand(message) == C_INTERNAL; + + // If we still don't have any node id, re-request and skip this message. + if (nc.nodeId == AUTO && !(isInternal && message.type == I_ID_REQUEST)) { + requestNodeId(); + return false; + } + + if (repeaterMode) { + uint8_t dest = message.destination; + uint8_t route = getChildRoute(dest); + if (route>GATEWAY_ADDRESS && route SEARCH_FAILURES) { + findParentNode(); + } + failedTransmissions++; + } else { + failedTransmissions = 0; + } + return ok; + } + return false; +} + +boolean MySensor::sendWrite(uint8_t next, MyMessage &message, bool broadcast) { + uint8_t length = mGetLength(message); + message.last = nc.nodeId; + mSetVersion(message, PROTOCOL_VERSION); + // Make sure radio has powered up + RF24::powerUp(); + RF24::stopListening(); + RF24::openWritingPipe(TO_ADDR(next)); + bool ok = RF24::write(&message, min(MAX_MESSAGE_LENGTH, HEADER_SIZE + length), broadcast); + RF24::startListening(); + + debug(PSTR("send: %d-%d-%d-%d s=%d,c=%d,t=%d,pt=%d,l=%d,st=%s:%s\n"), + message.sender,message.last, next, message.destination, message.sensor, mGetCommand(message), message.type, mGetPayloadType(message), mGetLength(message), ok?"ok":"fail", message.getString(convBuf)); + + return ok; +} + + +bool MySensor::send(MyMessage &message, bool enableAck) { + message.sender = nc.nodeId; + mSetCommand(message,C_SET); + mSetRequestAck(message,enableAck); + return sendRoute(message); +} + +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::sendSketchInfo(const char *name, const char *version, bool enableAck) { + if (name != NULL) { + sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_SKETCH_NAME, enableAck).set(name)); + } + if (version != NULL) { + sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_SKETCH_VERSION, enableAck).set(version)); + } +} + +void MySensor::request(uint8_t childSensorId, uint8_t variableType, uint8_t destination) { + sendRoute(build(msg, nc.nodeId, destination, childSensorId, C_REQ, variableType, false)); +} + +void MySensor::requestTime(void (* _timeCallback)(unsigned long)) { + timeCallback = _timeCallback; + sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_TIME, false)); +} + + +boolean MySensor::process() { + uint8_t pipe; + boolean available = RF24::available(&pipe); + + if (!available || pipe>6) + return false; + + uint8_t len = RF24::getDynamicPayloadSize(); + RF24::read(&msg, len); + RF24::writeAckPayload(pipe,&pipe, 1 ); + + // Add string termination, good if we later would want to print it. + msg.data[mGetLength(msg)] = '\0'; + debug(PSTR("read: %d-%d-%d s=%d,c=%d,t=%d,pt=%d,l=%d:%s\n"), + msg.sender, msg.last, msg.destination, msg.sensor, mGetCommand(msg), msg.type, mGetPayloadType(msg), mGetLength(msg), msg.getString(convBuf)); + + if(!(mGetVersion(msg) == PROTOCOL_VERSION)) { + debug(PSTR("version mismatch\n")); + return false; + } + + uint8_t command = mGetCommand(msg); + uint8_t type = msg.type; + uint8_t sender = msg.sender; + uint8_t last = msg.last; + uint8_t destination = msg.destination; + + if (repeaterMode && command == C_INTERNAL && type == I_FIND_PARENT) { + // 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 + delay(millis() & 0x3ff); + sendWrite(sender, build(msg, nc.nodeId, sender, NODE_SENSOR_ID, C_INTERNAL, I_FIND_PARENT_RESPONSE, false).set(nc.distance), true); + return false; + } else if (destination == nc.nodeId) { + // Check if sender requests an ack back. + if (mGetRequestAck(msg)) { + // Copy message + ack = msg; + mSetRequestAck(ack,false); // Reply without ack flag (otherwise we would end up in an eternal loop) + mSetAck(ack,true); + ack.sender = nc.nodeId; + ack.destination = msg.sender; + sendRoute(ack); + } + + // This message is addressed to this node + if (repeaterMode && last != nc.parentNodeId) { + // Message is from one of the child nodes. Add it to routing table. + addChildRoute(sender, last); + } + + if (command == C_INTERNAL) { + if (type == I_FIND_PARENT_RESPONSE && !isGateway) { + // We've received a reply to a FIND_PARENT message. Check if the distance is + // shorter than we already have. + uint8_t distance = msg.getByte(); + if (distance0 && route<255) { + // This message should be forwarded to a child node. If we send message + // to this nodes pipe then all children will receive it because the are + // all listening to this nodes pipe. + // + // +----B + // -A + // +----C------D + // + // We're node C, Message comes from A and has destination D + // + // lookup route in table and send message there + sendWrite(route, msg); + } else { + // A message comes from a child node and we have no + // route for it. + // + // +----B + // -A + // +----C------D <-- Message comes from D + // + // We're node C + // + // Message should be passed to node A (this nodes relay) + + // This message should be routed back towards sensor net gateway + sendWrite(nc.parentNodeId, msg); + // Add this child to our "routing table" if it not already exist + addChildRoute(sender, last); + } + } + return false; +} + + +MyMessage& MySensor::getLastMessage() { + return msg; +} + + +void MySensor::saveState(uint8_t pos, uint8_t value) { + if (loadState(pos) != value) { + eeprom_write_byte((uint8_t*)(EEPROM_LOCAL_CONFIG_ADDRESS+pos), value); + } +} +uint8_t MySensor::loadState(uint8_t pos) { + return eeprom_read_byte((uint8_t*)(EEPROM_LOCAL_CONFIG_ADDRESS+pos)); +} + + +void MySensor::addChildRoute(uint8_t childId, uint8_t route) { + if (childNodeTable[childId] != route) { + childNodeTable[childId] = route; + eeprom_write_byte((uint8_t*)EEPROM_ROUTES_ADDRESS+childId, route); + } +} + +void MySensor::removeChildRoute(uint8_t childId) { + if (childNodeTable[childId] != 0xff) { + childNodeTable[childId] = 0xff; + eeprom_write_byte((uint8_t*)EEPROM_ROUTES_ADDRESS+childId, 0xff); + } +} + +uint8_t MySensor::getChildRoute(uint8_t childId) { + return childNodeTable[childId]; +} + + +int MySensor::getInternalTemp(void) +{ + long result; + // Read internal temp sensor against 1.1V reference + ADMUX = _BV(REFS1) | _BV(REFS0) | _BV(MUX3); + delay(20); // Wait until Vref has settled + ADCSRA |= _BV(ADSC); + while (bit_is_set(ADCSRA,ADSC)); + result = ADCL; + result |= ADCH<<8; + result = (result - 125) * 1075 + 500; // add 500 to round to nearest full degree + + return result/10000; +} + +int continueTimer = true; +void wakeUp() //place to send the interrupts +{ + continueTimer = false; +} + +void MySensor::internalSleep(unsigned long ms) { + while (continueTimer && ms >= 8000) { LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF); ms -= 8000; } + if (continueTimer && ms >= 4000) { LowPower.powerDown(SLEEP_4S, ADC_OFF, BOD_OFF); ms -= 4000; } + if (continueTimer && ms >= 2000) { LowPower.powerDown(SLEEP_2S, ADC_OFF, BOD_OFF); ms -= 2000; } + if (continueTimer && ms >= 1000) { LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF); ms -= 1000; } + if (continueTimer && ms >= 500) { LowPower.powerDown(SLEEP_500MS, ADC_OFF, BOD_OFF); ms -= 500; } + if (continueTimer && ms >= 250) { LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF); ms -= 250; } + if (continueTimer && ms >= 125) { LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_OFF); ms -= 120; } + if (continueTimer && ms >= 64) { LowPower.powerDown(SLEEP_60MS, ADC_OFF, BOD_OFF); ms -= 60; } + if (continueTimer && ms >= 32) { LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_OFF); ms -= 30; } + if (continueTimer && ms >= 16) { LowPower.powerDown(SLEEP_15Ms, ADC_OFF, BOD_OFF); ms -= 15; } +} + +void MySensor::sleep(unsigned long ms) { + // Let serial prints finish (debug, log etc) + Serial.flush(); + RF24::powerDown(); + continueTimer = true; + internalSleep(ms); +} + +bool MySensor::sleep(int interrupt, int mode, unsigned long ms) { + // Let serial prints finish (debug, log etc) + bool pinTriggeredWakeup = true; + Serial.flush(); + RF24::powerDown(); + attachInterrupt(interrupt, wakeUp, mode); //Interrupt on pin 3 for any change in solar power + if (ms>0) { + continueTimer = true; + sleep(ms); + pinTriggeredWakeup = !continueTimer; + } else { + Serial.flush(); + LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF); + } + detachInterrupt(interrupt); + return pinTriggeredWakeup; +} + + + +#ifdef DEBUG +void MySensor::debugPrint(const char *fmt, ... ) { + char fmtBuffer[300]; + if (isGateway) { + // prepend debug message to be handled correctly by gw (C_INTERNAL, I_LOG_MESSAGE) + snprintf_P(fmtBuffer, 299, PSTR("0;0;%d;0;%d;"), C_INTERNAL, I_LOG_MESSAGE); + Serial.print(fmtBuffer); + } + va_list args; + va_start (args, fmt ); + va_end (args); + if (isGateway) { + // Truncate message if this is gateway node + vsnprintf_P(fmtBuffer, 60, fmt, args); + fmtBuffer[59] = '\n'; + fmtBuffer[60] = '\0'; + } else { + vsnprintf_P(fmtBuffer, 299, fmt, args); + } + va_end (args); + Serial.print(fmtBuffer); + Serial.flush(); + + //Serial.write(freeRam()); +} +#endif + + +#ifdef DEBUG +int MySensor::freeRam (void) { + extern int __heap_start, *__brkval; + int v; + return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); +} +#endif diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h new file mode 100644 index 0000000..d55cd0f --- /dev/null +++ b/libraries/MySensors/MySensor.h @@ -0,0 +1,266 @@ +/* + The MySensors library adds a new layer on top of the RF24 library. + It handles radio network routing, relaying and ids. + + Created by Henrik Ekblad + + 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. +*/ + +#ifndef MySensor_h +#define MySensor_h + +#include "Version.h" // Auto generated by bot +#include "MyConfig.h" +#include "MyMessage.h" +#include +#include +#include +#include +#include + +#ifdef __cplusplus +#include +#include +#include "utility/LowPower.h" +#include "utility/RF24.h" +#include "utility/RF24_config.h" +#endif + +#ifdef DEBUG +#define debug(x,...) debugPrint(x, ##__VA_ARGS__) +#else +#define debug(x,...) +#endif + +#define BAUD_RATE 115200 + +#define AUTO 0xFF // 0-254. Id 255 is reserved for auto initialization of nodeId. +#define NODE_SENSOR_ID 0xFF // Node child id is always created for when a node + +// EEPROM start address for mysensors library data +#define EEPROM_START 0 +// EEPROM location of node id +#define EEPROM_NODE_ID_ADDRESS EEPROM_START +// EEPROM location of parent id +#define EEPROM_PARENT_NODE_ID_ADDRESS (EEPROM_START+1) +// EEPROM location of distance to gateway +#define EEPROM_DISTANCE_ADDRESS (EEPROM_PARENT_NODE_ID_ADDRESS+1) +#define EEPROM_ROUTES_ADDRESS (EEPROM_DISTANCE_ADDRESS+1) // Where to start storing routing information in EEPROM. Will allocate 256 bytes. +#define EEPROM_CONTROLLER_CONFIG_ADDRESS (EEPROM_ROUTES_ADDRESS+256) // Location of controller sent configuration (we allow one payload of config data from controller) +#define EEPROM_FIRMWARE_TYPE_ADDRESS (EEPROM_CONTROLLER_CONFIG_ADDRESS+24) +#define EEPROM_FIRMWARE_VERSION_ADDRESS (EEPROM_FIRMWARE_TYPE_ADDRESS+2) +#define EEPROM_FIRMWARE_BLOCKS_ADDRESS (EEPROM_FIRMWARE_VERSION_ADDRESS+2) +#define EEPROM_FIRMWARE_CRC_ADDRESS (EEPROM_FIRMWARE_BLOCKS_ADDRESS+2) +#define EEPROM_LOCAL_CONFIG_ADDRESS (EEPROM_FIRMWARE_CRC_ADDRESS+2) // First free address for sketch static configuration + +// This is the nodeId for sensor net gateway receiver sketch (where all sensors should send their data). +#define GATEWAY_ADDRESS ((uint8_t)0) +#define BROADCAST_ADDRESS ((uint8_t)0xFF) +#define TO_ADDR(x) (BASE_RADIO_ID + x) + +#define WRITE_PIPE ((uint8_t)0) +#define CURRENT_NODE_PIPE ((uint8_t)1) +#define BROADCAST_PIPE ((uint8_t)2) + +// Search for a new parent node after this many transmission failures +#define SEARCH_FAILURES 5 + +struct NodeConfig +{ + uint8_t nodeId; // Current node id + uint8_t parentNodeId; // Where this node sends its messages + uint8_t distance; // This nodes distance to sensor net gateway (number of hops) +}; + +struct ControllerConfig { + uint8_t isMetric; +}; + +#ifdef __cplusplus +class MySensor : public RF24 +{ + public: + /** + * Constructor + * + * Creates a new instance of Sensor class. + * + * @param _cepin The pin attached to RF24 Chip Enable on the RF module (default 9) + * @param _cspin The pin attached to RF24 Chip Select (default 10) + */ + MySensor(uint8_t _cepin=DEFAULT_CE_PIN, uint8_t _cspin=DEFAULT_CS_PIN); + + /** + * Begin operation of the MySensors library + * + * Call this in setup(), before calling any other sensor net library methods. + * @param incomingMessageCallback Callback function for incoming messages from other nodes or controller and request responses. Default is NULL. + * @param nodeId The unique id (1-254) for this sensor. Default is AUTO(255) which means sensor tries to fetch an id from controller. + * @param repeaterMode Activate repeater mode. This node will forward messages to other nodes in the radio network. Make sure to call process() regularly. Default in false + * @param parentNodeId Use this to force node to always communicate with a certain parent node. Default is AUTO which means node automatically tries to find a parent. + * @param paLevel Radio PA Level for this sensor. Default RF24_PA_MAX + * @param channel Radio channel. Default is channel 76 + * @param dataRate Radio transmission speed. Default RF24_1MBPS + */ + + void begin(void (* msgCallback)(const MyMessage &)=NULL, uint8_t nodeId=AUTO, boolean repeaterMode=false, uint8_t parentNodeId=AUTO, rf24_pa_dbm_e paLevel=RF24_PA_LEVEL, uint8_t channel=RF24_CHANNEL, rf24_datarate_e dataRate=RF24_DATARATE); + + /** + * Return the nodes nodeId. + */ + uint8_t getNodeId(); + + /** + * Each node must present all attached sensors before any values can be handled correctly by the controller. + * It is usually good to present all attached sensors after power-up in setup(). + * + * @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 ack Set this to true if you want destination node to send ack back to this node. Default is not to request any ack. + */ + void present(uint8_t sensorId, uint8_t sensorType, bool ack=false); + + /** + * Sends sketch meta information to the gateway. Not mandatory but a nice thing to do. + * @param name String containing a short Sketch name or NULL if not applicable + * @param version String containing a short Sketch version or NULL if not applicable + * @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. + * + */ + void sendSketchInfo(const char *name, const char *version, bool ack=false); + + /** + * Sends a message to gateway or one of the other nodes in the radio network + * + * @param msg Message to send + * @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. + * @return true Returns true if message reached the first stop on its way to destination. + */ + bool send(MyMessage &msg, bool ack=false); + + /** + * Send this nodes battery level to gateway. + * @param level Level between 0-100(%) + * @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. + * + */ + void sendBatteryLevel(uint8_t level, bool ack=false); + + /** + * 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. + * + * @param childSensorId The unique child id for the different sensors connected to this Arduino. 0-254. + * @param variableType The variableType to fetch + * @param destination The nodeId of other node in radio network. Default is gateway + */ + void request(uint8_t childSensorId, uint8_t variableType, uint8_t destination=GATEWAY_ADDRESS); + + /** + * Requests time from controller. Answer will be delivered to callback. + * + * @param callback for time request. Incoming argument is seconds since 1970. + */ + void requestTime(void (* timeCallback)(unsigned long)); + + + /** + * Processes incoming messages to this node. If this is a relaying node it will + * Returns true if there is a message addressed for this node just was received. + * Use callback to handle incoming messages. + */ + boolean process(); + + /** + * Returns the most recent node configuration received from controller + */ + ControllerConfig getConfig(); + + /** + * Save a state (in local EEPROM). Good for actuators to "remember" state between + * power cycles. + * + * You have 256 bytes to play with. Note that there is a limitation on the number + * of writes the EEPROM can handle (~100 000 cycles). + * + * @param pos The position to store value in (0-255) + * @param Value to store in position + */ + void saveState(uint8_t pos, uint8_t value); + + /** + * Load a state (from local EEPROM). + * + * @param pos The position to fetch value from (0-255) + * @return Value to store in position + */ + uint8_t loadState(uint8_t pos); + + /** + * Returns the last received message + */ + MyMessage& getLastMessage(void); + + /** + * Sleep (PowerDownMode) the Arduino and radio. Wake up on timer. + * @param ms Number of milliseconds to sleep. + */ + void sleep(unsigned long ms); + + /** + * Sleep (PowerDownMode) the Arduino and radio. Wake up on timer or pin change. + * See: http://arduino.cc/en/Reference/attachInterrupt for details on modes and which pin + * is assigned to what interrupt. On Nano/Pro Mini: 0=Pin2, 1=Pin3 + * @param interrupt Interrupt that should trigger the wakeup + * @param mode RISING, FALLING, CHANGE + * @param ms Number of milliseconds to sleep or 0 to sleep forever + * @return true if wake up was triggered by pin change and false means timer woke it up. + */ + bool sleep(int interrupt, int mode, unsigned long ms=0); + + + + +#ifdef DEBUG + void debugPrint(const char *fmt, ... ); + int freeRam(); +#endif + + protected: + NodeConfig nc; // Essential settings for node to work + ControllerConfig cc; // Configuration coming from controller + bool repeaterMode; + bool autoFindParent; + bool isGateway; + MyMessage msg; // Buffer for incoming messages. + MyMessage ack; // Buffer for ack messages. + + void setupRepeaterMode(); + void setupRadio(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate); + boolean sendRoute(MyMessage &message); + boolean sendWrite(uint8_t dest, MyMessage &message, bool broadcast=false); + + private: +#ifdef DEBUG + char convBuf[MAX_PAYLOAD]; +#endif + uint8_t failedTransmissions; + uint8_t *childNodeTable; // In memory buffer for routing information to other nodes. also stored in EEPROM + void (*timeCallback)(unsigned long); // Callback for requested time messages + void (*msgCallback)(const MyMessage &); // Callback for incoming messages from other nodes and gateway. + + void waitForReply(); + void requestNodeId(); + void findParentNode(); + uint8_t crc8Message(MyMessage &message); + uint8_t getChildRoute(uint8_t childId); + void addChildRoute(uint8_t childId, uint8_t route); + void removeChildRoute(uint8_t childId); + void internalSleep(unsigned long ms); +}; +#endif + +#endif diff --git a/libraries/MySensors/Relay.cpp b/libraries/MySensors/Relay.cpp deleted file mode 100644 index d955c99..0000000 --- a/libraries/MySensors/Relay.cpp +++ /dev/null @@ -1,256 +0,0 @@ -/* - The MySensors Arduino library adds a new layer on top of the RF24 library. - It handles radio network routing, relaying and ids. - - Created by Henrik Ekblad - - 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. -*/ - -#include "Relay.h" - -Relay::Relay(uint8_t _cepin, uint8_t _cspin) : Sensor(_cepin, _cspin) { - isRelay = true; -} - - -void Relay::begin(uint8_t radioId, rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate) { - Sensor::begin(radioId, paLevel, channel, dataRate); - // Read routing table from EEPROM - for (unsigned int i=0;i0) { - debug(PSTR("Found child in routing table. Sending to %d\n"),route); - buildMsg(from, to, childId, messageType, type, data, length, binary); - // Found node in route table - ok = sendWrite(route, msg, length); - } else if (radioId == GATEWAY_ADDRESS) { - // If we're GW (no parent...). As a last resort try sending message directly to node. - debug(PSTR("No route... try sending direct.\n")); - buildMsg(from, to, childId, messageType, type, data, length, binary); - // Found node in route table - ok = sendWrite(to, msg, length); - } else { - // We are probably a repeater node which should send message back to relay - ok = Sensor::sendData(from, to, childId, messageType, type, data, length, binary); - } - } else { - debug(PSTR("Message too large\n")); - } - return ok; -} - - - -boolean Relay::send(message_s message, int length) { - bool ok = true; - uint8_t route = getChildRoute(msg.header.to); - - if (route>0 && route<255 && message.header.to != GATEWAY_ADDRESS) { - debug(PSTR("Routing message to %d.\n"), route); - // Message destination is not gateway and is in routing table for this node. - // Send it downstream - ok = sendWrite(route, message, length); - - - } else if (radioId != GATEWAY_ADDRESS) { - debug(PSTR("Sending message back towards gw.\n")); - // Should be routed back to gateway. Sensor code knows how to do this. - ok = Sensor::send(message, length); - } - - if (!ok) { - debug(PSTR("No ack received.\n")); - } - return ok; -} - - - -boolean Relay::messageAvailable() { - uint8_t pipe; - boolean available = RF24::available(&pipe); - - if (available) { - debug(PSTR("Message available on pipe %d\n"),pipe); - } - - if (available && pipe<7) { - uint8_t len = RF24::getDynamicPayloadSize()-sizeof(msg.header); - boolean ok = readMessage(); - if (ok) { - if (msg.header.messageType == M_INTERNAL && - msg.header.type == I_PING) { - // We always answer ping messages - // Wait a random delay of 0-2 seconds to minimize collision - // between ping ack messages from other relaying nodes - randomSeed(millis()); - delay(random(2000)); - ltoa(distance, convBuffer, 10); - uint8_t to = msg.header.from; - debug(PSTR("Answer ping message. %d\n"), strlen(convBuffer)); - buildMsg(radioId, to, NODE_CHILD_ID, M_INTERNAL, I_PING_ACK, convBuffer,strlen(convBuffer), false); - sendWrite(to, msg, strlen(convBuffer)); - } else if (msg.header.to == radioId) { - // This message is addressed to this node - if (msg.header.messageType == M_INTERNAL) { - // Handle all internal messages to this node - if (msg.header.type == I_RELAY_NODE && msg.header.to != GATEWAY_ADDRESS) { - // Someone at sensor net gateway side wants this node to refresh its relay node - findRelay(); - // Send relay information back to sensor net gateway node device. - sendInternal(I_RELAY_NODE, ltoa(relayId, convBuffer, 10)); - return false; - } else if (msg.header.type == I_CHILDREN && msg.header.to != GATEWAY_ADDRESS) { - debug(PSTR("Route command received")); - if (strncmp(msg.data,"F", 1) == 0) { - // Send in as many children we can fit in a message (binary) - sendChildren(); - } else if (strncmp(msg.data,"C", 1) == 0) { - // Clears child relay data for this node - clearChildRoutes(); - } - return false; - } - // Return rest of internal messages back to sketch... - if (msg.header.last != GATEWAY_ADDRESS) - addChildRoute(msg.header.from, msg.header.last); - - return true; - } else { - // If this is variable message from sensor net gateway. Send ack back. - debug(PSTR("Message addressed for this node.\n")); - if (msg.header.from == GATEWAY_ADDRESS && - msg.header.messageType == M_SET_VARIABLE) { - // Send back ack message to sensor net gateway - sendVariableAck(); - } - // Return message to waiting sketch... - if (msg.header.last != GATEWAY_ADDRESS) - addChildRoute(msg.header.from, msg.header.last); - - return true; - } - } else { - // We should probably try to relay this message - relayMessage(len, pipe); - } - } - } - return false; -} - - - - -void Relay::relayMessage(uint8_t length, uint8_t pipe) { - uint8_t route = getChildRoute(msg.header.to); - if (route>0 && route<255) { - debug(PSTR("Routing message to child node.\n")); - // This message should be forwarded to a child node. If we send message - // to this nodes pipe then all children will receive it because the are - // all listening to this nodes pipe. - // - // +----B - // -A - // +----C------D - // - // We're node C, Message comes from A and has destination D - // - // lookup route in table and send message there - sendWrite(route, msg, length); - } else if (pipe == CURRENT_NODE_PIPE) { - // A message comes from a child node and we have no - // route for it. - // - // +----B - // -A - // +----C------D <-- Message comes from D - // - // We're node C - // - // Message should be passed to node A (this nodes relay) - - debug(PSTR("Routing message to relay.\n")); - // This message should be routed back towards sensor net gateway - sendWrite(relayId, msg, length); - // Add this child to our "routing table" if it not already exist - addChildRoute(msg.header.from, msg.header.last); - } else { - // We're snooped a message directed to gateway from another branch - // Make sure to remove the sender node from our routing table. - // - // +-----B <-- Message comes from here - // -A - // +-----C <-- We're here - // - // So the sender of message should never be in our - // routing table. - // - // We could also end up in this else-statement if message - // destination has no route. - // This can happen if a node never has sent any message to - // sensor net gateway (which will build up routing information in all nodes - // that gets passed). - if (radioId == GATEWAY_ADDRESS) { - // We should perhaps inform gateway about the no-route situation?! - debug(PSTR("Unknown route from GW\n")); - - } else { - debug(PSTR("Remove child node from routing table.\n")); - removeChildRoute(msg.header.from); - } - } -} - - -void Relay::addChildRoute(uint8_t childId, uint8_t route) { - if (childNodeTable[childId] != route) { - childNodeTable[childId] = route; - EEPROM.write(EEPROM_ROUTES_ADDRESS+childId, route); - } -} - -void Relay::removeChildRoute(uint8_t childId) { - if (childNodeTable[childId] != 0xff) { - childNodeTable[childId] = 0xff; - EEPROM.write(EEPROM_ROUTES_ADDRESS+childId, 0xff); - } -} - -uint8_t Relay::getChildRoute(uint8_t childId) { - return childNodeTable[childId]; -} - -void Relay::clearChildRoutes() { - debug(PSTR("Clear child routing data\n")); - for (unsigned int i=0;i< sizeof(childNodeTable); i++) { - removeChildRoute(i); - } - sendInternal(I_CHILDREN, ""); -} - -void Relay::sendChildren() { - // Send in which children that is using this node as an relay. - // TODO: Fix this - debug(PSTR("Send child info to sensor gateway.\n")); - - for (int i=0;i< 10; i++) { -// Serial.println(childNodeTable[i]); - debug(PSTR("rt:%d, %d\n"), i, getChildRoute(i) ); - } - - //sendInternal(I_CHILDREN, "not implemented"); -} - - diff --git a/libraries/MySensors/Relay.h b/libraries/MySensors/Relay.h deleted file mode 100644 index 6c17656..0000000 --- a/libraries/MySensors/Relay.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - The MySensors Arduino library adds a new layer on top of the RF24 library. - It handles radio network routing, relaying and ids. - - Created by Henrik Ekblad - - 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. -*/ - -#ifndef Relay_h -#define Relay_h - -#include "Sensor.h" - -#ifdef DEBUG -#define debug(x,...) debugPrint(x, ##__VA_ARGS__) -#else -#define debug(x,...) -#endif - - - -#define EEPROM_ROUTES_ADDRESS ((uint8_t)3) // Where to start storing routing information in EEPROM. Will allocate 256 bytes. - - -class Relay : public Sensor -{ - - public: - /** - * Constructor - * - * Creates a new instance of Relay class. - * - * @param _cepin The pin attached to RF24 Chip Enable on the RF module (default 9) - * @param _cspin The pin attached to RF24 Chip Select (default 10) - */ - Relay(uint8_t _cepin = 9, uint8_t _cspin = 10); - - void begin(uint8_t radioId=AUTO, rf24_pa_dbm_e paLevel=RF24_PA_LEVEL, uint8_t channel=RF24_CHANNEL, rf24_datarate_e dataRate=RF24_DATARATE); - boolean messageAvailable(); - boolean send(message_s message, int length); - - boolean sendData(uint8_t from, uint8_t to, uint8_t childId, uint8_t messageType, uint8_t type, const char *data, uint8_t length, boolean binary); - - protected: - void sendChildren(); - - private: - uint8_t childNodeTable[256]; // Buffer to store child node information. Store this in EEPROM - - uint8_t getChildRoute(uint8_t childId); - void addChildRoute(uint8_t childId, uint8_t route); - void removeChildRoute(uint8_t childId); - void clearChildRoutes(); - void relayMessage(uint8_t length, uint8_t pipe); - -}; - -#endif diff --git a/libraries/MySensors/Sensor.cpp b/libraries/MySensors/Sensor.cpp deleted file mode 100644 index 6a77ebd..0000000 --- a/libraries/MySensors/Sensor.cpp +++ /dev/null @@ -1,567 +0,0 @@ - /* - The MySensors library adds a new layer on top of the RF24 library. - It handles radio network routing, relaying and ids. - - Created by Henrik Ekblad - - 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. - */ - -#include "Sensor.h" - - -Sensor::Sensor(uint8_t _cepin, uint8_t _cspin) : RF24(_cepin, _cspin) { - isRelay = false; -} - - -void Sensor::setupRadio(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate) { - failedTransmissions = 0; - - // Start up the radio library - RF24::begin(); - RF24::enableDynamicPayloads(); - RF24::setAutoAck(false); - RF24::setRetries(15, 15); - RF24::setPALevel(paLevel); - RF24::setChannel(channel); - RF24::setDataRate(dataRate); - RF24::setCRCLength(RF24_CRC_16); - - // All repeater nodes and gateway listen to broadcast pipe (for PING messages) - if (isRelay) { - RF24::openReadingPipe(BROADCAST_PIPE, TO_ADDR(BROADCAST_ADDRESS)); - } -} - -void Sensor::begin(uint8_t _radioId, rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate) { - Serial.begin(BAUD_RATE); - - radioId = _radioId; - - debug(PSTR("Started %s.\n"), isRelay?"relay":"sensor"); - - setupRadio(paLevel, channel, dataRate); - - // Fetch relay from EEPROM - relayId = EEPROM.read(EEPROM_RELAY_ID_ADDRESS); - // Fetch distance from eeprom - distance = EEPROM.read(EEPROM_DISTANCE_ADDRESS); - if (relayId == 0xff) { - // No relay previously fetched and stored in eeprom. Try to find one. - findRelay(); - } - debug(PSTR("Relay=%d, distance=%d\n"), relayId, distance); - - initializeRadioId(); - - // Open reading pipe for messages directed to this node - RF24::openReadingPipe(CURRENT_NODE_PIPE, TO_ADDR(radioId)); - - // Send presentation for this radio node - sendSensorPresentation(NODE_CHILD_ID, isRelay? S_ARDUINO_RELAY : S_ARDUINO_NODE); - - // Send relay information back to sensor net gateway. - sendInternal(I_RELAY_NODE, itoa(relayId, convBuffer, 10)); - - // Initialize ack message header - ack.header.version = PROTOCOL_VERSION; - ack.header.binary = 0; - ack.header.from = radioId; - ack.header.to = GATEWAY_ADDRESS; - ack.header.messageType = M_SET_VARIABLE; -} - - -uint8_t Sensor::getRadioId() { - return radioId; -} - -void Sensor::initializeRadioId() { - if (radioId == AUTO) { - radioId = EEPROM.read(EEPROM_RADIO_ID_ADDRESS); - if (radioId == 0xFF || radioId == 0) { - radioId = AUTO; - debug(PSTR("No radio id found in EEPROM fetching one from sensor net gateway\n")); - // No radio id has been fetched yet ant EEPROM is unwritten. - // Request new id from sensor net gateway. Use radioId 4095 temporarily - // to be able to receive my correct nodeId. - RF24::openReadingPipe(CURRENT_NODE_PIPE, TO_ADDR(radioId)); - radioId = atoi(getInternal(I_REQUEST_ID)); - // Write id to EEPROM - if (radioId == AUTO) { // sensor net gateway will return max id if all sensor id are taken - debug(PSTR("Sensor network is full! You already have the maximum of sensors!\n")); - while (1) {} // Wait here. Nothing else we can do... - } else { - debug(PSTR("Radio id received: %d\n"), radioId); - EEPROM.write(EEPROM_RADIO_ID_ADDRESS, radioId); - } - } - debug(PSTR("Radio id stored in EEPROM was: %d\n"), radioId); - } -} - - -void Sensor::findRelay() { - // This can be improved by using status = read_register(OBSERVE_TX,&observe_tx,1) on the - // sending side.. the problem is getting this information here without too much fuss. - // Stay in this method until one or more relay nodes answers ping message. - if (radioId == GATEWAY_ADDRESS) - return; // Gateway has no business here! - - failedTransmissions = 0; - - // Open a reading pipe for current radioId (if it differs from broadcast) - if (radioId != BROADCAST_PIPE) { - RF24::openReadingPipe(CURRENT_NODE_PIPE, TO_ADDR(radioId)); - debug(PSTR("Open ping reading pipe: %d\n"), radioId); - } - distance = 255; - uint8_t oldRelayId = relayId; - while (distance == 255) { - // Send ping message to BROADCAST_ADDRESS (to which all nodes listens and should reply to) - buildMsg(radioId, BROADCAST_ADDRESS, NODE_CHILD_ID, M_INTERNAL, I_PING, "", 0, false); - sendWrite(BROADCAST_ADDRESS, msg, 0); - // Wait for replies for max 10 seconds (or when buffer for all relay nodes have been filled up) - unsigned long enter = millis(); - uint8_t neighborDistanceToGW; - - // Wait for ack responses 5 seconds - while (millis() - enter < 5000) { - if (messageAvailable()) { - if (msg.header.messageType == M_INTERNAL && - msg.header.type == I_PING_ACK && - msg.header.to == radioId) { - neighborDistanceToGW = atoi(msg.data); - if (neighborDistanceToGW FIND_RELAY_RETRIES) { - findRelay(); - } - failedTransmissions++; - } else { - failedTransmissions = 0; - } - return ok; -} - - -boolean Sensor::sendWrite(uint8_t dest, message_s message, int length) { - - message.header.last = radioId; - message.header.crc = crc8Message(message, length); - debug(PSTR("Tx: fr=%d,to=%d,la=%d,ne=%d,ci=%d,mt=%d,ty=%d,cr=%d: %s\n"), - message.header.from,message.header.to, message.header.last, dest, message.header.childId, message.header.messageType, message.header.type, message.header.crc, message.data); - - bool ok = true; - bool broadcast = message.header.messageType == M_INTERNAL && message.header.type == I_PING; -// int retry = WRITE_RETRY; - RF24::stopListening(); - RF24::openWritingPipe(TO_ADDR(dest)); - RF24::write(&message, min(MAX_MESSAGE_LENGTH, sizeof(message.header) + length), broadcast); - RF24::closeReadingPipe(WRITE_PIPE); // Stop listening to write-pipe after transmit - RF24::startListening(); - - if (!broadcast) { - // ---------------- WAIT FOR ACK ------------------ - unsigned long startedWaiting = millis(); - bool timeout = false; - // Wait for ack message maximum 50 ms - while ( !RF24::available() && !timeout ) { - if (millis() - startedWaiting > ACK_MAX_WAIT ) { - timeout = true; - debug(PSTR("Ack: receive timeout\n")); - ok = false; - } - } - // Check payload size and content - if (!timeout) { - // Check payload size and content - if (RF24::getDynamicPayloadSize()==sizeof(uint8_t)) { - uint8_t idest; - RF24::read( &idest, sizeof(uint8_t)); - if (dest != idest) { - debug(PSTR("Ack: received ack from the wrong sensor\n")); - ok = false; - } else { - debug(PSTR("Ack: received OK\n")); - } - } else { - ok = false; - debug(PSTR("Ack: received none ack msg.\n")); - } - } - } - - - return ok; -} - -void Sensor::sendInternal(uint8_t variableType, const char *value) { - sendData(radioId, GATEWAY_ADDRESS, NODE_CHILD_ID, M_INTERNAL, variableType, value, strlen(value), false); -} - -// This will be added in 1.4 -/*void Sensor::sendVariable(uint8_t childId, uint8_t variableType, - const char *value, length) { - sendData(radioId, GATEWAY_ADDRESS, childId, M_SET_VARIABLE, variableType, value, length, true); -}*/ - - -void Sensor::sendVariable(uint8_t childId, uint8_t variableType, - const char *value) { - sendData(radioId, GATEWAY_ADDRESS, childId, M_SET_VARIABLE, variableType, value, strlen(value), false); -} - -void Sensor::sendVariable(uint8_t childId, uint8_t variableType, double value, int decimals) { - sendVariable(childId, variableType, dtostrf(value,2,decimals,convBuffer)); -} - -void Sensor::sendVariable(uint8_t childId, uint8_t variableType, int value) { - sendVariable(childId, variableType, itoa(value, convBuffer, 10)); -} - -void Sensor::sendVariable(uint8_t childId, uint8_t variableType, long value) { - sendVariable(childId, variableType, ltoa(value, convBuffer, 10)); -} - -void Sensor::sendVariable(uint8_t childId, uint8_t variableType, unsigned long value) { - sendVariable(childId, variableType, ltoa(value, convBuffer, 10)); -} - -void Sensor::sendVariable(uint8_t childId, uint8_t variableType, unsigned int value) { - sendVariable(childId, variableType, ltoa(value, convBuffer, 10)); -} - -void Sensor::sendVariable(uint8_t nodeId, uint8_t childId, uint8_t variableType, - const char *value) { - sendData(radioId, nodeId, childId, M_SET_VARIABLE, variableType, value, strlen(value), false); -} - -void Sensor::sendVariable(uint8_t nodeId, uint8_t childId, uint8_t variableType, double value, int decimals) { - sendVariable(nodeId, childId, variableType, dtostrf(value,2,decimals,convBuffer)); -} - -void Sensor::sendVariable(uint8_t nodeId, uint8_t childId, uint8_t variableType, int value) { - sendVariable(nodeId, childId, variableType, itoa(value, convBuffer, 10)); -} - -void Sensor::sendVariable(uint8_t nodeId, uint8_t childId, uint8_t variableType, long value) { - sendVariable(nodeId, childId, variableType, ltoa(value, convBuffer, 10)); -} - -void Sensor::sendVariable(uint8_t nodeId, uint8_t childId, uint8_t variableType, unsigned long value) { - sendVariable(nodeId, childId, variableType, ltoa(value, convBuffer, 10)); -} - -void Sensor::sendVariable(uint8_t nodeId, uint8_t childId, uint8_t variableType, unsigned int value) { - sendVariable(nodeId, childId, variableType, ltoa(value, convBuffer, 10)); -} - -void Sensor::sendSensorPresentation(uint8_t childId, uint8_t sensorType) { - sendData(radioId, GATEWAY_ADDRESS, childId, M_PRESENTATION, sensorType, LIBRARY_VERSION, strlen(LIBRARY_VERSION), false); -} - -void Sensor::requestStatus(uint8_t childId, uint8_t variableType) { - sendData(radioId, GATEWAY_ADDRESS, childId, M_REQ_VARIABLE, variableType, "", 0, false); -} - -void Sensor::requestStatus(uint8_t nodeId, int8_t childId, uint8_t variableType) { - sendData(radioId, nodeId, childId, M_REQ_VARIABLE, variableType, "", 0, false); -} - -void Sensor::sendSketchInfo(const char *name, const char *version) { - sendSketchName(name); - sendSketchVersion(version); -} - -void Sensor::sendSketchName(const char *name) { - if (name != NULL) - sendInternal(I_SKETCH_NAME, name); -} - -void Sensor::sendSketchVersion(const char *version) { - if (version != NULL) - sendInternal(I_SKETCH_VERSION, version); -} - -void Sensor::sendBatteryLevel(int value) { - sendInternal(I_BATTERY_LEVEL, ltoa(value, convBuffer, 10)); -} - -char* Sensor::get(uint8_t nodeId, uint8_t childId, uint8_t sendType, uint8_t receiveType, uint8_t variableType) { - while (1) { - sendData(radioId, nodeId, childId, sendType, variableType, "", 0, false); - uint8_t i = 0; - while (i < 100) { // 5 seconds timeout before re-sending status request - while (messageAvailable()) { - // Check that it is right type of message and not a routing message - if (msg.header.messageType == receiveType && - msg.header.type == variableType && - msg.header.childId == childId) { - return msg.data; - } - } - delay(50); - i++; - } - } - return NULL; -} - -char* Sensor::getStatus(uint8_t childId, uint8_t variableType) { - return get(GATEWAY_ADDRESS, childId, M_REQ_VARIABLE, M_ACK_VARIABLE, variableType); -} - -char * Sensor::getStatus(uint8_t nodeId, int8_t childId, uint8_t variableType) { - return get(nodeId, childId, M_REQ_VARIABLE, M_ACK_VARIABLE, variableType); -} - - - -char* Sensor::getInternal(uint8_t variableType) { - return get(GATEWAY_ADDRESS, NODE_CHILD_ID, M_INTERNAL, M_INTERNAL, variableType); -} - -unsigned long Sensor::getTime() { - return atol(getInternal(I_TIME)); -} - -void Sensor::requestTime() { - sendData(radioId, GATEWAY_ADDRESS, NODE_CHILD_ID, M_INTERNAL, I_TIME, "", 0, false); -} - - -bool Sensor::isMetricSystem() { - return getInternal(I_UNIT)[0] == 'M'; -} - -void Sensor::requestIsMetricSystem() { - sendData(radioId, GATEWAY_ADDRESS, NODE_CHILD_ID, M_INTERNAL, I_UNIT, "", 0, false); -} - - -boolean Sensor::messageAvailable() { - uint8_t pipe; - boolean available = RF24::available(&pipe); - - if (available) { - debug(PSTR("Message available on pipe %d\n"),pipe); - } - - - if (available && pipe<7) { - boolean ok = readMessage(); - if (ok && msg.header.to == radioId) { - // This message is addressed to this node - debug(PSTR("Message addressed for this node.\n")); - if (msg.header.from == GATEWAY_ADDRESS && - // If this is variable message from sensor net gateway. Send ack back. - msg.header.messageType == M_SET_VARIABLE) { - // Send back ack message to sensor net gateway - sendVariableAck(); - } - // Return message to waiting sketch... - return true; - } - } - return false; -} - - -message_s Sensor::waitForMessage() { - while (1) { - if (messageAvailable()) { - return msg; - } - } -} - -message_s Sensor::getMessage() { - return msg; -} - - -boolean Sensor::readMessage() { - uint8_t len = RF24::getDynamicPayloadSize(); - RF24::read(&msg, len); - - uint8_t valid = validate(len-sizeof(header_s)); - boolean ok = valid == VALIDATE_OK; - - if (ok && !(msg.header.messageType==M_INTERNAL && msg.header.type == I_PING_ACK)) { - delay(ACK_SEND_DELAY); // Small delay here to let other side switch to reading mode - RF24::stopListening(); - RF24::openWritingPipe(TO_ADDR(msg.header.last)); - RF24::write(&radioId, sizeof(uint8_t)); - RF24::closeReadingPipe(WRITE_PIPE); // Stop listening to write-pipe after transmit - RF24::startListening(); - debug(PSTR("Sent ack msg to %d\n"), msg.header.last); - } - - // Make sure string gets terminated ok for full sized messages. - msg.data[len - sizeof(header_s) ] = '\0'; - debug(PSTR("Rx: fr=%d,to=%d,la=%d,ci=%d,mt=%d,t=%d,cr=%d(%s): %s\n"), - msg.header.from,msg.header.to, msg.header.last, msg.header.childId, msg.header.messageType, msg.header.type, msg.header.crc, valid==0?"ok":valid==1?"ec":"ev", msg.data); - return ok; -} - -/* - * calculate CRC8 on message_s data taking care of data structure and protocol version - */ -uint8_t Sensor::crc8Message(message_s var_msg, uint8_t len) { - uint8_t crc = 0x00; - uint8_t loop_count; - uint8_t bit_counter; - uint8_t data; - uint8_t feedback_bit; - uint8_t number_of_bytes_to_read = (uint8_t)sizeof(var_msg); - - // Must set crc to a constant value. - var_msg.header.crc = 0; - - // fill unused space by zeroes for string data only - if(len>=0 && len < sizeof(var_msg.data)-1) { - memset(&var_msg.data[len], 0, sizeof(var_msg.data) - 1 - len); - } - - - for (loop_count = 0; loop_count != number_of_bytes_to_read; loop_count++) - { - data = ((uint8_t*)&var_msg)[loop_count]; - - bit_counter = 8; - do { - feedback_bit = (crc ^ data) & 0x01; - - if ( feedback_bit == 0x01 ) { - crc = crc ^ 0x18; //0X18 = X^8+X^5+X^4+X^0 - } - crc = (crc >> 1) & 0x7F; - if ( feedback_bit == 0x01 ) { - crc = crc | 0x80; - } - - data = data >> 1; - bit_counter--; - - } while (bit_counter > 0); - } - return crc; -} - - -uint8_t Sensor::validate(uint8_t length) { - uint8_t oldCrc = msg.header.crc; - uint8_t newCrc = crc8Message(msg, length); - - if(!(msg.header.version == PROTOCOL_VERSION)) return VALIDATE_BAD_VERSION; - - if(!(oldCrc == newCrc)) return VALIDATE_BAD_CRC; - return VALIDATE_OK; -} - -#ifdef DEBUG -void Sensor::debugPrint(const char *fmt, ... ) { - char fmtBuffer[300]; - if (radioId == GATEWAY_ADDRESS) { - // prepend debug message to be handled correctly by gw - Serial.print("0;0;4;11;"); - } - va_list args; - va_start (args, fmt ); - vsnprintf_P(fmtBuffer, 300, fmt, args); - va_end (args); - if (radioId == GATEWAY_ADDRESS) { - // Truncate message if this is gateway node - vsnprintf_P(fmtBuffer, 60, fmt, args); - fmtBuffer[59] = '\n'; - fmtBuffer[60] = '\0'; - } else { - vsnprintf_P(fmtBuffer, 299, fmt, args); - } - va_end (args); - Serial.print(fmtBuffer); - - - //Serial.print("0;0;4;11;Mem free:"); - //Serial.println(freeRam()); -} -#endif - - -#ifdef DEBUG -int Sensor::freeRam (void) { - extern int __heap_start, *__brkval; - int v; - return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); -} -#endif diff --git a/libraries/MySensors/Sensor.h b/libraries/MySensors/Sensor.h deleted file mode 100644 index 60aea19..0000000 --- a/libraries/MySensors/Sensor.h +++ /dev/null @@ -1,301 +0,0 @@ -/* - The Sensor Net Arduino library adds a new layer on top of the RF24 library. - It handles radio network routing, relaying and ids. - - Created by Henrik Ekblad - - 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. -*/ - -#ifndef Sensor_h -#define Sensor_h - -#include "Config.h" -#include "Version.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef DEBUG -#define debug(x,...) debugPrint(x, ##__VA_ARGS__) -#else -#define debug(x,...) -#endif - -#define PROTOCOL_VERSION 1 -#define BAUD_RATE 115200 - -#define AUTO 0xFF // 0-254. Id 255 is reserved for auto initialization of radioId. -#define NODE_CHILD_ID 0xFF // Node child id is always created for when a new sensor is detected -#define EEPROM_RADIO_ID_ADDRESS 0 // Where to store radio id in EEPROM -#define EEPROM_RELAY_ID_ADDRESS 1 // Where to store relay id in EEPROM -#define EEPROM_DISTANCE_ADDRESS 2 // Where to store distance to gateway in EEPROM - -// This is the radioId for sensor net gateway receiver sketch (where all sensors should send their data). -// This is also act as base value for sensor radioId -#define BASE_RADIO_ID ((uint64_t)0xABCDABC000LL) -#define GATEWAY_ADDRESS ((uint8_t)0) -#define BROADCAST_ADDRESS ((uint8_t)0xFF) -#define TO_ADDR(x) (BASE_RADIO_ID + x) - -#define WRITE_PIPE ((uint8_t)0) -#define CURRENT_NODE_PIPE ((uint8_t)1) -#define BROADCAST_PIPE ((uint8_t)2) - -#define ACK_MAX_WAIT 50 -#define ACK_SEND_DELAY 10 - -#define WRITE_RETRY 5 -#define FIND_RELAY_RETRIES 20 - - -#define MAX_MESSAGE_LENGTH 32 - -// Message types -typedef enum { - M_PRESENTATION = 0, - M_SET_VARIABLE = 1, - M_REQ_VARIABLE = 2, - M_ACK_VARIABLE = 3, - M_INTERNAL = 4 -} messageType; - -// Sensor variables that can be used in sketches -typedef enum { - V_TEMP,V_HUM, V_LIGHT, V_DIMMER, V_PRESSURE, V_FORECAST, V_RAIN, - V_RAINRATE, V_WIND, V_GUST, V_DIRECTION, V_UV, V_WEIGHT, V_DISTANCE, - V_IMPEDANCE, V_ARMED, V_TRIPPED, V_WATT, V_KWH, V_SCENE_ON, V_SCENE_OFF, - V_HEATER, V_HEATER_SW, V_LIGHT_LEVEL, V_VAR1, V_VAR2, V_VAR3, V_VAR4, V_VAR5, - V_UP, V_DOWN, V_STOP, V_IR_SEND, V_IR_RECEIVE, V_FLOW, V_VOLUME, V_LOCK_STATUS -} variableType; - -// Internal messages -typedef enum { - I_BATTERY_LEVEL, I_BATTERY_DATE, I_LAST_TRIP, I_TIME, I_VERSION, I_REQUEST_ID, - I_INCLUSION_MODE, I_RELAY_NODE, I_LAST_UPDATE, I_PING, I_PING_ACK, - I_LOG_MESSAGE, I_CHILDREN, I_UNIT, I_SKETCH_NAME, I_SKETCH_VERSION -} internalMessageType; - -// Sensor types -typedef enum { - S_DOOR, S_MOTION, S_SMOKE, S_LIGHT, S_DIMMER, S_COVER, S_TEMP, S_HUM, S_BARO, S_WIND, - S_RAIN, S_UV, S_WEIGHT, S_POWER, S_HEATER, S_DISTANCE, S_LIGHT_LEVEL, S_ARDUINO_NODE, - S_ARDUINO_RELAY, S_LOCK, S_IR, S_WATER -} sensor; - -// Possible return values by validate() when doing crc check of received message. -enum { - VALIDATE_OK, VALIDATE_BAD_CRC, VALIDATE_BAD_VERSION -}; - -// The message structure -typedef struct { - uint8_t crc : 8; // 8 bits crc - uint8_t version : 3; // 3 bits protocol version - uint8_t binary : 1; // 1 bit. Data is binary and should be encoded when sent to sensor net gateway - uint8_t from : 8; // 8 bits. RadioId of sender node - uint8_t to : 8; // 8 bits. RadioId of destination node - uint8_t last : 8; // 8 bits. RadioId of last node this message passed - uint8_t childId : 8; // 1 byte. Up to MAX_CHILD_DEVICES child sensors per radioId - uint8_t messageType : 4; // 4 bits. Type of message. See messageType - - uint8_t type : 8; // 8 bits. variableType or deviceType depending on messageType -} header_s; - -typedef struct { - header_s header; - char data[MAX_MESSAGE_LENGTH - sizeof(header_s) + 1]; // Each message can transfer a payload. Add one extra byte for \0 -} message_s; - - -class Sensor : public RF24 -{ - public: - /** - * Constructor - * - * Creates a new instance of Sensor class. - * - * @param _cepin The pin attached to RF24 Chip Enable on the RF module (defualt 9) - * @param _cspin The pin attached to RF24 Chip Select (default 10) - */ - Sensor(uint8_t _cepin=9, uint8_t _cspin=10); - - /** - * Begin operation of the MySensors library - * - * Call this in setup(), before calling any other sensor net library methods. - * @param radioId The unique id (1-254) for this sensor. Default 255 (auto mode). - * @param paLevel Radio PA Level for this sensor. Default RF24_PA_MAX - * @param channel Radio channel. Default is channel 76 - * @param dataRate Radio transmission speed. Default RF24_2MBPS - */ - void begin(uint8_t radioId=AUTO, rf24_pa_dbm_e paLevel=RF24_PA_LEVEL, uint8_t channel=RF24_CHANNEL, rf24_datarate_e dataRate=RF24_DATARATE); - - uint8_t getRadioId(); - - /** - * The arduino node must send a presentation of all the sensors connected before any - * variable changes will be registered on sensor net gateway side. - * Usually it's good to present all sensors when arduino starts up (setup). - * Note that gateway must be in include mode to register new devices. - * - * @param childId The unique child id for the different sensors connected to this arduino. 0-254. - * @param sensorType Sensor types to create. They will be numbered from 0 up to 127. - */ - void sendSensorPresentation(uint8_t childId, uint8_t sensorType); - - - /** - * Sends a variable change to sensor net gateway (or another sensor if radioId is specified) - * - * @param radioId The radioId of other node in radio network (used for communicating between sensors) - * @param childId The child id for which to update variable. Value can be 0-254. - * @param variableType The variableType to update - * @param value New value of the variable - */ - - void sendVariable(uint8_t childId, uint8_t variableType, const char *value); - void sendVariable(uint8_t childId, uint8_t variableType, double value, int decimals); - void sendVariable(uint8_t childId, uint8_t variableType, unsigned long value); - void sendVariable(uint8_t childId, uint8_t variableType, long value); - void sendVariable(uint8_t childId, uint8_t variableType, unsigned int value); - void sendVariable(uint8_t childId, uint8_t variableType, int value); - - void sendVariable(uint8_t radioId, uint8_t childId, uint8_t variableType, const char *value); - void sendVariable(uint8_t radioId, uint8_t childId, uint8_t variableType, double value, int decimals); - void sendVariable(uint8_t radioId, uint8_t childId, uint8_t variableType, unsigned long value); - void sendVariable(uint8_t radioId, uint8_t childId, uint8_t variableType, long value); - void sendVariable(uint8_t radioId, uint8_t childId, uint8_t variableType, unsigned int value); - void sendVariable(uint8_t radioId, uint8_t childId, uint8_t variableType, int value); - - /** - * Sends sketch info to sensor net gateway for this radio node. - * @param name String containing a short Sketch name - * @param version String containing a short Sketch version - */ - void sendSketchInfo(const char *name, const char *version); - - /** - * Sends sketch name to sensor net gateway for this radio node. - * @param info String containing a short Sketch name and version - */ - void sendSketchName(const char *name); - - /** - * Sends sketch version to sensor net gateway for this radio node. - * @param info String containing a short Sketch name and version - */ - void sendSketchVersion(const char *version); - - /** - * Sends battery status to sensor net gateway for this radio node. - * @param value Set a value between 0-100(%) - */ - void sendBatteryLevel(int value); - - /** - * Requests a variable value from sensor net gateway (or another sensor). This method will not wait for an answer. - * You should use mesageAvailable/getMessage to pick up the response. - * - * @param radioId The radioId of other node in radio network (used when fetching from other node) - * @param childId The unique child id for the different sensors connected to this arduino. 0-254. - * @param variableType The variableType to fetch - */ - void requestStatus(uint8_t childId, uint8_t variableType); - void requestStatus(uint8_t radioId, int8_t childId, uint8_t variableType); - - /** - * Requests status for a sensor variable from sensor net gateway. Waits until message arrives. - * - * @param radioId The radioId of other node in radio network (used when fetching from other node) - * @param childId The unique child id for the different sensors connected to this arduino. 0-254. - * @param variableType The variableType to fetch - * @return The variable value - */ - char *getStatus(uint8_t childId, uint8_t variableType); - char *getStatus(uint8_t radioId, int8_t childId, uint8_t variableType); - - - /** - * Fetches time from sensor net gateway - */ - void requestTime(); - unsigned long getTime(); - - /** - * Fetches unit setting from sensor net gateway. Returns true if metric system has been selected which means - * that sensor should report it's information in: celsius, meter, cm, gram, km/h, m/s etc.. - * If false is returned the sensor should report data in imperial system which means - * fahrenheit, feet, gallon, mph etc... - */ - void requestIsMetricSystem(); - bool isMetricSystem(); - - - /** - * Busy waits until there is a message for this node available to be read - */ - message_s waitForMessage(void); - - /** - * Returns true if there is a message addressed for this node is available to be read - */ - boolean messageAvailable(void); - - /** - * Returns the last received message - */ - message_s getMessage(void); - - /** - * Validates consistency of the message including CRC and protocol version - */ - uint8_t validate(uint8_t length); - - -#ifdef DEBUG - void debugPrint(const char *fmt, ... ); - int freeRam(); -#endif - - - protected: - uint8_t failedTransmissions; - boolean isRelay; - uint8_t radioId; - uint8_t distance; // This nodes distance to sensor net gateway (number of hops) - uint8_t relayId; - message_s msg; // Buffer for incoming messages. - char convBuffer[20]; - - void setupRadio(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate); - void findRelay(); - boolean send(message_s message, int length); - boolean sendWrite(uint8_t dest, message_s message, int length); - boolean readMessage(); - void buildMsg(uint8_t from, uint8_t to, uint8_t childId, uint8_t messageType, uint8_t type, const char *data, uint8_t length, boolean binary); - void sendInternal(uint8_t variableType, const char *value); - boolean sendVariableAck(); - boolean sendData(uint8_t from, uint8_t to, uint8_t childId, uint8_t messageType, uint8_t type, const char *data, uint8_t length, boolean binaryMessage); - - - - private: - message_s ack; // Buffer for ack messages. - - void initializeRadioId(); - uint8_t crc8Message(message_s, uint8_t length); - char* get(uint8_t nodeId, uint8_t childId, uint8_t sendType, uint8_t receiveType, uint8_t variableType); - char *getInternal(uint8_t variableType); -}; - -#endif diff --git a/libraries/MySensors/Version.h b/libraries/MySensors/Version.h index 867b7ce..026d736 100644 --- a/libraries/MySensors/Version.h +++ b/libraries/MySensors/Version.h @@ -6,6 +6,6 @@ #ifndef Version_h #define Version_h -#define LIBRARY_VERSION "1.3b3 (67f4ca1)" +#define LIBRARY_VERSION "1.4" #endif diff --git a/libraries/MySensors/examples/AirQualitySensor/AirQualitySensor.ino b/libraries/MySensors/examples/AirQualitySensor/AirQualitySensor.ino new file mode 100644 index 0000000..efe12f3 --- /dev/null +++ b/libraries/MySensors/examples/AirQualitySensor/AirQualitySensor.ino @@ -0,0 +1,196 @@ +/* + Vera Arduino MQ2 + + connect the MQ2 sensor as follows : + + A H A >>> 5V + B >>> A0 + H >>> GND + B >>> 10K ohm >>> GND + + Contribution: epierre + Based on http://sandboxelectronics.com/?p=165 + + License: Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0) + + Modified by HEK to work in 1.4 +*/ + +#include +#include +#include + +#define CHILD_ID_MQ 0 +/************************Hardware Related Macros************************************/ +#define MQ_SENSOR_ANALOG_PIN (0) //define which analog input channel you are going to use +#define RL_VALUE (5) //define the load resistance on the board, in kilo ohms +#define RO_CLEAN_AIR_FACTOR (9.83) //RO_CLEAR_AIR_FACTOR=(Sensor resistance in clean air)/RO, + //which is derived from the chart in datasheet +/***********************Software Related Macros************************************/ +#define CALIBARAION_SAMPLE_TIMES (50) //define how many samples you are going to take in the calibration phase +#define CALIBRATION_SAMPLE_INTERVAL (500) //define the time interal(in milisecond) between each samples in the + //cablibration phase +#define READ_SAMPLE_INTERVAL (50) //define how many samples you are going to take in normal operation +#define READ_SAMPLE_TIMES (5) //define the time interal(in milisecond) between each samples in + //normal operation +/**********************Application Related Macros**********************************/ +#define GAS_LPG (0) +#define GAS_CO (1) +#define GAS_SMOKE (2) +/*****************************Globals***********************************************/ +unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) +//VARIABLES +float Ro = 10000.0; // this has to be tuned 10K Ohm +int val = 0; // variable to store the value coming from the sensor +float valMQ =0.0; +float lastMQ =0.0; +float LPGCurve[3] = {2.3,0.21,-0.47}; //two points are taken from the curve. + //with these two points, a line is formed which is "approximately equivalent" + //to the original curve. + //data format:{ x, y, slope}; point1: (lg200, 0.21), point2: (lg10000, -0.59) +float COCurve[3] = {2.3,0.72,-0.34}; //two points are taken from the curve. + //with these two points, a line is formed which is "approximately equivalent" + //to the original curve. + //data format:{ x, y, slope}; point1: (lg200, 0.72), point2: (lg10000, 0.15) +float SmokeCurve[3] ={2.3,0.53,-0.44}; //two points are taken from the curve. + //with these two points, a line is formed which is "approximately equivalent" + //to the original curve. + //data format:{ x, y, slope}; point1: (lg200, 0.53), point2:(lg10000,-0.22) + + +MySensor gw; +MyMessage msg(CHILD_ID_MQ, V_VAR1); + + +void setup() +{ + gw.begin(); + + // Send the sketch version information to the gateway and Controller + gw.sendSketchInfo("Air Quality Sensor", "1.0"); + + // Register all sensors to gateway (they will be created as child devices) + gw.present(CHILD_ID_MQ, S_AIR_QUALITY); + + Ro = MQCalibration(MQ_SENSOR_ANALOG_PIN); //Calibrating the sensor. Please make sure the sensor is in clean air + //when you perform the calibration +} + +void loop() +{ + uint16_t valMQ = MQGetGasPercentage(MQRead(MQ_SENSOR_ANALOG_PIN)/Ro,GAS_CO); + Serial.println(val); + + Serial.print("LPG:"); + Serial.print(MQGetGasPercentage(MQRead(MQ_SENSOR_ANALOG_PIN)/Ro,GAS_LPG) ); + Serial.print( "ppm" ); + Serial.print(" "); + Serial.print("CO:"); + Serial.print(MQGetGasPercentage(MQRead(MQ_SENSOR_ANALOG_PIN)/Ro,GAS_CO) ); + Serial.print( "ppm" ); + Serial.print(" "); + Serial.print("SMOKE:"); + Serial.print(MQGetGasPercentage(MQRead(MQ_SENSOR_ANALOG_PIN)/Ro,GAS_SMOKE) ); + Serial.print( "ppm" ); + Serial.print("\n"); + + if (valMQ != lastMQ) { + gw.send(msg.set((int)ceil(valMQ))); + lastMQ = ceil(valMQ); + } + + gw.sleep(SLEEP_TIME); //sleep for: sleepTime +} + +/****************** MQResistanceCalculation **************************************** +Input: raw_adc - raw value read from adc, which represents the voltage +Output: the calculated sensor resistance +Remarks: The sensor and the load resistor forms a voltage divider. Given the voltage + across the load resistor and its resistance, the resistance of the sensor + could be derived. +************************************************************************************/ +float MQResistanceCalculation(int raw_adc) +{ + return ( ((float)RL_VALUE*(1023-raw_adc)/raw_adc)); +} + +/***************************** MQCalibration **************************************** +Input: mq_pin - analog channel +Output: Ro of the sensor +Remarks: This function assumes that the sensor is in clean air. It use + MQResistanceCalculation to calculates the sensor resistance in clean air + and then divides it with RO_CLEAN_AIR_FACTOR. RO_CLEAN_AIR_FACTOR is about + 10, which differs slightly between different sensors. +************************************************************************************/ +float MQCalibration(int mq_pin) +{ + int i; + float val=0; + + for (i=0;i #include -#include -#include -#include +#include int BATTERY_SENSE_PIN = A0; // select the input pin for the battery sense point -Sensor gw; -Sleep sleep; +MySensor gw; unsigned long SLEEP_TIME = 900000; // sleep time between reads (seconds * 1000 milliseconds) int oldBatteryPcnt = 0; @@ -31,7 +26,7 @@ void loop() // get the battery Voltage int sensorValue = analogRead(BATTERY_SENSE_PIN); Serial.println(sensorValue); - + // 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 // ((1e6+470e3)/470e3)*1.1 = Vmax = 3.44 Volts @@ -52,14 +47,5 @@ void loop() gw.sendBatteryLevel(batteryPcnt); oldBatteryPcnt = batteryPcnt; } - - // delay to allow transmissions to gateway to be completed before sleep - delay(500); - - // Power down the radio. Note that the radio will get powered back up - // on the next write() call - gw.powerDown(); - - sleep.pwrDownMode(); // set sleep mode - sleep.sleepDelay(SLEEP_TIME); // sleep for SLEEP_TIME + gw.sleep(SLEEP_TIME); } diff --git a/libraries/MySensors/examples/BinarySwitchSensor/BinarySwitchSensor.ino b/libraries/MySensors/examples/BinarySwitchSensor/BinarySwitchSensor.ino index 61f4da2..6ca5886 100644 --- a/libraries/MySensors/examples/BinarySwitchSensor/BinarySwitchSensor.ino +++ b/libraries/MySensors/examples/BinarySwitchSensor/BinarySwitchSensor.ino @@ -2,18 +2,20 @@ // Connect button or door/window reed switch between // digitial I/O pin 3 (BUTTON_PIN below) and GND. -#include +#include #include -#include -#include #include +#define CHILD_ID 3 #define BUTTON_PIN 3 // Arduino Digital I/O pin for button/reed switch -Sensor gw; +MySensor gw; Bounce debouncer = Bounce(); int oldValue=-1; +// Change to V_LIGHT if you use S_LIGHT in presentation below +MyMessage msg(CHILD_ID,V_TRIPPED); + void setup() { gw.begin(); @@ -29,8 +31,8 @@ void setup() // Register binary input sensor to gw (they will be created as child devices) // You can use S_DOOR, S_MOTION or S_LIGHT here depending on your usage. - // If S_LIGHT is used, remember to update variable type you send in below. - gw.sendSensorPresentation(BUTTON_PIN, S_DOOR); + // If S_LIGHT is used, remember to update variable type you send in. See "msg" above. + gw.present(CHILD_ID, S_DOOR); } @@ -43,7 +45,7 @@ void loop() if (value != oldValue) { // Send in the new value - gw.sendVariable(BUTTON_PIN, V_TRIPPED, value==HIGH ? "1" : "0"); // Change to V_LIGHT if you use S_LIGHT in presentation above + gw.send(msg.set(value==HIGH ? 1 : 0)); oldValue = value; } } diff --git a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino index e4fe953..3c6c2c0 100644 --- a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino +++ b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino @@ -1,61 +1,67 @@ -#include +// Example sketch showing how to send in OneWire temperature readings +#include #include -#include #include #include -#include -#include #define ONE_WIRE_BUS 3 // Pin where dallase sensor is connected #define MAX_ATTACHED_DS18B20 16 -unsigned long SLEEP_TIME = 30; // Sleep time between reads (in seconds) - +unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire); -Sensor gw; -Sleep sleep; +MySensor gw; float lastTemperature[MAX_ATTACHED_DS18B20]; int numSensors=0; +boolean receivedConfig = false; boolean metric = true; +// Initialize temperature message +MyMessage msg(0,V_TEMP); void setup() { + // Startup OneWire sensors.begin(); + + // Startup and initialize MySensors library. Set callback for incoming messages. gw.begin(); // Send the sketch version information to the gateway and Controller gw.sendSketchInfo("Temperature Sensor", "1.0"); - // Fetch the number of attached sensors + // Fetch the number of attached temperature sensors numSensors = sensors.getDeviceCount(); - // Register all sensors to gw (they will be created as child devices) + + // Present all sensors to controller for (int i=0; i(static_cast((metric?sensors.getTempCByIndex(i):sensors.getTempFByIndex(i)) * 10.)) / 10.; + float temperature = static_cast(static_cast((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) { - gw.powerUp(); // Powerup introduces a small delay (which is missing in radio.write powerup) - // Send variable (using registered shortcut) to gw - gw.sendVariable(i, V_TEMP, temperature, 1); + + // Send in the new temperature + gw.send(msg.setSensor(i).set(temperature,1)); lastTemperature[i]=temperature; } } - // Power down the radio. Note that the radio will get powered back up - // on the next write() call. - delay(500); - gw.powerDown(); - sleep.pwrDownMode(); //set sleep mode - sleep.sleepDelay(SLEEP_TIME * 1000); //sleep for: sleepTime + gw.sleep(SLEEP_TIME); } + diff --git a/libraries/MySensors/examples/DimmableLEDActuator/DimmableLEDActuator.ino b/libraries/MySensors/examples/DimmableLEDActuator/DimmableLEDActuator.ino new file mode 100644 index 0000000..23188f1 --- /dev/null +++ b/libraries/MySensors/examples/DimmableLEDActuator/DimmableLEDActuator.ino @@ -0,0 +1,107 @@ +/*** + * 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. + * + * DESCRIPTION + * This sketch provides a Dimmable LED Light using PWM and based Henrik Ekblad + * Vera Arduino Sensor project. + * Developed by Bruce Lacey, inspired by Hek's MySensor's example sketches. + * + * The circuit uses a MOSFET for Pulse-Wave-Modulation to dim the attached LED or LED strip. + * The MOSFET Gate pin is connected to Arduino pin 3 (LED_PIN), the MOSFET Drain pin is connected + * to the LED negative terminal and the MOSFET Source pin is connected to ground. + * + * This sketch is extensible to support more than one MOSFET/PWM dimmer per circuit. + * + * REVISION HISTORY + * Version 1.0 - February 15, 2014 - Bruce Lacey + * Version 1.1 - August 13, 2014 - Converted to 1.4 (hek) + * + ***/ +#define SN "DimmableLED" +#define SV "1.1" + +#include +#include + +#define LED_PIN 3 // Arduino pin attached to MOSFET Gate pin +#define FADE_DELAY 10 // Delay in ms for each percentage fade up/down (10ms = 1s full-range dim) + +MySensor gw(9,10); + +static int currentLevel = 0; // Current dim level... +MyMessage dimmerMsg(0, V_DIMMER); +MyMessage lightMsg(0, V_LIGHT); + + +/*** + * Dimmable LED initialization method + */ +void setup() +{ + Serial.println( SN ); + gw.begin( incomingMessage ); + + // Register the LED Dimmable Light with the gateway + gw.present( 0, S_DIMMER ); + + gw.sendSketchInfo(SN, SV); + // Pull the gateway's current dim level - restore light level upon sendor node power-up + gw.request( 0, V_DIMMER ); +} + +/*** + * Dimmable LED main processing loop + */ +void loop() +{ + gw.process(); +} + + + +void incomingMessage(const MyMessage &message) { + if (message.type == V_LIGHT || message.type == V_DIMMER) { + + // Retrieve the power or dim level from the incoming request message + int requestedLevel = atoi( message.data ); + + // Adjust incoming level if this is a V_LIGHT variable update [0 == off, 1 == on] + requestedLevel *= ( message.type == V_LIGHT ? 100 : 1 ); + + // Clip incoming level to valid range of 0 to 100 + requestedLevel = requestedLevel > 100 ? 100 : requestedLevel; + requestedLevel = requestedLevel < 0 ? 0 : requestedLevel; + + Serial.print( "Changing level to " ); + Serial.print( requestedLevel ); + Serial.print( ", from " ); + Serial.println( currentLevel ); + + fadeToLevel( requestedLevel ); + + // Inform the gateway of the current DimmableLED's SwitchPower1 and LoadLevelStatus value... + gw.send(lightMsg.set(currentLevel > 0 ? 1 : 0)); + + // hek comment: Is this really nessesary? + gw.send( dimmerMsg.set(currentLevel) ); + + + } +} + +/*** + * This method provides a graceful fade up/down effect + */ +void fadeToLevel( int toLevel ) { + + int delta = ( toLevel - currentLevel ) < 0 ? -1 : 1; + + while ( currentLevel != toLevel ) { + currentLevel += delta; + analogWrite( LED_PIN, (int)(currentLevel / 100. * 255) ); + delay( FADE_DELAY ); + } +} + diff --git a/libraries/MySensors/examples/DistanceSensor/DistanceSensor.ino b/libraries/MySensors/examples/DistanceSensor/DistanceSensor.ino index 8c246d0..abd0530 100644 --- a/libraries/MySensors/examples/DistanceSensor/DistanceSensor.ino +++ b/libraries/MySensors/examples/DistanceSensor/DistanceSensor.ino @@ -1,19 +1,16 @@ -#include #include -#include -#include -#include +#include #include +#define CHILD_ID 1 #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 MAX_DISTANCE 300 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm. -unsigned long SLEEP_TIME = 5; // Sleep time between reads (in seconds) +unsigned long SLEEP_TIME = 5000; // Sleep time between reads (in milliseconds) -Sensor gw; +MySensor gw; NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance. -Sleep sleep; - +MyMessage msg(CHILD_ID, V_DISTANCE); int lastDist; boolean metric = true; @@ -25,30 +22,23 @@ void setup() gw.sendSketchInfo("Distance Sensor", "1.0"); // Register all sensors to gw (they will be created as child devices) - gw.sendSensorPresentation(0, S_DISTANCE); - metric = gw.isMetricSystem(); + gw.present(CHILD_ID, S_DISTANCE); + boolean metric = gw.getConfig().isMetric; } void loop() { int dist = metric?sonar.ping_cm():sonar.ping_in(); - Serial.print("Ping: "); Serial.print(dist); // Convert ping time to distance in cm and print result (0 = outside set distance range) Serial.println(metric?" cm":" in"); - if (dist != lastDist) { - gw.sendVariable(0, V_DISTANCE, dist); + gw.send(msg.set(dist)); lastDist = dist; } - // Power down the radio. Note that the radio will get powered back up - // on the next write() call. - delay(1000); //delay to allow serial to fully print before sleep - gw.powerDown(); - sleep.pwrDownMode(); //set sleep mode - sleep.sleepDelay(SLEEP_TIME * 1000); //sleep for: sleepTime + gw.sleep(SLEEP_TIME); } diff --git a/libraries/MySensors/examples/DustSensor/DustSensor.ino b/libraries/MySensors/examples/DustSensor/DustSensor.ino new file mode 100644 index 0000000..4ebe804 --- /dev/null +++ b/libraries/MySensors/examples/DustSensor/DustSensor.ino @@ -0,0 +1,80 @@ +/* + Arduino Dust Sensort + + connect the sensor as follows : + + VCC >>> 5V + A >>> A0 + GND >>> GND + + Based on: http://www.dfrobot.com/wiki/index.php/Sharp_GP2Y1010AU + Authors: Cyrille Médard de Chardon (serialC), Christophe Trefois (Trefex) + Contribution: epierre + COnverted to 1.4 by Henrik Ekblad + + The dust sensor used (see purchase guide for latest link): + http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=2&pub=5575069610&toolid=10001&campid=5337433187&customid=&icep_item=171259125886&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg + +*/ + +#include +#include + +#define CHILD_ID_DUST 0 +#define DUST_SENSOR_ANALOG_PIN 1 + +unsigned long SLEEP_TIME = 30*1000; // Sleep time between reads (in milliseconds) +//VARIABLES +int val = 0; // variable to store the value coming from the sensor +float valDUST =0.0; +float lastDUST =0.0; +int samplingTime = 280; +int deltaTime = 40; +int sleepTime = 9680; +float voMeasured = 0; +float calcVoltage = 0; +float dustDensity = 0; + +MySensor gw; +MyMessage dustMsg(CHILD_ID_DUST, V_DUST_LEVEL); + +void setup() +{ + gw.begin(); + + // Send the sketch version information to the gateway and Controller + gw.sendSketchInfo("Dust Sensor", "1.1"); + + // Register all sensors to gateway (they will be created as child devices) + gw.present(CHILD_ID_DUST, S_DUST); + +} + +void loop() +{ + uint16_t voMeasured = analogRead(DUST_SENSOR_ANALOG_PIN);// Get DUST value + + // 0 - 5V mapped to 0 - 1023 integer values + // recover voltage + calcVoltage = voMeasured * (5.0 / 1024.0); + + // linear eqaution taken from http://www.howmuchsnow.com/arduino/airquality/ + // Chris Nafis (c) 2012 + dustDensity = (0.17 * calcVoltage - 0.1)*1000; + + Serial.print("Raw Signal Value (0-1023): "); + Serial.print(voMeasured); + + Serial.print(" - Voltage: "); + Serial.print(calcVoltage); + + Serial.print(" - Dust Density: "); + Serial.println(dustDensity); // unit: ug/m3 + + if (ceil(dustDensity) != lastDUST) { + gw.send(dustMsg.set((int)ceil(dustDensity))); + lastDUST = ceil(dustDensity); + } + + gw.sleep(SLEEP_TIME); +} diff --git a/libraries/MySensors/examples/EnergyMeterPulseSensor/EnergyMeterPulseSensor.ino b/libraries/MySensors/examples/EnergyMeterPulseSensor/EnergyMeterPulseSensor.ino index 2fc8cf8..4049473 100644 --- a/libraries/MySensors/examples/EnergyMeterPulseSensor/EnergyMeterPulseSensor.ino +++ b/libraries/MySensors/examples/EnergyMeterPulseSensor/EnergyMeterPulseSensor.ino @@ -7,26 +7,19 @@ // sleepmode. So we cannot make this sensor sleep if we also want // to calculate/report watt-number. -#include #include -#include -#include -#include +#include #define DIGITAL_INPUT_SENSOR 3 // The digital input you attached your light sensor. (Only 2 and 3 generates interrupt!) #define PULSE_FACTOR 1000 // Nummber of blinks per KWH of your meeter #define SLEEP_MODE false // Watt-value can only be reported when sleep mode is false. #define MAX_WATT 10000 // Max watt value to report. This filetrs outliers. #define INTERRUPT DIGITAL_INPUT_SENSOR-2 // Usually the interrupt = pin -2 (on uno/nano anyway) -#define CHILD_ID 1 // Id of the sensor child -unsigned long SEND_FREQUENCY = 20; // Minimum time between send (in seconds). We don't wnat to spam the gateway. - -Sensor gw; -Sleep sleep; - -//double kwhPerBlink = 1.0/((double)PULSE_FACTOR); +#define CHILD_ID 1 // Id of the sensor child +unsigned long SEND_FREQUENCY = 20000; // Minimum time between send (in milliseconds). We don't wnat to spam the gateway. +MySensor gw; double ppwh = ((double)PULSE_FACTOR)/1000; // Pulses per watt hour - +boolean pcReceived = false; volatile unsigned long pulseCount = 0; volatile unsigned long lastBlink = 0; volatile unsigned long watt = 0; @@ -34,21 +27,24 @@ unsigned long oldPulseCount = 0; unsigned long oldWatt = 0; double oldKwh; unsigned long lastSend; +MyMessage wattMsg(CHILD_ID,V_WATT); +MyMessage kwhMsg(CHILD_ID,V_KWH); +MyMessage pcMsg(CHILD_ID,V_VAR1); + void setup() { - gw.begin(); + gw.begin(incomingMessage); // Send the sketch version information to the gateway and Controller gw.sendSketchInfo("Energy Meter", "1.0"); // Register this device as power sensor - gw.sendSensorPresentation(CHILD_ID, S_POWER); + gw.present(CHILD_ID, S_POWER); // Fetch last known pulse count value from gw - pulseCount = oldPulseCount = atol(gw.getStatus(CHILD_ID, V_VAR1)); - Serial.print("Last pulse count from gw:"); - Serial.println(pulseCount); + gw.request(CHILD_ID, V_VAR1); + attachInterrupt(INTERRUPT, onPulse, RISING); lastSend=millis(); } @@ -56,15 +52,17 @@ void setup() void loop() { - unsigned long now = millis(); + gw.process(); + unsigned long now = millis(); // Only send values at a maximum frequency or woken up from sleep - if (SLEEP_MODE || now - lastSend > 1000*SEND_FREQUENCY) { + bool sendTime = now - lastSend > SEND_FREQUENCY; + if (pcReceived && (SLEEP_MODE || sendTime)) { // New watt value has been calculated if (!SLEEP_MODE && watt != oldWatt) { // Check that we dont get unresonable large watt value. // could hapen when long wraps or false interrupt triggered if (watt<((unsigned long)MAX_WATT)) { - gw.sendVariable(CHILD_ID, V_WATT, watt); // Send watt value to gw + gw.send(wattMsg.set(watt)); // Send watt value to gw } Serial.print("Watt:"); Serial.println(watt); @@ -73,26 +71,31 @@ void loop() // Pulse cout has changed if (pulseCount != oldPulseCount) { - gw.sendVariable(CHILD_ID, V_VAR1, pulseCount); // Send kwh value to gw + gw.send(pcMsg.set(pulseCount)); // Send pulse count value to gw double kwh = ((double)pulseCount/((double)PULSE_FACTOR)); oldPulseCount = pulseCount; - //Serial.print("Pulse count:"); - //Serial.println(pulseCount); if (kwh != oldKwh) { - gw.sendVariable(CHILD_ID, V_KWH, kwh, 4); // Send kwh value to gw - //Serial.print("KWH:"); - //Serial.println(kwh); + gw.send(kwhMsg.set(kwh, 4)); // Send kwh value to gw oldKwh = kwh; } - } + } lastSend = now; + } else if (sendTime && !pcReceived) { + // No count received. Try requesting it again + gw.request(CHILD_ID, V_VAR1); } if (SLEEP_MODE) { - delay(300); //delay to allow serial to fully print before sleep - gw.powerDown(); - sleep.pwrDownMode(); //set sleep mode - sleep.sleepDelay(SEND_FREQUENCY * 1000); //sleep for: sleepTime + gw.sleep(SEND_FREQUENCY); + } +} + +void incomingMessage(const MyMessage &message) { + if (message.type==V_VAR1) { + pulseCount = oldPulseCount = message.getLong(); + Serial.print("Received last pulse count from gw:"); + Serial.println(pulseCount); + pcReceived = true; } } diff --git a/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino similarity index 75% rename from EthernetGateway/EthernetGateway.ino rename to libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index 75fa991..df3b935 100644 --- a/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -44,20 +44,16 @@ * Powering: both NRF24l01 radio and Ethernet(ENC28J60) uses 3.3V */ - - - #include -#include -#include -#include -#include -#include +#include +#include #include -#include -#include // Use this if you have attached a Ethernet ENC28J60 shields -//#include // Use this fo WizNET module and Arduino Ethernet Shield +// Use this if you have attached a Ethernet ENC28J60 shields +//#include + +// Use this fo WizNET module and Arduino Ethernet Shield +#include #define INCLUSION_MODE_TIME 1 // Number of minutes inclusion mode is enabled @@ -81,10 +77,10 @@ byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // DEAD BEEF FEED EthernetServer server = EthernetServer(IP_PORT); // No blink or button functionality. Use the vanilla constructor. -Gateway gw(RADIO_CE_PIN, RADIO_SPI_SS_PIN, INCLUSION_MODE_TIME); +MyGateway gw(RADIO_CE_PIN, RADIO_SPI_SS_PIN, INCLUSION_MODE_TIME); // Uncomment this constructor if you have leds and include button attached to your gateway -//Gateway gw(RADIO_CE_PIN, RADIO_SPI_SS_PIN, INCLUSION_MODE_TIME, INCLUSION_MODE_PIN, RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN); +//MyGateway gw(RADIO_CE_PIN, RADIO_SPI_SS_PIN, INCLUSION_MODE_TIME, INCLUSION_MODE_PIN, RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN); char inputString[MAX_RECEIVE_LENGTH] = ""; // A string to hold incoming commands from serial/ethernet interface @@ -102,17 +98,6 @@ void setup() // start listening for clients server.begin(); - - // C++ classes and interrupts really sucks. Need to attach interrupt - // outside thw Gateway class due to language shortcomings! Gah! - - if (gw.isLedMode()) { - // Add led timer interrupt - MsTimer2::set(300, ledTimersInterrupt); - MsTimer2::start(); - // Add interrupt for inclustion button to pin - PCintPort::attachInterrupt(INCLUSION_MODE_PIN, startInclusionInterrupt, RISING); - } } // This will be called when data should be written to ethernet @@ -121,24 +106,22 @@ void writeEthernet(char *writeBuffer) { } -void processEthernetMessages() +void loop() { - // if an incoming client connects, there will be - // bytes available to read via the client object - EthernetClient client = server.available(); + // if an incoming client connects, there will be + // bytes available to read via the client object + EthernetClient client = server.available(); - if (client) - { + if (client) { // if got 1 or more bytes - if (client.available()) - { + if (client.available()) { // read the bytes incoming from the client char inChar = client.read(); if (inputPos #include -#include -#include -#include +#include #include #define CHILD_ID_HUM 0 #define CHILD_ID_TEMP 1 #define HUMIDITY_SENSOR_DIGITAL_PIN 3 -unsigned long SLEEP_TIME = 30; // Sleep time between reads (in seconds) +unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) -Sensor gw; +MySensor gw; DHT dht; -Sleep sleep; float lastTemp; float lastHum; boolean metric = true; +MyMessage msgHum(CHILD_ID_HUM, V_HUM); +MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP); + void setup() { @@ -26,10 +25,10 @@ void setup() gw.sendSketchInfo("Humidity", "1.0"); // Register all sensors to gw (they will be created as child devices) - gw.sendSensorPresentation(CHILD_ID_HUM, S_HUM); - gw.sendSensorPresentation(CHILD_ID_TEMP, S_TEMP); + gw.present(CHILD_ID_HUM, S_HUM); + gw.present(CHILD_ID_TEMP, S_TEMP); - metric = gw.isMetricSystem(); + metric = gw.getConfig().isMetric; } void loop() @@ -44,9 +43,9 @@ void loop() if (!metric) { temperature = dht.toFahrenheit(temperature); } - gw.sendVariable(CHILD_ID_TEMP, V_TEMP, temperature, 1); - Serial.print("T: "); - Serial.println(temperature); + gw.send(msgTemp.set(temperature, 1)); + Serial.print("T: "); + Serial.println(temperature); } float humidity = dht.getHumidity(); @@ -54,18 +53,12 @@ void loop() Serial.println("Failed reading humidity from DHT"); } else if (humidity != lastHum) { lastHum = humidity; - gw.sendVariable(CHILD_ID_HUM, V_HUM, humidity, 1); + gw.send(msgHum.set(humidity, 1)); Serial.print("H: "); Serial.println(humidity); } - // Power down the radio. Note that the radio will get powered back up - // on the next write() call. - delay(1000); //delay to allow serial to fully print before sleep - gw.powerDown(); - sleep.pwrDownMode(); //set sleep mode - sleep.sleepDelay(SLEEP_TIME * 1000); //sleep for: sleepTime + gw.sleep(SLEEP_TIME); //sleep a bit } - diff --git a/libraries/MySensors/examples/IrSensor/IrSensor.ino b/libraries/MySensors/examples/IrSensor/IrSensor.ino index bb1ea65..e954fcd 100644 --- a/libraries/MySensors/examples/IrSensor/IrSensor.ino +++ b/libraries/MySensors/examples/IrSensor/IrSensor.ino @@ -5,10 +5,8 @@ // When binary light on is clicked - sketch will send volume up ir command // When binary light off is clicked - sketch will send volume down ir command -#include +#include #include -#include -#include #include int RECV_PIN = 8; @@ -20,39 +18,26 @@ IRrecv irrecv(RECV_PIN); IRdecode decoder; //decode_results results; unsigned int Buffer[RAWBUF]; - -Sensor gw; +MySensor gw; +MyMessage msg(CHILD_1, V_VAR1); void setup() { irrecv.enableIRIn(); // Start the ir receiver decoder.UseExtnBuf(Buffer); - gw.begin(); + gw.begin(incomingMessage); // Send the sketch version information to the gateway and Controller gw.sendSketchInfo("IR Sensor", "1.0"); // Register a sensors to gw. Use binary light for test purposes. - gw.sendSensorPresentation(CHILD_1, S_LIGHT); + gw.present(CHILD_1, S_LIGHT); } void loop() { - if (gw.messageAvailable()) { - message_s message = gw.getMessage(); - - int incomingRelayStatus = atoi(message.data); - if (incomingRelayStatus == 1) { - irsend.send(NEC, 0x1EE17887, 32); // Vol up yamaha ysp-900 - } else { - irsend.send(NEC, 0x1EE1F807, 32); // Vol down yamaha ysp-900 - } - // Start receiving ir again... - irrecv.enableIRIn(); - } - - + gw.process(); if (irrecv.GetResults(&decoder)) { irrecv.resume(); decoder.decode(); @@ -61,11 +46,26 @@ void loop() char buffer[10]; sprintf(buffer, "%08lx", decoder.value); // Send ir result to gw - gw.sendVariable(CHILD_1, V_VAR1, buffer); + gw.send(msg.set(buffer)); } } + +void incomingMessage(const MyMessage &message) { + // We only expect one type of message from controller. But we better check anyway. + if (message.type==V_LIGHT) { + int incomingRelayStatus = message.getInt(); + if (incomingRelayStatus == 1) { + irsend.send(NEC, 0x1EE17887, 32); // Vol up yamaha ysp-900 + } else { + irsend.send(NEC, 0x1EE1F807, 32); // Vol down yamaha ysp-900 + } + // Start receiving ir again... + irrecv.enableIRIn(); + } +} + // Dumps out the decode_results structure. // Call this after IRrecv::decode() // void * to work around compiler issue diff --git a/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino b/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino index c995316..441c65e 100644 --- a/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino +++ b/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino @@ -16,23 +16,19 @@ */ - -#include #include -#include -#include -#include +#include #include #include #define CHILD_ID_LIGHT 0 #define LIGHT_SENSOR_ANALOG_PIN 0 -unsigned long SLEEP_TIME = 30; // Sleep time between reads (in seconds) +unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) -BH1750 lightSensor; -Sensor gw; -Sleep sleep; -int lastlux; +BH1750 lightSensor; +MySensor gw; +MyMessage msg(CHILD_ID_LIGHT, V_LIGHT_LEVEL); +uint16_t lastlux; void setup() { @@ -42,7 +38,7 @@ void setup() gw.sendSketchInfo("Light Lux Sensor", "1.0"); // Register all sensors to gateway (they will be created as child devices) - gw.sendSensorPresentation(CHILD_ID_LIGHT, S_LIGHT_LEVEL); + gw.present(CHILD_ID_LIGHT, S_LIGHT_LEVEL); lightSensor.begin(); } @@ -52,14 +48,9 @@ void loop() uint16_t lux = lightSensor.readLightLevel();// Get Lux value Serial.println(lux); if (lux != lastlux) { - gw.sendVariable(CHILD_ID_LIGHT, V_LIGHT_LEVEL, lux); + gw.send(msg.set(lux)); lastlux = lux; } - // Power down the radio. Note that the radio will get powered back up - // on the next write() call. - delay(1000); //delay to allow serial to fully print before sleep - gw.powerDown(); - sleep.pwrDownMode(); //set sleep mode - sleep.sleepDelay(SLEEP_TIME * 1000); //sleep for: sleepTime + gw.sleep(SLEEP_TIME); } diff --git a/libraries/MySensors/examples/LightSensor/LightSensor.ino b/libraries/MySensors/examples/LightSensor/LightSensor.ino index 0b5de6f..534f8bb 100644 --- a/libraries/MySensors/examples/LightSensor/LightSensor.ino +++ b/libraries/MySensors/examples/LightSensor/LightSensor.ino @@ -1,17 +1,14 @@ -#include #include -#include -#include -#include +#include #define CHILD_ID_LIGHT 0 #define LIGHT_SENSOR_ANALOG_PIN 0 -unsigned long SLEEP_TIME = 30; // Sleep time between reads (in seconds) +unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) -Sensor gw; +MySensor gw; +MyMessage msg(CHILD_ID_LIGHT, V_LIGHT_LEVEL); int lastLightLevel; -Sleep sleep; void setup() { @@ -21,7 +18,7 @@ void setup() gw.sendSketchInfo("Light Sensor", "1.0"); // Register all sensors to gateway (they will be created as child devices) - gw.sendSensorPresentation(CHILD_ID_LIGHT, S_LIGHT_LEVEL); + gw.present(CHILD_ID_LIGHT, S_LIGHT_LEVEL); } void loop() @@ -29,16 +26,10 @@ void loop() int lightLevel = (1023-analogRead(LIGHT_SENSOR_ANALOG_PIN))/10.23; Serial.println(lightLevel); if (lightLevel != lastLightLevel) { - gw.sendVariable(CHILD_ID_LIGHT, V_LIGHT_LEVEL, lightLevel); + gw.send(msg.set(lightLevel)); lastLightLevel = lightLevel; } - - // Power down the radio. Note that the radio will get powered back up - // on the next write() call. - delay(1000); //delay to allow serial to fully print before sleep - gw.powerDown(); - sleep.pwrDownMode(); //set sleep mode - sleep.sleepDelay(SLEEP_TIME * 1000); //sleep for: sleepTime + gw.sleep(SLEEP_TIME); } diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino new file mode 100644 index 0000000..bbd44dd --- /dev/null +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -0,0 +1,129 @@ +/* MyMQTT Broker Gateway 0.1b + +Created by Daniel Wiegert +Based on MySensors Ethernet Gateway by Henrik Ekblad +http://www.mysensors.org + +Requires MySensors lib 1.4b + +* Change below; TCP_IP, TCP_PORT, TCP_MAC +This will listen on your selected TCP_IP:TCP_PORT below, Please change TCP_MAC your liking also. +*1 -> NOTE: Keep first byte at x2, x6, xA or xE (replace x with any hex value) for using Local Ranges. + +*2 You can use standard pin set-up as MySensors recommends or if you own a IBOARD you may change + the radio-pins below if you hardware mod your iBoard. see [URL BELOW] for more details. + http://forum.mysensors.org/topic/224/iboard-cheap-single-board-ethernet-arduino-with-radio/5 + +* Don't forget to look at the definitions in libraries\MySensors\MyMQTT.h! + + define TCPDUMP and connect serial interface if you have problems, please write on + http://forum.mysensors.org/ and explain your problem, include serial output. Don't forget to + turn on DEBUG in libraries\MySensors\MyConfig.h also. + + MQTT_FIRST_SENSORID is for 'DHCP' server in MyMQTT. You may limit the ID's with FIRST and LAST definition. + If you want your manually configured below 20 set MQTT_FIRST_SENSORID to 20. + To disable: set MQTT_FIRST_SENSORID to 255. + + MQTT_BROKER_PREFIX is the leading prefix for your nodes. This can be only one char if like. + + MQTT_SEND_SUBSCRIPTION is if you want the MyMQTT to send a empty payload message to your nodes. + This can be useful if you want to send latest state back to the MQTT client. Just check if incoming + message has any length or not. + Example: if (msg.type==V_LIGHT && strlen(msg.getString())>0) otherwise the code might do strange things. + +* Address-layout is : [MQTT_BROKER_PREFIX]/[NodeID]/[SensorID]/V_[SensorType] + NodeID and SensorID is uint8 (0-255) number. + Last segment is translation of the sensor type, look inside MyMQTT.cpp for the definitions. + User can change this to their needs. We have also left some space for custom types. + +Special: (sensor 255 reserved for special commands) +You can receive a node sketch name with MyMQTT/20/255/V_Sketch_name (or version with _version) + +To-do: +Special commands : clear or set EEPROM Values, Send REBOOT and Receive reboot for MyMQTT itself. +Be able to send ACK so client returns the data being sent. +... Please come with ideas! +What to do with publish messages. + +Test in more MQTT clients, So far tested in openhab and MyMQTT for Android (Not my creation) +- http://www.openhab.org/ +- https://play.google.com/store/apps/details?id=at.tripwire.mqtt.client&hl=en +... Please notify me if you use this broker with other software. + + +* How to set-up Openhab and MQTTGateway: +http://forum.mysensors.org/topic/303/mqtt-broker-gateway + +*/ + +#include +#include +#include +#include + + +// * Use this for IBOARD modded to use standard MISO/MOSI/SCK, see note *1 above! +/* +#define RADIO_CE_PIN 3 // radio chip enable +#define RADIO_SPI_SS_PIN 8 // radio SPI serial select +#define RADIO_ERROR_LED_PIN A2 // Error led pin +#define RADIO_RX_LED_PIN A1 // Receive led pin +#define RADIO_TX_LED_PIN A0 // the PCB, on board LED*/ + +// * Use this for default configured pro mini / nano etc : +///* +#define RADIO_CE_PIN 5 // radio chip enable +#define RADIO_SPI_SS_PIN 6 // radio SPI serial select +#define RADIO_ERROR_LED_PIN 7 // Error led pin +#define RADIO_RX_LED_PIN 8 // Receive led pin +#define RADIO_TX_LED_PIN 9 // the PCB, on board LED*/ + +#define TCP_PORT 1883 // Set your MQTT Broker Listening port. +IPAddress TCP_IP ( 192, 168, 0, 234 ); // Configure your static ip-address here +uint8_t TCP_MAC[] = { 0x02, 0xDE, 0xAD, 0x00, 0x00, 0x42 }; // Mac-address - You should change this! see note *2 above! + +////////////////////////////////////////////////////////////////// + +EthernetServer server = EthernetServer(TCP_PORT); +MyMQTT gw(RADIO_CE_PIN, RADIO_SPI_SS_PIN); + +void processEthernetMessages() { + char inputString[MQTT_MAX_PACKET_SIZE] = ""; + uint8_t inputSize = 0; + EthernetClient client = server.available(); + if (client) { + while (client.available()) { + char inChar = client.read(); + inputString[inputSize] = inChar; + inputSize++; + } +#ifdef TCPDUMP + Serial.print("<<"); + char buf[4]; + for (uint8_t a=0; a>"); + char buf[4]; + for (uint8_t a=0; a<*writeSize; a++) { sprintf(buf,"%02X ",(uint8_t)writeBuffer[a]); Serial.print(buf); } Serial.println(""); +#endif + server.write((const uint8_t *)writeBuffer, *writeSize); +} + + +int main(void) { + init(); + Ethernet.begin(TCP_MAC, TCP_IP); + delay(1000); // Wait for Ethernet to get configured. + gw.begin(RF24_PA_LEVEL_GW, RF24_CHANNEL, RF24_DATARATE, writeEthernet, RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN); + server.begin(); + while (1) { + processEthernetMessages(); + gw.processRadioMessage(); + } +} diff --git a/libraries/MySensors/examples/MotionSensor/MotionSensor.ino b/libraries/MySensors/examples/MotionSensor/MotionSensor.ino index 2241c9c..db8373f 100644 --- a/libraries/MySensors/examples/MotionSensor/MotionSensor.ino +++ b/libraries/MySensors/examples/MotionSensor/MotionSensor.ino @@ -1,15 +1,14 @@ -#include +#include #include -#include -#include -#include +unsigned long SLEEP_TIME = 120000; // Sleep time between reports (in milliseconds) #define DIGITAL_INPUT_SENSOR 3 // The digital input you attached your motion sensor. (Only 2 and 3 generates interrupt!) #define INTERRUPT DIGITAL_INPUT_SENSOR-2 // Usually the interrupt = pin -2 (on uno/nano anyway) -#define CHILD_ID 0 // Id of the sensor child +#define CHILD_ID 1 // Id of the sensor child -Sensor gw; -Sleep sleep; +MySensor gw; +// Initialize motion message +MyMessage msg(CHILD_ID, V_TRIPPED); void setup() { @@ -20,7 +19,8 @@ void setup() pinMode(DIGITAL_INPUT_SENSOR, INPUT); // sets the motion sensor digital pin as input // Register all sensors to gw (they will be created as child devices) - gw.sendSensorPresentation(CHILD_ID, S_MOTION); + gw.present(CHILD_ID, S_MOTION); + } void loop() @@ -29,14 +29,10 @@ void loop() boolean tripped = digitalRead(DIGITAL_INPUT_SENSOR) == HIGH; Serial.println(tripped); - gw.sendVariable(CHILD_ID, V_TRIPPED, tripped?"1":"0"); // Send tripped value to gw + gw.send(msg.set(tripped?"1":"0")); // Send tripped value to gw - // Power down the radio. Note that the radio will get powered back up - // on the next write() call. - delay(200); //delay to allow serial to fully print before sleep - gw.powerDown(); - sleep.pwrDownMode(); //set sleep mode - sleep.sleepInterrupt(INTERRUPT,CHANGE); + // Sleep until interrupt comes in on motion sensor. Send update every two minute. + gw.sleep(INTERRUPT,CHANGE, SLEEP_TIME); } diff --git a/libraries/MySensors/examples/PressureSensor/PressureSensor.ino b/libraries/MySensors/examples/PressureSensor/PressureSensor.ino index 603f402..fafe08c 100644 --- a/libraries/MySensors/examples/PressureSensor/PressureSensor.ino +++ b/libraries/MySensors/examples/PressureSensor/PressureSensor.ino @@ -1,21 +1,19 @@ -#include #include -#include -#include -#include +#include #include #include -#define LIGHT_SENSOR_ANALOG_PIN 0 -unsigned long SLEEP_TIME = 60; // Sleep time between reads (in seconds) +#define BARO_CHILD 0 +#define TEMP_CHILD 1 + +unsigned long SLEEP_TIME = 60000; // Sleep time between reads (in seconds) Adafruit_BMP085 bmp = Adafruit_BMP085(); // Digital Pressure Sensor -Sensor gw; +MySensor gw; float lastPressure = -1; float lastTemp = -1; int lastForecast = -1; -Sleep sleep; char *weather[] = {"stable","sunny","cloudy","unstable","thunderstorm","unknown"}; int minutes; float pressureSamples[180]; @@ -24,6 +22,9 @@ bool firstRound = true; float pressureAvg[7]; float dP_dt; boolean metric; +MyMessage tempMsg(TEMP_CHILD, V_TEMP); +MyMessage pressureMsg(BARO_CHILD, V_PRESSURE); +MyMessage forecastMsg(BARO_CHILD, V_FORECAST); void setup() { gw.begin(); @@ -37,14 +38,13 @@ void setup() { } // Register sensors to gw (they will be created as child devices) - gw.sendSensorPresentation(0, S_BARO); - gw.sendSensorPresentation(1, S_TEMP); - metric = gw.isMetricSystem(); + gw.present(BARO_CHILD, S_BARO); + gw.present(TEMP_CHILD, S_TEMP); + metric = gw.getConfig().isMetric; } - void loop() { - float pressure = bmp.readPressure(); + float pressure = bmp.readPressure()/100; float temperature = bmp.readTemperature(); if (!metric) { @@ -64,17 +64,17 @@ void loop() { if (temperature != lastTemp) { - gw.sendVariable(1, V_TEMP, temperature,1); + gw.send(tempMsg.set(temperature,1)); lastTemp = temperature; } if (pressure != lastPressure) { - gw.sendVariable(0, V_PRESSURE, pressure, 0); + gw.send(pressureMsg.set(pressure, 0)); lastPressure = pressure; } if (forecast != lastForecast) { - gw.sendVariable(0, V_FORECAST, weather[forecast]); + gw.send(forecastMsg.set(weather[forecast])); lastForecast = forecast; } @@ -89,12 +89,7 @@ void loop() { 5 = "Unknown (More Time needed) */ - // Power down the radio. Note that the radio will get powered back up - // on the next write() call. - delay(1000); //delay to allow serial to fully print before sleep - gw.powerDown(); - sleep.pwrDownMode(); //set sleep mode - sleep.sleepDelay(SLEEP_TIME * 1000); // sleep to conserve power + gw.sleep(SLEEP_TIME); } int sample(float pressure) { diff --git a/libraries/MySensors/examples/RFIDLockSensor/RFIDLockSensor.ino b/libraries/MySensors/examples/RFIDLockSensor/RFIDLockSensor.ino new file mode 100644 index 0000000..ecb9756 --- /dev/null +++ b/libraries/MySensors/examples/RFIDLockSensor/RFIDLockSensor.ino @@ -0,0 +1,161 @@ +/* + RFID Lock sensor/actuator + + Henrik Ekblad + + Use RFID tag to lock/unlock a door or trigger a scene on your controller. + This example sketch allows you to add an optional relay or solenoid + which can be activated/opened by RFID or controller. + + Use the I2C wiring option for your RFID module and connect to the following Arduino pins. + + RFID Arduino + ----- ------- + GND -> GND + VCC -> +5V + SCL -> A5 + SDA -> A4 + + Use normal wiring for NRF24L01 radio + + Attach a optional relay or solonoid lock to pin 4 + +*/ + +#include +#include +#include +#include +#include + + +// Add your valid rfid keys here. To find you your key just run sketch; hold your new RFID tag in fron ot the reader; +// and copy the key from serial output of this sketch. +const uint8_t maxKeyLength = 7; +uint8_t validKeys[][maxKeyLength] = { + { 0xB3, 0xC6, 0xD9, 0x80, 0x00, 0x00, 0x00 }, + { 0, 0, 0, 0, 0, 0, 0 }, // ADD YOUR KEYS HERE! + { 0, 0, 0, 0, 0, 0, 0 }}; +int keyCount = sizeof validKeys / maxKeyLength; + + +#define CHILD_ID 99 // Id of the sensor child + +/*Pin definitions*/ +const int lockPin = 4; // (Digital 4) The pin that activates the relay/solenoid lock. + +bool lockStatus; +MySensor gw; +MyMessage lockMsg(CHILD_ID, V_LOCK_STATUS); +PN532_I2C pn532i2c(Wire); +PN532 nfc(pn532i2c); + +void setup() { + + pinMode(lockPin, OUTPUT); + + nfc.begin(); + uint32_t versiondata = nfc.getFirmwareVersion(); + if (! versiondata) { + Serial.print("Couldn't find PN53x board"); + while (1); // halt + } + Serial.print("Found NFC chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX); + Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC); + Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC); + // Set the max number of retry attempts to read from a card + // This prevents us from waiting forever for a card, which is + // the default behaviour of the PN532. + nfc.setPassiveActivationRetries(0x3); + + // configure board to read RFID tags + nfc.SAMConfig(); + + // Init mysensors library + gw.begin(incomingMessage); + + gw.sendSketchInfo("RFID Lock", "1.0"); + gw.present(CHILD_ID, S_LOCK); + + lockStatus = gw.loadState(0); // Read last lock status from eeprom + setLockState(lockStatus, true); // Now set the last known state and send it to controller +} + +void loop() { + gw.process(); // Process incomming messages + + boolean success; + uint8_t key[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID + uint8_t currentKeyLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type) + + + // Wait for an ISO14443A type cards (Mifare, etc.). When one is found + // 'uid' will be populated with the UID, and uidLength will indicate + // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight) + success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &key[0], ¤tKeyLength); + + if (success) { + Serial.print("Found tag id: "); + for (uint8_t i=0; i < currentKeyLength; i++) + { + if (i>0) Serial.print(","); + Serial.print("0x");Serial.print(key[i], HEX); + } + for (uint8_t i=currentKeyLength; i < maxKeyLength; i++) + { + Serial.print(",0x00"); + } + + + Serial.println(""); + + boolean valid = false; + // Compare this key to the valid once registered here in sketch + for (int i=0;i +#include #include -#include -#include #define RELAY_1 3 // Arduino Digital I/O pin number for first relay (second on pin+1 etc) -#define NUMBER_OF_RELAYS 1 -#define RELAY_ON 0 -#define RELAY_OFF 1 +#define NUMBER_OF_RELAYS 1 // Total number of attached relays +#define RELAY_ON 1 // GPIO value to write to turn on attached relay +#define RELAY_OFF 0 // GPIO value to write to turn off attached relay -Sensor gw; +MySensor gw; void setup() -{ - gw.begin(); - +{ + // Initialize library and add callback for incoming messages + gw.begin(incomingMessage, AUTO, true); // Send the sketch version information to the gateway and Controller gw.sendSketchInfo("Relay", "1.0"); - // Register all sensors to gw (they will be created as child devices) - for (int i=0; i +#include #include -#include -#include +#include #define RELAY_PIN 4 // Arduino Digital I/O pin number for relay -#define BUTTON_PIN 3 // Arduino Digital I/O pin number for button (with 10k pulldown) +#define BUTTON_PIN 3 // Arduino Digital I/O pin number for button #define CHILD_ID 1 // Id of the sensor child -#define RELAY_ON 0 -#define RELAY_OFF 1 +#define RELAY_ON 1 +#define RELAY_OFF 0 -int buttVal; -int previousVal; -int state; -int switched = 0; -long pressTime = 0; // the last time the button pin was pressed -long debounce = 200; // the debounce time, increase if the output flickers - -Relay gw; +Bounce debouncer = Bounce(); +int oldValue=0; +bool state; +MySensor gw; +MyMessage msg(CHILD_ID,V_LIGHT); void setup() { - gw.begin(); + gw.begin(incomingMessage, AUTO, true); // Send the sketch version information to the gateway and Controller gw.sendSketchInfo("Relay & Button", "1.0"); - // Set buttonPin as Input - pinMode(BUTTON_PIN, INPUT); - buttVal = digitalRead(BUTTON_PIN); //read initial state + // Setup the button + pinMode(BUTTON_PIN,INPUT); + // Activate internal pull-up + digitalWrite(BUTTON_PIN,HIGH); + + // After setting up the button, setup debouncer + debouncer.attach(BUTTON_PIN); + debouncer.interval(5); // Register all sensors to gw (they will be created as child devices) - gw.sendSensorPresentation(CHILD_ID, S_LIGHT); + gw.present(CHILD_ID, S_LIGHT); // Make sure relays are off when starting up digitalWrite(RELAY_PIN, RELAY_OFF); // Then set relay pins in output mode pinMode(RELAY_PIN, OUTPUT); - // Request/wait for relay status - gw.getStatus(CHILD_ID, V_LIGHT); - setRelayStatus(gw.getMessage()); // Wait here until status message arrive from gw - + // Set relay to last known state (using eeprom storage) + state = gw.loadState(CHILD_ID); + digitalWrite(RELAY_PIN, state?RELAY_ON:RELAY_OFF); } @@ -53,40 +54,34 @@ void setup() */ void loop() { - if (gw.messageAvailable()) { - // ot new messsage from gw - message_s message = gw.getMessage(); - setRelayStatus(message); + gw.process(); + debouncer.update(); + // Get the update value + int value = debouncer.read(); + if (value != oldValue && value==0) { + gw.send(msg.set(state?false:true), true); // Send new state and request ack back } - - buttVal = digitalRead(BUTTON_PIN); // read input value and store it in val - - if (buttVal == HIGH && previousVal == LOW) { - // Start counter from when button was pressed - pressTime = millis(); - switched = 0; - } - - if (buttVal == HIGH && switched == 0 && millis() - pressTime > debounce) { - // Switch state if button pressed more than 200 msec - state = state==1?0:1; - gw.sendVariable(CHILD_ID, V_LIGHT, state); // We will receive an ack message - switched = 1; // No more switches until button is released - } - previousVal = buttVal; + oldValue = value; } - - +void incomingMessage(const MyMessage &message) { + // We only expect one type of message from controller. But we better check anyway. + if (message.isAck()) { + Serial.println("This is an ack from gateway"); + } -void setRelayStatus(message_s message) { - if (message.header.type==V_LIGHT) { // This could be M_ACK_VARIABLE or M_SET_VARIABLE - state = atoi(message.data); + if (message.type == V_LIGHT && strlen(msg.getString()) != 0) { // Change relay state - digitalWrite(RELAY_PIN, state==1?RELAY_ON:RELAY_OFF); + state = message.getBool(); + digitalWrite(RELAY_PIN, state?RELAY_ON:RELAY_OFF); + // Store state in eeprom + gw.saveState(CHILD_ID, state); + // Write some debug info - Serial.print(message.header.messageType == M_ACK_VARIABLE ? "Button":"Gateway"); - Serial.print(" change. New state: "); - Serial.println(state == 1 ?"on":"off" ); - } + Serial.print("Incoming change for sensor:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println(message.getBool()); + } } + diff --git a/libraries/MySensors/examples/RelayingNode/RelayingNode.ino b/libraries/MySensors/examples/RelayingNode/RelayingNode.ino deleted file mode 100644 index 40864f7..0000000 --- a/libraries/MySensors/examples/RelayingNode/RelayingNode.ino +++ /dev/null @@ -1,30 +0,0 @@ -// Example sketch showing how to create a node thay relays messages -// from nodes far from gateway back to gateway. -// Important here is that node uses Relay-class and calls -// gw.messageAvailable() frequently. This sketch should not -// sleep. - -#include -#include -#include -#include - -Relay gw; - -void setup() -{ - gw.begin(); - - //Send the sensor node sketch version information to the gateway - gw.sendSketchInfo("Relaying Node", "1.0"); -} - -void loop() -{ - // By calling this regularely you route messages in the background - if (gw.messageAvailable()) { - - // Handleincoming message for this node here... - } -} - diff --git a/libraries/MySensors/examples/RepeaterNode/RepeaterNode.ino b/libraries/MySensors/examples/RepeaterNode/RepeaterNode.ino new file mode 100644 index 0000000..8ada2de --- /dev/null +++ b/libraries/MySensors/examples/RepeaterNode/RepeaterNode.ino @@ -0,0 +1,25 @@ +// Example sketch showing how to create a node thay repeates messages +// from nodes far from gateway back to gateway. +// It is important that nodes that has enabled repeater mode calls +// gw.preocess() frequently. This node should never sleep. + +#include +#include + +MySensor gw; + +void setup() +{ + // The third argument enables repeater mode. + gw.begin(NULL, AUTO, true); + + //Send the sensor node sketch version information to the gateway + gw.sendSketchInfo("Repeater Node", "1.0"); +} + +void loop() +{ + // By calling process() you route messages in the background + gw.process(); +} + diff --git a/libraries/MySensors/examples/SecretKnockSensor/SecretKnockSensor.ino b/libraries/MySensors/examples/SecretKnockSensor/SecretKnockSensor.ino new file mode 100644 index 0000000..9f5f00f --- /dev/null +++ b/libraries/MySensors/examples/SecretKnockSensor/SecretKnockSensor.ino @@ -0,0 +1,349 @@ +/* Secret Knock Sensor + + See original instructions here (note: The MySensors adopted code might differ in wiring. The instructions below is correct): + https://learn.adafruit.com/secret-knock-activated-drawer-lock/ + Version 13.10.31 Built with Arduino IDE 1.0.5 + + By Steve Hoefer http://grathio.com + Adapted to MySensors by Henrik Ekblad + + Licensed under Creative Commons Attribution-Noncommercial-Share Alike 3.0 + http://creativecommons.org/licenses/by-nc-sa/3.0/us/ + (In short: Do what you want, as long as you credit me, don't relicense it, and don't sell it or use it in anything you sell without contacting me.) + + ------Wiring------ + Pin 0: Program button used for recording a new Knock (connect Pin0 -> button -> GND) + Pin 1: Optional: Connect LED here (remember resisor in series) + Pin 2: Optional: Piezo element (for beeps). + Pin 5: A sound sensor (digital output) for sensing knocks. See MySensors purchase guide. I used this: http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=2&pub=5575069610&toolid=10001&campid=5337433187&customid=&icep_item=200941260251&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg + Pin 4: Connects to either 1. Relay which open door or lock or + 2. transistor that opens a solenoid lock when HIGH (see adafruit guide for this option). + + + Connect radio according as usual(you can skip IRQ pin) + http://www.mysensors.org/build/connect_radio +*/ + +#include +#include + + +#define CHILD_ID 99 // Id of the sensor child + +const byte eepromValid = 121; // If the first byte in eeprom is this then the data is valid. + +/*Pin definitions*/ +const int programButton = 0; // (Digital 0) Record A New Knock button. +const int ledPin = 1; // (Digital 1) The LED pin (if any) +const int knockSensor = 5; // (Digital 5) for using the microphone digital output (tune knob to register knock) +const int audioOut = 2; // (Digital 2) for using the peizo as an output device. (Thing that goes beep.) +const int lockPin = 4; // (Digital 4) The pin that activates the relay/solenoid lock. + +/*Tuning constants. Changing the values below changes the behavior of the device.*/ +int threshold = 3; // Minimum signal from the piezo to register as a knock. Higher = less sensitive. Typical values 1 - 10 +const int rejectValue = 25; // If an individual knock is off by this percentage of a knock we don't unlock. Typical values 10-30 +const int averageRejectValue = 15; // If the average timing of all the knocks is off by this percent we don't unlock. Typical values 5-20 +const int knockFadeTime = 150; // Milliseconds we allow a knock to fade before we listen for another one. (Debounce timer.) +const int lockOperateTime = 2500; // Milliseconds that we operate the lock solenoid latch before releasing it. +const int maximumKnocks = 20; // Maximum number of knocks to listen for. +const int knockComplete = 1200; // Longest time to wait for a knock before we assume that it's finished. (milliseconds) + +byte secretCode[maximumKnocks] = {50, 25, 25, 50, 100, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Initial setup: "Shave and a Hair Cut, two bits." +int knockReadings[maximumKnocks]; // When someone knocks this array fills with the delays between knocks. +int knockSensorValue = 0; // Last reading of the knock sensor. +boolean programModeActive = false; // True if we're trying to program a new knock. + +bool lockStatus; +MySensor gw; +MyMessage lockMsg(CHILD_ID, V_LOCK_STATUS); + + +void setup() { + + pinMode(ledPin, OUTPUT); + pinMode(knockSensor, INPUT); + pinMode(lockPin, OUTPUT); + pinMode(programButton, INPUT); + digitalWrite(programButton, HIGH); // Enable internal pull up + + gw.begin(incomingMessage); + + gw.sendSketchInfo("Secret Knock", "1.0"); + gw.present(CHILD_ID, S_LOCK); + + readSecretKnock(); // Load the secret knock (if any) from EEPROM. + + digitalWrite(lockPin, HIGH); // Unlock the door for a bit when we power up. For system check and to allow a way in if the key is forgotten + delay(500); // Wait a short time + + lockStatus = gw.loadState(0); // Read last lock status from eeprom + setLockState(lockStatus, true); // Now set the last known state and send it to controller + + delay(500); // This delay is here because the solenoid lock returning to place can otherwise trigger and inadvertent knock. +} + +void loop() { + gw.process(); // Process incomming messages + // Listen for any knock at all. + knockSensorValue = digitalRead(knockSensor); + if (digitalRead(programButton) == LOW){ // is the program button pressed? + delay(100); // Cheap debounce. + if (digitalRead(programButton) == LOW){ + if (programModeActive == false){ // If we're not in programming mode, turn it on. + programModeActive = true; // Remember we're in programming mode. + digitalWrite(ledPin, HIGH); // Turn on the red light too so the user knows we're programming. + chirp(500, 1500); // And play a tone in case the user can't see the LED. + chirp(500, 1000); + } else { // If we are in programing mode, turn it off. + programModeActive = false; + digitalWrite(ledPin, LOW); + chirp(500, 1000); // Turn off the programming LED and play a sad note. + chirp(500, 1500); + delay(500); + } + while (digitalRead(programButton) == LOW){ + delay(10); // Hang around until the button is released. + } + } + delay(250); // Another cheap debounce. Longer because releasing the button can sometimes be sensed as a knock. + } + + + if (knockSensorValue == 0) { + if (programModeActive == true){ // Blink the LED when we sense a knock. + digitalWrite(ledPin, LOW); + } else { + digitalWrite(ledPin, HIGH); + } + knockDelay(); + if (programModeActive == true){ // Un-blink the LED. + digitalWrite(ledPin, HIGH); + } else { + digitalWrite(ledPin, LOW); + } + listenToSecretKnock(); // We have our first knock. Go and see what other knocks are in store... + } + +} + +// Records the timing of knocks. +void listenToSecretKnock(){ + int i = 0; + // First reset the listening array. + for (i=0; i < maximumKnocks; i++){ + knockReadings[i] = 0; + } + + int currentKnockNumber = 0; // Position counter for the array. + int startTime = millis(); // Reference for when this knock started. + int now = millis(); + + do { // Listen for the next knock or wait for it to timeout. + knockSensorValue = digitalRead(knockSensor); + + if (knockSensorValue == 0){ // Here's another knock. Save the time between knocks. + Serial.println("knock"); + + now=millis(); + knockReadings[currentKnockNumber] = now - startTime; + currentKnockNumber ++; + startTime = now; + + if (programModeActive==true){ // Blink the LED when we sense a knock. + digitalWrite(ledPin, LOW); + } else { + digitalWrite(ledPin, HIGH); + } + knockDelay(); + if (programModeActive == true){ // Un-blink the LED. + digitalWrite(ledPin, HIGH); + } else { + digitalWrite(ledPin, LOW); + } + } + + now = millis(); + + // Stop listening if there are too many knocks or there is too much time between knocks. + } while ((now-startTime < knockComplete) && (currentKnockNumber < maximumKnocks)); + Serial.println("end"); + + //we've got our knock recorded, lets see if it's valid + if (programModeActive == false){ // Only do this if we're not recording a new knock. + if (validateKnock() == true){ + // Lock/unlock door + chirp(500, 1500); // And play a tone in case the user can't see the LED. + chirp(500, 1000); + setLockState(!lockStatus, true); + } else { + Serial.println("fail unlock"); + + // knock is invalid. Blink the LED as a warning to others. + for (i=0; i < 4; i++){ + digitalWrite(ledPin, HIGH); + delay(50); + digitalWrite(ledPin, LOW); + delay(50); + } + } + } else { // If we're in programming mode we still validate the lock because it makes some numbers we need, we just don't do anything with the return. + validateKnock(); + } +} + + +// Unlocks the door. +void setLockState(bool state, bool send){ + if (state) + Serial.println("open lock"); + else + Serial.println("close lock"); + if (send) + gw.send(lockMsg.set(state)); + + digitalWrite(ledPin, state); + digitalWrite(lockPin, state); + gw.saveState(0,state); + lockStatus = state; + delay(500); // This delay is here because releasing the latch can cause a vibration that will be sensed as a knock. +} + +// Checks to see if our knock matches the secret. +// Returns true if it's a good knock, false if it's not. +boolean validateKnock(){ + int i = 0; + + int currentKnockCount = 0; + int secretKnockCount = 0; + int maxKnockInterval = 0; // We use this later to normalize the times. + + for (i=0;i 0){ + currentKnockCount++; + } + if (secretCode[i] > 0){ + secretKnockCount++; + } + + if (knockReadings[i] > maxKnockInterval){ // Collect normalization data while we're looping. + maxKnockInterval = knockReadings[i]; + } + } + + // If we're recording a new knock, save the info and get out of here. + if (programModeActive == true){ + for (i=0; i < maximumKnocks; i++){ // Normalize the time between knocks. (the longest time = 100) + secretCode[i] = map(knockReadings[i], 0, maxKnockInterval, 0, 100); + } + saveSecretKnock(); // save the result to EEPROM + programModeActive = false; + playbackKnock(maxKnockInterval); + return false; + } + + if (currentKnockCount != secretKnockCount){ // Easiest check first. If the number of knocks is wrong, don't unlock. + return false; + } + + /* Now we compare the relative intervals of our knocks, not the absolute time between them. + (ie: if you do the same pattern slow or fast it should still open the door.) + This makes it less picky, which while making it less secure can also make it + less of a pain to use if you're tempo is a little slow or fast. + */ + int totaltimeDifferences = 0; + int timeDiff = 0; + for (i=0; i < maximumKnocks; i++){ // Normalize the times + knockReadings[i]= map(knockReadings[i], 0, maxKnockInterval, 0, 100); + timeDiff = abs(knockReadings[i] - secretCode[i]); + if (timeDiff > rejectValue){ // Individual value too far out of whack. No access for this knock! + return false; + } + totaltimeDifferences += timeDiff; + } + // It can also fail if the whole thing is too inaccurate. + if (totaltimeDifferences / secretKnockCount > averageRejectValue){ + return false; + } + + return true; +} + + +// reads the secret knock from EEPROM. (if any.) +void readSecretKnock(){ + byte reading; + int i; + reading = gw.loadState(1); + if (reading == eepromValid){ // only read EEPROM if the signature byte is correct. + for (int i=0; i < maximumKnocks ;i++){ + secretCode[i] = gw.loadState(i+2); + } + } +} + + +//saves a new pattern too eeprom +void saveSecretKnock(){ + gw.saveState(1, 0); // clear out the signature. That way we know if we didn't finish the write successfully. + for (int i=0; i < maximumKnocks; i++){ + gw.saveState(i+2, secretCode[i]); + } + gw.saveState(1, eepromValid); // all good. Write the signature so we'll know it's all good. +} + +// Plays back the pattern of the knock in blinks and beeps +void playbackKnock(int maxKnockInterval){ + digitalWrite(ledPin, LOW); + delay(1000); + digitalWrite(ledPin, HIGH); + chirp(200, 1800); + for (int i = 0; i < maximumKnocks ; i++){ + digitalWrite(ledPin, LOW); + // only turn it on if there's a delay + if (secretCode[i] > 0){ + delay(map(secretCode[i], 0, 100, 0, maxKnockInterval)); // Expand the time back out to what it was. Roughly. + digitalWrite(ledPin, HIGH); + chirp(200, 1800); + } + } + digitalWrite(ledPin, LOW); +} + +// Deals with the knock delay thingy. +void knockDelay(){ + int itterations = (knockFadeTime / 20); // Wait for the peak to dissipate before listening to next one. + for (int i=0; i < itterations; i++){ + delay(10); + analogRead(knockSensor); // This is done in an attempt to defuse the analog sensor's capacitor that will give false readings on high impedance sensors. + delay(10); + } +} + +// Plays a non-musical tone on the piezo. +// playTime = milliseconds to play the tone +// delayTime = time in microseconds between ticks. (smaller=higher pitch tone.) +void chirp(int playTime, int delayTime){ + long loopTime = (playTime * 1000L) / delayTime; + pinMode(audioOut, OUTPUT); + for(int i=0; i < loopTime; i++){ + digitalWrite(audioOut, HIGH); + delayMicroseconds(delayTime); + digitalWrite(audioOut, LOW); + } + pinMode(audioOut, INPUT); +} + + + +void incomingMessage(const MyMessage &message) { + // We only expect one type of message from controller. But we better check anyway. + if (message.type==V_LOCK_STATUS) { + // Change relay state + setLockState(message.getBool(), false); + + // Write some debug info + Serial.print("Incoming lock status:"); + Serial.println(message.getBool()); + } +} + diff --git a/SerialGateway/SerialGateway.ino b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino similarity index 72% rename from SerialGateway/SerialGateway.ino rename to libraries/MySensors/examples/SerialGateway/SerialGateway.ino index 2d3d5a3..8c3a7dd 100644 --- a/SerialGateway/SerialGateway.ino +++ b/libraries/MySensors/examples/SerialGateway/SerialGateway.ino @@ -1,4 +1,4 @@ -/* + /* * Copyright (C) 2013 Henrik Ekblad * * This program is free software; you can redistribute it and/or @@ -15,31 +15,22 @@ * - Inclusion button should be connected between digital pin 3 and GND * - RX/TX/ERR leds need to be connected between +5V (anode) and digital ping 6/5/4 with resistor 270-330R in a series * - * LED purposes: + * LEDs (OPTIONAL): * - RX (green) - blink fast on radio message recieved. In inclusion mode will blink fast only on presentation recieved * - TX (yellow) - blink fast on radio message transmitted. In inclusion mode will blink slowly * - ERR (red) - fast blink on error during transmission error or recieve crc error */ #include -#include -#include -#include -#include -#include +#include +#include #include -#include #define INCLUSION_MODE_TIME 1 // Number of minutes inclusion mode is enabled #define INCLUSION_MODE_PIN 3 // Digital pin used for inclusion mode button -// No blink or button functionality. Use the vanilla constructor. -//Gateway gw; - -// To start gateway with include button and led blinking functionality enabled use this instead! -Gateway gw(9, 10, INCLUSION_MODE_TIME, INCLUSION_MODE_PIN, 6, 5, 4); - +MyGateway gw(DEFAULT_CE_PIN, DEFAULT_CS_PIN, INCLUSION_MODE_TIME, INCLUSION_MODE_PIN, 6, 5, 4); char inputString[MAX_RECEIVE_LENGTH] = ""; // A string to hold incoming commands from serial/ethernet interface int inputPos = 0; @@ -48,36 +39,11 @@ boolean commandComplete = false; // whether the string is complete void setup() { gw.begin(); - - // C++ classes and interrupts really sucks. Need to attach interrupt - // outside thw Gateway class due to language shortcomings! Gah! - - if (gw.isLedMode()) { - // Add led timer interrupt - MsTimer2::set(300, ledTimersInterrupt); - MsTimer2::start(); - // Add interrupt for inclustion button to pin - PCintPort::attachInterrupt(INCLUSION_MODE_PIN, startInclusionInterrupt, RISING); - } } void loop() { gw.processRadioMessage(); - checkSerialInput(); - -} - - -void startInclusionInterrupt() { - gw.startInclusionInterrupt(); -} - -void ledTimersInterrupt() { - gw.ledTimersInterrupt(); -} - -void checkSerialInput() { if (commandComplete) { // A command wass issued from serial interface // We will now try to send it to the actuator @@ -87,6 +53,7 @@ void checkSerialInput() { } } + /* SerialEvent occurs whenever a new data comes in the hardware serial RX. This routine is run between each diff --git a/libraries/MySensors/examples/ServoActuator/ServoActuator.ino b/libraries/MySensors/examples/ServoActuator/ServoActuator.ino index 729694f..561fc73 100644 --- a/libraries/MySensors/examples/ServoActuator/ServoActuator.ino +++ b/libraries/MySensors/examples/ServoActuator/ServoActuator.ino @@ -6,11 +6,9 @@ // Contribution by: Derek Macias -#include +#include #include -#include #include -#include #define SERVO_DIGITAL_OUT_PIN 3 #define SERVO_MIN 0 // Fine tune your servos min. 0-180 @@ -18,59 +16,55 @@ #define DETACH_DELAY 900 // Tune this to let your movement finish before detaching the servo #define CHILD_ID 10 // Id of the sensor child -Sensor gw; +MySensor gw; +MyMessage msg(CHILD_ID, V_DIMMER); Servo myservo; // create servo object to control a servo // a maximum of eight servo objects can be created Sensor gw(9,10); unsigned long timeOfLastChange = 0; bool attachedServo = false; - void setup() { - gw.begin(); + // Attach method for incoming messages + gw.begin(incomingMessage); // Send the sketch version information to the gateway and Controller gw.sendSketchInfo("Servo", "1.0"); // Register all sensors to gw (they will be created as child devices) - gw.sendSensorPresentation(CHILD_ID, S_COVER); + gw.present(CHILD_ID, S_COVER); - // Fetch servo state at startup - gw.getStatus(CHILD_ID, V_DIMMER); - setRelayStatus(gw.getMessage()); // Wait here until status message arrive from gw + // Request last servo state at startup + gw.request(CHILD_ID, V_DIMMER); } void loop() { - if (gw.messageAvailable()) { - // New messsage from gw - message_s message = gw.getMessage(); - setRelayStatus(message); - } + gw.process(); if (attachedServo && millis() - timeOfLastChange > DETACH_DELAY) { myservo.detach(); attachedServo = false; } } -void setRelayStatus(message_s message) { +void incomingMessage(const MyMessage &message) { myservo.attach(SERVO_DIGITAL_OUT_PIN); attachedServo = true; - if (message.header.type==V_DIMMER) { // This could be M_ACK_VARIABLE or M_SET_VARIABLE - int val = atoi(message.data); + if (message.type==V_DIMMER) { // This could be M_ACK_VARIABLE or M_SET_VARIABLE + int val = message.getInt(); myservo.write(SERVO_MAX + (SERVO_MIN-SERVO_MAX)/100 * val); // sets the servo position 0-180 // Write some debug info Serial.print("Servo changed. new state: "); Serial.println(val); - } else if (message.header.type==V_UP) { + } else if (message.type==V_UP) { Serial.println("Servo UP command"); myservo.write(SERVO_MIN); - gw.sendVariable(CHILD_ID, V_DIMMER, 100); - } else if (message.header.type==V_DOWN) { + gw.send(msg.set(100)); + } else if (message.type==V_DOWN) { Serial.println("Servo DOWN command"); myservo.write(SERVO_MAX); - gw.sendVariable(CHILD_ID, V_DIMMER, 0); - } else if (message.header.type==V_STOP) { + gw.send(msg.set(0)); + } else if (message.type==V_STOP) { Serial.println("Servo STOP command"); myservo.detach(); attachedServo = false; diff --git a/libraries/MySensors/examples/SoilMoistSensor/SoilMoistSensor.ino b/libraries/MySensors/examples/SoilMoistSensor/SoilMoistSensor.ino index 9cfb218..ca6249a 100644 --- a/libraries/MySensors/examples/SoilMoistSensor/SoilMoistSensor.ino +++ b/libraries/MySensors/examples/SoilMoistSensor/SoilMoistSensor.ino @@ -1,15 +1,12 @@ -#include #include -#include -#include -#include +#include #define DIGITAL_INPUT_SOIL_SENSOR 3 // Digital input did you attach your soil sensor. #define INTERRUPT DIGITAL_INPUT_SOIL_SENSOR-2 // Usually the interrupt = pin -2 (on uno/nano anyway) #define CHILD_ID 0 // Id of the sensor child -Sensor gw; -Sleep sleep; +MySensor gw; +MyMessage msg(CHILD_ID, V_TRIPPED); int lastSoilValue = -1; void setup() @@ -18,10 +15,10 @@ void setup() // Send the sketch version information to the gateway and Controller gw.sendSketchInfo("Soil Moisture Sensor", "1.0"); - - pinMode(DIGITAL_INPUT_SOIL_SENSOR, INPUT); // sets the soil sensor digital pin as input + // sets the soil sensor digital pin as input + pinMode(DIGITAL_INPUT_SOIL_SENSOR, INPUT); // Register all sensors to gw (they will be created as child devices) - gw.sendSensorPresentation(CHILD_ID, S_MOTION); + gw.present(CHILD_ID, S_MOTION); } void loop() @@ -30,14 +27,11 @@ void loop() int soilValue = digitalRead(DIGITAL_INPUT_SOIL_SENSOR); // 1 = Not triggered, 0 = In soil with water if (soilValue != lastSoilValue) { Serial.println(soilValue); - gw.sendVariable(CHILD_ID, V_TRIPPED, soilValue==0?"1":"0"); // Send the inverse to gw as tripped should be when no water in soil + gw.send(msg.set(soilValue==0?1:0)); // Send the inverse to gw as tripped should be when no water in soil lastSoilValue = soilValue; } - // Power down the radio. Note that the radio will get powered back up - // on the next write() call. - gw.powerDown(); - sleep.pwrDownMode(); //set sleep mode - sleep.sleepInterrupt(INTERRUPT,CHANGE); + // Power down the radio and arduino until digital input changes. + gw.sleep(INTERRUPT,CHANGE); } diff --git a/libraries/MySensors/examples/TimeAndVariableSensor/TimeAndVariableSensor.ino b/libraries/MySensors/examples/TimeAndVariableSensor/TimeAndVariableSensor.ino deleted file mode 100644 index f0545a2..0000000 --- a/libraries/MySensors/examples/TimeAndVariableSensor/TimeAndVariableSensor.ino +++ /dev/null @@ -1,66 +0,0 @@ - -// Example sketch showing how to request time from vera -// and how to set a cutom variable on a sensor - -#include -#include -#include -#include -#include - -#define CHILD_ID 0 // Id of the sensor child - -Sensor gw; - - -void setup() -{ - gw.begin(); - - // Send the sketch version information to the gateway and Controller - gw.sendSketchInfo("Clock", "1.0"); - - // Register any sensortype. This example we just create a motion sensor. - gw.sendSensorPresentation(CHILD_ID, S_MOTION); - - setSyncProvider(getTime); - setSyncInterval(3600); // get time from gw every hour -} - -unsigned long getTime() { - return gw.getTime(); // Vera is time provider -} - -void loop() -{ -// long time = gw.getTime(); -// setTime(time); - - Serial.print(hour()); - printDigits(minute()); - printDigits(second()); - Serial.print(" "); - Serial.print(day()); - Serial.print(" "); - Serial.print(month()); - Serial.print(" "); - Serial.print(year()); - Serial.println(); - - // Ok now send time back to gw and store in in Variable1 - // of the motion sensor device - gw.sendVariable(CHILD_ID, V_VAR1, minute()); - - // wait 10 seconds... - delay(10000); -} - -void printDigits(int digits){ - // utility function for digital clock display: prints preceding colon and leading 0 - Serial.print(":"); - if(digits < 10) - Serial.print('0'); - Serial.print(digits); -} - - diff --git a/libraries/MySensors/examples/TimeAwareSensor/TimeAwareSensor.ino b/libraries/MySensors/examples/TimeAwareSensor/TimeAwareSensor.ino new file mode 100644 index 0000000..2635f2e --- /dev/null +++ b/libraries/MySensors/examples/TimeAwareSensor/TimeAwareSensor.ino @@ -0,0 +1,55 @@ + +// Example sketch showing how to request time from controller + +#include +#include +#include + +MySensor gw; +boolean timeReceived = false; + +void setup() +{ + gw.begin(); + + // Send the sketch version information to the gateway and Controller + gw.sendSketchInfo("Clock", "1.0"); + + // Request time from controller. + gw.requestTime(receiveTime); +} + +// This is called when a new time value was received +void receiveTime(unsigned long time) { + // Ok, set incoming time + setTime(time); + timeReceived = true; +} + +void loop() +{ + gw.process(); + // Print time + if (timeReceived) { + Serial.print(hour()); + printDigits(minute()); + printDigits(second()); + Serial.print(" "); + Serial.print(day()); + Serial.print(" "); + Serial.print(month()); + Serial.print(" "); + Serial.print(year()); + Serial.println(); + } +} + +void printDigits(int digits){ + // utility function for digital clock display: prints preceding colon and leading 0 + Serial.print(":"); + if(digits < 10) + Serial.print('0'); + Serial.print(digits); +} + + diff --git a/libraries/MySensors/examples/UVSensor/UVSensor.ino b/libraries/MySensors/examples/UVSensor/UVSensor.ino new file mode 100644 index 0000000..838cdbd --- /dev/null +++ b/libraries/MySensors/examples/UVSensor/UVSensor.ino @@ -0,0 +1,64 @@ +/* + Vera Arduino UVM-30A + + connect the sensor as follows : + + + >>> 5V + - >>> GND + out >>> A0 + + Contribution: epierre, bulldoglowell + Converted to 1.4 by Henrik Ekblad + + License: Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0) + +*/ + +#include +#include + +#define CHILD_ID_UV 0 +#define UV_SENSOR_ANALOG_PIN 0 +unsigned long SLEEP_TIME = 30*1000; // Sleep time between reads (in milliseconds) + +MySensor gw; +MyMessage uvMsg(CHILD_ID_UV, V_UV); +int lastUV = -1; +int uvIndexValue [13] = { 50, 227, 318, 408, 503, 606, 696, 795, 881, 976, 1079, 1170, 3000}; +int uvIndex; + +void setup() +{ + gw.begin(); + + // Send the sketch version information to the gateway and Controller + gw.sendSketchInfo("UV Sensor", "1.1"); + + // Register all sensors to gateway (they will be created as child devices) + gw.present(CHILD_ID_UV, S_UV); + +} + +void loop() +{ + uint16_t uv = analogRead(0);// Get UV value + Serial.print("Uv reading: "); + Serial.println(uv); + for (int i = 0; i < 13; i++) + { + if (uv <= uvIndexValue[i]) + { + uvIndex = i; + break; + } + } + Serial.print("Uv index: "); + Serial.println(uvIndex); + + if (uvIndex != lastUV) { + gw.send(uvMsg.set(uvIndex)); + lastUV = uvIndex; + } + + gw.sleep(SLEEP_TIME); +} diff --git a/libraries/MySensors/examples/WaterMeterPulseSensor/WaterMeterPulseSensor.ino b/libraries/MySensors/examples/WaterMeterPulseSensor/WaterMeterPulseSensor.ino index 3583ca8..5905e8c 100644 --- a/libraries/MySensors/examples/WaterMeterPulseSensor/WaterMeterPulseSensor.ino +++ b/libraries/MySensors/examples/WaterMeterPulseSensor/WaterMeterPulseSensor.ino @@ -8,15 +8,9 @@ // sleepmode. So we cannot make this sensor sleep if we also want // to calculate/report flow. // -// Sensor on pin 3 - -#include -#include #include -#include -#include -#include +#include #define DIGITAL_INPUT_SENSOR 3 // The digital input you attached your sensor. (Only 2 and 3 generates interrupt!) #define PULSE_FACTOR 1000 // Nummber of blinks per m3 of your meter (One rotation/liter) @@ -24,16 +18,16 @@ #define MAX_FLOW 40 // Max flow (l/min) value to report. This filetrs outliers. #define INTERRUPT DIGITAL_INPUT_SENSOR-2 // Usually the interrupt = pin -2 (on uno/nano anyway) #define CHILD_ID 5 // Id of the sensor child -unsigned long SEND_FREQUENCY = 20; // Minimum time between send (in seconds). We don't want to spam the gateway. +unsigned long SEND_FREQUENCY = 20000; // Minimum time between send (in milliseconds). We don't want to spam the gateway. -Sensor gw; -Sleep sleep; +MySensor gw; double ppl = ((double)PULSE_FACTOR)/1000; // Pulses per liter volatile unsigned long pulseCount = 0; volatile unsigned long lastBlink = 0; -volatile double flow = 0; +volatile double flow = 0; +boolean pcReceived = false; unsigned long oldPulseCount = 0; unsigned long newBlink = 0; double oldflow = 0; @@ -43,21 +37,24 @@ unsigned long lastSend; unsigned long lastPulse; unsigned long currentTime; boolean metric; +MyMessage flowMsg(CHILD_ID,V_FLOW); +MyMessage volumeMsg(CHILD_ID,V_VOLUME); +MyMessage pcMsg(CHILD_ID,V_VAR1); + void setup() { - gw.begin(); + gw.begin(incomingMessage); // Send the sketch version information to the gateway and Controller gw.sendSketchInfo("Water Meter", "1.0"); // Register this device as Waterflow sensor - gw.sendSensorPresentation(CHILD_ID, S_WATER); + gw.present(CHILD_ID, S_WATER); // Fetch last known pulse count value from gw - pulseCount = oldPulseCount = atol(gw.getStatus(CHILD_ID, V_VAR1)); - //Serial.print("Last pulse count from gw:"); - //Serial.println(pulseCount); + gw.request(CHILD_ID, V_VAR1); + attachInterrupt(INTERRUPT, onPulse, RISING); lastSend = millis(); } @@ -65,16 +62,18 @@ void setup() void loop() { - currentTime = millis(); + gw.process(); + currentTime = millis(); // Only send values at a maximum frequency or woken up from sleep - if (SLEEP_MODE || currentTime - lastSend > 1000*SEND_FREQUENCY) { + bool sendTime = currentTime - lastSend > SEND_FREQUENCY; + if (pcReceived && (SLEEP_MODE || sendTime)) { // New flow value has been calculated if (!SLEEP_MODE && flow != oldflow) { // Check that we dont get unresonable large flow value. // could hapen when long wraps or false interrupt triggered if (flow<((unsigned long)MAX_FLOW)) { - gw.sendVariable(CHILD_ID, V_FLOW, flow, 2); // Send flow value to gw + gw.send(flowMsg.set(flow, 2)); // Send flow value to gw } //Serial.print("l/min:"); //Serial.println(flow); @@ -82,39 +81,38 @@ void loop() } // No Pulse count in 2min - - //Serial.print("currentTime"); - //Serial.println(currentTime); - //Serial.print("lastPulse"); - //Serial.println(lastPulse); - if(currentTime - lastPulse > 120000){ - flow = 0; - } + flow = 0; + } // Pulse count has changed if (pulseCount != oldPulseCount) { - gw.sendVariable(CHILD_ID, V_VAR1, pulseCount); // Send volumevalue to gw VAR1 + gw.send(pcMsg.set(pulseCount)); // Send volumevalue to gw VAR1 double volume = ((double)pulseCount/((double)PULSE_FACTOR)); oldPulseCount = pulseCount; - //Serial.print("Pulse count:"); - //Serial.println(pulseCount); if (volume != oldvolume) { - gw.sendVariable(CHILD_ID, V_VOLUME, volume, 3); // Send volume value to gw - //Serial.print("m3:"); - //Serial.println(volume, 3); + gw.send(volumeMsg.set(volume, 3)); // Send volume value to gw oldvolume = volume; } } lastSend = currentTime; + } else if (sendTime) { + // No count received. Try requesting it again + gw.request(CHILD_ID, V_VAR1); } if (SLEEP_MODE) { - delay(300); //delay to allow serial to fully print before sleep - gw.powerDown(); - sleep.pwrDownMode(); //set sleep mode - sleep.sleepDelay(SEND_FREQUENCY * 1000); //sleep for: sleepTime + gw.sleep(SEND_FREQUENCY); + } +} + +void incomingMessage(const MyMessage &message) { + if (message.type==V_VAR1) { + pulseCount = oldPulseCount = message.getLong(); + Serial.print("Received last pulse count from gw:"); + Serial.println(pulseCount); + pcReceived = true; } } @@ -129,10 +127,8 @@ void onPulse() // Sometimes we get interrupt on RISING, 500000 = 0.5sek debounce ( max 120 l/min) return; } - flow = (60000000.0 /interval) / ppl; lastBlink = newBlink; - //Serial.println(flow, 4); } pulseCount++; } diff --git a/libraries/MySensors/utility/LowPower.cpp b/libraries/MySensors/utility/LowPower.cpp new file mode 100644 index 0000000..a72cc31 --- /dev/null +++ b/libraries/MySensors/utility/LowPower.cpp @@ -0,0 +1,856 @@ +/******************************************************************************* +* LowPower Library +* Version: 1.30 +* Date: 22-05-2013 +* Company: Rocket Scream Electronics +* Website: www.rocketscream.com +* +* This is a lightweight low power library for Arduino. Please check our wiki +* (www.rocketscream.com/wiki) for more information on using this piece of +* library. +* +* This library is licensed under Creative Commons Attribution-ShareAlike 3.0 +* Unported License. +* +* Revision Description +* ======== =========== +* 1.30 Added support for ATMega168, ATMega2560, ATMega1280 & ATMega32U4. +* Tested to work with Arduino IDE 1.0.1 - 1.0.4. +* 1.20 Remove typo error in idle method for checking whether Timer 0 was +* turned off. +* Remove dependecy on WProgram.h which is not required. +* Tested to work with Arduino IDE 1.0. +* 1.10 Added #ifndef for sleep_bod_disable() for compatibility with future +* Arduino IDE release. +* 1.00 Initial public release. +*******************************************************************************/ +#include +#include +#include +#include +#include "LowPower.h" + +// Only Pico Power devices can change BOD settings through software +#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 lowPowerBodOn(mode) \ +do { \ + set_sleep_mode(mode); \ + cli(); \ + sleep_enable(); \ + sei(); \ + sleep_cpu(); \ + sleep_disable(); \ + sei(); \ +} while (0); + +// Only Pico Power devices can change BOD settings through software +#if defined __AVR_ATmega328P__ +#define lowPowerBodOff(mode)\ +do { \ + set_sleep_mode(mode); \ + cli(); \ + sleep_enable(); \ + sleep_bod_disable(); \ + sei(); \ + sleep_cpu(); \ + sleep_disable(); \ + sei(); \ +} while (0); +#endif + +// Some macros is still missing from AVR GCC distribution for ATmega32U4 +#if defined __AVR_ATmega32U4__ + // Timer 4 PRR bit is currently not defined in iom32u4.h + #ifndef PRTIM4 + #define PRTIM4 4 + #endif + + // Timer 4 power reduction macro is not defined currently in power.h + #ifndef power_timer4_disable + #define power_timer4_disable() (PRR1 |= (uint8_t)(1 << PRTIM4)) + #endif + + #ifndef power_timer4_enable + #define power_timer4_enable() (PRR1 &= (uint8_t)~(1 << PRTIM4)) + #endif +#endif + +/******************************************************************************* +* Name: idle +* Description: Putting ATmega328P/168 into idle state. Please make sure you +* understand the implication and result of disabling module. +* +* Argument Description +* ========= =========== +* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake +* up resource: +* (a) SLEEP_15MS - 15 ms sleep +* (b) SLEEP_30MS - 30 ms sleep +* (c) SLEEP_60MS - 60 ms sleep +* (d) SLEEP_120MS - 120 ms sleep +* (e) SLEEP_250MS - 250 ms sleep +* (f) SLEEP_500MS - 500 ms sleep +* (g) SLEEP_1S - 1 s sleep +* (h) SLEEP_2S - 2 s sleep +* (i) SLEEP_4S - 4 s sleep +* (j) SLEEP_8S - 8 s sleep +* (k) SLEEP_FOREVER - Sleep without waking up through WDT +* +* 2. adc ADC module disable control: +* (a) ADC_OFF - Turn off ADC module +* (b) ADC_ON - Leave ADC module in its default state +* +* 3. timer2 Timer 2 module disable control: +* (a) TIMER2_OFF - Turn off Timer 2 module +* (b) TIMER2_ON - Leave Timer 2 module in its default state +* +* 4. timer1 Timer 1 module disable control: +* (a) TIMER1_OFF - Turn off Timer 1 module +* (b) TIMER1_ON - Leave Timer 1 module in its default state +* +* 5. timer0 Timer 0 module disable control: +* (a) TIMER0_OFF - Turn off Timer 0 module +* (b) TIMER0_ON - Leave Timer 0 module in its default state +* +* 6. spi SPI module disable control: +* (a) SPI_OFF - Turn off SPI module +* (b) SPI_ON - Leave SPI module in its default state +* +* 7. usart0 USART0 module disable control: +* (a) USART0_OFF - Turn off USART0 module +* (b) USART0_ON - Leave USART0 module in its default state +* +* 8. twi TWI module disable control: +* (a) TWI_OFF - Turn off TWI module +* (b) TWI_ON - Leave TWI module in its default state +* +*******************************************************************************/ +#if defined (__AVR_ATmega328P__) || defined (__AVR_ATmega168__) +void LowPowerClass::idle(period_t period, adc_t adc, timer2_t timer2, + timer1_t timer1, timer0_t timer0, + spi_t spi, usart0_t usart0, twi_t twi) +{ + // Temporary clock source variable + unsigned char clockSource = 0; + + if (timer2 == TIMER2_OFF) + { + if (TCCR2B & CS22) clockSource |= (1 << CS22); + if (TCCR2B & CS21) clockSource |= (1 << CS21); + if (TCCR2B & CS20) clockSource |= (1 << CS20); + + // Remove the clock source to shutdown Timer2 + TCCR2B &= ~(1 << CS22); + TCCR2B &= ~(1 << CS21); + TCCR2B &= ~(1 << CS20); + + power_timer2_disable(); + } + + if (adc == ADC_OFF) + { + ADCSRA &= ~(1 << ADEN); + power_adc_disable(); + } + + if (timer1 == TIMER1_OFF) power_timer1_disable(); + if (timer0 == TIMER0_OFF) power_timer0_disable(); + if (spi == SPI_OFF) power_spi_disable(); + if (usart0 == USART0_OFF) power_usart0_disable(); + if (twi == TWI_OFF) power_twi_disable(); + + if (period != SLEEP_FOREVER) + { + wdt_enable(period); + WDTCSR |= (1 << WDIE); + } + + lowPowerBodOn(SLEEP_MODE_IDLE); + + if (adc == ADC_OFF) + { + power_adc_enable(); + ADCSRA |= (1 << ADEN); + } + + if (timer2 == TIMER2_OFF) + { + if (clockSource & CS22) TCCR2B |= (1 << CS22); + if (clockSource & CS21) TCCR2B |= (1 << CS21); + if (clockSource & CS20) TCCR2B |= (1 << CS20); + + power_timer2_enable(); + } + + if (timer1 == TIMER1_OFF) power_timer1_enable(); + if (timer0 == TIMER0_OFF) power_timer0_enable(); + if (spi == SPI_OFF) power_spi_enable(); + if (usart0 == USART0_OFF) power_usart0_enable(); + if (twi == TWI_OFF) power_twi_enable(); +} +#endif + +/******************************************************************************* +* Name: idle +* Description: Putting ATmega32U4 into idle state. Please make sure you +* understand the implication and result of disabling module. +* Take note that Timer 2 is not available and USART0 +* is replaced with USART1 on ATmega32U4. +* +* Argument Description +* ========= =========== +* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake +* up resource: +* (a) SLEEP_15MS - 15 ms sleep +* (b) SLEEP_30MS - 30 ms sleep +* (c) SLEEP_60MS - 60 ms sleep +* (d) SLEEP_120MS - 120 ms sleep +* (e) SLEEP_250MS - 250 ms sleep +* (f) SLEEP_500MS - 500 ms sleep +* (g) SLEEP_1S - 1 s sleep +* (h) SLEEP_2S - 2 s sleep +* (i) SLEEP_4S - 4 s sleep +* (j) SLEEP_8S - 8 s sleep +* (k) SLEEP_FOREVER - Sleep without waking up through WDT +* +* 2. adc ADC module disable control: +* (a) ADC_OFF - Turn off ADC module +* (b) ADC_ON - Leave ADC module in its default state +* +* 3. timer4 Timer 4 module disable control: +* (a) TIMER4_OFF - Turn off Timer 4 module +* (b) TIMER4_ON - Leave Timer 4 module in its default state +* +* 4. timer3 Timer 3 module disable control: +* (a) TIMER3_OFF - Turn off Timer 3 module +* (b) TIMER3_ON - Leave Timer 3 module in its default state +* +* 5. timer1 Timer 1 module disable control: +* (a) TIMER1_OFF - Turn off Timer 1 module +* (b) TIMER1_ON - Leave Timer 1 module in its default state +* +* 6. timer0 Timer 0 module disable control: +* (a) TIMER0_OFF - Turn off Timer 0 module +* (b) TIMER0_ON - Leave Timer 0 module in its default state +* +* 7. spi SPI module disable control: +* (a) SPI_OFF - Turn off SPI module +* (b) SPI_ON - Leave SPI module in its default state +* +* 8. usart1 USART1 module disable control: +* (a) USART1_OFF - Turn off USART1 module +* (b) USART1_ON - Leave USART1 module in its default state +* +* 9. twi TWI module disable control: +* (a) TWI_OFF - Turn off TWI module +* (b) TWI_ON - Leave TWI module in its default state +* +* 10.usb USB module disable control: +* (a) USB_OFF - Turn off USB module +* (b) USB_ON - Leave USB module in its default state +*******************************************************************************/ +#if defined __AVR_ATmega32U4__ +void LowPowerClass::idle(period_t period, adc_t adc, + timer4_t timer4, timer3_t timer3, + timer1_t timer1, timer0_t timer0, + spi_t spi, usart1_t usart1, twi_t twi, usb_t usb) +{ + if (adc == ADC_OFF) + { + ADCSRA &= ~(1 << ADEN); + power_adc_disable(); + } + + if (timer4 == TIMER4_OFF) power_timer4_disable(); + if (timer3 == TIMER3_OFF) power_timer3_disable(); + if (timer1 == TIMER1_OFF) power_timer1_disable(); + if (timer0 == TIMER0_OFF) power_timer0_disable(); + if (spi == SPI_OFF) power_spi_disable(); + if (usart1 == USART1_OFF) power_usart1_disable(); + if (twi == TWI_OFF) power_twi_disable(); + if (usb == USB_OFF) power_usb_disable(); + + if (period != SLEEP_FOREVER) + { + wdt_enable(period); + WDTCSR |= (1 << WDIE); + } + + lowPowerBodOn(SLEEP_MODE_IDLE); + + if (adc == ADC_OFF) + { + power_adc_enable(); + ADCSRA |= (1 << ADEN); + } + + if (timer4 == TIMER4_OFF) power_timer4_enable(); + if (timer3 == TIMER3_OFF) power_timer3_enable(); + if (timer1 == TIMER1_OFF) power_timer1_enable(); + if (timer0 == TIMER0_OFF) power_timer0_enable(); + if (spi == SPI_OFF) power_spi_enable(); + if (usart1 == USART1_OFF) power_usart1_enable(); + if (twi == TWI_OFF) power_twi_enable(); + if (usb == USB_OFF) power_usb_enable(); +} +#endif + +/******************************************************************************* +* Name: idle +* Description: Putting ATmega2560 & ATmega1280 into idle state. Please make sure +* you understand the implication and result of disabling module. +* Take note that extra Timer 5, 4, 3 compared to an ATmega328P/168. +* Also take note that extra USART 3, 2, 1 compared to an +* ATmega328P/168. +* +* Argument Description +* ========= =========== +* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake +* up resource: +* (a) SLEEP_15MS - 15 ms sleep +* (b) SLEEP_30MS - 30 ms sleep +* (c) SLEEP_60MS - 60 ms sleep +* (d) SLEEP_120MS - 120 ms sleep +* (e) SLEEP_250MS - 250 ms sleep +* (f) SLEEP_500MS - 500 ms sleep +* (g) SLEEP_1S - 1 s sleep +* (h) SLEEP_2S - 2 s sleep +* (i) SLEEP_4S - 4 s sleep +* (j) SLEEP_8S - 8 s sleep +* (k) SLEEP_FOREVER - Sleep without waking up through WDT +* +* 2. adc ADC module disable control: +* (a) ADC_OFF - Turn off ADC module +* (b) ADC_ON - Leave ADC module in its default state +* +* 3. timer5 Timer 5 module disable control: +* (a) TIMER5_OFF - Turn off Timer 5 module +* (b) TIMER5_ON - Leave Timer 5 module in its default state +* +* 4. timer4 Timer 4 module disable control: +* (a) TIMER4_OFF - Turn off Timer 4 module +* (b) TIMER4_ON - Leave Timer 4 module in its default state +* +* 5. timer3 Timer 3 module disable control: +* (a) TIMER3_OFF - Turn off Timer 3 module +* (b) TIMER3_ON - Leave Timer 3 module in its default state +* +* 6. timer2 Timer 2 module disable control: +* (a) TIMER2_OFF - Turn off Timer 2 module +* (b) TIMER2_ON - Leave Timer 2 module in its default state +* +* 7. timer1 Timer 1 module disable control: +* (a) TIMER1_OFF - Turn off Timer 1 module +* (b) TIMER1_ON - Leave Timer 1 module in its default state +* +* 8. timer0 Timer 0 module disable control: +* (a) TIMER0_OFF - Turn off Timer 0 module +* (b) TIMER0_ON - Leave Timer 0 module in its default state +* +* 9. spi SPI module disable control: +* (a) SPI_OFF - Turn off SPI module +* (b) SPI_ON - Leave SPI module in its default state +* +* 10.usart3 USART3 module disable control: +* (a) USART3_OFF - Turn off USART3 module +* (b) USART3_ON - Leave USART3 module in its default state +* +* 11.usart2 USART2 module disable control: +* (a) USART2_OFF - Turn off USART2 module +* (b) USART2_ON - Leave USART2 module in its default state +* +* 12.usart1 USART1 module disable control: +* (a) USART1_OFF - Turn off USART1 module +* (b) USART1_ON - Leave USART1 module in its default state +* +* 13.usart0 USART0 module disable control: +* (a) USART0_OFF - Turn off USART0 module +* (b) USART0_ON - Leave USART0 module in its default state +* +* 14.twi TWI module disable control: +* (a) TWI_OFF - Turn off TWI module +* (b) TWI_ON - Leave TWI module in its default state +* +*******************************************************************************/ +#if defined (__AVR_ATmega2560__) || defined (__AVR_ATmega1280__) +void LowPowerClass::idle(period_t period, adc_t adc, timer5_t timer5, + timer4_t timer4, timer3_t timer3, timer2_t timer2, + timer1_t timer1, timer0_t timer0, spi_t spi, + usart3_t usart3, usart2_t usart2, usart1_t usart1, + usart0_t usart0, twi_t twi) +{ + // Temporary clock source variable + unsigned char clockSource = 0; + + if (timer2 == TIMER2_OFF) + { + if (TCCR2B & CS22) clockSource |= (1 << CS22); + if (TCCR2B & CS21) clockSource |= (1 << CS21); + if (TCCR2B & CS20) clockSource |= (1 << CS20); + + // Remove the clock source to shutdown Timer2 + TCCR2B &= ~(1 << CS22); + TCCR2B &= ~(1 << CS21); + TCCR2B &= ~(1 << CS20); + + power_timer2_disable(); + } + + if (adc == ADC_OFF) + { + ADCSRA &= ~(1 << ADEN); + power_adc_disable(); + } + + if (timer5 == TIMER5_OFF) power_timer5_disable(); + if (timer4 == TIMER4_OFF) power_timer4_disable(); + if (timer3 == TIMER3_OFF) power_timer3_disable(); + if (timer1 == TIMER1_OFF) power_timer1_disable(); + if (timer0 == TIMER0_OFF) power_timer0_disable(); + if (spi == SPI_OFF) power_spi_disable(); + if (usart3 == USART3_OFF) power_usart3_disable(); + if (usart2 == USART2_OFF) power_usart2_disable(); + if (usart1 == USART1_OFF) power_usart1_disable(); + if (usart0 == USART0_OFF) power_usart0_disable(); + if (twi == TWI_OFF) power_twi_disable(); + + if (period != SLEEP_FOREVER) + { + wdt_enable(period); + WDTCSR |= (1 << WDIE); + } + + lowPowerBodOn(SLEEP_MODE_IDLE); + + if (adc == ADC_OFF) + { + power_adc_enable(); + ADCSRA |= (1 << ADEN); + } + + if (timer2 == TIMER2_OFF) + { + if (clockSource & CS22) TCCR2B |= (1 << CS22); + if (clockSource & CS21) TCCR2B |= (1 << CS21); + if (clockSource & CS20) TCCR2B |= (1 << CS20); + + power_timer2_enable(); + } + + if (timer5 == TIMER5_OFF) power_timer5_enable(); + if (timer4 == TIMER4_OFF) power_timer4_enable(); + if (timer3 == TIMER3_OFF) power_timer3_enable(); + if (timer1 == TIMER1_OFF) power_timer1_enable(); + if (timer0 == TIMER0_OFF) power_timer0_enable(); + if (spi == SPI_OFF) power_spi_enable(); + if (usart3 == USART3_OFF) power_usart3_enable(); + if (usart2 == USART2_OFF) power_usart2_enable(); + if (usart1 == USART1_OFF) power_usart1_enable(); + if (usart0 == USART0_OFF) power_usart0_enable(); + if (twi == TWI_OFF) power_twi_enable(); +} +#endif + +/******************************************************************************* +* Name: adcNoiseReduction +* Description: Putting microcontroller into ADC noise reduction state. This is +* a very useful state when using the ADC to achieve best and low +* noise signal. +* +* Argument Description +* ========= =========== +* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake +* up resource: +* (a) SLEEP_15MS - 15 ms sleep +* (b) SLEEP_30MS - 30 ms sleep +* (c) SLEEP_60MS - 60 ms sleep +* (d) SLEEP_120MS - 120 ms sleep +* (e) SLEEP_250MS - 250 ms sleep +* (f) SLEEP_500MS - 500 ms sleep +* (g) SLEEP_1S - 1 s sleep +* (h) SLEEP_2S - 2 s sleep +* (i) SLEEP_4S - 4 s sleep +* (j) SLEEP_8S - 8 s sleep +* (k) SLEEP_FOREVER - Sleep without waking up through WDT +* +* 2. adc ADC module disable control. Turning off the ADC module is +* basically removing the purpose of this low power mode. +* (a) ADC_OFF - Turn off ADC module +* (b) ADC_ON - Leave ADC module in its default state +* +* 3. timer2 Timer 2 module disable control: +* (a) TIMER2_OFF - Turn off Timer 2 module +* (b) TIMER2_ON - Leave Timer 2 module in its default state +* +*******************************************************************************/ +void LowPowerClass::adcNoiseReduction(period_t period, adc_t adc, + timer2_t timer2) +{ + // Temporary clock source variable + unsigned char clockSource = 0; + + #if !defined(__AVR_ATmega32U4__) + if (timer2 == TIMER2_OFF) + { + if (TCCR2B & CS22) clockSource |= (1 << CS22); + if (TCCR2B & CS21) clockSource |= (1 << CS21); + if (TCCR2B & CS20) clockSource |= (1 << CS20); + + // Remove the clock source to shutdown Timer2 + TCCR2B &= ~(1 << CS22); + TCCR2B &= ~(1 << CS21); + TCCR2B &= ~(1 << CS20); + } + #endif + + if (adc == ADC_OFF) ADCSRA &= ~(1 << ADEN); + + if (period != SLEEP_FOREVER) + { + wdt_enable(period); + WDTCSR |= (1 << WDIE); + } + + lowPowerBodOn(SLEEP_MODE_ADC); + + if (adc == ADC_OFF) ADCSRA |= (1 << ADEN); + + #if !defined(__AVR_ATmega32U4__) + if (timer2 == TIMER2_OFF) + { + if (clockSource & CS22) TCCR2B |= (1 << CS22); + if (clockSource & CS21) TCCR2B |= (1 << CS21); + if (clockSource & CS20) TCCR2B |= (1 << CS20); + + } + #endif +} + +/******************************************************************************* +* Name: powerDown +* Description: Putting microcontroller into power down state. This is +* the lowest current consumption state. Use this together with +* external pin interrupt to wake up through external event +* triggering (example: RTC clockout pin, SD card detect pin). +* +* Argument Description +* ========= =========== +* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake +* up resource: +* (a) SLEEP_15MS - 15 ms sleep +* (b) SLEEP_30MS - 30 ms sleep +* (c) SLEEP_60MS - 60 ms sleep +* (d) SLEEP_120MS - 120 ms sleep +* (e) SLEEP_250MS - 250 ms sleep +* (f) SLEEP_500MS - 500 ms sleep +* (g) SLEEP_1S - 1 s sleep +* (h) SLEEP_2S - 2 s sleep +* (i) SLEEP_4S - 4 s sleep +* (j) SLEEP_8S - 8 s sleep +* (k) SLEEP_FOREVER - Sleep without waking up through WDT +* +* 2. adc ADC module disable control. Turning off the ADC module is +* basically removing the purpose of this low power mode. +* (a) ADC_OFF - Turn off ADC module +* (b) ADC_ON - Leave ADC module in its default state +* +* 3. bod Brown Out Detector (BOD) module disable control: +* (a) BOD_OFF - Turn off BOD module +* (b) BOD_ON - Leave BOD module in its default state +* +*******************************************************************************/ +void LowPowerClass::powerDown(period_t period, adc_t adc, bod_t bod) +{ + if (adc == ADC_OFF) ADCSRA &= ~(1 << ADEN); + + if (period != SLEEP_FOREVER) + { + wdt_enable(period); + WDTCSR |= (1 << WDIE); + } + if (bod == BOD_OFF) + { + #if defined __AVR_ATmega328P__ + lowPowerBodOff(SLEEP_MODE_PWR_DOWN); + #else + lowPowerBodOn(SLEEP_MODE_PWR_DOWN); + #endif + } + else + { + lowPowerBodOn(SLEEP_MODE_PWR_DOWN); + } + + if (adc == ADC_OFF) ADCSRA |= (1 << ADEN); +} + +/******************************************************************************* +* Name: powerSave +* Description: Putting microcontroller into power save state. This is +* the lowest current consumption state after power down. +* Use this state together with an external 32.768 kHz crystal (but +* 8/16 MHz crystal/resonator need to be removed) to provide an +* asynchronous clock source to Timer 2. Please take note that +* Timer 2 is also used by the Arduino core for PWM operation. +* Please refer to wiring.c for explanation. Removal of the external +* 8/16 MHz crystal/resonator requires the microcontroller to run +* on its internal RC oscillator which is not so accurate for time +* critical operation. +* +* Argument Description +* ========= =========== +* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake +* up resource: +* (a) SLEEP_15MS - 15 ms sleep +* (b) SLEEP_30MS - 30 ms sleep +* (c) SLEEP_60MS - 60 ms sleep +* (d) SLEEP_120MS - 120 ms sleep +* (e) SLEEP_250MS - 250 ms sleep +* (f) SLEEP_500MS - 500 ms sleep +* (g) SLEEP_1S - 1 s sleep +* (h) SLEEP_2S - 2 s sleep +* (i) SLEEP_4S - 4 s sleep +* (j) SLEEP_8S - 8 s sleep +* (k) SLEEP_FOREVER - Sleep without waking up through WDT +* +* 2. adc ADC module disable control. Turning off the ADC module is +* basically removing the purpose of this low power mode. +* (a) ADC_OFF - Turn off ADC module +* (b) ADC_ON - Leave ADC module in its default state +* +* 3. bod Brown Out Detector (BOD) module disable control: +* (a) BOD_OFF - Turn off BOD module +* (b) BOD_ON - Leave BOD module in its default state +* +* 4. timer2 Timer 2 module disable control: +* (a) TIMER2_OFF - Turn off Timer 2 module +* (b) TIMER2_ON - Leave Timer 2 module in its default state +* +*******************************************************************************/ +void LowPowerClass::powerSave(period_t period, adc_t adc, bod_t bod, + timer2_t timer2) +{ + // Temporary clock source variable + unsigned char clockSource = 0; + + #if !defined(__AVR_ATmega32U4__) + if (timer2 == TIMER2_OFF) + { + if (TCCR2B & CS22) clockSource |= (1 << CS22); + if (TCCR2B & CS21) clockSource |= (1 << CS21); + if (TCCR2B & CS20) clockSource |= (1 << CS20); + + // Remove the clock source to shutdown Timer2 + TCCR2B &= ~(1 << CS22); + TCCR2B &= ~(1 << CS21); + TCCR2B &= ~(1 << CS20); + } + #endif + + if (adc == ADC_OFF) ADCSRA &= ~(1 << ADEN); + + if (period != SLEEP_FOREVER) + { + wdt_enable(period); + WDTCSR |= (1 << WDIE); + } + + if (bod == BOD_OFF) + { + #if defined __AVR_ATmega328P__ + lowPowerBodOff(SLEEP_MODE_PWR_SAVE); + #else + lowPowerBodOn(SLEEP_MODE_PWR_SAVE); + #endif + } + else + { + lowPowerBodOn(SLEEP_MODE_PWR_SAVE); + } + + if (adc == ADC_OFF) ADCSRA |= (1 << ADEN); + + #if !defined(__AVR_ATmega32U4__) + if (timer2 == TIMER2_OFF) + { + if (clockSource & CS22) TCCR2B |= (1 << CS22); + if (clockSource & CS21) TCCR2B |= (1 << CS21); + if (clockSource & CS20) TCCR2B |= (1 << CS20); + } + #endif +} + +/******************************************************************************* +* Name: powerStandby +* Description: Putting microcontroller into power standby state. +* +* Argument Description +* ========= =========== +* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake +* up resource: +* (a) SLEEP_15MS - 15 ms sleep +* (b) SLEEP_30MS - 30 ms sleep +* (c) SLEEP_60MS - 60 ms sleep +* (d) SLEEP_120MS - 120 ms sleep +* (e) SLEEP_250MS - 250 ms sleep +* (f) SLEEP_500MS - 500 ms sleep +* (g) SLEEP_1S - 1 s sleep +* (h) SLEEP_2S - 2 s sleep +* (i) SLEEP_4S - 4 s sleep +* (j) SLEEP_8S - 8 s sleep +* (k) SLEEP_FOREVER - Sleep without waking up through WDT +* +* 2. adc ADC module disable control. Turning off the ADC module is +* basically removing the purpose of this low power mode. +* (a) ADC_OFF - Turn off ADC module +* (b) ADC_ON - Leave ADC module in its default state +* +* 3. bod Brown Out Detector (BOD) module disable control: +* (a) BOD_OFF - Turn off BOD module +* (b) BOD_ON - Leave BOD module in its default state +* +*******************************************************************************/ +void LowPowerClass::powerStandby(period_t period, adc_t adc, bod_t bod) +{ + if (adc == ADC_OFF) ADCSRA &= ~(1 << ADEN); + + if (period != SLEEP_FOREVER) + { + wdt_enable(period); + WDTCSR |= (1 << WDIE); + } + + if (bod == BOD_OFF) + { + #if defined __AVR_ATmega328P__ + lowPowerBodOff(SLEEP_MODE_STANDBY); + #else + lowPowerBodOn(SLEEP_MODE_STANDBY); + #endif + } + else + { + lowPowerBodOn(SLEEP_MODE_STANDBY); + } + + if (adc == ADC_OFF) ADCSRA |= (1 << ADEN); +} + +/******************************************************************************* +* Name: powerExtStandby +* Description: Putting microcontroller into power extended standby state. This +* is different from the power standby state as it has the +* capability to run Timer 2 asynchronously. +* +* Argument Description +* ========= =========== +* 1. period Duration of low power mode. Use SLEEP_FOREVER to use other wake +* up resource: +* (a) SLEEP_15MS - 15 ms sleep +* (b) SLEEP_30MS - 30 ms sleep +* (c) SLEEP_60MS - 60 ms sleep +* (d) SLEEP_120MS - 120 ms sleep +* (e) SLEEP_250MS - 250 ms sleep +* (f) SLEEP_500MS - 500 ms sleep +* (g) SLEEP_1S - 1 s sleep +* (h) SLEEP_2S - 2 s sleep +* (i) SLEEP_4S - 4 s sleep +* (j) SLEEP_8S - 8 s sleep +* (k) SLEEP_FOREVER - Sleep without waking up through WDT +* +* 2. adc ADC module disable control. +* (a) ADC_OFF - Turn off ADC module +* (b) ADC_ON - Leave ADC module in its default state +* +* 3. bod Brown Out Detector (BOD) module disable control: +* (a) BOD_OFF - Turn off BOD module +* (b) BOD_ON - Leave BOD module in its default state +* +* 4. timer2 Timer 2 module disable control: +* (a) TIMER2_OFF - Turn off Timer 2 module +* (b) TIMER2_ON - Leave Timer 2 module in its default state +* +*******************************************************************************/ +void LowPowerClass::powerExtStandby(period_t period, adc_t adc, bod_t bod, + timer2_t timer2) +{ + // Temporary clock source variable + unsigned char clockSource = 0; + + #if !defined(__AVR_ATmega32U4__) + if (timer2 == TIMER2_OFF) + { + if (TCCR2B & CS22) clockSource |= (1 << CS22); + if (TCCR2B & CS21) clockSource |= (1 << CS21); + if (TCCR2B & CS20) clockSource |= (1 << CS20); + + // Remove the clock source to shutdown Timer2 + TCCR2B &= ~(1 << CS22); + TCCR2B &= ~(1 << CS21); + TCCR2B &= ~(1 << CS20); + } + #endif + + if (adc == ADC_OFF) ADCSRA &= ~(1 << ADEN); + + if (period != SLEEP_FOREVER) + { + wdt_enable(period); + WDTCSR |= (1 << WDIE); + } + if (bod == BOD_OFF) + { + #if defined __AVR_ATmega328P__ + lowPowerBodOff(SLEEP_MODE_EXT_STANDBY); + #else + lowPowerBodOn(SLEEP_MODE_EXT_STANDBY); + #endif + } + else + { + lowPowerBodOn(SLEEP_MODE_EXT_STANDBY); + } + + if (adc == ADC_OFF) ADCSRA |= (1 << ADEN); + + #if !defined(__AVR_ATmega32U4__) + if (timer2 == TIMER2_OFF) + { + if (clockSource & CS22) TCCR2B |= (1 << CS22); + if (clockSource & CS21) TCCR2B |= (1 << CS21); + if (clockSource & CS20) TCCR2B |= (1 << CS20); + } + #endif +} + +/******************************************************************************* +* Name: ISR (WDT_vect) +* Description: Watchdog Timer interrupt service routine. This routine is +* required to allow automatic WDIF and WDIE bit clearance in +* hardware. +* +*******************************************************************************/ +ISR (WDT_vect) +{ + // WDIE & WDIF is cleared in hardware upon entering this ISR + wdt_disable(); +} + +LowPowerClass LowPower; \ No newline at end of file diff --git a/libraries/MySensors/utility/LowPower.h b/libraries/MySensors/utility/LowPower.h new file mode 100644 index 0000000..ef05901 --- /dev/null +++ b/libraries/MySensors/utility/LowPower.h @@ -0,0 +1,137 @@ +#ifndef LowPower_h +#define LowPower_h + +enum period_t +{ + SLEEP_15Ms, + SLEEP_30MS, + SLEEP_60MS, + SLEEP_120MS, + SLEEP_250MS, + SLEEP_500MS, + SLEEP_1S, + SLEEP_2S, + SLEEP_4S, + SLEEP_8S, + SLEEP_FOREVER +}; + +enum bod_t +{ + BOD_OFF, + BOD_ON +}; + +enum adc_t +{ + ADC_OFF, + ADC_ON +}; + +enum timer5_t +{ + TIMER5_OFF, + TIMER5_ON +}; + +enum timer4_t +{ + TIMER4_OFF, + TIMER4_ON +}; + +enum timer3_t +{ + TIMER3_OFF, + TIMER3_ON +}; + +enum timer2_t +{ + TIMER2_OFF, + TIMER2_ON +}; + +enum timer1_t +{ + TIMER1_OFF, + TIMER1_ON +}; + +enum timer0_t +{ + TIMER0_OFF, + TIMER0_ON +}; + +enum spi_t +{ + SPI_OFF, + SPI_ON +}; + +enum usart0_t +{ + USART0_OFF, + USART0_ON +}; + +enum usart1_t +{ + USART1_OFF, + USART1_ON +}; + +enum usart2_t +{ + USART2_OFF, + USART2_ON +}; + +enum usart3_t +{ + USART3_OFF, + USART3_ON +}; + +enum twi_t +{ + TWI_OFF, + TWI_ON +}; + +enum usb_t +{ + USB_OFF, + USB_ON +}; + +class LowPowerClass +{ + public: + #if defined (__AVR_ATmega328P__) || defined (__AVR_ATmega168__) + void idle(period_t period, adc_t adc, timer2_t timer2, + timer1_t timer1, timer0_t timer0, spi_t spi, + usart0_t usart0, twi_t twi); + #elif defined __AVR_ATmega2560__ + void idle(period_t period, adc_t adc, timer5_t timer5, + timer4_t timer4, timer3_t timer3, timer2_t timer2, + timer1_t timer1, timer0_t timer0, spi_t spi, + usart3_t usart3, usart2_t usart2, usart1_t usart1, + usart0_t usart0, twi_t twi); + #elif defined __AVR_ATmega32U4__ + void idle(period_t period, adc_t adc, timer4_t timer4, timer3_t timer3, + timer1_t timer1, timer0_t timer0, spi_t spi, + usart1_t usart1, twi_t twi, usb_t usb); + #else + #error "Please ensure chosen MCU is either 328P, 32U4 or 2560." + #endif + void adcNoiseReduction(period_t period, adc_t adc, timer2_t timer2); + void powerDown(period_t period, adc_t adc, bod_t bod); + void powerSave(period_t period, adc_t adc, bod_t bod, timer2_t timer2); + void powerStandby(period_t period, adc_t adc, bod_t bod); + void powerExtStandby(period_t period, adc_t adc, bod_t bod, timer2_t timer2); +}; + +extern LowPowerClass LowPower; +#endif \ No newline at end of file diff --git a/libraries/MsTimer2/MsTimer2.cpp b/libraries/MySensors/utility/MsTimer2.cpp similarity index 100% rename from libraries/MsTimer2/MsTimer2.cpp rename to libraries/MySensors/utility/MsTimer2.cpp diff --git a/libraries/MsTimer2/MsTimer2.h b/libraries/MySensors/utility/MsTimer2.h similarity index 100% rename from libraries/MsTimer2/MsTimer2.h rename to libraries/MySensors/utility/MsTimer2.h diff --git a/libraries/PinChangeInt/PinChangeInt.h b/libraries/MySensors/utility/PinChangeInt.h similarity index 100% rename from libraries/PinChangeInt/PinChangeInt.h rename to libraries/MySensors/utility/PinChangeInt.h diff --git a/libraries/RF24/RF24.cpp b/libraries/MySensors/utility/RF24.cpp similarity index 60% rename from libraries/RF24/RF24.cpp rename to libraries/MySensors/utility/RF24.cpp index d54bb6e..2efb7bb 100644 --- a/libraries/RF24/RF24.cpp +++ b/libraries/MySensors/utility/RF24.cpp @@ -1,34 +1,40 @@ /* Copyright (C) 2011 J. Coliz - Portions Copyright (C) 2011 Greg Copeland 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. */ +#include "nRF24L01.h" +#include "RF24_config.h" #include "RF24.h" - /****************************************************************************/ -void RF24::csn(int mode) +void RF24::csn(bool mode) { // Minimum ideal SPI bus speed is 2x data rate // If we assume 2Mbs data rate and 16Mhz clock, a // divider of 4 is the minimum we want. // CLK:BUS 8Mhz:2Mhz, 16Mhz:4Mhz, or 20Mhz:5Mhz #ifdef ARDUINO - SPI.setBitOrder(MSBFIRST); - SPI.setDataMode(SPI_MODE0); - SPI.setClockDivider(SPI_CLOCK_DIV4); + #if !defined( __AVR_ATtiny85__ ) && !defined( __AVR_ATtiny84__) && !defined (__arm__) + SPI.setBitOrder(MSBFIRST); + SPI.setDataMode(SPI_MODE0); + SPI.setClockDivider(SPI_CLOCK_DIV2); + #endif #endif - digitalWrite(csn_pin,mode); + +#ifndef __arm__ + digitalWrite(csn_pin,mode); +#endif + } /****************************************************************************/ -void RF24::ce(int level) +void RF24::ce(bool level) { digitalWrite(ce_pin,level); } @@ -39,13 +45,23 @@ uint8_t RF24::read_register(uint8_t reg, uint8_t* buf, uint8_t len) { uint8_t status; +#if defined (__arm__) + status = SPI.transfer(csn_pin, R_REGISTER | ( REGISTER_MASK & reg ), SPI_CONTINUE ); + while ( len-- > 1 ){ + *buf++ = SPI.transfer(csn_pin,0xff, SPI_CONTINUE); + } + *buf++ = SPI.transfer(csn_pin,0xff); + +#else csn(LOW); status = SPI.transfer( R_REGISTER | ( REGISTER_MASK & reg ) ); - while ( len-- ) + while ( len-- ){ *buf++ = SPI.transfer(0xff); - + } csn(HIGH); +#endif + return status; } @@ -53,11 +69,18 @@ uint8_t RF24::read_register(uint8_t reg, uint8_t* buf, uint8_t len) uint8_t RF24::read_register(uint8_t reg) { + + #if defined (__arm__) + SPI.transfer(csn_pin, R_REGISTER | ( REGISTER_MASK & reg ) , SPI_CONTINUE); + uint8_t result = SPI.transfer(csn_pin,0xff); + #else csn(LOW); SPI.transfer( R_REGISTER | ( REGISTER_MASK & reg ) ); uint8_t result = SPI.transfer(0xff); csn(HIGH); + #endif + return result; } @@ -67,6 +90,14 @@ uint8_t RF24::write_register(uint8_t reg, const uint8_t* buf, uint8_t len) { uint8_t status; + #if defined (__arm__) + status = SPI.transfer(csn_pin, W_REGISTER | ( REGISTER_MASK & reg ), SPI_CONTINUE ); + while ( len-- > 1){ + SPI.transfer(csn_pin,*buf++, SPI_CONTINUE); + } + SPI.transfer(csn_pin,*buf++); + #else + csn(LOW); status = SPI.transfer( W_REGISTER | ( REGISTER_MASK & reg ) ); while ( len-- ) @@ -74,6 +105,8 @@ uint8_t RF24::write_register(uint8_t reg, const uint8_t* buf, uint8_t len) csn(HIGH); + #endif + return status; } @@ -85,59 +118,116 @@ uint8_t RF24::write_register(uint8_t reg, uint8_t value) IF_SERIAL_DEBUG(printf_P(PSTR("write_register(%02x,%02x)\r\n"),reg,value)); + #if defined (__arm__) + status = SPI.transfer(csn_pin, W_REGISTER | ( REGISTER_MASK & reg ), SPI_CONTINUE); + SPI.transfer(csn_pin,value); + #else + csn(LOW); status = SPI.transfer( W_REGISTER | ( REGISTER_MASK & reg ) ); SPI.transfer(value); csn(HIGH); + #endif + return status; } /****************************************************************************/ -uint8_t RF24::write_payload(const void* buf, uint8_t len, const uint8_t writeType) +uint8_t RF24::write_payload(const void* buf, uint8_t data_len, const uint8_t writeType) { uint8_t status; - const uint8_t* current = reinterpret_cast(buf); - uint8_t data_len = min(len,payload_size); + if(data_len > payload_size) data_len = payload_size; uint8_t blank_len = dynamic_payloads_enabled ? 0 : payload_size - data_len; //printf("[Writing %u bytes %u blanks]",data_len,blank_len); + #if defined (__arm__) + + status = SPI.transfer(csn_pin, writeType , SPI_CONTINUE); + + if(blank_len){ + while ( data_len--){ + SPI.transfer(csn_pin,*current++, SPI_CONTINUE); + } + while ( --blank_len ){ + SPI.transfer(csn_pin,0, SPI_CONTINUE); + } + SPI.transfer(csn_pin,0); + }else{ + while( --data_len ){ + SPI.transfer(csn_pin,*current++, SPI_CONTINUE); + } + SPI.transfer(csn_pin,*current); + } + + #else + csn(LOW); status = SPI.transfer( writeType ); - while ( data_len-- ) + while ( data_len-- ) { SPI.transfer(*current++); - while ( blank_len-- ) + } + while ( blank_len-- ) { SPI.transfer(0); + } csn(HIGH); + #endif + return status; } /****************************************************************************/ -uint8_t RF24::read_payload(void* buf, uint8_t len) +uint8_t RF24::read_payload(void* buf, uint8_t data_len) { uint8_t status; uint8_t* current = reinterpret_cast(buf); - uint8_t data_len = min(len,payload_size); + if(data_len > payload_size) data_len = payload_size; uint8_t blank_len = dynamic_payloads_enabled ? 0 : payload_size - data_len; - + //printf("[Reading %u bytes %u blanks]",data_len,blank_len); - ce(LOW); // <----- NEED THIS ALSO + + + #if defined (__arm__) + + status = SPI.transfer(csn_pin, R_RX_PAYLOAD, SPI_CONTINUE ); + + if( blank_len ){ + + while ( data_len-- ){ + *current++ = SPI.transfer(csn_pin,0xFF, SPI_CONTINUE); + } + while ( --blank_len ){ + SPI.transfer(csn_pin,0xFF, SPI_CONTINUE); + } + SPI.transfer(csn_pin,0xFF); + }else{ + while ( --data_len ){ + *current++ = SPI.transfer(csn_pin,0xFF, SPI_CONTINUE); + } + *current = SPI.transfer(csn_pin,0xFF); + } + + #else csn(LOW); status = SPI.transfer( R_RX_PAYLOAD ); - while ( data_len-- ) - *current++ = SPI.transfer(0xff); - while ( blank_len-- ) + while ( data_len-- ) { + *current++ = SPI.transfer(0xFF); + } + while ( blank_len-- ) { SPI.transfer(0xff); + } csn(HIGH); - ce(HIGH); //? ADDED IN + + #endif + return status; } @@ -145,39 +235,38 @@ uint8_t RF24::read_payload(void* buf, uint8_t len) uint8_t RF24::flush_rx(void) { - uint8_t status; - - csn(LOW); - status = SPI.transfer( FLUSH_RX ); - csn(HIGH); - - return status; + return spiTrans( FLUSH_RX ); } /****************************************************************************/ uint8_t RF24::flush_tx(void) { + return spiTrans( FLUSH_TX ); +} + +/****************************************************************************/ + +uint8_t RF24::spiTrans(uint8_t cmd){ + uint8_t status; + #if defined (__arm__) + status = SPI.transfer(csn_pin, cmd ); + #else csn(LOW); - status = SPI.transfer( FLUSH_TX ); + status = SPI.transfer( cmd ); csn(HIGH); - + #endif return status; + } /****************************************************************************/ uint8_t RF24::get_status(void) { - uint8_t status; - - csn(LOW); - status = SPI.transfer( NOP ); - csn(HIGH); - - return status; + return spiTrans(NOP); } /****************************************************************************/ @@ -240,8 +329,8 @@ void RF24::print_address_register(const char* name, uint8_t reg, uint8_t qty) /****************************************************************************/ RF24::RF24(uint8_t _cepin, uint8_t _cspin): - ce_pin(_cepin), csn_pin(_cspin), wide_band(false), p_variant(false), - payload_size(32), ack_payload_available(false), dynamic_payloads_enabled(false), + ce_pin(_cepin), csn_pin(_cspin), wide_band(false), p_variant(false), + payload_size(32), dynamic_payloads_enabled(false), pipe0_reading_address(0) { } @@ -259,17 +348,9 @@ void RF24::setChannel(uint8_t channel) /****************************************************************************/ -uint8_t RF24::getChannel( void ) -{ - return read_register( RF_CH ); -} - -/****************************************************************************/ - void RF24::setPayloadSize(uint8_t size) { - const uint8_t max_payload_size = 32; - payload_size = min(size,max_payload_size); + payload_size = min(size,32); } /****************************************************************************/ @@ -281,6 +362,8 @@ uint8_t RF24::getPayloadSize(void) /****************************************************************************/ +#if !defined (MINIMAL) + static const char rf24_datarate_e_str_0[] PROGMEM = "1MBPS"; static const char rf24_datarate_e_str_1[] PROGMEM = "2MBPS"; static const char rf24_datarate_e_str_2[] PROGMEM = "250KBPS"; @@ -307,7 +390,7 @@ static const char rf24_pa_dbm_e_str_0[] PROGMEM = "PA_MIN"; static const char rf24_pa_dbm_e_str_1[] PROGMEM = "PA_LOW"; static const char rf24_pa_dbm_e_str_2[] PROGMEM = "PA_HIGH"; static const char rf24_pa_dbm_e_str_3[] PROGMEM = "PA_MAX"; -static const char * const rf24_pa_dbm_e_str_P[] PROGMEM = { +static const char * const rf24_pa_dbm_e_str_P[] PROGMEM = { rf24_pa_dbm_e_str_0, rf24_pa_dbm_e_str_1, rf24_pa_dbm_e_str_2, @@ -330,25 +413,40 @@ void RF24::printDetails(void) print_byte_register(PSTR("CONFIG"),CONFIG); print_byte_register(PSTR("DYNPD/FEATURE"),DYNPD,2); +#if defined(__arm__) + printf_P(PSTR("Data Rate\t = %s\r\n"),pgm_read_word(&rf24_datarate_e_str_P[getDataRate()])); + printf_P(PSTR("Model\t\t = %s\r\n"),pgm_read_word(&rf24_model_e_str_P[isPVariant()])); + printf_P(PSTR("CRC Length\t = %s\r\n"),pgm_read_word(&rf24_crclength_e_str_P[getCRCLength()])); + printf_P(PSTR("PA Power\t = %s\r\n"),pgm_read_word(&rf24_pa_dbm_e_str_P[getPALevel()])); +#else printf_P(PSTR("Data Rate\t = %S\r\n"),pgm_read_word(&rf24_datarate_e_str_P[getDataRate()])); printf_P(PSTR("Model\t\t = %S\r\n"),pgm_read_word(&rf24_model_e_str_P[isPVariant()])); printf_P(PSTR("CRC Length\t = %S\r\n"),pgm_read_word(&rf24_crclength_e_str_P[getCRCLength()])); printf_P(PSTR("PA Power\t = %S\r\n"),pgm_read_word(&rf24_pa_dbm_e_str_P[getPALevel()])); +#endif } +#endif /****************************************************************************/ void RF24::begin(void) { // Initialize pins pinMode(ce_pin,OUTPUT); - pinMode(csn_pin,OUTPUT); - // Initialize SPI bus - SPI.begin(); - - ce(LOW); - csn(HIGH); + #if defined(__arm__) + SPI.begin(csn_pin); // Using the extended SPI features of the DUE + SPI.setClockDivider(csn_pin, 9); // Set the bus speed to 8.4mhz on Due + SPI.setBitOrder(csn_pin,MSBFIRST); // Set the bit order and mode specific to this device + SPI.setDataMode(csn_pin,SPI_MODE0); + ce(LOW); + //csn(HIGH); + #else + pinMode(csn_pin,OUTPUT); + SPI.begin(); + ce(LOW); + csn(HIGH); + #endif // Must allow the radio time to settle else configuration bits will not necessarily stick. // This is actually only required following power up but some settling time also appears to @@ -361,10 +459,10 @@ void RF24::begin(void) // Set 1500uS (minimum for 32B payload in ESB@250KBPS) timeouts, to make testing a little easier // WARNING: If this is ever lowered, either 250KBS mode with AA is broken or maximum packet // sizes must never be used. See documentation for a more complete explanation. - write_register(SETUP_RETR,(B0101 << ARD) | (B1111 << ARC)); + setRetries(5,15); - // Restore our default PA level - setPALevel( RF24_PA_MAX ) ; + // Reset value is MAX + //setPALevel( RF24_PA_MAX ) ; // Determine if this is a p or non-p RF24 module and then // reset our data rate back to default value. This works @@ -374,16 +472,16 @@ void RF24::begin(void) { p_variant = true ; } - + // Then set the data rate to the slowest (and most reliable) speed supported by all // hardware. setDataRate( RF24_1MBPS ) ; // Initialize CRC and request 2-byte (16bit) CRC setCRCLength( RF24_CRC_16 ) ; - - // Disable dynamic payloads, to match dynamic_payloads_enabled setting - write_register(DYNPD,0); + + // Disable dynamic payloads, to match dynamic_payloads_enabled setting - Reset value is 0 + //write_register(DYNPD,0); // Reset current status // Notice reset and flush is the last thing we do @@ -397,33 +495,36 @@ void RF24::begin(void) // Flush buffers flush_rx(); flush_tx(); + + powerUp(); //Power up by default when begin() is called + + // Enable PTX, do not write CE high so radio will remain in standby I mode ( 130us max to transition to RX or TX instead of 1500us from powerUp ) + // PTX should use only 22uA of power + write_register(CONFIG, ( read_register(CONFIG) ) & ~_BV(PRIM_RX) ); + + } /****************************************************************************/ void RF24::startListening(void) { - - // receiver on, transmitter off - write_register(CONFIG, read_register(CONFIG) | _BV(PRIM_RX)); - - // if not powered up already, power up the radio powerUp(); - + write_register(CONFIG, read_register(CONFIG) | _BV(PRIM_RX)); write_register(STATUS, _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); // Restore the pipe0 adddress, if exists - if (pipe0_reading_address) + if (pipe0_reading_address){ write_register(RX_ADDR_P0, reinterpret_cast(&pipe0_reading_address), 5); + } -#if 0 // Flush buffers flush_rx(); flush_tx(); -#endif // Go! ce(HIGH); + } /****************************************************************************/ @@ -433,107 +534,198 @@ void RF24::stopListening(void) ce(LOW); flush_tx(); flush_rx(); + write_register(CONFIG, ( read_register(CONFIG) ) & ~_BV(PRIM_RX) ); + } /****************************************************************************/ void RF24::powerDown(void) { + ce(LOW); // Guarantee CE is low on powerDown write_register(CONFIG,read_register(CONFIG) & ~_BV(PWR_UP)); } /****************************************************************************/ +//Power up now. Radio will not power down unless instructed by MCU for config changes etc. void RF24::powerUp(void) { - uint8_t cfg = read_register(CONFIG); - - // if not powered up then power up and wait for the radio to initialize - if (!(cfg & _BV(PWR_UP))) - { - //printf("RF24::powerUp - powering up radio\n"); - write_register(CONFIG,read_register(CONFIG) | _BV(PWR_UP)); - delayMicroseconds(400); - } + uint8_t cfg = read_register(CONFIG); + + // if not powered up then power up and wait for the radio to initialize + if (!(cfg & _BV(PWR_UP))){ + write_register(CONFIG,read_register(CONFIG) | _BV(PWR_UP)); + + // For nRF24L01+ to go from power down mode to TX or RX mode it must first pass through stand-by mode. + // There must be a delay of Tpd2stby (see Table 16.) after the nRF24L01+ leaves power down mode before + // the CEis set high. - Tpd2stby can be up to 5ms per the 1.0 datasheet + delay(5); + + } } /******************************************************************/ +//Similar to the previous write, clears the interrupt flags bool RF24::write( const void* buf, uint8_t len, const bool multicast ) { - bool result = false; + //Start Writing + startWrite(buf,len,multicast); - // Begin the write - startWrite( buf, len, multicast ); + //Wait until complete or failed + //ACK payloads that are handled improperly will cause this to hang + //If autoAck is ON, a payload has to be written prior to reading a payload, else write after reading a payload + while( ! ( get_status() & ( _BV(TX_DS) | _BV(MAX_RT) ))) { } - // ------------ - // At this point we could return from a non-blocking write, and then call - // the rest after an interrupt + uint8_t status = write_register(STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); - // Instead, we are going to block here until we get TX_DS (transmission completed and ack'd) - // or MAX_RT (maximum retries, transmission failed). Also, we'll timeout in case the radio - // is flaky and we get neither. - - // IN the end, the send should be blocking. It comes back in 60ms worst case. - // Generally much faster. - uint8_t observe_tx; - uint8_t status; - uint32_t sent_at = micros(); - const uint16_t timeout = getMaxTimeout() ; //us to wait for timeout - - // Monitor the send - do - { - status = read_register(OBSERVE_TX,&observe_tx,1); - IF_SERIAL_DEBUG(Serial.print(observe_tx,HEX)); + //Max retries exceeded + if( status & _BV(MAX_RT)){ + flush_tx(); //Only going to be 1 packet int the FIFO at a time using this method, so just flush + return 0; } - while( ! ( status & ( _BV(TX_DS) | _BV(MAX_RT) ) ) && ( micros() - sent_at < timeout ) ); + //TX OK 1 or 0 + return 1; +} - // The part above is what you could recreate with your own interrupt handler, - // and then call this when you got an interrupt - // ------------ - - // Call this when you get an interrupt - // The status tells us three things - // * The send was successful (TX_DS) - // * The send failed, too many retries (MAX_RT) - // * There is an ack packet waiting (RX_DR) - bool tx_ok, tx_fail; - whatHappened(tx_ok,tx_fail,ack_payload_available); - - //printf("%u%u%u\r\n",tx_ok,tx_fail,ack_payload_available); - - result = tx_ok; - IF_SERIAL_DEBUG(Serial.print(result?"...OK.":"...Failed")); - - // Handle the ack packet - if ( ack_payload_available ) - { - ack_payload_length = getDynamicPayloadSize(); - IF_SERIAL_DEBUG(Serial.print("[AckPacket]/")); - IF_SERIAL_DEBUG(Serial.println(ack_payload_length,DEC)); - } - - return result; +bool RF24::write( const void* buf, uint8_t len ){ + return write(buf,len,0); } /****************************************************************************/ -void RF24::startWrite( const void* buf, uint8_t len, const bool multicast ) +//For general use, the interrupt flags are not important to clear +bool RF24::writeBlocking( const void* buf, uint8_t len, uint32_t timeout ) { - // receiver off, transmitter on - write_register(CONFIG, read_register(CONFIG) & ~_BV(PRIM_RX)); + //Block until the FIFO is NOT full. + //Keep track of the MAX retries and set auto-retry if seeing failures + //This way the FIFO will fill up and allow blocking until packets go through + //The radio will auto-clear everything in the FIFO as long as CE remains high - // if not powered up already, power up the radio - powerUp(); + uint32_t timer = millis(); //Get the time that the payload transmission started - // Send the payload - Unicast (W_TX_PAYLOAD) or multicast (W_TX_PAYLOAD_NO_ACK) - write_payload( buf, len, - multicast?static_cast(W_TX_PAYLOAD_NO_ACK):static_cast(W_TX_PAYLOAD) ) ; + while( ( get_status() & ( _BV(TX_FULL) ))) { //Blocking only if FIFO is full. This will loop and block until TX is successful or timeout + + if( get_status() & _BV(MAX_RT)){ //If MAX Retries have been reached + reUseTX(); //Set re-transmit and clear the MAX_RT interrupt flag + if(millis() - timer > timeout){ return 0; } //If this payload has exceeded the user-defined timeout, exit and return 0 + } + + } + + //Start Writing + startFastWrite(buf,len,0); //Write the payload if a buffer is clear + + return 1; //Return 1 to indicate successful transmission +} + +/****************************************************************************/ + +void RF24::reUseTX(){ + write_register(STATUS,_BV(MAX_RT) ); //Clear max retry flag + spiTrans( REUSE_TX_PL ); + ce(LOW); //Re-Transfer packet + ce(HIGH); +} + +/****************************************************************************/ + +bool RF24::writeFast( const void* buf, uint8_t len, const bool multicast ) +{ + //Block until the FIFO is NOT full. + //Keep track of the MAX retries and set auto-retry if seeing failures + //Return 0 so the user can control the retrys and set a timer or failure counter if required + //The radio will auto-clear everything in the FIFO as long as CE remains high + + while( ( get_status() & ( _BV(TX_FULL) ))) { //Blocking only if FIFO is full. This will loop and block until TX is successful or fail + + if( get_status() & _BV(MAX_RT)){ + //reUseTX(); //Set re-transmit + write_register(STATUS,_BV(MAX_RT) ); //Clear max retry flag + return 0; //Return 0. The previous payload has been retransmitted + //From the user perspective, if you get a 0, just keep trying to send the same payload + } + + } + //Start Writing + startFastWrite(buf,len,multicast); + + return 1; +} + +bool RF24::writeFast( const void* buf, uint8_t len ){ + return writeFast(buf,len,0); +} + +/****************************************************************************/ + +//Per the documentation, we want to set PTX Mode when not listening. Then all we do is write data and set CE high +//In this mode, if we can keep the FIFO buffers loaded, packets will transmit immediately (no 130us delay) +//Otherwise we enter Standby-II mode, which is still faster than standby mode +//Also, we remove the need to keep writing the config register over and over and delaying for 150 us each time if sending a stream of data + +void RF24::startFastWrite( const void* buf, uint8_t len, const bool multicast){ //TMRh20 + + //write_payload( buf,len); + write_payload( buf, len,multicast ? W_TX_PAYLOAD_NO_ACK : W_TX_PAYLOAD ) ; + ce(HIGH); + +} + + +//Added the original startWrite back in so users can still use interrupts, ack payloads, etc +//Allows the library to pass all tests +void RF24::startWrite( const void* buf, uint8_t len, const bool multicast ){ + + // Send the payload + + //write_payload( buf, len ); + write_payload( buf, len, multicast?static_cast(W_TX_PAYLOAD_NO_ACK):static_cast(W_TX_PAYLOAD)) ; - // Allons! ce(HIGH); - delayMicroseconds(10); - ce(LOW); + ce(LOW); + + +} + +bool RF24::txStandBy(){ + + while( ! (read_register(FIFO_STATUS) & _BV(TX_EMPTY)) ){ + if( get_status() & _BV(MAX_RT)){ + write_register(STATUS,_BV(MAX_RT) ); + ce(LOW); + flush_tx(); //Non blocking, flush the data + return 0; + } + } + + ce(LOW); //Set STANDBY-I mode + return 1; +} + +bool RF24::txStandBy(uint32_t timeout){ + + uint32_t start = millis(); + + while( ! (read_register(FIFO_STATUS) & _BV(TX_EMPTY)) ){ + if( get_status() & _BV(MAX_RT)){ + write_register(STATUS,_BV(MAX_RT) ); + ce(LOW); //Set re-transmit + ce(HIGH); + if(millis() - start >= timeout){ + ce(LOW); flush_tx(); return 0; + } + } + } + ce(LOW); //Set STANDBY-I mode + return 1; + +} +/****************************************************************************/ + +void RF24::maskIRQ(bool tx, bool fail, bool rx){ + + write_register(CONFIG, ( read_register(CONFIG) ) | fail << MASK_MAX_RT | tx << MASK_TX_DS | rx << MASK_RX_DR ); } /****************************************************************************/ @@ -542,11 +734,18 @@ uint8_t RF24::getDynamicPayloadSize(void) { uint8_t result = 0; + #if defined (__arm__) + SPI.transfer(csn_pin, R_RX_PL_WID, SPI_CONTINUE ); + result = SPI.transfer(csn_pin,0xff); + #else csn(LOW); SPI.transfer( R_RX_PL_WID ); result = SPI.transfer(0xff); csn(HIGH); + #endif + + if(result > 32) { flush_rx(); return 0; } return result; } @@ -561,45 +760,35 @@ bool RF24::available(void) bool RF24::available(uint8_t* pipe_num) { - uint8_t status = get_status(); - // Too noisy, enable if you really want lots o data!! - //IF_SERIAL_DEBUG(print_status(status)); + //Check the FIFO buffer to see if data is waitng to be read - bool result = ( status & _BV(RX_DR) ); + if (!( read_register(FIFO_STATUS) & _BV(RX_EMPTY) )){ - if (result) - { // If the caller wants the pipe number, include that - if ( pipe_num ) + if ( pipe_num ){ + uint8_t status = get_status(); *pipe_num = ( status >> RX_P_NO ) & B111; - - // Clear the status bit - - // ??? Should this REALLY be cleared now? Or wait until we - // actually READ the payload? - - write_register(STATUS,_BV(RX_DR) ); - - // Handle ack payload receipt - if ( status & _BV(TX_DS) ) - { - write_register(STATUS,_BV(TX_DS)); - } + } + return 1; } - return result; + return 0; + + + } /****************************************************************************/ -bool RF24::read( void* buf, uint8_t len ) -{ +void RF24::read( void* buf, uint8_t len ){ + // Fetch the payload read_payload( buf, len ); - // was this the last of the data available? - return read_register(FIFO_STATUS) & _BV(RX_EMPTY); + //Clear the two possible interrupt flags with one command + write_register(STATUS,_BV(RX_DR) | _BV(MAX_RT) | _BV(TX_DS) ); + } /****************************************************************************/ @@ -626,8 +815,9 @@ void RF24::openWritingPipe(uint64_t value) write_register(RX_ADDR_P0, reinterpret_cast(&value), 5); write_register(TX_ADDR, reinterpret_cast(&value), 5); - const uint8_t max_payload_size = 32; - write_register(RX_PW_P0,min(payload_size,max_payload_size)); + //const uint8_t max_payload_size = 32; + //write_register(RX_PW_P0,min(payload_size,max_payload_size)); + write_register(RX_PW_P0,payload_size); } /****************************************************************************/ @@ -677,14 +867,21 @@ void RF24::closeReadingPipe( uint8_t pipe ) write_register(EN_RXADDR,read_register(EN_RXADDR) & ~_BV(pgm_read_byte(&child_pipe_enable[pipe]))); } + /****************************************************************************/ void RF24::toggle_features(void) { + + #if defined (__arm__) + SPI.transfer(csn_pin, ACTIVATE, SPI_CONTINUE ); + SPI.transfer(csn_pin, 0x73 ); + #else csn(LOW); SPI.transfer( ACTIVATE ); SPI.transfer( 0x73 ); csn(HIGH); + #endif } /****************************************************************************/ @@ -692,15 +889,10 @@ void RF24::toggle_features(void) void RF24::enableDynamicPayloads(void) { // Enable dynamic payload throughout the system - write_register(FEATURE,read_register(FEATURE) | _BV(EN_DPL) ); - // If it didn't work, the features are not enabled - if ( ! read_register(FEATURE) ) - { - // So enable them and try again toggle_features(); write_register(FEATURE,read_register(FEATURE) | _BV(EN_DPL) ); - } + IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n",read_register(FEATURE))); @@ -721,15 +913,8 @@ void RF24::enableAckPayload(void) // enable ack payload and dynamic payload features // - write_register(FEATURE,read_register(FEATURE) | _BV(EN_DYN_ACK) | _BV(EN_ACK_PAY) | _BV(EN_DPL) ); - - // If it didn't work, the features are not enabled - if ( ! read_register(FEATURE) ) - { - // So enable them and try again toggle_features(); - write_register(FEATURE,read_register(FEATURE) | _BV(EN_DYN_ACK) | _BV(EN_ACK_PAY) | _BV(EN_DPL) ); - } + write_register(FEATURE,read_register(FEATURE) | _BV(EN_ACK_PAY) | _BV(EN_DPL) ); IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n",read_register(FEATURE))); @@ -742,27 +927,50 @@ void RF24::enableAckPayload(void) /****************************************************************************/ +void RF24::enableDynamicAck(void){ + // + // enable dynamic ack features + // + toggle_features(); + write_register(FEATURE,read_register(FEATURE) | _BV(EN_DYN_ACK) ); + + IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n",read_register(FEATURE))); + + +} + +/****************************************************************************/ + void RF24::writeAckPayload(uint8_t pipe, const void* buf, uint8_t len) { const uint8_t* current = reinterpret_cast(buf); + uint8_t data_len = min(len,32); + + #if defined (__arm__) + SPI.transfer(csn_pin, W_ACK_PAYLOAD | ( pipe & B111 ), SPI_CONTINUE); + while ( data_len-- > 1 ){ + SPI.transfer(csn_pin,*current++, SPI_CONTINUE); + } + SPI.transfer(csn_pin,*current++); + + #else csn(LOW); - SPI.transfer( W_ACK_PAYLOAD | ( pipe & B111 ) ); - const uint8_t max_payload_size = 32; - uint8_t data_len = min(len,max_payload_size); + SPI.transfer(W_ACK_PAYLOAD | ( pipe & B111 ) ); + while ( data_len-- ) SPI.transfer(*current++); csn(HIGH); + + #endif } /****************************************************************************/ bool RF24::isAckPayloadAvailable(void) { - bool result = ack_payload_available; - ack_payload_available = false; - return result; + return ! read_register(FIFO_STATUS) & _BV(RX_EMPTY); } /****************************************************************************/ @@ -817,63 +1025,27 @@ bool RF24::testRPD(void) /****************************************************************************/ -void RF24::setPALevel(rf24_pa_dbm_e level) +void RF24::setPALevel(uint8_t level) { - uint8_t setup = read_register(RF_SETUP) ; - setup &= ~(_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ; - // switch uses RAM (evil!) - if ( level == RF24_PA_MAX ) - { - setup |= (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ; - } - else if ( level == RF24_PA_HIGH ) - { - setup |= _BV(RF_PWR_HIGH) ; - } - else if ( level == RF24_PA_LOW ) - { - setup |= _BV(RF_PWR_LOW); - } - else if ( level == RF24_PA_MIN ) - { - // nothing - } - else if ( level == RF24_PA_ERROR ) - { - // On error, go to maximum PA - setup |= (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ; + uint8_t setup = read_register(RF_SETUP) & 0b11111000; + + if(level > 3){ // If invalid level, go to max PA + level = RF24_PA_MAX << 1 + 1; // +1 to support the SI24R1 chip extra bit + }else{ + level = (level << 1) + 1; // Else set level as requested } - write_register( RF_SETUP, setup ) ; + + write_register( RF_SETUP, setup |= level ) ; // Write it to the chip } /****************************************************************************/ -rf24_pa_dbm_e RF24::getPALevel(void) +uint8_t RF24::getPALevel(void) { - rf24_pa_dbm_e result = RF24_PA_ERROR ; - uint8_t power = read_register(RF_SETUP) & (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ; - // switch uses RAM (evil!) - if ( power == (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ) - { - result = RF24_PA_MAX ; - } - else if ( power == _BV(RF_PWR_HIGH) ) - { - result = RF24_PA_HIGH ; - } - else if ( power == _BV(RF_PWR_LOW) ) - { - result = RF24_PA_LOW ; - } - else - { - result = RF24_PA_MIN ; - } - - return result ; + return (read_register(RF_SETUP) & (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH))) >> 1 ; } /****************************************************************************/ @@ -929,7 +1101,7 @@ rf24_datarate_e RF24::getDataRate( void ) { rf24_datarate_e result ; uint8_t dr = read_register(RF_SETUP) & (_BV(RF_DR_LOW) | _BV(RF_DR_HIGH)); - + // switch uses RAM (evil!) // Order matters in our case below if ( dr == _BV(RF_DR_LOW) ) @@ -955,11 +1127,11 @@ rf24_datarate_e RF24::getDataRate( void ) void RF24::setCRCLength(rf24_crclength_e length) { uint8_t config = read_register(CONFIG) & ~( _BV(CRCO) | _BV(EN_CRC)) ; - + // switch uses RAM (evil!) if ( length == RF24_CRC_DISABLED ) { - // Do nothing, we turned it off above. + // Do nothing, we turned it off above. } else if ( length == RF24_CRC_8 ) { @@ -1000,28 +1172,57 @@ void RF24::disableCRC( void ) } /****************************************************************************/ - void RF24::setRetries(uint8_t delay, uint8_t count) { write_register(SETUP_RETR,(delay&0xf)<> 4))) * (retries & 0x0f)) ; + USIDR = b; + USISR = _BV(USIOIF); + do + USICR = _BV(USIWM0) | _BV(USICS1) | _BV(USICLK) | _BV(USITC); + while ((USISR & _BV(USIOIF)) == 0); + return USIDR; - return to ; } -// vim:ai:cin:sts=2 sw=2 ft=cpp +void SPIClass::end() {} +void SPIClass::setDataMode(uint8_t mode){} +void SPIClass::setBitOrder(uint8_t bitOrder){} +void SPIClass::setClockDivider(uint8_t rate){} + +#endif diff --git a/libraries/RF24/RF24.h b/libraries/MySensors/utility/RF24.h similarity index 53% rename from libraries/RF24/RF24.h rename to libraries/MySensors/utility/RF24.h index 713b38e..55253bb 100644 --- a/libraries/RF24/RF24.h +++ b/libraries/MySensors/utility/RF24.h @@ -1,6 +1,5 @@ /* Copyright (C) 2011 J. Coliz - Portions Copyright (C) 2011 Greg Copeland This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License @@ -16,8 +15,6 @@ #ifndef __RF24_H__ #define __RF24_H__ -#include -#include /** * Power Amplifier level. @@ -52,12 +49,719 @@ private: bool wide_band; /* 2Mbs data rate in use? */ bool p_variant; /* False for RF24L01 and true for RF24L01P */ uint8_t payload_size; /**< Fixed size of payloads */ - bool ack_payload_available; /**< Whether there is an ack payload waiting */ - bool dynamic_payloads_enabled; /**< Whether dynamic payloads are enabled. */ - uint8_t ack_payload_length; /**< Dynamic size of pending ack payload. */ + bool dynamic_payloads_enabled; /**< Whether dynamic payloads are enabled. */ uint64_t pipe0_reading_address; /**< Last address set on pipe 0 for reading. */ -protected: +public: + + /** + * @name Primary public interface + * + * These are the main methods you need to operate the chip + */ + /**@{*/ + + /** + * Constructor + * + * Creates a new instance of this driver. Before using, you create an instance + * and send in the unique pins that this chip is connected to. + * + * @param _cepin The pin attached to Chip Enable on the RF module + * @param _cspin The pin attached to Chip Select + */ + RF24(uint8_t _cepin, uint8_t _cspin); + + /** + * Begin operation of the chip + * + * Call this in setup(), before calling any other methods. + * + * @note Optimization: The radio is partially configured in PTX mode + * when begin is called to make the transition to PTX mode simpler. + */ + void begin(void); + + /** + * Start listening on the pipes opened for reading. + * + * Be sure to call openReadingPipe() first. Do not call write() while + * in this mode, without first calling stopListening(). Call + * isAvailable() to check for incoming traffic, and read() to get it. + */ + void startListening(void); + + /** + * Stop listening for incoming messages + * + * Do this before calling write(). + * + * @note Optimization: The radio will be taken out of PRX mode as soon + * as listening is stopped. Enables quicker and simpler engaging of + * primary transmitter (PTX) mode. + */ + void stopListening(void); + + /** + * Test whether there are bytes available to be read + * + * @note Optimization: The available functino now checks the FIFO + * buffers directly for data instead of relying of interrupt flags. + * + * @note Interrupt flags will not be cleared until a payload is + * actually read from the FIFO + * + * @see txStandBy() + * @see startWrite() + * @see write() + * @see writeFast() + * + * @return True if there is a payload available, false if none is + */ + bool available(void); + + /** + * Read the payload + * + * The size of data read is the fixed payload size, see getPayloadSize() + * + * @note I specifically chose 'void*' as a data type to make it easier + * for beginners to use. No casting needed. + * + * @note Optimization: No longer boolean. Use available to + * determine if packets are available. Interrupt flags are now cleared + * during reads instead of when calling available(). + * + * @param buf Pointer to a buffer where the data should be written + * @param len Maximum number of bytes to read into the buffer + * @return No return value. Use available(). + */ + void read( void* buf, uint8_t len ); + + /** + * @note Optimization: Improved performance slightly + * Write to the open writing pipe + * + * Be sure to call openWritingPipe() first to set the destination + * of where to write to. + * + * This blocks until the message is successfully acknowledged by + * the receiver or the timeout/retransmit maxima are reached. In + * the current configuration, the max delay here is 60ms. + * + * The maximum size of data written is the fixed payload size, see + * getPayloadSize(). However, you can write less, and the remainder + * will just be filled with zeroes. + * + * TX/RX/RT interrupt flags will be cleared every time write is called + * + * @param buf Pointer to the data to be sent + * @param len Number of bytes to be sent + * @return True if the payload was delivered successfully false if not + */ + bool write( const void* buf, uint8_t len ); + + /** + * Open a pipe for writing + * + * Only one pipe can be open at once, but you can change the pipe + * you'll listen to. Do not call this while actively listening. + * Remember to stopListening() first. + * + * Addresses are 40-bit hex values, e.g.: + * + * @code + * openWritingPipe(0xF0F0F0F0F0); + * @endcode + * + * @param address The 40-bit address of the pipe to open. This can be + * any value whatsoever, as long as you are the only one writing to it + * and only one other radio is listening to it. Coordinate these pipe + * addresses amongst nodes on the network. + */ + void openWritingPipe(uint64_t address); + + /** + * Open a pipe for reading + * + * Up to 6 pipes can be open for reading at once. Open all the + * reading pipes, and then call startListening(). + * + * @see openWritingPipe + * + * @warning Pipes 1-5 should share the first 32 bits. + * Only the least significant byte should be unique, e.g. + * @code + * openReadingPipe(1,0xF0F0F0F0AA); + * openReadingPipe(2,0xF0F0F0F066); + * @endcode + * + * @warning Pipe 0 is also used by the writing pipe. So if you open + * pipe 0 for reading, and then startListening(), it will overwrite the + * writing pipe. Ergo, do an openWritingPipe() again before write(). + * + * @todo Enforce the restriction that pipes 1-5 must share the top 32 bits + * + * @param number Which pipe# to open, 0-5. + * @param address The 40-bit address of the pipe to open. + */ + void openReadingPipe(uint8_t number, uint64_t address); + + + + /** + * Close a pipe after it has been previously opened. + * Can be safely called without having previously opened a pipe. + * @param pipe Which pipe # to close, 0-5. + */ + void closeReadingPipe( uint8_t pipe ) ; + + /**@}*/ + /** + * @name Advanced Operation + * + * Methods you can use to drive the chip in more advanced ways + */ + /**@{*/ + + /** + * Print a giant block of debugging information to stdout + * + * @warning Does nothing if stdout is not defined. See fdevopen in stdio.h + */ + void printDetails(void); + + /** + * Test whether there are bytes available to be read in the + * FIFO buffers. This optimized version does not rely on interrupt + * flags, but checks the actual FIFO buffers. + * + * @note Optimization: Interrupt flags are no longer cleared when available is called, + * but will be reset only when the data is read from the FIFO buffers. + * + * @param[out] pipe_num Which pipe has the payload available + * @return True if there is a payload available, false if none is + */ + bool available(uint8_t* pipe_num); + + /** + * Enter low-power mode + * + * To return to normal power mode, either write() some data or + * startListening, or powerUp(). + * + * @note Optimization: The radio will never enter power down unless instructed + * by the MCU via this command. + */ + void powerDown(void); + + /** + * Leave low-power mode - making radio more responsive + * + * To return to low power mode, call powerDown(). + */ + void powerUp(void) ; + + /** + * Write for single NOACK writes. Disables acknowledgements/autoretries for a single write. + * + * @note enableDynamicAck() must be called to enable this feature + * + * Can be used with enableAckPayload() to request a response + * @see enableDynamicAck() + * @see setAutoAck() + * @see write() + * + * @param buf Pointer to the data to be sent + * @param len Number of bytes to be sent + * @param multicast Request ACK (0), NOACK (1) + */ + bool write( const void* buf, uint8_t len, const bool multicast ); + + /** + * @note Optimization: New Command * + * This will not block until the 3 FIFO buffers are filled with data. + * Once the FIFOs are full, writeFast will simply wait for success or + * timeout, and return 1 or 0 respectively. From a user perspective, just + * keep trying to send the same data. The library will keep auto retrying + * the current payload using the built in functionality. + * @warning It is important to never keep the nRF24L01 in TX mode for more than 4ms at a time. If the auto + * retransmit is enabled, the nRF24L01 is never in TX mode long enough to disobey this rule. Allow the FIFO + * to clear by issuing txStandBy() or ensure appropriate time between transmissions. + * + * ONLY max retry interrupt flags will be cleared when writeFast is called + * + * @code + * Example (Partial blocking): + * + * radio.writeFast(&buf,32); // Writes 1 payload to the buffers + * txStandBy(); // Returns 0 if failed. 1 if success. Blocks only until MAX_RT timeout or success. Data flushed on fail. + * + * radio.writeFast(&buf,32); // Writes 1 payload to the buffers + * txStandBy(1000); // Using extended timeouts, returns 1 if success. Retries failed payloads for 1 seconds before returning 0. + * @endcode + * + * @see txStandBy() + * @see write() + * @see writeBlocking() + * + * @param buf Pointer to the data to be sent + * @param len Number of bytes to be sent + * @return True if the payload was delivered successfully false if not + */ + bool writeFast( const void* buf, uint8_t len ); + + /** + * WriteFast for single NOACK writes. Disables acknowledgements/autoretries for a single write. + * + * @note enableDynamicAck() must be called to enable this feature + * @see enableDynamicAck() + * @see setAutoAck() + * + * @param buf Pointer to the data to be sent + * @param len Number of bytes to be sent + * @param multicast Request ACK (0) or NOACK (1) + */ + bool writeFast( const void* buf, uint8_t len, const bool multicast ); + + /** + * @note Optimization: New Command + * This function extends the auto-retry mechanism to any specified duration. + * It will not block until the 3 FIFO buffers are filled with data. + * If so the library will auto retry until a new payload is written + * or the user specified timeout period is reached. + * @warning It is important to never keep the nRF24L01 in TX mode for more than 4ms at a time. If the auto + * retransmit is enabled, the nRF24L01 is never in TX mode long enough to disobey this rule. Allow the FIFO + * to clear by issuing txStandBy() or ensure appropriate time between transmissions. + * + * ONLY max retry interrupt flags will be cleared when writeBlocking is called + * @code + * Example (Full blocking): + * + * radio.writeBlocking(&buf,32,1000); //Wait up to 1 second to write 1 payload to the buffers + * txStandBy(1000); //Wait up to 1 second for the payload to send. Return 1 if ok, 0 if failed. + * //Blocks only until user timeout or success. Data flushed on fail. + * @endcode + * @note If used from within an interrupt, the interrupt should be disabled until completion, and sei(); called to enable millis(). + * @see txStandBy() + * @see write() + * @see writeFast() + * + * @param buf Pointer to the data to be sent + * @param len Number of bytes to be sent + * @param timeout User defined timeout in milliseconds. + * @return True if the payload was loaded into the buffer successfully false if not + */ + bool writeBlocking( const void* buf, uint8_t len, uint32_t timeout ); + + /** + * @note Optimization: New Command + * This function should be called as soon as transmission is finished to + * drop the radio back to STANDBY-I mode. If not issued, the radio will + * remain in STANDBY-II mode which, per the data sheet, is not a recommended + * operating mode. + * + * @note When transmitting data in rapid succession, it is still recommended by + * the manufacturer to drop the radio out of TX or STANDBY-II mode if there is + * time enough between sends for the FIFOs to empty. + * + * Relies on built-in auto retry functionality. + * + * @code + * Example (Partial blocking): + * + * radio.writeFast(&buf,32); + * radio.writeFast(&buf,32); + * radio.writeFast(&buf,32); //Fills the FIFO buffers up + * bool ok = txStandBy(); //Returns 0 if failed. 1 if success. + * //Blocks only until MAX_RT timeout or success. Data flushed on fail. + * @endcode + * @see txStandBy(unsigned long timeout) + * @return True if transmission is successful + * + */ + bool txStandBy(); + + /** + * @note Optimization: New Command + * + * This function allows extended blocking and auto-retries per a user defined timeout + * @code + * Fully Blocking Example: + * + * radio.writeFast(&buf,32); + * radio.writeFast(&buf,32); + * radio.writeFast(&buf,32); //Fills the FIFO buffers up + * bool ok = txStandBy(1000); //Returns 0 if failed after 1 second of retries. 1 if success. + * //Blocks only until user defined timeout or success. Data flushed on fail. + * @endcode + * @note If used from within an interrupt, the interrupt should be disabled until completion, and sei(); called to enable millis(). + * @param timeout Number of milliseconds to retry failed payloads + * @return True if transmission is successful + * + */ + bool txStandBy(uint32_t timeout); + + /** + * Write an ack payload for the specified pipe + * + * The next time a message is received on @p pipe, the data in @p buf will + * be sent back in the acknowledgement. + * + * @warning According to the data sheet, only three of these can be pending + * at any time as there are only 3 FIFO buffers. + * + * @param pipe Which pipe# (typically 1-5) will get this response. + * @param buf Pointer to data that is sent + * @param len Length of the data to send, up to 32 bytes max. Not affected + * by the static payload set by setPayloadSize(). + */ + void writeAckPayload(uint8_t pipe, const void* buf, uint8_t len); + + /** + * Enable dynamic ACKs (single write multicasting) for chosen messages + * + * @note To enable full multicasting or per-pipe multicast, use setAutoAck() + * + * @warning This MUST be called prior to attempting single write NOACK calls + * @code + * radio.enableDynamicAck(); + * radio.write(&data,32,1); // Sends a payload with no acknowledgement requested + * radio.write(&data,32,0); // Sends a payload using auto-retry/autoACK + * @endcode + */ + void enableDynamicAck(); + + /** + * Determine if an ack payload was received in the most recent call to + * write(). + * + * Call read() to retrieve the ack payload. + * + * @note Optimization: Calling this function NO LONGER clears the interrupt + * flag. The new functionality checks the RX FIFO buffer for an ACK payload + * instead of relying on interrupt flags.Reading the payload will clear the flags. + * + * @return True if an ack payload is available. + */ + bool isAckPayloadAvailable(void); + + /** + * Call this when you get an interrupt to find out why + * + * Tells you what caused the interrupt, and clears the state of + * interrupts. + * + * @param[out] tx_ok The send was successful (TX_DS) + * @param[out] tx_fail The send failed, too many retries (MAX_RT) + * @param[out] rx_ready There is a message waiting to be read (RX_DS) + */ + void whatHappened(bool& tx_ok,bool& tx_fail,bool& rx_ready); + + /** + * Non-blocking write to the open writing pipe used for buffered writes + * + * @note Optimization: This function now leaves the CE pin high, so the radio + * will remain in TX or STANDBY-II Mode until a txStandBy() command is issued. + * This allows the chip to be used to its full potential in TX mode. + * @warning It is important to never keep the nRF24L01 in TX mode for more than 4ms at a time. If the auto + * retransmit is enabled, the nRF24L01 is never in TX mode long enough to disobey this rule. Allow the FIFO + * to clear by issuing txStandBy() or ensure appropriate time between transmissions. + * + * @see write() + * @see writeFast() + * @see startWrite() + * @see writeBlocking() + * + * For single noAck writes see: + * @see enableDynamicAck() + * @see setAutoAck() + * + * @param buf Pointer to the data to be sent + * @param len Number of bytes to be sent + * @param multicast Request ACK (0) or NOACK (1) + * @return True if the payload was delivered successfully false if not + */ + void startFastWrite( const void* buf, uint8_t len, const bool multicast ); + + /** + * Non-blocking write to the open writing pipe + * + * Just like write(), but it returns immediately. To find out what happened + * to the send, catch the IRQ and then call whatHappened(). + * + * @note Optimization: This function again behaves as it did previously for backwards-compatibility. + * with user code. The library uses startFastWrite() internally. + * This is mainly used for single-payload transactions. + * + * @see write() + * @see writeFast() + * @see startFastWrite() + * @see whatHappened() + * + * For single noAck writes see: + * @see enableDynamicAck() + * @see setAutoAck() + * + * @param buf Pointer to the data to be sent + * @param len Number of bytes to be sent + * @param multicast Request ACK (0) or NOACK (1) + * + */ + void startWrite( const void* buf, uint8_t len, const bool multicast ); + + /** + * Optimization: New Command + * + * This function is mainly used internally to take advantage of the auto payload + * re-use functionality of the chip, but can be beneficial to users as well. + * + * The function will instruct the radio to re-use the data in the FIFO buffers, + * and instructs the radio to re-send once the timeout limit has been reached. + * Used by writeFast and writeBlocking to initiate retries when a TX failure + * occurs. Retries are automatically initiated except with the standard write(). + * This way, data is not flushed from the buffer until switching between modes. + * + * @note This is to be used AFTER auto-retry fails if wanting to resend + * using the built-in payload reuse features. + * After issuing reUseTX(), it will keep reending the same payload forever or until + * a payload is written to the FIFO, or a flush_tx command is given. + */ + void reUseTX(); + + /** + * Empty the transmit buffer + * + * @return Current value of status register + */ + uint8_t flush_tx(void); + + /** + * Test whether there was a carrier on the line for the + * previous listening period. + * + * Useful to check for interference on the current channel. + * + * @return true if was carrier, false if not + */ + bool testCarrier(void); + + /** + * Test whether a signal (carrier or otherwise) greater than + * or equal to -64dBm is present on the channel. Valid only + * on nRF24L01P (+) hardware. On nRF24L01, use testCarrier(). + * + * Useful to check for interference on the current channel and + * channel hopping strategies. + * + * @return true if signal => -64dBm, false if not + */ + bool testRPD(void) ; + + /** + * Test whether this is a real radio, or a mock shim for + * debugging. Setting either pin to 0xff is the way to + * indicate that this is not a real radio. + * + * @return true if this is a legitimate radio + */ + bool isValid() { return ce_pin != 0xff && csn_pin != 0xff; } + + /** + * The radio will generate interrupt signals when a transmission is complete, + * a transmission fails, or a payload is received. This allows users to mask + * those interrupts to prevent them from generating a signal on the interrupt + * pin. + * + * @code + * Mask all interrupts except the receive interrupt: + * + * radio.maskIRQ(1,1,0); + * @endcode + * + * @param tx_ok Mask transmission complete interrupts + * @param tx_fail Mask transmit failure interrupts + * @param rx_ready Mask payload received interrupts + */ + void maskIRQ(bool tx_ok,bool tx_fail,bool rx_ready); + + /**@}*/ + + /**@}*/ + /** + * @name Optional Configurators + * + * Methods you can use to get or set the configuration of the chip. + * None are required. Calling begin() sets up a reasonable set of + * defaults. + */ + /**@{*/ + + /** + * Set the number and delay of retries upon failed submit + * + * @param delay How long to wait between each retry, in multiples of 250us, + * max is 15. 0 means 250us, 15 means 4000us. + * @param count How many retries before giving up, max 15 + */ + void setRetries(uint8_t delay, uint8_t count); + + /** + * Set RF communication channel + * + * @param channel Which RF channel to communicate on, 0-127 + */ + void setChannel(uint8_t channel); + + /** + * Set Static Payload Size + * + * This implementation uses a pre-stablished fixed payload size for all + * transmissions. If this method is never called, the driver will always + * transmit the maximum payload size (32 bytes), no matter how much + * was sent to write(). + * + * @todo Implement variable-sized payloads feature + * + * @param size The number of bytes in the payload + */ + void setPayloadSize(uint8_t size); + + /** + * Get Static Payload Size + * + * @see setPayloadSize() + * + * @return The number of bytes in the payload + */ + uint8_t getPayloadSize(void); + + /** + * Get Dynamic Payload Size + * + * For dynamic payloads, this pulls the size of the payload off + * the chip + * + * @note Optimization: Corrupt packets are now detected and flushed per the + * manufacturer. + * + * @return Payload length of last-received dynamic payload + */ + uint8_t getDynamicPayloadSize(void); + + /** + * Enable custom payloads on the acknowledge packets + * + * Ack payloads are a handy way to return data back to senders without + * manually changing the radio modes on both units. + * + * @see examples/pingpair_pl/pingpair_pl.pde + */ + void enableAckPayload(void); + + /** + * Enable dynamically-sized payloads + * + * This way you don't always have to send large packets just to send them + * once in a while. This enables dynamic payloads on ALL pipes. + * + * @see examples/pingpair_pl/pingpair_dyn.pde + */ + void enableDynamicPayloads(void); + + /** + * Determine whether the hardware is an nRF24L01+ or not. + * + * @return true if the hardware is nRF24L01+ (or compatible) and false + * if its not. + */ + bool isPVariant(void) ; + + /** + * Enable or disable auto-acknowlede packets + * + * This is enabled by default, so it's only needed if you want to turn + * it off for some reason. + * + * @param enable Whether to enable (true) or disable (false) auto-acks + */ + void setAutoAck(bool enable); + + /** + * Enable or disable auto-acknowlede packets on a per pipeline basis. + * + * AA is enabled by default, so it's only needed if you want to turn + * it off/on for some reason on a per pipeline basis. + * + * @param pipe Which pipeline to modify + * @param enable Whether to enable (true) or disable (false) auto-acks + */ + void setAutoAck( uint8_t pipe, bool enable ) ; + + /** + * Set Power Amplifier (PA) level to one of four levels: + * RF24_PA_MIN, RF24_PA_LOW, RF24_PA_HIGH and RF24_PA_MAX + * + * The power levels correspond to the following output levels respectively: + * NRF24L01: -18dBm, -12dBm,-6dBM, and 0dBm + * + * SI24R1: -6dBm, 0dBm, 3dBM, and 7dBm. + * + * @param level Desired PA level. + */ + void setPALevel ( uint8_t level ); + + /** + * Fetches the current PA level. + * + * NRF24L01: -18dBm, -12dBm, -6dBm and 0dBm + * SI24R1: -6dBm, 0dBm, 3dBm, 7dBm + * + * @return Returns values 0 to 3 representing the PA Level. + */ + uint8_t getPALevel( void ); + + /** + * Set the transmission data rate + * + * @warning setting RF24_250KBPS will fail for non-plus units + * + * @param speed RF24_250KBPS for 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS for 2Mbps + * @return true if the change was successful + */ + bool setDataRate(rf24_datarate_e speed); + + /** + * Fetches the transmission data rate + * + * @return Returns the hardware's currently configured datarate. The value + * is one of 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS, as defined in the + * rf24_datarate_e enum. + */ + rf24_datarate_e getDataRate( void ) ; + + /** + * Set the CRC length + * + * @param length RF24_CRC_8 for 8-bit or RF24_CRC_16 for 16-bit + */ + void setCRCLength(rf24_crclength_e length); + + /** + * Get the CRC length + * + * @return RF24_DISABLED if disabled or RF24_CRC_8 for 8-bit or RF24_CRC_16 for 16-bit + */ + rf24_crclength_e getCRCLength(void); + + /** + * Disable CRC validation + * + */ + void disableCRC( void ) ; + +private: + /** * @name Low-level internal interface. * @@ -77,7 +781,7 @@ protected: * * @param mode HIGH to take this unit off the SPI bus, LOW to put it on */ - void csn(int mode); + void csn(bool mode); /** * Set chip enable @@ -85,7 +789,7 @@ protected: * @param level HIGH to actively begin transmission or LOW to put in standby. Please see data sheet * for a much more detailed description of this pin. */ - void ce(int level); + void ce(bool level); /** * Read a chunk of data in from a register @@ -153,13 +857,6 @@ protected: */ uint8_t flush_rx(void); - /** - * Empty the transmit buffer - * - * @return Current value of status register - */ - uint8_t flush_tx(void); - /** * Retrieve the current status of the chip * @@ -218,492 +915,124 @@ protected: * are enabled. See the datasheet for details. */ void toggle_features(void); + + /** + * Built in spi transfer function to simplify repeating code repeating code + */ + + uint8_t spiTrans(uint8_t cmd); /**@}*/ -public: - /** - * @name Primary public interface - * - * These are the main methods you need to operate the chip - */ - /**@{*/ - - /** - * Constructor - * - * Creates a new instance of this driver. Before using, you create an instance - * and send in the unique pins that this chip is connected to. - * - * @param _cepin The pin attached to Chip Enable on the RF module - * @param _cspin The pin attached to Chip Select - */ - RF24(uint8_t _cepin, uint8_t _cspin); - - /** - * Begin operation of the chip - * - * Call this in setup(), before calling any other methods. - */ - void begin(void); - - /** - * Start listening on the pipes opened for reading. - * - * Be sure to call openReadingPipe() first. Do not call write() while - * in this mode, without first calling stopListening(). Call - * isAvailable() to check for incoming traffic, and read() to get it. - */ - void startListening(void); - - /** - * Stop listening for incoming messages - * - * Do this before calling write(). - */ - void stopListening(void); - - /** - * Write to the open writing pipe - * - * Be sure to call openWritingPipe() first to set the destination - * of where to write to. - * - * This blocks until the message is successfully acknowledged by - * the receiver or the timeout/retransmit maxima are reached. In - * the current configuration, the max delay here is 60ms. - * - * The maximum size of data written is the fixed payload size, see - * getPayloadSize(). However, you can write less, and the remainder - * will just be filled with zeroes. - * - * @param buf Pointer to the data to be sent - * @param len Number of bytes to be sent - * @param multicast true or false. True, buffer will be multicast; ignoring retry/timeout - * @return True if the payload was delivered successfully false if not - * for multicast payloads, true only means it was transmitted. - */ - bool write( const void* buf, uint8_t len, const bool multicast=false ); - - /** - * Test whether there are bytes available to be read - * - * @return True if there is a payload available, false if none is - */ - bool available(void); - - /** - * Read the payload - * - * Return the last payload received - * - * The size of data read is the fixed payload size, see getPayloadSize() - * - * @note I specifically chose 'void*' as a data type to make it easier - * for beginners to use. No casting needed. - * - * @param buf Pointer to a buffer where the data should be written - * @param len Maximum number of bytes to read into the buffer - * @return True if the payload was delivered successfully false if not - */ - bool read( void* buf, uint8_t len ); - - /** - * Open a pipe for writing - * - * Only one pipe can be open at once, but you can change the pipe - * you'll listen to. Do not call this while actively listening. - * Remember to stopListening() first. - * - * Addresses are 40-bit hex values, e.g.: - * - * @code - * openWritingPipe(0xF0F0F0F0F0); - * @endcode - * - * @param address The 40-bit address of the pipe to open. This can be - * any value whatsoever, as long as you are the only one writing to it - * and only one other radio is listening to it. Coordinate these pipe - * addresses amongst nodes on the network. - */ - void openWritingPipe(uint64_t address); - - /** - * Open a pipe for reading - * - * Up to 6 pipes can be open for reading at once. Open all the - * reading pipes, and then call startListening(). - * - * @see openWritingPipe - * - * @warning Pipes 1-5 should share the first 32 bits. - * Only the least significant byte should be unique, e.g. - * @code - * openReadingPipe(1,0xF0F0F0F0AA); - * openReadingPipe(2,0xF0F0F0F066); - * @endcode - * - * @warning Pipe 0 is also used by the writing pipe. So if you open - * pipe 0 for reading, and then startListening(), it will overwrite the - * writing pipe. Ergo, do an openWritingPipe() again before write(). - * - * @warning Pipe 0 is also used as the multicast address pipe. Pipe 1 - * is the unicast pipe address. - * - * @todo Enforce the restriction that pipes 1-5 must share the top 32 bits - * - * @param number Which pipe# to open, 0-5. - * @param address The 40-bit address of the pipe to open. - */ - void openReadingPipe(uint8_t number, uint64_t address); - - - /** - * Close a pipe after it has been previously opened. - * Can be safely called without having previously opened a pipe. - * @param pipe Which pipe # to close, 0-5. - */ - void closeReadingPipe( uint8_t pipe ) ; - - /**@}*/ - /** - * @name Optional Configurators - * - * Methods you can use to get or set the configuration of the chip. - * None are required. Calling begin() sets up a reasonable set of - * defaults. - */ - /**@{*/ - /** - * Set the number and delay of retries upon failed submit - * - * @param delay How long to wait between each retry, in multiples of 250us, - * max is 15. 0 means 250us, 15 means 4000us. - * @param count How many retries before giving up, max 15 - */ - void setRetries(uint8_t delay, uint8_t count); - - /**@{*/ - /** - * Get delay and count values of the radio - * - * @param high and low nibbles of delay and count as currently configured on - * the radio. Valid ranges for both nibbles are 0x00-0x0f. The delay nibble - * translates as 0=250us, 15=4000us, in bit multiples of 250us. - */ - uint8_t getRetries( void ) ; - - /** - * Set RF communication channel - * - * @param channel Which RF channel to communicate on, 0-127 - */ - void setChannel(uint8_t channel); - - /** - * Get RF communication channel - * - * @param channel To which RF channel radio is current tuned, 0-127 - */ - uint8_t getChannel(void); - - /** - * Set Static Payload Size - * - * This implementation uses a pre-stablished fixed payload size for all - * transmissions. If this method is never called, the driver will always - * transmit the maximum payload size (32 bytes), no matter how much - * was sent to write(). - * - * @todo Implement variable-sized payloads feature - * - * @param size The number of bytes in the payload - */ - void setPayloadSize(uint8_t size); - - /** - * Get Static Payload Size - * - * @see setPayloadSize() - * - * @return The number of bytes in the payload - */ - uint8_t getPayloadSize(void); - - /** - * Get Dynamic Payload Size - * - * For dynamic payloads, this pulls the size of the payload off - * the chip - * - * @return Payload length of last-received dynamic payload - */ - uint8_t getDynamicPayloadSize(void); - - /** - * Enable custom payloads on the acknowledge packets - * - * Ack payloads are a handy way to return data back to senders without - * manually changing the radio modes on both units. - * - * @warning Do note, multicast payloads will not trigger ack payloads. - * - * @see examples/pingpair_pl/pingpair_pl.pde - */ - void enableAckPayload(void); - - /** - * Enable dynamically-sized payloads - * - * This way you don't always have to send large packets just to send them - * once in a while. This enables dynamic payloads on ALL pipes. - * - * @see examples/pingpair_pl/pingpair_dyn.pde - */ - void enableDynamicPayloads(void); - - /** - * Determine whether the hardware is an nRF24L01+ or not. - * - * @return true if the hardware is nRF24L01+ (or compatible) and false - * if its not. - */ - bool isPVariant(void) ; - - /** - * Enable or disable auto-acknowlede packets - * - * This is enabled by default, so it's only needed if you want to turn - * it off for some reason. - * - * @param enable Whether to enable (true) or disable (false) auto-acks - */ - void setAutoAck(bool enable); - - /** - * Enable or disable auto-acknowlede packets on a per pipeline basis. - * - * AA is enabled by default, so it's only needed if you want to turn - * it off/on for some reason on a per pipeline basis. - * - * @param pipe Which pipeline to modify - * @param enable Whether to enable (true) or disable (false) auto-acks - */ - void setAutoAck( uint8_t pipe, bool enable ) ; - - /** - * Set Power Amplifier (PA) level to one of four levels. - * Relative mnemonics have been used to allow for future PA level - * changes. According to 6.5 of the nRF24L01+ specification sheet, - * they translate to: RF24_PA_MIN=-18dBm, RF24_PA_LOW=-12dBm, - * RF24_PA_HIGH=-6dBM, and RF24_PA_MAX=0dBm. - * - * @param level Desired PA level. - */ - void setPALevel( rf24_pa_dbm_e level ) ; - - /** - * Fetches the current PA level. - * - * @return Returns a value from the rf24_pa_dbm_e enum describing - * the current PA setting. Please remember, all values represented - * by the enum mnemonics are negative dBm. See setPALevel for - * return value descriptions. - */ - rf24_pa_dbm_e getPALevel( void ) ; - - /** - * Set the transmission data rate - * - * @warning setting RF24_250KBPS will fail for non-plus units - * - * @param speed RF24_250KBPS for 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS for 2Mbps - * @return true if the change was successful - */ - bool setDataRate(rf24_datarate_e speed); - - /** - * Fetches the transmission data rate - * - * @return Returns the hardware's currently configured datarate. The value - * is one of 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS, as defined in the - * rf24_datarate_e enum. - */ - rf24_datarate_e getDataRate( void ) ; - - /** - * Set the CRC length - * - * @param length RF24_CRC_8 for 8-bit or RF24_CRC_16 for 16-bit - */ - void setCRCLength(rf24_crclength_e length); - - /** - * Get the CRC length - * - * @return RF24_DISABLED if disabled or RF24_CRC_8 for 8-bit or RF24_CRC_16 for 16-bit - */ - rf24_crclength_e getCRCLength(void); - - /** - * Disable CRC validation - * - */ - void disableCRC( void ) ; - - /**@}*/ - /** - * @name Advanced Operation - * - * Methods you can use to drive the chip in more advanced ways - */ - /**@{*/ - - /** - * Print a giant block of debugging information to stdout - * - * @warning Does nothing if stdout is not defined. See fdevopen in stdio.h - */ - void printDetails(void); - - /** - * Enter low-power mode - * - * To return to normal power mode, either write() some data or - * startListening, or powerUp(). - */ - void powerDown(void); - - /** - * Leave low-power mode - making radio more responsive - * - * To return to low power mode, call powerDown(). - */ - void powerUp(void) ; - - /** - * Test whether there are bytes available to be read - * - * Use this version to discover on which pipe the message - * arrived. - * - * @param[out] pipe_num Which pipe has the payload available - * @return True if there is a payload available, false if none is - */ - bool available(uint8_t* pipe_num); - - /** - * Non-blocking write to the open writing pipe - * - * Just like write(), but it returns immediately. To find out what happened - * to the send, catch the IRQ and then call whatHappened(). - * - * @see write() - * @see whatHappened() - * - * @param buf Pointer to the data to be sent - * @param len Number of bytes to be sent - * @param multicast true or false. True, buffer will be multicast; ignoring retry/timeout - */ - void startWrite( const void* buf, uint8_t len, const bool multicast=false ); - - /** - * Write an ack payload for the specified pipe - * - * The next time a message is received on @p pipe, the data in @p buf will - * be sent back in the acknowledgement. - * - * @warning Do note, multicast payloads will not trigger ack payloads. - * - * @warning According to the data sheet, only three of these can be pending - * at any time. I have not tested this. - * - * @param pipe Which pipe# (typically 1-5) will get this response. - * @param buf Pointer to data that is sent - * @param len Length of the data to send, up to 32 bytes max. Not affected - * by the static payload set by setPayloadSize(). - */ - void writeAckPayload(uint8_t pipe, const void* buf, uint8_t len); - - /** - * Determine if an ack payload was received in the most recent call to - * write(). - * - * Call read() to retrieve the ack payload. - * - * @warning Calling this function clears the internal flag which indicates - * a payload is available. If it returns true, you must read the packet - * out as the very next interaction with the radio, or the results are - * undefined. - * - * @return True if an ack payload is available. - */ - bool isAckPayloadAvailable(void); - - /** - * Call this when you get an interrupt to find out why - * - * Tells you what caused the interrupt, and clears the state of - * interrupts. - * - * @param[out] tx_ok The send was successful (TX_DS) - * @param[out] tx_fail The send failed, too many retries (MAX_RT) - * @param[out] rx_ready There is a message waiting to be read (RX_DS) - */ - void whatHappened(bool& tx_ok,bool& tx_fail,bool& rx_ready); - - /** - * Test whether there was a carrier on the line for the - * previous listening period. - * - * Useful to check for interference on the current channel. - * - * @return true if was carrier, false if not - */ - bool testCarrier(void); - - /** - * Test whether a signal (carrier or otherwise) greater than - * or equal to -64dBm is present on the channel. Valid only - * on nRF24L01P (+) hardware. On nRF24L01, use testCarrier(). - * - * Useful to check for interference on the current channel and - * channel hopping strategies. - * - * @return true if signal => -64dBm, false if not - */ - bool testRPD(void) ; - - /** - * Test whether this is a real radio, or a mock shim for - * debugging. Setting either pin to 0xff is the way to - * indicate that this is not a real radio. - * - * @return true if this is a legitimate radio - */ - bool isValid() { return ce_pin != 0xff && csn_pin != 0xff; } - - /** - * Calculate the maximum timeout in us based on current hardware - * configuration. - * - * @return us of maximum timeout; accounting for retries - */ - uint16_t getMaxTimeout(void) ; - - /**@}*/ }; /** - * @example GettingStarted.pde + * @example GettingStarted.ino + * Updated: TMRh20 2014
* - * This is an example which corresponds to my "Getting Started" blog post: - * Getting Started with nRF24L01+ on Arduino. + * This is an example of how to use the RF24 class to communicate on a basic level. Write this sketch to two + * different nodes. Put one of the nodes into 'transmit' mode by connecting with the serial monitor and
+ * sending a 'T'. The ping node sends the current time to the pong node, which responds by sending the value + * back. The ping node can then see how long the whole cycle took.
+ * @note For a more efficient call-response scenario see the GettingStarted_CallResponse.ino example. + * @note When switching between sketches, the radio may need to be powered down to clear settings that are not "un-set" otherwise + */ + +/** + * @example GettingStarted_CallResponse.ino + * New: TMRh20 2014
* - * It is an example of how to use the RF24 class. Write this sketch to two - * different nodes. Put one of the nodes into 'transmit' mode by connecting - * with the serial monitor and sending a 'T'. The ping node sends the current - * time to the pong node, which responds by sending the value back. The ping - * node can then see how long the whole cycle took. + * This example continues to make use of all the normal functionality of the radios including + * the auto-ack and auto-retry features, but allows ack-payloads to be written optionlly as well.
+ * This allows very fast call-response communication, with the responding radio never having to + * switch out of Primary Receiver mode to send back a payload, but having the option to switch to
+ * primary transmitter if wanting to initiate communication instead of respond to a commmunication. + */ + +/** + * @example Transfer.ino + * New: TMRh20
+ * This example demonstrates half-rate transfer using the FIFO buffers
+ * + * It is an example of how to use the RF24 class. Write this sketch to two + * different nodes. Put one of the nodes into 'transmit' mode by connecting
+ * with the serial monitor and sending a 'T'. The data transfer will begin, + * with the receiver displaying the payload count. (32Byte Payloads)
+ */ + +/** + * @example TransferTimeouts.ino + * New: TMRh20
+ * This example demonstrates the use of and extended timeout period and + * auto-retries/auto-reUse to increase reliability in noisy or low signal scenarios.
+ * + * Write this sketch to two different nodes. Put one of the nodes into 'transmit' + * mode by connecting with the serial monitor and sending a 'T'. The data
+ * transfer will begin, with the receiver displaying the payload count and the + * data transfer rate. + */ + +/** + * @example starping.pde + * + * This sketch is a more complex example of using the RF24 library for Arduino. + * Deploy this on up to six nodes. Set one as the 'pong receiver' by tying the + * role_pin low, and the others will be 'ping transmit' units. The ping units + * unit will send out the value of millis() once a second. The pong unit will + * respond back with a copy of the value. Each ping unit can get that response + * back, and determine how long the whole cycle took. + * + * This example requires a bit more complexity to determine which unit is which. + * The pong receiver is identified by having its role_pin tied to ground. + * The ping senders are further differentiated by a byte in eeprom. + */ + +/** + * @example pingpair_ack.ino + * Update: TMRh20
+ * This example continues to make use of all the normal functionality of the radios including + * the auto-ack and auto-retry features, but allows ack-payloads to be written optionlly as well.
+ * This allows very fast call-response communication, with the responding radio never having to + * switch out of Primary Receiver mode to send back a payload, but having the option to if wanting
+ * to initiate communication instead of respond to a commmunication. + */ + +/** + * @example pingpair_irq.ino + * Update: TMRh20
+ * This is an example of how to user interrupts to interact with the radio, and a demonstration + * of how to use them to sleep when receiving, and not miss any payloads.
+ * The pingpair_sleepy example expands on sleep functionality with a timed sleep option for the transmitter. + * Sleep functionality is built directly into my fork of the RF24Network library
+ */ + +/** + * @example pingpair_sleepy.ino + * Update: TMRh20
+ * This is an example of how to use the RF24 class to create a battery- + * efficient system. It is just like the GettingStarted_CallResponse example, but the
+ * ping node powers down the radio and sleeps the MCU after every + * ping/pong cycle, and the receiver sleeps between payloads.
+ */ + +/** + * @example pingpair_dyn.ino + * + * This is an example of how to use payloads of a varying (dynamic) size. + */ + +/** + * @example pingpair_maple.pde + * + * This is an example of how to use the RF24 class on the Maple. For a more + * detailed explanation, see my blog post: + * nRF24L01+ Running on Maple + * + * It will communicate well to an Arduino-based unit as well, so it's not for only Maple-to-Maple communication. + * + * Write this sketch to two different nodes, + * connect the role_pin to ground on one. The ping node sends the current time to the pong node, + * which responds by sending the value back. The ping node can then see how long the whole cycle + * took. */ /** @@ -725,71 +1054,7 @@ public: */ /** - * @example pingpair.pde - * - * This is an example of how to use the RF24 class. Write this sketch to two - * different nodes, connect the role_pin to ground on one. The ping node sends - * the current time to the pong node, which responds by sending the value back. - * The ping node can then see how long the whole cycle took. - */ - -/** - * @example pingpair_maple.pde - * - * This is an example of how to use the RF24 class on the Maple. For a more - * detailed explanation, see my blog post: - * nRF24L01+ Running on Maple - * - * It will communicate well to an Arduino-based unit as well, so it's not for only Maple-to-Maple communication. - * - * Write this sketch to two different nodes, - * connect the role_pin to ground on one. The ping node sends the current time to the pong node, - * which responds by sending the value back. The ping node can then see how long the whole cycle - * took. - */ - -/** - * @example starping.pde - * - * This sketch is a more complex example of using the RF24 library for Arduino. - * Deploy this on up to six nodes. Set one as the 'pong receiver' by tying the - * role_pin low, and the others will be 'ping transmit' units. The ping units - * unit will send out the value of millis() once a second. The pong unit will - * respond back with a copy of the value. Each ping unit can get that response - * back, and determine how long the whole cycle took. - * - * This example requires a bit more complexity to determine which unit is which. - * The pong receiver is identified by having its role_pin tied to ground. - * The ping senders are further differentiated by a byte in eeprom. - */ - -/** - * @example pingpair_pl.pde - * - * This is an example of how to do two-way communication without changing - * transmit/receive modes. Here, a payload is set to the transmitter within - * the Ack packet of each transmission. Note that the payload is set BEFORE - * the sender's message arrives. - */ - -/** - * @example pingpair_irq.pde - * - * This is an example of how to user interrupts to interact with the radio. - * It builds on the pingpair_pl example, and uses ack payloads. - */ - -/** - * @example pingpair_sleepy.pde - * - * This is an example of how to use the RF24 class to create a battery- - * efficient system. It is just like the pingpair.pde example, but the - * ping node powers down the radio and sleeps the MCU after every - * ping/pong cycle. - */ - -/** - * @example scanner.pde + * @example scanner.ino * * Example to detect interference on the various channels available. * This is a good diagnostic tool to check whether you're picking a @@ -800,64 +1065,68 @@ public: */ /** - * @mainpage Driver for nRF24L01(+) 2.4GHz Wireless Transceiver + * @mainpage Optimized High Speed Driver for nRF24L01(+) 2.4GHz Wireless Transceiver * * @section Goals Design Goals - * - * This library is designed to be... - * @li Maximally compliant with the intended operation of the chip - * @li Easy for beginners to use + * + * This library fork is designed to be... + * @li More compliant with the manufacturer specified operation of the chip, while allowing advanced users + * to work outside the reccommended operation. + * @li Utilize the capabilities of the radio to their full potential via Arduino + * @li More reliable, responsive and feature rich + * @li Easy for beginners to use, with well documented examples and features * @li Consumed with a public interface that's similiar to other Arduino standard libraries * * @section News News - * - * NOW COMPATIBLE WITH ARDUINO 1.0 - The 'master' branch and all examples work with both Arduino 1.0 and earlier versions. - * Please open an issue if you find any problems using it with any version of Arduino. * - * NOW COMPATIBLE WITH MAPLE - RF24 has been tested with the - * Maple Native, - * and should work with any Maple board. See the pingpair_maple example. - * Note that only the pingpair_maple example has been tested on Maple, although - * the others can certainly be adapted. + * April 2014: Official Release: Still some work to do, but most benefits have been realized
+ * - The library has been tweaked to allow full use of the FIFO buffers for maximum transfer speeds + * - Changes to read() and available () functionality have increased reliability and response + * - Extended timeout periods have been added to aid in noisy or otherwise unreliable environments + * - Delays have been removed where possible to ensure maximum efficiency + * - Full Due support with extended SPI functions + * - ATTiny 24/44/84 25/45/85 now supported. + * - More! See the links below and class documentation for more info. * + * If issues are discovered with the documentation, please report them here: here * @section Useful Useful References - * + * * Please refer to: * - * @li Documentation Main Page - * @li RF24 Class Documentation - * @li Source Code - * @li Downloads Page + * @li Documentation Main Page + * @li RF24 Class Documentation + * @li Source Code + * @li Downloads Page * @li Chip Datasheet + * @li Original Library * * This chip uses the SPI bus, plus two chip control pins. Remember that pin 10 must still remain an output, or * the SPI hardware will go into 'slave' mode. * + * @section Board_Support Board Support + * + * Most standard Arduino based boards are supported: + * - ATMega 328 based boards (Uno, Nano, etc) + * - Mega Boards (1280, 2560, etc) + * - ARM based boards (Arduino Due) Note: Do not include printf.h or use printf begin. This functionality is already present. Must use one of the + * hardware SS/CSN pins as extended SPI methods are used. + * Initial Due support taken from https://github.com/mcrosson/RF24/tree/due + * - ATTiny board support added from https://github.com/jscrane/RF24 + * Note: ATTiny support is built into the library. Do not include SPI.h.
+ * ATTiny 85: D0(pin 5): MISO, D1(pin6) MOSI, D2(pin7) SCK, D3(pin2):CSN/SS, D4(pin3): CE
+ * ATTiny 84: PA6:MISO, PA5:MOSI, PA4:SCK, PA7:CSN/SS, CE as desired
+ * * @section More More Information * - * @subpage FAQ + * @section Info and Projects * - * @section Projects Projects - * - * Stuff I have built with RF24 - * - * RF24 Getting Started - Finished Product - * - * Getting Started with nRF24L01+ on Arduino - * - * Nordic FOB and nRF24L01+ - * - * Using the Sparkfun Nordic FOB - * - * RF Duinode V3 (2V4) - * - * Low-Power Wireless Sensor Node - * - * nRF24L01+ connected to Leaf Labs Maple Native - * - * nRF24L01+ Running on Maple + * @li Project blog: + * @li TMRh20.blogspot.com + * @li RF24 Wireless Audio Library (Coming Soon) + * @li Optimized RF24 Network Layer + * @li ManiacBug on GitHub (Original Library Author) */ #endif // __RF24_H__ -// vim:ai:cin:sts=2 sw=2 ft=cpp + diff --git a/libraries/MySensors/utility/RF24_config.h b/libraries/MySensors/utility/RF24_config.h new file mode 100644 index 0000000..b7154a5 --- /dev/null +++ b/libraries/MySensors/utility/RF24_config.h @@ -0,0 +1,129 @@ + +/* + Copyright (C) 2011 J. Coliz + + 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. + + Added Arduino Due support from https://github.com/mcrosson/ + */ + +#ifndef __RF24_CONFIG_H__ +#define __RF24_CONFIG_H__ + + #if ARDUINO < 100 + #include + #else + #include + #endif + + #include + + //TMRh20: + //#define MINIMAL + + // Define _BV for non-Arduino platforms and for Arduino DUE +#if defined (ARDUINO) + #include +#else + #include + #include + #include + extern HardwareSPI SPI; + #define _BV(x) (1<<(x)) + #endif + + + #undef SERIAL_DEBUG + #ifdef SERIAL_DEBUG + #define IF_SERIAL_DEBUG(x) ({x;}) + #else + #define IF_SERIAL_DEBUG(x) + #if defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny85__) + #define printf_P(...) + #endif + #endif + +// Avoid spurious warnings +// Arduino DUE is arm and uses traditional PROGMEM constructs +#if 1 +#if ! defined( NATIVE ) && defined( ARDUINO ) && ! defined(__arm__) +#undef PROGMEM +#define PROGMEM __attribute__(( section(".progmem.data") )) +#undef PSTR +#define PSTR(s) (__extension__({static const char __c[] PROGMEM = (s); &__c[0];})) +#endif +#endif + +// Progmem is Arduino-specific +// Arduino DUE is arm and does not include avr/pgmspace +#if defined(ARDUINO) && ! defined(__arm__) + #include + #define PRIPSTR "%S" +#else +#if ! defined(ARDUINO) // This doesn't work on Arduino DUE + typedef char const char; +#else // Fill in pgm_read_byte that is used, but missing from DUE + #define pgm_read_byte(addr) (*(const unsigned char *)(addr)) +#endif + + typedef uint16_t prog_uint16_t; + #define PSTR(x) (x) + #define printf_P printf + #define strlen_P strlen + #define PROGMEM + #define pgm_read_word(p) (*(p)) + #define PRIPSTR "%s" +#endif + + + +// ATTiny support code is from https://github.com/jscrane/RF24 + +#if defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) || defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) +#include +#include +#include + +#define SPI_CLOCK_DIV4 0x00 +#define SPI_CLOCK_DIV16 0x01 +#define SPI_CLOCK_DIV64 0x02 +#define SPI_CLOCK_DIV128 0x03 +#define SPI_CLOCK_DIV2 0x04 +#define SPI_CLOCK_DIV8 0x05 +#define SPI_CLOCK_DIV32 0x06 +//#define SPI_CLOCK_DIV64 0x07 + +#define SPI_MODE0 0x00 +#define SPI_MODE1 0x04 +#define SPI_MODE2 0x08 +#define SPI_MODE3 0x0C + +#define SPI_MODE_MASK 0x0C // CPOL = bit 3, CPHA = bit 2 on SPCR +#define SPI_CLOCK_MASK 0x03 // SPR1 = bit 1, SPR0 = bit 0 on SPCR +#define SPI_2XCLOCK_MASK 0x01 // SPI2X = bit 0 on SPSR + + + +class SPIClass { +public: + static byte transfer(byte _data); + + // SPI Configuration methods + + inline static void attachInterrupt(); + inline static void detachInterrupt(); // Default + + static void begin(); // Default + static void end(); + + static void setBitOrder(uint8_t); + static void setDataMode(uint8_t); + static void setClockDivider(uint8_t); +}; +extern SPIClass SPI; + +#endif //ATTiny +#endif // __RF24_CONFIG_H__ + diff --git a/AVR/lib/RF24/nRF24L01.h b/libraries/MySensors/utility/nRF24L01.h similarity index 89% rename from AVR/lib/RF24/nRF24L01.h rename to libraries/MySensors/utility/nRF24L01.h index 2012ce6..132de94 100644 --- a/AVR/lib/RF24/nRF24L01.h +++ b/libraries/MySensors/utility/nRF24L01.h @@ -1,24 +1,25 @@ /* Copyright (c) 2007 Stefan Engelke + Portions Copyright (C) 2011 Greg Copeland - 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 + 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 + 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 + 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. */ @@ -117,6 +118,7 @@ /* P model memory Map */ #define RPD 0x09 +#define W_TX_PAYLOAD_NO_ACK 0xB0 /* P model bit Mnemonics */ #define RF_DR_LOW 5 diff --git a/libraries/PN532/examples/iso14443a_uid/iso14443a_uid.pde b/libraries/PN532/examples/iso14443a_uid/iso14443a_uid.ino similarity index 100% rename from libraries/PN532/examples/iso14443a_uid/iso14443a_uid.pde rename to libraries/PN532/examples/iso14443a_uid/iso14443a_uid.ino diff --git a/libraries/PN532/examples/mifareclassic_formatndef/mifareclassic_formatndef.pde b/libraries/PN532/examples/mifareclassic_formatndef/mifareclassic_formatndef.ino similarity index 100% rename from libraries/PN532/examples/mifareclassic_formatndef/mifareclassic_formatndef.pde rename to libraries/PN532/examples/mifareclassic_formatndef/mifareclassic_formatndef.ino diff --git a/libraries/PN532/examples/mifareclassic_memdump/mifareclassic_memdump.pde b/libraries/PN532/examples/mifareclassic_memdump/mifareclassic_memdump.ino similarity index 100% rename from libraries/PN532/examples/mifareclassic_memdump/mifareclassic_memdump.pde rename to libraries/PN532/examples/mifareclassic_memdump/mifareclassic_memdump.ino diff --git a/libraries/PN532/examples/mifareclassic_ndeftoclassic/mifareclassic_ndeftoclassic.pde b/libraries/PN532/examples/mifareclassic_ndeftoclassic/mifareclassic_ndeftoclassic.ino similarity index 100% rename from libraries/PN532/examples/mifareclassic_ndeftoclassic/mifareclassic_ndeftoclassic.pde rename to libraries/PN532/examples/mifareclassic_ndeftoclassic/mifareclassic_ndeftoclassic.ino diff --git a/libraries/PN532/examples/mifareclassic_updatendef/mifareclassic_updatendef.pde b/libraries/PN532/examples/mifareclassic_updatendef/mifareclassic_updatendef.ino similarity index 100% rename from libraries/PN532/examples/mifareclassic_updatendef/mifareclassic_updatendef.pde rename to libraries/PN532/examples/mifareclassic_updatendef/mifareclassic_updatendef.ino diff --git a/libraries/PN532/examples/readMifare/readMifare.pde b/libraries/PN532/examples/readMifare/readMifare.ino similarity index 100% rename from libraries/PN532/examples/readMifare/readMifare.pde rename to libraries/PN532/examples/readMifare/readMifare.ino diff --git a/libraries/PN532_HSU/PN532_HSU.cpp b/libraries/PN532_HSU/PN532_HSU.cpp deleted file mode 100644 index d0e67a2..0000000 --- a/libraries/PN532_HSU/PN532_HSU.cpp +++ /dev/null @@ -1,190 +0,0 @@ - -#include "PN532_HSU.h" -#include "PN532_debug.h" - - -PN532_HSU::PN532_HSU(HardwareSerial &serial) -{ - _serial = &serial; - command = 0; -} - -void PN532_HSU::begin() -{ - _serial->begin((long)115200); -} - -void PN532_HSU::wakeup() -{ - _serial->write((uint8_t)0x55); - _serial->write((uint8_t)0x55); - _serial->write((uint8_t)0x00); - _serial->write((uint8_t)0x00); - _serial->write((uint8_t)0x00); - - /** dump serial buffer */ - if(_serial->available()){ - DMSG("Dump serial buffer: "); - } - while(_serial->available()){ - uint8_t ret = _serial->read(); - DMSG_HEX(ret); - } - -} - -int8_t PN532_HSU::writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen) -{ - - /** dump serial buffer */ - if(_serial->available()){ - DMSG("Dump serial buffer: "); - } - while(_serial->available()){ - uint8_t ret = _serial->read(); - DMSG_HEX(ret); - } - - command = header[0]; - - _serial->write((uint8_t)PN532_PREAMBLE); - _serial->write((uint8_t)PN532_STARTCODE1); - _serial->write((uint8_t)PN532_STARTCODE2); - - uint8_t length = hlen + blen + 1; // length of data field: TFI + DATA - _serial->write(length); - _serial->write(~length + 1); // checksum of length - - _serial->write((uint8_t)PN532_HOSTTOPN532); - uint8_t sum = PN532_HOSTTOPN532; // sum of TFI + DATA - - _serial->write(header, hlen); - for (uint8_t i = 0; i < hlen; i++) { - sum += header[i]; - } - - _serial->write(body, blen); - for (uint8_t i = 0; i < blen; i++) { - sum += body[i]; - } - - uint8_t checksum = ~sum + 1; // checksum of TFI + DATA - _serial->write(checksum); - _serial->write((uint8_t)PN532_POSTAMBLE); - - return readAckFrame(); -} - -int16_t PN532_HSU::readResponse(uint8_t buf[], uint8_t len, uint16_t timeout) -{ - uint8_t tmp[3]; - - DMSG("Read response\n"); - - /** Frame Preamble and Start Code */ - if(receive(tmp, 3, timeout)<=0){ - return PN532_TIMEOUT; - } - if(0 != tmp[0] || 0!= tmp[1] || 0xFF != tmp[2]){ - DMSG("Preamble error"); - return PN532_INVALID_FRAME; - } - - /** receive length and check */ - uint8_t length[2]; - if(receive(length, 2, timeout) <= 0){ - return PN532_TIMEOUT; - } - if( 0 != (uint8_t)(length[0] + length[1]) ){ - DMSG("Length error"); - return PN532_INVALID_FRAME; - } - length[0] -= 2; - if( length[0] > len){ - return PN532_NO_SPACE; - } - - /** receive command byte */ - uint8_t cmd = command + 1; // response command - if(receive(tmp, 2, timeout) <= 0){ - return PN532_TIMEOUT; - } - if( PN532_PN532TOHOST != tmp[0] || cmd != tmp[1]){ - DMSG("Command error"); - return PN532_INVALID_FRAME; - } - - if(receive(buf, length[0], timeout) != length[0]){ - return PN532_TIMEOUT; - } - uint8_t sum = PN532_PN532TOHOST + cmd; - for(uint8_t i=0; i return value buffer. - len --> length expect to receive. - timeout --> time of reveiving - @retval number of received bytes, 0 means no data received. -*/ -int8_t PN532_HSU::receive(uint8_t *buf, int len, uint16_t timeout) -{ - int read_bytes = 0; - int ret; - unsigned long start_millis; - - while (read_bytes < len) { - start_millis = millis(); - do { - ret = _serial->read(); - if (ret >= 0) { - break; - } - } while( (millis()- start_millis ) < timeout); - - if (ret < 0) { - if(read_bytes){ - return read_bytes; - }else{ - return PN532_TIMEOUT; - } - } - buf[read_bytes] = (uint8_t)ret; - DMSG_HEX(ret); - read_bytes++; - } - return read_bytes; -} \ No newline at end of file diff --git a/libraries/PN532_HSU/PN532_HSU.h b/libraries/PN532_HSU/PN532_HSU.h deleted file mode 100644 index 54dddd3..0000000 --- a/libraries/PN532_HSU/PN532_HSU.h +++ /dev/null @@ -1,29 +0,0 @@ - -#ifndef __PN532_HSU_H__ -#define __PN532_HSU_H__ - -#include "PN532Interface.h" - -#define PN532_HSU_DEBUG - -#define PN532_HSU_READ_TIMEOUT (1000) - -class PN532_HSU : public PN532Interface { -public: - PN532_HSU(HardwareSerial &serial); - - void begin(); - void wakeup(); - virtual int8_t writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0); - int16_t readResponse(uint8_t buf[], uint8_t len, uint16_t timeout); - -private: - HardwareSerial* _serial; - uint8_t command; - - int8_t readAckFrame(); - - int8_t receive(uint8_t *buf, int len, uint16_t timeout=PN532_HSU_READ_TIMEOUT); -}; - -#endif diff --git a/libraries/PN532_SPI/PN532_SPI.cpp b/libraries/PN532_SPI/PN532_SPI.cpp deleted file mode 100644 index 39adbf9..0000000 --- a/libraries/PN532_SPI/PN532_SPI.cpp +++ /dev/null @@ -1,209 +0,0 @@ - -#include "PN532_SPI.h" -#include "PN532_debug.h" - -#define STATUS_READ 2 -#define DATA_WRITE 1 -#define DATA_READ 3 - -PN532_SPI::PN532_SPI(SPIClass &spi, uint8_t ss) -{ - command = 0; - _spi = &spi; - _ss = ss; -} - -void PN532_SPI::begin() -{ - pinMode(_ss, OUTPUT); - - _spi->begin(); - _spi->setDataMode(SPI_MODE0); // PN532 only supports mode0 - _spi->setBitOrder(LSBFIRST); -#ifndef __SAM3X8E__ - _spi->setClockDivider(SPI_CLOCK_DIV8); // set clock 2MHz(max: 5MHz) -#else - /** DUE spi library does not support SPI_CLOCK_DIV8 macro */ - _spi->setClockDivider(42); // set clock 2MHz(max: 5MHz) -#endif - -} - -void PN532_SPI::wakeup() -{ - digitalWrite(_ss, LOW); - delay(2); - digitalWrite(_ss, HIGH); -} - - - -int8_t PN532_SPI::writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen) -{ - command = header[0]; - writeFrame(header, hlen, body, blen); - - uint8_t timeout = PN532_ACK_WAIT_TIME; - while (!isReady()) { - delay(1); - timeout--; - if (0 == timeout) { - DMSG("Time out when waiting for ACK\n"); - return -2; - } - } - if (readAckFrame()) { - DMSG("Invalid ACK\n"); - return PN532_INVALID_ACK; - } - return 0; -} - -int16_t PN532_SPI::readResponse(uint8_t buf[], uint8_t len, uint16_t timeout) -{ - uint16_t time = 0; - while (!isReady()) { - delay(1); - time++; - if (timeout > 0 && time > timeout) { - return PN532_TIMEOUT; - } - } - - digitalWrite(_ss, LOW); - delay(1); - - int16_t result; - do { - write(DATA_READ); - - if (0x00 != read() || // PREAMBLE - 0x00 != read() || // STARTCODE1 - 0xFF != read() // STARTCODE2 - ) { - - result = PN532_INVALID_FRAME; - break; - } - - uint8_t length = read(); - if (0 != (uint8_t)(length + read())) { // checksum of length - result = PN532_INVALID_FRAME; - break; - } - - uint8_t cmd = command + 1; // response command - if (PN532_PN532TOHOST != read() || (cmd) != read()) { - result = PN532_INVALID_FRAME; - break; - } - - DMSG("read: "); - DMSG_HEX(cmd); - - length -= 2; - if (length > len) { - for (uint8_t i = 0; i < length; i++) { - DMSG_HEX(read()); // dump message - } - DMSG("\nNot enough space\n"); - read(); - read(); - result = PN532_NO_SPACE; // not enough space - break; - } - - uint8_t sum = PN532_PN532TOHOST + cmd; - for (uint8_t i = 0; i < length; i++) { - buf[i] = read(); - sum += buf[i]; - - DMSG_HEX(buf[i]); - } - DMSG('\n'); - - uint8_t checksum = read(); - if (0 != (uint8_t)(sum + checksum)) { - DMSG("checksum is not ok\n"); - result = PN532_INVALID_FRAME; - break; - } - read(); // POSTAMBLE - - result = length; - } while (0); - - digitalWrite(_ss, HIGH); - - return result; -} - -boolean PN532_SPI::isReady() -{ - digitalWrite(_ss, LOW); - - write(STATUS_READ); - uint8_t status = read() & 1; - digitalWrite(_ss, HIGH); - return status; -} - -void PN532_SPI::writeFrame(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen) -{ - digitalWrite(_ss, LOW); - delay(2); // wake up PN532 - - write(DATA_WRITE); - write(PN532_PREAMBLE); - write(PN532_STARTCODE1); - write(PN532_STARTCODE2); - - uint8_t length = hlen + blen + 1; // length of data field: TFI + DATA - write(length); - write(~length + 1); // checksum of length - - write(PN532_HOSTTOPN532); - uint8_t sum = PN532_HOSTTOPN532; // sum of TFI + DATA - - DMSG("write: "); - - for (uint8_t i = 0; i < hlen; i++) { - write(header[i]); - sum += header[i]; - - DMSG_HEX(header[i]); - } - for (uint8_t i = 0; i < blen; i++) { - write(body[i]); - sum += body[i]; - - DMSG_HEX(body[i]); - } - - uint8_t checksum = ~sum + 1; // checksum of TFI + DATA - write(checksum); - write(PN532_POSTAMBLE); - - digitalWrite(_ss, HIGH); - - DMSG('\n'); -} - -int8_t PN532_SPI::readAckFrame() -{ - const uint8_t PN532_ACK[] = {0, 0, 0xFF, 0, 0xFF, 0}; - - uint8_t ackBuf[sizeof(PN532_ACK)]; - - digitalWrite(_ss, LOW); - delay(1); - write(DATA_READ); - - for (uint8_t i = 0; i < sizeof(PN532_ACK); i++) { - ackBuf[i] = read(); - } - - digitalWrite(_ss, HIGH); - - return memcmp(ackBuf, PN532_ACK, sizeof(PN532_ACK)); -} diff --git a/libraries/PN532_SPI/PN532_SPI.h b/libraries/PN532_SPI/PN532_SPI.h deleted file mode 100644 index 53ff697..0000000 --- a/libraries/PN532_SPI/PN532_SPI.h +++ /dev/null @@ -1,36 +0,0 @@ - -#ifndef __PN532_SPI_H__ -#define __PN532_SPI_H__ - -#include -#include "PN532Interface.h" - -class PN532_SPI : public PN532Interface { -public: - PN532_SPI(SPIClass &spi, uint8_t ss); - - void begin(); - void wakeup(); - int8_t writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0); - - int16_t readResponse(uint8_t buf[], uint8_t len, uint16_t timeout); - -private: - SPIClass* _spi; - uint8_t _ss; - uint8_t command; - - boolean isReady(); - void writeFrame(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0); - int8_t readAckFrame(); - - inline void write(uint8_t data) { - _spi->transfer(data); - }; - - inline uint8_t read() { - return _spi->transfer(0); - }; -}; - -#endif diff --git a/libraries/PinChangeInt/Examples/ByteBuffer/ByteBuffer.cpp b/libraries/PinChangeInt/Examples/ByteBuffer/ByteBuffer.cpp deleted file mode 100644 index db49dce..0000000 --- a/libraries/PinChangeInt/Examples/ByteBuffer/ByteBuffer.cpp +++ /dev/null @@ -1,272 +0,0 @@ -/* - ByteBuffer.cpp - A circular buffer implementation for Arduino - Created by Sigurdur Orn, July 19, 2010. - siggi@mit.edu - Updated by GreyGnome (aka Mike Schwager) Thu Feb 23 17:25:14 CST 2012 - added the putString() method and the fillError variable. - added the checkError() and resetError() methods. The checkError() method resets the fillError variable - to false as a side effect. - added the ByteBuffer(unsigned int buf_size) constructor. - added the init() method, and had the constructor call it automagically. - Also made the capacity, position, length, and fillError variables volatile, for safe use by interrupts. - */ - -#include "ByteBuffer.h" - -void ByteBuffer::init(){ - ByteBuffer::init(DEFAULTBUFSIZE); -} - -void ByteBuffer::init(unsigned int buf_length){ - data = (byte*)malloc(sizeof(byte)*buf_length); - capacity = buf_length; - position = 0; - length = 0; - fillError=false; -} - -void ByteBuffer::deAllocate(){ - free(data); -} - -void ByteBuffer::clear(){ - position = 0; - length = 0; -} - -void ByteBuffer::resetError(){ - fillError=false; -} - -boolean ByteBuffer::checkError(){ - /* - if (fillError) { - Serial.print("E: checkError: length "); - Serial.println(length, DEC); - } - */ - - boolean result=fillError; - fillError=false; - return(result); -} - -int ByteBuffer::getSize(){ - return length; -} - -int ByteBuffer::getCapacity(){ - return capacity; -} - -byte ByteBuffer::peek(unsigned int index){ - byte b = data[(position+index)%capacity]; - return b; -} - -uint8_t ByteBuffer::put(byte in){ - if(length < capacity){ - // save data byte at end of buffer - data[(position+length) % capacity] = in; - // increment the length - length++; - return 1; - } - // return failure - //Serial.print("E: put: "); - //Serial.println(length, DEC); - fillError=true; - return 0; -} - - -uint8_t ByteBuffer::putString(char *in){ - uint8_t count=0; - char *inString; - - inString=in; - uint8_t oldSREG = SREG; cli(); - while(length <= capacity){ - if (length == capacity) { - fillError=true; - return count; - } - // save data byte at end of buffer - data[(position+length) % capacity] = *inString; - // increment the length - length++; - inString++; - count++; - if (*inString == 0) { - if (count==0) fillError=true; // Serial.println("E: putString"); }; - SREG = oldSREG; // Restore register; reenables interrupts - return count; - } - } - SREG = oldSREG; // Restore register; reenables interrupts - return count; -} - -uint8_t ByteBuffer::putInFront(byte in){ - uint8_t oldSREG = SREG; cli(); - if(length < capacity){ - // save data byte at end of buffer - if( position == 0 ) - position = capacity-1; - else - position = (position-1)%capacity; - data[position] = in; - // increment the length - length++; - SREG = oldSREG; // Restore register; reenables interrupts - return 1; - } - // return failure - //Serial.println("E: putInFront"); - fillError=true; - SREG = oldSREG; // Restore register; reenables interrupts - return 0; -} - -byte ByteBuffer::get(){ - uint8_t oldSREG = SREG; cli(); - byte b = 0; - - if(length > 0){ - b = data[position]; - // move index down and decrement length - position = (position+1)%capacity; - length--; - } - SREG = oldSREG; // Restore register; reenables interrupts - return b; -} - -byte ByteBuffer::getFromBack(){ - byte b = 0; - if(length > 0){ - uint8_t oldSREG = SREG; cli(); - b = data[(position+length-1)%capacity]; - length--; - SREG = oldSREG; // Restore register; reenables interrupts - } - - return b; -} - -// -// Ints -// - -void ByteBuffer::putIntInFront(int in){ - byte *pointer = (byte *)∈ - putInFront(pointer[0]); - putInFront(pointer[1]); -} - -void ByteBuffer::putInt(int in){ - byte *pointer = (byte *)∈ - put(pointer[1]); - put(pointer[0]); -} - - -int ByteBuffer::getInt(){ - int ret; - byte *pointer = (byte *)&ret; - pointer[1] = get(); - pointer[0] = get(); - return ret; -} - -int ByteBuffer::getIntFromBack(){ - int ret; - byte *pointer = (byte *)&ret; - pointer[0] = getFromBack(); - pointer[1] = getFromBack(); - return ret; -} - -// -// Longs -// - -void ByteBuffer::putLongInFront(long in){ - byte *pointer = (byte *)∈ - putInFront(pointer[0]); - putInFront(pointer[1]); - putInFront(pointer[2]); - putInFront(pointer[3]); -} - -void ByteBuffer::putLong(long in){ - byte *pointer = (byte *)∈ - put(pointer[3]); - put(pointer[2]); - put(pointer[1]); - put(pointer[0]); -} - - -long ByteBuffer::getLong(){ - long ret; - byte *pointer = (byte *)&ret; - pointer[3] = get(); - pointer[2] = get(); - pointer[1] = get(); - pointer[0] = get(); - return ret; -} - -long ByteBuffer::getLongFromBack(){ - long ret; - byte *pointer = (byte *)&ret; - pointer[0] = getFromBack(); - pointer[1] = getFromBack(); - pointer[2] = getFromBack(); - pointer[3] = getFromBack(); - return ret; -} - - -// -// Floats -// - -void ByteBuffer::putFloatInFront(float in){ - byte *pointer = (byte *)∈ - putInFront(pointer[0]); - putInFront(pointer[1]); - putInFront(pointer[2]); - putInFront(pointer[3]); -} - -void ByteBuffer::putFloat(float in){ - byte *pointer = (byte *)∈ - put(pointer[3]); - put(pointer[2]); - put(pointer[1]); - put(pointer[0]); -} - -float ByteBuffer::getFloat(){ - float ret; - byte *pointer = (byte *)&ret; - pointer[3] = get(); - pointer[2] = get(); - pointer[1] = get(); - pointer[0] = get(); - return ret; -} - -float ByteBuffer::getFloatFromBack(){ - float ret; - byte *pointer = (byte *)&ret; - pointer[0] = getFromBack(); - pointer[1] = getFromBack(); - pointer[2] = getFromBack(); - pointer[3] = getFromBack(); - return ret; -} - - diff --git a/libraries/PinChangeInt/Examples/ByteBuffer/ByteBuffer.h b/libraries/PinChangeInt/Examples/ByteBuffer/ByteBuffer.h deleted file mode 100644 index 8916e58..0000000 --- a/libraries/PinChangeInt/Examples/ByteBuffer/ByteBuffer.h +++ /dev/null @@ -1,104 +0,0 @@ -/* - ByteBuffer.h - A circular buffer implementation for Arduino - Created by Sigurdur Orn, July 19, 2010. siggi@mit.edu - Updated by GreyGnome (aka Mike Schwager) Thu Feb 23 17:25:14 CST 2012 - added the putString() method and the fillError variable. - added the checkError() and resetError() methods. The checkError() method resets the fillError variable - to false as a side effect. - added the ByteBuffer(unsigned int buf_size) constructor. - added the init() method, and had the constructor call it automagically. - protected certain sections of the code with cli()/sei() calls, for safe use by interrupts. - Also made the capacity, position, length, and fillError variables volatile, for safe use by interrupts. - */ - -#ifndef ByteBuffer_h -#define ByteBuffer_h - -#if defined(ARDUINO) && ARDUINO >= 100 - #include -#else - #include -#endif -//#include - -#define DEFAULTBUFSIZE 32 -class ByteBuffer -{ -public: - ByteBuffer() { - init(); - }; - ByteBuffer(unsigned int buf_size) { - init(buf_size); - }; - - // This method initializes the datastore of the buffer to a certain size. - void init(unsigned int buf_size); - - // This method initializes the datastore of the buffer to the default size. - void init(); - - // This method resets the buffer into an original state (with no data) - void clear(); - - // This method resets the fillError variable to false. - void resetError(); - - // This method tells you if your buffer overflowed at some time since the last - // check. The error state will be reset to false. - boolean checkError(); - - // This releases resources for this buffer, after this has been called the buffer should NOT be used - void deAllocate(); - - // Returns how much space is used in the buffer - int getSize(); - - // Returns the maximum capacity of the buffer - int getCapacity(); - - // This method returns the byte that is located at index in the buffer but doesn't modify the buffer like the get methods (doesn't remove the retured byte from the buffer) - byte peek(unsigned int index); - - // - // Put methods, either a regular put in back or put in front - // - uint8_t putInFront(byte in); - uint8_t put(byte in); - uint8_t putString(char *in); - - void putIntInFront(int in); - void putInt(int in); - - void putLongInFront(long in); - void putLong(long in); - - void putFloatInFront(float in); - void putFloat(float in); - - // - // Get methods, either a regular get from front or from back - // - byte get(); - byte getFromBack(); - - int getInt(); - int getIntFromBack(); - - long getLong(); - long getLongFromBack(); - - float getFloat(); - float getFloatFromBack(); - -private: - byte* data; - - volatile unsigned int capacity; - volatile unsigned int position; - volatile unsigned int length; - volatile boolean fillError; -}; - -#endif - diff --git a/libraries/PinChangeInt/Examples/GetPSTR/GetPSTR.h b/libraries/PinChangeInt/Examples/GetPSTR/GetPSTR.h deleted file mode 100644 index aaab06a..0000000 --- a/libraries/PinChangeInt/Examples/GetPSTR/GetPSTR.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef INCLUDE_GETPSTR -#define INCLUDE_GETPSTR - -#if defined(ARDUINO) && ARDUINO >= 100 - #include -#else - #include "pins_arduino.h" - #include "WProgram.h" - #include "wiring.h" -#endif - -#define getPSTR(s) pgmStrToRAM(PSTR(s)) - -char *_pstr_to_print; -char *pgmStrToRAM(PROGMEM char *theString) { - free(_pstr_to_print); - _pstr_to_print=(char *) malloc(strlen_P(theString)); - strcpy_P(_pstr_to_print, theString); - return (_pstr_to_print); -} -#endif diff --git a/libraries/PinChangeInt/Examples/PinChangeIntExample/PinChangeIntExample.pde b/libraries/PinChangeInt/Examples/PinChangeIntExample/PinChangeIntExample.pde deleted file mode 100644 index 2f254d4..0000000 --- a/libraries/PinChangeInt/Examples/PinChangeIntExample/PinChangeIntExample.pde +++ /dev/null @@ -1,77 +0,0 @@ -// PinChangeIntExample, version 1.1 Sun Jan 15 06:24:19 CST 2012 -// See the Wiki at http://code.google.com/p/arduino-pinchangeint/wiki for more information. -//-------- define these in your sketch, if applicable ---------------------------------------------------------- -// You can reduce the memory footprint of this handler by declaring that there will be no pin change interrupts -// on any one or two of the three ports. If only a single port remains, the handler will be declared inline -// reducing the size and latency of the handler. -//#define NO_PORTB_PINCHANGES // to indicate that port b will not be used for pin change interrupts -//#define NO_PORTC_PINCHANGES // to indicate that port c will not be used for pin change interrupts -// #define NO_PORTD_PINCHANGES // to indicate that port d will not be used for pin change interrupts -// if there is only one PCInt vector in use the code can be inlined -// reducing latency and code size -// define DISABLE_PCINT_MULTI_SERVICE below to limit the handler to servicing a single interrupt per invocation. -// #define DISABLE_PCINT_MULTI_SERVICE -//-------- define the above in your sketch, if applicable ------------------------------------------------------ -#include - -// This example demonstrates a configuration of 3 interrupting pins and 2 interrupt functions. -// All interrupts are serviced immediately, but one of the pins (pin 4) will show you immediately -// on the Terminal. The other function connected to 2 pins sets an array member that is queried in loop(). -// You can then query the array at your leisure. -// This makes loop timing non-critical. - -// Add more Pins at your leisure. -// For the Analog Input pins used as digital input pins, and you can use 14, 15, 16, etc. -// or you can use A0, A1, A2, etc. (the Arduino code comes with #define's -// for the Analog Input pins and will properly recognize e.g., pinMode(A0, INPUT); -#define PIN1 2 -#define PIN2 3 -#define PIN3 4 - -uint8_t latest_interrupted_pin; -uint8_t interrupt_count[20]={0}; // 20 possible arduino pins -void quicfunc() { - latest_interrupted_pin=PCintPort::arduinoPin; - interrupt_count[latest_interrupted_pin]++; -}; - -// You can assign any number of functions to any number of pins. -// How cool is that? -void pin3func() { - Serial.print("Pin "); Serial.print(PIN3, DEC); Serial.println("!"); -} - -void setup() { - pinMode(PIN1, INPUT); digitalWrite(PIN1, HIGH); - PCintPort::attachInterrupt(PIN1, &quicfunc, FALLING); // add more attachInterrupt code as required - pinMode(PIN2, INPUT); digitalWrite(PIN2, HIGH); - PCintPort::attachInterrupt(PIN2, &quicfunc, FALLING); - pinMode(PIN3, INPUT); digitalWrite(PIN3, HIGH); - PCintPort::attachInterrupt(PIN3, &pin3func, CHANGE); - Serial.begin(115200); - Serial.println("---------------------------------------"); -} - -uint8_t i; -void loop() { - uint8_t count; - Serial.print("."); - delay(1000); - for (i=0; i < 20; i++) { - if (interrupt_count[i] != 0) { - count=interrupt_count[i]; - interrupt_count[i]=0; - Serial.print("Count for pin "); - if (i < 14) { - Serial.print("D"); - Serial.print(i, DEC); - } else { - Serial.print("A"); - Serial.print(i-14, DEC); - } - Serial.print(" is "); - Serial.println(count, DEC); - } - } -} - diff --git a/libraries/PinChangeInt/Examples/PinChangeIntSpeedTest/PinChangeIntSpeedTest.pde b/libraries/PinChangeInt/Examples/PinChangeIntSpeedTest/PinChangeIntSpeedTest.pde deleted file mode 100644 index f0ac0f2..0000000 --- a/libraries/PinChangeInt/Examples/PinChangeIntSpeedTest/PinChangeIntSpeedTest.pde +++ /dev/null @@ -1,265 +0,0 @@ -// PinChangeIntSpeedTest by GreyGnome aka Mike Schwager. Version numbers here refer to this sketch. -// Version 1.0 - initial version -// Version 1.1 - added code to test digitalRead() -// Version 1.2 - added new comments for the #define's for the NO_PORTx_PINCHANGES. -// Version 1.3 - includes cbiface.h with ooPinChangeInt, rather than cb.h -// Version 1.4 - testing version 2.10Beta with robtillaart's optimization -// Also added a #define/#undef INLINE_PCINTFUNC for inlining of the function called by the interrupt. -// Default: #undef for using the function as per usual. Changed PCIVERSION so that -// ooPinChangeInt starts at 1000 instead of 200. Modified the "Start" message to show "Start..", pause -// for 1 second, show "*\n" (where \n is a newline), pause for 1 second, then run the test. -// Version 1.4 - made this compatible with version 1.5 of PinChangeInt -// Version 1.5 - modified it to use #define OOPCIVERSION for ooPinChangeInt - -// This version number is for ooPinChangeInt -//#define OOPCIVERSION 1030 -#ifndef OOPCIVERSION -#define PCIVERSION 217 // 110 if using PinChangeInt-1.1, 120 for version 1.2 - // 1000 for ooPinChangeIntversion 1.00, 1001 for ooPinChangeInt version 1.01, etc. -#endif - -//-------- define these in your sketch, if applicable ---------------------------------------------------------- -// You can reduce the memory footprint of this handler by declaring that there will be no pin change interrupts -// on any one or two of the three ports. If only a single port remains, the handler will be declared inline -// reducing the size and latency of the handler. -#undef NO_PORTB_PINCHANGES // to indicate that port b will not be used for pin change interrupts -#undef NO_PORTC_PINCHANGES // to indicate that port c will not be used for pin change interrupts -// #define NO_PORTD_PINCHANGES // to indicate that port d will not be used for pin change interrupts -// You can reduce the code size by 20-50 bytes, and you can speed up the interrupt routine -// slightly by declaring that you don't care if the static variables PCintPort::pinState and/or -// PCintPort::arduinoPin are set and made available to your interrupt routine. -// #define NO_PIN_STATE // to indicate that you don't need the pinState -// #define NO_PIN_NUMBER // to indicate that you don't need the arduinoPin -// if there is only one PCInt vector in use the code can be inlined -// reducing latency and code size -// define DISABLE_PCINT_MULTI_SERVICE below to limit the handler to servicing a single interrupt per invocation. -//#define DISABLE_PCINT_MULTI_SERVICE -//-------- define the above in your sketch, if applicable ------------------------------------------------------ -#if defined(OOPCIVERSION) - #define LIBRARYUNDERTEST "ooPinChangeInt" - #include - #if PCIVERSION == 1001 - #include - #else - #include - #endif -#else - #define LIBRARYUNDERTEST "PinChangeInt" - #include -#endif - -#define SERIALSTUFF // undef to take out all serial statements. Default: #define for measuring time. -#undef MEMTEST // undef to take out memory tests. Default: #undef for measuring time. -#undef INLINE_PCINTFUNC // define to inline the function called from the interrupt. This should have no effect, - // because the compiler will store the registers upon calling the interrupt routine, just - // like calling a function. Still, we test all assumptions. -//----------------------- -// NOTE: BECAUSE OF COLLISIONS in these libraries, you CANNOT have both libraries: PinChangeInt -// and ooPinChangeInt in the libraries directory at the same time. That said, under UNIX-y operating -// systems, it's easy to move the library directory to a name such as "PinChangeInt-1.3", which the -// Arduino will not recognize, and then create a symbolic link when you want to use a library. Such as: -// cd ~/Documents/Arduino/libaries -// mv PinChangeInt PinChangeInt-1.30 -// mv ooPinChangeInt ooPinChangeInt-1.00 -// ln -s PinChangeInt-1.30 PinChangeInt - -#undef FLASH // to flash LED on pin 13 during test - -#ifdef MEMTEST -#include -#endif - -#define TEST 6 - -#if TEST == 1 -#define PTEST 2 // pin to trigger interrupt. pins 0 and 1 are used -#define PLOW 2 // by Serial, so steer clear of them! -#define PHIGH 2 // Interrupts are attached to these pins - -#elif TEST == 2 // see the #if TEST == 2 || TEST == 3 code, below -#define PTEST 2 -#define PLOW 2 -#define PHIGH 2 // need to attachInterrupt to 5 in the code - -#elif TEST == 3 // see the #if TEST == 2 || TEST == 3 code, below -#define PTEST 5 -#define PLOW 2 -#define PHIGH 2 // need to attachInterrupt to 5 in the code - -#elif TEST == 4 -#define PTEST 2 -#define PLOW 2 -#define PHIGH 5 - -#elif TEST == 5 -#define PTEST 3 -#define PLOW 2 -#define PHIGH 5 - -#elif TEST == 6 -#define PTEST 4 -#define PLOW 2 -#define PHIGH 5 - -#elif TEST == 7 -#define PTEST 5 -#define PLOW 2 -#define PHIGH 5 -#endif - -uint8_t qf0; - -#ifdef INLINE_PCINTFUNC -#define INLINE_PCINTFUNC inline -#else -#define INLINE_PCINTFUNC -#endif -INLINE_PCINTFUNC void quicfunc(); -void quicfunc() { - qf0=TCNT0; -} - -#if defined(OOPCIVERSION) -class speedy : public CallBackInterface -{ - public: - uint8_t id; - static uint8_t var0; - speedy () { id=0; }; - speedy (uint8_t _i): id(_i) {}; - - void cbmethod() { - speedy::var0=TCNT0; - //Serial.print("Speedy method "); // debugging - //Serial.println(id, DEC); - }; -}; -uint8_t speedy::var0=0; -#endif - -volatile uint8_t *led_port; -volatile uint8_t *pinT_OP; -volatile uint8_t *pinT_IP; -uint8_t led_mask, not_led_mask; -uint8_t pinT_M, not_pinT_M; -volatile uint8_t pintest, pinIntLow, pinIntHigh; -uint8_t totalpins; -#if defined(OOPCIVERSION) -speedy speedster[8]={speedy(0), speedy(1), speedy(2), speedy(3), speedy(4), speedy(5), speedy(6), speedy(7) }; -#endif -#ifdef MEMTEST -int freemem; -#endif - -int i=0; - -#define PINLED 13 -void setup() -{ -#ifdef SERIALSTUFF - Serial.begin(115200); Serial.println("---------------------------------------"); -#endif // SERIALSTUFF - // set up ports for trigger - pinMode(0, OUTPUT); digitalWrite(0, HIGH); - pinMode(1, OUTPUT); digitalWrite(1, HIGH); - pinMode(2, OUTPUT); digitalWrite(2, HIGH); - pinMode(3, OUTPUT); digitalWrite(3, HIGH); - pinMode(4, OUTPUT); digitalWrite(4, HIGH); - pinMode(5, OUTPUT); digitalWrite(5, HIGH); - pinMode(6, OUTPUT); digitalWrite(6, HIGH); - pinMode(7, OUTPUT); digitalWrite(7, HIGH); -#ifdef FLASH - led_port=portOutputRegister(digitalPinToPort(PINLED)); - led_mask=digitalPinToBitMask(PINLED); - not_led_mask=led_mask^0xFF; - pinMode(PINLED, OUTPUT); digitalWrite(PINLED, LOW); -#endif - // ***************************************************************************** - // set up ports for output ************ PIN TO TEST IS GIVEN HERE ************** - // ***************************************************************************** - pintest=PTEST; - pinIntLow=PLOW; pinIntHigh=PHIGH; // Interrupts are attached to these pins - // ***************************************************************************** - // ***************************************************************************** - pinT_OP=portOutputRegister(digitalPinToPort(pintest)); // output port - pinT_IP=portInputRegister(digitalPinToPort(pintest)); // input port - pinT_M=digitalPinToBitMask(pintest); // mask - not_pinT_M=pinT_M^0xFF; // not-mask - *pinT_OP|=pinT_M; - for (i=pinIntLow; i <= pinIntHigh; i++) { -#if defined(OOPCIVERSION) - PCintPort::attachInterrupt(i, &speedster[i], CHANGE); // C++ technique; v1.3 or better -#endif -#if defined(PCIVERSION) - PCintPort::attachInterrupt((uint8_t) i, &quicfunc, CHANGE); // C technique; v1.2 or earlier -#endif - } -#if TEST == 2 || TEST == 3 - i=5; totalpins=2; -#if defined(OOPCIVERSION) - PCintPort::attachInterrupt(i, &speedster[i], CHANGE); // C++ technique; v1.3 or better -#endif -#if defined(PCIVERSION) - PCintPort::attachInterrupt(i, &quicfunc, CHANGE); // C technique; v1.2 or earlier -#endif -#else - totalpins=pinIntHigh - pinIntLow + 1; -#endif - i=0; -} // end setup() - -uint8_t k=0; -unsigned long milliStart, milliEnd, elapsed; -void loop() { - k=0; - *pinT_OP|=pinT_M; // pintest to 1 -#ifdef SERIALSTUFF - Serial.print(LIBRARYUNDERTEST); Serial.print(" "); - Serial.print("TEST: "); Serial.print(TEST, DEC); Serial.print(" "); -#ifndef MEMTEST - Serial.print("test pin mask: "); Serial.print(pinT_M, HEX); - Serial.print(". Total of "); Serial.print(totalpins, DEC); Serial.println(" pins enabled."); -#endif -#ifdef MEMTEST - freemem=freeMemory(); Serial.print("Free memory: "); Serial.println(freemem, DEC); -#endif -#endif - delay(1000); - Serial.print("Start.."); - delay(1000); Serial.print("*"); - #ifdef FLASH - *led_port|=led_mask; - #endif - milliStart=millis(); - while (k < 10) { - i=0; - while (i < 10000) { - *pinT_OP&=not_pinT_M; // pintest to 0 ****************************** 16.8 us - *pinT_OP|=pinT_M; // pintest to 1 ****************************** ...to get here - i++; - } - k++; - } - milliEnd=millis(); - #ifdef FLASH - *led_port&=not_led_mask; - #endif - elapsed=milliEnd-milliStart; - #ifndef MEMTEST - Serial.print(" Elapsed: "); - Serial.println(elapsed, DEC); - #endif - #ifdef SERIALSTUFF - Serial.print("Interrupted pin: "); - #if defined(OOPCIVERSION) - Serial.println(speedster[pintest].id, DEC); - #else - Serial.println(PCintPort::arduinoPin, DEC); - #endif -#ifdef MEMTEST - freemem=freeMemory(); Serial.print("END-Free memory: "); Serial.println(freemem, DEC); -#endif -#endif - delay(500); -} - diff --git a/libraries/PinChangeInt/Examples/PinChangeIntTest/PinChangeIntTest.pde b/libraries/PinChangeInt/Examples/PinChangeIntTest/PinChangeIntTest.pde deleted file mode 100644 index c8df127..0000000 --- a/libraries/PinChangeInt/Examples/PinChangeIntTest/PinChangeIntTest.pde +++ /dev/null @@ -1,344 +0,0 @@ -// PinChangeIntTest -// version 1.0 Wed Feb 15 07:25:09 CST 2012 -// Version 1.1 Fri Jun 22 19:10:50 CDT 2012 minor tweaks to eliminate compiler warnings. Also, there were bugfixes in ByteBuffer. -// I had some "cli()" without "sei()" in there. -// See the Wiki at http://code.google.com/p/arduino-pinchangeint/wiki for more information. -// This sketch requires the ByteBuffer library, which is found in the PinChangeInt zipfile. -//-------- define these in your sketch, if applicable ---------------------------------------------------------- -//-------- This must go ahead of the #include statement -------------------------------------------------------- -// You can reduce the memory footprint of this handler by declaring that there will be no pin change interrupts -// on any one or two of the three ports. If only a single port remains, the handler will be declared inline -// reducing the size and latency of the handler. -// #define NO_PORTB_PINCHANGES // to indicate that port b will not be used for pin change interrupts -// #define NO_PORTC_PINCHANGES // to indicate that port c will not be used for pin change interrupts -// #define NO_PORTD_PINCHANGES // to indicate that port d will not be used for pin change interrupts -// You can reduce the code size by 20-50 bytes, and you can speed up the interrupt routine -// slightly by declaring that you don't care if the static variables PCintPort::pinState and/or -// PCintPort::arduinoPin are set and made available to your interrupt routine. -// #define NO_PIN_STATE // to indicate that you don't need the pinState -// #define NO_PIN_NUMBER // to indicate that you don't need the arduinoPin -// if there is only one PCInt vector in use the code can be inlined -// reducing latency and code size -// define DISABLE_PCINT_MULTI_SERVICE below to limit the handler to servicing a single interrupt per invocation. -// #define DISABLE_PCINT_MULTI_SERVICE -// The following is intended for testing purposes. If defined, then a variable PCintPort::pinMode can be read -// in your interrupt subroutine. It is not defined by default: -// #define PINMODE -//-------- define the above in your sketch, if applicable ------------------------------------------------------ -#define PINMODE -#define FLASH -#include -#include - -// This example demonstrates a configuration of 6 interrupting pins and 3 interrupt functions. -// A variety of interrupting pins have been chosen, so as to test all PORTs on the Arduino. -// The pins are as follows: -#define tPIN1 2 // port D -#define tPIN2 3 -#define tPIN3 11 // Port B -#define tPIN4 12 -#define tPIN5 A3 // Port C, also can be given as "17" -#define tPIN6 A4 // starts and stops the count -// All pins send interrupts. Arduino pins 2 and A4 (tPIN1,6) interrupt on FALLING. -// Arduino pins 3 and 12 (tPIN2,4) interrupt on RISING. -// Arduino pins 11 and A3 (tPIN5) interrupts on CHANGE. -// quicfunc0 is attached to Arduino pins 2, 3, 11, and 12 (tPIN1-4) -// quicfunc1 is attached to Arduino pin A3 (tPIN5) -// quicfunc2 is attached to Arduino pin A4 (tPIN6). -// NOTE: -// For the Analog Input pins used as digital input pins, you can use numbers such as 14, 15, 16, etc. -// or you can use A0, A1, A2, etc. (the Arduino code comes with #define's for the Analog Input pin -// names and will properly recognize e.g., pinMode(A0, INPUT)); - -// HOW IT WORKS -// The interrupt on Arduino pin A4 (tPIN6) will, when triggered, start the counting of interrupts. -// The array interrupt_count0[20] is updated in the interrupts; each cell keeps track of the number -// of interrupts on one of the 20 available interrupt pins on the Arduino. Every second in the main -// loop the array is scanned and registered interrupts are reported for all pins interrupted since -// the previous second. If no interrupts, the output is quiet. - -// tPIN6 is special. Not only does it start the counting of the interrups, but it turns on and off -// interrupts on pins 2, 11, and A3/17 (tPIN1, tPIN3, tPIN5). All pins start by interrupting, but after -// the count is turned on and then turned off, the 3 pins are detached from interrupts. -// Everytime thereafter when the count is turned off the 3 pins are detached. They are reattached -// when turned on. - -// Output is copied to a buffer, because we can't do a Serial.print() statement in an interrupt -// routine. The main loop checks for entries in the buffer and prints them if found. -// Output looks like this: -// -F- - an interrupt triggered by a falling signal occurred. -// +R+ - an interrupt triggered by a rising signal occurred. -// *C* - an interrupt triggered by a change in signal occurred. -// f#p#-P# - f# shows the interrupt subroutine that was called: 0, 1, or 2 -// - p# shows the pin number that triggered the interrupt -// - P# shows the port that this pin number is attached to. 2 is PORTB, 3 is PORTC, 4 is PORTD - -// HOW TO CONNECT -// Each pin gets a momentary contact switch connected to it. One side of the switch should connect -// to ground. The other side of the switch connects to the Arduino pin. For my purposes, I am using -// two rotary encoders. Each encoder contains 3 switches. But 6 regular pushbuttons would work, too. - -/* WHAT TO LOOK FOR - Output is sent to the serial line, so the Arduino IDE's serial terminal should be opened. - Upon startup, press tPINS1-5. You will see output like this: --F-f0p2-P4 (counting off) -..*C*f0p11-P2 (counting off) -+R+f0p3-P4 (counting off) - This shows that - 1. an interrupt was triggered on a falling signal (*F*). It called (f0) function 0, which is quicfunc0. - The triggering pin was (p2) Arduuino pin 2, which is on (P4) Port 4 (PORTD). Counting of this interrupt is - off, so you will not see any output from the main loop. - 2. Two dots appeared. Dots came from iterations of loop(), so these 2 dots show that the two interrupts happened 2 seconds apart. - 3. an interrupt was triggered on a change in signal (*C*). It called quicfunc0, from Arduino pin 11, on Port 2 (PORTB). - The interrupt was not counted. - 4. an interrupt was triggered on a rising signal (+R+). It called quicfunc0, from Arduino pin 3, on Purt 4 (PORTD). - The pin should have started out at the high level, so likely the signal fell during onother interrupt, and now - the rise has been caught. - - Now press the button attached to tPIN6 (in our case, A4 or D18). You will see something like this: --F-START! f2p18-P3 -.Count for pin A4 is 1 - This shows that - 1. The counting machanism (START!) was triggered by a folling signal (-F-) on pin 18 (p18) which is in Port 3 (P3) (which == PORTC) and - function f2 was called (f2). - 2. A dot appeared, which came from loop() because a second passed. - 3. The count for p18 or A4 was displayed. - - Now you will see messages for all the pins that you manipulate, for example: -*C*f0p11-P2 -+R+f0p3-P4 -*C*f0p11-P2 -+R+f0p3-P4 -*C*f0p11-P2 -.Count for pin D3 is 6 -Count for pin D11 is 9 -.+R+f0p3-P4 --F-f0p2-P4 -.Count for pin D2 is 1 -Count for pin D3 is 1 - These codes reflect the interrupts, as described above. This output will take place until you press tPIN6: --F-f2: STOP! Counting off. -Interrupt OFF on tPIN1 (2) tPIN3 (11) tPIN5 (17) - Then you will see output like this: -.....................+R+f0p12-P2 (counting off) -.+R+f0p12-P2 (counting off) -+R+f0p12-P2 (counting off) -+R+f0p12-P2 (counting off) - and tPIN1, tPIN3, and tPIN5 will not trigger interrupts. -*/ -// NOTES -// Output overwrites: -// It's possible during moderately fast interrupts to see your print output get garbled; eg, -// +R+f0p12-P2 (+R+f0p12-P2 (counting +R+f0p12-P2 (cou+R+f0p12-P+R+f0p12 -// This is because the print of the buffer takes place inside a while loop, and it can -// be interrupted and new data inserted into the buffer at a midpoint of the buffer's text. -// Just by spinning my rotary encoders I can readily generate over 200 interrupts per second -// on a pin, which is easily fast enough to overrun Serial output at 115,200 bps. -// The lesson here? ...Interrupts are tricky, and interrupt service routines should be fast. -// Just sayin'. - -// Pins: -// We want to use pins from each of ports B, C and D. So choose wisely. Ports are shown in -// this diagram of the ATmega328P chip. PD0 means "Port D, pin 0". PC3 means "Port C, Pin 3", -// PB2 means "Port B, pin 2" and so on. The corresponding Arduino pins are in parentheses. -// So PB2 is Arduino pin D 10, for example. -/* - +-\/-+ - PC6 1| |28 PC5 (AI 5) - (D 0) PD0 2| |27 PC4 (AI 4) - (D 1) PD1 3| |26 PC3 (AI 3) - (D 2) PD2 4| |25 PC2 (AI 2) - PWM+ (D 3) PD3 5| |24 PC1 (AI 1) - (D 4) PD4 6| |23 PC0 (AI 0) - VCC 7| |22 GND - GND 8| |21 AREF - PB6 9| |20 AVCC - PB7 10| |19 PB5 (D 13) - PWM+ (D 5) PD5 11| |18 PB4 (D 12) - PWM+ (D 6) PD6 12| |17 PB3 (D 11) PWM - (D 7) PD7 13| |16 PB2 (D 10) PWM - (D 8) PB0 14| |15 PB1 (D 9) PWM - +----+ -*/ - -uint8_t pins[6]={ tPIN1, tPIN2, tPIN3, tPIN4, tPIN5, tPIN6 }; -uint8_t ports[6]={ 0, 0, 0, 0, 0, 0 }; - -uint8_t latest_interrupted_pin; -uint8_t interrupt_count[20]={0}; // 20 possible arduino pins -uint8_t port; -uint8_t mode; - -ByteBuffer printBuffer(80); -char charArray[16]; -char numBuffer[4] = { 0, 0, 0, 0 }; -uint8_t printFull=0; - -volatile boolean start=0; -volatile boolean initial=true; -long begintime=0; -long now=0; - -void uint8ToString(char *outString, uint8_t number) { - uint8_t hundreds=0; - uint8_t tens=0; - uint8_t ones=0; - - while (number >= 100 ) { - hundreds++; - number-=100; - } - while (number >= 10 ) { - tens++; - number-=10; - } - ones=number; - ones+=48; - if (hundreds > 0) { hundreds+=48; tens+=48; outString[0]=hundreds; outString[1]=tens; outString[2]=ones; outString[3]=0; } - else if (tens > 0) { tens+=48; outString[0]=tens; outString[1]=ones; outString[2]=0; } - else { outString[0]=ones; outString[1]=0; }; -} - -void showMode() { - switch (mode) { - case FALLING: - printBuffer.putString((char *) "-F-"); - break; - case RISING: - printBuffer.putString((char *) "+R+"); - break; - case CHANGE: - printBuffer.putString((char *) "*C*"); - break; - } -} - -void quicfunc0() { - latest_interrupted_pin=PCintPort::arduinoPin; - mode=PCintPort::pinmode; - showMode(); - if (start==1) { - interrupt_count[latest_interrupted_pin]++; - } - uint8ToString(numBuffer, latest_interrupted_pin); - printBuffer.putString((char *) "f0p"); printBuffer.putString(numBuffer); printBuffer.putString((char *) "-P"); - uint8ToString(numBuffer, digitalPinToPort(latest_interrupted_pin)); - printBuffer.putString(numBuffer); - if (start !=1) printBuffer.putString((char *) " (counting off)"); - printBuffer.putString((char *) "\n"); -}; - -void quicfunc1() { - latest_interrupted_pin=PCintPort::arduinoPin; - mode=PCintPort::pinmode; - showMode(); - if (start==1) { - interrupt_count[latest_interrupted_pin]++; - } - uint8ToString(numBuffer, latest_interrupted_pin); - printBuffer.putString((char *) "f1p"); printBuffer.putString(numBuffer); printBuffer.putString((char *) "-P"); - uint8ToString(numBuffer, digitalPinToPort(latest_interrupted_pin)); - printBuffer.putString(numBuffer); - if (start !=1) printBuffer.putString((char *) " (counting off)"); - printBuffer.putString((char *) "\n"); -}; - -void quicfunc2() { - latest_interrupted_pin=PCintPort::arduinoPin; - mode=PCintPort::pinmode; - showMode(); - if (start == 1) { - printBuffer.putString((char *) "f2: STOP! Counting off.\n"); - printBuffer.putString((char *) "Interrupt OFF on tPIN1 ("); uint8ToString(numBuffer, tPIN1), printBuffer.putString(numBuffer); - printBuffer.putString((char *) ") tPIN3 (");uint8ToString(numBuffer, tPIN3), printBuffer.putString(numBuffer); - printBuffer.putString((char *) ") tPIN5 (");uint8ToString(numBuffer, tPIN5), printBuffer.putString(numBuffer); - printBuffer.putString((char *) ")\n"); - PCintPort::detachInterrupt(tPIN1); PCintPort::detachInterrupt(tPIN3); PCintPort::detachInterrupt(tPIN5); - start=0; - } else { - start=1; - interrupt_count[latest_interrupted_pin]++; - printBuffer.putString((char *) "START! f2p"); - uint8ToString(numBuffer, latest_interrupted_pin); - printBuffer.putString(numBuffer); printBuffer.putString((char *) "-P"); - uint8ToString(numBuffer, digitalPinToPort(latest_interrupted_pin)); - printBuffer.putString(numBuffer); printBuffer.putString((char *) "\n"); - if (! initial) { - PCintPort::attachInterrupt(tPIN1, &quicfunc0, FALLING); - PCintPort::attachInterrupt(tPIN3, &quicfunc0, CHANGE); - PCintPort::attachInterrupt(tPIN5, &quicfunc1, CHANGE); - } else { - initial=false; - } - } -}; - -uint8_t i; -void setup() { - Serial.begin(115200); - delay(250); - Serial.println("Test"); - delay(500); - for (i=0; i < 7; i++) { - pinMode(pins[i], INPUT); digitalWrite(pins[i], HIGH); - ports[i]=digitalPinToPort(pins[i]); - switch (pins[i]) { - case tPIN1: - PCintPort::attachInterrupt(pins[i], &quicfunc0, FALLING); - break; - case tPIN3: - PCintPort::attachInterrupt(pins[i], &quicfunc0, CHANGE); - break; - case tPIN2: - case tPIN4: - PCintPort::attachInterrupt(pins[i], &quicfunc0, RISING); - break; - case tPIN5: - PCintPort::attachInterrupt(pins[i], &quicfunc1, CHANGE); - break; - case tPIN6: - PCintPort::attachInterrupt(pins[i], &quicfunc2, FALLING); - break; - } - } - //Serial.println(printBuffer.getCapacity(), DEC); - //Serial.println("*---------------------------------------*"); - Serial.print("*---*"); - delay(250); - begintime=millis(); -} - -void loop() { - now=millis(); - uint8_t count; - char outChar; - // uint8_t bufsize; - //if (printBuffer.getSize() != 0) { Serial.print("SZ:"); Serial.println (printBuffer.getSize(), DEC); }; - //bufsize=printBuffer.getSize(); - //if (bufsize > 0) { Serial.print("S:"); Serial.println(bufsize); } - while ((outChar=(char)printBuffer.get()) != 0) Serial.print(outChar); - if ((now - begintime) > 1000) { - Serial.print("."); - if (printBuffer.checkError()) { - Serial.println("NOTICE: Some output lost due to filled buffer."); - } - for (i=0; i < 20; i++) { - if (interrupt_count[i] != 0) { - count=interrupt_count[i]; - interrupt_count[i]=0; - Serial.print("Count for pin "); - if (i < 14) { - Serial.print("D"); - Serial.print(i, DEC); - } else { - Serial.print("A"); - Serial.print(i-14, DEC); - } - Serial.print(" is "); - Serial.println(count, DEC); - } - } - begintime=millis(); - } -} - diff --git a/libraries/PinChangeInt/Examples/PinChangeIntTest2/PinChangeIntTest2.ino b/libraries/PinChangeInt/Examples/PinChangeIntTest2/PinChangeIntTest2.ino deleted file mode 100644 index aec34c4..0000000 --- a/libraries/PinChangeInt/Examples/PinChangeIntTest2/PinChangeIntTest2.ino +++ /dev/null @@ -1,275 +0,0 @@ -//#define DISABLE_PCINT_MULTI_SERVICE -#define PINMODE -#define FLASH -#include -#include -#include - -// This example demonstrates a configuration of 6 interrupting pins and 3 interrupt functions. -// A variety of interrupting pins have been chosen, so as to test all PORTs on the Arduino. -// The pins are as follows: -#define tPIN1 2 // port D -#define tPIN2 3 -#define tPIN3 11 // Port B -#define tPIN4 12 -#define tPIN5 A3 // Port C, also can be given as "17" -#define tPIN6 A4 // starts and stops the count - -uint8_t pins[6]={ tPIN1, tPIN2, tPIN3, tPIN4, tPIN5, tPIN6 }; -uint8_t ports[6]={ 0, 0, 0, 0, 0, 0 }; - -uint8_t latest_interrupted_pin; -uint8_t interrupt_count[20]={0}; // 20 possible arduino pins -uint8_t port; -uint8_t mode; - -ByteBuffer printBuffer(200); -char charArray[16]; -char numBuffer[5] = { 0, 0, 0, 0, 0 }; -uint8_t printFull=0; - -volatile boolean start=0; -volatile boolean initial=true; -long begintime=0; -long now=0; - -void uint8ToHexString(char *outString, uint8_t theByte) { - outString[0]='0'; outString[1]='x'; - uint8_t hinybble=theByte>>4; - uint8_t lonybble=theByte & 0x0F; - if (hinybble < 0x0a) outString[2]=hinybble+48; - else outString[2]=hinybble+55; - if (lonybble < 0x0a) outString[3]=lonybble+48; - else outString[3]=lonybble+55; - outString[4]=0; -} - -void uint8ToString(char *outString, uint8_t number) { - uint8_t hundreds=0; - uint8_t tens=0; - uint8_t ones=0; - - while (number >= 100 ) { - hundreds++; - number-=100; - } - while (number >= 10 ) { - tens++; - number-=10; - } - ones=number; - ones+=48; - if (hundreds > 0) { hundreds+=48; tens+=48; outString[0]=hundreds; outString[1]=tens; outString[2]=ones; outString[3]=0; } - else if (tens > 0) { tens+=48; outString[0]=tens; outString[1]=ones; outString[2]=0; } - else { outString[0]=ones; outString[1]=0; }; -} - -void showMode() { - switch (mode) { - case FALLING: - printBuffer.putString(getPSTR("-F-")); - break; - case RISING: - printBuffer.putString(getPSTR("+R+")); - break; - case CHANGE: - printBuffer.putString(getPSTR("*C*")); - break; - } -} - -/* -void quicfunc0() { - latest_interrupted_pin=PCintPort::arduinoPin; - mode=PCintPort::pinmode; - showMode(); - if (start==1) { - interrupt_count[latest_interrupted_pin]++; - } - uint8ToString(numBuffer, latest_interrupted_pin); - printBuffer.putString((char *) "f0p"); printBuffer.putString(numBuffer); printBuffer.putString((char *) "-P"); - uint8ToString(numBuffer, digitalPinToPort(latest_interrupted_pin)); - printBuffer.putString(numBuffer); - if (start !=1) printBuffer.putString(getPSTR(" no count")); - printBuffer.putString((char *) "\n"); -}; - -void quicfunc1() { - latest_interrupted_pin=PCintPort::arduinoPin; - mode=PCintPort::pinmode; - showMode(); - if (start==1) { - interrupt_count[latest_interrupted_pin]++; - } - uint8ToString(numBuffer, latest_interrupted_pin); - printBuffer.putString(getPSTR("f1p")); printBuffer.putString(numBuffer); printBuffer.putString((char *) "-P"); - uint8ToString(numBuffer, digitalPinToPort(latest_interrupted_pin)); - printBuffer.putString(numBuffer); - if (start !=1) printBuffer.putString(getPSTR(" (counting off)")); - printBuffer.putString((char *) "\n"); -}; -*/ - -void quicfunc2() { - //*led_port|=led_mask; - //*led_port&=not_led_mask; // 2 micros to here (ie, 2 micros used to push registers and call subroutine) - latest_interrupted_pin=PCintPort::arduinoPin; - mode=PCintPort::pinmode; - showMode(); - *led_port|=led_mask; // 73 micros to get here from above. Used in "Rigol Timing Example" - *led_port&=not_led_mask; - //uint8ToString(numBuffer, PCintPort::s_count); printBuffer.putString(numBuffer); - *led_port|=led_mask; // 73 micros to get here from above. Second pulse in "Rigol Timing Example" - *led_port&=not_led_mask; - printBuffer.putString(getPSTR(" f2: P"));/* - uint8ToHexString(numBuffer, *portInputRegister(3)); printBuffer.putString(numBuffer);// C port - printBuffer.putString(getPSTR(" pin:")); uint8ToString(numBuffer, latest_interrupted_pin); printBuffer.putString(numBuffer); - printBuffer.putString(getPSTR(" c")); uint8ToHexString(numBuffer, PCintPort::curr); printBuffer.putString(numBuffer); - printBuffer.putString(getPSTR(" l")); uint8ToHexString(numBuffer, PCintPort::s_lastPinView); printBuffer.putString(numBuffer); - printBuffer.putString(getPSTR(" r")); uint8ToHexString(numBuffer, PCintPort::s_portRisingPins); printBuffer.putString(numBuffer); - printBuffer.putString(getPSTR(" f")); uint8ToHexString(numBuffer, PCintPort::s_portFallingPins); printBuffer.putString(numBuffer); - printBuffer.putString(getPSTR(" m")); uint8ToHexString(numBuffer, PCintPort::s_pmask); printBuffer.putString(numBuffer); - printBuffer.putString(getPSTR(" P")); printBuffer.put(PCintPort::s_PORT); printBuffer.putString("\r\n"); - printBuffer.putString(getPSTR("cp")); uint8ToHexString(numBuffer, PCintPort::s_changedPins); printBuffer.putString(numBuffer); - printBuffer.putString(getPSTR(" cXORlpv")); uint8ToHexString(numBuffer, PCintPort::s_currXORlastPinView); printBuffer.putString(numBuffer); - printBuffer.putString(getPSTR(" rp_nCurr")); uint8ToHexString(numBuffer, PCintPort::s_portRisingPins_nCurr); printBuffer.putString(numBuffer); - printBuffer.putString(getPSTR(" fp_nNCurr")); uint8ToHexString(numBuffer, PCintPort::s_portFallingPins_nNCurr); printBuffer.putString(numBuffer); - */printBuffer.putString("\r\n"); - if (PCintPort::pcint_multi > 0) { - printBuffer.putString("MULTI!\n"); PCintPort::pcint_multi=0; - } - if (PCintPort::PCIFRbug > 0) { printBuffer.putString("ERROR: BUG- PCIFR should be reset!"); PCintPort::PCIFRbug=0; } - //s_registers, if it existed, could be used to keep a running queue of the latest interrupts that have - //been serviced by the PCint(). But generally I don't think it's necessary for debugging at this point (famous last words?) - /*if (PCintPort::s_count > 2) { - for (uint8_t i=0; i < PCintPort::s_count; i++) { - uint8ToHexString(numBuffer, PCintPort::s_registers[i]); printBuffer.putString(numBuffer); printBuffer.putString(" "); - } - } - PCintPort::s_count=0;*/ - /* - if (start == 1) { - printBuffer.putString(getPSTR("STOP Count off\n")); - printBuffer.putString(getPSTR("Intr OFF: (")); uint8ToString(numBuffer, tPIN1), printBuffer.putString(numBuffer); - printBuffer.putString((char *) " "); uint8ToString(numBuffer, tPIN3), printBuffer.putString(numBuffer); - printBuffer.putString((char *) " "); uint8ToString(numBuffer, tPIN5), printBuffer.putString(numBuffer); - printBuffer.putString((char *) ")\n"); - PCintPort::detachInterrupt(tPIN1); PCintPort::detachInterrupt(tPIN3); PCintPort::detachInterrupt(tPIN5); - start=0; - } else { - start=1; - interrupt_count[latest_interrupted_pin]++; - printBuffer.putString(getPSTR("START! p")); - uint8ToString(numBuffer, latest_interrupted_pin); - printBuffer.putString(numBuffer); printBuffer.putString((char *) "-P"); - // MIKE put the REAL PORT HERE - uint8ToString(numBuffer, digitalPinToPort(latest_interrupted_pin)); - printBuffer.putString(numBuffer); printBuffer.putString((char *) "\n"); - if (! initial) { - PCintPort::attachInterrupt(tPIN1, &quicfunc0, FALLING); - PCintPort::attachInterrupt(tPIN3, &quicfunc0, CHANGE); - PCintPort::attachInterrupt(tPIN5, &quicfunc1, CHANGE); - } else { - initial=false; - } - }*/ -}; - -uint8_t i; -char hexBuffer[5]; -void setup() { - int8_t returncode=1; - Serial.begin(115200); - Serial.println("Test"); - delay(500); - for (i=5; i < 6; i++) { - pinMode(pins[i], INPUT); digitalWrite(pins[i], HIGH); - ports[i]=digitalPinToPort(pins[i]); - switch (pins[i]) { - /*case tPIN1: - #if PCINT_VERSION > 2100 - returncode=PCintPort::attachInterrupt(pins[i], &quicfunc0, FALLING); - #else - PCintPort::attachInterrupt(pins[i], &quicfunc0, FALLING); - #endif - Serial.println(getPSTR("FIRST FAILURE OK.")); - break; - case tPIN3: - #if PCINT_VERSION > 2100 - returncode=PCintPort::attachInterrupt(pins[i], &quicfunc0, CHANGE); - #else - PCintPort::attachInterrupt(pins[i], &quicfunc0, CHANGE); - #endif - break; - case tPIN2: - case tPIN4: - #if PCINT_VERSION > 2100 - returncode=PCintPort::attachInterrupt(pins[i], &quicfunc0, RISING); - #else - PCintPort::attachInterrupt(pins[i], &quicfunc0, RISING); - #endif - break; - case tPIN5: - #if PCINT_VERSION > 2100 - returncode=PCintPort::attachInterrupt(pins[i], &quicfunc1, CHANGE); - #else - PCintPort::attachInterrupt(pins[i], &quicfunc1, CHANGE); - #endif - break;*/ - case tPIN6: - #if PCINT_VERSION > 2100 - returncode=PCintPort::attachInterrupt(pins[i], &quicfunc2, FALLING); - #else - PCintPort::attachInterrupt(pins[i], &quicfunc2, FALLING); - #endif - break; - } - #if PCINT_VERSION > 2100 - Serial.print(getPSTR("setup(): Interrupt attach ")); - if (returncode != 1) Serial.print(getPSTR("unsuccessful ")); - else Serial.print(getPSTR("GOOD ")); - Serial.print(pins[i], DEC); - Serial.print(getPSTR(":pin, code: ")); Serial.println(returncode, DEC); - #endif - } - //Serial.println(printBuffer.getCapacity(), DEC); - //Serial.println("*---------------------------------------*"); - Serial.print("*---*"); - delay(250); - begintime=millis(); -} - -void loop() { - now=millis(); - uint8_t count; - char outChar; - // uint8_t bufsize; - //if (printBuffer.getSize() != 0) { Serial.print("SZ:"); Serial.println (printBuffer.getSize(), DEC); }; - //bufsize=printBuffer.getSize(); - //if (bufsize > 0) { Serial.print("S:"); Serial.println(bufsize); } - while ((outChar=(char)printBuffer.get()) != 0) Serial.print(outChar); - if ((now - begintime) > 1000) { - Serial.print("."); - if (printBuffer.checkError()) { - Serial.println(getPSTR("!Some output lost due to full buffer!")); - } - for (i=0; i < 20; i++) { - if (interrupt_count[i] != 0) { - count=interrupt_count[i]; - interrupt_count[i]=0; - Serial.print(getPSTR("Count for pin ")); - if (i < 14) { - Serial.print("D"); - Serial.print(i, DEC); - } else { - Serial.print("A"); - Serial.print(i-14, DEC); - } - Serial.print(" is "); - Serial.println(count, DEC); - } - } - begintime=millis(); - } -} - diff --git a/libraries/PinChangeInt/RELEASE_NOTES b/libraries/PinChangeInt/RELEASE_NOTES deleted file mode 100644 index 635e4f8..0000000 --- a/libraries/PinChangeInt/RELEASE_NOTES +++ /dev/null @@ -1,332 +0,0 @@ -****************************************************************************** - - PinChangeInt - ---- RELEASE NOTES --- - -Version 2.19 (beta) Tue Nov 20 07:33:37 CST 2012 -SANGUINO SUPPORT! ...And Mioduino! -...The ATmega644 chip is so cool, how can I not? 4 full ports of Pin Change Interrupt bliss! 32 i/o pins! 64k Flash! 4k RAM! Well I wish I had one. That said, Sanguino users, PLEASE send in your bug or bliss reports! Your interrupt-loving brethren and sistren are depending on you, so I can assure everyone that my changes work on that platform. Thanks. - -Modified the addPin() method to save 12 bytes; thanks again robtilllart! - if (firstPin != NULL) { - tmp=firstPin; - do { - if (tmp->arduinoPin == arduinoPin) { enable(tmp, userFunc, mode); return(0); } - if (tmp->next == NULL) break; - tmp=tmp->next; - } while (true); - } -Also changed the goto in the PCint() loop to be a while/break combination. No change to -code speed, but it looks better and passes the cleanliness "gut check". - -Includes PinChangeIntTest 1.5 sketch. - -...Ooops! Forgot the GetPSTR library, needed for the PinChangeIntTest code! Now it's included. -****************************************************************************** -Version 2.17 (beta) Sat Nov 17 09:46:50 CST 2012 -Another bugfix in the PCINT_MULTI_SERVICE section. I was using sbi(PCIFR, PCICRbit); -I didn't realize that was for I/O ports, and not ATmega registers. -But according to "deprecated.h", -"These macros became obsolete, as reading and writing IO ports can - be done by simply using the IO port name in an expression, and all - bit manipulation (including those on IO ports) can be done using - generic C bit manipulation operators." -So now I do: - PCIFR |= PCICRbit; -****************************************************************************** -Version 2.15 (beta) Sat Nov 17 01:17:44 CST 2012 -Fixed it so that attachInterrupt() will now follow your changes to the user function, -as well as the mode. detachInterrupt() still does not delete the PCintPin object but -at least you can detach and reattach at will, using different modes (RISING, FALLING, -CHANGE) and different functions as you wish. - -****************************************************************************** -Version 2.13 (beta) Mon Nov 12 09:33:06 CST 2012 -SIGNIFICANT BUGFIX release! Significant changes: -1. PCintPort::curr bug. Interrupts that occur rapidly will likely not get serviced properly by PCint(). -2. PCint() interrupt handler optimization. -3. PCIFR port bit set bug fix. -4. Many static variables added for debugging; used only when #define PINMODE is on. -5. detachInterrupt() no longer does a delete(), since that wasn't working anyway. When you detachInterrupt(), the PORT just disables interrupts for that pin; the PCintPin object remains in memory and in the linked list of pins (possibly slowing down your interrupts a couple of micros). You can reenable a detached interrupt- but you must do it within the PinChangeInt library (would anyone ever enable an interrupt on a pin, then disable it, then have need to reenable it but not using the library?). -6. attachInterrupt() now returns a uint8_t value: 1 on successful attach, 0 on successful attach but using an already-enabled pin, and -1 if the new() operator failed to create a PCintPin object. -Also, modified these release notes. - -Details: - -Uncovered a nasty bug, thanks to robtillaart on the Arduino Forums and Andre' Franken who posted to the PinChangeInt groups. This bug was introduced by me when I assigned PCintPort::curr early in the interrupt handler: -ISR(PCINT0_vect) { - PCintPort::curr = portB.portInputReg; - portB.PCint(); -} -Later, in the interrupt handler PCint(), we loop as long as PCIFR indicates a new interrupt wants to be triggered, provided DISABLE_PCINT_MULTI_SERVICE is not defined (it is not by default): -#ifndef DISABLE_PCINT_MULTI_SERVICE - pcifr = PCIFR & PCICRbit; - PCIFR = pcifr; // clear the interrupt if we will process it (no effect if bit is zero) -} while(pcifr); -#endif -...Well. Problem is, if a pin pops up and causes the PCIFR to change, we have to reread the port and look at how it is now! I wasn't doing that before, so if a new interrupt appeared while I was still servicing the old one, odd behavior would take place. For example, an interrupt would register but then the userFunc would not be called upon to service it. The code needs to be: - pcifr = PCIFR & PCICRbit; - PCIFR = pcifr; // clear the interrupt if we will process it (no effect if bit is zero) - PCintPort::curr=portInputReg; // ...Fixed in 2.11beta. -} while(pcifr); - -Also, made the interrupt handler even faster with an optimization from robtillaart to take out the checks for changed pins from the while() loop that steps through the pins: -uint8_t changedPins = (PCintPort::curr ^ lastPinView) & - ((portRisingPins & PCintPort::curr ) | ( portFallingPins & ~PCintPort::curr )); - -...This speedup is offset by more changes in the PCint() handler, which now looks like the following; there are two bug fixes: ----------------------------- -FIX 1: sbi(PCIFR, PCICRbit); -FIX 2: ...the aforementioned PCintPort::curr=portInputReg; -Here's the new code: ----------------------------- - #ifndef DISABLE_PCINT_MULTI_SERVICE - pcifr = PCIFR & PCICRbit; - if (pcifr) { - //if (PCIFR & PCICRbit) { // believe it or not, this adds .6 micros - sbi(PCIFR, PCICRbit); // This was a BUG: PCIFR = pcifr ...And here is the fix. - #ifdef PINMODE - PCintPort::pcint_multi++; - if (PCIFR & PCICRbit) PCintPort::PCIFRbug=1; // PCIFR & PCICRbit should ALWAYS be 0 here! - #endif - PCintPort::curr=portInputReg; // ...Fixed in 2.11beta. - goto loop; // A goto!!! Don't want to look at the portInputReg gratuitously, so the while() will not do. - } - #endif - -Also I added a lot of variables for debugging when PINMODE is defined, for routing out nasty bugs. I may need them in the future... :-( - -Finally, I am not putting newlines in this commentary so I can make it easier to paste online. - -****************************************************************************** -Version 2.11 (beta) Mon Nov 12 09:33:06 CST 2012 -See version 2.13 (beta) above. No change other than tidying up the release notes. -****************************************************************************** - Version 2.01 (beta) Thu Jun 28 12:35:48 CDT 2012 - ...Wow, Version 2! What? Why? - Modified the way that the pin is tested inside the interrupt subroutine (ISR) PCintPort::PCint(), - to make the interrupt quicker and slightly reduce the memory footprint. The interrupt's time is - reduced by 2 microseconds or about 7%. Instead of using the mode variable, two bitmasks are maintained - for each port. One bitmask contains all the pins that are configured to work on RISING signals, the other - on FALLING signals. A pin configured to work on CHANGE signals will appear in both bitmasks of the port. - Then, the test for a change goes like this: - if (thisChangedPin) { - if ((thisChangedPin & portRisingPins & PCintPort::curr ) || - (thisChangedPin & portFallingPins & ~PCintPort::curr )) { - where portRisingPins is the bitmask for the pins configured to interrupt on RISING signals, and - portFallingPins is the bitmask for the pins configured to interrupt on FALLING signals. Each port includes - these two bitmask variables. - - This is a significant change to some core functionality to the library, and it saves an appreciable amount - of time (2 out of 36 or so micros). Hence, the 2.00 designation. - - Tue Jun 26 12:42:20 CDT 2012 - I was officially given permission to use the PCint library: - - Re: PCint library - « Sent to: GreyGnome on: Today at 08:10:33 AM » - « You have forwarded or responded to this message. » - Quote Reply Remove - HI, - Yeah, I wrote the original PCint library. It was a bit of a hack and the new one has better features. - I intended the code to be freely usable. Didn't really think about a license. Feel free to use it in - your code: I hereby grant you permission. - - I'll investigate the MIT license, and see if it is appropriate. - Chris J. Kiick - Robot builder and all around geek. - - Version 1.81 (beta) Tue Jun 19 07:29:08 CDT 2012 - Created the getPCIntVersion function, and its associated GET_PCINT_VERSION preprocessor macro. The version - is a 16-bit int, therefore versions are represented as a 4-digit integer. 1810, then, is the first beta - release of 1.81x series. 1811 would be a bugfix of 1.810. 1820 would be the production release. - - Reversed the order of this list, so the most recent notes come first. - - Made some variables "volatile", because they are changed in the interrupt code. Thanks, Tony Cappellini! - - Added support for the Arduino Mega! Thanks to cserveny...@gmail.com! - NOTE: I don't have a Mega, so I rely on you to give me error (or working) reports! - To sum it up for the Mega: No Port C, no Port D. Instead, you get Port J and Port K. Port B remains. - Port J, however, is practically useless because there is only 1 pin available for interrupts. - Most of the Port J pins are not even connected to a header connector. Caveat Programmer. - - Created a function to report the version of this code. Put this #define ahead of the #include of this file, - in your sketch: - #define GET_PCINT_VERSION - Then you can call - uint16_t getPCIntVersion (); - and it will return a 16-bit integer representation of the version of this library. That is, version 1.73beta - will be reported as "1730". 1.74, then, will return "1740". And so on, for whatever version of the library - this happens to be. The odd number in the 10's position will indicate a beta version, as per usual, and the - number in the 1s place will indicate the beta revision (bugs may necessitate a 1.731, 1.732, etc.). - - Here are some of his notes based on his changes: - Mega and friends are using port B, J and K for interrupts. B is working without any modifications. - - J is mostly useless, because of the hardware UART. I was not able to get pin change notifications from - the TX pin (14), so only 15 left. All other (PORT J) pins are not connected on the Arduino boards. - - K controls Arduino pin A8-A15, working fine. - - 328/168 boards use C and D. So in case the lib is compiled with Mega target, the C and D will be - disabled. Also you cannot see port J/K with other targets. For J and K new flags introduced: - NO_PORTJ_PINCHANGES and NO_PORTK_PINCHANGES. - Maybe we should have PORTJ_PINCHANGES to enable PJ, because they will be most likely unused. - - Enjoy! - - Note: To remain consistent, I have not included PORTJ_PINCHANGES. All ports behave the same, - no matter how trivial those ports may seem... no surprises... - - Version 1.72 Wed Mar 14 18:57:55 CDT 2012 - Release. - - Version 1.71beta Sat Mar 10 12:57:05 CST 2012 - Code reordering: Starting in version 1.3 of this library, I put the code that enables - interrupts for the given pin, and the code that enables Pin Change Interrupts, ahead of actually - setting the user's function for the pin. Thus in the small interval between turning on the - interrupts and actually creating a valid link to an interrupt handler, it is possible to get an - interrupt. At that point the value of the pointer is 0, so this means that the Arduino - will start over again from memory location 0- just as if you'd pressed the reset button. Oops! - - I corrected it so the code now operates in the proper order. - (EDITORIAL NOTE: If you want to really learn something, teach it!) - - Minor code clean-up: All references to PCintPort::curr are now explicit. This changes the compiled - hex code not one whit. I just sleep better at night. - - Numbering: Changed the numbering scheme. Beta versions will end with an odd number in the hundredths - place- because they may be odd- and continue to be marked "beta". I'll just sleep better at night. :-) - - Version 1.70beta Mon Feb 27 07:20:42 CST 2012 - Happy Birthday to me! Happy Birthday tooooo meee! Happy Birthday, Dear Meeeeee-eeeee! - Happy Birthday to me! - - Yes, it is on this auspicious occasion of mine (and Elizabeth Taylor's [R.I.P.]) birthday that I - humbly submit to you, gracious Arduino PinChangeInt user, version 1.70beta of the PinChangeInt - library. I hope you enjoy it. - - New in this release: - The PinChangeIntTest sketch was created, which can be found in the Examples directory. It exercises: - * Two interrupting pins, one on each of the Arduino's PORTs. - * detachInterrupt() (and subsequent attachInterrupt()s). - Hopefully this will help avoid the embarrassing bugs that I have heretofore missed. - - As well, it has come to this author's (GreyGnome) attention that the Serial class in Arduino 1.0 - uses an interrupt that, if you attempt to print from an interrupt (which is what I was doing in my - tests) can easily lock up the Arduino. So I have taken SigurðurOrn's excellent ByteBuffer library - and modified it for my own nefarious purposes. (see http://siggiorn.com/?p=460). The zipfile - comes complete with the ByteBuffer library; see the ByteBuffer/ByteBuffer.h file for a list of - changes, and see the PinChangeIntTest sketch for a usage scenario. Now the (interrupt-less and) - relatively fast operation of filling a circular buffer is used in the interrupt routines. The buffer - is then printed from loop(). - - The library has been modified so it can be used in other libraries, such as my AdaEncoder library - (http://code.google.com/p/adaencoder/). When #include'd by another library you should #define - the LIBCALL_PINCHANGEINT macro. For example: - #ifndef PinChangeInt_h - #define LIBCALL_PINCHANGEINT - #include "../PinChangeInt/PinChangeInt.h" - #endif - This is necessary because the IDE compiles both your sketch and the .cpp file of your library, and - the .h file is included in both places. But since the .h file actually contains the code, any variable - or function definitions would occur twice and cause compilation errors- unless #ifdef'ed out. - - Version 1.6beta Fri Feb 10 08:48:35 CST 2012 - Set the value of the current register settings, first thing in each ISR; e.g., - ISR(PCINT0_vect) { - PCintPort::curr = portB.portInputReg; // version 1.6 - ... - ...instead of at the beginning of the PCintPort::PCint() static method. This means that the port is read - closer to the beginning of the interrupt, and may be slightly more accurate- only by a couple of microseconds, - really, but it's a cheap win. - - Fixed a bug- a BUG!- in the attachInterrupt() and detachInterrupt() methods. I didn't have breaks in my - switch statements! Augh! What am I, a (UNIX) shell programmer? ...Uh, generally, yes... - - Added the PINMODE define and the PCintPort::pinmode variable. - - Version 1.51 Sun Feb 5 23:28:02 CST 2012 - Crap, a bug! Changed line 392 from this: - PCintPort::pinState=curr & changedPins ? HIGH : LOW; - to this: - PCintPort::pinState=curr & p->mask ? HIGH : LOW; - Also added a few lines of (commented-out) debug code. - - Version 1.5 Thu Feb 2 18:09:49 CST 2012 - Added the PCintPort::pinState static variable to allow the programmer to query the state of the pin - at the time of interrupt. - Added two new #defines, NO_PIN_STATE and NO_PIN_NUMBER so as to reduce the code size by 20-50 bytes, - and to speed up the interrupt routine slightly by declaring that you don't care if the static variables - PCintPort::pinState and/or PCintPort::arduinoPin are set and made available to your interrupt routine. - // #define NO_PIN_STATE // to indicate that you don't need the pinState - // #define NO_PIN_NUMBER // to indicate that you don't need the arduinoPin - - Version 1.4 Tue Jan 10 09:41:14 CST 2012 - All the code has been moved into this .h file, so as to allow #define's to work from the user's - sketch. Thanks to Paul Stoffregen from pjrc.com for the inspiration! (Check out his website for - some nice [lots more memory] Arduino-like boards at really good prices. ...This has been an unsolicited - plug. Now back to our regular programming. ...Hehe, "programming", get it?) - - As a result, we no longer use the PinChangeIntConfig.h file. The user must #define things in his/her - sketch. Which is better anyway. - - Removed the pcIntPorts[] array, which created all the ports by default no matter what. Now, only - those ports (PCintPort objects) that you need will get created if you use the NO_PORTx_PINCHANGES #defines. - This saves flash memory, and actually we get a bit of a memory savings anyway even if all the ports are - left enabled. - - The attachInterrupt and detachInterrupt routines were modified to handle the new PCintPort objects. - - Version 1.3 Sat Dec 3 22:56:20 CST 2011 - Significant internal changes: - Tested and modified to work with Arduino 1.0. - - Modified to use the new() operator and symbolic links instead of creating a pre-populated - PCintPins[]. Renamed some variables to simplify or make their meaning more obvious (IMHO anyway). - Modified the PCintPort::PCint() code (ie, the interrupt code) to loop over a linked-list. For - those who love arrays, I have left some code in there that should work to loop over an array - instead. But it is commented out in the release version. - - For Arduino versions prior to 1.0: The new() operator requires the cppfix.h library, which is - included with this package. For Arduino 1.0 and above: new.h comes with the distribution, and - that is #included. - - Version 1.2 Sat Dec 3 Sat Dec 3 09:15:52 CST 2011 - Modified Thu Sep 8 07:33:17 CDT 2011 by GreyGnome. Fixes a bug with the initial port - value. Now it sets the initial value to be the state of the port at the time of - attachInterrupt(). The line is port.PCintLast=port.portInputReg; in attachInterrupt(). - See GreyGnome comment, below. - - Added the "arduinoPin" variable, so the user's function will know exactly which pin on - the Arduino was triggered. - - Version 1.1 Sat Dec 3 00:06:03 CST 2011 - ...updated to fix the "delPin" function as per "pekka"'s bug report. Thanks! - - ---- ^^^ VERSIONS ^^^ (NOTE TO SELF: Update the PCINT_VERSION define, below) ------------- - - See google code project for latest, bugs and info http://code.google.com/p/arduino-pinchangeint/ - For more information Refer to avr-gcc header files, arduino source and atmega datasheet. - - This library was inspired by and derived from "johnboiles" (it seems) - PCInt Arduino Playground example here: http://www.arduino.cc/playground/Main/PcInt - If you are the original author, please let us know at the google code page - - It provides an extension to the interrupt support for arduino by - adding pin change interrupts, giving a way for users to have - interrupts drive off of any pin. - - 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 . diff --git a/libraries/PinChangeInt/gpl.txt b/libraries/PinChangeInt/gpl.txt deleted file mode 100644 index 94a9ed0..0000000 --- a/libraries/PinChangeInt/gpl.txt +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/libraries/PinChangeInt/keywords.txt b/libraries/PinChangeInt/keywords.txt deleted file mode 100644 index 24e1cec..0000000 --- a/libraries/PinChangeInt/keywords.txt +++ /dev/null @@ -1,10 +0,0 @@ -# LITERAL1 specifies constants - -# KEYWORD1 specifies datatypes and C/C++ keywords -pinState KEYWORD1 PinState -arduinoPin KEYWORD1 ArduinoPin -PCintPort KEYWORD1 PCInterruptPort - -# KEYWORD2 specifies methods and functions -attachInterrupt KEYWORD2 AttachInterrupt -detachInterrupt KEYWORD2 DetachInterrupt diff --git a/libraries/RF24/.gitignore b/libraries/RF24/.gitignore deleted file mode 100644 index 1ac5497..0000000 --- a/libraries/RF24/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -*.bak -*.o -.*.swp -*.orig -.swp -docs/ -output/ -ojam/ -version.h -Session.vim diff --git a/libraries/RF24/Doxyfile b/libraries/RF24/Doxyfile deleted file mode 100644 index 2bd1ea0..0000000 --- a/libraries/RF24/Doxyfile +++ /dev/null @@ -1,1551 +0,0 @@ -# Doxyfile 1.6.3 - -# This file describes the settings to be used by the documentation system -# doxygen (www.doxygen.org) for a project -# -# All text after a hash (#) is considered a comment and will be ignored -# The format is: -# TAG = value [value, ...] -# For lists items can also be appended using: -# TAG += value [value, ...] -# Values that contain spaces should be placed between quotes (" ") - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- - -# This tag specifies the encoding used for all characters in the config file -# that follow. The default is UTF-8 which is also the encoding used for all -# text before the first occurrence of this tag. Doxygen uses libiconv (or the -# iconv built into libc) for the transcoding. See -# http://www.gnu.org/software/libiconv for the list of possible encodings. - -DOXYFILE_ENCODING = UTF-8 - -# The PROJECT_NAME tag is a single word (or a sequence of words surrounded -# by quotes) that should identify the project. - -PROJECT_NAME = RF24 - -# The PROJECT_NUMBER tag can be used to enter a project or revision number. -# This could be handy for archiving the generated documentation or -# if some version control system is used. - -PROJECT_NUMBER = v1 - -# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) -# base path where the generated documentation will be put. -# If a relative path is entered, it will be relative to the location -# where doxygen was started. If left blank the current directory will be used. - -OUTPUT_DIRECTORY = docs - -# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create -# 4096 sub-directories (in 2 levels) under the output directory of each output -# format and will distribute the generated files over these directories. -# Enabling this option can be useful when feeding doxygen a huge amount of -# source files, where putting all generated files in the same directory would -# otherwise cause performance problems for the file system. - -CREATE_SUBDIRS = NO - -# The OUTPUT_LANGUAGE tag is used to specify the language in which all -# documentation generated by doxygen is written. Doxygen will use this -# information to generate all constant output in the proper language. -# The default language is English, other supported languages are: -# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, -# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, -# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English -# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, -# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak, -# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. - -OUTPUT_LANGUAGE = English - -# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will -# include brief member descriptions after the members that are listed in -# the file and class documentation (similar to JavaDoc). -# Set to NO to disable this. - -BRIEF_MEMBER_DESC = YES - -# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend -# the brief description of a member or function before the detailed description. -# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the -# brief descriptions will be completely suppressed. - -REPEAT_BRIEF = YES - -# This tag implements a quasi-intelligent brief description abbreviator -# that is used to form the text in various listings. Each string -# in this list, if found as the leading text of the brief description, will be -# stripped from the text and the result after processing the whole list, is -# used as the annotated text. Otherwise, the brief description is used as-is. -# If left blank, the following values are used ("$name" is automatically -# replaced with the name of the entity): "The $name class" "The $name widget" -# "The $name file" "is" "provides" "specifies" "contains" -# "represents" "a" "an" "the" - -ABBREVIATE_BRIEF = - -# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then -# Doxygen will generate a detailed section even if there is only a brief -# description. - -ALWAYS_DETAILED_SEC = NO - -# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all -# inherited members of a class in the documentation of that class as if those -# members were ordinary class members. Constructors, destructors and assignment -# operators of the base classes will not be shown. - -INLINE_INHERITED_MEMB = NO - -# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full -# path before files name in the file list and in the header files. If set -# to NO the shortest path that makes the file name unique will be used. - -FULL_PATH_NAMES = YES - -# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag -# can be used to strip a user-defined part of the path. Stripping is -# only done if one of the specified strings matches the left-hand part of -# the path. The tag can be used to show relative paths in the file list. -# If left blank the directory from which doxygen is run is used as the -# path to strip. - -STRIP_FROM_PATH = - -# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of -# the path mentioned in the documentation of a class, which tells -# the reader which header file to include in order to use a class. -# If left blank only the name of the header file containing the class -# definition is used. Otherwise one should specify the include paths that -# are normally passed to the compiler using the -I flag. - -STRIP_FROM_INC_PATH = - -# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter -# (but less readable) file names. This can be useful is your file systems -# doesn't support long names like on DOS, Mac, or CD-ROM. - -SHORT_NAMES = NO - -# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen -# will interpret the first line (until the first dot) of a JavaDoc-style -# comment as the brief description. If set to NO, the JavaDoc -# comments will behave just like regular Qt-style comments -# (thus requiring an explicit @brief command for a brief description.) - -JAVADOC_AUTOBRIEF = YES - -# If the QT_AUTOBRIEF tag is set to YES then Doxygen will -# interpret the first line (until the first dot) of a Qt-style -# comment as the brief description. If set to NO, the comments -# will behave just like regular Qt-style comments (thus requiring -# an explicit \brief command for a brief description.) - -QT_AUTOBRIEF = YES - -# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen -# treat a multi-line C++ special comment block (i.e. a block of //! or /// -# comments) as a brief description. This used to be the default behaviour. -# The new default is to treat a multi-line C++ comment block as a detailed -# description. Set this tag to YES if you prefer the old behaviour instead. - -MULTILINE_CPP_IS_BRIEF = NO - -# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented -# member inherits the documentation from any documented member that it -# re-implements. - -INHERIT_DOCS = YES - -# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce -# a new page for each member. If set to NO, the documentation of a member will -# be part of the file/class/namespace that contains it. - -SEPARATE_MEMBER_PAGES = NO - -# The TAB_SIZE tag can be used to set the number of spaces in a tab. -# Doxygen uses this value to replace tabs by spaces in code fragments. - -TAB_SIZE = 8 - -# This tag can be used to specify a number of aliases that acts -# as commands in the documentation. An alias has the form "name=value". -# For example adding "sideeffect=\par Side Effects:\n" will allow you to -# put the command \sideeffect (or @sideeffect) in the documentation, which -# will result in a user-defined paragraph with heading "Side Effects:". -# You can put \n's in the value part of an alias to insert newlines. - -ALIASES = - -# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C -# sources only. Doxygen will then generate output that is more tailored for C. -# For instance, some of the names that are used will be different. The list -# of all members will be omitted, etc. - -OPTIMIZE_OUTPUT_FOR_C = NO - -# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java -# sources only. Doxygen will then generate output that is more tailored for -# Java. For instance, namespaces will be presented as packages, qualified -# scopes will look different, etc. - -OPTIMIZE_OUTPUT_JAVA = NO - -# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran -# sources only. Doxygen will then generate output that is more tailored for -# Fortran. - -OPTIMIZE_FOR_FORTRAN = NO - -# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL -# sources. Doxygen will then generate output that is tailored for -# VHDL. - -OPTIMIZE_OUTPUT_VHDL = NO - -# Doxygen selects the parser to use depending on the extension of the files it parses. -# With this tag you can assign which parser to use for a given extension. -# Doxygen has a built-in mapping, but you can override or extend it using this tag. -# The format is ext=language, where ext is a file extension, and language is one of -# the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP, -# Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat -# .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran), -# use: inc=Fortran f=C. Note that for custom extensions you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. - -EXTENSION_MAPPING = - -# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want -# to include (a tag file for) the STL sources as input, then you should -# set this tag to YES in order to let doxygen match functions declarations and -# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. -# func(std::string) {}). This also make the inheritance and collaboration -# diagrams that involve STL classes more complete and accurate. - -BUILTIN_STL_SUPPORT = NO - -# If you use Microsoft's C++/CLI language, you should set this option to YES to -# enable parsing support. - -CPP_CLI_SUPPORT = NO - -# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. -# Doxygen will parse them like normal C++ but will assume all classes use public -# instead of private inheritance when no explicit protection keyword is present. - -SIP_SUPPORT = NO - -# For Microsoft's IDL there are propget and propput attributes to indicate getter -# and setter methods for a property. Setting this option to YES (the default) -# will make doxygen to replace the get and set methods by a property in the -# documentation. This will only work if the methods are indeed getting or -# setting a simple type. If this is not the case, or you want to show the -# methods anyway, you should set this option to NO. - -IDL_PROPERTY_SUPPORT = YES - -# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC -# tag is set to YES, then doxygen will reuse the documentation of the first -# member in the group (if any) for the other members of the group. By default -# all members of a group must be documented explicitly. - -DISTRIBUTE_GROUP_DOC = NO - -# Set the SUBGROUPING tag to YES (the default) to allow class member groups of -# the same type (for instance a group of public functions) to be put as a -# subgroup of that type (e.g. under the Public Functions section). Set it to -# NO to prevent subgrouping. Alternatively, this can be done per class using -# the \nosubgrouping command. - -SUBGROUPING = YES - -# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum -# is documented as struct, union, or enum with the name of the typedef. So -# typedef struct TypeS {} TypeT, will appear in the documentation as a struct -# with name TypeT. When disabled the typedef will appear as a member of a file, -# namespace, or class. And the struct will be named TypeS. This can typically -# be useful for C code in case the coding convention dictates that all compound -# types are typedef'ed and only the typedef is referenced, never the tag name. - -TYPEDEF_HIDES_STRUCT = NO - -# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to -# determine which symbols to keep in memory and which to flush to disk. -# When the cache is full, less often used symbols will be written to disk. -# For small to medium size projects (<1000 input files) the default value is -# probably good enough. For larger projects a too small cache size can cause -# doxygen to be busy swapping symbols to and from disk most of the time -# causing a significant performance penality. -# If the system has enough physical memory increasing the cache will improve the -# performance by keeping more symbols in memory. Note that the value works on -# a logarithmic scale so increasing the size by one will rougly double the -# memory usage. The cache size is given by this formula: -# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, -# corresponding to a cache size of 2^16 = 65536 symbols - -SYMBOL_CACHE_SIZE = 0 - -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- - -# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in -# documentation are documented, even if no documentation was available. -# Private class members and static file members will be hidden unless -# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES - -EXTRACT_ALL = NO - -# If the EXTRACT_PRIVATE tag is set to YES all private members of a class -# will be included in the documentation. - -EXTRACT_PRIVATE = NO - -# If the EXTRACT_STATIC tag is set to YES all static members of a file -# will be included in the documentation. - -EXTRACT_STATIC = NO - -# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) -# defined locally in source files will be included in the documentation. -# If set to NO only classes defined in header files are included. - -EXTRACT_LOCAL_CLASSES = YES - -# This flag is only useful for Objective-C code. When set to YES local -# methods, which are defined in the implementation section but not in -# the interface are included in the documentation. -# If set to NO (the default) only methods in the interface are included. - -EXTRACT_LOCAL_METHODS = NO - -# If this flag is set to YES, the members of anonymous namespaces will be -# extracted and appear in the documentation as a namespace called -# 'anonymous_namespace{file}', where file will be replaced with the base -# name of the file that contains the anonymous namespace. By default -# anonymous namespace are hidden. - -EXTRACT_ANON_NSPACES = NO - -# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all -# undocumented members of documented classes, files or namespaces. -# If set to NO (the default) these members will be included in the -# various overviews, but no documentation section is generated. -# This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_MEMBERS = NO - -# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all -# undocumented classes that are normally visible in the class hierarchy. -# If set to NO (the default) these classes will be included in the various -# overviews. This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_CLASSES = NO - -# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all -# friend (class|struct|union) declarations. -# If set to NO (the default) these declarations will be included in the -# documentation. - -HIDE_FRIEND_COMPOUNDS = NO - -# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any -# documentation blocks found inside the body of a function. -# If set to NO (the default) these blocks will be appended to the -# function's detailed documentation block. - -HIDE_IN_BODY_DOCS = NO - -# The INTERNAL_DOCS tag determines if documentation -# that is typed after a \internal command is included. If the tag is set -# to NO (the default) then the documentation will be excluded. -# Set it to YES to include the internal documentation. - -INTERNAL_DOCS = NO - -# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate -# file names in lower-case letters. If set to YES upper-case letters are also -# allowed. This is useful if you have classes or files whose names only differ -# in case and if your file system supports case sensitive file names. Windows -# and Mac users are advised to set this option to NO. - -CASE_SENSE_NAMES = YES - -# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen -# will show members with their full class and namespace scopes in the -# documentation. If set to YES the scope will be hidden. - -HIDE_SCOPE_NAMES = NO - -# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen -# will put a list of the files that are included by a file in the documentation -# of that file. - -SHOW_INCLUDE_FILES = YES - -# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen -# will list include files with double quotes in the documentation -# rather than with sharp brackets. - -FORCE_LOCAL_INCLUDES = NO - -# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] -# is inserted in the documentation for inline members. - -INLINE_INFO = YES - -# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen -# will sort the (detailed) documentation of file and class members -# alphabetically by member name. If set to NO the members will appear in -# declaration order. - -SORT_MEMBER_DOCS = YES - -# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the -# brief documentation of file, namespace and class members alphabetically -# by member name. If set to NO (the default) the members will appear in -# declaration order. - -SORT_BRIEF_DOCS = NO - -# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the (brief and detailed) documentation of class members so that constructors and destructors are listed first. If set to NO (the default) the constructors will appear in the respective orders defined by SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. - -SORT_MEMBERS_CTORS_1ST = NO - -# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the -# hierarchy of group names into alphabetical order. If set to NO (the default) -# the group names will appear in their defined order. - -SORT_GROUP_NAMES = NO - -# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be -# sorted by fully-qualified names, including namespaces. If set to -# NO (the default), the class list will be sorted only by class name, -# not including the namespace part. -# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. -# Note: This option applies only to the class list, not to the -# alphabetical list. - -SORT_BY_SCOPE_NAME = NO - -# The GENERATE_TODOLIST tag can be used to enable (YES) or -# disable (NO) the todo list. This list is created by putting \todo -# commands in the documentation. - -GENERATE_TODOLIST = YES - -# The GENERATE_TESTLIST tag can be used to enable (YES) or -# disable (NO) the test list. This list is created by putting \test -# commands in the documentation. - -GENERATE_TESTLIST = YES - -# The GENERATE_BUGLIST tag can be used to enable (YES) or -# disable (NO) the bug list. This list is created by putting \bug -# commands in the documentation. - -GENERATE_BUGLIST = YES - -# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or -# disable (NO) the deprecated list. This list is created by putting -# \deprecated commands in the documentation. - -GENERATE_DEPRECATEDLIST= YES - -# The ENABLED_SECTIONS tag can be used to enable conditional -# documentation sections, marked by \if sectionname ... \endif. - -ENABLED_SECTIONS = - -# The MAX_INITIALIZER_LINES tag determines the maximum number of lines -# the initial value of a variable or define consists of for it to appear in -# the documentation. If the initializer consists of more lines than specified -# here it will be hidden. Use a value of 0 to hide initializers completely. -# The appearance of the initializer of individual variables and defines in the -# documentation can be controlled using \showinitializer or \hideinitializer -# command in the documentation regardless of this setting. - -MAX_INITIALIZER_LINES = 30 - -# Set the SHOW_USED_FILES tag to NO to disable the list of files generated -# at the bottom of the documentation of classes and structs. If set to YES the -# list will mention the files that were used to generate the documentation. - -SHOW_USED_FILES = YES - -# If the sources in your project are distributed over multiple directories -# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy -# in the documentation. The default is NO. - -SHOW_DIRECTORIES = NO - -# Set the SHOW_FILES tag to NO to disable the generation of the Files page. -# This will remove the Files entry from the Quick Index and from the -# Folder Tree View (if specified). The default is YES. - -SHOW_FILES = YES - -# Set the SHOW_NAMESPACES tag to NO to disable the generation of the -# Namespaces page. -# This will remove the Namespaces entry from the Quick Index -# and from the Folder Tree View (if specified). The default is YES. - -SHOW_NAMESPACES = YES - -# The FILE_VERSION_FILTER tag can be used to specify a program or script that -# doxygen should invoke to get the current version for each file (typically from -# the version control system). Doxygen will invoke the program by executing (via -# popen()) the command , where is the value of -# the FILE_VERSION_FILTER tag, and is the name of an input file -# provided by doxygen. Whatever the program writes to standard output -# is used as the file version. See the manual for examples. - -FILE_VERSION_FILTER = - -# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by -# doxygen. The layout file controls the global structure of the generated output files -# in an output format independent way. The create the layout file that represents -# doxygen's defaults, run doxygen with the -l option. You can optionally specify a -# file name after the option, if omitted DoxygenLayout.xml will be used as the name -# of the layout file. - -LAYOUT_FILE = - -#--------------------------------------------------------------------------- -# configuration options related to warning and progress messages -#--------------------------------------------------------------------------- - -# The QUIET tag can be used to turn on/off the messages that are generated -# by doxygen. Possible values are YES and NO. If left blank NO is used. - -QUIET = NO - -# The WARNINGS tag can be used to turn on/off the warning messages that are -# generated by doxygen. Possible values are YES and NO. If left blank -# NO is used. - -WARNINGS = YES - -# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings -# for undocumented members. If EXTRACT_ALL is set to YES then this flag will -# automatically be disabled. - -WARN_IF_UNDOCUMENTED = YES - -# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for -# potential errors in the documentation, such as not documenting some -# parameters in a documented function, or documenting parameters that -# don't exist or using markup commands wrongly. - -WARN_IF_DOC_ERROR = YES - -# This WARN_NO_PARAMDOC option can be abled to get warnings for -# functions that are documented, but have no documentation for their parameters -# or return value. If set to NO (the default) doxygen will only warn about -# wrong or incomplete parameter documentation, but not about the absence of -# documentation. - -WARN_NO_PARAMDOC = NO - -# The WARN_FORMAT tag determines the format of the warning messages that -# doxygen can produce. The string should contain the $file, $line, and $text -# tags, which will be replaced by the file and line number from which the -# warning originated and the warning text. Optionally the format may contain -# $version, which will be replaced by the version of the file (if it could -# be obtained via FILE_VERSION_FILTER) - -WARN_FORMAT = "$file:$line: $text" - -# The WARN_LOGFILE tag can be used to specify a file to which warning -# and error messages should be written. If left blank the output is written -# to stderr. - -WARN_LOGFILE = - -#--------------------------------------------------------------------------- -# configuration options related to the input files -#--------------------------------------------------------------------------- - -# The INPUT tag can be used to specify the files and/or directories that contain -# documented source files. You may enter file names like "myfile.cpp" or -# directories like "/usr/src/myproject". Separate the files or directories -# with spaces. - -INPUT = . - -# This tag can be used to specify the character encoding of the source files -# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is -# also the default input encoding. Doxygen uses libiconv (or the iconv built -# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for -# the list of possible encodings. - -INPUT_ENCODING = UTF-8 - -# If the value of the INPUT tag contains directories, you can use the -# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp -# and *.h) to filter out the source-files in the directories. If left -# blank the following patterns are tested: -# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx -# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90 - -FILE_PATTERNS = *.h FAQ - -# The RECURSIVE tag can be used to turn specify whether or not subdirectories -# should be searched for input files as well. Possible values are YES and NO. -# If left blank NO is used. - -RECURSIVE = NO - -# The EXCLUDE tag can be used to specify files and/or directories that should -# excluded from the INPUT source files. This way you can easily exclude a -# subdirectory from a directory tree whose root is specified with the INPUT tag. - -EXCLUDE = - -# The EXCLUDE_SYMLINKS tag can be used select whether or not files or -# directories that are symbolic links (a Unix filesystem feature) are excluded -# from the input. - -EXCLUDE_SYMLINKS = NO - -# If the value of the INPUT tag contains directories, you can use the -# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude -# certain files from those directories. Note that the wildcards are matched -# against the file with absolute path, so to exclude all test directories -# for example use the pattern */test/* - -EXCLUDE_PATTERNS = - -# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names -# (namespaces, classes, functions, etc.) that should be excluded from the -# output. The symbol name can be a fully qualified name, a word, or if the -# wildcard * is used, a substring. Examples: ANamespace, AClass, -# AClass::ANamespace, ANamespace::*Test - -EXCLUDE_SYMBOLS = - -# The EXAMPLE_PATH tag can be used to specify one or more files or -# directories that contain example code fragments that are included (see -# the \include command). - -EXAMPLE_PATH = examples - -# If the value of the EXAMPLE_PATH tag contains directories, you can use the -# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp -# and *.h) to filter out the source-files in the directories. If left -# blank all files are included. - -EXAMPLE_PATTERNS = - -# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be -# searched for input files to be used with the \include or \dontinclude -# commands irrespective of the value of the RECURSIVE tag. -# Possible values are YES and NO. If left blank NO is used. - -EXAMPLE_RECURSIVE = YES - -# The IMAGE_PATH tag can be used to specify one or more files or -# directories that contain image that are included in the documentation (see -# the \image command). - -IMAGE_PATH = - -# The INPUT_FILTER tag can be used to specify a program that doxygen should -# invoke to filter for each input file. Doxygen will invoke the filter program -# by executing (via popen()) the command , where -# is the value of the INPUT_FILTER tag, and is the name of an -# input file. Doxygen will then use the output that the filter program writes -# to standard output. -# If FILTER_PATTERNS is specified, this tag will be -# ignored. - -INPUT_FILTER = - -# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern -# basis. -# Doxygen will compare the file name with each pattern and apply the -# filter if there is a match. -# The filters are a list of the form: -# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further -# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER -# is applied to all files. - -FILTER_PATTERNS = - -# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using -# INPUT_FILTER) will be used to filter the input files when producing source -# files to browse (i.e. when SOURCE_BROWSER is set to YES). - -FILTER_SOURCE_FILES = NO - -#--------------------------------------------------------------------------- -# configuration options related to source browsing -#--------------------------------------------------------------------------- - -# If the SOURCE_BROWSER tag is set to YES then a list of source files will -# be generated. Documented entities will be cross-referenced with these sources. -# Note: To get rid of all source code in the generated output, make sure also -# VERBATIM_HEADERS is set to NO. - -SOURCE_BROWSER = NO - -# Setting the INLINE_SOURCES tag to YES will include the body -# of functions and classes directly in the documentation. - -INLINE_SOURCES = NO - -# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct -# doxygen to hide any special comment blocks from generated source code -# fragments. Normal C and C++ comments will always remain visible. - -STRIP_CODE_COMMENTS = YES - -# If the REFERENCED_BY_RELATION tag is set to YES -# then for each documented function all documented -# functions referencing it will be listed. - -REFERENCED_BY_RELATION = NO - -# If the REFERENCES_RELATION tag is set to YES -# then for each documented function all documented entities -# called/used by that function will be listed. - -REFERENCES_RELATION = NO - -# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) -# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from -# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will -# link to the source code. -# Otherwise they will link to the documentation. - -REFERENCES_LINK_SOURCE = NO - -# If the USE_HTAGS tag is set to YES then the references to source code -# will point to the HTML generated by the htags(1) tool instead of doxygen -# built-in source browser. The htags tool is part of GNU's global source -# tagging system (see http://www.gnu.org/software/global/global.html). You -# will need version 4.8.6 or higher. - -USE_HTAGS = NO - -# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen -# will generate a verbatim copy of the header file for each class for -# which an include is specified. Set to NO to disable this. - -VERBATIM_HEADERS = YES - -#--------------------------------------------------------------------------- -# configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- - -# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index -# of all compounds will be generated. Enable this if the project -# contains a lot of classes, structs, unions or interfaces. - -ALPHABETICAL_INDEX = NO - -# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then -# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns -# in which this list will be split (can be a number in the range [1..20]) - -COLS_IN_ALPHA_INDEX = 5 - -# In case all classes in a project start with a common prefix, all -# classes will be put under the same header in the alphabetical index. -# The IGNORE_PREFIX tag can be used to specify one or more prefixes that -# should be ignored while generating the index headers. - -IGNORE_PREFIX = - -#--------------------------------------------------------------------------- -# configuration options related to the HTML output -#--------------------------------------------------------------------------- - -# If the GENERATE_HTML tag is set to YES (the default) Doxygen will -# generate HTML output. - -GENERATE_HTML = YES - -# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `html' will be used as the default path. - -HTML_OUTPUT = html - -# The HTML_FILE_EXTENSION tag can be used to specify the file extension for -# each generated HTML page (for example: .htm,.php,.asp). If it is left blank -# doxygen will generate files with .html extension. - -HTML_FILE_EXTENSION = .html - -# The HTML_HEADER tag can be used to specify a personal HTML header for -# each generated HTML page. If it is left blank doxygen will generate a -# standard header. - -HTML_HEADER = - -# The HTML_FOOTER tag can be used to specify a personal HTML footer for -# each generated HTML page. If it is left blank doxygen will generate a -# standard footer. - -HTML_FOOTER = - -# The HTML_STYLESHEET tag can be used to specify a user-defined cascading -# style sheet that is used by each HTML page. It can be used to -# fine-tune the look of the HTML output. If the tag is left blank doxygen -# will generate a default style sheet. Note that doxygen will try to copy -# the style sheet file to the HTML output directory, so don't put your own -# stylesheet in the HTML output directory as well, or it will be erased! - -HTML_STYLESHEET = - -# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML -# page will contain the date and time when the page was generated. Setting -# this to NO can help when comparing the output of multiple runs. - -HTML_TIMESTAMP = YES - -# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, -# files or namespaces will be aligned in HTML using tables. If set to -# NO a bullet list will be used. - -HTML_ALIGN_MEMBERS = YES - -# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML -# documentation will contain sections that can be hidden and shown after the -# page has loaded. For this to work a browser that supports -# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox -# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). - -HTML_DYNAMIC_SECTIONS = NO - -# If the GENERATE_DOCSET tag is set to YES, additional index files -# will be generated that can be used as input for Apple's Xcode 3 -# integrated development environment, introduced with OSX 10.5 (Leopard). -# To create a documentation set, doxygen will generate a Makefile in the -# HTML output directory. Running make will produce the docset in that -# directory and running "make install" will install the docset in -# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find -# it at startup. -# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information. - -GENERATE_DOCSET = NO - -# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the -# feed. A documentation feed provides an umbrella under which multiple -# documentation sets from a single provider (such as a company or product suite) -# can be grouped. - -DOCSET_FEEDNAME = "Doxygen generated docs" - -# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that -# should uniquely identify the documentation set bundle. This should be a -# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen -# will append .docset to the name. - -DOCSET_BUNDLE_ID = org.doxygen.Project - -# If the GENERATE_HTMLHELP tag is set to YES, additional index files -# will be generated that can be used as input for tools like the -# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) -# of the generated HTML documentation. - -GENERATE_HTMLHELP = NO - -# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can -# be used to specify the file name of the resulting .chm file. You -# can add a path in front of the file if the result should not be -# written to the html output directory. - -CHM_FILE = - -# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can -# be used to specify the location (absolute path including file name) of -# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run -# the HTML help compiler on the generated index.hhp. - -HHC_LOCATION = - -# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag -# controls if a separate .chi index file is generated (YES) or that -# it should be included in the master .chm file (NO). - -GENERATE_CHI = NO - -# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING -# is used to encode HtmlHelp index (hhk), content (hhc) and project file -# content. - -CHM_INDEX_ENCODING = - -# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag -# controls whether a binary table of contents is generated (YES) or a -# normal table of contents (NO) in the .chm file. - -BINARY_TOC = NO - -# The TOC_EXPAND flag can be set to YES to add extra items for group members -# to the contents of the HTML help documentation and to the tree view. - -TOC_EXPAND = NO - -# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER -# are set, an additional index file will be generated that can be used as input for -# Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated -# HTML documentation. - -GENERATE_QHP = NO - -# If the QHG_LOCATION tag is specified, the QCH_FILE tag can -# be used to specify the file name of the resulting .qch file. -# The path specified is relative to the HTML output folder. - -QCH_FILE = - -# The QHP_NAMESPACE tag specifies the namespace to use when generating -# Qt Help Project output. For more information please see -# http://doc.trolltech.com/qthelpproject.html#namespace - -QHP_NAMESPACE = org.doxygen.Project - -# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating -# Qt Help Project output. For more information please see -# http://doc.trolltech.com/qthelpproject.html#virtual-folders - -QHP_VIRTUAL_FOLDER = doc - -# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add. -# For more information please see -# http://doc.trolltech.com/qthelpproject.html#custom-filters - -QHP_CUST_FILTER_NAME = - -# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see -# Qt Help Project / Custom Filters. - -QHP_CUST_FILTER_ATTRS = - -# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's -# filter section matches. -# Qt Help Project / Filter Attributes. - -QHP_SECT_FILTER_ATTRS = - -# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can -# be used to specify the location of Qt's qhelpgenerator. -# If non-empty doxygen will try to run qhelpgenerator on the generated -# .qhp file. - -QHG_LOCATION = - -# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files -# will be generated, which together with the HTML files, form an Eclipse help -# plugin. To install this plugin and make it available under the help contents -# menu in Eclipse, the contents of the directory containing the HTML and XML -# files needs to be copied into the plugins directory of eclipse. The name of -# the directory within the plugins directory should be the same as -# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before the help appears. - -GENERATE_ECLIPSEHELP = NO - -# A unique identifier for the eclipse help plugin. When installing the plugin -# the directory name containing the HTML and XML files should also have -# this name. - -ECLIPSE_DOC_ID = org.doxygen.Project - -# The DISABLE_INDEX tag can be used to turn on/off the condensed index at -# top of each HTML page. The value NO (the default) enables the index and -# the value YES disables it. - -DISABLE_INDEX = NO - -# This tag can be used to set the number of enum values (range [1..20]) -# that doxygen will group on one line in the generated HTML documentation. - -ENUM_VALUES_PER_LINE = 4 - -# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index -# structure should be generated to display hierarchical information. -# If the tag value is set to YES, a side panel will be generated -# containing a tree-like index structure (just like the one that -# is generated for HTML Help). For this to work a browser that supports -# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). -# Windows users are probably better off using the HTML help feature. - -GENERATE_TREEVIEW = NO - -# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, -# and Class Hierarchy pages using a tree view instead of an ordered list. - -USE_INLINE_TREES = NO - -# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be -# used to set the initial width (in pixels) of the frame in which the tree -# is shown. - -TREEVIEW_WIDTH = 250 - -# Use this tag to change the font size of Latex formulas included -# as images in the HTML documentation. The default is 10. Note that -# when you change the font size after a successful doxygen run you need -# to manually remove any form_*.png images from the HTML output directory -# to force them to be regenerated. - -FORMULA_FONTSIZE = 10 - -# When the SEARCHENGINE tag is enabled doxygen will generate a search box for the HTML output. The underlying search engine uses javascript -# and DHTML and should work on any modern browser. Note that when using HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) there is already a search function so this one should -# typically be disabled. For large projects the javascript based search engine -# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. - -SEARCHENGINE = YES - -# When the SERVER_BASED_SEARCH tag is enabled the search engine will be implemented using a PHP enabled web server instead of at the web client using Javascript. Doxygen will generate the search PHP script and index -# file to put on the web server. The advantage of the server based approach is that it scales better to large projects and allows full text search. The disadvances is that it is more difficult to setup -# and does not have live searching capabilities. - -SERVER_BASED_SEARCH = NO - -#--------------------------------------------------------------------------- -# configuration options related to the LaTeX output -#--------------------------------------------------------------------------- - -# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will -# generate Latex output. - -GENERATE_LATEX = NO - -# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `latex' will be used as the default path. - -LATEX_OUTPUT = latex - -# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be -# invoked. If left blank `latex' will be used as the default command name. -# Note that when enabling USE_PDFLATEX this option is only used for -# generating bitmaps for formulas in the HTML output, but not in the -# Makefile that is written to the output directory. - -LATEX_CMD_NAME = latex - -# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to -# generate index for LaTeX. If left blank `makeindex' will be used as the -# default command name. - -MAKEINDEX_CMD_NAME = makeindex - -# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact -# LaTeX documents. This may be useful for small projects and may help to -# save some trees in general. - -COMPACT_LATEX = NO - -# The PAPER_TYPE tag can be used to set the paper type that is used -# by the printer. Possible values are: a4, a4wide, letter, legal and -# executive. If left blank a4wide will be used. - -PAPER_TYPE = a4wide - -# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX -# packages that should be included in the LaTeX output. - -EXTRA_PACKAGES = - -# The LATEX_HEADER tag can be used to specify a personal LaTeX header for -# the generated latex document. The header should contain everything until -# the first chapter. If it is left blank doxygen will generate a -# standard header. Notice: only use this tag if you know what you are doing! - -LATEX_HEADER = - -# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated -# is prepared for conversion to pdf (using ps2pdf). The pdf file will -# contain links (just like the HTML output) instead of page references -# This makes the output suitable for online browsing using a pdf viewer. - -PDF_HYPERLINKS = YES - -# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of -# plain latex in the generated Makefile. Set this option to YES to get a -# higher quality PDF documentation. - -USE_PDFLATEX = YES - -# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. -# command to the generated LaTeX files. This will instruct LaTeX to keep -# running if errors occur, instead of asking the user for help. -# This option is also used when generating formulas in HTML. - -LATEX_BATCHMODE = NO - -# If LATEX_HIDE_INDICES is set to YES then doxygen will not -# include the index chapters (such as File Index, Compound Index, etc.) -# in the output. - -LATEX_HIDE_INDICES = NO - -# If LATEX_SOURCE_CODE is set to YES then doxygen will include source code with syntax highlighting in the LaTeX output. Note that which sources are shown also depends on other settings such as SOURCE_BROWSER. - -LATEX_SOURCE_CODE = NO - -#--------------------------------------------------------------------------- -# configuration options related to the RTF output -#--------------------------------------------------------------------------- - -# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output -# The RTF output is optimized for Word 97 and may not look very pretty with -# other RTF readers or editors. - -GENERATE_RTF = NO - -# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `rtf' will be used as the default path. - -RTF_OUTPUT = rtf - -# If the COMPACT_RTF tag is set to YES Doxygen generates more compact -# RTF documents. This may be useful for small projects and may help to -# save some trees in general. - -COMPACT_RTF = NO - -# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated -# will contain hyperlink fields. The RTF file will -# contain links (just like the HTML output) instead of page references. -# This makes the output suitable for online browsing using WORD or other -# programs which support those fields. -# Note: wordpad (write) and others do not support links. - -RTF_HYPERLINKS = NO - -# Load stylesheet definitions from file. Syntax is similar to doxygen's -# config file, i.e. a series of assignments. You only have to provide -# replacements, missing definitions are set to their default value. - -RTF_STYLESHEET_FILE = - -# Set optional variables used in the generation of an rtf document. -# Syntax is similar to doxygen's config file. - -RTF_EXTENSIONS_FILE = - -#--------------------------------------------------------------------------- -# configuration options related to the man page output -#--------------------------------------------------------------------------- - -# If the GENERATE_MAN tag is set to YES (the default) Doxygen will -# generate man pages - -GENERATE_MAN = NO - -# The MAN_OUTPUT tag is used to specify where the man pages will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `man' will be used as the default path. - -MAN_OUTPUT = man - -# The MAN_EXTENSION tag determines the extension that is added to -# the generated man pages (default is the subroutine's section .3) - -MAN_EXTENSION = .3 - -# If the MAN_LINKS tag is set to YES and Doxygen generates man output, -# then it will generate one additional man file for each entity -# documented in the real man page(s). These additional files -# only source the real man page, but without them the man command -# would be unable to find the correct page. The default is NO. - -MAN_LINKS = NO - -#--------------------------------------------------------------------------- -# configuration options related to the XML output -#--------------------------------------------------------------------------- - -# If the GENERATE_XML tag is set to YES Doxygen will -# generate an XML file that captures the structure of -# the code including all documentation. - -GENERATE_XML = YES - -# The XML_OUTPUT tag is used to specify where the XML pages will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `xml' will be used as the default path. - -XML_OUTPUT = xml - -# The XML_SCHEMA tag can be used to specify an XML schema, -# which can be used by a validating XML parser to check the -# syntax of the XML files. - -XML_SCHEMA = - -# The XML_DTD tag can be used to specify an XML DTD, -# which can be used by a validating XML parser to check the -# syntax of the XML files. - -XML_DTD = - -# If the XML_PROGRAMLISTING tag is set to YES Doxygen will -# dump the program listings (including syntax highlighting -# and cross-referencing information) to the XML output. Note that -# enabling this will significantly increase the size of the XML output. - -XML_PROGRAMLISTING = NO - -#--------------------------------------------------------------------------- -# configuration options for the AutoGen Definitions output -#--------------------------------------------------------------------------- - -# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will -# generate an AutoGen Definitions (see autogen.sf.net) file -# that captures the structure of the code including all -# documentation. Note that this feature is still experimental -# and incomplete at the moment. - -GENERATE_AUTOGEN_DEF = NO - -#--------------------------------------------------------------------------- -# configuration options related to the Perl module output -#--------------------------------------------------------------------------- - -# If the GENERATE_PERLMOD tag is set to YES Doxygen will -# generate a Perl module file that captures the structure of -# the code including all documentation. Note that this -# feature is still experimental and incomplete at the -# moment. - -GENERATE_PERLMOD = NO - -# If the PERLMOD_LATEX tag is set to YES Doxygen will generate -# the necessary Makefile rules, Perl scripts and LaTeX code to be able -# to generate PDF and DVI output from the Perl module output. - -PERLMOD_LATEX = NO - -# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be -# nicely formatted so it can be parsed by a human reader. -# This is useful -# if you want to understand what is going on. -# On the other hand, if this -# tag is set to NO the size of the Perl module output will be much smaller -# and Perl will parse it just the same. - -PERLMOD_PRETTY = YES - -# The names of the make variables in the generated doxyrules.make file -# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. -# This is useful so different doxyrules.make files included by the same -# Makefile don't overwrite each other's variables. - -PERLMOD_MAKEVAR_PREFIX = - -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- - -# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will -# evaluate all C-preprocessor directives found in the sources and include -# files. - -ENABLE_PREPROCESSING = YES - -# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro -# names in the source code. If set to NO (the default) only conditional -# compilation will be performed. Macro expansion can be done in a controlled -# way by setting EXPAND_ONLY_PREDEF to YES. - -MACRO_EXPANSION = NO - -# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES -# then the macro expansion is limited to the macros specified with the -# PREDEFINED and EXPAND_AS_DEFINED tags. - -EXPAND_ONLY_PREDEF = NO - -# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files -# in the INCLUDE_PATH (see below) will be search if a #include is found. - -SEARCH_INCLUDES = YES - -# The INCLUDE_PATH tag can be used to specify one or more directories that -# contain include files that are not input files but should be processed by -# the preprocessor. - -INCLUDE_PATH = - -# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard -# patterns (like *.h and *.hpp) to filter out the header-files in the -# directories. If left blank, the patterns specified with FILE_PATTERNS will -# be used. - -INCLUDE_FILE_PATTERNS = - -# The PREDEFINED tag can be used to specify one or more macro names that -# are defined before the preprocessor is started (similar to the -D option of -# gcc). The argument of the tag is a list of macros of the form: name -# or name=definition (no spaces). If the definition and the = are -# omitted =1 is assumed. To prevent a macro definition from being -# undefined via #undef or recursively expanded use the := operator -# instead of the = operator. - -PREDEFINED = - -# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then -# this tag can be used to specify a list of macro names that should be expanded. -# The macro definition that is found in the sources will be used. -# Use the PREDEFINED tag if you want to use a different macro definition. - -EXPAND_AS_DEFINED = - -# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then -# doxygen's preprocessor will remove all function-like macros that are alone -# on a line, have an all uppercase name, and do not end with a semicolon. Such -# function macros are typically used for boiler-plate code, and will confuse -# the parser if not removed. - -SKIP_FUNCTION_MACROS = YES - -#--------------------------------------------------------------------------- -# Configuration::additions related to external references -#--------------------------------------------------------------------------- - -# The TAGFILES option can be used to specify one or more tagfiles. -# Optionally an initial location of the external documentation -# can be added for each tagfile. The format of a tag file without -# this location is as follows: -# -# TAGFILES = file1 file2 ... -# Adding location for the tag files is done as follows: -# -# TAGFILES = file1=loc1 "file2 = loc2" ... -# where "loc1" and "loc2" can be relative or absolute paths or -# URLs. If a location is present for each tag, the installdox tool -# does not have to be run to correct the links. -# Note that each tag file must have a unique name -# (where the name does NOT include the path) -# If a tag file is not located in the directory in which doxygen -# is run, you must also specify the path to the tagfile here. - -TAGFILES = - -# When a file name is specified after GENERATE_TAGFILE, doxygen will create -# a tag file that is based on the input files it reads. - -GENERATE_TAGFILE = - -# If the ALLEXTERNALS tag is set to YES all external classes will be listed -# in the class index. If set to NO only the inherited external classes -# will be listed. - -ALLEXTERNALS = NO - -# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed -# in the modules index. If set to NO, only the current project's groups will -# be listed. - -EXTERNAL_GROUPS = YES - -# The PERL_PATH should be the absolute path and name of the perl script -# interpreter (i.e. the result of `which perl'). - -PERL_PATH = /usr/bin/perl - -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- - -# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will -# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base -# or super classes. Setting the tag to NO turns the diagrams off. Note that -# this option is superseded by the HAVE_DOT option below. This is only a -# fallback. It is recommended to install and use dot, since it yields more -# powerful graphs. - -CLASS_DIAGRAMS = YES - -# You can define message sequence charts within doxygen comments using the \msc -# command. Doxygen will then run the mscgen tool (see -# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the -# documentation. The MSCGEN_PATH tag allows you to specify the directory where -# the mscgen tool resides. If left empty the tool is assumed to be found in the -# default search path. - -MSCGEN_PATH = - -# If set to YES, the inheritance and collaboration graphs will hide -# inheritance and usage relations if the target is undocumented -# or is not a class. - -HIDE_UNDOC_RELATIONS = YES - -# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is -# available from the path. This tool is part of Graphviz, a graph visualization -# toolkit from AT&T and Lucent Bell Labs. The other options in this section -# have no effect if this option is set to NO (the default) - -HAVE_DOT = NO - -# By default doxygen will write a font called FreeSans.ttf to the output -# directory and reference it in all dot files that doxygen generates. This -# font does not include all possible unicode characters however, so when you need -# these (or just want a differently looking font) you can specify the font name -# using DOT_FONTNAME. You need need to make sure dot is able to find the font, -# which can be done by putting it in a standard location or by setting the -# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory -# containing the font. - -DOT_FONTNAME = FreeSans - -# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. -# The default size is 10pt. - -DOT_FONTSIZE = 10 - -# By default doxygen will tell dot to use the output directory to look for the -# FreeSans.ttf font (which doxygen will put there itself). If you specify a -# different font using DOT_FONTNAME you can set the path where dot -# can find it using this tag. - -DOT_FONTPATH = - -# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for each documented class showing the direct and -# indirect inheritance relations. Setting this tag to YES will force the -# the CLASS_DIAGRAMS tag to NO. - -CLASS_GRAPH = YES - -# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for each documented class showing the direct and -# indirect implementation dependencies (inheritance, containment, and -# class references variables) of the class with other documented classes. - -COLLABORATION_GRAPH = YES - -# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for groups, showing the direct groups dependencies - -GROUP_GRAPHS = YES - -# If the UML_LOOK tag is set to YES doxygen will generate inheritance and -# collaboration diagrams in a style similar to the OMG's Unified Modeling -# Language. - -UML_LOOK = NO - -# If set to YES, the inheritance and collaboration graphs will show the -# relations between templates and their instances. - -TEMPLATE_RELATIONS = NO - -# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT -# tags are set to YES then doxygen will generate a graph for each documented -# file showing the direct and indirect include dependencies of the file with -# other documented files. - -INCLUDE_GRAPH = YES - -# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and -# HAVE_DOT tags are set to YES then doxygen will generate a graph for each -# documented header file showing the documented files that directly or -# indirectly include this file. - -INCLUDED_BY_GRAPH = YES - -# If the CALL_GRAPH and HAVE_DOT options are set to YES then -# doxygen will generate a call dependency graph for every global function -# or class method. Note that enabling this option will significantly increase -# the time of a run. So in most cases it will be better to enable call graphs -# for selected functions only using the \callgraph command. - -CALL_GRAPH = NO - -# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then -# doxygen will generate a caller dependency graph for every global function -# or class method. Note that enabling this option will significantly increase -# the time of a run. So in most cases it will be better to enable caller -# graphs for selected functions only using the \callergraph command. - -CALLER_GRAPH = NO - -# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen -# will graphical hierarchy of all classes instead of a textual one. - -GRAPHICAL_HIERARCHY = YES - -# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES -# then doxygen will show the dependencies a directory has on other directories -# in a graphical way. The dependency relations are determined by the #include -# relations between the files in the directories. - -DIRECTORY_GRAPH = YES - -# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images -# generated by dot. Possible values are png, jpg, or gif -# If left blank png will be used. - -DOT_IMAGE_FORMAT = png - -# The tag DOT_PATH can be used to specify the path where the dot tool can be -# found. If left blank, it is assumed the dot tool can be found in the path. - -DOT_PATH = - -# The DOTFILE_DIRS tag can be used to specify one or more directories that -# contain dot files that are included in the documentation (see the -# \dotfile command). - -DOTFILE_DIRS = - -# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of -# nodes that will be shown in the graph. If the number of nodes in a graph -# becomes larger than this value, doxygen will truncate the graph, which is -# visualized by representing a node as a red box. Note that doxygen if the -# number of direct children of the root node in a graph is already larger than -# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note -# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. - -DOT_GRAPH_MAX_NODES = 50 - -# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the -# graphs generated by dot. A depth value of 3 means that only nodes reachable -# from the root by following a path via at most 3 edges will be shown. Nodes -# that lay further from the root node will be omitted. Note that setting this -# option to 1 or 2 may greatly reduce the computation time needed for large -# code bases. Also note that the size of a graph can be further restricted by -# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. - -MAX_DOT_GRAPH_DEPTH = 0 - -# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent -# background. This is disabled by default, because dot on Windows does not -# seem to support this out of the box. Warning: Depending on the platform used, -# enabling this option may lead to badly anti-aliased labels on the edges of -# a graph (i.e. they become hard to read). - -DOT_TRANSPARENT = NO - -# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output -# files in one run (i.e. multiple -o and -T options on the command line). This -# makes dot run faster, but since only newer versions of dot (>1.8.10) -# support this, this feature is disabled by default. - -DOT_MULTI_TARGETS = YES - -# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will -# generate a legend page explaining the meaning of the various boxes and -# arrows in the dot generated graphs. - -GENERATE_LEGEND = YES - -# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will -# remove the intermediate dot files that are used to generate -# the various graphs. - -DOT_CLEANUP = YES diff --git a/libraries/RF24/FAQ b/libraries/RF24/FAQ deleted file mode 100644 index d134bb8..0000000 --- a/libraries/RF24/FAQ +++ /dev/null @@ -1,56 +0,0 @@ -/** - * @page FAQ Frequently Asked Questions - * - * @ref starting - * - * @ref hardware - * - * @ref range - * - * @ref tests - * - * @section starting Where do I start? - * - * Start with the pingpair example. Follow the instructions in the comments - * of that sketch. - * - * @section hardware Where can I buy some hardware? - * - * I've been using modules from mdfly.com. - * - * Mostly these units as the workhorse of the system: - * - * @li 2.4Ghz Wireless nRF24L01 Transceiver Module $6.95 - * http://www.mdfly.com/index.php?main_page=product_info&cPath=8_52&products_id=82 - * - * And then also experimenting with these for greater range - * - * @li nRF24L01 2.4GHz Transceiver Module w/ Power Amplifier $12.95 - * http://www.mdfly.com/index.php?main_page=product_info&cPath=8_52&products_id=394 - * @li 2.4GHz Transceiver Module w/ Power Amplifier $19.95 - * http://www.mdfly.com/index.php?main_page=product_info&cPath=8_52&products_id=583 - * - * However, I also noticed that iTeadStudio has nRF24L01+ units for $4! - * - * @section range What is the range of these units? - * - * Here are some results from measurements I have taken. I recommend that everyone - * take their own measurements in their particular circumstances. - * - * @li non-plus unit, 2MBps (worst case), 41+ ft line of sight indoors, immediate dropoff with any deviation from LOS. (41 ft is as far as I can go in my house without turning a corner) - * @li Plus unit, 250kbps (best case), 46 ft around two corners indoors, 49 ft around one corner. More importantly, at 250k, packet loss is almost negligible through almost all of that range. - * @li Both units at 1MBps, plus unit gets about 10% range improvement over non-plus in almost all situations. - * - * @section tests Why are the examples in the 'tests' directory failing? - * - * The sketches in the 'tests' directory are not for general use. - * Please use the examples in the 'examples' directory instead. - * - * The 'tests' directory is only for people making changes to the library - * to ensure that their changes do not break anything. - * - * - * - * - * - */ diff --git a/libraries/RF24/README.md b/libraries/RF24/README.md deleted file mode 100644 index 9d30e6c..0000000 --- a/libraries/RF24/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Arduino driver for nRF24L01(+) 2.4GHz Wireless Transceiver - -Design Goals: This library is designed to be... - -* Maximally compliant with the intended operation of the chip -* Easy for beginners to use -* Consumed with a public interface that's similiar to other Arduino standard libraries -* Built against the standard SPI library. - -* Modifications to the RF24 library in this fork is backward compatible. A single - enhancement which may cause issue, is code which relies on the driver to power down the - radio, as a side effect. The radio is no longer powered down after each transmit. Rather, - the application must take responsibility for power management. Normally this is - achieved by use of powerDown and powerUp. If you wish to maximize power efficiency, - you must call powerDown after transmit (write, startWrite). - -Please refer to: - -* [Documentation Main Page](http://maniacbug.github.com/RF24) -* [RF24 Class Documentation](http://maniacbug.github.com/RF24/classRF24.html) -* [Source Code](https://github.com/maniacbug/RF24) -* [Downloads](https://github.com/maniacbug/RF24/archives/master) -* [Chip Datasheet](http://www.nordicsemi.com/files/Product/data_sheet/nRF24L01_Product_Specification_v2_0.pdf) - -This chip uses the SPI bus, plus two chip control pins. Remember that pin 10 must still remain an output, or -the SPI hardware will go into 'slave' mode. This is because the 'SS', or slave select, pin on the arduino -controls if the arduino is the slave. For RF24 use, the arduino is the master and the RF24 is the slave. - - diff --git a/libraries/RF24/RF24_config.h b/libraries/RF24/RF24_config.h deleted file mode 100644 index fc7397f..0000000 --- a/libraries/RF24/RF24_config.h +++ /dev/null @@ -1,65 +0,0 @@ - -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -#ifndef __RF24_CONFIG_H__ -#define __RF24_CONFIG_H__ - -#if ARDUINO < 100 -#include -#else -#include -#endif - -#include - -// Stuff that is normally provided by Arduino -#ifdef ARDUINO -#include -#else -#include -#include -#include -extern HardwareSPI SPI; -#define _BV(x) (1<<(x)) -#endif - -#undef SERIAL_DEBUG -#ifdef SERIAL_DEBUG -#define IF_SERIAL_DEBUG(x) ({x;}) -#else -#define IF_SERIAL_DEBUG(x) -#endif - -// Avoid spurious warnings -#if 1 -#if ! defined( NATIVE ) && defined( ARDUINO ) -#undef PROGMEM -#define PROGMEM __attribute__(( section(".progmem.data") )) -#undef PSTR -#define PSTR(s) (__extension__({static const char __c[] PROGMEM = (s); &__c[0];})) -#endif -#endif - -// Progmem is Arduino-specific -#ifdef ARDUINO -#include -#define PRIPSTR "%S" -#else -typedef char const char; -typedef uint16_t prog_uint16_t; -#define PSTR(x) (x) -#define printf_P printf -#define strlen_P strlen -#define PROGMEM -#define pgm_read_word(p) (*(p)) -#define PRIPSTR "%s" -#endif - -#endif // __RF24_CONFIG_H__ -// vim:ai:cin:sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/doxygen-custom.css b/libraries/RF24/doxygen-custom.css deleted file mode 100644 index d7d0e12..0000000 --- a/libraries/RF24/doxygen-custom.css +++ /dev/null @@ -1,835 +0,0 @@ -/* The standard CSS for doxygen */ - -body, table, div, p, dl { - font-family: Lucida Grande, Verdana, Geneva, Arial, sans-serif; - font-size: 12px; -} - -/* @group Heading Levels */ - -h1 { - font-size: 150%; -} - -.title { - font-size: 150%; - font-weight: bold; - margin: 10px 2px; -} - -h2 { - font-size: 120%; -} - -h3 { - font-size: 100%; -} - -dt { - font-weight: bold; -} - -div.multicol { - -moz-column-gap: 1em; - -webkit-column-gap: 1em; - -moz-column-count: 3; - -webkit-column-count: 3; -} - -p.startli, p.startdd, p.starttd { - margin-top: 2px; -} - -p.endli { - margin-bottom: 0px; -} - -p.enddd { - margin-bottom: 4px; -} - -p.endtd { - margin-bottom: 2px; -} - -/* @end */ - -caption { - font-weight: bold; -} - -span.legend { - font-size: 70%; - text-align: center; -} - -h3.version { - font-size: 90%; - text-align: center; -} - -div.qindex, div.navtab{ - background-color: #EBEFF6; - border: 1px solid #A3B4D7; - text-align: center; - margin: 2px; - padding: 2px; -} - -div.qindex, div.navpath { - width: 100%; - line-height: 140%; -} - -div.navtab { - margin-right: 15px; -} - -/* @group Link Styling */ - -a { - color: #3D578C; - font-weight: normal; - text-decoration: none; -} - -.contents a:visited { - color: #4665A2; -} - -a:hover { - text-decoration: underline; -} - -a.qindex { - font-weight: bold; -} - -a.qindexHL { - font-weight: bold; - background-color: #9CAFD4; - color: #ffffff; - border: 1px double #869DCA; -} - -.contents a.qindexHL:visited { - color: #ffffff; -} - -a.el { - font-weight: bold; -} - -a.elRef { -} - -a.code { - color: #4665A2; -} - -a.codeRef { - color: #4665A2; -} - -/* @end */ - -dl.el { - margin-left: -1cm; -} - -.fragment { - font-family: monospace, fixed; - font-size: 105%; -} - -pre.fragment { - border: 1px solid #C4CFE5; - background-color: #FBFCFD; - padding: 4px 6px; - margin: 4px 8px 4px 2px; - overflow: auto; - word-wrap: break-word; - font-size: 9pt; - line-height: 125%; -} - -div.ah { - background-color: black; - font-weight: bold; - color: #ffffff; - margin-bottom: 3px; - margin-top: 3px; - padding: 0.2em; - border: solid thin #333; - border-radius: 0.5em; - -webkit-border-radius: .5em; - -moz-border-radius: .5em; - box-shadow: 2px 2px 3px #999; - -webkit-box-shadow: 2px 2px 3px #999; - -moz-box-shadow: rgba(0, 0, 0, 0.15) 2px 2px 2px; - background-image: -webkit-gradient(linear, left top, left bottom, from(#eee), to(#000),color-stop(0.3, #444)); - background-image: -moz-linear-gradient(center top, #eee 0%, #444 40%, #000); -} - -div.groupHeader { - margin-left: 16px; - margin-top: 12px; - font-weight: bold; -} - -div.groupText { - margin-left: 16px; - font-style: italic; -} - -body { - background: white; - color: black; - margin: 0; -} - -div.contents { - margin-top: 10px; - margin-left: 10px; - margin-right: 5px; -} - -td.indexkey { - background-color: #EBEFF6; - font-weight: bold; - border: 1px solid #C4CFE5; - margin: 2px 0px 2px 0; - padding: 2px 10px; -} - -td.indexvalue { - background-color: #EBEFF6; - border: 1px solid #C4CFE5; - padding: 2px 10px; - margin: 2px 0px; -} - -tr.memlist { - background-color: #EEF1F7; -} - -p.formulaDsp { - text-align: center; -} - -img.formulaDsp { - -} - -img.formulaInl { - vertical-align: middle; -} - -div.center { - text-align: center; - margin-top: 0px; - margin-bottom: 0px; - padding: 0px; -} - -div.center img { - border: 0px; -} - -address.footer { - text-align: right; - padding-right: 12px; -} - -img.footer { - border: 0px; - vertical-align: middle; -} - -/* @group Code Colorization */ - -span.keyword { - color: #008000 -} - -span.keywordtype { - color: #604020 -} - -span.keywordflow { - color: #e08000 -} - -span.comment { - color: #800000 -} - -span.preprocessor { - color: #806020 -} - -span.stringliteral { - color: #002080 -} - -span.charliteral { - color: #008080 -} - -span.vhdldigit { - color: #ff00ff -} - -span.vhdlchar { - color: #000000 -} - -span.vhdlkeyword { - color: #700070 -} - -span.vhdllogic { - color: #ff0000 -} - -/* @end */ - -/* -.search { - color: #003399; - font-weight: bold; -} - -form.search { - margin-bottom: 0px; - margin-top: 0px; -} - -input.search { - font-size: 75%; - color: #000080; - font-weight: normal; - background-color: #e8eef2; -} -*/ - -td.tiny { - font-size: 75%; -} - -.dirtab { - padding: 4px; - border-collapse: collapse; - border: 1px solid #A3B4D7; -} - -th.dirtab { - background: #EBEFF6; - font-weight: bold; -} - -hr { - height: 0px; - border: none; - border-top: 1px solid #4A6AAA; -} - -hr.footer { - height: 1px; -} - -/* @group Member Descriptions */ - -table.memberdecls { - border-spacing: 0px; - padding: 0px; -} - -.mdescLeft, .mdescRight, -.memItemLeft, .memItemRight, -.memTemplItemLeft, .memTemplItemRight, .memTemplParams { - background-color: #F9FAFC; - border: none; - margin: 4px; - padding: 1px 0 0 8px; -} - -.mdescLeft, .mdescRight { - padding: 0px 8px 4px 8px; - color: #555; -} - -.memItemLeft, .memItemRight, .memTemplParams { - border-top: 1px solid #C4CFE5; -} - -.memItemLeft, .memTemplItemLeft { - white-space: nowrap; -} - -.memItemRight { - width: 100%; -} - -.memTemplParams { - color: #4665A2; - white-space: nowrap; -} - -/* @end */ - -/* @group Member Details */ - -/* Styles for detailed member documentation */ - -.memtemplate { - font-size: 80%; - color: #4665A2; - font-weight: normal; - margin-left: 9px; -} - -.memnav { - background-color: #EBEFF6; - border: 1px solid #A3B4D7; - text-align: center; - margin: 2px; - margin-right: 15px; - padding: 2px; -} - -.mempage { - width: 100%; -} - -.memitem { - padding: 0; - margin-bottom: 10px; - margin-right: 5px; -} - -.memname { - white-space: nowrap; - font-weight: bold; - margin-left: 6px; -} - -.memproto { - border-top: 1px solid #A8B8D9; - border-left: 1px solid #A8B8D9; - border-right: 1px solid #A8B8D9; - padding: 6px 0px 6px 0px; - color: #253555; - font-weight: bold; - text-shadow: 0px 1px 1px rgba(255, 255, 255, 0.9); - /* opera specific markup */ - box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); - border-top-right-radius: 8px; - border-top-left-radius: 8px; - /* firefox specific markup */ - -moz-box-shadow: rgba(0, 0, 0, 0.15) 5px 5px 5px; - -moz-border-radius-topright: 8px; - -moz-border-radius-topleft: 8px; - /* webkit specific markup */ - -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); - -webkit-border-top-right-radius: 8px; - -webkit-border-top-left-radius: 8px; - background-image:url('nav_f.png'); - background-repeat:repeat-x; - background-color: #E2E8F2; - -} - -.memdoc { - border-bottom: 1px solid #A8B8D9; - border-left: 1px solid #A8B8D9; - border-right: 1px solid #A8B8D9; - padding: 2px 5px; - background-color: #FBFCFD; - border-top-width: 0; - /* opera specific markup */ - border-bottom-left-radius: 8px; - border-bottom-right-radius: 8px; - box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); - /* firefox specific markup */ - -moz-border-radius-bottomleft: 8px; - -moz-border-radius-bottomright: 8px; - -moz-box-shadow: rgba(0, 0, 0, 0.15) 5px 5px 5px; - background-image: -moz-linear-gradient(center top, #FFFFFF 0%, #FFFFFF 60%, #F7F8FB 95%, #EEF1F7); - /* webkit specific markup */ - -webkit-border-bottom-left-radius: 8px; - -webkit-border-bottom-right-radius: 8px; - -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); - background-image: -webkit-gradient(linear,center top,center bottom,from(#FFFFFF), color-stop(0.6,#FFFFFF), color-stop(0.60,#FFFFFF), color-stop(0.95,#F7F8FB), to(#EEF1F7)); -} - -.paramkey { - text-align: right; -} - -.paramtype { - white-space: nowrap; -} - -.paramname { - color: #602020; - white-space: nowrap; -} -.paramname em { - font-style: normal; -} - -.params, .retval, .exception, .tparams { - border-spacing: 6px 2px; -} - -.params .paramname, .retval .paramname { - font-weight: bold; - vertical-align: top; -} - -.params .paramtype { - font-style: italic; - vertical-align: top; -} - -.params .paramdir { - font-family: "courier new",courier,monospace; - vertical-align: top; -} - - - - -/* @end */ - -/* @group Directory (tree) */ - -/* for the tree view */ - -.ftvtree { - font-family: sans-serif; - margin: 0px; -} - -/* these are for tree view when used as main index */ - -.directory { - font-size: 9pt; - font-weight: bold; - margin: 5px; -} - -.directory h3 { - margin: 0px; - margin-top: 1em; - font-size: 11pt; -} - -/* -The following two styles can be used to replace the root node title -with an image of your choice. Simply uncomment the next two styles, -specify the name of your image and be sure to set 'height' to the -proper pixel height of your image. -*/ - -/* -.directory h3.swap { - height: 61px; - background-repeat: no-repeat; - background-image: url("yourimage.gif"); -} -.directory h3.swap span { - display: none; -} -*/ - -.directory > h3 { - margin-top: 0; -} - -.directory p { - margin: 0px; - white-space: nowrap; -} - -.directory div { - display: none; - margin: 0px; -} - -.directory img { - vertical-align: -30%; -} - -/* these are for tree view when not used as main index */ - -.directory-alt { - font-size: 100%; - font-weight: bold; -} - -.directory-alt h3 { - margin: 0px; - margin-top: 1em; - font-size: 11pt; -} - -.directory-alt > h3 { - margin-top: 0; -} - -.directory-alt p { - margin: 0px; - white-space: nowrap; -} - -.directory-alt div { - display: none; - margin: 0px; -} - -.directory-alt img { - vertical-align: -30%; -} - -/* @end */ - -div.dynheader { - margin-top: 8px; -} - -address { - font-style: normal; - color: #2A3D61; -} - -table.doxtable { - border-collapse:collapse; -} - -table.doxtable td, table.doxtable th { - border: 1px solid #2D4068; - padding: 3px 7px 2px; -} - -table.doxtable th { - background-color: #374F7F; - color: #FFFFFF; - font-size: 110%; - padding-bottom: 4px; - padding-top: 5px; - text-align:left; -} - -.tabsearch { - top: 0px; - left: 10px; - height: 36px; - background-image: url('tab_b.png'); - z-index: 101; - overflow: hidden; - font-size: 13px; -} - -.navpath ul -{ - font-size: 11px; - background-image:url('tab_b.png'); - background-repeat:repeat-x; - height:30px; - line-height:30px; - color:#8AA0CC; - border:solid 1px #C2CDE4; - overflow:hidden; - margin:0px; - padding:0px; -} - -.navpath li -{ - list-style-type:none; - float:left; - padding-left:10px; - padding-right:15px; - background-image:url('bc_s.png'); - background-repeat:no-repeat; - background-position:right; - color:#364D7C; -} - -.navpath li.navelem a -{ - height:32px; - display:block; - text-decoration: none; - outline: none; -} - -.navpath li.navelem a:hover -{ - color:#6884BD; -} - -.navpath li.footer -{ - list-style-type:none; - float:right; - padding-left:10px; - padding-right:15px; - background-image:none; - background-repeat:no-repeat; - background-position:right; - color:#364D7C; - font-size: 8pt; -} - - -div.summary -{ - float: right; - font-size: 8pt; - padding-right: 5px; - width: 50%; - text-align: right; -} - -div.summary a -{ - white-space: nowrap; -} - -div.ingroups -{ - font-size: 8pt; - padding-left: 5px; - width: 50%; - text-align: left; -} - -div.ingroups a -{ - white-space: nowrap; -} - -div.header -{ - background-image:url('nav_h.png'); - background-repeat:repeat-x; - background-color: #F9FAFC; - margin: 0px; - border-bottom: 1px solid #C4CFE5; -} - -div.headertitle -{ - padding: 5px 5px 5px 10px; -} - -dl -{ - padding: 0 0 0 10px; -} - -dl.note, dl.warning, dl.attention, dl.pre, dl.post, dl.invariant, dl.deprecated, dl.todo, dl.test, dl.bug -{ - border-left:4px solid; - padding: 0 0 0 6px; -} - -dl.note -{ - border-color: #D0C000; -} - -dl.warning, dl.attention -{ - border-color: #FF0000; -} - -dl.pre, dl.post, dl.invariant -{ - border-color: #00D000; -} - -dl.deprecated -{ - border-color: #505050; -} - -dl.todo -{ - border-color: #00C0E0; -} - -dl.test -{ - border-color: #3030E0; -} - -dl.bug -{ - border-color: #C08050; -} - -#projectlogo -{ - text-align: center; - vertical-align: bottom; - border-collapse: separate; -} - -#projectlogo img -{ - border: 0px none; -} - -#projectname -{ - font: 300% Tahoma, Arial,sans-serif; - margin: 0px; - padding: 2px 0px; -} - -#projectbrief -{ - font: 120% Tahoma, Arial,sans-serif; - margin: 0px; - padding: 0px; -} - -#projectnumber -{ - font: 50% Tahoma, Arial,sans-serif; - margin: 0px; - padding: 0px; -} - -#titlearea -{ - padding: 0px; - margin: 0px; - width: 100%; - border-bottom: 1px solid #5373B4; -} - -.image -{ - text-align: left; -} - -.dotgraph -{ - text-align: center; -} - -.mscgraph -{ - text-align: center; -} - -.caption -{ - font-weight: bold; -} - diff --git a/libraries/RF24/examples/GettingStarted/GettingStarted.pde b/libraries/RF24/examples/GettingStarted/GettingStarted.pde deleted file mode 100644 index bf1851a..0000000 --- a/libraries/RF24/examples/GettingStarted/GettingStarted.pde +++ /dev/null @@ -1,227 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * Example for Getting Started with nRF24L01+ radios. - * - * This is an example of how to use the RF24 class. Write this sketch to two - * different nodes. Put one of the nodes into 'transmit' mode by connecting - * with the serial monitor and sending a 'T'. The ping node sends the current - * time to the pong node, which responds by sending the value back. The ping - * node can then see how long the whole cycle took. - */ - -#include -#include "nRF24L01.h" -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 9 & 10 - -RF24 radio(9,10); - -// -// Topology -// - -// Radio pipe addresses for the 2 nodes to communicate. -const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL }; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes -// in this system. Doing so greatly simplifies testing. -// - -// The various roles supported by this sketch -typedef enum { role_ping_out = 1, role_pong_back } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"}; - -// The role of the current running sketch -role_e role = role_pong_back; - -void setup(void) -{ - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/GettingStarted/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - printf("*** PRESS 'T' to begin transmitting to the other node\n\r"); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // optionally, increase the delay between retries & # of retries - radio.setRetries(15,15); - - // optionally, reduce the payload size. seems to - // improve reliability - //radio.setPayloadSize(8); - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens two pipes for these two nodes to communicate - // back and forth. - // Open 'our' pipe for writing - // Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading) - - //if ( role == role_ping_out ) - { - //radio.openWritingPipe(pipes[0]); - radio.openReadingPipe(1,pipes[1]); - } - //else - { - //radio.openWritingPipe(pipes[1]); - //radio.openReadingPipe(1,pipes[0]); - } - - // - // Start listening - // - - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); -} - -void loop(void) -{ - // - // Ping out role. Repeatedly send the current time - // - - if (role == role_ping_out) - { - // First, stop listening so we can talk. - radio.stopListening(); - - // Take the time, and send it. This will block until complete - unsigned long time = millis(); - printf("Now sending %lu...",time); - bool ok = radio.write( &time, sizeof(unsigned long) ); - - if (ok) - printf("ok..."); - else - printf("failed.\n\r"); - - // Now, continue listening - radio.startListening(); - - // Wait here until we get a response, or timeout (250ms) - unsigned long started_waiting_at = millis(); - bool timeout = false; - while ( ! radio.available() && ! timeout ) - if (millis() - started_waiting_at > 200 ) - timeout = true; - - // Describe the results - if ( timeout ) - { - printf("Failed, response timed out.\n\r"); - } - else - { - // Grab the response, compare, and send to debugging spew - unsigned long got_time; - radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got response %lu, round-trip delay: %lu\n\r",got_time,millis()-got_time); - } - - // Try again 1s later - delay(1000); - } - - // - // Pong back role. Receive each packet, dump it out, and send it back - // - - if ( role == role_pong_back ) - { - // if there is data ready - if ( radio.available() ) - { - // Dump the payloads until we've gotten everything - unsigned long got_time; - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - done = radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got payload %lu...",got_time); - - // Delay just a little bit to let the other unit - // make the transition to receiver - delay(20); - } - - // First, stop listening so we can talk - radio.stopListening(); - - // Send the final one back. - radio.write( &got_time, sizeof(unsigned long) ); - printf("Sent response.\n\r"); - - // Now, resume listening so we catch the next packets. - radio.startListening(); - } - } - - // - // Change roles - // - - if ( Serial.available() ) - { - char c = toupper(Serial.read()); - if ( c == 'T' && role == role_pong_back ) - { - printf("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK\n\r"); - - // Become the primary transmitter (ping out) - role = role_ping_out; - radio.openWritingPipe(pipes[0]); - radio.openReadingPipe(1,pipes[1]); - } - else if ( c == 'R' && role == role_ping_out ) - { - printf("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK\n\r"); - - // Become the primary receiver (pong back) - role = role_pong_back; - radio.openWritingPipe(pipes[1]); - radio.openReadingPipe(1,pipes[0]); - } - } -} -// vim:cin:ai:sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/examples/GettingStarted/Jamfile b/libraries/RF24/examples/GettingStarted/Jamfile deleted file mode 100644 index 9a5f2c4..0000000 --- a/libraries/RF24/examples/GettingStarted/Jamfile +++ /dev/null @@ -1,210 +0,0 @@ -# (1) Project Information - -PROJECT_LIBS = SPI RF24 ; - -# (2) Board Information - -UPLOAD_PROTOCOL ?= arduino ; -UPLOAD_SPEED ?= 57600 ; -MCU ?= atmega328p ; -F_CPU ?= 16000000 ; -CORE ?= arduino ; -VARIANT ?= standard ; -ARDUINO_VERSION ?= 100 ; - -# (3) USB Ports - -PORTS = p4 p6 p9 u0 u1 u2 ; -PORT_p6 = /dev/tty.usbserial-A600eHIs ; -PORT_p4 = /dev/tty.usbserial-A40081RP ; -PORT_p9 = /dev/tty.usbserial-A9007LmI ; -PORT_u0 = /dev/ttyUSB0 ; -PORT_u1 = /dev/ttyUSB1 ; -PORT_u2 = /dev/ttyUSB2 ; - -# (4) Location of AVR tools -# -# This configuration assumes using avr-tools that were obtained separate from the Arduino -# distribution. - -if $(OS) = MACOSX -{ - AVR_BIN = /usr/local/avrtools/bin ; - AVR_ETC = /usr/local/avrtools/etc ; - AVR_INCLUDE = /usr/local/avrtools/include ; -} -else -{ - AVR_BIN ?= /usr/bin ; - AVR_INCLUDE ?= /usr/lib/avr/include ; - AVR_ETC = /etc ; -} - -# (5) Directories where Arduino core and libraries are located - -ARDUINO_DIR ?= /opt/Arduino ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/$(CORE) $(ARDUINO_DIR)/hardware/arduino/variants/$(VARIANT) ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; - -# -# -------------------------------------------------- -# Below this line usually never needs to be modified -# - -# Tool locations - -CC = $(AVR_BIN)/avr-gcc ; -C++ = $(AVR_BIN)/avr-g++ ; -LINK = $(AVR_BIN)/avr-gcc ; -OBJCOPY = $(AVR_BIN)/avr-objcopy ; -AVRDUDE = $(AVR_BIN)/avrdude ; - -# Flags - -DEFINES += F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -OPTIM = -Os ; -CCFLAGS = -Wall -Wextra -mmcu=$(MCU) -ffunction-sections -fdata-sections ; -C++FLAGS = $(CCFLAGS) -fno-exceptions -fno-strict-aliasing ; -LINKFLAGS = $(OPTIM) -lm -Wl,--gc-sections -mmcu=$(MCU) ; -AVRDUDEFLAGS = -V -F -D -C $(AVR_ETC)/avrdude.conf -p $(MCU) -c $(UPLOAD_PROTOCOL) -b $(UPLOAD_SPEED) ; - -# Search everywhere for headers - -HDRS = $(PWD) $(AVR_INCLUDE) $(ARDUINO_CORE) $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) ; - -# Output locations - -LOCATE_TARGET = $(F_CPU) ; -LOCATE_SOURCE = $(F_CPU) ; - -# -# Custom rules -# - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule Pde -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_SOURCE) ; - Clean clean : $(<) ; -} - -if ( $(ARDUINO_VERSION) < 100 ) -{ - ARDUINO_H = WProgram.h ; -} -else -{ - ARDUINO_H = Arduino.h ; -} - -actions Pde -{ - echo "#include <$(ARDUINO_H)>" > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule C++Pde -{ - local _CPP = $(>:B).cpp ; - Pde $(_CPP) : $(>) ; - C++ $(<) : $(_CPP) ; -} - -rule UserObject -{ - switch $(>:S) - { - case .ino : C++Pde $(<) : $(>) ; - case .pde : C++Pde $(<) : $(>) ; - } -} - -rule Objects -{ - local _i ; - - for _i in [ FGristFiles $(<) ] - { - local _b = $(_i:B)$(SUFOBJ) ; - local _o = $(_b:G=$(SOURCE_GRIST:E)) ; - Object $(_o) : $(_i) ; - Depends obj : $(_o) ; - } -} - -rule Main -{ - MainFromObjects $(<) : $(>:B)$(SUFOBJ) ; - Objects $(>) ; -} - -rule Hex -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_TARGET) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions Hex -{ - $(OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule Upload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - UploadAction $(2) : $(3) ; -} - -actions UploadAction -{ - $(AVRDUDE) $(AVRDUDEFLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -# -# Targets -# - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp *.c ] ; - -# Grab everything from the current dir -PROJECT_MODULES += [ GLOB $(PWD) : *.c *.cpp *.pde *.ino ] ; - -# Main output executable -MAIN = $(PWD:B).elf ; - -Main $(MAIN) : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -Hex $(MAIN:B).hex : $(MAIN) ; - -# Upload targets -for _p in $(PORTS) -{ - Upload $(_p) : $(PORT_$(_p)) : $(MAIN:B).hex ; -} diff --git a/libraries/RF24/examples/GettingStarted/printf.h b/libraries/RF24/examples/GettingStarted/printf.h deleted file mode 100644 index b2efd56..0000000 --- a/libraries/RF24/examples/GettingStarted/printf.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -#ifdef ARDUINO - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#else -#error This example is only for use on Arduino. -#endif // ARDUINO - -#endif // __PRINTF_H__ diff --git a/libraries/RF24/examples/led_remote/Jamfile b/libraries/RF24/examples/led_remote/Jamfile deleted file mode 100644 index 901f8da..0000000 --- a/libraries/RF24/examples/led_remote/Jamfile +++ /dev/null @@ -1,206 +0,0 @@ -PROJECT_NAME = $(PWD:B) ; -PROJECT_DIR = . ; -PROJECT_LIBS = SPI RF24 ; - -OUT_DIR = ojam ; -F_CPU = 16000000 ; -MCU = atmega328p ; -PORTS = /dev/tty.usbserial-A600eHIs /dev/tty.usbserial-A40081RP /dev/tty.usbserial-A9007LmI ; - -UPLOAD_RATE = 57600 ; -AVRDUDE_PROTOCOL = stk500v1 ; -COM = 33 ; - -# Host-specific overrides for locations -if $(OS) = MACOSX -{ -ARDUINO_VERSION = 22 ; -OLD_DIR = /opt/arduino-0021 ; -AVR_TOOLS_PATH = $(OLD_DIR)/hardware/tools/avr/bin ; -AVRDUDECONFIG_PATH = $(OLD_DIR)/hardware/tools/avr/etc ; -ARDUINO_DIR = /opt/Arduino ; -ARDUINO_AVR = /usr/lib/avr/include ; -} - -# Where is everything? -ARDUINO_VERSION ?= 22 ; -AVR_TOOLS_PATH ?= /usr/bin ; -ARDUINO_DIR ?= /opt/arduino-00$(ARDUINO_VERSION) ; -ARDUINO_AVR ?= $(ARDUINO_DIR)/hardware/tools/avr/avr/include/avr ; -AVRDUDECONFIG_PATH ?= $(ARDUINO_DIR)/hardware/tools ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; -AVR_CC = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_CXX = $(AVR_TOOLS_PATH)/avr-g++ ; -AVR_LD = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_OBJCOPY = $(AVR_TOOLS_PATH)/avr-objcopy ; -AVRDUDE = $(AVR_TOOLS_PATH)/avrdude ; - -DEFINES = F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -CTUNING = -ffunction-sections -fdata-sections ; -CXXTUNING = -fno-exceptions -fno-strict-aliasing ; -CFLAGS = -Os -Wall -Wextra -mmcu=$(MCU) $(CTUNING) ; -CXXFLAGS = $(CFLAGS) $(CXXTUNING) ; -LDFLAGS = -Os -lm -Wl,--gc-sections -mmcu=atmega328p ; - -# Search everywhere for headers -HDRS = $(PROJECT_DIR) $(ARDUINO_AVR) $(ARDUINO_CORE) [ GLOB $(ARDUINO_LIB) $(SKETCH_LIB) : [^.]* ] ; - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp ] ; - -# In addition to explicitly-specified program modules, pick up anything from the current -# dir. -PROJECT_MODULES += [ GLOB $(PROJECT_DIR) : *.c *.cpp *.pde ] ; - -# Shortcut for the out files -OUT = $(OUT_DIR)/$(PROJECT_NAME) ; - -# AvrDude setup -AVRDUDE_FLAGS = -V -F -D -C $(AVRDUDECONFIG_PATH)/avrdude.conf -p $(MCU) -c $(AVRDUDE_PROTOCOL) -b $(UPLOAD_RATE) ; - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule AvrCc -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrCc -{ - $(AVR_CC) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CFLAGS) $(>) -} - -rule AvrC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrC++ -{ - $(AVR_CXX) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule Pde -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - -} - -actions Pde -{ - echo "#include " > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule AvrPde -{ - local _CPP = $(OUT_DIR)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - AvrC++ $(<) : $(_CPP) ; -} - -rule AvrObject -{ - switch $(>:S) - { - case .c : AvrCc $(<) : $(>) ; - case .cpp : AvrC++ $(<) : $(>) ; - case .pde : AvrPde $(<) : $(>) ; - } -} - -rule AvrObjects -{ - for _I in $(<) - { - AvrObject $(OUT_DIR)/$(_I:B).o : $(_I) ; - } -} - -rule AvrMainFromObjects -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - MkDir $(<:D) ; - Depends all : $(<) ; - Clean clean : $(<) ; -} - -actions AvrMainFromObjects -{ - $(AVR_LD) $(LDFLAGS) -o $(<) $(>) -} - -rule AvrMain -{ - AvrMainFromObjects $(<) : $(OUT_DIR)/$(>:B).o ; - AvrObjects $(>) ; -} - -rule AvrHex -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions AvrHex -{ - $(AVR_OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule AvrUpload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - AvrUploadAction $(2) : $(3) ; -} - -actions AvrUploadAction -{ - $(AVRDUDE) $(AVRDUDE_FLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -AvrMain $(OUT).elf : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -AvrHex $(OUT).hex : $(OUT).elf ; - -AvrUpload p6 : /dev/tty.usbserial-A600eHIs : $(OUT).hex ; -AvrUpload p4 : /dev/tty.usbserial-A40081RP : $(OUT).hex ; -AvrUpload p9 : /dev/tty.usbserial-A9007LmI : $(OUT).hex ; - diff --git a/libraries/RF24/examples/led_remote/led_remote.pde b/libraries/RF24/examples/led_remote/led_remote.pde deleted file mode 100644 index 2238845..0000000 --- a/libraries/RF24/examples/led_remote/led_remote.pde +++ /dev/null @@ -1,254 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * Example LED Remote - * - * This is an example of how to use the RF24 class to control a remote - * bank of LED's using buttons on a remote control. - * - * On the 'remote', connect any number of buttons or switches from - * an arduino pin to ground. Update 'button_pins' to reflect the - * pins used. - * - * On the 'led' board, connect the same number of LED's from an - * arduino pin to a resistor to ground. Update 'led_pins' to reflect - * the pins used. Also connect a separate pin to ground and change - * the 'role_pin'. This tells the sketch it's running on the LED board. - * - * Every time the buttons change on the remote, the entire state of - * buttons is send to the led board, which displays the state. - */ - -#include -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 8 & 9 - -RF24 radio(8,9); - -// sets the role of this unit in hardware. Connect to GND to be the 'led' board receiver -// Leave open to be the 'remote' transmitter -const int role_pin = A4; - -// Pins on the remote for buttons -const uint8_t button_pins[] = { 2,3,4,5,6,7 }; -const uint8_t num_button_pins = sizeof(button_pins); - -// Pins on the LED board for LED's -const uint8_t led_pins[] = { 2,3,4,5,6,7 }; -const uint8_t num_led_pins = sizeof(led_pins); - -// -// Topology -// - -// Single radio pipe address for the 2 nodes to communicate. -const uint64_t pipe = 0xE8E8F0F0E1LL; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes in this -// system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_remote = 1, role_led } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Remote", "LED Board"}; - -// The role of the current running sketch -role_e role; - -// -// Payload -// - -uint8_t button_states[num_button_pins]; -uint8_t led_states[num_led_pins]; - -// -// Setup -// - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_remote; - else - role = role_led; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/led_remote/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens a single pipes for these two nodes to communicate - // back and forth. One listens on it, the other talks to it. - - if ( role == role_remote ) - { - radio.openWritingPipe(pipe); - } - else - { - radio.openReadingPipe(1,pipe); - } - - // - // Start listening - // - - if ( role == role_led ) - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); - - // - // Set up buttons / LED's - // - - // Set pull-up resistors for all buttons - if ( role == role_remote ) - { - int i = num_button_pins; - while(i--) - { - pinMode(button_pins[i],INPUT); - digitalWrite(button_pins[i],HIGH); - } - } - - // Turn LED's ON until we start getting keys - if ( role == role_led ) - { - int i = num_led_pins; - while(i--) - { - pinMode(button_pins[i],OUTPUT); - led_states[i] = HIGH; - digitalWrite(led_pins[i],led_states[i]); - } - } - -} - -// -// Loop -// - -void loop(void) -{ - // - // Remote role. If the state of any button has changed, send the whole state of - // all buttons. - // - - if ( role == role_remote ) - { - // Get the current state of buttons, and - // Test if the current state is different from the last state we sent - int i = num_button_pins; - bool different = false; - while(i--) - { - uint8_t state = ! digitalRead(button_pins[i]); - if ( state != button_states[i] ) - { - different = true; - button_states[i] = state; - } - } - - // Send the state of the buttons to the LED board - if ( different ) - { - printf("Now sending..."); - bool ok = radio.write( button_states, num_button_pins ); - if (ok) - printf("ok\n\r"); - else - printf("failed\n\r"); - } - - // Try again in a short while - delay(20); - } - - // - // LED role. Receive the state of all buttons, and reflect that in the LEDs - // - - if ( role == role_led ) - { - // if there is data ready - if ( radio.available() ) - { - // Dump the payloads until we've gotten everything - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - done = radio.read( button_states, num_button_pins ); - - // Spew it - printf("Got buttons\n\r"); - - // For each button, if the button now on, then toggle the LED - int i = num_led_pins; - while(i--) - { - if ( button_states[i] ) - { - led_states[i] ^= HIGH; - digitalWrite(led_pins[i],led_states[i]); - } - } - } - } - } -} -// vim:ai:cin:sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/examples/led_remote/printf.h b/libraries/RF24/examples/led_remote/printf.h deleted file mode 100644 index df6c46a..0000000 --- a/libraries/RF24/examples/led_remote/printf.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -#include "WProgram.h" - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#endif // __PRINTF_H__ diff --git a/libraries/RF24/examples/nordic_fob/Jamfile b/libraries/RF24/examples/nordic_fob/Jamfile deleted file mode 100644 index ec519f7..0000000 --- a/libraries/RF24/examples/nordic_fob/Jamfile +++ /dev/null @@ -1,219 +0,0 @@ -# (1) Project Information - -PROJECT_LIBS = RF24 SPI ; -PROJECT_DIRS = $(PWD) ; - -# (2) Board Information - -UPLOAD_PROTOCOL ?= stk500v1 ; -UPLOAD_SPEED ?= 115200 ; -MCU ?= atmega328p ; -F_CPU ?= 16000000 ; -CORE ?= arduino ; -VARIANT ?= standard ; -ARDUINO_VERSION ?= 100 ; - -# (3) USB Ports - -PORTS = p4 p6 p9 u0 u1 u2 ; -PORT_p6 = /dev/tty.usbserial-A600eHIs ; -PORT_p4 = /dev/tty.usbserial-A40081RP ; -PORT_p9 = /dev/tty.usbserial-A9007LmI ; -PORT_u0 = /dev/ttyUSB0 ; -PORT_u1 = /dev/ttyUSB1 ; -PORT_u2 = /dev/ttyUSB2 ; - -# (4) Location of AVR tools -# -# This configuration assumes using avr-tools that were obtained separate from the Arduino -# distribution. - -if $(OS) = MACOSX -{ - AVR_BIN = /usr/local/avrtools/bin ; - AVR_ETC = /usr/local/avrtools/etc ; - AVR_INCLUDE = /usr/local/avrtools/include ; -} -else -{ - AVR_BIN = /usr/bin ; - AVR_INCLUDE = /usr/lib/avr/include ; - AVR_ETC = /etc ; -} - -# (5) Directories where Arduino core and libraries are located - -ARDUINO_DIR ?= /opt/Arduino ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/$(CORE) $(ARDUINO_DIR)/hardware/arduino/variants/$(VARIANT) ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; - -# -# -------------------------------------------------- -# Below this line usually never needs to be modified -# - -# Tool locations - -CC = $(AVR_BIN)/avr-gcc ; -C++ = $(AVR_BIN)/avr-g++ ; -LINK = $(AVR_BIN)/avr-gcc ; -AR = $(AVR_BIN)/avr-ar rcs ; -RANLIB = ; -OBJCOPY = $(AVR_BIN)/avr-objcopy ; -AVRDUDE = $(AVR_BIN)/avrdude ; - -# Flags - -DEFINES += F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -OPTIM = -Os ; -CCFLAGS = -Wall -Wextra -Wno-strict-aliasing -mmcu=$(MCU) -ffunction-sections -fdata-sections ; -C++FLAGS = $(CCFLAGS) -fno-exceptions -fno-strict-aliasing ; -LINKFLAGS = $(OPTIM) -lm -Wl,--gc-sections -mmcu=$(MCU) ; -AVRDUDEFLAGS = -V -F -D -C $(AVR_ETC)/avrdude.conf -p $(MCU) -c $(UPLOAD_PROTOCOL) -b $(UPLOAD_SPEED) ; - -# Search everywhere for headers - -HDRS = $(PROJECT_DIRS) $(AVR_INCLUDE) $(ARDUINO_CORE) $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) ; - -# Output locations - -LOCATE_TARGET = $(F_CPU) ; -LOCATE_SOURCE = $(F_CPU) ; - -# -# Custom rules -# - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule Pde -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_SOURCE) ; - Clean clean : $(<) ; -} - -if ( $(ARDUINO_VERSION) < 100 ) -{ - ARDUINO_H = WProgram.h ; -} -else -{ - ARDUINO_H = Arduino.h ; -} - -actions Pde -{ - echo "#include <$(ARDUINO_H)>" > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule C++Pde -{ - local _CPP = $(>:B).cpp ; - Pde $(_CPP) : $(>) ; - C++ $(<) : $(_CPP) ; -} - -rule UserObject -{ - switch $(>:S) - { - case .ino : C++Pde $(<) : $(>) ; - case .pde : C++Pde $(<) : $(>) ; - } -} - -rule Objects -{ - local _i ; - - for _i in [ FGristFiles $(<) ] - { - local _b = $(_i:B)$(SUFOBJ) ; - local _o = $(_b:G=$(SOURCE_GRIST:E)) ; - Object $(_o) : $(_i) ; - Depends obj : $(_o) ; - } -} - -rule Library -{ - LibraryFromObjects $(<) : $(>:B)$(SUFOBJ) ; - Objects $(>) ; -} - -rule Main -{ - MainFromObjects $(<) : $(>:B)$(SUFOBJ) ; - Objects $(>) ; -} - -rule Hex -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_TARGET) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions Hex -{ - $(OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule Upload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - UploadAction $(2) : $(3) ; -} - -actions UploadAction -{ - $(AVRDUDE) $(AVRDUDEFLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -rule Arduino -{ - LINKFLAGS on $(<) = $(LINKFLAGS) -Wl,-Map=$(LOCATE_TARGET)/$(<:B).map ; - Main $(<) : $(>) ; - LinkLibraries $(<) : libs core ; - Hex $(<:B).hex : $(<) ; - for _p in $(PORTS) - { - Upload $(_p) : $(PORT_$(_p)) : $(<:B).hex ; - } -} - -# -# Targets -# - -# Grab everything from the core directory -Library core : [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -Library libs : [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp *.c ] ; - -# Main output executable -Arduino $(PWD:B).elf : $(PROJECT_MODULES) [ GLOB $(PROJECT_DIRS) : *.c *.cpp *.pde *.ino ] ; diff --git a/libraries/RF24/examples/nordic_fob/nordic_fob.pde b/libraries/RF24/examples/nordic_fob/nordic_fob.pde deleted file mode 100644 index 5a316a0..0000000 --- a/libraries/RF24/examples/nordic_fob/nordic_fob.pde +++ /dev/null @@ -1,142 +0,0 @@ -/* - Copyright (C) 2012 J. Coliz - - 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. - */ - -/** - * Example Nordic FOB Receiver - * - * This is an example of how to use the RF24 class to receive signals from the - * Sparkfun Nordic FOB. Thanks to Kirk Mower for providing test hardware. - * - * See blog post at http://maniacbug.wordpress.com/2012/01/08/nordic-fob/ - */ - -#include -#include -#include "nRF24L01.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 9 & 10 - -RF24 radio(9,10); - -// -// Payload -// - -struct payload_t -{ - uint8_t buttons; - uint16_t id; - uint8_t empty; -}; - -const char* button_names[] = { "Up", "Down", "Left", "Right", "Center" }; -const int num_buttons = 5; - -// -// Forward declarations -// - -uint16_t flip_endian(uint16_t in); - -// -// Setup -// - -void setup(void) -{ - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\r\nRF24/examples/nordic_fob/\r\n"); - - // - // Setup and configure rf radio according to the built-in parameters - // of the FOB. - // - - radio.begin(); - radio.setChannel(2); - radio.setPayloadSize(4); - radio.setAutoAck(false); - radio.setCRCLength(RF24_CRC_8); - radio.openReadingPipe(1,0xE7E7E7E7E7LL); - - // - // Start listening - // - - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); -} - -// -// Loop -// - -void loop(void) -{ - // - // Receive each packet, dump it out - // - - // if there is data ready - if ( radio.available() ) - { - // Get the packet from the radio - payload_t payload; - radio.read( &payload, sizeof(payload) ); - - // Print the ID of this message. Note that the message - // is sent 'big-endian', so we have to flip it. - printf("#%05u Buttons ",flip_endian(payload.id)); - - // Print the name of each button - int i = num_buttons; - while (i--) - { - if ( ! ( payload.buttons & _BV(i) ) ) - { - printf("%s ",button_names[i]); - } - } - - // If no buttons, print None - if ( payload.buttons == _BV(num_buttons) - 1 ) - printf("None"); - - printf("\r\n"); - } -} - -// -// Helper functions -// - -// Change a big-endian word into a little-endian -uint16_t flip_endian(uint16_t in) -{ - uint16_t low = in >> 8; - uint16_t high = in << 8; - - return high | low; -} - -// vim:cin:ai:sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/examples/nordic_fob/printf.h b/libraries/RF24/examples/nordic_fob/printf.h deleted file mode 100644 index b2efd56..0000000 --- a/libraries/RF24/examples/nordic_fob/printf.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -#ifdef ARDUINO - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#else -#error This example is only for use on Arduino. -#endif // ARDUINO - -#endif // __PRINTF_H__ diff --git a/libraries/RF24/examples/pingpair/Jamfile b/libraries/RF24/examples/pingpair/Jamfile deleted file mode 100644 index 901f8da..0000000 --- a/libraries/RF24/examples/pingpair/Jamfile +++ /dev/null @@ -1,206 +0,0 @@ -PROJECT_NAME = $(PWD:B) ; -PROJECT_DIR = . ; -PROJECT_LIBS = SPI RF24 ; - -OUT_DIR = ojam ; -F_CPU = 16000000 ; -MCU = atmega328p ; -PORTS = /dev/tty.usbserial-A600eHIs /dev/tty.usbserial-A40081RP /dev/tty.usbserial-A9007LmI ; - -UPLOAD_RATE = 57600 ; -AVRDUDE_PROTOCOL = stk500v1 ; -COM = 33 ; - -# Host-specific overrides for locations -if $(OS) = MACOSX -{ -ARDUINO_VERSION = 22 ; -OLD_DIR = /opt/arduino-0021 ; -AVR_TOOLS_PATH = $(OLD_DIR)/hardware/tools/avr/bin ; -AVRDUDECONFIG_PATH = $(OLD_DIR)/hardware/tools/avr/etc ; -ARDUINO_DIR = /opt/Arduino ; -ARDUINO_AVR = /usr/lib/avr/include ; -} - -# Where is everything? -ARDUINO_VERSION ?= 22 ; -AVR_TOOLS_PATH ?= /usr/bin ; -ARDUINO_DIR ?= /opt/arduino-00$(ARDUINO_VERSION) ; -ARDUINO_AVR ?= $(ARDUINO_DIR)/hardware/tools/avr/avr/include/avr ; -AVRDUDECONFIG_PATH ?= $(ARDUINO_DIR)/hardware/tools ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; -AVR_CC = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_CXX = $(AVR_TOOLS_PATH)/avr-g++ ; -AVR_LD = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_OBJCOPY = $(AVR_TOOLS_PATH)/avr-objcopy ; -AVRDUDE = $(AVR_TOOLS_PATH)/avrdude ; - -DEFINES = F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -CTUNING = -ffunction-sections -fdata-sections ; -CXXTUNING = -fno-exceptions -fno-strict-aliasing ; -CFLAGS = -Os -Wall -Wextra -mmcu=$(MCU) $(CTUNING) ; -CXXFLAGS = $(CFLAGS) $(CXXTUNING) ; -LDFLAGS = -Os -lm -Wl,--gc-sections -mmcu=atmega328p ; - -# Search everywhere for headers -HDRS = $(PROJECT_DIR) $(ARDUINO_AVR) $(ARDUINO_CORE) [ GLOB $(ARDUINO_LIB) $(SKETCH_LIB) : [^.]* ] ; - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp ] ; - -# In addition to explicitly-specified program modules, pick up anything from the current -# dir. -PROJECT_MODULES += [ GLOB $(PROJECT_DIR) : *.c *.cpp *.pde ] ; - -# Shortcut for the out files -OUT = $(OUT_DIR)/$(PROJECT_NAME) ; - -# AvrDude setup -AVRDUDE_FLAGS = -V -F -D -C $(AVRDUDECONFIG_PATH)/avrdude.conf -p $(MCU) -c $(AVRDUDE_PROTOCOL) -b $(UPLOAD_RATE) ; - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule AvrCc -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrCc -{ - $(AVR_CC) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CFLAGS) $(>) -} - -rule AvrC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrC++ -{ - $(AVR_CXX) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule Pde -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - -} - -actions Pde -{ - echo "#include " > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule AvrPde -{ - local _CPP = $(OUT_DIR)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - AvrC++ $(<) : $(_CPP) ; -} - -rule AvrObject -{ - switch $(>:S) - { - case .c : AvrCc $(<) : $(>) ; - case .cpp : AvrC++ $(<) : $(>) ; - case .pde : AvrPde $(<) : $(>) ; - } -} - -rule AvrObjects -{ - for _I in $(<) - { - AvrObject $(OUT_DIR)/$(_I:B).o : $(_I) ; - } -} - -rule AvrMainFromObjects -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - MkDir $(<:D) ; - Depends all : $(<) ; - Clean clean : $(<) ; -} - -actions AvrMainFromObjects -{ - $(AVR_LD) $(LDFLAGS) -o $(<) $(>) -} - -rule AvrMain -{ - AvrMainFromObjects $(<) : $(OUT_DIR)/$(>:B).o ; - AvrObjects $(>) ; -} - -rule AvrHex -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions AvrHex -{ - $(AVR_OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule AvrUpload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - AvrUploadAction $(2) : $(3) ; -} - -actions AvrUploadAction -{ - $(AVRDUDE) $(AVRDUDE_FLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -AvrMain $(OUT).elf : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -AvrHex $(OUT).hex : $(OUT).elf ; - -AvrUpload p6 : /dev/tty.usbserial-A600eHIs : $(OUT).hex ; -AvrUpload p4 : /dev/tty.usbserial-A40081RP : $(OUT).hex ; -AvrUpload p9 : /dev/tty.usbserial-A9007LmI : $(OUT).hex ; - diff --git a/libraries/RF24/examples/pingpair/pingpair.pde b/libraries/RF24/examples/pingpair/pingpair.pde deleted file mode 100644 index b83de60..0000000 --- a/libraries/RF24/examples/pingpair/pingpair.pde +++ /dev/null @@ -1,218 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * Example RF Radio Ping Pair - * - * This is an example of how to use the RF24 class. Write this sketch to two different nodes, - * connect the role_pin to ground on one. The ping node sends the current time to the pong node, - * which responds by sending the value back. The ping node can then see how long the whole cycle - * took. - */ - -#include -#include -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 8 & 9 - -RF24 radio(9,10); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const int role_pin = 7; - -// -// Topology -// - -// Radio pipe addresses for the 2 nodes to communicate. -const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL }; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes -// in this system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_ping_out = 1, role_pong_back } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"}; - -// The role of the current running sketch -role_e role; - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_ping_out; - else - role = role_pong_back; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/pingpair/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // optionally, increase the delay between retries & # of retries - // radio.setRetries(15,15); - - // optionally, reduce the payload size. seems to - // improve reliability - // radio.setPayloadSize(8); - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens two pipes for these two nodes to communicate - // back and forth. - // Open 'our' pipe for writing - // Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading) - - if ( role == role_ping_out ) - { - radio.openWritingPipe(pipes[0]); - radio.openReadingPipe(1,pipes[1]); - } - else - { - radio.openWritingPipe(pipes[1]); - radio.openReadingPipe(1,pipes[0]); - } - - // - // Start listening - // - // if( radio.setDataRate( RF24_250KBPS ) ) { - // printf( "Data rate 250KBPS set!\n\r" ) ; - // } else { - // printf( "Data rate 250KBPS set FAILED!!\n\r" ) ; - // } - // radio.setDataRate( RF24_2MBPS ) ; - // radio.setPALevel( RF24_PA_MAX ) ; - radio.enableDynamicPayloads() ; - radio.setAutoAck( true ) ; - radio.powerUp() ; - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); -} - -void loop(void) -{ - // - // Ping out role. Repeatedly send the current time - // - - if (role == role_ping_out) - { - // First, stop listening so we can talk. - radio.stopListening(); - - // Take the time, and send it. This will block until complete - unsigned long time = millis(); - printf("Now sending %lu...",time); - radio.write( &time, sizeof(unsigned long) ); - - // Now, continue listening - radio.startListening(); - - // Wait here until we get a response, or timeout (250ms) - unsigned long started_waiting_at = millis(); - bool timeout = false; - while ( ! radio.available() && ! timeout ) - if (millis() - started_waiting_at > 1+(radio.getMaxTimeout()/1000) ) - timeout = true; - - // Describe the results - if ( timeout ) - { - printf("Failed, response timed out.\n\r"); - printf("Timeout duration: %d\n\r", (1+radio.getMaxTimeout()/1000) ) ; - } - else - { - // Grab the response, compare, and send to debugging spew - unsigned long got_time; - radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got response %lu, round-trip delay: %lu\n\r",got_time,millis()-got_time); - } - - // Try again 1s later - delay(1000); - } - - // - // Pong back role. Receive each packet, dump it out, and send it back - // - - if ( role == role_pong_back ) - { - // if there is data ready - if ( radio.available() ) - { - // Dump the payloads until we've gotten everything - unsigned long got_time; - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - done = radio.read( &got_time, sizeof(unsigned long) ); - } - - // First, stop listening so we can talk - radio.stopListening(); - - // Send the final one back. This way, we don't delay - // the reply while we wait on serial i/o. - radio.write( &got_time, sizeof(unsigned long) ); - printf("Sent response %lu\n\r", got_time); - - // Now, resume listening so we catch the next packets. - radio.startListening(); - } - } -} -// vim:cin:ai:sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/examples/pingpair/printf.h b/libraries/RF24/examples/pingpair/printf.h deleted file mode 100644 index 05dd088..0000000 --- a/libraries/RF24/examples/pingpair/printf.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -#include - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#endif // __PRINTF_H__ diff --git a/libraries/RF24/examples/pingpair_dyn/Jamfile b/libraries/RF24/examples/pingpair_dyn/Jamfile deleted file mode 100644 index 901f8da..0000000 --- a/libraries/RF24/examples/pingpair_dyn/Jamfile +++ /dev/null @@ -1,206 +0,0 @@ -PROJECT_NAME = $(PWD:B) ; -PROJECT_DIR = . ; -PROJECT_LIBS = SPI RF24 ; - -OUT_DIR = ojam ; -F_CPU = 16000000 ; -MCU = atmega328p ; -PORTS = /dev/tty.usbserial-A600eHIs /dev/tty.usbserial-A40081RP /dev/tty.usbserial-A9007LmI ; - -UPLOAD_RATE = 57600 ; -AVRDUDE_PROTOCOL = stk500v1 ; -COM = 33 ; - -# Host-specific overrides for locations -if $(OS) = MACOSX -{ -ARDUINO_VERSION = 22 ; -OLD_DIR = /opt/arduino-0021 ; -AVR_TOOLS_PATH = $(OLD_DIR)/hardware/tools/avr/bin ; -AVRDUDECONFIG_PATH = $(OLD_DIR)/hardware/tools/avr/etc ; -ARDUINO_DIR = /opt/Arduino ; -ARDUINO_AVR = /usr/lib/avr/include ; -} - -# Where is everything? -ARDUINO_VERSION ?= 22 ; -AVR_TOOLS_PATH ?= /usr/bin ; -ARDUINO_DIR ?= /opt/arduino-00$(ARDUINO_VERSION) ; -ARDUINO_AVR ?= $(ARDUINO_DIR)/hardware/tools/avr/avr/include/avr ; -AVRDUDECONFIG_PATH ?= $(ARDUINO_DIR)/hardware/tools ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; -AVR_CC = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_CXX = $(AVR_TOOLS_PATH)/avr-g++ ; -AVR_LD = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_OBJCOPY = $(AVR_TOOLS_PATH)/avr-objcopy ; -AVRDUDE = $(AVR_TOOLS_PATH)/avrdude ; - -DEFINES = F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -CTUNING = -ffunction-sections -fdata-sections ; -CXXTUNING = -fno-exceptions -fno-strict-aliasing ; -CFLAGS = -Os -Wall -Wextra -mmcu=$(MCU) $(CTUNING) ; -CXXFLAGS = $(CFLAGS) $(CXXTUNING) ; -LDFLAGS = -Os -lm -Wl,--gc-sections -mmcu=atmega328p ; - -# Search everywhere for headers -HDRS = $(PROJECT_DIR) $(ARDUINO_AVR) $(ARDUINO_CORE) [ GLOB $(ARDUINO_LIB) $(SKETCH_LIB) : [^.]* ] ; - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp ] ; - -# In addition to explicitly-specified program modules, pick up anything from the current -# dir. -PROJECT_MODULES += [ GLOB $(PROJECT_DIR) : *.c *.cpp *.pde ] ; - -# Shortcut for the out files -OUT = $(OUT_DIR)/$(PROJECT_NAME) ; - -# AvrDude setup -AVRDUDE_FLAGS = -V -F -D -C $(AVRDUDECONFIG_PATH)/avrdude.conf -p $(MCU) -c $(AVRDUDE_PROTOCOL) -b $(UPLOAD_RATE) ; - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule AvrCc -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrCc -{ - $(AVR_CC) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CFLAGS) $(>) -} - -rule AvrC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrC++ -{ - $(AVR_CXX) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule Pde -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - -} - -actions Pde -{ - echo "#include " > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule AvrPde -{ - local _CPP = $(OUT_DIR)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - AvrC++ $(<) : $(_CPP) ; -} - -rule AvrObject -{ - switch $(>:S) - { - case .c : AvrCc $(<) : $(>) ; - case .cpp : AvrC++ $(<) : $(>) ; - case .pde : AvrPde $(<) : $(>) ; - } -} - -rule AvrObjects -{ - for _I in $(<) - { - AvrObject $(OUT_DIR)/$(_I:B).o : $(_I) ; - } -} - -rule AvrMainFromObjects -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - MkDir $(<:D) ; - Depends all : $(<) ; - Clean clean : $(<) ; -} - -actions AvrMainFromObjects -{ - $(AVR_LD) $(LDFLAGS) -o $(<) $(>) -} - -rule AvrMain -{ - AvrMainFromObjects $(<) : $(OUT_DIR)/$(>:B).o ; - AvrObjects $(>) ; -} - -rule AvrHex -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions AvrHex -{ - $(AVR_OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule AvrUpload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - AvrUploadAction $(2) : $(3) ; -} - -actions AvrUploadAction -{ - $(AVRDUDE) $(AVRDUDE_FLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -AvrMain $(OUT).elf : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -AvrHex $(OUT).hex : $(OUT).elf ; - -AvrUpload p6 : /dev/tty.usbserial-A600eHIs : $(OUT).hex ; -AvrUpload p4 : /dev/tty.usbserial-A40081RP : $(OUT).hex ; -AvrUpload p9 : /dev/tty.usbserial-A9007LmI : $(OUT).hex ; - diff --git a/libraries/RF24/examples/pingpair_dyn/pingpair_dyn.pde b/libraries/RF24/examples/pingpair_dyn/pingpair_dyn.pde deleted file mode 100644 index c0662b6..0000000 --- a/libraries/RF24/examples/pingpair_dyn/pingpair_dyn.pde +++ /dev/null @@ -1,234 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * Example using Dynamic Payloads - * - * This is an example of how to use payloads of a varying (dynamic) size. - */ - -#include -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 8 & 9 - -//RF24 radio(8,9); -RF24 radio(22,23); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const int role_pin = 7; - -// -// Topology -// - -// Radio pipe addresses for the 2 nodes to communicate. -const uint64_t pipes[2] = { 0xEEFDFDFDECLL, 0xEEFDFDF0DFLL }; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes -// in this system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_ping_out = 1, role_pong_back } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"}; - -// The role of the current running sketch -role_e role; - -// -// Payload -// - -const int min_payload_size = 1; -const int max_payload_size = 32; -const int payload_size_increments_by = 1; -int next_payload_size = min_payload_size; - -char receive_payload[max_payload_size+1]; // +1 to allow room for a terminating NULL char - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_ping_out; - else - role = role_pong_back; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/pingpair_dyn/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // enable dynamic payloads - radio.setCRCLength( RF24_CRC_16 ) ; - radio.enableDynamicPayloads(); - - // optionally, increase the delay between retries & # of retries - radio.setAutoAck( true ) ; - radio.setPALevel( RF24_PA_HIGH ) ; - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens two pipes for these two nodes to communicate - // back and forth. - // Open 'our' pipe for writing - // Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading) - - if ( role == role_ping_out ) - { - radio.openWritingPipe(pipes[0]); - radio.openReadingPipe(1,pipes[1]); - } - else - { - radio.openWritingPipe(pipes[1]); - radio.openReadingPipe(1,pipes[0]); - } - - // - // Start listening - // - - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); -} - -void loop(void) -{ - // - // Ping out role. Repeatedly send the current time - // - - if (role == role_ping_out) - { - // The payload will always be the same, what will change is how much of it we send. - static char send_payload[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ789012"; - - // First, stop listening so we can talk. - radio.stopListening(); - - // Take the time, and send it. This will block until complete - printf("Now sending length %i...",next_payload_size); - radio.write( send_payload, next_payload_size, false ); - - // Now, continue listening - radio.startListening(); - - // Wait here until we get a response, or timeout - unsigned long started_waiting_at = millis(); - bool timeout = false; - while ( ! radio.available() && ! timeout ) - if (millis() - started_waiting_at > 1 + radio.getMaxTimeout()/1000 ) - timeout = true; - - // Describe the results - if ( timeout ) - { - printf("Failed, response timed out.\n\r"); - } - else - { - // Grab the response, compare, and send to debugging spew - uint8_t len = radio.getDynamicPayloadSize(); - radio.read( receive_payload, len ); - - // Put a zero at the end for easy printing - receive_payload[len] = 0; - - // Spew it - printf("Got response size=%i value=%s\n\r",len,receive_payload); - } - - // Update size for next time. - next_payload_size += payload_size_increments_by; - if ( next_payload_size > max_payload_size ) - next_payload_size = min_payload_size; - - // Try again 1s later - delay(1000); - } - - // - // Pong back role. Receive each packet, dump it out, and send it back - // - - if ( role == role_pong_back ) - { - // if there is data ready - if ( radio.available() ) - { - // Dump the payloads until we've gotten everything - uint8_t len; - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - len = radio.getDynamicPayloadSize(); - done = radio.read( receive_payload, len ); - - // Put a zero at the end for easy printing - receive_payload[len] = 0; - - // Spew it - printf("Got payload size=%i value=%s\n\r",len,receive_payload); - } - - // First, stop listening so we can talk - radio.stopListening(); - - // Send the final one back. - radio.(write receive_payload, len ); - printf("Sent response.\n\r"); - - // Now, resume listening so we catch the next packets. - radio.startListening(); - } - } -} -// vim:cin:ai:sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/examples/pingpair_dyn/printf.h b/libraries/RF24/examples/pingpair_dyn/printf.h deleted file mode 100644 index 1b853db..0000000 --- a/libraries/RF24/examples/pingpair_dyn/printf.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#endif // __PRINTF_H__ diff --git a/libraries/RF24/examples/pingpair_irq/Jamfile b/libraries/RF24/examples/pingpair_irq/Jamfile deleted file mode 100644 index 901f8da..0000000 --- a/libraries/RF24/examples/pingpair_irq/Jamfile +++ /dev/null @@ -1,206 +0,0 @@ -PROJECT_NAME = $(PWD:B) ; -PROJECT_DIR = . ; -PROJECT_LIBS = SPI RF24 ; - -OUT_DIR = ojam ; -F_CPU = 16000000 ; -MCU = atmega328p ; -PORTS = /dev/tty.usbserial-A600eHIs /dev/tty.usbserial-A40081RP /dev/tty.usbserial-A9007LmI ; - -UPLOAD_RATE = 57600 ; -AVRDUDE_PROTOCOL = stk500v1 ; -COM = 33 ; - -# Host-specific overrides for locations -if $(OS) = MACOSX -{ -ARDUINO_VERSION = 22 ; -OLD_DIR = /opt/arduino-0021 ; -AVR_TOOLS_PATH = $(OLD_DIR)/hardware/tools/avr/bin ; -AVRDUDECONFIG_PATH = $(OLD_DIR)/hardware/tools/avr/etc ; -ARDUINO_DIR = /opt/Arduino ; -ARDUINO_AVR = /usr/lib/avr/include ; -} - -# Where is everything? -ARDUINO_VERSION ?= 22 ; -AVR_TOOLS_PATH ?= /usr/bin ; -ARDUINO_DIR ?= /opt/arduino-00$(ARDUINO_VERSION) ; -ARDUINO_AVR ?= $(ARDUINO_DIR)/hardware/tools/avr/avr/include/avr ; -AVRDUDECONFIG_PATH ?= $(ARDUINO_DIR)/hardware/tools ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; -AVR_CC = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_CXX = $(AVR_TOOLS_PATH)/avr-g++ ; -AVR_LD = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_OBJCOPY = $(AVR_TOOLS_PATH)/avr-objcopy ; -AVRDUDE = $(AVR_TOOLS_PATH)/avrdude ; - -DEFINES = F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -CTUNING = -ffunction-sections -fdata-sections ; -CXXTUNING = -fno-exceptions -fno-strict-aliasing ; -CFLAGS = -Os -Wall -Wextra -mmcu=$(MCU) $(CTUNING) ; -CXXFLAGS = $(CFLAGS) $(CXXTUNING) ; -LDFLAGS = -Os -lm -Wl,--gc-sections -mmcu=atmega328p ; - -# Search everywhere for headers -HDRS = $(PROJECT_DIR) $(ARDUINO_AVR) $(ARDUINO_CORE) [ GLOB $(ARDUINO_LIB) $(SKETCH_LIB) : [^.]* ] ; - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp ] ; - -# In addition to explicitly-specified program modules, pick up anything from the current -# dir. -PROJECT_MODULES += [ GLOB $(PROJECT_DIR) : *.c *.cpp *.pde ] ; - -# Shortcut for the out files -OUT = $(OUT_DIR)/$(PROJECT_NAME) ; - -# AvrDude setup -AVRDUDE_FLAGS = -V -F -D -C $(AVRDUDECONFIG_PATH)/avrdude.conf -p $(MCU) -c $(AVRDUDE_PROTOCOL) -b $(UPLOAD_RATE) ; - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule AvrCc -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrCc -{ - $(AVR_CC) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CFLAGS) $(>) -} - -rule AvrC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrC++ -{ - $(AVR_CXX) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule Pde -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - -} - -actions Pde -{ - echo "#include " > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule AvrPde -{ - local _CPP = $(OUT_DIR)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - AvrC++ $(<) : $(_CPP) ; -} - -rule AvrObject -{ - switch $(>:S) - { - case .c : AvrCc $(<) : $(>) ; - case .cpp : AvrC++ $(<) : $(>) ; - case .pde : AvrPde $(<) : $(>) ; - } -} - -rule AvrObjects -{ - for _I in $(<) - { - AvrObject $(OUT_DIR)/$(_I:B).o : $(_I) ; - } -} - -rule AvrMainFromObjects -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - MkDir $(<:D) ; - Depends all : $(<) ; - Clean clean : $(<) ; -} - -actions AvrMainFromObjects -{ - $(AVR_LD) $(LDFLAGS) -o $(<) $(>) -} - -rule AvrMain -{ - AvrMainFromObjects $(<) : $(OUT_DIR)/$(>:B).o ; - AvrObjects $(>) ; -} - -rule AvrHex -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions AvrHex -{ - $(AVR_OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule AvrUpload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - AvrUploadAction $(2) : $(3) ; -} - -actions AvrUploadAction -{ - $(AVRDUDE) $(AVRDUDE_FLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -AvrMain $(OUT).elf : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -AvrHex $(OUT).hex : $(OUT).elf ; - -AvrUpload p6 : /dev/tty.usbserial-A600eHIs : $(OUT).hex ; -AvrUpload p4 : /dev/tty.usbserial-A40081RP : $(OUT).hex ; -AvrUpload p9 : /dev/tty.usbserial-A9007LmI : $(OUT).hex ; - diff --git a/libraries/RF24/examples/pingpair_irq/pingpair_irq.pde b/libraries/RF24/examples/pingpair_irq/pingpair_irq.pde deleted file mode 100644 index 58eec33..0000000 --- a/libraries/RF24/examples/pingpair_irq/pingpair_irq.pde +++ /dev/null @@ -1,217 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * Example of using interrupts - * - * This is an example of how to user interrupts to interact with the radio. - * It builds on the pingpair_pl example, and uses ack payloads. - */ - -#include -#include "nRF24L01.h" -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 8 & 9 - -RF24 radio(8,9); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const short role_pin = 7; - -// -// Topology -// - -// Single radio pipe address for the 2 nodes to communicate. -const uint64_t pipe = 0xE8E8F0F0E1LL; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes in this -// system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_sender = 1, role_receiver } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Sender", "Receiver"}; - -// The role of the current running sketch -role_e role; - -// Interrupt handler, check the radio because we got an IRQ -void check_radio(void); - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_sender; - else - role = role_receiver; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/pingpair_irq/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // We will be using the Ack Payload feature, so please enable it - radio.enableAckPayload(); - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens a single pipe for these two nodes to communicate - // back and forth. One listens on it, the other talks to it. - - if ( role == role_sender ) - { - radio.openWritingPipe(pipe); - } - else - { - radio.openReadingPipe(1,pipe); - } - - // - // Start listening - // - - if ( role == role_receiver ) - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); - - // - // Attach interrupt handler to interrupt #0 (using pin 2) - // on BOTH the sender and receiver - // - - attachInterrupt(0, check_radio, FALLING); -} - -static uint32_t message_count = 0; - -void loop(void) -{ - // - // Sender role. Repeatedly send the current time - // - - if (role == role_sender) - { - // Take the time, and send it. - unsigned long time = millis(); - printf("Now sending %lu\n\r",time); - radio.powerUp() ; - radio.startWrite( &time, sizeof(unsigned long) ); - - // Try again soon - delay(1000); - } - - // - // Receiver role: Does nothing! All the work is in IRQ - // - -} - -void check_radio(void) -{ - // What happened? - bool tx,fail,rx; - radio.whatHappened(tx,fail,rx); - - // Have we successfully transmitted? - if ( tx ) - { - if ( role == role_sender ) - printf("Send:OK\n\r"); - - if ( role == role_receiver ) - printf("Ack Payload:Sent\n\r"); - } - - // Have we failed to transmit? - if ( fail ) - { - if ( role == role_sender ) - printf("Send:Failed\n\r"); - - if ( role == role_receiver ) - printf("Ack Payload:Failed\n\r"); - } - - // Transmitter can power down for now, because - // the transmission is done. - if ( ( tx || fail ) && ( role == role_sender ) ) - radio.powerDown(); - - // Did we receive a message? - if ( rx ) - { - // If we're the sender, we've received an ack payload - if ( role == role_sender ) - { - radio.read(&message_count,sizeof(message_count)); - printf("Ack:%lu\n\r",message_count); - } - - // If we're the receiver, we've received a time message - if ( role == role_receiver ) - { - // Get this payload and dump it - static unsigned long got_time; - radio.read( &got_time, sizeof(got_time) ); - printf("Got payload %lu\n\r",got_time); - - // Add an ack packet for the next time around. This is a simple - // packet counter - radio.writeAckPayload( 1, &message_count, sizeof(message_count) ); - ++message_count; - } - } -} - -// vim:ai:cin:sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/examples/pingpair_irq/printf.h b/libraries/RF24/examples/pingpair_irq/printf.h deleted file mode 100644 index ef29df7..0000000 --- a/libraries/RF24/examples/pingpair_irq/printf.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#endif // __PRINTF_H__ diff --git a/libraries/RF24/examples/pingpair_maple/Jamfile b/libraries/RF24/examples/pingpair_maple/Jamfile deleted file mode 100644 index 798096c..0000000 --- a/libraries/RF24/examples/pingpair_maple/Jamfile +++ /dev/null @@ -1,182 +0,0 @@ -MCU = cortex-m3 ; -CHIP = STM32F103ZE ; -BOARD = maple_native ; - -#CHIP = at91sam3u4 ; -#BOARD = sam3u-ek ; - -if ! $(TOOLSET) -{ - TOOLSET = devkit ; - Echo "Assuming TOOLSET=devkit" ; -} - -if $(TOOLSET) = yagarto -{ - TOOLS_PATH = ~/Source/yagarto-4.6.2/bin ; - TOOLS_ARCH = arm-none-eabi- ; -} -if $(TOOLSET) = yagarto-install -{ - TOOLS_PATH = ~/Source/yagarto/install/bin ; - TOOLS_ARCH = arm-none-eabi- ; -} -else if $(TOOLSET) = devkit -{ - TOOLS_PATH = /opt/devkitARM/bin ; - TOOLS_ARCH = arm-eabi- ; -} -else if $(TOOLSET) = maple -{ - TOOLS_PATH = /opt/Maple/Resources/Java/hardware/tools/arm/bin ; - TOOLS_ARCH = arm-none-eabi- ; -} -else if $(TOOLSET) = ports -{ - TOOLS_PATH = /opt/local/bin ; - TOOLS_ARCH = arm-none-eabi- ; -} - -CC = $(TOOLS_PATH)/$(TOOLS_ARCH)gcc ; -C++ = $(TOOLS_PATH)/$(TOOLS_ARCH)g++ ; -AS = $(TOOLS_PATH)/$(TOOLS_ARCH)gcc -c ; -LINK = $(TOOLS_PATH)/$(TOOLS_ARCH)g++ ; -OBJCOPY = $(TOOLS_PATH)/$(TOOLS_ARCH)objcopy ; -DFU = dfu-util ; - -DEFINES += VECT_TAB_FLASH BOARD_$(BOARD) MCU_$(CHIP) ERROR_LED_PORT=GPIOC ERROR_LED_PIN=15 STM32_HIGH_DENSITY MAPLE_IDE ; -OPTIM = -Os ; -MFLAGS = cpu=$(MCU) thumb arch=armv7-m ; -CCFLAGS = -Wall -m$(MFLAGS) -g -nostdlib -ffunction-sections -fdata-sections -Wl,--gc-sections ; -C++FLAGS = $(CCFLAGS) -fno-rtti -fno-exceptions ; -LINKFLAGS += -m$(MFLAGS) -Xlinker --gc-sections ; -DFUFLAGS = -a1 -d 0x1eaf:0x0003 -R ; - -MAPLE_DIR = $(HOME)/Source/SAM3U/libmaple ; -MAPLE_LIBS = Servo LiquidCrystal Wire FreeRTOS ; -MAPLE_SUBDIRS = wirish wirish/comm wirish/boards libmaple libmaple/usb libmaple/usb/usb_lib ; - -SKETCH_DIR = $(HOME)/Source/Arduino ; -SKETCH_LIBS = RF24 ; - -MODULE_DIRS = . $(MAPLE_DIR)/$(MAPLE_SUBDIRS) $(MAPLE_DIR)/libraries/$(MAPLE_LIBS) $(SKETCH_DIR)/libraries/$(SKETCH_LIBS) ; -HDRS = $(MODULE_DIRS) ; -LOCATE_TARGET = out/$(TOOLSET) ; -LOCATE_SOURCE = $(LOCATE_TARGET) ; - -rule Pde -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_SOURCE) ; - Clean clean : $(<) ; -} - -if ( $(ARDUINO_VERSION) < 100 ) -{ - ARDUINO_H = WProgram.h ; -} -else -{ - ARDUINO_H = Arduino.h ; -} - -actions Pde -{ - echo "#include <$(ARDUINO_H)>" > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule C++Pde -{ - local _CPP = $(>:B).cpp ; - Pde $(_CPP) : $(>) ; - C++ $(<) : $(_CPP) ; -} - -rule Hex -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_TARGET) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions Hex -{ - $(OBJCOPY) -O ihex $(>) $(<) -} - -rule Binary -{ - Depends $(<) : $(>) ; - MakeLocate $(<) : $(LOCATE_TARGET) ; - Depends binary : $(<) ; - Clean clean : $(<) ; -} - -actions Binary -{ - $(OBJCOPY) -O binary $(>) $(<) -} - -rule UserObject -{ - switch $(>:S) - { - case .S : As $(<) : $(>) ; - case .ino : C++Pde $(<) : $(>) ; - case .pde : C++Pde $(<) : $(>) ; - } -} - -rule Upload -{ - Depends up : $(<) ; - NotFile up ; - Always $(<) ; - Always up ; -} - -actions Upload -{ - $(DFU) $(DFUFLAGS) -D $(<) -} - -# Override base objects rule, so all output can go in the output dir -rule Objects -{ - local _i ; - - for _i in [ FGristFiles $(<) ] - { - local _b = $(_i:B)$(SUFOBJ) ; - local _o = $(_b:G=$(SOURCE_GRIST:E)) ; - Object $(_o) : $(_i) ; - Depends obj : $(_o) ; - } -} - -# Override base main rule, so all output can go in the output dir -rule Main -{ - MainFromObjects $(<) : $(>:B)$(SUFOBJ) ; - Objects $(>) ; -} - -# Modules -MODULES = [ GLOB $(MODULE_DIRS) : *.pde *.c *.cpp *.S ] ; - -# Main output executable -MAIN = $(PWD:B).elf ; - -# Linker script -LINK_DIR = $(MAPLE_DIR)/support/ld ; -LINKSCRIPT = $(LINK_DIR)/$(BOARD)/flash.ld ; - -# Bring in the map and link script -LINKFLAGS += -Wl,-Map=$(LOCATE_TARGET)/$(MAIN:B).map -T$(LINKSCRIPT) -L$(LINK_DIR) ; - -Main $(MAIN) : $(MODULES) ; -Binary $(MAIN:B).bin : $(MAIN) ; -Upload $(MAIN:B).bin ; diff --git a/libraries/RF24/examples/pingpair_maple/main.cpp b/libraries/RF24/examples/pingpair_maple/main.cpp deleted file mode 100644 index b4f976d..0000000 --- a/libraries/RF24/examples/pingpair_maple/main.cpp +++ /dev/null @@ -1,87 +0,0 @@ -#ifdef MAPLE_IDE - -#include -#include "wirish.h" - -extern void setup(void); -extern void loop(void); - -void board_start(const char* program_name) -{ - // Set up the LED to steady on - pinMode(BOARD_LED_PIN, OUTPUT); - digitalWrite(BOARD_LED_PIN, HIGH); - - // Setup the button as input - pinMode(BOARD_BUTTON_PIN, INPUT); - digitalWrite(BOARD_BUTTON_PIN, HIGH); - - SerialUSB.begin(); - SerialUSB.println("Press BUT"); - - // Wait for button press - while ( !isButtonPressed() ) - { - } - - SerialUSB.println("Welcome!"); - SerialUSB.println(program_name); - - int i = 11; - while (i--) - { - toggleLED(); - delay(50); - } -} - -/** - * Custom version of _write, which will print to the USB. - * In order to use it you MUST ADD __attribute__((weak)) - * to _write in libmaple/syscalls.c -*/ -extern "C" int _write (int file, char * ptr, int len) -{ - if ( (file != 1) && (file != 2) ) - return 0; - else - SerialUSB.write(ptr,len); - return len; -} - -/** - * Re-entrant version of _write. Yagarto and Devkit now use - * the re-entrant newlib, so these get called instead of the - * non_r versions. - */ -extern "C" int _write_r (void*, int file, char * ptr, int len) -{ - return _write( file, ptr, len); -} - -__attribute__((constructor)) __attribute__ ((weak)) void premain() -{ - init(); -} - -__attribute__((weak)) void setup(void) -{ - board_start("No program defined"); -} - -__attribute__((weak)) void loop(void) -{ -} - -__attribute__((weak)) int main(void) -{ - setup(); - - while (true) - { - loop(); - } - return 0; -} -#endif // ifdef MAPLE_IDE -// vim:cin:ai:sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/examples/pingpair_maple/pingpair_maple.pde b/libraries/RF24/examples/pingpair_maple/pingpair_maple.pde deleted file mode 100644 index 2d3925b..0000000 --- a/libraries/RF24/examples/pingpair_maple/pingpair_maple.pde +++ /dev/null @@ -1,242 +0,0 @@ -/* - Copyright (C) 2011 J. Coliz - - 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. - */ - -/** - * Example RF Radio Ping Pair ... for Maple - * - * This is an example of how to use the RF24 class. Write this sketch to two different nodes, - * connect the role_pin to ground on one. The ping node sends the current time to the pong node, - * which responds by sending the value back. The ping node can then see how long the whole cycle - * took. - */ - -#include "WProgram.h" -#include -#include "nRF24L01.h" -#include "RF24.h" - -// -// Maple specific setup. Other than this section, the sketch is the same on Maple as on -// Arduino -// - -#ifdef MAPLE_IDE - -// External startup function -extern void board_start(const char* program_name); - -// Use SPI #2. -HardwareSPI SPI(2); - -#else -#define board_startup printf -#define toggleLED(x) (x) -#endif - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 7 & 6 -// (This works for the Getting Started board plugged into the -// Maple Native backwards.) - -RF24 radio(7,6); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const int role_pin = 10; - -// -// Topology -// - -// Radio pipe addresses for the 2 nodes to communicate. -const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL }; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes -// in this system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_ping_out = 1, role_pong_back } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"}; - -// The role of the current running sketch -role_e role; - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_ping_out; - else - role = role_pong_back; - - // - // Print preamble - // - - board_start("\n\rRF24/examples/pingpair/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // optionally, increase the delay between retries & # of retries - radio.setRetries(15,15); - - // optionally, reduce the payload size. seems to - // improve reliability - radio.setPayloadSize(8); - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens two pipes for these two nodes to communicate - // back and forth. - // Open 'our' pipe for writing - // Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading) - - if ( role == role_ping_out ) - { - radio.openWritingPipe(pipes[0]); - radio.openReadingPipe(1,pipes[1]); - } - else - { - radio.openWritingPipe(pipes[1]); - radio.openReadingPipe(1,pipes[0]); - } - - // - // Start listening - // - - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); -} - -void loop(void) -{ - // - // Ping out role. Repeatedly send the current time - // - - if (role == role_ping_out) - { - toggleLED(); - - // First, stop listening so we can talk. - radio.stopListening(); - - // Take the time, and send it. This will block until complete - unsigned long time = millis(); - printf("Now sending %lu...",time); - bool ok = radio.write( &time, sizeof(unsigned long) ); - - if (ok) - printf("ok...\r\n"); - else - printf("failed.\r\n"); - - // Now, continue listening - radio.startListening(); - - // Wait here until we get a response, or timeout (250ms) - unsigned long started_waiting_at = millis(); - bool timeout = false; - while ( ! radio.available() && ! timeout ) - if (millis() - started_waiting_at > 200 ) - timeout = true; - - // Describe the results - if ( timeout ) - { - printf("Failed, response timed out.\r\n"); - } - else - { - // Grab the response, compare, and send to debugging spew - unsigned long got_time; - radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got response %lu, round-trip delay: %lu\r\n",got_time,millis()-got_time); - } - - toggleLED(); - - // Try again 1s later - delay(1000); - } - - // - // Pong back role. Receive each packet, dump it out, and send it back - // - - if ( role == role_pong_back ) - { - // if there is data ready - if ( radio.available() ) - { - // Dump the payloads until we've gotten everything - unsigned long got_time; - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - done = radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got payload %lu...",got_time); - - // Delay just a little bit to let the other unit - // make the transition to receiver - delay(20); - } - - // First, stop listening so we can talk - radio.stopListening(); - - // Send the final one back. - radio.write( &got_time, sizeof(unsigned long) ); - printf("Sent response.\r\n"); - - // Now, resume listening so we catch the next packets. - radio.startListening(); - } - } -} -// vim:cin:ai:sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/examples/pingpair_multi_dyn/Jamfile b/libraries/RF24/examples/pingpair_multi_dyn/Jamfile deleted file mode 100644 index 901f8da..0000000 --- a/libraries/RF24/examples/pingpair_multi_dyn/Jamfile +++ /dev/null @@ -1,206 +0,0 @@ -PROJECT_NAME = $(PWD:B) ; -PROJECT_DIR = . ; -PROJECT_LIBS = SPI RF24 ; - -OUT_DIR = ojam ; -F_CPU = 16000000 ; -MCU = atmega328p ; -PORTS = /dev/tty.usbserial-A600eHIs /dev/tty.usbserial-A40081RP /dev/tty.usbserial-A9007LmI ; - -UPLOAD_RATE = 57600 ; -AVRDUDE_PROTOCOL = stk500v1 ; -COM = 33 ; - -# Host-specific overrides for locations -if $(OS) = MACOSX -{ -ARDUINO_VERSION = 22 ; -OLD_DIR = /opt/arduino-0021 ; -AVR_TOOLS_PATH = $(OLD_DIR)/hardware/tools/avr/bin ; -AVRDUDECONFIG_PATH = $(OLD_DIR)/hardware/tools/avr/etc ; -ARDUINO_DIR = /opt/Arduino ; -ARDUINO_AVR = /usr/lib/avr/include ; -} - -# Where is everything? -ARDUINO_VERSION ?= 22 ; -AVR_TOOLS_PATH ?= /usr/bin ; -ARDUINO_DIR ?= /opt/arduino-00$(ARDUINO_VERSION) ; -ARDUINO_AVR ?= $(ARDUINO_DIR)/hardware/tools/avr/avr/include/avr ; -AVRDUDECONFIG_PATH ?= $(ARDUINO_DIR)/hardware/tools ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; -AVR_CC = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_CXX = $(AVR_TOOLS_PATH)/avr-g++ ; -AVR_LD = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_OBJCOPY = $(AVR_TOOLS_PATH)/avr-objcopy ; -AVRDUDE = $(AVR_TOOLS_PATH)/avrdude ; - -DEFINES = F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -CTUNING = -ffunction-sections -fdata-sections ; -CXXTUNING = -fno-exceptions -fno-strict-aliasing ; -CFLAGS = -Os -Wall -Wextra -mmcu=$(MCU) $(CTUNING) ; -CXXFLAGS = $(CFLAGS) $(CXXTUNING) ; -LDFLAGS = -Os -lm -Wl,--gc-sections -mmcu=atmega328p ; - -# Search everywhere for headers -HDRS = $(PROJECT_DIR) $(ARDUINO_AVR) $(ARDUINO_CORE) [ GLOB $(ARDUINO_LIB) $(SKETCH_LIB) : [^.]* ] ; - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp ] ; - -# In addition to explicitly-specified program modules, pick up anything from the current -# dir. -PROJECT_MODULES += [ GLOB $(PROJECT_DIR) : *.c *.cpp *.pde ] ; - -# Shortcut for the out files -OUT = $(OUT_DIR)/$(PROJECT_NAME) ; - -# AvrDude setup -AVRDUDE_FLAGS = -V -F -D -C $(AVRDUDECONFIG_PATH)/avrdude.conf -p $(MCU) -c $(AVRDUDE_PROTOCOL) -b $(UPLOAD_RATE) ; - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule AvrCc -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrCc -{ - $(AVR_CC) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CFLAGS) $(>) -} - -rule AvrC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrC++ -{ - $(AVR_CXX) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule Pde -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - -} - -actions Pde -{ - echo "#include " > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule AvrPde -{ - local _CPP = $(OUT_DIR)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - AvrC++ $(<) : $(_CPP) ; -} - -rule AvrObject -{ - switch $(>:S) - { - case .c : AvrCc $(<) : $(>) ; - case .cpp : AvrC++ $(<) : $(>) ; - case .pde : AvrPde $(<) : $(>) ; - } -} - -rule AvrObjects -{ - for _I in $(<) - { - AvrObject $(OUT_DIR)/$(_I:B).o : $(_I) ; - } -} - -rule AvrMainFromObjects -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - MkDir $(<:D) ; - Depends all : $(<) ; - Clean clean : $(<) ; -} - -actions AvrMainFromObjects -{ - $(AVR_LD) $(LDFLAGS) -o $(<) $(>) -} - -rule AvrMain -{ - AvrMainFromObjects $(<) : $(OUT_DIR)/$(>:B).o ; - AvrObjects $(>) ; -} - -rule AvrHex -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions AvrHex -{ - $(AVR_OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule AvrUpload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - AvrUploadAction $(2) : $(3) ; -} - -actions AvrUploadAction -{ - $(AVRDUDE) $(AVRDUDE_FLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -AvrMain $(OUT).elf : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -AvrHex $(OUT).hex : $(OUT).elf ; - -AvrUpload p6 : /dev/tty.usbserial-A600eHIs : $(OUT).hex ; -AvrUpload p4 : /dev/tty.usbserial-A40081RP : $(OUT).hex ; -AvrUpload p9 : /dev/tty.usbserial-A9007LmI : $(OUT).hex ; - diff --git a/libraries/RF24/examples/pingpair_multi_dyn/pingpair_multi_dyn.pde b/libraries/RF24/examples/pingpair_multi_dyn/pingpair_multi_dyn.pde deleted file mode 100644 index 8809023..0000000 --- a/libraries/RF24/examples/pingpair_multi_dyn/pingpair_multi_dyn.pde +++ /dev/null @@ -1,253 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * Example using Dynamic Payloads - * - * This is an example of how to use payloads of a varying (dynamic) size. - */ - -#include -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 8 & 9 -RF24 radio(8,9); - -// Use multicast? -// sets the multicast behavior this unit in hardware. Connect to GND to use unicast -// Leave open (default) to use multicast. -const int multicast_pin = 6 ; - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const int role_pin = 7; -bool multicast = true ; - -// -// Topology -// - -// Radio pipe addresses for the 2 nodes to communicate. -const uint64_t pipes[2] = { 0xEEFAFDFDEELL, 0xEEFDFAF50DFLL }; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes -// in this system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_ping_out = 1, role_pong_back } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"}; - -// The role of the current running sketch -role_e role; - -// -// Payload -// - -const int min_payload_size = 1; -const int max_payload_size = 32; -const int payload_size_increments_by = 1; -int next_payload_size = min_payload_size; - -char receive_payload[max_payload_size+1]; // +1 to allow room for a terminating NULL char - -void setup(void) -{ - // - // Multicast - // - pinMode(multicast_pin, INPUT); - digitalWrite(multicast_pin,HIGH); - delay( 20 ) ; - - // read multicast role, LOW for unicast - if( digitalRead( multicast_pin ) ) - multicast = true ; - else - multicast = false ; - - - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay( 20 ); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_ping_out; - else - role = role_pong_back; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/pingpair_multi_dyn/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - printf("MULTICAST: %s\r\n",(multicast?"true (unreliable)":"false (reliable)")); - // - // Setup and configure rf radio - // - - radio.begin(); - - // enable dynamic payloads - radio.enableDynamicPayloads(); - radio.setCRCLength( RF24_CRC_16 ) ; - - // optionally, increase the delay between retries & # of retries - radio.setRetries( 15, 5 ) ; - radio.setAutoAck( true ) ; - //radio.setPALevel( RF24_PA_LOW ) ; - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens two pipes for these two nodes to communicate - // back and forth. - // Open 'our' pipe for writing - // Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading) - - if ( role == role_ping_out ) - { - radio.openWritingPipe(pipes[0]); - radio.openReadingPipe(1,pipes[1]); - } - else - { - radio.openWritingPipe(pipes[1]); - radio.openReadingPipe(1,pipes[0]); - } - - // - // Start listening - // - radio.powerUp() ; - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); -} - -void loop(void) -{ - // - // Ping out role. Repeatedly send the current time - // - - if (role == role_ping_out) - { - // The payload will always be the same, what will change is how much of it we send. - static char send_payload[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ789012"; - - // First, stop listening so we can talk. - radio.stopListening(); - - // Take the time, and send it. This will block until complete - printf("Now sending length %i...",next_payload_size); - radio.write( send_payload, next_payload_size, multicast ); - - // Now, continue listening - radio.startListening(); - - // Wait here until we get a response, or timeout - unsigned long started_waiting_at = millis(); - bool timeout = false; - while ( ! radio.available() && ! timeout ) - if (millis() - started_waiting_at > 1 + radio.getMaxTimeout()/1000 ) - timeout = true; - - // Describe the results - if ( timeout ) - { - printf("Failed, response timed out.\n\r"); - } - else - { - // Grab the response, compare, and send to debugging spew - uint8_t len = radio.getDynamicPayloadSize(); - radio.read( receive_payload, len ); - - // Put a zero at the end for easy printing - receive_payload[len] = 0; - - // Spew it - printf("Got response size=%i value=%s\n\r",len,receive_payload); - } - - // Update size for next time. - next_payload_size += payload_size_increments_by; - if ( next_payload_size > max_payload_size ) - next_payload_size = min_payload_size; - - // Try again 1s later - delay(250); - } - - // - // Pong back role. Receive each packet, dump it out, and send it back - // - - if ( role == role_pong_back ) - { - // if there is data ready - if ( radio.available() ) - { - // Dump the payloads until we've gotten everything - uint8_t len; - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - len = radio.getDynamicPayloadSize(); - done = radio.read( receive_payload, len ); - - // Put a zero at the end for easy printing - receive_payload[len] = 0; - - // Spew it - printf("Got payload size=%i value=%s\n\r",len,receive_payload); - } - - // First, stop listening so we can talk - radio.stopListening(); - - // Send the final one back. - radio.write( receive_payload, len, multicast ); - printf("Sent response.\n\r"); - - // Now, resume listening so we catch the next packets. - radio.startListening(); - } - } -} -// vim:cin:ai:sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/examples/pingpair_multi_dyn/printf.h b/libraries/RF24/examples/pingpair_multi_dyn/printf.h deleted file mode 100644 index 1b853db..0000000 --- a/libraries/RF24/examples/pingpair_multi_dyn/printf.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#endif // __PRINTF_H__ diff --git a/libraries/RF24/examples/pingpair_pl/Jamfile b/libraries/RF24/examples/pingpair_pl/Jamfile deleted file mode 100644 index 901f8da..0000000 --- a/libraries/RF24/examples/pingpair_pl/Jamfile +++ /dev/null @@ -1,206 +0,0 @@ -PROJECT_NAME = $(PWD:B) ; -PROJECT_DIR = . ; -PROJECT_LIBS = SPI RF24 ; - -OUT_DIR = ojam ; -F_CPU = 16000000 ; -MCU = atmega328p ; -PORTS = /dev/tty.usbserial-A600eHIs /dev/tty.usbserial-A40081RP /dev/tty.usbserial-A9007LmI ; - -UPLOAD_RATE = 57600 ; -AVRDUDE_PROTOCOL = stk500v1 ; -COM = 33 ; - -# Host-specific overrides for locations -if $(OS) = MACOSX -{ -ARDUINO_VERSION = 22 ; -OLD_DIR = /opt/arduino-0021 ; -AVR_TOOLS_PATH = $(OLD_DIR)/hardware/tools/avr/bin ; -AVRDUDECONFIG_PATH = $(OLD_DIR)/hardware/tools/avr/etc ; -ARDUINO_DIR = /opt/Arduino ; -ARDUINO_AVR = /usr/lib/avr/include ; -} - -# Where is everything? -ARDUINO_VERSION ?= 22 ; -AVR_TOOLS_PATH ?= /usr/bin ; -ARDUINO_DIR ?= /opt/arduino-00$(ARDUINO_VERSION) ; -ARDUINO_AVR ?= $(ARDUINO_DIR)/hardware/tools/avr/avr/include/avr ; -AVRDUDECONFIG_PATH ?= $(ARDUINO_DIR)/hardware/tools ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; -AVR_CC = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_CXX = $(AVR_TOOLS_PATH)/avr-g++ ; -AVR_LD = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_OBJCOPY = $(AVR_TOOLS_PATH)/avr-objcopy ; -AVRDUDE = $(AVR_TOOLS_PATH)/avrdude ; - -DEFINES = F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -CTUNING = -ffunction-sections -fdata-sections ; -CXXTUNING = -fno-exceptions -fno-strict-aliasing ; -CFLAGS = -Os -Wall -Wextra -mmcu=$(MCU) $(CTUNING) ; -CXXFLAGS = $(CFLAGS) $(CXXTUNING) ; -LDFLAGS = -Os -lm -Wl,--gc-sections -mmcu=atmega328p ; - -# Search everywhere for headers -HDRS = $(PROJECT_DIR) $(ARDUINO_AVR) $(ARDUINO_CORE) [ GLOB $(ARDUINO_LIB) $(SKETCH_LIB) : [^.]* ] ; - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp ] ; - -# In addition to explicitly-specified program modules, pick up anything from the current -# dir. -PROJECT_MODULES += [ GLOB $(PROJECT_DIR) : *.c *.cpp *.pde ] ; - -# Shortcut for the out files -OUT = $(OUT_DIR)/$(PROJECT_NAME) ; - -# AvrDude setup -AVRDUDE_FLAGS = -V -F -D -C $(AVRDUDECONFIG_PATH)/avrdude.conf -p $(MCU) -c $(AVRDUDE_PROTOCOL) -b $(UPLOAD_RATE) ; - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule AvrCc -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrCc -{ - $(AVR_CC) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CFLAGS) $(>) -} - -rule AvrC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrC++ -{ - $(AVR_CXX) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule Pde -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - -} - -actions Pde -{ - echo "#include " > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule AvrPde -{ - local _CPP = $(OUT_DIR)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - AvrC++ $(<) : $(_CPP) ; -} - -rule AvrObject -{ - switch $(>:S) - { - case .c : AvrCc $(<) : $(>) ; - case .cpp : AvrC++ $(<) : $(>) ; - case .pde : AvrPde $(<) : $(>) ; - } -} - -rule AvrObjects -{ - for _I in $(<) - { - AvrObject $(OUT_DIR)/$(_I:B).o : $(_I) ; - } -} - -rule AvrMainFromObjects -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - MkDir $(<:D) ; - Depends all : $(<) ; - Clean clean : $(<) ; -} - -actions AvrMainFromObjects -{ - $(AVR_LD) $(LDFLAGS) -o $(<) $(>) -} - -rule AvrMain -{ - AvrMainFromObjects $(<) : $(OUT_DIR)/$(>:B).o ; - AvrObjects $(>) ; -} - -rule AvrHex -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions AvrHex -{ - $(AVR_OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule AvrUpload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - AvrUploadAction $(2) : $(3) ; -} - -actions AvrUploadAction -{ - $(AVRDUDE) $(AVRDUDE_FLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -AvrMain $(OUT).elf : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -AvrHex $(OUT).hex : $(OUT).elf ; - -AvrUpload p6 : /dev/tty.usbserial-A600eHIs : $(OUT).hex ; -AvrUpload p4 : /dev/tty.usbserial-A40081RP : $(OUT).hex ; -AvrUpload p9 : /dev/tty.usbserial-A9007LmI : $(OUT).hex ; - diff --git a/libraries/RF24/examples/pingpair_pl/pingpair_pl.pde b/libraries/RF24/examples/pingpair_pl/pingpair_pl.pde deleted file mode 100644 index 8980293..0000000 --- a/libraries/RF24/examples/pingpair_pl/pingpair_pl.pde +++ /dev/null @@ -1,180 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * Example of using Ack Payloads - * - * This is an example of how to do two-way communication without changing - * transmit/receive modes. Here, a payload is set to the transmitter within - * the Ack packet of each transmission. Note that the payload is set BEFORE - * the sender's message arrives. - */ - -#include -#include "nRF24L01.h" -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 8 & 9 - -RF24 radio(8,9); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const short role_pin = 7; - -// -// Topology -// - -// Single radio pipe address for the 2 nodes to communicate. -const uint64_t pipe = 0xE8E8F0F0E1LL; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes in this -// system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_sender = 1, role_receiver } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Sender", "Receiver"}; - -// The role of the current running sketch -role_e role; - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_sender; - else - role = role_receiver; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/pingpair_pl/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // We will be using the Ack Payload feature, so please enable it - radio.enableAckPayload(); - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens a single pipes for these two nodes to communicate - // back and forth. One listens on it, the other talks to it. - - if ( role == role_sender ) - { - radio.openWritingPipe(pipe); - } - else - { - radio.openReadingPipe(1,pipe); - } - - // - // Start listening - // - - if ( role == role_receiver ) - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); -} - -void loop(void) -{ - static uint32_t message_count = 0; - - // - // Sender role. Repeatedly send the current time - // - - if (role == role_sender) - { - // Take the time, and send it. This will block until complete - unsigned long time = millis(); - printf("Now sending %lu...",time); - radio.write( &time, sizeof(unsigned long) ); - - if ( radio.isAckPayloadAvailable() ) - { - radio.read(&message_count,sizeof(message_count)); - printf("Ack: [%lu] ",message_count); - } - printf("OK\n\r"); - - // Try again soon - delay(2000); - } - - // - // Receiver role. Receive each packet, dump it out, add ack payload for next time - // - - if ( role == role_receiver ) - { - // if there is data ready - if ( radio.available() ) - { - // Dump the payloads until we've gotten everything - static unsigned long got_time; - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - done = radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got payload %lu\n",got_time); - } - - // Add an ack packet for the next time around. This is a simple - // packet counter - radio.writeAckPayload( 1, &message_count, sizeof(message_count) ); - ++message_count; - } - } -} -// vim:ai:cin:sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/examples/pingpair_pl/printf.h b/libraries/RF24/examples/pingpair_pl/printf.h deleted file mode 100644 index df6c46a..0000000 --- a/libraries/RF24/examples/pingpair_pl/printf.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -#include "WProgram.h" - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#endif // __PRINTF_H__ diff --git a/libraries/RF24/examples/pingpair_sleepy/Jamfile b/libraries/RF24/examples/pingpair_sleepy/Jamfile deleted file mode 100644 index 901f8da..0000000 --- a/libraries/RF24/examples/pingpair_sleepy/Jamfile +++ /dev/null @@ -1,206 +0,0 @@ -PROJECT_NAME = $(PWD:B) ; -PROJECT_DIR = . ; -PROJECT_LIBS = SPI RF24 ; - -OUT_DIR = ojam ; -F_CPU = 16000000 ; -MCU = atmega328p ; -PORTS = /dev/tty.usbserial-A600eHIs /dev/tty.usbserial-A40081RP /dev/tty.usbserial-A9007LmI ; - -UPLOAD_RATE = 57600 ; -AVRDUDE_PROTOCOL = stk500v1 ; -COM = 33 ; - -# Host-specific overrides for locations -if $(OS) = MACOSX -{ -ARDUINO_VERSION = 22 ; -OLD_DIR = /opt/arduino-0021 ; -AVR_TOOLS_PATH = $(OLD_DIR)/hardware/tools/avr/bin ; -AVRDUDECONFIG_PATH = $(OLD_DIR)/hardware/tools/avr/etc ; -ARDUINO_DIR = /opt/Arduino ; -ARDUINO_AVR = /usr/lib/avr/include ; -} - -# Where is everything? -ARDUINO_VERSION ?= 22 ; -AVR_TOOLS_PATH ?= /usr/bin ; -ARDUINO_DIR ?= /opt/arduino-00$(ARDUINO_VERSION) ; -ARDUINO_AVR ?= $(ARDUINO_DIR)/hardware/tools/avr/avr/include/avr ; -AVRDUDECONFIG_PATH ?= $(ARDUINO_DIR)/hardware/tools ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; -AVR_CC = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_CXX = $(AVR_TOOLS_PATH)/avr-g++ ; -AVR_LD = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_OBJCOPY = $(AVR_TOOLS_PATH)/avr-objcopy ; -AVRDUDE = $(AVR_TOOLS_PATH)/avrdude ; - -DEFINES = F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -CTUNING = -ffunction-sections -fdata-sections ; -CXXTUNING = -fno-exceptions -fno-strict-aliasing ; -CFLAGS = -Os -Wall -Wextra -mmcu=$(MCU) $(CTUNING) ; -CXXFLAGS = $(CFLAGS) $(CXXTUNING) ; -LDFLAGS = -Os -lm -Wl,--gc-sections -mmcu=atmega328p ; - -# Search everywhere for headers -HDRS = $(PROJECT_DIR) $(ARDUINO_AVR) $(ARDUINO_CORE) [ GLOB $(ARDUINO_LIB) $(SKETCH_LIB) : [^.]* ] ; - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp ] ; - -# In addition to explicitly-specified program modules, pick up anything from the current -# dir. -PROJECT_MODULES += [ GLOB $(PROJECT_DIR) : *.c *.cpp *.pde ] ; - -# Shortcut for the out files -OUT = $(OUT_DIR)/$(PROJECT_NAME) ; - -# AvrDude setup -AVRDUDE_FLAGS = -V -F -D -C $(AVRDUDECONFIG_PATH)/avrdude.conf -p $(MCU) -c $(AVRDUDE_PROTOCOL) -b $(UPLOAD_RATE) ; - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule AvrCc -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrCc -{ - $(AVR_CC) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CFLAGS) $(>) -} - -rule AvrC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrC++ -{ - $(AVR_CXX) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule Pde -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - -} - -actions Pde -{ - echo "#include " > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule AvrPde -{ - local _CPP = $(OUT_DIR)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - AvrC++ $(<) : $(_CPP) ; -} - -rule AvrObject -{ - switch $(>:S) - { - case .c : AvrCc $(<) : $(>) ; - case .cpp : AvrC++ $(<) : $(>) ; - case .pde : AvrPde $(<) : $(>) ; - } -} - -rule AvrObjects -{ - for _I in $(<) - { - AvrObject $(OUT_DIR)/$(_I:B).o : $(_I) ; - } -} - -rule AvrMainFromObjects -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - MkDir $(<:D) ; - Depends all : $(<) ; - Clean clean : $(<) ; -} - -actions AvrMainFromObjects -{ - $(AVR_LD) $(LDFLAGS) -o $(<) $(>) -} - -rule AvrMain -{ - AvrMainFromObjects $(<) : $(OUT_DIR)/$(>:B).o ; - AvrObjects $(>) ; -} - -rule AvrHex -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions AvrHex -{ - $(AVR_OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule AvrUpload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - AvrUploadAction $(2) : $(3) ; -} - -actions AvrUploadAction -{ - $(AVRDUDE) $(AVRDUDE_FLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -AvrMain $(OUT).elf : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -AvrHex $(OUT).hex : $(OUT).elf ; - -AvrUpload p6 : /dev/tty.usbserial-A600eHIs : $(OUT).hex ; -AvrUpload p4 : /dev/tty.usbserial-A40081RP : $(OUT).hex ; -AvrUpload p9 : /dev/tty.usbserial-A9007LmI : $(OUT).hex ; - diff --git a/libraries/RF24/examples/pingpair_sleepy/pingpair_sleepy.pde b/libraries/RF24/examples/pingpair_sleepy/pingpair_sleepy.pde deleted file mode 100644 index 0acf623..0000000 --- a/libraries/RF24/examples/pingpair_sleepy/pingpair_sleepy.pde +++ /dev/null @@ -1,288 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * Example RF Radio Ping Pair which Sleeps between Sends - * - * This is an example of how to use the RF24 class to create a battery- - * efficient system. It is just like the pingpair.pde example, but the - * ping node powers down the radio and sleeps the MCU after every - * ping/pong cycle. - * - * As with the pingpair.pde example, write this sketch to two different nodes, - * connect the role_pin to ground on one. The ping node sends the current - * time to the pong node, which responds by sending the value back. The ping - * node can then see how long the whole cycle took. - */ - -#include -#include -#include -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 8 & 9 - -RF24 radio(8,9); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const int role_pin = 7; - -// -// Topology -// - -// Radio pipe addresses for the 2 nodes to communicate. -const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL }; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes -// in this system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_ping_out = 1, role_pong_back } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"}; - -// The role of the current running sketch -role_e role; - -// -// Sleep declarations -// - -typedef enum { wdt_16ms = 0, wdt_32ms, wdt_64ms, wdt_128ms, wdt_250ms, wdt_500ms, wdt_1s, wdt_2s, wdt_4s, wdt_8s } wdt_prescalar_e; - -void setup_watchdog(uint8_t prescalar); -void do_sleep(void); - -const short sleep_cycles_per_transmission = 4; -volatile short sleep_cycles_remaining = sleep_cycles_per_transmission; - -// -// Normal operation -// - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_ping_out; - else - role = role_pong_back; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/pingpair_sleepy/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // Prepare sleep parameters - // - - // Only the ping out role sleeps. Wake up every 4s to send a ping - if ( role == role_ping_out ) - setup_watchdog(wdt_1s); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens two pipes for these two nodes to communicate - // back and forth. - // Open 'our' pipe for writing - // Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading) - - if ( role == role_ping_out ) - { - radio.openWritingPipe(pipes[0]); - radio.openReadingPipe(1,pipes[1]); - } - else - { - radio.openWritingPipe(pipes[1]); - radio.openReadingPipe(1,pipes[0]); - } - - // - // Start listening - // - - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); -} - -void loop(void) -{ - // - // Ping out role. Repeatedly send the current time - // - - if (role == role_ping_out) - { - // First, stop listening so we can talk. - radio.stopListening(); - - // Take the time, and send it. This will block until complete - unsigned long time = millis(); - printf("Now sending %lu...",time); - radio.write( &time, sizeof(unsigned long) ); - - // Now, continue listening - radio.startListening(); - - // Wait here until we get a response, or timeout (250ms) - unsigned long started_waiting_at = millis(); - bool timeout = false; - while ( ! radio.available() && ! timeout ) - if (millis() - started_waiting_at > 250 ) - timeout = true; - - // Describe the results - if ( timeout ) - { - printf("Failed, response timed out.\n\r"); - } - else - { - // Grab the response, compare, and send to debugging spew - unsigned long got_time; - radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got response %lu, round-trip delay: %lu\n\r",got_time,millis()-got_time); - } - - // - // Shut down the system - // - - // Experiment with some delay here to see if it has an effect - delay(500); - - // Power down the radio. Note that the radio will get powered back up - // on the next write() call. - radio.powerDown(); - - // Sleep the MCU. The watchdog timer will awaken in a short while, and - // continue execution here. - while( sleep_cycles_remaining ) - do_sleep(); - - sleep_cycles_remaining = sleep_cycles_per_transmission; - } - - // - // Pong back role. Receive each packet, dump it out, and send it back - // - // This is untouched from the pingpair example. - // - - if ( role == role_pong_back ) - { - // if there is data ready - if ( radio.available() ) - { - // Dump the payloads until we've gotten everything - unsigned long got_time; - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - done = radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it. Include our time, because the ping_out millis counter is unreliable - // due to it sleeping - printf("Got payload %lu @ %lu...",got_time,millis()); - } - - // First, stop listening so we can talk - radio.stopListening(); - - // Send the final one back. - radio.write( &got_time, sizeof(unsigned long) ); - printf("Sent response.\n\r"); - - // Now, resume listening so we catch the next packets. - radio.startListening(); - } - } -} - -// -// Sleep helpers -// - -// 0=16ms, 1=32ms,2=64ms,3=125ms,4=250ms,5=500ms -// 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec - -void setup_watchdog(uint8_t prescalar) -{ - prescalar = min(9,prescalar); - uint8_t wdtcsr = prescalar & 7; - if ( prescalar & 8 ) - wdtcsr |= _BV(WDP3); - - MCUSR &= ~_BV(WDRF); - WDTCSR = _BV(WDCE) | _BV(WDE); - WDTCSR = _BV(WDCE) | wdtcsr | _BV(WDIE); -} - -ISR(WDT_vect) -{ - --sleep_cycles_remaining; -} - -void do_sleep(void) -{ - set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here - sleep_enable(); - - sleep_mode(); // System sleeps here - - sleep_disable(); // System continues execution here when watchdog timed out - radio.powerUp() ; -} - -// vim:ai:cin:sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/examples/pingpair_sleepy/printf.h b/libraries/RF24/examples/pingpair_sleepy/printf.h deleted file mode 100644 index 1b853db..0000000 --- a/libraries/RF24/examples/pingpair_sleepy/printf.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#endif // __PRINTF_H__ diff --git a/libraries/RF24/examples/scanner/Jamfile b/libraries/RF24/examples/scanner/Jamfile deleted file mode 100644 index 901f8da..0000000 --- a/libraries/RF24/examples/scanner/Jamfile +++ /dev/null @@ -1,206 +0,0 @@ -PROJECT_NAME = $(PWD:B) ; -PROJECT_DIR = . ; -PROJECT_LIBS = SPI RF24 ; - -OUT_DIR = ojam ; -F_CPU = 16000000 ; -MCU = atmega328p ; -PORTS = /dev/tty.usbserial-A600eHIs /dev/tty.usbserial-A40081RP /dev/tty.usbserial-A9007LmI ; - -UPLOAD_RATE = 57600 ; -AVRDUDE_PROTOCOL = stk500v1 ; -COM = 33 ; - -# Host-specific overrides for locations -if $(OS) = MACOSX -{ -ARDUINO_VERSION = 22 ; -OLD_DIR = /opt/arduino-0021 ; -AVR_TOOLS_PATH = $(OLD_DIR)/hardware/tools/avr/bin ; -AVRDUDECONFIG_PATH = $(OLD_DIR)/hardware/tools/avr/etc ; -ARDUINO_DIR = /opt/Arduino ; -ARDUINO_AVR = /usr/lib/avr/include ; -} - -# Where is everything? -ARDUINO_VERSION ?= 22 ; -AVR_TOOLS_PATH ?= /usr/bin ; -ARDUINO_DIR ?= /opt/arduino-00$(ARDUINO_VERSION) ; -ARDUINO_AVR ?= $(ARDUINO_DIR)/hardware/tools/avr/avr/include/avr ; -AVRDUDECONFIG_PATH ?= $(ARDUINO_DIR)/hardware/tools ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; -AVR_CC = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_CXX = $(AVR_TOOLS_PATH)/avr-g++ ; -AVR_LD = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_OBJCOPY = $(AVR_TOOLS_PATH)/avr-objcopy ; -AVRDUDE = $(AVR_TOOLS_PATH)/avrdude ; - -DEFINES = F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -CTUNING = -ffunction-sections -fdata-sections ; -CXXTUNING = -fno-exceptions -fno-strict-aliasing ; -CFLAGS = -Os -Wall -Wextra -mmcu=$(MCU) $(CTUNING) ; -CXXFLAGS = $(CFLAGS) $(CXXTUNING) ; -LDFLAGS = -Os -lm -Wl,--gc-sections -mmcu=atmega328p ; - -# Search everywhere for headers -HDRS = $(PROJECT_DIR) $(ARDUINO_AVR) $(ARDUINO_CORE) [ GLOB $(ARDUINO_LIB) $(SKETCH_LIB) : [^.]* ] ; - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp ] ; - -# In addition to explicitly-specified program modules, pick up anything from the current -# dir. -PROJECT_MODULES += [ GLOB $(PROJECT_DIR) : *.c *.cpp *.pde ] ; - -# Shortcut for the out files -OUT = $(OUT_DIR)/$(PROJECT_NAME) ; - -# AvrDude setup -AVRDUDE_FLAGS = -V -F -D -C $(AVRDUDECONFIG_PATH)/avrdude.conf -p $(MCU) -c $(AVRDUDE_PROTOCOL) -b $(UPLOAD_RATE) ; - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule AvrCc -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrCc -{ - $(AVR_CC) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CFLAGS) $(>) -} - -rule AvrC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrC++ -{ - $(AVR_CXX) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule Pde -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - -} - -actions Pde -{ - echo "#include " > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule AvrPde -{ - local _CPP = $(OUT_DIR)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - AvrC++ $(<) : $(_CPP) ; -} - -rule AvrObject -{ - switch $(>:S) - { - case .c : AvrCc $(<) : $(>) ; - case .cpp : AvrC++ $(<) : $(>) ; - case .pde : AvrPde $(<) : $(>) ; - } -} - -rule AvrObjects -{ - for _I in $(<) - { - AvrObject $(OUT_DIR)/$(_I:B).o : $(_I) ; - } -} - -rule AvrMainFromObjects -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - MkDir $(<:D) ; - Depends all : $(<) ; - Clean clean : $(<) ; -} - -actions AvrMainFromObjects -{ - $(AVR_LD) $(LDFLAGS) -o $(<) $(>) -} - -rule AvrMain -{ - AvrMainFromObjects $(<) : $(OUT_DIR)/$(>:B).o ; - AvrObjects $(>) ; -} - -rule AvrHex -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions AvrHex -{ - $(AVR_OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule AvrUpload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - AvrUploadAction $(2) : $(3) ; -} - -actions AvrUploadAction -{ - $(AVRDUDE) $(AVRDUDE_FLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -AvrMain $(OUT).elf : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -AvrHex $(OUT).hex : $(OUT).elf ; - -AvrUpload p6 : /dev/tty.usbserial-A600eHIs : $(OUT).hex ; -AvrUpload p4 : /dev/tty.usbserial-A40081RP : $(OUT).hex ; -AvrUpload p9 : /dev/tty.usbserial-A9007LmI : $(OUT).hex ; - diff --git a/libraries/RF24/examples/scanner/printf.h b/libraries/RF24/examples/scanner/printf.h deleted file mode 100644 index 1b853db..0000000 --- a/libraries/RF24/examples/scanner/printf.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#endif // __PRINTF_H__ diff --git a/libraries/RF24/examples/scanner/scanner.pde b/libraries/RF24/examples/scanner/scanner.pde deleted file mode 100644 index 8f93174..0000000 --- a/libraries/RF24/examples/scanner/scanner.pde +++ /dev/null @@ -1,138 +0,0 @@ - -/* - Copyright (C) 2011 James Coliz, Jr. - Copyright (c) 2012 Greg Copeland - - 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. - */ - -/** - * Channel scanner - * - * Example to detect interference on the various channels available. - * This is a good diagnostic tool to check whether you're picking a - * good channel for your application. - * - * Inspired by cpixip. - * See http://arduino.cc/forum/index.php/topic,54795.0.html - */ - -#include -#include "RF24.h" -#include "printf.h" - -// Only display active frequencies -static const bool activeOnly = true ; - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 8 & 9 - -RF24 radio(9,10); - -// -// Channel info -// - -const short num_channels = 128; -short values[num_channels]; -uint8_t signalMeter[55] ; - -// -// Setup -// - -void setup(void) -{ - // - // Print preamble - // - - Serial.begin(115200); - printf_begin(); - printf("\n\rRF24/examples/scanner/\n\r"); - - // - // Setup and configure rf radio - // - - radio.begin(); - radio.powerUp() ; - radio.setAutoAck(false); - - // Get into standby mode - radio.openReadingPipe( 0, 0xFFFFFFFFFFULL ) ; - // radio.setDataRate( RF24_250KBPS ) ; // may fallback to 1Mbps - radio.setDataRate( RF24_1MBPS ) ; // may fallback to 1Mbps - radio.startListening() ; - radio.stopListening() ; -} - -// -// Loop -// -void loop(void) -{ - // Clear measurement values - memset( values, 0x00, num_channels ) ; - printf( "Scanning all available frequencies..." ) ; - - // Repeatedly scan multiple channels - for( int channel=0 ; channel < num_channels; channel++ ) { - radio.setChannel( channel ) ; - - // Amplify the signal based on carrier bandwidth - int ampFactor ; - for( int amp=0; amp <= 300; amp++ ) { - // Alternate data rates - ampFactor = amp%3 ; - switch( ampFactor ) { - case 0: - radio.setDataRate( RF24_250KBPS ) ; - break ; - - case 1: - radio.setDataRate( RF24_1MBPS ) ; - break ; - - default: - radio.setDataRate( RF24_2MBPS ) ; - break ; - } - - // Listen for carrier - ampFactor++ ; - radio.startListening() ; - delayMicroseconds( 6 - ampFactor ) ; - radio.stopListening() ; - - // Was carrier detected? If so, signal level based on bandwidth - if( radio.testRPD() ) { - values[channel] += ampFactor ; - } - } - } - - // Now display our results - printf( "Scan completed.\r\n" ) ; - for( int channel=0 ; channel < num_channels; channel++ ) { - if( !activeOnly || (activeOnly && values[channel] > 0) ) { - memset( signalMeter, '*', min( values[channel], 54 ) ) ; - signalMeter[min(values[channel], 54)] = 0x00 ; - printf( "%03d (%4dMhz): %02d - %s\r\n", - channel, - 2400+channel, - values[channel], - signalMeter ) ; - - // Reset the scanned value since its already beend displayed - values[channel] = 0 ; - } - } -} - -// vim:ai:cin:sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/examples/starping/Jamfile b/libraries/RF24/examples/starping/Jamfile deleted file mode 100644 index de9b1f6..0000000 --- a/libraries/RF24/examples/starping/Jamfile +++ /dev/null @@ -1,206 +0,0 @@ -PROJECT_NAME = $(PWD:B) ; -PROJECT_DIR = . ; -PROJECT_LIBS = EEPROM SPI RF24 ; - -OUT_DIR = ojam ; -F_CPU = 16000000 ; -MCU = atmega328p ; -PORTS = /dev/tty.usbserial-A600eHIs /dev/tty.usbserial-A40081RP /dev/tty.usbserial-A9007LmI ; - -UPLOAD_RATE = 57600 ; -AVRDUDE_PROTOCOL = stk500v1 ; -COM = 33 ; - -# Host-specific overrides for locations -if $(OS) = MACOSX -{ -ARDUINO_VERSION = 22 ; -OLD_DIR = /opt/arduino-0021 ; -AVR_TOOLS_PATH = $(OLD_DIR)/hardware/tools/avr/bin ; -AVRDUDECONFIG_PATH = $(OLD_DIR)/hardware/tools/avr/etc ; -ARDUINO_DIR = /opt/Arduino ; -ARDUINO_AVR = /usr/lib/avr/include ; -} - -# Where is everything? -ARDUINO_VERSION ?= 22 ; -AVR_TOOLS_PATH ?= /usr/bin ; -ARDUINO_DIR ?= /opt/arduino-00$(ARDUINO_VERSION) ; -ARDUINO_AVR ?= $(ARDUINO_DIR)/hardware/tools/avr/avr/include/avr ; -AVRDUDECONFIG_PATH ?= $(ARDUINO_DIR)/hardware/tools ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; -AVR_CC = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_CXX = $(AVR_TOOLS_PATH)/avr-g++ ; -AVR_LD = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_OBJCOPY = $(AVR_TOOLS_PATH)/avr-objcopy ; -AVRDUDE = $(AVR_TOOLS_PATH)/avrdude ; - -DEFINES = F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -CTUNING = -ffunction-sections -fdata-sections ; -CXXTUNING = -fno-exceptions -fno-strict-aliasing ; -CFLAGS = -Os -Wall -Wextra -mmcu=$(MCU) $(CTUNING) ; -CXXFLAGS = $(CFLAGS) $(CXXTUNING) ; -LDFLAGS = -Os -lm -Wl,--gc-sections -mmcu=atmega328p ; - -# Search everywhere for headers -HDRS = $(PROJECT_DIR) $(ARDUINO_AVR) $(ARDUINO_CORE) [ GLOB $(ARDUINO_LIB) $(SKETCH_LIB) : [^.]* ] ; - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp ] ; - -# In addition to explicitly-specified program modules, pick up anything from the current -# dir. -PROJECT_MODULES += [ GLOB $(PROJECT_DIR) : *.c *.cpp *.pde ] ; - -# Shortcut for the out files -OUT = $(OUT_DIR)/$(PROJECT_NAME) ; - -# AvrDude setup -AVRDUDE_FLAGS = -V -F -D -C $(AVRDUDECONFIG_PATH)/avrdude.conf -p $(MCU) -c $(AVRDUDE_PROTOCOL) -b $(UPLOAD_RATE) ; - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule AvrCc -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrCc -{ - $(AVR_CC) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CFLAGS) $(>) -} - -rule AvrC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrC++ -{ - $(AVR_CXX) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule Pde -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - -} - -actions Pde -{ - echo "#include " > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule AvrPde -{ - local _CPP = $(OUT_DIR)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - AvrC++ $(<) : $(_CPP) ; -} - -rule AvrObject -{ - switch $(>:S) - { - case .c : AvrCc $(<) : $(>) ; - case .cpp : AvrC++ $(<) : $(>) ; - case .pde : AvrPde $(<) : $(>) ; - } -} - -rule AvrObjects -{ - for _I in $(<) - { - AvrObject $(OUT_DIR)/$(_I:B).o : $(_I) ; - } -} - -rule AvrMainFromObjects -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - MkDir $(<:D) ; - Depends all : $(<) ; - Clean clean : $(<) ; -} - -actions AvrMainFromObjects -{ - $(AVR_LD) $(LDFLAGS) -o $(<) $(>) -} - -rule AvrMain -{ - AvrMainFromObjects $(<) : $(OUT_DIR)/$(>:B).o ; - AvrObjects $(>) ; -} - -rule AvrHex -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions AvrHex -{ - $(AVR_OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule AvrUpload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - AvrUploadAction $(2) : $(3) ; -} - -actions AvrUploadAction -{ - $(AVRDUDE) $(AVRDUDE_FLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -AvrMain $(OUT).elf : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -AvrHex $(OUT).hex : $(OUT).elf ; - -AvrUpload p6 : /dev/tty.usbserial-A600eHIs : $(OUT).hex ; -AvrUpload p4 : /dev/tty.usbserial-A40081RP : $(OUT).hex ; -AvrUpload p9 : /dev/tty.usbserial-A9007LmI : $(OUT).hex ; - diff --git a/libraries/RF24/examples/starping/printf.h b/libraries/RF24/examples/starping/printf.h deleted file mode 100644 index 1b853db..0000000 --- a/libraries/RF24/examples/starping/printf.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#endif // __PRINTF_H__ diff --git a/libraries/RF24/examples/starping/starping.pde b/libraries/RF24/examples/starping/starping.pde deleted file mode 100644 index ac5197a..0000000 --- a/libraries/RF24/examples/starping/starping.pde +++ /dev/null @@ -1,293 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * Example RF Radio Ping Star Group - * - * This sketch is a more complex example of using the RF24 library for Arduino. - * Deploy this on up to six nodes. Set one as the 'pong receiver' by tying the - * role_pin low, and the others will be 'ping transmit' units. The ping units - * unit will send out the value of millis() once a second. The pong unit will - * respond back with a copy of the value. Each ping unit can get that response - * back, and determine how long the whole cycle took. - * - * This example requires a bit more complexity to determine which unit is which. - * The pong receiver is identified by having its role_pin tied to ground. - * The ping senders are further differentiated by a byte in eeprom. - */ - -#include -#include -#include "nRF24L01.h" -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 8 & 9 - -RF24 radio(8,9); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'pong' receiver. -const int role_pin = 7; - -// -// Topology -// - -// Radio pipe addresses for the nodes to communicate. Only ping nodes need -// dedicated pipes in this topology. Each ping node has a talking pipe -// that it will ping into, and a listening pipe that it will listen for -// the pong. The pong node listens on all the ping node talking pipes -// and sends the pong back on the sending node's specific listening pipe. - -const uint64_t talking_pipes[5] = { 0xF0F0F0F0D2LL, 0xF0F0F0F0C3LL, 0xF0F0F0F0B4LL, 0xF0F0F0F0A5LL, 0xF0F0F0F096LL }; -const uint64_t listening_pipes[5] = { 0x3A3A3A3AD2LL, 0x3A3A3A3AC3LL, 0x3A3A3A3AB4LL, 0x3A3A3A3AA5LL, 0x3A3A3A3A96LL }; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes -// in this system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_invalid = 0, role_ping_out, role_pong_back } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"}; - -// The role of the current running sketch -role_e role; - -// -// Address management -// - -// Where in EEPROM is the address stored? -const uint8_t address_at_eeprom_location = 0; - -// What is our address (SRAM cache of the address from EEPROM) -// Note that zero is an INVALID address. The pong back unit takes address -// 1, and the rest are 2-6 -uint8_t node_address; - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_ping_out; - else - role = role_pong_back; - - // - // Address - // - - if ( role == role_pong_back ) - node_address = 1; - else - { - // Read the address from EEPROM - uint8_t reading = EEPROM.read(address_at_eeprom_location); - - // If it is in a valid range for node addresses, it is our - // address. - if ( reading >= 2 && reading <= 6 ) - node_address = reading; - - // Otherwise, it is invalid, so set our address AND ROLE to 'invalid' - else - { - node_address = 0; - role = role_invalid; - } - } - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/starping/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - printf("ADDRESS: %i\n\r",node_address); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // - // Open pipes to other nodes for communication - // - - // The pong node listens on all the ping node talking pipes - // and sends the pong back on the sending node's specific listening pipe. - if ( role == role_pong_back ) - { - radio.openReadingPipe(1,talking_pipes[0]); - radio.openReadingPipe(2,talking_pipes[1]); - radio.openReadingPipe(3,talking_pipes[2]); - radio.openReadingPipe(4,talking_pipes[3]); - radio.openReadingPipe(5,talking_pipes[4]); - } - - // Each ping node has a talking pipe that it will ping into, and a listening - // pipe that it will listen for the pong. - if ( role == role_ping_out ) - { - // Write on our talking pipe - radio.openWritingPipe(talking_pipes[node_address-2]); - // Listen on our listening pipe - radio.openReadingPipe(1,listening_pipes[node_address-2]); - } - - // - // Start listening - // - - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); - - // - // Prompt the user to assign a node address if we don't have one - // - - if ( role == role_invalid ) - { - printf("\n\r*** NO NODE ADDRESS ASSIGNED *** Send 1 through 6 to assign an address\n\r"); - } -} - -void loop(void) -{ - // - // Ping out role. Repeatedly send the current time - // - - if (role == role_ping_out) - { - // First, stop listening so we can talk. - radio.stopListening(); - - // Take the time, and send it. This will block until complete - unsigned long time = millis(); - printf("Now sending %lu...",time); - radio.write( &time, sizeof(unsigned long) ); - - // Now, continue listening - radio.startListening(); - - // Wait here until we get a response, or timeout (250ms) - unsigned long started_waiting_at = millis(); - bool timeout = false; - while ( ! radio.available() && ! timeout ) - if (millis() - started_waiting_at > 250 ) - timeout = true; - - // Describe the results - if ( timeout ) - { - printf("Failed, response timed out.\n\r"); - } - else - { - // Grab the response, compare, and send to debugging spew - unsigned long got_time; - radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got response %lu, round-trip delay: %lu\n\r",got_time,millis()-got_time); - } - - // Try again 1s later - delay(1000); - } - - // - // Pong back role. Receive each packet, dump it out, and send it back - // - - if ( role == role_pong_back ) - { - // if there is data ready - uint8_t pipe_num; - if ( radio.available(&pipe_num) ) - { - // Dump the payloads until we've gotten everything - unsigned long got_time; - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - done = radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got payload %lu from node %i...",got_time,pipe_num+1); - } - - // First, stop listening so we can talk - radio.stopListening(); - - // Open the correct pipe for writing - radio.openWritingPipe(listening_pipes[pipe_num-1]); - - // Retain the low 2 bytes to identify the pipe for the spew - uint16_t pipe_id = listening_pipes[pipe_num-1] & 0xffff; - - // Send the final one back. - radio.write( &got_time, sizeof(unsigned long) ); - printf("Sent response to %04x.\n\r",pipe_id); - - // Now, resume listening so we catch the next packets. - radio.startListening(); - } - } - - // - // Listen for serial input, which is how we set the address - // - if (Serial.available()) - { - // If the character on serial input is in a valid range... - char c = Serial.read(); - if ( c >= '1' && c <= '6' ) - { - // It is our address - EEPROM.write(address_at_eeprom_location,c-'0'); - - // And we are done right now (no easy way to soft reset) - printf("\n\rManually reset address to: %c\n\rPress RESET to continue!",c); - while(1) ; - } - } -} -// vim:ai:ci sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/keywords.txt b/libraries/RF24/keywords.txt deleted file mode 100644 index 79987eb..0000000 --- a/libraries/RF24/keywords.txt +++ /dev/null @@ -1,26 +0,0 @@ - RF24 KEYWORD1 - begin KEYWORD2 - setDataRate KEYWORD2 - getDataRate KEYWORD2 - powerUp KEYWORD2 - powerDown KEYWORD2 - whatHappened KEYWORD2 - writeAckPayload KEYWORD2 - setChannel KEYWORD2 - setPayloadSize KEYWORD2 - getPayloadSize KEYWORD2 - printDetails KEYWORD2 - startListening KEYWORD2 - stopListening KEYWORD2 - write KEYWORD2 - startWrite KEYWORD2 - available KEYWORD2 - read KEYWORD2 - openWritingPipe KEYWORD2 - openReadingPipe KEYWORD2 - closeReadingPipe KEYWORD2 - enableDynamicPayloads KEYWORD2 - enableAckPayload KEYWORD2 - setAutoAck KEYWORD2 - setCRCLength KEYWORD2 - getCRCLength KEYWORD2 diff --git a/libraries/RF24/nRF24L01.h b/libraries/RF24/nRF24L01.h deleted file mode 100644 index 9943c3a..0000000 --- a/libraries/RF24/nRF24L01.h +++ /dev/null @@ -1,127 +0,0 @@ -/* - Copyright (c) 2007 Stefan Engelke - Portions Copyright (C) 2011 Greg Copeland - - 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. -*/ - -/* Memory Map */ -#define CONFIG 0x00 -#define EN_AA 0x01 -#define EN_RXADDR 0x02 -#define SETUP_AW 0x03 -#define SETUP_RETR 0x04 -#define RF_CH 0x05 -#define RF_SETUP 0x06 -#define STATUS 0x07 -#define OBSERVE_TX 0x08 -#define CD 0x09 -#define RX_ADDR_P0 0x0A -#define RX_ADDR_P1 0x0B -#define RX_ADDR_P2 0x0C -#define RX_ADDR_P3 0x0D -#define RX_ADDR_P4 0x0E -#define RX_ADDR_P5 0x0F -#define TX_ADDR 0x10 -#define RX_PW_P0 0x11 -#define RX_PW_P1 0x12 -#define RX_PW_P2 0x13 -#define RX_PW_P3 0x14 -#define RX_PW_P4 0x15 -#define RX_PW_P5 0x16 -#define FIFO_STATUS 0x17 -#define DYNPD 0x1C -#define FEATURE 0x1D - -/* Bit Mnemonics */ -#define MASK_RX_DR 6 -#define MASK_TX_DS 5 -#define MASK_MAX_RT 4 -#define EN_CRC 3 -#define CRCO 2 -#define PWR_UP 1 -#define PRIM_RX 0 -#define ENAA_P5 5 -#define ENAA_P4 4 -#define ENAA_P3 3 -#define ENAA_P2 2 -#define ENAA_P1 1 -#define ENAA_P0 0 -#define ERX_P5 5 -#define ERX_P4 4 -#define ERX_P3 3 -#define ERX_P2 2 -#define ERX_P1 1 -#define ERX_P0 0 -#define AW 0 -#define ARD 4 -#define ARC 0 -#define PLL_LOCK 4 -#define RF_DR 3 -#define RF_PWR 6 -#define RX_DR 6 -#define TX_DS 5 -#define MAX_RT 4 -#define RX_P_NO 1 -#define TX_FULL 0 -#define PLOS_CNT 4 -#define ARC_CNT 0 -#define TX_REUSE 6 -#define FIFO_FULL 5 -#define TX_EMPTY 4 -#define RX_FULL 1 -#define RX_EMPTY 0 -#define DPL_P5 5 -#define DPL_P4 4 -#define DPL_P3 3 -#define DPL_P2 2 -#define DPL_P1 1 -#define DPL_P0 0 -#define EN_DPL 2 -#define EN_ACK_PAY 1 -#define EN_DYN_ACK 0 - -/* Instruction Mnemonics */ -#define R_REGISTER 0x00 -#define W_REGISTER 0x20 -#define REGISTER_MASK 0x1F -#define ACTIVATE 0x50 -#define R_RX_PL_WID 0x60 -#define R_RX_PAYLOAD 0x61 -#define W_TX_PAYLOAD 0xA0 -#define W_ACK_PAYLOAD 0xA8 -#define FLUSH_TX 0xE1 -#define FLUSH_RX 0xE2 -#define REUSE_TX_PL 0xE3 -#define NOP 0xFF - -/* Non-P omissions */ -#define LNA_HCURR 0 - -/* P model memory Map */ -#define RPD 0x09 -#define W_TX_PAYLOAD_NO_ACK 0xB0 - -/* P model bit Mnemonics */ -#define RF_DR_LOW 5 -#define RF_DR_HIGH 3 -#define RF_PWR_LOW 1 -#define RF_PWR_HIGH 2 diff --git a/libraries/RF24/tests/README b/libraries/RF24/tests/README deleted file mode 100644 index 43ceaf5..0000000 --- a/libraries/RF24/tests/README +++ /dev/null @@ -1,7 +0,0 @@ -The sketches in this directory are intended to be checkin tests. -No code should be pushed to github without these tests passing. - -See "runtests.sh" script inside each sketch dir. This script is fully compatible with -git bisest. - -Note that this requires python and py-serial diff --git a/libraries/RF24/tests/native/Jamfile b/libraries/RF24/tests/native/Jamfile deleted file mode 100644 index 10d0336..0000000 --- a/libraries/RF24/tests/native/Jamfile +++ /dev/null @@ -1,300 +0,0 @@ -PROJECT_NAME = $(PWD:B) ; -PROJECT_DIR = . ; -PROJECT_LIBS = RF24 ; - -OUT_DIR = ojam ; -F_CPU = 16000000 ; -MCU = atmega328p ; -PORTS = /dev/tty.usbserial-A600eHIs /dev/tty.usbserial-A40081RP /dev/tty.usbserial-A9007LmI ; - -UPLOAD_RATE = 57600 ; -AVRDUDE_PROTOCOL = stk500v1 ; -COM = 33 ; - -# Host-specific overrides for locations -if $(OS) = MACOSX -{ -ARDUINO_VERSION = 22 ; -OLD_DIR = /opt/arduino-0021 ; -AVR_TOOLS_PATH = $(OLD_DIR)/hardware/tools/avr/bin ; -AVRDUDECONFIG_PATH = $(OLD_DIR)/hardware/tools/avr/etc ; -ARDUINO_DIR = /opt/Arduino ; -ARDUINO_AVR = /usr/lib/avr/include ; -} - -# Where is everything? -ARDUINO_VERSION ?= 22 ; -SKETCH_DIR = $(HOME)/Source/Arduino ; -AVR_TOOLS_PATH ?= /usr/bin ; -ARDUINO_DIR ?= /opt/arduino-00$(ARDUINO_VERSION) ; -ARDUINO_AVR ?= $(ARDUINO_DIR)/hardware/tools/avr/avr/include/avr ; -AVRDUDECONFIG_PATH ?= $(ARDUINO_DIR)/hardware/tools ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(SKETCH_DIR)/libraries ; -AVR_AS = $(AVR_TOOLS_PATH)/avr-as ; -AVR_CC = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_CXX = $(AVR_TOOLS_PATH)/avr-g++ ; -AVR_LD = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_OBJCOPY = $(AVR_TOOLS_PATH)/avr-objcopy ; -AVRDUDE = $(AVR_TOOLS_PATH)/avrdude ; - -DEFINES = F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H HAL=1 ; -CTUNING = -ffunction-sections -fdata-sections ; -CXXTUNING = -fno-exceptions -fno-strict-aliasing ; -ASFLAGS = -mmcu=$(MCU) ; -CFLAGS = -Os -Wall -Wextra $(ASFLAGS) $(CTUNING) ; -CXXFLAGS = $(CFLAGS) $(CXXTUNING) ; -LDFLAGS = -Os -lm -Wl,--gc-sections -mmcu=atmega328p ; - -# Search everywhere for headers -HDRS = $(PROJECT_DIR) $(ARDUINO_AVR) $(ARDUINO_CORE) [ GLOB $(ARDUINO_LIB) $(SKETCH_LIB) : [^.]* ] ; -HDRS += [ GLOB $(HDRS) : utility ] ; - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(ARDUINO_LIB)/$(PROJECT_LIBS)/utility $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp *.c ] ; - -# In addition to explicitly-specified program modules, pick up anything from the current -# dir. -PROJECT_MODULES += [ GLOB $(PROJECT_DIR) : *.c *.cpp *.pde ] ; - -# Shortcut for the out files -OUT = $(OUT_DIR)/$(PROJECT_NAME) ; - -# AvrDude setup -AVRDUDE_FLAGS = -V -F -D -C $(AVRDUDECONFIG_PATH)/avrdude.conf -p $(MCU) -c $(AVRDUDE_PROTOCOL) -b $(UPLOAD_RATE) ; - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -# GitVersion version.h ; - -rule AvrAsm -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrAsm -{ - $(AVR_AS) $(ASFLAGS) -o $(<) $(>) -} - -rule AvrCc -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrCc -{ - $(AVR_CC) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CFLAGS) $(>) -} - -rule AvrC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrC++ -{ - $(AVR_CXX) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule AvrAsmFromC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrAsmFromC++ -{ - $(AVR_CXX) -S -fverbose-asm -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule Pde -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; -} - -actions Pde -{ - echo "#include " > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule AvrPde -{ - local _CPP = $(OUT_DIR)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - AvrC++ $(<) : $(_CPP) ; -} - -rule AvrObject -{ - switch $(>:S) - { - case .S : AvrAsm $(<) : $(>) ; - case .c : AvrCc $(<) : $(>) ; - case .cpp : AvrC++ $(<) : $(>) ; - case .pde : AvrPde $(<) : $(>) ; - } -} - -rule AvrObjects -{ - for _I in $(<) - { - AvrObject $(OUT_DIR)/$(_I:B).o : $(_I) ; - } -} - -rule AvrMainFromObjects -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - MkDir $(<:D) ; - Depends all : $(<) ; - Clean clean : $(<) ; -} - -actions AvrMainFromObjects -{ - $(AVR_LD) $(LDFLAGS) -o $(<) $(>) -} - -rule AvrMain -{ - AvrMainFromObjects $(<) : $(OUT_DIR)/$(>:B).o ; - AvrObjects $(>) ; -} - -rule AvrHex -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions AvrHex -{ - $(AVR_OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule AvrUpload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - AvrUploadAction $(2) : $(3) ; -} - -actions AvrUploadAction -{ - $(AVRDUDE) $(AVRDUDE_FLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -AvrMain $(OUT).elf : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) -AvrHex $(OUT).hex : $(OUT).elf ; - -AvrUpload p6 : /dev/tty.usbserial-A600eHIs : $(OUT).hex ; -AvrUpload p4 : /dev/tty.usbserial-A40081RP : $(OUT).hex ; -AvrUpload p9 : /dev/tty.usbserial-A9007LmI : $(OUT).hex ; - -# -# Native -# - -OUT_DIR_NATIVE = out_native ; -OUT_NATIVE = $(OUT_DIR_NATIVE)/$(PROJECT_NAME) ; -NATIVE_CORE = $(SKETCH_DIR)/hardware/native ; -HDRS = $(NATIVE_CORE) $(HDRS) ; -NATIVE_CORE_MODULES = [ GLOB $(NATIVE_CORE) : *.c *.cpp ] ; -NATIVE_MODULES = ; -DEFINES += NATIVE ; - -rule NativePde -{ - local _CPP = $(OUT_DIR_NATIVE)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - C++ $(<) : $(_CPP) ; -} - -rule UserObject -{ - switch $(>) - { - case *.pde : NativePde $(<) : $(>) ; - } -} - -rule Objects -{ - for _I in $(<) - { - local _O = $(OUT_DIR_NATIVE)/$(_I:B).o ; - Object $(_O) : $(_I) ; - } -} - -rule Main -{ - MainFromObjects $(<) : $(OUT_DIR_NATIVE)/$(>:B).o ; - Objects $(>) ; -} - -actions C++ -{ - c++ -c -o $(<) $(CCHDRS) $(CCDEFS) $(>) -} - -actions Link -{ - c++ -o $(<) $(>) -} - - - -MkDir $(OUT_DIR_NATIVE) ; -Depends $(OUT_NATIVE) : $(OUT_DIR_NATIVE) ; -Main $(OUT_NATIVE) : $(NATIVE_CORE_MODULES) $(NATIVE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; - -Depends native : $(OUT_NATIVE) ; - diff --git a/libraries/RF24/tests/native/pingpair_irq.pde b/libraries/RF24/tests/native/pingpair_irq.pde deleted file mode 100644 index 99c2cdf..0000000 --- a/libraries/RF24/tests/native/pingpair_irq.pde +++ /dev/null @@ -1,223 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * Interrupt-driven test for native target - * - * This example is the friendliest for the native target because it doesn't do - * any polling. Made a slight change to call done() at the end of setup. - */ - -#include -#include "nRF24L01.h" -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 8 & 9 - -RF24 radio(8,9); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const short role_pin = 7; - -// -// Topology -// - -// Single radio pipe address for the 2 nodes to communicate. -const uint64_t pipe = 0xE8E8F0F0E1LL; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes in this -// system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_sender = 1, role_receiver } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Sender", "Receiver"}; - -// The role of the current running sketch -role_e role; - -// Interrupt handler, check the radio because we got an IRQ -void check_radio(void); - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_sender; - else - role = role_receiver; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/examples/pingpair_irq/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // We will be using the Ack Payload feature, so please enable it - radio.enableAckPayload(); - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens a single pipe for these two nodes to communicate - // back and forth. One listens on it, the other talks to it. - - if ( role == role_sender ) - { - radio.openWritingPipe(pipe); - } - else - { - radio.openReadingPipe(1,pipe); - } - - // - // Start listening - // - - if ( role == role_receiver ) - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); - - // - // Attach interrupt handler to interrupt #0 (using pin 2) - // on BOTH the sender and receiver - // - - attachInterrupt(0, check_radio, FALLING); - - // - // On the native target, this is as far as we get - // -#if NATIVE - done(); -#endif -} - -static uint32_t message_count = 0; - -void loop(void) -{ - // - // Sender role. Repeatedly send the current time - // - - if (role == role_sender) - { - // Take the time, and send it. - unsigned long time = millis(); - printf("Now sending %lu\n\r",time); - radio.startWrite( &time, sizeof(unsigned long) ); - - // Try again soon - delay(2000); - } - - // - // Receiver role: Does nothing! All the work is in IRQ - // - -} - -void check_radio(void) -{ - // What happened? - bool tx,fail,rx; - radio.whatHappened(tx,fail,rx); - - // Have we successfully transmitted? - if ( tx ) - { - if ( role == role_sender ) - printf("Send:OK\n\r"); - - if ( role == role_receiver ) - printf("Ack Payload:Sent\n\r"); - } - - // Have we failed to transmit? - if ( fail ) - { - if ( role == role_sender ) - printf("Send:Failed\n\r"); - - if ( role == role_receiver ) - printf("Ack Payload:Failed\n\r"); - } - - // Transmitter can power down for now, because - // the transmission is done. - if ( ( tx || fail ) && ( role == role_sender ) ) - radio.powerDown(); - - // Did we receive a message? - if ( rx ) - { - // If we're the sender, we've received an ack payload - if ( role == role_sender ) - { - radio.read(&message_count,sizeof(message_count)); - printf("Ack:%lu\n\r",(unsigned long)message_count); - } - - // If we're the receiver, we've received a time message - if ( role == role_receiver ) - { - // Get this payload and dump it - static unsigned long got_time; - radio.read( &got_time, sizeof(got_time) ); - printf("Got payload %lu\n\r",got_time); - - // Add an ack packet for the next time around. This is a simple - // packet counter - radio.writeAckPayload( 1, &message_count, sizeof(message_count) ); - ++message_count; - } - } -} - -// vim:ai:cin:sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/tests/native/printf.h b/libraries/RF24/tests/native/printf.h deleted file mode 100644 index df6c46a..0000000 --- a/libraries/RF24/tests/native/printf.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -#include "WProgram.h" - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#endif // __PRINTF_H__ diff --git a/libraries/RF24/tests/pingpair_blocking/Jamfile b/libraries/RF24/tests/pingpair_blocking/Jamfile deleted file mode 100644 index 98ec12f..0000000 --- a/libraries/RF24/tests/pingpair_blocking/Jamfile +++ /dev/null @@ -1,206 +0,0 @@ -PROJECT_NAME = $(PWD:B) ; -PROJECT_DIR = . ; -PROJECT_LIBS = SPI RF24 ; - -OUT_DIR = ojam ; -F_CPU = 16000000 ; -MCU = atmega328p ; -PORTS = /dev/tty.usbserial-A600eHIs /dev/tty.usbserial-A40081RP /dev/tty.usbserial-A9007LmI ; - -UPLOAD_RATE = 57600 ; -AVRDUDE_PROTOCOL = stk500v1 ; -COM = 33 ; - -# Host-specific overrides for locations -if $(OS) = MACOSX -{ -ARDUINO_VERSION = 22 ; -OLD_DIR = /opt/arduino-0021 ; -AVR_TOOLS_PATH = $(OLD_DIR)/hardware/tools/avr/bin ; -AVRDUDECONFIG_PATH = $(OLD_DIR)/hardware/tools/avr/etc ; -ARDUINO_DIR = /opt/Arduino ; -ARDUINO_AVR = /usr/lib/avr/include ; -} - -# Where is everything? -ARDUINO_VERSION ?= 22 ; -AVR_TOOLS_PATH ?= /usr/bin ; -ARDUINO_DIR ?= /opt/arduino-00$(ARDUINO_VERSION) ; -ARDUINO_AVR ?= $(ARDUINO_DIR)/hardware/tools/avr/avr/include/avr ; -AVRDUDECONFIG_PATH ?= $(ARDUINO_DIR)/hardware/tools ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; -AVR_CC = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_CXX = $(AVR_TOOLS_PATH)/avr-g++ ; -AVR_LD = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_OBJCOPY = $(AVR_TOOLS_PATH)/avr-objcopy ; -AVRDUDE = $(AVR_TOOLS_PATH)/avrdude ; - -DEFINES = F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -CTUNING = -ffunction-sections -fdata-sections ; -CXXTUNING = -fno-exceptions -fno-strict-aliasing ; -CFLAGS = -Os -Werror -Wall -Wextra -mmcu=$(MCU) $(CTUNING) ; -CXXFLAGS = $(CFLAGS) $(CXXTUNING) ; -LDFLAGS = -Os -lm -Wl,--gc-sections -mmcu=atmega328p ; - -# Search everywhere for headers -HDRS = $(PROJECT_DIR) $(ARDUINO_AVR) $(ARDUINO_CORE) [ GLOB $(ARDUINO_LIB) $(SKETCH_LIB) : [^.]* ] ; - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp ] ; - -# In addition to explicitly-specified program modules, pick up anything from the current -# dir. -PROJECT_MODULES += [ GLOB $(PROJECT_DIR) : *.c *.cpp *.pde ] ; - -# Shortcut for the out files -OUT = $(OUT_DIR)/$(PROJECT_NAME) ; - -# AvrDude setup -AVRDUDE_FLAGS = -V -F -D -C $(AVRDUDECONFIG_PATH)/avrdude.conf -p $(MCU) -c $(AVRDUDE_PROTOCOL) -b $(UPLOAD_RATE) ; - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule AvrCc -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrCc -{ - $(AVR_CC) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CFLAGS) $(>) -} - -rule AvrC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrC++ -{ - $(AVR_CXX) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule Pde -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - -} - -actions Pde -{ - echo "#include " > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule AvrPde -{ - local _CPP = $(OUT_DIR)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - AvrC++ $(<) : $(_CPP) ; -} - -rule AvrObject -{ - switch $(>:S) - { - case .c : AvrCc $(<) : $(>) ; - case .cpp : AvrC++ $(<) : $(>) ; - case .pde : AvrPde $(<) : $(>) ; - } -} - -rule AvrObjects -{ - for _I in $(<) - { - AvrObject $(OUT_DIR)/$(_I:B).o : $(_I) ; - } -} - -rule AvrMainFromObjects -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - MkDir $(<:D) ; - Depends all : $(<) ; - Clean clean : $(<) ; -} - -actions AvrMainFromObjects -{ - $(AVR_LD) $(LDFLAGS) -o $(<) $(>) -} - -rule AvrMain -{ - AvrMainFromObjects $(<) : $(OUT_DIR)/$(>:B).o ; - AvrObjects $(>) ; -} - -rule AvrHex -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions AvrHex -{ - $(AVR_OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule AvrUpload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - AvrUploadAction $(2) : $(3) ; -} - -actions AvrUploadAction -{ - $(AVRDUDE) $(AVRDUDE_FLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -AvrMain $(OUT).elf : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -AvrHex $(OUT).hex : $(OUT).elf ; - -AvrUpload p6 : /dev/tty.usbserial-A600eHIs : $(OUT).hex ; -AvrUpload p4 : /dev/tty.usbserial-A40081RP : $(OUT).hex ; -AvrUpload p9 : /dev/tty.usbserial-A9007LmI : $(OUT).hex ; - diff --git a/libraries/RF24/tests/pingpair_blocking/pingpair_blocking.pde b/libraries/RF24/tests/pingpair_blocking/pingpair_blocking.pde deleted file mode 100644 index 504b8c8..0000000 --- a/libraries/RF24/tests/pingpair_blocking/pingpair_blocking.pde +++ /dev/null @@ -1,268 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -#include -#include "RF24.h" -#include "printf.h" - -// -// Test version of RF24, exposes some protected interface -// - -class RF24Test: public RF24 -{ -public: RF24Test(int a, int b): RF24(a,b) {} -}; - - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 8 & 9 - -RF24Test radio(8,9); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const int role_pin = 7; - -// -// Topology -// - -// Radio pipe addresses for the 2 nodes to communicate. -const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL }; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes -// in this system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_ping_out = 1, role_pong_back } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"}; - -// The role of the current running sketch -role_e role; - -// -// Test state -// - -bool done; //*< Are we done with the test? */ -bool passed; //*< Have we passed the test? */ -bool notified; //*< Have we notified the user we're done? */ -const int num_needed = 10; //*< How many success/failures until we're done? */ -int receives_remaining = num_needed; //*< How many ack packets until we declare victory? */ -int failures_remaining = num_needed; //*< How many more failed sends until we declare failure? */ -int interval = 100; //*< ms to wait between sends */ - -char configuration = '1'; //*< Configuration key, one char sent in by the test framework to tell us how to configure, this is the default */ - -void one_ok(void) -{ - // Have we received enough yet? - if ( ! --receives_remaining ) - { - done = true; - passed = true; - } -} - -void one_failed(void) -{ - // Have we failed enough yet? - if ( ! --failures_remaining ) - { - done = true; - passed = false; - } -} - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_ping_out; - else - role = role_pong_back; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/tests/pingpair_blocking/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // get test config - // - - printf("+READY press any key to start\n\r\n\r"); - - while (! Serial.available() ) {} - configuration = Serial.read(); - printf("Configuration\t = %c\n\r",configuration); - - // - // Setup and configure rf radio - // - - radio.begin(); - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens two pipes for these two nodes to communicate - // back and forth. - // Open 'our' pipe for writing - // Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading) - - if ( role == role_ping_out ) - { - radio.openWritingPipe(pipes[0]); - radio.openReadingPipe(1,pipes[1]); - } - else - { - radio.openWritingPipe(pipes[1]); - radio.openReadingPipe(1,pipes[0]); - } - - // - // Start listening - // - - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - - radio.printDetails(); -} - -void loop(void) -{ - // - // Ping out role. Repeatedly send the current time - // - - if (role == role_ping_out) - { - // First, stop listening so we can talk. - radio.stopListening(); - - // Take the time, and send it. This will block until complete - unsigned long time = millis(); - printf("Now sending %lu...",time); - radio.write( &time, sizeof(unsigned long) ); - - // Now, continue listening - radio.startListening(); - - // Wait here until we get a response, or timeout - unsigned long started_waiting_at = micros(); - bool timeout = false; - while ( ! radio.available() && ! timeout ) - if (micros() - started_waiting_at > radio.getMaxTimeout() ) - timeout = true; - - // Describe the results - if ( timeout ) - { - printf("Failed, response timed out.\n\r"); - one_failed(); - } - else - { - // Grab the response, compare, and send to debugging spew - unsigned long got_time; - radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got response %lu, round-trip delay: %lu\n\r",got_time,millis()-got_time); - one_ok(); - } - - // Try again later - delay(250); - } - - // - // Pong back role. Receive each packet, dump it out, and send it back - // - - if ( role == role_pong_back ) - { - // if there is data ready - if ( radio.available() ) - { - // Dump the payloads until we've gotten everything - unsigned long got_time; - bool done = false; - while (!done) - { - // Fetch the payload, and see if this was the last one. - done = radio.read( &got_time, sizeof(unsigned long) ); - - // Spew it - printf("Got payload %lu...",got_time); - - // Delay just a little bit to let the other unit - // make the transition to receiver - delay(20); - } - - // First, stop listening so we can talk - radio.stopListening(); - - // Send the final one back. - radio.write( &got_time, sizeof(unsigned long) ); - printf("Sent response.\n\r"); - - // Now, resume listening so we catch the next packets. - radio.startListening(); - - } - } - - // - // Stop the test if we're done and report results - // - if ( done && ! notified ) - { - notified = true; - - printf("\n\r+OK "); - if ( passed ) - printf("PASS\n\r\n\r"); - else - printf("FAIL\n\r\n\r"); - } -} -// vim:cin:ai:sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/tests/pingpair_blocking/printf.h b/libraries/RF24/tests/pingpair_blocking/printf.h deleted file mode 100644 index 1b853db..0000000 --- a/libraries/RF24/tests/pingpair_blocking/printf.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#endif // __PRINTF_H__ diff --git a/libraries/RF24/tests/pingpair_blocking/runtest.py b/libraries/RF24/tests/pingpair_blocking/runtest.py deleted file mode 100644 index 45fb65c..0000000 --- a/libraries/RF24/tests/pingpair_blocking/runtest.py +++ /dev/null @@ -1,25 +0,0 @@ -#!/opt/local/bin/python - -import sys,serial - -def read_until(token): - while 1: - line = ser.readline(None,"\r") - sys.stdout.write(line) - - if (line.startswith(token)): - break - return line - - -ser = serial.Serial(sys.argv[1], 57600, timeout=5, dsrdtr=False, rtscts=False) - -read_until("+READY") -ser.write(sys.argv[2]) - -line = read_until("+OK") -ser.close() -if (line.find("PASS") != -1): - sys.exit(0) -else: - sys.exit(1) diff --git a/libraries/RF24/tests/pingpair_blocking/runtests.sh b/libraries/RF24/tests/pingpair_blocking/runtests.sh deleted file mode 100644 index 53b16f9..0000000 --- a/libraries/RF24/tests/pingpair_blocking/runtests.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/sh - -# Connect p6 to receiver, p4 to sender - -jam p4 p6 || exit 1 -./runtest.py /dev/tty.usbserial-A600eHIs 1 & -./runtest.py /dev/tty.usbserial-A40081RP 1 || ( kill `jobs -p` && exit 1 ) -kill `jobs -p` -exit 0 diff --git a/libraries/RF24/tests/pingpair_blocking/test.ex b/libraries/RF24/tests/pingpair_blocking/test.ex deleted file mode 100644 index ea992ad..0000000 --- a/libraries/RF24/tests/pingpair_blocking/test.ex +++ /dev/null @@ -1,11 +0,0 @@ -#/usr/bin/expect - -set timeout 100 -spawn picocom -b 57600 /dev/ttyUSB0 -expect "+READY" -send "1" -expect "+OK" -spawn picocom -b 57600 /dev/ttyUSB1 -expect "+READY" -send "1" -expect "+OK" diff --git a/libraries/RF24/tests/pingpair_test/Jamfile b/libraries/RF24/tests/pingpair_test/Jamfile deleted file mode 100644 index 98ec12f..0000000 --- a/libraries/RF24/tests/pingpair_test/Jamfile +++ /dev/null @@ -1,206 +0,0 @@ -PROJECT_NAME = $(PWD:B) ; -PROJECT_DIR = . ; -PROJECT_LIBS = SPI RF24 ; - -OUT_DIR = ojam ; -F_CPU = 16000000 ; -MCU = atmega328p ; -PORTS = /dev/tty.usbserial-A600eHIs /dev/tty.usbserial-A40081RP /dev/tty.usbserial-A9007LmI ; - -UPLOAD_RATE = 57600 ; -AVRDUDE_PROTOCOL = stk500v1 ; -COM = 33 ; - -# Host-specific overrides for locations -if $(OS) = MACOSX -{ -ARDUINO_VERSION = 22 ; -OLD_DIR = /opt/arduino-0021 ; -AVR_TOOLS_PATH = $(OLD_DIR)/hardware/tools/avr/bin ; -AVRDUDECONFIG_PATH = $(OLD_DIR)/hardware/tools/avr/etc ; -ARDUINO_DIR = /opt/Arduino ; -ARDUINO_AVR = /usr/lib/avr/include ; -} - -# Where is everything? -ARDUINO_VERSION ?= 22 ; -AVR_TOOLS_PATH ?= /usr/bin ; -ARDUINO_DIR ?= /opt/arduino-00$(ARDUINO_VERSION) ; -ARDUINO_AVR ?= $(ARDUINO_DIR)/hardware/tools/avr/avr/include/avr ; -AVRDUDECONFIG_PATH ?= $(ARDUINO_DIR)/hardware/tools ; -ARDUINO_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino ; -ARDUINO_LIB = $(ARDUINO_DIR)/libraries ; -SKETCH_LIB = $(HOME)/Source/Arduino/libraries ; -AVR_CC = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_CXX = $(AVR_TOOLS_PATH)/avr-g++ ; -AVR_LD = $(AVR_TOOLS_PATH)/avr-gcc ; -AVR_OBJCOPY = $(AVR_TOOLS_PATH)/avr-objcopy ; -AVRDUDE = $(AVR_TOOLS_PATH)/avrdude ; - -DEFINES = F_CPU=$(F_CPU)L ARDUINO=$(ARDUINO_VERSION) VERSION_H ; -CTUNING = -ffunction-sections -fdata-sections ; -CXXTUNING = -fno-exceptions -fno-strict-aliasing ; -CFLAGS = -Os -Werror -Wall -Wextra -mmcu=$(MCU) $(CTUNING) ; -CXXFLAGS = $(CFLAGS) $(CXXTUNING) ; -LDFLAGS = -Os -lm -Wl,--gc-sections -mmcu=atmega328p ; - -# Search everywhere for headers -HDRS = $(PROJECT_DIR) $(ARDUINO_AVR) $(ARDUINO_CORE) [ GLOB $(ARDUINO_LIB) $(SKETCH_LIB) : [^.]* ] ; - -# Grab everything from the core directory -CORE_MODULES = [ GLOB $(ARDUINO_CORE) : *.c *.cpp ] ; - -# Grab everything from libraries. To avoid this "grab everything" behaviour, you -# can specify specific modules to pick up in PROJECT_MODULES -LIB_MODULES = [ GLOB $(ARDUINO_LIB)/$(PROJECT_LIBS) $(SKETCH_LIB)/$(PROJECT_LIBS) : *.cpp ] ; - -# In addition to explicitly-specified program modules, pick up anything from the current -# dir. -PROJECT_MODULES += [ GLOB $(PROJECT_DIR) : *.c *.cpp *.pde ] ; - -# Shortcut for the out files -OUT = $(OUT_DIR)/$(PROJECT_NAME) ; - -# AvrDude setup -AVRDUDE_FLAGS = -V -F -D -C $(AVRDUDECONFIG_PATH)/avrdude.conf -p $(MCU) -c $(AVRDUDE_PROTOCOL) -b $(UPLOAD_RATE) ; - -rule GitVersion -{ - Always $(<) ; - Depends all : $(<) ; -} - -actions GitVersion -{ - echo "const char program_version[] = \"\\" > $(<) - git log -1 --pretty=format:%h >> $(<) - echo "\";" >> $(<) -} - -GitVersion version.h ; - -rule AvrCc -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrCc -{ - $(AVR_CC) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CFLAGS) $(>) -} - -rule AvrC++ -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - - CCHDRS on $(<) = [ on $(<) FIncludes $(HDRS) ] ; - CCDEFS on $(<) = [ on $(<) FDefines $(DEFINES) ] ; -} - -actions AvrC++ -{ - $(AVR_CXX) -c -o $(<) $(CCHDRS) $(CCDEFS) $(CXXFLAGS) $(>) -} - -rule Pde -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Clean clean : $(<) ; - -} - -actions Pde -{ - echo "#include " > $(<) - echo "#line 1 \"$(>)\"" >> $(<) - cat $(>) >> $(<) -} - -rule AvrPde -{ - local _CPP = $(OUT_DIR)/$(_I:B).cpp ; - Pde $(_CPP) : $(>) ; - AvrC++ $(<) : $(_CPP) ; -} - -rule AvrObject -{ - switch $(>:S) - { - case .c : AvrCc $(<) : $(>) ; - case .cpp : AvrC++ $(<) : $(>) ; - case .pde : AvrPde $(<) : $(>) ; - } -} - -rule AvrObjects -{ - for _I in $(<) - { - AvrObject $(OUT_DIR)/$(_I:B).o : $(_I) ; - } -} - -rule AvrMainFromObjects -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - MkDir $(<:D) ; - Depends all : $(<) ; - Clean clean : $(<) ; -} - -actions AvrMainFromObjects -{ - $(AVR_LD) $(LDFLAGS) -o $(<) $(>) -} - -rule AvrMain -{ - AvrMainFromObjects $(<) : $(OUT_DIR)/$(>:B).o ; - AvrObjects $(>) ; -} - -rule AvrHex -{ - Depends $(<) : $(>) ; - Depends $(<) : $(<:D) ; - Depends hex : $(<) ; - Clean clean : $(<) ; -} - -actions AvrHex -{ - $(AVR_OBJCOPY) -O ihex -R .eeprom $(>) $(<) -} - -rule AvrUpload -{ - Depends $(1) : $(2) ; - Depends $(2) : $(3) ; - NotFile $(1) ; - Always $(1) ; - Always $(2) ; - AvrUploadAction $(2) : $(3) ; -} - -actions AvrUploadAction -{ - $(AVRDUDE) $(AVRDUDE_FLAGS) -P $(<) $(AVRDUDE_WRITE_FLASH) -U flash:w:$(>):i -} - -AvrMain $(OUT).elf : $(CORE_MODULES) $(LIB_MODULES) $(PROJECT_MODULES) ; -AvrHex $(OUT).hex : $(OUT).elf ; - -AvrUpload p6 : /dev/tty.usbserial-A600eHIs : $(OUT).hex ; -AvrUpload p4 : /dev/tty.usbserial-A40081RP : $(OUT).hex ; -AvrUpload p9 : /dev/tty.usbserial-A9007LmI : $(OUT).hex ; - diff --git a/libraries/RF24/tests/pingpair_test/pingpair_test.pde b/libraries/RF24/tests/pingpair_test/pingpair_test.pde deleted file mode 100644 index 403c195..0000000 --- a/libraries/RF24/tests/pingpair_test/pingpair_test.pde +++ /dev/null @@ -1,395 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * Full test on single RF pair - * - * This sketches uses as many RF24 methods as possible in a single test. - * - * To operate: - * Upload this sketch on two nodes, each with IRQ -> pin 2 - * One node needs pin 7 -> GND, the other NC. That's the receiving node - * Monitor the sending node's serial output - * Look for "+OK PASS" or "+OK FAIL" - */ - -#include -#include "RF24.h" -#include "printf.h" - -// -// Hardware configuration -// - -// Set up nRF24L01 radio on SPI bus plus pins 8 & 9 - -RF24 radio(8,9); - -// sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver -// Leave open to be the 'ping' transmitter -const short role_pin = 7; - -// -// Topology -// - -// Single radio pipe address for the 2 nodes to communicate. -const uint64_t pipe = 0xE8E8F0F0E1LL; - -// -// Role management -// -// Set up role. This sketch uses the same software for all the nodes in this -// system. Doing so greatly simplifies testing. The hardware itself specifies -// which node it is. -// -// This is done through the role_pin -// - -// The various roles supported by this sketch -typedef enum { role_sender = 1, role_receiver } role_e; - -// The debug-friendly names of those roles -const char* role_friendly_name[] = { "invalid", "Sender", "Receiver"}; - -// The role of the current running sketch -role_e role; - -// Interrupt handler, check the radio because we got an IRQ -void check_radio(void); - -// -// Payload -// - -const int min_payload_size = 4; -const int max_payload_size = 32; -int payload_size_increments_by = 2; -int next_payload_size = min_payload_size; - -char receive_payload[max_payload_size+1]; // +1 to allow room for a terminating NULL char - -// -// Test state -// - -bool done; //*< Are we done with the test? */ -bool passed; //*< Have we passed the test? */ -bool notified; //*< Have we notified the user we're done? */ -const int num_needed = 10; //*< How many success/failures until we're done? */ -int receives_remaining = num_needed; //*< How many ack packets until we declare victory? */ -int failures_remaining = num_needed; //*< How many more failed sends until we declare failure? */ -int interval = 100; //*< ms to wait between sends */ - -char configuration = '1'; //*< Configuration key, one char sent in by the test framework to tell us how to configure, this is the default */ - -void one_ok(void) -{ - // Have we received enough yet? - if ( ! --receives_remaining ) - { - done = true; - passed = true; - } -} - -void one_failed(void) -{ - // Have we failed enough yet? - if ( ! --failures_remaining ) - { - done = true; - passed = false; - } -} - -// -// Setup -// - -void setup(void) -{ - // - // Role - // - - // set up the role pin - pinMode(role_pin, INPUT); - digitalWrite(role_pin,HIGH); - delay(20); // Just to get a solid reading on the role pin - - // read the address pin, establish our role - if ( digitalRead(role_pin) ) - role = role_sender; - else - role = role_receiver; - - // - // Print preamble - // - - Serial.begin(57600); - printf_begin(); - printf("\n\rRF24/tests/pingpair_test/\n\r"); - printf("ROLE: %s\n\r",role_friendly_name[role]); - - // - // Read configuration from serial - // - // It would be a much better test if this program could accept configuration - // from the serial port. Then it would be possible to run the same test under - // lots of different circumstances. - // - // The idea is that we will print "+READY" at this point. The python script - // will wait for it, and then send down a configuration script that we - // execute here and then run with. - // - // The test controller will need to configure the receiver first, then go run - // the test on the sender. - // - - printf("+READY press any key to start\n\r\n\r"); - - while (! Serial.available() ) {} - configuration = Serial.read(); - printf("Configuration\t = %c\n\r",configuration); - - // - // Setup and configure rf radio - // - - radio.begin(); - - // We will be using the Ack Payload feature, so please enable it - radio.enableAckPayload(); - - // Config 2 is special radio config - if (configuration=='2') - { - radio.setCRCLength(RF24_CRC_8); - radio.setDataRate(RF24_250KBPS); - radio.setChannel(10); - } - else - { - //Otherwise, default radio config - - // Optional: Increase CRC length for improved reliability - radio.setCRCLength(RF24_CRC_16); - - // Optional: Decrease data rate for improved reliability - radio.setDataRate(RF24_1MBPS); - - // Optional: Pick a high channel - radio.setChannel(90); - } - - // Config 3 is static payloads only - if (configuration == '3') - { - next_payload_size = 16; - payload_size_increments_by = 0; - radio.setPayloadSize(next_payload_size); - } - else - { - // enable dynamic payloads - radio.enableDynamicPayloads(); - } - - // - // Open pipes to other nodes for communication - // - - // This simple sketch opens a single pipe for these two nodes to communicate - // back and forth. One listens on it, the other talks to it. - - if ( role == role_sender ) - { - radio.openWritingPipe(pipe); - } - else - { - radio.openReadingPipe(1,pipe); - } - - // - // Start listening - // - - if ( role == role_receiver ) - radio.startListening(); - - // - // Dump the configuration of the rf unit for debugging - // - radio.printDetails(); - - // - // Attach interrupt handler to interrupt #0 (using pin 2) - // on BOTH the sender and receiver - // - delay(40) ; - attachInterrupt(0, check_radio, FALLING); -} - -// -// Loop -// - -static uint32_t message_count = 0; -static uint32_t last_message_count = 0; - -void loop(void) -{ - // - // Sender role. Repeatedly send the current time - // - - if (role == role_sender && !done) - { - // The payload will always be the same, what will change is how much of it we send. - static char send_payload[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ789012"; - - // First, stop listening so we can talk. - radio.stopListening(); - - // Send it. This will block until complete - radio.powerUp() ; - printf("\n\rNow sending length %i...",next_payload_size); - radio.startWrite( send_payload, next_payload_size ); - - // Update size for next time. - next_payload_size += payload_size_increments_by; - if ( next_payload_size > max_payload_size ) - next_payload_size = min_payload_size; - - // Try again soon - interval = 1 + (radio.getMaxTimeout()/1000) ; - delay(interval); - - // Timeout if we have not received anything back ever - if ( ! last_message_count && millis() > interval * 10 ) - { - printf("No responses received. Are interrupts connected??\n\r"); - done = true; - } - } - - // - // Receiver role: Does nothing! All the work is in IRQ - // - - // - // Stop the test if we're done and report results - // - if ( done && ! notified ) - { - notified = true; - - printf("\n\r+OK "); - if ( passed ) - printf("PASS\n\r\n\r"); - else - printf("FAIL\n\r\n\r"); - } - - // - // -} - -void check_radio(void) -{ - // What happened? - bool tx,fail,rx; - radio.whatHappened(tx,fail,rx); - - // Have we successfully transmitted? - if ( tx ) - { - if ( role == role_sender ) - printf("Send:OK "); - - if ( role == role_receiver ) - printf("Ack Payload:Sent\n\r"); - } - - // Have we failed to transmit? - if ( fail ) - { - if ( role == role_sender ) - { - printf("Send:Failed "); - - // log status of this line - one_failed(); - } - - if ( role == role_receiver ) - printf("Ack Payload:Failed\n\r"); - } - - // Transmitter can power down for now, because - // the transmission is done. - if ( ( tx || fail ) && ( role == role_sender ) ) - radio.powerDown(); - - // Did we receive a message? - if ( rx ) - { - // If we're the sender, we've received an ack payload - if ( role == role_sender ) - { - radio.read(&message_count,sizeof(message_count)); - printf("Ack:%lu ",message_count); - - // is this ack what we were expecting? to account - // for failures, we simply want to make sure we get a - // DIFFERENT ack every time. - if ( ( message_count != last_message_count ) || ( configuration=='3' && message_count == 16 ) ) - { - printf("OK "); - one_ok(); - } - else - { - printf("FAILED "); - one_failed(); - } - last_message_count = message_count; - } - - // If we're the receiver, we've received a time message - if ( role == role_receiver ) - { - // Get this payload and dump it - size_t len = max_payload_size; - memset(receive_payload,0,max_payload_size); - - if ( configuration == '3' ) - len = next_payload_size; - else - len = radio.getDynamicPayloadSize(); - - radio.read( receive_payload, len ); - - // Put a zero at the end for easy printing - receive_payload[len] = 0; - - // Spew it - printf("Got payload size=%i value=%s strlen=%u\n\r",len,receive_payload,strlen(receive_payload)); - - // Add an ack packet for the next time around. - // Here we will report back how many bytes we got this time. - radio.writeAckPayload( 1, &len, sizeof(len) ); - ++message_count; - } - } -} - -// vim:ai:cin:sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/tests/pingpair_test/printf.h b/libraries/RF24/tests/pingpair_test/printf.h deleted file mode 100644 index 1b853db..0000000 --- a/libraries/RF24/tests/pingpair_test/printf.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright (C) 2011 James Coliz, Jr. - - 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. - */ - -/** - * @file printf.h - * - * Setup necessary to direct stdout to the Arduino Serial library, which - * enables 'printf' - */ - -#ifndef __PRINTF_H__ -#define __PRINTF_H__ - -int serial_putc( char c, FILE * ) -{ - Serial.write( c ); - - return c; -} - -void printf_begin(void) -{ - fdevopen( &serial_putc, 0 ); -} - -#endif // __PRINTF_H__ diff --git a/libraries/RF24/tests/pingpair_test/runtest.py b/libraries/RF24/tests/pingpair_test/runtest.py deleted file mode 100644 index 45fb65c..0000000 --- a/libraries/RF24/tests/pingpair_test/runtest.py +++ /dev/null @@ -1,25 +0,0 @@ -#!/opt/local/bin/python - -import sys,serial - -def read_until(token): - while 1: - line = ser.readline(None,"\r") - sys.stdout.write(line) - - if (line.startswith(token)): - break - return line - - -ser = serial.Serial(sys.argv[1], 57600, timeout=5, dsrdtr=False, rtscts=False) - -read_until("+READY") -ser.write(sys.argv[2]) - -line = read_until("+OK") -ser.close() -if (line.find("PASS") != -1): - sys.exit(0) -else: - sys.exit(1) diff --git a/libraries/RF24/tests/pingpair_test/runtests.sh b/libraries/RF24/tests/pingpair_test/runtests.sh deleted file mode 100644 index 76f8f77..0000000 --- a/libraries/RF24/tests/pingpair_test/runtests.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/sh - -# Connect p6 to receiver, p4 to sender -# WARNING: Test config 2 only works with PLUS units. - -jam p4 p6 || exit 1 -./runtest.py /dev/tty.usbserial-A600eHIs 1 & -./runtest.py /dev/tty.usbserial-A40081RP 1 || ( kill `jobs -p` && exit 1 ) -kill `jobs -p` -./runtest.py /dev/tty.usbserial-A600eHIs 2 & -./runtest.py /dev/tty.usbserial-A40081RP 2 || ( kill `jobs -p` && exit 1 ) -kill `jobs -p` -./runtest.py /dev/tty.usbserial-A600eHIs 3 & -./runtest.py /dev/tty.usbserial-A40081RP 3 || ( kill `jobs -p` && exit 1 ) -kill `jobs -p` -exit 0 diff --git a/libraries/RF24/tests/pingpair_test/test.ex b/libraries/RF24/tests/pingpair_test/test.ex deleted file mode 100644 index a14ffef..0000000 --- a/libraries/RF24/tests/pingpair_test/test.ex +++ /dev/null @@ -1,11 +0,0 @@ -#/usr/bin/expect - -set timeout 100 -spawn picocom -b 57600 /dev/ttyUSB0 -expect "+READY" -send [lindex $argv 0] -expect "+OK" -spawn picocom -b 57600 /dev/ttyUSB1 -expect "+READY" -send [lindex $argv 0] -expect "+OK" diff --git a/libraries/RF24/wikidoc.xslt b/libraries/RF24/wikidoc.xslt deleted file mode 100644 index b94d3ef..0000000 --- a/libraries/RF24/wikidoc.xslt +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - === === - - - - - '''' - -Parameters: - - - - * '''': - - - - - -Returns: - -* - - -Warning: - - - - <pre> </pre> - - - - - - - diff --git a/libraries/SimpleFIFO/README b/libraries/SimpleFIFO/README deleted file mode 100644 index 1ceee3f..0000000 --- a/libraries/SimpleFIFO/README +++ /dev/null @@ -1,7 +0,0 @@ -Found the code via http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1267762668/9 - -Noticed it's not interrupt safe so did a quick-and-dirty sprinkling of volatile keywors and it happens to work - -Also limited the FIFO size the 255 (char vs int, for strategic variables) to conserve memory. - -See also http://code.google.com/p/alexanderbrevig/downloads/list diff --git a/libraries/SimpleFIFO/SimpleFIFO.h b/libraries/SimpleFIFO/SimpleFIFO.h deleted file mode 100644 index 3cf0c7a..0000000 --- a/libraries/SimpleFIFO/SimpleFIFO.h +++ /dev/null @@ -1,89 +0,0 @@ -#ifndef SimpleFIFO_h -#define SimpleFIFO_h -/* -|| -|| @file SimpleFIFO.h -|| @version 1.2 -|| @author Alexander Brevig -|| @contact alexanderbrevig@gmail.com -|| -|| @description -|| | A simple FIFO class, mostly for primitive types but can be used with classes if assignment to int is allowed -|| | This FIFO is not dynamic, so be sure to choose an appropriate size for it -|| # -|| -|| @license -|| | Copyright (c) 2010 Alexander Brevig -|| | 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; version -|| | 2.1 of the License. -|| | -|| | This library is distributed in the hope that it will be useful, -|| | but WITHOUT ANY WARRANTY; without even the implied warranty of -|| | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -|| | Lesser General Public License for more details. -|| | -|| | You should have received a copy of the GNU Lesser General Public -|| | License along with this library; if not, write to the Free Software -|| | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -|| # -|| -*/ -template -class SimpleFIFO { -public: - const char size; //speculative feature, in case it's needed - - SimpleFIFO(); - - T dequeue(); //get next element - bool enqueue( T element ); //add an element - T peek() const; //get the next element without releasing it from the FIFO - void flush(); //[1.1] reset to default state - - //how many elements are currently in the FIFO? - char count() { return numberOfElements; } - -private: -#ifndef SimpleFIFO_NONVOLATILE - volatile char numberOfElements; - volatile char nextIn; - volatile char nextOut; - volatile T raw[rawSize]; -#else - char numberOfElements; - char nextIn; - char nextOut; - T raw[rawSize]; -#endif -}; - -template -SimpleFIFO::SimpleFIFO() : size(rawSize) { - flush(); -} -template -bool SimpleFIFO::enqueue( T element ) { - if ( count() >= rawSize ) { return false; } - numberOfElements++; - nextIn %= size; - raw[nextIn] = element; - nextIn++; //advance to next index - return true; -} -template -T SimpleFIFO::dequeue() { - numberOfElements--; - nextOut %= size; - return raw[ nextOut++]; -} -template -T SimpleFIFO::peek() const { - return raw[ nextOut % size]; -} -template -void SimpleFIFO::flush() { - nextIn = nextOut = numberOfElements = 0; -} -#endif diff --git a/libraries/SimpleFIFO/examples/HelloSimpleFIFO/HelloSimpleFIFO.ino b/libraries/SimpleFIFO/examples/HelloSimpleFIFO/HelloSimpleFIFO.ino deleted file mode 100644 index 3e7bfae..0000000 --- a/libraries/SimpleFIFO/examples/HelloSimpleFIFO/HelloSimpleFIFO.ino +++ /dev/null @@ -1,27 +0,0 @@ -#include - -void setup() { - Serial.begin(9600); - - SimpleFIFO sFIFO; //store 10 ints - - sFIFO.enqueue(1); - sFIFO.enqueue(2); - sFIFO.enqueue(3); - sFIFO.enqueue(4); - sFIFO.enqueue(5); - - Serial.print(F("Peek: ")); - Serial.println(sFIFO.peek()); - - for (int i=0; i. - * - ***********************************************************************************/ - -#include "Sleep_n0m1.h" - -Sleep* Sleep::pSleep = 0; - -Sleep::Sleep() -{ - pSleep = this; //the ptr points to this object - timeSleep = 0; // total time due to sleep - calibv = 1.0; // ratio of real clock with WDT clock - byte isrcalled = 0; // WDT vector flag - sleepCycleCount = 0; - sleepCycleInterval = 100; - -} - -/******************************************************************** -* -* setSleepMode -* -********************************************************************/ -void Sleep::setSleepMode(int mode) -{ - sleepMode_ = mode; -} - - -/******************************************************************** -* -* calibrateTime -* -********************************************************************/ -void Sleep::calibrateTime(unsigned long sleepTime, boolean &abortCycle) { - // timer0 continues to run in idle sleep mode - set_sleep_mode(SLEEP_MODE_IDLE); - long tt1=millis(); - sleepWDT(sleepTime,abortCycle); - long tt2=millis(); - - calibv = (float) sleepTime/(tt2-tt1); - - //Serial.println(calibv); -} - -/******************************************************************** -* -* WDTMillis -* -********************************************************************/ -unsigned long Sleep::WDTMillis() { - return millis()+timeSleep; -} - -/******************************************************************** -* -* sleepNow -* -********************************************************************/ -void Sleep::sleepInterrupt(int interrupt,int mode) { - - if(mode == FALLING || mode == LOW) - { - int pin = interrupt + 2; //will fail on the mega - pinMode (pin, INPUT); - digitalWrite (pin, HIGH); - } - - set_sleep_mode(sleepMode_); - sleep_enable(); - attachInterrupt(interrupt,sleepHandler,mode); - sei(); //make sure interrupts are on! - sleep_mode(); - //----------------------------- ZZZZZZ sleeping here---------------------- - sleep_disable(); //disable sleep, awake now - detachInterrupt(interrupt); -} - - -/******************************************************************** -* -* sleepDelay -* -********************************************************************/ -void Sleep::sleepDelay(unsigned long sleepTime){ - - boolean abortCycle = false; - - sleepDelay(sleepTime,abortCycle); -} - -/******************************************************************** -* -* sleepDelay -* -********************************************************************/ -void Sleep::sleepDelay(unsigned long sleepTime, boolean &abortCycle) { - ADCSRA &= ~(1< 0) { - //work out next prescale unit to use - while ((0x10< remainTime && WDTps > 0) { - WDTps--; - } - // send prescaler mask to WDT_On - WDT_On((WDTps & 0x08 ? (1<WDT_Off(); - Sleep::pSleep->isrcalled=1; -} diff --git a/libraries/Sleep_n0m1/Sleep_n0m1.h b/libraries/Sleep_n0m1/Sleep_n0m1.h deleted file mode 100644 index 57ebda7..0000000 --- a/libraries/Sleep_n0m1/Sleep_n0m1.h +++ /dev/null @@ -1,109 +0,0 @@ -/************************************************************************************ - * - * Name : Sleep_n0m1.h - * Author : Noah Shibley / NoMi Design - * Date : July 10th 2011 - * Version : 0.1 - * Notes : Some of this code comes from "Cloudy" on the arduino forum - * http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1292898715 - * - * Copyright (c) 2012 NoMi Design (http://n0m1.com) All right reserved. - * - * This file is part of Triggertrap. See Triggertrap.com for more information. - * - * Triggertrap 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. - * - * Triggertrap 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 Triggertrap. If not, see . - * - ***********************************************************************************/ - -#ifndef SLEEP_H -#define SLEEP_H - - - -#include -#include -#if defined(ARDUINO) && ARDUINO >= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif - -extern "C" void WDT_vect(void) __attribute__ ((signal)); -extern "C" void sleepHandler(void) __attribute__ ((signal)); - -class Sleep { - -public: - - friend void WDT_vect(void); - friend void sleepHandler(void); - -Sleep(); - - /* modes of sleep - SLEEP_MODE_IDLE - SLEEP_MODE_ADC - SLEEP_MODE_PWR_SAVE - SLEEP_MODE_EXT_STANDBY - SLEEP_MODE_STANDBY - SLEEP_MODE_PWR_DOWN - */ - - void idleMode() { setSleepMode(SLEEP_MODE_IDLE);} - void adcMode() {setSleepMode(SLEEP_MODE_ADC);} - void pwrSaveMode() {setSleepMode(SLEEP_MODE_PWR_SAVE);} - void extStandbyMode(){setSleepMode(SLEEP_MODE_EXT_STANDBY);} - void standbyMode(){setSleepMode(SLEEP_MODE_STANDBY);} - void pwrDownMode(){setSleepMode(SLEEP_MODE_PWR_DOWN);} - - //WatchDog Sleep Functions: Sleep for a specfic length of time - void sleepDelay(unsigned long sleepTime); - void sleepDelay(unsigned long sleepTime,boolean &abortCycle); - void setCalibrationInterval(int interval){ sleepCycleInterval = interval; } - - //Interrupt Sleep Function: Sleep till something interrupts sleep - void sleepInterrupt(int interrupt,int mode); - - - - - - -private: - - int sleepMode_; - unsigned long timeSleep; - float calibv; - volatile byte isrcalled; - static Sleep* pSleep; //static ptr to Sleep class for the ISR - int sleepCycleCount; - int sleepCycleInterval; - - void setSleepMode(int mode); - void WDT_Off(); - void WDT_On(byte psMask); - int sleepWDT(unsigned long remainTime,boolean &abortCycle); - void calibrateTime(unsigned long sleepTime,boolean &abortCycle); //calibrate the time keeping difference between WDT and Timer0 - unsigned long WDTMillis(); // Estimated millis is real clock + calibrated sleep time - -}; - -#endif - - - - - - - diff --git a/libraries/Sleep_n0m1/examples/Sleep_n0m1_Interrupt/Sleep_n0m1_Interrupt.ino b/libraries/Sleep_n0m1/examples/Sleep_n0m1_Interrupt/Sleep_n0m1_Interrupt.ino deleted file mode 100644 index b8fe2af..0000000 --- a/libraries/Sleep_n0m1/examples/Sleep_n0m1_Interrupt/Sleep_n0m1_Interrupt.ino +++ /dev/null @@ -1,28 +0,0 @@ -#include - -Sleep sleep; - -void setup() -{ - - Serial.begin(9600); - - -} - -void loop() -{ - - delay(100); ////delays are just for serial print, without serial they can be removed - Serial.println("execute your code here"); - - Serial.print("Sleeping Till Interrupt"); - - delay(100); //delay to allow serial to fully print before sleep - - sleep.pwrDownMode(); //set sleep mode - sleep.sleepInterrupt(0,FALLING); //sleep for: sleepTime - - - -} diff --git a/libraries/Sleep_n0m1/examples/Sleep_n0m1_abortCycle/Sleep_n0m1_abortCycle.ino b/libraries/Sleep_n0m1/examples/Sleep_n0m1_abortCycle/Sleep_n0m1_abortCycle.ino deleted file mode 100644 index 8a5390f..0000000 --- a/libraries/Sleep_n0m1/examples/Sleep_n0m1_abortCycle/Sleep_n0m1_abortCycle.ino +++ /dev/null @@ -1,44 +0,0 @@ -#include - -Sleep sleep; -boolean abortSleep; //cancel sleep cycle -int sleepCycleCount; //the number of times awake then asleep -unsigned long sleepTime; //how long you want the arduino to sleep - - - -void setup() -{ - - Serial.begin(9600); - abortSleep = false; //can be used to cancel the sleep cycle - sleepTime = 5000; //set sleep time in ms, max sleep time is 49.7 days - -} - -void loop() -{ - if(abortSleep) - { - Serial.println("sleep no more!"); - } - else - { - delay(100); - Serial.print("sleeping for "); - Serial.println(sleepTime); - delay(100); //delay to allow serial to fully print before sleep - } - - sleepCycleCount++; - if(sleepCycleCount > 5) - { - abortSleep = true; - } - - sleep.pwrDownMode(); //set sleep mode - sleep.sleepDelay(sleepTime,abortSleep); //sleep for: sleepTime - - - -} diff --git a/libraries/Sleep_n0m1/examples/Sleep_n0m1_countDown/Sleep_n0m1_countDown.ino b/libraries/Sleep_n0m1/examples/Sleep_n0m1_countDown/Sleep_n0m1_countDown.ino deleted file mode 100644 index a2ca62c..0000000 --- a/libraries/Sleep_n0m1/examples/Sleep_n0m1_countDown/Sleep_n0m1_countDown.ino +++ /dev/null @@ -1,39 +0,0 @@ -#include - -int count = 0; -Sleep sleep; -unsigned long sleepTime; //how long you want the arduino to sleep - - - -void setup() -{ - - Serial.begin(9600); - sleepTime = 50000; //set sleep time in ms, max sleep time is 49.7 days - -} - -void loop() -{ - delay(100); //delay to allow serial output to be ready after wake up - Serial.print("Awake for "); - Serial.print(count); - Serial.println("sec"); - - count++; - delay(1000); // waits for a second - - if(count >= 3) - { - count = 0; - Serial.print("sleeping "); - Serial.println(sleepTime); - delay(100); //delay to allow serial to fully print before sleep - - sleep.pwrDownMode(); //set sleep mode - sleep.sleepDelay(sleepTime); //sleep for: sleepTime - } - - -} diff --git a/libraries/Sleep_n0m1/examples/Sleep_n0m1_simple/Sleep_n0m1_simple.ino b/libraries/Sleep_n0m1/examples/Sleep_n0m1_simple/Sleep_n0m1_simple.ino deleted file mode 100644 index 09a04ce..0000000 --- a/libraries/Sleep_n0m1/examples/Sleep_n0m1_simple/Sleep_n0m1_simple.ino +++ /dev/null @@ -1,31 +0,0 @@ -#include - -Sleep sleep; -unsigned long sleepTime; //how long you want the arduino to sleep - - - -void setup() -{ - - Serial.begin(9600); - sleepTime = 50000; //set sleep time in ms, max sleep time is 49.7 days - -} - -void loop() -{ - - delay(100); ////delays are just for serial print, without serial they can be removed - Serial.println("execute your code here"); - - Serial.print("sleeping for "); - Serial.println(sleepTime); - delay(100); //delay to allow serial to fully print before sleep - - sleep.pwrDownMode(); //set sleep mode - sleep.sleepDelay(sleepTime); //sleep for: sleepTime - - - -} diff --git a/libraries/UIPEthernet/utility/Enc28J60Network.cpp b/libraries/UIPEthernet/utility/Enc28J60Network.cpp deleted file mode 100644 index baf5b11..0000000 --- a/libraries/UIPEthernet/utility/Enc28J60Network.cpp +++ /dev/null @@ -1,554 +0,0 @@ -/* - Enc28J60Network.h - UIPEthernet network driver for Microchip ENC28J60 Ethernet Interface. - - Copyright (c) 2013 Norbert Truchsess - All rights reserved. - - based on enc28j60.c file from the AVRlib library by Pascal Stang. - For AVRlib See http://www.procyonengineering.com/ - - 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 . - */ - -#include "Enc28J60Network.h" -#include "Arduino.h" - -extern "C" { -#include -#include "enc28j60.h" -#include "uip.h" -} - -#ifdef ENC28J60DEBUG -#include "HardwareSerial.h" -#endif - -// set CS to 0 = active -#define CSACTIVE digitalWrite(ENC28J60_CONTROL_CS, LOW) -// set CS to 1 = passive -#define CSPASSIVE digitalWrite(ENC28J60_CONTROL_CS, HIGH) -// -#define waitspi() while(!(SPSR&(1< ip checksum for theses bytes=f7f9 - // in binary these poitions are:11 0000 0011 1111 - // This is hex 303F->EPMM0=0x3f,EPMM1=0x30 - //TODO define specific pattern to receive dhcp-broadcast packages instead of setting ERFCON_BCEN! - writeReg(ERXFCON, ERXFCON_UCEN|ERXFCON_CRCEN|ERXFCON_PMEN|ERXFCON_BCEN); - writeRegPair(EPMM0, 0x303f); - writeRegPair(EPMCSL, 0xf7f9); - // - // - // do bank 2 stuff - // enable MAC receive - // and bring MAC out of reset (writes 0x00 to MACON2) - writeRegPair(MACON1, MACON1_MARXEN|MACON1_TXPAUS|MACON1_RXPAUS); - // enable automatic padding to 60bytes and CRC operations - writeOp(ENC28J60_BIT_FIELD_SET, MACON3, MACON3_PADCFG0|MACON3_TXCRCEN|MACON3_FRMLNEN); - // set inter-frame gap (non-back-to-back) - writeRegPair(MAIPGL, 0x0C12); - // set inter-frame gap (back-to-back) - writeReg(MABBIPG, 0x12); - // Set the maximum packet size which the controller will accept - // Do not send packets longer than MAX_FRAMELEN: - writeRegPair(MAMXFLL, MAX_FRAMELEN); - // do bank 3 stuff - // write MAC address - // NOTE: MAC address in ENC28J60 is byte-backward - writeReg(MAADR5, macaddr[0]); - writeReg(MAADR4, macaddr[1]); - writeReg(MAADR3, macaddr[2]); - writeReg(MAADR2, macaddr[3]); - writeReg(MAADR1, macaddr[4]); - writeReg(MAADR0, macaddr[5]); - // no loopback of transmitted frames - phyWrite(PHCON2, PHCON2_HDLDIS); - // switch to bank 0 - setBank(ECON1); - // enable interrutps - writeOp(ENC28J60_BIT_FIELD_SET, EIE, EIE_INTIE|EIE_PKTIE); - // enable packet reception - writeOp(ENC28J60_BIT_FIELD_SET, ECON1, ECON1_RXEN); - //Configure leds - phyWrite(PHLCON,0x476); -} - -memhandle -Enc28J60Network::receivePacket() -{ - uint16_t rxstat; - uint16_t len; - // check if a packet has been received and buffered - //if( !(readReg(EIR) & EIR_PKTIF) ){ - // The above does not work. See Rev. B4 Silicon Errata point 6. - if (readReg(EPKTCNT) != 0) - { - uint16_t readPtr = nextPacketPtr+6; - // Set the read pointer to the start of the received packet - writeRegPair(ERDPTL, nextPacketPtr); - // read the next packet pointer - nextPacketPtr = readOp(ENC28J60_READ_BUF_MEM, 0); - nextPacketPtr |= readOp(ENC28J60_READ_BUF_MEM, 0) << 8; - // read the packet length (see datasheet page 43) - len = readOp(ENC28J60_READ_BUF_MEM, 0); - len |= readOp(ENC28J60_READ_BUF_MEM, 0) << 8; - len -= 4; //remove the CRC count - // read the receive status (see datasheet page 43) - rxstat = readOp(ENC28J60_READ_BUF_MEM, 0); - rxstat |= readOp(ENC28J60_READ_BUF_MEM, 0) << 8; - // decrement the packet counter indicate we are done with this packet - writeOp(ENC28J60_BIT_FIELD_SET, ECON2, ECON2_PKTDEC); - // check CRC and symbol errors (see datasheet page 44, table 7-3): - // The ERXFCON.CRCEN is set by default. Normally we should not - // need to check this. - if ((rxstat & 0x80) != 0) - { - receivePkt.begin = readPtr; - receivePkt.size = len; - return UIP_RECEIVEBUFFERHANDLE; - } - // Move the RX read pointer to the start of the next received packet - // This frees the memory we just read out - setERXRDPT(); - } - return (NOBLOCK); -} - -void -Enc28J60Network::setERXRDPT() -{ - writeRegPair(ERXRDPTL, nextPacketPtr == RXSTART_INIT ? RXSTOP_INIT : nextPacketPtr-1); -} - -memaddress -Enc28J60Network::blockSize(memhandle handle) -{ - return handle == UIP_RECEIVEBUFFERHANDLE ? receivePkt.size : blocks[handle].size; -} - -void -Enc28J60Network::sendPacket(memhandle handle) -{ - memblock *packet = &blocks[handle]; - uint16_t start = packet->begin-1; - uint16_t end = start + packet->size; - - // backup data at control-byte position - uint8_t data = readByte(start); - // write control-byte (if not 0 anyway) - if (data) - writeByte(start, 0); - -#ifdef ENC28J60DEBUG - Serial.print("sendPacket("); - Serial.print(handle); - Serial.print(") ["); - Serial.print(start); - Serial.print("-"); - Serial.print(end); - Serial.println("]:"); - for (uint16_t i=start; i<=end; i++) - { - Serial.print(readByte(i),HEX); - Serial.print(" "); - } - Serial.println(); -#endif - - // TX start - writeRegPair(ETXSTL, start); - // Set the TXND pointer to correspond to the packet size given - writeRegPair(ETXNDL, end); - // send the contents of the transmit buffer onto the network - writeOp(ENC28J60_BIT_FIELD_SET, ECON1, ECON1_TXRTS); - // Reset the transmit logic problem. See Rev. B4 Silicon Errata point 12. - if( (readReg(EIR) & EIR_TXERIF) ) - { - writeOp(ENC28J60_BIT_FIELD_CLR, ECON1, ECON1_TXRTS); - } - - //restore data on control-byte position - if (data) - writeByte(start, data); -} - -uint16_t -Enc28J60Network::setReadPtr(memhandle handle, memaddress position, uint16_t len) -{ - memblock *packet = handle == UIP_RECEIVEBUFFERHANDLE ? &receivePkt : &blocks[handle]; - memaddress start = packet->begin + position; - - writeRegPair(ERDPTL, start); - - if (len > packet->size - position) - len = packet->size - position; - return len; -} - -uint16_t -Enc28J60Network::readPacket(memhandle handle, memaddress position, uint8_t* buffer, uint16_t len) -{ - len = setReadPtr(handle, position, len); - readBuffer(len, buffer); - return len; -} - -uint16_t -Enc28J60Network::writePacket(memhandle handle, memaddress position, uint8_t* buffer, uint16_t len) -{ - memblock *packet = &blocks[handle]; - uint16_t start = packet->begin + position; - - writeRegPair(EWRPTL, start); - - if (len > packet->size - position) - len = packet->size - position; - writeBuffer(len, buffer); - return len; -} - -uint8_t Enc28J60Network::readByte(uint16_t addr) -{ - writeRegPair(ERDPTL, addr); - - CSACTIVE; - // issue read command - SPDR = ENC28J60_READ_BUF_MEM; - waitspi(); - // read data - SPDR = 0x00; - waitspi(); - CSPASSIVE; - return (SPDR); -} - -void Enc28J60Network::writeByte(uint16_t addr, uint8_t data) -{ - writeRegPair(EWRPTL, addr); - - CSACTIVE; - // issue write command - SPDR = ENC28J60_WRITE_BUF_MEM; - waitspi(); - // write data - SPDR = data; - waitspi(); - CSPASSIVE; -} - -void -Enc28J60Network::copyPacket(memhandle dest_pkt, memaddress dest_pos, memhandle src_pkt, memaddress src_pos, uint16_t len) -{ - memblock *dest = &blocks[dest_pkt]; - memblock *src = src_pkt == UIP_RECEIVEBUFFERHANDLE ? &receivePkt : &blocks[src_pkt]; - memblock_mv_cb(dest->begin+dest_pos,src->begin+src_pos,len); - // Move the RX read pointer to the start of the next received packet - // This frees the memory we just read out - setERXRDPT(); -} - -void -Enc28J60Network::memblock_mv_cb(uint16_t dest, uint16_t src, uint16_t len) -{ - //as ENC28J60 DMA is unable to copy single bytes: - if (len == 1) - { - writeByte(dest,readByte(src)); - } - else - { - // calculate address of last byte - len += src - 1; - - /* 1. Appropriately program the EDMAST, EDMAND - and EDMADST register pairs. The EDMAST - registers should point to the first byte to copy - from, the EDMAND registers should point to the - last byte to copy and the EDMADST registers - should point to the first byte in the destination - range. The destination range will always be - linear, never wrapping at any values except from - 8191 to 0 (the 8-Kbyte memory boundary). - Extreme care should be taken when - programming the start and end pointers to - prevent a never ending DMA operation which - would overwrite the entire 8-Kbyte buffer. - */ - writeRegPair(EDMASTL, src); - writeRegPair(EDMADSTL, dest); - - if ((src <= RXSTOP_INIT)&& (len > RXSTOP_INIT))len -= (RXSTOP_INIT-RXSTART_INIT); - writeRegPair(EDMANDL, len); - - /* - 2. If an interrupt at the end of the copy process is - desired, set EIE.DMAIE and EIE.INTIE and - clear EIR.DMAIF. - - 3. Verify that ECON1.CSUMEN is clear. */ - writeOp(ENC28J60_BIT_FIELD_CLR, ECON1, ECON1_CSUMEN); - - /* 4. Start the DMA copy by setting ECON1.DMAST. */ - writeOp(ENC28J60_BIT_FIELD_SET, ECON1, ECON1_DMAST); - - // wait until runnig DMA is completed - while (readOp(ENC28J60_READ_CTRL_REG, ECON1) & ECON1_DMAST); - } -} - -void -Enc28J60Network::freePacket() -{ - setERXRDPT(); -} - -uint8_t -Enc28J60Network::readOp(uint8_t op, uint8_t address) -{ - CSACTIVE; - // issue read command - SPDR = op | (address & ADDR_MASK); - waitspi(); - // read data - SPDR = 0x00; - waitspi(); - // do dummy read if needed (for mac and mii, see datasheet page 29) - if(address & 0x80) - { - SPDR = 0x00; - waitspi(); - } - // release CS - CSPASSIVE; - return(SPDR); -} - -void -Enc28J60Network::writeOp(uint8_t op, uint8_t address, uint8_t data) -{ - CSACTIVE; - // issue write command - SPDR = op | (address & ADDR_MASK); - waitspi(); - // write data - SPDR = data; - waitspi(); - CSPASSIVE; -} - -void -Enc28J60Network::readBuffer(uint16_t len, uint8_t* data) -{ - CSACTIVE; - // issue read command - SPDR = ENC28J60_READ_BUF_MEM; - waitspi(); - while(len) - { - len--; - // read data - SPDR = 0x00; - waitspi(); - *data = SPDR; - data++; - } - //*data='\0'; - CSPASSIVE; -} - -void -Enc28J60Network::writeBuffer(uint16_t len, uint8_t* data) -{ - CSACTIVE; - // issue write command - SPDR = ENC28J60_WRITE_BUF_MEM; - waitspi(); - while(len) - { - len--; - // write data - SPDR = *data; - data++; - waitspi(); - } - CSPASSIVE; -} - -void -Enc28J60Network::setBank(uint8_t address) -{ - // set the bank (if needed) - if((address & BANK_MASK) != bank) - { - // set the bank - writeOp(ENC28J60_BIT_FIELD_CLR, ECON1, (ECON1_BSEL1|ECON1_BSEL0)); - writeOp(ENC28J60_BIT_FIELD_SET, ECON1, (address & BANK_MASK)>>5); - bank = (address & BANK_MASK); - } -} - -uint8_t -Enc28J60Network::readReg(uint8_t address) -{ - // set the bank - setBank(address); - // do the read - return readOp(ENC28J60_READ_CTRL_REG, address); -} - -void -Enc28J60Network::writeReg(uint8_t address, uint8_t data) -{ - // set the bank - setBank(address); - // do the write - writeOp(ENC28J60_WRITE_CTRL_REG, address, data); -} - -void -Enc28J60Network::writeRegPair(uint8_t address, uint16_t data) -{ - // set the bank - setBank(address); - // do the write - writeOp(ENC28J60_WRITE_CTRL_REG, address, (data&0xFF)); - writeOp(ENC28J60_WRITE_CTRL_REG, address+1, (data) >> 8); -} - -void -Enc28J60Network::phyWrite(uint8_t address, uint16_t data) -{ - // set the PHY register address - writeReg(MIREGADR, address); - // write the PHY data - writeRegPair(MIWRL, data); - // wait until the PHY write completes - while(readReg(MISTAT) & MISTAT_BUSY){ - delayMicroseconds(15); - } -} - -void -Enc28J60Network::clkout(uint8_t clk) -{ - //setup clkout: 2 is 12.5MHz: - writeReg(ECOCON, clk & 0x7); -} - -// read the revision of the chip: -uint8_t -Enc28J60Network::getrev(void) -{ - return(readReg(EREVID)); -} - -uint16_t -Enc28J60Network::chksum(uint16_t sum, memhandle handle, memaddress pos, uint16_t len) -{ - uint16_t t; - len = setReadPtr(handle, pos, len)-1; - CSACTIVE; - // issue read command - SPDR = ENC28J60_READ_BUF_MEM; - waitspi(); - uint16_t i; - for (i = 0; i < len; i+=2) - { - // read data - SPDR = 0x00; - waitspi(); - t = SPDR << 8; - SPDR = 0x00; - waitspi(); - t += SPDR; - sum += t; - if(sum < t) { - sum++; /* carry */ - } - } - if(i == len) { - SPDR = 0x00; - waitspi(); - t = (SPDR << 8) + 0; - sum += t; - if(sum < t) { - sum++; /* carry */ - } - } - CSPASSIVE; - - /* Return sum in host byte order. */ - return sum; -} diff --git a/libraries/UIPEthernet/utility/Enc28J60Network.h b/libraries/UIPEthernet/utility/Enc28J60Network.h deleted file mode 100644 index 96f5600..0000000 --- a/libraries/UIPEthernet/utility/Enc28J60Network.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - Enc28J60Network.h - UIPEthernet network driver for Microchip ENC28J60 Ethernet Interface. - - Copyright (c) 2013 Norbert Truchsess - All rights reserved. - - inspired by enc28j60.c file from the AVRlib library by Pascal Stang. - For AVRlib See http://www.procyonengineering.com/ - - 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 . - */ - -#ifndef ENC28J60NETWORK_H_ -#define ENC28J60NETWORK_H_ - -#include "mempool.h" - -#define ENC28J60_CONTROL_CS SS -#define SPI_MOSI MOSI -#define SPI_MISO MISO -#define SPI_SCK SCK -#define SPI_SS SS - -#define UIP_RECEIVEBUFFERHANDLE 0xff - -//#define ENC28J60DEBUG - -/* - * Empfangen von ip-header, arp etc... - * wenn tcp/udp -> tcp/udp-callback -> assign new packet to connection - */ - -class Enc28J60Network : public MemoryPool -{ - -private: - uint16_t nextPacketPtr; - uint8_t bank; - - struct memblock receivePkt; - - uint8_t readOp(uint8_t op, uint8_t address); - void writeOp(uint8_t op, uint8_t address, uint8_t data); - uint16_t setReadPtr(memhandle handle, memaddress position, uint16_t len); - void setERXRDPT(); - void readBuffer(uint16_t len, uint8_t* data); - void writeBuffer(uint16_t len, uint8_t* data); - uint8_t readByte(uint16_t addr); - void writeByte(uint16_t addr, uint8_t data); - void setBank(uint8_t address); - uint8_t readReg(uint8_t address); - void writeReg(uint8_t address, uint8_t data); - void writeRegPair(uint8_t address, uint16_t data); - void phyWrite(uint8_t address, uint16_t data); - void clkout(uint8_t clk); - uint8_t getrev(void); - -protected: - void memblock_mv_cb(memaddress dest, memaddress src, memaddress size); - -public: - Enc28J60Network(); - void init(uint8_t* macaddr); - memhandle receivePacket(); - void freePacket(); - memaddress blockSize(memhandle handle); - void sendPacket(memhandle handle); - uint16_t readPacket(memhandle handle, memaddress position, uint8_t* buffer, uint16_t len); - uint16_t writePacket(memhandle handle, memaddress position, uint8_t* buffer, uint16_t len); - void copyPacket(memhandle dest, memaddress dest_pos, memhandle src, memaddress src_pos, uint16_t len); - uint16_t chksum(uint16_t sum, memhandle handle, memaddress pos, uint16_t len); -}; - -#endif /* ENC28J60NETWORK_H_ */ diff --git a/libraries/UIPEthernet/utility/clock-arch.c b/libraries/UIPEthernet/utility/clock-arch.c deleted file mode 100644 index 13b886d..0000000 --- a/libraries/UIPEthernet/utility/clock-arch.c +++ /dev/null @@ -1,28 +0,0 @@ -/* - clock-arch.c - Arduino implementation of uIP clock device. - Copyright (c) 2010 Adam Nielsen - All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include -#include "clock-arch.h" - -clock_time_t -clock_time(void) -{ - return (clock_time_t) millis(); -} diff --git a/libraries/UIPEthernet/utility/clock-arch.h b/libraries/UIPEthernet/utility/clock-arch.h deleted file mode 100644 index d7a828b..0000000 --- a/libraries/UIPEthernet/utility/clock-arch.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - clock-arch.h - Arduino implementation of uIP clock device. - Copyright (c) 2010 Adam Nielsen - All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef clock_h_ -#define clock_h_ - -typedef unsigned long clock_time_t; -#define CLOCK_CONF_SECOND 1000 - -#endif diff --git a/libraries/UIPEthernet/utility/enc28j60.h b/libraries/UIPEthernet/utility/enc28j60.h deleted file mode 100644 index 3a45c59..0000000 --- a/libraries/UIPEthernet/utility/enc28j60.h +++ /dev/null @@ -1,257 +0,0 @@ -/***************************************************************************** -* -* Title : Microchip ENC28J60 Ethernet Interface Driver -* Author : Pascal Stang (c)2005 -* Modified by Norbert Truchsess -* Copyright: GPL V2 -* -*This driver provides initialization and transmit/receive -*functions for the Microchip ENC28J60 10Mb Ethernet Controller and PHY. -*This chip is novel in that it is a full MAC+PHY interface all in a 28-pin -*chip, using an SPI interface to the host processor. -* -* -*****************************************************************************/ - -#ifndef ENC28J60_H -#define ENC28J60_H -#include - -// ENC28J60 Control Registers -// Control register definitions are a combination of address, -// bank number, and Ethernet/MAC/PHY indicator bits. -// - Register address (bits 0-4) -// - Bank number (bits 5-6) -// - MAC/PHY indicator (bit 7) -#define ADDR_MASK 0x1F -#define BANK_MASK 0x60 -#define SPRD_MASK 0x80 -// All-bank registers -#define EIE 0x1B -#define EIR 0x1C -#define ESTAT 0x1D -#define ECON2 0x1E -#define ECON1 0x1F -// Bank 0 registers -#define ERDPTL (0x00|0x00) -#define ERDPTH (0x01|0x00) -#define EWRPTL (0x02|0x00) -#define EWRPTH (0x03|0x00) -#define ETXSTL (0x04|0x00) -#define ETXSTH (0x05|0x00) -#define ETXNDL (0x06|0x00) -#define ETXNDH (0x07|0x00) -#define ERXSTL (0x08|0x00) -#define ERXSTH (0x09|0x00) -#define ERXNDL (0x0A|0x00) -#define ERXNDH (0x0B|0x00) -#define ERXRDPTL (0x0C|0x00) -#define ERXRDPTH (0x0D|0x00) -#define ERXWRPTL (0x0E|0x00) -#define ERXWRPTH (0x0F|0x00) -#define EDMASTL (0x10|0x00) -#define EDMASTH (0x11|0x00) -#define EDMANDL (0x12|0x00) -#define EDMANDH (0x13|0x00) -#define EDMADSTL (0x14|0x00) -#define EDMADSTH (0x15|0x00) -#define EDMACSL (0x16|0x00) -#define EDMACSH (0x17|0x00) -// Bank 1 registers -#define EHT0 (0x00|0x20) -#define EHT1 (0x01|0x20) -#define EHT2 (0x02|0x20) -#define EHT3 (0x03|0x20) -#define EHT4 (0x04|0x20) -#define EHT5 (0x05|0x20) -#define EHT6 (0x06|0x20) -#define EHT7 (0x07|0x20) -#define EPMM0 (0x08|0x20) -#define EPMM1 (0x09|0x20) -#define EPMM2 (0x0A|0x20) -#define EPMM3 (0x0B|0x20) -#define EPMM4 (0x0C|0x20) -#define EPMM5 (0x0D|0x20) -#define EPMM6 (0x0E|0x20) -#define EPMM7 (0x0F|0x20) -#define EPMCSL (0x10|0x20) -#define EPMCSH (0x11|0x20) -#define EPMOL (0x14|0x20) -#define EPMOH (0x15|0x20) -#define EWOLIE (0x16|0x20) -#define EWOLIR (0x17|0x20) -#define ERXFCON (0x18|0x20) -#define EPKTCNT (0x19|0x20) -// Bank 2 registers -#define MACON1 (0x00|0x40|0x80) -#define MACON2 (0x01|0x40|0x80) -#define MACON3 (0x02|0x40|0x80) -#define MACON4 (0x03|0x40|0x80) -#define MABBIPG (0x04|0x40|0x80) -#define MAIPGL (0x06|0x40|0x80) -#define MAIPGH (0x07|0x40|0x80) -#define MACLCON1 (0x08|0x40|0x80) -#define MACLCON2 (0x09|0x40|0x80) -#define MAMXFLL (0x0A|0x40|0x80) -#define MAMXFLH (0x0B|0x40|0x80) -#define MAPHSUP (0x0D|0x40|0x80) -#define MICON (0x11|0x40|0x80) -#define MICMD (0x12|0x40|0x80) -#define MIREGADR (0x14|0x40|0x80) -#define MIWRL (0x16|0x40|0x80) -#define MIWRH (0x17|0x40|0x80) -#define MIRDL (0x18|0x40|0x80) -#define MIRDH (0x19|0x40|0x80) -// Bank 3 registers -#define MAADR1 (0x00|0x60|0x80) -#define MAADR0 (0x01|0x60|0x80) -#define MAADR3 (0x02|0x60|0x80) -#define MAADR2 (0x03|0x60|0x80) -#define MAADR5 (0x04|0x60|0x80) -#define MAADR4 (0x05|0x60|0x80) -#define EBSTSD (0x06|0x60) -#define EBSTCON (0x07|0x60) -#define EBSTCSL (0x08|0x60) -#define EBSTCSH (0x09|0x60) -#define MISTAT (0x0A|0x60|0x80) -#define EREVID (0x12|0x60) -#define ECOCON (0x15|0x60) -#define EFLOCON (0x17|0x60) -#define EPAUSL (0x18|0x60) -#define EPAUSH (0x19|0x60) -// PHY registers -#define PHCON1 0x00 -#define PHSTAT1 0x01 -#define PHHID1 0x02 -#define PHHID2 0x03 -#define PHCON2 0x10 -#define PHSTAT2 0x11 -#define PHIE 0x12 -#define PHIR 0x13 -#define PHLCON 0x14 - -// ENC28J60 ERXFCON Register Bit Definitions -#define ERXFCON_UCEN 0x80 -#define ERXFCON_ANDOR 0x40 -#define ERXFCON_CRCEN 0x20 -#define ERXFCON_PMEN 0x10 -#define ERXFCON_MPEN 0x08 -#define ERXFCON_HTEN 0x04 -#define ERXFCON_MCEN 0x02 -#define ERXFCON_BCEN 0x01 -// ENC28J60 EIE Register Bit Definitions -#define EIE_INTIE 0x80 -#define EIE_PKTIE 0x40 -#define EIE_DMAIE 0x20 -#define EIE_LINKIE 0x10 -#define EIE_TXIE 0x08 -#define EIE_WOLIE 0x04 -#define EIE_TXERIE 0x02 -#define EIE_RXERIE 0x01 -// ENC28J60 EIR Register Bit Definitions -#define EIR_PKTIF 0x40 -#define EIR_DMAIF 0x20 -#define EIR_LINKIF 0x10 -#define EIR_TXIF 0x08 -#define EIR_WOLIF 0x04 -#define EIR_TXERIF 0x02 -#define EIR_RXERIF 0x01 -// ENC28J60 ESTAT Register Bit Definitions -#define ESTAT_INT 0x80 -#define ESTAT_LATECOL 0x10 -#define ESTAT_RXBUSY 0x04 -#define ESTAT_TXABRT 0x02 -#define ESTAT_CLKRDY 0x01 -// ENC28J60 ECON2 Register Bit Definitions -#define ECON2_AUTOINC 0x80 -#define ECON2_PKTDEC 0x40 -#define ECON2_PWRSV 0x20 -#define ECON2_VRPS 0x08 -// ENC28J60 ECON1 Register Bit Definitions -#define ECON1_TXRST 0x80 -#define ECON1_RXRST 0x40 -#define ECON1_DMAST 0x20 -#define ECON1_CSUMEN 0x10 -#define ECON1_TXRTS 0x08 -#define ECON1_RXEN 0x04 -#define ECON1_BSEL1 0x02 -#define ECON1_BSEL0 0x01 -// ENC28J60 MACON1 Register Bit Definitions -#define MACON1_LOOPBK 0x10 -#define MACON1_TXPAUS 0x08 -#define MACON1_RXPAUS 0x04 -#define MACON1_PASSALL 0x02 -#define MACON1_MARXEN 0x01 -// ENC28J60 MACON2 Register Bit Definitions -#define MACON2_MARST 0x80 -#define MACON2_RNDRST 0x40 -#define MACON2_MARXRST 0x08 -#define MACON2_RFUNRST 0x04 -#define MACON2_MATXRST 0x02 -#define MACON2_TFUNRST 0x01 -// ENC28J60 MACON3 Register Bit Definitions -#define MACON3_PADCFG2 0x80 -#define MACON3_PADCFG1 0x40 -#define MACON3_PADCFG0 0x20 -#define MACON3_TXCRCEN 0x10 -#define MACON3_PHDRLEN 0x08 -#define MACON3_HFRMLEN 0x04 -#define MACON3_FRMLNEN 0x02 -#define MACON3_FULDPX 0x01 -// ENC28J60 MICMD Register Bit Definitions -#define MICMD_MIISCAN 0x02 -#define MICMD_MIIRD 0x01 -// ENC28J60 MISTAT Register Bit Definitions -#define MISTAT_NVALID 0x04 -#define MISTAT_SCAN 0x02 -#define MISTAT_BUSY 0x01 -// ENC28J60 PHY PHCON1 Register Bit Definitions -#define PHCON1_PRST 0x8000 -#define PHCON1_PLOOPBK 0x4000 -#define PHCON1_PPWRSV 0x0800 -#define PHCON1_PDPXMD 0x0100 -// ENC28J60 PHY PHSTAT1 Register Bit Definitions -#define PHSTAT1_PFDPX 0x1000 -#define PHSTAT1_PHDPX 0x0800 -#define PHSTAT1_LLSTAT 0x0004 -#define PHSTAT1_JBSTAT 0x0002 -// ENC28J60 PHY PHCON2 Register Bit Definitions -#define PHCON2_FRCLINK 0x4000 -#define PHCON2_TXDIS 0x2000 -#define PHCON2_JABBER 0x0400 -#define PHCON2_HDLDIS 0x0100 - -// ENC28J60 Packet Control Byte Bit Definitions -#define PKTCTRL_PHUGEEN 0x08 -#define PKTCTRL_PPADEN 0x04 -#define PKTCTRL_PCRCEN 0x02 -#define PKTCTRL_POVERRIDE 0x01 - -// SPI operation codes -#define ENC28J60_READ_CTRL_REG 0x00 -#define ENC28J60_READ_BUF_MEM 0x3A -#define ENC28J60_WRITE_CTRL_REG 0x40 -#define ENC28J60_WRITE_BUF_MEM 0x7A -#define ENC28J60_BIT_FIELD_SET 0x80 -#define ENC28J60_BIT_FIELD_CLR 0xA0 -#define ENC28J60_SOFT_RESET 0xFF - - -// The RXSTART_INIT should be zero. See Rev. B4 Silicon Errata -// buffer boundaries applied to internal 8K ram -// the entire available packet buffer space is allocated -// -// start with recbuf at 0/ -#define RXSTART_INIT 0x0 -// receive buffer end. make sure this is an odd value ( See Rev. B1,B4,B5,B7 Silicon Errata 'Memory (Ethernet Buffer)') -#define RXSTOP_INIT (0x1FFF-0x1800) -// start TX buffer RXSTOP_INIT+1 -#define TXSTART_INIT (RXSTOP_INIT+1) -// stp TX buffer at end of mem -#define TXSTOP_INIT 0x1FFF -// -// max frame length which the conroller will accept: -#define MAX_FRAMELEN 1500 // (note: maximum ethernet frame length would be 1518) -//#define MAX_FRAMELEN 600 - -#endif diff --git a/libraries/UIPEthernet/utility/mempool.cpp b/libraries/UIPEthernet/utility/mempool.cpp deleted file mode 100644 index 01f17fb..0000000 --- a/libraries/UIPEthernet/utility/mempool.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/* - mempool.cpp - sleek implementation of a memory pool - Copyright (c) 2013 Norbert Truchsess - All rights reserved. - - 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 . - */ - -#include "mempool.h" -#include - -#define POOLOFFSET 1 - -MemoryPool::MemoryPool(memaddress start, memaddress size) -{ - memset(&blocks[0], 0, sizeof(blocks)); - blocks[POOLSTART].begin = start; - blocks[POOLSTART].size = 0; - blocks[POOLSTART].nextblock = NOBLOCK; - poolsize = size; -} - -memhandle -MemoryPool::allocBlock(memaddress size) -{ - memblock* best = NULL; - memhandle cur = POOLSTART; - memblock* block = &blocks[POOLSTART]; - memaddress bestsize = poolsize + 1; - - do - { - memhandle next = block->nextblock; - memaddress freesize = ( next == NOBLOCK ? blocks[POOLSTART].begin + poolsize : blocks[next].begin) - block->begin - block->size; - if (freesize == size) - { - best = &blocks[cur]; - goto found; - } - if (freesize > size && freesize < bestsize) - { - bestsize = freesize; - best = &blocks[cur]; - } - if (next == NOBLOCK) - { - if (best) - goto found; - else - goto collect; - } - block = &blocks[next]; - cur = next; - } - while (true); - - collect: - { - cur = POOLSTART; - block = &blocks[POOLSTART]; - memhandle next; - while ((next = block->nextblock) != NOBLOCK) - { - memaddress dest = block->begin + block->size; - memblock* nextblock = &blocks[next]; - memaddress* src = &nextblock->begin; - if (dest != *src) - { -#ifdef MEMBLOCK_MV - memblock_mv_cb(dest,*src,nextblock->size); -#endif - *src = dest; - } - block = nextblock; - } - if (blocks[POOLSTART].begin + poolsize - block->begin - block->size >= size) - best = block; - else - goto notfound; - } - - found: - { - block = &blocks[POOLOFFSET]; - for (cur = POOLOFFSET; cur < NUM_MEMBLOCKS + POOLOFFSET; cur++) - { - if (block->size) - { - block++; - continue; - } - memaddress address = best->begin + best->size; -#ifdef MEMBLOCK_ALLOC - MEMBLOCK_ALLOC(address,size); -#endif - block->begin = address; - block->size = size; - block->nextblock = best->nextblock; - best->nextblock = cur; - return cur; - } - } - - notfound: return NOBLOCK; -} - -void -MemoryPool::freeBlock(memhandle handle) -{ - memblock *b = &blocks[POOLSTART]; - - do - { - memhandle next = b->nextblock; - if (next == handle) - { - memblock *f = &blocks[next]; -#ifdef MEMBLOCK_FREE - MEMBLOCK_FREE(f->begin,f->size); -#endif - b->nextblock = f->nextblock; - f->size = 0; - f->nextblock = NOBLOCK; - return; - } - if (next == NOBLOCK) - return; - b = &blocks[next]; - } - while (true); -} - -void -MemoryPool::resizeBlock(memhandle handle, memaddress position) -{ - memblock * block = &blocks[handle]; - block->begin += position; - block->size -= position; -} - -void -MemoryPool::resizeBlock(memhandle handle, memaddress position, memaddress size) -{ - memblock * block = &blocks[handle]; - block->begin += position; - block->size = size; -} - -memaddress -MemoryPool::blockSize(memhandle handle) -{ - return blocks[handle].size; -} diff --git a/libraries/UIPEthernet/utility/mempool.h b/libraries/UIPEthernet/utility/mempool.h deleted file mode 100644 index ea79473..0000000 --- a/libraries/UIPEthernet/utility/mempool.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - mempool.h - sleek implementation of a memory pool - Copyright (c) 2013 Norbert Truchsess - All rights reserved. - - 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 . - */ - -#ifndef MEMPOOL_H -#define MEMPOOL_H - -#include - -#define POOLSTART 0 -#define NOBLOCK 0 - -#include "mempool_conf.h" - -//#ifdef MEMBLOCK_MV -//#define memblock_mv_cb(dest,src,size) MEMBLOCK_MV(dest,src,size) -//#endif - -#ifdef MEMBLOCK_ALLOC -#define memblock_alloc_cb(address,size) MEMBLOCK_ALLOC(address,size) -#endif - -#ifdef MEMBLOCK_FREE -#define memblock_free_cb(address,size) MEMBLOCK_FREE(address,size) -#endif - -struct memblock -{ - memaddress begin; - memaddress size; - memhandle nextblock; -}; - -class MemoryPool -{ -#ifdef MEMPOOLTEST_H - friend class MemoryPoolTest; -#endif - -protected: - memaddress poolsize; - struct memblock blocks[NUM_MEMBLOCKS+1]; -#ifdef MEMBLOCK_MV - virtual void memblock_mv_cb(memaddress dest, memaddress src, memaddress size) = 0; -#endif - -public: - MemoryPool(memaddress start, memaddress size); - memhandle - allocBlock(memaddress); - void freeBlock(memhandle); - void resizeBlock(memhandle handle, memaddress position); - void resizeBlock(memhandle handle, memaddress position, memaddress size); - memaddress blockSize(memhandle); -}; -#endif diff --git a/libraries/UIPEthernet/utility/mempool_conf.h b/libraries/UIPEthernet/utility/mempool_conf.h deleted file mode 100644 index bd5a726..0000000 --- a/libraries/UIPEthernet/utility/mempool_conf.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef MEMPOOLCONF_H -#define MEMPOOLCONF_H -#include "uipethernet-conf.h" -extern "C" { - #include "uipopt.h" -} -#include - -typedef uint16_t memaddress; -typedef uint8_t memhandle; - -#if UIP_SOCKET_NUMPACKETS and UIP_CONNS -#define NUM_TCP_MEMBLOCKS (UIP_SOCKET_NUMPACKETS*2)*UIP_CONNS -#else -#define NUM_TCP_MEMBLOCKS 0 -#endif - -#if UIP_UDP and UIP_UDP_NUMPACKETS and UIP_UDP_CONNS -#define NUM_UDP_MEMBLOCKS (UIP_UDP_NUMPACKETS+1)*UIP_UDP_CONNS -#else -#define NUM_UDP_MEMBLOCKS 0 -#endif - -#define NUM_MEMBLOCKS (NUM_TCP_MEMBLOCKS+NUM_UDP_MEMBLOCKS) - -#define MEMBLOCK_MV - -#endif diff --git a/libraries/UIPEthernet/utility/uip-conf.h b/libraries/UIPEthernet/utility/uip-conf.h deleted file mode 100644 index 814aeb9..0000000 --- a/libraries/UIPEthernet/utility/uip-conf.h +++ /dev/null @@ -1,185 +0,0 @@ -/** - * UIPEthernet Project-specific configuration options - * Copyright (c) 2013 Norbert Truchsess - * @{ - * - * uIP has a number of configuration options that can be overridden - * for each project. These are kept in a project-specific uip-conf.h - * file and all configuration names have the prefix UIP_CONF. - */ - -/* - * Copyright (c) 2006, Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the Institute nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * This file is part of the uIP TCP/IP stack - * - */ - -#ifndef __UIP_CONF_H__ -#define __UIP_CONF_H__ - -#include -#include "uipethernet-conf.h" - -/** - * 8 bit datatype - * - * This typedef defines the 8-bit type used throughout uIP. - * - * \hideinitializer - */ -typedef uint8_t u8_t; - -/** - * 16 bit datatype - * - * This typedef defines the 16-bit type used throughout uIP. - * - * \hideinitializer - */ -typedef uint16_t u16_t; - -/** - * Statistics datatype - * - * This typedef defines the dataype used for keeping statistics in - * uIP. - * - * \hideinitializer - */ -typedef unsigned short uip_stats_t; - -/** - * Maximum number of TCP connections. - * (see uipethernet-conf.h) - * \hideinitializer - * - * #define UIP_CONF_MAX_CONNECTIONS 4 - */ - -/** - * Maximum number of listening TCP ports. - * - * \hideinitializer - */ -#define UIP_CONF_MAX_LISTENPORTS 4 - -/** - * uIP buffer size. - * - * \hideinitializer - */ -#define UIP_CONF_BUFFER_SIZE 98 -//#define UIP_CONF_BUFFER_SIZE 118 - -/** - * The TCP maximum segment size. - * - * This is should not be to set to more than - * UIP_BUFSIZE - UIP_LLH_LEN - UIP_TCPIP_HLEN. - */ - -#define UIP_CONF_TCP_MSS 512 - -/** - * The size of the advertised receiver's window. - * - * Should be set low (i.e., to the size of the uip_buf buffer) is the - * application is slow to process incoming data, or high (32768 bytes) - * if the application processes data quickly. - * - * \hideinitializer - */ -#define UIP_CONF_RECEIVE_WINDOW 512 - -/** - * CPU byte order. - * - * \hideinitializer - */ -#define UIP_CONF_BYTE_ORDER LITTLE_ENDIAN - -/** - * Logging on or off - * - * \hideinitializer - */ -#define UIP_CONF_LOGGING 0 - -/** - * UDP support on or off - * (see uipethernet-conf.h) - * \hideinitializer - * - * #define UIP_CONF_UDP 1 - * - * #define UIP_CONF_UDP_CONNS 4 - */ - -/** - * UDP checksums on or off - * - * \hideinitializer - */ -#define UIP_CONF_UDP_CHECKSUMS 1 - -/** - * UDP Broadcast (receive) on or off - * (see uipethernet-conf.h) - * \hideinitializer - * #define UIP_CONF_BROADCAST 1 - */ - - -/** - * uIP statistics on or off - * - * \hideinitializer - */ -#define UIP_CONF_STATISTICS 0 - -// SLIP -//#define UIP_CONF_LLH_LEN 0 - -typedef void* uip_tcp_appstate_t; - -void uipclient_appcall(void); - -#define UIP_APPCALL uipclient_appcall - -typedef void* uip_udp_appstate_t; - -void uipudp_appcall(void); - -#define UIP_UDP_APPCALL uipudp_appcall - -#define CC_REGISTER_ARG register - -#define UIP_ARCH_CHKSUM 1 - -#endif /* __UIP_CONF_H__ */ diff --git a/libraries/UIPEthernet/utility/uip-neighbor.c b/libraries/UIPEthernet/utility/uip-neighbor.c deleted file mode 100644 index 739c03e..0000000 --- a/libraries/UIPEthernet/utility/uip-neighbor.c +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright (c) 2006, Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the Institute nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * This file is part of the uIP TCP/IP stack - * - * $Id: uip-neighbor.c,v 1.2 2006/06/12 08:00:30 adam Exp $ - */ - -/** - * \file - * Database of link-local neighbors, used by IPv6 code and - * to be used by a future ARP code rewrite. - * \author - * Adam Dunkels - */ - -#include "uip-neighbor.h" - -#include - -#define MAX_TIME 128 - -#ifdef UIP_NEIGHBOR_CONF_ENTRIES -#define ENTRIES UIP_NEIGHBOR_CONF_ENTRIES -#else /* UIP_NEIGHBOR_CONF_ENTRIES */ -#define ENTRIES 8 -#endif /* UIP_NEIGHBOR_CONF_ENTRIES */ - -struct neighbor_entry { - uip_ipaddr_t ipaddr; - struct uip_neighbor_addr addr; - u8_t time; -}; -static struct neighbor_entry entries[ENTRIES]; - -/*---------------------------------------------------------------------------*/ -void -uip_neighbor_init(void) -{ - int i; - - for(i = 0; i < ENTRIES; ++i) { - entries[i].time = MAX_TIME; - } -} -/*---------------------------------------------------------------------------*/ -void -uip_neighbor_periodic(void) -{ - int i; - - for(i = 0; i < ENTRIES; ++i) { - if(entries[i].time < MAX_TIME) { - entries[i].time++; - } - } -} -/*---------------------------------------------------------------------------*/ -void -uip_neighbor_add(uip_ipaddr_t ipaddr, struct uip_neighbor_addr *addr) -{ - int i, oldest; - u8_t oldest_time; - - printf("Adding neighbor with link address %02x:%02x:%02x:%02x:%02x:%02x\n", - addr->addr.addr[0], addr->addr.addr[1], addr->addr.addr[2], addr->addr.addr[3], - addr->addr.addr[4], addr->addr.addr[5]); - - /* Find the first unused entry or the oldest used entry. */ - oldest_time = 0; - oldest = 0; - for(i = 0; i < ENTRIES; ++i) { - if(entries[i].time == MAX_TIME) { - oldest = i; - break; - } - if(uip_ipaddr_cmp(entries[i].ipaddr, addr)) { - oldest = i; - break; - } - if(entries[i].time > oldest_time) { - oldest = i; - oldest_time = entries[i].time; - } - } - - /* Use the oldest or first free entry (either pointed to by the - "oldest" variable). */ - entries[oldest].time = 0; - uip_ipaddr_copy(entries[oldest].ipaddr, ipaddr); - memcpy(&entries[oldest].addr, addr, sizeof(struct uip_neighbor_addr)); -} -/*---------------------------------------------------------------------------*/ -static struct neighbor_entry * -find_entry(uip_ipaddr_t ipaddr) -{ - int i; - - for(i = 0; i < ENTRIES; ++i) { - if(uip_ipaddr_cmp(entries[i].ipaddr, ipaddr)) { - return &entries[i]; - } - } - return NULL; -} -/*---------------------------------------------------------------------------*/ -void -uip_neighbor_update(uip_ipaddr_t ipaddr) -{ - struct neighbor_entry *e; - - e = find_entry(ipaddr); - if(e != NULL) { - e->time = 0; - } -} -/*---------------------------------------------------------------------------*/ -struct uip_neighbor_addr * -uip_neighbor_lookup(uip_ipaddr_t ipaddr) -{ - struct neighbor_entry *e; - - e = find_entry(ipaddr); - if(e != NULL) { - /* printf("Lookup neighbor with link address %02x:%02x:%02x:%02x:%02x:%02x\n", - e->addr.addr.addr[0], e->addr.addr.addr[1], e->addr.addr.addr[2], e->addr.addr.addr[3], - e->addr.addr.addr[4], e->addr.addr.addr[5]);*/ - - return &e->addr; - } - return NULL; -} -/*---------------------------------------------------------------------------*/ diff --git a/libraries/UIPEthernet/utility/uip-neighbor.h b/libraries/UIPEthernet/utility/uip-neighbor.h deleted file mode 100644 index d3b351c..0000000 --- a/libraries/UIPEthernet/utility/uip-neighbor.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2006, Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the Institute nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * This file is part of the uIP TCP/IP stack - * - * $Id: uip-neighbor.h,v 1.2 2006/06/12 08:00:30 adam Exp $ - */ - -/** - * \file - * Header file for database of link-local neighbors, used by - * IPv6 code and to be used by future ARP code. - * \author - * Adam Dunkels - */ - -#ifndef __UIP_NEIGHBOR_H__ -#define __UIP_NEIGHBOR_H__ - -#include "uip.h" - -struct uip_neighbor_addr { -#if UIP_NEIGHBOR_CONF_ADDRTYPE - UIP_NEIGHBOR_CONF_ADDRTYPE addr; -#else - struct uip_eth_addr addr; -#endif -}; - -void uip_neighbor_init(void); -void uip_neighbor_add(uip_ipaddr_t ipaddr, struct uip_neighbor_addr *addr); -void uip_neighbor_update(uip_ipaddr_t ipaddr); -struct uip_neighbor_addr *uip_neighbor_lookup(uip_ipaddr_t ipaddr); -void uip_neighbor_periodic(void); - -#endif /* __UIP-NEIGHBOR_H__ */ diff --git a/libraries/UIPEthernet/utility/uip.c b/libraries/UIPEthernet/utility/uip.c deleted file mode 100644 index 84ea8c3..0000000 --- a/libraries/UIPEthernet/utility/uip.c +++ /dev/null @@ -1,1897 +0,0 @@ -#define DEBUG_PRINTF(...) /*printf(__VA_ARGS__)*/ - -/** - * \defgroup uip The uIP TCP/IP stack - * @{ - * - * uIP is an implementation of the TCP/IP protocol stack intended for - * small 8-bit and 16-bit microcontrollers. - * - * uIP provides the necessary protocols for Internet communication, - * with a very small code footprint and RAM requirements - the uIP - * code size is on the order of a few kilobytes and RAM usage is on - * the order of a few hundred bytes. - */ - -/** - * \file - * The uIP TCP/IP stack code. - * \author Adam Dunkels - */ - -/* - * Copyright (c) 2001-2003, Adam Dunkels. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote - * products derived from this software without specific prior - * written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS - * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * This file is part of the uIP TCP/IP stack. - * - * $Id: uip.c,v 1.65 2006/06/11 21:46:39 adam Exp $ - * - */ - -/* - * uIP is a small implementation of the IP, UDP and TCP protocols (as - * well as some basic ICMP stuff). The implementation couples the IP, - * UDP, TCP and the application layers very tightly. To keep the size - * of the compiled code down, this code frequently uses the goto - * statement. While it would be possible to break the uip_process() - * function into many smaller functions, this would increase the code - * size because of the overhead of parameter passing and the fact that - * the optimier would not be as efficient. - * - * The principle is that we have a small buffer, called the uip_buf, - * in which the device driver puts an incoming packet. The TCP/IP - * stack parses the headers in the packet, and calls the - * application. If the remote host has sent data to the application, - * this data is present in the uip_buf and the application read the - * data from there. It is up to the application to put this data into - * a byte stream if needed. The application will not be fed with data - * that is out of sequence. - * - * If the application whishes to send data to the peer, it should put - * its data into the uip_buf. The uip_appdata pointer points to the - * first available byte. The TCP/IP stack will calculate the - * checksums, and fill in the necessary header fields and finally send - * the packet back to the peer. -*/ - -#include "uip.h" -#include "uipopt.h" -#include "uip_arch.h" - -#if UIP_CONF_IPV6 -#include "uip-neighbor.h" -#endif /* UIP_CONF_IPV6 */ - -#include - -/*---------------------------------------------------------------------------*/ -/* Variable definitions. */ - - -/* The IP address of this host. If it is defined to be fixed (by - setting UIP_FIXEDADDR to 1 in uipopt.h), the address is set - here. Otherwise, the address */ -#if UIP_FIXEDADDR > 0 -const uip_ipaddr_t uip_hostaddr = - {HTONS((UIP_IPADDR0 << 8) | UIP_IPADDR1), - HTONS((UIP_IPADDR2 << 8) | UIP_IPADDR3)}; -const uip_ipaddr_t uip_draddr = - {HTONS((UIP_DRIPADDR0 << 8) | UIP_DRIPADDR1), - HTONS((UIP_DRIPADDR2 << 8) | UIP_DRIPADDR3)}; -const uip_ipaddr_t uip_netmask = - {HTONS((UIP_NETMASK0 << 8) | UIP_NETMASK1), - HTONS((UIP_NETMASK2 << 8) | UIP_NETMASK3)}; -#else -uip_ipaddr_t uip_hostaddr, uip_draddr, uip_netmask; -#endif /* UIP_FIXEDADDR */ - -static const uip_ipaddr_t all_ones_addr = -#if UIP_CONF_IPV6 - {0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff}; -#else /* UIP_CONF_IPV6 */ - {0xffff,0xffff}; -#endif /* UIP_CONF_IPV6 */ -static const uip_ipaddr_t all_zeroes_addr = -#if UIP_CONF_IPV6 - {0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000}; -#else /* UIP_CONF_IPV6 */ - {0x0000,0x0000}; -#endif /* UIP_CONF_IPV6 */ - - -#if UIP_FIXEDETHADDR -const struct uip_eth_addr uip_ethaddr = {{UIP_ETHADDR0, - UIP_ETHADDR1, - UIP_ETHADDR2, - UIP_ETHADDR3, - UIP_ETHADDR4, - UIP_ETHADDR5}}; -#else -struct uip_eth_addr uip_ethaddr = {{0,0,0,0,0,0}}; -#endif - -#ifndef UIP_CONF_EXTERNAL_BUFFER -u8_t uip_buf[UIP_BUFSIZE + 2]; /* The packet buffer that contains - incoming packets. */ -#endif /* UIP_CONF_EXTERNAL_BUFFER */ - -void *uip_appdata; /* The uip_appdata pointer points to - application data. */ -void *uip_sappdata; /* The uip_appdata pointer points to - the application data which is to - be sent. */ -#if UIP_URGDATA > 0 -void *uip_urgdata; /* The uip_urgdata pointer points to - urgent data (out-of-band data), if - present. */ -u16_t uip_urglen, uip_surglen; -#endif /* UIP_URGDATA > 0 */ - -u16_t uip_len, uip_slen; - /* The uip_len is either 8 or 16 bits, - depending on the maximum packet - size. */ - -u8_t uip_flags; /* The uip_flags variable is used for - communication between the TCP/IP stack - and the application program. */ -struct uip_conn *uip_conn; /* uip_conn always points to the current - connection. */ - -struct uip_conn uip_conns[UIP_CONNS]; - /* The uip_conns array holds all TCP - connections. */ -u16_t uip_listenports[UIP_LISTENPORTS]; - /* The uip_listenports list all currently - listning ports. */ -#if UIP_UDP -struct uip_udp_conn *uip_udp_conn; -struct uip_udp_conn uip_udp_conns[UIP_UDP_CONNS]; -#endif /* UIP_UDP */ - -static u16_t ipid; /* Ths ipid variable is an increasing - number that is used for the IP ID - field. */ - -void uip_setipid(u16_t id) { ipid = id; } - -static u8_t iss[4]; /* The iss variable is used for the TCP - initial sequence number. */ - -#if UIP_ACTIVE_OPEN -static u16_t lastport; /* Keeps track of the last port used for - a new connection. */ -#endif /* UIP_ACTIVE_OPEN */ - -/* Temporary variables. */ -u8_t uip_acc32[4]; -static u8_t c, opt; -static u16_t tmp16; - -/* Structures and definitions. */ -#define TCP_FIN 0x01 -#define TCP_SYN 0x02 -#define TCP_RST 0x04 -#define TCP_PSH 0x08 -#define TCP_ACK 0x10 -#define TCP_URG 0x20 -#define TCP_CTL 0x3f - -#define TCP_OPT_END 0 /* End of TCP options list */ -#define TCP_OPT_NOOP 1 /* "No-operation" TCP option */ -#define TCP_OPT_MSS 2 /* Maximum segment size TCP option */ - -#define TCP_OPT_MSS_LEN 4 /* Length of TCP MSS option. */ - -#define ICMP_ECHO_REPLY 0 -#define ICMP_ECHO 8 - -#define ICMP6_ECHO_REPLY 129 -#define ICMP6_ECHO 128 -#define ICMP6_NEIGHBOR_SOLICITATION 135 -#define ICMP6_NEIGHBOR_ADVERTISEMENT 136 - -#define ICMP6_FLAG_S (1 << 6) - -#define ICMP6_OPTION_SOURCE_LINK_ADDRESS 1 -#define ICMP6_OPTION_TARGET_LINK_ADDRESS 2 - - -/* Macros. */ -#define BUF ((struct uip_tcpip_hdr *)&uip_buf[UIP_LLH_LEN]) -#define FBUF ((struct uip_tcpip_hdr *)&uip_reassbuf[0]) -#define ICMPBUF ((struct uip_icmpip_hdr *)&uip_buf[UIP_LLH_LEN]) -#define UDPBUF ((struct uip_udpip_hdr *)&uip_buf[UIP_LLH_LEN]) - - -#if UIP_STATISTICS == 1 -struct uip_stats uip_stat; -#define UIP_STAT(s) s -#else -#define UIP_STAT(s) -#endif /* UIP_STATISTICS == 1 */ - -#if UIP_LOGGING == 1 -#include -void uip_log(char *msg); -#define UIP_LOG(m) uip_log(m) -#else -#define UIP_LOG(m) -#endif /* UIP_LOGGING == 1 */ - -#if ! UIP_ARCH_ADD32 -void -uip_add32(u8_t *op32, u16_t op16) -{ - uip_acc32[3] = op32[3] + (op16 & 0xff); - uip_acc32[2] = op32[2] + (op16 >> 8); - uip_acc32[1] = op32[1]; - uip_acc32[0] = op32[0]; - - if(uip_acc32[2] < (op16 >> 8)) { - ++uip_acc32[1]; - if(uip_acc32[1] == 0) { - ++uip_acc32[0]; - } - } - - - if(uip_acc32[3] < (op16 & 0xff)) { - ++uip_acc32[2]; - if(uip_acc32[2] == 0) { - ++uip_acc32[1]; - if(uip_acc32[1] == 0) { - ++uip_acc32[0]; - } - } - } -} - -#endif /* UIP_ARCH_ADD32 */ - -#if ! UIP_ARCH_CHKSUM -/*---------------------------------------------------------------------------*/ -static u16_t -chksum(u16_t sum, const u8_t *data, u16_t len) -{ - u16_t t; - const u8_t *dataptr; - const u8_t *last_byte; - - dataptr = data; - last_byte = data + len - 1; - - while(dataptr < last_byte) { /* At least two more bytes */ - t = (dataptr[0] << 8) + dataptr[1]; - sum += t; - if(sum < t) { - sum++; /* carry */ - } - dataptr += 2; - } - - if(dataptr == last_byte) { - t = (dataptr[0] << 8) + 0; - sum += t; - if(sum < t) { - sum++; /* carry */ - } - } - - /* Return sum in host byte order. */ - return sum; -} -/*---------------------------------------------------------------------------*/ -u16_t -uip_chksum(u16_t *data, u16_t len) -{ - return htons(chksum(0, (u8_t *)data, len)); -} -/*---------------------------------------------------------------------------*/ -#ifndef UIP_ARCH_IPCHKSUM -u16_t -uip_ipchksum(void) -{ - u16_t sum; - - sum = chksum(0, &uip_buf[UIP_LLH_LEN], UIP_IPH_LEN); - DEBUG_PRINTF("uip_ipchksum: sum 0x%04x\n", sum); - return (sum == 0) ? 0xffff : htons(sum); -} -#endif -/*---------------------------------------------------------------------------*/ -static u16_t -upper_layer_chksum(u8_t proto) -{ - u16_t upper_layer_len; - u16_t sum; - -#if UIP_CONF_IPV6 - upper_layer_len = (((u16_t)(BUF->len[0]) << 8) + BUF->len[1]); -#else /* UIP_CONF_IPV6 */ - upper_layer_len = (((u16_t)(BUF->len[0]) << 8) + BUF->len[1]) - UIP_IPH_LEN; -#endif /* UIP_CONF_IPV6 */ - - /* First sum pseudoheader. */ - - /* IP protocol and length fields. This addition cannot carry. */ - sum = upper_layer_len + proto; - /* Sum IP source and destination addresses. */ - sum = chksum(sum, (u8_t *)&BUF->srcipaddr[0], 2 * sizeof(uip_ipaddr_t)); - - /* Sum TCP header and data. */ - sum = chksum(sum, &uip_buf[UIP_IPH_LEN + UIP_LLH_LEN], - upper_layer_len); - - return (sum == 0) ? 0xffff : htons(sum); -} -/*---------------------------------------------------------------------------*/ -#if UIP_CONF_IPV6 -u16_t -uip_icmp6chksum(void) -{ - return upper_layer_chksum(UIP_PROTO_ICMP6); - -} -#endif /* UIP_CONF_IPV6 */ -/*---------------------------------------------------------------------------*/ -u16_t -uip_tcpchksum(void) -{ - return upper_layer_chksum(UIP_PROTO_TCP); -} -/*---------------------------------------------------------------------------*/ -#if UIP_UDP_CHECKSUMS -u16_t -uip_udpchksum(void) -{ - return upper_layer_chksum(UIP_PROTO_UDP); -} -#endif /* UIP_UDP_CHECKSUMS */ -#endif /* UIP_ARCH_CHKSUM */ -/*---------------------------------------------------------------------------*/ -void -uip_init(void) -{ - for(c = 0; c < UIP_LISTENPORTS; ++c) { - uip_listenports[c] = 0; - } - for(c = 0; c < UIP_CONNS; ++c) { - uip_conns[c].tcpstateflags = UIP_CLOSED; - } -#if UIP_ACTIVE_OPEN - lastport = 1024; -#endif /* UIP_ACTIVE_OPEN */ - -#if UIP_UDP - for(c = 0; c < UIP_UDP_CONNS; ++c) { - uip_udp_conns[c].lport = 0; - } -#endif /* UIP_UDP */ - - - /* IPv4 initialization. */ -#if UIP_FIXEDADDR == 0 - /* uip_hostaddr[0] = uip_hostaddr[1] = 0;*/ -#endif /* UIP_FIXEDADDR */ - -} -/*---------------------------------------------------------------------------*/ -#if UIP_ACTIVE_OPEN -struct uip_conn * -uip_connect(uip_ipaddr_t *ripaddr, u16_t rport) -{ - register struct uip_conn *conn, *cconn; - - /* Find an unused local port. */ - again: - ++lastport; - - if(lastport >= 32000) { - lastport = 4096; - } - - /* Check if this port is already in use, and if so try to find - another one. */ - for(c = 0; c < UIP_CONNS; ++c) { - conn = &uip_conns[c]; - if(conn->tcpstateflags != UIP_CLOSED && - conn->lport == htons(lastport)) { - goto again; - } - } - - conn = 0; - for(c = 0; c < UIP_CONNS; ++c) { - cconn = &uip_conns[c]; - if(cconn->tcpstateflags == UIP_CLOSED) { - conn = cconn; - break; - } - if(cconn->tcpstateflags == UIP_TIME_WAIT) { - if(conn == 0 || - cconn->timer > conn->timer) { - conn = cconn; - } - } - } - - if(conn == 0) { - return 0; - } - - conn->tcpstateflags = UIP_SYN_SENT; - - conn->snd_nxt[0] = iss[0]; - conn->snd_nxt[1] = iss[1]; - conn->snd_nxt[2] = iss[2]; - conn->snd_nxt[3] = iss[3]; - - conn->initialmss = conn->mss = UIP_TCP_MSS; - - conn->len = 1; /* TCP length of the SYN is one. */ - conn->nrtx = 0; - conn->timer = 1; /* Send the SYN next time around. */ - conn->rto = UIP_RTO; - conn->sa = 0; - conn->sv = 16; /* Initial value of the RTT variance. */ - conn->lport = htons(lastport); - conn->rport = rport; - uip_ipaddr_copy(&conn->ripaddr, ripaddr); - - return conn; -} -#endif /* UIP_ACTIVE_OPEN */ -/*---------------------------------------------------------------------------*/ -#if UIP_UDP -struct uip_udp_conn * -uip_udp_new(uip_ipaddr_t *ripaddr, u16_t rport) -{ - register struct uip_udp_conn *conn; - - /* Find an unused local port. */ - again: - ++lastport; - - if(lastport >= 32000) { - lastport = 4096; - } - - for(c = 0; c < UIP_UDP_CONNS; ++c) { - if(uip_udp_conns[c].lport == htons(lastport)) { - goto again; - } - } - - - conn = 0; - for(c = 0; c < UIP_UDP_CONNS; ++c) { - if(uip_udp_conns[c].lport == 0) { - conn = &uip_udp_conns[c]; - break; - } - } - - if(conn == 0) { - return 0; - } - - conn->lport = HTONS(lastport); - conn->rport = rport; - if(ripaddr == NULL) { - memset(conn->ripaddr, 0, sizeof(uip_ipaddr_t)); - } else { - uip_ipaddr_copy(&conn->ripaddr, ripaddr); - } - conn->ttl = UIP_TTL; - - return conn; -} -#endif /* UIP_UDP */ -/*---------------------------------------------------------------------------*/ -void -uip_unlisten(u16_t port) -{ - for(c = 0; c < UIP_LISTENPORTS; ++c) { - if(uip_listenports[c] == port) { - uip_listenports[c] = 0; - return; - } - } -} -/*---------------------------------------------------------------------------*/ -void -uip_listen(u16_t port) -{ - for(c = 0; c < UIP_LISTENPORTS; ++c) { - if(uip_listenports[c] == 0) { - uip_listenports[c] = port; - return; - } - } -} -/*---------------------------------------------------------------------------*/ -/* XXX: IP fragment reassembly: not well-tested. */ - -#if UIP_REASSEMBLY && !UIP_CONF_IPV6 -#define UIP_REASS_BUFSIZE (UIP_BUFSIZE - UIP_LLH_LEN) -static u8_t uip_reassbuf[UIP_REASS_BUFSIZE]; -static u8_t uip_reassbitmap[UIP_REASS_BUFSIZE / (8 * 8)]; -static const u8_t bitmap_bits[8] = {0xff, 0x7f, 0x3f, 0x1f, - 0x0f, 0x07, 0x03, 0x01}; -static u16_t uip_reasslen; -static u8_t uip_reassflags; -#define UIP_REASS_FLAG_LASTFRAG 0x01 -static u8_t uip_reasstmr; - -#define IP_MF 0x20 - -static u8_t -uip_reass(void) -{ - u16_t offset, len; - u16_t i; - - /* If ip_reasstmr is zero, no packet is present in the buffer, so we - write the IP header of the fragment into the reassembly - buffer. The timer is updated with the maximum age. */ - if(uip_reasstmr == 0) { - memcpy(uip_reassbuf, &BUF->vhl, UIP_IPH_LEN); - uip_reasstmr = UIP_REASS_MAXAGE; - uip_reassflags = 0; - /* Clear the bitmap. */ - memset(uip_reassbitmap, 0, sizeof(uip_reassbitmap)); - } - - /* Check if the incoming fragment matches the one currently present - in the reasembly buffer. If so, we proceed with copying the - fragment into the buffer. */ - if(BUF->srcipaddr[0] == FBUF->srcipaddr[0] && - BUF->srcipaddr[1] == FBUF->srcipaddr[1] && - BUF->destipaddr[0] == FBUF->destipaddr[0] && - BUF->destipaddr[1] == FBUF->destipaddr[1] && - BUF->ipid[0] == FBUF->ipid[0] && - BUF->ipid[1] == FBUF->ipid[1]) { - - len = (BUF->len[0] << 8) + BUF->len[1] - (BUF->vhl & 0x0f) * 4; - offset = (((BUF->ipoffset[0] & 0x3f) << 8) + BUF->ipoffset[1]) * 8; - - /* If the offset or the offset + fragment length overflows the - reassembly buffer, we discard the entire packet. */ - if(offset > UIP_REASS_BUFSIZE || - offset + len > UIP_REASS_BUFSIZE) { - uip_reasstmr = 0; - goto nullreturn; - } - - /* Copy the fragment into the reassembly buffer, at the right - offset. */ - memcpy(&uip_reassbuf[UIP_IPH_LEN + offset], - (char *)BUF + (int)((BUF->vhl & 0x0f) * 4), - len); - - /* Update the bitmap. */ - if(offset / (8 * 8) == (offset + len) / (8 * 8)) { - /* If the two endpoints are in the same byte, we only update - that byte. */ - - uip_reassbitmap[offset / (8 * 8)] |= - bitmap_bits[(offset / 8 ) & 7] & - ~bitmap_bits[((offset + len) / 8 ) & 7]; - } else { - /* If the two endpoints are in different bytes, we update the - bytes in the endpoints and fill the stuff inbetween with - 0xff. */ - uip_reassbitmap[offset / (8 * 8)] |= - bitmap_bits[(offset / 8 ) & 7]; - for(i = 1 + offset / (8 * 8); i < (offset + len) / (8 * 8); ++i) { - uip_reassbitmap[i] = 0xff; - } - uip_reassbitmap[(offset + len) / (8 * 8)] |= - ~bitmap_bits[((offset + len) / 8 ) & 7]; - } - - /* If this fragment has the More Fragments flag set to zero, we - know that this is the last fragment, so we can calculate the - size of the entire packet. We also set the - IP_REASS_FLAG_LASTFRAG flag to indicate that we have received - the final fragment. */ - - if((BUF->ipoffset[0] & IP_MF) == 0) { - uip_reassflags |= UIP_REASS_FLAG_LASTFRAG; - uip_reasslen = offset + len; - } - - /* Finally, we check if we have a full packet in the buffer. We do - this by checking if we have the last fragment and if all bits - in the bitmap are set. */ - if(uip_reassflags & UIP_REASS_FLAG_LASTFRAG) { - /* Check all bytes up to and including all but the last byte in - the bitmap. */ - for(i = 0; i < uip_reasslen / (8 * 8) - 1; ++i) { - if(uip_reassbitmap[i] != 0xff) { - goto nullreturn; - } - } - /* Check the last byte in the bitmap. It should contain just the - right amount of bits. */ - if(uip_reassbitmap[uip_reasslen / (8 * 8)] != - (u8_t)~bitmap_bits[uip_reasslen / 8 & 7]) { - goto nullreturn; - } - - /* If we have come this far, we have a full packet in the - buffer, so we allocate a pbuf and copy the packet into it. We - also reset the timer. */ - uip_reasstmr = 0; - memcpy(BUF, FBUF, uip_reasslen); - - /* Pretend to be a "normal" (i.e., not fragmented) IP packet - from now on. */ - BUF->ipoffset[0] = BUF->ipoffset[1] = 0; - BUF->len[0] = uip_reasslen >> 8; - BUF->len[1] = uip_reasslen & 0xff; - BUF->ipchksum = 0; - BUF->ipchksum = ~(uip_ipchksum()); - - return uip_reasslen; - } - } - - nullreturn: - return 0; -} -#endif /* UIP_REASSEMBLY */ -/*---------------------------------------------------------------------------*/ -static void -uip_add_rcv_nxt(u16_t n) -{ - uip_add32(uip_conn->rcv_nxt, n); - uip_conn->rcv_nxt[0] = uip_acc32[0]; - uip_conn->rcv_nxt[1] = uip_acc32[1]; - uip_conn->rcv_nxt[2] = uip_acc32[2]; - uip_conn->rcv_nxt[3] = uip_acc32[3]; -} -/*---------------------------------------------------------------------------*/ -void -uip_process(u8_t flag) -{ - register struct uip_conn *uip_connr = uip_conn; - -#if UIP_UDP - if(flag == UIP_UDP_SEND_CONN) { - goto udp_send; - } -#endif /* UIP_UDP */ - - uip_sappdata = uip_appdata = &uip_buf[UIP_IPTCPH_LEN + UIP_LLH_LEN]; - - /* Check if we were invoked because of a poll request for a - particular connection. */ - if(flag == UIP_POLL_REQUEST) { - if((uip_connr->tcpstateflags & UIP_TS_MASK) == UIP_ESTABLISHED && - !uip_outstanding(uip_connr)) { - uip_flags = UIP_POLL; - UIP_APPCALL(); - goto appsend; - } - goto drop; - - /* Check if we were invoked because of the perodic timer fireing. */ - } else if(flag == UIP_TIMER) { -#if UIP_REASSEMBLY - if(uip_reasstmr != 0) { - --uip_reasstmr; - } -#endif /* UIP_REASSEMBLY */ - /* Increase the initial sequence number. */ - if(++iss[3] == 0) { - if(++iss[2] == 0) { - if(++iss[1] == 0) { - ++iss[0]; - } - } - } - - /* Reset the length variables. */ - uip_len = 0; - uip_slen = 0; - - /* Check if the connection is in a state in which we simply wait - for the connection to time out. If so, we increase the - connection's timer and remove the connection if it times - out. */ - if(uip_connr->tcpstateflags == UIP_TIME_WAIT || - uip_connr->tcpstateflags == UIP_FIN_WAIT_2) { - ++(uip_connr->timer); - if(uip_connr->timer == UIP_TIME_WAIT_TIMEOUT) { - uip_connr->tcpstateflags = UIP_CLOSED; - } - } else if(uip_connr->tcpstateflags != UIP_CLOSED) { - /* If the connection has outstanding data, we increase the - connection's timer and see if it has reached the RTO value - in which case we retransmit. */ - if(uip_outstanding(uip_connr)) { - if(uip_connr->timer-- == 0) { - if(uip_connr->nrtx == UIP_MAXRTX || - ((uip_connr->tcpstateflags == UIP_SYN_SENT || - uip_connr->tcpstateflags == UIP_SYN_RCVD) && - uip_connr->nrtx == UIP_MAXSYNRTX)) { - uip_connr->tcpstateflags = UIP_CLOSED; - - /* We call UIP_APPCALL() with uip_flags set to - UIP_TIMEDOUT to inform the application that the - connection has timed out. */ - uip_flags = UIP_TIMEDOUT; - UIP_APPCALL(); - - /* We also send a reset packet to the remote host. */ - BUF->flags = TCP_RST | TCP_ACK; - goto tcp_send_nodata; - } - - /* Exponential backoff. */ - uip_connr->timer = UIP_RTO << (uip_connr->nrtx > 4? - 4: - uip_connr->nrtx); - ++(uip_connr->nrtx); - - /* Ok, so we need to retransmit. We do this differently - depending on which state we are in. In ESTABLISHED, we - call upon the application so that it may prepare the - data for the retransmit. In SYN_RCVD, we resend the - SYNACK that we sent earlier and in LAST_ACK we have to - retransmit our FINACK. */ - UIP_STAT(++uip_stat.tcp.rexmit); - switch(uip_connr->tcpstateflags & UIP_TS_MASK) { - case UIP_SYN_RCVD: - /* In the SYN_RCVD state, we should retransmit our - SYNACK. */ - goto tcp_send_synack; - -#if UIP_ACTIVE_OPEN - case UIP_SYN_SENT: - /* In the SYN_SENT state, we retransmit out SYN. */ - BUF->flags = 0; - goto tcp_send_syn; -#endif /* UIP_ACTIVE_OPEN */ - - case UIP_ESTABLISHED: - /* In the ESTABLISHED state, we call upon the application - to do the actual retransmit after which we jump into - the code for sending out the packet (the apprexmit - label). */ - uip_flags = UIP_REXMIT; - UIP_APPCALL(); - goto apprexmit; - - case UIP_FIN_WAIT_1: - case UIP_CLOSING: - case UIP_LAST_ACK: - /* In all these states we should retransmit a FINACK. */ - goto tcp_send_finack; - - } - } - } else if((uip_connr->tcpstateflags & UIP_TS_MASK) == UIP_ESTABLISHED) { - /* If there was no need for a retransmission, we poll the - application for new data. */ - uip_flags = UIP_POLL; - UIP_APPCALL(); - goto appsend; - } - } - goto drop; - } -#if UIP_UDP - if(flag == UIP_UDP_TIMER) { - if(uip_udp_conn->lport != 0) { - uip_conn = NULL; - uip_sappdata = uip_appdata = &uip_buf[UIP_LLH_LEN + UIP_IPUDPH_LEN]; - uip_len = uip_slen = 0; - uip_flags = UIP_POLL; - UIP_UDP_APPCALL(); - goto udp_send; - } else { - goto drop; - } - } -#endif - - /* This is where the input processing starts. */ - UIP_STAT(++uip_stat.ip.recv); - - /* Start of IP input header processing code. */ - -#if UIP_CONF_IPV6 - /* Check validity of the IP header. */ - if((BUF->vtc & 0xf0) != 0x60) { /* IP version and header length. */ - UIP_STAT(++uip_stat.ip.drop); - UIP_STAT(++uip_stat.ip.vhlerr); - UIP_LOG("ipv6: invalid version."); - goto drop; - } -#else /* UIP_CONF_IPV6 */ - /* Check validity of the IP header. */ - if(BUF->vhl != 0x45) { /* IP version and header length. */ - UIP_STAT(++uip_stat.ip.drop); - UIP_STAT(++uip_stat.ip.vhlerr); - UIP_LOG("ip: invalid version or header length."); - goto drop; - } -#endif /* UIP_CONF_IPV6 */ - - /* Check the size of the packet. If the size reported to us in - uip_len is smaller the size reported in the IP header, we assume - that the packet has been corrupted in transit. If the size of - uip_len is larger than the size reported in the IP packet header, - the packet has been padded and we set uip_len to the correct - value.. */ - - if((BUF->len[0] << 8) + BUF->len[1] <= uip_len) { - uip_len = (BUF->len[0] << 8) + BUF->len[1]; -#if UIP_CONF_IPV6 - uip_len += 40; /* The length reported in the IPv6 header is the - length of the payload that follows the - header. However, uIP uses the uip_len variable - for holding the size of the entire packet, - including the IP header. For IPv4 this is not a - problem as the length field in the IPv4 header - contains the length of the entire packet. But - for IPv6 we need to add the size of the IPv6 - header (40 bytes). */ -#endif /* UIP_CONF_IPV6 */ - } else { - UIP_LOG("ip: packet shorter than reported in IP header."); - goto drop; - } - -#if !UIP_CONF_IPV6 - /* Check the fragment flag. */ - if((BUF->ipoffset[0] & 0x3f) != 0 || - BUF->ipoffset[1] != 0) { -#if UIP_REASSEMBLY - uip_len = uip_reass(); - if(uip_len == 0) { - goto drop; - } -#else /* UIP_REASSEMBLY */ - UIP_STAT(++uip_stat.ip.drop); - UIP_STAT(++uip_stat.ip.fragerr); - UIP_LOG("ip: fragment dropped."); - goto drop; -#endif /* UIP_REASSEMBLY */ - } -#endif /* UIP_CONF_IPV6 */ - - if(uip_ipaddr_cmp(uip_hostaddr, all_zeroes_addr)) { - /* If we are configured to use ping IP address configuration and - hasn't been assigned an IP address yet, we accept all ICMP - packets. */ -#if UIP_PINGADDRCONF && !UIP_CONF_IPV6 - if(BUF->proto == UIP_PROTO_ICMP) { - UIP_LOG("ip: possible ping config packet received."); - goto icmp_input; - } else { - UIP_LOG("ip: packet dropped since no address assigned."); - goto drop; - } -#endif /* UIP_PINGADDRCONF */ - - } else { - /* If IP broadcast support is configured, we check for a broadcast - UDP packet, which may be destined to us. */ -#if UIP_BROADCAST - DEBUG_PRINTF("UDP IP checksum 0x%04x\n", uip_ipchksum()); - if(BUF->proto == UIP_PROTO_UDP && - uip_ipaddr_cmp(BUF->destipaddr, all_ones_addr) - /*&& - uip_ipchksum() == 0xffff*/) { - goto udp_input; - } -#endif /* UIP_BROADCAST */ - - /* Check if the packet is destined for our IP address. */ -#if !UIP_CONF_IPV6 - if(!uip_ipaddr_cmp(BUF->destipaddr, uip_hostaddr)) { - UIP_STAT(++uip_stat.ip.drop); - goto drop; - } -#else /* UIP_CONF_IPV6 */ - /* For IPv6, packet reception is a little trickier as we need to - make sure that we listen to certain multicast addresses (all - hosts multicast address, and the solicited-node multicast - address) as well. However, we will cheat here and accept all - multicast packets that are sent to the ff02::/16 addresses. */ - if(!uip_ipaddr_cmp(BUF->destipaddr, uip_hostaddr) && - BUF->destipaddr[0] != HTONS(0xff02)) { - UIP_STAT(++uip_stat.ip.drop); - goto drop; - } -#endif /* UIP_CONF_IPV6 */ - } - -#if !UIP_CONF_IPV6 - if(uip_ipchksum() != 0xffff) { /* Compute and check the IP header - checksum. */ - UIP_STAT(++uip_stat.ip.drop); - UIP_STAT(++uip_stat.ip.chkerr); - UIP_LOG("ip: bad checksum."); - goto drop; - } -#endif /* UIP_CONF_IPV6 */ - - if(BUF->proto == UIP_PROTO_TCP) { /* Check for TCP packet. If so, - proceed with TCP input - processing. */ - goto tcp_input; - } - -#if UIP_UDP - if(BUF->proto == UIP_PROTO_UDP) { - goto udp_input; - } -#endif /* UIP_UDP */ - -#if !UIP_CONF_IPV6 - /* ICMPv4 processing code follows. */ - if(BUF->proto != UIP_PROTO_ICMP) { /* We only allow ICMP packets from - here. */ - UIP_STAT(++uip_stat.ip.drop); - UIP_STAT(++uip_stat.ip.protoerr); - UIP_LOG("ip: neither tcp nor icmp."); - goto drop; - } - -#if UIP_PINGADDRCONF - icmp_input: -#endif /* UIP_PINGADDRCONF */ - UIP_STAT(++uip_stat.icmp.recv); - - /* ICMP echo (i.e., ping) processing. This is simple, we only change - the ICMP type from ECHO to ECHO_REPLY and adjust the ICMP - checksum before we return the packet. */ - if(ICMPBUF->type != ICMP_ECHO) { - UIP_STAT(++uip_stat.icmp.drop); - UIP_STAT(++uip_stat.icmp.typeerr); - UIP_LOG("icmp: not icmp echo."); - goto drop; - } - - /* If we are configured to use ping IP address assignment, we use - the destination IP address of this ping packet and assign it to - ourself. */ -#if UIP_PINGADDRCONF - if((uip_hostaddr[0] | uip_hostaddr[1]) == 0) { - uip_hostaddr[0] = BUF->destipaddr[0]; - uip_hostaddr[1] = BUF->destipaddr[1]; - } -#endif /* UIP_PINGADDRCONF */ - - ICMPBUF->type = ICMP_ECHO_REPLY; - - if(ICMPBUF->icmpchksum >= HTONS(0xffff - (ICMP_ECHO << 8))) { - ICMPBUF->icmpchksum += HTONS(ICMP_ECHO << 8) + 1; - } else { - ICMPBUF->icmpchksum += HTONS(ICMP_ECHO << 8); - } - - /* Swap IP addresses. */ - uip_ipaddr_copy(BUF->destipaddr, BUF->srcipaddr); - uip_ipaddr_copy(BUF->srcipaddr, uip_hostaddr); - - UIP_STAT(++uip_stat.icmp.sent); - goto send; - - /* End of IPv4 input header processing code. */ -#else /* !UIP_CONF_IPV6 */ - - /* This is IPv6 ICMPv6 processing code. */ - DEBUG_PRINTF("icmp6_input: length %d\n", uip_len); - - if(BUF->proto != UIP_PROTO_ICMP6) { /* We only allow ICMPv6 packets from - here. */ - UIP_STAT(++uip_stat.ip.drop); - UIP_STAT(++uip_stat.ip.protoerr); - UIP_LOG("ip: neither tcp nor icmp6."); - goto drop; - } - - UIP_STAT(++uip_stat.icmp.recv); - - /* If we get a neighbor solicitation for our address we should send - a neighbor advertisement message back. */ - if(ICMPBUF->type == ICMP6_NEIGHBOR_SOLICITATION) { - if(uip_ipaddr_cmp(ICMPBUF->icmp6data, uip_hostaddr)) { - - if(ICMPBUF->options[0] == ICMP6_OPTION_SOURCE_LINK_ADDRESS) { - /* Save the sender's address in our neighbor list. */ - uip_neighbor_add(ICMPBUF->srcipaddr, &(ICMPBUF->options[2])); - } - - /* We should now send a neighbor advertisement back to where the - neighbor solicication came from. */ - ICMPBUF->type = ICMP6_NEIGHBOR_ADVERTISEMENT; - ICMPBUF->flags = ICMP6_FLAG_S; /* Solicited flag. */ - - ICMPBUF->reserved1 = ICMPBUF->reserved2 = ICMPBUF->reserved3 = 0; - - uip_ipaddr_copy(ICMPBUF->destipaddr, ICMPBUF->srcipaddr); - uip_ipaddr_copy(ICMPBUF->srcipaddr, uip_hostaddr); - ICMPBUF->options[0] = ICMP6_OPTION_TARGET_LINK_ADDRESS; - ICMPBUF->options[1] = 1; /* Options length, 1 = 8 bytes. */ - memcpy(&(ICMPBUF->options[2]), &uip_ethaddr, sizeof(uip_ethaddr)); - ICMPBUF->icmpchksum = 0; - ICMPBUF->icmpchksum = ~uip_icmp6chksum(); - goto send; - - } - goto drop; - } else if(ICMPBUF->type == ICMP6_ECHO) { - /* ICMP echo (i.e., ping) processing. This is simple, we only - change the ICMP type from ECHO to ECHO_REPLY and update the - ICMP checksum before we return the packet. */ - - ICMPBUF->type = ICMP6_ECHO_REPLY; - - uip_ipaddr_copy(BUF->destipaddr, BUF->srcipaddr); - uip_ipaddr_copy(BUF->srcipaddr, uip_hostaddr); - ICMPBUF->icmpchksum = 0; - ICMPBUF->icmpchksum = ~uip_icmp6chksum(); - - UIP_STAT(++uip_stat.icmp.sent); - goto send; - } else { - DEBUG_PRINTF("Unknown icmp6 message type %d\n", ICMPBUF->type); - UIP_STAT(++uip_stat.icmp.drop); - UIP_STAT(++uip_stat.icmp.typeerr); - UIP_LOG("icmp: unknown ICMP message."); - goto drop; - } - - /* End of IPv6 ICMP processing. */ - -#endif /* !UIP_CONF_IPV6 */ - -#if UIP_UDP - /* UDP input processing. */ - udp_input: - /* UDP processing is really just a hack. We don't do anything to the - UDP/IP headers, but let the UDP application do all the hard - work. If the application sets uip_slen, it has a packet to - send. */ -#if UIP_UDP_CHECKSUMS - uip_len = uip_len - UIP_IPUDPH_LEN; - uip_appdata = &uip_buf[UIP_LLH_LEN + UIP_IPUDPH_LEN]; - if(UDPBUF->udpchksum != 0 && uip_udpchksum() != 0xffff) { - UIP_STAT(++uip_stat.udp.drop); - UIP_STAT(++uip_stat.udp.chkerr); - UIP_LOG("udp: bad checksum."); - goto drop; - } -#else /* UIP_UDP_CHECKSUMS */ - uip_len = uip_len - UIP_IPUDPH_LEN; -#endif /* UIP_UDP_CHECKSUMS */ - - /* Demultiplex this UDP packet between the UDP "connections". */ - for(uip_udp_conn = &uip_udp_conns[0]; - uip_udp_conn < &uip_udp_conns[UIP_UDP_CONNS]; - ++uip_udp_conn) { - /* If the local UDP port is non-zero, the connection is considered - to be used. If so, the local port number is checked against the - destination port number in the received packet. If the two port - numbers match, the remote port number is checked if the - connection is bound to a remote port. Finally, if the - connection is bound to a remote IP address, the source IP - address of the packet is checked. */ - if(uip_udp_conn->lport != 0 && - UDPBUF->destport == uip_udp_conn->lport && - (uip_udp_conn->rport == 0 || - UDPBUF->srcport == uip_udp_conn->rport) && - (uip_ipaddr_cmp(uip_udp_conn->ripaddr, all_zeroes_addr) || - uip_ipaddr_cmp(uip_udp_conn->ripaddr, all_ones_addr) || - uip_ipaddr_cmp(BUF->srcipaddr, uip_udp_conn->ripaddr))) { - goto udp_found; - } - } - UIP_LOG("udp: no matching connection found"); - goto drop; - - udp_found: - uip_conn = NULL; - uip_flags = UIP_NEWDATA; - uip_sappdata = uip_appdata = &uip_buf[UIP_LLH_LEN + UIP_IPUDPH_LEN]; - uip_slen = 0; - UIP_UDP_APPCALL(); - udp_send: - if(uip_slen == 0) { - goto drop; - } - uip_len = uip_slen + UIP_IPUDPH_LEN; - -#if UIP_CONF_IPV6 - /* For IPv6, the IP length field does not include the IPv6 IP header - length. */ - BUF->len[0] = ((uip_len - UIP_IPH_LEN) >> 8); - BUF->len[1] = ((uip_len - UIP_IPH_LEN) & 0xff); -#else /* UIP_CONF_IPV6 */ - BUF->len[0] = (uip_len >> 8); - BUF->len[1] = (uip_len & 0xff); -#endif /* UIP_CONF_IPV6 */ - - BUF->ttl = uip_udp_conn->ttl; - BUF->proto = UIP_PROTO_UDP; - - UDPBUF->udplen = HTONS(uip_slen + UIP_UDPH_LEN); - UDPBUF->udpchksum = 0; - - BUF->srcport = uip_udp_conn->lport; - BUF->destport = uip_udp_conn->rport; - - uip_ipaddr_copy(BUF->srcipaddr, uip_hostaddr); - uip_ipaddr_copy(BUF->destipaddr, uip_udp_conn->ripaddr); - - uip_appdata = &uip_buf[UIP_LLH_LEN + UIP_IPTCPH_LEN]; - -#if UIP_UDP_CHECKSUMS - /* Calculate UDP checksum. */ - UDPBUF->udpchksum = ~(uip_udpchksum()); - if(UDPBUF->udpchksum == 0) { - UDPBUF->udpchksum = 0xffff; - } -#endif /* UIP_UDP_CHECKSUMS */ - - goto ip_send_nolen; -#endif /* UIP_UDP */ - - /* TCP input processing. */ - tcp_input: - UIP_STAT(++uip_stat.tcp.recv); - - /* Start of TCP input header processing code. */ - - if(uip_tcpchksum() != 0xffff) { /* Compute and check the TCP - checksum. */ - UIP_STAT(++uip_stat.tcp.drop); - UIP_STAT(++uip_stat.tcp.chkerr); - UIP_LOG("tcp: bad checksum."); - goto drop; - } - - - /* Demultiplex this segment. */ - /* First check any active connections. */ - for(uip_connr = &uip_conns[0]; uip_connr <= &uip_conns[UIP_CONNS - 1]; - ++uip_connr) { - if(uip_connr->tcpstateflags != UIP_CLOSED && - BUF->destport == uip_connr->lport && - BUF->srcport == uip_connr->rport && - uip_ipaddr_cmp(BUF->srcipaddr, uip_connr->ripaddr)) { - goto found; - } - } - - /* If we didn't find and active connection that expected the packet, - either this packet is an old duplicate, or this is a SYN packet - destined for a connection in LISTEN. If the SYN flag isn't set, - it is an old packet and we send a RST. */ - if((BUF->flags & TCP_CTL) != TCP_SYN) { - goto reset; - } - - tmp16 = BUF->destport; - /* Next, check listening connections. */ - for(c = 0; c < UIP_LISTENPORTS; ++c) { - if(tmp16 == uip_listenports[c]) - goto found_listen; - } - - /* No matching connection found, so we send a RST packet. */ - UIP_STAT(++uip_stat.tcp.synrst); - reset: - - /* We do not send resets in response to resets. */ - if(BUF->flags & TCP_RST) { - goto drop; - } - - UIP_STAT(++uip_stat.tcp.rst); - - BUF->flags = TCP_RST | TCP_ACK; - uip_len = UIP_IPTCPH_LEN; - BUF->tcpoffset = 5 << 4; - - /* Flip the seqno and ackno fields in the TCP header. */ - c = BUF->seqno[3]; - BUF->seqno[3] = BUF->ackno[3]; - BUF->ackno[3] = c; - - c = BUF->seqno[2]; - BUF->seqno[2] = BUF->ackno[2]; - BUF->ackno[2] = c; - - c = BUF->seqno[1]; - BUF->seqno[1] = BUF->ackno[1]; - BUF->ackno[1] = c; - - c = BUF->seqno[0]; - BUF->seqno[0] = BUF->ackno[0]; - BUF->ackno[0] = c; - - /* We also have to increase the sequence number we are - acknowledging. If the least significant byte overflowed, we need - to propagate the carry to the other bytes as well. */ - if(++BUF->ackno[3] == 0) { - if(++BUF->ackno[2] == 0) { - if(++BUF->ackno[1] == 0) { - ++BUF->ackno[0]; - } - } - } - - /* Swap port numbers. */ - tmp16 = BUF->srcport; - BUF->srcport = BUF->destport; - BUF->destport = tmp16; - - /* Swap IP addresses. */ - uip_ipaddr_copy(BUF->destipaddr, BUF->srcipaddr); - uip_ipaddr_copy(BUF->srcipaddr, uip_hostaddr); - - /* And send out the RST packet! */ - goto tcp_send_noconn; - - /* This label will be jumped to if we matched the incoming packet - with a connection in LISTEN. In that case, we should create a new - connection and send a SYNACK in return. */ - found_listen: - /* First we check if there are any connections avaliable. Unused - connections are kept in the same table as used connections, but - unused ones have the tcpstate set to CLOSED. Also, connections in - TIME_WAIT are kept track of and we'll use the oldest one if no - CLOSED connections are found. Thanks to Eddie C. Dost for a very - nice algorithm for the TIME_WAIT search. */ - uip_connr = 0; - for(c = 0; c < UIP_CONNS; ++c) { - if(uip_conns[c].tcpstateflags == UIP_CLOSED) { - uip_connr = &uip_conns[c]; - break; - } - if(uip_conns[c].tcpstateflags == UIP_TIME_WAIT) { - if(uip_connr == 0 || - uip_conns[c].timer > uip_connr->timer) { - uip_connr = &uip_conns[c]; - } - } - } - - if(uip_connr == 0) { - /* All connections are used already, we drop packet and hope that - the remote end will retransmit the packet at a time when we - have more spare connections. */ - UIP_STAT(++uip_stat.tcp.syndrop); - UIP_LOG("tcp: found no unused connections."); - goto drop; - } - uip_conn = uip_connr; - - /* Fill in the necessary fields for the new connection. */ - uip_connr->rto = uip_connr->timer = UIP_RTO; - uip_connr->sa = 0; - uip_connr->sv = 4; - uip_connr->nrtx = 0; - uip_connr->lport = BUF->destport; - uip_connr->rport = BUF->srcport; - uip_ipaddr_copy(uip_connr->ripaddr, BUF->srcipaddr); - uip_connr->tcpstateflags = UIP_SYN_RCVD; - - uip_connr->snd_nxt[0] = iss[0]; - uip_connr->snd_nxt[1] = iss[1]; - uip_connr->snd_nxt[2] = iss[2]; - uip_connr->snd_nxt[3] = iss[3]; - uip_connr->len = 1; - - /* rcv_nxt should be the seqno from the incoming packet + 1. */ - uip_connr->rcv_nxt[3] = BUF->seqno[3]; - uip_connr->rcv_nxt[2] = BUF->seqno[2]; - uip_connr->rcv_nxt[1] = BUF->seqno[1]; - uip_connr->rcv_nxt[0] = BUF->seqno[0]; - uip_add_rcv_nxt(1); - - /* Parse the TCP MSS option, if present. */ - if((BUF->tcpoffset & 0xf0) > 0x50) { - for(c = 0; c < ((BUF->tcpoffset >> 4) - 5) << 2 ;) { - opt = uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + c]; - if(opt == TCP_OPT_END) { - /* End of options. */ - break; - } else if(opt == TCP_OPT_NOOP) { - ++c; - /* NOP option. */ - } else if(opt == TCP_OPT_MSS && - uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 1 + c] == TCP_OPT_MSS_LEN) { - /* An MSS option with the right option length. */ - tmp16 = ((u16_t)uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 2 + c] << 8) | - (u16_t)uip_buf[UIP_IPTCPH_LEN + UIP_LLH_LEN + 3 + c]; - uip_connr->initialmss = uip_connr->mss = - tmp16 > UIP_TCP_MSS? UIP_TCP_MSS: tmp16; - - /* And we are done processing options. */ - break; - } else { - /* All other options have a length field, so that we easily - can skip past them. */ - if(uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 1 + c] == 0) { - /* If the length field is zero, the options are malformed - and we don't process them further. */ - break; - } - c += uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 1 + c]; - } - } - } - - /* Our response will be a SYNACK. */ -#if UIP_ACTIVE_OPEN - tcp_send_synack: - BUF->flags = TCP_ACK; - - tcp_send_syn: - BUF->flags |= TCP_SYN; -#else /* UIP_ACTIVE_OPEN */ - tcp_send_synack: - BUF->flags = TCP_SYN | TCP_ACK; -#endif /* UIP_ACTIVE_OPEN */ - - /* We send out the TCP Maximum Segment Size option with our - SYNACK. */ - BUF->optdata[0] = TCP_OPT_MSS; - BUF->optdata[1] = TCP_OPT_MSS_LEN; - BUF->optdata[2] = (UIP_TCP_MSS) / 256; - BUF->optdata[3] = (UIP_TCP_MSS) & 255; - uip_len = UIP_IPTCPH_LEN + TCP_OPT_MSS_LEN; - BUF->tcpoffset = ((UIP_TCPH_LEN + TCP_OPT_MSS_LEN) / 4) << 4; - goto tcp_send; - - /* This label will be jumped to if we found an active connection. */ - found: - uip_conn = uip_connr; - uip_flags = 0; - /* We do a very naive form of TCP reset processing; we just accept - any RST and kill our connection. We should in fact check if the - sequence number of this reset is wihtin our advertised window - before we accept the reset. */ - if(BUF->flags & TCP_RST) { - uip_connr->tcpstateflags = UIP_CLOSED; - UIP_LOG("tcp: got reset, aborting connection."); - uip_flags = UIP_ABORT; - UIP_APPCALL(); - goto drop; - } - /* Calculated the length of the data, if the application has sent - any data to us. */ - c = (BUF->tcpoffset >> 4) << 2; - /* uip_len will contain the length of the actual TCP data. This is - calculated by subtracing the length of the TCP header (in - c) and the length of the IP header (20 bytes). */ - uip_len = uip_len - c - UIP_IPH_LEN; - - /* First, check if the sequence number of the incoming packet is - what we're expecting next. If not, we send out an ACK with the - correct numbers in. */ - if(!(((uip_connr->tcpstateflags & UIP_TS_MASK) == UIP_SYN_SENT) && - ((BUF->flags & TCP_CTL) == (TCP_SYN | TCP_ACK)))) { - if((uip_len > 0 || ((BUF->flags & (TCP_SYN | TCP_FIN)) != 0)) && - (BUF->seqno[0] != uip_connr->rcv_nxt[0] || - BUF->seqno[1] != uip_connr->rcv_nxt[1] || - BUF->seqno[2] != uip_connr->rcv_nxt[2] || - BUF->seqno[3] != uip_connr->rcv_nxt[3])) { - goto tcp_send_ack; - } - } - - /* Next, check if the incoming segment acknowledges any outstanding - data. If so, we update the sequence number, reset the length of - the outstanding data, calculate RTT estimations, and reset the - retransmission timer. */ - if((BUF->flags & TCP_ACK) && uip_outstanding(uip_connr)) { - uip_add32(uip_connr->snd_nxt, uip_connr->len); - - if(BUF->ackno[0] == uip_acc32[0] && - BUF->ackno[1] == uip_acc32[1] && - BUF->ackno[2] == uip_acc32[2] && - BUF->ackno[3] == uip_acc32[3]) { - /* Update sequence number. */ - uip_connr->snd_nxt[0] = uip_acc32[0]; - uip_connr->snd_nxt[1] = uip_acc32[1]; - uip_connr->snd_nxt[2] = uip_acc32[2]; - uip_connr->snd_nxt[3] = uip_acc32[3]; - - - /* Do RTT estimation, unless we have done retransmissions. */ - if(uip_connr->nrtx == 0) { - signed char m; - m = uip_connr->rto - uip_connr->timer; - /* This is taken directly from VJs original code in his paper */ - m = m - (uip_connr->sa >> 3); - uip_connr->sa += m; - if(m < 0) { - m = -m; - } - m = m - (uip_connr->sv >> 2); - uip_connr->sv += m; - uip_connr->rto = (uip_connr->sa >> 3) + uip_connr->sv; - - } - /* Set the acknowledged flag. */ - uip_flags = UIP_ACKDATA; - /* Reset the retransmission timer. */ - uip_connr->timer = uip_connr->rto; - - /* Reset length of outstanding data. */ - uip_connr->len = 0; - } - - } - - /* Do different things depending on in what state the connection is. */ - switch(uip_connr->tcpstateflags & UIP_TS_MASK) { - /* CLOSED and LISTEN are not handled here. CLOSE_WAIT is not - implemented, since we force the application to close when the - peer sends a FIN (hence the application goes directly from - ESTABLISHED to LAST_ACK). */ - case UIP_SYN_RCVD: - /* In SYN_RCVD we have sent out a SYNACK in response to a SYN, and - we are waiting for an ACK that acknowledges the data we sent - out the last time. Therefore, we want to have the UIP_ACKDATA - flag set. If so, we enter the ESTABLISHED state. */ - if(uip_flags & UIP_ACKDATA) { - uip_connr->tcpstateflags = UIP_ESTABLISHED; - uip_flags = UIP_CONNECTED; - uip_connr->len = 0; - if(uip_len > 0) { - uip_flags |= UIP_NEWDATA; - uip_add_rcv_nxt(uip_len); - } - uip_slen = 0; - UIP_APPCALL(); - goto appsend; - } - goto drop; -#if UIP_ACTIVE_OPEN - case UIP_SYN_SENT: - /* In SYN_SENT, we wait for a SYNACK that is sent in response to - our SYN. The rcv_nxt is set to sequence number in the SYNACK - plus one, and we send an ACK. We move into the ESTABLISHED - state. */ - if((uip_flags & UIP_ACKDATA) && - (BUF->flags & TCP_CTL) == (TCP_SYN | TCP_ACK)) { - - /* Parse the TCP MSS option, if present. */ - if((BUF->tcpoffset & 0xf0) > 0x50) { - for(c = 0; c < ((BUF->tcpoffset >> 4) - 5) << 2 ;) { - opt = uip_buf[UIP_IPTCPH_LEN + UIP_LLH_LEN + c]; - if(opt == TCP_OPT_END) { - /* End of options. */ - break; - } else if(opt == TCP_OPT_NOOP) { - ++c; - /* NOP option. */ - } else if(opt == TCP_OPT_MSS && - uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 1 + c] == TCP_OPT_MSS_LEN) { - /* An MSS option with the right option length. */ - tmp16 = (uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 2 + c] << 8) | - uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 3 + c]; - uip_connr->initialmss = - uip_connr->mss = tmp16 > UIP_TCP_MSS? UIP_TCP_MSS: tmp16; - - /* And we are done processing options. */ - break; - } else { - /* All other options have a length field, so that we easily - can skip past them. */ - if(uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 1 + c] == 0) { - /* If the length field is zero, the options are malformed - and we don't process them further. */ - break; - } - c += uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 1 + c]; - } - } - } - uip_connr->tcpstateflags = UIP_ESTABLISHED; - uip_connr->rcv_nxt[0] = BUF->seqno[0]; - uip_connr->rcv_nxt[1] = BUF->seqno[1]; - uip_connr->rcv_nxt[2] = BUF->seqno[2]; - uip_connr->rcv_nxt[3] = BUF->seqno[3]; - uip_add_rcv_nxt(1); - uip_flags = UIP_CONNECTED | UIP_NEWDATA; - uip_connr->len = 0; - uip_len = 0; - uip_slen = 0; - UIP_APPCALL(); - goto appsend; - } - /* Inform the application that the connection failed */ - uip_flags = UIP_ABORT; - UIP_APPCALL(); - /* The connection is closed after we send the RST */ - uip_conn->tcpstateflags = UIP_CLOSED; - goto reset; -#endif /* UIP_ACTIVE_OPEN */ - - case UIP_ESTABLISHED: - /* In the ESTABLISHED state, we call upon the application to feed - data into the uip_buf. If the UIP_ACKDATA flag is set, the - application should put new data into the buffer, otherwise we are - retransmitting an old segment, and the application should put that - data into the buffer. - - If the incoming packet is a FIN, we should close the connection on - this side as well, and we send out a FIN and enter the LAST_ACK - state. We require that there is no outstanding data; otherwise the - sequence numbers will be screwed up. */ - - if(BUF->flags & TCP_FIN && !(uip_connr->tcpstateflags & UIP_STOPPED)) { - if(uip_outstanding(uip_connr)) { - goto drop; - } - uip_add_rcv_nxt(1 + uip_len); - uip_flags |= UIP_CLOSE; - if(uip_len > 0) { - uip_flags |= UIP_NEWDATA; - } - UIP_APPCALL(); - uip_connr->len = 1; - uip_connr->tcpstateflags = UIP_LAST_ACK; - uip_connr->nrtx = 0; - tcp_send_finack: - BUF->flags = TCP_FIN | TCP_ACK; - goto tcp_send_nodata; - } - - /* Check the URG flag. If this is set, the segment carries urgent - data that we must pass to the application. */ - if((BUF->flags & TCP_URG) != 0) { -#if UIP_URGDATA > 0 - uip_urglen = (BUF->urgp[0] << 8) | BUF->urgp[1]; - if(uip_urglen > uip_len) { - /* There is more urgent data in the next segment to come. */ - uip_urglen = uip_len; - } - uip_add_rcv_nxt(uip_urglen); - uip_len -= uip_urglen; - uip_urgdata = uip_appdata; - uip_appdata += uip_urglen; - } else { - uip_urglen = 0; -#else /* UIP_URGDATA > 0 */ - uip_appdata = ((char *)uip_appdata) + ((BUF->urgp[0] << 8) | BUF->urgp[1]); - uip_len -= (BUF->urgp[0] << 8) | BUF->urgp[1]; -#endif /* UIP_URGDATA > 0 */ - } - - /* If uip_len > 0 we have TCP data in the packet, and we flag this - by setting the UIP_NEWDATA flag and update the sequence number - we acknowledge. If the application has stopped the dataflow - using uip_stop(), we must not accept any data packets from the - remote host. */ - if(uip_len > 0 && !(uip_connr->tcpstateflags & UIP_STOPPED)) { - uip_flags |= UIP_NEWDATA; - uip_add_rcv_nxt(uip_len); - } - - /* Check if the available buffer space advertised by the other end - is smaller than the initial MSS for this connection. If so, we - set the current MSS to the window size to ensure that the - application does not send more data than the other end can - handle. - - If the remote host advertises a zero window, we set the MSS to - the initial MSS so that the application will send an entire MSS - of data. This data will not be acknowledged by the receiver, - and the application will retransmit it. This is called the - "persistent timer" and uses the retransmission mechanim. - */ - tmp16 = ((u16_t)BUF->wnd[0] << 8) + (u16_t)BUF->wnd[1]; - if(tmp16 > uip_connr->initialmss || - tmp16 == 0) { - tmp16 = uip_connr->initialmss; - } - uip_connr->mss = tmp16; - - /* If this packet constitutes an ACK for outstanding data (flagged - by the UIP_ACKDATA flag, we should call the application since it - might want to send more data. If the incoming packet had data - from the peer (as flagged by the UIP_NEWDATA flag), the - application must also be notified. - - When the application is called, the global variable uip_len - contains the length of the incoming data. The application can - access the incoming data through the global pointer - uip_appdata, which usually points UIP_IPTCPH_LEN + UIP_LLH_LEN - bytes into the uip_buf array. - - If the application wishes to send any data, this data should be - put into the uip_appdata and the length of the data should be - put into uip_len. If the application don't have any data to - send, uip_len must be set to 0. */ - if(uip_flags & (UIP_NEWDATA | UIP_ACKDATA)) { - uip_slen = 0; - UIP_APPCALL(); - - appsend: - - if(uip_flags & UIP_ABORT) { - uip_slen = 0; - uip_connr->tcpstateflags = UIP_CLOSED; - BUF->flags = TCP_RST | TCP_ACK; - goto tcp_send_nodata; - } - - if(uip_flags & UIP_CLOSE) { - uip_slen = 0; - uip_connr->len = 1; - uip_connr->tcpstateflags = UIP_FIN_WAIT_1; - uip_connr->nrtx = 0; - BUF->flags = TCP_FIN | TCP_ACK; - goto tcp_send_nodata; - } - - /* If uip_slen > 0, the application has data to be sent. */ - if(uip_slen > 0) { - - /* If the connection has acknowledged data, the contents of - the ->len variable should be discarded. */ - if((uip_flags & UIP_ACKDATA) != 0) { - uip_connr->len = 0; - } - - /* If the ->len variable is non-zero the connection has - already data in transit and cannot send anymore right - now. */ - if(uip_connr->len == 0) { - - /* The application cannot send more than what is allowed by - the mss (the minumum of the MSS and the available - window). */ - if(uip_slen > uip_connr->mss) { - uip_slen = uip_connr->mss; - } - - /* Remember how much data we send out now so that we know - when everything has been acknowledged. */ - uip_connr->len = uip_slen; - } else { - - /* If the application already had unacknowledged data, we - make sure that the application does not send (i.e., - retransmit) out more than it previously sent out. */ - uip_slen = uip_connr->len; - } - } - uip_connr->nrtx = 0; - apprexmit: - uip_appdata = uip_sappdata; - - /* If the application has data to be sent, or if the incoming - packet had new data in it, we must send out a packet. */ - if(uip_slen > 0 && uip_connr->len > 0) { - /* Add the length of the IP and TCP headers. */ - uip_len = uip_connr->len + UIP_TCPIP_HLEN; - /* We always set the ACK flag in response packets. */ - BUF->flags = TCP_ACK | TCP_PSH; - /* Send the packet. */ - goto tcp_send_noopts; - } - /* If there is no data to send, just send out a pure ACK if - there is newdata. */ - if(uip_flags & UIP_NEWDATA) { - uip_len = UIP_TCPIP_HLEN; - BUF->flags = TCP_ACK; - goto tcp_send_noopts; - } - } - goto drop; - case UIP_LAST_ACK: - /* We can close this connection if the peer has acknowledged our - FIN. This is indicated by the UIP_ACKDATA flag. */ - if(uip_flags & UIP_ACKDATA) { - uip_connr->tcpstateflags = UIP_CLOSED; - uip_flags = UIP_CLOSE; - UIP_APPCALL(); - } - break; - - case UIP_FIN_WAIT_1: - /* The application has closed the connection, but the remote host - hasn't closed its end yet. Thus we do nothing but wait for a - FIN from the other side. */ - if(uip_len > 0) { - uip_add_rcv_nxt(uip_len); - } - if(BUF->flags & TCP_FIN) { - if(uip_flags & UIP_ACKDATA) { - uip_connr->tcpstateflags = UIP_TIME_WAIT; - uip_connr->timer = 0; - uip_connr->len = 0; - } else { - uip_connr->tcpstateflags = UIP_CLOSING; - } - uip_add_rcv_nxt(1); - uip_flags = UIP_CLOSE; - UIP_APPCALL(); - goto tcp_send_ack; - } else if(uip_flags & UIP_ACKDATA) { - uip_connr->tcpstateflags = UIP_FIN_WAIT_2; - uip_connr->len = 0; - goto drop; - } - if(uip_len > 0) { - goto tcp_send_ack; - } - goto drop; - - case UIP_FIN_WAIT_2: - if(uip_len > 0) { - uip_add_rcv_nxt(uip_len); - } - if(BUF->flags & TCP_FIN) { - uip_connr->tcpstateflags = UIP_TIME_WAIT; - uip_connr->timer = 0; - uip_add_rcv_nxt(1); - uip_flags = UIP_CLOSE; - UIP_APPCALL(); - goto tcp_send_ack; - } - if(uip_len > 0) { - goto tcp_send_ack; - } - goto drop; - - case UIP_TIME_WAIT: - goto tcp_send_ack; - - case UIP_CLOSING: - if(uip_flags & UIP_ACKDATA) { - uip_connr->tcpstateflags = UIP_TIME_WAIT; - uip_connr->timer = 0; - } - } - goto drop; - - - /* We jump here when we are ready to send the packet, and just want - to set the appropriate TCP sequence numbers in the TCP header. */ - tcp_send_ack: - BUF->flags = TCP_ACK; - tcp_send_nodata: - uip_len = UIP_IPTCPH_LEN; - tcp_send_noopts: - BUF->tcpoffset = (UIP_TCPH_LEN / 4) << 4; - tcp_send: - /* We're done with the input processing. We are now ready to send a - reply. Our job is to fill in all the fields of the TCP and IP - headers before calculating the checksum and finally send the - packet. */ - BUF->ackno[0] = uip_connr->rcv_nxt[0]; - BUF->ackno[1] = uip_connr->rcv_nxt[1]; - BUF->ackno[2] = uip_connr->rcv_nxt[2]; - BUF->ackno[3] = uip_connr->rcv_nxt[3]; - - BUF->seqno[0] = uip_connr->snd_nxt[0]; - BUF->seqno[1] = uip_connr->snd_nxt[1]; - BUF->seqno[2] = uip_connr->snd_nxt[2]; - BUF->seqno[3] = uip_connr->snd_nxt[3]; - - BUF->proto = UIP_PROTO_TCP; - - BUF->srcport = uip_connr->lport; - BUF->destport = uip_connr->rport; - - uip_ipaddr_copy(BUF->srcipaddr, uip_hostaddr); - uip_ipaddr_copy(BUF->destipaddr, uip_connr->ripaddr); - - if(uip_connr->tcpstateflags & UIP_STOPPED) { - /* If the connection has issued uip_stop(), we advertise a zero - window so that the remote host will stop sending data. */ - BUF->wnd[0] = BUF->wnd[1] = 0; - } else { - BUF->wnd[0] = ((UIP_RECEIVE_WINDOW) >> 8); - BUF->wnd[1] = ((UIP_RECEIVE_WINDOW) & 0xff); - } - - tcp_send_noconn: - BUF->ttl = UIP_TTL; -#if UIP_CONF_IPV6 - /* For IPv6, the IP length field does not include the IPv6 IP header - length. */ - BUF->len[0] = ((uip_len - UIP_IPH_LEN) >> 8); - BUF->len[1] = ((uip_len - UIP_IPH_LEN) & 0xff); -#else /* UIP_CONF_IPV6 */ - BUF->len[0] = (uip_len >> 8); - BUF->len[1] = (uip_len & 0xff); -#endif /* UIP_CONF_IPV6 */ - - BUF->urgp[0] = BUF->urgp[1] = 0; - - /* Calculate TCP checksum. */ - BUF->tcpchksum = 0; - BUF->tcpchksum = ~(uip_tcpchksum()); - - ip_send_nolen: - -#if UIP_CONF_IPV6 - BUF->vtc = 0x60; - BUF->tcflow = 0x00; - BUF->flow = 0x00; -#else /* UIP_CONF_IPV6 */ - BUF->vhl = 0x45; - BUF->tos = 0; - BUF->ipoffset[0] = BUF->ipoffset[1] = 0; - ++ipid; - BUF->ipid[0] = ipid >> 8; - BUF->ipid[1] = ipid & 0xff; - /* Calculate IP checksum. */ - BUF->ipchksum = 0; - BUF->ipchksum = ~(uip_ipchksum()); - DEBUG_PRINTF("uip ip_send_nolen: chkecum 0x%04x\n", uip_ipchksum()); -#endif /* UIP_CONF_IPV6 */ - - UIP_STAT(++uip_stat.tcp.sent); - send: - DEBUG_PRINTF("Sending packet with length %d (%d)\n", uip_len, - (BUF->len[0] << 8) | BUF->len[1]); - - UIP_STAT(++uip_stat.ip.sent); - /* Return and let the caller do the actual transmission. */ - uip_flags = 0; - return; - drop: - uip_len = 0; - uip_flags = 0; - return; -} -/*---------------------------------------------------------------------------*/ -u16_t -htons(u16_t val) -{ - return HTONS(val); -} -/*---------------------------------------------------------------------------*/ -void -uip_send(const void *data, int len) -{ - uip_slen = len; - if(len > 0) { - if(data != uip_sappdata) { - memcpy(uip_sappdata, (data), uip_slen); - } - } -} -/** @} */ diff --git a/libraries/UIPEthernet/utility/uip.h b/libraries/UIPEthernet/utility/uip.h deleted file mode 100644 index 4fc0452..0000000 --- a/libraries/UIPEthernet/utility/uip.h +++ /dev/null @@ -1,1601 +0,0 @@ - -/** - * \addtogroup uip - * @{ - */ - -/** - * \file - * Header file for the uIP TCP/IP stack. - * \author Adam Dunkels - * - * The uIP TCP/IP stack header file contains definitions for a number - * of C macros that are used by uIP programs as well as internal uIP - * structures, TCP/IP header structures and function declarations. - * - */ - - -/* - * Copyright (c) 2001-2003, Adam Dunkels. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote - * products derived from this software without specific prior - * written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS - * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * This file is part of the uIP TCP/IP stack. - * - * $Id: uip.h,v 1.40 2006/06/08 07:12:07 adam Exp $ - * - */ - -#ifndef __UIP_H__ -#define __UIP_H__ - -#include "uipopt.h" - -/** - * Repressentation of an IP address. - * - */ -typedef u16_t uip_ip4addr_t[2]; -typedef u16_t uip_ip6addr_t[8]; -#if UIP_CONF_IPV6 -typedef uip_ip6addr_t uip_ipaddr_t; -#else /* UIP_CONF_IPV6 */ -typedef uip_ip4addr_t uip_ipaddr_t; -#endif /* UIP_CONF_IPV6 */ - -/*---------------------------------------------------------------------------*/ -/* First, the functions that should be called from the - * system. Initialization, the periodic timer and incoming packets are - * handled by the following three functions. - */ - -/** - * \defgroup uipconffunc uIP configuration functions - * @{ - * - * The uIP configuration functions are used for setting run-time - * parameters in uIP such as IP addresses. - */ - -/** - * Set the IP address of this host. - * - * The IP address is represented as a 4-byte array where the first - * octet of the IP address is put in the first member of the 4-byte - * array. - * - * Example: - \code - - uip_ipaddr_t addr; - - uip_ipaddr(&addr, 192,168,1,2); - uip_sethostaddr(&addr); - - \endcode - * \param addr A pointer to an IP address of type uip_ipaddr_t; - * - * \sa uip_ipaddr() - * - * \hideinitializer - */ -#define uip_sethostaddr(addr) uip_ipaddr_copy(uip_hostaddr, (addr)) - -/** - * Get the IP address of this host. - * - * The IP address is represented as a 4-byte array where the first - * octet of the IP address is put in the first member of the 4-byte - * array. - * - * Example: - \code - uip_ipaddr_t hostaddr; - - uip_gethostaddr(&hostaddr); - \endcode - * \param addr A pointer to a uip_ipaddr_t variable that will be - * filled in with the currently configured IP address. - * - * \hideinitializer - */ -#define uip_gethostaddr(addr) uip_ipaddr_copy((addr), uip_hostaddr) - -/** - * Set the default router's IP address. - * - * \param addr A pointer to a uip_ipaddr_t variable containing the IP - * address of the default router. - * - * \sa uip_ipaddr() - * - * \hideinitializer - */ -#define uip_setdraddr(addr) uip_ipaddr_copy(uip_draddr, (addr)) - -/** - * Set the netmask. - * - * \param addr A pointer to a uip_ipaddr_t variable containing the IP - * address of the netmask. - * - * \sa uip_ipaddr() - * - * \hideinitializer - */ -#define uip_setnetmask(addr) uip_ipaddr_copy(uip_netmask, (addr)) - - -/** - * Get the default router's IP address. - * - * \param addr A pointer to a uip_ipaddr_t variable that will be - * filled in with the IP address of the default router. - * - * \hideinitializer - */ -#define uip_getdraddr(addr) uip_ipaddr_copy((addr), uip_draddr) - -/** - * Get the netmask. - * - * \param addr A pointer to a uip_ipaddr_t variable that will be - * filled in with the value of the netmask. - * - * \hideinitializer - */ -#define uip_getnetmask(addr) uip_ipaddr_copy((addr), uip_netmask) - -/** @} */ - -/** - * \defgroup uipinit uIP initialization functions - * @{ - * - * The uIP initialization functions are used for booting uIP. - */ - -/** - * uIP initialization function. - * - * This function should be called at boot up to initilize the uIP - * TCP/IP stack. - */ -void uip_init(void); - -/** - * uIP initialization function. - * - * This function may be used at boot time to set the initial ip_id. - */ -void uip_setipid(u16_t id); - -/** @} */ - -/** - * \defgroup uipdevfunc uIP device driver functions - * @{ - * - * These functions are used by a network device driver for interacting - * with uIP. - */ - -/** - * Process an incoming packet. - * - * This function should be called when the device driver has received - * a packet from the network. The packet from the device driver must - * be present in the uip_buf buffer, and the length of the packet - * should be placed in the uip_len variable. - * - * When the function returns, there may be an outbound packet placed - * in the uip_buf packet buffer. If so, the uip_len variable is set to - * the length of the packet. If no packet is to be sent out, the - * uip_len variable is set to 0. - * - * The usual way of calling the function is presented by the source - * code below. - \code - uip_len = devicedriver_poll(); - if(uip_len > 0) { - uip_input(); - if(uip_len > 0) { - devicedriver_send(); - } - } - \endcode - * - * \note If you are writing a uIP device driver that needs ARP - * (Address Resolution Protocol), e.g., when running uIP over - * Ethernet, you will need to call the uIP ARP code before calling - * this function: - \code - #define BUF ((struct uip_eth_hdr *)&uip_buf[0]) - uip_len = ethernet_devicedrver_poll(); - if(uip_len > 0) { - if(BUF->type == HTONS(UIP_ETHTYPE_IP)) { - uip_arp_ipin(); - uip_input(); - if(uip_len > 0) { - uip_arp_out(); - ethernet_devicedriver_send(); - } - } else if(BUF->type == HTONS(UIP_ETHTYPE_ARP)) { - uip_arp_arpin(); - if(uip_len > 0) { - ethernet_devicedriver_send(); - } - } - \endcode - * - * \hideinitializer - */ -#define uip_input() uip_process(UIP_DATA) - -/** - * Periodic processing for a connection identified by its number. - * - * This function does the necessary periodic processing (timers, - * polling) for a uIP TCP conneciton, and should be called when the - * periodic uIP timer goes off. It should be called for every - * connection, regardless of whether they are open of closed. - * - * When the function returns, it may have an outbound packet waiting - * for service in the uIP packet buffer, and if so the uip_len - * variable is set to a value larger than zero. The device driver - * should be called to send out the packet. - * - * The ususal way of calling the function is through a for() loop like - * this: - \code - for(i = 0; i < UIP_CONNS; ++i) { - uip_periodic(i); - if(uip_len > 0) { - devicedriver_send(); - } - } - \endcode - * - * \note If you are writing a uIP device driver that needs ARP - * (Address Resolution Protocol), e.g., when running uIP over - * Ethernet, you will need to call the uip_arp_out() function before - * calling the device driver: - \code - for(i = 0; i < UIP_CONNS; ++i) { - uip_periodic(i); - if(uip_len > 0) { - uip_arp_out(); - ethernet_devicedriver_send(); - } - } - \endcode - * - * \param conn The number of the connection which is to be periodically polled. - * - * \hideinitializer - */ -#define uip_periodic(conn) do { uip_conn = &uip_conns[conn]; \ - uip_process(UIP_TIMER); } while (0) - -/** - * - * - */ -#define uip_conn_active(conn) (uip_conns[conn].tcpstateflags != UIP_CLOSED) - -/** - * Perform periodic processing for a connection identified by a pointer - * to its structure. - * - * Same as uip_periodic() but takes a pointer to the actual uip_conn - * struct instead of an integer as its argument. This function can be - * used to force periodic processing of a specific connection. - * - * \param conn A pointer to the uip_conn struct for the connection to - * be processed. - * - * \hideinitializer - */ -#define uip_periodic_conn(conn) do { uip_conn = conn; \ - uip_process(UIP_TIMER); } while (0) - -/** - * Reuqest that a particular connection should be polled. - * - * Similar to uip_periodic_conn() but does not perform any timer - * processing. The application is polled for new data. - * - * \param conn A pointer to the uip_conn struct for the connection to - * be processed. - * - * \hideinitializer - */ -#define uip_poll_conn(conn) do { uip_conn = conn; \ - uip_process(UIP_POLL_REQUEST); } while (0) - - -#if UIP_UDP -/** - * Periodic processing for a UDP connection identified by its number. - * - * This function is essentially the same as uip_periodic(), but for - * UDP connections. It is called in a similar fashion as the - * uip_periodic() function: - \code - for(i = 0; i < UIP_UDP_CONNS; i++) { - uip_udp_periodic(i); - if(uip_len > 0) { - devicedriver_send(); - } - } - \endcode - * - * \note As for the uip_periodic() function, special care has to be - * taken when using uIP together with ARP and Ethernet: - \code - for(i = 0; i < UIP_UDP_CONNS; i++) { - uip_udp_periodic(i); - if(uip_len > 0) { - uip_arp_out(); - ethernet_devicedriver_send(); - } - } - \endcode - * - * \param conn The number of the UDP connection to be processed. - * - * \hideinitializer - */ -#define uip_udp_periodic(conn) do { uip_udp_conn = &uip_udp_conns[conn]; \ - uip_process(UIP_UDP_TIMER); } while (0) - -/** - * Periodic processing for a UDP connection identified by a pointer to - * its structure. - * - * Same as uip_udp_periodic() but takes a pointer to the actual - * uip_conn struct instead of an integer as its argument. This - * function can be used to force periodic processing of a specific - * connection. - * - * \param conn A pointer to the uip_udp_conn struct for the connection - * to be processed. - * - * \hideinitializer - */ -#define uip_udp_periodic_conn(conn) do { uip_udp_conn = conn; \ - uip_process(UIP_UDP_TIMER); } while (0) - - -#endif /* UIP_UDP */ - -/** - * The uIP packet buffer. - * - * The uip_buf array is used to hold incoming and outgoing - * packets. The device driver should place incoming data into this - * buffer. When sending data, the device driver should read the link - * level headers and the TCP/IP headers from this buffer. The size of - * the link level headers is configured by the UIP_LLH_LEN define. - * - * \note The application data need not be placed in this buffer, so - * the device driver must read it from the place pointed to by the - * uip_appdata pointer as illustrated by the following example: - \code - void - devicedriver_send(void) - { - hwsend(&uip_buf[0], UIP_LLH_LEN); - if(uip_len <= UIP_LLH_LEN + UIP_TCPIP_HLEN) { - hwsend(&uip_buf[UIP_LLH_LEN], uip_len - UIP_LLH_LEN); - } else { - hwsend(&uip_buf[UIP_LLH_LEN], UIP_TCPIP_HLEN); - hwsend(uip_appdata, uip_len - UIP_TCPIP_HLEN - UIP_LLH_LEN); - } - } - \endcode - */ -extern u8_t uip_buf[UIP_BUFSIZE+2]; - -/** @} */ - -/*---------------------------------------------------------------------------*/ -/* Functions that are used by the uIP application program. Opening and - * closing connections, sending and receiving data, etc. is all - * handled by the functions below. -*/ -/** - * \defgroup uipappfunc uIP application functions - * @{ - * - * Functions used by an application running of top of uIP. - */ - -/** - * Start listening to the specified port. - * - * \note Since this function expects the port number in network byte - * order, a conversion using HTONS() or htons() is necessary. - * - \code - uip_listen(HTONS(80)); - \endcode - * - * \param port A 16-bit port number in network byte order. - */ -void uip_listen(u16_t port); - -/** - * Stop listening to the specified port. - * - * \note Since this function expects the port number in network byte - * order, a conversion using HTONS() or htons() is necessary. - * - \code - uip_unlisten(HTONS(80)); - \endcode - * - * \param port A 16-bit port number in network byte order. - */ -void uip_unlisten(u16_t port); - -/** - * Connect to a remote host using TCP. - * - * This function is used to start a new connection to the specified - * port on the specied host. It allocates a new connection identifier, - * sets the connection to the SYN_SENT state and sets the - * retransmission timer to 0. This will cause a TCP SYN segment to be - * sent out the next time this connection is periodically processed, - * which usually is done within 0.5 seconds after the call to - * uip_connect(). - * - * \note This function is avaliable only if support for active open - * has been configured by defining UIP_ACTIVE_OPEN to 1 in uipopt.h. - * - * \note Since this function requires the port number to be in network - * byte order, a conversion using HTONS() or htons() is necessary. - * - \code - uip_ipaddr_t ipaddr; - - uip_ipaddr(&ipaddr, 192,168,1,2); - uip_connect(&ipaddr, HTONS(80)); - \endcode - * - * \param ripaddr The IP address of the remote hot. - * - * \param port A 16-bit port number in network byte order. - * - * \return A pointer to the uIP connection identifier for the new connection, - * or NULL if no connection could be allocated. - * - */ -struct uip_conn *uip_connect(uip_ipaddr_t *ripaddr, u16_t port); - - - -/** - * \internal - * - * Check if a connection has outstanding (i.e., unacknowledged) data. - * - * \param conn A pointer to the uip_conn structure for the connection. - * - * \hideinitializer - */ -#define uip_outstanding(conn) ((conn)->len) - -/** - * Send data on the current connection. - * - * This function is used to send out a single segment of TCP - * data. Only applications that have been invoked by uIP for event - * processing can send data. - * - * The amount of data that actually is sent out after a call to this - * funcion is determined by the maximum amount of data TCP allows. uIP - * will automatically crop the data so that only the appropriate - * amount of data is sent. The function uip_mss() can be used to query - * uIP for the amount of data that actually will be sent. - * - * \note This function does not guarantee that the sent data will - * arrive at the destination. If the data is lost in the network, the - * application will be invoked with the uip_rexmit() event being - * set. The application will then have to resend the data using this - * function. - * - * \param data A pointer to the data which is to be sent. - * - * \param len The maximum amount of data bytes to be sent. - * - * \hideinitializer - */ -void uip_send(const void *data, int len); - -/** - * The length of any incoming data that is currently avaliable (if avaliable) - * in the uip_appdata buffer. - * - * The test function uip_data() must first be used to check if there - * is any data available at all. - * - * \hideinitializer - */ -/*void uip_datalen(void);*/ -#define uip_datalen() uip_len - -/** - * The length of any out-of-band data (urgent data) that has arrived - * on the connection. - * - * \note The configuration parameter UIP_URGDATA must be set for this - * function to be enabled. - * - * \hideinitializer - */ -#define uip_urgdatalen() uip_urglen - -/** - * Close the current connection. - * - * This function will close the current connection in a nice way. - * - * \hideinitializer - */ -#define uip_close() (uip_flags = UIP_CLOSE) - -/** - * Abort the current connection. - * - * This function will abort (reset) the current connection, and is - * usually used when an error has occured that prevents using the - * uip_close() function. - * - * \hideinitializer - */ -#define uip_abort() (uip_flags = UIP_ABORT) - -/** - * Tell the sending host to stop sending data. - * - * This function will close our receiver's window so that we stop - * receiving data for the current connection. - * - * \hideinitializer - */ -#define uip_stop() (uip_conn->tcpstateflags |= UIP_STOPPED) - -/** - * Find out if the current connection has been previously stopped with - * uip_stop(). - * - * \hideinitializer - */ -#define uip_stopped(conn) ((conn)->tcpstateflags & UIP_STOPPED) - -/** - * Restart the current connection, if is has previously been stopped - * with uip_stop(). - * - * This function will open the receiver's window again so that we - * start receiving data for the current connection. - * - * \hideinitializer - */ -#define uip_restart() do { uip_flags |= UIP_NEWDATA; \ - uip_conn->tcpstateflags &= ~UIP_STOPPED; \ - } while(0) - - -/* uIP tests that can be made to determine in what state the current - connection is, and what the application function should do. */ - -/** - * Is the current connection a UDP connection? - * - * This function checks whether the current connection is a UDP connection. - * - * \hideinitializer - * - */ -#define uip_udpconnection() (uip_conn == NULL) - -/** - * Is new incoming data available? - * - * Will reduce to non-zero if there is new data for the application - * present at the uip_appdata pointer. The size of the data is - * avaliable through the uip_len variable. - * - * \hideinitializer - */ -#define uip_newdata() (uip_flags & UIP_NEWDATA) - -/** - * Has previously sent data been acknowledged? - * - * Will reduce to non-zero if the previously sent data has been - * acknowledged by the remote host. This means that the application - * can send new data. - * - * \hideinitializer - */ -#define uip_acked() (uip_flags & UIP_ACKDATA) - -/** - * Has the connection just been connected? - * - * Reduces to non-zero if the current connection has been connected to - * a remote host. This will happen both if the connection has been - * actively opened (with uip_connect()) or passively opened (with - * uip_listen()). - * - * \hideinitializer - */ -#define uip_connected() (uip_flags & UIP_CONNECTED) - -/** - * Has the connection been closed by the other end? - * - * Is non-zero if the connection has been closed by the remote - * host. The application may then do the necessary clean-ups. - * - * \hideinitializer - */ -#define uip_closed() (uip_flags & UIP_CLOSE) - -/** - * Has the connection been aborted by the other end? - * - * Non-zero if the current connection has been aborted (reset) by the - * remote host. - * - * \hideinitializer - */ -#define uip_aborted() (uip_flags & UIP_ABORT) - -/** - * Has the connection timed out? - * - * Non-zero if the current connection has been aborted due to too many - * retransmissions. - * - * \hideinitializer - */ -#define uip_timedout() (uip_flags & UIP_TIMEDOUT) - -/** - * Do we need to retransmit previously data? - * - * Reduces to non-zero if the previously sent data has been lost in - * the network, and the application should retransmit it. The - * application should send the exact same data as it did the last - * time, using the uip_send() function. - * - * \hideinitializer - */ -#define uip_rexmit() (uip_flags & UIP_REXMIT) - -/** - * Is the connection being polled by uIP? - * - * Is non-zero if the reason the application is invoked is that the - * current connection has been idle for a while and should be - * polled. - * - * The polling event can be used for sending data without having to - * wait for the remote host to send data. - * - * \hideinitializer - */ -#define uip_poll() (uip_flags & UIP_POLL) - -/** - * Get the initial maxium segment size (MSS) of the current - * connection. - * - * \hideinitializer - */ -#define uip_initialmss() (uip_conn->initialmss) - -/** - * Get the current maxium segment size that can be sent on the current - * connection. - * - * The current maxiumum segment size that can be sent on the - * connection is computed from the receiver's window and the MSS of - * the connection (which also is available by calling - * uip_initialmss()). - * - * \hideinitializer - */ -#define uip_mss() (uip_conn->mss) - -/** - * Set up a new UDP connection. - * - * This function sets up a new UDP connection. The function will - * automatically allocate an unused local port for the new - * connection. However, another port can be chosen by using the - * uip_udp_bind() call, after the uip_udp_new() function has been - * called. - * - * Example: - \code - uip_ipaddr_t addr; - struct uip_udp_conn *c; - - uip_ipaddr(&addr, 192,168,2,1); - c = uip_udp_new(&addr, HTONS(12345)); - if(c != NULL) { - uip_udp_bind(c, HTONS(12344)); - } - \endcode - * \param ripaddr The IP address of the remote host. - * - * \param rport The remote port number in network byte order. - * - * \return The uip_udp_conn structure for the new connection or NULL - * if no connection could be allocated. - */ -struct uip_udp_conn *uip_udp_new(uip_ipaddr_t *ripaddr, u16_t rport); - -/** - * Removed a UDP connection. - * - * \param conn A pointer to the uip_udp_conn structure for the connection. - * - * \hideinitializer - */ -#define uip_udp_remove(conn) (conn)->lport = 0 - -/** - * Bind a UDP connection to a local port. - * - * \param conn A pointer to the uip_udp_conn structure for the - * connection. - * - * \param port The local port number, in network byte order. - * - * \hideinitializer - */ -#define uip_udp_bind(conn, port) (conn)->lport = port - -/** - * Send a UDP datagram of length len on the current connection. - * - * This function can only be called in response to a UDP event (poll - * or newdata). The data must be present in the uip_buf buffer, at the - * place pointed to by the uip_appdata pointer. - * - * \param len The length of the data in the uip_buf buffer. - * - * \hideinitializer - */ -#define uip_udp_send(len) uip_send((char *)uip_appdata, len) - -/** @} */ - -/* uIP convenience and converting functions. */ - -/** - * \defgroup uipconvfunc uIP conversion functions - * @{ - * - * These functions can be used for converting between different data - * formats used by uIP. - */ - -/** - * Construct an IP address from four bytes. - * - * This function constructs an IP address of the type that uIP handles - * internally from four bytes. The function is handy for specifying IP - * addresses to use with e.g. the uip_connect() function. - * - * Example: - \code - uip_ipaddr_t ipaddr; - struct uip_conn *c; - - uip_ipaddr(&ipaddr, 192,168,1,2); - c = uip_connect(&ipaddr, HTONS(80)); - \endcode - * - * \param addr A pointer to a uip_ipaddr_t variable that will be - * filled in with the IP address. - * - * \param addr0 The first octet of the IP address. - * \param addr1 The second octet of the IP address. - * \param addr2 The third octet of the IP address. - * \param addr3 The forth octet of the IP address. - * - * \hideinitializer - */ -#define uip_ipaddr(addr, addr0,addr1,addr2,addr3) do { \ - ((u16_t *)(addr))[0] = HTONS(((addr0) << 8) | (addr1)); \ - ((u16_t *)(addr))[1] = HTONS(((addr2) << 8) | (addr3)); \ - } while(0) - -/** - * Construct an IPv6 address from eight 16-bit words. - * - * This function constructs an IPv6 address. - * - * \hideinitializer - */ -#define uip_ip6addr(addr, addr0,addr1,addr2,addr3,addr4,addr5,addr6,addr7) do { \ - ((u16_t *)(addr))[0] = HTONS((addr0)); \ - ((u16_t *)(addr))[1] = HTONS((addr1)); \ - ((u16_t *)(addr))[2] = HTONS((addr2)); \ - ((u16_t *)(addr))[3] = HTONS((addr3)); \ - ((u16_t *)(addr))[4] = HTONS((addr4)); \ - ((u16_t *)(addr))[5] = HTONS((addr5)); \ - ((u16_t *)(addr))[6] = HTONS((addr6)); \ - ((u16_t *)(addr))[7] = HTONS((addr7)); \ - } while(0) - -/** - * Copy an IP address to another IP address. - * - * Copies an IP address from one place to another. - * - * Example: - \code - uip_ipaddr_t ipaddr1, ipaddr2; - - uip_ipaddr(&ipaddr1, 192,16,1,2); - uip_ipaddr_copy(&ipaddr2, &ipaddr1); - \endcode - * - * \param dest The destination for the copy. - * \param src The source from where to copy. - * - * \hideinitializer - */ -#if !UIP_CONF_IPV6 -#define uip_ipaddr_copy(dest, src) do { \ - ((u16_t *)dest)[0] = ((u16_t *)src)[0]; \ - ((u16_t *)dest)[1] = ((u16_t *)src)[1]; \ - } while(0) -#else /* !UIP_CONF_IPV6 */ -#define uip_ipaddr_copy(dest, src) memcpy(dest, src, sizeof(uip_ip6addr_t)) -#endif /* !UIP_CONF_IPV6 */ - -/** - * Compare two IP addresses - * - * Compares two IP addresses. - * - * Example: - \code - uip_ipaddr_t ipaddr1, ipaddr2; - - uip_ipaddr(&ipaddr1, 192,16,1,2); - if(uip_ipaddr_cmp(&ipaddr2, &ipaddr1)) { - printf("They are the same"); - } - \endcode - * - * \param addr1 The first IP address. - * \param addr2 The second IP address. - * - * \hideinitializer - */ -#if !UIP_CONF_IPV6 -#define uip_ipaddr_cmp(addr1, addr2) (((u16_t *)addr1)[0] == ((u16_t *)addr2)[0] && \ - ((u16_t *)addr1)[1] == ((u16_t *)addr2)[1]) -#else /* !UIP_CONF_IPV6 */ -#define uip_ipaddr_cmp(addr1, addr2) (memcmp(addr1, addr2, sizeof(uip_ip6addr_t)) == 0) -#endif /* !UIP_CONF_IPV6 */ - -/** - * Compare two IP addresses with netmasks - * - * Compares two IP addresses with netmasks. The masks are used to mask - * out the bits that are to be compared. - * - * Example: - \code - uip_ipaddr_t ipaddr1, ipaddr2, mask; - - uip_ipaddr(&mask, 255,255,255,0); - uip_ipaddr(&ipaddr1, 192,16,1,2); - uip_ipaddr(&ipaddr2, 192,16,1,3); - if(uip_ipaddr_maskcmp(&ipaddr1, &ipaddr2, &mask)) { - printf("They are the same"); - } - \endcode - * - * \param addr1 The first IP address. - * \param addr2 The second IP address. - * \param mask The netmask. - * - * \hideinitializer - */ -#define uip_ipaddr_maskcmp(addr1, addr2, mask) \ - (((((u16_t *)addr1)[0] & ((u16_t *)mask)[0]) == \ - (((u16_t *)addr2)[0] & ((u16_t *)mask)[0])) && \ - ((((u16_t *)addr1)[1] & ((u16_t *)mask)[1]) == \ - (((u16_t *)addr2)[1] & ((u16_t *)mask)[1]))) - - -/** - * Mask out the network part of an IP address. - * - * Masks out the network part of an IP address, given the address and - * the netmask. - * - * Example: - \code - uip_ipaddr_t ipaddr1, ipaddr2, netmask; - - uip_ipaddr(&ipaddr1, 192,16,1,2); - uip_ipaddr(&netmask, 255,255,255,0); - uip_ipaddr_mask(&ipaddr2, &ipaddr1, &netmask); - \endcode - * - * In the example above, the variable "ipaddr2" will contain the IP - * address 192.168.1.0. - * - * \param dest Where the result is to be placed. - * \param src The IP address. - * \param mask The netmask. - * - * \hideinitializer - */ -#define uip_ipaddr_mask(dest, src, mask) do { \ - ((u16_t *)dest)[0] = ((u16_t *)src)[0] & ((u16_t *)mask)[0]; \ - ((u16_t *)dest)[1] = ((u16_t *)src)[1] & ((u16_t *)mask)[1]; \ - } while(0) - -/** - * Pick the first octet of an IP address. - * - * Picks out the first octet of an IP address. - * - * Example: - \code - uip_ipaddr_t ipaddr; - u8_t octet; - - uip_ipaddr(&ipaddr, 1,2,3,4); - octet = uip_ipaddr1(&ipaddr); - \endcode - * - * In the example above, the variable "octet" will contain the value 1. - * - * \hideinitializer - */ -#define uip_ipaddr1(addr) (htons(((u16_t *)(addr))[0]) >> 8) - -/** - * Pick the second octet of an IP address. - * - * Picks out the second octet of an IP address. - * - * Example: - \code - uip_ipaddr_t ipaddr; - u8_t octet; - - uip_ipaddr(&ipaddr, 1,2,3,4); - octet = uip_ipaddr2(&ipaddr); - \endcode - * - * In the example above, the variable "octet" will contain the value 2. - * - * \hideinitializer - */ -#define uip_ipaddr2(addr) (htons(((u16_t *)(addr))[0]) & 0xff) - -/** - * Pick the third octet of an IP address. - * - * Picks out the third octet of an IP address. - * - * Example: - \code - uip_ipaddr_t ipaddr; - u8_t octet; - - uip_ipaddr(&ipaddr, 1,2,3,4); - octet = uip_ipaddr3(&ipaddr); - \endcode - * - * In the example above, the variable "octet" will contain the value 3. - * - * \hideinitializer - */ -#define uip_ipaddr3(addr) (htons(((u16_t *)(addr))[1]) >> 8) - -/** - * Pick the fourth octet of an IP address. - * - * Picks out the fourth octet of an IP address. - * - * Example: - \code - uip_ipaddr_t ipaddr; - u8_t octet; - - uip_ipaddr(&ipaddr, 1,2,3,4); - octet = uip_ipaddr4(&ipaddr); - \endcode - * - * In the example above, the variable "octet" will contain the value 4. - * - * \hideinitializer - */ -#define uip_ipaddr4(addr) (htons(((u16_t *)(addr))[1]) & 0xff) - -/** - * Convert 16-bit quantity from host byte order to network byte order. - * - * This macro is primarily used for converting constants from host - * byte order to network byte order. For converting variables to - * network byte order, use the htons() function instead. - * - * \hideinitializer - */ -#ifndef HTONS -# if UIP_BYTE_ORDER == UIP_BIG_ENDIAN -# define HTONS(n) (n) -# else /* UIP_BYTE_ORDER == UIP_BIG_ENDIAN */ -# define HTONS(n) (u16_t)((((u16_t) (n)) << 8) | (((u16_t) (n)) >> 8)) -# endif /* UIP_BYTE_ORDER == UIP_BIG_ENDIAN */ -#else -#error "HTONS already defined!" -#endif /* HTONS */ - -/** - * Convert 16-bit quantity from host byte order to network byte order. - * - * This function is primarily used for converting variables from host - * byte order to network byte order. For converting constants to - * network byte order, use the HTONS() macro instead. - */ -#ifndef htons -u16_t htons(u16_t val); -#endif /* htons */ -#ifndef ntohs -#define ntohs htons -#endif - -/** @} */ - -/** - * Pointer to the application data in the packet buffer. - * - * This pointer points to the application data when the application is - * called. If the application wishes to send data, the application may - * use this space to write the data into before calling uip_send(). - */ -extern void *uip_appdata; - -#if UIP_URGDATA > 0 -/* u8_t *uip_urgdata: - * - * This pointer points to any urgent data that has been received. Only - * present if compiled with support for urgent data (UIP_URGDATA). - */ -extern void *uip_urgdata; -#endif /* UIP_URGDATA > 0 */ - - -/** - * \defgroup uipdrivervars Variables used in uIP device drivers - * @{ - * - * uIP has a few global variables that are used in device drivers for - * uIP. - */ - -/** - * The length of the packet in the uip_buf buffer. - * - * The global variable uip_len holds the length of the packet in the - * uip_buf buffer. - * - * When the network device driver calls the uIP input function, - * uip_len should be set to the length of the packet in the uip_buf - * buffer. - * - * When sending packets, the device driver should use the contents of - * the uip_len variable to determine the length of the outgoing - * packet. - * - */ -extern u16_t uip_len; - -/** @} */ - -#if UIP_URGDATA > 0 -extern u16_t uip_urglen, uip_surglen; -#endif /* UIP_URGDATA > 0 */ - - -/** - * Representation of a uIP TCP connection. - * - * The uip_conn structure is used for identifying a connection. All - * but one field in the structure are to be considered read-only by an - * application. The only exception is the appstate field whos purpose - * is to let the application store application-specific state (e.g., - * file pointers) for the connection. The type of this field is - * configured in the "uipopt.h" header file. - */ -struct uip_conn { - uip_ipaddr_t ripaddr; /**< The IP address of the remote host. */ - - u16_t lport; /**< The local TCP port, in network byte order. */ - u16_t rport; /**< The local remote TCP port, in network byte - order. */ - - u8_t rcv_nxt[4]; /**< The sequence number that we expect to - receive next. */ - u8_t snd_nxt[4]; /**< The sequence number that was last sent by - us. */ - u16_t len; /**< Length of the data that was previously sent. */ - u16_t mss; /**< Current maximum segment size for the - connection. */ - u16_t initialmss; /**< Initial maximum segment size for the - connection. */ - u8_t sa; /**< Retransmission time-out calculation state - variable. */ - u8_t sv; /**< Retransmission time-out calculation state - variable. */ - u8_t rto; /**< Retransmission time-out. */ - u8_t tcpstateflags; /**< TCP state and flags. */ - u8_t timer; /**< The retransmission timer. */ - u8_t nrtx; /**< The number of retransmissions for the last - segment sent. */ - - /** The application state. */ - uip_tcp_appstate_t appstate; -}; - - -/** - * Pointer to the current TCP connection. - * - * The uip_conn pointer can be used to access the current TCP - * connection. - */ -extern struct uip_conn *uip_conn; -/* The array containing all uIP connections. */ -extern struct uip_conn uip_conns[UIP_CONNS]; -/** - * \addtogroup uiparch - * @{ - */ - -/** - * 4-byte array used for the 32-bit sequence number calculations. - */ -extern u8_t uip_acc32[4]; - -/** @} */ - - -#if UIP_UDP -/** - * Representation of a uIP UDP connection. - */ -struct uip_udp_conn { - uip_ipaddr_t ripaddr; /**< The IP address of the remote peer. */ - u16_t lport; /**< The local port number in network byte order. */ - u16_t rport; /**< The remote port number in network byte order. */ - u8_t ttl; /**< Default time-to-live. */ - - /** The application state. */ - uip_udp_appstate_t appstate; -}; - -/** - * The current UDP connection. - */ -extern struct uip_udp_conn *uip_udp_conn; -extern struct uip_udp_conn uip_udp_conns[UIP_UDP_CONNS]; -#endif /* UIP_UDP */ - -/** - * The structure holding the TCP/IP statistics that are gathered if - * UIP_STATISTICS is set to 1. - * - */ -struct uip_stats { - struct { - uip_stats_t drop; /**< Number of dropped packets at the IP - layer. */ - uip_stats_t recv; /**< Number of received packets at the IP - layer. */ - uip_stats_t sent; /**< Number of sent packets at the IP - layer. */ - uip_stats_t vhlerr; /**< Number of packets dropped due to wrong - IP version or header length. */ - uip_stats_t hblenerr; /**< Number of packets dropped due to wrong - IP length, high byte. */ - uip_stats_t lblenerr; /**< Number of packets dropped due to wrong - IP length, low byte. */ - uip_stats_t fragerr; /**< Number of packets dropped since they - were IP fragments. */ - uip_stats_t chkerr; /**< Number of packets dropped due to IP - checksum errors. */ - uip_stats_t protoerr; /**< Number of packets dropped since they - were neither ICMP, UDP nor TCP. */ - } ip; /**< IP statistics. */ - struct { - uip_stats_t drop; /**< Number of dropped ICMP packets. */ - uip_stats_t recv; /**< Number of received ICMP packets. */ - uip_stats_t sent; /**< Number of sent ICMP packets. */ - uip_stats_t typeerr; /**< Number of ICMP packets with a wrong - type. */ - } icmp; /**< ICMP statistics. */ - struct { - uip_stats_t drop; /**< Number of dropped TCP segments. */ - uip_stats_t recv; /**< Number of recived TCP segments. */ - uip_stats_t sent; /**< Number of sent TCP segments. */ - uip_stats_t chkerr; /**< Number of TCP segments with a bad - checksum. */ - uip_stats_t ackerr; /**< Number of TCP segments with a bad ACK - number. */ - uip_stats_t rst; /**< Number of recevied TCP RST (reset) segments. */ - uip_stats_t rexmit; /**< Number of retransmitted TCP segments. */ - uip_stats_t syndrop; /**< Number of dropped SYNs due to too few - connections was avaliable. */ - uip_stats_t synrst; /**< Number of SYNs for closed ports, - triggering a RST. */ - } tcp; /**< TCP statistics. */ -#if UIP_UDP - struct { - uip_stats_t drop; /**< Number of dropped UDP segments. */ - uip_stats_t recv; /**< Number of recived UDP segments. */ - uip_stats_t sent; /**< Number of sent UDP segments. */ - uip_stats_t chkerr; /**< Number of UDP segments with a bad - checksum. */ - } udp; /**< UDP statistics. */ -#endif /* UIP_UDP */ -}; - -/** - * The uIP TCP/IP statistics. - * - * This is the variable in which the uIP TCP/IP statistics are gathered. - */ -extern struct uip_stats uip_stat; - - -/*---------------------------------------------------------------------------*/ -/* All the stuff below this point is internal to uIP and should not be - * used directly by an application or by a device driver. - */ -/*---------------------------------------------------------------------------*/ -/* u8_t uip_flags: - * - * When the application is called, uip_flags will contain the flags - * that are defined in this file. Please read below for more - * infomation. - */ -extern u8_t uip_flags; - -/* The following flags may be set in the global variable uip_flags - before calling the application callback. The UIP_ACKDATA, - UIP_NEWDATA, and UIP_CLOSE flags may both be set at the same time, - whereas the others are mutualy exclusive. Note that these flags - should *NOT* be accessed directly, but only through the uIP - functions/macros. */ - -#define UIP_ACKDATA 1 /* Signifies that the outstanding data was - acked and the application should send - out new data instead of retransmitting - the last data. */ -#define UIP_NEWDATA 2 /* Flags the fact that the peer has sent - us new data. */ -#define UIP_REXMIT 4 /* Tells the application to retransmit the - data that was last sent. */ -#define UIP_POLL 8 /* Used for polling the application, to - check if the application has data that - it wants to send. */ -#define UIP_CLOSE 16 /* The remote host has closed the - connection, thus the connection has - gone away. Or the application signals - that it wants to close the - connection. */ -#define UIP_ABORT 32 /* The remote host has aborted the - connection, thus the connection has - gone away. Or the application signals - that it wants to abort the - connection. */ -#define UIP_CONNECTED 64 /* We have got a connection from a remote - host and have set up a new connection - for it, or an active connection has - been successfully established. */ - -#define UIP_TIMEDOUT 128 /* The connection has been aborted due to - too many retransmissions. */ - -/* uip_process(flag): - * - * The actual uIP function which does all the work. - */ -void uip_process(u8_t flag); - -/* The following flags are passed as an argument to the uip_process() - function. They are used to distinguish between the two cases where - uip_process() is called. It can be called either because we have - incoming data that should be processed, or because the periodic - timer has fired. These values are never used directly, but only in - the macrose defined in this file. */ - -#define UIP_DATA 1 /* Tells uIP that there is incoming - data in the uip_buf buffer. The - length of the data is stored in the - global variable uip_len. */ -#define UIP_TIMER 2 /* Tells uIP that the periodic timer - has fired. */ -#define UIP_POLL_REQUEST 3 /* Tells uIP that a connection should - be polled. */ -#define UIP_UDP_SEND_CONN 4 /* Tells uIP that a UDP datagram - should be constructed in the - uip_buf buffer. */ -#if UIP_UDP -#define UIP_UDP_TIMER 5 -#endif /* UIP_UDP */ - -/* The TCP states used in the uip_conn->tcpstateflags. */ -#define UIP_CLOSED 0 -#define UIP_SYN_RCVD 1 -#define UIP_SYN_SENT 2 -#define UIP_ESTABLISHED 3 -#define UIP_FIN_WAIT_1 4 -#define UIP_FIN_WAIT_2 5 -#define UIP_CLOSING 6 -#define UIP_TIME_WAIT 7 -#define UIP_LAST_ACK 8 -#define UIP_TS_MASK 15 - -#define UIP_STOPPED 16 - -/* The TCP and IP headers. */ -struct uip_tcpip_hdr { -#if UIP_CONF_IPV6 - /* IPv6 header. */ - u8_t vtc, - tcflow; - u16_t flow; - u8_t len[2]; - u8_t proto, ttl; - uip_ip6addr_t srcipaddr, destipaddr; -#else /* UIP_CONF_IPV6 */ - /* IPv4 header. */ - u8_t vhl, - tos, - len[2], - ipid[2], - ipoffset[2], - ttl, - proto; - u16_t ipchksum; - u16_t srcipaddr[2], - destipaddr[2]; -#endif /* UIP_CONF_IPV6 */ - - /* TCP header. */ - u16_t srcport, - destport; - u8_t seqno[4], - ackno[4], - tcpoffset, - flags, - wnd[2]; - u16_t tcpchksum; - u8_t urgp[2]; - u8_t optdata[4]; -}; - -/* The ICMP and IP headers. */ -struct uip_icmpip_hdr { -#if UIP_CONF_IPV6 - /* IPv6 header. */ - u8_t vtc, - tcf; - u16_t flow; - u8_t len[2]; - u8_t proto, ttl; - uip_ip6addr_t srcipaddr, destipaddr; -#else /* UIP_CONF_IPV6 */ - /* IPv4 header. */ - u8_t vhl, - tos, - len[2], - ipid[2], - ipoffset[2], - ttl, - proto; - u16_t ipchksum; - u16_t srcipaddr[2], - destipaddr[2]; -#endif /* UIP_CONF_IPV6 */ - - /* ICMP (echo) header. */ - u8_t type, icode; - u16_t icmpchksum; -#if !UIP_CONF_IPV6 - u16_t id, seqno; -#else /* !UIP_CONF_IPV6 */ - u8_t flags, reserved1, reserved2, reserved3; - u8_t icmp6data[16]; - u8_t options[1]; -#endif /* !UIP_CONF_IPV6 */ -}; - - -/* The UDP and IP headers. */ -struct uip_udpip_hdr { -#if UIP_CONF_IPV6 - /* IPv6 header. */ - u8_t vtc, - tcf; - u16_t flow; - u8_t len[2]; - u8_t proto, ttl; - uip_ip6addr_t srcipaddr, destipaddr; -#else /* UIP_CONF_IPV6 */ - /* IP header. */ - u8_t vhl, - tos, - len[2], - ipid[2], - ipoffset[2], - ttl, - proto; - u16_t ipchksum; - u16_t srcipaddr[2], - destipaddr[2]; -#endif /* UIP_CONF_IPV6 */ - - /* UDP header. */ - u16_t srcport, - destport; - u16_t udplen; - u16_t udpchksum; -}; - - - -/** - * The buffer size available for user data in the \ref uip_buf buffer. - * - * This macro holds the available size for user data in the \ref - * uip_buf buffer. The macro is intended to be used for checking - * bounds of available user data. - * - * Example: - \code - snprintf(uip_appdata, UIP_APPDATA_SIZE, "%u\n", i); - \endcode - * - * \hideinitializer - */ -#define UIP_APPDATA_SIZE (UIP_BUFSIZE - UIP_LLH_LEN - UIP_TCPIP_HLEN) - - -#define UIP_PROTO_ICMP 1 -#define UIP_PROTO_TCP 6 -#define UIP_PROTO_UDP 17 -#define UIP_PROTO_ICMP6 58 - -/* Header sizes. */ -#if UIP_CONF_IPV6 -#define UIP_IPH_LEN 40 -#else /* UIP_CONF_IPV6 */ -#define UIP_IPH_LEN 20 /* Size of IP header */ -#endif /* UIP_CONF_IPV6 */ -#define UIP_UDPH_LEN 8 /* Size of UDP header */ -#define UIP_TCPH_LEN 20 /* Size of TCP header */ -#define UIP_IPUDPH_LEN (UIP_UDPH_LEN + UIP_IPH_LEN) /* Size of IP + - UDP - header */ -#define UIP_IPTCPH_LEN (UIP_TCPH_LEN + UIP_IPH_LEN) /* Size of IP + - TCP - header */ -#define UIP_TCPIP_HLEN UIP_IPTCPH_LEN - - -#if UIP_FIXEDADDR -extern const uip_ipaddr_t uip_hostaddr, uip_netmask, uip_draddr; -#else /* UIP_FIXEDADDR */ -extern uip_ipaddr_t uip_hostaddr, uip_netmask, uip_draddr; -#endif /* UIP_FIXEDADDR */ - - - -/** - * Representation of a 48-bit Ethernet address. - */ -struct uip_eth_addr { - u8_t addr[6]; -}; - -/** - * Calculate the Internet checksum over a buffer. - * - * The Internet checksum is the one's complement of the one's - * complement sum of all 16-bit words in the buffer. - * - * See RFC1071. - * - * \param buf A pointer to the buffer over which the checksum is to be - * computed. - * - * \param len The length of the buffer over which the checksum is to - * be computed. - * - * \return The Internet checksum of the buffer. - */ -u16_t uip_chksum(u16_t *buf, u16_t len); - -/** - * Calculate the IP header checksum of the packet header in uip_buf. - * - * The IP header checksum is the Internet checksum of the 20 bytes of - * the IP header. - * - * \return The IP header checksum of the IP header in the uip_buf - * buffer. - */ -u16_t uip_ipchksum(void); - -/** - * Calculate the TCP checksum of the packet in uip_buf and uip_appdata. - * - * The TCP checksum is the Internet checksum of data contents of the - * TCP segment, and a pseudo-header as defined in RFC793. - * - * \return The TCP checksum of the TCP segment in uip_buf and pointed - * to by uip_appdata. - */ -u16_t uip_tcpchksum(void); - -/** - * Calculate the UDP checksum of the packet in uip_buf and uip_appdata. - * - * The UDP checksum is the Internet checksum of data contents of the - * UDP segment, and a pseudo-header as defined in RFC768. - * - * \return The UDP checksum of the UDP segment in uip_buf and pointed - * to by uip_appdata. - */ -u16_t uip_udpchksum(void); - - -#endif /* __UIP_H__ */ - - -/** @} */ diff --git a/libraries/UIPEthernet/utility/uip_arch.h b/libraries/UIPEthernet/utility/uip_arch.h deleted file mode 100644 index 71fd84b..0000000 --- a/libraries/UIPEthernet/utility/uip_arch.h +++ /dev/null @@ -1,138 +0,0 @@ -/** - * \addtogroup uip - * {@ - */ - -/** - * \defgroup uiparch Architecture specific uIP functions - * @{ - * - * The functions in the architecture specific module implement the IP - * check sum and 32-bit additions. - * - * The IP checksum calculation is the most computationally expensive - * operation in the TCP/IP stack and it therefore pays off to - * implement this in efficient assembler. The purpose of the uip-arch - * module is to let the checksum functions to be implemented in - * architecture specific assembler. - * - */ - -/** - * \file - * Declarations of architecture specific functions. - * \author Adam Dunkels - */ - -/* - * Copyright (c) 2001, Adam Dunkels. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote - * products derived from this software without specific prior - * written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS - * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * This file is part of the uIP TCP/IP stack. - * - * $Id: uip_arch.h,v 1.2 2006/06/07 09:15:19 adam Exp $ - * - */ - -#ifndef __UIP_ARCH_H__ -#define __UIP_ARCH_H__ - -#include "uip.h" - -/** - * Carry out a 32-bit addition. - * - * Because not all architectures for which uIP is intended has native - * 32-bit arithmetic, uIP uses an external C function for doing the - * required 32-bit additions in the TCP protocol processing. This - * function should add the two arguments and place the result in the - * global variable uip_acc32. - * - * \note The 32-bit integer pointed to by the op32 parameter and the - * result in the uip_acc32 variable are in network byte order (big - * endian). - * - * \param op32 A pointer to a 4-byte array representing a 32-bit - * integer in network byte order (big endian). - * - * \param op16 A 16-bit integer in host byte order. - */ -void uip_add32(u8_t *op32, u16_t op16); - -/** - * Calculate the Internet checksum over a buffer. - * - * The Internet checksum is the one's complement of the one's - * complement sum of all 16-bit words in the buffer. - * - * See RFC1071. - * - * \note This function is not called in the current version of uIP, - * but future versions might make use of it. - * - * \param buf A pointer to the buffer over which the checksum is to be - * computed. - * - * \param len The length of the buffer over which the checksum is to - * be computed. - * - * \return The Internet checksum of the buffer. - */ -u16_t uip_chksum(u16_t *buf, u16_t len); - -/** - * Calculate the IP header checksum of the packet header in uip_buf. - * - * The IP header checksum is the Internet checksum of the 20 bytes of - * the IP header. - * - * \return The IP header checksum of the IP header in the uip_buf - * buffer. - */ -u16_t uip_ipchksum(void); - -/** - * Calculate the TCP checksum of the packet in uip_buf and uip_appdata. - * - * The TCP checksum is the Internet checksum of data contents of the - * TCP segment, and a pseudo-header as defined in RFC793. - * - * \note The uip_appdata pointer that points to the packet data may - * point anywhere in memory, so it is not possible to simply calculate - * the Internet checksum of the contents of the uip_buf buffer. - * - * \return The TCP checksum of the TCP segment in uip_buf and pointed - * to by uip_appdata. - */ -u16_t uip_tcpchksum(void); - -u16_t uip_udpchksum(void); - -/** @} */ -/** @} */ - -#endif /* __UIP_ARCH_H__ */ diff --git a/libraries/UIPEthernet/utility/uip_arp.c b/libraries/UIPEthernet/utility/uip_arp.c deleted file mode 100644 index 44ca7c4..0000000 --- a/libraries/UIPEthernet/utility/uip_arp.c +++ /dev/null @@ -1,423 +0,0 @@ -/** - * \addtogroup uip - * @{ - */ - -/** - * \defgroup uiparp uIP Address Resolution Protocol - * @{ - * - * The Address Resolution Protocol ARP is used for mapping between IP - * addresses and link level addresses such as the Ethernet MAC - * addresses. ARP uses broadcast queries to ask for the link level - * address of a known IP address and the host which is configured with - * the IP address for which the query was meant, will respond with its - * link level address. - * - * \note This ARP implementation only supports Ethernet. - */ - -/** - * \file - * Implementation of the ARP Address Resolution Protocol. - * \author Adam Dunkels - * - */ - -/* - * Copyright (c) 2001-2003, Adam Dunkels. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote - * products derived from this software without specific prior - * written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS - * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * This file is part of the uIP TCP/IP stack. - * - * $Id: uip_arp.c,v 1.8 2006/06/02 23:36:21 adam Exp $ - * - */ - - -#include "uip_arp.h" - -#include - -struct arp_hdr { - struct uip_eth_hdr ethhdr; - u16_t hwtype; - u16_t protocol; - u8_t hwlen; - u8_t protolen; - u16_t opcode; - struct uip_eth_addr shwaddr; - u16_t sipaddr[2]; - struct uip_eth_addr dhwaddr; - u16_t dipaddr[2]; -}; - -struct ethip_hdr { - struct uip_eth_hdr ethhdr; - /* IP header. */ - u8_t vhl, - tos, - len[2], - ipid[2], - ipoffset[2], - ttl, - proto; - u16_t ipchksum; - u16_t srcipaddr[2], - destipaddr[2]; -}; - -#define ARP_REQUEST 1 -#define ARP_REPLY 2 - -#define ARP_HWTYPE_ETH 1 - -struct arp_entry { - u16_t ipaddr[2]; - struct uip_eth_addr ethaddr; - u8_t time; -}; - -static const struct uip_eth_addr broadcast_ethaddr = - {{0xff,0xff,0xff,0xff,0xff,0xff}}; -static const u16_t broadcast_ipaddr[2] = {0xffff,0xffff}; - -static struct arp_entry arp_table[UIP_ARPTAB_SIZE]; -static u16_t ipaddr[2]; -static u8_t i, c; - -static u8_t arptime; -static u8_t tmpage; - -#define BUF ((struct arp_hdr *)&uip_buf[0]) -#define IPBUF ((struct ethip_hdr *)&uip_buf[0]) -/*-----------------------------------------------------------------------------------*/ -/** - * Initialize the ARP module. - * - */ -/*-----------------------------------------------------------------------------------*/ -void -uip_arp_init(void) -{ - for(i = 0; i < UIP_ARPTAB_SIZE; ++i) { - memset(arp_table[i].ipaddr, 0, 4); - } -} -/*-----------------------------------------------------------------------------------*/ -/** - * Periodic ARP processing function. - * - * This function performs periodic timer processing in the ARP module - * and should be called at regular intervals. The recommended interval - * is 10 seconds between the calls. - * - */ -/*-----------------------------------------------------------------------------------*/ -void -uip_arp_timer(void) -{ - struct arp_entry *tabptr; - - ++arptime; - for(i = 0; i < UIP_ARPTAB_SIZE; ++i) { - tabptr = &arp_table[i]; - if((tabptr->ipaddr[0] | tabptr->ipaddr[1]) != 0 && - arptime - tabptr->time >= UIP_ARP_MAXAGE) { - memset(tabptr->ipaddr, 0, 4); - } - } - -} -/*-----------------------------------------------------------------------------------*/ -static void -uip_arp_update(u16_t *ipaddr, struct uip_eth_addr *ethaddr) -{ - register struct arp_entry *tabptr; - /* Walk through the ARP mapping table and try to find an entry to - update. If none is found, the IP -> MAC address mapping is - inserted in the ARP table. */ - for(i = 0; i < UIP_ARPTAB_SIZE; ++i) { - - tabptr = &arp_table[i]; - /* Only check those entries that are actually in use. */ - if(tabptr->ipaddr[0] != 0 && - tabptr->ipaddr[1] != 0) { - - /* Check if the source IP address of the incoming packet matches - the IP address in this ARP table entry. */ - if(ipaddr[0] == tabptr->ipaddr[0] && - ipaddr[1] == tabptr->ipaddr[1]) { - - /* An old entry found, update this and return. */ - memcpy(tabptr->ethaddr.addr, ethaddr->addr, 6); - tabptr->time = arptime; - - return; - } - } - } - - /* If we get here, no existing ARP table entry was found, so we - create one. */ - - /* First, we try to find an unused entry in the ARP table. */ - for(i = 0; i < UIP_ARPTAB_SIZE; ++i) { - tabptr = &arp_table[i]; - if(tabptr->ipaddr[0] == 0 && - tabptr->ipaddr[1] == 0) { - break; - } - } - - /* If no unused entry is found, we try to find the oldest entry and - throw it away. */ - if(i == UIP_ARPTAB_SIZE) { - tmpage = 0; - c = 0; - for(i = 0; i < UIP_ARPTAB_SIZE; ++i) { - tabptr = &arp_table[i]; - if(arptime - tabptr->time > tmpage) { - tmpage = arptime - tabptr->time; - c = i; - } - } - i = c; - tabptr = &arp_table[i]; - } - - /* Now, i is the ARP table entry which we will fill with the new - information. */ - memcpy(tabptr->ipaddr, ipaddr, 4); - memcpy(tabptr->ethaddr.addr, ethaddr->addr, 6); - tabptr->time = arptime; -} -/*-----------------------------------------------------------------------------------*/ -/** - * ARP processing for incoming IP packets - * - * This function should be called by the device driver when an IP - * packet has been received. The function will check if the address is - * in the ARP cache, and if so the ARP cache entry will be - * refreshed. If no ARP cache entry was found, a new one is created. - * - * This function expects an IP packet with a prepended Ethernet header - * in the uip_buf[] buffer, and the length of the packet in the global - * variable uip_len. - */ -/*-----------------------------------------------------------------------------------*/ -//#if 0 -void -uip_arp_ipin(void) -{ - uip_len -= sizeof(struct uip_eth_hdr); - - /* Only insert/update an entry if the source IP address of the - incoming IP packet comes from a host on the local network. */ - if((IPBUF->srcipaddr[0] & uip_netmask[0]) != - (uip_hostaddr[0] & uip_netmask[0])) { - return; - } - if((IPBUF->srcipaddr[1] & uip_netmask[1]) != - (uip_hostaddr[1] & uip_netmask[1])) { - return; - } - uip_arp_update(IPBUF->srcipaddr, &(IPBUF->ethhdr.src)); - - return; -} -//#endif /* 0 */ -/*-----------------------------------------------------------------------------------*/ -/** - * ARP processing for incoming ARP packets. - * - * This function should be called by the device driver when an ARP - * packet has been received. The function will act differently - * depending on the ARP packet type: if it is a reply for a request - * that we previously sent out, the ARP cache will be filled in with - * the values from the ARP reply. If the incoming ARP packet is an ARP - * request for our IP address, an ARP reply packet is created and put - * into the uip_buf[] buffer. - * - * When the function returns, the value of the global variable uip_len - * indicates whether the device driver should send out a packet or - * not. If uip_len is zero, no packet should be sent. If uip_len is - * non-zero, it contains the length of the outbound packet that is - * present in the uip_buf[] buffer. - * - * This function expects an ARP packet with a prepended Ethernet - * header in the uip_buf[] buffer, and the length of the packet in the - * global variable uip_len. - */ -/*-----------------------------------------------------------------------------------*/ -void -uip_arp_arpin(void) -{ - - if(uip_len < sizeof(struct arp_hdr)) { - uip_len = 0; - return; - } - uip_len = 0; - - switch(BUF->opcode) { - case HTONS(ARP_REQUEST): - /* ARP request. If it asked for our address, we send out a - reply. */ - if(uip_ipaddr_cmp(BUF->dipaddr, uip_hostaddr)) { - /* First, we register the one who made the request in our ARP - table, since it is likely that we will do more communication - with this host in the future. */ - uip_arp_update(BUF->sipaddr, &BUF->shwaddr); - - /* The reply opcode is 2. */ - BUF->opcode = HTONS(2); - - memcpy(BUF->dhwaddr.addr, BUF->shwaddr.addr, 6); - memcpy(BUF->shwaddr.addr, uip_ethaddr.addr, 6); - memcpy(BUF->ethhdr.src.addr, uip_ethaddr.addr, 6); - memcpy(BUF->ethhdr.dest.addr, BUF->dhwaddr.addr, 6); - - BUF->dipaddr[0] = BUF->sipaddr[0]; - BUF->dipaddr[1] = BUF->sipaddr[1]; - BUF->sipaddr[0] = uip_hostaddr[0]; - BUF->sipaddr[1] = uip_hostaddr[1]; - - BUF->ethhdr.type = HTONS(UIP_ETHTYPE_ARP); - uip_len = sizeof(struct arp_hdr); - } - break; - case HTONS(ARP_REPLY): - /* ARP reply. We insert or update the ARP table if it was meant - for us. */ - if(uip_ipaddr_cmp(BUF->dipaddr, uip_hostaddr)) { - uip_arp_update(BUF->sipaddr, &BUF->shwaddr); - } - break; - } - - return; -} -/*-----------------------------------------------------------------------------------*/ -/** - * Prepend Ethernet header to an outbound IP packet and see if we need - * to send out an ARP request. - * - * This function should be called before sending out an IP packet. The - * function checks the destination IP address of the IP packet to see - * what Ethernet MAC address that should be used as a destination MAC - * address on the Ethernet. - * - * If the destination IP address is in the local network (determined - * by logical ANDing of netmask and our IP address), the function - * checks the ARP cache to see if an entry for the destination IP - * address is found. If so, an Ethernet header is prepended and the - * function returns. If no ARP cache entry is found for the - * destination IP address, the packet in the uip_buf[] is replaced by - * an ARP request packet for the IP address. The IP packet is dropped - * and it is assumed that they higher level protocols (e.g., TCP) - * eventually will retransmit the dropped packet. - * - * If the destination IP address is not on the local network, the IP - * address of the default router is used instead. - * - * When the function returns, a packet is present in the uip_buf[] - * buffer, and the length of the packet is in the global variable - * uip_len. - */ -/*-----------------------------------------------------------------------------------*/ -void -uip_arp_out(void) -{ - struct arp_entry *tabptr; - - /* Find the destination IP address in the ARP table and construct - the Ethernet header. If the destination IP addres isn't on the - local network, we use the default router's IP address instead. - - If not ARP table entry is found, we overwrite the original IP - packet with an ARP request for the IP address. */ - - /* First check if destination is a local broadcast. */ - if(uip_ipaddr_cmp(IPBUF->destipaddr, broadcast_ipaddr)) { - memcpy(IPBUF->ethhdr.dest.addr, broadcast_ethaddr.addr, 6); - } else { - /* Check if the destination address is on the local network. */ - if(!uip_ipaddr_maskcmp(IPBUF->destipaddr, uip_hostaddr, uip_netmask)) { - /* Destination address was not on the local network, so we need to - use the default router's IP address instead of the destination - address when determining the MAC address. */ - uip_ipaddr_copy(ipaddr, uip_draddr); - } else { - /* Else, we use the destination IP address. */ - uip_ipaddr_copy(ipaddr, IPBUF->destipaddr); - } - - for(i = 0; i < UIP_ARPTAB_SIZE; ++i) { - tabptr = &arp_table[i]; - if(uip_ipaddr_cmp(ipaddr, tabptr->ipaddr)) { - break; - } - } - - if(i == UIP_ARPTAB_SIZE) { - /* The destination address was not in our ARP table, so we - overwrite the IP packet with an ARP request. */ - - memset(BUF->ethhdr.dest.addr, 0xff, 6); - memset(BUF->dhwaddr.addr, 0x00, 6); - memcpy(BUF->ethhdr.src.addr, uip_ethaddr.addr, 6); - memcpy(BUF->shwaddr.addr, uip_ethaddr.addr, 6); - - uip_ipaddr_copy(BUF->dipaddr, ipaddr); - uip_ipaddr_copy(BUF->sipaddr, uip_hostaddr); - BUF->opcode = HTONS(ARP_REQUEST); /* ARP request. */ - BUF->hwtype = HTONS(ARP_HWTYPE_ETH); - BUF->protocol = HTONS(UIP_ETHTYPE_IP); - BUF->hwlen = 6; - BUF->protolen = 4; - BUF->ethhdr.type = HTONS(UIP_ETHTYPE_ARP); - - uip_appdata = &uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN]; - - uip_len = sizeof(struct arp_hdr); - return; - } - - /* Build an ethernet header. */ - memcpy(IPBUF->ethhdr.dest.addr, tabptr->ethaddr.addr, 6); - } - memcpy(IPBUF->ethhdr.src.addr, uip_ethaddr.addr, 6); - - IPBUF->ethhdr.type = HTONS(UIP_ETHTYPE_IP); - - uip_len += sizeof(struct uip_eth_hdr); -} -/*-----------------------------------------------------------------------------------*/ - -/** @} */ -/** @} */ diff --git a/libraries/UIPEthernet/utility/uip_arp.h b/libraries/UIPEthernet/utility/uip_arp.h deleted file mode 100644 index ef93054..0000000 --- a/libraries/UIPEthernet/utility/uip_arp.h +++ /dev/null @@ -1,144 +0,0 @@ -/** - * \addtogroup uip - * @{ - */ - -/** - * \addtogroup uiparp - * @{ - */ - -/** - * \file - * Macros and definitions for the ARP module. - * \author Adam Dunkels - */ - - -/* - * Copyright (c) 2001-2003, Adam Dunkels. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote - * products derived from this software without specific prior - * written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS - * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * This file is part of the uIP TCP/IP stack. - * - * $Id: uip_arp.h,v 1.5 2006/06/11 21:46:39 adam Exp $ - * - */ - -#ifndef __UIP_ARP_H__ -#define __UIP_ARP_H__ - -#include "uip.h" - - -extern struct uip_eth_addr uip_ethaddr; - -/** - * The Ethernet header. - */ -struct uip_eth_hdr { - struct uip_eth_addr dest; - struct uip_eth_addr src; - u16_t type; -}; - -#define UIP_ETHTYPE_ARP 0x0806 -#define UIP_ETHTYPE_IP 0x0800 -#define UIP_ETHTYPE_IP6 0x86dd - - -/* The uip_arp_init() function must be called before any of the other - ARP functions. */ -void uip_arp_init(void); - -/* The uip_arp_ipin() function should be called whenever an IP packet - arrives from the Ethernet. This function refreshes the ARP table or - inserts a new mapping if none exists. The function assumes that an - IP packet with an Ethernet header is present in the uip_buf buffer - and that the length of the packet is in the uip_len variable. */ -void uip_arp_ipin(void); -//#define uip_arp_ipin() - -/* The uip_arp_arpin() should be called when an ARP packet is received - by the Ethernet driver. This function also assumes that the - Ethernet frame is present in the uip_buf buffer. When the - uip_arp_arpin() function returns, the contents of the uip_buf - buffer should be sent out on the Ethernet if the uip_len variable - is > 0. */ -void uip_arp_arpin(void); - -/* The uip_arp_out() function should be called when an IP packet - should be sent out on the Ethernet. This function creates an - Ethernet header before the IP header in the uip_buf buffer. The - Ethernet header will have the correct Ethernet MAC destination - address filled in if an ARP table entry for the destination IP - address (or the IP address of the default router) is present. If no - such table entry is found, the IP packet is overwritten with an ARP - request and we rely on TCP to retransmit the packet that was - overwritten. In any case, the uip_len variable holds the length of - the Ethernet frame that should be transmitted. */ -void uip_arp_out(void); - -/* The uip_arp_timer() function should be called every ten seconds. It - is responsible for flushing old entries in the ARP table. */ -void uip_arp_timer(void); - -/** @} */ - -/** - * \addtogroup uipconffunc - * @{ - */ - - -/** - * Specifiy the Ethernet MAC address. - * - * The ARP code needs to know the MAC address of the Ethernet card in - * order to be able to respond to ARP queries and to generate working - * Ethernet headers. - * - * \note This macro only specifies the Ethernet MAC address to the ARP - * code. It cannot be used to change the MAC address of the Ethernet - * card. - * - * \param eaddr A pointer to a struct uip_eth_addr containing the - * Ethernet MAC address of the Ethernet card. - * - * \hideinitializer - */ -#define uip_setethaddr(eaddr) do {uip_ethaddr.addr[0] = eaddr.addr[0]; \ - uip_ethaddr.addr[1] = eaddr.addr[1];\ - uip_ethaddr.addr[2] = eaddr.addr[2];\ - uip_ethaddr.addr[3] = eaddr.addr[3];\ - uip_ethaddr.addr[4] = eaddr.addr[4];\ - uip_ethaddr.addr[5] = eaddr.addr[5];} while(0) - -/** @} */ -/** @} */ - -#endif /* __UIP_ARP_H__ */ diff --git a/libraries/UIPEthernet/utility/uip_clock.h b/libraries/UIPEthernet/utility/uip_clock.h deleted file mode 100644 index 6dd72be..0000000 --- a/libraries/UIPEthernet/utility/uip_clock.h +++ /dev/null @@ -1,88 +0,0 @@ -/** - * \defgroup clock Clock interface - * - * The clock interface is the interface between the \ref timer "timer library" - * and the platform specific clock functionality. The clock - * interface must be implemented for each platform that uses the \ref - * timer "timer library". - * - * The clock interface does only one this: it measures time. The clock - * interface provides a macro, CLOCK_SECOND, which corresponds to one - * second of system time. - * - * \sa \ref timer "Timer library" - * - * @{ - */ - -/* - * Copyright (c) 2004, Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the Institute nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * This file is part of the uIP TCP/IP stack - * - * Author: Adam Dunkels - * - * $Id: clock.h,v 1.3 2006/06/11 21:46:39 adam Exp $ - */ -#ifndef __UIP_CLOCK_H__ -#define __UIP_CLOCK_H__ - -#include "clock-arch.h" - -/** - * Initialize the clock library. - * - * This function initializes the clock library and should be called - * from the main() function of the system. - * - */ -void uip_clock_init(void); - -/** - * Get the current clock time. - * - * This function returns the current system clock time. - * - * \return The current clock time, measured in system ticks. - */ -clock_time_t clock_time(void); - -/** - * A second, measured in system clock time. - * - * \hideinitializer - */ -#ifdef CLOCK_CONF_SECOND -#define CLOCK_SECOND CLOCK_CONF_SECOND -#else -#define CLOCK_SECOND (clock_time_t)32 -#endif - -#endif /* __CLOCK_H__ */ - -/** @} */ diff --git a/libraries/UIPEthernet/utility/uip_debug.cpp b/libraries/UIPEthernet/utility/uip_debug.cpp deleted file mode 100644 index 444bd0e..0000000 --- a/libraries/UIPEthernet/utility/uip_debug.cpp +++ /dev/null @@ -1,170 +0,0 @@ -#include -#include -#include -#include -extern "C" { - #import "utility/uip.h" -} - -struct uip_conn con[UIP_CONNS]; - -void -UIPDebug::uip_debug_printconns() -{ - for(uint8_t i=0;iripaddr,rhs->ripaddr)) - { - Serial.print(" ripaddr: "); - uip_debug_printbytes((const uint8_t *)lhs->ripaddr,4); - Serial.print(" -> "); - uip_debug_printbytes((const uint8_t *)rhs->ripaddr,4); - Serial.println(); - uip_ipaddr_copy(lhs->ripaddr,rhs->ripaddr); - changed = true; - } - if (lhs->lport != rhs->lport) - { - Serial.print(" lport: "); - Serial.print(htons(lhs->lport)); - Serial.print(" -> "); - Serial.println(htons(rhs->lport)); - lhs->lport = rhs->lport; - changed = true; - } - if (lhs->rport != rhs->rport) - { - Serial.print(" rport: "); - Serial.print(htons(lhs->rport)); - Serial.print(" -> "); - Serial.println(htons(rhs->rport)); - lhs->rport = rhs->rport; - changed = true; - } - if ((uint32_t)lhs->rcv_nxt[0] != (uint32_t)rhs->rcv_nxt[0]) - { - Serial.print(" rcv_nxt: "); - uip_debug_printbytes(lhs->rcv_nxt,4); - Serial.print(" -> "); - uip_debug_printbytes(rhs->rcv_nxt,4); - *((uint32_t *)&lhs->rcv_nxt[0]) = (uint32_t)rhs->rcv_nxt[0]; - Serial.println(); - changed = true; - } - if ((uint32_t)lhs->snd_nxt[0] != (uint32_t)rhs->snd_nxt[0]) - { - Serial.print(" snd_nxt: "); - uip_debug_printbytes(lhs->snd_nxt,4); - Serial.print(" -> "); - uip_debug_printbytes(rhs->snd_nxt,4); - *((uint32_t *)&lhs->snd_nxt[0]) = (uint32_t)rhs->snd_nxt[0]; - Serial.println(); - changed = true; - } - if (lhs->len != rhs->len) - { - Serial.print(" len: "); - Serial.print(lhs->len); - Serial.print(" -> "); - Serial.println(rhs->len); - lhs->len = rhs->len; - changed = true; - } - if (lhs->mss != rhs->mss) - { - Serial.print(" mss: "); - Serial.print(lhs->mss); - Serial.print(" -> "); - Serial.println(rhs->mss); - lhs->mss = rhs->mss; - changed = true; - } - if (lhs->initialmss != rhs->initialmss) - { - Serial.print(" initialmss: "); - Serial.print(lhs->initialmss); - Serial.print(" -> "); - Serial.println(rhs->initialmss); - lhs->initialmss = rhs->initialmss; - changed = true; - } - if (lhs->sa != rhs->sa) - { - Serial.print(" sa: "); - Serial.print(lhs->sa); - Serial.print(" -> "); - Serial.println(rhs->sa); - lhs->sa = rhs->sa; - changed = true; - } - if (lhs->sv != rhs->sv) - { - Serial.print(" sv: "); - Serial.print(lhs->sv); - Serial.print(" -> "); - Serial.println(rhs->sv); - lhs->sv = rhs->sv; - changed = true; - } - if (lhs->rto != rhs->rto) - { - Serial.print(" rto: "); - Serial.print(lhs->rto); - Serial.print(" -> "); - Serial.println(rhs->rto); - lhs->rto = rhs->rto; - changed = true; - } - if (lhs->tcpstateflags != rhs->tcpstateflags) - { - Serial.print(" tcpstateflags: "); - Serial.print(lhs->tcpstateflags); - Serial.print(" -> "); - Serial.println(rhs->tcpstateflags); - lhs->tcpstateflags = rhs->tcpstateflags; - changed = true; - } - if (lhs->timer != rhs->timer) - { - Serial.print(" timer: "); - Serial.print(lhs->timer); - Serial.print(" -> "); - Serial.println(rhs->timer); - lhs->timer = rhs->timer; - changed = true; - } - if (lhs->nrtx != rhs->nrtx) - { - Serial.print(" nrtx: "); - Serial.print(lhs->nrtx); - Serial.print(" -> "); - Serial.println(rhs->nrtx); - lhs->nrtx = rhs->nrtx; - changed = true; - } - return changed; -} - -void -UIPDebug::uip_debug_printbytes(const uint8_t *data, uint8_t len) -{ - for(uint8_t i=0;i - */ - -/* - * Copyright (c) 2004, Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the Institute nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * This file is part of the uIP TCP/IP stack - * - * Author: Adam Dunkels - * - * $Id: timer.c,v 1.2 2006/06/12 08:00:30 adam Exp $ - */ - -#include "uip_clock.h" -#include "uip_timer.h" - -/*---------------------------------------------------------------------------*/ -/** - * Set a timer. - * - * This function is used to set a timer for a time sometime in the - * future. The function timer_expired() will evaluate to true after - * the timer has expired. - * - * \param t A pointer to the timer - * \param interval The interval before the timer expires. - * - */ -void -uip_timer_set(struct uip_timer *t, clock_time_t interval) -{ - t->interval = interval; - t->start = clock_time(); -} -/*---------------------------------------------------------------------------*/ -/** - * Reset the timer with the same interval. - * - * This function resets the timer with the same interval that was - * given to the timer_set() function. The start point of the interval - * is the exact time that the timer last expired. Therefore, this - * function will cause the timer to be stable over time, unlike the - * timer_rester() function. - * - * \param t A pointer to the timer. - * - * \sa timer_restart() - */ -void -uip_timer_reset(struct uip_timer *t) -{ - t->start += t->interval; -} -/*---------------------------------------------------------------------------*/ -/** - * Restart the timer from the current point in time - * - * This function restarts a timer with the same interval that was - * given to the timer_set() function. The timer will start at the - * current time. - * - * \note A periodic timer will drift if this function is used to reset - * it. For preioric timers, use the timer_reset() function instead. - * - * \param t A pointer to the timer. - * - * \sa timer_reset() - */ -void -uip_timer_restart(struct uip_timer *t) -{ - t->start = clock_time(); -} -/*---------------------------------------------------------------------------*/ -/** - * Check if a timer has expired. - * - * This function tests if a timer has expired and returns true or - * false depending on its status. - * - * \param t A pointer to the timer - * - * \return Non-zero if the timer has expired, zero otherwise. - * - */ -int -uip_timer_expired(struct uip_timer *t) -{ - return (clock_time_t)(clock_time() - t->start) >= (clock_time_t)t->interval; -} -/*---------------------------------------------------------------------------*/ - -/** @} */ diff --git a/libraries/UIPEthernet/utility/uip_timer.h b/libraries/UIPEthernet/utility/uip_timer.h deleted file mode 100644 index f260349..0000000 --- a/libraries/UIPEthernet/utility/uip_timer.h +++ /dev/null @@ -1,86 +0,0 @@ -/** - * \defgroup timer Timer library - * - * The timer library provides functions for setting, resetting and - * restarting timers, and for checking if a timer has expired. An - * application must "manually" check if its timers have expired; this - * is not done automatically. - * - * A timer is declared as a \c struct \c timer and all access to the - * timer is made by a pointer to the declared timer. - * - * \note The timer library uses the \ref clock "Clock library" to - * measure time. Intervals should be specified in the format used by - * the clock library. - * - * @{ - */ - - -/** - * \file - * Timer library header file. - * \author - * Adam Dunkels - */ - -/* - * Copyright (c) 2004, Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the Institute nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * This file is part of the uIP TCP/IP stack - * - * Author: Adam Dunkels - * - * $Id: timer.h,v 1.3 2006/06/11 21:46:39 adam Exp $ - */ -#ifndef __UIP_TIMER_H__ -#define __UIP_TIMER_H__ - -#include "uip_clock.h" - -/** - * A timer. - * - * This structure is used for declaring a timer. The timer must be set - * with timer_set() before it can be used. - * - * \hideinitializer - */ -struct uip_timer { - clock_time_t start; - clock_time_t interval; -}; - -void uip_timer_set(struct uip_timer *t, clock_time_t interval); -void uip_timer_reset(struct uip_timer *t); -void uip_timer_restart(struct uip_timer *t); -int uip_timer_expired(struct uip_timer *t); - -#endif /* __UIP_TIMER_H__ */ - -/** @} */ diff --git a/libraries/UIPEthernet/utility/uipethernet-conf.h b/libraries/UIPEthernet/utility/uipethernet-conf.h deleted file mode 100644 index 733e26e..0000000 --- a/libraries/UIPEthernet/utility/uipethernet-conf.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef UIPETHERNET_CONF_H -#define UIPETHERNET_CONF_H - -/* for TCP */ -#define UIP_SOCKET_NUMPACKETS 5 -#define UIP_CONF_MAX_CONNECTIONS 4 - -/* for UDP */ -#define UIP_CONF_UDP 0//1 -#define UIP_CONF_BROADCAST 0//1 -#define UIP_CONF_UDP_CONNS 0//4 -#define UIP_UDP_NUMPACKETS 0//5 - -/* number of attempts on write before returning number of bytes sent so far - * set to -1 to block until connection is closed by timeout */ -#define UIP_ATTEMPTS_ON_WRITE -1 - -#endif diff --git a/libraries/UIPEthernet/utility/uipopt.h b/libraries/UIPEthernet/utility/uipopt.h deleted file mode 100644 index 42badf8..0000000 --- a/libraries/UIPEthernet/utility/uipopt.h +++ /dev/null @@ -1,543 +0,0 @@ -/** - * \defgroup uipopt Configuration options for uIP - * @{ - * - * uIP is configured using the per-project configuration file - * uipopt.h. This file contains all compile-time options for uIP and - * should be tweaked to match each specific project. The uIP - * distribution contains a documented example "uipopt.h" that can be - * copied and modified for each project. - * - * \note Most of the configuration options in the uipopt.h should not - * be changed, but rather the per-project uip-conf.h file. - */ - -/** - * \file - * Configuration options for uIP. - * \author Adam Dunkels - * - * This file is used for tweaking various configuration options for - * uIP. You should make a copy of this file into one of your project's - * directories instead of editing this example "uipopt.h" file that - * comes with the uIP distribution. - */ - -/* - * Copyright (c) 2001-2003, Adam Dunkels. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote - * products derived from this software without specific prior - * written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS - * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * This file is part of the uIP TCP/IP stack. - * - * $Id: uipopt.h,v 1.4 2006/06/12 08:00:31 adam Exp $ - * - */ - -#ifndef __UIPOPT_H__ -#define __UIPOPT_H__ - -#ifndef UIP_LITTLE_ENDIAN -#define UIP_LITTLE_ENDIAN 3412 -#endif /* UIP_LITTLE_ENDIAN */ -#ifndef UIP_BIG_ENDIAN -#define UIP_BIG_ENDIAN 1234 -#endif /* UIP_BIG_ENDIAN */ - -#include "uip-conf.h" - -/*------------------------------------------------------------------------------*/ - -/** - * \name Static configuration options - * @{ - * - * These configuration options can be used for setting the IP address - * settings statically, but only if UIP_FIXEDADDR is set to 1. The - * configuration options for a specific node includes IP address, - * netmask and default router as well as the Ethernet address. The - * netmask, default router and Ethernet address are appliciable only - * if uIP should be run over Ethernet. - * - * All of these should be changed to suit your project. -*/ - -/** - * Determines if uIP should use a fixed IP address or not. - * - * If uIP should use a fixed IP address, the settings are set in the - * uipopt.h file. If not, the macros uip_sethostaddr(), - * uip_setdraddr() and uip_setnetmask() should be used instead. - * - * \hideinitializer - */ -#define UIP_FIXEDADDR 0 - -/** - * Ping IP address asignment. - * - * uIP uses a "ping" packets for setting its own IP address if this - * option is set. If so, uIP will start with an empty IP address and - * the destination IP address of the first incoming "ping" (ICMP echo) - * packet will be used for setting the hosts IP address. - * - * \note This works only if UIP_FIXEDADDR is 0. - * - * \hideinitializer - */ -#ifdef UIP_CONF_PINGADDRCONF -#define UIP_PINGADDRCONF UIP_CONF_PINGADDRCONF -#else /* UIP_CONF_PINGADDRCONF */ -#define UIP_PINGADDRCONF 0 -#endif /* UIP_CONF_PINGADDRCONF */ - - -/** - * Specifies if the uIP ARP module should be compiled with a fixed - * Ethernet MAC address or not. - * - * If this configuration option is 0, the macro uip_setethaddr() can - * be used to specify the Ethernet address at run-time. - * - * \hideinitializer - */ -#define UIP_FIXEDETHADDR 0 - -/** @} */ -/*------------------------------------------------------------------------------*/ -/** - * \name IP configuration options - * @{ - * - */ -/** - * The IP TTL (time to live) of IP packets sent by uIP. - * - * This should normally not be changed. - */ -#define UIP_TTL 64 - -/** - * Turn on support for IP packet reassembly. - * - * uIP supports reassembly of fragmented IP packets. This features - * requires an additonal amount of RAM to hold the reassembly buffer - * and the reassembly code size is approximately 700 bytes. The - * reassembly buffer is of the same size as the uip_buf buffer - * (configured by UIP_BUFSIZE). - * - * \note IP packet reassembly is not heavily tested. - * - * \hideinitializer - */ -#define UIP_REASSEMBLY 0 - -/** - * The maximum time an IP fragment should wait in the reassembly - * buffer before it is dropped. - * - */ -#define UIP_REASS_MAXAGE 40 - -/** @} */ - -/*------------------------------------------------------------------------------*/ -/** - * \name UDP configuration options - * @{ - */ - -/** - * Toggles wether UDP support should be compiled in or not. - * - * \hideinitializer - */ -#ifdef UIP_CONF_UDP -#define UIP_UDP UIP_CONF_UDP -#else /* UIP_CONF_UDP */ -#define UIP_UDP 0 -#endif /* UIP_CONF_UDP */ - -/** - * Toggles if UDP checksums should be used or not. - * - * \note Support for UDP checksums is currently not included in uIP, - * so this option has no function. - * - * \hideinitializer - */ -#ifdef UIP_CONF_UDP_CHECKSUMS -#define UIP_UDP_CHECKSUMS UIP_CONF_UDP_CHECKSUMS -#else -#define UIP_UDP_CHECKSUMS 0 -#endif - -/** - * The maximum amount of concurrent UDP connections. - * - * \hideinitializer - */ -#ifdef UIP_CONF_UDP_CONNS -#define UIP_UDP_CONNS UIP_CONF_UDP_CONNS -#else /* UIP_CONF_UDP_CONNS */ -#define UIP_UDP_CONNS 10 -#endif /* UIP_CONF_UDP_CONNS */ - -/** - * The name of the function that should be called when UDP datagrams arrive. - * - * \hideinitializer - */ - - -/** @} */ -/*------------------------------------------------------------------------------*/ -/** - * \name TCP configuration options - * @{ - */ - -/** - * Determines if support for opening connections from uIP should be - * compiled in. - * - * If the applications that are running on top of uIP for this project - * do not need to open outgoing TCP connections, this configration - * option can be turned off to reduce the code size of uIP. - * - * \hideinitializer - */ -#define UIP_ACTIVE_OPEN 1 - -/** - * The maximum number of simultaneously open TCP connections. - * - * Since the TCP connections are statically allocated, turning this - * configuration knob down results in less RAM used. Each TCP - * connection requires approximatly 30 bytes of memory. - * - * \hideinitializer - */ -#ifndef UIP_CONF_MAX_CONNECTIONS -#define UIP_CONNS 10 -#else /* UIP_CONF_MAX_CONNECTIONS */ -#define UIP_CONNS UIP_CONF_MAX_CONNECTIONS -#endif /* UIP_CONF_MAX_CONNECTIONS */ - - -/** - * The maximum number of simultaneously listening TCP ports. - * - * Each listening TCP port requires 2 bytes of memory. - * - * \hideinitializer - */ -#ifndef UIP_CONF_MAX_LISTENPORTS -#define UIP_LISTENPORTS 20 -#else /* UIP_CONF_MAX_LISTENPORTS */ -#define UIP_LISTENPORTS UIP_CONF_MAX_LISTENPORTS -#endif /* UIP_CONF_MAX_LISTENPORTS */ - -/** - * Determines if support for TCP urgent data notification should be - * compiled in. - * - * Urgent data (out-of-band data) is a rarely used TCP feature that - * very seldom would be required. - * - * \hideinitializer - */ -#define UIP_URGDATA 0 - -/** - * The initial retransmission timeout counted in timer pulses. - * - * This should not be changed. - */ -#define UIP_RTO 3 - -/** - * The maximum number of times a segment should be retransmitted - * before the connection should be aborted. - * - * This should not be changed. - */ -#define UIP_MAXRTX 8 - -/** - * The maximum number of times a SYN segment should be retransmitted - * before a connection request should be deemed to have been - * unsuccessful. - * - * This should not need to be changed. - */ -#define UIP_MAXSYNRTX 5 - -/** - * The TCP maximum segment size. - * - * This is should not be to set to more than - * UIP_BUFSIZE - UIP_LLH_LEN - UIP_TCPIP_HLEN. - */ -#ifndef UIP_CONF_TCP_MSS -#define UIP_TCP_MSS (UIP_BUFSIZE - UIP_LLH_LEN - UIP_TCPIP_HLEN) -#else -#define UIP_TCP_MSS UIP_CONF_TCP_MSS -#endif - -/** - * The size of the advertised receiver's window. - * - * Should be set low (i.e., to the size of the uip_buf buffer) is the - * application is slow to process incoming data, or high (32768 bytes) - * if the application processes data quickly. - * - * \hideinitializer - */ -#ifndef UIP_CONF_RECEIVE_WINDOW -#define UIP_RECEIVE_WINDOW UIP_TCP_MSS -#else -#define UIP_RECEIVE_WINDOW UIP_CONF_RECEIVE_WINDOW -#endif - -/** - * How long a connection should stay in the TIME_WAIT state. - * - * This configiration option has no real implication, and it should be - * left untouched. - */ -#define UIP_TIME_WAIT_TIMEOUT 120 - - -/** @} */ -/*------------------------------------------------------------------------------*/ -/** - * \name ARP configuration options - * @{ - */ - -/** - * The size of the ARP table. - * - * This option should be set to a larger value if this uIP node will - * have many connections from the local network. - * - * \hideinitializer - */ -#ifdef UIP_CONF_ARPTAB_SIZE -#define UIP_ARPTAB_SIZE UIP_CONF_ARPTAB_SIZE -#else -#define UIP_ARPTAB_SIZE 8 -#endif - -/** - * The maxium age of ARP table entries measured in 10ths of seconds. - * - * An UIP_ARP_MAXAGE of 120 corresponds to 20 minutes (BSD - * default). - */ -#define UIP_ARP_MAXAGE 120 - -/** @} */ - -/*------------------------------------------------------------------------------*/ - -/** - * \name General configuration options - * @{ - */ - -/** - * The size of the uIP packet buffer. - * - * The uIP packet buffer should not be smaller than 60 bytes, and does - * not need to be larger than 1500 bytes. Lower size results in lower - * TCP throughput, larger size results in higher TCP throughput. - * - * \hideinitializer - */ -#ifndef UIP_CONF_BUFFER_SIZE -#define UIP_BUFSIZE 400 -#else /* UIP_CONF_BUFFER_SIZE */ -#define UIP_BUFSIZE UIP_CONF_BUFFER_SIZE -#endif /* UIP_CONF_BUFFER_SIZE */ - - -/** - * Determines if statistics support should be compiled in. - * - * The statistics is useful for debugging and to show the user. - * - * \hideinitializer - */ -#ifndef UIP_CONF_STATISTICS -#define UIP_STATISTICS 0 -#else /* UIP_CONF_STATISTICS */ -#define UIP_STATISTICS UIP_CONF_STATISTICS -#endif /* UIP_CONF_STATISTICS */ - -/** - * Determines if logging of certain events should be compiled in. - * - * This is useful mostly for debugging. The function uip_log() - * must be implemented to suit the architecture of the project, if - * logging is turned on. - * - * \hideinitializer - */ -#ifndef UIP_CONF_LOGGING -#define UIP_LOGGING 0 -#else /* UIP_CONF_LOGGING */ -#define UIP_LOGGING UIP_CONF_LOGGING -#endif /* UIP_CONF_LOGGING */ - -/** - * Broadcast support. - * - * This flag configures IP broadcast support. This is useful only - * together with UDP. - * - * \hideinitializer - * - */ -#if UIP_UDP && UIP_CONF_BROADCAST -#define UIP_BROADCAST UIP_CONF_BROADCAST -#else /* UIP_CONF_BROADCAST */ -#define UIP_BROADCAST 0 -#endif /* UIP_CONF_BROADCAST */ - -/** - * Print out a uIP log message. - * - * This function must be implemented by the module that uses uIP, and - * is called by uIP whenever a log message is generated. - */ -void uip_log(char *msg); - -/** - * The link level header length. - * - * This is the offset into the uip_buf where the IP header can be - * found. For Ethernet, this should be set to 14. For SLIP, this - * should be set to 0. - * - * \hideinitializer - */ -#ifdef UIP_CONF_LLH_LEN -#define UIP_LLH_LEN UIP_CONF_LLH_LEN -#else /* UIP_CONF_LLH_LEN */ -#define UIP_LLH_LEN 14 -#endif /* UIP_CONF_LLH_LEN */ - -/** @} */ -/*------------------------------------------------------------------------------*/ -/** - * \name CPU architecture configuration - * @{ - * - * The CPU architecture configuration is where the endianess of the - * CPU on which uIP is to be run is specified. Most CPUs today are - * little endian, and the most notable exception are the Motorolas - * which are big endian. The BYTE_ORDER macro should be changed to - * reflect the CPU architecture on which uIP is to be run. - */ - -/** - * The byte order of the CPU architecture on which uIP is to be run. - * - * This option can be either BIG_ENDIAN (Motorola byte order) or - * LITTLE_ENDIAN (Intel byte order). - * - * \hideinitializer - */ -#ifdef UIP_CONF_BYTE_ORDER -#define UIP_BYTE_ORDER UIP_CONF_BYTE_ORDER -#else /* UIP_CONF_BYTE_ORDER */ -#define UIP_BYTE_ORDER UIP_LITTLE_ENDIAN -#endif /* UIP_CONF_BYTE_ORDER */ - -/** @} */ -/*------------------------------------------------------------------------------*/ - -/** - * \name Appication specific configurations - * @{ - * - * An uIP application is implemented using a single application - * function that is called by uIP whenever a TCP/IP event occurs. The - * name of this function must be registered with uIP at compile time - * using the UIP_APPCALL definition. - * - * uIP applications can store the application state within the - * uip_conn structure by specifying the type of the application - * structure by typedef:ing the type uip_tcp_appstate_t and uip_udp_appstate_t. - * - * The file containing the definitions must be included in the - * uipopt.h file. - * - * The following example illustrates how this can look. - \code - -void httpd_appcall(void); -#define UIP_APPCALL httpd_appcall - -struct httpd_state { - u8_t state; - u16_t count; - char *dataptr; - char *script; -}; -typedef struct httpd_state uip_tcp_appstate_t - \endcode - */ - -/** - * \var #define UIP_APPCALL - * - * The name of the application function that uIP should call in - * response to TCP/IP events. - * - */ - -/** - * \var typedef uip_tcp_appstate_t - * - * The type of the application state that is to be stored in the - * uip_conn structure. This usually is typedef:ed to a struct holding - * application state information. - */ - -/** - * \var typedef uip_udp_appstate_t - * - * The type of the application state that is to be stored in the - * uip_conn structure. This usually is typedef:ed to a struct holding - * application state information. - */ -/** @} */ -/** @} */ - -#endif /* __UIPOPT_H__ */ diff --git a/libraries/UIPEthernet/utility/util.h b/libraries/UIPEthernet/utility/util.h deleted file mode 100644 index 5042e82..0000000 --- a/libraries/UIPEthernet/utility/util.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef UTIL_H -#define UTIL_H - -#define htons(x) ( ((x)<<8) | (((x)>>8)&0xFF) ) -#define ntohs(x) htons(x) - -#define htonl(x) ( ((x)<<24 & 0xFF000000UL) | \ - ((x)<< 8 & 0x00FF0000UL) | \ - ((x)>> 8 & 0x0000FF00UL) | \ - ((x)>>24 & 0x000000FFUL) ) -#define ntohl(x) htonl(x) - -#endif