diff --git a/libraries/RF24/.gitignore b/libraries/RF24/.gitignore new file mode 100644 index 0000000..ac32040 --- /dev/null +++ b/libraries/RF24/.gitignore @@ -0,0 +1,14 @@ +*.bak +*.o +.*.swp +*.orig +.swp +docs/ +output/ +ojam/ +out/ +16000000/ +8000000/ +out_native/ +version.h +Session.vim diff --git a/libraries/RF24/Doxyfile b/libraries/RF24/Doxyfile new file mode 100644 index 0000000..4604afc --- /dev/null +++ b/libraries/RF24/Doxyfile @@ -0,0 +1,1551 @@ +# 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/libraries/RF24/FAQ b/libraries/RF24/FAQ new file mode 100644 index 0000000..eccd03a --- /dev/null +++ b/libraries/RF24/FAQ @@ -0,0 +1,53 @@ +/** + * @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/libraries/RF24/README.md b/libraries/RF24/README.md new file mode 100644 index 0000000..d0f2c0e --- /dev/null +++ b/libraries/RF24/README.md @@ -0,0 +1,41 @@ +# Optimized High Speed Arduino driver for nRF24L01 2.4GHz Wireless Transceiver + +Design Goals: This library is designed to be... + +* More compliant with the manufacturer specified operation of the chip, while allowing advanced users +* to work outside the reccommended operation. +* Utilize the capabilities of the radio to their full potential via Arduino +* More reliable and feature rich +* Easy for beginners to use, with well documented examples and features +* Consumed with a public interface that's similiar to other Arduino standard libraries +* Built against the standard SPI library. + +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. + +Please refer to: + +* [Documentation Main Page](http://tmrh20.github.io/) +* [Class Reference]( http://tmrh20.github.io/RF24/classRF24.html) +* [Source Code](https://github.com/tmrh20/RF24) +* [Downloads](https://github.com/TMRh20/RF24/archive/master.zip) +* [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. + +Supported Boards: + +* Uno, Nano, etc (328 based boards) +* Mega Types (2560, 1280, etc) +* ARM (Arduino Due) via extended SPI methods +* ATTiny 24/44/84 25/45/85 +* Raspberry Pi +* See the [documentation](http://tmrh20.github.io/) for more info \ No newline at end of file diff --git a/libraries/RF24/RF24.cpp b/libraries/RF24/RF24.cpp new file mode 100644 index 0000000..ebfbf81 --- /dev/null +++ b/libraries/RF24/RF24.cpp @@ -0,0 +1,1220 @@ +/* + 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. + */ + +#include "nRF24L01.h" +#include "RF24_config.h" +#include "RF24.h" + +/****************************************************************************/ + +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 + #if !defined( __AVR_ATtiny85__ ) && !defined( __AVR_ATtiny84__) && !defined (__arm__) + SPI.setBitOrder(MSBFIRST); + SPI.setDataMode(SPI_MODE0); + SPI.setClockDivider(SPI_CLOCK_DIV2); + #endif +#endif + +#ifndef __arm__ + digitalWrite(csn_pin,mode); +#endif + +} + +/****************************************************************************/ + +void RF24::ce(bool level) +{ + digitalWrite(ce_pin,level); +} + +/****************************************************************************/ + +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-- ){ + *buf++ = SPI.transfer(0xff); + } + csn(HIGH); + +#endif + + return status; +} + +/****************************************************************************/ + +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; +} + +/****************************************************************************/ + +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-- ) + SPI.transfer(*buf++); + + csn(HIGH); + + #endif + + return status; +} + +/****************************************************************************/ + +uint8_t RF24::write_register(uint8_t reg, uint8_t value) +{ + uint8_t status; + + 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 data_len, const uint8_t writeType) +{ + uint8_t status; + const uint8_t* current = reinterpret_cast(buf); + + 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-- ) { + SPI.transfer(*current++); + } + while ( blank_len-- ) { + SPI.transfer(0); + } + csn(HIGH); + + #endif + + return status; +} + +/****************************************************************************/ + +uint8_t RF24::read_payload(void* buf, uint8_t data_len) +{ + uint8_t status; + uint8_t* current = reinterpret_cast(buf); + + 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); + + + #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-- ) { + SPI.transfer(0xff); + } + csn(HIGH); + + #endif + + return status; +} + +/****************************************************************************/ + +uint8_t RF24::flush_rx(void) +{ + 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( cmd ); + csn(HIGH); + #endif + return status; + +} + +/****************************************************************************/ + +uint8_t RF24::get_status(void) +{ + return spiTrans(NOP); +} + +/****************************************************************************/ + +void RF24::print_status(uint8_t status) +{ + printf_P(PSTR("STATUS\t\t = 0x%02x RX_DR=%x TX_DS=%x MAX_RT=%x RX_P_NO=%x TX_FULL=%x\r\n"), + status, + (status & _BV(RX_DR))?1:0, + (status & _BV(TX_DS))?1:0, + (status & _BV(MAX_RT))?1:0, + ((status >> RX_P_NO) & B111), + (status & _BV(TX_FULL))?1:0 + ); +} + +/****************************************************************************/ + +void RF24::print_observe_tx(uint8_t value) +{ + printf_P(PSTR("OBSERVE_TX=%02x: POLS_CNT=%x ARC_CNT=%x\r\n"), + value, + (value >> PLOS_CNT) & B1111, + (value >> ARC_CNT) & B1111 + ); +} + +/****************************************************************************/ + +void RF24::print_byte_register(const char* name, uint8_t reg, uint8_t qty) +{ + char extra_tab = strlen_P(name) < 8 ? '\t' : 0; + printf_P(PSTR(PRIPSTR"\t%c ="),name,extra_tab); + while (qty--) + printf_P(PSTR(" 0x%02x"),read_register(reg++)); + printf_P(PSTR("\r\n")); +} + +/****************************************************************************/ + +void RF24::print_address_register(const char* name, uint8_t reg, uint8_t qty) +{ + char extra_tab = strlen_P(name) < 8 ? '\t' : 0; + printf_P(PSTR(PRIPSTR"\t%c ="),name,extra_tab); + + while (qty--) + { + uint8_t buffer[5]; + read_register(reg++,buffer,sizeof buffer); + + printf_P(PSTR(" 0x")); + uint8_t* bufptr = buffer + sizeof buffer; + while( --bufptr >= buffer ) + printf_P(PSTR("%02x"),*bufptr); + } + + printf_P(PSTR("\r\n")); +} + +/****************************************************************************/ + +RF24::RF24(uint8_t _cepin, uint8_t _cspin): + ce_pin(_cepin), csn_pin(_cspin), wide_band(false), p_variant(false), + payload_size(32), dynamic_payloads_enabled(false), + pipe0_reading_address(0) +{ +} + +/****************************************************************************/ + +void RF24::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 RF24::setPayloadSize(uint8_t size) +{ + payload_size = min(size,32); +} + +/****************************************************************************/ + +uint8_t RF24::getPayloadSize(void) +{ + return payload_size; +} + +/****************************************************************************/ + +#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"; +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 = "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 = { + 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 RF24::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); + +#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); + + #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 + // 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. + setRetries(5,15); + + // 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 + // 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 - Reset value is 0 + //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(); + + 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) +{ + 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){ + write_register(RX_ADDR_P0, reinterpret_cast(&pipe0_reading_address), 5); + } + + // Flush buffers + flush_rx(); + flush_tx(); + + // Go! + ce(HIGH); + +} + +/****************************************************************************/ + +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))){ + 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 ) +{ + //Start Writing + 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) ))) { } + + uint8_t status = write_register(STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); + + //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; + } + //TX OK 1 or 0 + return 1; +} + +bool RF24::write( const void* buf, uint8_t len ){ + return write(buf,len,0); +} +/****************************************************************************/ + +//For general use, the interrupt flags are not important to clear +bool RF24::writeBlocking( const void* buf, uint8_t len, uint32_t timeout ) +{ + //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 + + uint32_t timer = millis(); //Get the time that the payload transmission started + + 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? W_TX_PAYLOAD_NO_ACK : W_TX_PAYLOAD ) ; + + ce(HIGH); + 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 ); +} + +/****************************************************************************/ + +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; +} + +/****************************************************************************/ + +bool RF24::available(void) +{ + return available(NULL); +} + +/****************************************************************************/ + +bool RF24::available(uint8_t* pipe_num) +{ + + //Check the FIFO buffer to see if data is waitng to be read + + if (!( read_register(FIFO_STATUS) & _BV(RX_EMPTY) )){ + + // If the caller wants the pipe number, include that + if ( pipe_num ){ + uint8_t status = get_status(); + *pipe_num = ( status >> RX_P_NO ) & B111; + } + return 1; + } + + return 0; + + + +} + +/****************************************************************************/ + +void RF24::read( void* buf, uint8_t len ){ + + // Fetch the payload + read_payload( buf, len ); + + //Clear the two possible interrupt flags with one command + write_register(STATUS,_BV(RX_DR) | _BV(MAX_RT) | _BV(TX_DS) ); + +} + +/****************************************************************************/ + +void RF24::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 RF24::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, 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)); + write_register(RX_PW_P0,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 RF24::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]), reinterpret_cast(&address), 5); + else + write_register(pgm_read_byte(&child_pipe[child]), reinterpret_cast(&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 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 +} + +/****************************************************************************/ + +void RF24::enableDynamicPayloads(void) +{ + // Enable dynamic payload throughout the system + + toggle_features(); + write_register(FEATURE,read_register(FEATURE) | _BV(EN_DPL) ); + + + IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n",read_register(FEATURE))); + + // 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 RF24::enableAckPayload(void) +{ + // + // enable ack payload and dynamic payload features + // + + toggle_features(); + write_register(FEATURE,read_register(FEATURE) | _BV(EN_ACK_PAY) | _BV(EN_DPL) ); + + IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n",read_register(FEATURE))); + + // + // Enable dynamic payload on pipes 0 & 1 + // + + write_register(DYNPD,read_register(DYNPD) | _BV(DPL_P1) | _BV(DPL_P0)); +} + +/****************************************************************************/ + +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 ) ); + + while ( data_len-- ) + SPI.transfer(*current++); + + csn(HIGH); + + #endif +} + +/****************************************************************************/ + +bool RF24::isAckPayloadAvailable(void) +{ + return ! read_register(FIFO_STATUS) & _BV(RX_EMPTY); +} + +/****************************************************************************/ + +bool RF24::isPVariant(void) +{ + return p_variant ; +} + +/****************************************************************************/ + +void RF24::setAutoAck(bool enable) +{ + if ( enable ) + write_register(EN_AA, B111111); + else + write_register(EN_AA, 0); +} + +/****************************************************************************/ + +void RF24::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 RF24::testCarrier(void) +{ + return ( read_register(CD) & 1 ); +} + +/****************************************************************************/ + +bool RF24::testRPD(void) +{ + return ( read_register(RPD) & 1 ) ; +} + +/****************************************************************************/ + +void RF24::setPALevel(uint8_t level) +{ + + 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 |= level ) ; // Write it to the chip +} + +/****************************************************************************/ + +uint8_t RF24::getPALevel(void) +{ + + return (read_register(RF_SETUP) & (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH))) >> 1 ; +} + +/****************************************************************************/ + +bool RF24::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 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) ) + { + // '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 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. + } + 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 RF24::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 RF24::disableCRC( void ) +{ + uint8_t disable = read_register(CONFIG) & ~_BV(EN_CRC) ; + write_register( CONFIG, disable ) ; +} + +/****************************************************************************/ +void RF24::setRetries(uint8_t delay, uint8_t count) +{ + 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. + */ + +/** + * @file RF24.h + * + * Class declaration for RF24 and helper enums + */ + +#ifndef __RF24_H__ +#define __RF24_H__ + +#include + +/** + * 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 + */ + +class RF24 +{ +private: + uint8_t ce_pin; /**< "Chip Enable" pin, activates the RX or TX role */ + uint8_t csn_pin; /**< SPI Chip select */ + 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 dynamic_payloads_enabled; /**< Whether dynamic payloads are enabled. */ + uint64_t pipe0_reading_address; /**< Last address set on pipe 0 for reading. */ + +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); + + /**@}*/ + /** + * @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. + * + * 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 csn(bool 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 ce(bool 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 read_register(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 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 write_register(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 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 write_payload(const void* buf, uint8_t len, const uint8_t writeType); + + /** + * 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 read_payload(void* buf, uint8_t len); + + /** + * Empty the receive buffer + * + * @return Current value of status register + */ + uint8_t flush_rx(void); + + /** + * Retrieve the current status of the chip + * + * @return Current value of status register + */ + uint8_t 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 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 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 print_byte_register(const char* name, uint8_t reg, uint8_t qty = 1); + + /** + * 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 print_address_register(const char* name, uint8_t reg, uint8_t qty = 1); + + /** + * 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 toggle_features(void); + + /** + * Built in spi transfer function to simplify repeating code repeating code + */ + + uint8_t spiTrans(uint8_t cmd); + /**@}*/ + +}; + +/** + * @example GettingStarted.ino + * Updated: TMRh20 2014
+ * + * 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
+ * + * 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. + */ + +/** + * @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 scanner.ino + * + * 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 Optimized High Speed Driver for nRF24L01(+) 2.4GHz Wireless Transceiver + * + * @section Goals Design Goals + * + * 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 + * + * 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 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 + * + * @section Info and Projects + * + * @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__ + + diff --git a/libraries/RF24/RF24_config.h b/libraries/RF24/RF24_config.h new file mode 100644 index 0000000..b7154a5 --- /dev/null +++ b/libraries/RF24/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/libraries/RF24/RPi/RF24/Makefile b/libraries/RF24/RPi/RF24/Makefile new file mode 100644 index 0000000..c2ae37d --- /dev/null +++ b/libraries/RF24/RPi/RF24/Makefile @@ -0,0 +1,55 @@ +############################################################################# +# +# Makefile for librf24-bcm on Raspberry Pi +# +# License: GPL (General Public License) +# Author: Charles-Henri Hallard +# Date: 2013/03/13 +# +# Description: +# ------------ +# use make all and mak install to install the library +# You can change the install directory by editing the LIBDIR line +# +PREFIX=/usr/local + +# Library parameters +# where to put the lib +LIBDIR=$(PREFIX)/lib +# lib name +LIB=librf24-bcm +# shared library name +LIBNAME=$(LIB).so.1.0 + + +# The recommended compiler flags for the Raspberry Pi +CCFLAGS=-Ofast -mfpu=vfp -mfloat-abi=hard -march=armv6zk -mtune=arm1176jzf-s + +# make all +# reinstall the library after each recompilation +all: librf24-bcm install + +# Make the library +librf24-bcm: RF24.o bcm2835.o + g++ -shared -Wl,-soname,$@.so.1 ${CCFLAGS} -o ${LIBNAME} $^ + +# Library parts +RF24.o: RF24.cpp + g++ -Wall -fPIC ${CCFLAGS} -c $^ + +bcm2835.o: bcm2835.c + gcc -Wall -fPIC ${CCFLAGS} -c $^ + +# clear build files +clean: + rm -rf *.o ${LIB}.* + +# Install the library to LIBPATH +install: + @echo "[Install]" + @if ( test ! -d $(PREFIX)/lib ) ; then mkdir -p $(PREFIX)/lib ; fi + #@install -m 0755 ${LIB}.a ${LIBDIR} + @install -m 0755 ${LIBNAME} ${LIBDIR} + @ln -sf ${LIBDIR}/${LIBNAME} ${LIBDIR}/${LIB}.so.1 + @ln -sf ${LIBDIR}/${LIBNAME} ${LIBDIR}/${LIB}.so + @ldconfig diff --git a/libraries/RF24/RPi/RF24/RF24.cpp b/libraries/RF24/RPi/RF24/RF24.cpp new file mode 100644 index 0000000..c45afaf --- /dev/null +++ b/libraries/RF24/RPi/RF24/RF24.cpp @@ -0,0 +1,1145 @@ +/* + 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. + + + +03/17/2013 : Charles-Henri Hallard (http://hallard.me) + Modified to use with Arduipi board http://hallard.me/arduipi + Changed to use modified bcm2835 library + +TMRh20 2014: Updated to work with optimized RF24 and RF24 Network Arduino libs. +*/ + +#include "./RF24_config.h" +#include "./RF24.h" +#include "./nRF24L01.h" + + +/****************************************************************************/ +uint8_t RF24::read_register(uint8_t reg, uint8_t* buf, uint8_t len) +{ + uint8_t status; + uint8_t * prx = spi_rxbuff; + uint8_t * ptx = spi_txbuff; + uint8_t size = len + 1; // Add register value to transmit buffer + + *ptx++ = ( R_REGISTER | ( REGISTER_MASK & reg ) ); + while (len--){ + *ptx++ = NOP ; // Dummy operation, just for reading + } + bcm2835_spi_transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, size); + //bcm2835_spi_transfernb( (char *) spi_txbuff, (char *) buf, size); + + status = *prx++; // status is 1st byte of receive buffer + + // decrement before to skip status byte + while ( --size ){ + *buf++ = *prx++; + } + + return status; +} + +/****************************************************************************/ +uint8_t RF24::read_register(uint8_t reg) +{ + uint8_t result; + uint8_t * prx = spi_rxbuff; + uint8_t * ptx = spi_txbuff; + + *ptx++ = ( R_REGISTER | ( REGISTER_MASK & reg ) ); + *ptx++ = NOP ; // Dummy operation, just for reading + + bcm2835_spi_transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, 2); + + result = *++prx; // result is 2nd byte of receive buffer + + return result; +} + +/****************************************************************************/ + +uint8_t RF24::write_register(uint8_t reg, uint8_t value) +{ + uint8_t status; + uint8_t * prx = spi_rxbuff; + uint8_t * ptx = spi_txbuff; + + *ptx++ = ( W_REGISTER | ( REGISTER_MASK & reg ) ); + *ptx = value ; + + bcm2835_spi_transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, 2); + + status = *prx++; // status is 1st byte of receive buffer + + if (debug) + printf("write_register(%02x,%02x)\r\n",reg,value); + + return status; +} + +/****************************************************************************/ + +uint8_t RF24::write_register(uint8_t reg, const uint8_t* buf, uint8_t len) +{ + uint8_t status; + uint8_t * prx = spi_rxbuff; + uint8_t * ptx = spi_txbuff; + uint8_t size = len + 1; // Add register value to transmit buffer + + *ptx++ = ( W_REGISTER | ( REGISTER_MASK & reg ) ); + while ( len-- ) + *ptx++ = *buf++; + + bcm2835_spi_transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, size); + + status = *prx; // status is 1st byte of receive buffer + + return status; +} + + +/****************************************************************************/ + +uint8_t RF24::write_payload(const void* buf, uint8_t len, const uint8_t writeType) +{ + uint8_t status; + uint8_t * prx = spi_rxbuff; + uint8_t * ptx = spi_txbuff; + uint8_t size ; + + const uint8_t* current = reinterpret_cast(buf); + + uint8_t data_len = min(len,payload_size); + uint8_t blank_len = dynamic_payloads_enabled ? 0 : payload_size - data_len; + + size = data_len + blank_len + 1 ; // Add register value to transmit buffer + + if (debug) + printf("[Writing %u bytes %u blanks]",data_len,blank_len); + + *ptx++ = W_TX_PAYLOAD; + while ( data_len-- ) + *ptx++ = *current++; + while ( blank_len-- ) + *ptx++ = 0; + + bcm2835_spi_transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, size); + + status = *prx; // status is 1st byte of receive buffer + + + return status; +} + +/****************************************************************************/ + +uint8_t RF24::read_payload(void* buf, uint8_t len) +{ + uint8_t status; + uint8_t * prx = spi_rxbuff; + uint8_t * ptx = spi_txbuff; + uint8_t size ; + + uint8_t* current = reinterpret_cast(buf); + + uint8_t data_len = min(len,payload_size); + uint8_t blank_len = dynamic_payloads_enabled ? 0 : payload_size - data_len; + + size = data_len + blank_len + 1; // Add register value to transmit buffer + + if (debug) + printf("[Reading %u bytes %u blanks]",data_len,blank_len); + + *ptx++ = R_RX_PAYLOAD; + while(size--) + *ptx++ = NOP; + + // Size has been lost during while, re affect + size = data_len + blank_len + 1; // Add register value to transmit buffer + + bcm2835_spi_transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, size); + + // 1st byte is status + status = *prx++; + + // Decrement before to skip 1st status byte + while ( --size ) + *current++ = *prx++; + + return status; +} + +/****************************************************************************/ + +uint8_t RF24::flush_rx(void) +{ + uint8_t status; + + status = bcm2835_spi_transfer( FLUSH_RX ); + + return status; +} + +/****************************************************************************/ + +uint8_t RF24::flush_tx(void) +{ + uint8_t status; + + status = bcm2835_spi_transfer( FLUSH_TX ); + + return status; +} + +/****************************************************************************/ + +uint8_t RF24::get_status(void) +{ + return bcm2835_spi_transfer( NOP ); +} + +/****************************************************************************/ + +void RF24::print_status(uint8_t status) +{ + printf("STATUS\t\t = 0x%02x RX_DR=%x TX_DS=%x MAX_RT=%x RX_P_NO=%x TX_FULL=%x\r\n", + status, + (status & _BV(RX_DR))?1:0, + (status & _BV(TX_DS))?1:0, + (status & _BV(MAX_RT))?1:0, + ((status >> RX_P_NO) & 0b111), + (status & _BV(TX_FULL))?1:0 + ); +} + +/****************************************************************************/ + +void RF24::print_observe_tx(uint8_t value) +{ + printf("OBSERVE_TX=%02x: POLS_CNT=%x ARC_CNT=%x\r\n", + value, + (value >> PLOS_CNT) & 0b1111, + (value >> ARC_CNT) & 0b1111 + ); +} + +/****************************************************************************/ + +void RF24::print_byte_register(const char* name, uint8_t reg, uint8_t qty) +{ + char extra_tab = strlen(name) < 8 ? '\t' : 0; + printf("%s\t%c =", name, extra_tab); + while (qty--) + printf(" 0x%02x",read_register(reg++)); + printf("\n"); +} + +/****************************************************************************/ + +void RF24::print_address_register(const char* name, uint8_t reg, uint8_t qty) +{ + char extra_tab = strlen(name) < 8 ? '\t' : 0; + printf("%s\t%c =",name,extra_tab); + + while (qty--) + { + uint8_t buffer[5]; + read_register(reg++,buffer,sizeof buffer); + + printf(" 0x"); + uint8_t* bufptr = buffer + sizeof buffer; + while( --bufptr >= buffer ) + printf("%02x",*bufptr); + } + + printf("\r\n"); +} + + +/****************************************************************************/ + +RF24::RF24(uint8_t _cepin, uint8_t _cspin, uint32_t _spi_speed): + ce_pin(_cepin), csn_pin(_cspin), spi_speed(_spi_speed), wide_band(true), p_variant(false), + payload_size(32), dynamic_payloads_enabled(false), + pipe0_reading_address(0) +{ +} + +/****************************************************************************/ + +void RF24::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 RF24::setPayloadSize(uint8_t size) +{ + const uint8_t max_payload_size = 32; + payload_size = min(size,max_payload_size); +} + +/****************************************************************************/ + +uint8_t RF24::getPayloadSize(void) +{ + return payload_size; +} + +/****************************************************************************/ + +static const char rf24_datarate_e_str_0[] = "1MBPS"; +static const char rf24_datarate_e_str_1[] = "2MBPS"; +static const char rf24_datarate_e_str_2[] = "250KBPS"; +static const char * const rf24_datarate_e_str_P[] = { + rf24_datarate_e_str_0, + rf24_datarate_e_str_1, + rf24_datarate_e_str_2, +}; +static const char rf24_model_e_str_0[] = "nRF24L01"; +static const char rf24_model_e_str_1[] = "nRF24L01+"; +static const char * const rf24_model_e_str_P[] = { + rf24_model_e_str_0, + rf24_model_e_str_1, +}; +static const char rf24_crclength_e_str_0[] = "Disabled"; +static const char rf24_crclength_e_str_1[] = "8 bits"; +static const char rf24_crclength_e_str_2[] = "16 bits" ; +static const char * const rf24_crclength_e_str_P[] = { + rf24_crclength_e_str_0, + rf24_crclength_e_str_1, + rf24_crclength_e_str_2, +}; +static const char rf24_pa_dbm_e_str_0[] = "PA_MIN"; +static const char rf24_pa_dbm_e_str_1[] = "PA_LOW"; +static const char rf24_pa_dbm_e_str_2[] = "PA_HIGH"; +static const char rf24_pa_dbm_e_str_3[] = "PA_MAX"; +static const char * const rf24_pa_dbm_e_str_P[] = { + rf24_pa_dbm_e_str_0, + rf24_pa_dbm_e_str_1, + rf24_pa_dbm_e_str_2, + rf24_pa_dbm_e_str_3, +}; + +static const char rf24_csn_e_str_0[] = "CE0 (PI Hardware Driven)"; +static const char rf24_csn_e_str_1[] = "CE1 (PI Hardware Driven)"; +static const char rf24_csn_e_str_2[] = "CE2 (PI Hardware Driven)"; +static const char rf24_csn_e_str_3[] = "Custom GPIO Software Driven"; +static const char * const rf24_csn_e_str_P[] = { + rf24_csn_e_str_0, + rf24_csn_e_str_1, + rf24_csn_e_str_2, + rf24_csn_e_str_3, +}; + +// Display NRF24L01 details +void RF24::printDetails(void) +{ + printf("================ SPI Configuration ================\n" ); + + if (csn_pin < BCM2835_SPI_CS_NONE ) + { + printf("CSN Pin \t = %s\n",rf24_csn_e_str_P[csn_pin]); + } + else + { + printf("CSN Pin \t = Custom GPIO%d%s\n", csn_pin, + csn_pin==RPI_V2_GPIO_P1_26 ? " (CE1) Software Driven" : "" ); + } + + printf("CE Pin \t = Custom GPIO%d\n", ce_pin ); + + // SPI Bus Speed + printf("Clock Speed\t = " ); + switch (spi_speed) + { + case BCM2835_SPI_SPEED_64MHZ : printf("64 Mhz"); break ; + case BCM2835_SPI_SPEED_32MHZ : printf("32 Mhz"); break ; + case BCM2835_SPI_SPEED_16MHZ : printf("16 Mhz"); break ; + case BCM2835_SPI_SPEED_8MHZ : printf("8 Mhz"); break ; + case BCM2835_SPI_SPEED_4MHZ : printf("4 Mhz"); break ; + case BCM2835_SPI_SPEED_2MHZ : printf("2 Mhz"); break ; + case BCM2835_SPI_SPEED_1MHZ : printf("1 Mhz"); break ; + case BCM2835_SPI_SPEED_512KHZ: printf("512 KHz"); break ; + case BCM2835_SPI_SPEED_256KHZ: printf("256 KHz"); break ; + case BCM2835_SPI_SPEED_128KHZ: printf("128 KHz"); break ; + case BCM2835_SPI_SPEED_64KHZ : printf("64 KHz"); break ; + case BCM2835_SPI_SPEED_32KHZ : printf("32 KHz"); break ; + case BCM2835_SPI_SPEED_16KHZ : printf("16 KHz"); break ; + case BCM2835_SPI_SPEED_8KHZ : printf("8 KHz"); break ; + default : printf("Probably Bad !!!"); break ; + } + printf("\n"); + + printf("================ NRF Configuration ================\n" ); + + print_status(get_status()); + + print_address_register("RX_ADDR_P0-1",RX_ADDR_P0,2); + print_byte_register("RX_ADDR_P2-5",RX_ADDR_P2,4); + print_address_register("TX_ADDR",TX_ADDR); + + print_byte_register("RX_PW_P0-6",RX_PW_P0,6); + print_byte_register("EN_AA",EN_AA); + print_byte_register("EN_RXADDR",EN_RXADDR); + print_byte_register("RF_CH",RF_CH); + print_byte_register("RF_SETUP",RF_SETUP); + print_byte_register("CONFIG",CONFIG); + print_byte_register("DYNPD/FEATURE",DYNPD,2); + + printf("Data Rate\t = %s\r\n",rf24_datarate_e_str_P[getDataRate()]); + printf("Model\t\t = %s\r\n",rf24_model_e_str_P[isPVariant()]); + printf("CRC Length\t = %s\r\n",rf24_crclength_e_str_P[getCRCLength()]); + printf("PA Power\t = %s\r\n",rf24_pa_dbm_e_str_P[getPALevel()]); +} + +/****************************************************************************/ + +bool RF24::begin(void) +{ + debug = false; + //debug = true; + // This initialize the SPI bus with + // csn pin as chip select (custom or not) + + + // Init BCM2835 chipset for talking with us + if (!bcm2835_init()){ + return false; + } + + switch(csn_pin){ //Ensure valid hardware CS pin + case 0: break; + case 1: break; + case 8: csn_pin = 0; break; + case 7: csn_pin = 1; break; + default: csn_pin = 0; break; + } + + + bcm2835_spi_begin(); + + // used to drive custom I/O to trigger my logic analyser + // bcm2835_gpio_fsel(GPIO_CTRL_PIN , BCM2835_GPIO_FSEL_OUTP); + + // start the SPI library: + // Note the NRF24 wants mode 0, MSB first and default to 1 Mbps + bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST); + bcm2835_spi_setDataMode(BCM2835_SPI_MODE0); + + // Set SPI bus Speed + bcm2835_spi_setClockDivider(spi_speed); + + // Choose hardware CSN pin + bcm2835_spi_chipSelect(csn_pin); + + + // Initialise the CE pin of NRF24 (chip enable) after the CSN pin, so that + // The input mode is not changed if using one of the hardware CE pins + bcm2835_gpio_fsel(ce_pin, BCM2835_GPIO_FSEL_OUTP); + bcm2835_gpio_write(ce_pin, LOW); + + // wait 100ms + delay(100); + + // 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. + //printf("write_register(%02X, %02X)\n", SETUP_RETR, (0b0100 << ARD) | (0b1111 << ARC)); + setRetries(5,15); + + // 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 ) ; + + // 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(); + + powerUp(); + + // 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) ); + + return true; +} + +/****************************************************************************/ + +void RF24::startListening(void) +{ + 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) + write_register(RX_ADDR_P0, reinterpret_cast(&pipe0_reading_address), 5); + + // Flush buffers + flush_rx(); + flush_tx(); + + // Go! + bcm2835_gpio_write(ce_pin, HIGH); + + // wait for the radio to come up (130us actually only needed) + //delayMicroseconds(130); +} + +/****************************************************************************/ + +void RF24::stopListening(void) +{ + bcm2835_gpio_write(ce_pin, LOW); + flush_tx(); + flush_rx(); + write_register(CONFIG, ( read_register(CONFIG) ) & ~_BV(PRIM_RX) ); + +} + +/****************************************************************************/ + +void RF24::powerDown(void) +{ + bcm2835_gpio_write(ce_pin, LOW); + write_register(CONFIG,read_register(CONFIG) & ~_BV(PWR_UP)); +} + +/****************************************************************************/ + +void RF24::powerUp(void) +{ + bool up = read_register(CONFIG) & _BV(PWR_UP); + + if(! up ){ + write_register(CONFIG, ( read_register(CONFIG) | _BV(PWR_UP) )); + delay(5); + } + + +} + +/******************************************************************/ + +bool RF24::write( const void* buf, uint8_t len, const bool multicast ){ + + // Begin the write + startFastWrite(buf,len, multicast); + + + //Wait until complete or failed + // If this hangs, it ain't coming back, no sense in timing out + while( ! ( get_status() & ( _BV(TX_DS) | _BV(MAX_RT) ))) { } + + + uint8_t status = write_register(STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); + bcm2835_gpio_write(ce_pin, LOW); + + //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; + } + //TX OK 1 or 0 + return 1; +} + +bool RF24::write( const void* buf, uint8_t len ){ + return write(buf,len,0); +} + +/****************************************************************************/ + +//For general use, the interrupt flags are not important to clear +bool RF24::writeBlocking( const void* buf, uint8_t len, uint32_t timeout ) +{ + //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 + + uint32_t timer = millis(); //Get the time that the payload transmission started + + 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 ); + bcm2835_spi_transfer( REUSE_TX_PL); + bcm2835_gpio_write(ce_pin, LOW); //Re-Transfer packet + bcm2835_gpio_write(ce_pin, 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 ) ; + bcm2835_gpio_write(ce_pin, HIGH); + +} + +/****************************************************************************/ + +void RF24::startWrite( const void* buf, uint8_t len, const bool multicast ) +{ + + // Send the payload + + write_payload( buf, len,multicast ? W_TX_PAYLOAD_NO_ACK : W_TX_PAYLOAD ) ; + bcm2835_gpio_write(ce_pin, HIGH); + delayMicroseconds(10); + bcm2835_gpio_write(ce_pin, LOW); +} + +/****************************************************************************/ + +bool RF24::txStandBy(){ + + while( ! (read_register(FIFO_STATUS) & _BV(TX_EMPTY)) ){ + if( get_status() & _BV(MAX_RT)){ + write_register(STATUS,_BV(MAX_RT) ); + bcm2835_gpio_write(ce_pin, LOW); + flush_tx(); //Non blocking, flush the data + return 0; + } + } + + bcm2835_gpio_write(ce_pin, 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) ); + bcm2835_gpio_write(ce_pin, LOW); //Set re-transmit + bcm2835_gpio_write(ce_pin, HIGH); + if(millis() - start >= timeout){ + bcm2835_gpio_write(ce_pin, LOW); + flush_tx(); + return 0; + } + } + } + bcm2835_gpio_write(ce_pin, 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 ); +} + +/****************************************************************************/ + +uint8_t RF24::getDynamicPayloadSize(void) +{ + spi_txbuff[0] = R_RX_PL_WID; + spi_rxbuff[1] = 0xff; + + bcm2835_spi_transfernb( (char *) spi_txbuff, (char *) spi_rxbuff, 2); + + if(spi_rxbuff[1] > 32) { flush_rx(); return 0; } + + return spi_rxbuff[1]; +} + +/****************************************************************************/ + +bool RF24::available(void) +{ + return available(NULL); +} + +/****************************************************************************/ + +bool RF24::available(uint8_t* pipe_num) +{ + //Check the FIFO buffer to see if data is waitng to be read + + if (!( read_register(FIFO_STATUS) & _BV(RX_EMPTY) )){ + + + // If the caller wants the pipe number, include that + if ( pipe_num ){ + uint8_t status = get_status(); + *pipe_num = ( status >> RX_P_NO ) & 0b111; + } + return 1; + } + + return 0; +} + +/****************************************************************************/ + +void RF24::read( void* buf, uint8_t len ) +{ + // Fetch the payload + read_payload( buf, len ); + + //Clear the two possible interrupt flags with one command + write_register(STATUS,_BV(RX_DR) | _BV(MAX_RT) | _BV(TX_DS) ); +} + +/****************************************************************************/ + +void RF24::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 RF24::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, reinterpret_cast(&value), 5); + write_register(TX_ADDR, reinterpret_cast(&value), 5); + + + write_register(RX_PW_P0,payload_size); +} + +/****************************************************************************/ + +static const uint8_t child_pipe[] = +{ + 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[] = +{ + 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[] = +{ + ERX_P0, ERX_P1, ERX_P2, ERX_P3, ERX_P4, ERX_P5 +}; + +void RF24::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]), reinterpret_cast(&address), 5); + else + write_register(pgm_read_byte(&child_pipe[child]), reinterpret_cast(&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 RF24::toggle_features(void) +{ + bcm2835_spi_transfer( ACTIVATE ); + bcm2835_spi_transfer( 0x73 ); +} + +/****************************************************************************/ + +void RF24::enableDynamicPayloads(void) +{ + + // So enable them and try again + toggle_features(); + write_register(FEATURE,read_register(FEATURE) | _BV(EN_DPL) ); + + if (debug) + printf("FEATURE=%i\r\n",read_register(FEATURE)); + + // 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 RF24::enableAckPayload(void) +{ + // + // enable ack payload and dynamic payload features + // + + + // So enable them and try again + toggle_features(); + write_register(FEATURE,read_register(FEATURE) | _BV(EN_ACK_PAY) | _BV(EN_DPL) ); + + if (debug) + printf("FEATURE=%i\r\n",read_register(FEATURE)); + + // + // Enable dynamic payload on pipes 0 & 1 + // + + write_register(DYNPD,read_register(DYNPD) | _BV(DPL_P1) | _BV(DPL_P0)); +} + +/****************************************************************************/ + +void RF24::enableDynamicAck(void){ + // + // enable dynamic ack features + // + toggle_features(); + write_register(FEATURE,read_register(FEATURE) | _BV(EN_DYN_ACK) ); + + if(debug){printf("FEATURE=%i\r\n",read_register(FEATURE));} + + +} + +/****************************************************************************/ + +void RF24::writeAckPayload(uint8_t pipe, const void* buf, uint8_t len) +{ + + uint8_t * ptx = spi_txbuff; + uint8_t size ; + + const uint8_t* current = reinterpret_cast(buf); + + uint8_t data_len = min(len,payload_size); + + size = data_len + 1 ; // Add register value to transmit buffer + + if (debug){ + printf("[Writing %u bytes]",data_len); + } + *ptx++ = W_ACK_PAYLOAD | ( pipe & 0b111 ); + while ( data_len-- ){ + *ptx++ = *current++; + } + bcm2835_spi_transfern( (char *) spi_txbuff, size); + +} + + +/****************************************************************************/ + +bool RF24::isAckPayloadAvailable(void) +{ + return ! read_register(FIFO_STATUS) & _BV(RX_EMPTY); +} + +/****************************************************************************/ + +bool RF24::isPVariant(void) +{ + return p_variant ; +} + +/****************************************************************************/ + +void RF24::setAutoAck(bool enable) +{ + if ( enable ) + write_register(EN_AA, 0b111111); + else + write_register(EN_AA, 0); +} + +/****************************************************************************/ + +void RF24::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 RF24::testCarrier(void) +{ + return ( read_register(CD) & 1 ); +} + +/****************************************************************************/ + +bool RF24::testRPD(void) +{ + return ( read_register(RPD) & 1 ) ; +} + +/****************************************************************************/ + +void RF24::setPALevel(uint8_t level) +{ + 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 |= level ) ; // Write it to the chip +} + +/****************************************************************************/ + +uint8_t RF24::getPALevel(void) +{ + return (read_register(RF_SETUP) & (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH))) >> 1 ; +} + +/****************************************************************************/ + +bool RF24::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 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) ) + { + // '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 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. + } + 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 RF24::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 RF24::disableCRC( void ) +{ + uint8_t disable = read_register(CONFIG) & ~_BV(EN_CRC) ; + write_register( CONFIG, disable ) ; +} + +/****************************************************************************/ +void RF24::setRetries(uint8_t delay, uint8_t count) +{ + 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. + + 03/17/2013 : Charles-Henri Hallard (http://hallard.me) + Modified to use with Arduipi board http://hallard.me/arduipi + Modified to use the great bcm2835 library for I/O and SPI + + */ + +/** + * @file RF24.h + * + * Class declaration for RF24 and helper enums + */ + +#ifndef __RF24_H__ +#define __RF24_H__ + +#include "RF24_config.h" +#include "./bcm2835.h" + + +/** + * 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 + */ + +class RF24 +{ +private: + uint8_t ce_pin; /**< "Chip Enable" pin, activates the RX or TX role */ + uint8_t csn_pin; /**< SPI Chip select */ + uint16_t spi_speed; /**< SPI Bus Speed */ + 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. */ + uint64_t pipe0_reading_address; /**< Last address set on pipe 0 for reading. */ + //uint32_t spispeed; + uint8_t debug ; /* Debug flag */ + uint8_t spi_rxbuff[32+1] ; //SPI receive buffer (payload max 32 bytes) + uint8_t spi_txbuff[32+1] ; //SPI transmit buffer (payload max 32 bytes + 1 byte for the command) + +protected: + /** + * @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. + */ + /**@{*/ + + + /** + * 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 read_register(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 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 write_register(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 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 write_payload(const void* buf, uint8_t len, const uint8_t writeType); + + /** + * 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 read_payload(void* buf, uint8_t len); + + /** + * Empty the receive buffer + * + * @return Current value of status register + */ + 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 + * + * @return Current value of status register + */ + uint8_t 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 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 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 print_byte_register(const char* name, uint8_t reg, uint8_t qty = 1); + + /** + * 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 print_address_register(const char* name, uint8_t reg, uint8_t qty = 1); + + /** + * 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 toggle_features(void); + /**@}*/ + +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); + RF24(uint8_t _cepin, uint8_t _cspin, uint32_t spispeed ); + + /** + * Begin operation of the chip + * + * Call this in setup(), before calling any other methods. + */ + bool 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 + * @return True if the payload was delivered successfully false if not + */ + bool 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 + */ + 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 + */ + void 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(). + * + * @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); + + /**@}*/ + /** + * @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 + * + * @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. + * 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 setPALevel( uint8_t 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. + */ + 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 ) ; + + /**@}*/ + /** + * @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) ; + +/** + * 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); + + /** + * 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 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(); + + /** + * 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 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. + * + * @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; } + + /** + * 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); + + /**@}*/ +}; + +/** + * @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 + */ + +#endif // __RF24_H__ +// vim:ai:cin:sts=2 sw=2 ft=cpp + diff --git a/libraries/RF24/RPi/RF24/RF24_config.h b/libraries/RF24/RPi/RF24/RF24_config.h new file mode 100644 index 0000000..eef0704 --- /dev/null +++ b/libraries/RF24/RPi/RF24/RF24_config.h @@ -0,0 +1,34 @@ + +/* + 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. + + 03/17/2013 : Charles-Henri Hallard (http://hallard.me) + Modified to use with Arduipi board http://hallard.me/arduipi + Modified to use the great bcm2835 library for I/O and SPI + + */ + +#ifndef __RF24_CONFIG_H__ +#define __RF24_CONFIG_H__ + +#include +#include +#include +#include +#include +#include +#include "bcm2835.h" + +// GCC a Arduino Missing +#define max(a,b) (a>b?a:b) +#define min(a,b) (a +#include +#include +#include +#include +#include +#include +#include +#include + + +#include "bcm2835.h" + +// This define enables a little test program (by default a blinking output on pin RPI_GPIO_PIN_11) +// You can do some safe, non-destructive testing on any platform with: +// gcc bcm2835.c -D BCM2835_TEST +// ./a.out +//#define BCM2835_TEST + +// Uncommenting this define compiles alternative I2C code for the version 1 RPi +// The P1 header I2C pins are connected to SDA0 and SCL0 on V1. +// By default I2C code is generated for the V2 RPi which has SDA1 and SCL1 connected. +// #define I2C_V1 + +// Pointers to the hardware register bases +volatile uint32_t *bcm2835_gpio = (volatile uint32_t *)MAP_FAILED; +volatile uint32_t *bcm2835_pwm = (volatile uint32_t *)MAP_FAILED; +volatile uint32_t *bcm2835_clk = (volatile uint32_t *)MAP_FAILED; +volatile uint32_t *bcm2835_pads = (volatile uint32_t *)MAP_FAILED; +volatile uint32_t *bcm2835_spi0 = (volatile uint32_t *)MAP_FAILED; +volatile uint32_t *bcm2835_bsc0 = (volatile uint32_t *)MAP_FAILED; +volatile uint32_t *bcm2835_bsc1 = (volatile uint32_t *)MAP_FAILED; +volatile uint32_t *bcm2835_st = (volatile uint32_t *)MAP_FAILED; + + +// This variable allows us to test on hardware other than RPi. +// It prevents access to the kernel memory, and does not do any peripheral access +// Instead it prints out what it _would_ do if debug were 0 +static uint8_t debug = 0; + +// I2C The time needed to transmit one byte. In microseconds. +static int i2c_byte_wait_us = 0; + +// SPI Custom Chip Select Pin +//static int spi_custom_cs = 0; + +// Time for millis() +static unsigned long long epoch ; + +// +// Low level register access functions +// + +void bcm2835_set_debug(uint8_t d) +{ + debug = d; +} + +// safe read from peripheral +uint32_t bcm2835_peri_read(volatile uint32_t* paddr) +{ + if (debug) + { + printf("bcm2835_peri_read paddr %08X\n", (unsigned) paddr); + return 0; + } + else + { + // Make sure we dont return the _last_ read which might get lost + // if subsequent code changes to a different peripheral + uint32_t ret = *paddr; + *paddr; // Read without assigneing to an unused variable + return ret; + } +} + +// read from peripheral without the read barrier +uint32_t bcm2835_peri_read_nb(volatile uint32_t* paddr) +{ + if (debug) + { + printf("bcm2835_peri_read_nb paddr %08X\n", (unsigned) paddr); + return 0; + } + else + { + return *paddr; + } +} + +// safe write to peripheral +void bcm2835_peri_write(volatile uint32_t* paddr, uint32_t value) +{ + if (debug) + { + printf("bcm2835_peri_write paddr %08X, value %08X\n", (unsigned) paddr, value); + } + else + { + // Make sure we don't rely on the first write, which may get + // lost if the previous access was to a different peripheral. + *paddr = value; + *paddr = value; + } +} + +// write to peripheral without the write barrier +void bcm2835_peri_write_nb(volatile uint32_t* paddr, uint32_t value) +{ + if (debug) + { + printf("bcm2835_peri_write_nb paddr %08X, value %08X\n", + (unsigned) paddr, value); + } + else + { + *paddr = value; + } +} + +// Set/clear only the bits in value covered by the mask +void bcm2835_peri_set_bits(volatile uint32_t* paddr, uint32_t value, uint32_t mask) +{ + uint32_t v = bcm2835_peri_read(paddr); + v = (v & ~mask) | (value & mask); + bcm2835_peri_write(paddr, v); +} + +// +// Low level convenience functions +// + +// Function select +// pin is a BCM2835 GPIO pin number NOT RPi pin number +// There are 6 control registers, each control the functions of a block +// of 10 pins. +// Each control register has 10 sets of 3 bits per GPIO pin: +// +// 000 = GPIO Pin X is an input +// 001 = GPIO Pin X is an output +// 100 = GPIO Pin X takes alternate function 0 +// 101 = GPIO Pin X takes alternate function 1 +// 110 = GPIO Pin X takes alternate function 2 +// 111 = GPIO Pin X takes alternate function 3 +// 011 = GPIO Pin X takes alternate function 4 +// 010 = GPIO Pin X takes alternate function 5 +// +// So the 3 bits for port X are: +// X / 10 + ((X % 10) * 3) +void bcm2835_gpio_fsel(uint8_t pin, uint8_t mode) +{ + // Function selects are 10 pins per 32 bit word, 3 bits per pin + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPFSEL0/4 + (pin/10); + uint8_t shift = (pin % 10) * 3; + uint32_t mask = BCM2835_GPIO_FSEL_MASK << shift; + uint32_t value = mode << shift; + bcm2835_peri_set_bits(paddr, value, mask); +} + +// Set output pin +void bcm2835_gpio_set(uint8_t pin) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPSET0/4 + pin/32; + uint8_t shift = pin % 32; + bcm2835_peri_write(paddr, 1 << shift); +} + +// Clear output pin +void bcm2835_gpio_clr(uint8_t pin) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPCLR0/4 + pin/32; + uint8_t shift = pin % 32; + bcm2835_peri_write(paddr, 1 << shift); +} + +// Set all output pins in the mask +void bcm2835_gpio_set_multi(uint32_t mask) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPSET0/4; + bcm2835_peri_write(paddr, mask); +} + +// Clear all output pins in the mask +void bcm2835_gpio_clr_multi(uint32_t mask) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPCLR0/4; + bcm2835_peri_write(paddr, mask); +} + +// Read input pin +uint8_t bcm2835_gpio_lev(uint8_t pin) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPLEV0/4 + pin/32; + uint8_t shift = pin % 32; + uint32_t value = bcm2835_peri_read(paddr); + return (value & (1 << shift)) ? HIGH : LOW; +} + +// See if an event detection bit is set +// Sigh cant support interrupts yet +uint8_t bcm2835_gpio_eds(uint8_t pin) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPEDS0/4 + pin/32; + uint8_t shift = pin % 32; + uint32_t value = bcm2835_peri_read(paddr); + return (value & (1 << shift)) ? HIGH : LOW; +} + +// Write a 1 to clear the bit in EDS +void bcm2835_gpio_set_eds(uint8_t pin) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPEDS0/4 + pin/32; + uint8_t shift = pin % 32; + uint32_t value = 1 << shift; + bcm2835_peri_write(paddr, value); +} + +// Rising edge detect enable +void bcm2835_gpio_ren(uint8_t pin) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPREN0/4 + pin/32; + uint8_t shift = pin % 32; + uint32_t value = 1 << shift; + bcm2835_peri_set_bits(paddr, value, value); +} +void bcm2835_gpio_clr_ren(uint8_t pin) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPREN0/4 + pin/32; + uint8_t shift = pin % 32; + uint32_t value = 1 << shift; + bcm2835_peri_set_bits(paddr, 0, value); +} + +// Falling edge detect enable +void bcm2835_gpio_fen(uint8_t pin) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPFEN0/4 + pin/32; + uint8_t shift = pin % 32; + uint32_t value = 1 << shift; + bcm2835_peri_set_bits(paddr, value, value); +} +void bcm2835_gpio_clr_fen(uint8_t pin) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPFEN0/4 + pin/32; + uint8_t shift = pin % 32; + uint32_t value = 1 << shift; + bcm2835_peri_set_bits(paddr, 0, value); +} + +// High detect enable +void bcm2835_gpio_hen(uint8_t pin) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPHEN0/4 + pin/32; + uint8_t shift = pin % 32; + uint32_t value = 1 << shift; + bcm2835_peri_set_bits(paddr, value, value); +} +void bcm2835_gpio_clr_hen(uint8_t pin) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPHEN0/4 + pin/32; + uint8_t shift = pin % 32; + uint32_t value = 1 << shift; + bcm2835_peri_set_bits(paddr, 0, value); +} + +// Low detect enable +void bcm2835_gpio_len(uint8_t pin) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPLEN0/4 + pin/32; + uint8_t shift = pin % 32; + uint32_t value = 1 << shift; + bcm2835_peri_set_bits(paddr, value, value); +} +void bcm2835_gpio_clr_len(uint8_t pin) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPLEN0/4 + pin/32; + uint8_t shift = pin % 32; + uint32_t value = 1 << shift; + bcm2835_peri_set_bits(paddr, 0, value); +} + +// Async rising edge detect enable +void bcm2835_gpio_aren(uint8_t pin) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPAREN0/4 + pin/32; + uint8_t shift = pin % 32; + uint32_t value = 1 << shift; + bcm2835_peri_set_bits(paddr, value, value); +} +void bcm2835_gpio_clr_aren(uint8_t pin) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPAREN0/4 + pin/32; + uint8_t shift = pin % 32; + uint32_t value = 1 << shift; + bcm2835_peri_set_bits(paddr, 0, value); +} + +// Async falling edge detect enable +void bcm2835_gpio_afen(uint8_t pin) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPAFEN0/4 + pin/32; + uint8_t shift = pin % 32; + uint32_t value = 1 << shift; + bcm2835_peri_set_bits(paddr, value, value); +} +void bcm2835_gpio_clr_afen(uint8_t pin) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPAFEN0/4 + pin/32; + uint8_t shift = pin % 32; + uint32_t value = 1 << shift; + bcm2835_peri_set_bits(paddr, 0, value); +} + +// Set pullup/down +void bcm2835_gpio_pud(uint8_t pud) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPPUD/4; + bcm2835_peri_write(paddr, pud); +} + +// Pullup/down clock +// Clocks the value of pud into the GPIO pin +void bcm2835_gpio_pudclk(uint8_t pin, uint8_t on) +{ + volatile uint32_t* paddr = bcm2835_gpio + BCM2835_GPPUDCLK0/4 + pin/32; + uint8_t shift = pin % 32; + bcm2835_peri_write(paddr, (on ? 1 : 0) << shift); +} + +// Read GPIO pad behaviour for groups of GPIOs +uint32_t bcm2835_gpio_pad(uint8_t group) +{ + volatile uint32_t* paddr = bcm2835_pads + BCM2835_PADS_GPIO_0_27/4 + group*2; + return bcm2835_peri_read(paddr); +} + +// Set GPIO pad behaviour for groups of GPIOs +// powerup value for al pads is +// BCM2835_PAD_SLEW_RATE_UNLIMITED | BCM2835_PAD_HYSTERESIS_ENABLED | BCM2835_PAD_DRIVE_8mA +void bcm2835_gpio_set_pad(uint8_t group, uint32_t control) +{ + volatile uint32_t* paddr = bcm2835_pads + BCM2835_PADS_GPIO_0_27/4 + group*2; + bcm2835_peri_write(paddr, control | BCM2835_PAD_PASSWRD); +} + +// Some convenient arduino-like functions +// milliseconds +void bcm2835_delay(unsigned int millis) +{ + struct timespec sleeper; + + sleeper.tv_sec = (time_t)(millis / 1000); + sleeper.tv_nsec = (long)(millis % 1000) * 1000000; + nanosleep(&sleeper, NULL); +} + +// microseconds +void bcm2835_delayMicroseconds(uint64_t micros) +{ + struct timespec t1; + uint64_t start; + + // Calling nanosleep() takes at least 100-200 us, so use it for + // long waits and use a busy wait on the System Timer for the rest. + start = bcm2835_st_read(); + + if (micros > 450) + { + t1.tv_sec = 0; + t1.tv_nsec = 1000 * (long)(micros - 200); + nanosleep(&t1, NULL); + } + + bcm2835_st_delay(start, micros); +} + +// This function is added in order to simulate arduino millis() function +unsigned int bcm2835_millis(void) +{ +struct timeval now; +unsigned long long ms; + +gettimeofday(&now, NULL); + +ms = (now.tv_sec * 1000000 + now.tv_usec) / 1000 ; + +return ((uint32_t) (ms - epoch )); +} + +// +// Higher level convenience functions +// + +// Set the state of an output +void bcm2835_gpio_write(uint8_t pin, uint8_t on) +{ + if (on) + bcm2835_gpio_set(pin); + else + bcm2835_gpio_clr(pin); +} + +// Set the state of a all 32 outputs in the mask to on or off +void bcm2835_gpio_write_multi(uint32_t mask, uint8_t on) +{ + if (on) + bcm2835_gpio_set_multi(mask); + else + bcm2835_gpio_clr_multi(mask); +} + +// Set the state of a all 32 outputs in the mask to the values in value +void bcm2835_gpio_write_mask(uint32_t value, uint32_t mask) +{ + bcm2835_gpio_set_multi(value & mask); + bcm2835_gpio_clr_multi((~value) & mask); +} + +// Set the pullup/down resistor for a pin +// +// The GPIO Pull-up/down Clock Registers control the actuation of internal pull-downs on +// the respective GPIO pins. These registers must be used in conjunction with the GPPUD +// register to effect GPIO Pull-up/down changes. The following sequence of events is +// required: +// 1. Write to GPPUD to set the required control signal (i.e. Pull-up or Pull-Down or neither +// to remove the current Pull-up/down) +// 2. Wait 150 cycles ? this provides the required set-up time for the control signal +// 3. Write to GPPUDCLK0/1 to clock the control signal into the GPIO pads you wish to +// modify ? NOTE only the pads which receive a clock will be modified, all others will +// retain their previous state. +// 4. Wait 150 cycles ? this provides the required hold time for the control signal +// 5. Write to GPPUD to remove the control signal +// 6. Write to GPPUDCLK0/1 to remove the clock +// +// RPi has P1-03 and P1-05 with 1k8 pullup resistor +void bcm2835_gpio_set_pud(uint8_t pin, uint8_t pud) +{ + bcm2835_gpio_pud(pud); + delayMicroseconds(10); + bcm2835_gpio_pudclk(pin, 1); + delayMicroseconds(10); + bcm2835_gpio_pud(BCM2835_GPIO_PUD_OFF); + bcm2835_gpio_pudclk(pin, 0); +} + +void bcm2835_spi_begin() +{ + + // Set the SPI0 pins to the Alt 0 function to enable SPI0 access on them + //bcm2835_gpio_fsel(RPI_GPIO_P1_26, BCM2835_GPIO_FSEL_ALT0); // CE1 + + // Enable CE0 by default, will be disabled if bcm2835_chipSelect() is called using another pin + bcm2835_gpio_fsel(RPI_GPIO_P1_24, BCM2835_GPIO_FSEL_ALT0); // CE0 + + + bcm2835_gpio_fsel(RPI_GPIO_P1_21, BCM2835_GPIO_FSEL_ALT0); // MISO + bcm2835_gpio_fsel(RPI_GPIO_P1_19, BCM2835_GPIO_FSEL_ALT0); // MOSI + bcm2835_gpio_fsel(RPI_GPIO_P1_23, BCM2835_GPIO_FSEL_ALT0); // CLK + + // Set the SPI CS register to the some sensible defaults + volatile uint32_t* paddr = bcm2835_spi0 + BCM2835_SPI0_CS/4; + bcm2835_peri_write(paddr, 0); // All 0s + + // Clear TX and RX fifos + bcm2835_peri_write_nb(paddr, BCM2835_SPI0_CS_CLEAR); +} + +void bcm2835_spi_end(void) +{ + /* // Set all the SPI0 pins back to input + if (spi_custom_cs == 0) + { + bcm2835_gpio_fsel(RPI_GPIO_P1_26, BCM2835_GPIO_FSEL_INPT); // CE1 + bcm2835_gpio_fsel(RPI_GPIO_P1_24, BCM2835_GPIO_FSEL_INPT); // CE0 + } + else + { + bcm2835_gpio_fsel(spi_custom_cs, BCM2835_GPIO_FSEL_INPT); // Custom GPIO + } + bcm2835_gpio_fsel(RPI_GPIO_P1_21, BCM2835_GPIO_FSEL_INPT); // MISO + bcm2835_gpio_fsel(RPI_GPIO_P1_19, BCM2835_GPIO_FSEL_INPT); // MOSI + bcm2835_gpio_fsel(RPI_GPIO_P1_23, BCM2835_GPIO_FSEL_INPT); // CLK + */ + + // Set all the SPI0 pins back to input + bcm2835_gpio_fsel(RPI_GPIO_P1_26, BCM2835_GPIO_FSEL_INPT); // CE1 + bcm2835_gpio_fsel(RPI_GPIO_P1_24, BCM2835_GPIO_FSEL_INPT); // CE0 + bcm2835_gpio_fsel(RPI_GPIO_P1_21, BCM2835_GPIO_FSEL_INPT); // MISO + bcm2835_gpio_fsel(RPI_GPIO_P1_19, BCM2835_GPIO_FSEL_INPT); // MOSI + bcm2835_gpio_fsel(RPI_GPIO_P1_23, BCM2835_GPIO_FSEL_INPT); // CLK + +} + +/* +// Drive Custom chip select pin +void bcm2835_spi_setChipSelect(uint8_t level) +{ + // Do this only if we are using custom ChipSelect I/O + if ( spi_custom_cs > BCM2835_SPI_CS_NONE ) + bcm2835_gpio_write(spi_custom_cs, level); +}*/ + + + void bcm2835_spi_setBitOrder(uint8_t order) +{ + // BCM2835_SPI_BIT_ORDER_MSBFIRST is the only one suported by SPI0 +} + +// defaults to 0, which means a divider of 65536. +// The divisor must be a power of 2. Odd numbers +// rounded down. The maximum SPI clock rate is +// of the APB clock +void bcm2835_spi_setClockDivider(uint16_t divider) +{ + volatile uint32_t* paddr = bcm2835_spi0 + BCM2835_SPI0_CLK/4; + bcm2835_peri_write(paddr, divider); +} + +void bcm2835_spi_setDataMode(uint8_t mode) +{ + volatile uint32_t* paddr = bcm2835_spi0 + BCM2835_SPI0_CS/4; + // Mask in the CPO and CPHA bits of CS + bcm2835_peri_set_bits(paddr, mode << 2, BCM2835_SPI0_CS_CPOL | BCM2835_SPI0_CS_CPHA); +} + +// Writes (and reads) a single byte to SPI +uint8_t bcm2835_spi_transfer(uint8_t value) +{ + volatile uint32_t* paddr = bcm2835_spi0 + BCM2835_SPI0_CS/4; + volatile uint32_t* fifo = bcm2835_spi0 + BCM2835_SPI0_FIFO/4; + + // Custom chip select LOW + /*if(spi_custom_cs > BCM2835_SPI_CS_NONE){ + bcm2835_spi_setChipSelect(LOW); + }*/ + + // This is Polled transfer as per section 10.6.1 + // BUG ALERT: what happens if we get interupted in this section, and someone else + // accesses a different peripheral? + // Clear TX and RX fifos + bcm2835_peri_set_bits(paddr, BCM2835_SPI0_CS_CLEAR, BCM2835_SPI0_CS_CLEAR); + + // Set TA = 1 + bcm2835_peri_set_bits(paddr, BCM2835_SPI0_CS_TA, BCM2835_SPI0_CS_TA); + + // Maybe wait for TXD + while (!(bcm2835_peri_read(paddr) & BCM2835_SPI0_CS_TXD)){ + delayMicroseconds(10); + } + + // Write to FIFO, no barrier + bcm2835_peri_write_nb(fifo, value); + + // Wait for DONE to be set + while (!(bcm2835_peri_read_nb(paddr) & BCM2835_SPI0_CS_DONE)){ + delayMicroseconds(10); + } + + // Read any byte that was sent back by the slave while we sere sending to it + uint32_t ret = bcm2835_peri_read_nb(fifo); + + // Set TA = 0, and also set the barrier + bcm2835_peri_set_bits(paddr, 0, BCM2835_SPI0_CS_TA); + + // Custom chip select HIGH + //if(spi_custom_cs > BCM2835_SPI_CS_NONE){ + // bcm2835_spi_setChipSelect(HIGH); + //} + return ret; +} + +// Writes (and reads) an number of bytes to SPI +void bcm2835_spi_transfernb(char* tbuf, char* rbuf, uint32_t len) +{ + volatile uint32_t* paddr = bcm2835_spi0 + BCM2835_SPI0_CS/4; + volatile uint32_t* fifo = bcm2835_spi0 + BCM2835_SPI0_FIFO/4; + uint32_t TXCnt=0; + uint32_t RXCnt=0; + + // This is Polled transfer as per section 10.6.1 + // BUG ALERT: what happens if we get interupted in this section, and someone else + // accesses a different peripheral? + + // Clear TX and RX fifos + bcm2835_peri_set_bits(paddr, BCM2835_SPI0_CS_CLEAR, BCM2835_SPI0_CS_CLEAR); + + // Set TA = 1 + bcm2835_peri_set_bits(paddr, BCM2835_SPI0_CS_TA, BCM2835_SPI0_CS_TA); + + // Use the FIFO's to reduce the interbyte times + while((TXCnt < len)||(RXCnt < len)) + { + // TX fifo not full, so add some more bytes + while(((bcm2835_peri_read(paddr) & BCM2835_SPI0_CS_TXD))&&(TXCnt < len )) + { + delayMicroseconds(10); + bcm2835_peri_write_nb(fifo, tbuf[TXCnt]); + TXCnt++; + } + //Rx fifo not empty, so get the next received bytes + while(((bcm2835_peri_read(paddr) & BCM2835_SPI0_CS_RXD))&&( RXCnt < len )) + { + delayMicroseconds(10); + rbuf[RXCnt] = bcm2835_peri_read_nb(fifo); + RXCnt++; + } + } + // Wait for DONE to be set + while (!(bcm2835_peri_read_nb(paddr) & BCM2835_SPI0_CS_DONE)){ + delayMicroseconds(10); + } + // Set TA = 0, and also set the barrier + bcm2835_peri_set_bits(paddr, 0, BCM2835_SPI0_CS_TA); +} + +// Writes an number of bytes to SPI +void bcm2835_spi_writenb(char* tbuf, uint32_t len) +{ + volatile uint32_t* paddr = bcm2835_spi0 + BCM2835_SPI0_CS/4; + volatile uint32_t* fifo = bcm2835_spi0 + BCM2835_SPI0_FIFO/4; + + //if(spi_custom_cs > BCM2835_SPI_CS_NONE){ + // bcm2835_spi_setChipSelect(LOW); + //} + // This is Polled transfer as per section 10.6.1 + // BUG ALERT: what happens if we get interupted in this section, and someone else + // accesses a different peripheral? + + // Clear TX and RX fifos + bcm2835_peri_set_bits(paddr, BCM2835_SPI0_CS_CLEAR, BCM2835_SPI0_CS_CLEAR); + + // Set TA = 1 + bcm2835_peri_set_bits(paddr, BCM2835_SPI0_CS_TA, BCM2835_SPI0_CS_TA); + + uint32_t i; + for (i = 0; i < len; i++) + { + // Maybe wait for TXD + while (!(bcm2835_peri_read(paddr) & BCM2835_SPI0_CS_TXD)) + ; + + // Write to FIFO, no barrier + bcm2835_peri_write_nb(fifo, tbuf[i]); + + // Read from FIFO to prevent stalling + while (bcm2835_peri_read(paddr) & BCM2835_SPI0_CS_RXD) + (void) bcm2835_peri_read_nb(fifo); + } + + // Wait for DONE to be set + while (!(bcm2835_peri_read_nb(paddr) & BCM2835_SPI0_CS_DONE)) { + while (bcm2835_peri_read(paddr) & BCM2835_SPI0_CS_RXD) + (void) bcm2835_peri_read_nb(fifo); + }; + + // Set TA = 0, and also set the barrier + bcm2835_peri_set_bits(paddr, 0, BCM2835_SPI0_CS_TA); + + //if(spi_custom_cs > BCM2835_SPI_CS_NONE){ + // bcm2835_spi_setChipSelect(HIGH); + //} +} + +// Writes (and reads) an number of bytes to SPI +// Read bytes are copied over onto the transmit buffer +void bcm2835_spi_transfern(char* buf, uint32_t len) +{ + bcm2835_spi_transfernb(buf, buf, len); +} + +void bcm2835_spi_chipSelect(uint8_t cs) +{ + volatile uint32_t* paddr = bcm2835_spi0 + BCM2835_SPI0_CS/4; + + if(cs){ + bcm2835_gpio_fsel(RPI_GPIO_P1_26, BCM2835_GPIO_FSEL_ALT0); // CE1 + bcm2835_gpio_fsel(RPI_GPIO_P1_24, BCM2835_GPIO_FSEL_INPT); // Revert default of CE0 back to input + }else{ + bcm2835_gpio_fsel(RPI_GPIO_P1_24, BCM2835_GPIO_FSEL_ALT0); // CE0 + } + + // Mask in the CS bits of CS + bcm2835_peri_set_bits(paddr, cs, BCM2835_SPI0_CS_CS); +} + +void bcm2835_spi_setChipSelectPolarity(uint8_t cs, uint8_t active) +{ + volatile uint32_t* paddr = bcm2835_spi0 + BCM2835_SPI0_CS/4; + uint8_t shift = 21 + cs; + // Mask in the appropriate CSPOLn bit + bcm2835_peri_set_bits(paddr, active << shift, 1 << shift); +} + +void bcm2835_i2c_begin(void) +{ +#ifdef I2C_V1 + volatile uint32_t* paddr = bcm2835_bsc0 + BCM2835_BSC_DIV/4; + // Set the I2C/BSC0 pins to the Alt 0 function to enable I2C access on them + bcm2835_gpio_fsel(RPI_GPIO_P1_03, BCM2835_GPIO_FSEL_ALT0); // SDA + bcm2835_gpio_fsel(RPI_GPIO_P1_05, BCM2835_GPIO_FSEL_ALT0); // SCL +#else + volatile uint32_t* paddr = bcm2835_bsc1 + BCM2835_BSC_DIV/4; + // Set the I2C/BSC1 pins to the Alt 0 function to enable I2C access on them + bcm2835_gpio_fsel(RPI_V2_GPIO_P1_03, BCM2835_GPIO_FSEL_ALT0); // SDA + bcm2835_gpio_fsel(RPI_V2_GPIO_P1_05, BCM2835_GPIO_FSEL_ALT0); // SCL +#endif + + // Read the clock divider register + uint16_t cdiv = bcm2835_peri_read(paddr); + // Calculate time for transmitting one byte + // 1000000 = micros seconds in a second + // 9 = Clocks per byte : 8 bits + ACK + i2c_byte_wait_us = ((float)cdiv / BCM2835_CORE_CLK_HZ) * 1000000 * 9; +} + +void bcm2835_i2c_end(void) +{ +#ifdef I2C_V1 + // Set all the I2C/BSC0 pins back to input + bcm2835_gpio_fsel(RPI_GPIO_P1_03, BCM2835_GPIO_FSEL_INPT); // SDA + bcm2835_gpio_fsel(RPI_GPIO_P1_05, BCM2835_GPIO_FSEL_INPT); // SCL +#else + // Set all the I2C/BSC1 pins back to input + bcm2835_gpio_fsel(RPI_V2_GPIO_P1_03, BCM2835_GPIO_FSEL_INPT); // SDA + bcm2835_gpio_fsel(RPI_V2_GPIO_P1_05, BCM2835_GPIO_FSEL_INPT); // SCL +#endif +} + +void bcm2835_i2c_setSlaveAddress(uint8_t addr) +{ + // Set I2C Device Address +#ifdef I2C_V1 + volatile uint32_t* paddr = bcm2835_bsc0 + BCM2835_BSC_A/4; +#else + volatile uint32_t* paddr = bcm2835_bsc1 + BCM2835_BSC_A/4; +#endif + bcm2835_peri_write(paddr, addr); +} + +// defaults to 0x5dc, should result in a 166.666 kHz I2C clock frequency. +// The divisor must be a power of 2. Odd numbers +// rounded down. +void bcm2835_i2c_setClockDivider(uint16_t divider) +{ +#ifdef I2C_V1 + volatile uint32_t* paddr = bcm2835_bsc0 + BCM2835_BSC_DIV/4; +#else + volatile uint32_t* paddr = bcm2835_bsc1 + BCM2835_BSC_DIV/4; +#endif + bcm2835_peri_write(paddr, divider); + // Calculate time for transmitting one byte + // 1000000 = micros seconds in a second + // 9 = Clocks per byte : 8 bits + ACK + i2c_byte_wait_us = ((float)divider / BCM2835_CORE_CLK_HZ) * 1000000 * 9; +} + +// set I2C clock divider by means of a baudrate number +void bcm2835_i2c_set_baudrate(uint32_t baudrate) +{ + uint32_t divider; + // use 0xFFFE mask to limit a max value and round down any odd number + divider = (BCM2835_CORE_CLK_HZ / baudrate) & 0xFFFE; + bcm2835_i2c_setClockDivider( (uint16_t)divider ); +} + +// Writes an number of bytes to I2C +uint8_t bcm2835_i2c_write(const char * buf, uint32_t len) +{ +#ifdef I2C_V1 + volatile uint32_t* dlen = bcm2835_bsc0 + BCM2835_BSC_DLEN/4; + volatile uint32_t* fifo = bcm2835_bsc0 + BCM2835_BSC_FIFO/4; + volatile uint32_t* status = bcm2835_bsc0 + BCM2835_BSC_S/4; + volatile uint32_t* control = bcm2835_bsc0 + BCM2835_BSC_C/4; +#else + volatile uint32_t* dlen = bcm2835_bsc1 + BCM2835_BSC_DLEN/4; + volatile uint32_t* fifo = bcm2835_bsc1 + BCM2835_BSC_FIFO/4; + volatile uint32_t* status = bcm2835_bsc1 + BCM2835_BSC_S/4; + volatile uint32_t* control = bcm2835_bsc1 + BCM2835_BSC_C/4; +#endif + + uint32_t remaining = len; + uint32_t i = 0; + uint8_t reason = BCM2835_I2C_REASON_OK; + + // Clear FIFO + bcm2835_peri_set_bits(control, BCM2835_BSC_C_CLEAR_1 , BCM2835_BSC_C_CLEAR_1 ); + // Clear Status + bcm2835_peri_write_nb(status, BCM2835_BSC_S_CLKT | BCM2835_BSC_S_ERR | BCM2835_BSC_S_DONE); + // Set Data Length + bcm2835_peri_write_nb(dlen, len); + // pre populate FIFO with max buffer + while( remaining && ( i < BCM2835_BSC_FIFO_SIZE ) ) + { + bcm2835_peri_write_nb(fifo, buf[i]); + i++; + remaining--; + } + + // Enable device and start transfer + bcm2835_peri_write_nb(control, BCM2835_BSC_C_I2CEN | BCM2835_BSC_C_ST); + + // Transfer is over when BCM2835_BSC_S_DONE + while(!(bcm2835_peri_read_nb(status) & BCM2835_BSC_S_DONE )) + { + while ( remaining && (bcm2835_peri_read_nb(status) & BCM2835_BSC_S_TXD )) + { + // Write to FIFO, no barrier + bcm2835_peri_write_nb(fifo, buf[i]); + i++; + remaining--; + } + } + + // Received a NACK + if (bcm2835_peri_read(status) & BCM2835_BSC_S_ERR) + { + reason = BCM2835_I2C_REASON_ERROR_NACK; + } + + // Received Clock Stretch Timeout + else if (bcm2835_peri_read(status) & BCM2835_BSC_S_CLKT) + { + reason = BCM2835_I2C_REASON_ERROR_CLKT; + } + + // Not all data is sent + else if (remaining) + { + reason = BCM2835_I2C_REASON_ERROR_DATA; + } + + bcm2835_peri_set_bits(control, BCM2835_BSC_S_DONE , BCM2835_BSC_S_DONE); + + return reason; +} + +// Read an number of bytes from I2C +uint8_t bcm2835_i2c_read(char* buf, uint32_t len) +{ +#ifdef I2C_V1 + volatile uint32_t* dlen = bcm2835_bsc0 + BCM2835_BSC_DLEN/4; + volatile uint32_t* fifo = bcm2835_bsc0 + BCM2835_BSC_FIFO/4; + volatile uint32_t* status = bcm2835_bsc0 + BCM2835_BSC_S/4; + volatile uint32_t* control = bcm2835_bsc0 + BCM2835_BSC_C/4; +#else + volatile uint32_t* dlen = bcm2835_bsc1 + BCM2835_BSC_DLEN/4; + volatile uint32_t* fifo = bcm2835_bsc1 + BCM2835_BSC_FIFO/4; + volatile uint32_t* status = bcm2835_bsc1 + BCM2835_BSC_S/4; + volatile uint32_t* control = bcm2835_bsc1 + BCM2835_BSC_C/4; +#endif + + uint32_t remaining = len; + uint32_t i = 0; + uint8_t reason = BCM2835_I2C_REASON_OK; + + // Clear FIFO + bcm2835_peri_set_bits(control, BCM2835_BSC_C_CLEAR_1 , BCM2835_BSC_C_CLEAR_1 ); + // Clear Status + bcm2835_peri_write_nb(status, BCM2835_BSC_S_CLKT | BCM2835_BSC_S_ERR | BCM2835_BSC_S_DONE); + // Set Data Length + bcm2835_peri_write_nb(dlen, len); + // Start read + bcm2835_peri_write_nb(control, BCM2835_BSC_C_I2CEN | BCM2835_BSC_C_ST | BCM2835_BSC_C_READ); + + // wait for transfer to complete + while (!(bcm2835_peri_read_nb(status) & BCM2835_BSC_S_DONE)) + { + // we must empty the FIFO as it is populated and not use any delay + while (bcm2835_peri_read_nb(status) & BCM2835_BSC_S_RXD) + { + // Read from FIFO, no barrier + buf[i] = bcm2835_peri_read_nb(fifo); + i++; + remaining--; + } + } + + // transfer has finished - grab any remaining stuff in FIFO + while (remaining && (bcm2835_peri_read_nb(status) & BCM2835_BSC_S_RXD)) + { + // Read from FIFO, no barrier + buf[i] = bcm2835_peri_read_nb(fifo); + i++; + remaining--; + } + + // Received a NACK + if (bcm2835_peri_read(status) & BCM2835_BSC_S_ERR) + { + reason = BCM2835_I2C_REASON_ERROR_NACK; + } + + // Received Clock Stretch Timeout + else if (bcm2835_peri_read(status) & BCM2835_BSC_S_CLKT) + { + reason = BCM2835_I2C_REASON_ERROR_CLKT; + } + + // Not all data is received + else if (remaining) + { + reason = BCM2835_I2C_REASON_ERROR_DATA; + } + + bcm2835_peri_set_bits(control, BCM2835_BSC_S_DONE , BCM2835_BSC_S_DONE); + + return reason; +} + +// Read an number of bytes from I2C sending a repeated start after writing +// the required register. Only works if your device supports this mode +uint8_t bcm2835_i2c_read_register_rs(char* regaddr, char* buf, uint32_t len) +{ +#ifdef I2C_V1 + volatile uint32_t* dlen = bcm2835_bsc0 + BCM2835_BSC_DLEN/4; + volatile uint32_t* fifo = bcm2835_bsc0 + BCM2835_BSC_FIFO/4; + volatile uint32_t* status = bcm2835_bsc0 + BCM2835_BSC_S/4; + volatile uint32_t* control = bcm2835_bsc0 + BCM2835_BSC_C/4; +#else + volatile uint32_t* dlen = bcm2835_bsc1 + BCM2835_BSC_DLEN/4; + volatile uint32_t* fifo = bcm2835_bsc1 + BCM2835_BSC_FIFO/4; + volatile uint32_t* status = bcm2835_bsc1 + BCM2835_BSC_S/4; + volatile uint32_t* control = bcm2835_bsc1 + BCM2835_BSC_C/4; +#endif + uint32_t remaining = len; + uint32_t i = 0; + uint8_t reason = BCM2835_I2C_REASON_OK; + + // Clear FIFO + bcm2835_peri_set_bits(control, BCM2835_BSC_C_CLEAR_1 , BCM2835_BSC_C_CLEAR_1 ); + // Clear Status + bcm2835_peri_write_nb(status, BCM2835_BSC_S_CLKT | BCM2835_BSC_S_ERR | BCM2835_BSC_S_DONE); + // Set Data Length + bcm2835_peri_write_nb(dlen, 1); + // Enable device and start transfer + bcm2835_peri_write_nb(control, BCM2835_BSC_C_I2CEN); + bcm2835_peri_write_nb(fifo, regaddr[0]); + bcm2835_peri_write_nb(control, BCM2835_BSC_C_I2CEN | BCM2835_BSC_C_ST); + + // poll for transfer has started + while ( !( bcm2835_peri_read_nb(status) & BCM2835_BSC_S_TA ) ) + { + // Linux may cause us to miss entire transfer stage + if(bcm2835_peri_read(status) & BCM2835_BSC_S_DONE) + break; + } + + // Send a repeated start with read bit set in address + bcm2835_peri_write_nb(dlen, len); + bcm2835_peri_write_nb(control, BCM2835_BSC_C_I2CEN | BCM2835_BSC_C_ST | BCM2835_BSC_C_READ ); + + // Wait for write to complete and first byte back. + bcm2835_delayMicroseconds(i2c_byte_wait_us * 3); + + // wait for transfer to complete + while (!(bcm2835_peri_read_nb(status) & BCM2835_BSC_S_DONE)) + { + // we must empty the FIFO as it is populated and not use any delay + while (remaining && bcm2835_peri_read_nb(status) & BCM2835_BSC_S_RXD) + { + // Read from FIFO, no barrier + buf[i] = bcm2835_peri_read_nb(fifo); + i++; + remaining--; + } + } + + // transfer has finished - grab any remaining stuff in FIFO + while (remaining && (bcm2835_peri_read_nb(status) & BCM2835_BSC_S_RXD)) + { + // Read from FIFO, no barrier + buf[i] = bcm2835_peri_read_nb(fifo); + i++; + remaining--; + } + + // Received a NACK + if (bcm2835_peri_read(status) & BCM2835_BSC_S_ERR) + { + reason = BCM2835_I2C_REASON_ERROR_NACK; + } + + // Received Clock Stretch Timeout + else if (bcm2835_peri_read(status) & BCM2835_BSC_S_CLKT) + { + reason = BCM2835_I2C_REASON_ERROR_CLKT; + } + + // Not all data is sent + else if (remaining) + { + reason = BCM2835_I2C_REASON_ERROR_DATA; + } + + bcm2835_peri_set_bits(control, BCM2835_BSC_S_DONE , BCM2835_BSC_S_DONE); + + return reason; +} + +// Sending an arbitrary number of bytes before issuing a repeated start +// (with no prior stop) and reading a response. Some devices require this behavior. +uint8_t bcm2835_i2c_write_read_rs(char* cmds, uint32_t cmds_len, char* buf, uint32_t buf_len) +{ +#ifdef I2C_V1 + volatile uint32_t* dlen = bcm2835_bsc0 + BCM2835_BSC_DLEN/4; + volatile uint32_t* fifo = bcm2835_bsc0 + BCM2835_BSC_FIFO/4; + volatile uint32_t* status = bcm2835_bsc0 + BCM2835_BSC_S/4; + volatile uint32_t* control = bcm2835_bsc0 + BCM2835_BSC_C/4; +#else + volatile uint32_t* dlen = bcm2835_bsc1 + BCM2835_BSC_DLEN/4; + volatile uint32_t* fifo = bcm2835_bsc1 + BCM2835_BSC_FIFO/4; + volatile uint32_t* status = bcm2835_bsc1 + BCM2835_BSC_S/4; + volatile uint32_t* control = bcm2835_bsc1 + BCM2835_BSC_C/4; +#endif + + uint32_t remaining = cmds_len; + uint32_t i = 0; + uint8_t reason = BCM2835_I2C_REASON_OK; + + // Clear FIFO + bcm2835_peri_set_bits(control, BCM2835_BSC_C_CLEAR_1 , BCM2835_BSC_C_CLEAR_1 ); + + // Clear Status + bcm2835_peri_write_nb(status, BCM2835_BSC_S_CLKT | BCM2835_BSC_S_ERR | BCM2835_BSC_S_DONE); + + // Set Data Length + bcm2835_peri_write_nb(dlen, cmds_len); + + // pre populate FIFO with max buffer + while( remaining && ( i < BCM2835_BSC_FIFO_SIZE ) ) + { + bcm2835_peri_write_nb(fifo, cmds[i]); + i++; + remaining--; + } + + // Enable device and start transfer + bcm2835_peri_write_nb(control, BCM2835_BSC_C_I2CEN | BCM2835_BSC_C_ST); + + // poll for transfer has started (way to do repeated start, from BCM2835 datasheet) + while ( !( bcm2835_peri_read_nb(status) & BCM2835_BSC_S_TA ) ) + { + // Linux may cause us to miss entire transfer stage + if(bcm2835_peri_read(status) & BCM2835_BSC_S_DONE) + break; + } + + remaining = buf_len; + i = 0; + + // Send a repeated start with read bit set in address + bcm2835_peri_write_nb(dlen, buf_len); + bcm2835_peri_write_nb(control, BCM2835_BSC_C_I2CEN | BCM2835_BSC_C_ST | BCM2835_BSC_C_READ ); + + // Wait for write to complete and first byte back. + bcm2835_delayMicroseconds(i2c_byte_wait_us * (cmds_len + 1)); + + // wait for transfer to complete + while (!(bcm2835_peri_read_nb(status) & BCM2835_BSC_S_DONE)) + { + // we must empty the FIFO as it is populated and not use any delay + while (remaining && bcm2835_peri_read_nb(status) & BCM2835_BSC_S_RXD) + { + // Read from FIFO, no barrier + buf[i] = bcm2835_peri_read_nb(fifo); + i++; + remaining--; + } + } + + // transfer has finished - grab any remaining stuff in FIFO + while (remaining && (bcm2835_peri_read_nb(status) & BCM2835_BSC_S_RXD)) + { + // Read from FIFO, no barrier + buf[i] = bcm2835_peri_read_nb(fifo); + i++; + remaining--; + } + + // Received a NACK + if (bcm2835_peri_read(status) & BCM2835_BSC_S_ERR) + { + reason = BCM2835_I2C_REASON_ERROR_NACK; + } + + // Received Clock Stretch Timeout + else if (bcm2835_peri_read(status) & BCM2835_BSC_S_CLKT) + { + reason = BCM2835_I2C_REASON_ERROR_CLKT; + } + + // Not all data is sent + else if (remaining) + { + reason = BCM2835_I2C_REASON_ERROR_DATA; + } + + bcm2835_peri_set_bits(control, BCM2835_BSC_S_DONE , BCM2835_BSC_S_DONE); + + return reason; +} + +// Read the System Timer Counter (64-bits) +uint64_t bcm2835_st_read(void) +{ + volatile uint32_t* paddr; + uint64_t st; + paddr = bcm2835_st + BCM2835_ST_CHI/4; + st = bcm2835_peri_read(paddr); + st <<= 32; + paddr = bcm2835_st + BCM2835_ST_CLO/4; + st += bcm2835_peri_read(paddr); + return st; +} + +// Delays for the specified number of microseconds with offset +void bcm2835_st_delay(uint64_t offset_micros, uint64_t micros) +{ + uint64_t compare = offset_micros + micros; + + while(bcm2835_st_read() < compare) + ; +} + +// PWM + +void bcm2835_pwm_set_clock(uint32_t divisor) +{ + // From Gerts code + divisor &= 0xfff; + // Stop PWM clock + bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_CNTL, BCM2835_PWM_PASSWRD | 0x01); + bcm2835_delay(110); // Prevents clock going slow + // Wait for the clock to be not busy + while ((bcm2835_peri_read(bcm2835_clk + BCM2835_PWMCLK_CNTL) & 0x80) != 0) + bcm2835_delay(1); + // set the clock divider and enable PWM clock + bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_DIV, BCM2835_PWM_PASSWRD | (divisor << 12)); + bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_CNTL, BCM2835_PWM_PASSWRD | 0x11); // Source=osc and enable +} + +void bcm2835_pwm_set_mode(uint8_t channel, uint8_t markspace, uint8_t enabled) +{ + uint32_t control = bcm2835_peri_read(bcm2835_pwm + BCM2835_PWM_CONTROL); + + if (channel == 0) + { + if (markspace) + control |= BCM2835_PWM0_MS_MODE; + else + control &= ~BCM2835_PWM0_MS_MODE; + if (enabled) + control |= BCM2835_PWM0_ENABLE; + else + control &= ~BCM2835_PWM0_ENABLE; + } + else if (channel == 1) + { + if (markspace) + control |= BCM2835_PWM1_MS_MODE; + else + control &= ~BCM2835_PWM1_MS_MODE; + if (enabled) + control |= BCM2835_PWM1_ENABLE; + else + control &= ~BCM2835_PWM1_ENABLE; + } + + // If you use the barrier here, wierd things happen, and the commands dont work + bcm2835_peri_write_nb(bcm2835_pwm + BCM2835_PWM_CONTROL, control); + // bcm2835_peri_write_nb(bcm2835_pwm + BCM2835_PWM_CONTROL, BCM2835_PWM0_ENABLE | BCM2835_PWM1_ENABLE | BCM2835_PWM0_MS_MODE | BCM2835_PWM1_MS_MODE); + +} + +void bcm2835_pwm_set_range(uint8_t channel, uint32_t range) +{ + if (channel == 0) + bcm2835_peri_write_nb(bcm2835_pwm + BCM2835_PWM0_RANGE, range); + else if (channel == 1) + bcm2835_peri_write_nb(bcm2835_pwm + BCM2835_PWM1_RANGE, range); +} + +void bcm2835_pwm_set_data(uint8_t channel, uint32_t data) +{ + if (channel == 0) + bcm2835_peri_write_nb(bcm2835_pwm + BCM2835_PWM0_DATA, data); + else if (channel == 1) + bcm2835_peri_write_nb(bcm2835_pwm + BCM2835_PWM1_DATA, data); +} + +// Allocate page-aligned memory. +void *malloc_aligned(size_t size) +{ + void *mem; + errno = posix_memalign(&mem, BCM2835_PAGE_SIZE, size); + return (errno ? NULL : mem); +} + +// Map 'size' bytes starting at 'off' in file 'fd' to memory. +// Return mapped address on success, MAP_FAILED otherwise. +// On error print message. +static void *mapmem(const char *msg, size_t size, int fd, off_t off) +{ + void *map = mmap(NULL, size, (PROT_READ | PROT_WRITE), MAP_SHARED, fd, off); + if (MAP_FAILED == map) + fprintf(stderr, "bcm2835_init: %s mmap failed: %s\n", msg, strerror(errno)); + return map; +} + +static void unmapmem(void **pmem, size_t size) +{ + if (*pmem == MAP_FAILED) return; + munmap(*pmem, size); + *pmem = MAP_FAILED; +} + +// Initialise this library. +int bcm2835_init(void) +{ + struct timeval tv ; + + if (debug) + { + bcm2835_pads = (uint32_t*)BCM2835_GPIO_PADS; + bcm2835_clk = (uint32_t*)BCM2835_CLOCK_BASE; + bcm2835_gpio = (uint32_t*)BCM2835_GPIO_BASE; + bcm2835_pwm = (uint32_t*)BCM2835_GPIO_PWM; + bcm2835_spi0 = (uint32_t*)BCM2835_SPI0_BASE; + bcm2835_bsc0 = (uint32_t*)BCM2835_BSC0_BASE; + bcm2835_bsc1 = (uint32_t*)BCM2835_BSC1_BASE; + bcm2835_st = (uint32_t*)BCM2835_ST_BASE; + return 1; // Success + } + int memfd = -1; + int ok = 0; + // Open the master /dev/memory device + if ((memfd = open("/dev/mem", O_RDWR | O_SYNC) ) < 0) + { + fprintf(stderr, "bcm2835_init: Unable to open /dev/mem: %s\n", + strerror(errno)) ; + goto exit; + } + + // GPIO: + bcm2835_gpio = (volatile uint32_t *)mapmem("gpio", BCM2835_BLOCK_SIZE, memfd, BCM2835_GPIO_BASE); + if (bcm2835_gpio == MAP_FAILED) goto exit; + + // PWM + bcm2835_pwm = (volatile uint32_t *)mapmem("pwm", BCM2835_BLOCK_SIZE, memfd, BCM2835_GPIO_PWM); + if (bcm2835_pwm == MAP_FAILED) goto exit; + + // Clock control (needed for PWM) + bcm2835_clk = (volatile uint32_t *)mapmem("clk", BCM2835_BLOCK_SIZE, memfd, BCM2835_CLOCK_BASE); + if (bcm2835_clk == MAP_FAILED) goto exit; + + bcm2835_pads = (volatile uint32_t *)mapmem("pads", BCM2835_BLOCK_SIZE, memfd, BCM2835_GPIO_PADS); + if (bcm2835_pads == MAP_FAILED) goto exit; + + bcm2835_spi0 = (volatile uint32_t *)mapmem("spi0", BCM2835_BLOCK_SIZE, memfd, BCM2835_SPI0_BASE); + if (bcm2835_spi0 == MAP_FAILED) goto exit; + + // I2C + bcm2835_bsc0 = (volatile uint32_t *)mapmem("bsc0", BCM2835_BLOCK_SIZE, memfd, BCM2835_BSC0_BASE); + if (bcm2835_bsc0 == MAP_FAILED) goto exit; + + bcm2835_bsc1 = (volatile uint32_t *)mapmem("bsc1", BCM2835_BLOCK_SIZE, memfd, BCM2835_BSC1_BASE); + if (bcm2835_bsc1 == MAP_FAILED) goto exit; + + // ST + bcm2835_st = (volatile uint32_t *)mapmem("st", BCM2835_BLOCK_SIZE, memfd, BCM2835_ST_BASE); + if (bcm2835_st == MAP_FAILED) goto exit; + + ok = 1; + +exit: + if (memfd >= 0) + close(memfd); + + if (!ok) + bcm2835_close(); + + gettimeofday (&tv, NULL) ; + epoch = (tv.tv_sec * 1000000 + tv.tv_usec) / 1000 ; + + return ok; +} + +// Close this library and deallocate everything +int bcm2835_close(void) +{ + if (debug) return 1; // Success + unmapmem((void**) &bcm2835_gpio, BCM2835_BLOCK_SIZE); + unmapmem((void**) &bcm2835_pwm, BCM2835_BLOCK_SIZE); + unmapmem((void**) &bcm2835_clk, BCM2835_BLOCK_SIZE); + unmapmem((void**) &bcm2835_spi0, BCM2835_BLOCK_SIZE); + unmapmem((void**) &bcm2835_bsc0, BCM2835_BLOCK_SIZE); + unmapmem((void**) &bcm2835_bsc1, BCM2835_BLOCK_SIZE); + unmapmem((void**) &bcm2835_st, BCM2835_BLOCK_SIZE); + unmapmem((void**) &bcm2835_pads, BCM2835_BLOCK_SIZE); + return 1; // Success +} + +#ifdef BCM2835_TEST +// this is a simple test program that prints out what it will do rather than +// actually doing it +int main(int argc, char **argv) +{ + // Be non-destructive + bcm2835_set_debug(1); + + if (!bcm2835_init()) + return 1; + + // Configure some GPIO pins fo some testing + // Set RPI pin P1-11 to be an output + bcm2835_gpio_fsel(RPI_GPIO_P1_11, BCM2835_GPIO_FSEL_OUTP); + // Set RPI pin P1-15 to be an input + bcm2835_gpio_fsel(RPI_GPIO_P1_15, BCM2835_GPIO_FSEL_INPT); + // with a pullup + bcm2835_gpio_set_pud(RPI_GPIO_P1_15, BCM2835_GPIO_PUD_UP); + // And a low detect enable + bcm2835_gpio_len(RPI_GPIO_P1_15); + // and input hysteresis disabled on GPIOs 0 to 27 + bcm2835_gpio_set_pad(BCM2835_PAD_GROUP_GPIO_0_27, BCM2835_PAD_SLEW_RATE_UNLIMITED|BCM2835_PAD_DRIVE_8mA); + +#if 1 + // Blink + while (1) + { + // Turn it on + bcm2835_gpio_write(RPI_GPIO_P1_11, HIGH); + + // wait a bit + bcm2835_delay(500); + + // turn it off + bcm2835_gpio_write(RPI_GPIO_P1_11, LOW); + + // wait a bit + bcm2835_delay(500); + } +#endif + +#if 0 + // Read input + while (1) + { + // Read some data + uint8_t value = bcm2835_gpio_lev(RPI_GPIO_P1_15); + printf("read from pin 15: %d\n", value); + + // wait a bit + bcm2835_delay(500); + } +#endif + +#if 0 + // Look for a low event detection + // eds will be set whenever pin 15 goes low + while (1) + { + if (bcm2835_gpio_eds(RPI_GPIO_P1_15)) + { + // Now clear the eds flag by setting it to 1 + bcm2835_gpio_set_eds(RPI_GPIO_P1_15); + printf("low event detect for pin 15\n"); + } + + // wait a bit + bcm2835_delay(500); + } +#endif + + if (!bcm2835_close()) + return 1; + + return 0; +} +#endif + + + diff --git a/libraries/RF24/RPi/RF24/bcm2835.h b/libraries/RF24/RPi/RF24/bcm2835.h new file mode 100644 index 0000000..f550fcb --- /dev/null +++ b/libraries/RF24/RPi/RF24/bcm2835.h @@ -0,0 +1,1353 @@ +// bcm2835.h +// +// C and C++ support for Broadcom BCM 2835 as used in Raspberry Pi +// +// Author: Mike McCauley +// Copyright (C) 2011-2013 Mike McCauley +// $Id: bcm2835.h,v 1.13 2013/12/06 22:24:52 mikem Exp mikem $ +// +//****************************************/ +// TMRh20 2014 - Merge updated lib from here: http://www.airspayce.com/mikem/bcm2835/group__spi.html#ga2fa186568605c21e9166a19b1d82ea95 +// with lib from here: https://github.com/farconada/RF24Network/blob/master/bcm2835.c +// Uses ONLY hardware CS pins +// Any CE pin can be used +// For use with optimized RPi RF24 and RF24 Network libs - see github.com/TMRh20 +//****************************************/ +// +/// \mainpage C library for Broadcom BCM 2835 as used in Raspberry Pi +/// +/// This is a C library for Raspberry Pi (RPi). It provides access to +/// GPIO and other IO functions on the Broadcom BCM 2835 chip, +/// allowing access to the GPIO pins on the +/// 26 pin IDE plug on the RPi board so you can control and interface with various external devices. +/// +/// It provides functions for reading digital inputs and setting digital outputs, using SPI and I2C, +/// and for accessing the system timers. +/// Pin event detection is supported by polling (interrupts are not supported). +/// +/// It is C++ compatible, and installs as a header file and non-shared library on +/// any Linux-based distro (but clearly is no use except on Raspberry Pi or another board with +/// BCM 2835). +/// +/// The version of the package that this documentation refers to can be downloaded +/// from http://www.airspayce.com/mikem/bcm2835/bcm2835-1.36.tar.gz +/// You can find the latest version at http://www.airspayce.com/mikem/bcm2835 +/// +/// Several example programs are provided. +/// +/// Based on data in http://elinux.org/RPi_Low-level_peripherals and +/// http://www.raspberrypi.org/wp-content/uploads/2012/02/BCM2835-ARM-Peripherals.pdf +/// and http://www.scribd.com/doc/101830961/GPIO-Pads-Control2 +/// +/// You can also find online help and discussion at http://groups.google.com/group/bcm2835 +/// Please use that group for all questions and discussions on this topic. +/// Do not contact the author directly, unless it is to discuss commercial licensing. +/// +/// Tested on debian6-19-04-2012, 2012-07-15-wheezy-raspbian, 2013-07-26-wheezy-raspbian +/// and Occidentalisv01 +/// CAUTION: it has been observed that when detect enables such as bcm2835_gpio_len() +/// are used and the pin is pulled LOW +/// it can cause temporary hangs on 2012-07-15-wheezy-raspbian, 2013-07-26-wheezy-raspbian +/// and Occidentalisv01. +/// Reason for this is not yet determined, but we suspect that an interrupt handler is +/// hitting a hard loop on those OSs. +/// If you must use bcm2835_gpio_len() and friends, make sure you disable the pins with +/// bcm2835_gpio_clr_len() and friends after use. +/// +/// \par Installation +/// +/// This library consists of a single non-shared library and header file, which will be +/// installed in the usual places by make install +/// +/// \code +/// # download the latest version of the library, say bcm2835-1.xx.tar.gz, then: +/// tar zxvf bcm2835-1.xx.tar.gz +/// cd bcm2835-1.xx +/// ./configure +/// make +/// sudo make check +/// sudo make install +/// \endcode +/// +/// \par Physical Addresses +/// +/// The functions bcm2835_peri_read(), bcm2835_peri_write() and bcm2835_peri_set_bits() +/// are low level peripheral register access functions. They are designed to use +/// physical addresses as described in section 1.2.3 ARM physical addresses +/// of the BCM2835 ARM Peripherals manual. +/// Physical addresses range from 0x20000000 to 0x20FFFFFF for peripherals. The bus +/// addresses for peripherals are set up to map onto the peripheral bus address range starting at +/// 0x7E000000. Thus a peripheral advertised in the manual at bus address 0x7Ennnnnn is available at +/// physical address 0x20nnnnnn. +/// +/// The base address of the various peripheral registers are available with the following +/// externals: +/// bcm2835_gpio +/// bcm2835_pwm +/// bcm2835_clk +/// bcm2835_pads +/// bcm2835_spio0 +/// bcm2835_st +/// bcm2835_bsc0 +/// bcm2835_bsc1 +/// +/// \par Pin Numbering +/// +/// The GPIO pin numbering as used by RPi is different to and inconsistent with the underlying +/// BCM 2835 chip pin numbering. http://elinux.org/RPi_BCM2835_GPIOs +/// +/// RPi has a 26 pin IDE header that provides access to some of the GPIO pins on the BCM 2835, +/// as well as power and ground pins. Not all GPIO pins on the BCM 2835 are available on the +/// IDE header. +/// +/// RPi Version 2 also has a P5 connector with 4 GPIO pins, 5V, 3.3V and Gnd. +/// +/// The functions in this library are designed to be passed the BCM 2835 GPIO pin number and _not_ +/// the RPi pin number. There are symbolic definitions for each of the available pins +/// that you should use for convenience. See \ref RPiGPIOPin. +/// +/// \par SPI Pins +/// +/// The bcm2835_spi_* functions allow you to control the BCM 2835 SPI0 interface, +/// allowing you to send and received data by SPI (Serial Peripheral Interface). +/// For more information about SPI, see http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus +/// +/// When bcm2835_spi_begin() is called it changes the bahaviour of the SPI interface pins from their +/// default GPIO behaviour in order to support SPI. While SPI is in use, you will not be able +/// to control the state of the SPI pins through the usual bcm2835_spi_gpio_write(). +/// When bcm2835_spi_end() is called, the SPI pins will all revert to inputs, and can then be +/// configured and controled with the usual bcm2835_gpio_* calls. +/// +/// The Raspberry Pi GPIO pins used for SPI are: +/// +/// - P1-19 (MOSI) +/// - P1-21 (MISO) +/// - P1-23 (CLK) +/// - P1-24 (CE0) +/// - P1-26 (CE1) +/// +/// \par I2C Pins +/// +/// The bcm2835_i2c_* functions allow you to control the BCM 2835 BSC interface, +/// allowing you to send and received data by I2C ("eye-squared cee"; generically referred to as "two-wire interface") . +/// For more information about I?C, see http://en.wikipedia.org/wiki/I%C2%B2C +/// +/// The Raspberry Pi V2 GPIO pins used for I2C are: +/// +/// - P1-03 (SDA) +/// - P1-05 (SLC) +/// +/// \par PWM +/// +/// The BCM2835 supports hardware PWM on a limited subset of GPIO pins. This bcm2835 library provides +/// functions for configuring and controlling PWM output on these pins. +/// +/// The BCM2835 contains 2 independent PWM channels (0 and 1), each of which be connnected to a limited subset of +/// GPIO pins. The following GPIO pins may be connected to the following PWM channels (from section 9.5): +/// \code +/// GPIO PIN RPi pin PWM Channel ALT FUN +/// 12 0 0 +/// 13 1 0 +/// 18 1-12 0 5 +/// 19 1 5 +/// 40 0 0 +/// 41 1 0 +/// 45 1 0 +/// 52 0 1 +/// 53 1 1 +/// \endcode +/// In order for a GPIO pin to emit output from its PWM channel, it must be set to the Alt Function given above. +/// Note carefully that current versions of the Raspberry Pi only expose one of these pins (GPIO 18 = RPi Pin 1-12) +/// on the IO headers, and therefore this is the only IO pin on the RPi that can be used for PWM. +/// Further it must be set to ALT FUN 5 to get PWM output. +/// +/// Both PWM channels are driven by the same PWM clock, whose clock dvider can be varied using +/// bcm2835_pwm_set_clock(). Each channel can be separately enabled with bcm2835_pwm_set_mode(). +/// The average output of the PWM channel is determined by the ratio of DATA/RANGE for that channel. +/// Use bcm2835_pwm_set_range() to set the range and bcm2835_pwm_set_data() to set the data in that ratio +/// +/// Each PWM channel can run in either Balanced or Mark-Space mode. In Balanced mode, the hardware +/// sends a combination of clock pulses that results in an overall DATA pulses per RANGE pulses. +/// In Mark-Space mode, the hardware sets the output HIGH for DATA clock pulses wide, followed by +/// LOW for RANGE-DATA clock pulses. +/// +/// The PWM clock can be set to control the PWM pulse widths. The PWM clock is derived from +/// a 19.2MHz clock. You can set any divider, but some common ones are provided by the BCM2835_PWM_CLOCK_DIVIDER_* +/// values of \ref bcm2835PWMClockDivider. +/// +/// For example, say you wanted to drive a DC motor with PWM at about 1kHz, +/// and control the speed in 1/1024 increments from +/// 0/1024 (stopped) through to 1024/1024 (full on). In that case you might set the +/// clock divider to be 16, and the RANGE to 1024. The pulse repetition frequency will be +/// 1.2MHz/1024 = 1171.875Hz. +/// +/// \par Real Time performance constraints +/// +/// The bcm2835 is a library for user programs (i.e. they run in 'userland'). +/// Such programs are not part of the kernel and are usually +/// subject to paging and swapping by the kernel while it does other things besides running your program. +/// This means that you should not expect to get real-time performance or +/// real-time timing constraints from such programs. In particular, there is no guarantee that the +/// bcm2835_delay() and bcm2835_delayMicroseconds() will return after exactly the time requested. +/// In fact, depending on other activity on the host, IO etc, you might get significantly longer delay times +/// than the one you asked for. So please dont expect to get exactly the time delay you request. +/// +/// Arjan reports that you can prevent swapping on Linux with the following code fragment: +/// +/// \code +/// struct sched_param sp; +/// memset(&sp, 0, sizeof(sp)); +/// sp.sched_priority = sched_get_priority_max(SCHED_FIFO); +/// sched_setscheduler(0, SCHED_FIFO, &sp); +/// mlockall(MCL_CURRENT | MCL_FUTURE); +/// \endcode +/// +/// \par Bindings to other languages +/// +/// mikem has made Perl bindings available at CPAN: +/// http://search.cpan.org/~mikem/Device-BCM2835-1.9/lib/Device/BCM2835.pm +/// Matthew Baker has kindly made Python bindings available at: +/// https://github.com/mubeta06/py-libbcm2835 +/// Gary Marks has created a Serial Peripheral Interface (SPI) command-line utility +/// for Raspberry Pi, based on the bcm2835 library. The +/// utility, spincl, is licensed under Open Source GNU GPLv3 by iP Solutions (http://ipsolutionscorp.com), as a +/// free download with source included: http://ipsolutionscorp.com/raspberry-pi-spi-utility/ +/// +/// \par Open Source Licensing GPL V2 +/// +/// This is the appropriate option if you want to share the source code of your +/// application with everyone you distribute it to, and you also want to give them +/// the right to share who uses it. If you wish to use this software under Open +/// Source Licensing, you must contribute all your source code to the open source +/// community in accordance with the GPL Version 2 when your application is +/// distributed. See http://www.gnu.org/copyleft/gpl.html and COPYING +/// +/// \par Acknowledgements +/// +/// Some of this code has been inspired by Dom and Gert. +/// The I2C code has been inspired by Alan Barr. +/// +/// \par Revision History +/// +/// \version 1.0 Initial release +/// \version 1.1 Minor bug fixes +/// \version 1.2 Added support for SPI +/// \version 1.3 Added bcm2835_spi_transfern() +/// \version 1.4 Fixed a problem that prevented SPI CE1 being used. Reported by David Robinson. +/// \version 1.5 Added bcm2835_close() to deinit the library. Suggested by C?sar Ortiz +/// \version 1.6 Document testing on 2012-07-15-wheezy-raspbian and Occidentalisv01 +/// Functions bcm2835_gpio_ren(), bcm2835_gpio_fen(), bcm2835_gpio_hen() +/// bcm2835_gpio_len(), bcm2835_gpio_aren() and bcm2835_gpio_afen() now +/// changes only the pin specified. Other pins that were already previously +/// enabled stay enabled. +/// Added bcm2835_gpio_clr_ren(), bcm2835_gpio_clr_fen(), bcm2835_gpio_clr_hen() +/// bcm2835_gpio_clr_len(), bcm2835_gpio_clr_aren(), bcm2835_gpio_clr_afen() +/// to clear the enable for individual pins, suggested by Andreas Sundstrom. +/// \version 1.7 Added bcm2835_spi_transfernb to support different buffers for read and write. +/// \version 1.8 Improvements to read barrier, as suggested by maddin. +/// \version 1.9 Improvements contributed by mikew: +/// I noticed that it was mallocing memory for the mmaps on /dev/mem. +/// It's not necessary to do that, you can just mmap the file directly, +/// so I've removed the mallocs (and frees). +/// I've also modified delayMicroseconds() to use nanosleep() for long waits, +/// and a busy wait on a high resolution timer for the rest. This is because +/// I've found that calling nanosleep() takes at least 100-200 us. +/// You need to link using '-lrt' using this version. +/// I've added some unsigned casts to the debug prints to silence compiler +/// warnings I was getting, fixed some typos, and changed the value of +/// BCM2835_PAD_HYSTERESIS_ENABLED to 0x08 as per Gert van Loo's doc at +/// http://www.scribd.com/doc/101830961/GPIO-Pads-Control2 +/// Also added a define for the passwrd value that Gert says is needed to +/// change pad control settings. +/// \version 1.10 Changed the names of the delay functions to bcm2835_delay() +/// and bcm2835_delayMicroseconds() to prevent collisions with wiringPi. +/// Macros to map delay()-> bcm2835_delay() and +/// Macros to map delayMicroseconds()-> bcm2835_delayMicroseconds(), which +/// can be disabled by defining BCM2835_NO_DELAY_COMPATIBILITY +/// \version 1.11 Fixed incorrect link to download file +/// \version 1.12 New GPIO pin definitions for RPi version 2 (which has a different GPIO mapping) +/// \version 1.13 New GPIO pin definitions for RPi version 2 plug P5 +/// Hardware base pointers are now available (after initialisation) externally as bcm2835_gpio +/// bcm2835_pwm bcm2835_clk bcm2835_pads bcm2835_spi0. +/// \version 1.14 Now compiles even if CLOCK_MONOTONIC_RAW is not available, uses CLOCK_MONOTONIC instead. +/// Fixed errors in documentation of SPI divider frequencies based on 250MHz clock. +/// Reported by Ben Simpson. +/// \version 1.15 Added bcm2835_close() to end of examples as suggested by Mark Wolfe. +/// \version 1.16 Added bcm2835_gpio_set_multi, bcm2835_gpio_clr_multi and bcm2835_gpio_write_multi +/// to allow a mask of pins to be set all at once. Requested by Sebastian Loncar. +/// \version 1.17 Added bcm2835_gpio_write_mask. Requested by Sebastian Loncar. +/// \version 1.18 Added bcm2835_i2c_* functions. Changes to bcm2835_delayMicroseconds: +/// now uses the RPi system timer counter, instead of clock_gettime, for improved accuracy. +/// No need to link with -lrt now. Contributed by Arjan van Vught. +/// \version 1.19 Removed inlines added by previous patch since they don't seem to work everywhere. +/// Reported by olly. +/// \version 1.20 Patch from Mark Dootson to close /dev/mem after access to the peripherals has been granted. +/// \version 1.21 delayMicroseconds is now not susceptible to 32 bit timer overruns. +/// Patch courtesy Jeremy Mortis. +/// \version 1.22 Fixed incorrect definition of BCM2835_GPFEN0 which broke the ability to set +/// falling edge events. Reported by Mark Dootson. +/// \version 1.23 Added bcm2835_i2c_set_baudrate and bcm2835_i2c_read_register_rs. +/// Improvements to bcm2835_i2c_read and bcm2835_i2c_write functions +/// to fix ocasional reads not completing. Patched by Mark Dootson. +/// \version 1.24 Mark Dootson p[atched a problem with his previously submitted code +/// under high load from other processes. +/// \version 1.25 Updated author and distribution location details to airspayce.com +/// \version 1.26 Added missing unmapmem for pads in bcm2835_close to prevent a memory leak. +/// Reported by Hartmut Henkel. +/// \version 1.27 bcm2835_gpio_set_pad() no longer needs BCM2835_PAD_PASSWRD: it is +/// now automatically included. +/// Added suport for PWM mode with bcm2835_pwm_* functions. +/// \version 1.28 Fixed a problem where bcm2835_spi_writenb() would have problems with transfers of more than +/// 64 bytes dues to read buffer filling. Patched by Peter Würtz. +/// \version 1.29 Further fix to SPI from Peter Würtz. +/// \version 1.30 10 microsecond delays from bcm2835_spi_transfer and bcm2835_spi_transfern for +/// significant performance improvements, Patch by Alan Watson. +/// \version 1.31 Fix a GCC warning about dummy variable, patched by Alan Watson. Thanks. +/// \version 1.32 Added option I2C_V1 definition to compile for version 1 RPi. +/// By default I2C code is generated for the V2 RPi which has SDA1 and SCL1 connected. +/// Contributed by Malcolm Wiles based on work by Arvi Govindaraj. +/// \version 1.33 Added command line utilities i2c and gpio to examples. Contributed by Shahrooz Shahparnia. +/// \version 1.34 Added bcm2835_i2c_write_read_rs() which writes an arbitrary number of bytes, +/// sends a repeat start, and reads from the device. Contributed by Eduardo Steinhorst. +/// \version 1.35 Fix build errors when compiled under Qt. Also performance improvements with SPI transfers. Contributed by Udo Klaas. +/// \version 1.36 Make automake's test runner detect that we're skipping tests when not root, the second +/// one makes us skip the test when using fakeroot (as used when building +/// Debian packages). Contributed by Guido Günther. +/// +/// \author Mike McCauley (mikem@airspayce.com) DO NOT CONTACT THE AUTHOR DIRECTLY: USE THE LISTS + + + +// Defines for BCM2835 +#ifndef BCM2835_H +#define BCM2835_H + +#include + +/// \defgroup constants Constants for passing to and from library functions +/// The values here are designed to be passed to various functions in the bcm2835 library. +/// @{ + + +/// This means pin HIGH, true, 3.3volts on a pin. +#define HIGH 0x1 +/// This means pin LOW, false, 0volts on a pin. +#define LOW 0x0 + +/// Speed of the core clock core_clk +#define BCM2835_CORE_CLK_HZ 250000000 ///< 250 MHz + +// Physical addresses for various peripheral register sets +/// Base Physical Address of the BCM 2835 peripheral registers +#define BCM2835_PERI_BASE 0x20000000 +/// Base Physical Address of the System Timer registers +#define BCM2835_ST_BASE (BCM2835_PERI_BASE + 0x3000) +/// Base Physical Address of the Pads registers +#define BCM2835_GPIO_PADS (BCM2835_PERI_BASE + 0x100000) +/// Base Physical Address of the Clock/timer registers +#define BCM2835_CLOCK_BASE (BCM2835_PERI_BASE + 0x101000) +/// Base Physical Address of the GPIO registers +#define BCM2835_GPIO_BASE (BCM2835_PERI_BASE + 0x200000) +/// Base Physical Address of the SPI0 registers +#define BCM2835_SPI0_BASE (BCM2835_PERI_BASE + 0x204000) +/// Base Physical Address of the BSC0 registers +#define BCM2835_BSC0_BASE (BCM2835_PERI_BASE + 0x205000) +/// Base Physical Address of the PWM registers +#define BCM2835_GPIO_PWM (BCM2835_PERI_BASE + 0x20C000) + /// Base Physical Address of the BSC1 registers +#define BCM2835_BSC1_BASE (BCM2835_PERI_BASE + 0x804000) + + +/// Base of the ST (System Timer) registers. +/// Available after bcm2835_init has been called +extern volatile uint32_t *bcm2835_st; + +/// Base of the GPIO registers. +/// Available after bcm2835_init has been called +extern volatile uint32_t *bcm2835_gpio; + +/// Base of the PWM registers. +/// Available after bcm2835_init has been called +extern volatile uint32_t *bcm2835_pwm; + +/// Base of the CLK registers. +/// Available after bcm2835_init has been called +extern volatile uint32_t *bcm2835_clk; + +/// Base of the PADS registers. +/// Available after bcm2835_init has been called +extern volatile uint32_t *bcm2835_pads; + +/// Base of the SPI0 registers. +/// Available after bcm2835_init has been called +extern volatile uint32_t *bcm2835_spi0; + +/// Base of the BSC0 registers. +/// Available after bcm2835_init has been called +extern volatile uint32_t *bcm2835_bsc0; + +/// Base of the BSC1 registers. +/// Available after bcm2835_init has been called +extern volatile uint32_t *bcm2835_bsc1; + +/// Size of memory page on RPi +#define BCM2835_PAGE_SIZE (4*1024) +/// Size of memory block on RPi +#define BCM2835_BLOCK_SIZE (4*1024) + + +// Defines for GPIO +// The BCM2835 has 54 GPIO pins. +// BCM2835 data sheet, Page 90 onwards. +/// GPIO register offsets from BCM2835_GPIO_BASE. Offsets into the GPIO Peripheral block in bytes per 6.1 Register View +#define BCM2835_GPFSEL0 0x0000 ///< GPIO Function Select 0 +#define BCM2835_GPFSEL1 0x0004 ///< GPIO Function Select 1 +#define BCM2835_GPFSEL2 0x0008 ///< GPIO Function Select 2 +#define BCM2835_GPFSEL3 0x000c ///< GPIO Function Select 3 +#define BCM2835_GPFSEL4 0x0010 ///< GPIO Function Select 4 +#define BCM2835_GPFSEL5 0x0014 ///< GPIO Function Select 5 +#define BCM2835_GPSET0 0x001c ///< GPIO Pin Output Set 0 +#define BCM2835_GPSET1 0x0020 ///< GPIO Pin Output Set 1 +#define BCM2835_GPCLR0 0x0028 ///< GPIO Pin Output Clear 0 +#define BCM2835_GPCLR1 0x002c ///< GPIO Pin Output Clear 1 +#define BCM2835_GPLEV0 0x0034 ///< GPIO Pin Level 0 +#define BCM2835_GPLEV1 0x0038 ///< GPIO Pin Level 1 +#define BCM2835_GPEDS0 0x0040 ///< GPIO Pin Event Detect Status 0 +#define BCM2835_GPEDS1 0x0044 ///< GPIO Pin Event Detect Status 1 +#define BCM2835_GPREN0 0x004c ///< GPIO Pin Rising Edge Detect Enable 0 +#define BCM2835_GPREN1 0x0050 ///< GPIO Pin Rising Edge Detect Enable 1 +#define BCM2835_GPFEN0 0x0058 ///< GPIO Pin Falling Edge Detect Enable 0 +#define BCM2835_GPFEN1 0x005c ///< GPIO Pin Falling Edge Detect Enable 1 +#define BCM2835_GPHEN0 0x0064 ///< GPIO Pin High Detect Enable 0 +#define BCM2835_GPHEN1 0x0068 ///< GPIO Pin High Detect Enable 1 +#define BCM2835_GPLEN0 0x0070 ///< GPIO Pin Low Detect Enable 0 +#define BCM2835_GPLEN1 0x0074 ///< GPIO Pin Low Detect Enable 1 +#define BCM2835_GPAREN0 0x007c ///< GPIO Pin Async. Rising Edge Detect 0 +#define BCM2835_GPAREN1 0x0080 ///< GPIO Pin Async. Rising Edge Detect 1 +#define BCM2835_GPAFEN0 0x0088 ///< GPIO Pin Async. Falling Edge Detect 0 +#define BCM2835_GPAFEN1 0x008c ///< GPIO Pin Async. Falling Edge Detect 1 +#define BCM2835_GPPUD 0x0094 ///< GPIO Pin Pull-up/down Enable +#define BCM2835_GPPUDCLK0 0x0098 ///< GPIO Pin Pull-up/down Enable Clock 0 +#define BCM2835_GPPUDCLK1 0x009c ///< GPIO Pin Pull-up/down Enable Clock 1 + +/// \brief bcm2835PortFunction +/// Port function select modes for bcm2835_gpio_fsel() +typedef enum +{ + BCM2835_GPIO_FSEL_INPT = 0b000, ///< Input + BCM2835_GPIO_FSEL_OUTP = 0b001, ///< Output + BCM2835_GPIO_FSEL_ALT0 = 0b100, ///< Alternate function 0 + BCM2835_GPIO_FSEL_ALT1 = 0b101, ///< Alternate function 1 + BCM2835_GPIO_FSEL_ALT2 = 0b110, ///< Alternate function 2 + BCM2835_GPIO_FSEL_ALT3 = 0b111, ///< Alternate function 3 + BCM2835_GPIO_FSEL_ALT4 = 0b011, ///< Alternate function 4 + BCM2835_GPIO_FSEL_ALT5 = 0b010, ///< Alternate function 5 + BCM2835_GPIO_FSEL_MASK = 0b111 ///< Function select bits mask +} bcm2835FunctionSelect; + +/// \brief bcm2835PUDControl +/// Pullup/Pulldown defines for bcm2835_gpio_pud() +typedef enum +{ + BCM2835_GPIO_PUD_OFF = 0b00, ///< Off ? disable pull-up/down + BCM2835_GPIO_PUD_DOWN = 0b01, ///< Enable Pull Down control + BCM2835_GPIO_PUD_UP = 0b10 ///< Enable Pull Up control +} bcm2835PUDControl; + +/// Pad control register offsets from BCM2835_GPIO_PADS +#define BCM2835_PADS_GPIO_0_27 0x002c ///< Pad control register for pads 0 to 27 +#define BCM2835_PADS_GPIO_28_45 0x0030 ///< Pad control register for pads 28 to 45 +#define BCM2835_PADS_GPIO_46_53 0x0034 ///< Pad control register for pads 46 to 53 + +/// Pad Control masks +#define BCM2835_PAD_PASSWRD (0x5A << 24) ///< Password to enable setting pad mask +#define BCM2835_PAD_SLEW_RATE_UNLIMITED 0x10 ///< Slew rate unlimited +#define BCM2835_PAD_HYSTERESIS_ENABLED 0x08 ///< Hysteresis enabled +#define BCM2835_PAD_DRIVE_2mA 0x00 ///< 2mA drive current +#define BCM2835_PAD_DRIVE_4mA 0x01 ///< 4mA drive current +#define BCM2835_PAD_DRIVE_6mA 0x02 ///< 6mA drive current +#define BCM2835_PAD_DRIVE_8mA 0x03 ///< 8mA drive current +#define BCM2835_PAD_DRIVE_10mA 0x04 ///< 10mA drive current +#define BCM2835_PAD_DRIVE_12mA 0x05 ///< 12mA drive current +#define BCM2835_PAD_DRIVE_14mA 0x06 ///< 14mA drive current +#define BCM2835_PAD_DRIVE_16mA 0x07 ///< 16mA drive current + +/// \brief bcm2835PadGroup +/// Pad group specification for bcm2835_gpio_pad() +typedef enum +{ + BCM2835_PAD_GROUP_GPIO_0_27 = 0, ///< Pad group for GPIO pads 0 to 27 + BCM2835_PAD_GROUP_GPIO_28_45 = 1, ///< Pad group for GPIO pads 28 to 45 + BCM2835_PAD_GROUP_GPIO_46_53 = 2 ///< Pad group for GPIO pads 46 to 53 +} bcm2835PadGroup; + +/// \brief GPIO Pin Numbers +/// +/// Here we define Raspberry Pin GPIO pins on P1 in terms of the underlying BCM GPIO pin numbers. +/// These can be passed as a pin number to any function requiring a pin. +/// Not all pins on the RPi 26 bin IDE plug are connected to GPIO pins +/// and some can adopt an alternate function. +/// RPi version 2 has some slightly different pinouts, and these are values RPI_V2_*. +/// At bootup, pins 8 and 10 are set to UART0_TXD, UART0_RXD (ie the alt0 function) respectively +/// When SPI0 is in use (ie after bcm2835_spi_begin()), pins 19, 21, 23, 24, 26 are dedicated to SPI +/// and cant be controlled independently +typedef enum +{ + RPI_GPIO_P1_03 = 0, ///< Version 1, Pin P1-03 + RPI_GPIO_P1_05 = 1, ///< Version 1, Pin P1-05 + RPI_GPIO_P1_07 = 4, ///< Version 1, Pin P1-07 + RPI_GPIO_P1_08 = 14, ///< Version 1, Pin P1-08, defaults to alt function 0 UART0_TXD + RPI_GPIO_P1_10 = 15, ///< Version 1, Pin P1-10, defaults to alt function 0 UART0_RXD + RPI_GPIO_P1_11 = 17, ///< Version 1, Pin P1-11 + RPI_GPIO_P1_12 = 18, ///< Version 1, Pin P1-12, can be PWM channel 0 in ALT FUN 5 + RPI_GPIO_P1_13 = 21, ///< Version 1, Pin P1-13 + RPI_GPIO_P1_15 = 22, ///< Version 1, Pin P1-15 + RPI_GPIO_P1_16 = 23, ///< Version 1, Pin P1-16 + RPI_GPIO_P1_18 = 24, ///< Version 1, Pin P1-18 + RPI_GPIO_P1_19 = 10, ///< Version 1, Pin P1-19, MOSI when SPI0 in use + RPI_GPIO_P1_21 = 9, ///< Version 1, Pin P1-21, MISO when SPI0 in use + RPI_GPIO_P1_22 = 25, ///< Version 1, Pin P1-22 + RPI_GPIO_P1_23 = 11, ///< Version 1, Pin P1-23, CLK when SPI0 in use + RPI_GPIO_P1_24 = 8, ///< Version 1, Pin P1-24, CE0 when SPI0 in use + RPI_GPIO_P1_26 = 7, ///< Version 1, Pin P1-26, CE1 when SPI0 in use + + // RPi Version 2 + RPI_V2_GPIO_P1_03 = 2, ///< Version 2, Pin P1-03 + RPI_V2_GPIO_P1_05 = 3, ///< Version 2, Pin P1-05 + RPI_V2_GPIO_P1_07 = 4, ///< Version 2, Pin P1-07 + RPI_V2_GPIO_P1_08 = 14, ///< Version 2, Pin P1-08, defaults to alt function 0 UART0_TXD + RPI_V2_GPIO_P1_10 = 15, ///< Version 2, Pin P1-10, defaults to alt function 0 UART0_RXD + RPI_V2_GPIO_P1_11 = 17, ///< Version 2, Pin P1-11 + RPI_V2_GPIO_P1_12 = 18, ///< Version 2, Pin P1-12, can be PWM channel 0 in ALT FUN 5 + RPI_V2_GPIO_P1_13 = 27, ///< Version 2, Pin P1-13 + RPI_V2_GPIO_P1_15 = 22, ///< Version 2, Pin P1-15 + RPI_V2_GPIO_P1_16 = 23, ///< Version 2, Pin P1-16 + RPI_V2_GPIO_P1_18 = 24, ///< Version 2, Pin P1-18 + RPI_V2_GPIO_P1_19 = 10, ///< Version 2, Pin P1-19, MOSI when SPI0 in use + RPI_V2_GPIO_P1_21 = 9, ///< Version 2, Pin P1-21, MISO when SPI0 in use + RPI_V2_GPIO_P1_22 = 25, ///< Version 2, Pin P1-22 + RPI_V2_GPIO_P1_23 = 11, ///< Version 2, Pin P1-23, CLK when SPI0 in use + RPI_V2_GPIO_P1_24 = 8, ///< Version 2, Pin P1-24, CE0 when SPI0 in use + RPI_V2_GPIO_P1_26 = 7, ///< Version 2, Pin P1-26, CE1 when SPI0 in use + + // RPi Version 2, new plug P5 + RPI_V2_GPIO_P5_03 = 28, ///< Version 2, Pin P5-03 + RPI_V2_GPIO_P5_04 = 29, ///< Version 2, Pin P5-04 + RPI_V2_GPIO_P5_05 = 30, ///< Version 2, Pin P5-05 + RPI_V2_GPIO_P5_06 = 31, ///< Version 2, Pin P5-06 + +} RPiGPIOPin; + +// Defines for SPI +// GPIO register offsets from BCM2835_SPI0_BASE. +// Offsets into the SPI Peripheral block in bytes per 10.5 SPI Register Map +#define BCM2835_SPI0_CS 0x0000 ///< SPI Master Control and Status +#define BCM2835_SPI0_FIFO 0x0004 ///< SPI Master TX and RX FIFOs +#define BCM2835_SPI0_CLK 0x0008 ///< SPI Master Clock Divider +#define BCM2835_SPI0_DLEN 0x000c ///< SPI Master Data Length +#define BCM2835_SPI0_LTOH 0x0010 ///< SPI LOSSI mode TOH +#define BCM2835_SPI0_DC 0x0014 ///< SPI DMA DREQ Controls + +// Register masks for SPI0_CS +#define BCM2835_SPI0_CS_LEN_LONG 0x02000000 ///< Enable Long data word in Lossi mode if DMA_LEN is set +#define BCM2835_SPI0_CS_DMA_LEN 0x01000000 ///< Enable DMA mode in Lossi mode +#define BCM2835_SPI0_CS_CSPOL2 0x00800000 ///< Chip Select 2 Polarity +#define BCM2835_SPI0_CS_CSPOL1 0x00400000 ///< Chip Select 1 Polarity +#define BCM2835_SPI0_CS_CSPOL0 0x00200000 ///< Chip Select 0 Polarity +#define BCM2835_SPI0_CS_RXF 0x00100000 ///< RXF - RX FIFO Full +#define BCM2835_SPI0_CS_RXR 0x00080000 ///< RXR RX FIFO needs Reading ( full) +#define BCM2835_SPI0_CS_TXD 0x00040000 ///< TXD TX FIFO can accept Data +#define BCM2835_SPI0_CS_RXD 0x00020000 ///< RXD RX FIFO contains Data +#define BCM2835_SPI0_CS_DONE 0x00010000 ///< Done transfer Done +#define BCM2835_SPI0_CS_TE_EN 0x00008000 ///< Unused +#define BCM2835_SPI0_CS_LMONO 0x00004000 ///< Unused +#define BCM2835_SPI0_CS_LEN 0x00002000 ///< LEN LoSSI enable +#define BCM2835_SPI0_CS_REN 0x00001000 ///< REN Read Enable +#define BCM2835_SPI0_CS_ADCS 0x00000800 ///< ADCS Automatically Deassert Chip Select +#define BCM2835_SPI0_CS_INTR 0x00000400 ///< INTR Interrupt on RXR +#define BCM2835_SPI0_CS_INTD 0x00000200 ///< INTD Interrupt on Done +#define BCM2835_SPI0_CS_DMAEN 0x00000100 ///< DMAEN DMA Enable +#define BCM2835_SPI0_CS_TA 0x00000080 ///< Transfer Active +#define BCM2835_SPI0_CS_CSPOL 0x00000040 ///< Chip Select Polarity +#define BCM2835_SPI0_CS_CLEAR 0x00000030 ///< Clear FIFO Clear RX and TX +#define BCM2835_SPI0_CS_CLEAR_RX 0x00000020 ///< Clear FIFO Clear RX +#define BCM2835_SPI0_CS_CLEAR_TX 0x00000010 ///< Clear FIFO Clear TX +#define BCM2835_SPI0_CS_CPOL 0x00000008 ///< Clock Polarity +#define BCM2835_SPI0_CS_CPHA 0x00000004 ///< Clock Phase +#define BCM2835_SPI0_CS_CS 0x00000003 ///< Chip Select + +/// \brief bcm2835SPIBitOrder SPI Bit order +/// Specifies the SPI data bit ordering for bcm2835_spi_setBitOrder() +typedef enum +{ + BCM2835_SPI_BIT_ORDER_LSBFIRST = 0, ///< LSB First + BCM2835_SPI_BIT_ORDER_MSBFIRST = 1 ///< MSB First +}bcm2835SPIBitOrder; + +/// \brief SPI Data mode +/// Specify the SPI data mode to be passed to bcm2835_spi_setDataMode() +typedef enum +{ + BCM2835_SPI_MODE0 = 0, ///< CPOL = 0, CPHA = 0 + BCM2835_SPI_MODE1 = 1, ///< CPOL = 0, CPHA = 1 + BCM2835_SPI_MODE2 = 2, ///< CPOL = 1, CPHA = 0 + BCM2835_SPI_MODE3 = 3, ///< CPOL = 1, CPHA = 1 +}bcm2835SPIMode; + +/// \brief bcm2835SPIChipSelect +/// Specify the SPI chip select pin(s) +typedef enum +{ + // Can also use non-standard pins with this lib + BCM2835_SPI_CS0 = 0, ///< Chip Select 0 + BCM2835_SPI_CS1 = 1, ///< Chip Select 1 + BCM2835_SPI_CS2 = 2, ///< Chip Select 2 (ie pins CS1 and CS2 are asserted) + BCM2835_SPI_CS_NONE = 3, ///< No CS, control it yourself + + // Only GPIO > 3 can be used (to not interfere with the previous value just above ) + // Lucky we have plenty of theese pins + BCM2835_SPI_CS_GPIO4 = RPI_V2_GPIO_P1_07, /// BCM GPIO 4 + BCM2835_SPI_CS_GPIO17 = RPI_V2_GPIO_P1_11, /// BCM GPIO 17 + BCM2835_SPI_CS_GPIO18 = RPI_V2_GPIO_P1_12, /// BCM GPIO 18 + BCM2835_SPI_CS_GPIO22 = RPI_V2_GPIO_P1_15, /// BCM GPIO 22 + BCM2835_SPI_CS_GPIO23 = RPI_V2_GPIO_P1_16, /// BCM GPIO 23 + BCM2835_SPI_CS_GPIO24 = RPI_V2_GPIO_P1_18, /// BCM GPIO 24 + BCM2835_SPI_CS_GPIO25 = RPI_V2_GPIO_P1_22, /// BCM GPIO 25 + BCM2835_SPI_CS_GPIO28 = RPI_V2_GPIO_P5_03, /// BCM GPIO 28 + BCM2835_SPI_CS_GPIO29 = RPI_V2_GPIO_P5_04, /// BCM GPIO 29 + BCM2835_SPI_CS_GPIO30 = RPI_V2_GPIO_P5_05, /// BCM GPIO 30 + BCM2835_SPI_CS_GPIO31 = RPI_V2_GPIO_P5_06, /// BCM GPIO 31 + +} bcm2835SPIChipSelect; + +/// \brief bcm2835SPIClockDivider +/// Specifies the divider used to generate the SPI clock from the system clock. +/// Figures below give the divider, clock period and clock frequency. +/// Clock divided is based on nominal base clock rate of 250MHz +/// It is reported that (contrary to the documentation) any even divider may used. +/// The frequencies shown for each divider have been confirmed by measurement +typedef enum +{ + BCM2835_SPI_CLOCK_DIVIDER_65536 = 0, ///< 65536 = 262.144us = 3.814697260kHz + BCM2835_SPI_CLOCK_DIVIDER_32768 = 32768, ///< 32768 = 131.072us = 7.629394531kHz + BCM2835_SPI_CLOCK_DIVIDER_16384 = 16384, ///< 16384 = 65.536us = 15.25878906kHz + BCM2835_SPI_CLOCK_DIVIDER_8192 = 8192, ///< 8192 = 32.768us = 30/51757813kHz + BCM2835_SPI_CLOCK_DIVIDER_4096 = 4096, ///< 4096 = 16.384us = 61.03515625kHz + BCM2835_SPI_CLOCK_DIVIDER_2048 = 2048, ///< 2048 = 8.192us = 122.0703125kHz + BCM2835_SPI_CLOCK_DIVIDER_1024 = 1024, ///< 1024 = 4.096us = 244.140625kHz + BCM2835_SPI_CLOCK_DIVIDER_512 = 512, ///< 512 = 2.048us = 488.28125kHz + BCM2835_SPI_CLOCK_DIVIDER_256 = 256, ///< 256 = 1.024us = 976.5625MHz + BCM2835_SPI_CLOCK_DIVIDER_128 = 128, ///< 128 = 512ns = = 1.953125MHz + BCM2835_SPI_CLOCK_DIVIDER_64 = 64, ///< 64 = 256ns = 3.90625MHz + BCM2835_SPI_CLOCK_DIVIDER_32 = 32, ///< 32 = 128ns = 7.8125MHz + BCM2835_SPI_CLOCK_DIVIDER_16 = 16, ///< 16 = 64ns = 15.625MHz + BCM2835_SPI_CLOCK_DIVIDER_8 = 8, ///< 8 = 32ns = 31.25MHz + BCM2835_SPI_CLOCK_DIVIDER_4 = 4, ///< 4 = 16ns = 62.5MHz + BCM2835_SPI_CLOCK_DIVIDER_2 = 2, ///< 2 = 8ns = 125MHz, fastest you can get + BCM2835_SPI_CLOCK_DIVIDER_1 = 1, ///< 1 = 262.144us = 3.814697260kHz, same as 0/65536 +} bcm2835SPIClockDivider; + +/// \brief bcm2835SPISpeed +/// Specifies the divider used to generate the SPI clock from the system clock. +/// Figures below give the clock speed instead of clock divider. +#define BCM2835_SPI_SPEED_64MHZ BCM2835_SPI_CLOCK_DIVIDER_4 +#define BCM2835_SPI_SPEED_32MHZ BCM2835_SPI_CLOCK_DIVIDER_8 +#define BCM2835_SPI_SPEED_16MHZ BCM2835_SPI_CLOCK_DIVIDER_16 +#define BCM2835_SPI_SPEED_8MHZ BCM2835_SPI_CLOCK_DIVIDER_32 +#define BCM2835_SPI_SPEED_4MHZ BCM2835_SPI_CLOCK_DIVIDER_64 +#define BCM2835_SPI_SPEED_2MHZ BCM2835_SPI_CLOCK_DIVIDER_128 +#define BCM2835_SPI_SPEED_1MHZ BCM2835_SPI_CLOCK_DIVIDER_256 +#define BCM2835_SPI_SPEED_512KHZ BCM2835_SPI_CLOCK_DIVIDER_512 +#define BCM2835_SPI_SPEED_256KHZ BCM2835_SPI_CLOCK_DIVIDER_1024 +#define BCM2835_SPI_SPEED_128KHZ BCM2835_SPI_CLOCK_DIVIDER_2048 +#define BCM2835_SPI_SPEED_64KHZ BCM2835_SPI_CLOCK_DIVIDER_4096 +#define BCM2835_SPI_SPEED_32KHZ BCM2835_SPI_CLOCK_DIVIDER_8192 +#define BCM2835_SPI_SPEED_16KHZ BCM2835_SPI_CLOCK_DIVIDER_16384 +#define BCM2835_SPI_SPEED_8KHZ BCM2835_SPI_CLOCK_DIVIDER_32768 + +// Defines for I2C +// GPIO register offsets from BCM2835_BSC*_BASE. +// Offsets into the BSC Peripheral block in bytes per 3.1 BSC Register Map +#define BCM2835_BSC_C 0x0000 ///< BSC Master Control +#define BCM2835_BSC_S 0x0004 ///< BSC Master Status +#define BCM2835_BSC_DLEN 0x0008 ///< BSC Master Data Length +#define BCM2835_BSC_A 0x000c ///< BSC Master Slave Address +#define BCM2835_BSC_FIFO 0x0010 ///< BSC Master Data FIFO +#define BCM2835_BSC_DIV 0x0014 ///< BSC Master Clock Divider +#define BCM2835_BSC_DEL 0x0018 ///< BSC Master Data Delay +#define BCM2835_BSC_CLKT 0x001c ///< BSC Master Clock Stretch Timeout + +// Register masks for BSC_C +#define BCM2835_BSC_C_I2CEN 0x00008000 ///< I2C Enable, 0 = disabled, 1 = enabled +#define BCM2835_BSC_C_INTR 0x00000400 ///< Interrupt on RX +#define BCM2835_BSC_C_INTT 0x00000200 ///< Interrupt on TX +#define BCM2835_BSC_C_INTD 0x00000100 ///< Interrupt on DONE +#define BCM2835_BSC_C_ST 0x00000080 ///< Start transfer, 1 = Start a new transfer +#define BCM2835_BSC_C_CLEAR_1 0x00000020 ///< Clear FIFO Clear +#define BCM2835_BSC_C_CLEAR_2 0x00000010 ///< Clear FIFO Clear +#define BCM2835_BSC_C_READ 0x00000001 ///< Read transfer + +// Register masks for BSC_S +#define BCM2835_BSC_S_CLKT 0x00000200 ///< Clock stretch timeout +#define BCM2835_BSC_S_ERR 0x00000100 ///< ACK error +#define BCM2835_BSC_S_RXF 0x00000080 ///< RXF FIFO full, 0 = FIFO is not full, 1 = FIFO is full +#define BCM2835_BSC_S_TXE 0x00000040 ///< TXE FIFO full, 0 = FIFO is not full, 1 = FIFO is full +#define BCM2835_BSC_S_RXD 0x00000020 ///< RXD FIFO contains data +#define BCM2835_BSC_S_TXD 0x00000010 ///< TXD FIFO can accept data +#define BCM2835_BSC_S_RXR 0x00000008 ///< RXR FIFO needs reading (full) +#define BCM2835_BSC_S_TXW 0x00000004 ///< TXW FIFO needs writing (full) +#define BCM2835_BSC_S_DONE 0x00000002 ///< Transfer DONE +#define BCM2835_BSC_S_TA 0x00000001 ///< Transfer Active + +#define BCM2835_BSC_FIFO_SIZE 16 ///< BSC FIFO size + +/// \brief bcm2835I2CClockDivider +/// Specifies the divider used to generate the I2C clock from the system clock. +/// Clock divided is based on nominal base clock rate of 250MHz +typedef enum +{ + BCM2835_I2C_CLOCK_DIVIDER_2500 = 2500, ///< 2500 = 10us = 100 kHz + BCM2835_I2C_CLOCK_DIVIDER_626 = 626, ///< 622 = 2.504us = 399.3610 kHz + BCM2835_I2C_CLOCK_DIVIDER_150 = 150, ///< 150 = 60ns = 1.666 MHz (default at reset) + BCM2835_I2C_CLOCK_DIVIDER_148 = 148, ///< 148 = 59ns = 1.689 MHz +} bcm2835I2CClockDivider; + +/// \brief bcm2835I2CReasonCodes +/// Specifies the reason codes for the bcm2835_i2c_write and bcm2835_i2c_read functions. +typedef enum +{ + BCM2835_I2C_REASON_OK = 0x00, ///< Success + BCM2835_I2C_REASON_ERROR_NACK = 0x01, ///< Received a NACK + BCM2835_I2C_REASON_ERROR_CLKT = 0x02, ///< Received Clock Stretch Timeout + BCM2835_I2C_REASON_ERROR_DATA = 0x04, ///< Not all data is sent / received +} bcm2835I2CReasonCodes; + +// Defines for ST +// GPIO register offsets from BCM2835_ST_BASE. +// Offsets into the ST Peripheral block in bytes per 12.1 System Timer Registers +// The System Timer peripheral provides four 32-bit timer channels and a single 64-bit free running counter. +// BCM2835_ST_CLO is the System Timer Counter Lower bits register. +// The system timer free-running counter lower register is a read-only register that returns the current value +// of the lower 32-bits of the free running counter. +// BCM2835_ST_CHI is the System Timer Counter Upper bits register. +// The system timer free-running counter upper register is a read-only register that returns the current value +// of the upper 32-bits of the free running counter. +#define BCM2835_ST_CS 0x0000 ///< System Timer Control/Status +#define BCM2835_ST_CLO 0x0004 ///< System Timer Counter Lower 32 bits +#define BCM2835_ST_CHI 0x0008 ///< System Timer Counter Upper 32 bits + +/// @} + + +// Defines for PWM, word offsets (ie 4 byte multiples) +#define BCM2835_PWM_CONTROL 0 +#define BCM2835_PWM_STATUS 1 +#define BCM2835_PWM_DMAC 2 +#define BCM2835_PWM0_RANGE 4 +#define BCM2835_PWM0_DATA 5 +#define BCM2835_PWM_FIF1 6 +#define BCM2835_PWM1_RANGE 8 +#define BCM2835_PWM1_DATA 9 + +// Defines for PWM Clock, word offsets (ie 4 byte multiples) +#define BCM2835_PWMCLK_CNTL 40 +#define BCM2835_PWMCLK_DIV 41 +#define BCM2835_PWM_PASSWRD (0x5A << 24) ///< Password to enable setting PWM clock + +#define BCM2835_PWM1_MS_MODE 0x8000 ///< Run in Mark/Space mode +#define BCM2835_PWM1_USEFIFO 0x2000 ///< Data from FIFO +#define BCM2835_PWM1_REVPOLAR 0x1000 ///< Reverse polarity +#define BCM2835_PWM1_OFFSTATE 0x0800 ///< Ouput Off state +#define BCM2835_PWM1_REPEATFF 0x0400 ///< Repeat last value if FIFO empty +#define BCM2835_PWM1_SERIAL 0x0200 ///< Run in serial mode +#define BCM2835_PWM1_ENABLE 0x0100 ///< Channel Enable + +#define BCM2835_PWM0_MS_MODE 0x0080 ///< Run in Mark/Space mode +#define BCM2835_PWM_CLEAR_FIFO 0x0040 ///< Clear FIFO +#define BCM2835_PWM0_USEFIFO 0x0020 ///< Data from FIFO +#define BCM2835_PWM0_REVPOLAR 0x0010 ///< Reverse polarity +#define BCM2835_PWM0_OFFSTATE 0x0008 ///< Ouput Off state +#define BCM2835_PWM0_REPEATFF 0x0004 ///< Repeat last value if FIFO empty +#define BCM2835_PWM0_SERIAL 0x0002 ///< Run in serial mode +#define BCM2835_PWM0_ENABLE 0x0001 ///< Channel Enable + + +/// \brief bcm2835PWMClockDivider +/// Specifies the divider used to generate the PWM clock from the system clock. +/// Figures below give the divider, clock period and clock frequency. +/// Clock divided is based on nominal PWM base clock rate of 19.2MHz +/// The frequencies shown for each divider have been confirmed by measurement +typedef enum +{ + BCM2835_PWM_CLOCK_DIVIDER_32768 = 32768, ///< 32768 = 585Hz + BCM2835_PWM_CLOCK_DIVIDER_16384 = 16384, ///< 16384 = 1171.8Hz + BCM2835_PWM_CLOCK_DIVIDER_8192 = 8192, ///< 8192 = 2.34375kHz + BCM2835_PWM_CLOCK_DIVIDER_4096 = 4096, ///< 4096 = 4.6875kHz + BCM2835_PWM_CLOCK_DIVIDER_2048 = 2048, ///< 2048 = 9.375kHz + BCM2835_PWM_CLOCK_DIVIDER_1024 = 1024, ///< 1024 = 18.75kHz + BCM2835_PWM_CLOCK_DIVIDER_512 = 512, ///< 512 = 37.5kHz + BCM2835_PWM_CLOCK_DIVIDER_256 = 256, ///< 256 = 75kHz + BCM2835_PWM_CLOCK_DIVIDER_128 = 128, ///< 128 = 150kHz + BCM2835_PWM_CLOCK_DIVIDER_64 = 64, ///< 64 = 300kHz + BCM2835_PWM_CLOCK_DIVIDER_32 = 32, ///< 32 = 600.0kHz + BCM2835_PWM_CLOCK_DIVIDER_16 = 16, ///< 16 = 1.2MHz + BCM2835_PWM_CLOCK_DIVIDER_8 = 8, ///< 8 = 2.4MHz + BCM2835_PWM_CLOCK_DIVIDER_4 = 4, ///< 4 = 4.8MHz + BCM2835_PWM_CLOCK_DIVIDER_2 = 2, ///< 2 = 9.6MHz, fastest you can get + BCM2835_PWM_CLOCK_DIVIDER_1 = 1, ///< 1 = 4.6875kHz, same as divider 4096 +} bcm2835PWMClockDivider; + +// Historical name compatibility +#ifndef BCM2835_NO_DELAY_COMPATIBILITY +#define delay(x) bcm2835_delay(x) +#define delayMicroseconds(x) bcm2835_delayMicroseconds(x) +#define millis() bcm2835_millis() +#endif + +#ifdef __cplusplus +extern "C" { +#endif + + /// \defgroup init Library initialisation and management + /// These functions allow you to intialise and control the bcm2835 library + /// @{ + + /// Initialise the library by opening /dev/mem and getting pointers to the + /// internal memory for BCM 2835 device registers. You must call this (successfully) + /// before calling any other + /// functions in this library (except bcm2835_set_debug). + /// If bcm2835_init() fails by returning 0, + /// calling any other function may result in crashes or other failures. + /// Prints messages to stderr in case of errors. + /// \return 1 if successful else 0 + extern int bcm2835_init(void); + + /// Close the library, deallocating any allocated memory and closing /dev/mem + /// \return 1 if successful else 0 + extern int bcm2835_close(void); + + /// Sets the debug level of the library. + /// A value of 1 prevents mapping to /dev/mem, and makes the library print out + /// what it would do, rather than accessing the GPIO registers. + /// A value of 0, the default, causes normal operation. + /// Call this before calling bcm2835_init(); + /// \param[in] debug The new debug level. 1 means debug + extern void bcm2835_set_debug(uint8_t debug); + + /// @} // end of init + + /// \defgroup lowlevel Low level register access + /// These functions provide low level register access, and should not generally + /// need to be used + /// + /// @{ + + /// Reads 32 bit value from a peripheral address + /// The read is done twice, and is therefore always safe in terms of + /// manual section 1.3 Peripheral access precautions for correct memory ordering + /// \param[in] paddr Physical address to read from. See BCM2835_GPIO_BASE etc. + /// \return the value read from the 32 bit register + /// \sa Physical Addresses + extern uint32_t bcm2835_peri_read(volatile uint32_t* paddr); + + + /// Reads 32 bit value from a peripheral address without the read barrier + /// You should only use this when your code has previously called bcm2835_peri_read() + /// within the same peripheral, and no other peripheral access has occurred since. + /// \param[in] paddr Physical address to read from. See BCM2835_GPIO_BASE etc. + /// \return the value read from the 32 bit register + /// \sa Physical Addresses + extern uint32_t bcm2835_peri_read_nb(volatile uint32_t* paddr); + + + /// Writes 32 bit value from a peripheral address + /// The write is done twice, and is therefore always safe in terms of + /// manual section 1.3 Peripheral access precautions for correct memory ordering + /// \param[in] paddr Physical address to read from. See BCM2835_GPIO_BASE etc. + /// \param[in] value The 32 bit value to write + /// \sa Physical Addresses + extern void bcm2835_peri_write(volatile uint32_t* paddr, uint32_t value); + + /// Writes 32 bit value from a peripheral address without the write barrier + /// You should only use this when your code has previously called bcm2835_peri_write() + /// within the same peripheral, and no other peripheral access has occurred since. + /// \param[in] paddr Physical address to read from. See BCM2835_GPIO_BASE etc. + /// \param[in] value The 32 bit value to write + /// \sa Physical Addresses + extern void bcm2835_peri_write_nb(volatile uint32_t* paddr, uint32_t value); + + /// Alters a number of bits in a 32 peripheral regsiter. + /// It reads the current valu and then alters the bits deines as 1 in mask, + /// according to the bit value in value. + /// All other bits that are 0 in the mask are unaffected. + /// Use this to alter a subset of the bits in a register. + /// The write is done twice, and is therefore always safe in terms of + /// manual section 1.3 Peripheral access precautions for correct memory ordering + /// \param[in] paddr Physical address to read from. See BCM2835_GPIO_BASE etc. + /// \param[in] value The 32 bit value to write, masked in by mask. + /// \param[in] mask Bitmask that defines the bits that will be altered in the register. + /// \sa Physical Addresses + extern void bcm2835_peri_set_bits(volatile uint32_t* paddr, uint32_t value, uint32_t mask); + /// @} // end of lowlevel + + /// \defgroup gpio GPIO register access + /// These functions allow you to control the GPIO interface. You can set the + /// function of each GPIO pin, read the input state and set the output state. + /// @{ + + /// Sets the Function Select register for the given pin, which configures + /// the pin as Input, Output or one of the 6 alternate functions. + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + /// \param[in] mode Mode to set the pin to, one of BCM2835_GPIO_FSEL_* from \ref bcm2835FunctionSelect + extern void bcm2835_gpio_fsel(uint8_t pin, uint8_t mode); + + /// Sets the specified pin output to + /// HIGH. + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + /// \sa bcm2835_gpio_write() + extern void bcm2835_gpio_set(uint8_t pin); + + /// Sets the specified pin output to + /// LOW. + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + /// \sa bcm2835_gpio_write() + extern void bcm2835_gpio_clr(uint8_t pin); + + /// Sets any of the first 32 GPIO output pins specified in the mask to + /// HIGH. + /// \param[in] mask Mask of pins to affect. Use eg: (1 << RPI_GPIO_P1_03) | (1 << RPI_GPIO_P1_05) + /// \sa bcm2835_gpio_write_multi() + extern void bcm2835_gpio_set_multi(uint32_t mask); + + /// Sets any of the first 32 GPIO output pins specified in the mask to + /// LOW. + /// \param[in] mask Mask of pins to affect. Use eg: (1 << RPI_GPIO_P1_03) | (1 << RPI_GPIO_P1_05) + /// \sa bcm2835_gpio_write_multi() + extern void bcm2835_gpio_clr_multi(uint32_t mask); + + /// Reads the current level on the specified + /// pin and returns either HIGH or LOW. Works whether or not the pin + /// is an input or an output. + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + /// \return the current level either HIGH or LOW + extern uint8_t bcm2835_gpio_lev(uint8_t pin); + + /// Event Detect Status. + /// Tests whether the specified pin has detected a level or edge + /// as requested by bcm2835_gpio_ren(), bcm2835_gpio_fen(), bcm2835_gpio_hen(), + /// bcm2835_gpio_len(), bcm2835_gpio_aren(), bcm2835_gpio_afen(). + /// Clear the flag for a given pin by calling bcm2835_gpio_set_eds(pin); + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + /// \return HIGH if the event detect status for the given pin is true. + extern uint8_t bcm2835_gpio_eds(uint8_t pin); + + /// Sets the Event Detect Status register for a given pin to 1, + /// which has the effect of clearing the flag. Use this afer seeing + /// an Event Detect Status on the pin. + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + extern void bcm2835_gpio_set_eds(uint8_t pin); + + /// Enable Rising Edge Detect Enable for the specified pin. + /// When a rising edge is detected, sets the appropriate pin in Event Detect Status. + /// The GPRENn registers use + /// synchronous edge detection. This means the input signal is sampled using the + /// system clock and then it is looking for a ?011? pattern on the sampled signal. This + /// has the effect of suppressing glitches. + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + extern void bcm2835_gpio_ren(uint8_t pin); + + /// Disable Rising Edge Detect Enable for the specified pin. + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + extern void bcm2835_gpio_clr_ren(uint8_t pin); + + /// Enable Falling Edge Detect Enable for the specified pin. + /// When a falling edge is detected, sets the appropriate pin in Event Detect Status. + /// The GPRENn registers use + /// synchronous edge detection. This means the input signal is sampled using the + /// system clock and then it is looking for a ?100? pattern on the sampled signal. This + /// has the effect of suppressing glitches. + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + extern void bcm2835_gpio_fen(uint8_t pin); + + /// Disable Falling Edge Detect Enable for the specified pin. + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + extern void bcm2835_gpio_clr_fen(uint8_t pin); + + /// Enable High Detect Enable for the specified pin. + /// When a HIGH level is detected on the pin, sets the appropriate pin in Event Detect Status. + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + extern void bcm2835_gpio_hen(uint8_t pin); + + /// Disable High Detect Enable for the specified pin. + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + extern void bcm2835_gpio_clr_hen(uint8_t pin); + + /// Enable Low Detect Enable for the specified pin. + /// When a LOW level is detected on the pin, sets the appropriate pin in Event Detect Status. + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + extern void bcm2835_gpio_len(uint8_t pin); + + /// Disable Low Detect Enable for the specified pin. + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + extern void bcm2835_gpio_clr_len(uint8_t pin); + + /// Enable Asynchronous Rising Edge Detect Enable for the specified pin. + /// When a rising edge is detected, sets the appropriate pin in Event Detect Status. + /// Asynchronous means the incoming signal is not sampled by the system clock. As such + /// rising edges of very short duration can be detected. + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + extern void bcm2835_gpio_aren(uint8_t pin); + + /// Disable Asynchronous Rising Edge Detect Enable for the specified pin. + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + extern void bcm2835_gpio_clr_aren(uint8_t pin); + + /// Enable Asynchronous Falling Edge Detect Enable for the specified pin. + /// When a falling edge is detected, sets the appropriate pin in Event Detect Status. + /// Asynchronous means the incoming signal is not sampled by the system clock. As such + /// falling edges of very short duration can be detected. + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + extern void bcm2835_gpio_afen(uint8_t pin); + + /// Disable Asynchronous Falling Edge Detect Enable for the specified pin. + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + extern void bcm2835_gpio_clr_afen(uint8_t pin); + + /// Sets the Pull-up/down register for the given pin. This is + /// used with bcm2835_gpio_pudclk() to set the Pull-up/down resistor for the given pin. + /// However, it is usually more convenient to use bcm2835_gpio_set_pud(). + /// \param[in] pud The desired Pull-up/down mode. One of BCM2835_GPIO_PUD_* from bcm2835PUDControl + /// \sa bcm2835_gpio_set_pud() + extern void bcm2835_gpio_pud(uint8_t pud); + + /// Clocks the Pull-up/down value set earlier by bcm2835_gpio_pud() into the pin. + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + /// \param[in] on HIGH to clock the value from bcm2835_gpio_pud() into the pin. + /// LOW to remove the clock. + /// \sa bcm2835_gpio_set_pud() + extern void bcm2835_gpio_pudclk(uint8_t pin, uint8_t on); + + /// Reads and returns the Pad Control for the given GPIO group. + /// \param[in] group The GPIO pad group number, one of BCM2835_PAD_GROUP_GPIO_* + /// \return Mask of bits from BCM2835_PAD_* from \ref bcm2835PadGroup + extern uint32_t bcm2835_gpio_pad(uint8_t group); + + /// Sets the Pad Control for the given GPIO group. + /// \param[in] group The GPIO pad group number, one of BCM2835_PAD_GROUP_GPIO_* + /// \param[in] control Mask of bits from BCM2835_PAD_* from \ref bcm2835PadGroup. Note + /// that it is not necessary to include BCM2835_PAD_PASSWRD in the mask as this + /// is automatically included. + extern void bcm2835_gpio_set_pad(uint8_t group, uint32_t control); + + /// Delays for the specified number of milliseconds. + /// Uses nanosleep(), and therefore does not use CPU until the time is up. + /// However, you are at the mercy of nanosleep(). From the manual for nanosleep(): + /// If the interval specified in req is not an exact multiple of the granularity + /// underlying clock (see time(7)), then the interval will be + /// rounded up to the next multiple. Furthermore, after the sleep completes, + /// there may still be a delay before the CPU becomes free to once + /// again execute the calling thread. + /// \param[in] millis Delay in milliseconds + extern void bcm2835_delay (unsigned int millis); + + /// Delays for the specified number of microseconds. + /// Uses a combination of nanosleep() and a busy wait loop on the BCM2835 system timers, + /// However, you are at the mercy of nanosleep(). From the manual for nanosleep(): + /// If the interval specified in req is not an exact multiple of the granularity + /// underlying clock (see time(7)), then the interval will be + /// rounded up to the next multiple. Furthermore, after the sleep completes, + /// there may still be a delay before the CPU becomes free to once + /// again execute the calling thread. + /// For times less than about 450 microseconds, uses a busy wait on the System Timer. + /// It is reported that a delay of 0 microseconds on RaspberryPi will in fact + /// result in a delay of about 80 microseconds. Your mileage may vary. + /// \param[in] micros Delay in microseconds + extern void bcm2835_delayMicroseconds (uint64_t micros); + + /// Indicate the number of milliseconds since startup of PI + /// This function is like the Arduino millis function + /// \return Number of milliseconds + extern unsigned int bcm2835_millis(void); + + /// Sets the output state of the specified pin + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + /// \param[in] on HIGH sets the output to HIGH and LOW to LOW. + extern void bcm2835_gpio_write(uint8_t pin, uint8_t on); + + /// Sets any of the first 32 GPIO output pins specified in the mask to the state given by on + /// \param[in] mask Mask of pins to affect. Use eg: (1 << RPI_GPIO_P1_03) | (1 << RPI_GPIO_P1_05) + /// \param[in] on HIGH sets the output to HIGH and LOW to LOW. + extern void bcm2835_gpio_write_multi(uint32_t mask, uint8_t on); + + /// Sets the first 32 GPIO output pins specified in the mask to the value given by value + /// \param[in] value values required for each bit masked in by mask, eg: (1 << RPI_GPIO_P1_03) | (1 << RPI_GPIO_P1_05) + /// \param[in] mask Mask of pins to affect. Use eg: (1 << RPI_GPIO_P1_03) | (1 << RPI_GPIO_P1_05) + extern void bcm2835_gpio_write_mask(uint32_t value, uint32_t mask); + + /// Sets the Pull-up/down mode for the specified pin. This is more convenient than + /// clocking the mode in with bcm2835_gpio_pud() and bcm2835_gpio_pudclk(). + /// \param[in] pin GPIO number, or one of RPI_GPIO_P1_* from \ref RPiGPIOPin. + /// \param[in] pud The desired Pull-up/down mode. One of BCM2835_GPIO_PUD_* from bcm2835PUDControl + extern void bcm2835_gpio_set_pud(uint8_t pin, uint8_t pud); + + /// @} + + /// \defgroup spi SPI access + /// These functions let you use SPI0 (Serial Peripheral Interface) to + /// interface with an external SPI device. + /// @{ + + /// Start SPI operations. + /// Forces RPi SPI0 pins P1-19 (MOSI), P1-21 (MISO), P1-23 (CLK), P1-24 (CE0) and P1-26 (CE1) + /// to alternate function ALT0, which enables those pins for SPI interface. + /// \param[in] cs Specifies the CS pins(s) that are used to activate the desired slave. + /// One of BCM2835_SPI_CS*, see \ref bcm2835SPIChipSelect + /// or one of One of BCM2835_SPI_CS*, see \ref bcm2835SPIChipSelect + /// by default PI hardware driven using CE0 + /// You should call bcm2835_spi_end() when all SPI funcitons are complete to return the pins to + /// their default functions + /// \sa bcm2835_spi_end() + extern void bcm2835_spi_begin(); + + /// End SPI operations. + /// SPI0 pins P1-19 (MOSI), P1-21 (MISO), P1-23 (CLK), P1-24 (CE0) and P1-26 (CE1) + /// are returned to their default INPUT behaviour. + extern void bcm2835_spi_end(void); + + /// Sets the SPI custom Chip Select pin to correct level + /// Defaults to + /// \param[in] level The desired level, LOW or HIGH, + extern void bcm2835_spi_setChipSelect(uint8_t level); + + /// Sets the SPI bit order + /// NOTE: has no effect. Not supported by SPI0. + /// Defaults to + /// \param[in] order The desired bit order, one of BCM2835_SPI_BIT_ORDER_*, + /// see \ref bcm2835SPIBitOrder + extern void bcm2835_spi_setBitOrder(uint8_t order); + + /// Sets the SPI clock divider and therefore the + /// SPI clock speed. + /// \param[in] divider The desired SPI clock divider, one of BCM2835_SPI_CLOCK_DIVIDER_*, + /// see \ref bcm2835SPIClockDivider + extern void bcm2835_spi_setClockDivider(uint16_t divider); + + /// Sets the SPI data mode + /// Sets the clock polariy and phase + /// \param[in] mode The desired data mode, one of BCM2835_SPI_MODE*, + /// see \ref bcm2835SPIMode + extern void bcm2835_spi_setDataMode(uint8_t mode); + + /// Sets the chip select pin(s) + /// When an bcm2835_spi_transfer() is made, the selected pin(s) will be asserted during the + /// transfer. + /// \param[in] cs Specifies the CS pins(s) that are used to activate the desired slave. + /// One of BCM2835_SPI_CS*, see \ref bcm2835SPIChipSelect + /// or one of One of BCM2835_SPI_CS*, see \ref bcm2835SPIChipSelect + extern void bcm2835_spi_chipSelect(uint8_t cs); + + /// Sets the chip select pin polarity for a given pin + /// When an bcm2835_spi_transfer() occurs, the currently selected chip select pin(s) + /// will be asserted to the + /// value given by active. When transfers are not happening, the chip select pin(s) + /// return to the complement (inactive) value. + /// \param[in] cs The chip select pin to affect + /// \param[in] active Whether the chip select pin is to be active HIGH + extern void bcm2835_spi_setChipSelectPolarity(uint8_t cs, uint8_t active); + + /// Transfers one byte to and from the currently selected SPI slave. + /// Asserts the currently selected CS pins (as previously set by bcm2835_spi_chipSelect) + /// during the transfer. + /// Clocks the 8 bit value out on MOSI, and simultaneously clocks in data from MISO. + /// Returns the read data byte from the slave. + /// Uses polled transfer as per section 10.6.1 of the BCM 2835 ARM Peripherls manual + /// \param[in] value The 8 bit data byte to write to MOSI + /// \return The 8 bit byte simultaneously read from MISO + /// \sa bcm2835_spi_transfern() + extern uint8_t bcm2835_spi_transfer(uint8_t value); + + /// Transfers any number of bytes to and from the currently selected SPI slave. + /// Asserts the currently selected CS pins (as previously set by bcm2835_spi_chipSelect) + /// during the transfer. + /// Clocks the len 8 bit bytes out on MOSI, and simultaneously clocks in data from MISO. + /// The data read read from the slave is placed into rbuf. rbuf must be at least len bytes long + /// Uses polled transfer as per section 10.6.1 of the BCM 2835 ARM Peripherls manual + /// \param[in] tbuf Buffer of bytes to send. + /// \param[out] rbuf Received bytes will by put in this buffer + /// \param[in] len Number of bytes in the tbuf buffer, and the number of bytes to send/received + /// \sa bcm2835_spi_transfer() + extern void bcm2835_spi_transfernb(char* tbuf, char* rbuf, uint32_t len); + + /// Transfers any number of bytes to and from the currently selected SPI slave + /// using bcm2835_spi_transfernb. + /// The returned data from the slave replaces the transmitted data in the buffer. + /// \param[in,out] buf Buffer of bytes to send. Received bytes will replace the contents + /// \param[in] len Number of bytes int eh buffer, and the number of bytes to send/received + /// \sa bcm2835_spi_transfer() + extern void bcm2835_spi_transfern(char* buf, uint32_t len); + + /// Transfers any number of bytes to the currently selected SPI slave. + /// Asserts the currently selected CS pins (as previously set by bcm2835_spi_chipSelect) + /// during the transfer. + /// \param[in] buf Buffer of bytes to send. + /// \param[in] len Number of bytes in the tbuf buffer, and the number of bytes to send + extern void bcm2835_spi_writenb(char* buf, uint32_t len); + + /// @} + + /// \defgroup i2c I2C access + /// These functions let you use I2C (The Broadcom Serial Control bus with the Philips + /// I2C bus/interface version 2.1 January 2000.) to interface with an external I2C device. + /// @{ + + /// Start I2C operations. + /// Forces RPi I2C pins P1-03 (SDA) and P1-05 (SCL) + /// to alternate function ALT0, which enables those pins for I2C interface. + /// You should call bcm2835_i2c_end() when all I2C functions are complete to return the pins to + /// their default functions + /// \sa bcm2835_i2c_end() + extern void bcm2835_i2c_begin(void); + + /// End I2C operations. + /// I2C pins P1-03 (SDA) and P1-05 (SCL) + /// are returned to their default INPUT behaviour. + extern void bcm2835_i2c_end(void); + + /// Sets the I2C slave address. + /// \param[in] addr The I2C slave address. + extern void bcm2835_i2c_setSlaveAddress(uint8_t addr); + + /// Sets the I2C clock divider and therefore the I2C clock speed. + /// \param[in] divider The desired I2C clock divider, one of BCM2835_I2C_CLOCK_DIVIDER_*, + /// see \ref bcm2835I2CClockDivider + extern void bcm2835_i2c_setClockDivider(uint16_t divider); + + /// Sets the I2C clock divider by converting the baudrate parameter to + /// the equivalent I2C clock divider. ( see \sa bcm2835_i2c_setClockDivider) + /// For the I2C standard 100khz you would set baudrate to 100000 + /// The use of baudrate corresponds to its use in the I2C kernel device + /// driver. (Of course, bcm2835 has nothing to do with the kernel driver) + extern void bcm2835_i2c_set_baudrate(uint32_t baudrate); + + /// Transfers any number of bytes to the currently selected I2C slave. + /// (as previously set by \sa bcm2835_i2c_setSlaveAddress) + /// \param[in] buf Buffer of bytes to send. + /// \param[in] len Number of bytes in the buf buffer, and the number of bytes to send. + /// \return reason see \ref bcm2835I2CReasonCodes + extern uint8_t bcm2835_i2c_write(const char * buf, uint32_t len); + + /// Transfers any number of bytes from the currently selected I2C slave. + /// (as previously set by \sa bcm2835_i2c_setSlaveAddress) + /// \param[in] buf Buffer of bytes to receive. + /// \param[in] len Number of bytes in the buf buffer, and the number of bytes to received. + /// \return reason see \ref bcm2835I2CReasonCodes + extern uint8_t bcm2835_i2c_read(char* buf, uint32_t len); + + /// Allows reading from I2C slaves that require a repeated start (without any prior stop) + /// to read after the required slave register has been set. For example, the popular + /// MPL3115A2 pressure and temperature sensor. Note that your device must support or + /// require this mode. If your device does not require this mode then the standard + /// combined: + /// \sa bcm2835_i2c_write + /// \sa bcm2835_i2c_read + /// are a better choice. + /// Will read from the slave previously set by \sa bcm2835_i2c_setSlaveAddress + /// \param[in] regaddr Buffer containing the slave register you wish to read from. + /// \param[in] buf Buffer of bytes to receive. + /// \param[in] len Number of bytes in the buf buffer, and the number of bytes to received. + /// \return reason see \ref bcm2835I2CReasonCodes + extern uint8_t bcm2835_i2c_read_register_rs(char* regaddr, char* buf, uint32_t len); + + /// Allows sending an arbitrary number of bytes to I2C slaves before issuing a repeated + /// start (with no prior stop) and reading a response. + /// Necessary for devices that require such behavior, such as the MLX90620. + /// Will write to and read from the slave previously set by \sa bcm2835_i2c_setSlaveAddress + /// \param[in] cmds Buffer containing the bytes to send before the repeated start condition. + /// \param[in] cmds_len Number of bytes to send from cmds buffer + /// \param[in] buf Buffer of bytes to receive. + /// \param[in] buf_len Number of bytes to receive in the buf buffer. + /// \return reason see \ref bcm2835I2CReasonCodes + extern uint8_t bcm2835_i2c_write_read_rs(char* cmds, uint32_t cmds_len, char* buf, uint32_t buf_len); + + /// @} + + /// \defgroup st System Timer access + /// Allows access to and delays using the System Timer Counter. + /// @{ + + /// Read the System Timer Counter register. + /// \return the value read from the System Timer Counter Lower 32 bits register + extern uint64_t bcm2835_st_read(void); + + /// Delays for the specified number of microseconds with offset. + /// \param[in] offset_micros Offset in microseconds + /// \param[in] micros Delay in microseconds + extern void bcm2835_st_delay(uint64_t offset_micros, uint64_t micros); + + /// @} + + /// \defgroup pwm Pulse Width Modulation + /// Allows control of 2 independent PWM channels. A limited subset of GPIO pins + /// can be connected to one of these 2 channels, allowing PWM control of GPIO pins. + /// You have to set the desired pin into a particular Alt Fun to PWM output. See the PWM + /// documentation on the Main Page. + /// @{ + + /// Sets the PWM clock divisor, + /// to control the basic PWM pulse widths. + /// \param[in] divisor Divides the basic 19.2MHz PWM clock. You can use one of the common + /// values BCM2835_PWM_CLOCK_DIVIDER_* in \ref bcm2835PWMClockDivider + extern void bcm2835_pwm_set_clock(uint32_t divisor); + + /// Sets the mode of the given PWM channel, + /// allowing you to control the PWM mode and enable/disable that channel + /// \param[in] channel The PWM channel. 0 or 1. + /// \param[in] markspace Set true if you want Mark-Space mode. 0 for Balanced mode. + /// \param[in] enabled Set true to enable this channel and produce PWM pulses. + extern void bcm2835_pwm_set_mode(uint8_t channel, uint8_t markspace, uint8_t enabled); + + /// Sets the maximum range of the PWM output. + /// The data value can vary between 0 and this range to control PWM output + /// \param[in] channel The PWM channel. 0 or 1. + /// \param[in] range The maximum value permitted for DATA. + extern void bcm2835_pwm_set_range(uint8_t channel, uint32_t range); + + /// Sets the PWM pulse ratio to emit to DATA/RANGE, + /// where RANGE is set by bcm2835_pwm_set_range(). + /// \param[in] channel The PWM channel. 0 or 1. + /// \param[in] data Controls the PWM output ratio as a fraction of the range. + /// Can vary from 0 to RANGE. + extern void bcm2835_pwm_set_data(uint8_t channel, uint32_t data); + + /// @} +#ifdef __cplusplus +} +#endif + +#endif // BCM2835_H + +/// @example blink.c +/// Blinks RPi GPIO pin 11 on and off + +/// @example input.c +/// Reads the state of an RPi input pin + +/// @example event.c +/// Shows how to use event detection on an input pin + +/// @example spi.c +/// Shows how to use SPI interface to transfer a byte to and from an SPI device + +/// @example spin.c +/// Shows how to use SPI interface to transfer a number of bytes to and from an SPI device + +/// @example pwm.c +/// Shows how to use PWM to control GPIO pins + +/// @example i2c.c +/// Command line utility for executing i2c commands with the +/// Broadcom bcm2835. Contributed by Shahrooz Shahparnia. + +/// example gpio.c +/// Command line utility for executing gpio commands with the +/// Broadcom bcm2835. Contributed by Shahrooz Shahparnia. diff --git a/libraries/RF24/RPi/RF24/examples/Makefile b/libraries/RF24/RPi/RF24/examples/Makefile new file mode 100644 index 0000000..73da217 --- /dev/null +++ b/libraries/RF24/RPi/RF24/examples/Makefile @@ -0,0 +1,40 @@ +############################################################################# +# +# Makefile for librf24 examples on Raspberry Pi +# +# License: GPL (General Public License) +# Author: gnulnulf +# Date: 2013/02/07 (version 1.0) +# +# Description: +# ------------ +# use make all and make install to install the examples +# You can change the install directory by editing the prefix line +# +prefix := /usr/local + +# The recommended compiler flags for the Raspberry Pi +CCFLAGS=-Ofast -mfpu=vfp -mfloat-abi=hard -march=armv6zk -mtune=arm1176jzf-s +#CCFLAGS= + +# define all programs +#PROGRAMS = scanner pingtest gettingstarted +PROGRAMS = gettingstarted gettingstarted_call_response transfer pingpair_dyn +SOURCES = ${PROGRAMS:=.cpp} + +all: ${PROGRAMS} + +${PROGRAMS}: ${SOURCES} + g++ ${CCFLAGS} -Wall -I../ -lrf24-bcm $@.cpp -o $@ + +clean: + rm -rf $(PROGRAMS) + +install: all + test -d $(prefix) || mkdir $(prefix) + test -d $(prefix)/bin || mkdir $(prefix)/bin + for prog in $(PROGRAMS); do \ + install -m 0755 $$prog $(prefix)/bin; \ + done + +.PHONY: install diff --git a/libraries/RF24/RPi/RF24/examples/extra/Makefile b/libraries/RF24/RPi/RF24/examples/extra/Makefile new file mode 100644 index 0000000..c313b5b --- /dev/null +++ b/libraries/RF24/RPi/RF24/examples/extra/Makefile @@ -0,0 +1,40 @@ +############################################################################# +# +# Makefile for librf24 examples on Raspberry Pi +# +# License: GPL (General Public License) +# Author: gnulnulf +# Date: 2013/02/07 (version 1.0) +# +# Description: +# ------------ +# use make all and make install to install the examples +# You can change the install directory by editing the prefix line +# +prefix := /usr/local + +# The recommended compiler flags for the Raspberry Pi +CCFLAGS=-Ofast -mfpu=vfp -mfloat-abi=hard -march=armv6zk -mtune=arm1176jzf-s +#CCFLAGS= + +# define all programs +PROGRAMS = rpi-hub scanner + +SOURCES = ${PROGRAMS:=.cpp} + +all: ${PROGRAMS} + +${PROGRAMS}: ${SOURCES} + g++ ${CCFLAGS} -Wall -I../ -lrf24-bcm $@.cpp -o $@ + +clean: + rm -rf $(PROGRAMS) + +install: all + test -d $(prefix) || mkdir $(prefix) + test -d $(prefix)/bin || mkdir $(prefix)/bin + for prog in $(PROGRAMS); do \ + install -m 0755 $$prog $(prefix)/bin; \ + done + +.PHONY: install diff --git a/libraries/RF24/RPi/RF24/examples/extra/rpi-hub.cpp b/libraries/RF24/RPi/RF24/examples/extra/rpi-hub.cpp new file mode 100644 index 0000000..4785148 --- /dev/null +++ b/libraries/RF24/RPi/RF24/examples/extra/rpi-hub.cpp @@ -0,0 +1,134 @@ +/* + * + * Filename : rpi-hub.cpp + * + * This program makes the RPi as a hub listening to all six pipes from the remote sensor nodes ( usually Arduino ) + * and will return the packet back to the sensor on pipe0 so that the sender can calculate the round trip delays + * when the payload matches. + * + * I encounter that at times, it also receive from pipe7 ( or pipe0 ) with content of FFFFFFFFF that I will not sent + * back to the sender + * + * Refer to RF24/examples/rpi_hub_arduino/ for the corresponding Arduino sketches to work with this code. + * + * + * CE is not used and CSN is GPIO25 (not pinout) + * + * Refer to RPi docs for GPIO numbers + * + * Author : Stanley Seow + * e-mail : stanleyseow@gmail.com + * date : 6th Mar 2013 + * + * 03/17/2013 : Charles-Henri Hallard (http://hallard.me) + * Modified to use with Arduipi board http://hallard.me/arduipi + * Changed to use modified bcm2835 and RF24 library + * + * + */ + +#include +#include +#include "../RF24.h" + +using namespace std; + +// Radio pipe addresses for the 2 nodes to communicate. +// First pipe is for writing, 2nd, 3rd, 4th, 5th & 6th is for reading... +const uint64_t pipes[6] = + { 0xF0F0F0F0D2LL, 0xF0F0F0F0E1LL, + 0xF0F0F0F0E2LL, 0xF0F0F0F0E3LL, + 0xF0F0F0F0F1, 0xF0F0F0F0F2 + }; + +// CE Pin, CSN Pin, SPI Speed + +// Setup for GPIO 22 CE and GPIO 25 CSN with SPI Speed @ 1Mhz +//RF24 radio(RPI_V2_GPIO_P1_22, RPI_V2_GPIO_P1_18, BCM2835_SPI_SPEED_1MHZ); + +// Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 4Mhz +//RF24 radio(RPI_V2_GPIO_P1_15, BCM2835_SPI_CS0, BCM2835_SPI_SPEED_4MHZ); + +// Setup for GPIO 22 CE and CE1 CSN with SPI Speed @ 8Mhz +RF24 radio(RPI_V2_GPIO_P1_15, RPI_V2_GPIO_P1_26, BCM2835_SPI_SPEED_8MHZ); + + +int main(int argc, char** argv) +{ + uint8_t len; + + // Refer to RF24.h or nRF24L01 DS for settings + radio.begin(); + radio.enableDynamicPayloads(); + radio.setAutoAck(1); + radio.setRetries(15,15); + radio.setDataRate(RF24_1MBPS); + radio.setPALevel(RF24_PA_MAX); + radio.setChannel(76); + radio.setCRCLength(RF24_CRC_16); + + // Open 6 pipes for readings ( 5 plus pipe0, also can be used for reading ) + radio.openWritingPipe(pipes[0]); + radio.openReadingPipe(1,pipes[1]); + radio.openReadingPipe(2,pipes[2]); + radio.openReadingPipe(3,pipes[3]); + radio.openReadingPipe(4,pipes[4]); + radio.openReadingPipe(5,pipes[5]); + + // + // Start listening + // + radio.startListening(); + + // + // Dump the configuration of the rf unit for debugging + // + radio.printDetails(); + + printf("Output below : \n"); + delay(1); + + while(1) + { + char receivePayload[32]; + uint8_t pipe = 1; + + // Start listening + radio.startListening(); + + while ( radio.available(&pipe) ) + { + len = radio.getDynamicPayloadSize(); + radio.read( receivePayload, len ); + + // Display it on screen + printf("Recv: size=%i payload=%s pipe=%i",len,receivePayload,pipe); + + // Send back payload to sender + radio.stopListening(); + + // if pipe is 7, do not send it back + if ( pipe != 7 ) + { + radio.write(receivePayload,len); + receivePayload[len]=0; + printf("\t Send: size=%i payload=%s pipe:%i\n",len,receivePayload,pipe); + } + else + { + printf("\n"); + } + + pipe++; + + // reset pipe to 0 + if ( pipe > 6 ) + pipe = 0; + } + + delayMicroseconds(20); + } + + return 0; +} + diff --git a/libraries/RF24/RPi/RF24/examples/extra/scanner.cpp b/libraries/RF24/RPi/RF24/examples/extra/scanner.cpp new file mode 100644 index 0000000..1390495 --- /dev/null +++ b/libraries/RF24/RPi/RF24/examples/extra/scanner.cpp @@ -0,0 +1,147 @@ +/* + 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. + + + 03/17/2013 : Charles-Henri Hallard (http://hallard.me) + Modified to use with Arduipi board http://hallard.me/arduipi + Changed to use modified bcm2835 and RF24 library + + */ + +/** + * 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 +#include "../RF24.h" + +using namespace std; + +// +// Hardware configuration +// + +// CE Pin, CSN Pin, SPI Speed + +// Setup for GPIO 22 CE and GPIO 25 CSN with SPI Speed @ 1Mhz +//RF24 radio(RPI_V2_GPIO_P1_22, RPI_V2_GPIO_P1_18, BCM2835_SPI_SPEED_1MHZ); + +// Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 4Mhz +//RF24 radio(RPI_V2_GPIO_P1_15, BCM2835_SPI_CS0, BCM2835_SPI_SPEED_4MHZ); + +// Setup for GPIO 22 CE and CE1 CSN with SPI Speed @ 8Mhz +RF24 radio(RPI_V2_GPIO_P1_15, RPI_V2_GPIO_P1_26, BCM2835_SPI_SPEED_8MHZ); + + +// +// Channel info +// +//const uint8_t num_channels = 128; +const uint8_t num_channels = 120; +uint8_t values[num_channels]; + + +const int num_reps = 100; +int reset_array=0; + + +int main(int argc, char** argv) +{ + // + // Print preamble + // + + //Serial.begin(57600); + //printf_begin(); + printf("RF24/examples/scanner/\n"); + + // + // Setup and configure rf radio + // + radio.begin(); + + radio.setAutoAck(false); + + // Get into standby mode + radio.startListening(); + radio.stopListening(); + + radio.printDetails(); + + // Print out header, high then low digit + int i = 0; + + while ( i < num_channels ) + { + printf("%x",i>>4); + ++i; + } + printf("\n"); + + i = 0; + while ( i < num_channels ) + { + printf("%x",i&0xf); + ++i; + } + printf("\n"); + + // forever loop + while(1) + { + if ( reset_array == 1 ) + { + // Clear measurement values + memset(values,0,sizeof(values)); + printf("\n"); + } + + // Scan all channels num_reps times + 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]; + if ( values[i] == 0xf ) + { + reset_array = 2; + } + radio.stopListening(); + } + + // Print out channel measurements, clamped to a single hex digit + i = 0; + while ( i < num_channels ) + { + printf("%x",min(0xf,(values[i]&0xf))); + ++i; + } + + printf("\n"); + } + + return 0; +} + +// vim:ai:cin:sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/RPi/RF24/examples/gettingstarted.cpp b/libraries/RF24/RPi/RF24/examples/gettingstarted.cpp new file mode 100644 index 0000000..5539c4d --- /dev/null +++ b/libraries/RF24/RPi/RF24/examples/gettingstarted.cpp @@ -0,0 +1,187 @@ +/* + 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. + + 03/17/2013 : Charles-Henri Hallard (http://hallard.me) + Modified to use with Arduipi board http://hallard.me/arduipi + Changed to use modified bcm2835 and RF24 library +TMRh20 2014 - Updated to work with optimized RF24 Arduino library + + */ + +/** + * Example RF Radio Ping Pair + * + * This is an example of how to use the RF24 class on RPi, communicating to an Arduino running + * the GettingStarted sketch. + */ + +#include +#include +#include +#include +#include "./RF24.h" + +using namespace std; +// +// Hardware configuration +// + +// CE Pin, CSN Pin, SPI Speed + +// Setup for GPIO 22 CE and CE1 CSN with SPI Speed @ 1Mhz +//RF24 radio(RPI_V2_GPIO_P1_22, RPI_V2_GPIO_P1_26, BCM2835_SPI_SPEED_1MHZ); + +// Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 4Mhz +//RF24 radio(RPI_V2_GPIO_P1_15, BCM2835_SPI_CS0, BCM2835_SPI_SPEED_4MHZ); + +// Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 8Mhz +RF24 radio(RPI_V2_GPIO_P1_15, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ); + + + +// Radio pipe addresses for the 2 nodes to communicate. +const uint64_t pipes[2] = { 0xABCDABCD71LL, 0x544d52687CLL }; + +bool role_ping_out = 1, role_pong_back = 0; +bool role = 0; + +int main(int argc, char** argv){ + + + // Print preamble: + printf("RF24/examples/pingtest/\n"); + + // Setup and configure rf radio + radio.begin(); + + // optionally, increase the delay between retries & # of retries + radio.setRetries(15,15); + + // Dump the configuration of the rf unit for debugging + radio.printDetails(); + + +/********* Role chooser ***********/ + + printf("\n ************ Role Setup ***********\n"); + string input = ""; + char myChar = {0}; + cout << "Choose a role: Enter 0 for pong_back, 1 for ping_out (CTRL+C to exit) \n>"; + getline(cin,input); + + if(input.length() == 1) { + myChar = input[0]; + if(myChar == '0'){ + cout << "Role: Pong Back, awaiting transmission " << endl << endl; + }else{ cout << "Role: Ping Out, starting transmission " << endl << endl; + role = role_ping_out; + } + } +/***********************************/ + // This simple sketch opens two pipes for these two nodes to communicate + // back and forth. + + if ( role == role_ping_out ) { + radio.openWritingPipe(pipes[0]); + radio.openReadingPipe(1,pipes[1]); + } else { + radio.openWritingPipe(pipes[1]); + radio.openReadingPipe(1,pipes[0]); + radio.startListening(); + + } + + // forever loop + while (1) + { + 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 + + printf("Now sending...\n"); + unsigned long time = millis(); + + bool ok = radio.write( &time, sizeof(unsigned long) ); + + if (!ok){ + printf("failed.\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 ) { + // by bcatalin » Thu Feb 14, 2013 11:26 am + //delay(5); //add a small delay to let radio.available to check payload + if (millis() - started_waiting_at > 200 ) + timeout = true; + } + + + // Describe the results + if ( timeout ) + { + printf("Failed, response timed out.\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\n",got_time,millis()-got_time); + } + + // Try again 1s later + // delay(1000); + sleep(1); + + } + + // + // Pong back role. Receive each packet, dump it out, and send it back + // + + if ( role == role_pong_back ) + { + // if there is data ready + //printf("Check available...\n"); + //delay(3); + if ( radio.available() ) + { + // Dump the payloads until we've gotten everything + unsigned long got_time; + + + // Fetch the payload, and see if this was the last one. + radio.read( &got_time, sizeof(unsigned long) ); + + radio.stopListening(); + //delay(1); + // Seem to need a delay, or the RPi is too quick + radio.write( &got_time, sizeof(unsigned long) ); + + //delay(1); + // Now, resume listening so we catch the next packets. + radio.startListening(); + //delay(1); + // Spew it + printf("Got payload(%d) %lu...\n",sizeof(unsigned long), got_time); + } + //delay(5); + } + } // forever loop + + return 0; +} + diff --git a/libraries/RF24/RPi/RF24/examples/gettingstarted_call_response.cpp b/libraries/RF24/RPi/RF24/examples/gettingstarted_call_response.cpp new file mode 100644 index 0000000..19a16cc --- /dev/null +++ b/libraries/RF24/RPi/RF24/examples/gettingstarted_call_response.cpp @@ -0,0 +1,137 @@ +/* +TMRh20 2014 - Updated to work with optimized RF24 Arduino library +*/ + + +/** + * Example for efficient call-response using ack-payloads + * + * 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. + */ + +#include +#include +#include +#include +#include "./RF24.h" + +using namespace std; + +// +// Hardware configuration +// + +// CE Pin, CSN Pin, SPI Speed + +// Setup for GPIO 22 CE and CE1 CSN with SPI Speed @ 1Mhz +//RF24 radio(RPI_V2_GPIO_P1_22, RPI_V2_GPIO_P1_26, BCM2835_SPI_SPEED_1MHZ); + +// Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 4Mhz +//RF24 radio(RPI_V2_GPIO_P1_15, BCM2835_SPI_CS0, BCM2835_SPI_SPEED_4MHZ); + +// Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 8Mhz +RF24 radio(RPI_V2_GPIO_P1_15, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ); + + +// Radio pipe addresses for the 2 nodes to communicate. +const uint64_t addresses[2] = { 0xABCDABCD71LL, 0x544d52687CLL }; + +bool role_ping_out = 1, role_pong_back = 0, role = 0; + +uint8_t counter = 1; // A single byte to keep track of the data being sent back and forth + + +int main(int argc, char** argv){ + + + printf("RF24/examples/gettingstarted_call_response\n"); + + radio.begin(); + radio.setAutoAck(1); // Ensure autoACK is enabled + radio.enableAckPayload(); // Allow optional ack payloads + radio.setRetries(1,15); // Smallest time between retries, max no. of retries + radio.setPayloadSize(1); // Here we are sending 1-byte payloads to test the call-response speed + //radio.powerUp(); + radio.printDetails(); // Dump the configuration of the rf unit for debugging + + +/********* Role chooser ***********/ + + printf("\n ************ Role Setup ***********\n"); + string input = ""; + char myChar = {0}; + cout << "Choose a role: Enter 0 for pong_back, 1 for ping_out (CTRL+C to exit)\n>"; + getline(cin,input); + + if(input.length() == 1) { + myChar = input[0]; + if(myChar == '0'){ + cout << "Role: Pong Back, awaiting transmission " << endl << endl; + }else{ cout << "Role: Ping Out, starting transmission " << endl << endl; + role = role_ping_out; + } + } +/***********************************/ + // This simple sketch opens two pipes for these two nodes to communicate + // back and forth. + + if ( role == role_ping_out ) { + radio.openWritingPipe(addresses[0]); + radio.openReadingPipe(1,addresses[1]); + }else{ + radio.openWritingPipe(addresses[1]); + radio.openReadingPipe(1,addresses[0]); + radio.startListening(); + } + +// forever loop +while (1){ + + +/****************** Ping Out Role ***************************/ + + if (role == role_ping_out){ // Radio is in ping mode + + uint8_t gotByte; // Initialize a variable for the incoming response + + radio.stopListening(); // First, stop listening so we can talk. + printf("Now sending %d as payload. ",counter); // Use a simple byte counter as payload + unsigned long time = millis(); // Record the current microsecond count + + if ( radio.write(&counter,1) ){ // Send the counter variable to the other radio + if(!radio.available()){ // If nothing in the buffer, we got an ack but it is blank + printf("Got blank response. round-trip delay: %lu ms\n\r",millis()-time); + }else{ + while(radio.available() ){ // If an ack with payload was received + radio.read( &gotByte, 1 ); // Read it, and display the response time + printf("Got response %d, round-trip delay: %lu ms\n\r",gotByte,millis()-time); + counter++; // Increment the counter variable + } + } + + }else{ printf("Sending failed.\n\r"); } // If no ack response, sending failed + + sleep(1); // Try again later + } + +/****************** Pong Back Role ***************************/ + + if ( role == role_pong_back ) { + uint8_t pipeNo, gotByte; // Declare variables for the pipe and the byte received + while( radio.available(&pipeNo)){ // Read all available payloads + radio.read( &gotByte, 1 ); + // Since this is a call-response. Respond directly with an ack payload. + // Ack payloads are much more efficient than switching to transmit mode to respond to a call + radio.writeAckPayload(pipeNo,&gotByte, 1 ); // This can be commented out to send empty payloads. + printf("Sent response %d \n\r", gotByte); + } + } + +} //while 1 +} //main + + diff --git a/libraries/RF24/RPi/RF24/examples/pingpair_dyn.cpp b/libraries/RF24/RPi/RF24/examples/pingpair_dyn.cpp new file mode 100644 index 0000000..09f94e6 --- /dev/null +++ b/libraries/RF24/RPi/RF24/examples/pingpair_dyn.cpp @@ -0,0 +1,181 @@ +/* + TMRh20 2014 - Optimized RF24 Library Fork +*/ + +/** + * Example using Dynamic Payloads + * + * This is an example of how to use payloads of a varying (dynamic) size. + */ + +#include +#include +#include +#include +#include "./RF24.h" + + +using namespace std; +// +// Hardware configuration +// + +// CE Pin, CSN Pin, SPI Speed + +// Setup for GPIO 22 CE and CE1 CSN with SPI Speed @ 1Mhz +//RF24 radio(RPI_V2_GPIO_P1_22, RPI_V2_GPIO_P1_26, BCM2835_SPI_SPEED_1MHZ); + +// Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 4Mhz +//RF24 radio(RPI_V2_GPIO_P1_15, BCM2835_SPI_CS0, BCM2835_SPI_SPEED_4MHZ); + +// Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 8Mhz +RF24 radio(RPI_V2_GPIO_P1_15, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ); + + +// Radio pipe addresses for the 2 nodes to communicate. +const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL }; + +bool role_ping_out = 1, role_pong_back = 0; +bool role = 0; + +const int min_payload_size = 4; +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 + +int main(int argc, char** argv){ + + + // Print preamble: + printf("RF24/examples/pingpair_dyn/\n"); + + // Setup and configure rf radio + radio.begin(); + radio.enableDynamicPayloads(); + radio.setRetries(5,15); + radio.printDetails(); + + +/********* Role chooser ***********/ + + printf("\n ************ Role Setup ***********\n"); + string input = ""; + char myChar = {0}; + cout << "Choose a role: Enter 0 for receiver, 1 for transmitter (CTRL+C to exit) \n>"; + getline(cin,input); + + if(input.length() == 1) { + myChar = input[0]; + if(myChar == '0'){ + cout << "Role: Pong Back, awaiting transmission " << endl << endl; + }else{ cout << "Role: Ping Out, starting transmission " << endl << endl; + role = role_ping_out; + } + } +/***********************************/ + + if ( role == role_ping_out ) { + radio.openWritingPipe(pipes[0]); + radio.openReadingPipe(1,pipes[1]); + } else { + radio.openWritingPipe(pipes[1]); + radio.openReadingPipe(1,pipes[0]); + radio.startListening(); + } + + +// forever loop + while (1) + { + +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(100); + } + + // + // 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; + + while (radio.available()) + { + // Fetch the payload, and see if this was the last one. + 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\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(); + } + } +} +} + + diff --git a/libraries/RF24/RPi/RF24/examples/transfer.cpp b/libraries/RF24/RPi/RF24/examples/transfer.cpp new file mode 100644 index 0000000..9d55470 --- /dev/null +++ b/libraries/RF24/RPi/RF24/examples/transfer.cpp @@ -0,0 +1,148 @@ +/* +TMRh20 2014 + + 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. + */ + +/** General Data Transfer Rate Test + * This example demonstrates basic data transfer functionality with the + updated library. This example will display the transfer rates acheived using + the slower form of high-speed transfer using blocking-writes. + */ + +#include +#include +#include +#include +#include "./RF24.h" + + +using namespace std; +// +// Hardware configuration +// + +// CE Pin, CSN Pin, SPI Speed + +// Setup for GPIO 22 CE and CE1 CSN with SPI Speed @ 1Mhz +//RF24 radio(RPI_V2_GPIO_P1_22, RPI_V2_GPIO_P1_26, BCM2835_SPI_SPEED_1MHZ); + +// Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 4Mhz +//RF24 radio(RPI_V2_GPIO_P1_15, BCM2835_SPI_CS0, BCM2835_SPI_SPEED_4MHZ); + +// Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 8Mhz +RF24 radio(RPI_V2_GPIO_P1_15, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ); + + + +// Radio pipe addresses for the 2 nodes to communicate. +const uint64_t addresses[2] = { 0xABCDABCD71LL, 0x544d52687CLL }; + +bool role_ping_out = 1, role_pong_back = 0; +bool role = 0; +uint8_t data[32]; +unsigned long startTime, stopTime, counter, rxTimer=0; + +int main(int argc, char** argv){ + + + // Print preamble: + + printf("RF24/examples/Transfer/\n"); + + radio.begin(); // Setup and configure rf radio + radio.setChannel(1); + radio.setPALevel(RF24_PA_MAX); + radio.setDataRate(RF24_2MBPS); + radio.setAutoAck(1); // Ensure autoACK is enabled + radio.setRetries(2,15); // Optionally, increase the delay between retries & # of retries + radio.setCRCLength(RF24_CRC_8); + radio.printDetails(); +/********* Role chooser ***********/ + + printf("\n ************ Role Setup ***********\n"); + string input = ""; + char myChar = {0}; + cout << "Choose a role: Enter 0 for receiver, 1 for transmitter (CTRL+C to exit)\n>"; + getline(cin,input); + + if(input.length() == 1) { + myChar = input[0]; + if(myChar == '0'){ + cout << "Role: Pong Back, awaiting transmission " << endl << endl; + }else{ cout << "Role: Ping Out, starting transmission " << endl << endl; + role = role_ping_out; + } + } +/***********************************/ + + if ( role == role_ping_out ) { + radio.openWritingPipe(addresses[0]); + radio.openReadingPipe(1,addresses[1]); + } else { + radio.openWritingPipe(addresses[1]); + radio.openReadingPipe(1,addresses[0]); + radio.startListening(); + } + + + for(int i=0; i<32; i++){ + data[i] = rand() % 255; //Load the buffer with random data + } + + // forever loop + while (1){ + + if (role == role_ping_out){ + sleep(2); + printf("Initiating Basic Data Transfer\n\r"); + + long int cycles = 10000; //Change this to a higher or lower number. + + startTime = millis(); + + for(int i=0; i 1000){ + rxTimer = millis(); + printf("Rate: "); + float numBytes = counter*32; + printf("%.2f KB/s \n\r",numBytes/1000); + printf("Payload Count: %lu \n\r", counter); + counter = 0; + } + } + +} // loop +} // main + + + + + + diff --git a/libraries/RF24/RPi/RF24/nRF24L01.h b/libraries/RF24/RPi/RF24/nRF24L01.h new file mode 100644 index 0000000..ba83534 --- /dev/null +++ b/libraries/RF24/RPi/RF24/nRF24L01.h @@ -0,0 +1,127 @@ +/* + 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/RPi/RF24/readme.md b/libraries/RF24/RPi/RF24/readme.md new file mode 100644 index 0000000..a7880d6 --- /dev/null +++ b/libraries/RF24/RPi/RF24/readme.md @@ -0,0 +1,117 @@ + +Optimized Raspberry Pi RF24 and RF24 Network Libraries +============================================= + General Documentation: http://tmrh20.github.io + + Library functions are mostly the same. + See the included examples for RPi specific usage + +##Raspberry Pi - PreConfig + + +####Possible pre-configuration: + If SPI is not already enabled, load it on boot: +``` + sudo raspi-config +``` +A. Update the tool via the menu as required +B. Select Advanced and enable the SPI kernel module +C. Update other software and libraries: +``` + sudo apt-get update + sudo apt-get upgrade +``` +RPi - RF24 Quick-Start +====================== +A. Make a directory to contain the RF24 and possibly RF24Network lib and enter it: +``` + mkdir ~/rf24libs + cd ~/rf24libs +``` +B. Clone the RF24 Repo +``` + git clone https://github.com/tmrh20/RF24.git rtemp +``` +C. Copy the RPi library folder to the current directory, and delete the rest +``` + mv rtemp/RPi/RF24 ./ + rm -r rtemp + cd RF24 +``` +D. Build the library, and run an example file: +``` + sudo make + cd examples + sudo make + sudo ./gettingstarted +``` + +RPi - RF24Network Quick-Start +============================= +A. Enter the same directory that contains the RF24 library folder +``` + cd ~/rf24libs +``` +B. Clone the RF24Network Repo +``` + git clone https://github.com/tmrh20/RF24Network.git ntemp +``` +C. Copy the RF24Network folder to the current directory, and delete the rest +``` + mv ntemp/RPi/RF24Network ./ + rm -r ntemp + cd RF24Network +``` +D. Build the library +``` + sudo make + cd examples + sudo make + sudo ./helloworld_rx OR sudo ./helloworld_tx +``` + +Connection Info +=============== + +Using pin 15/GPIO 22 for CE, pin 24/GPIO8 (CE0) for CSN + +Can use either RPi CE0 or CE1 pins for radio CSN. +Choose any RPi output pin for radio CE pin. + +**Constructor:** +``` +RF24 radio(RPI_V2_GPIO_P1_15,BCM2835_SPI_CS0, BCM2835_SPI_SPEED_8MHZ); +or +RF24 radio(RPI_V2_GPIO_P1_15,BCM2835_SPI_CS1, BCM2835_SPI_SPEED_8MHZ); +``` + +**Pins:** + + |NRF24L01 | RPI | P1 Connector | + |-----|-----------|-------------| + | VCC | rpi-3v3 | (17) | + | GND | rpi-gnd | (25) | + | CE | rpi-gpio22 | (15) | + | CSN | rpi-gpio8 | (24) | + | SCK | rpi-sckl | (23) | + | MOSI | rpi-mosi | (19) | + | MISO | rpi-miso | (21) | + + +See http://www.airspayce.com/mikem/bcm2835/index.html for BCM2835 class documentation. +Note: The BCM library has been customized slightly to allow use of hardware CE pins not +in use for SPI, and to include a millis() function. + +**************** + + +Based on the arduino lib from J. Coliz . +the library was berryfied by Purinda Gunasekara . +then forked from github stanleyseow/RF24 to https://github.com/jscrane/RF24-rpi +Network lib also based on https://github.com/farconada/RF24Network + +Currently optimized and aligned with Arduino fork of libraries by TMRh20: +https://github.com/tmrh20/RF24/RPi and https://github.com/tmrh20/RF24Network/RPi +Documentation: http://tmrh20.github.io + + diff --git a/libraries/RF24/RPi/readme.md b/libraries/RF24/RPi/readme.md new file mode 100644 index 0000000..a7880d6 --- /dev/null +++ b/libraries/RF24/RPi/readme.md @@ -0,0 +1,117 @@ + +Optimized Raspberry Pi RF24 and RF24 Network Libraries +============================================= + General Documentation: http://tmrh20.github.io + + Library functions are mostly the same. + See the included examples for RPi specific usage + +##Raspberry Pi - PreConfig + + +####Possible pre-configuration: + If SPI is not already enabled, load it on boot: +``` + sudo raspi-config +``` +A. Update the tool via the menu as required +B. Select Advanced and enable the SPI kernel module +C. Update other software and libraries: +``` + sudo apt-get update + sudo apt-get upgrade +``` +RPi - RF24 Quick-Start +====================== +A. Make a directory to contain the RF24 and possibly RF24Network lib and enter it: +``` + mkdir ~/rf24libs + cd ~/rf24libs +``` +B. Clone the RF24 Repo +``` + git clone https://github.com/tmrh20/RF24.git rtemp +``` +C. Copy the RPi library folder to the current directory, and delete the rest +``` + mv rtemp/RPi/RF24 ./ + rm -r rtemp + cd RF24 +``` +D. Build the library, and run an example file: +``` + sudo make + cd examples + sudo make + sudo ./gettingstarted +``` + +RPi - RF24Network Quick-Start +============================= +A. Enter the same directory that contains the RF24 library folder +``` + cd ~/rf24libs +``` +B. Clone the RF24Network Repo +``` + git clone https://github.com/tmrh20/RF24Network.git ntemp +``` +C. Copy the RF24Network folder to the current directory, and delete the rest +``` + mv ntemp/RPi/RF24Network ./ + rm -r ntemp + cd RF24Network +``` +D. Build the library +``` + sudo make + cd examples + sudo make + sudo ./helloworld_rx OR sudo ./helloworld_tx +``` + +Connection Info +=============== + +Using pin 15/GPIO 22 for CE, pin 24/GPIO8 (CE0) for CSN + +Can use either RPi CE0 or CE1 pins for radio CSN. +Choose any RPi output pin for radio CE pin. + +**Constructor:** +``` +RF24 radio(RPI_V2_GPIO_P1_15,BCM2835_SPI_CS0, BCM2835_SPI_SPEED_8MHZ); +or +RF24 radio(RPI_V2_GPIO_P1_15,BCM2835_SPI_CS1, BCM2835_SPI_SPEED_8MHZ); +``` + +**Pins:** + + |NRF24L01 | RPI | P1 Connector | + |-----|-----------|-------------| + | VCC | rpi-3v3 | (17) | + | GND | rpi-gnd | (25) | + | CE | rpi-gpio22 | (15) | + | CSN | rpi-gpio8 | (24) | + | SCK | rpi-sckl | (23) | + | MOSI | rpi-mosi | (19) | + | MISO | rpi-miso | (21) | + + +See http://www.airspayce.com/mikem/bcm2835/index.html for BCM2835 class documentation. +Note: The BCM library has been customized slightly to allow use of hardware CE pins not +in use for SPI, and to include a millis() function. + +**************** + + +Based on the arduino lib from J. Coliz . +the library was berryfied by Purinda Gunasekara . +then forked from github stanleyseow/RF24 to https://github.com/jscrane/RF24-rpi +Network lib also based on https://github.com/farconada/RF24Network + +Currently optimized and aligned with Arduino fork of libraries by TMRh20: +https://github.com/tmrh20/RF24/RPi and https://github.com/tmrh20/RF24Network/RPi +Documentation: http://tmrh20.github.io + + diff --git a/libraries/RF24/doxygen-custom.css b/libraries/RF24/doxygen-custom.css new file mode 100644 index 0000000..d7d0e12 --- /dev/null +++ b/libraries/RF24/doxygen-custom.css @@ -0,0 +1,835 @@ +/* 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.ino b/libraries/RF24/examples/GettingStarted/GettingStarted.ino new file mode 100644 index 0000000..ff871be --- /dev/null +++ b/libraries/RF24/examples/GettingStarted/GettingStarted.ino @@ -0,0 +1,136 @@ +/* + 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. +//2014 - TMRh20 - Updated along with Optimized RF24 Library fork + */ + +/** + * Example for Getting Started with nRF24L01+ radios. + * + * 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 + */ + + +#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(7,8); + +const uint64_t addresses[2] = { 0xABCDABCD71LL, 0x544d52687CLL }; // Radio pipe addresses for the 2 nodes to communicate. + +// Set up roles to simplify testing +boolean role; // The main role variable, holds the current role identifier +boolean role_ping_out = 1, role_pong_back = 0; // The two different roles. + +void setup() { + + + Serial.begin(57600); + printf_begin(); + printf("\n\rRF24/examples/GettingStarted/\n\r"); + printf("*** PRESS 'T' to begin transmitting to the other node\n\r"); + + // Setup and configure rf radio + radio.begin(); // Start up the radio + radio.setAutoAck(1); // Ensure autoACK is enabled + radio.setRetries(15,15); // Max delay between retries & number of retries + + radio.openWritingPipe(addresses[1]); // Open a writing pipe on pipe 0, with address 1 + radio.openReadingPipe(1,addresses[0]); // Open a reading pipe on pipe 1, with address 0 + + radio.startListening(); // Start listening + radio.printDetails(); // Dump the configuration of the rf unit for debugging +} + +void loop(void){ + + +/****************** Ping Out Role ***************************/ + if (role == role_ping_out) { + + radio.stopListening(); // First, stop listening so we can talk. + + + printf("Now sending \n\r"); + + unsigned long time = micros(); // Take the time, and send it. This will block until complete + if (!radio.write( &time, sizeof(unsigned long) )){ printf("failed.\n\r"); } + + radio.startListening(); // Now, continue listening + + unsigned long started_waiting_at = micros(); // Set up a timeout period, get the current microseconds + boolean timeout = false; // Set up a variable to indicate if a response was received or not + + while ( ! radio.available() ){ // While nothing is received + if (micros() - started_waiting_at > 200000 ){ // If waited longer than 200ms, indicate timeout and exit while loop + timeout = true; + break; + } + } + + if ( timeout ){ // Describe the results + printf("Failed, response timed out.\n\r"); + }else{ + unsigned long got_time; // Grab the response, compare, and send to debugging spew + radio.read( &got_time, sizeof(unsigned long) ); + + // Spew it + printf("Sent %lu, Got response %lu, round-trip delay: %lu microseconds\n\r",time,got_time,micros()-got_time); + } + + // Try again 1s later + delay(1000); + } + +/****************** Pong Back Role ***************************/ + + if ( role == role_pong_back ) + { + if( radio.available()){ + unsigned long got_time; // Variable for the received timestamp + while (radio.available()) { // While there is data ready + radio.read( &got_time, sizeof(unsigned long) ); // Get the payload + } + + radio.stopListening(); // First, stop listening so we can talk + radio.write( &got_time, sizeof(unsigned long) ); // Send the final one back. + radio.startListening(); // Now, resume listening so we catch the next packets. + printf("Sent response %lu \n\r", got_time); + } + } + + +/****************** Change Roles via Serial Commands ***************************/ + + 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"); + + role = role_ping_out; // Become the primary transmitter (ping out) + radio.openWritingPipe(addresses[0]); + radio.openReadingPipe(1,addresses[1]); + } + else if ( c == 'R' && role == role_ping_out ) + { + printf("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK\n\r"); + + role = role_pong_back; // Become the primary receiver (pong back) + radio.openWritingPipe(addresses[1]); + radio.openReadingPipe(1,addresses[0]); + } + } +} \ No newline at end of file diff --git a/libraries/RF24/examples/GettingStarted/printf.h b/libraries/RF24/examples/GettingStarted/printf.h new file mode 100644 index 0000000..b2efd56 --- /dev/null +++ b/libraries/RF24/examples/GettingStarted/printf.h @@ -0,0 +1,37 @@ +/* + 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/GettingStarted_CallResponse/GettingStarted_CallResponse.ino b/libraries/RF24/examples/GettingStarted_CallResponse/GettingStarted_CallResponse.ino new file mode 100644 index 0000000..8b2d0d5 --- /dev/null +++ b/libraries/RF24/examples/GettingStarted_CallResponse/GettingStarted_CallResponse.ino @@ -0,0 +1,124 @@ +/* + March 2014 - TMRh20 - Updated along with High Speed RF24 Library fork + Parts derived from examples by J. Coliz +*/ +/** + * Example for efficient call-response using ack-payloads + * + * 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. + */ + +#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(7,8); + // Topology +const uint64_t addresses[2] = { 0xABCDABCD71LL, 0x544d52687CLL }; // Radio pipe addresses for the 2 nodes to communicate. + +// Role management: Set up role. This sketch uses the same software for all the nodes +// in this system. Doing so greatly simplifies testing. +typedef enum { role_ping_out = 1, role_pong_back } role_e; // The various roles supported by this sketch +const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"}; // The debug-friendly names of those roles +role_e role = role_pong_back; // The role of the current running sketch + +byte counter = 1; // A single byte to keep track of the data being sent back and forth + + +void setup(){ + + 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 radio + + radio.begin(); + radio.setAutoAck(1); // Ensure autoACK is enabled + radio.enableAckPayload(); // Allow optional ack payloads + radio.setRetries(0,15); // Smallest time between retries, max no. of retries + radio.setPayloadSize(1); // Here we are sending 1-byte payloads to test the call-response speed + radio.openWritingPipe(addresses[1]); // Both radios listen on the same pipes by default, and switch when writing + radio.openReadingPipe(1,addresses[0]); // Open a reading pipe on address 0, pipe 1 + radio.startListening(); // Start listening + radio.powerUp(); + radio.printDetails(); // Dump the configuration of the rf unit for debugging +} + +void loop(void) { + + +/****************** Ping Out Role ***************************/ + + if (role == role_ping_out){ // Radio is in ping mode + + byte gotByte; // Initialize a variable for the incoming response + + radio.stopListening(); // First, stop listening so we can talk. + printf("Now sending %d as payload. ",counter); // Use a simple byte counter as payload + unsigned long time = micros(); // Record the current microsecond count + + if ( radio.write(&counter,1) ){ // Send the counter variable to the other radio + if(!radio.available()){ // If nothing in the buffer, we got an ack but it is blank + printf("Got blank response. round-trip delay: %lu microseconds\n\r",micros()-time); + }else{ + while(radio.available() ){ // If an ack with payload was received + radio.read( &gotByte, 1 ); // Read it, and display the response time + printf("Got response %d, round-trip delay: %lu microseconds\n\r",gotByte,micros()-time); + counter++; // Increment the counter variable + } + } + + }else{ printf("Sending failed.\n\r"); } // If no ack response, sending failed + + delay(1000); // Try again later + } + + +/****************** Pong Back Role ***************************/ + + if ( role == role_pong_back ) { + byte pipeNo, gotByte; // Declare variables for the pipe and the byte received + while( radio.available(&pipeNo)){ // Read all available payloads + radio.read( &gotByte, 1 ); + // Since this is a call-response. Respond directly with an ack payload. + // Ack payloads are much more efficient than switching to transmit mode to respond to a call + radio.writeAckPayload(pipeNo,&gotByte, 1 ); // This can be commented out to send empty payloads. + printf("Sent response %d \n\r", gotByte); + } + } + + + +/****************** Change Roles via Serial Commands ***************************/ + + 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"); + + role = role_ping_out; // Change roles (ping out) + radio.openWritingPipe(addresses[0]); // Open different pipes when writing. Write on pipe 0, address 0 + radio.openReadingPipe(1,addresses[1]); // Read on pipe 1, as address 1 + } + else if ( c == 'R' && role == role_ping_out ) + { + printf("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK\n\r"); + + role = role_pong_back; // Become the primary receiver (pong back) + radio.openWritingPipe(addresses[1]); // Since only two radios involved, both listen on the same addresses and pipe numbers in RX mode + radio.openReadingPipe(1,addresses[0]); // then switch pipes & addresses to transmit. + radio.startListening(); // Need to start listening after opening new reading pipes + } + } +} diff --git a/libraries/RF24/examples/GettingStarted_CallResponse/printf.h b/libraries/RF24/examples/GettingStarted_CallResponse/printf.h new file mode 100644 index 0000000..b2efd56 --- /dev/null +++ b/libraries/RF24/examples/GettingStarted_CallResponse/printf.h @@ -0,0 +1,37 @@ +/* + 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/Transfer/Transfer.ino b/libraries/RF24/examples/Transfer/Transfer.ino new file mode 100644 index 0000000..b9b1362 --- /dev/null +++ b/libraries/RF24/examples/Transfer/Transfer.ino @@ -0,0 +1,144 @@ +/* +TMRh20 2014 + + 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. + */ + +/** General Data Transfer Rate Test + * This example demonstrates basic data transfer functionality with the + updated library. This example will display the transfer rates acheived using + the slower form of high-speed transfer using blocking-writes. + */ + + + +#include +#include "nRF24L01.h" +#include "RF24.h" +#include "printf.h" + +/************* USER Configuration *****************************/ + // Hardware configuration +RF24 radio(48,49); // Set up nRF24L01 radio on SPI bus plus pins 7 & 8 +boolean RADIO_NO = 0; //SET THIS TO 0 or 1 for 1st or 2nd radio + +/***************************************************************/ + +const uint64_t pipes[2] = { 0xABCDABCD71LL, 0x544d52687CLL }; // Radio pipe addresses for the 2 nodes to communicate. + +byte data[32]; //Data buffer for testing data transfer speeds + +unsigned long counter, rxTimer; //Counter and timer for keeping track transfer info +unsigned long startTime, stopTime; +bool TX=1,RX=0,role=0; + +void setup(void) { + + Serial.begin(57600); + printf_begin(); + + radio.begin(); // Setup and configure rf radio + radio.setChannel(1); + radio.setPALevel(RF24_PA_MAX); + radio.setDataRate(RF24_1MBPS); + radio.setAutoAck(1); // Ensure autoACK is enabled + radio.setRetries(2,15); // Optionally, increase the delay between retries & # of retries + radio.setCRCLength(RF24_CRC_8); + //radio.disableCRC(); + radio.openWritingPipe(pipes[0]); + radio.openReadingPipe(1,pipes[1]); + + radio.startListening(); // Start listening + radio.printDetails(); // Dump the configuration of the rf unit for debugging + + printf("\n\rRF24/examples/Transfer Rates/\n\r"); + printf("*** PRESS 'T' to begin transmitting to the other node\n\r"); + + randomSeed(analogRead(0)); //Seed for random number generation + + for(int i=0; i<32; i++){ + data[i] = random(255); //Load the buffer with random data + } + radio.powerUp(); //Power up the radio +} + +void loop(void){ + + + if(role == TX){ + + delay(2000); + + printf("Initiating Basic Data Transfer\n\r"); + + + unsigned long cycles = 10000; //Change this to a higher or lower number. + + startTime = millis(); + + for(int i=0; i 1000){ + rxTimer = millis(); + printf("Rate: "); + float numBytes = counter*32; + Serial.print(numBytes/1000); + printf(" KB/s\n\r"); + printf("Payload Count: %d \n\r", counter); + counter = 0; + } + } + // + // Change roles + // + + if ( Serial.available() ) + { + char c = toupper(Serial.read()); + if ( c == 'T' && role == RX ) + { + printf("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK\n\r"); + radio.openWritingPipe(pipes[1]); + radio.openReadingPipe(1,pipes[0]); + radio.stopListening(); + role = TX; // Become the primary transmitter (ping out) + } + else if ( c == 'R' && role == TX ) + { + radio.openWritingPipe(pipes[0]); + radio.openReadingPipe(1,pipes[1]); + radio.startListening(); + printf("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK\n\r"); + role = RX; // Become the primary receiver (pong back) + } + } +} +// vim:cin:ai:sts=2 sw=2 ft=cpp diff --git a/libraries/RF24/examples/Transfer/printf.h b/libraries/RF24/examples/Transfer/printf.h new file mode 100644 index 0000000..b40dd38 --- /dev/null +++ b/libraries/RF24/examples/Transfer/printf.h @@ -0,0 +1,37 @@ +/* + 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/TransferTimeouts/TransferTimeouts.ino b/libraries/RF24/examples/TransferTimeouts/TransferTimeouts.ino new file mode 100644 index 0000000..65fce99 --- /dev/null +++ b/libraries/RF24/examples/TransferTimeouts/TransferTimeouts.ino @@ -0,0 +1,189 @@ +/* +TMRh20 2014 + + 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. + */ + +/** Reliably transmitting large volumes of data with a low signal or in noisy environments + * This example demonstrates data transfer functionality with the use of auto-retry + and auto-reUse functionality enabled. This sketch demonstrates how a user can extend + the auto-retry functionality to any chosen time period, preventing data loss and ensuring + the consistency of data. + + This sketh demonstrates use of the writeBlocking() functionality, and extends the standard + retry functionality of the radio. Payloads will be auto-retried until successful or the + extended timeout period is reached. + */ + + + +#include +#include "nRF24L01.h" +#include "RF24.h" +#include "printf.h" + +/************* USER Configuration *****************************/ + +RF24 radio(48,49); // Set up nRF24L01 radio on SPI bus plus pins 7 & 8 +unsigned long timeoutPeriod = 3000; // Set a user-defined timeout period. With auto-retransmit set to (15,15) retransmission will take up to 60ms and as little as 7.5ms with it set to (1,15). + // With a timeout period of 1000, the radio will retry each payload for up to 1 second before giving up on the transmission and starting over + +/***************************************************************/ + +const uint64_t pipes[2] = { 0xABCDABCD71LL, 0x544d52687CLL }; // Radio pipe addresses for the 2 nodes to communicate. + +byte data[32]; //Data buffer + +volatile unsigned long counter; +unsigned long rxTimer,startTime, stopTime, payloads = 0; +bool TX=1,RX=0,role=0, transferInProgress = 0; + + +void setup(void) { + + Serial.begin(57600); + printf_begin(); + + radio.begin(); // Setup and configure rf radio + radio.setChannel(1); // Set the channel + radio.setPALevel(RF24_PA_LOW); // Set PA LOW for this demonstration. We want the radio to be as lossy as possible for this example. + radio.setDataRate(RF24_1MBPS); // Raise the data rate to reduce transmission distance and increase lossiness + radio.setAutoAck(1); // Ensure autoACK is enabled + radio.setRetries(2,15); // Optionally, increase the delay between retries. Want the number of auto-retries as high as possible (15) + radio.setCRCLength(RF24_CRC_16); // Set CRC length to 16-bit to ensure quality of data + radio.openWritingPipe(pipes[0]); // Open the default reading and writing pipe + radio.openReadingPipe(1,pipes[1]); + + radio.startListening(); // Start listening + radio.printDetails(); // Dump the configuration of the rf unit for debugging + + printf("\n\rRF24/examples/Transfer Rates/\n\r"); + printf("*** PRESS 'T' to begin transmitting to the other node\n\r"); + + randomSeed(analogRead(0)); //Seed for random number generation + for(int i=0; i<32; i++){ + data[i] = random(255); //Load the buffer with random data + } + radio.powerUp(); //Power up the radio + + +} + + + +void loop(void){ + + + if(role == TX){ + delay(2000); // Pause for a couple seconds between transfers + printf("Initiating Extended Timeout Data Transfer\n\r"); + + unsigned long cycles = 1000; // Change this to a higher or lower number. This is the number of payloads that will be sent. + + unsigned long transferCMD[] = {'H','S',cycles }; // Indicate to the other radio that we are starting, and provide the number of payloads that will be sent + radio.writeFast(&transferCMD,12); // Send the transfer command + if(radio.txStandBy(timeoutPeriod)){ // If transfer initiation was successful, do the following + + startTime = millis(); // For calculating transfer rate + boolean timedOut = 0; // Boolean for keeping track of failures + + for(int i=0; i timeoutPeriod){ // If no data available, check the timeout period + Serial.println("Transfer Failed"); // If per-payload timeout exceeeded, end the transfer + transferInProgress = 0; + }else + if(counter >= payloads){ // If the specified number of payloads is reached, transfer is completed + startTime = millis() - startTime; // Calculate the total time spent during transfer + float numBytes = counter*32; // Calculate the number of bytes transferred + Serial.print("Rate: "); // Print the transfer rate and number of payloads + Serial.print(numBytes/startTime); + Serial.println(" KB/s"); + printf("Payload Count: %d \n\r", counter); + transferInProgress = 0; // End the transfer as complete + } + } + + + } + + // + // Change roles + // + + if ( Serial.available() ) + { + char c = toupper(Serial.read()); + if ( c == 'T' && role == RX ) + { + printf("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK\n\r"); + radio.openWritingPipe(pipes[1]); + radio.openReadingPipe(1,pipes[0]); + radio.stopListening(); + role = TX; // Become the primary transmitter (ping out) + } + else if ( c == 'R' && role == TX ) + { + radio.openWritingPipe(pipes[0]); + radio.openReadingPipe(1,pipes[1]); + radio.startListening(); + printf("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK\n\r"); + role = RX; // Become the primary receiver (pong back) + } + } +} + + diff --git a/libraries/RF24/examples/TransferTimeouts/printf.h b/libraries/RF24/examples/TransferTimeouts/printf.h new file mode 100644 index 0000000..b2efd56 --- /dev/null +++ b/libraries/RF24/examples/TransferTimeouts/printf.h @@ -0,0 +1,37 @@ +/* + 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/Usage/led_remote/Jamfile b/libraries/RF24/examples/Usage/led_remote/Jamfile new file mode 100644 index 0000000..901f8da --- /dev/null +++ b/libraries/RF24/examples/Usage/led_remote/Jamfile @@ -0,0 +1,206 @@ +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/Usage/led_remote/led_remote.pde b/libraries/RF24/examples/Usage/led_remote/led_remote.pde new file mode 100644 index 0000000..80e2955 --- /dev/null +++ b/libraries/RF24/examples/Usage/led_remote/led_remote.pde @@ -0,0 +1,255 @@ +/* + 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(led_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/Usage/led_remote/printf.h b/libraries/RF24/examples/Usage/led_remote/printf.h new file mode 100644 index 0000000..b2efd56 --- /dev/null +++ b/libraries/RF24/examples/Usage/led_remote/printf.h @@ -0,0 +1,37 @@ +/* + 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/Usage/nordic_fob/Jamfile b/libraries/RF24/examples/Usage/nordic_fob/Jamfile new file mode 100644 index 0000000..ec519f7 --- /dev/null +++ b/libraries/RF24/examples/Usage/nordic_fob/Jamfile @@ -0,0 +1,219 @@ +# (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/Usage/nordic_fob/nordic_fob.pde b/libraries/RF24/examples/Usage/nordic_fob/nordic_fob.pde new file mode 100644 index 0000000..5a316a0 --- /dev/null +++ b/libraries/RF24/examples/Usage/nordic_fob/nordic_fob.pde @@ -0,0 +1,142 @@ +/* + 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/Usage/nordic_fob/printf.h b/libraries/RF24/examples/Usage/nordic_fob/printf.h new file mode 100644 index 0000000..b2efd56 --- /dev/null +++ b/libraries/RF24/examples/Usage/nordic_fob/printf.h @@ -0,0 +1,37 @@ +/* + 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/Usage/pingpair_maple/Jamfile b/libraries/RF24/examples/Usage/pingpair_maple/Jamfile new file mode 100644 index 0000000..798096c --- /dev/null +++ b/libraries/RF24/examples/Usage/pingpair_maple/Jamfile @@ -0,0 +1,182 @@ +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/Usage/pingpair_maple/main.cpp b/libraries/RF24/examples/Usage/pingpair_maple/main.cpp new file mode 100644 index 0000000..b4f976d --- /dev/null +++ b/libraries/RF24/examples/Usage/pingpair_maple/main.cpp @@ -0,0 +1,87 @@ +#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/Usage/pingpair_maple/pingpair_maple.pde b/libraries/RF24/examples/Usage/pingpair_maple/pingpair_maple.pde new file mode 100644 index 0000000..2d3925b --- /dev/null +++ b/libraries/RF24/examples/Usage/pingpair_maple/pingpair_maple.pde @@ -0,0 +1,242 @@ +/* + 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_ack/pingpair_ack.ino b/libraries/RF24/examples/pingpair_ack/pingpair_ack.ino new file mode 100644 index 0000000..4cd3fe3 --- /dev/null +++ b/libraries/RF24/examples/pingpair_ack/pingpair_ack.ino @@ -0,0 +1,123 @@ +/* + // March 2014 - TMRh20 - Updated along with High Speed RF24 Library fork + // Parts derived from examples by J. Coliz +*/ +/** + * Example for efficient call-response using ack-payloads + * + * 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. + */ + + + +#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(7,8); + +// Topology +const uint64_t pipes[2] = { 0xABCDABCD71LL, 0x544d52687CLL }; // Radio pipe addresses for the 2 nodes to communicate. + +// Role management: Set up role. This sketch uses the same software for all the nodes +// in this system. Doing so greatly simplifies testing. + +typedef enum { role_ping_out = 1, role_pong_back } role_e; // The various roles supported by this sketch +const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"}; // The debug-friendly names of those roles +role_e role = role_pong_back; // The role of the current running sketch + +// A single byte to keep track of the data being sent back and forth +byte counter = 1; + +void setup(){ + + 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(); + radio.setAutoAck(1); // Ensure autoACK is enabled + radio.enableAckPayload(); // Allow optional ack payloads + radio.setRetries(0,15); // Smallest time between retries, max no. of retries + radio.setPayloadSize(1); // Here we are sending 1-byte payloads to test the call-response speed + radio.openWritingPipe(pipes[1]); // Both radios listen on the same pipes by default, and switch when writing + radio.openReadingPipe(1,pipes[0]); + radio.startListening(); // Start listening + radio.printDetails(); // Dump the configuration of the rf unit for debugging +} + +void loop(void) { + + if (role == role_ping_out){ + + radio.stopListening(); // First, stop listening so we can talk. + + printf("Now sending %d as payload. ",counter); + byte gotByte; + unsigned long time = micros(); // Take the time, and send it. This will block until complete + //Called when STANDBY-I mode is engaged (User is finished sending) + if (!radio.write( &counter, 1 )){ + printf("failed.\n\r"); + }else{ + + if(!radio.available()){ + printf("Blank Payload Received\n\r"); + }else{ + while(radio.available() ){ + unsigned long tim = micros(); + radio.read( &gotByte, 1 ); + printf("Got response %d, round-trip delay: %lu microseconds\n\r",gotByte,tim-time); + counter++; + } + } + + } + // Try again later + delay(1000); + } + + // Pong back role. Receive each packet, dump it out, and send it back + + if ( role == role_pong_back ) { + byte pipeNo; + byte gotByte; // Dump the payloads until we've gotten everything + while( radio.available(&pipeNo)){ + radio.read( &gotByte, 1 ); + radio.writeAckPayload(pipeNo,&gotByte, 1 ); + } + } + + // 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"); + + role = role_ping_out; // Become the primary transmitter (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"); + + role = role_pong_back; // Become the primary receiver (pong back) + radio.openWritingPipe(pipes[1]); + radio.openReadingPipe(1,pipes[0]); + radio.startListening(); + } + } +} diff --git a/libraries/RF24/examples/pingpair_ack/printf.h b/libraries/RF24/examples/pingpair_ack/printf.h new file mode 100644 index 0000000..b2efd56 --- /dev/null +++ b/libraries/RF24/examples/pingpair_ack/printf.h @@ -0,0 +1,37 @@ +/* + 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_dyn/Jamfile b/libraries/RF24/examples/pingpair_dyn/Jamfile new file mode 100644 index 0000000..901f8da --- /dev/null +++ b/libraries/RF24/examples/pingpair_dyn/Jamfile @@ -0,0 +1,206 @@ +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.ino b/libraries/RF24/examples/pingpair_dyn/pingpair_dyn.ino new file mode 100644 index 0000000..e1b1319 --- /dev/null +++ b/libraries/RF24/examples/pingpair_dyn/pingpair_dyn.ino @@ -0,0 +1,232 @@ +/* + 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(7,8); + +// 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 = 5; + +// +// 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 = 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.enableDynamicPayloads(); + + // optionally, increase the delay between retries & # of retries + radio.setRetries(5,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(100); + } + + // + // 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 (radio.available()) + { + // Fetch the payload, and see if this was the last one. + 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\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 \ No newline at end of file diff --git a/libraries/RF24/examples/pingpair_dyn/printf.h b/libraries/RF24/examples/pingpair_dyn/printf.h new file mode 100644 index 0000000..b2efd56 --- /dev/null +++ b/libraries/RF24/examples/pingpair_dyn/printf.h @@ -0,0 +1,37 @@ +/* + 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_irq/pingpair_irq.ino b/libraries/RF24/examples/pingpair_irq/pingpair_irq.ino new file mode 100644 index 0000000..fb3f429 --- /dev/null +++ b/libraries/RF24/examples/pingpair_irq/pingpair_irq.ino @@ -0,0 +1,137 @@ +/* + 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. + + Update 2014 - TMRh20 + */ + +/** + * Example of using interrupts + * + * 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 + */ + +#include +#include "nRF24L01.h" +#include "RF24.h" +#include "printf.h" +#include +#include + +// Hardware configuration +RF24 radio(7,8); // Set up nRF24L01 radio on SPI bus plus pins 9 & 10 + +const short role_pin = 5; // sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver + // Leave open to be the 'ping' transmitter + + const uint64_t address[2] = {0xABCDABCD71LL, 0x544d52687CLL}; // Radio pipe addresses for the 2 nodes to communicate. + +// 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 +typedef enum { role_sender = 1, role_receiver } role_e; // The various roles supported by this sketch +const char* role_friendly_name[] = { "invalid", "Sender", "Receiver"}; // The debug-friendly names of those roles +role_e role; // The role of the current running sketch + +boolean gotMsg = 0; // So we know when to go to sleep + +/********************** Setup *********************/ +void setup(){ + + pinMode(role_pin, INPUT); // set up the role pin + digitalWrite(role_pin,HIGH); // Change this to LOW/HIGH instead of using an external pin + delay(20); // Just to get a solid reading on the role pin + + if ( digitalRead(role_pin) ) // read the address pin, establish our role + role = role_sender; + else + role = role_receiver; + + + Serial.begin(115200); + 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(); + radio.enableAckPayload(); // We will be using the Ack Payload feature, so please enable it + // Open pipes to other node for communication + if ( role == role_sender ) { // This simple sketch opens a pipe on a single address for these two nodes to + radio.openWritingPipe(address[0]); // communicate back and forth. One listens on it, the other talks to it. + radio.openReadingPipe(1,address[1]); + }else{ + radio.openWritingPipe(address[1]); + radio.openReadingPipe(1,address[0]); + radio.startListening(); + } + radio.printDetails(); // Dump the configuration of the rf unit for debugging + delay(50); + attachInterrupt(0, check_radio, FALLING); // Attach interrupt handler to interrupt #0 (using pin 2) on BOTH the sender and receiver +} + +static uint32_t message_count = 0; + + +/********************** Main Loop *********************/ +void loop() { + + + if (role == role_sender) { // Sender role. Repeatedly send the current time + unsigned long time = millis(); // Take the time, and send it. + printf("Now sending %lu\n\r",time); + radio.startWrite( &time, sizeof(unsigned long) ,0); + delay(2000); // Try again soon + } + + + if(role == role_receiver){ // Receiver does nothing except in IRQ + } +} + + +/********************** Interrupt *********************/ + +void check_radio(void) // Receiver role: Does nothing! All the work is in IRQ +{ + + bool tx,fail,rx; + radio.whatHappened(tx,fail,rx); // What happened? + + if ( tx ) { // Have we successfully transmitted? + if ( role == role_sender ){ printf("Send:OK\n\r"); } + if ( role == role_receiver ){ printf("Ack Payload:Sent\n\r"); } + } + + if ( fail ) { // Have we failed to transmit? + if ( role == role_sender ){ printf("Send:Failed\n\r"); } + if ( role == role_receiver ){ printf("Ack Payload:Failed\n\r"); } + } + + if ( rx || radio.available()){ // Did we receive a message? + + if ( role == role_sender ) { // If we're the sender, we've received an ack payload + radio.read(&message_count,sizeof(message_count)); + printf("Ack:%lu\n\r",message_count); + } + + + if ( role == role_receiver ) { // If we're the receiver, we've received a time message + static unsigned long got_time; // Get this payload and dump it + radio.read( &got_time, sizeof(got_time) ); + printf("Got payload %lu\n\r",got_time); + radio.writeAckPayload( 1, &message_count, sizeof(message_count) ); // Add an ack packet for the next time around. This is a simple + ++message_count; // packet counter + + } + } +} diff --git a/libraries/RF24/examples/pingpair_irq/printf.h b/libraries/RF24/examples/pingpair_irq/printf.h new file mode 100644 index 0000000..b2efd56 --- /dev/null +++ b/libraries/RF24/examples/pingpair_irq/printf.h @@ -0,0 +1,37 @@ +/* + 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_sleepy/pingpair_sleepy.ino b/libraries/RF24/examples/pingpair_sleepy/pingpair_sleepy.ino new file mode 100644 index 0000000..8a8bc4e --- /dev/null +++ b/libraries/RF24/examples/pingpair_sleepy/pingpair_sleepy.ino @@ -0,0 +1,225 @@ +/* + 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. + + TMRh20 2014 - Updates to the library allow sleeping both in TX and RX modes: + TX Mode: The radio can be powered down (.9uA current) and the Arduino slept using the watchdog timer + RX Mode: The radio can be left in standby mode (22uA current) and the Arduino slept using an interrupt pin + */ + +/** + * 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 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. + * + * 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" + + +// Set up nRF24L01 radio on SPI bus plus pins 9 & 10 +RF24 radio(7,8); + +// 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 = 5; + +const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL }; // Radio pipe addresses for the 2 nodes to communicate. + +// 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. + +// 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; + + + +void setup(){ + + // 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; + + 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 uses WDT. Wake up every 4s to send a ping + //if ( role == role_ping_out ) + setup_watchdog(wdt_4s); + + // 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(){ + + + if (role == role_ping_out) { // Ping out role. Repeatedly send the current time + radio.powerUp(); // Power up the radio after sleeping + radio.stopListening(); // First, stop listening so we can talk. + + unsigned long time = millis(); // Take the time, and send it. + printf("Now sending... %lu \n\r",time); + + radio.write( &time, sizeof(unsigned long) ); + + radio.startListening(); // Now, continue listening + + unsigned long started_waiting_at = millis(); // Wait here until we get a response, or timeout (250ms) + bool timeout = false; + while ( ! radio.available() ){ + if (millis() - started_waiting_at > 250 ){ // Break out of the while loop if nothing available + timeout = true; + break; + } + } + + if ( timeout ) { // Describe the results + printf("Failed, response timed out.\n\r"); + }else{ + unsigned long got_time; // Grab the response, compare, and send to debugging spew + radio.read( &got_time, sizeof(unsigned long) ); + + printf("Got response %lu, round-trip delay: %lu\n\r",got_time,millis()-got_time); + } + + // Shut down the system + delay(500); // Experiment with some delay here to see if it has an effect + // Power down the radio. + radio.powerDown(); // NOTE: The radio MUST be powered back up again manually + + // Sleep the MCU. + do_sleep(); + + + } + + + // Pong back role. Receive each packet, dump it out, and send it back + if ( role == role_pong_back ) { + + if ( radio.available() ) { // if there is data ready + + unsigned long got_time; + while (radio.available()) { // Dump the payloads until we've gotten everything + radio.read( &got_time, sizeof(unsigned long) ); // Get the payload, and see if this was the last one. + // Spew it. Include our time, because the ping_out millis counter is unreliable + printf("Got payload %lu @ %lu...",got_time,millis()); // due to it sleeping + } + + radio.stopListening(); // First, stop listening so we can talk + radio.write( &got_time, sizeof(unsigned long) ); // Send the final one back. + printf("Sent response.\n\r"); + radio.startListening(); // Now, resume listening so we catch the next packets. + }else{ + Serial.println("Sleeping"); + delay(50); // Delay so the serial data can print out + do_sleep(); + + } + } +} + +void wakeUp(){ + sleep_disable(); +} + +// Sleep helpers + +//Prescaler values +// 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){ + + uint8_t wdtcsr = prescalar & 7; + if ( prescalar & 8 ) + wdtcsr |= _BV(WDP3); + MCUSR &= ~_BV(WDRF); // Clear the WD System Reset Flag + WDTCSR = _BV(WDCE) | _BV(WDE); // Write the WD Change enable bit to enable changing the prescaler and enable system reset + WDTCSR = _BV(WDCE) | wdtcsr | _BV(WDIE); // Write the prescalar bits (how long to sleep, enable the interrupt to wake the MCU +} + +ISR(WDT_vect) +{ + //--sleep_cycles_remaining; + Serial.println("WDT"); +} + +void do_sleep(void) +{ + set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here + sleep_enable(); + attachInterrupt(0,wakeUp,LOW); + WDTCSR |= _BV(WDIE); + sleep_mode(); // System sleeps here + // The WDT_vect interrupt wakes the MCU from here + sleep_disable(); // System continues execution here when watchdog timed out + detachInterrupt(0); + WDTCSR &= ~_BV(WDIE); +} diff --git a/libraries/RF24/examples/pingpair_sleepy/printf.h b/libraries/RF24/examples/pingpair_sleepy/printf.h new file mode 100644 index 0000000..b2efd56 --- /dev/null +++ b/libraries/RF24/examples/pingpair_sleepy/printf.h @@ -0,0 +1,37 @@ +/* + 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/scanner/Jamfile b/libraries/RF24/examples/scanner/Jamfile new file mode 100644 index 0000000..1bf541e --- /dev/null +++ b/libraries/RF24/examples/scanner/Jamfile @@ -0,0 +1,210 @@ +# (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/libraries/RF24/examples/scanner/output/core.a b/libraries/RF24/examples/scanner/output/core.a new file mode 100644 index 0000000..6ae105d Binary files /dev/null and b/libraries/RF24/examples/scanner/output/core.a differ diff --git a/libraries/RF24/examples/scanner/output/scanner.cpp b/libraries/RF24/examples/scanner/output/scanner.cpp new file mode 100644 index 0000000..5eb1627 --- /dev/null +++ b/libraries/RF24/examples/scanner/output/scanner.cpp @@ -0,0 +1,128 @@ +#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/libraries/RF24/examples/scanner/output/scanner.elf b/libraries/RF24/examples/scanner/output/scanner.elf new file mode 100755 index 0000000..5e0f4b1 Binary files /dev/null and b/libraries/RF24/examples/scanner/output/scanner.elf differ diff --git a/libraries/RF24/examples/scanner/output/scanner.hex b/libraries/RF24/examples/scanner/output/scanner.hex new file mode 100644 index 0000000..00a3175 --- /dev/null +++ b/libraries/RF24/examples/scanner/output/scanner.hex @@ -0,0 +1,325 @@ +: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/libraries/RF24/examples/scanner/printf.h b/libraries/RF24/examples/scanner/printf.h new file mode 100644 index 0000000..66f6438 --- /dev/null +++ b/libraries/RF24/examples/scanner/printf.h @@ -0,0 +1,31 @@ +/* + 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/libraries/RF24/examples/scanner/scanner.ino b/libraries/RF24/examples/scanner/scanner.ino new file mode 100644 index 0000000..e4aca24 --- /dev/null +++ b/libraries/RF24/examples/scanner/scanner.ino @@ -0,0 +1,126 @@ +/* + 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(225); + + + // Did we get a carrier? + if ( radio.testCarrier() ){ + ++values[i]; + } + radio.stopListening(); + } + } + + // 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 \ No newline at end of file diff --git a/libraries/RF24/examples/starping/Jamfile b/libraries/RF24/examples/starping/Jamfile new file mode 100644 index 0000000..de9b1f6 --- /dev/null +++ b/libraries/RF24/examples/starping/Jamfile @@ -0,0 +1,206 @@ +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 new file mode 100644 index 0000000..b2efd56 --- /dev/null +++ b/libraries/RF24/examples/starping/printf.h @@ -0,0 +1,37 @@ +/* + 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/starping/starping.pde b/libraries/RF24/examples/starping/starping.pde new file mode 100644 index 0000000..4813a77 --- /dev/null +++ b/libraries/RF24/examples/starping/starping.pde @@ -0,0 +1,293 @@ +/* + 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/libraries/RF24/keywords.txt b/libraries/RF24/keywords.txt new file mode 100644 index 0000000..d829ee9 --- /dev/null +++ b/libraries/RF24/keywords.txt @@ -0,0 +1,16 @@ + RF24 KEYWORD1 + begin KEYWORD2 + setChannel KEYWORD2 + setPayloadSize KEYWORD2 + getPayloadSize KEYWORD2 + print_details KEYWORD2 + startListening KEYWORD2 + stopListening KEYWORD2 + write KEYWORD2 + writeFast KEYWORD2 + writeBlocking KEYWORD2 + txStandBy KEYWORD2 + available KEYWORD2 + read KEYWORD2 + openWritingPipe KEYWORD2 + openReadingPipe KEYWORD2 \ No newline at end of file diff --git a/libraries/RF24/nRF24L01.h b/libraries/RF24/nRF24L01.h new file mode 100644 index 0000000..132de94 --- /dev/null +++ b/libraries/RF24/nRF24L01.h @@ -0,0 +1,127 @@ +/* + 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 new file mode 100644 index 0000000..43ceaf5 --- /dev/null +++ b/libraries/RF24/tests/README @@ -0,0 +1,7 @@ +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 new file mode 100644 index 0000000..10d0336 --- /dev/null +++ b/libraries/RF24/tests/native/Jamfile @@ -0,0 +1,300 @@ +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 new file mode 100644 index 0000000..99c2cdf --- /dev/null +++ b/libraries/RF24/tests/native/pingpair_irq.pde @@ -0,0 +1,223 @@ +/* + 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 new file mode 100644 index 0000000..df6c46a --- /dev/null +++ b/libraries/RF24/tests/native/printf.h @@ -0,0 +1,33 @@ +/* + 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 new file mode 100644 index 0000000..18244ec --- /dev/null +++ b/libraries/RF24/tests/pingpair_blocking/Jamfile @@ -0,0 +1,219 @@ +# (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/libraries/RF24/tests/pingpair_blocking/pingpair_blocking.pde b/libraries/RF24/tests/pingpair_blocking/pingpair_blocking.pde new file mode 100644 index 0000000..004b421 --- /dev/null +++ b/libraries/RF24/tests/pingpair_blocking/pingpair_blocking.pde @@ -0,0 +1,273 @@ +/* + 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(48,49); + +// 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 = 5; + +// +// 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 (radio.available()) + { + // Fetch the payload, and see if this was the last one. + radio.read( &got_time, sizeof(unsigned long) ); + } + // 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(); + + // Spew it + printf("Got payload %lu...",got_time); + + // Send the final one back. + radio.write( &got_time, sizeof(unsigned long) ); + + // Now, resume listening so we catch the next packets. + radio.startListening(); + printf("Sent response.\n\r"); + + } + } + + // + // 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 \ No newline at end of file diff --git a/libraries/RF24/tests/pingpair_blocking/printf.h b/libraries/RF24/tests/pingpair_blocking/printf.h new file mode 100644 index 0000000..b2efd56 --- /dev/null +++ b/libraries/RF24/tests/pingpair_blocking/printf.h @@ -0,0 +1,37 @@ +/* + 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/tests/pingpair_blocking/runtest.py b/libraries/RF24/tests/pingpair_blocking/runtest.py new file mode 100755 index 0000000..0772f95 --- /dev/null +++ b/libraries/RF24/tests/pingpair_blocking/runtest.py @@ -0,0 +1,25 @@ +#!/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/libraries/RF24/tests/pingpair_blocking/runtests.sh b/libraries/RF24/tests/pingpair_blocking/runtests.sh new file mode 100755 index 0000000..e106448 --- /dev/null +++ b/libraries/RF24/tests/pingpair_blocking/runtests.sh @@ -0,0 +1,5 @@ +#!/bin/sh + +# Connect u0 to receiver, u1 to sender + +jam u0 u1 && expect test.ex diff --git a/libraries/RF24/tests/pingpair_blocking/test.ex b/libraries/RF24/tests/pingpair_blocking/test.ex new file mode 100755 index 0000000..ea992ad --- /dev/null +++ b/libraries/RF24/tests/pingpair_blocking/test.ex @@ -0,0 +1,11 @@ +#/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 new file mode 100644 index 0000000..18244ec --- /dev/null +++ b/libraries/RF24/tests/pingpair_test/Jamfile @@ -0,0 +1,219 @@ +# (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/libraries/RF24/tests/pingpair_test/pingpair_test.pde b/libraries/RF24/tests/pingpair_test/pingpair_test.pde new file mode 100644 index 0000000..7685ca8 --- /dev/null +++ b/libraries/RF24/tests/pingpair_test/pingpair_test.pde @@ -0,0 +1,435 @@ +/* + 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(7,8); + +// 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 = 5; + +// +// 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); + delay(50); + 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,0 ); + + // 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"); + } + + // Not powering down since radio is in standby mode + //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; + } + + } +} diff --git a/libraries/RF24/tests/pingpair_test/printf.h b/libraries/RF24/tests/pingpair_test/printf.h new file mode 100644 index 0000000..b2efd56 --- /dev/null +++ b/libraries/RF24/tests/pingpair_test/printf.h @@ -0,0 +1,37 @@ +/* + 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/tests/pingpair_test/runtest.py b/libraries/RF24/tests/pingpair_test/runtest.py new file mode 100755 index 0000000..45fb65c --- /dev/null +++ b/libraries/RF24/tests/pingpair_test/runtest.py @@ -0,0 +1,25 @@ +#!/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 new file mode 100755 index 0000000..4d02310 --- /dev/null +++ b/libraries/RF24/tests/pingpair_test/runtests.sh @@ -0,0 +1,21 @@ +#!/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/libraries/RF24/tests/pingpair_test/test.ex b/libraries/RF24/tests/pingpair_test/test.ex new file mode 100755 index 0000000..a14ffef --- /dev/null +++ b/libraries/RF24/tests/pingpair_test/test.ex @@ -0,0 +1,11 @@ +#/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 new file mode 100644 index 0000000..b94d3ef --- /dev/null +++ b/libraries/RF24/wikidoc.xslt @@ -0,0 +1,41 @@ + + + + + + + + === === + + + + + '''' + +Parameters: + + + + * '''': + + + + + +Returns: + +* + + +Warning: + + + + <pre> </pre> + + + + + + +