diff --git a/.clang-format b/.clang-format new file mode 100644 index 000000000..530535669 --- /dev/null +++ b/.clang-format @@ -0,0 +1,165 @@ +# See options listed at https://releases.llvm.org/12.0.1/tools/clang/docs/ClangFormatStyleOptions.html +--- +Language: Cpp +# BasedOnStyle: WebKit +AccessModifierOffset: -4 +AlignAfterOpenBracket: Align +AlignConsecutiveMacros: Consecutive +AlignConsecutiveAssignments: None +AlignConsecutiveBitFields: None +AlignConsecutiveDeclarations: None +AlignEscapedNewlines: Left +AlignOperands: DontAlign +AlignTrailingComments: true +AllowAllArgumentsOnNextLine: true +AllowAllConstructorInitializersOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortEnumsOnASingleLine: true +AllowShortBlocksOnASingleLine: Always +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: All +AllowShortLambdasOnASingleLine: All +AllowShortIfStatementsOnASingleLine: WithoutElse +AllowShortLoopsOnASingleLine: true +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: Yes +AttributeMacros: ["__capability", "__output", "__ununsed"] +BinPackArguments: true +BinPackParameters: true +BitFieldColonSpacing: Both +BraceWrapping: + AfterCaseLabel: false + AfterClass: true + AfterControlStatement: MultiLine + AfterEnum: true + AfterFunction: true + AfterNamespace: false + AfterStruct: true + AfterUnion: true + AfterExternBlock: false + BeforeCatch: true + BeforeElse: true + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: All +BreakBeforeConceptDeclarations: true +BreakBeforeBraces: Custom +BreakBeforeInheritanceComma: false +BreakInheritanceList: BeforeColon +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakStringLiterals: true +ColumnLimit: 0 +# CommentPragmas are a regex pattern indicating the comment is not be touched by the formatter +CommentPragmas: "^ Include gaurd .*" +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DeriveLineEnding: false +DerivePointerAlignment: false +DisableFormat: false +EmptyLineBeforeAccessModifier: Always +# --- +# only in v13+ +# EmptyLineAfterAccessModifier: Leave +# --- +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: ".*" + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: "(Test)?$" +IncludeIsMainSourceRegex: "" +# --- +# only in v13+ +# IndentAccessModifiers: false +# --- +IndentCaseLabels: true +IndentCaseBlocks: false +IndentGotoLabels: false +IndentPPDirectives: BeforeHash +IndentExternBlock: AfterExternBlock +IndentRequires: false +IndentWidth: 4 +IndentWrappedFunctionNames: false +InsertTrailingCommas: None +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: "" +MacroBlockEnd: "" +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: Inner +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 60 +PenaltyIndentedWhitespace: 0 +PointerAlignment: Left +# --- +# only in v13+ +# ReferenceAlignment: Right +# --- +ReflowComments: true +# --- +# only in v13+ +# ShortNamespaceLines: 0 +# --- +# Sort**** is about sorting include/using statements alphabetically +SortIncludes: false +SortUsingDeclarations: false +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: true +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceAroundPointerQualifiers: Default +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInConditionalStatement: false +SpacesInContainerLiterals: false +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +SpaceBeforeSquareBrackets: false +Standard: c++11 +StatementAttributeLikeMacros: [emit] +StatementMacros: [Q_UNUSED, QT_REQUIRE_VERSION] +TabWidth: 4 +UseCRLF: false +UseTab: Never +WhitespaceSensitiveMacros: + - PRIPSTR + - STRINGIZE + - PP_STRINGIZE + - BOOST_PP_STRINGIZE + - NS_SWIFT_NAME + - CF_SWIFT_NAME diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..b88e369ad --- /dev/null +++ b/.gitattributes @@ -0,0 +1,12 @@ +# Set the default behavior, in case people don't have core.autocrlf set. +* text=auto + +# Explicitly declare text files you want to always be normalized and converted +# to native line endings on checkout. +*.py text eol=lf +*.rst text eol=lf +*.sh text eol=lf +*.h text eol=lf +*.cpp text eol=lf +*.c text eol=lf +configure text eol=lf diff --git a/.github/workflows/build_arduino.yml b/.github/workflows/build_arduino.yml index 688236a40..52140bf16 100644 --- a/.github/workflows/build_arduino.yml +++ b/.github/workflows/build_arduino.yml @@ -12,25 +12,37 @@ on: - ".github/workflows/build_arduino.yml" - "examples/**" - "!examples/old_backups/**" +env: + # convenient variable used multiple times + SKETCHES_REPORTS: sketches-reports jobs: check_formatting: runs-on: ubuntu-latest steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Check code formatting - uses: per1234/artistic-style-action@main - with: - options-file-path: ./examples/examples_formatter.conf - name-patterns: | - - '*.ino' - - '*.cpp' - - '*.hpp' - - '*.h' - target-paths: | - - examples + - uses: actions/checkout@v3 + - uses: actions/setup-python@v3 + # Ubuntu 20.04.4 LTS reunners ship with clang-tools v12 + # - name: Install clang-tools + # uses: KyleMayes/install-llvm-action@v1 + # with: + # version: 12 + - name: Install linter python package + run: python3 -m pip install git+https://github.com/cpp-linter/cpp-linter-action@v1 + - name: run linter as a python package + id: linter + run: | + cpp-linter \ + --version=12 \ + --style=file \ + --tidy-checks='-*' \ + --files-changed-only='False' \ + --extensions=ino \ + --ignore='examples/old_backups' + - name: Linter checks failed? + if: steps.linter.outputs.checks-failed > 0 + run: exit 1 build: needs: check_formatting runs-on: ubuntu-latest @@ -83,7 +95,16 @@ jobs: - "arduino:megaavr:uno2018" # - "arduino:megaavr:nano4809" # board not found - "arduino:sam:arduino_due_x_dbg" - + # By default, don't generate size deltas data. + enable-deltas-report: + - false + # Generate size deltas data for this board + include: + - fqbn: arduino:avr:nano + enable-deltas-report: true + - fqbn: arduino:samd:mkrzero + enable-deltas-report: true + steps: - name: Checkout @@ -112,6 +133,17 @@ jobs: # - examples/old_backups/recipes/nordic_fob # - examples/old_backups/recipes/pingpair_maple fqbn: ${{ matrix.fqbn }} + enable-deltas-report: ${{ matrix.enable-deltas-report }} + sketches-report-path: ${{ env.SKETCHES_REPORTS }} + + # This step is needed to pass the size data to the report job + - name: Upload sketches report to workflow artifact + if: ${{ matrix.enable-deltas-report }} + uses: actions/upload-artifact@v2 + with: + name: ${{ env.SKETCHES_REPORTS }} + path: ${{ env.SKETCHES_REPORTS }} + attiny: needs: check_formatting runs-on: ubuntu-latest @@ -143,6 +175,13 @@ jobs: - ATTinyCore:avr:attiny1634 - ATTinyCore:avr:attiny1634opti - ATTinyCore:avr:attinyx313 + # By default, don't generate size deltas data. + enable-deltas-report: + - false + # Generate size deltas data for this board + include: + - fqbn: ATTinyCore:avr:attinyx5 + enable-deltas-report: true steps: - name: Checkout @@ -159,3 +198,29 @@ jobs: - examples/rf24_ATTiny/rf24ping85 - examples/rf24_ATTiny/timingSearch3pin fqbn: ${{ matrix.fqbn }} + enable-deltas-report: ${{ matrix.enable-deltas-report }} + sketches-report-path: ${{ env.SKETCHES_REPORTS }} + + # This step is needed to pass the size data to the report job + - name: Upload sketches report to workflow artifact + if: ${{ matrix.enable-deltas-report }} + uses: actions/upload-artifact@v2 + with: + name: ${{ env.SKETCHES_REPORTS }} + path: ${{ env.SKETCHES_REPORTS }} + + # When using a matrix to compile for multiple boards, it's necessary to use a separate job for the deltas report + report: + needs: [build, attiny] + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + steps: + - name: Download sketches reports artifact + uses: actions/download-artifact@v2 + with: + name: ${{ env.SKETCHES_REPORTS }} + path: ${{ env.SKETCHES_REPORTS }} + + - uses: arduino/report-size-deltas@v1 + with: + sketches-reports-source: ${{ env.SKETCHES_REPORTS }} \ No newline at end of file diff --git a/.github/workflows/build_linux.yml b/.github/workflows/build_linux.yml index 8ce3f16d2..9c5510e75 100644 --- a/.github/workflows/build_linux.yml +++ b/.github/workflows/build_linux.yml @@ -53,8 +53,35 @@ env: BUILD_TYPE: Release jobs: + check_formatting: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v3 + # Ubuntu 20.04.4 LTS reunners ship with clang-tools v12 + # - name: Install clang-tools + # uses: KyleMayes/install-llvm-action@v1 + # with: + # version: 12 + - name: Install linter python package + run: python3 -m pip install git+https://github.com/cpp-linter/cpp-linter-action@v1 + - name: run linter as a python package + id: linter + run: | + cpp-linter \ + --version=12 \ + --style=file \ + --tidy-checks='-*' \ + --files-changed-only='False' \ + --ignore='examples|examples_pico|utility/RPi/bcm2835.h|utility/RPi/bcm2835.c' + - name: Linter checks failed? + if: steps.linter.outputs.checks-failed > 0 + run: exit 1 + ####################### using Makefile ############################# build: + needs: check_formatting runs-on: ubuntu-latest strategy: @@ -144,6 +171,7 @@ jobs: ####################### using CMake ################################ using_cmake: + needs: check_formatting runs-on: ubuntu-latest env: diff --git a/.github/workflows/build_platformIO.yml b/.github/workflows/build_platformIO.yml index 00da9e103..9e6b6ac70 100644 --- a/.github/workflows/build_platformIO.yml +++ b/.github/workflows/build_platformIO.yml @@ -66,19 +66,28 @@ jobs: runs-on: ubuntu-latest steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Check code formatting - uses: per1234/artistic-style-action@main - with: - options-file-path: ./examples/examples_formatter.conf - name-patterns: | - - '*.ino' - - '*.cpp' - - '*.hpp' - - '*.h' - target-paths: | - - examples + - uses: actions/checkout@v3 + - uses: actions/setup-python@v3 + # Ubuntu 20.04.4 LTS reunners ship with clang-tools v12 + # - name: Install clang-tools + # uses: KyleMayes/install-llvm-action@v1 + # with: + # version: 12 + - name: Install linter python package + run: python3 -m pip install git+https://github.com/cpp-linter/cpp-linter-action@v1 + - name: run linter as a python package + id: linter + run: | + cpp-linter \ + --version=12 \ + --style=file \ + --tidy-checks='-*' \ + --files-changed-only='False' \ + --extensions=ino \ + --ignore='examples/old_backups' + - name: Linter checks failed? + if: steps.linter.outputs.checks-failed > 0 + run: exit 1 build: needs: [check_formatting, validate_lib_json] diff --git a/.github/workflows/build_rp2xxx.yml b/.github/workflows/build_rp2xxx.yml index 681f0ff56..6135c01f8 100644 --- a/.github/workflows/build_rp2xxx.yml +++ b/.github/workflows/build_rp2xxx.yml @@ -29,7 +29,34 @@ env: BUILD_TYPE: Release jobs: + check_formatting: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v3 + # Ubuntu 20.04.4 LTS reunners ship with clang-tools v12 + # - name: Install clang-tools + # uses: KyleMayes/install-llvm-action@v1 + # with: + # version: 12 + - name: Install linter python package + run: python3 -m pip install git+https://github.com/cpp-linter/cpp-linter-action@v1 + - name: run linter as a python package + id: linter + run: | + cpp-linter \ + --version=12 \ + --style=file \ + --tidy-checks='-*' \ + --files-changed-only='False' \ + --ignore='!examples_pico|' + - name: Linter checks failed? + if: steps.linter.outputs.checks-failed > 0 + run: exit 1 + build: + needs: check_formatting runs-on: ubuntu-latest strategy: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0218e2b4c..41f960580 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,7 +6,7 @@ These are the current requirements for getting your code included in RF24: - Definetly follow [PEP-8](https://www.python.org/dev/peps/pep-0008/) if it's Python code. -- Follow the [Arduino IDE formatting style](https://www.arduino.cc/en/Reference/StyleGuide) for Arduino examples +- Follow the [Arduino example formatting style](https://docs.arduino.cc/learn/contributions/arduino-writing-style-guide) for Arduino examples - Add [doxygen-compatible documentation](https://www.doxygen.nl/manual/docblocks.html) to any new functions you add, or update existing documentation if you change behaviour diff --git a/RF24.cpp b/RF24.cpp index 7d6f4b7f8..027072b97 100644 --- a/RF24.cpp +++ b/RF24.cpp @@ -15,88 +15,88 @@ void RF24::csn(bool mode) { - #if defined(RF24_TINY) +#if defined(RF24_TINY) if (ce_pin != csn_pin) { digitalWrite(csn_pin, mode); } else { if (mode == HIGH) { - PORTB |= (1<CSN HIGH + PORTB |= (1 << PINB2); // SCK->CSN HIGH delayMicroseconds(RF24_CSN_SETTLE_HIGH_DELAY); // allow csn to settle. } else { - PORTB &= ~(1<CSN LOW + PORTB &= ~(1 << PINB2); // SCK->CSN LOW delayMicroseconds(RF24_CSN_SETTLE_LOW_DELAY); // allow csn to settle } } // Return, CSN toggle complete return; - #elif defined (ARDUINO) && !defined(RF24_SPI_TRANSACTIONS) +#elif defined(ARDUINO) && !defined(RF24_SPI_TRANSACTIONS) // 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 - #if !defined(SOFTSPI) + #if !defined(SOFTSPI) // applies to SPI_UART and inherent hardware SPI - #if defined (RF24_SPI_PTR) + #if defined(RF24_SPI_PTR) _spi->setBitOrder(MSBFIRST); _spi->setDataMode(SPI_MODE0); - #if !defined(F_CPU) || F_CPU < 20000000 + #if !defined(F_CPU) || F_CPU < 20000000 _spi->setClockDivider(SPI_CLOCK_DIV2); - #elif F_CPU < 40000000 + #elif F_CPU < 40000000 _spi->setClockDivider(SPI_CLOCK_DIV4); - #elif F_CPU < 80000000 + #elif F_CPU < 80000000 _spi->setClockDivider(SPI_CLOCK_DIV8); - #elif F_CPU < 160000000 + #elif F_CPU < 160000000 _spi->setClockDivider(SPI_CLOCK_DIV16); - #elif F_CPU < 320000000 + #elif F_CPU < 320000000 _spi->setClockDivider(SPI_CLOCK_DIV32); - #elif F_CPU < 640000000 + #elif F_CPU < 640000000 _spi->setClockDivider(SPI_CLOCK_DIV64); - #elif F_CPU < 1280000000 + #elif F_CPU < 1280000000 _spi->setClockDivider(SPI_CLOCK_DIV128); - #else // F_CPU >= 1280000000 - #error "Unsupported CPU frequency. Please set correct SPI divider." - #endif // F_CPU to SPI_CLOCK_DIV translation + #else // F_CPU >= 1280000000 + #error "Unsupported CPU frequency. Please set correct SPI divider." + #endif // F_CPU to SPI_CLOCK_DIV translation - #else // !defined(RF24_SPI_PTR) + #else // !defined(RF24_SPI_PTR) _SPI.setBitOrder(MSBFIRST); _SPI.setDataMode(SPI_MODE0); - #if !defined(F_CPU) || F_CPU < 20000000 + #if !defined(F_CPU) || F_CPU < 20000000 _SPI.setClockDivider(SPI_CLOCK_DIV2); - #elif F_CPU < 40000000 + #elif F_CPU < 40000000 _SPI.setClockDivider(SPI_CLOCK_DIV4); - #elif F_CPU < 80000000 + #elif F_CPU < 80000000 _SPI.setClockDivider(SPI_CLOCK_DIV8); - #elif F_CPU < 160000000 + #elif F_CPU < 160000000 _SPI.setClockDivider(SPI_CLOCK_DIV16); - #elif F_CPU < 320000000 + #elif F_CPU < 320000000 _SPI.setClockDivider(SPI_CLOCK_DIV32); - #elif F_CPU < 640000000 + #elif F_CPU < 640000000 _SPI.setClockDivider(SPI_CLOCK_DIV64); - #elif F_CPU < 1280000000 + #elif F_CPU < 1280000000 _SPI.setClockDivider(SPI_CLOCK_DIV128); - #else // F_CPU >= 1280000000 - #error "Unsupported CPU frequency. Please set correct SPI divider." - #endif // F_CPU to SPI_CLOCK_DIV translation - #endif // !defined(RF24_SPI_PTR) - #endif // !defined(SOFTSPI) - - #elif defined (RF24_RPi) - if(!mode) + #else // F_CPU >= 1280000000 + #error "Unsupported CPU frequency. Please set correct SPI divider." + #endif // F_CPU to SPI_CLOCK_DIV translation + #endif // !defined(RF24_SPI_PTR) + #endif // !defined(SOFTSPI) + +#elif defined(RF24_RPi) + if (!mode) _SPI.chipSelect(csn_pin); - #endif // defined(RF24_RPi) +#endif // defined(RF24_RPi) - #if !defined(RF24_LINUX) +#if !defined(RF24_LINUX) digitalWrite(csn_pin, mode); delayMicroseconds(csDelay); - #else +#else static_cast(mode); // ignore -Wunused-parameter - #endif // !defined(RF24_LINUX) +#endif // !defined(RF24_LINUX) } /****************************************************************************/ @@ -113,17 +113,17 @@ void RF24::ce(bool level) inline void RF24::beginTransaction() { - #if defined (RF24_SPI_TRANSACTIONS) - #if defined (RF24_SPI_PTR) - #if defined (RF24_RP2) +#if defined(RF24_SPI_TRANSACTIONS) + #if defined(RF24_SPI_PTR) + #if defined(RF24_RP2) _spi->beginTransaction(spi_speed); - #else // ! defined (RF24_RP2) + #else // ! defined (RF24_RP2) _spi->beginTransaction(SPISettings(spi_speed, MSBFIRST, SPI_MODE0)); - #endif // ! defined (RF24_RP2) - #else // !defined(RF24_SPI_PTR) + #endif // ! defined (RF24_RP2) + #else // !defined(RF24_SPI_PTR) _SPI.beginTransaction(SPISettings(spi_speed, MSBFIRST, SPI_MODE0)); - #endif // !defined(RF24_SPI_PTR) - #endif // defined (RF24_SPI_TRANSACTIONS) + #endif // !defined(RF24_SPI_PTR) +#endif // defined (RF24_SPI_TRANSACTIONS) csn(LOW); } @@ -132,56 +132,64 @@ inline void RF24::beginTransaction() inline void RF24::endTransaction() { csn(HIGH); - #if defined (RF24_SPI_TRANSACTIONS) - #if defined (RF24_SPI_PTR) +#if defined(RF24_SPI_TRANSACTIONS) + #if defined(RF24_SPI_PTR) _spi->endTransaction(); - #else // !defined(RF24_SPI_PTR) + #else // !defined(RF24_SPI_PTR) _SPI.endTransaction(); - #endif // !defined(RF24_SPI_PTR) - #endif // defined (RF24_SPI_TRANSACTIONS) + #endif // !defined(RF24_SPI_PTR) +#endif // defined (RF24_SPI_TRANSACTIONS) } /****************************************************************************/ void RF24::read_register(uint8_t reg, uint8_t* buf, uint8_t len) { - #if defined (RF24_LINUX) || defined (RF24_RP2) +#if defined(RF24_LINUX) || defined(RF24_RP2) beginTransaction(); //configures the spi settings for RPi, locks mutex and setting csn low - uint8_t * prx = spi_rxbuff; - uint8_t * ptx = spi_txbuff; + uint8_t* prx = spi_rxbuff; + uint8_t* ptx = spi_txbuff; uint8_t size = static_cast(len + 1); // Add register value to transmit buffer *ptx++ = (R_REGISTER | reg); - while (len--){ *ptx++ = RF24_NOP; } // Dummy operation, just for reading + while (len--) { + *ptx++ = RF24_NOP; + } // Dummy operation, just for reading - #if defined (RF24_RP2) + #if defined(RF24_RP2) _spi->transfernb((const uint8_t*)spi_txbuff, spi_rxbuff, size); - #else // !defined (RF24_RP2) - _SPI.transfernb(reinterpret_cast(spi_txbuff), reinterpret_cast(spi_rxbuff), size); - #endif // !defined (RF24_RP2) + #else // !defined (RF24_RP2) + _SPI.transfernb(reinterpret_cast(spi_txbuff), reinterpret_cast(spi_rxbuff), size); + #endif // !defined (RF24_RP2) status = *prx++; // status is 1st byte of receive buffer // decrement before to skip status byte - while (--size) { *buf++ = *prx++; } + while (--size) { + *buf++ = *prx++; + } endTransaction(); // unlocks mutex and setting csn high - #else // !defined(RF24_LINUX) && !defined(RF24_RP2) +#else // !defined(RF24_LINUX) && !defined(RF24_RP2) beginTransaction(); - #if defined (RF24_SPI_PTR) + #if defined(RF24_SPI_PTR) status = _spi->transfer(R_REGISTER | reg); - while (len--) { *buf++ = _spi->transfer(0xFF); } + while (len--) { + *buf++ = _spi->transfer(0xFF); + } - #else // !defined(RF24_SPI_PTR) + #else // !defined(RF24_SPI_PTR) status = _SPI.transfer(R_REGISTER | reg); - while (len--) { *buf++ = _SPI.transfer(0xFF); } + while (len--) { + *buf++ = _SPI.transfer(0xFF); + } - #endif // !defined(RF24_SPI_PTR) + #endif // !defined(RF24_SPI_PTR) endTransaction(); - #endif // !defined(RF24_LINUX) && !defined(RF24_RP2) +#endif // !defined(RF24_LINUX) && !defined(RF24_RP2) } /****************************************************************************/ @@ -190,38 +198,38 @@ uint8_t RF24::read_register(uint8_t reg) { uint8_t result; - #if defined (RF24_LINUX) || defined (RF24_RP2) +#if defined(RF24_LINUX) || defined(RF24_RP2) beginTransaction(); - uint8_t * prx = spi_rxbuff; - uint8_t * ptx = spi_txbuff; + uint8_t* prx = spi_rxbuff; + uint8_t* ptx = spi_txbuff; *ptx++ = (R_REGISTER | reg); - *ptx++ = RF24_NOP ; // Dummy operation, just for reading + *ptx++ = RF24_NOP; // Dummy operation, just for reading - #if defined (RF24_RP2) + #if defined(RF24_RP2) _spi->transfernb((const uint8_t*)spi_txbuff, spi_rxbuff, 2); - #else // !defined(RF24_RP2) - _SPI.transfernb(reinterpret_cast(spi_txbuff), reinterpret_cast(spi_rxbuff), 2); - #endif // !defined(RF24_RP2) + #else // !defined(RF24_RP2) + _SPI.transfernb(reinterpret_cast(spi_txbuff), reinterpret_cast(spi_rxbuff), 2); + #endif // !defined(RF24_RP2) - status = *prx; // status is 1st byte of receive buffer - result = *++prx; // result is 2nd byte of receive buffer + status = *prx; // status is 1st byte of receive buffer + result = *++prx; // result is 2nd byte of receive buffer endTransaction(); - #else // !defined(RF24_LINUX) && !defined(RF24_RP2) +#else // !defined(RF24_LINUX) && !defined(RF24_RP2) beginTransaction(); - #if defined (RF24_SPI_PTR) + #if defined(RF24_SPI_PTR) status = _spi->transfer(R_REGISTER | reg); result = _spi->transfer(0xff); - #else // !defined(RF24_SPI_PTR) + #else // !defined(RF24_SPI_PTR) status = _SPI.transfer(R_REGISTER | reg); result = _SPI.transfer(0xff); - #endif // !defined(RF24_SPI_PTR) + #endif // !defined(RF24_SPI_PTR) endTransaction(); - #endif // !defined(RF24_LINUX) && !defined(RF24_RP2) +#endif // !defined(RF24_LINUX) && !defined(RF24_RP2) return result; } @@ -230,37 +238,43 @@ uint8_t RF24::read_register(uint8_t reg) void RF24::write_register(uint8_t reg, const uint8_t* buf, uint8_t len) { - #if defined (RF24_LINUX) || defined (RF24_RP2) +#if defined(RF24_LINUX) || defined(RF24_RP2) beginTransaction(); - uint8_t * prx = spi_rxbuff; - uint8_t * ptx = spi_txbuff; + uint8_t* prx = spi_rxbuff; + uint8_t* ptx = spi_txbuff; uint8_t size = static_cast(len + 1); // Add register value to transmit buffer *ptx++ = (W_REGISTER | (REGISTER_MASK & reg)); - while (len--) { *ptx++ = *buf++; } + while (len--) { + *ptx++ = *buf++; + } - #if defined (RF24_RP2) + #if defined(RF24_RP2) _spi->transfernb((const uint8_t*)spi_txbuff, spi_rxbuff, size); - #else // !defined(RF24_RP2) - _SPI.transfernb(reinterpret_cast(spi_txbuff), reinterpret_cast(spi_rxbuff), size); - #endif // !defined(RF24_RP2) + #else // !defined(RF24_RP2) + _SPI.transfernb(reinterpret_cast(spi_txbuff), reinterpret_cast(spi_rxbuff), size); + #endif // !defined(RF24_RP2) status = *prx; // status is 1st byte of receive buffer endTransaction(); - #else // !defined(RF24_LINUX) && !defined(RF24_RP2) +#else // !defined(RF24_LINUX) && !defined(RF24_RP2) beginTransaction(); - #if defined (RF24_SPI_PTR) + #if defined(RF24_SPI_PTR) status = _spi->transfer(W_REGISTER | reg); - while (len--) { _spi->transfer(*buf++); } + while (len--) { + _spi->transfer(*buf++); + } - #else // !defined(RF24_SPI_PTR) + #else // !defined(RF24_SPI_PTR) status = _SPI.transfer(W_REGISTER | reg); - while (len--) { _SPI.transfer(*buf++); } + while (len--) { + _SPI.transfer(*buf++); + } - #endif // !defined(RF24_SPI_PTR) + #endif // !defined(RF24_SPI_PTR) endTransaction(); - #endif // !defined(RF24_LINUX) && !defined(RF24_RP2) +#endif // !defined(RF24_LINUX) && !defined(RF24_RP2) } /****************************************************************************/ @@ -272,46 +286,46 @@ void RF24::write_register(uint8_t reg, uint8_t value, bool is_cmd_only) IF_SERIAL_DEBUG(printf_P(PSTR("write_register(%02x)\r\n"), reg)); } beginTransaction(); - #if defined (RF24_LINUX) +#if defined(RF24_LINUX) status = _SPI.transfer(W_REGISTER | reg); - #else // !defined(RF24_LINUX) || defined (RF24_RP2) - #if defined (RF24_SPI_PTR) +#else // !defined(RF24_LINUX) || defined (RF24_RP2) + #if defined(RF24_SPI_PTR) status = _spi->transfer(W_REGISTER | reg); - #else // !defined (RF24_SPI_PTR) + #else // !defined (RF24_SPI_PTR) status = _SPI.transfer(W_REGISTER | reg); - #endif // !defined (RF24_SPI_PTR) - #endif // !defined(RF24_LINUX) || defined(RF24_RP2) + #endif // !defined (RF24_SPI_PTR) +#endif // !defined(RF24_LINUX) || defined(RF24_RP2) endTransaction(); } else { IF_SERIAL_DEBUG(printf_P(PSTR("write_register(%02x,%02x)\r\n"), reg, value)); - #if defined (RF24_LINUX) || defined (RF24_RP2) +#if defined(RF24_LINUX) || defined(RF24_RP2) beginTransaction(); - uint8_t * prx = spi_rxbuff; - uint8_t * ptx = spi_txbuff; + uint8_t* prx = spi_rxbuff; + uint8_t* ptx = spi_txbuff; *ptx++ = (W_REGISTER | reg); *ptx = value; - #if defined (RF24_RP2) + #if defined(RF24_RP2) _spi->transfernb((const uint8_t*)spi_txbuff, spi_rxbuff, 2); - #else // !defined(RF24_RP2) - _SPI.transfernb(reinterpret_cast(spi_txbuff), reinterpret_cast(spi_rxbuff), 2); - #endif // !defined(RF24_RP2) + #else // !defined(RF24_RP2) + _SPI.transfernb(reinterpret_cast(spi_txbuff), reinterpret_cast(spi_rxbuff), 2); + #endif // !defined(RF24_RP2) status = *prx++; // status is 1st byte of receive buffer endTransaction(); - #else // !defined(RF24_LINUX) && !defined(RF24_RP2) +#else // !defined(RF24_LINUX) && !defined(RF24_RP2) beginTransaction(); - #if defined (RF24_SPI_PTR) + #if defined(RF24_SPI_PTR) status = _spi->transfer(W_REGISTER | reg); _spi->transfer(value); - #else // !defined(RF24_SPI_PTR) + #else // !defined(RF24_SPI_PTR) status = _SPI.transfer(W_REGISTER | reg); _SPI.transfer(value); - #endif // !defined(RF24_SPI_PTR) + #endif // !defined(RF24_SPI_PTR) endTransaction(); - #endif // !defined(RF24_LINUX) && !defined(RF24_RP2) +#endif // !defined(RF24_LINUX) && !defined(RF24_RP2) } } @@ -331,45 +345,57 @@ void RF24::write_payload(const void* buf, uint8_t data_len, const uint8_t writeT } //printf("[Writing %u bytes %u blanks]",data_len,blank_len); - IF_SERIAL_DEBUG(printf("[Writing %u bytes %u blanks]\n", data_len, blank_len); ); + IF_SERIAL_DEBUG(printf("[Writing %u bytes %u blanks]\n", data_len, blank_len);); - #if defined (RF24_LINUX) || defined (RF24_RP2) +#if defined(RF24_LINUX) || defined(RF24_RP2) beginTransaction(); - uint8_t * prx = spi_rxbuff; - uint8_t * ptx = spi_txbuff; + uint8_t* prx = spi_rxbuff; + uint8_t* ptx = spi_txbuff; uint8_t size; size = static_cast(data_len + blank_len + 1); // Add register value to transmit buffer - *ptx++ = writeType; - while (data_len--) { *ptx++ = *current++; } - while (blank_len--) { *ptx++ = 0; } + *ptx++ = writeType; + while (data_len--) { + *ptx++ = *current++; + } + while (blank_len--) { + *ptx++ = 0; + } - #if defined (RF24_RP2) + #if defined(RF24_RP2) _spi->transfernb((const uint8_t*)spi_txbuff, spi_rxbuff, size); - #else // !defined(RF24_RP2) - _SPI.transfernb(reinterpret_cast(spi_txbuff), reinterpret_cast(spi_rxbuff), size); - #endif // !defined(RF24_RP2) + #else // !defined(RF24_RP2) + _SPI.transfernb(reinterpret_cast(spi_txbuff), reinterpret_cast(spi_rxbuff), size); + #endif // !defined(RF24_RP2) status = *prx; // status is 1st byte of receive buffer endTransaction(); - #else // !defined(RF24_LINUX) && !defined(RF24_RP2) +#else // !defined(RF24_LINUX) && !defined(RF24_RP2) beginTransaction(); - #if defined (RF24_SPI_PTR) + #if defined(RF24_SPI_PTR) status = _spi->transfer(writeType); - while (data_len--) { _spi->transfer(*current++); } - while (blank_len--) { _spi->transfer(0); } + while (data_len--) { + _spi->transfer(*current++); + } + while (blank_len--) { + _spi->transfer(0); + } - #else // !defined(RF24_SPI_PTR) + #else // !defined(RF24_SPI_PTR) status = _SPI.transfer(writeType); - while (data_len--) { _SPI.transfer(*current++); } + while (data_len--) { + _SPI.transfer(*current++); + } - while (blank_len--) { _SPI.transfer(0); } + while (blank_len--) { + _SPI.transfer(0); + } - #endif // !defined(RF24_SPI_PTR) + #endif // !defined(RF24_SPI_PTR) endTransaction(); - #endif // !defined(RF24_LINUX) && !defined(RF24_RP2) +#endif // !defined(RF24_LINUX) && !defined(RF24_RP2) } /****************************************************************************/ @@ -389,53 +415,65 @@ void RF24::read_payload(void* buf, uint8_t data_len) //printf("[Reading %u bytes %u blanks]",data_len,blank_len); - IF_SERIAL_DEBUG(printf("[Reading %u bytes %u blanks]\n", data_len, blank_len); ); + IF_SERIAL_DEBUG(printf("[Reading %u bytes %u blanks]\n", data_len, blank_len);); - #if defined (RF24_LINUX) || defined (RF24_RP2) +#if defined(RF24_LINUX) || defined(RF24_RP2) beginTransaction(); - uint8_t * prx = spi_rxbuff; - uint8_t * ptx = spi_txbuff; + uint8_t* prx = spi_rxbuff; + uint8_t* ptx = spi_txbuff; uint8_t size; size = static_cast(data_len + blank_len + 1); // Add register value to transmit buffer - *ptx++ = R_RX_PAYLOAD; - while(--size) { *ptx++ = RF24_NOP; } + *ptx++ = R_RX_PAYLOAD; + while (--size) { + *ptx++ = RF24_NOP; + } size = static_cast(data_len + blank_len + 1); // Size has been lost during while, re affect - #if defined (RF24_RP2) + #if defined(RF24_RP2) _spi->transfernb((const uint8_t*)spi_txbuff, spi_rxbuff, size); - #else // !defined(RF24_RP2) - _SPI.transfernb(reinterpret_cast(spi_txbuff), reinterpret_cast(spi_rxbuff), size); - #endif // !defined(RF24_RP2) + #else // !defined(RF24_RP2) + _SPI.transfernb(reinterpret_cast(spi_txbuff), reinterpret_cast(spi_rxbuff), size); + #endif // !defined(RF24_RP2) status = *prx++; // 1st byte is status if (data_len > 0) { // Decrement before to skip 1st status byte - while (--data_len) { *current++ = *prx++; } + while (--data_len) { + *current++ = *prx++; + } *current = *prx; } endTransaction(); - #else // !defined(RF24_LINUX) && !defined(RF24_RP2) +#else // !defined(RF24_LINUX) && !defined(RF24_RP2) beginTransaction(); - #if defined (RF24_SPI_PTR) + #if defined(RF24_SPI_PTR) status = _spi->transfer(R_RX_PAYLOAD); - while (data_len--) { *current++ = _spi->transfer(0xFF); } + while (data_len--) { + *current++ = _spi->transfer(0xFF); + } - while (blank_len--) { _spi->transfer(0xFF); } + while (blank_len--) { + _spi->transfer(0xFF); + } - #else // !defined(RF24_SPI_PTR) + #else // !defined(RF24_SPI_PTR) status = _SPI.transfer(R_RX_PAYLOAD); - while (data_len--) { *current++ = _SPI.transfer(0xFF); } - while (blank_len--) { _SPI.transfer(0xff); } + while (data_len--) { + *current++ = _SPI.transfer(0xFF); + } + while (blank_len--) { + _SPI.transfer(0xff); + } - #endif // !defined(RF24_SPI_PTR) + #endif // !defined(RF24_SPI_PTR) endTransaction(); - #endif // !defined(RF24_LINUX) && !defined(RF24_RP2) +#endif // !defined(RF24_LINUX) && !defined(RF24_RP2) } /****************************************************************************/ @@ -468,7 +506,7 @@ uint8_t RF24::get_status(void) 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) & 0x07), (_status & _BV(TX_FULL)) ? 1 : 0); + (_status & _BV(TX_DS)) ? 1 : 0, (_status & _BV(MAX_RT)) ? 1 : 0, ((_status >> RX_P_NO) & 0x07), (_status & _BV(TX_FULL)) ? 1 : 0); } /****************************************************************************/ @@ -482,13 +520,9 @@ void RF24::print_observe_tx(uint8_t value) 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); - #if defined(RF24_LINUX) - printf("%s\t=", name); - #else // !defined(RF24_LINUX) - printf_P(PSTR(PRIPSTR"\t="),name); - #endif // !defined(RF24_LINUX) + printf_P(PSTR(PRIPSTR + "\t="), + name); while (qty--) { printf_P(PSTR(" 0x%02x"), read_register(reg++)); } @@ -500,37 +534,35 @@ void RF24::print_byte_register(const char* name, uint8_t reg, uint8_t qty) void RF24::print_address_register(const char* name, uint8_t reg, uint8_t qty) { - #if defined(RF24_LINUX) - printf("%s\t=", name); - #else // !defined(RF24_LINUX) - printf_P(PSTR(PRIPSTR"\t="), name); - #endif // !defined(RF24_LINUX) - uint8_t *buffer = new uint8_t[addr_width]; + printf_P(PSTR(PRIPSTR + "\t="), + name); while (qty--) { + uint8_t* buffer = new uint8_t[addr_width]; read_register(reg++ & REGISTER_MASK, buffer, addr_width); printf_P(PSTR(" 0x")); uint8_t* bufptr = buffer + addr_width; while (--bufptr >= buffer) { - printf_P(PSTR("%02x"), *bufptr); + printf_P(PSTR("%02x"), *bufptr); // NOLINT: clang-tidy seems to emit a false positive about zero-allocated memory here (*bufptr) } + delete[] buffer; } - delete[] buffer; printf_P(PSTR("\r\n")); } /****************************************************************************/ -uint8_t RF24::sprintf_address_register(char *out_buffer, uint8_t reg, uint8_t qty) +uint8_t RF24::sprintf_address_register(char* out_buffer, uint8_t reg, uint8_t qty) { uint8_t offset = 0; - uint8_t *read_buffer = new uint8_t[addr_width]; + uint8_t* read_buffer = new uint8_t[addr_width]; while (qty--) { read_register(reg++ & REGISTER_MASK, read_buffer, addr_width); uint8_t* bufptr = read_buffer + addr_width; while (--bufptr >= read_buffer) { offset += sprintf_P(out_buffer + offset, PSTR("%02X"), *bufptr); - } + } } delete[] read_buffer; return offset; @@ -540,8 +572,7 @@ uint8_t RF24::sprintf_address_register(char *out_buffer, uint8_t reg, uint8_t qt /****************************************************************************/ RF24::RF24(uint16_t _cepin, uint16_t _cspin, uint32_t _spi_speed) - :ce_pin(_cepin), csn_pin(_cspin), spi_speed(_spi_speed), payload_size(32), _is_p_variant(false), _is_p0_rx(false), addr_width(5), dynamic_payloads_enabled(true), - csDelay(5) + : ce_pin(_cepin), csn_pin(_cspin), spi_speed(_spi_speed), payload_size(32), _is_p_variant(false), _is_p0_rx(false), addr_width(5), dynamic_payloads_enabled(true), csDelay(5) { _init_obj(); } @@ -549,8 +580,7 @@ RF24::RF24(uint16_t _cepin, uint16_t _cspin, uint32_t _spi_speed) /****************************************************************************/ RF24::RF24(uint32_t _spi_speed) - :ce_pin(0xFFFF), csn_pin(0xFFFF), spi_speed(_spi_speed), payload_size(32), _is_p_variant(false), _is_p0_rx(false), addr_width(5), dynamic_payloads_enabled(true), - csDelay(5) + : ce_pin(0xFFFF), csn_pin(0xFFFF), spi_speed(_spi_speed), payload_size(32), _is_p_variant(false), _is_p0_rx(false), addr_width(5), dynamic_payloads_enabled(true), csDelay(5) { _init_obj(); } @@ -561,12 +591,12 @@ void RF24::_init_obj() { // Use a pointer on the Arduino platform - #if defined (RF24_SPI_PTR) && !defined (RF24_RP2) +#if defined(RF24_SPI_PTR) && !defined(RF24_RP2) _spi = &SPI; - #endif // defined (RF24_SPI_PTR) +#endif // defined (RF24_SPI_PTR) pipe0_reading_address[0] = 0; - if(spi_speed <= 35000){ //Handle old BCM2835 speed constants, default to RF24_SPI_SPEED + if (spi_speed <= 35000) { //Handle old BCM2835 speed constants, default to RF24_SPI_SPEED spi_speed = RF24_SPI_SPEED; } } @@ -610,34 +640,34 @@ uint8_t RF24::getPayloadSize(void) static const PROGMEM char rf24_datarate_e_str_0[] = "= 1 MBPS"; static const PROGMEM char rf24_datarate_e_str_1[] = "= 2 MBPS"; static const PROGMEM char rf24_datarate_e_str_2[] = "= 250 KBPS"; -static const PROGMEM char * const rf24_datarate_e_str_P[] = { - rf24_datarate_e_str_0, - rf24_datarate_e_str_1, - rf24_datarate_e_str_2, +static const PROGMEM char* const rf24_datarate_e_str_P[] = { + rf24_datarate_e_str_0, + rf24_datarate_e_str_1, + rf24_datarate_e_str_2, }; static const PROGMEM char rf24_model_e_str_0[] = "nRF24L01"; static const PROGMEM char rf24_model_e_str_1[] = "nRF24L01+"; -static const PROGMEM char * const rf24_model_e_str_P[] = { - rf24_model_e_str_0, - rf24_model_e_str_1, +static const PROGMEM char* const rf24_model_e_str_P[] = { + rf24_model_e_str_0, + rf24_model_e_str_1, }; static const PROGMEM char rf24_crclength_e_str_0[] = "= Disabled"; static const PROGMEM char rf24_crclength_e_str_1[] = "= 8 bits"; -static const PROGMEM char rf24_crclength_e_str_2[] = "= 16 bits" ; -static const PROGMEM char * const rf24_crclength_e_str_P[] = { - rf24_crclength_e_str_0, - rf24_crclength_e_str_1, - rf24_crclength_e_str_2, +static const PROGMEM char rf24_crclength_e_str_2[] = "= 16 bits"; +static const PROGMEM char* const rf24_crclength_e_str_P[] = { + rf24_crclength_e_str_0, + rf24_crclength_e_str_1, + rf24_crclength_e_str_2, }; static const PROGMEM char rf24_pa_dbm_e_str_0[] = "= PA_MIN"; static const PROGMEM char rf24_pa_dbm_e_str_1[] = "= PA_LOW"; static const PROGMEM char rf24_pa_dbm_e_str_2[] = "= PA_HIGH"; static const PROGMEM char rf24_pa_dbm_e_str_3[] = "= PA_MAX"; -static const PROGMEM 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 PROGMEM 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, }; #if defined(RF24_LINUX) @@ -645,11 +675,11 @@ 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, +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, }; #endif // defined(RF24_LINUX) @@ -657,19 +687,19 @@ static const PROGMEM char rf24_feature_e_str_on[] = "= Enabled"; static const PROGMEM char rf24_feature_e_str_allowed[] = "= Allowed"; static const PROGMEM char rf24_feature_e_str_open[] = " open "; static const PROGMEM char rf24_feature_e_str_closed[] = "closed"; -static const PROGMEM char * const rf24_feature_e_str_P[] = { +static const PROGMEM char* const rf24_feature_e_str_P[] = { rf24_crclength_e_str_0, rf24_feature_e_str_on, rf24_feature_e_str_allowed, rf24_feature_e_str_closed, - rf24_feature_e_str_open + rf24_feature_e_str_open, }; void RF24::printDetails(void) { #if defined(RF24_LINUX) - printf("================ SPI Configuration ================\n" ); + printf("================ SPI Configuration ================\n"); uint8_t bus_ce = static_cast(csn_pin % 10); uint8_t bus_numb = static_cast((csn_pin - bus_ce) / 10); printf("CSN Pin\t\t= /dev/spidev%d.%d\n", bus_numb, bus_ce); @@ -694,22 +724,23 @@ void RF24::printDetails(void) print_byte_register(PSTR("CONFIG\t"), NRF_CONFIG); print_byte_register(PSTR("DYNPD/FEATURE"), DYNPD, 2); - printf_P(PSTR("Data Rate\t" - PRIPSTR - "\r\n"), (char *)(pgm_read_ptr(&rf24_datarate_e_str_P[getDataRate()]))); - printf_P(PSTR("Model\t\t= " - PRIPSTR - "\r\n"), (char *)(pgm_read_ptr(&rf24_model_e_str_P[isPVariant()]))); - printf_P(PSTR("CRC Length\t" - PRIPSTR - "\r\n"), (char *)(pgm_read_ptr(&rf24_crclength_e_str_P[getCRCLength()]))); - printf_P(PSTR("PA Power\t" - PRIPSTR - "\r\n"), (char *)(pgm_read_ptr(&rf24_pa_dbm_e_str_P[getPALevel()]))); + printf_P(PSTR("Data Rate\t" PRIPSTR + "\r\n"), + (char*)(pgm_read_ptr(&rf24_datarate_e_str_P[getDataRate()]))); + printf_P(PSTR("Model\t\t= " PRIPSTR + "\r\n"), + (char*)(pgm_read_ptr(&rf24_model_e_str_P[isPVariant()]))); + printf_P(PSTR("CRC Length\t" PRIPSTR + "\r\n"), + (char*)(pgm_read_ptr(&rf24_crclength_e_str_P[getCRCLength()]))); + printf_P(PSTR("PA Power\t" PRIPSTR + "\r\n"), + (char*)(pgm_read_ptr(&rf24_pa_dbm_e_str_P[getPALevel()]))); printf_P(PSTR("ARC\t\t= %d\r\n"), getARC()); } -void RF24::printPrettyDetails(void) { +void RF24::printPrettyDetails(void) +{ #if defined(RF24_LINUX) printf("================ SPI Configuration ================\n"); @@ -727,18 +758,18 @@ void RF24::printPrettyDetails(void) { uint16_t frequency = static_cast(channel + 2400); printf_P(PSTR("Channel\t\t\t= %u (~ %u MHz)\r\n"), channel, frequency); - printf_P(PSTR("RF Data Rate\t\t" - PRIPSTR - "\r\n"), (char *)(pgm_read_ptr(&rf24_datarate_e_str_P[getDataRate()]))); - printf_P(PSTR("RF Power Amplifier\t" - PRIPSTR - "\r\n"), (char *)(pgm_read_ptr(&rf24_pa_dbm_e_str_P[getPALevel()]))); - printf_P(PSTR("RF Low Noise Amplifier\t" - PRIPSTR - "\r\n"), (char *)(pgm_read_ptr(&rf24_feature_e_str_P[(read_register(RF_SETUP) & 1) * 1]))); - printf_P(PSTR("CRC Length\t\t" - PRIPSTR - "\r\n"), (char *)(pgm_read_ptr(&rf24_crclength_e_str_P[getCRCLength()]))); + printf_P(PSTR("RF Data Rate\t\t" PRIPSTR + "\r\n"), + (char*)(pgm_read_ptr(&rf24_datarate_e_str_P[getDataRate()]))); + printf_P(PSTR("RF Power Amplifier\t" PRIPSTR + "\r\n"), + (char*)(pgm_read_ptr(&rf24_pa_dbm_e_str_P[getPALevel()]))); + printf_P(PSTR("RF Low Noise Amplifier\t" PRIPSTR + "\r\n"), + (char*)(pgm_read_ptr(&rf24_feature_e_str_P[(read_register(RF_SETUP) & 1) * 1]))); + printf_P(PSTR("CRC Length\t\t" PRIPSTR + "\r\n"), + (char*)(pgm_read_ptr(&rf24_crclength_e_str_P[getCRCLength()]))); printf_P(PSTR("Address Length\t\t= %d bytes\r\n"), (read_register(SETUP_AW) & 3) + 2); printf_P(PSTR("Static Payload Length\t= %d bytes\r\n"), getPayloadSize()); @@ -751,25 +782,26 @@ void RF24::printPrettyDetails(void) { printf_P(PSTR("Retry attempts made for\n last transmission\t= %d\r\n"), observeTx & 0x0F); uint8_t features = read_register(FEATURE); - printf_P(PSTR("Multicast\t\t" - PRIPSTR - "\r\n"), (char *)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast(features & _BV(EN_DYN_ACK)) * 2]))); - printf_P(PSTR("Custom ACK Payload\t" - PRIPSTR - "\r\n"), (char *)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast(features & _BV(EN_ACK_PAY)) * 1]))); + printf_P(PSTR("Multicast\t\t" PRIPSTR + "\r\n"), + (char*)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast(features & _BV(EN_DYN_ACK)) * 2]))); + printf_P(PSTR("Custom ACK Payload\t" PRIPSTR + "\r\n"), + (char*)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast(features & _BV(EN_ACK_PAY)) * 1]))); uint8_t dynPl = read_register(DYNPD); - printf_P(PSTR("Dynamic Payloads\t" - PRIPSTR - "\r\n"), (char *)(pgm_read_ptr(&rf24_feature_e_str_P[(dynPl && (features &_BV(EN_DPL))) * 1]))); + printf_P(PSTR("Dynamic Payloads\t" PRIPSTR + "\r\n"), + (char*)(pgm_read_ptr(&rf24_feature_e_str_P[(dynPl && (features & _BV(EN_DPL))) * 1]))); uint8_t autoAck = read_register(EN_AA); if (autoAck == 0x3F || autoAck == 0) { // all pipes have the same configuration about auto-ack feature - printf_P(PSTR("Auto Acknowledgment\t" - PRIPSTR - "\r\n"), (char *)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast(autoAck) * 1]))); - } else { + printf_P(PSTR("Auto Acknowledgment\t" PRIPSTR + "\r\n"), + (char*)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast(autoAck) * 1]))); + } + else { // representation per pipe printf_P(PSTR("Auto Acknowledgment\t= 0b%c%c%c%c%c%c\r\n"), static_cast(static_cast(autoAck & _BV(ENAA_P5)) + 48), @@ -787,9 +819,9 @@ void RF24::printPrettyDetails(void) { uint8_t openPipes = read_register(EN_RXADDR); for (uint8_t i = 0; i < 6; ++i) { bool isOpen = openPipes & _BV(i); - printf_P(PSTR("pipe %u (" - PRIPSTR - ") bound"), i, (char *)(pgm_read_ptr(&rf24_feature_e_str_P[isOpen + 3]))); + printf_P(PSTR("pipe %u (" PRIPSTR + ") bound"), + i, (char*)(pgm_read_ptr(&rf24_feature_e_str_P[isOpen + 3]))); if (i < 2) { print_address_register(PSTR(""), static_cast(RX_ADDR_P0 + i)); } @@ -801,8 +833,9 @@ void RF24::printPrettyDetails(void) { /****************************************************************************/ -uint16_t RF24::sprintfPrettyDetails(char *debugging_information) { - const char *format_string = PSTR( +uint16_t RF24::sprintfPrettyDetails(char* debugging_information) +{ + const char* format_string = PSTR( "================ SPI Configuration ================\n" "CSN Pin\t\t\t= %d\n" "CE Pin\t\t\t= %d\n" @@ -830,28 +863,23 @@ uint16_t RF24::sprintfPrettyDetails(char *debugging_information) { debugging_information, format_string, csn_pin, ce_pin, static_cast(spi_speed / 1000000), getChannel(), static_cast(getChannel() + 2400), - (char *)(pgm_read_ptr(&rf24_datarate_e_str_P[getDataRate()])), - (char *)(pgm_read_ptr(&rf24_pa_dbm_e_str_P[getPALevel()])), - (char *)(pgm_read_ptr(&rf24_feature_e_str_P[ - (read_register(RF_SETUP) & 1) * 1])), - (char *)(pgm_read_ptr(&rf24_crclength_e_str_P[getCRCLength()])), + (char*)(pgm_read_ptr(&rf24_datarate_e_str_P[getDataRate()])), + (char*)(pgm_read_ptr(&rf24_pa_dbm_e_str_P[getPALevel()])), + (char*)(pgm_read_ptr(&rf24_feature_e_str_P[(read_register(RF_SETUP) & 1) * 1])), + (char*)(pgm_read_ptr(&rf24_crclength_e_str_P[getCRCLength()])), ((read_register(SETUP_AW) & 3) + 2), getPayloadSize(), ((read_register(SETUP_RETR) >> ARD) * 250 + 250), (read_register(SETUP_RETR) & 0x0F), (read_register(OBSERVE_TX) >> 4), (read_register(OBSERVE_TX) & 0x0F), - (char *)(pgm_read_ptr(&rf24_feature_e_str_P[ - static_cast(read_register(FEATURE) & _BV(EN_DYN_ACK)) * 2])), - (char *)(pgm_read_ptr(&rf24_feature_e_str_P[ - static_cast(read_register(FEATURE) & _BV(EN_ACK_PAY)) * 1])), - (char *)(pgm_read_ptr(&rf24_feature_e_str_P[ - (read_register(DYNPD) && (read_register(FEATURE) & _BV(EN_DPL))) * 1]))); + (char*)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast(read_register(FEATURE) & _BV(EN_DYN_ACK)) * 2])), + (char*)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast(read_register(FEATURE) & _BV(EN_ACK_PAY)) * 1])), + (char*)(pgm_read_ptr(&rf24_feature_e_str_P[(read_register(DYNPD) && (read_register(FEATURE) & _BV(EN_DPL))) * 1]))); uint8_t autoAck = read_register(EN_AA); if (autoAck == 0x3F || autoAck == 0) { // all pipes have the same configuration about auto-ack feature offset += sprintf_P( debugging_information + offset, PSTR("" PRIPSTR ""), - (char *)(pgm_read_ptr(&rf24_feature_e_str_P[ - static_cast(autoAck) * 1]))); + (char*)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast(autoAck) * 1]))); } else { // representation per pipe @@ -872,8 +900,7 @@ uint16_t RF24::sprintfPrettyDetails(char *debugging_information) { for (uint8_t i = 0; i < 6; ++i) { offset += sprintf_P( debugging_information + offset, format_str3, - i, ((char *)(pgm_read_ptr(&rf24_feature_e_str_P[ - static_cast(openPipes & _BV(i)) + 3])))); + i, ((char*)(pgm_read_ptr(&rf24_feature_e_str_P[static_cast(openPipes & _BV(i)) + 3])))); if (i < 2) { offset += sprintf_address_register( debugging_information + offset, static_cast(RX_ADDR_P0 + i)); @@ -889,7 +916,7 @@ uint16_t RF24::sprintfPrettyDetails(char *debugging_information) { /****************************************************************************/ -void RF24::encodeRadioDetails(uint8_t *encoded_details) +void RF24::encodeRadioDetails(uint8_t* encoded_details) { uint8_t end = FEATURE + 1; for (uint8_t i = NRF_CONFIG; i < end; ++i) { @@ -912,7 +939,7 @@ void RF24::encodeRadioDetails(uint8_t *encoded_details) #endif // !defined(MINIMAL) /****************************************************************************/ -#if defined (RF24_SPI_PTR) || defined (DOXYGEN_FORCED) +#if defined(RF24_SPI_PTR) || defined(DOXYGEN_FORCED) // does not apply to RF24_LINUX bool RF24::begin(_SPI* spiBus) @@ -945,38 +972,52 @@ bool RF24::begin(uint16_t _cepin, uint16_t _cspin) bool RF24::begin(void) { - #if defined (RF24_LINUX) - #if defined (RF24_RPi) - switch(csn_pin) { // Ensure valid hardware CS pin - case 0: break; - case 1: break; +#if defined(RF24_LINUX) + #if defined(RF24_RPi) + switch (csn_pin) { // Ensure valid hardware CS pin + case 0: + break; + case 1: + break; // Allow BCM2835 enums for RPi - case 8: csn_pin = 0; break; - case 7: csn_pin = 1; break; - case 18: csn_pin = 10; break; // to make it work on SPI1 - case 17: csn_pin = 11; break; - case 16: csn_pin = 12; break; - default: csn_pin = 0; break; + case 8: + csn_pin = 0; + break; + case 7: + csn_pin = 1; + break; + case 18: + csn_pin = 10; + break; // to make it work on SPI1 + case 17: + csn_pin = 11; + break; + case 16: + csn_pin = 12; + break; + default: + csn_pin = 0; + break; } - #endif // RF24_RPi + #endif // RF24_RPi _SPI.begin(csn_pin, spi_speed); - #elif defined (XMEGA_D3) +#elif defined(XMEGA_D3) _spi->begin(csn_pin); - #elif defined (RF24_RP2) +#elif defined(RF24_RP2) _spi->begin(PICO_DEFAULT_SPI ? spi1 : spi0); - #else // using an Arduino platform || defined (LITTLEWIRE) +#else // using an Arduino platform || defined (LITTLEWIRE) - #if defined (RF24_SPI_PTR) + #if defined(RF24_SPI_PTR) _spi->begin(); - #else // !defined(RF24_SPI_PTR) + #else // !defined(RF24_SPI_PTR) _SPI.begin(); - #endif // !defined(RF24_SPI_PTR) + #endif // !defined(RF24_SPI_PTR) - #endif // !defined(XMEGA_D3) && !defined(RF24_LINUX) +#endif // !defined(XMEGA_D3) && !defined(RF24_LINUX) return _init_pins() && _init_radio(); } @@ -990,22 +1031,22 @@ bool RF24::_init_pins() return false; } - #if defined (RF24_LINUX) +#if defined(RF24_LINUX) - #if defined (MRAA) + #if defined(MRAA) GPIO(); gpio.begin(ce_pin, csn_pin); - #endif + #endif pinMode(ce_pin, OUTPUT); ce(LOW); delay(100); - #elif defined (LITTLEWIRE) +#elif defined(LITTLEWIRE) pinMode(csn_pin, OUTPUT); csn(HIGH); - #elif defined (XMEGA_D3) +#elif defined(XMEGA_D3) if (ce_pin != csn_pin) { pinMode(ce_pin, OUTPUT); }; @@ -1013,7 +1054,7 @@ bool RF24::_init_pins() csn(HIGH); delay(200); - #else // using an Arduino platform +#else // using an Arduino platform // Initialize pins if (ce_pin != csn_pin) { @@ -1024,10 +1065,10 @@ bool RF24::_init_pins() ce(LOW); csn(HIGH); - #if defined (__ARDUINO_X86__) + #if defined(__ARDUINO_X86__) delay(100); - #endif - #endif // !defined(XMEGA_D3) && !defined(LITTLEWIRE) && !defined(RF24_LINUX) + #endif +#endif // !defined(XMEGA_D3) && !defined(LITTLEWIRE) && !defined(RF24_LINUX) return true; // assuming pins are connected properly } @@ -1059,21 +1100,21 @@ bool RF24::_init_radio() toggle_features(); uint8_t after_toggle = read_register(FEATURE); _is_p_variant = before_toggle == after_toggle; - if (after_toggle){ - if (_is_p_variant){ + if (after_toggle) { + if (_is_p_variant) { // module did not experience power-on-reset (#401) toggle_features(); } // allow use of multicast parameter and dynamic payloads by default write_register(FEATURE, 0); } - ack_payloads_enabled = false; // ack payloads disabled by default - write_register(DYNPD, 0); // disable dynamic payloads by default (for all pipes) + ack_payloads_enabled = false; // ack payloads disabled by default + write_register(DYNPD, 0); // disable dynamic payloads by default (for all pipes) dynamic_payloads_enabled = false; - write_register(EN_AA, 0x3F); // enable auto-ack on all pipes - write_register(EN_RXADDR, 3); // only open RX pipes 0 & 1 - setPayloadSize(32); // set static payload size to 32 (max) bytes by default - setAddressWidth(5); // set default address length to (max) 5 bytes + write_register(EN_AA, 0x3F); // enable auto-ack on all pipes + write_register(EN_RXADDR, 3); // only open RX pipes 0 & 1 + setPayloadSize(32); // set static payload size to 32 (max) bytes by default + setAddressWidth(5); // set default address length to (max) 5 bytes // Set up default configuration. Callers can always change it later. // This channel should be universally safe and not bleed over into adjacent @@ -1084,7 +1125,6 @@ bool RF24::_init_radio() // Notice reset and flush is the last thing we do write_register(NRF_STATUS, _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT)); - // Flush buffers flush_rx(); flush_tx(); @@ -1096,7 +1136,7 @@ bool RF24::_init_radio() // 16-bit CRC (CRC required by auto-ack) // Do not write CE high so radio will remain in standby I mode // PTX should use only 22uA of power - write_register(NRF_CONFIG, (_BV(EN_CRC) | _BV(CRCO)) ); + write_register(NRF_CONFIG, (_BV(EN_CRC) | _BV(CRCO))); config_reg = read_register(NRF_CONFIG); powerUp(); @@ -1123,9 +1163,9 @@ bool RF24::isValid() void RF24::startListening(void) { - #if !defined(RF24_TINY) && !defined(LITTLEWIRE) +#if !defined(RF24_TINY) && !defined(LITTLEWIRE) powerUp(); - #endif +#endif config_reg |= _BV(PRIM_RX); write_register(NRF_CONFIG, config_reg); write_register(NRF_STATUS, _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT)); @@ -1134,12 +1174,14 @@ void RF24::startListening(void) // Restore the pipe0 address, if exists if (_is_p0_rx) { write_register(RX_ADDR_P0, pipe0_reading_address, addr_width); - } else { + } + else { closeReadingPipe(0); } } /****************************************************************************/ + static const PROGMEM uint8_t child_pipe_enable[] = {ERX_P0, ERX_P1, ERX_P2, ERX_P3, ERX_P4, ERX_P5}; @@ -1149,20 +1191,20 @@ void RF24::stopListening(void) //delayMicroseconds(100); delayMicroseconds(static_cast(txDelay)); - if (ack_payloads_enabled){ + if (ack_payloads_enabled) { flush_tx(); } config_reg = static_cast(config_reg & ~_BV(PRIM_RX)); write_register(NRF_CONFIG, config_reg); - #if defined(RF24_TINY) || defined(LITTLEWIRE) +#if defined(RF24_TINY) || defined(LITTLEWIRE) // for 3 pins solution TX mode is only left with additional powerDown/powerUp cycle if (ce_pin == csn_pin) { - powerDown(); - powerUp(); + powerDown(); + powerUp(); } - #endif +#endif write_register(EN_RXADDR, static_cast(read_register(EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[0])))); // Enable RX on pipe0 } @@ -1193,14 +1235,14 @@ void RF24::powerUp(void) } /******************************************************************/ -#if defined (FAILURE_HANDLING) || defined (RF24_LINUX) +#if defined(FAILURE_HANDLING) || defined(RF24_LINUX) void RF24::errNotify() { - #if defined (SERIAL_DEBUG) || defined (RF24_LINUX) + #if defined(SERIAL_DEBUG) || defined(RF24_LINUX) printf_P(PSTR("RF24 HARDWARE FAIL: Radio not responding, verify pin connections, wiring, etc.\r\n")); #endif - #if defined (FAILURE_HANDLING) + #if defined(FAILURE_HANDLING) failureDetected = 1; #else delay(5000); @@ -1216,22 +1258,22 @@ bool RF24::write(const void* buf, uint8_t len, const bool multicast) //Start Writing startFastWrite(buf, len, multicast); - //Wait until complete or failed - #if defined(FAILURE_HANDLING) || defined(RF24_LINUX) +//Wait until complete or failed +#if defined(FAILURE_HANDLING) || defined(RF24_LINUX) uint32_t timer = millis(); - #endif // defined(FAILURE_HANDLING) || defined(RF24_LINUX) +#endif // defined(FAILURE_HANDLING) || defined(RF24_LINUX) while (!(get_status() & (_BV(TX_DS) | _BV(MAX_RT)))) { - #if defined(FAILURE_HANDLING) || defined(RF24_LINUX) +#if defined(FAILURE_HANDLING) || defined(RF24_LINUX) if (millis() - timer > 95) { errNotify(); - #if defined(FAILURE_HANDLING) + #if defined(FAILURE_HANDLING) return 0; - #else + #else delay(100); - #endif + #endif } - #endif +#endif } ce(LOW); @@ -1251,6 +1293,7 @@ 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 @@ -1261,40 +1304,39 @@ bool RF24::writeBlocking(const void* buf, uint8_t len, uint32_t timeout) //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 + 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 + while ((get_status() & (_BV(TX_FULL)))) { // Blocking only if FIFO is full. This will loop and block until TX is successful or timeout - if (status & _BV(MAX_RT)) { // If MAX Retries have been reached - reUseTX(); // Set re-transmit and clear the MAX_RT interrupt flag + if (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 + return 0; // If this payload has exceeded the user-defined timeout, exit and return 0 } } - #if defined(FAILURE_HANDLING) || defined(RF24_LINUX) +#if defined(FAILURE_HANDLING) || defined(RF24_LINUX) if (millis() - timer > (timeout + 95)) { errNotify(); - #if defined(FAILURE_HANDLING) + #if defined(FAILURE_HANDLING) return 0; - #endif + #endif } - #endif - +#endif } //Start Writing - startFastWrite(buf, len, 0); // Write the payload if a buffer is clear + startFastWrite(buf, len, 0); // Write the payload if a buffer is clear - return 1; // Return 1 to indicate successful transmission + return 1; // Return 1 to indicate successful transmission } /****************************************************************************/ void RF24::reUseTX() { - write_register(NRF_STATUS, _BV(MAX_RT)); //Clear max retry flag + write_register(NRF_STATUS, _BV(MAX_RT)); //Clear max retry flag write_register(REUSE_TX_PL, RF24_NOP, true); - ce(LOW); //Re-Transfer packet + ce(LOW); //Re-Transfer packet ce(HIGH); } @@ -1307,26 +1349,26 @@ bool RF24::writeFast(const void* buf, uint8_t len, const bool multicast) //Return 0 so the user can control the retries and set a timer or failure counter if required //The radio will auto-clear everything in the FIFO as long as CE remains high - #if defined(FAILURE_HANDLING) || defined(RF24_LINUX) +#if defined(FAILURE_HANDLING) || defined(RF24_LINUX) uint32_t timer = millis(); - #endif +#endif //Blocking only if FIFO is full. This will loop and block until TX is successful or fail while ((get_status() & (_BV(TX_FULL)))) { if (status & _BV(MAX_RT)) { - return 0; //Return 0. The previous payload has not been retransmitted + return 0; //Return 0. The previous payload has not been retransmitted // From the user perspective, if you get a 0, just keep trying to send the same payload } - #if defined(FAILURE_HANDLING) || defined(RF24_LINUX) +#if defined(FAILURE_HANDLING) || defined(RF24_LINUX) if (millis() - timer > 95) { errNotify(); - #if defined(FAILURE_HANDLING) + #if defined(FAILURE_HANDLING) return 0; - #endif // defined(FAILURE_HANDLING) + #endif // defined(FAILURE_HANDLING) } - #endif +#endif } - startFastWrite(buf, len, multicast); // Start Writing + startFastWrite(buf, len, multicast); // Start Writing return 1; } @@ -1362,9 +1404,9 @@ bool 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); ce(HIGH); - #if !defined(F_CPU) || F_CPU > 20000000 +#if !defined(F_CPU) || F_CPU > 20000000 delayMicroseconds(10); - #endif +#endif ce(LOW); return !(status & _BV(TX_FULL)); } @@ -1381,27 +1423,27 @@ bool RF24::rxFifoFull() bool RF24::txStandBy() { - #if defined(FAILURE_HANDLING) || defined(RF24_LINUX) +#if defined(FAILURE_HANDLING) || defined(RF24_LINUX) uint32_t timeout = millis(); - #endif +#endif while (!(read_register(FIFO_STATUS) & _BV(TX_EMPTY))) { if (status & _BV(MAX_RT)) { write_register(NRF_STATUS, _BV(MAX_RT)); ce(LOW); - flush_tx(); //Non blocking, flush the data + flush_tx(); //Non blocking, flush the data return 0; } - #if defined(FAILURE_HANDLING) || defined(RF24_LINUX) +#if defined(FAILURE_HANDLING) || defined(RF24_LINUX) if (millis() - timeout > 95) { errNotify(); - #if defined(FAILURE_HANDLING) + #if defined(FAILURE_HANDLING) return 0; - #endif + #endif } - #endif +#endif } - ce(LOW); //Set STANDBY-I mode + ce(LOW); //Set STANDBY-I mode return 1; } @@ -1427,19 +1469,18 @@ bool RF24::txStandBy(uint32_t timeout, bool startTx) return 0; } } - #if defined(FAILURE_HANDLING) || defined(RF24_LINUX) +#if defined(FAILURE_HANDLING) || defined(RF24_LINUX) if (millis() - start > (timeout + 95)) { errNotify(); - #if defined(FAILURE_HANDLING) + #if defined(FAILURE_HANDLING) return 0; - #endif + #endif } - #endif +#endif } - ce(LOW); //Set STANDBY-I mode + ce(LOW); //Set STANDBY-I mode return 1; - } /****************************************************************************/ @@ -1500,7 +1541,6 @@ void RF24::read(void* buf, uint8_t len) //Clear the only applicable interrupt flags write_register(NRF_STATUS, _BV(RX_DR)); - } /****************************************************************************/ @@ -1529,6 +1569,7 @@ void RF24::openWritingPipe(uint64_t value) } /****************************************************************************/ + void RF24::openWritingPipe(const uint8_t* address) { // Note that AVR 8-bit uC's store this LSB first, and the NRF24L01(+) @@ -1538,6 +1579,7 @@ void RF24::openWritingPipe(const uint8_t* address) } /****************************************************************************/ + static const PROGMEM uint8_t child_pipe[] = {RX_ADDR_P0, RX_ADDR_P1, RX_ADDR_P2, RX_ADDR_P3, RX_ADDR_P4, RX_ADDR_P5}; @@ -1555,7 +1597,8 @@ void RF24::openReadingPipe(uint8_t child, uint64_t address) // For pipes 2-5, only write the LSB if (child < 2) { write_register(pgm_read_byte(&child_pipe[child]), reinterpret_cast(&address), addr_width); - } else { + } + else { write_register(pgm_read_byte(&child_pipe[child]), reinterpret_cast(&address), 1); } @@ -1574,11 +1617,11 @@ void RF24::setAddressWidth(uint8_t a_width) if (a_width) { write_register(SETUP_AW, static_cast(a_width % 4)); addr_width = static_cast((a_width % 4) + 2); - } else { + } + else { write_register(SETUP_AW, static_cast(0)); addr_width = static_cast(2); } - } /****************************************************************************/ @@ -1596,7 +1639,8 @@ void RF24::openReadingPipe(uint8_t child, const uint8_t* address) // For pipes 2-5, only write the LSB if (child < 2) { write_register(pgm_read_byte(&child_pipe[child]), address, addr_width); - } else { + } + else { write_register(pgm_read_byte(&child_pipe[child]), address, 1); } @@ -1604,7 +1648,6 @@ void RF24::openReadingPipe(uint8_t child, const uint8_t* address) // pipes at once. However, I thought it would make the calling code // more simple to do it this way. write_register(EN_RXADDR, static_cast(read_register(EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[child])))); - } } @@ -1624,13 +1667,13 @@ void RF24::closeReadingPipe(uint8_t pipe) void RF24::toggle_features(void) { beginTransaction(); - #if defined (RF24_SPI_PTR) +#if defined(RF24_SPI_PTR) status = _spi->transfer(ACTIVATE); _spi->transfer(0x73); - #else +#else status = _SPI.transfer(ACTIVATE); _SPI.transfer(0x73); - #endif +#endif endTransaction(); } @@ -1655,6 +1698,7 @@ void RF24::enableDynamicPayloads(void) } /****************************************************************************/ + void RF24::disableDynamicPayloads(void) { // Disables dynamic payload throughout the system. Also disables Ack Payloads @@ -1680,7 +1724,7 @@ void RF24::enableAckPayload(void) { // enable ack payloads and dynamic payload features - if (!ack_payloads_enabled){ + if (!ack_payloads_enabled) { write_register(FEATURE, read_register(FEATURE) | _BV(EN_ACK_PAY) | _BV(EN_DPL)); IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n", read_register(FEATURE))); @@ -1697,7 +1741,7 @@ void RF24::enableAckPayload(void) void RF24::disableAckPayload(void) { // disable ack payloads (leave dynamic payload features as is) - if (ack_payloads_enabled){ + if (ack_payloads_enabled) { write_register(FEATURE, static_cast(read_register(FEATURE) & ~_BV(EN_ACK_PAY))); IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n", read_register(FEATURE))); @@ -1723,7 +1767,7 @@ void RF24::enableDynamicAck(void) bool RF24::writeAckPayload(uint8_t pipe, const void* buf, uint8_t len) { - if (ack_payloads_enabled){ + if (ack_payloads_enabled) { const uint8_t* current = reinterpret_cast(buf); write_payload(current, len, W_ACK_PAYLOAD | (pipe & 0x07)); @@ -1750,12 +1794,13 @@ bool RF24::isPVariant(void) void RF24::setAutoAck(bool enable) { - if (enable){ + if (enable) { write_register(EN_AA, 0x3F); - }else{ + } + else { write_register(EN_AA, 0); // accommodate ACK payloads feature - if (ack_payloads_enabled){ + if (ack_payloads_enabled) { disableAckPayload(); } } @@ -1769,9 +1814,10 @@ void RF24::setAutoAck(uint8_t pipe, bool enable) uint8_t en_aa = read_register(EN_AA); if (enable) { en_aa |= static_cast(_BV(pipe)); - }else{ + } + else { en_aa = static_cast(en_aa & ~_BV(pipe)); - if (ack_payloads_enabled && !pipe){ + if (ack_payloads_enabled && !pipe) { disableAckPayload(); } } @@ -1806,7 +1852,6 @@ void RF24::setPALevel(uint8_t level, bool lnaEnable) uint8_t RF24::getPALevel(void) { - return (read_register(RF_SETUP) & (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH))) >> 1; } @@ -1814,7 +1859,6 @@ uint8_t RF24::getPALevel(void) uint8_t RF24::getARC(void) { - return read_register(OBSERVE_TX) & 0x0F; } @@ -1850,10 +1894,12 @@ rf24_datarate_e RF24::getDataRate(void) if (dr == _BV(RF_DR_LOW)) { // '10' = 250KBPS result = RF24_250KBPS; - } else if (dr == _BV(RF_DR_HIGH)) { + } + else if (dr == _BV(RF_DR_HIGH)) { // '01' = 2MBPS result = RF24_2MBPS; - } else { + } + else { // '00' = 1MBPS result = RF24_1MBPS; } @@ -1869,9 +1915,11 @@ void RF24::setCRCLength(rf24_crclength_e length) // switch uses RAM (evil!) if (length == RF24_CRC_DISABLED) { // Do nothing, we turned it off above. - } else if (length == RF24_CRC_8) { + } + else if (length == RF24_CRC_8) { config_reg |= _BV(EN_CRC); - } else { + } + else { config_reg |= _BV(EN_CRC); config_reg |= _BV(CRCO); } @@ -1889,7 +1937,8 @@ rf24_crclength_e RF24::getCRCLength(void) if (config_reg & _BV(EN_CRC) || AA) { if (config_reg & _BV(CRCO)) { result = RF24_CRC_16; - } else { + } + else { result = RF24_CRC_8; } } @@ -1916,7 +1965,7 @@ void RF24::startConstCarrier(rf24_pa_dbm_e level, uint8_t channel) { stopListening(); write_register(RF_SETUP, read_register(RF_SETUP) | _BV(CONT_WAVE) | _BV(PLL_LOCK)); - if (isPVariant()){ + if (isPVariant()) { setAutoAck(0); setRetries(0, 0); uint8_t dummy_buf[32]; @@ -1926,7 +1975,7 @@ void RF24::startConstCarrier(rf24_pa_dbm_e level, uint8_t channel) // use write_register() instead of openWritingPipe() to bypass // truncation of the address with the current RF24::addr_width value write_register(TX_ADDR, reinterpret_cast(&dummy_buf), 5); - flush_tx(); // so we can write to top level + flush_tx(); // so we can write to top level // use write_register() instead of write_payload() to bypass // truncation of the payload with the current RF24::payload_size value @@ -1938,7 +1987,7 @@ void RF24::startConstCarrier(rf24_pa_dbm_e level, uint8_t channel) setChannel(channel); IF_SERIAL_DEBUG(printf_P(PSTR("RF_SETUP=%02x\r\n"), read_register(RF_SETUP))); ce(HIGH); - if (isPVariant()){ + if (isPVariant()) { delay(1); // datasheet says 1 ms is ok in this instance ce(LOW); reUseTX(); @@ -1955,7 +2004,7 @@ void RF24::stopConstCarrier() * registers are set the chip does not react when setting CE low. If * however, both registers are set PWR_UP = 0 will turn TX mode off. */ - powerDown(); // per datasheet recommendation (just to be safe) + powerDown(); // per datasheet recommendation (just to be safe) write_register(RF_SETUP, static_cast(read_register(RF_SETUP) & ~_BV(CONT_WAVE) & ~_BV(PLL_LOCK))); ce(LOW); } @@ -1971,34 +2020,33 @@ void RF24::toggleAllPipes(bool isEnabled) uint8_t RF24::_data_rate_reg_value(rf24_datarate_e speed) { - #if !defined(F_CPU) || F_CPU > 20000000 +#if !defined(F_CPU) || F_CPU > 20000000 txDelay = 280; - #else //16Mhz Arduino - txDelay=85; - #endif +#else //16Mhz Arduino + txDelay = 85; +#endif if (speed == RF24_250KBPS) { - #if !defined(F_CPU) || F_CPU > 20000000 +#if !defined(F_CPU) || F_CPU > 20000000 txDelay = 505; - #else //16Mhz Arduino +#else //16Mhz Arduino txDelay = 155; - #endif +#endif // Must set the RF_DR_LOW to 1; RF_DR_HIGH (used to be RF_DR) is already 0 // Making it '10'. return static_cast(_BV(RF_DR_LOW)); } else if (speed == RF24_2MBPS) { - #if !defined(F_CPU) || F_CPU > 20000000 +#if !defined(F_CPU) || F_CPU > 20000000 txDelay = 240; - #else // 16Mhz Arduino +#else // 16Mhz Arduino txDelay = 65; - #endif +#endif // Set 2Mbs, RF_DR (RF_DR_HIGH) is set 1 // Making it '01' return static_cast(_BV(RF_DR_HIGH)); } // HIGH and LOW '00' is 1Mbs - our default return static_cast(0); - } /****************************************************************************/ diff --git a/RF24.h b/RF24.h index 023f99b01..987e1521b 100644 --- a/RF24.h +++ b/RF24.h @@ -17,13 +17,12 @@ #include "RF24_config.h" -#if defined (RF24_LINUX) || defined (LITTLEWIRE) +#if defined(RF24_LINUX) || defined(LITTLEWIRE) #include "utility/includes.h" #elif defined SOFTSPI #include #endif - /** * @defgroup PALevel Power Amplifier level * Power Amplifier level. The units dBm (decibel-milliwatts or dBmW) @@ -33,7 +32,8 @@ * - RF24::getPALevel() * @{ */ -typedef enum { +typedef enum +{ /** * (0) represents: * nRF24L01 | Si24R1 with
lnaEnabled = 1 | Si24R1 with
lnaEnabled = 0 @@ -77,7 +77,8 @@ typedef enum { * - RF24::getDataRate() * @{ */ -typedef enum { +typedef enum +{ /** (0) represents 1 Mbps */ RF24_1MBPS = 0, /** (1) represents 2 Mbps */ @@ -97,7 +98,8 @@ typedef enum { * - RF24::disableCRC() * @{ */ -typedef enum { +typedef enum +{ /** (0) represents no CRC checksum is used */ RF24_CRC_DISABLED = 0, /** (1) represents CRC 8 bit checksum is used */ @@ -110,37 +112,38 @@ typedef enum { * @} * @brief Driver class for nRF24L01(+) 2.4GHz Wireless Transceiver */ -class RF24 { +class RF24 +{ private: - #ifdef SOFTSPI +#ifdef SOFTSPI SoftSPI spi; - #elif defined (SPI_UART) +#elif defined(SPI_UART) SPIUARTClass uspi; - #endif +#endif - #if defined (RF24_LINUX) || defined (XMEGA_D3) || defined (RF24_RP2) /* XMEGA can use SPI class */ +#if defined(RF24_LINUX) || defined(XMEGA_D3) || defined(RF24_RP2) /* XMEGA can use SPI class */ SPI spi; - #endif // defined (RF24_LINUX) || defined (XMEGA_D3) - #if defined (RF24_SPI_PTR) +#endif // defined (RF24_LINUX) || defined (XMEGA_D3) +#if defined(RF24_SPI_PTR) _SPI* _spi; - #endif // defined (RF24_SPI_PTR) - #if defined (MRAA) +#endif // defined (RF24_SPI_PTR) +#if defined(MRAA) GPIO gpio; - #endif +#endif - uint16_t ce_pin; /* "Chip Enable" pin, activates the RX or TX role */ - uint16_t csn_pin; /* SPI Chip select */ + uint16_t ce_pin; /* "Chip Enable" pin, activates the RX or TX role */ + uint16_t csn_pin; /* SPI Chip select */ uint32_t spi_speed; /* SPI Bus Speed */ - #if defined (RF24_LINUX) || defined (XMEGA_D3) || defined (RF24_RP2) - 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) - #endif - uint8_t status; /* The status byte returned from every SPI transaction */ - uint8_t payload_size; /* Fixed size of payloads */ - uint8_t pipe0_reading_address[5]; /** Last address set on pipe 0 for reading. */ - uint8_t config_reg; /* For storing the value of the NRF_CONFIG register */ - bool _is_p_variant; /* For storing the result of testing the toggleFeatures() affect */ - bool _is_p0_rx; /* For keeping track of pipe 0's usage in user-triggered RX mode. */ +#if defined(RF24_LINUX) || defined(XMEGA_D3) || defined(RF24_RP2) + 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) +#endif + uint8_t status; /* The status byte returned from every SPI transaction */ + uint8_t payload_size; /* Fixed size of payloads */ + uint8_t pipe0_reading_address[5]; /* Last address set on pipe 0 for reading. */ + uint8_t config_reg; /* For storing the value of the NRF_CONFIG register */ + bool _is_p_variant; /* For storing the result of testing the toggleFeatures() affect */ + bool _is_p0_rx; /* For keeping track of pipe 0's usage in user-triggered RX mode. */ protected: /** @@ -180,7 +183,6 @@ class RF24 { uint8_t read_register(uint8_t reg); public: - /** * @name Primary public interface * @@ -220,9 +222,9 @@ class RF24 { */ RF24(uint32_t _spi_speed = RF24_SPI_SPEED); - #if defined (RF24_LINUX) +#if defined(RF24_LINUX) virtual ~RF24() {}; - #endif +#endif /** * Begin operation of the chip @@ -240,7 +242,7 @@ class RF24 { */ bool begin(void); - #if defined (RF24_SPI_PTR) || defined (DOXYGEN_FORCED) +#if defined(RF24_SPI_PTR) || defined(DOXYGEN_FORCED) /** * Same as begin(), but allows specifying a non-default SPI bus to use. * @@ -280,7 +282,7 @@ class RF24 { * @return same result as begin() */ bool begin(_SPI* spiBus, uint16_t _cepin, uint16_t _cspin); - #endif // defined (RF24_SPI_PTR) || defined (DOXYGEN_FORCED) +#endif // defined (RF24_SPI_PTR) || defined (DOXYGEN_FORCED) /** * Same as begin(), but allows dynamically specifying a CE pin @@ -650,7 +652,7 @@ class RF24 { * represent pipes 0-5 respectively. A `0` means the feature is disabled, and * a `1` means the feature is enabled. */ - uint16_t sprintfPrettyDetails(char *debugging_information); + uint16_t sprintfPrettyDetails(char* debugging_information); /** * Encode radio debugging information into an array of uint8_t. This function @@ -705,7 +707,7 @@ class RF24 { * | 40-41 | csn_pin | * | 42 | SPI speed (in MHz) or'd with (isPlusVariant << 4) | */ - void encodeRadioDetails(uint8_t *encoded_status); + void encodeRadioDetails(uint8_t* encoded_status); /** * Test whether there are bytes available to be read from the @@ -1271,7 +1273,7 @@ class RF24 { */ void closeReadingPipe(uint8_t pipe); - #if defined (FAILURE_HANDLING) +#if defined(FAILURE_HANDLING) /** * * If a failure has been detected, it usually indicates a hardware issue. By default the library @@ -1303,7 +1305,7 @@ class RF24 { * @endcode */ bool failureDetected; - #endif // defined (FAILURE_HANDLING) +#endif // defined (FAILURE_HANDLING) /**@}*/ /** @@ -1836,7 +1838,6 @@ class RF24 { bool isAckPayloadAvailable(void); private: - /**@}*/ /** * @name Low-level internal interface. @@ -1940,7 +1941,7 @@ class RF24 { */ uint8_t get_status(void); - #if !defined (MINIMAL) +#if !defined(MINIMAL) /** * Decode and print the given status to stdout @@ -1998,8 +1999,8 @@ class RF24 { * @param qty How many successive registers to print * @return The total number of characters written to the given buffer. */ - uint8_t sprintf_address_register(char *out_buffer, uint8_t reg, uint8_t qty = 1); - #endif + uint8_t sprintf_address_register(char* out_buffer, uint8_t reg, uint8_t qty = 1); +#endif /** * Turn on or off the special features of the chip @@ -2009,11 +2010,11 @@ class RF24 { */ void toggle_features(void); - #if defined (FAILURE_HANDLING) || defined (RF24_LINUX) +#if defined(FAILURE_HANDLING) || defined(RF24_LINUX) void errNotify(void); - #endif +#endif /** * @brief Manipulate the @ref Datarate and txDelay @@ -2033,10 +2034,8 @@ class RF24 { inline uint8_t _pa_level_reg_value(uint8_t level, bool lnaEnable); /**@}*/ - }; - /** * @example{lineno} examples/GettingStarted/GettingStarted.ino * Written by [2bndy5](http://github.com/2bndy5) in 2020 diff --git a/RF24_config.h b/RF24_config.h index 728c136fb..74b3baf22 100644 --- a/RF24_config.h +++ b/RF24_config.h @@ -32,55 +32,54 @@ * know your radio's hardware is, in fact, genuine and reliable. */ #if !defined(RF24_POWERUP_DELAY) -#define RF24_POWERUP_DELAY 5000 + #define RF24_POWERUP_DELAY 5000 #endif /**********************/ -#define rf24_max(a, b) (a>b?a:b) -#define rf24_min(a, b) (a b ? a : b) +#define rf24_min(a, b) (a < b ? a : b) /** @brief The default SPI speed (in Hz) */ #ifndef RF24_SPI_SPEED -#define RF24_SPI_SPEED 10000000 + #define RF24_SPI_SPEED 10000000 #endif //ATXMega -#if defined (__AVR_ATxmega64D3__) || defined (__AVR_ATxmega128D3__) || defined (__AVR_ATxmega192D3__) || defined (__AVR_ATxmega256D3__) || defined (__AVR_ATxmega384D3__) -// In order to be available both in Windows and Linux this should take presence here. +#if defined(__AVR_ATxmega64D3__) || defined(__AVR_ATxmega128D3__) || defined(__AVR_ATxmega192D3__) || defined(__AVR_ATxmega256D3__) || defined(__AVR_ATxmega384D3__) + // In order to be available both in Windows and Linux this should take presence here. #define XMEGA #define XMEGA_D3 #include "utility/ATXMegaD3/RF24_arch_config.h" // RaspberryPi rp2xxx-based devices (e.g. RPi Pico board) -#elif defined (PICO_BUILD) && !defined (ARDUINO) +#elif defined(PICO_BUILD) && !defined(ARDUINO) #include "utility/rp2/RF24_arch_config.h" -#elif (!defined (ARDUINO)) // Any non-arduino device is handled via configure/Makefile +#elif (!defined(ARDUINO)) // Any non-arduino device is handled via configure/Makefile // The configure script detects device and copies the correct includes.h file to /utility/includes.h // This behavior can be overridden by calling configure with respective parameters // The includes.h file defines either RF24_RPi, MRAA, LITTLEWIRE or RF24_SPIDEV and includes the correct RF24_arch_config.h file #include "utility/includes.h" //ATTiny -#elif defined (__AVR_ATtiny25__) || defined (__AVR_ATtiny45__) || defined (__AVR_ATtiny85__) || defined (__AVR_ATtiny24__) || defined (__AVR_ATtiny44__) || defined (__AVR_ATtiny84__) || defined (__AVR_ATtiny2313__) || defined (__AVR_ATtiny4313__) || defined (__AVR_ATtiny861__) || defined (__AVR_ATtinyX5__) || defined (__AVR_ATtinyX4__) || defined (__AVR_ATtinyX313__) || defined (__AVR_ATtinyX61__) +#elif defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) || defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny2313__) || defined(__AVR_ATtiny4313__) || defined(__AVR_ATtiny861__) || defined(__AVR_ATtinyX5__) || defined(__AVR_ATtinyX4__) || defined(__AVR_ATtinyX313__) || defined(__AVR_ATtinyX61__) #define RF24_TINY #include "utility/ATTiny/RF24_arch_config.h" -#elif defined (LITTLEWIRE) //LittleWire +#elif defined(LITTLEWIRE) //LittleWire #include "utility/LittleWire/RF24_arch_config.h" -#elif defined (TEENSYDUINO) //Teensy +#elif defined(TEENSYDUINO) //Teensy #include "utility/Teensy/RF24_arch_config.h" #else //Everything else #include - - #if defined (ARDUINO) && !defined (__arm__) && !defined (__ARDUINO_X86__) + #if defined(ARDUINO) && !defined(__arm__) && !defined(__ARDUINO_X86__) #if defined SPI_UART #include #define _SPI uspi - #elif defined (SOFTSPI) + #elif defined(SOFTSPI) // change these pins to your liking // #ifndef SOFT_SPI_MISO_PIN @@ -95,10 +94,10 @@ #define SOFT_SPI_SCK_PIN 7 #endif // SOFT_SPI_SCK_PIN - const uint8_t SPI_MODE = 0; +const uint8_t SPI_MODE = 0; #define _SPI spi - #elif defined (ARDUINO_SAM_DUE) + #elif defined(ARDUINO_SAM_DUE) #include #define _SPI SPI @@ -114,8 +113,8 @@ #include #include - #if defined (__arm__) || defined (__ARDUINO_X86__) - #if defined (__arm__) && defined (SPI_UART) + #if defined(__arm__) || defined(__ARDUINO_X86__) + #if defined(__arm__) && defined(SPI_UART) #include #define _SPI uspi @@ -125,68 +124,68 @@ #define RF24_SPI_PTR #endif // !defined (__arm__) || !defined (SPI_UART) - #elif !defined(__arm__) && !defined (__ARDUINO_X86__) - // fallback to unofficially supported Hardware (courtesy of ManiacBug) - extern HardwareSPI SPI; + #elif !defined(__arm__) && !defined(__ARDUINO_X86__) +// fallback to unofficially supported Hardware (courtesy of ManiacBug) +extern HardwareSPI SPI; #define _SPI HardwareSPI #define RF24_SPI_PTR #endif // !defined(__arm__) && !defined (__ARDUINO_X86__) #ifndef _BV - #define _BV(x) (1<<(x)) + #define _BV(x) (1 << (x)) #endif #endif // defined (ARDUINO) && !defined (__arm__) && !defined (__ARDUINO_X86__) #ifdef SERIAL_DEBUG - #define IF_SERIAL_DEBUG(x) ({x;}) + #define IF_SERIAL_DEBUG(x) ({ x; }) #else #define IF_SERIAL_DEBUG(x) #if defined(RF24_TINY) #define printf_P(...) - #endif // defined(RF24_TINY) + #endif // SERIAL_DEBUG - #if defined (__ARDUINO_X86__) + #if defined(__ARDUINO_X86__) #define printf_P printf - #define _BV(bit) (1<<(bit)) + #define _BV(bit) (1 << (bit)) #endif // defined (__ARDUINO_X86__) // Progmem is Arduino-specific - #if defined (ARDUINO_ARCH_ESP8266) || defined (ESP32) + #if defined(ARDUINO_ARCH_ESP8266) || defined(ESP32) #include #define PRIPSTR "%s" #ifndef pgm_read_ptr #define pgm_read_ptr(p) (*(p)) #endif - #elif defined (ARDUINO) && !defined (ESP_PLATFORM) && !defined (__arm__) && !defined (__ARDUINO_X86__) || defined (XMEGA) + #elif defined(ARDUINO) && !defined(ESP_PLATFORM) && !defined(__arm__) && !defined(__ARDUINO_X86__) || defined(XMEGA) #include #define PRIPSTR "%S" - #else // !defined (ARDUINO) || defined (ESP_PLATFORM) || defined (__arm__) || defined (__ARDUINO_X86__) && !defined (XMEGA) - #if !defined (ARDUINO) // This doesn't work on Arduino DUE - typedef char const char; - #else // Fill in pgm_read_byte that is used - #if defined (ARDUINO_ARCH_AVR) || defined (ARDUINO_ARCH_SAMD) || defined (ARDUINO_SAM_DUE) + #else // !defined (ARDUINO) || defined (ESP_PLATFORM) || defined (__arm__) || defined (__ARDUINO_X86__) && !defined (XMEGA) + #if !defined(ARDUINO) // This doesn't work on Arduino DUE +typedef char const char; + #else // Fill in pgm_read_byte that is used + #if defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_SAMD) || defined(ARDUINO_SAM_DUE) #include // added to ArduinoCore-sam (Due core) in 2013 #endif // Since the official arduino/ArduinoCore-samd repo switched to a unified API in 2016, // Serial.printf() is no longer defined in the unifying Arduino/ArduinoCore-API repo - #if defined (ARDUINO_ARCH_SAMD) && defined (ARDUINO_SAMD_ADAFRUIT) + #if defined(ARDUINO_ARCH_SAMD) && defined(ARDUINO_SAMD_ADAFRUIT) // it is defined if using the adafruit/ArduinoCore-samd repo #define printf_P Serial.printf #endif // defined (ARDUINO_ARCH_SAMD) #ifndef pgm_read_byte - #define pgm_read_byte(addr) (*(const unsigned char *)(addr)) + #define pgm_read_byte(addr) (*(const unsigned char*)(addr)) #endif #endif // !defined (ARDUINO) #ifndef prog_uint16_t - typedef uint16_t prog_uint16_t; +typedef uint16_t prog_uint16_t; #endif #ifndef PSTR #define PSTR(x) (x) @@ -211,9 +210,10 @@ #endif #endif // !defined (ARDUINO) || defined (ESP_PLATFORM) || defined (__arm__) || defined (__ARDUINO_X86__) && !defined (XMEGA) + #endif //Everything else -#if defined (SPI_HAS_TRANSACTION) && !defined (SPI_UART) && !defined (SOFTSPI) +#if defined(SPI_HAS_TRANSACTION) && !defined(SPI_UART) && !defined(SOFTSPI) #define RF24_SPI_TRANSACTIONS #endif // defined (SPI_HAS_TRANSACTION) && !defined (SPI_UART) && !defined (SOFTSPI) diff --git a/cmake/toolchains/clang.cmake b/cmake/toolchains/clang.cmake new file mode 100644 index 000000000..4795f407b --- /dev/null +++ b/cmake/toolchains/clang.cmake @@ -0,0 +1,9 @@ +set(CMAKE_SYSTEM_NAME Linux) +set(CMAKE_SYSTEM_PROCESSOR arm) + +set(triple arm-linux-gnueabihf) + +set(CMAKE_C_COMPILER clang) +set(CMAKE_C_COMPILER_TARGET ${triple}) +set(CMAKE_CXX_COMPILER clang++) +set(CMAKE_CXX_COMPILER_TARGET ${triple}) diff --git a/examples/.clang-format b/examples/.clang-format new file mode 100644 index 000000000..f95490cfd --- /dev/null +++ b/examples/.clang-format @@ -0,0 +1,145 @@ +# See: https://releases.llvm.org/11.0.1/tools/clang/docs/ClangFormatStyleOptions.html +--- +Language: Cpp +# LLVM is the default style setting, used when a configuration option is not set here +BasedOnStyle: LLVM +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveBitFields: false +AlignConsecutiveDeclarations: false +AlignConsecutiveMacros: false +AlignEscapedNewlines: DontAlign +AlignOperands: Align +AlignTrailingComments: true +AllowAllArgumentsOnNextLine: true +AllowAllConstructorInitializersOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: Always +AllowShortCaseLabelsOnASingleLine: true +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: Empty +AllowShortIfStatementsOnASingleLine: Always +AllowShortLambdasOnASingleLine: Empty +AllowShortLoopsOnASingleLine: true +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: No +BinPackArguments: true +BinPackParameters: true +# Only used when "BreakBeforeBraces" set to "Custom" +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterFunction: false + AfterNamespace: false + #AfterObjCDeclaration: + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false +# Java-specific +#BreakAfterJavaFieldAnnotations: +BreakBeforeBinaryOperators: NonAssignment +BreakBeforeBraces: Attach +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeColon +BreakInheritanceList: BeforeColon +BreakStringLiterals: false +ColumnLimit: 0 +# "" matches none +CommentPragmas: "" +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 2 +ContinuationIndentWidth: 2 +Cpp11BracedListStyle: false +DeriveLineEnding: true +DerivePointerAlignment: true +DisableFormat: false +# Docs say "Do not use this in config files". The default (LLVM 11.0.1) is "false". +#ExperimentalAutoDetectBinPacking: +FixNamespaceComments: false +ForEachMacros: [] +IncludeBlocks: Preserve +IncludeCategories: [] +# "" matches none +IncludeIsMainRegex: "" +IncludeIsMainSourceRegex: "" +IndentCaseBlocks: true +IndentCaseLabels: true +IndentExternBlock: Indent +IndentGotoLabels: false +IndentPPDirectives: None +IndentWidth: 2 +IndentWrappedFunctionNames: false +InsertTrailingCommas: None +# Java-specific +#JavaImportGroups: +# JavaScript-specific +#JavaScriptQuotes: +#JavaScriptWrapImports +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: "" +MacroBlockEnd: "" +# Set to a large number to effectively disable +MaxEmptyLinesToKeep: 100000 +NamespaceIndentation: None +NamespaceMacros: [] +# Objective C-specific +#ObjCBinPackProtocolList: +#ObjCBlockIndentWidth: +#ObjCBreakBeforeNestedBlockParam: +#ObjCSpaceAfterProperty: +#ObjCSpaceBeforeProtocolList +PenaltyBreakAssignment: 1 +PenaltyBreakBeforeFirstCallParameter: 1 +PenaltyBreakComment: 1 +PenaltyBreakFirstLessLess: 1 +PenaltyBreakString: 1 +PenaltyBreakTemplateDeclaration: 1 +PenaltyExcessCharacter: 1 +PenaltyReturnTypeOnItsOwnLine: 1 +# Used as a fallback if alignment style can't be detected from code (DerivePointerAlignment: true) +PointerAlignment: Right +RawStringFormats: [] +ReflowComments: false +SortIncludes: false +SortUsingDeclarations: false +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: false +SpacesInCStyleCastParentheses: false +SpacesInConditionalStatement: false +SpacesInContainerLiterals: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Auto +StatementMacros: [] +TabWidth: 2 +TypenameMacros: [] +# Default to LF if line endings can't be detected from the content (DeriveLineEnding). +UseCRLF: false +UseTab: Never +WhitespaceSensitiveMacros: [] diff --git a/examples/AcknowledgementPayloads/AcknowledgementPayloads.ino b/examples/AcknowledgementPayloads/AcknowledgementPayloads.ino index bc2cbc238..7f5d445e0 100644 --- a/examples/AcknowledgementPayloads/AcknowledgementPayloads.ino +++ b/examples/AcknowledgementPayloads/AcknowledgementPayloads.ino @@ -16,17 +16,17 @@ #include "RF24.h" // instantiate an object for the nRF24L01 transceiver -RF24 radio(7, 8); // using pin 7 for the CE pin, and pin 8 for the CSN pin +RF24 radio(7, 8); // using pin 7 for the CE pin, and pin 8 for the CSN pin // an identifying device destination // Let these addresses be used for the pair -uint8_t address[][6] = {"1Node", "2Node"}; +uint8_t address[][6] = { "1Node", "2Node" }; // It is very helpful to think of an address as a path instead of as // an identifying device destination // to use different addresses on a pair of radios, we need a variable to // uniquely identify which address this radio will use to transmit -bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit +bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit // Used to control whether this node is sending or receiving bool role = false; // true = TX role, false = RX role @@ -36,7 +36,7 @@ bool role = false; // true = TX role, false = RX role // on every successful transmission. // Make a data structure to store the entire payload of different datatypes struct PayloadStruct { - char message[7]; // only using 6 characters for TX & ACK payloads + char message[7]; // only using 6 characters for TX & ACK payloads uint8_t counter; }; PayloadStruct payload; @@ -51,7 +51,7 @@ void setup() { // initialize the transceiver on the SPI bus if (!radio.begin()) { Serial.println(F("radio hardware is not responding!!")); - while (1) {} // hold in infinite loop + while (1) {} // hold in infinite loop } // print example's introductory prompt @@ -73,42 +73,41 @@ void setup() { // Set the PA Level low to try preventing power supply related problems // because these examples are likely run with nodes in close proximity to // each other. - radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. + radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. // to use ACK payloads, we need to enable dynamic payload lengths (for all nodes) - radio.enableDynamicPayloads(); // ACK payloads are dynamically sized + radio.enableDynamicPayloads(); // ACK payloads are dynamically sized // Acknowledgement packets have no payloads by default. We need to enable // this feature for all nodes (TX & RX) to use ACK payloads. radio.enableAckPayload(); // set the TX address of the RX node into the TX pipe - radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 + radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 // set the RX address of the TX node into a RX pipe - radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 + radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 // additional setup specific to the node's role if (role) { // setup the TX payload - memcpy(payload.message, "Hello ", 6); // set the payload message - radio.stopListening(); // put radio in TX mode + memcpy(payload.message, "Hello ", 6); // set the payload message + radio.stopListening(); // put radio in TX mode } else { // setup the ACK payload & load the first response into the FIFO - memcpy(payload.message, "World ", 6); // set the payload message + memcpy(payload.message, "World ", 6); // set the payload message // load the payload for the first received transmission on pipe 0 radio.writeAckPayload(1, &payload, sizeof(payload)); - radio.startListening(); // put radio in RX mode + radio.startListening(); // put radio in RX mode } // For debugging info // printf_begin(); // needed only once for printing details // radio.printDetails(); // (smaller) function that prints raw register values // radio.printPrettyDetails(); // (larger) function that prints human readable data - } void loop() { @@ -116,39 +115,39 @@ void loop() { if (role) { // This device is a TX node - unsigned long start_timer = micros(); // start the timer - bool report = radio.write(&payload, sizeof(payload)); // transmit & save the report - unsigned long end_timer = micros(); // end the timer + unsigned long start_timer = micros(); // start the timer + bool report = radio.write(&payload, sizeof(payload)); // transmit & save the report + unsigned long end_timer = micros(); // end the timer if (report) { - Serial.print(F("Transmission successful! ")); // payload was delivered + Serial.print(F("Transmission successful! ")); // payload was delivered Serial.print(F("Time to transmit = ")); - Serial.print(end_timer - start_timer); // print the timer result + Serial.print(end_timer - start_timer); // print the timer result Serial.print(F(" us. Sent: ")); - Serial.print(payload.message); // print the outgoing message - Serial.print(payload.counter); // print the outgoing counter + Serial.print(payload.message); // print the outgoing message + Serial.print(payload.counter); // print the outgoing counter uint8_t pipe; - if (radio.available(&pipe)) { // is there an ACK payload? grab the pipe number that received it + if (radio.available(&pipe)) { // is there an ACK payload? grab the pipe number that received it PayloadStruct received; - radio.read(&received, sizeof(received)); // get incoming ACK payload + radio.read(&received, sizeof(received)); // get incoming ACK payload Serial.print(F(" Recieved ")); - Serial.print(radio.getDynamicPayloadSize()); // print incoming payload size + Serial.print(radio.getDynamicPayloadSize()); // print incoming payload size Serial.print(F(" bytes on pipe ")); - Serial.print(pipe); // print pipe number that received the ACK + Serial.print(pipe); // print pipe number that received the ACK Serial.print(F(": ")); - Serial.print(received.message); // print incoming message - Serial.println(received.counter); // print incoming counter + Serial.print(received.message); // print incoming message + Serial.println(received.counter); // print incoming counter // save incoming counter & increment for next outgoing payload.counter = received.counter + 1; } else { - Serial.println(F(" Recieved: an empty ACK packet")); // empty ACK packet received + Serial.println(F(" Recieved: an empty ACK packet")); // empty ACK packet received } } else { - Serial.println(F("Transmission failed or timed out")); // payload was not delivered + Serial.println(F("Transmission failed or timed out")); // payload was not delivered } // to make this example readable in the serial monitor @@ -158,27 +157,27 @@ void loop() { // This device is a RX node uint8_t pipe; - if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it - uint8_t bytes = radio.getDynamicPayloadSize(); // get the size of the payload + if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it + uint8_t bytes = radio.getDynamicPayloadSize(); // get the size of the payload PayloadStruct received; - radio.read(&received, sizeof(received)); // get incoming payload + radio.read(&received, sizeof(received)); // get incoming payload Serial.print(F("Received ")); - Serial.print(bytes); // print the size of the payload + Serial.print(bytes); // print the size of the payload Serial.print(F(" bytes on pipe ")); - Serial.print(pipe); // print the pipe number + Serial.print(pipe); // print the pipe number Serial.print(F(": ")); - Serial.print(received.message); // print incoming message - Serial.print(received.counter); // print incoming counter + Serial.print(received.message); // print incoming message + Serial.print(received.counter); // print incoming counter Serial.print(F(" Sent: ")); - Serial.print(payload.message); // print outgoing message - Serial.println(payload.counter); // print outgoing counter + Serial.print(payload.message); // print outgoing message + Serial.println(payload.counter); // print outgoing counter // save incoming counter & increment for next outgoing payload.counter = received.counter + 1; // load the payload for the first received transmission on pipe 0 radio.writeAckPayload(1, &payload, sizeof(payload)); } - } // role + } // role if (Serial.available()) { // change the role via the serial monitor @@ -190,19 +189,19 @@ void loop() { role = true; Serial.println(F("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK")); - memcpy(payload.message, "Hello ", 6); // change payload message - radio.stopListening(); // this also discards any unused ACK payloads + memcpy(payload.message, "Hello ", 6); // change payload message + radio.stopListening(); // this also discards any unused ACK payloads } else if (c == 'R' && role) { // Become the RX node role = false; Serial.println(F("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK")); - memcpy(payload.message, "World ", 6); // change payload message + memcpy(payload.message, "World ", 6); // change payload message // load the payload for the first received transmission on pipe 0 radio.writeAckPayload(1, &payload, sizeof(payload)); radio.startListening(); } } -} // loop \ No newline at end of file +} // loop diff --git a/examples/GettingStarted/GettingStarted.ino b/examples/GettingStarted/GettingStarted.ino index d38ed9969..c0ca324ed 100644 --- a/examples/GettingStarted/GettingStarted.ino +++ b/examples/GettingStarted/GettingStarted.ino @@ -15,16 +15,16 @@ #include "RF24.h" // instantiate an object for the nRF24L01 transceiver -RF24 radio(7, 8); // using pin 7 for the CE pin, and pin 8 for the CSN pin +RF24 radio(7, 8); // using pin 7 for the CE pin, and pin 8 for the CSN pin // Let these addresses be used for the pair -uint8_t address[][6] = {"1Node", "2Node"}; +uint8_t address[][6] = { "1Node", "2Node" }; // It is very helpful to think of an address as a path instead of as // an identifying device destination // to use different addresses on a pair of radios, we need a variable to // uniquely identify which address this radio will use to transmit -bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit +bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit // Used to control whether this node is sending or receiving bool role = false; // true = TX role, false = RX role @@ -44,7 +44,7 @@ void setup() { // initialize the transceiver on the SPI bus if (!radio.begin()) { Serial.println(F("radio hardware is not responding!!")); - while (1) {} // hold in infinite loop + while (1) {} // hold in infinite loop } // print example's introductory prompt @@ -70,19 +70,19 @@ void setup() { // save on transmission time by setting the radio to only transmit the // number of bytes we need to transmit a float - radio.setPayloadSize(sizeof(payload)); // float datatype occupies 4 bytes + radio.setPayloadSize(sizeof(payload)); // float datatype occupies 4 bytes // set the TX address of the RX node into the TX pipe - radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 + radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 // set the RX address of the TX node into a RX pipe - radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 + radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 // additional setup specific to the node's role if (role) { radio.stopListening(); // put radio in TX mode } else { - radio.startListening(); // put radio in RX mode + radio.startListening(); // put radio in RX mode } // For debugging info @@ -90,26 +90,26 @@ void setup() { // radio.printDetails(); // (smaller) function that prints raw register values // radio.printPrettyDetails(); // (larger) function that prints human readable data -} // setup +} // setup void loop() { if (role) { // This device is a TX node - unsigned long start_timer = micros(); // start the timer - bool report = radio.write(&payload, sizeof(float)); // transmit & save the report - unsigned long end_timer = micros(); // end the timer + unsigned long start_timer = micros(); // start the timer + bool report = radio.write(&payload, sizeof(float)); // transmit & save the report + unsigned long end_timer = micros(); // end the timer if (report) { - Serial.print(F("Transmission successful! ")); // payload was delivered + Serial.print(F("Transmission successful! ")); // payload was delivered Serial.print(F("Time to transmit = ")); - Serial.print(end_timer - start_timer); // print the timer result + Serial.print(end_timer - start_timer); // print the timer result Serial.print(F(" us. Sent: ")); - Serial.println(payload); // print payload sent - payload += 0.01; // increment float payload + Serial.println(payload); // print payload sent + payload += 0.01; // increment float payload } else { - Serial.println(F("Transmission failed or timed out")); // payload was not delivered + Serial.println(F("Transmission failed or timed out")); // payload was not delivered } // to make this example readable in the serial monitor @@ -119,17 +119,17 @@ void loop() { // This device is a RX node uint8_t pipe; - if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it - uint8_t bytes = radio.getPayloadSize(); // get the size of the payload - radio.read(&payload, bytes); // fetch payload from FIFO + if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it + uint8_t bytes = radio.getPayloadSize(); // get the size of the payload + radio.read(&payload, bytes); // fetch payload from FIFO Serial.print(F("Received ")); - Serial.print(bytes); // print the size of the payload + Serial.print(bytes); // print the size of the payload Serial.print(F(" bytes on pipe ")); - Serial.print(pipe); // print the pipe number + Serial.print(pipe); // print the pipe number Serial.print(F(": ")); - Serial.println(payload); // print the payload's value + Serial.println(payload); // print the payload's value } - } // role + } // role if (Serial.available()) { // change the role via the serial monitor @@ -151,4 +151,4 @@ void loop() { } } -} // loop +} // loop diff --git a/examples/InterruptConfigure/InterruptConfigure.ino b/examples/InterruptConfigure/InterruptConfigure.ino index 5d616edba..0de7bc971 100644 --- a/examples/InterruptConfigure/InterruptConfigure.ino +++ b/examples/InterruptConfigure/InterruptConfigure.ino @@ -18,20 +18,20 @@ #include "RF24.h" // We will be using the nRF24L01's IRQ pin for this example -#define IRQ_PIN 2 // this needs to be a digital input capable pin -volatile bool wait_for_event = false; // used to wait for an IRQ event to trigger +#define IRQ_PIN 2 // this needs to be a digital input capable pin +volatile bool wait_for_event = false; // used to wait for an IRQ event to trigger // instantiate an object for the nRF24L01 transceiver -RF24 radio(7, 8); // using pin 7 for the CE pin, and pin 8 for the CSN pin +RF24 radio(7, 8); // using pin 7 for the CE pin, and pin 8 for the CSN pin // Let these addresses be used for the pair -uint8_t address[][6] = {"1Node", "2Node"}; +uint8_t address[][6] = { "1Node", "2Node" }; // It is very helpful to think of an address as a path instead of as // an identifying device destination // to use different addresses on a pair of radios, we need a variable to // uniquely identify which address this radio will use to transmit -bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit +bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit // Used to control whether this node is sending or receiving bool role = false; // true = TX node, false = RX node @@ -43,11 +43,11 @@ const uint8_t tx_pl_size = 5; const uint8_t ack_pl_size = 4; uint8_t pl_iterator = 0; // The " + 1" compensates for the c-string's NULL terminating 0 -char tx_payloads[][tx_pl_size + 1] = {"Ping ", "Pong ", "Radio", "1FAIL"}; -char ack_payloads[][ack_pl_size + 1] = {"Yak ", "Back", " ACK"}; +char tx_payloads[][tx_pl_size + 1] = { "Ping ", "Pong ", "Radio", "1FAIL" }; +char ack_payloads[][ack_pl_size + 1] = { "Yak ", "Back", " ACK" }; -void interruptHandler(); // prototype to handle IRQ events -void printRxFifo(); // prototype to print RX FIFO with 1 buffer +void interruptHandler(); // prototype to handle IRQ events +void printRxFifo(); // prototype to print RX FIFO with 1 buffer void setup() { @@ -59,7 +59,7 @@ void setup() { // initialize the transceiver on the SPI bus if (!radio.begin()) { Serial.println(F("radio hardware is not responding!!")); - while (1) {} // hold in infinite loop + while (1) {} // hold in infinite loop } // print example's introductory prompt @@ -89,12 +89,12 @@ void setup() { // Set the PA Level low to try preventing power supply related problems // because these examples are likely run with nodes in close proximity to // each other. - radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. + radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. // For this example we use acknowledgment (ACK) payloads to trigger the // IRQ pin when data is received on the TX node. // to use ACK payloads, we need to enable dynamic payload lengths - radio.enableDynamicPayloads(); // ACK payloads are dynamically sized + radio.enableDynamicPayloads(); // ACK payloads are dynamically sized // Acknowledgement packets have no payloads by default. We need to enable // this feature for all nodes (TX & RX) to use ACK payloads. @@ -102,21 +102,21 @@ void setup() { // Fot this example, we use the same address to send data back and forth // set the TX address of the RX node into the TX pipe - radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 + radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 // set the RX address of the TX node into a RX pipe - radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 + radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 // additional setup specific to the node's role if (role) { // setup for TX mode - radio.stopListening(); // put radio in TX mode + radio.stopListening(); // put radio in TX mode } else { // setup for RX mode // let IRQ pin only trigger on "data ready" event in RX mode - radio.maskIRQ(1, 1, 0); // args = "data_sent", "data_fail", "data_ready" + radio.maskIRQ(1, 1, 0); // args = "data_sent", "data_fail", "data_ready" // Fill the TX FIFO with 3 ACK payloads for the first 3 received // transmissions on pipe 1 @@ -124,14 +124,13 @@ void setup() { radio.writeAckPayload(1, &ack_payloads[1], ack_pl_size); radio.writeAckPayload(1, &ack_payloads[2], ack_pl_size); - radio.startListening(); // put radio in RX mode + radio.startListening(); // put radio in RX mode } // For debugging info // printf_begin(); // needed only once for printing details // radio.printDetails(); // (smaller) function that prints raw register values // radio.printPrettyDetails(); // (larger) function that prints human readable data - } void loop() { @@ -146,21 +145,21 @@ void loop() { // Test the "data ready" event with the IRQ pin Serial.println(F("\nConfiguring IRQ pin to ignore the 'data sent' event")); - radio.maskIRQ(true, false, false); // args = "data_sent", "data_fail", "data_ready" + radio.maskIRQ(true, false, false); // args = "data_sent", "data_fail", "data_ready" Serial.println(F(" Pinging RX node for 'data ready' event...")); } else if (pl_iterator == 1) { // Test the "data sent" event with the IRQ pin Serial.println(F("\nConfiguring IRQ pin to ignore the 'data ready' event")); - radio.maskIRQ(false, false, true); // args = "data_sent", "data_fail", "data_ready" + radio.maskIRQ(false, false, true); // args = "data_sent", "data_fail", "data_ready" Serial.println(F(" Pinging RX node for 'data sent' event...")); } else if (pl_iterator == 2) { // Use this iteration to fill the RX node's FIFO which sets us up for the next test. // write() uses virtual interrupt flags that work despite the masking of the IRQ pin - radio.maskIRQ(1, 1, 1); // disable IRQ masking for this step + radio.maskIRQ(1, 1, 1); // disable IRQ masking for this step Serial.println(F("\nSending 1 payload to fill RX node's FIFO. IRQ pin is neglected.")); // write() will call flush_tx() on 'data fail' events @@ -172,14 +171,14 @@ void loop() { } } else { Serial.println(F("Transmission failed or timed out. Continuing anyway.")); - radio.flush_tx(); // discard payload(s) that failed to transmit + radio.flush_tx(); // discard payload(s) that failed to transmit } } else if (pl_iterator == 3) { // test the "data fail" event with the IRQ pin Serial.println(F("\nConfiguring IRQ pin to reflect all events")); - radio.maskIRQ(0, 0, 0); // args = "data_sent", "data_fail", "data_ready" + radio.maskIRQ(0, 0, 0); // args = "data_sent", "data_fail", "data_ready" Serial.println(F(" Pinging inactive RX node for 'data fail' event...")); } @@ -201,7 +200,7 @@ void loop() { // all IRQ tests are done; flush_tx() and print the ACK payloads for fun // CE pin is still HIGH which consumes more power. Example is now idling so... - radio.stopListening(); // ensure CE pin is LOW + radio.stopListening(); // ensure CE pin is LOW // stopListening() also calls flush_tx() when ACK payloads are enabled printRxFifo(); @@ -214,7 +213,7 @@ void loop() { } else if (pl_iterator == 2) { - pl_iterator++; // proceed from step 3 to last step (stop at step 4 for readability) + pl_iterator++; // proceed from step 3 to last step (stop at step 4 for readability) } } else if (!role) { @@ -233,11 +232,11 @@ void loop() { radio.writeAckPayload(1, &ack_payloads[1], ack_pl_size); radio.writeAckPayload(1, &ack_payloads[2], ack_pl_size); - delay(100); // let TX node finish its role - radio.startListening(); // We're ready to start over. Begin listening. + delay(100); // let TX node finish its role + radio.startListening(); // We're ready to start over. Begin listening. } - } // role + } // role if (Serial.available()) { // change the role via the serial monitor @@ -257,7 +256,7 @@ void loop() { // startListening() clears the IRQ masks also. This is required for // continued TX operations when a transmission fails. - radio.stopListening(); // this also discards any unused ACK payloads + radio.stopListening(); // this also discards any unused ACK payloads } else if (c == 'R' && role) { // Become the RX node @@ -265,18 +264,18 @@ void loop() { role = false; - radio.maskIRQ(0, 0, 0); // the IRQ pin should only trigger on "data ready" event + radio.maskIRQ(0, 0, 0); // the IRQ pin should only trigger on "data ready" event // Fill the TX FIFO with 3 ACK payloads for the first 3 received // transmissions on pipe 1 - radio.flush_tx(); // make sure there is room for 3 new ACK payloads + radio.flush_tx(); // make sure there is room for 3 new ACK payloads radio.writeAckPayload(1, &ack_payloads[0], ack_pl_size); radio.writeAckPayload(1, &ack_payloads[1], ack_pl_size); radio.writeAckPayload(1, &ack_payloads[2], ack_pl_size); radio.startListening(); } - } // Serial.available() -} // loop + } // Serial.available() +} // loop /** @@ -285,23 +284,23 @@ void loop() { void interruptHandler() { // print IRQ status and all masking flags' states - Serial.println(F("\tIRQ pin is actively LOW")); // show that this function was called + Serial.println(F("\tIRQ pin is actively LOW")); // show that this function was called delayMicroseconds(250); - bool tx_ds, tx_df, rx_dr; // declare variables for IRQ masks - radio.whatHappened(tx_ds, tx_df, rx_dr); // get values for IRQ masks + bool tx_ds, tx_df, rx_dr; // declare variables for IRQ masks + radio.whatHappened(tx_ds, tx_df, rx_dr); // get values for IRQ masks // whatHappened() clears the IRQ masks also. This is required for // continued TX operations when a transmission fails. // clearing the IRQ masks resets the IRQ pin to its inactive state (HIGH) Serial.print(F("\tdata_sent: ")); - Serial.print(tx_ds); // print "data sent" mask state + Serial.print(tx_ds); // print "data sent" mask state Serial.print(F(", data_fail: ")); - Serial.print(tx_df); // print "data fail" mask state + Serial.print(tx_df); // print "data fail" mask state Serial.print(F(", data_ready: ")); - Serial.println(rx_dr); // print "data ready" mask state + Serial.println(rx_dr); // print "data ready" mask state - if (tx_df) // if TX payload failed - radio.flush_tx(); // clear all payloads from the TX FIFO + if (tx_df) // if TX payload failed + radio.flush_tx(); // clear all payloads from the TX FIFO // print if test passed or failed. Unintentional fails mean the RX node was not listening. // pl_iterator has already been incremented by now @@ -315,8 +314,8 @@ void interruptHandler() { Serial.print(F(" 'Data Fail' event test ")); Serial.println(tx_df ? F("passed") : F("failed")); } - wait_for_event = false; // ready to continue with loop() operations -} // interruptHandler + wait_for_event = false; // ready to continue with loop() operations +} // interruptHandler /** @@ -324,23 +323,23 @@ void interruptHandler() { * Remember that the payload sizes are declared as tx_pl_size and ack_pl_size. */ void printRxFifo() { - if (radio.available()) { // if there is data in the RX FIFO + if (radio.available()) { // if there is data in the RX FIFO // to flush the data from the RX FIFO, we'll fetch it all using 1 buffer uint8_t pl_size = !role ? tx_pl_size : ack_pl_size; - char rx_fifo[pl_size * 3 + 1]; // RX FIFO is full & we know ACK payloads' size + char rx_fifo[pl_size * 3 + 1]; // RX FIFO is full & we know ACK payloads' size if (radio.rxFifoFull()) { - rx_fifo[pl_size * 3] = 0; // add a NULL terminating char to use as a c-string - radio.read(&rx_fifo, pl_size * 3); // this clears the RX FIFO (for this example) + rx_fifo[pl_size * 3] = 0; // add a NULL terminating char to use as a c-string + radio.read(&rx_fifo, pl_size * 3); // this clears the RX FIFO (for this example) } else { uint8_t i = 0; while (radio.available()) { radio.read(&rx_fifo + (i * pl_size), pl_size); i++; } - rx_fifo[i * pl_size] = 0; // add a NULL terminating char to use as a c-string + rx_fifo[i * pl_size] = 0; // add a NULL terminating char to use as a c-string } Serial.print(F("Complete RX FIFO: ")); - Serial.println(rx_fifo); // print the entire RX FIFO with 1 buffer + Serial.println(rx_fifo); // print the entire RX FIFO with 1 buffer } -} \ No newline at end of file +} diff --git a/examples/ManualAcknowledgements/ManualAcknowledgements.ino b/examples/ManualAcknowledgements/ManualAcknowledgements.ino index 17d45933b..81c1b5423 100644 --- a/examples/ManualAcknowledgements/ManualAcknowledgements.ino +++ b/examples/ManualAcknowledgements/ManualAcknowledgements.ino @@ -21,16 +21,16 @@ #include "RF24.h" // instantiate an object for the nRF24L01 transceiver -RF24 radio(7, 8); // using pin 7 for the CE pin, and pin 8 for the CSN pin +RF24 radio(7, 8); // using pin 7 for the CE pin, and pin 8 for the CSN pin // Let these addresses be used for the pair -uint8_t address[][6] = {"1Node", "2Node"}; +uint8_t address[][6] = { "1Node", "2Node" }; // It is very helpful to think of an address as a path instead of as // an identifying device destination // to use different addresses on a pair of radios, we need a variable to // uniquely identify which address this radio will use to transmit -bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit +bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit // Used to control whether this node is sending or receiving bool role = false; // true = TX node, false = RX node @@ -40,7 +40,7 @@ bool role = false; // true = TX node, false = RX node // on every successful transmission. // Make a data structure to store the entire payload of different datatypes struct PayloadStruct { - char message[7]; // only using 6 characters for TX & RX payloads + char message[7]; // only using 6 characters for TX & RX payloads uint8_t counter; }; PayloadStruct payload; @@ -58,7 +58,7 @@ void setup() { // initialize the transceiver on the SPI bus if (!radio.begin()) { Serial.println(F("radio hardware is not responding!!")); - while (1) {} // hold in infinite loop + while (1) {} // hold in infinite loop } // print example's introductory prompt @@ -80,28 +80,28 @@ void setup() { // Set the PA Level low to try preventing power supply related problems // because these examples are likely run with nodes in close proximity to // each other. - radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. + radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. // save on transmission time by setting the radio to only transmit the // number of bytes we need to transmit a float - radio.setPayloadSize(sizeof(payload)); // char[7] & uint8_t datatypes occupy 8 bytes + radio.setPayloadSize(sizeof(payload)); // char[7] & uint8_t datatypes occupy 8 bytes // set the TX address of the RX node into the TX pipe - radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 + radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 // set the RX address of the TX node into a RX pipe - radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 + radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 if (role) { // setup the TX node - memcpy(payload.message, "Hello ", 6); // set the outgoing message - radio.stopListening(); // put radio in TX mode + memcpy(payload.message, "Hello ", 6); // set the outgoing message + radio.stopListening(); // put radio in TX mode } else { // setup the RX node - memcpy(payload.message, "World ", 6); // set the outgoing message - radio.startListening(); // put radio in RX mode + memcpy(payload.message, "World ", 6); // set the outgoing message + radio.startListening(); // put radio in RX mode } // For debugging info @@ -109,53 +109,53 @@ void setup() { // radio.printDetails(); // (smaller) function that prints raw register values // radio.printPrettyDetails(); // (larger) function that prints human readable data -} // setup() +} // setup() void loop() { if (role) { // This device is a TX node - unsigned long start_timer = micros(); // start the timer - bool report = radio.write(&payload, sizeof(payload)); // transmit & save the report + unsigned long start_timer = micros(); // start the timer + bool report = radio.write(&payload, sizeof(payload)); // transmit & save the report if (report) { // transmission successful; wait for response and print results - radio.startListening(); // put in RX mode - unsigned long start_timeout = millis(); // timer to detect timeout - while (!radio.available()) { // wait for response - if (millis() - start_timeout > 200) // only wait 200 ms + radio.startListening(); // put in RX mode + unsigned long start_timeout = millis(); // timer to detect timeout + while (!radio.available()) { // wait for response + if (millis() - start_timeout > 200) // only wait 200 ms break; } - unsigned long end_timer = micros(); // end the timer - radio.stopListening(); // put back in TX mode + unsigned long end_timer = micros(); // end the timer + radio.stopListening(); // put back in TX mode // print summary of transactions - Serial.print(F("Transmission successful!")); // payload was delivered + Serial.print(F("Transmission successful!")); // payload was delivered uint8_t pipe; - if (radio.available(&pipe)) { // is there a payload received + if (radio.available(&pipe)) { // is there a payload received Serial.print(F(" Round-trip delay: ")); - Serial.print(end_timer - start_timer); // print the timer result + Serial.print(end_timer - start_timer); // print the timer result Serial.print(F(" us. Sent: ")); - Serial.print(payload.message); // print the outgoing payload's message - Serial.print(payload.counter); // print outgoing payload's counter + Serial.print(payload.message); // print the outgoing payload's message + Serial.print(payload.counter); // print outgoing payload's counter PayloadStruct received; - radio.read(&received, sizeof(received)); // get payload from RX FIFO + radio.read(&received, sizeof(received)); // get payload from RX FIFO Serial.print(F(" Received ")); - Serial.print(radio.getPayloadSize()); // print the size of the payload + Serial.print(radio.getPayloadSize()); // print the size of the payload Serial.print(F(" bytes on pipe ")); - Serial.print(pipe); // print the pipe number + Serial.print(pipe); // print the pipe number Serial.print(F(": ")); - Serial.print(received.message); // print the incoming payload's message - Serial.println(received.counter); // print the incoming payload's counter - payload.counter = received.counter; // save incoming counter for next outgoing counter + Serial.print(received.message); // print the incoming payload's message + Serial.println(received.counter); // print the incoming payload's counter + payload.counter = received.counter; // save incoming counter for next outgoing counter } else { - Serial.println(F(" Recieved no response.")); // no response received + Serial.println(F(" Recieved no response.")); // no response received } } else { - Serial.println(F("Transmission failed or timed out")); // payload was not delivered - } // report + Serial.println(F("Transmission failed or timed out")); // payload was not delivered + } // report // to make this example readable in the serial monitor delay(1000); // slow transmissions down by 1 second @@ -164,37 +164,37 @@ void loop() { // This device is a RX node uint8_t pipe; - if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it + if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it PayloadStruct received; - radio.read(&received, sizeof(received)); // get incoming payload - payload.counter = received.counter + 1; // increment incoming counter for next outgoing response + radio.read(&received, sizeof(received)); // get incoming payload + payload.counter = received.counter + 1; // increment incoming counter for next outgoing response // transmit response & save result to `report` - radio.stopListening(); // put in TX mode + radio.stopListening(); // put in TX mode radio.writeFast(&payload, sizeof(payload)); // load response to TX FIFO - bool report = radio.txStandBy(150); // keep retrying for 150 ms + bool report = radio.txStandBy(150); // keep retrying for 150 ms - radio.startListening(); // put back in RX mode + radio.startListening(); // put back in RX mode // print summary of transactions Serial.print(F("Received ")); - Serial.print(radio.getPayloadSize()); // print the size of the payload + Serial.print(radio.getPayloadSize()); // print the size of the payload Serial.print(F(" bytes on pipe ")); - Serial.print(pipe); // print the pipe number + Serial.print(pipe); // print the pipe number Serial.print(F(": ")); - Serial.print(received.message); // print incoming message - Serial.print(received.counter); // print incoming counter + Serial.print(received.message); // print incoming message + Serial.print(received.counter); // print incoming counter if (report) { Serial.print(F(" Sent: ")); - Serial.print(payload.message); // print outgoing message - Serial.println(payload.counter); // print outgoing counter + Serial.print(payload.message); // print outgoing message + Serial.println(payload.counter); // print outgoing counter } else { - Serial.println(" Response failed."); // failed to send response + Serial.println(" Response failed."); // failed to send response } } - } // role + } // role if (Serial.available()) { // change the role via the serial monitor @@ -204,17 +204,17 @@ void loop() { // Become the TX node role = true; - memcpy(payload.message, "Hello ", 6); // set the outgoing message + memcpy(payload.message, "Hello ", 6); // set the outgoing message Serial.println(F("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK")); - radio.stopListening(); // put in TX mode + radio.stopListening(); // put in TX mode } else if (c == 'R' && role) { // Become the RX node role = false; - memcpy(payload.message, "World ", 6); // set the response message + memcpy(payload.message, "World ", 6); // set the response message Serial.println(F("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK")); - radio.startListening(); // put in RX mode + radio.startListening(); // put in RX mode } } -} // loop \ No newline at end of file +} // loop diff --git a/examples/MulticeiverDemo/MulticeiverDemo.ino b/examples/MulticeiverDemo/MulticeiverDemo.ino index c3ed97b7b..d6d4379c6 100644 --- a/examples/MulticeiverDemo/MulticeiverDemo.ino +++ b/examples/MulticeiverDemo/MulticeiverDemo.ino @@ -18,7 +18,7 @@ #include "RF24.h" // instantiate an object for the nRF24L01 transceiver -RF24 radio(7, 8); // using pin 7 for the CE pin, and pin 8 for the CSN pin +RF24 radio(7, 8); // using pin 7 for the CE pin, and pin 8 for the CSN pin // For this example, we'll be using 6 addresses; 1 for each TX node // It is very helpful to think of an address as a path instead of as @@ -26,26 +26,24 @@ RF24 radio(7, 8); // using pin 7 for the CE pin, and pin 8 for the CSN pin // Notice that the last byte is the only byte that changes in the last 5 // addresses. This is a limitation of the nRF24L01 transceiver for pipes 2-5 // because they use the same first 4 bytes from pipe 1. -uint64_t address[6] = {0x7878787878LL, - 0xB3B4B5B6F1LL, - 0xB3B4B5B6CDLL, - 0xB3B4B5B6A3LL, - 0xB3B4B5B60FLL, - 0xB3B4B5B605LL - }; +uint64_t address[6] = { 0x7878787878LL, + 0xB3B4B5B6F1LL, + 0xB3B4B5B6CDLL, + 0xB3B4B5B6A3LL, + 0xB3B4B5B60FLL, + 0xB3B4B5B605LL }; // Because this example allow up to 6 nodes (specified by numbers 0-5) to // transmit and only 1 node to receive, we will use a negative value in our // role variable to signify this node is a receiver. // role variable is used to control whether this node is sending or receiving -char role = 'R'; // integers 0-5 = TX node; character 'R' or integer 82 = RX node +char role = 'R'; // integers 0-5 = TX node; character 'R' or integer 82 = RX node // For this example, we'll be using a payload containing // a node ID number and a single integer number that will be incremented // on every successful transmission. // Make a data structure to use as a payload. -struct PayloadStruct -{ +struct PayloadStruct { unsigned long nodeID; unsigned long payloadID; }; @@ -54,7 +52,7 @@ PayloadStruct payload; // This example uses all 6 pipes to receive while TX nodes only use 2 pipes // To make this easier we'll use a function to manage the addresses, and the // payload's nodeID -void setRole(); // declare a prototype; definition is found after the loop() +void setRole(); // declare a prototype; definition is found after the loop() void setup() { @@ -66,7 +64,7 @@ void setup() { // initialize the transceiver on the SPI bus if (!radio.begin()) { Serial.println(F("radio hardware is not responding!!")); - while (1) {} // hold in infinite loop + while (1) {} // hold in infinite loop } // print example's introductory prompt @@ -77,11 +75,11 @@ void setup() { // Set the PA Level low to try preventing power supply related problems // because these examples are likely run with nodes in close proximity of // each other. - radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. + radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. // save on transmission time by setting the radio to only transmit the // number of bytes we need to transmit a float - radio.setPayloadSize(sizeof(payload)); // 2x int datatype occupy 8 bytes + radio.setPayloadSize(sizeof(payload)); // 2x int datatype occupy 8 bytes // Set the pipe addresses accordingly. This function additionally also // calls startListening() or stopListening() and sets the payload's nodeID @@ -92,53 +90,53 @@ void setup() { // radio.printDetails(); // (smaller) function that prints raw register values // radio.printPrettyDetails(); // (larger) function that prints human readable data -} // setup() +} // setup() void loop() { if (role <= 53) { // This device is a TX node - unsigned long start_timer = micros(); // start the timer - bool report = radio.write(&payload, sizeof(payload)); // transmit & save the report - unsigned long end_timer = micros(); // end the timer + unsigned long start_timer = micros(); // start the timer + bool report = radio.write(&payload, sizeof(payload)); // transmit & save the report + unsigned long end_timer = micros(); // end the timer if (report) { // payload was delivered Serial.print(F("Transmission of payloadID ")); - Serial.print(payload.payloadID); // print payloadID + Serial.print(payload.payloadID); // print payloadID Serial.print(F(" as node ")); - Serial.print(payload.nodeID); // print nodeID + Serial.print(payload.nodeID); // print nodeID Serial.print(F(" successful!")); Serial.print(F(" Time to transmit: ")); - Serial.print(end_timer - start_timer); // print the timer result + Serial.print(end_timer - start_timer); // print the timer result Serial.println(F(" us")); } else { - Serial.println(F("Transmission failed or timed out")); // payload was not delivered + Serial.println(F("Transmission failed or timed out")); // payload was not delivered } - payload.payloadID++; // increment payload number + payload.payloadID++; // increment payload number // to make this example readable in the serial monitor - delay(1000); // slow transmissions down by 1 second + delay(1000); // slow transmissions down by 1 second } else if (role == 'R') { // This device is the RX node uint8_t pipe; - if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it - uint8_t bytes = radio.getPayloadSize(); // get the size of the payload - radio.read(&payload, bytes); // fetch payload from FIFO + if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it + uint8_t bytes = radio.getPayloadSize(); // get the size of the payload + radio.read(&payload, bytes); // fetch payload from FIFO Serial.print(F("Received ")); - Serial.print(bytes); // print the size of the payload + Serial.print(bytes); // print the size of the payload Serial.print(F(" bytes on pipe ")); - Serial.print(pipe); // print the pipe number + Serial.print(pipe); // print the pipe number Serial.print(F(" from node ")); - Serial.print(payload.nodeID); // print the payload's origin + Serial.print(payload.nodeID); // print the payload's origin Serial.print(F(". PayloadID: ")); - Serial.println(payload.payloadID); // print the payload's number + Serial.println(payload.payloadID); // print the payload's number } - } // role + } // role if (Serial.available()) { // change the role via the serial monitor @@ -151,7 +149,7 @@ void loop() { Serial.println(F("*** CHANGING ROLE TO RECEIVER ***")); Serial.println(F("--- Enter a number between 0 and 5 (inclusive) to act as")); Serial.println(F(" a unique node number that transmits to the RX node.")); - setRole(); // change address on all pipes to TX nodes + setRole(); // change address on all pipes to TX nodes } else if (c >= 48 && c <= 53 && c != role) { // Become a TX node with identifier 'c' @@ -163,11 +161,11 @@ void loop() { Serial.println(F("--- Enter a number between 0 and 5 (inclusive) to change")); Serial.println(F(" the identifying node number that transmits.")); Serial.println(F("--- PRESS 'R' to act as the RX node.")); - setRole(); // change address on pipe 0 to the RX node + setRole(); // change address on pipe 0 to the RX node } } -} // loop +} // loop void setRole() { if (role == 'R') { @@ -177,7 +175,7 @@ void setRole() { for (uint8_t i = 0; i < 6; ++i) radio.openReadingPipe(i, address[i]); - radio.startListening(); // put radio in RX mode + radio.startListening(); // put radio in RX mode } else { // For the TX node @@ -187,12 +185,12 @@ void setRole() { payload.payloadID = 0; // Set the address on pipe 0 to the RX node. - radio.stopListening(); // put radio in TX mode + radio.stopListening(); // put radio in TX mode radio.openWritingPipe(address[role]); // According to the datasheet, the auto-retry features's delay value should // be "skewed" to allow the RX node to receive 1 transmission at a time. // So, use varying delay between retry attempts and 15 (at most) retry attempts - radio.setRetries(((role * 3) % 12) + 3, 15); // maximum value is 15 for both args + radio.setRetries(((role * 3) % 12) + 3, 15); // maximum value is 15 for both args } -} // setRole +} // setRole diff --git a/examples/StreamingData/StreamingData.ino b/examples/StreamingData/StreamingData.ino index e17d9b509..8046568f8 100644 --- a/examples/StreamingData/StreamingData.ino +++ b/examples/StreamingData/StreamingData.ino @@ -15,32 +15,32 @@ #include "RF24.h" // instantiate an object for the nRF24L01 transceiver -RF24 radio(7, 8); // using pin 7 for the CE pin, and pin 8 for the CSN pin +RF24 radio(7, 8); // using pin 7 for the CE pin, and pin 8 for the CSN pin // Let these addresses be used for the pair -uint8_t address[][6] = {"1Node", "2Node"}; +uint8_t address[][6] = { "1Node", "2Node" }; // It is very helpful to think of an address as a path instead of as // an identifying device destination // to use different addresses on a pair of radios, we need a variable to // uniquely identify which address this radio will use to transmit -bool radioNumber; // 0 uses address[0] to transmit, 1 uses address[1] to transmit +bool radioNumber; // 0 uses address[0] to transmit, 1 uses address[1] to transmit // Used to control whether this node is sending or receiving -bool role = false; // true = TX node, false = RX node +bool role = false; // true = TX node, false = RX node // For this example, we'll be sending 32 payloads each containing // 32 bytes of data that looks like ASCII art when printed to the serial // monitor. The TX node and RX node needs only a single 32 byte buffer. -#define SIZE 32 // this is the maximum for this example. (minimum is 1) -char buffer[SIZE + 1]; // for the RX node -uint8_t counter = 0; // for counting the number of received payloads -void makePayload(uint8_t); // prototype to construct a payload dynamically +#define SIZE 32 // this is the maximum for this example. (minimum is 1) +char buffer[SIZE + 1]; // for the RX node +uint8_t counter = 0; // for counting the number of received payloads +void makePayload(uint8_t); // prototype to construct a payload dynamically void setup() { - buffer[SIZE] = 0; // add a NULL terminating character (for easy printing) + buffer[SIZE] = 0; // add a NULL terminating character (for easy printing) Serial.begin(115200); while (!Serial) { @@ -50,7 +50,7 @@ void setup() { // initialize the transceiver on the SPI bus if (!radio.begin()) { Serial.println(F("radio hardware is not responding!!")); - while (1) {} // hold in infinite loop + while (1) {} // hold in infinite loop } // print example's introductory prompt @@ -76,19 +76,19 @@ void setup() { // save on transmission time by setting the radio to only transmit the // number of bytes we need to transmit - radio.setPayloadSize(SIZE); // default value is the maximum 32 bytes + radio.setPayloadSize(SIZE); // default value is the maximum 32 bytes // set the TX address of the RX node into the TX pipe - radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 + radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 // set the RX address of the TX node into a RX pipe - radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 + radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 // additional setup specific to the node's role if (role) { radio.stopListening(); // put radio in TX mode } else { - radio.startListening(); // put radio in RX mode + radio.startListening(); // put radio in RX mode } // For debugging info @@ -96,7 +96,7 @@ void setup() { // radio.printDetails(); // (smaller) function that prints raw register values // radio.printPrettyDetails(); // (larger) function that prints human readable data -} // setup() +} // setup() void loop() { @@ -107,9 +107,9 @@ void loop() { radio.flush_tx(); uint8_t i = 0; uint8_t failures = 0; - unsigned long start_timer = micros(); // start the timer + unsigned long start_timer = micros(); // start the timer while (i < SIZE) { - makePayload(i); // make the payload + makePayload(i); // make the payload if (!radio.writeFast(&buffer, SIZE)) { failures++; radio.reUseTX(); @@ -123,12 +123,12 @@ void loop() { break; } } - unsigned long end_timer = micros(); // end the timer + unsigned long end_timer = micros(); // end the timer Serial.print(F("Time to transmit = ")); - Serial.print(end_timer - start_timer); // print the timer result + Serial.print(end_timer - start_timer); // print the timer result Serial.print(F(" us with ")); - Serial.print(failures); // print failures detected + Serial.print(failures); // print failures detected Serial.println(F(" failures detected")); // to make this example readable in the serial monitor @@ -137,14 +137,14 @@ void loop() { } else { // This device is a RX node - if (radio.available()) { // is there a payload? - radio.read(&buffer, SIZE); // fetch payload from FIFO + if (radio.available()) { // is there a payload? + radio.read(&buffer, SIZE); // fetch payload from FIFO Serial.print(F("Received: ")); - Serial.print(buffer); // print the payload's value + Serial.print(buffer); // print the payload's value Serial.print(F(" - ")); - Serial.println(counter++); // print the received counter + Serial.println(counter++); // print the received counter } - } // role + } // role if (Serial.available()) { // change the role via the serial monitor @@ -154,7 +154,7 @@ void loop() { // Become the TX node role = true; - counter = 0; //reset the RX node's counter + counter = 0; //reset the RX node's counter Serial.println(F("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK")); radio.stopListening(); @@ -167,7 +167,7 @@ void loop() { } } -} // loop +} // loop void makePayload(uint8_t i) { @@ -182,4 +182,4 @@ void makePayload(uint8_t i) { chr |= j < (SIZE - 1) / 2 - abs((SIZE - 1) / 2 - i); buffer[j + 1] = chr + 48; } -} \ No newline at end of file +} diff --git a/examples/encodeRadioDetails/encodeRadioDetails.ino b/examples/encodeRadioDetails/encodeRadioDetails.ino index 8cf8ebcd7..1cfcf090a 100644 --- a/examples/encodeRadioDetails/encodeRadioDetails.ino +++ b/examples/encodeRadioDetails/encodeRadioDetails.ino @@ -18,7 +18,7 @@ #include "RF24.h" // instantiate an object for the nRF24L01 transceiver -RF24 radio(7, 8); // using pin 7 for the CE pin, and pin 8 for the CSN pin +RF24 radio(7, 8); // using pin 7 for the CE pin, and pin 8 for the CSN pin /* For this example, we'll be using a data buffer containing @@ -29,7 +29,7 @@ RF24 radio(7, 8); // using pin 7 for the CE pin, and pin 8 for the CSN pin will take a space-delimited string of hexadecimal characters and decode then print it out as human readable information. */ -uint8_t encoded_details[43] = {0}; +uint8_t encoded_details[43] = { 0 }; // Use this function to print out the encoded_details as a // space-delimited string of hexadecimal characters. @@ -51,7 +51,7 @@ void setup() { // initialize the transceiver on the SPI bus if (!radio.begin()) { Serial.println(F("radio hardware is not responding!!")); - while (1) {} // hold in infinite loop + while (1) {} // hold in infinite loop } // print example's introductory prompt @@ -82,7 +82,7 @@ void setup() { Serial.print(F(" this example's folder. Like so:\npython print_details.py \"")); dumpRegData(); Serial.println(F("\"\n***You may need to use 'python3' (without quotes) on Linux")); -} // setup +} // setup /* Registers correspnding to index of encoded_details array 0: NRF_CONFIG @@ -116,7 +116,6 @@ void setup() { 42: SPI speed MHz | (isPlusVariant << 4) */ -void loop() -{ +void loop() { // Nothing to do here. We did it all at the end of setup() } diff --git a/examples/examples_formatter.conf b/examples/examples_formatter.conf deleted file mode 100644 index 57270c833..000000000 --- a/examples/examples_formatter.conf +++ /dev/null @@ -1,31 +0,0 @@ -# This configuration file contains a selection of the available options provided by the formatting tool "Artistic Style" -# http://astyle.sourceforge.net/astyle.html -# -# If you wish to change them, don't edit this file. -# Instead, copy it in the same folder of file "preferences.txt" and modify the copy. This way, you won't lose your custom formatter settings when upgrading the IDE -# If you don't know where file preferences.txt is stored, open the IDE, File -> Preferences and you'll find a link - -mode=c - -# 2 spaces indentation -indent=spaces=2 - -# also indent macros -indent-preprocessor - -# indent classes, switches (and cases), comments starting at column 1 -indent-classes -indent-switches -indent-cases -indent-col1-comments - -# put a space around operators -pad-oper - -# put a space after if/for/while -pad-header - -# if you like one-liners, keep them -keep-one-line-statements - -# remove-comment-prefix diff --git a/examples/old_backups/GettingStarted_HandlingFailures/GettingStarted_HandlingFailures.ino b/examples/old_backups/GettingStarted_HandlingFailures/GettingStarted_HandlingFailures.ino index 6e25c6f6e..09f418223 100644 --- a/examples/old_backups/GettingStarted_HandlingFailures/GettingStarted_HandlingFailures.ino +++ b/examples/old_backups/GettingStarted_HandlingFailures/GettingStarted_HandlingFailures.ino @@ -48,7 +48,7 @@ bool radioNumber = 0; RF24 radio(7, 8); /**********************************************************/ -byte addresses[][6] = {"1Node", "2Node"}; +byte addresses[][6] = { "1Node", "2Node" }; // Used to control whether this node is sending or receiving bool role = 0; @@ -91,7 +91,7 @@ void setup() { configureRadio(); } -uint32_t configTimer = millis(); +uint32_t configTimer = millis(); void loop() { @@ -116,23 +116,23 @@ void loop() { if (role == 1) { - radio.stopListening(); // First, stop listening so we can talk. + radio.stopListening(); // First, stop listening so we can talk. Serial.println(F("Now sending")); - unsigned long start_time = micros(); // Take the time, and send it. This will block until complete + unsigned long start_time = micros(); // Take the time, and send it. This will block until complete if (!radio.write(&start_time, sizeof(unsigned long))) { Serial.println(F("failed")); } - radio.startListening(); // Now, continue listening + radio.startListening(); // Now, continue listening - unsigned long started_waiting_at = micros(); // Set up a timeout period, get the current microseconds - bool timeout = false; // Set up a variable to indicate if a response was received or not + unsigned long started_waiting_at = micros(); // Set up a timeout period, get the current microseconds + bool timeout = false; // Set up a variable to indicate if a response was received or not - while (!radio.available()) // While nothing is received + while (!radio.available()) // While nothing is received { - if (micros() - started_waiting_at > 200000 ) // If waited longer than 200ms, indicate timeout and exit while loop + if (micros() - started_waiting_at > 200000) // If waited longer than 200ms, indicate timeout and exit while loop { timeout = true; break; @@ -145,11 +145,11 @@ void loop() { } else { // Grab the response, compare, and send to debugging spew - unsigned long got_time; // Variable for the received timestamp + unsigned long got_time; // Variable for the received timestamp // Failure Handling uint32_t failTimer = millis(); - while (radio.available()) // If available() always returns true, there is a problem + while (radio.available()) // If available() always returns true, there is a problem { if (millis() - failTimer > 250) { radio.failureDetected = true; @@ -170,31 +170,31 @@ void loop() { Serial.println(F(" microseconds")); } - delay(1000); // Try again 1s later + delay(1000); // Try again 1s later } /****************** Pong Back Role ***************************/ if (role == 0) { - unsigned long got_time; // Variable for the received timestamp + unsigned long got_time; // Variable for the received timestamp if (radio.available()) { uint32_t failTimer = millis(); - while (radio.available()) // While there is data ready + while (radio.available()) // While there is data ready { if (millis() - failTimer > 500) { Serial.println("Radio available failure detected"); radio.failureDetected = true; break; } - radio.read(&got_time, sizeof(unsigned long)); // Get the payload + 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. + 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. Serial.print(F("Sent response ")); Serial.println(got_time); } @@ -207,11 +207,11 @@ void loop() { char c = toupper(Serial.read()); if (c == 'T' && role == 0) { Serial.println(F("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK")); - role = 1; // Become the primary transmitter (ping out) - } else if ( c == 'R' && role == 1 ) { + role = 1; // Become the primary transmitter (ping out) + } else if (c == 'R' && role == 1) { Serial.println(F("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK")); - role = 0; // Become the primary receiver (pong back) + role = 0; // Become the primary receiver (pong back) radio.startListening(); } } -} // Loop +} // Loop diff --git a/examples/old_backups/TransferTimeouts/TransferTimeouts.ino b/examples/old_backups/TransferTimeouts/TransferTimeouts.ino index cec44ed96..9abb4d369 100644 --- a/examples/old_backups/TransferTimeouts/TransferTimeouts.ino +++ b/examples/old_backups/TransferTimeouts/TransferTimeouts.ino @@ -6,8 +6,9 @@ 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 +/** + 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. @@ -26,15 +27,15 @@ /************* USER Configuration *****************************/ -RF24 radio(7, 8); // 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). +RF24 radio(7, 8); // 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. +const uint64_t pipes[2] = { 0xABCDABCD71LL, 0x544d52687CLL }; // Radio pipe addresses for the 2 nodes to communicate. -byte data[32]; //Data buffer +byte data[32]; //Data buffer volatile unsigned long counter; unsigned long rxTimer, startTime, stopTime, payloads = 0; @@ -46,29 +47,27 @@ void setup(void) { Serial.begin(115200); 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.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 + 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 + 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 + data[i] = random(255); //Load the buffer with random data } - radio.powerUp(); //Power up the radio - - + radio.powerUp(); //Power up the radio } @@ -77,61 +76,62 @@ void loop(void) { if (role == tx) { - delay(2000); // Pause for a couple seconds between transfers + 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 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 + 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 + startTime = millis(); // For calculating transfer rate + boolean timedOut = 0; // Boolean for keeping track of failures - for (unsigned long i = 0; i < cycles; i++) // Loop through a number of cycles + for (unsigned long i = 0; i < cycles; i++) // Loop through a number of cycles { - data[0] = i; // Change the first byte of the payload for identification + data[0] = i; // Change the first byte of the payload for identification - if (!radio.writeBlocking(&data, 32, timeoutPeriod)) { // If retries are failing and the user defined timeout is exceeded - timedOut = 1; // Indicate failure - counter = cycles; // Set the fail count to maximum - break; // Break out of the for loop + if (!radio.writeBlocking(&data, 32, timeoutPeriod)) { // If retries are failing and the user defined timeout is exceeded + timedOut = 1; // Indicate failure + counter = cycles; // Set the fail count to maximum + break; // Break out of the for loop } } - stopTime = millis(); // Capture the time of completion or failure + stopTime = millis(); // Capture the time of completion or failure //This should be called to wait for completion and put the radio in standby mode after transmission, returns 0 if data still in FIFO (timed out), 1 if success if (timedOut) { radio.txStandBy(); //Partially blocking standby, blocks until success or max retries. FIFO flushed if auto timeout reached - } - else { - radio.txStandBy(timeoutPeriod); //Standby, block until FIFO empty (sent) or user specified timeout reached. FIFO flushed if user timeout reached. + } else { + radio.txStandBy(timeoutPeriod); //Standby, block until FIFO empty (sent) or user specified timeout reached. FIFO flushed if user timeout reached. } } else { - Serial.println("Communication not established"); //If unsuccessful initiating transfer, exit and retry later + Serial.println("Communication not established"); //If unsuccessful initiating transfer, exit and retry later } - float rate = cycles * 32 / (stopTime - startTime); //Display results: + float rate = cycles * 32 / (stopTime - startTime); //Display results: - Serial.print("Transfer complete at "); Serial.print(rate); printf(" KB/s \n\r"); + Serial.print("Transfer complete at "); + Serial.print(rate); + Serial.println(" KB/s"); Serial.print(counter); Serial.print(" of "); - Serial.print(cycles); Serial.println(" Packets Failed to Send"); + Serial.print(cycles); + Serial.println(" Packets Failed to Send"); counter = 0; - } if (role == rx) { - if (!transferInProgress) { // If a bulk data transfer has not been started + if (!transferInProgress) { // If a bulk data transfer has not been started if (radio.available()) { - radio.read(&data, 32); //Read any available payloads for analysis + radio.read(&data, 32); //Read any available payloads for analysis if (data[0] == 'H' && data[4] == 'S') { // If a bulk data transfer command has been received payloads = data[8]; // Read the first two bytes of the unsigned long. Need to read the 3rd and 4th if sending more than 65535 payloads @@ -142,50 +142,44 @@ void loop(void) { } } } else { - if (radio.available()) { // If in bulk transfer mode, and a payload is available - radio.read(&data, 32); // Read the payload - rxTimer = millis(); // Reset the timeout timer - counter++; // Keep a count of received payloads - } else if (millis() - rxTimer > timeoutPeriod) { // If no data available, check the timeout period - Serial.println("Transfer Failed"); // If per-payload timeout exceeeded, end the transfer + if (radio.available()) { // If in bulk transfer mode, and a payload is available + radio.read(&data, 32); // Read the payload + rxTimer = millis(); // Reset the timeout timer + counter++; // Keep a count of received payloads + } else if (millis() - rxTimer > 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 + } 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"); Serial.print("Payload Count: "); Serial.println(counter); - transferInProgress = 0; // End the transfer as complete + transferInProgress = 0; // End the transfer as complete } } - - } // // Change roles // - if ( Serial.available() ) - { + if (Serial.available()) { char c = toupper(Serial.read()); - if ( c == 'T' && role == rx ) - { + 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 ) - { + 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) + role = rx; // Become the primary receiver (pong back) } } } diff --git a/examples/old_backups/pingpair_dyn/pingpair_dyn.ino b/examples/old_backups/pingpair_dyn/pingpair_dyn.ino index 47636f87c..a27cbd39d 100644 --- a/examples/old_backups/pingpair_dyn/pingpair_dyn.ino +++ b/examples/old_backups/pingpair_dyn/pingpair_dyn.ino @@ -21,7 +21,7 @@ RF24 radio(7, 8); // Set up nRF24L01 radio on SPI bus plus pins 7 & 8 // Radio pipe addresses for the 2 nodes to communicate. -const uint64_t addresses[2] = {0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL}; +const uint64_t addresses[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL }; /************************* Role management ****************************/ // Set up role. This sketch uses the same software for all the nodes in this @@ -30,10 +30,11 @@ const uint64_t addresses[2] = {0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL}; // The role_pin is a digital input pin used to set the role of this radio. // Connect the role_pin to GND to be the 'pong' receiver // Leave the role_pin open to be the 'ping' transmitter -const short role_pin = 5; // use pin 5 -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; // The role of the current running sketch +const short role_pin = 5; // use pin 5 +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; // The role of the current running sketch // variables used for changing the payload size dynamically (used when role == role_ping_out) @@ -44,11 +45,10 @@ int send_payload_size = min_payload_size; char receive_payload[max_payload_size + 1]; // +1 to allow room for a terminating NULL char -void setup(void) -{ - pinMode(role_pin, INPUT); // set up the role pin +void setup(void) { + pinMode(role_pin, INPUT); // set up the role pin digitalWrite(role_pin, HIGH); - delay(20); // Just to get a solid reading on the role pin + delay(20); // Just to get a solid reading on the role pin // read the role_pin, establish our role if (digitalRead(role_pin)) { @@ -58,7 +58,7 @@ void setup(void) } Serial.begin(115200); - printf_begin(); // needed for printDetails() + printf_begin(); // needed for printDetails() // Print preamble Serial.println(F("RF24/examples/pingpair_dyn/")); @@ -79,8 +79,8 @@ void setup(void) radio.openReadingPipe(1, addresses[0]); } - radio.startListening(); // Start listening - radio.printDetails(); // Dump the configuration of the rf unit for debugging + radio.startListening(); // Start listening + radio.printDetails(); // Dump the configuration of the rf unit for debugging } void loop() { @@ -92,20 +92,20 @@ void loop() { // The payload will always be the same, what will change is how much of it we send. static char send_payload[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ789012"; - radio.stopListening(); // First, stop listening so we can talk. + radio.stopListening(); // First, stop listening so we can talk. // Send the payload Serial.print(F("Now sending length ")); Serial.println(send_payload_size); - radio.write(send_payload, send_payload_size); // This will block until complete + radio.write(send_payload, send_payload_size); // This will block until complete - radio.startListening(); // Now, continue listening + radio.startListening(); // Now, continue listening - unsigned long started_waiting_at = millis(); // Start a timer for measuring timout + unsigned long started_waiting_at = millis(); // Start a timer for measuring timout bool timeout = false; - while (!radio.available() && !timeout) // Wait until we get a response or timeout is reached + while (!radio.available() && !timeout) // Wait until we get a response or timeout is reached { - if (millis() - started_waiting_at > 500) // Only wait for 500 milliseconds + if (millis() - started_waiting_at > 500) // Only wait for 500 milliseconds timeout = true; } @@ -124,7 +124,7 @@ void loop() { radio.read(receive_payload, len); // Use payload as a C-string (for easy printing) - receive_payload[len] = 0; // put a NULL terminating zero at the end + receive_payload[len] = 0; // put a NULL terminating zero at the end // Spew it Serial.print(F("Got response size=")); @@ -133,11 +133,11 @@ void loop() { Serial.println(receive_payload); } - send_payload_size += payload_size_increment; // Update size for next time. - if (send_payload_size > max_payload_size) // if payload length is larger than the radio can handle - send_payload_size = min_payload_size; // reset the payload length + send_payload_size += payload_size_increment; // Update size for next time. + if (send_payload_size > max_payload_size) // if payload length is larger than the radio can handle + send_payload_size = min_payload_size; // reset the payload length - delay(1000); // Try again 1s later + delay(1000); // Try again 1s later } @@ -145,7 +145,7 @@ void loop() { // Receive each packet, send it back, and dump it out if (role == role_pong_back) { - while (radio.available()) // if there is data ready + while (radio.available()) // if there is data ready { uint8_t len = radio.getDynamicPayloadSize(); // Fetch the the payload size @@ -157,7 +157,7 @@ void loop() { radio.read(receive_payload, len); // Use payload as a C-string (for easy printing) - receive_payload[len] = 0; // put a NULL terminating zero at the end + receive_payload[len] = 0; // put a NULL terminating zero at the end // Spew it Serial.print(F("Got response size=")); @@ -165,7 +165,7 @@ void loop() { Serial.print(F(" value=")); Serial.println(receive_payload); - radio.stopListening(); // First, stop listening so we can talk + radio.stopListening(); // First, stop listening so we can talk // Send a reply that the packet was received // @@ -175,8 +175,8 @@ void loop() { radio.write(receive_payload, len); Serial.println(F("Sent response.")); - radio.startListening(); // Now, resume listening so we catch the next packets. + radio.startListening(); // Now, resume listening so we catch the next packets. } } -} // loop +} // loop // vim:cin:ai:sts=2 sw=2 ft=cpp diff --git a/examples/old_backups/pingpair_irq/pingpair_irq.ino b/examples/old_backups/pingpair_irq/pingpair_irq.ino index 2a5ed9125..39029b4e9 100644 --- a/examples/old_backups/pingpair_irq/pingpair_irq.ino +++ b/examples/old_backups/pingpair_irq/pingpair_irq.ino @@ -9,12 +9,12 @@ */ /** - Example of using interrupts + 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 + 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 @@ -23,13 +23,13 @@ #include "printf.h" // Hardware configuration -RF24 radio(7, 8); // Set up nRF24L01 radio on SPI bus plus pins 7 & 8 +RF24 radio(7, 8); // Set up nRF24L01 radio on SPI bus plus pins 7 & 8 // Our ACK payload will simply be 4 bytes containing the number of payloads received static uint32_t message_count = 1; // start counting at 1 // Demonstrates another method of setting up the addresses -byte address[][5] = {0xCC, 0xCE, 0xCC, 0xCE, 0xCC, 0xCE, 0xCC, 0xCE, 0xCC, 0xCE}; +byte address[][5] = { 0xCC, 0xCE, 0xCC, 0xCE, 0xCC, 0xCE, 0xCC, 0xCE, 0xCC, 0xCE }; /************************* Role management ****************************/ // Set up role. This sketch uses the same software for all the nodes in this @@ -38,10 +38,11 @@ byte address[][5] = {0xCC, 0xCE, 0xCC, 0xCE, 0xCC, 0xCE, 0xCC, 0xCE, 0xCC, 0xCE} // The role_pin is a digital input pin used to set the role of this radio. // Connect the role_pin to GND to be the 'pong' receiver // Leave the role_pin open to be the 'ping' transmitter -const short role_pin = 5; // use pin 5 -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 +const short role_pin = 5; // use pin 5 +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 void setup() { @@ -50,14 +51,14 @@ void setup() { 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 role_pin pin to establish our role + if (digitalRead(role_pin)) // read the role_pin pin to establish our role role = role_sender; else role = role_receiver; Serial.begin(115200); - printf_begin(); // needed for printDetails() + printf_begin(); // needed for printDetails() // print introduction Serial.print(F("\n\rRF24/examples/pingpair_irq\n\rROLE: ")); @@ -68,9 +69,9 @@ void setup() { radio.begin(); // Examples are usually run with both radios in close proximity to each other - radio.setPALevel(RF24_PA_LOW); // defaults to RF24_PA_MAX - radio.enableAckPayload(); // We will be using the ACK Payload feature which is not enabled by default - radio.enableDynamicPayloads(); // Ack payloads are dynamic payloads + radio.setPALevel(RF24_PA_LOW); // defaults to RF24_PA_MAX + radio.enableAckPayload(); // We will be using the ACK Payload feature which is not enabled by default + radio.enableDynamicPayloads(); // Ack payloads are dynamic payloads // Open a writing and reading pipe on each radio, with opposite addresses if (role == role_sender) { @@ -79,19 +80,19 @@ void setup() { } else { radio.openWritingPipe(address[1]); radio.openReadingPipe(1, address[0]); - radio.startListening(); // First we need to start listening + radio.startListening(); // First we need to start listening // Add an ACK payload for the first time around; 1 is the pipe number to acknowledge radio.writeAckPayload(1, &message_count, sizeof(message_count)); - ++message_count; // increment counter by 1 for next ACK payload + ++message_count; // increment counter by 1 for next ACK payload } - radio.printDetails(); // Dump the configuration of the rf unit for debugging + radio.printDetails(); // Dump the configuration of the rf unit for debugging delay(50); // Attach interrupt handler to interrupt #0 (using pin 2) on BOTH the sender and receiver attachInterrupt(0, check_radio, LOW); -} // setup +} // setup void loop() { @@ -102,7 +103,7 @@ void loop() { if (role == role_sender) { // Repeatedly send the current time - unsigned long time = millis(); // Take the time + unsigned long time = millis(); // Take the time Serial.print(F("Now sending ")); Serial.println(time); radio.startWrite(&time, sizeof(unsigned long), 0); // Send the time @@ -115,31 +116,31 @@ void loop() { if (role == role_receiver) {} -} // loop +} // loop /********************** Interrupt Handler *********************/ void check_radio(void) { - bool tx, fail, rx; // declare variables to store IRQ flags - radio.whatHappened(tx, fail, rx); // What happened? + bool tx, fail, rx; // declare variables to store IRQ flags + radio.whatHappened(tx, fail, rx); // What happened? - if (tx) { // Have we successfully transmitted? + if (tx) { // Have we successfully transmitted? if (role == role_sender) Serial.println(F("Send:OK")); if (role == role_receiver) Serial.println(F("Ack Payload:Sent")); } - if (fail) { // Have we failed to transmit? + if (fail) { // Have we failed to transmit? if (role == role_sender) Serial.println(F("Send:Failed")); if (role == role_receiver) Serial.println(F("Ack Payload:Failed")); } - if (rx || radio.available()) { // Did we receive a message? + if (rx || radio.available()) { // Did we receive a message? @@ -159,14 +160,14 @@ void check_radio(void) { if (role == role_receiver) { // Get the payload and dump it - static unsigned long got_time; // variable to hold the received time - radio.read(&got_time, sizeof(got_time)); // get the payload + static unsigned long got_time; // variable to hold the received time + radio.read(&got_time, sizeof(got_time)); // get the payload Serial.print(F("Got payload ")); Serial.println(got_time); // Add an ACK payload for the next time around; 1 is the pipe number to acknowledge radio.writeAckPayload(1, &message_count, sizeof(message_count)); - ++message_count; // increment packet counter + ++message_count; // increment packet counter } } -} // check_radio +} // check_radio diff --git a/examples/old_backups/pingpair_multi_dyn/pingpair_multi_dyn.ino b/examples/old_backups/pingpair_multi_dyn/pingpair_multi_dyn.ino index 5f169328c..fcdd377ac 100644 --- a/examples/old_backups/pingpair_multi_dyn/pingpair_multi_dyn.ino +++ b/examples/old_backups/pingpair_multi_dyn/pingpair_multi_dyn.ino @@ -7,9 +7,9 @@ */ /** - Example using Dynamic Payloads + Example using Dynamic Payloads - This is an example of how to use payloads of a varying (dynamic) size. + This is an example of how to use payloads of a varying (dynamic) size. */ #include @@ -30,7 +30,7 @@ const int multicast_pin = 6; // sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver // Leave open to be the 'ping' transmitter const int role_pin = 5; -bool multicast = true ; +bool multicast = true; // // Topology @@ -50,10 +50,11 @@ const uint64_t pipes[2] = { 0xEEFAFDFDEELL, 0xEEFDFAF50DFLL }; // // The various roles supported by this sketch -typedef enum { role_ping_out = 1, role_pong_back } role_e; +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"}; +const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back" }; // The role of the current running sketch role_e role; @@ -67,22 +68,21 @@ 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 +char receive_payload[max_payload_size + 1]; // +1 to allow room for a terminating NULL char -void setup(void) -{ +void setup(void) { // // Multicast // pinMode(multicast_pin, INPUT); digitalWrite(multicast_pin, HIGH); - delay( 20 ) ; + delay(20); // read multicast role, LOW for unicast - if ( digitalRead( multicast_pin ) ) - multicast = true ; + if (digitalRead(multicast_pin)) + multicast = true; else - multicast = false ; + multicast = false; // @@ -92,10 +92,10 @@ void setup(void) // 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 + delay(20); // Just to get a solid reading on the role pin // read the address pin, establish our role - if ( digitalRead(role_pin) ) + if (digitalRead(role_pin)) role = role_ping_out; else role = role_pong_back; @@ -121,11 +121,11 @@ void setup(void) // enable dynamic payloads radio.enableDynamicPayloads(); - radio.setCRCLength( RF24_CRC_16 ) ; + radio.setCRCLength(RF24_CRC_16); // optionally, increase the delay between retries & # of retries - radio.setRetries( 15, 5 ) ; - radio.setAutoAck( true ) ; + radio.setRetries(15, 5); + radio.setAutoAck(true); //radio.setPALevel( RF24_PA_LOW ) ; // @@ -137,13 +137,10 @@ void setup(void) // 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 ) - { + if (role == role_ping_out) { radio.openWritingPipe(pipes[0]); radio.openReadingPipe(1, pipes[1]); - } - else - { + } else { radio.openWritingPipe(pipes[1]); radio.openReadingPipe(1, pipes[0]); } @@ -151,7 +148,7 @@ void setup(void) // // Start listening // - radio.powerUp() ; + radio.powerUp(); radio.startListening(); // @@ -161,14 +158,12 @@ void setup(void) radio.printDetails(); } -void loop(void) -{ +void loop(void) { // // Ping out role. Repeatedly send the current time // - if (role == role_ping_out) - { + 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"; @@ -178,7 +173,7 @@ void loop(void) // Take the time, and send it. This will block until complete Serial.print(F("Now sending length ")); Serial.println(next_payload_size); - radio.write( send_payload, next_payload_size, multicast ); + radio.write(send_payload, next_payload_size, multicast); // Now, continue listening radio.startListening(); @@ -186,20 +181,17 @@ void loop(void) // 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 ) + while (!radio.available() && !timeout) + if (millis() - started_waiting_at > 500) timeout = true; // Describe the results - if ( timeout ) - { + if (timeout) { Serial.println(F("Failed, response timed out.")); - } - else - { + } else { // Grab the response, compare, and send to debugging spew uint8_t len = radio.getDynamicPayloadSize(); - radio.read( receive_payload, len ); + radio.read(receive_payload, len); // Put a zero at the end for easy printing receive_payload[len] = 0; @@ -213,7 +205,7 @@ void loop(void) // Update size for next time. next_payload_size += payload_size_increments_by; - if ( next_payload_size > max_payload_size ) + if (next_payload_size > max_payload_size) next_payload_size = min_payload_size; // Try again 1s later @@ -224,19 +216,16 @@ void loop(void) // Pong back role. Receive each packet, dump it out, and send it back // - if ( role == role_pong_back ) - { + if (role == role_pong_back) { // if there is data ready - if ( radio.available() ) - { + if (radio.available()) { // Dump the payloads until we've gotten everything uint8_t len; bool done = false; - while (radio.available()) - { + while (radio.available()) { // Fetch the payload, and see if this was the last one. len = radio.getDynamicPayloadSize(); - radio.read( receive_payload, len ); + radio.read(receive_payload, len); // Put a zero at the end for easy printing receive_payload[len] = 0; @@ -252,7 +241,7 @@ void loop(void) radio.stopListening(); // Send the final one back. - radio.write( receive_payload, len, multicast ); + radio.write(receive_payload, len, multicast); Serial.println(F("Sent response.")); // Now, resume listening so we catch the next packets. diff --git a/examples/old_backups/pingpair_sleepy/pingpair_sleepy.ino b/examples/old_backups/pingpair_sleepy/pingpair_sleepy.ino index 7f034b3c5..7122dc652 100644 --- a/examples/old_backups/pingpair_sleepy/pingpair_sleepy.ino +++ b/examples/old_backups/pingpair_sleepy/pingpair_sleepy.ino @@ -11,17 +11,17 @@ */ /** - Example RF Radio Ping Pair which Sleeps between Sends + 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. + 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. + 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 @@ -39,7 +39,7 @@ RF24 radio(7, 8); // 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. +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 @@ -47,17 +47,27 @@ const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL }; // Radio pipe ad // which node it is. // The various roles supported by this sketch -typedef enum { role_ping_out = 1, role_pong_back } role_e; +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"}; +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; +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); @@ -72,10 +82,10 @@ 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 + delay(20); // Just to get a solid reading on the role pin // read the address pin, establish our role - if ( digitalRead(role_pin) ) + if (digitalRead(role_pin)) role = role_ping_out; else role = role_pong_back; @@ -101,7 +111,7 @@ void setup() { // 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 ) { + if (role == role_ping_out) { radio.openWritingPipe(pipes[0]); radio.openReadingPipe(1, pipes[1]); } else { @@ -119,69 +129,66 @@ void setup() { 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. + 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. + unsigned long time = millis(); // Take the time, and send it. Serial.print(F("Now sending... ")); Serial.println(time); - radio.write( &time, sizeof(unsigned long) ); + radio.write(&time, sizeof(unsigned long)); - radio.startListening(); // Now, continue listening + radio.startListening(); // Now, continue listening - unsigned long started_waiting_at = millis(); // Wait here until we get a response, or timeout (250ms) + 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 + 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 + if (timeout) { // Describe the results Serial.println(F("Failed, response timed out.")); } else { - unsigned long got_time; // Grab the response, compare, and send to debugging spew - radio.read( &got_time, sizeof(unsigned long) ); + 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 + 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 + 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 (role == role_pong_back) { - if ( radio.available() ) { // if there is data ready + 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. + 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 + 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. + radio.stopListening(); // First, stop listening so we can talk + radio.write(&got_time, sizeof(unsigned long)); // Send the final one back. Serial.println(F("Sent response.")); - radio.startListening(); // Now, resume listening so we catch the next packets. + radio.startListening(); // Now, resume listening so we catch the next packets. } else { Serial.println(F("Sleeping")); - delay(50); // Delay so the serial data can print out + delay(50); // Delay so the serial data can print out do_sleep(); - } } } @@ -199,28 +206,26 @@ void wakeUp() { void setup_watchdog(uint8_t prescalar) { uint8_t wdtcsr = prescalar & 7; - if ( prescalar & 8 ) + 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) -{ +ISR(WDT_vect) { //--sleep_cycles_remaining; Serial.println(F("WDT")); } -void do_sleep(void) -{ - set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here +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 + sleep_mode(); // System sleeps here // The WDT_vect interrupt wakes the MCU from here - sleep_disable(); // System continues execution here when watchdog timed out + sleep_disable(); // System continues execution here when watchdog timed out detachInterrupt(0); WDTCSR &= ~_BV(WDIE); } diff --git a/examples/old_backups/recipes/led_remote/led_remote.ino b/examples/old_backups/recipes/led_remote/led_remote.ino index f1394f619..49df953d1 100644 --- a/examples/old_backups/recipes/led_remote/led_remote.ino +++ b/examples/old_backups/recipes/led_remote/led_remote.ino @@ -7,22 +7,22 @@ */ /** - Example LED Remote + 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. + 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 '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. + 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. + Every time the buttons change on the remote, the entire state of + buttons is send to the led board, which displays the state. */ #include @@ -68,10 +68,11 @@ const uint64_t pipe = 0xE8E8F0F0E1LL; // // The various roles supported by this sketch -typedef enum { role_remote = 1, role_led } role_e; +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"}; +const char* role_friendly_name[] = { "invalid", "Remote", "LED Board" }; // The role of the current running sketch role_e role; @@ -87,8 +88,7 @@ uint8_t led_states[num_led_pins]; // Setup // -void setup(void) -{ +void setup(void) { // // Role // @@ -96,10 +96,10 @@ void setup(void) // 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 + delay(20); // Just to get a solid reading on the role pin // read the address pin, establish our role - if ( digitalRead(role_pin) ) + if (digitalRead(role_pin)) role = role_remote; else role = role_led; @@ -126,12 +126,9 @@ void setup(void) // 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 ) - { + if (role == role_remote) { radio.openWritingPipe(pipe); - } - else - { + } else { radio.openReadingPipe(1, pipe); } @@ -139,7 +136,7 @@ void setup(void) // Start listening // - if ( role == role_led ) + if (role == role_led) radio.startListening(); // @@ -153,62 +150,52 @@ void setup(void) // // Set pull-up resistors for all buttons - if ( role == role_remote ) - { + if (role == role_remote) { int i = num_button_pins; - while (i--) - { + 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 ) - { + if (role == role_led) { int i = num_led_pins; - while (i--) - { + while (i--) { pinMode(led_pins[i], OUTPUT); led_states[i] = HIGH; digitalWrite(led_pins[i], led_states[i]); } } - } // // Loop // -void loop(void) -{ +void loop(void) { // // Remote role. If the state of any button has changed, send the whole state of // all buttons. // - if ( role == role_remote ) - { + 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] ) - { + 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 ) - { + if (different) { printf("Now sending..."); - bool ok = radio.write( button_states, num_button_pins ); + bool ok = radio.write(button_states, num_button_pins); if (ok) printf("ok\n\r"); else @@ -223,26 +210,21 @@ void loop(void) // LED role. Receive the state of all buttons, and reflect that in the LEDs // - if ( role == role_led ) - { + if (role == role_led) { // if there is data ready - if ( radio.available() ) - { + if (radio.available()) { // Dump the payloads until we've gotten everything - while (radio.available()) - { + while (radio.available()) { // Fetch the payload, and see if this was the last one. - radio.read( button_states, num_button_pins ); + 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] ) - { + while (i--) { + if (button_states[i]) { led_states[i] ^= HIGH; digitalWrite(led_pins[i], led_states[i]); } diff --git a/examples/old_backups/recipes/nordic_fob/nordic_fob.ino b/examples/old_backups/recipes/nordic_fob/nordic_fob.ino index cf40cbce7..518b1ba36 100644 --- a/examples/old_backups/recipes/nordic_fob/nordic_fob.ino +++ b/examples/old_backups/recipes/nordic_fob/nordic_fob.ino @@ -7,12 +7,12 @@ */ /** - Example Nordic FOB Receiver + 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. + 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/ + See blog post at http://maniacbug.wordpress.com/2012/01/08/nordic-fob/ */ #include @@ -32,8 +32,7 @@ RF24 radio(9, 10); // Payload // -struct payload_t -{ +struct payload_t { uint8_t buttons; uint16_t id; uint8_t empty; @@ -52,8 +51,7 @@ uint16_t flip_endian(uint16_t in); // Setup // -void setup(void) -{ +void setup(void) { // // Print preamble // @@ -91,18 +89,16 @@ void setup(void) // Loop // -void loop(void) -{ +void loop(void) { // // Receive each packet, dump it out // // if there is data ready - if ( radio.available() ) - { + if (radio.available()) { // Get the packet from the radio payload_t payload; - radio.read( &payload, sizeof(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. @@ -110,16 +106,14 @@ void loop(void) // Print the name of each button int i = num_buttons; - while (i--) - { - if ( ! ( payload.buttons & _BV(i) ) ) - { + while (i--) { + if (!(payload.buttons & _BV(i))) { printf("%s ", button_names[i]); } } // If no buttons, print None - if ( payload.buttons == _BV(num_buttons) - 1 ) + if (payload.buttons == _BV(num_buttons) - 1) printf("None"); printf("\r\n"); @@ -131,8 +125,7 @@ void loop(void) // // Change a big-endian word into a little-endian -uint16_t flip_endian(uint16_t in) -{ +uint16_t flip_endian(uint16_t in) { uint16_t low = in >> 8; uint16_t high = in << 8; diff --git a/examples/old_backups/recipes/pingpair_maple/main.cpp b/examples/old_backups/recipes/pingpair_maple/main.cpp index a6f505a4e..be3ea983a 100644 --- a/examples/old_backups/recipes/pingpair_maple/main.cpp +++ b/examples/old_backups/recipes/pingpair_maple/main.cpp @@ -1,87 +1,77 @@ -#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 +#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/examples/old_backups/recipes/pingpair_maple/pingpair_maple.ino b/examples/old_backups/recipes/pingpair_maple/pingpair_maple.ino index 83d99c8ac..821834b3f 100644 --- a/examples/old_backups/recipes/pingpair_maple/pingpair_maple.ino +++ b/examples/old_backups/recipes/pingpair_maple/pingpair_maple.ino @@ -7,12 +7,12 @@ */ /** - Example RF Radio Ping Pair ... for Maple + 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. + 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" @@ -70,16 +70,16 @@ const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL }; // // The various roles supported by this sketch -typedef enum { role_ping_out = 1, role_pong_back } role_e; +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"}; +const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back" }; // The role of the current running sketch role_e role; -void setup(void) -{ +void setup(void) { // // Role // @@ -87,10 +87,10 @@ void setup(void) // 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 + delay(20); // Just to get a solid reading on the role pin // read the address pin, establish our role - if ( digitalRead(role_pin) ) + if (digitalRead(role_pin)) role = role_ping_out; else role = role_pong_back; @@ -124,13 +124,10 @@ void setup(void) // 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 ) - { + if (role == role_ping_out) { radio.openWritingPipe(pipes[0]); radio.openReadingPipe(1, pipes[1]); - } - else - { + } else { radio.openWritingPipe(pipes[1]); radio.openReadingPipe(1, pipes[0]); } @@ -148,14 +145,12 @@ void setup(void) radio.printDetails(); } -void loop(void) -{ +void loop(void) { // // Ping out role. Repeatedly send the current time // - if (role == role_ping_out) - { + if (role == role_ping_out) { toggleLED(); // First, stop listening so we can talk. @@ -164,7 +159,7 @@ void loop(void) // 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) ); + bool ok = radio.write(&time, sizeof(unsigned long)); if (ok) printf("ok...\r\n"); @@ -177,20 +172,17 @@ void loop(void) // 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 ) + while (!radio.available() && !timeout) + if (millis() - started_waiting_at > 200) timeout = true; // Describe the results - if ( timeout ) - { + if (timeout) { printf("Failed, response timed out.\r\n"); - } - else - { + } else { // Grab the response, compare, and send to debugging spew unsigned long got_time; - radio.read( &got_time, sizeof(unsigned long) ); + radio.read(&got_time, sizeof(unsigned long)); // Spew it printf("Got response %lu, round-trip delay: %lu\r\n", got_time, millis() - got_time); @@ -206,18 +198,15 @@ void loop(void) // Pong back role. Receive each packet, dump it out, and send it back // - if ( role == role_pong_back ) - { + if (role == role_pong_back) { // if there is data ready - if ( radio.available() ) - { + if (radio.available()) { // Dump the payloads until we've gotten everything unsigned long got_time; bool done = false; - while (!done) - { + while (!done) { // Fetch the payload, and see if this was the last one. - done = radio.read( &got_time, sizeof(unsigned long) ); + done = radio.read(&got_time, sizeof(unsigned long)); // Spew it printf("Got payload %lu...", got_time); @@ -231,7 +220,7 @@ void loop(void) radio.stopListening(); // Send the final one back. - radio.write( &got_time, sizeof(unsigned long) ); + radio.write(&got_time, sizeof(unsigned long)); printf("Sent response.\r\n"); // Now, resume listening so we catch the next packets. diff --git a/examples/rf24_ATTiny/rf24ping85/rf24ping85.ino b/examples/rf24_ATTiny/rf24ping85/rf24ping85.ino index 49bec97e5..bca78908d 100644 --- a/examples/rf24_ATTiny/rf24ping85/rf24ping85.ino +++ b/examples/rf24_ATTiny/rf24ping85/rf24ping85.ino @@ -94,13 +94,13 @@ RF24 radio(CE_PIN, CSN_PIN); // Let these addresses be used for the pair -uint8_t address[][6] = {"1Node", "2Node"}; +uint8_t address[][6] = { "1Node", "2Node" }; // It is very helpful to think of an address as a path instead of as // an identifying device destination // to use different addresses on a pair of radios, we need a variable to // uniquely identify which address this radio will use to transmit -bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit +bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit // Used to control whether this node is sending or receiving bool role = false; // true = TX node, false = RX node @@ -110,7 +110,7 @@ bool role = false; // true = TX node, false = RX node // on every successful transmission. // Make a data structure to store the entire payload of different datatypes struct PayloadStruct { - char message[7]; // only using 6 characters for TX & RX payloads + char message[7]; // only using 6 characters for TX & RX payloads uint8_t counter; }; PayloadStruct payload; @@ -122,63 +122,63 @@ void setup() { // initialize the transceiver on the SPI bus if (!radio.begin()) { - while (1) {} // hold in infinite loop + while (1) {} // hold in infinite loop } // Set the PA Level low to try preventing power supply related problems // because these examples are likely run with nodes in close proximity to // each other. - radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. + radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. // save on transmission time by setting the radio to only transmit the // number of bytes we need to transmit a float - radio.setPayloadSize(sizeof(payload)); // char[7] & uint8_t datatypes occupy 8 bytes + radio.setPayloadSize(sizeof(payload)); // char[7] & uint8_t datatypes occupy 8 bytes // set the TX address of the RX node into the TX pipe - radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 + radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 // set the RX address of the TX node into a RX pipe - radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 + radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 if (role) { // setup the TX node - memcpy(payload.message, "Hello ", 6); // set the outgoing message - radio.stopListening(); // put radio in TX mode + memcpy(payload.message, "Hello ", 6); // set the outgoing message + radio.stopListening(); // put radio in TX mode } else { // setup the RX node - memcpy(payload.message, "World ", 6); // set the outgoing message - radio.startListening(); // put radio in RX mode + memcpy(payload.message, "World ", 6); // set the outgoing message + radio.startListening(); // put radio in RX mode } -} // setup() +} // setup() void loop() { if (role) { // This device is a TX node - bool report = radio.write(&payload, sizeof(payload)); // transmit & save the report + bool report = radio.write(&payload, sizeof(payload)); // transmit & save the report if (report) { // transmission successful; wait for response and print results - radio.startListening(); // put in RX mode - unsigned long start_timeout = millis(); // timer to detect no response - while (!radio.available()) { // wait for response or timeout - if (millis() - start_timeout > 200) // only wait 200 ms + radio.startListening(); // put in RX mode + unsigned long start_timeout = millis(); // timer to detect no response + while (!radio.available()) { // wait for response or timeout + if (millis() - start_timeout > 200) // only wait 200 ms break; } - radio.stopListening(); // put back in TX mode + radio.stopListening(); // put back in TX mode // print summary of transactions - if (radio.available()) { // is there a payload received? + if (radio.available()) { // is there a payload received? PayloadStruct received; - radio.read(&received, sizeof(received)); // get payload from RX FIFO - payload.counter = received.counter; // save incoming counter for next outgoing counter + radio.read(&received, sizeof(received)); // get payload from RX FIFO + payload.counter = received.counter; // save incoming counter for next outgoing counter } - } // report + } // report // to make this example readable in the serial monitor delay(1000); // slow transmissions down by 1 second @@ -186,19 +186,19 @@ void loop() { } else { // This device is a RX node - if (radio.available()) { // is there a payload? + if (radio.available()) { // is there a payload? PayloadStruct received; - radio.read(&received, sizeof(received)); // get incoming payload - payload.counter = received.counter + 1; // increment incoming counter for next outgoing response + radio.read(&received, sizeof(received)); // get incoming payload + payload.counter = received.counter + 1; // increment incoming counter for next outgoing response // transmit response & save result to `report` - radio.stopListening(); // put in TX mode + radio.stopListening(); // put in TX mode - radio.writeFast(&payload, sizeof(payload)); // load response to TX FIFO - radio.txStandBy(150); // keep retrying for 150 ms + radio.writeFast(&payload, sizeof(payload)); // load response to TX FIFO + radio.txStandBy(150); // keep retrying for 150 ms - radio.startListening(); // put back in RX mode + radio.startListening(); // put back in RX mode } - } // role -} // loop \ No newline at end of file + } // role +} // loop diff --git a/examples/rf24_ATTiny/timingSearch3pin/timingSearch3pin.ino b/examples/rf24_ATTiny/timingSearch3pin/timingSearch3pin.ino index ea1cd6ac3..d554c0452 100644 --- a/examples/rf24_ATTiny/timingSearch3pin/timingSearch3pin.ino +++ b/examples/rf24_ATTiny/timingSearch3pin/timingSearch3pin.ino @@ -23,7 +23,7 @@ #include -#if defined (ARDUINO) && !defined (__arm__) +#if defined(ARDUINO) && !defined(__arm__) #if defined(__AVR_ATtinyX5__) || defined(__AVR_ATtinyX4__) #define RF24_TINY #endif @@ -34,26 +34,26 @@ #if defined(RF24_TINY) // when Attiny84 or Attiny85 is detected -#define CE_PIN 3 /** "Chip Enable" pin, activates the RX or TX role */ -#define CSN_PIN 3 /** SPI Chip Select Not */ +#define CE_PIN 3 /** "Chip Enable" pin, activates the RX or TX role */ +#define CSN_PIN 3 /** SPI Chip Select Not */ #else // when not running on an ATTiny84 or ATTiny85 -#define CE_PIN 7 /** "Chip Enable" pin, activates the RX or TX role */ -#define CSN_PIN 8 /** SPI Chip Select Not */ +#define CE_PIN 7 /** "Chip Enable" pin, activates the RX or TX role */ +#define CSN_PIN 8 /** SPI Chip Select Not */ #endif -#define MAX_HIGH 100 -#define MAX_LOW 100 -#define MINIMAL 8 +#define MAX_HIGH 100 +#define MAX_LOW 100 +#define MINIMAL 8 // Use these adjustable variables to test for best configuration to be used on // the ATTiny chips. These variables are defined as macros in the library's // RF24/utility/ATTiny/RF24_arch_config.h file. To change them, simply define // the corresponding macro(s) before #include in your sketch. -uint8_t csnHighSettle = MAX_HIGH; // defined as RF24_CSN_SETTLE_HIGH_DELAY -uint8_t csnLowSettle = MAX_LOW; // defined as RF24_CSN_SETTLE_LOW_DELAY +uint8_t csnHighSettle = MAX_HIGH; // defined as RF24_CSN_SETTLE_HIGH_DELAY +uint8_t csnLowSettle = MAX_LOW; // defined as RF24_CSN_SETTLE_LOW_DELAY /****************************************************************************/ void ce(bool level) { @@ -67,18 +67,17 @@ void csn(bool mode) { } else { // digitalWrite(SCK, mode); if (mode == HIGH) { - PORTB |= (1 << PINB2); // SCK->CSN HIGH - delayMicroseconds(csnHighSettle); // allow csn to settle + PORTB |= (1 << PINB2); // SCK->CSN HIGH + delayMicroseconds(csnHighSettle); // allow csn to settle } else { - PORTB &= ~(1 << PINB2); // SCK->CSN LOW + PORTB &= ~(1 << PINB2); // SCK->CSN LOW delayMicroseconds(csnLowSettle); // allow csn to settle } } } /****************************************************************************/ -uint8_t read_register(uint8_t reg) -{ +uint8_t read_register(uint8_t reg) { csn(LOW); SPI.transfer(R_REGISTER | reg); uint8_t result = SPI.transfer(0xff); @@ -87,8 +86,7 @@ uint8_t read_register(uint8_t reg) } /****************************************************************************/ -void write_register(uint8_t reg, uint8_t value) -{ +void write_register(uint8_t reg, uint8_t value) { csn(LOW); SPI.transfer(W_REGISTER | reg); SPI.transfer(value); @@ -124,7 +122,7 @@ void setup(void) { // Technically we require 4.5ms Tpd2stby+ 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. write_register(NRF_CONFIG, read_register(NRF_CONFIG) | _BV(PWR_UP)); - delay(5) ; + delay(5); // Goto Standby-II ce(HIGH); @@ -133,13 +131,13 @@ void setup(void) { /************************** Main program *********************************/ - uint8_t result; // used to compare read/write results with read/write cmds + uint8_t result; // used to compare read/write results with read/write cmds bool success = true; uint8_t bottom_success; bool bottom_found; - uint8_t value[] = {5, 10}; - uint8_t limit[] = {MAX_HIGH, MAX_LOW}; - uint8_t advice[] = {MAX_HIGH, MAX_LOW}; + uint8_t value[] = { 5, 10 }; + uint8_t limit[] = { MAX_HIGH, MAX_LOW }; + uint8_t advice[] = { MAX_HIGH, MAX_LOW }; // check max values give correct behavior for (uint8_t k = 0; k < 2; k++) { @@ -186,7 +184,7 @@ void setup(void) { bottom_success++; } } - } // while (bottom_success < 255) + } // while (bottom_success < 255) Serial.print("Settle value found for "); if (k == 0) { Serial.print("csnHigh: "); @@ -196,14 +194,14 @@ void setup(void) { Serial.println(limit[k], DEC); advice[k] = limit[k] + (limit[k] / 10); limit[k] = 100; - } // for (uint8_t k = 0; k < 2; k++) + } // for (uint8_t k = 0; k < 2; k++) Serial.print("Advised Settle times are: csnHigh="); Serial.print(advice[0], DEC); Serial.print(" csnLow="); Serial.println(advice[1], DEC); -#endif // not defined __AVR_ATtinyX313__ +#endif // not defined __AVR_ATtinyX313__ } -void loop(void) {} // this program runs only once, thus it resides in setup() +void loop(void) {} // this program runs only once, thus it resides in setup() diff --git a/examples/scanner/scanner.ino b/examples/scanner/scanner.ino index 0473193d0..79dabd9f7 100644 --- a/examples/scanner/scanner.ino +++ b/examples/scanner/scanner.ino @@ -44,8 +44,7 @@ uint8_t values[num_channels]; // Setup // -void setup(void) -{ +void setup(void) { // // Print preamble // @@ -69,15 +68,13 @@ void setup(void) //delay(1000); // Print out header, high then low digit int i = 0; - while ( i < num_channels ) - { + while (i < num_channels) { Serial.print(i >> 4, HEX); ++i; } Serial.println(); i = 0; - while ( i < num_channels ) - { + while (i < num_channels) { Serial.print(i & 0xf, HEX); ++i; } @@ -92,8 +89,7 @@ void setup(void) const int num_reps = 100; bool constCarrierMode = 0; -void loop(void) -{ +void loop(void) { /****************************************/ // Send g over Serial to begin CCW output // Configure the channel and power level below @@ -119,11 +115,9 @@ void loop(void) // Scan all channels num_reps times int rep_counter = num_reps; - while (rep_counter--) - { + while (rep_counter--) { int i = num_channels; - while (i--) - { + while (i--) { // Select this channel radio.setChannel(i); @@ -133,7 +127,7 @@ void loop(void) radio.stopListening(); // Did we get a carrier? - if ( radio.testCarrier() ) { + if (radio.testCarrier()) { ++values[i]; } } @@ -142,8 +136,7 @@ void loop(void) // Print out channel measurements, clamped to a single hex digit int i = 0; - while ( i < num_channels ) - { + while (i < num_channels) { if (values[i]) Serial.print(min(0xf, values[i]), HEX); else @@ -153,5 +146,5 @@ void loop(void) } Serial.println(); - }//If constCarrierMode == 0 + } //If constCarrierMode == 0 } diff --git a/examples_linux/acknowledgementPayloads.cpp b/examples_linux/acknowledgementPayloads.cpp index d72831cb2..f81c8b8d5 100644 --- a/examples_linux/acknowledgementPayloads.cpp +++ b/examples_linux/acknowledgementPayloads.cpp @@ -1,230 +1,231 @@ -/* - * See documentation at https://nRF24.github.io/RF24 - * See License information at root directory of this library - * Author: Brendan Doherty (2bndy5) - */ - -/** - * A simple example of sending data from 1 nRF24L01 transceiver to another - * with Acknowledgement (ACK) payloads attached to ACK packets. - * - * This example was written to be used on 2 devices acting as "nodes". - * Use `ctrl+c` to quit at any time. - */ -#include // time() -#include // cin, cout, endl -#include // string, getline() -#include // CLOCK_MONOTONIC_RAW, timespec, clock_gettime() -#include // RF24, RF24_PA_LOW, delay() - -using namespace std; - -/****************** Linux ***********************/ -// Radio CE Pin, CSN Pin, SPI Speed -// CE Pin uses GPIO number with BCM and SPIDEV drivers, other platforms use their own pin numbering -// CS Pin addresses the SPI bus number at /dev/spidev. -// ie: RF24 radio(, *10+); spidev1.0 is 10, spidev1.1 is 11 etc.. - -// Generic: -RF24 radio(22, 0); -/****************** Linux (BBB,x86,etc) ***********************/ -// See http://nRF24.github.io/RF24/pages.html for more information on usage -// See http://iotdk.intel.com/docs/master/mraa/ for more information on MRAA -// See https://www.kernel.org/doc/Documentation/spi/spidev for more information on SPIDEV - -// For this example, we'll be using a payload containing -// a string & an integer number that will be incremented -// on every successful transmission. -// Make a data structure to store the entire payload of different datatypes -struct PayloadStruct { - char message[7]; // only using 6 characters for TX & ACK payloads - uint8_t counter; -}; -PayloadStruct payload; - -void setRole(); // prototype to set the node's role -void master(); // prototype of the TX node's behavior -void slave(); // prototype of the RX node's behavior - -// custom defined timer for evaluating transmission time in microseconds -struct timespec startTimer, endTimer; -uint32_t getMicros(); // prototype to get ellapsed time in microseconds - - -int main(int argc, char** argv) { - // perform hardware check - if (!radio.begin()) { - cout << "radio hardware is not responding!!" << endl; - return 0; // quit now - } - - // Let these addresses be used for the pair - uint8_t address[2][6] = {"1Node", "2Node"}; - // It is very helpful to think of an address as a path instead of as - // an identifying device destination - - // to use different addresses on a pair of radios, we need a variable to - // uniquely identify which address this radio will use to transmit - bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit - - // print example's name - cout << argv[0] << endl; - - // Set the radioNumber via the terminal on startup - cout << "Which radio is this? Enter '0' or '1'. Defaults to '0' "; - string input; - getline(cin, input); - radioNumber = input.length() > 0 && (uint8_t)input[0] == 49; - - // to use ACK payloads, we need to enable dynamic payload lengths - radio.enableDynamicPayloads(); // ACK payloads are dynamically sized - - // Acknowledgement packets have no payloads by default. We need to enable - // this feature for all nodes (TX & RX) to use ACK payloads. - radio.enableAckPayload(); - - // Set the PA Level low to try preventing power supply related problems - // because these examples are likely run with nodes in close proximity to - // each other. - radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. - - // set the TX address of the RX node into the TX pipe - radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 - - // set the RX address of the TX node into a RX pipe - radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 - - // For debugging info - // radio.printDetails(); // (smaller) function that prints raw register values - // radio.printPrettyDetails(); // (larger) function that prints human readable data - - // ready to execute program now - setRole(); // calls master() or slave() based on user input - return 0; -} - - -/** - * set this node's role from stdin stream. - * this only considers the first char as input. - */ -void setRole() { - string input = ""; - while (!input.length()) { - cout << "*** PRESS 'T' to begin transmitting to the other node\n"; - cout << "*** PRESS 'R' to begin receiving from the other node\n"; - cout << "*** PRESS 'Q' to exit" << endl; - getline(cin, input); - if (input.length() >= 1) { - if (input[0] == 'T' || input[0] == 't') - master(); - else if (input[0] == 'R' || input[0] == 'r') - slave(); - else if (input[0] == 'Q' || input[0] == 'q') - break; - else - cout << input[0] << " is an invalid input. Please try again." << endl; - } - input = ""; // stay in the while loop - } // while -} // setRole() - - -/** - * make this node act as the transmitter - */ -void master() { - memcpy(payload.message, "Hello ", 6); // set the payload message - radio.stopListening(); // put radio in TX mode - - unsigned int failures = 0; // keep track of failures - while (failures < 6) { - clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer); // start the timer - bool report = radio.write(&payload, sizeof(payload)); // transmit & save the report - uint32_t timerEllapsed = getMicros(); // end the timer - - if (report) { - // payload was delivered - cout << "Transmission successful! Time to transmit = "; - cout << timerEllapsed; // print the timer result - cout << " us. Sent: "; - cout << payload.message; // print outgoing message - cout << (unsigned int)payload.counter; // print outgoing counter counter - - uint8_t pipe; - if (radio.available(&pipe)) { - PayloadStruct received; - radio.read(&received, sizeof(received)); // get incoming ACK payload - cout << " Received "; - cout << (unsigned int)radio.getDynamicPayloadSize(); // print incoming payload size - cout << " bytes on pipe " << (unsigned int)pipe; // print pipe that received it - cout << ": " << received.message; // print incoming message - cout << (unsigned int)received.counter << endl; // print incoming counter - payload.counter = received.counter + 1; // save incoming counter & increment for next outgoing - } // if got an ACK payload - else { - cout << " Received an empty ACK packet." << endl; // ACK had no payload - } - } // if delivered - else { - cout << "Transmission failed or timed out" << endl; // payload was not delivered - failures++; // increment failures - } - - // to make this example readable in the terminal - delay(1000); // slow transmissions down by 1 second - } // while - cout << failures << " failures detected. Leaving TX role." << endl; -} // master - - -/** - * make this node act as the receiver - */ -void slave() { - memcpy(payload.message, "World ", 6); // set the payload message - - // load the payload for the first received transmission on pipe 0 - radio.writeAckPayload(1, &payload, sizeof(payload)); - - radio.startListening(); // put radio in RX mode - time_t startTimer = time(nullptr); // start a timer - while (time(nullptr) - startTimer < 6) { // use 6 second timeout - uint8_t pipe; - if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it - uint8_t bytes = radio.getDynamicPayloadSize(); // get the size of the payload - PayloadStruct received; - radio.read(&received, sizeof(received)); // fetch payload from RX FIFO - cout << "Received " << (unsigned int)bytes; // print the size of the payload - cout << " bytes on pipe " << (unsigned int)pipe; // print the pipe number - cout << ": " << received.message; - cout << (unsigned int)received.counter; // print received payload - cout << " Sent: "; - cout << payload.message; - cout << (unsigned int)payload.counter << endl; // print ACK payload sent - startTimer = time(nullptr); // reset timer - - // save incoming counter & increment for next outgoing - payload.counter = received.counter + 1; - // load the payload for the first received transmission on pipe 0 - radio.writeAckPayload(1, &payload, sizeof(payload)); - } // if received something - } // while - cout << "Nothing received in 6 seconds. Leaving RX role." << endl; - radio.stopListening(); // recommended idle behavior is TX mode -} // slave - - -/** - * Calculate the ellapsed time in microseconds - */ -uint32_t getMicros() { - // this function assumes that the timer was started using - // `clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer);` - - clock_gettime(CLOCK_MONOTONIC_RAW, &endTimer); - uint32_t seconds = endTimer.tv_sec - startTimer.tv_sec; - uint32_t useconds = (endTimer.tv_nsec - startTimer.tv_nsec) / 1000; - - return ((seconds) * 1000 + useconds) + 0.5; -} +/* + * See documentation at https://nRF24.github.io/RF24 + * See License information at root directory of this library + * Author: Brendan Doherty (2bndy5) + */ + +/** + * A simple example of sending data from 1 nRF24L01 transceiver to another + * with Acknowledgement (ACK) payloads attached to ACK packets. + * + * This example was written to be used on 2 devices acting as "nodes". + * Use `ctrl+c` to quit at any time. + */ +#include // time() +#include // cin, cout, endl +#include // string, getline() +#include // CLOCK_MONOTONIC_RAW, timespec, clock_gettime() +#include // RF24, RF24_PA_LOW, delay() + +using namespace std; + +/****************** Linux ***********************/ +// Radio CE Pin, CSN Pin, SPI Speed +// CE Pin uses GPIO number with BCM and SPIDEV drivers, other platforms use their own pin numbering +// CS Pin addresses the SPI bus number at /dev/spidev. +// ie: RF24 radio(, *10+); spidev1.0 is 10, spidev1.1 is 11 etc.. + +// Generic: +RF24 radio(22, 0); +/****************** Linux (BBB,x86,etc) ***********************/ +// See http://nRF24.github.io/RF24/pages.html for more information on usage +// See http://iotdk.intel.com/docs/master/mraa/ for more information on MRAA +// See https://www.kernel.org/doc/Documentation/spi/spidev for more information on SPIDEV + +// For this example, we'll be using a payload containing +// a string & an integer number that will be incremented +// on every successful transmission. +// Make a data structure to store the entire payload of different datatypes +struct PayloadStruct +{ + char message[7]; // only using 6 characters for TX & ACK payloads + uint8_t counter; +}; +PayloadStruct payload; + +void setRole(); // prototype to set the node's role +void master(); // prototype of the TX node's behavior +void slave(); // prototype of the RX node's behavior + +// custom defined timer for evaluating transmission time in microseconds +struct timespec startTimer, endTimer; +uint32_t getMicros(); // prototype to get ellapsed time in microseconds + +int main(int argc, char** argv) +{ + // perform hardware check + if (!radio.begin()) { + cout << "radio hardware is not responding!!" << endl; + return 0; // quit now + } + + // Let these addresses be used for the pair + uint8_t address[2][6] = {"1Node", "2Node"}; + // It is very helpful to think of an address as a path instead of as + // an identifying device destination + + // to use different addresses on a pair of radios, we need a variable to + // uniquely identify which address this radio will use to transmit + bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit + + // print example's name + cout << argv[0] << endl; + + // Set the radioNumber via the terminal on startup + cout << "Which radio is this? Enter '0' or '1'. Defaults to '0' "; + string input; + getline(cin, input); + radioNumber = input.length() > 0 && (uint8_t)input[0] == 49; + + // to use ACK payloads, we need to enable dynamic payload lengths + radio.enableDynamicPayloads(); // ACK payloads are dynamically sized + + // Acknowledgement packets have no payloads by default. We need to enable + // this feature for all nodes (TX & RX) to use ACK payloads. + radio.enableAckPayload(); + + // Set the PA Level low to try preventing power supply related problems + // because these examples are likely run with nodes in close proximity to + // each other. + radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. + + // set the TX address of the RX node into the TX pipe + radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 + + // set the RX address of the TX node into a RX pipe + radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 + + // For debugging info + // radio.printDetails(); // (smaller) function that prints raw register values + // radio.printPrettyDetails(); // (larger) function that prints human readable data + + // ready to execute program now + setRole(); // calls master() or slave() based on user input + return 0; +} + +/** + * set this node's role from stdin stream. + * this only considers the first char as input. + */ +void setRole() +{ + string input = ""; + while (!input.length()) { + cout << "*** PRESS 'T' to begin transmitting to the other node\n"; + cout << "*** PRESS 'R' to begin receiving from the other node\n"; + cout << "*** PRESS 'Q' to exit" << endl; + getline(cin, input); + if (input.length() >= 1) { + if (input[0] == 'T' || input[0] == 't') + master(); + else if (input[0] == 'R' || input[0] == 'r') + slave(); + else if (input[0] == 'Q' || input[0] == 'q') + break; + else + cout << input[0] << " is an invalid input. Please try again." << endl; + } + input = ""; // stay in the while loop + } // while +} // setRole() + +/** + * make this node act as the transmitter + */ +void master() +{ + memcpy(payload.message, "Hello ", 6); // set the payload message + radio.stopListening(); // put radio in TX mode + + unsigned int failures = 0; // keep track of failures + while (failures < 6) { + clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer); // start the timer + bool report = radio.write(&payload, sizeof(payload)); // transmit & save the report + uint32_t timerEllapsed = getMicros(); // end the timer + + if (report) { + // payload was delivered + cout << "Transmission successful! Time to transmit = "; + cout << timerEllapsed; // print the timer result + cout << " us. Sent: "; + cout << payload.message; // print outgoing message + cout << (unsigned int)payload.counter; // print outgoing counter counter + + uint8_t pipe; + if (radio.available(&pipe)) { + PayloadStruct received; + radio.read(&received, sizeof(received)); // get incoming ACK payload + cout << " Received "; + cout << (unsigned int)radio.getDynamicPayloadSize(); // print incoming payload size + cout << " bytes on pipe " << (unsigned int)pipe; // print pipe that received it + cout << ": " << received.message; // print incoming message + cout << (unsigned int)received.counter << endl; // print incoming counter + payload.counter = received.counter + 1; // save incoming counter & increment for next outgoing + } // if got an ACK payload + else { + cout << " Received an empty ACK packet." << endl; // ACK had no payload + } + } // if delivered + else { + cout << "Transmission failed or timed out" << endl; // payload was not delivered + failures++; // increment failures + } + + // to make this example readable in the terminal + delay(1000); // slow transmissions down by 1 second + } // while + cout << failures << " failures detected. Leaving TX role." << endl; +} // master + +/** + * make this node act as the receiver + */ +void slave() +{ + memcpy(payload.message, "World ", 6); // set the payload message + + // load the payload for the first received transmission on pipe 0 + radio.writeAckPayload(1, &payload, sizeof(payload)); + + radio.startListening(); // put radio in RX mode + time_t startTimer = time(nullptr); // start a timer + while (time(nullptr) - startTimer < 6) { // use 6 second timeout + uint8_t pipe; + if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it + uint8_t bytes = radio.getDynamicPayloadSize(); // get the size of the payload + PayloadStruct received; + radio.read(&received, sizeof(received)); // fetch payload from RX FIFO + cout << "Received " << (unsigned int)bytes; // print the size of the payload + cout << " bytes on pipe " << (unsigned int)pipe; // print the pipe number + cout << ": " << received.message; + cout << (unsigned int)received.counter; // print received payload + cout << " Sent: "; + cout << payload.message; + cout << (unsigned int)payload.counter << endl; // print ACK payload sent + startTimer = time(nullptr); // reset timer + + // save incoming counter & increment for next outgoing + payload.counter = received.counter + 1; + // load the payload for the first received transmission on pipe 0 + radio.writeAckPayload(1, &payload, sizeof(payload)); + } // if received something + } // while + cout << "Nothing received in 6 seconds. Leaving RX role." << endl; + radio.stopListening(); // recommended idle behavior is TX mode +} // slave + +/** + * Calculate the ellapsed time in microseconds + */ +uint32_t getMicros() +{ + // this function assumes that the timer was started using + // `clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer);` + + clock_gettime(CLOCK_MONOTONIC_RAW, &endTimer); + uint32_t seconds = endTimer.tv_sec - startTimer.tv_sec; + uint32_t useconds = (endTimer.tv_nsec - startTimer.tv_nsec) / 1000; + + return ((seconds)*1000 + useconds) + 0.5; +} diff --git a/examples_linux/acknowledgement_payloads.py b/examples_linux/acknowledgement_payloads.py index c326a6580..eb32e6ded 100644 --- a/examples_linux/acknowledgement_payloads.py +++ b/examples_linux/acknowledgement_payloads.py @@ -11,22 +11,21 @@ parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument( "-n", "--node", type=int, choices=range(2), - help="the identifying radio number (or node ID number)" + help="the identifying radio number (or node ID number)", ) parser.add_argument( "-r", "--role", type=int, choices=range(2), - help="'1' specifies the TX role. '0' specifies the RX role." + help="'1' specifies the TX role. '0' specifies the RX role.", ) ########### USER CONFIGURATION ########### @@ -49,6 +48,7 @@ # 1 item list to store our integer number for the payloads' counter counter = [0] + def master(): """Transmits a message and an incrementing integer every second.""" radio.stopListening() # put radio in TX mode @@ -68,9 +68,9 @@ def master(): "{} us. Sent: {}{}".format( int((end_timer - start_timer) / 1000), buffer[:6].decode("utf-8"), - counter[0] + counter[0], ), - end=" " + end=" ", ) has_payload, pipe_number = radio.available_pipe() if has_payload: @@ -82,7 +82,7 @@ def master(): length, pipe_number, bytes(response[:6]).decode("utf-8"), - response[7:8][0] + response[7:8][0], ) ) # increment counter from received payload @@ -128,7 +128,7 @@ def slave(timeout=6): bytes(received[:6]).decode("utf-8"), received[7:8][0], buffer[:6].decode("utf-8"), - buffer[7:8][0] + buffer[7:8][0], ) ) buffer = b"World \x00" + bytes(counter) # build a new ACK payload @@ -148,11 +148,14 @@ def set_role(): - True when role is complete & app should continue running. - False when app should exit """ - user_input = input( - "*** Enter 'R' for receiver role.\n" - "*** Enter 'T' for transmitter role.\n" - "*** Enter 'Q' to quit example.\n" - ) or "?" + user_input = ( + input( + "*** Enter 'R' for receiver role.\n" + "*** Enter 'T' for transmitter role.\n" + "*** Enter 'Q' to quit example.\n" + ) + or "?" + ) user_input = user_input.split() if user_input[0].upper().startswith("R"): if len(user_input) > 1: @@ -192,11 +195,7 @@ def set_role(): radio_number = args.node # uses default value from `parser` if args.node is None: # if '--node' arg wasn't specified radio_number = bool( - int( - input( - "Which radio is this? Enter '0' or '1'. Defaults to '0' " - ) or 0 - ) + int(input("Which radio is this? Enter '0' or '1'. Defaults to '0' ") or 0) ) # ACK payloads are dynamically sized. diff --git a/examples_linux/extra/rpi-hub.cpp b/examples_linux/extra/rpi-hub.cpp index bac485785..0363666df 100644 --- a/examples_linux/extra/rpi-hub.cpp +++ b/examples_linux/extra/rpi-hub.cpp @@ -1,17 +1,17 @@ -/* +/* * * 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 @@ -22,7 +22,7 @@ * * 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 + * Changed to use modified bcm2835 and RF24 library * * */ @@ -43,7 +43,7 @@ const uint64_t pipes[6] = {0xF0F0F0F0D2LL, 0xF0F0F0F0E1LL, 0xF0F0F0F0E2LL, 0xF0F //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); +//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_24, BCM2835_SPI_SPEED_8MHZ); @@ -105,7 +105,8 @@ int main(int argc, char** argv) radio.write(receivePayload, len); receivePayload[len] = 0; printf("\t Send: size=%i payload=%s pipe:%i\n", len, receivePayload, pipe); - } else { + } + else { printf("\n"); } @@ -122,4 +123,3 @@ int main(int argc, char** argv) return 0; } - diff --git a/examples_linux/getting_started.py b/examples_linux/getting_started.py index 9f5d4968b..90d993052 100644 --- a/examples_linux/getting_started.py +++ b/examples_linux/getting_started.py @@ -10,22 +10,21 @@ parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument( "-n", "--node", type=int, choices=range(2), - help="the identifying radio number (or node ID number)" + help="the identifying radio number (or node ID number)", ) parser.add_argument( "-r", "--role", type=int, choices=range(2), - help="'1' specifies the TX role. '0' specifies the RX role." + help="'1' specifies the TX role. '0' specifies the RX role.", ) @@ -67,10 +66,7 @@ def master(): else: print( "Transmission successful! Time to Transmit: " - "{} us. Sent: {}".format( - (end_timer - start_timer) / 1000, - payload[0] - ) + "{} us. Sent: {}".format((end_timer - start_timer) / 1000, payload[0]) ) payload[0] += 0.01 time.sleep(1) @@ -98,9 +94,7 @@ def slave(timeout=6): # print details about the received packet print( "Received {} bytes on pipe {}: {}".format( - radio.payloadSize, - pipe_number, - payload[0] + radio.payloadSize, pipe_number, payload[0] ) ) start_timer = time.monotonic() # reset the timeout timer @@ -118,11 +112,14 @@ def set_role(): - True when role is complete & app should continue running. - False when app should exit """ - user_input = input( - "*** Enter 'R' for receiver role.\n" - "*** Enter 'T' for transmitter role.\n" - "*** Enter 'Q' to quit example.\n" - ) or "?" + user_input = ( + input( + "*** Enter 'R' for receiver role.\n" + "*** Enter 'T' for transmitter role.\n" + "*** Enter 'Q' to quit example.\n" + ) + or "?" + ) user_input = user_input.split() if user_input[0].upper().startswith("R"): if len(user_input) > 1: @@ -162,11 +159,7 @@ def set_role(): radio_number = args.node # uses default value from `parser` if args.node is None: # if '--node' arg wasn't specified radio_number = bool( - int( - input( - "Which radio is this? Enter '0' or '1'. Defaults to '0' " - ) or 0 - ) + int(input("Which radio is this? Enter '0' or '1'. Defaults to '0' ") or 0) ) # set the Power Amplifier level to -12 dBm since this test example is diff --git a/examples_linux/gettingstarted.cpp b/examples_linux/gettingstarted.cpp index 2ba5ee09b..019a018e8 100644 --- a/examples_linux/gettingstarted.cpp +++ b/examples_linux/gettingstarted.cpp @@ -1,191 +1,193 @@ -/* - * See documentation at https://nRF24.github.io/RF24 - * See License information at root directory of this library - * Author: Brendan Doherty (2bndy5) - */ - -/** - * A simple example of sending data from 1 nRF24L01 transceiver to another. - * - * This example was written to be used on 2 devices acting as "nodes". - * Use `ctrl+c` to quit at any time. - */ -#include // time() -#include // cin, cout, endl -#include // string, getline() -#include // CLOCK_MONOTONIC_RAW, timespec, clock_gettime() -#include // RF24, RF24_PA_LOW, delay() - -using namespace std; - -/****************** Linux ***********************/ -// Radio CE Pin, CSN Pin, SPI Speed -// CE Pin uses GPIO number with BCM and SPIDEV drivers, other platforms use their own pin numbering -// CS Pin addresses the SPI bus number at /dev/spidev. -// ie: RF24 radio(, *10+); spidev1.0 is 10, spidev1.1 is 11 etc.. - -// Generic: -RF24 radio(22, 0); -/****************** Linux (BBB,x86,etc) ***********************/ -// See http://nRF24.github.io/RF24/pages.html for more information on usage -// See http://iotdk.intel.com/docs/master/mraa/ for more information on MRAA -// See https://www.kernel.org/doc/Documentation/spi/spidev for more information on SPIDEV - -// For this example, we'll be using a payload containing -// a single float number that will be incremented -// on every successful transmission -float payload = 0.0; - -void setRole(); // prototype to set the node's role -void master(); // prototype of the TX node's behavior -void slave(); // prototype of the RX node's behavior - -// custom defined timer for evaluating transmission time in microseconds -struct timespec startTimer, endTimer; -uint32_t getMicros(); // prototype to get ellapsed time in microseconds - -int main(int argc, char** argv) { - - // perform hardware check - if (!radio.begin()) { - cout << "radio hardware is not responding!!" << endl; - return 0; // quit now - } - - // to use different addresses on a pair of radios, we need a variable to - // uniquely identify which address this radio will use to transmit - bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit - - // print example's name - cout << argv[0] << endl; - - // Let these addresses be used for the pair - uint8_t address[2][6] = {"1Node", "2Node"}; - // It is very helpful to think of an address as a path instead of as - // an identifying device destination - - // Set the radioNumber via the terminal on startup - cout << "Which radio is this? Enter '0' or '1'. Defaults to '0' "; - string input; - getline(cin, input); - radioNumber = input.length() > 0 && (uint8_t)input[0] == 49; - - // save on transmission time by setting the radio to only transmit the - // number of bytes we need to transmit a float - radio.setPayloadSize(sizeof(payload)); // float datatype occupies 4 bytes - - // Set the PA Level low to try preventing power supply related problems - // because these examples are likely run with nodes in close proximity to - // each other. - radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. - - // set the TX address of the RX node into the TX pipe - radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 - - // set the RX address of the TX node into a RX pipe - radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 - - // For debugging info - // radio.printDetails(); // (smaller) function that prints raw register values - // radio.printPrettyDetails(); // (larger) function that prints human readable data - - // ready to execute program now - setRole(); // calls master() or slave() based on user input - return 0; -} - - -/** - * set this node's role from stdin stream. - * this only considers the first char as input. - */ -void setRole() { - string input = ""; - while (!input.length()) { - cout << "*** PRESS 'T' to begin transmitting to the other node\n"; - cout << "*** PRESS 'R' to begin receiving from the other node\n"; - cout << "*** PRESS 'Q' to exit" << endl; - getline(cin, input); - if (input.length() >= 1) { - if (input[0] == 'T' || input[0] == 't') - master(); - else if (input[0] == 'R' || input[0] == 'r') - slave(); - else if (input[0] == 'Q' || input[0] == 'q') - break; - else - cout << input[0] << " is an invalid input. Please try again." << endl; - } - input = ""; // stay in the while loop - } // while -} // setRole() - - -/** - * make this node act as the transmitter - */ -void master() { - radio.stopListening(); // put radio in TX mode - - unsigned int failure = 0; // keep track of failures - while (failure < 6) { - clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer); // start the timer - bool report = radio.write(&payload, sizeof(float)); // transmit & save the report - uint32_t timerEllapsed = getMicros(); // end the timer - - if (report) { - // payload was delivered - cout << "Transmission successful! Time to transmit = "; - cout << timerEllapsed; // print the timer result - cout << " us. Sent: " << payload << endl; // print payload sent - payload += 0.01; // increment float payload - - } else { - // payload was not delivered - cout << "Transmission failed or timed out" << endl; - failure++; - } - - // to make this example readable in the terminal - delay(1000); // slow transmissions down by 1 second - } - cout << failure << " failures detected. Leaving TX role." << endl; -} - -/** - * make this node act as the receiver - */ -void slave() { - - radio.startListening(); // put radio in RX mode - - time_t startTimer = time(nullptr); // start a timer - while (time(nullptr) - startTimer < 6) { // use 6 second timeout - uint8_t pipe; - if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it - uint8_t bytes = radio.getPayloadSize(); // get the size of the payload - radio.read(&payload, bytes); // fetch payload from FIFO - cout << "Received " << (unsigned int)bytes; // print the size of the payload - cout << " bytes on pipe " << (unsigned int)pipe; // print the pipe number - cout << ": " << payload << endl; // print the payload's value - startTimer = time(nullptr); // reset timer - } - } - cout << "Nothing received in 6 seconds. Leaving RX role." << endl; - radio.stopListening(); -} - - -/** - * Calculate the ellapsed time in microseconds - */ -uint32_t getMicros() { - // this function assumes that the timer was started using - // `clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer);` - - clock_gettime(CLOCK_MONOTONIC_RAW, &endTimer); - uint32_t seconds = endTimer.tv_sec - startTimer.tv_sec; - uint32_t useconds = (endTimer.tv_nsec - startTimer.tv_nsec) / 1000; - - return ((seconds) * 1000 + useconds) + 0.5; -} +/* + * See documentation at https://nRF24.github.io/RF24 + * See License information at root directory of this library + * Author: Brendan Doherty (2bndy5) + */ + +/** + * A simple example of sending data from 1 nRF24L01 transceiver to another. + * + * This example was written to be used on 2 devices acting as "nodes". + * Use `ctrl+c` to quit at any time. + */ +#include // time() +#include // cin, cout, endl +#include // string, getline() +#include // CLOCK_MONOTONIC_RAW, timespec, clock_gettime() +#include // RF24, RF24_PA_LOW, delay() + +using namespace std; + +/****************** Linux ***********************/ +// Radio CE Pin, CSN Pin, SPI Speed +// CE Pin uses GPIO number with BCM and SPIDEV drivers, other platforms use their own pin numbering +// CS Pin addresses the SPI bus number at /dev/spidev. +// ie: RF24 radio(, *10+); spidev1.0 is 10, spidev1.1 is 11 etc.. + +// Generic: +RF24 radio(22, 0); +/****************** Linux (BBB,x86,etc) ***********************/ +// See http://nRF24.github.io/RF24/pages.html for more information on usage +// See http://iotdk.intel.com/docs/master/mraa/ for more information on MRAA +// See https://www.kernel.org/doc/Documentation/spi/spidev for more information on SPIDEV + +// For this example, we'll be using a payload containing +// a single float number that will be incremented +// on every successful transmission +float payload = 0.0; + +void setRole(); // prototype to set the node's role +void master(); // prototype of the TX node's behavior +void slave(); // prototype of the RX node's behavior + +// custom defined timer for evaluating transmission time in microseconds +struct timespec startTimer, endTimer; +uint32_t getMicros(); // prototype to get ellapsed time in microseconds + +int main(int argc, char** argv) +{ + + // perform hardware check + if (!radio.begin()) { + cout << "radio hardware is not responding!!" << endl; + return 0; // quit now + } + + // to use different addresses on a pair of radios, we need a variable to + // uniquely identify which address this radio will use to transmit + bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit + + // print example's name + cout << argv[0] << endl; + + // Let these addresses be used for the pair + uint8_t address[2][6] = {"1Node", "2Node"}; + // It is very helpful to think of an address as a path instead of as + // an identifying device destination + + // Set the radioNumber via the terminal on startup + cout << "Which radio is this? Enter '0' or '1'. Defaults to '0' "; + string input; + getline(cin, input); + radioNumber = input.length() > 0 && (uint8_t)input[0] == 49; + + // save on transmission time by setting the radio to only transmit the + // number of bytes we need to transmit a float + radio.setPayloadSize(sizeof(payload)); // float datatype occupies 4 bytes + + // Set the PA Level low to try preventing power supply related problems + // because these examples are likely run with nodes in close proximity to + // each other. + radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. + + // set the TX address of the RX node into the TX pipe + radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 + + // set the RX address of the TX node into a RX pipe + radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 + + // For debugging info + // radio.printDetails(); // (smaller) function that prints raw register values + // radio.printPrettyDetails(); // (larger) function that prints human readable data + + // ready to execute program now + setRole(); // calls master() or slave() based on user input + return 0; +} + +/** + * set this node's role from stdin stream. + * this only considers the first char as input. + */ +void setRole() +{ + string input = ""; + while (!input.length()) { + cout << "*** PRESS 'T' to begin transmitting to the other node\n"; + cout << "*** PRESS 'R' to begin receiving from the other node\n"; + cout << "*** PRESS 'Q' to exit" << endl; + getline(cin, input); + if (input.length() >= 1) { + if (input[0] == 'T' || input[0] == 't') + master(); + else if (input[0] == 'R' || input[0] == 'r') + slave(); + else if (input[0] == 'Q' || input[0] == 'q') + break; + else + cout << input[0] << " is an invalid input. Please try again." << endl; + } + input = ""; // stay in the while loop + } // while +} // setRole() + +/** + * make this node act as the transmitter + */ +void master() +{ + radio.stopListening(); // put radio in TX mode + + unsigned int failure = 0; // keep track of failures + while (failure < 6) { + clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer); // start the timer + bool report = radio.write(&payload, sizeof(float)); // transmit & save the report + uint32_t timerEllapsed = getMicros(); // end the timer + + if (report) { + // payload was delivered + cout << "Transmission successful! Time to transmit = "; + cout << timerEllapsed; // print the timer result + cout << " us. Sent: " << payload << endl; // print payload sent + payload += 0.01; // increment float payload + } + else { + // payload was not delivered + cout << "Transmission failed or timed out" << endl; + failure++; + } + + // to make this example readable in the terminal + delay(1000); // slow transmissions down by 1 second + } + cout << failure << " failures detected. Leaving TX role." << endl; +} + +/** + * make this node act as the receiver + */ +void slave() +{ + + radio.startListening(); // put radio in RX mode + + time_t startTimer = time(nullptr); // start a timer + while (time(nullptr) - startTimer < 6) { // use 6 second timeout + uint8_t pipe; + if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it + uint8_t bytes = radio.getPayloadSize(); // get the size of the payload + radio.read(&payload, bytes); // fetch payload from FIFO + cout << "Received " << (unsigned int)bytes; // print the size of the payload + cout << " bytes on pipe " << (unsigned int)pipe; // print the pipe number + cout << ": " << payload << endl; // print the payload's value + startTimer = time(nullptr); // reset timer + } + } + cout << "Nothing received in 6 seconds. Leaving RX role." << endl; + radio.stopListening(); +} + +/** + * Calculate the ellapsed time in microseconds + */ +uint32_t getMicros() +{ + // this function assumes that the timer was started using + // `clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer);` + + clock_gettime(CLOCK_MONOTONIC_RAW, &endTimer); + uint32_t seconds = endTimer.tv_sec - startTimer.tv_sec; + uint32_t useconds = (endTimer.tv_nsec - startTimer.tv_nsec) / 1000; + + return ((seconds)*1000 + useconds) + 0.5; +} diff --git a/examples_linux/interruptConfigure.cpp b/examples_linux/interruptConfigure.cpp index 048f281f1..46e94a7f6 100644 --- a/examples_linux/interruptConfigure.cpp +++ b/examples_linux/interruptConfigure.cpp @@ -1,319 +1,316 @@ -/* - * See documentation at https://nRF24.github.io/RF24 - * See License information at root directory of this library - * Author: Brendan Doherty (2bndy5) - */ - -/** - * This example uses Acknowledgement (ACK) payloads attached to ACK packets to - * demonstrate how the nRF24L01's IRQ (Interrupt Request) pin can be - * configured to detect when data is received, or when data has transmitted - * successfully, or when data has failed to transmit. - * - * This example was written to be used on 2 devices acting as "nodes". - * Use `ctrl+c` to quit at any time. - */ -#include // time() -#include // cin, cout, endl -#include // string, getline() -#include // CLOCK_MONOTONIC_RAW, timespec, clock_gettime() -#include // RF24, RF24_PA_LOW, delay(), pinMode(), INPUT, attachInterrupt(), INT_EDGE_FALLING - -using namespace std; - -// We will be using the nRF24L01's IRQ pin for this example -#define IRQ_PIN 12 // this needs to be a digital input capable pin - -// this example is a sequential program. so we need to wait for the event to be handled -volatile bool wait_for_event = false; // used to signify that the event is handled - -/****************** Linux ***********************/ -// Radio CE Pin, CSN Pin, SPI Speed -// CE Pin uses GPIO number with BCM and SPIDEV drivers, other platforms use their own pin numbering -// CS Pin addresses the SPI bus number at /dev/spidev. -// ie: RF24 radio(, *10+); spidev1.0 is 10, spidev1.1 is 11 etc.. - -// Generic: -RF24 radio(22, 0); -/****************** Linux (BBB,x86,etc) ***********************/ -// See http://nRF24.github.io/RF24/pages.html for more information on usage -// See http://iotdk.intel.com/docs/master/mraa/ for more information on MRAA -// See https://www.kernel.org/doc/Documentation/spi/spidev for more information on SPIDEV - -// For this example, we'll be using a payload containing -// a string that changes on every transmission. (successful or not) -// Make a couple arrays of payloads & an iterator to traverse them -const uint8_t tx_pl_size = 5; -const uint8_t ack_pl_size = 4; -uint8_t pl_iterator = 0; -// The " + 1" compensates for the c-string's NULL terminating 0 -char tx_payloads[4][tx_pl_size + 1] = {"Ping ", "Pong ", "Radio", "1FAIL"}; -char ack_payloads[3][ack_pl_size + 1] = {"Yak ", "Back", " ACK"}; - -void interruptHandler(); // prototype to handle the interrupt request (IRQ) pin -void setRole(); // prototype to set the node's role -void master(); // prototype of the TX node's behavior -void slave(); // prototype of the RX node's behavior -void ping_n_wait(); // prototype that sends a payload and waits for the IRQ pin to get triggered -void printRxFifo(const uint8_t); // prototype to print entire contents of RX FIFO with 1 buffer - - -int main(int argc, char** argv) { - - // perform hardware check - if (!radio.begin()) { - cout << "radio hardware is not responding!!" << endl; - return 0; // quit now - } - - // Let these addresses be used for the pair - uint8_t address[2][6] = {"1Node", "2Node"}; - // It is very helpful to think of an address as a path instead of as - // an identifying device destination - - // to use different addresses on a pair of radios, we need a variable to - // uniquely identify which address this radio will use to transmit - bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit - - // print example's name - cout << argv[0] << endl; - - // Set the radioNumber via the terminal on startup - cout << "Which radio is this? Enter '0' or '1'. Defaults to '0' "; - string input; - getline(cin, input); - radioNumber = input.length() > 0 && (uint8_t)input[0] == 49; - - // to use ACK payloads, we need to enable dynamic payload lengths - radio.enableDynamicPayloads(); // ACK payloads are dynamically sized - - // Acknowledgement packets have no payloads by default. We need to enable - // this feature for all nodes (TX & RX) to use ACK payloads. - radio.enableAckPayload(); - - // Set the PA Level low to try preventing power supply related problems - // because these examples are likely run with nodes in close proximity to - // each other. - radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. - - // set the TX address of the RX node into the TX pipe - radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 - - // set the RX address of the TX node into a RX pipe - radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 - - // For debugging info - // radio.printDetails(); // (smaller) function that prints raw register values - // radio.printPrettyDetails(); // (larger) function that prints human readable data - - // setup the digital input pin connected to the nRF24L01's IRQ pin - pinMode(IRQ_PIN, INPUT); - - // register the interrupt request (IRQ) to call our - // Interrupt Service Routine (ISR) callback function interruptHandler() - attachInterrupt(IRQ_PIN, INT_EDGE_FALLING, &interruptHandler); - // IMPORTANT: do not call radio.available() before calling - // radio.whatHappened() when the interruptHandler() is triggered by the - // IRQ pin FALLING event. According to the datasheet, the pipe information - // is unreliable during the IRQ pin FALLING transition. - - // ready to execute program now - setRole(); // calls master() or slave() based on user input - return 0; -} // main - - -/** - * set this node's role from stdin stream. - * this only considers the first char as input. - */ -void setRole() { - string input = ""; - while (!input.length()) { - cout << "*** PRESS 'T' to begin transmitting to the other node\n"; - cout << "*** PRESS 'R' to begin receiving from the other node\n"; - cout << "*** PRESS 'Q' to exit" << endl; - getline(cin, input); - if (input.length() >= 1) { - if (input[0] == 'T' || input[0] == 't') - master(); - else if (input[0] == 'R' || input[0] == 'r') - slave(); - else if (input[0] == 'Q' || input[0] == 'q') - break; - else - cout << input[0] << " is an invalid input. Please try again." << endl; - } - input = ""; // stay in the while loop - } // while -} // setRole - - -/** - * act as the transmitter to show 3 different IRQ events by sending 4 payloads: - * 1. Successfully receive ACK payload first - * 2. Successfully transmit on second - * 3. Send a third payload to fill RX node's RX FIFO (supposedly making RX node unresponsive) - * 4. intentionally fail transmit on the fourth - */ -void master() { - pl_iterator = 0; // reset the iterator for the following tests done in master() - - // Test the "data ready" event with the IRQ pin - cout << "\nConfiguring IRQ pin to ignore the 'data sent' event\n"; - radio.maskIRQ(true, false, false); // args = "data_sent", "data_fail", "data_ready" - cout << " Pinging RX node for 'data ready' event..."; - ping_n_wait(); // transmit a payload and detect the IRQ pin - pl_iterator++; // increment iterator for next test - - - // Test the "data sent" event with the IRQ pin - cout << "\nConfiguring IRQ pin to ignore the 'data ready' event\n"; - radio.maskIRQ(false, false, true); // args = "data_sent", "data_fail", "data_ready" - cout << " Pinging RX node for 'data sent' event..."; - radio.flush_tx(); // flush payloads from any failed prior test - ping_n_wait(); // transmit a payload and detect the IRQ pin - pl_iterator++; // increment iterator for next test - - - // Use this iteration to fill the RX node's FIFO which sets us up for the next test. - // write() uses virtual interrupt flags that work despite the masking of the IRQ pin - radio.maskIRQ(1, 1, 1); // disable IRQ masking for this step - - cout << "\nSending 1 payload to fill RX node's FIFO. IRQ pin is neglected.\n"; - // write() will call flush_tx() on 'data fail' events - if (radio.write(&tx_payloads[pl_iterator], tx_pl_size)) - cout << "RX node's FIFO is full; it is not listening any more" << endl; - else { - cout << "Transmission failed or timed out. Continuing anyway." << endl; - radio.flush_tx(); - } - pl_iterator++; // increment iterator for next test - - - // test the "data fail" event with the IRQ pin - cout << "\nConfiguring IRQ pin to reflect all events\n"; - radio.maskIRQ(0, 0, 0); // args = "data_sent", "data_fail", "data_ready" - cout << " Pinging inactive RX node for 'data fail' event..."; - ping_n_wait(); // transmit a payload and detect the IRQ pin - - // CE pin is still HIGH which consumes more power. Example is now idling so... - radio.stopListening(); // ensure CE pin is LOW - // stopListening() also calls flush_tx() when ACK payloads are enabled - - if (radio.available()) { - printRxFifo(ack_pl_size); // doing this will flush the RX FIFO - } -} // master - - -/** - * act as the receiver - */ -void slave() { - - // let IRQ pin only trigger on "data_ready" event in RX mode - radio.maskIRQ(1, 1, 0); // args = "data_sent", "data_fail", "data_ready" - - // Fill the TX FIFO with 3 ACK payloads for the first 3 received - // transmissions on pipe 0. - radio.writeAckPayload(1, &ack_payloads[0], ack_pl_size); - radio.writeAckPayload(1, &ack_payloads[1], ack_pl_size); - radio.writeAckPayload(1, &ack_payloads[2], ack_pl_size); - - radio.startListening(); // put radio in RX mode - time_t startTimer = time(nullptr); // start a timer - while (time(nullptr) - startTimer < 6 && !radio.rxFifoFull()) { - // use 6 second timeout & wait till RX FIFO is full - } - delay(100); // wait for ACK payload to finish transmitting - radio.stopListening(); // also discards unused ACK payloads - - if (radio.available()) { - printRxFifo(tx_pl_size); - } - else { - cout << "Timeout was reached. Going back to setRole()" << endl; - } -} // slave - - -/** - * pings the receiver with a non-blocking startWrite(), then waits till - * the IRQ pin is triggered - */ -void ping_n_wait() { - // use the non-blocking call to write a payload and begin transmission - // the "false" argument means we are expecting an ACK packet response - radio.startFastWrite(tx_payloads[pl_iterator], tx_pl_size, false); - - wait_for_event = true; - while (wait_for_event) { - /* - * IRQ pin is LOW when activated. Otherwise it is always HIGH - * Wait in this empty loop until IRQ pin is activated. - * - * In this example, the "data fail" event is always configured to - * trigger the IRQ pin active. Because the auto-ACK feature is on by - * default, we don't need a timeout check to prevent an infinite loop. - */ - } -} - - -/** - * when the IRQ pin goes active LOW, call this fuction print out why - */ -void interruptHandler() { - // print IRQ status and all masking flags' states - - cout << "\tIRQ pin is actively LOW" << endl; // show that this function was called - - bool tx_ds, tx_df, rx_dr; // declare variables for IRQ masks - radio.whatHappened(tx_ds, tx_df, rx_dr); // get values for IRQ masks - // whatHappened() clears the IRQ masks also. This is required for - // continued TX operations when a transmission fails. - // clearing the IRQ masks resets the IRQ pin to its inactive state (HIGH) - - cout << "\tdata_sent: " << tx_ds; // print "data sent" mask state - cout << ", data_fail: " << tx_df; // print "data fail" mask state - cout << ", data_ready: " << rx_dr << endl; // print "data ready" mask state - - if (tx_df) // if TX payload failed - radio.flush_tx(); // clear all payloads from the TX FIFO - - // print if test passed or failed. Unintentional fails mean the RX node was not listening. - if (pl_iterator == 0) - cout << " 'Data Ready' event test " << (rx_dr ? "passed" : "failed") << endl; - else if (pl_iterator == 1) - cout << " 'Data Sent' event test " << (tx_ds ? "passed" : "failed") << endl; - else if (pl_iterator == 3) - cout << " 'Data Fail' event test " << (tx_df ? "passed" : "failed") << endl; - - wait_for_event = false; // ready to continue -} // interruptHandler - - -/** - * Print the entire RX FIFO with one buffer. This will also flush the RX FIFO. - * @param pl_size used to determine received payload size. Remember that the - * payload sizes are declared as tx_pl_size and ack_pl_size. - */ -void printRxFifo(const uint8_t pl_size) { - char rx_fifo[pl_size * 3 + 1]; // assuming RX FIFO is full; declare a buffer to hold it all - if (radio.rxFifoFull()) { - rx_fifo[pl_size * 3] = 0; // add a NULL terminating char to use as a c-string - radio.read(&rx_fifo, pl_size * 3); // this clears the RX FIFO (for this example) - } - else { - uint8_t i = 0; - while (radio.available()) { - radio.read(&rx_fifo + (i * pl_size), pl_size); - i++; - } - rx_fifo[i * pl_size] = 0; // add a NULL terminating char to use as a c-string - } - - // print the entire RX FIFO with 1 buffer - cout << "Complete RX FIFO: " << rx_fifo << endl; -} +/* + * See documentation at https://nRF24.github.io/RF24 + * See License information at root directory of this library + * Author: Brendan Doherty (2bndy5) + */ + +/** + * This example uses Acknowledgement (ACK) payloads attached to ACK packets to + * demonstrate how the nRF24L01's IRQ (Interrupt Request) pin can be + * configured to detect when data is received, or when data has transmitted + * successfully, or when data has failed to transmit. + * + * This example was written to be used on 2 devices acting as "nodes". + * Use `ctrl+c` to quit at any time. + */ +#include // time() +#include // cin, cout, endl +#include // string, getline() +#include // CLOCK_MONOTONIC_RAW, timespec, clock_gettime() +#include // RF24, RF24_PA_LOW, delay(), pinMode(), INPUT, attachInterrupt(), INT_EDGE_FALLING + +using namespace std; + +// We will be using the nRF24L01's IRQ pin for this example +#define IRQ_PIN 12 // this needs to be a digital input capable pin + +// this example is a sequential program. so we need to wait for the event to be handled +volatile bool wait_for_event = false; // used to signify that the event is handled + +/****************** Linux ***********************/ +// Radio CE Pin, CSN Pin, SPI Speed +// CE Pin uses GPIO number with BCM and SPIDEV drivers, other platforms use their own pin numbering +// CS Pin addresses the SPI bus number at /dev/spidev. +// ie: RF24 radio(, *10+); spidev1.0 is 10, spidev1.1 is 11 etc.. + +// Generic: +RF24 radio(22, 0); +/****************** Linux (BBB,x86,etc) ***********************/ +// See http://nRF24.github.io/RF24/pages.html for more information on usage +// See http://iotdk.intel.com/docs/master/mraa/ for more information on MRAA +// See https://www.kernel.org/doc/Documentation/spi/spidev for more information on SPIDEV + +// For this example, we'll be using a payload containing +// a string that changes on every transmission. (successful or not) +// Make a couple arrays of payloads & an iterator to traverse them +const uint8_t tx_pl_size = 5; +const uint8_t ack_pl_size = 4; +uint8_t pl_iterator = 0; +// The " + 1" compensates for the c-string's NULL terminating 0 +char tx_payloads[4][tx_pl_size + 1] = {"Ping ", "Pong ", "Radio", "1FAIL"}; +char ack_payloads[3][ack_pl_size + 1] = {"Yak ", "Back", " ACK"}; + +void interruptHandler(); // prototype to handle the interrupt request (IRQ) pin +void setRole(); // prototype to set the node's role +void master(); // prototype of the TX node's behavior +void slave(); // prototype of the RX node's behavior +void ping_n_wait(); // prototype that sends a payload and waits for the IRQ pin to get triggered +void printRxFifo(const uint8_t); // prototype to print entire contents of RX FIFO with 1 buffer + +int main(int argc, char** argv) +{ + + // perform hardware check + if (!radio.begin()) { + cout << "radio hardware is not responding!!" << endl; + return 0; // quit now + } + + // Let these addresses be used for the pair + uint8_t address[2][6] = {"1Node", "2Node"}; + // It is very helpful to think of an address as a path instead of as + // an identifying device destination + + // to use different addresses on a pair of radios, we need a variable to + // uniquely identify which address this radio will use to transmit + bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit + + // print example's name + cout << argv[0] << endl; + + // Set the radioNumber via the terminal on startup + cout << "Which radio is this? Enter '0' or '1'. Defaults to '0' "; + string input; + getline(cin, input); + radioNumber = input.length() > 0 && (uint8_t)input[0] == 49; + + // to use ACK payloads, we need to enable dynamic payload lengths + radio.enableDynamicPayloads(); // ACK payloads are dynamically sized + + // Acknowledgement packets have no payloads by default. We need to enable + // this feature for all nodes (TX & RX) to use ACK payloads. + radio.enableAckPayload(); + + // Set the PA Level low to try preventing power supply related problems + // because these examples are likely run with nodes in close proximity to + // each other. + radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. + + // set the TX address of the RX node into the TX pipe + radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 + + // set the RX address of the TX node into a RX pipe + radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 + + // For debugging info + // radio.printDetails(); // (smaller) function that prints raw register values + // radio.printPrettyDetails(); // (larger) function that prints human readable data + + // setup the digital input pin connected to the nRF24L01's IRQ pin + pinMode(IRQ_PIN, INPUT); + + // register the interrupt request (IRQ) to call our + // Interrupt Service Routine (ISR) callback function interruptHandler() + attachInterrupt(IRQ_PIN, INT_EDGE_FALLING, &interruptHandler); + // IMPORTANT: do not call radio.available() before calling + // radio.whatHappened() when the interruptHandler() is triggered by the + // IRQ pin FALLING event. According to the datasheet, the pipe information + // is unreliable during the IRQ pin FALLING transition. + + // ready to execute program now + setRole(); // calls master() or slave() based on user input + return 0; +} // main + +/** + * set this node's role from stdin stream. + * this only considers the first char as input. + */ +void setRole() +{ + string input = ""; + while (!input.length()) { + cout << "*** PRESS 'T' to begin transmitting to the other node\n"; + cout << "*** PRESS 'R' to begin receiving from the other node\n"; + cout << "*** PRESS 'Q' to exit" << endl; + getline(cin, input); + if (input.length() >= 1) { + if (input[0] == 'T' || input[0] == 't') + master(); + else if (input[0] == 'R' || input[0] == 'r') + slave(); + else if (input[0] == 'Q' || input[0] == 'q') + break; + else + cout << input[0] << " is an invalid input. Please try again." << endl; + } + input = ""; // stay in the while loop + } // while +} // setRole + +/** + * act as the transmitter to show 3 different IRQ events by sending 4 payloads: + * 1. Successfully receive ACK payload first + * 2. Successfully transmit on second + * 3. Send a third payload to fill RX node's RX FIFO (supposedly making RX node unresponsive) + * 4. intentionally fail transmit on the fourth + */ +void master() +{ + pl_iterator = 0; // reset the iterator for the following tests done in master() + + // Test the "data ready" event with the IRQ pin + cout << "\nConfiguring IRQ pin to ignore the 'data sent' event\n"; + radio.maskIRQ(true, false, false); // args = "data_sent", "data_fail", "data_ready" + cout << " Pinging RX node for 'data ready' event..."; + ping_n_wait(); // transmit a payload and detect the IRQ pin + pl_iterator++; // increment iterator for next test + + // Test the "data sent" event with the IRQ pin + cout << "\nConfiguring IRQ pin to ignore the 'data ready' event\n"; + radio.maskIRQ(false, false, true); // args = "data_sent", "data_fail", "data_ready" + cout << " Pinging RX node for 'data sent' event..."; + radio.flush_tx(); // flush payloads from any failed prior test + ping_n_wait(); // transmit a payload and detect the IRQ pin + pl_iterator++; // increment iterator for next test + + // Use this iteration to fill the RX node's FIFO which sets us up for the next test. + // write() uses virtual interrupt flags that work despite the masking of the IRQ pin + radio.maskIRQ(1, 1, 1); // disable IRQ masking for this step + + cout << "\nSending 1 payload to fill RX node's FIFO. IRQ pin is neglected.\n"; + // write() will call flush_tx() on 'data fail' events + if (radio.write(&tx_payloads[pl_iterator], tx_pl_size)) + cout << "RX node's FIFO is full; it is not listening any more" << endl; + else { + cout << "Transmission failed or timed out. Continuing anyway." << endl; + radio.flush_tx(); + } + pl_iterator++; // increment iterator for next test + + // test the "data fail" event with the IRQ pin + cout << "\nConfiguring IRQ pin to reflect all events\n"; + radio.maskIRQ(0, 0, 0); // args = "data_sent", "data_fail", "data_ready" + cout << " Pinging inactive RX node for 'data fail' event..."; + ping_n_wait(); // transmit a payload and detect the IRQ pin + + // CE pin is still HIGH which consumes more power. Example is now idling so... + radio.stopListening(); // ensure CE pin is LOW + // stopListening() also calls flush_tx() when ACK payloads are enabled + + if (radio.available()) { + printRxFifo(ack_pl_size); // doing this will flush the RX FIFO + } +} // master + +/** + * act as the receiver + */ +void slave() +{ + + // let IRQ pin only trigger on "data_ready" event in RX mode + radio.maskIRQ(1, 1, 0); // args = "data_sent", "data_fail", "data_ready" + + // Fill the TX FIFO with 3 ACK payloads for the first 3 received + // transmissions on pipe 0. + radio.writeAckPayload(1, &ack_payloads[0], ack_pl_size); + radio.writeAckPayload(1, &ack_payloads[1], ack_pl_size); + radio.writeAckPayload(1, &ack_payloads[2], ack_pl_size); + + radio.startListening(); // put radio in RX mode + time_t startTimer = time(nullptr); // start a timer + while (time(nullptr) - startTimer < 6 && !radio.rxFifoFull()) { + // use 6 second timeout & wait till RX FIFO is full + } + delay(100); // wait for ACK payload to finish transmitting + radio.stopListening(); // also discards unused ACK payloads + + if (radio.available()) { + printRxFifo(tx_pl_size); + } + else { + cout << "Timeout was reached. Going back to setRole()" << endl; + } +} // slave + +/** + * pings the receiver with a non-blocking startWrite(), then waits till + * the IRQ pin is triggered + */ +void ping_n_wait() +{ + // use the non-blocking call to write a payload and begin transmission + // the "false" argument means we are expecting an ACK packet response + radio.startFastWrite(tx_payloads[pl_iterator], tx_pl_size, false); + + wait_for_event = true; + while (wait_for_event) { + /* + * IRQ pin is LOW when activated. Otherwise it is always HIGH + * Wait in this empty loop until IRQ pin is activated. + * + * In this example, the "data fail" event is always configured to + * trigger the IRQ pin active. Because the auto-ACK feature is on by + * default, we don't need a timeout check to prevent an infinite loop. + */ + } +} + +/** + * when the IRQ pin goes active LOW, call this fuction print out why + */ +void interruptHandler() +{ + // print IRQ status and all masking flags' states + + cout << "\tIRQ pin is actively LOW" << endl; // show that this function was called + + bool tx_ds, tx_df, rx_dr; // declare variables for IRQ masks + radio.whatHappened(tx_ds, tx_df, rx_dr); // get values for IRQ masks + // whatHappened() clears the IRQ masks also. This is required for + // continued TX operations when a transmission fails. + // clearing the IRQ masks resets the IRQ pin to its inactive state (HIGH) + + cout << "\tdata_sent: " << tx_ds; // print "data sent" mask state + cout << ", data_fail: " << tx_df; // print "data fail" mask state + cout << ", data_ready: " << rx_dr << endl; // print "data ready" mask state + + if (tx_df) // if TX payload failed + radio.flush_tx(); // clear all payloads from the TX FIFO + + // print if test passed or failed. Unintentional fails mean the RX node was not listening. + if (pl_iterator == 0) + cout << " 'Data Ready' event test " << (rx_dr ? "passed" : "failed") << endl; + else if (pl_iterator == 1) + cout << " 'Data Sent' event test " << (tx_ds ? "passed" : "failed") << endl; + else if (pl_iterator == 3) + cout << " 'Data Fail' event test " << (tx_df ? "passed" : "failed") << endl; + + wait_for_event = false; // ready to continue +} // interruptHandler + +/** + * Print the entire RX FIFO with one buffer. This will also flush the RX FIFO. + * @param pl_size used to determine received payload size. Remember that the + * payload sizes are declared as tx_pl_size and ack_pl_size. + */ +void printRxFifo(const uint8_t pl_size) +{ + char rx_fifo[pl_size * 3 + 1]; // assuming RX FIFO is full; declare a buffer to hold it all + if (radio.rxFifoFull()) { + rx_fifo[pl_size * 3] = 0; // add a NULL terminating char to use as a c-string + radio.read(&rx_fifo, pl_size * 3); // this clears the RX FIFO (for this example) + } + else { + uint8_t i = 0; + while (radio.available()) { + radio.read(&rx_fifo + (i * pl_size), pl_size); + i++; + } + rx_fifo[i * pl_size] = 0; // add a NULL terminating char to use as a c-string + } + + // print the entire RX FIFO with 1 buffer + cout << "Complete RX FIFO: " << rx_fifo << endl; +} diff --git a/examples_linux/interrupt_configure.py b/examples_linux/interrupt_configure.py index 8dd7f6380..3018e582f 100644 --- a/examples_linux/interrupt_configure.py +++ b/examples_linux/interrupt_configure.py @@ -14,22 +14,21 @@ parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument( "-n", "--node", type=int, choices=range(2), - help="the identifying radio number (or node ID number)" + help="the identifying radio number (or node ID number)", ) parser.add_argument( "-r", "--role", type=int, choices=range(2), - help="'1' specifies the TX role. '0' specifies the RX role." + help="'1' specifies the TX role. '0' specifies the RX role.", ) ########### USER CONFIGURATION ########### @@ -62,28 +61,16 @@ def interrupt_handler(channel): """This function is called when IRQ pin is detected active LOW""" print("IRQ pin", channel, "went active LOW.") - tx_ds, tx_df, rx_dr = radio.whatHappened() # get IRQ status flags + tx_ds, tx_df, rx_dr = radio.whatHappened() # get IRQ status flags if tx_df: radio.flush_tx() print("\ttx_ds: {}, tx_df: {}, rx_dr: {}".format(tx_ds, tx_df, rx_dr)) if pl_iterator[0] == 0: - print( - " 'data ready' event test {}".format( - "passed" if rx_dr else "failed" - ) - ) + print(" 'data ready' event test {}".format("passed" if rx_dr else "failed")) elif pl_iterator[0] == 1: - print( - " 'data sent' event test {}".format( - "passed" if tx_ds else "failed" - ) - ) + print(" 'data sent' event test {}".format("passed" if tx_ds else "failed")) elif pl_iterator[0] == 3: - print( - " 'data fail' event test {}".format( - "passed" if tx_df else "failed" - ) - ) + print(" 'data fail' event test {}".format("passed" if tx_df else "failed")) # setup IRQ GPIO pin @@ -108,7 +95,7 @@ def _ping_n_wait(pl_iter): pl_iterator[0] = pl_iter # the following False parameter means we're expecting an ACK packet radio.startFastWrite(tx_payloads[pl_iter], False) - time.sleep(0.1) # wait 100 ms for interrupt_handler() to complete + time.sleep(0.1) # wait 100 ms for interrupt_handler() to complete def print_rx_fifo(pl_size): @@ -117,12 +104,9 @@ def print_rx_fifo(pl_size): :param int pl_size: the expected size of each payload """ if radio.rxFifoFull(): - # all 3 payloads received were 5 bytes each, and RX FIFO is full - # so, fetching 15 bytes from the RX FIFO also flushes RX FIFO - print( - "Complete RX FIFO:", - radio.read(pl_size * 3).decode("utf-8") - ) + # all 3 payloads received were 5 bytes each, and RX FIFO is full + # so, fetching 15 bytes from the RX FIFO also flushes RX FIFO + print("Complete RX FIFO:", radio.read(pl_size * 3).decode("utf-8")) else: buffer = bytearray() while radio.available(): @@ -134,11 +118,11 @@ def print_rx_fifo(pl_size): def master(): """Transmits 4 times and reports results - 1. successfully receive ACK payload first - 2. successfully transmit on second - 3. send a third payload to fill RX node's RX FIFO - (supposedly making RX node unresponsive) - 4. intentionally fail transmit on the fourth + 1. successfully receive ACK payload first + 2. successfully transmit on second + 3. send a third payload to fill RX node's RX FIFO + (supposedly making RX node unresponsive) + 4. intentionally fail transmit on the fourth """ radio.stopListening() # put radio in TX mode @@ -163,8 +147,7 @@ def master(): print("RX node's FIFO is full; it is not listening any more") else: print( - "Transmission successful, but the RX node might still be " - "listening." + "Transmission successful, but the RX node might still be " "listening." ) else: radio.flush_tx() @@ -212,11 +195,14 @@ def set_role(): - True when role is complete & app should continue running. - False when app should exit """ - user_input = input( - "*** Enter 'R' for receiver role.\n" - "*** Enter 'T' for transmitter role.\n" - "*** Enter 'Q' to quit example.\n" - ) or "?" + user_input = ( + input( + "*** Enter 'R' for receiver role.\n" + "*** Enter 'T' for transmitter role.\n" + "*** Enter 'Q' to quit example.\n" + ) + or "?" + ) user_input = user_input.split() if user_input[0].upper().startswith("R"): if len(user_input) > 1: @@ -257,11 +243,7 @@ def set_role(): radio_number = args.node # uses default value from `parser` if args.node is None: # if '--node' arg wasn't specified radio_number = bool( - int( - input( - "Which radio is this? Enter '0' or '1'. Defaults to '0' " - ) or 0 - ) + int(input("Which radio is this? Enter '0' or '1'. Defaults to '0' ") or 0) ) # set the Power Amplifier level to -12 dBm since this test example is diff --git a/examples_linux/interrupts/gettingstarted_call_response_int.cpp b/examples_linux/interrupts/gettingstarted_call_response_int.cpp index 3a9f9e27b..1362292c3 100644 --- a/examples_linux/interrupts/gettingstarted_call_response_int.cpp +++ b/examples_linux/interrupts/gettingstarted_call_response_int.cpp @@ -2,7 +2,6 @@ TMRh20 2014 - Updated to work with optimized RF24 Arduino library */ - /** * Example for efficient call-response using ack-payloads and interrupts * @@ -36,12 +35,11 @@ bool radioNumber = 1; int interruptPin = 23; /********************************/ - // Radio pipe addresses for the 2 nodes to communicate. const uint8_t addresses[][6] = {"1Node", "2Node"}; volatile 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 +uint8_t counter = 1; // A single byte to keep track of the data being sent back and forth volatile bool gotResponse = false; @@ -49,14 +47,13 @@ void intHandler() { if (role == role_pong_back) { - uint8_t pipeNo, gotByte; // Declare variables for the pipe and the byte received - if (radio.available(&pipeNo)) { // Read all available payloads + uint8_t pipeNo, gotByte; // Declare variables for the pipe and the byte received + if (radio.available(&pipeNo)) { // Read all available payloads radio.read(&gotByte, 1); // Since this is a call-response. Respond directly with an ack payload. - gotByte += 1; // 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. + gotByte += 1; // 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("Loaded next response %d \n\r", gotByte); - } } } @@ -66,10 +63,9 @@ int main(int argc, char** argv) cout << "RPi/RF24/examples/gettingstarted_call_response_int\n"; radio.begin(); - radio.enableAckPayload(); // Allow optional ack payloads - radio.enableDynamicPayloads(); // needed for using ACK payloads - radio.printDetails(); // Dump the configuration of the rf unit for debugging - + radio.enableAckPayload(); // Allow optional ack payloads + radio.enableDynamicPayloads(); // needed for using ACK payloads + radio.printDetails(); // Dump the configuration of the rf unit for debugging /********* Role chooser ***********/ @@ -82,9 +78,12 @@ int main(int argc, char** argv) 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; + cout << "Role: Pong Back, awaiting transmission " << endl + << endl; + } + else { + cout << "Role: Ping Out, starting transmission " << endl + << endl; role = role_ping_out; } } @@ -92,10 +91,11 @@ int main(int argc, char** argv) /***********************************/ // This opens two pipes for these two nodes to communicate // back and forth. - if (!radioNumber){ + if (!radioNumber) { radio.openWritingPipe(addresses[0]); radio.openReadingPipe(1, addresses[1]); - }else{ + } + else { radio.openWritingPipe(addresses[1]); radio.openReadingPipe(1, addresses[0]); } @@ -108,40 +108,38 @@ int main(int argc, char** argv) // forever loop while (1) { - /****************** Ping Out Role ***************************/ - if (role == role_ping_out){ // Radio is in ping mode + if (role == role_ping_out) { // Radio is in ping mode - uint8_t gotByte; // Initialize a variable for the incoming response + 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 + 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.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 + 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 + } + else { + while (radio.available()) // If an ack with payload was received { - radio.read(&gotByte, 1); // Read it, and display the response time + 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 + counter++; // Increment the counter variable } } - }else{ - printf("Sending failed.\n\r"); // If no ack response, sending failed } - sleep(1); // Try again later + else { + printf("Sending failed.\n\r"); // If no ack response, sending failed + } + sleep(1); // Try again later } - /****************** Pong Back Role ***************************/ // This is done using ACK payloads & IRQ } //while 1 } //main - - diff --git a/examples_linux/interrupts/gettingstarted_call_response_int2.cpp b/examples_linux/interrupts/gettingstarted_call_response_int2.cpp index ae01e608c..f7fe2e35d 100644 --- a/examples_linux/interrupts/gettingstarted_call_response_int2.cpp +++ b/examples_linux/interrupts/gettingstarted_call_response_int2.cpp @@ -2,7 +2,6 @@ TMRh20 2014 - Updated to work with optimized RF24 Arduino library */ - /** * Example for efficient call-response using ack-payloads * @@ -36,15 +35,15 @@ bool radioNumber = 1; int interruptPin = 23; /********************************/ - // Radio pipe addresses for the 2 nodes to communicate. const uint8_t addresses[][6] = {"1Node", "2Node"}; 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 +uint8_t counter = 1; // A single byte to keep track of the data being sent back and forth uint32_t timer = 0; -void intHandler(){ +void intHandler() +{ bool tx_ok, tx_fail, rx; radio.whatHappened(tx_ok, tx_fail, rx); @@ -53,14 +52,14 @@ void intHandler(){ printf("Sending failed.\n\r"); } - if (role == role_ping_out && tx_ok){ - if (!radio.available()){ + if (role == role_ping_out && tx_ok) { + if (!radio.available()) { printf("Got blank response. round-trip delay: %u ms\n\r", millis() - timer); } } - if (role == role_ping_out){ - while (radio.available()){ + if (role == role_ping_out) { + while (radio.available()) { uint8_t gotByte; radio.read(&gotByte, 1); printf("Got response %d, round-trip delay: %u ms\n\r", gotByte, millis() - timer); @@ -83,14 +82,14 @@ void intHandler(){ } } -int main(int argc, char** argv){ +int main(int argc, char** argv) +{ cout << "RPi/RF24/examples/gettingstarted_call_response\n"; radio.begin(); - radio.enableAckPayload(); // Allow optional ack payloads - radio.enableDynamicPayloads(); // needed for using ACK payloads - radio.printDetails(); // Dump the configuration of the rf unit for debugging - + radio.enableAckPayload(); // Allow optional ack payloads + radio.enableDynamicPayloads(); // needed for using ACK payloads + radio.printDetails(); // Dump the configuration of the rf unit for debugging /********* Role chooser ***********/ @@ -100,24 +99,27 @@ int main(int argc, char** argv){ 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){ + 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; + 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 opens two pipes for these two nodes to communicate // back and forth. - if (!radioNumber){ + if (!radioNumber) { radio.openWritingPipe(addresses[0]); radio.openReadingPipe(1, addresses[1]); - }else{ + } + else { radio.openWritingPipe(addresses[1]); radio.openReadingPipe(1, addresses[0]); } @@ -127,24 +129,22 @@ int main(int argc, char** argv){ attachInterrupt(interruptPin, INT_EDGE_FALLING, intHandler); //Attach interrupt to bcm pin 23 // forever loop - while (1){ - + while (1) { /****************** Ping Out Role ***************************/ - if (role == role_ping_out) // Radio is in ping mode + 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 - timer = millis(); // Record the current microsecond count + radio.stopListening(); // First, stop listening so we can talk. + printf("Now sending %d as payload. ", counter); // Use a simple byte counter as payload + timer = millis(); // Record the current microsecond count - radio.startWrite(&counter, 1, false); // Send the counter variable to the other radio - sleep(1); // Try again later + radio.startWrite(&counter, 1, false); // Send the counter variable to the other radio + sleep(1); // Try again later } - /****************** Pong Back Role ***************************/ // This is done by using ACK payloads & IRQ diff --git a/examples_linux/interrupts/pingpair_dyn_int.cpp b/examples_linux/interrupts/pingpair_dyn_int.cpp index e90e1739d..4c03c5ee7 100644 --- a/examples_linux/interrupts/pingpair_dyn_int.cpp +++ b/examples_linux/interrupts/pingpair_dyn_int.cpp @@ -79,7 +79,6 @@ void intHandler() int main(int argc, char** argv) { - // Print preamble: cout << "RF24/examples/pingpair_dyn/\n"; @@ -89,7 +88,6 @@ int main(int argc, char** argv) radio.setRetries(5, 15); radio.printDetails(); - /********* Role chooser ***********/ printf("\n ************ Role Setup ***********\n"); @@ -101,9 +99,12 @@ int main(int argc, char** argv) 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; + cout << "Role: Pong Back, awaiting transmission " << endl + << endl; + } + else { + cout << "Role: Ping Out, starting transmission " << endl + << endl; role = role_ping_out; } } @@ -112,7 +113,8 @@ int main(int argc, char** argv) if (role == role_ping_out) { radio.openWritingPipe(pipes[0]); radio.openReadingPipe(1, pipes[1]); - } else { + } + else { radio.openWritingPipe(pipes[1]); radio.openReadingPipe(1, pipes[0]); radio.startListening(); @@ -148,7 +150,8 @@ int main(int argc, char** argv) // Describe the results if (timeout) { printf("Failed, response timed out.\n\r"); - } else { + } + else { // Grab the response, compare, and send to debugging spew uint8_t len = radio.getDynamicPayloadSize(); radio.read(receive_payload, len); @@ -169,9 +172,5 @@ int main(int argc, char** argv) // Try again 1s later delay(100); } - - } } - - diff --git a/examples_linux/interrupts/transfer_interrupt.cpp b/examples_linux/interrupts/transfer_interrupt.cpp index 3fe0c178f..46387bf2d 100644 --- a/examples_linux/interrupts/transfer_interrupt.cpp +++ b/examples_linux/interrupts/transfer_interrupt.cpp @@ -48,7 +48,6 @@ RF24 radio(RPI_V2_GPIO_P1_15, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ); //RPi Alternate, with SPIDEV - Note: Edit RF24/arch/BBB/spi.cpp and set 'this->device = "/dev/spidev0.0";;' or as listed in /dev //RF24 radio(22,0); - /****************** Linux (BBB,x86,etc) ***********************/ // See http://tmrh20.github.io/RF24/pages.html for more information on usage @@ -59,8 +58,8 @@ RF24 radio(RPI_V2_GPIO_P1_15, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ); //RF24 radio(115,0); //BBB Alternate, with mraa -// CE pin = (Header P9, Pin 13) = 59 = 13 + 46 -//Note: Specify SPI BUS 0 or 1 instead of CS pin number. +// CE pin = (Header P9, Pin 13) = 59 = 13 + 46 +//Note: Specify SPI BUS 0 or 1 instead of CS pin number. //RF24 radio(59,0); /**************************************************************/ @@ -91,13 +90,13 @@ int main(int argc, char** argv) cout << "RF24/examples/Transfer/\n"; - radio.begin(); // Setup and configure rf radio + 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); // Use 8-bit CRC for performance + radio.setAutoAck(1); // Ensure autoACK is enabled + radio.setRetries(2, 15); // Optionally, increase the delay between retries & # of retries + radio.setCRCLength(RF24_CRC_8); // Use 8-bit CRC for performance radio.printDetails(); /********* Role chooser ***********/ @@ -112,9 +111,12 @@ int main(int argc, char** argv) 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; + cout << "Role: Pong Back, awaiting transmission " << endl + << endl; + } + else { + cout << "Role: Ping Out, starting transmission " << endl + << endl; role = role_ping_out; } } @@ -124,14 +126,15 @@ int main(int argc, char** argv) radio.openWritingPipe(addresses[1]); radio.openReadingPipe(1, addresses[0]); radio.stopListening(); - } else { + } + else { radio.openWritingPipe(addresses[0]); radio.openReadingPipe(1, addresses[1]); radio.startListening(); } for (int i = 0; i < 32; i++) { - data[i] = rand() % 255; //Load the buffer with random data + data[i] = rand() % 255; //Load the buffer with random data } // forever loop @@ -140,18 +143,17 @@ int main(int argc, char** argv) sleep(2); printf("Initiating Basic Data Transfer\n\r"); - long int cycles = 10000; //Change this to a higher or lower number. + long int cycles = 10000; //Change this to a higher or lower number. // unsigned long pauseTime = millis(); //Uncomment if autoAck == 1 ( NOACK ) startTime = millis(); - for (int i = 0; i < cycles; i++) { //Loop through a number of cycles - data[0] = i; //Change the first byte of the payload for identification - if (!radio.writeFast(&data, 32)) { //Write to the FIFO buffers - counter++; //Keep count of failed payloads + for (int i = 0; i < cycles; i++) { //Loop through a number of cycles + data[0] = i; //Change the first byte of the payload for identification + if (!radio.writeFast(&data, 32)) { //Write to the FIFO buffers + counter++; //Keep count of failed payloads } - //This is only required when NO ACK ( enableAutoAck(0) ) payloads are used /* if(millis() - pauseTime > 3){ // Need to drop out of TX mode every 4ms if sending a steady stream of multicast data pauseTime = millis(); @@ -171,7 +173,6 @@ int main(int argc, char** argv) printf("Transfer complete at %.2f KB/s \n\r", rate); printf("%lu of %lu Packets Failed to Send\n\r", counter, cycles); counter = 0; - } if (role == role_pong_back) { diff --git a/examples_linux/manualAcknowledgements.cpp b/examples_linux/manualAcknowledgements.cpp index 9f9f45de5..f352f33e2 100644 --- a/examples_linux/manualAcknowledgements.cpp +++ b/examples_linux/manualAcknowledgements.cpp @@ -1,259 +1,260 @@ -/* - * See documentation at https://nRF24.github.io/RF24 - * See License information at root directory of this library - * Author: Brendan Doherty (2bndy5) - */ - -/** - * A simple example of sending data from 1 nRF24L01 transceiver to another - * with manually transmitted (non-automatic) Acknowledgement (ACK) payloads. - * This example still uses ACK packets, but they have no payloads. Instead the - * acknowledging response is sent with `write()`. This tactic allows for more - * updated acknowledgement payload data, where actual ACK payloads' data are - * outdated by 1 transmission because they have to loaded before receiving a - * transmission. - * - * This example was written to be used on 2 devices acting as "nodes". - * Use `ctrl+c` to quit at any time. - */ -#include // time() -#include // cin, cout, endl -#include // string, getline() -#include // CLOCK_MONOTONIC_RAW, timespec, clock_gettime() -#include // RF24, RF24_PA_LOW, delay() - -using namespace std; - -/****************** Linux ***********************/ -// Radio CE Pin, CSN Pin, SPI Speed -// CE Pin uses GPIO number with BCM and SPIDEV drivers, other platforms use their own pin numbering -// CS Pin addresses the SPI bus number at /dev/spidev. -// ie: RF24 radio(, *10+); spidev1.0 is 10, spidev1.1 is 11 etc.. - -// Generic: -RF24 radio(22, 0); -/****************** Linux (BBB,x86,etc) ***********************/ -// See http://nRF24.github.io/RF24/pages.html for more information on usage -// See http://iotdk.intel.com/docs/master/mraa/ for more information on MRAA -// See https://www.kernel.org/doc/Documentation/spi/spidev for more information on SPIDEV - -// For this example, we'll be using a payload containing -// a string & an integer number that will be incremented -// on every successful transmission. -// Make a data structure to store the entire payload of different datatypes -struct PayloadStruct { - char message[7]; // only using 6 characters for TX & RX payloads - uint8_t counter; -}; -PayloadStruct payload; - -void setRole(); // prototype to set the node's role -void master(); // prototype of the TX node's behavior -void slave(); // prototype of the RX node's behavior - -// custom defined timer for evaluating transmission time in microseconds -struct timespec startTimer, endTimer; -uint32_t getMicros(); // prototype to get ellapsed time in microseconds - - -int main(int argc, char** argv) { - - // perform hardware check - if (!radio.begin()) { - cout << "radio hardware is not responding!!" << endl; - return 0; // quit now - } - - // append a NULL terminating 0 for printing as a c-string - payload.message[6] = 0; - - // Let these addresses be used for the pair of nodes used in this example - uint8_t address[2][6] = {"1Node", "2Node"}; - // the TX address^ , ^the RX address - // It is very helpful to think of an address as a path instead of as - // an identifying device destination - - // to use different addresses on a pair of radios, we need a variable to - // uniquely identify which address this radio will use to transmit - bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit - - // print example's name - cout << argv[0] << endl; - - // Set the radioNumber via the terminal on startup - cout << "Which radio is this? Enter '0' or '1'. Defaults to '0' "; - string input; - getline(cin, input); - radioNumber = input.length() > 0 && (uint8_t)input[0] == 49; - - // Set the PA Level low to try preventing power supply related problems - // because these examples are likely run with nodes in close proximity to - // each other. - radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. - - // save on transmission time by setting the radio to only transmit the - // number of bytes we need to transmit a float - radio.setPayloadSize(sizeof(payload)); // char[7] & uint8_t datatypes occupy 8 bytes - - // set the TX address of the RX node into the TX pipe - radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 - - // set the RX address of the TX node into a RX pipe - radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 - - // For debugging info - // radio.printDetails(); // (smaller) function that prints raw register values - // radio.printPrettyDetails(); // (larger) function that prints human readable data - - // ready to execute program now - setRole(); // calls master() or slave() based on user input - return 0; -} // main - - -/** - * set this node's role from stdin stream. - * this only considers the first char as input. - */ -void setRole() { - string input = ""; - while (!input.length()) { - cout << "*** PRESS 'T' to begin transmitting to the other node\n"; - cout << "*** PRESS 'R' to begin receiving from the other node\n"; - cout << "*** PRESS 'Q' to exit" << endl; - getline(cin, input); - if (input.length() >= 1) { - if (input[0] == 'T' || input[0] == 't') - master(); - else if (input[0] == 'R' || input[0] == 'r') - slave(); - else if (input[0] == 'Q' || input[0] == 'q') - break; - else - cout << input[0] << " is an invalid input. Please try again." << endl; - } - input = ""; // stay in the while loop - } // while -} // setRole() - - -/** - * make this node act as the transmitter - */ -void master() { - - memcpy(payload.message, "Hello ", 6); // set the outgoing message - radio.stopListening(); // put in TX mode - - unsigned int failures = 0; // keep track of failures - while (failures < 6) { - clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer); // start the timer - bool report = radio.write(&payload, sizeof(payload)); // transmit & save the report - - if (report) { - // transmission successful; wait for response and print results - - radio.startListening(); // put in RX mode - unsigned long start_timeout = millis(); // timer to detect no response - while (!radio.available()) { // wait for response - if (millis() - start_timeout > 200) // only wait 200 ms - break; - } - unsigned long ellapsedTime = getMicros(); // end the timer - radio.stopListening(); // put back in TX mode - - // print summary of transactions - uint8_t pipe; - cout << "Transmission successful! "; - if (radio.available(&pipe)) { // is there a payload received? grab the pipe number that received it - uint8_t bytes = radio.getPayloadSize(); // grab the incoming payload size - cout << "Round trip delay = "; - cout << ellapsedTime; // print the timer result - cout << " us. Sent: " << payload.message; // print outgoing message - cout << (unsigned int)payload.counter; // print outgoing counter - PayloadStruct received; - radio.read(&received, sizeof(received)); // get incoming payload - cout << " Recieved " << (unsigned int)bytes; // print incoming payload size - cout << " on pipe " << (unsigned int)pipe; // print RX pipe number - cout << ": " << received.message; // print the incoming message - cout << (unsigned int)received.counter; // print the incoming counter - cout << endl; - payload.counter = received.counter; // save incoming counter for next outgoing counter - } - else { - cout << "Recieved no response." << endl; // no response received - } - } - else { - cout << "Transmission failed or timed out"; // payload was not delivered - cout << endl; - failures++; // increment failure counter - } // report - - // to make this example readable in the terminal - delay(1000); // slow transmissions down by 1 second - } // while - - cout << failures << " failures detected. Leaving TX role." << endl; -} // master - - -/** - * make this node act as the receiver - */ -void slave() { - memcpy(payload.message, "World ", 6); // set the response message - radio.startListening(); // put in RX mode - - time_t startTimer = time(nullptr); // start a timer - while (time(nullptr) - startTimer < 6) { // use 6 second timeout - uint8_t pipe; - if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it - uint8_t bytes = radio.getPayloadSize(); // get size of incoming payload - PayloadStruct received; - radio.read(&received, sizeof(received)); // get incoming payload - payload.counter = received.counter + 1; // increment payload for response - - // transmit response & save result to `report` - radio.stopListening(); // put in TX mode - radio.writeFast(&payload, sizeof(payload)); // load response into TX FIFO - bool report = radio.txStandBy(150); // keep retrying for 150 ms - radio.startListening(); // put back in RX mode - - // print summary of transactions - cout << "Received " << (unsigned int)bytes; // print the size of the payload - cout << " bytes on pipe "; - cout << (unsigned int)pipe; // print the pipe number - cout << ": " << received.message; // print incoming message - cout << (unsigned int)received.counter; // print incoming counter - - if (report) { - cout << " Sent: " << payload.message; // print outgoing message - cout << (unsigned int)payload.counter; // print outgoing counter - cout << endl; - } - else { - cout << " Response failed to send." << endl; // failed to send response - } - startTimer = time(nullptr); // reset timer - } // available - } // while - - cout << "Nothing received in 6 seconds. Leaving RX role." << endl; - radio.stopListening(); // recommended idle mode is TX mode -} // slave - - -/** - * Calculate the ellapsed time in microseconds - */ -uint32_t getMicros() { - // this function assumes that the timer was started using - // `clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer);` - - clock_gettime(CLOCK_MONOTONIC_RAW, &endTimer); - uint32_t seconds = endTimer.tv_sec - startTimer.tv_sec; - uint32_t useconds = (endTimer.tv_nsec - startTimer.tv_nsec) / 1000; - - return ((seconds) * 1000 + useconds) + 0.5; -} +/* + * See documentation at https://nRF24.github.io/RF24 + * See License information at root directory of this library + * Author: Brendan Doherty (2bndy5) + */ + +/** + * A simple example of sending data from 1 nRF24L01 transceiver to another + * with manually transmitted (non-automatic) Acknowledgement (ACK) payloads. + * This example still uses ACK packets, but they have no payloads. Instead the + * acknowledging response is sent with `write()`. This tactic allows for more + * updated acknowledgement payload data, where actual ACK payloads' data are + * outdated by 1 transmission because they have to loaded before receiving a + * transmission. + * + * This example was written to be used on 2 devices acting as "nodes". + * Use `ctrl+c` to quit at any time. + */ +#include // time() +#include // cin, cout, endl +#include // string, getline() +#include // CLOCK_MONOTONIC_RAW, timespec, clock_gettime() +#include // RF24, RF24_PA_LOW, delay() + +using namespace std; + +/****************** Linux ***********************/ +// Radio CE Pin, CSN Pin, SPI Speed +// CE Pin uses GPIO number with BCM and SPIDEV drivers, other platforms use their own pin numbering +// CS Pin addresses the SPI bus number at /dev/spidev. +// ie: RF24 radio(, *10+); spidev1.0 is 10, spidev1.1 is 11 etc.. + +// Generic: +RF24 radio(22, 0); +/****************** Linux (BBB,x86,etc) ***********************/ +// See http://nRF24.github.io/RF24/pages.html for more information on usage +// See http://iotdk.intel.com/docs/master/mraa/ for more information on MRAA +// See https://www.kernel.org/doc/Documentation/spi/spidev for more information on SPIDEV + +// For this example, we'll be using a payload containing +// a string & an integer number that will be incremented +// on every successful transmission. +// Make a data structure to store the entire payload of different datatypes +struct PayloadStruct +{ + char message[7]; // only using 6 characters for TX & RX payloads + uint8_t counter; +}; +PayloadStruct payload; + +void setRole(); // prototype to set the node's role +void master(); // prototype of the TX node's behavior +void slave(); // prototype of the RX node's behavior + +// custom defined timer for evaluating transmission time in microseconds +struct timespec startTimer, endTimer; +uint32_t getMicros(); // prototype to get ellapsed time in microseconds + +int main(int argc, char** argv) +{ + + // perform hardware check + if (!radio.begin()) { + cout << "radio hardware is not responding!!" << endl; + return 0; // quit now + } + + // append a NULL terminating 0 for printing as a c-string + payload.message[6] = 0; + + // Let these addresses be used for the pair of nodes used in this example + uint8_t address[2][6] = {"1Node", "2Node"}; + // the TX address^ , ^the RX address + // It is very helpful to think of an address as a path instead of as + // an identifying device destination + + // to use different addresses on a pair of radios, we need a variable to + // uniquely identify which address this radio will use to transmit + bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit + + // print example's name + cout << argv[0] << endl; + + // Set the radioNumber via the terminal on startup + cout << "Which radio is this? Enter '0' or '1'. Defaults to '0' "; + string input; + getline(cin, input); + radioNumber = input.length() > 0 && (uint8_t)input[0] == 49; + + // Set the PA Level low to try preventing power supply related problems + // because these examples are likely run with nodes in close proximity to + // each other. + radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. + + // save on transmission time by setting the radio to only transmit the + // number of bytes we need to transmit a float + radio.setPayloadSize(sizeof(payload)); // char[7] & uint8_t datatypes occupy 8 bytes + + // set the TX address of the RX node into the TX pipe + radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 + + // set the RX address of the TX node into a RX pipe + radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 + + // For debugging info + // radio.printDetails(); // (smaller) function that prints raw register values + // radio.printPrettyDetails(); // (larger) function that prints human readable data + + // ready to execute program now + setRole(); // calls master() or slave() based on user input + return 0; +} // main + +/** + * set this node's role from stdin stream. + * this only considers the first char as input. + */ +void setRole() +{ + string input = ""; + while (!input.length()) { + cout << "*** PRESS 'T' to begin transmitting to the other node\n"; + cout << "*** PRESS 'R' to begin receiving from the other node\n"; + cout << "*** PRESS 'Q' to exit" << endl; + getline(cin, input); + if (input.length() >= 1) { + if (input[0] == 'T' || input[0] == 't') + master(); + else if (input[0] == 'R' || input[0] == 'r') + slave(); + else if (input[0] == 'Q' || input[0] == 'q') + break; + else + cout << input[0] << " is an invalid input. Please try again." << endl; + } + input = ""; // stay in the while loop + } // while +} // setRole() + +/** + * make this node act as the transmitter + */ +void master() +{ + + memcpy(payload.message, "Hello ", 6); // set the outgoing message + radio.stopListening(); // put in TX mode + + unsigned int failures = 0; // keep track of failures + while (failures < 6) { + clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer); // start the timer + bool report = radio.write(&payload, sizeof(payload)); // transmit & save the report + + if (report) { + // transmission successful; wait for response and print results + + radio.startListening(); // put in RX mode + unsigned long start_timeout = millis(); // timer to detect no response + while (!radio.available()) { // wait for response + if (millis() - start_timeout > 200) // only wait 200 ms + break; + } + unsigned long ellapsedTime = getMicros(); // end the timer + radio.stopListening(); // put back in TX mode + + // print summary of transactions + uint8_t pipe; + cout << "Transmission successful! "; + if (radio.available(&pipe)) { // is there a payload received? grab the pipe number that received it + uint8_t bytes = radio.getPayloadSize(); // grab the incoming payload size + cout << "Round trip delay = "; + cout << ellapsedTime; // print the timer result + cout << " us. Sent: " << payload.message; // print outgoing message + cout << (unsigned int)payload.counter; // print outgoing counter + PayloadStruct received; + radio.read(&received, sizeof(received)); // get incoming payload + cout << " Recieved " << (unsigned int)bytes; // print incoming payload size + cout << " on pipe " << (unsigned int)pipe; // print RX pipe number + cout << ": " << received.message; // print the incoming message + cout << (unsigned int)received.counter; // print the incoming counter + cout << endl; + payload.counter = received.counter; // save incoming counter for next outgoing counter + } + else { + cout << "Recieved no response." << endl; // no response received + } + } + else { + cout << "Transmission failed or timed out"; // payload was not delivered + cout << endl; + failures++; // increment failure counter + } // report + + // to make this example readable in the terminal + delay(1000); // slow transmissions down by 1 second + } // while + + cout << failures << " failures detected. Leaving TX role." << endl; +} // master + +/** + * make this node act as the receiver + */ +void slave() +{ + memcpy(payload.message, "World ", 6); // set the response message + radio.startListening(); // put in RX mode + + time_t startTimer = time(nullptr); // start a timer + while (time(nullptr) - startTimer < 6) { // use 6 second timeout + uint8_t pipe; + if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it + uint8_t bytes = radio.getPayloadSize(); // get size of incoming payload + PayloadStruct received; + radio.read(&received, sizeof(received)); // get incoming payload + payload.counter = received.counter + 1; // increment payload for response + + // transmit response & save result to `report` + radio.stopListening(); // put in TX mode + radio.writeFast(&payload, sizeof(payload)); // load response into TX FIFO + bool report = radio.txStandBy(150); // keep retrying for 150 ms + radio.startListening(); // put back in RX mode + + // print summary of transactions + cout << "Received " << (unsigned int)bytes; // print the size of the payload + cout << " bytes on pipe "; + cout << (unsigned int)pipe; // print the pipe number + cout << ": " << received.message; // print incoming message + cout << (unsigned int)received.counter; // print incoming counter + + if (report) { + cout << " Sent: " << payload.message; // print outgoing message + cout << (unsigned int)payload.counter; // print outgoing counter + cout << endl; + } + else { + cout << " Response failed to send." << endl; // failed to send response + } + startTimer = time(nullptr); // reset timer + } // available + } // while + + cout << "Nothing received in 6 seconds. Leaving RX role." << endl; + radio.stopListening(); // recommended idle mode is TX mode +} // slave + +/** + * Calculate the ellapsed time in microseconds + */ +uint32_t getMicros() +{ + // this function assumes that the timer was started using + // `clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer);` + + clock_gettime(CLOCK_MONOTONIC_RAW, &endTimer); + uint32_t seconds = endTimer.tv_sec - startTimer.tv_sec; + uint32_t useconds = (endTimer.tv_nsec - startTimer.tv_nsec) / 1000; + + return ((seconds)*1000 + useconds) + 0.5; +} diff --git a/examples_linux/manual_acknowledgements.py b/examples_linux/manual_acknowledgements.py index e0f79687a..c2ec930c2 100644 --- a/examples_linux/manual_acknowledgements.py +++ b/examples_linux/manual_acknowledgements.py @@ -1,254 +1,245 @@ -""" -A simple example of sending data from 1 nRF24L01 transceiver to another -with manually transmitted (non-automatic) Acknowledgement (ACK) payloads. -This example still uses ACK packets, but they have no payloads. Instead the -acknowledging response is sent with `write()`. This tactic allows for more -updated acknowledgement payload data, where actual ACK payloads' data are -outdated by 1 transmission because they have to loaded before receiving a -transmission. - -This example was written to be used on 2 devices acting as 'nodes'. -""" -import sys -import argparse -import time -import struct -from RF24 import RF24, RF24_PA_LOW - - -parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter -) -parser.add_argument( - "-n", - "--node", - type=int, - choices=range(2), - help="the identifying radio number (or node ID number)" -) -parser.add_argument( - "-r", - "--role", - type=int, - choices=range(2), - help="'1' specifies the TX role. '0' specifies the RX role." -) - -########### USER CONFIGURATION ########### -# See https://github.com/TMRh20/RF24/blob/master/pyRF24/readme.md -# Radio CE Pin, CSN Pin, SPI Speed -# CE Pin uses GPIO number with BCM and SPIDEV drivers, other platforms use -# their own pin numbering -# CS Pin addresses the SPI bus number at /dev/spidev. -# ie: RF24 radio(, *10+); spidev1.0 is 10, spidev1.1 is 11 etc.. - -# Generic: -radio = RF24(22, 0) -################## Linux (BBB,x86,etc) ######################### -# See http://nRF24.github.io/RF24/pages.html for more information on usage -# See http://iotdk.intel.com/docs/master/mraa/ for more information on MRAA -# See https://www.kernel.org/doc/Documentation/spi/spidev for more -# information on SPIDEV - -# using the python keyword global is bad practice. Instead we'll use a 1 item -# list to store our integer number for the payloads' counter -counter = [0] - - -def master(): - """Transmits a message and an incrementing integer every second, then - wait for a response for up to 200 ms. - """ - radio.stopListening() # put radio in TX mode - failures = 0 - while failures < 6: - # use bytes() to pack our counter data into the payload - # NOTE b"\x00" byte is a c-string's NULL terminating 0 - buffer = b"Hello \x00" + bytes(counter) - start_timer = time.monotonic_ns() # start timer - result = radio.write(buffer) - if not result: - failures += 1 - print("Transmission failed or timed out") - else: - radio.startListening() # put radio in RX mode - timout = time.monotonic() * 1000 + 200 # use 200 ms timeout - # declare a variable to save the incoming response - while not radio.available() and time.monotonic() * 1000 < timout: - pass # wait for incoming payload or timeout - radio.stopListening() # put radio in TX mode - end_timer = time.monotonic_ns() # end timer - print( - "Transmission successful. Sent: {}{}.".format( - buffer[:6].decode("utf-8"), - counter[0] - ), - end=" " - ) - has_payload, pipe_number = radio.available_pipe() - if has_payload: - # grab the incoming payload - received = radio.read(radio.payloadSize) - # NOTE received[7:8] discards NULL terminating 0 - counter[0] = received[7:8][0] # save the counter - print( - "Received {} bytes on pipe {}: {}{}. " - "Round-trip delay: {} us.".format( - radio.payloadSize, - pipe_number, - bytes(received[:6]).decode("utf-8"), - counter[0], - (end_timer - start_timer) / 1000 - ) - ) - else: - print("No response received.") - time.sleep(1) # make example readable by slowing down transmissions - print(failures, "failures detected. Leaving TX role.") - - -def slave(timeout=6): - """Listen for any payloads and print the transaction - - :param int timeout: The number of seconds to wait (with no transmission) - until exiting function. - """ - radio.startListening() # put radio in RX mode - - start_timer = time.monotonic() # start a timer to detect timeout - while (time.monotonic() - start_timer) < timeout: - # receive `count` payloads or wait 6 seconds till timing out - has_payload, pipe_number = radio.available_pipe() - if has_payload: - received = radio.read(radio.payloadSize) # fetch the payload - # NOTE received[7:8] discards NULL terminating 0 - # increment the counter from received payload - counter[0] = received[7:8][0] + 1 if received[7:8][0] < 255 else 0 - # use bytes() to pack our counter data into the payload - # NOTE b"\x00" byte is a c-string's NULL terminating 0 - buffer = b"World \x00" + bytes(counter) - radio.stopListening() # put radio in TX mode - radio.writeFast(buffer) # load response into TX FIFO - # keep retrying to send response for 150 milliseconds - result = radio.txStandBy(150) # save response's result - # NOTE txStandBy() flushes TX FIFO on transmission failure - radio.startListening() # put radio back in RX mode - # print the payload received payload - print( - "Received {} bytes on pipe {}: {}{}.".format( - radio.payloadSize, - pipe_number, - bytes(received[:6]).decode("utf-8"), - received[7:8][0] - ), - end=" " - ) - if result: # did response succeed? - # print response's payload - print( - "Sent: {}{}".format( - buffer[:6].decode("utf-8"), - counter[0] - ) - ) - else: - print("Response failed or timed out") - start_timer = time.monotonic() # reset the timeout timer - - print("Nothing received in", timeout, "seconds. Leaving RX role") - # recommended behavior is to keep in TX mode while idle - radio.stopListening() # put the radio in TX mode - - -def set_role(): - """Set the role using stdin stream. Timeout arg for slave() can be - specified using a space delimiter (e.g. 'R 10' calls `slave(10)`) - - :return: - - True when role is complete & app should continue running. - - False when app should exit - """ - user_input = input( - "*** Enter 'R' for receiver role.\n" - "*** Enter 'T' for transmitter role.\n" - "*** Enter 'Q' to quit example.\n" - ) or "?" - user_input = user_input.split() - if user_input[0].upper().startswith("R"): - if len(user_input) > 1: - slave(int(user_input[1])) - else: - slave() - return True - elif user_input[0].upper().startswith("T"): - master() - return True - elif user_input[0].upper().startswith("Q"): - radio.powerDown() - return False - print(user_input[0], "is an unrecognized input. Please try again.") - return set_role() - - -if __name__ == "__main__": - - args = parser.parse_args() # parse any CLI args - - # initialize the nRF24L01 on the spi bus - if not radio.begin(): - raise RuntimeError("radio hardware is not responding") - - # For this example, we will use different addresses - # An address need to be a buffer protocol object (bytearray) - address = [b"1Node", b"2Node"] - # It is very helpful to think of an address as a path instead of as - # an identifying device destination - - print(sys.argv[0]) # print example name - - # to use different addresses on a pair of radios, we need a variable to - # uniquely identify which address this radio will use to transmit - # 0 uses address[0] to transmit, 1 uses address[1] to transmit - radio_number = args.node # uses default value from `parser` - if args.node is None: # if '--node' arg wasn't specified - radio_number = bool( - int( - input( - "Which radio is this? Enter '0' or '1'. Defaults to '0' " - ) or 0 - ) - ) - - # set the Power Amplifier level to -12 dBm since this test example is - # usually run with nRF24L01 transceivers in close proximity of each other - radio.setPALevel(RF24_PA_LOW) # RF24_PA_MAX is default - - # set the TX address of the RX node into the TX pipe - radio.openWritingPipe(address[radio_number]) # always uses pipe 0 - - # set the RX address of the TX node into a RX pipe - radio.openReadingPipe(1, address[not radio_number]) # using pipe 1 - - # To save time during transmission, we'll set the payload size to be only - # what we need. For this example, we'll be using a byte for the - # payload counter and 7 bytes for the payload message - radio.payloadSize = 8 - - # for debugging, we have 2 options that print a large block of details - # (smaller) function that prints raw register values - # radio.printDetails() - # (larger) function that prints human readable data - # radio.printPrettyDetails() - - try: - if args.role is None: # if not specified with CLI arg '-r' - while set_role(): - pass # continue example until 'Q' is entered - else: # if role was set using CLI args - # run role once and exit - master() if bool(args.role) else slave() - except KeyboardInterrupt: - print(" Keyboard Interrupt detected. Exiting...") - radio.powerDown() - sys.exit() +""" +A simple example of sending data from 1 nRF24L01 transceiver to another +with manually transmitted (non-automatic) Acknowledgement (ACK) payloads. +This example still uses ACK packets, but they have no payloads. Instead the +acknowledging response is sent with `write()`. This tactic allows for more +updated acknowledgement payload data, where actual ACK payloads' data are +outdated by 1 transmission because they have to loaded before receiving a +transmission. + +This example was written to be used on 2 devices acting as 'nodes'. +""" +import sys +import argparse +import time +from RF24 import RF24, RF24_PA_LOW + + +parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter +) +parser.add_argument( + "-n", + "--node", + type=int, + choices=range(2), + help="the identifying radio number (or node ID number)", +) +parser.add_argument( + "-r", + "--role", + type=int, + choices=range(2), + help="'1' specifies the TX role. '0' specifies the RX role.", +) + +########### USER CONFIGURATION ########### +# See https://github.com/TMRh20/RF24/blob/master/pyRF24/readme.md +# Radio CE Pin, CSN Pin, SPI Speed +# CE Pin uses GPIO number with BCM and SPIDEV drivers, other platforms use +# their own pin numbering +# CS Pin addresses the SPI bus number at /dev/spidev. +# ie: RF24 radio(, *10+); spidev1.0 is 10, spidev1.1 is 11 etc.. + +# Generic: +radio = RF24(22, 0) +################## Linux (BBB,x86,etc) ######################### +# See http://nRF24.github.io/RF24/pages.html for more information on usage +# See http://iotdk.intel.com/docs/master/mraa/ for more information on MRAA +# See https://www.kernel.org/doc/Documentation/spi/spidev for more +# information on SPIDEV + +# using the python keyword global is bad practice. Instead we'll use a 1 item +# list to store our integer number for the payloads' counter +counter = [0] + + +def master(): + """Transmits a message and an incrementing integer every second, then + wait for a response for up to 200 ms. + """ + radio.stopListening() # put radio in TX mode + failures = 0 + while failures < 6: + # use bytes() to pack our counter data into the payload + # NOTE b"\x00" byte is a c-string's NULL terminating 0 + buffer = b"Hello \x00" + bytes(counter) + start_timer = time.monotonic_ns() # start timer + result = radio.write(buffer) + if not result: + failures += 1 + print("Transmission failed or timed out") + else: + radio.startListening() # put radio in RX mode + timout = time.monotonic() * 1000 + 200 # use 200 ms timeout + # declare a variable to save the incoming response + while not radio.available() and time.monotonic() * 1000 < timout: + pass # wait for incoming payload or timeout + radio.stopListening() # put radio in TX mode + end_timer = time.monotonic_ns() # end timer + print( + "Transmission successful. Sent: {}{}.".format( + buffer[:6].decode("utf-8"), counter[0] + ), + end=" ", + ) + has_payload, pipe_number = radio.available_pipe() + if has_payload: + # grab the incoming payload + received = radio.read(radio.payloadSize) + # NOTE received[7:8] discards NULL terminating 0 + counter[0] = received[7:8][0] # save the counter + print( + "Received {} bytes on pipe {}: {}{}. " + "Round-trip delay: {} us.".format( + radio.payloadSize, + pipe_number, + bytes(received[:6]).decode("utf-8"), + counter[0], + (end_timer - start_timer) / 1000, + ) + ) + else: + print("No response received.") + time.sleep(1) # make example readable by slowing down transmissions + print(failures, "failures detected. Leaving TX role.") + + +def slave(timeout=6): + """Listen for any payloads and print the transaction + + :param int timeout: The number of seconds to wait (with no transmission) + until exiting function. + """ + radio.startListening() # put radio in RX mode + + start_timer = time.monotonic() # start a timer to detect timeout + while (time.monotonic() - start_timer) < timeout: + # receive `count` payloads or wait 6 seconds till timing out + has_payload, pipe_number = radio.available_pipe() + if has_payload: + received = radio.read(radio.payloadSize) # fetch the payload + # NOTE received[7:8] discards NULL terminating 0 + # increment the counter from received payload + counter[0] = received[7:8][0] + 1 if received[7:8][0] < 255 else 0 + # use bytes() to pack our counter data into the payload + # NOTE b"\x00" byte is a c-string's NULL terminating 0 + buffer = b"World \x00" + bytes(counter) + radio.stopListening() # put radio in TX mode + radio.writeFast(buffer) # load response into TX FIFO + # keep retrying to send response for 150 milliseconds + result = radio.txStandBy(150) # save response's result + # NOTE txStandBy() flushes TX FIFO on transmission failure + radio.startListening() # put radio back in RX mode + # print the payload received payload + print( + "Received {} bytes on pipe {}: {}{}.".format( + radio.payloadSize, + pipe_number, + bytes(received[:6]).decode("utf-8"), + received[7:8][0], + ), + end=" ", + ) + if result: # did response succeed? + # print response's payload + print("Sent: {}{}".format(buffer[:6].decode("utf-8"), counter[0])) + else: + print("Response failed or timed out") + start_timer = time.monotonic() # reset the timeout timer + + print("Nothing received in", timeout, "seconds. Leaving RX role") + # recommended behavior is to keep in TX mode while idle + radio.stopListening() # put the radio in TX mode + + +def set_role(): + """Set the role using stdin stream. Timeout arg for slave() can be + specified using a space delimiter (e.g. 'R 10' calls `slave(10)`) + + :return: + - True when role is complete & app should continue running. + - False when app should exit + """ + user_input = ( + input( + "*** Enter 'R' for receiver role.\n" + "*** Enter 'T' for transmitter role.\n" + "*** Enter 'Q' to quit example.\n" + ) + or "?" + ) + user_input = user_input.split() + if user_input[0].upper().startswith("R"): + if len(user_input) > 1: + slave(int(user_input[1])) + else: + slave() + return True + elif user_input[0].upper().startswith("T"): + master() + return True + elif user_input[0].upper().startswith("Q"): + radio.powerDown() + return False + print(user_input[0], "is an unrecognized input. Please try again.") + return set_role() + + +if __name__ == "__main__": + + args = parser.parse_args() # parse any CLI args + + # initialize the nRF24L01 on the spi bus + if not radio.begin(): + raise RuntimeError("radio hardware is not responding") + + # For this example, we will use different addresses + # An address need to be a buffer protocol object (bytearray) + address = [b"1Node", b"2Node"] + # It is very helpful to think of an address as a path instead of as + # an identifying device destination + + print(sys.argv[0]) # print example name + + # to use different addresses on a pair of radios, we need a variable to + # uniquely identify which address this radio will use to transmit + # 0 uses address[0] to transmit, 1 uses address[1] to transmit + radio_number = args.node # uses default value from `parser` + if args.node is None: # if '--node' arg wasn't specified + radio_number = bool( + int(input("Which radio is this? Enter '0' or '1'. Defaults to '0' ") or 0) + ) + + # set the Power Amplifier level to -12 dBm since this test example is + # usually run with nRF24L01 transceivers in close proximity of each other + radio.setPALevel(RF24_PA_LOW) # RF24_PA_MAX is default + + # set the TX address of the RX node into the TX pipe + radio.openWritingPipe(address[radio_number]) # always uses pipe 0 + + # set the RX address of the TX node into a RX pipe + radio.openReadingPipe(1, address[not radio_number]) # using pipe 1 + + # To save time during transmission, we'll set the payload size to be only + # what we need. For this example, we'll be using a byte for the + # payload counter and 7 bytes for the payload message + radio.payloadSize = 8 + + # for debugging, we have 2 options that print a large block of details + # (smaller) function that prints raw register values + # radio.printDetails() + # (larger) function that prints human readable data + # radio.printPrettyDetails() + + try: + if args.role is None: # if not specified with CLI arg '-r' + while set_role(): + pass # continue example until 'Q' is entered + else: # if role was set using CLI args + # run role once and exit + master() if bool(args.role) else slave() + except KeyboardInterrupt: + print(" Keyboard Interrupt detected. Exiting...") + radio.powerDown() + sys.exit() diff --git a/examples_linux/multiceiverDemo.cpp b/examples_linux/multiceiverDemo.cpp index 58bab7aed..ee8b5ec60 100644 --- a/examples_linux/multiceiverDemo.cpp +++ b/examples_linux/multiceiverDemo.cpp @@ -1,273 +1,271 @@ -/* - * See documentation at https://nRF24.github.io/RF24 - * See License information at root directory of this library - * Author: Brendan Doherty (2bndy5) - */ - -/** - * A simple example of sending data from as many as 6 nRF24L01 transceivers to - * 1 receiving transceiver. This technique is trademarked by - * Nordic Semiconductors as "MultiCeiver". - * - * This example was written to be used on up to 6 devices acting as TX nodes & - * only 1 device acting as the RX node (that's a maximum of 7 devices). - * Use `ctrl+c` to quit at any time. - */ -#include // time() -#include // strcmp() -#include // cin, cout, endl -#include // string, getline() -#include // CLOCK_MONOTONIC_RAW, timespec, clock_gettime() -#include // RF24, RF24_PA_LOW, delay() - -using namespace std; - -/****************** Linux ***********************/ -// Radio CE Pin, CSN Pin, SPI Speed -// CE Pin uses GPIO number with BCM and SPIDEV drivers, other platforms use their own pin numbering -// CS Pin addresses the SPI bus number at /dev/spidev. -// ie: RF24 radio(, *10+); spidev1.0 is 10, spidev1.1 is 11 etc.. - -// Generic: -RF24 radio(22, 0); -/****************** Linux (BBB,x86,etc) ***********************/ -// See http://nRF24.github.io/RF24/pages.html for more information on usage -// See http://iotdk.intel.com/docs/master/mraa/ for more information on MRAA -// See https://www.kernel.org/doc/Documentation/spi/spidev for more information on SPIDEV - - -// For this example, we'll be using 6 addresses; 1 for each TX node -// It is very helpful to think of an address as a path instead of as -// an identifying device destination -// Notice that the last byte is the only byte that changes in the last 5 -// addresses. This is a limitation of the nRF24L01 transceiver for pipes 2-5 -// because they use the same first 4 bytes from pipe 1. -uint64_t address[6] = {0x7878787878LL, - 0xB3B4B5B6F1LL, - 0xB3B4B5B6CDLL, - 0xB3B4B5B6A3LL, - 0xB3B4B5B60FLL, - 0xB3B4B5B605LL}; - - -// For this example, we'll be using a payload containing -// a node ID number and a single integer number that will be incremented -// on every successful transmission. -// Make a data structure to use as a payload. -struct PayloadStruct -{ - unsigned int nodeID; - unsigned int payloadID; -}; -PayloadStruct payload; - -void setRole(); // prototype to set the node's role -void master(unsigned int); // prototype of a TX node's behavior -void slave(); // prototype of the RX node's behavior -void printHelp(string); // prototype to function that explain CLI arg usage - -// custom defined timer for evaluating transmission time in microseconds -struct timespec startTimer, endTimer; -uint32_t getMicros(); // prototype to get ellapsed time in microseconds - - -int main(int argc, char** argv) { - - // perform hardware check - if (!radio.begin()) { - cout << "radio hardware is not responding!!" << endl; - return 0; // quit now - } - - // to use different addresses on a pair of radios, we need a variable to - // uniquely identify which address this radio will use to transmit - unsigned int nodeNumber = 'R'; // integers 0-5 = TX node; character 'R' or integer 82 = RX node - - bool foundArgNode = false; - if (argc > 1) { - if ((argc - 1) != 2) { - // CLI arg "-n"/"--node" needs an option specified for it - // only 1 arg is expected, so only traverse the first "--arg option" pair - printHelp(string(argv[0])); - return 0; - } - else if (strcmp(argv[1], "-n") == 0 || strcmp(argv[1], "--node") == 0) { - // "-n" or "--node" has been specified - foundArgNode = true; - if ((argv[2][0] - 48) < 6 && (argv[2][0] - 48) >= 0) { - nodeNumber = argv[2][0] - 48; - } - else if (argv[2][0] == 'R' || argv[2][0] == 'r') { - nodeNumber = 'R'; - } - else { - printHelp(string(argv[0])); - return 0; - } - } - else { - // "-n"/"--node" arg was not specified - printHelp(string(argv[0])); - return 0; - } - } - - // print example's name - cout << argv[0] << endl; - - // Set the PA Level low to try preventing power supply related problems - // because these examples are likely run with nodes in close proximity to - // each other. - radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. - - // save on transmission time by setting the radio to only transmit the - // number of bytes we need to transmit a float - radio.setPayloadSize(sizeof(payload)); // 2x int datatype occupy 8 bytes - - // For debugging info - // radio.printDetails(); // (smaller) function that prints raw register values - // radio.printPrettyDetails(); // (larger) function that prints human readable data - - // ready to execute program now - if (!foundArgNode) { - setRole(); // calls master() or slave() based on user input - } - else { - nodeNumber < 6 ? master(nodeNumber) : slave(); - } - return 0; -} - - -/** - * set this node's role from stdin stream. - * this only considers the first char as input. - */ -void setRole() { - - string input = ""; - while (!input.length()) { - cout << "*** Enter a number between 0 and 5 (inclusive) to act as\n"; - cout << " a unique node number that transmits to the RX node.\n"; - cout << "*** PRESS 'R' to begin receiving from the other nodes\n"; - cout << "*** PRESS 'Q' to exit" << endl; - getline(cin, input); - if (input.length() >= 1) { - unsigned int toNumber = (unsigned int)(input[0]) - 48; - if (toNumber < 6 && toNumber >= 0) - master(toNumber); - else if (input[0] == 'R' || input[0] == 'r') - slave(); - else if (input[0] == 'Q' || input[0] == 'q') - break; - else - cout << input[0] << " is an invalid input. Please try again." << endl; - } - input = ""; // stay in the while loop - } // while -} // setRole - - -/** - * act as unique TX node identified by the `role` number - */ -void master(unsigned int role) { - // set the payload's nodeID & reset the payload's identifying number - payload.nodeID = role; - payload.payloadID = 0; - - // Set the address on pipe 0 to the RX node. - radio.stopListening(); // put radio in TX mode - radio.openWritingPipe(address[role]); - - // According to the datasheet, the auto-retry features's delay value should - // be "skewed" to allow the RX node to receive 1 transmission at a time. - // So, use varying delay between retry attempts and 15 (at most) retry attempts - radio.setRetries(((role * 3) % 12) + 3, 15); // maximum value is 15 for both args - - unsigned int failures = 0; - while (failures < 6) { - clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer); // start the timer - bool report = radio.write(&payload, sizeof(payload)); // transmit & save the report - uint32_t timerEllapsed = getMicros(); // end the timer - - if (report) { - // payload was delivered - cout << "Transmission of PayloadID "; - cout << payload.payloadID; // print payload number - cout << " as node " << payload.nodeID; // print node number - cout << " successful! Time to transmit = "; - cout << timerEllapsed << " us" << endl; // print the timer result - } - else { - // payload was not delivered - failures++; - cout << "Transmission failed or timed out" << endl; - } - payload.payloadID++; // increment payload number - - // to make this example readable in the terminal - delay(1000); // slow transmissions down by 1 second - } // while - cout << failures << " failures detected. Leaving TX role." << endl; -} // master - - -/** - * act as the RX node that receives from up to 6 other TX nodes - */ -void slave() { - - // Set the addresses for all pipes to TX nodes - for (uint8_t i = 0; i < 6; ++i) - radio.openReadingPipe(i, address[i]); - - radio.startListening(); // put radio in RX mode - - time_t startTimer = time(nullptr); // start a timer - while (time(nullptr) - startTimer < 6) { // use 6 second timeout - uint8_t pipe; - if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it - uint8_t bytes = radio.getPayloadSize(); // get the size of the payload - radio.read(&payload, bytes); // fetch payload from FIFO - cout << "Received " << (unsigned int)bytes; // print the size of the payload - cout << " bytes on pipe " << (unsigned int)pipe; // print the pipe number - cout << " from node " << payload.nodeID; // print the payload's origin - cout << ". PayloadID: " << payload.payloadID << endl; // print the payload's number - startTimer = time(nullptr); // reset timer - } - } - cout << "Nothing received in 6 seconds. Leaving RX role." << endl; -} // slave - - -/** - * Calculate the ellapsed time in microseconds - */ -uint32_t getMicros() { - // this function assumes that the timer was started using - // `clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer);` - - clock_gettime(CLOCK_MONOTONIC_RAW, &endTimer); - uint32_t seconds = endTimer.tv_sec - startTimer.tv_sec; - uint32_t useconds = (endTimer.tv_nsec - startTimer.tv_nsec) / 1000; - - return ((seconds) * 1000 + useconds) + 0.5; -} - - -/** - * print a manual page of instructions on how to use this example's CLI args - */ -void printHelp(string progName) { - cout << "usage: " << progName << " [-h] [-n {0,1,2,3,4,5,r,R}]\n\n" - << "A simple example of sending data from as many as 6 nRF24L01 transceivers to\n" - << "1 receiving transceiver. This technique is trademarked by\n" - << "Nordic Semiconductors as 'MultiCeiver'.\n" - << "\nThis example was written to be used on up to 6 devices acting as TX nodes with\n" - << "another device acting as a RX node (that's a total of 7 devices).\n" - << "\noptional arguments:\n -h, --help\t\tshow this help message and exit\n" - << " -n {0,1,2,3,4,5,r,R}, --node {0,1,2,3,4,5,r,R}" - << "\n\t\t\t0-5 specifies the identifying node ID number for the TX role." - << "\n\t\t\t'r' or 'R' specifies the RX role." << endl; -} +/* + * See documentation at https://nRF24.github.io/RF24 + * See License information at root directory of this library + * Author: Brendan Doherty (2bndy5) + */ + +/** + * A simple example of sending data from as many as 6 nRF24L01 transceivers to + * 1 receiving transceiver. This technique is trademarked by + * Nordic Semiconductors as "MultiCeiver". + * + * This example was written to be used on up to 6 devices acting as TX nodes & + * only 1 device acting as the RX node (that's a maximum of 7 devices). + * Use `ctrl+c` to quit at any time. + */ +#include // time() +#include // strcmp() +#include // cin, cout, endl +#include // string, getline() +#include // CLOCK_MONOTONIC_RAW, timespec, clock_gettime() +#include // RF24, RF24_PA_LOW, delay() + +using namespace std; + +/****************** Linux ***********************/ +// Radio CE Pin, CSN Pin, SPI Speed +// CE Pin uses GPIO number with BCM and SPIDEV drivers, other platforms use their own pin numbering +// CS Pin addresses the SPI bus number at /dev/spidev. +// ie: RF24 radio(, *10+); spidev1.0 is 10, spidev1.1 is 11 etc.. + +// Generic: +RF24 radio(22, 0); +/****************** Linux (BBB,x86,etc) ***********************/ +// See http://nRF24.github.io/RF24/pages.html for more information on usage +// See http://iotdk.intel.com/docs/master/mraa/ for more information on MRAA +// See https://www.kernel.org/doc/Documentation/spi/spidev for more information on SPIDEV + +// For this example, we'll be using 6 addresses; 1 for each TX node +// It is very helpful to think of an address as a path instead of as +// an identifying device destination +// Notice that the last byte is the only byte that changes in the last 5 +// addresses. This is a limitation of the nRF24L01 transceiver for pipes 2-5 +// because they use the same first 4 bytes from pipe 1. +uint64_t address[6] = {0x7878787878LL, + 0xB3B4B5B6F1LL, + 0xB3B4B5B6CDLL, + 0xB3B4B5B6A3LL, + 0xB3B4B5B60FLL, + 0xB3B4B5B605LL}; + +// For this example, we'll be using a payload containing +// a node ID number and a single integer number that will be incremented +// on every successful transmission. +// Make a data structure to use as a payload. +struct PayloadStruct +{ + unsigned int nodeID; + unsigned int payloadID; +}; +PayloadStruct payload; + +void setRole(); // prototype to set the node's role +void master(unsigned int); // prototype of a TX node's behavior +void slave(); // prototype of the RX node's behavior +void printHelp(string); // prototype to function that explain CLI arg usage + +// custom defined timer for evaluating transmission time in microseconds +struct timespec startTimer, endTimer; +uint32_t getMicros(); // prototype to get ellapsed time in microseconds + +int main(int argc, char** argv) +{ + + // perform hardware check + if (!radio.begin()) { + cout << "radio hardware is not responding!!" << endl; + return 0; // quit now + } + + // to use different addresses on a pair of radios, we need a variable to + // uniquely identify which address this radio will use to transmit + unsigned int nodeNumber = 'R'; // integers 0-5 = TX node; character 'R' or integer 82 = RX node + + bool foundArgNode = false; + if (argc > 1) { + if ((argc - 1) != 2) { + // CLI arg "-n"/"--node" needs an option specified for it + // only 1 arg is expected, so only traverse the first "--arg option" pair + printHelp(string(argv[0])); + return 0; + } + else if (strcmp(argv[1], "-n") == 0 || strcmp(argv[1], "--node") == 0) { + // "-n" or "--node" has been specified + foundArgNode = true; + if ((argv[2][0] - 48) < 6 && (argv[2][0] - 48) >= 0) { + nodeNumber = argv[2][0] - 48; + } + else if (argv[2][0] == 'R' || argv[2][0] == 'r') { + nodeNumber = 'R'; + } + else { + printHelp(string(argv[0])); + return 0; + } + } + else { + // "-n"/"--node" arg was not specified + printHelp(string(argv[0])); + return 0; + } + } + + // print example's name + cout << argv[0] << endl; + + // Set the PA Level low to try preventing power supply related problems + // because these examples are likely run with nodes in close proximity to + // each other. + radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. + + // save on transmission time by setting the radio to only transmit the + // number of bytes we need to transmit a float + radio.setPayloadSize(sizeof(payload)); // 2x int datatype occupy 8 bytes + + // For debugging info + // radio.printDetails(); // (smaller) function that prints raw register values + // radio.printPrettyDetails(); // (larger) function that prints human readable data + + // ready to execute program now + if (!foundArgNode) { + setRole(); // calls master() or slave() based on user input + } + else { + nodeNumber < 6 ? master(nodeNumber) : slave(); + } + return 0; +} + +/** + * set this node's role from stdin stream. + * this only considers the first char as input. + */ +void setRole() +{ + + string input = ""; + while (!input.length()) { + cout << "*** Enter a number between 0 and 5 (inclusive) to act as\n"; + cout << " a unique node number that transmits to the RX node.\n"; + cout << "*** PRESS 'R' to begin receiving from the other nodes\n"; + cout << "*** PRESS 'Q' to exit" << endl; + getline(cin, input); + if (input.length() >= 1) { + unsigned int toNumber = (unsigned int)(input[0]) - 48; + if (toNumber < 6 && toNumber >= 0) + master(toNumber); + else if (input[0] == 'R' || input[0] == 'r') + slave(); + else if (input[0] == 'Q' || input[0] == 'q') + break; + else + cout << input[0] << " is an invalid input. Please try again." << endl; + } + input = ""; // stay in the while loop + } // while +} // setRole + +/** + * act as unique TX node identified by the `role` number + */ +void master(unsigned int role) +{ + // set the payload's nodeID & reset the payload's identifying number + payload.nodeID = role; + payload.payloadID = 0; + + // Set the address on pipe 0 to the RX node. + radio.stopListening(); // put radio in TX mode + radio.openWritingPipe(address[role]); + + // According to the datasheet, the auto-retry features's delay value should + // be "skewed" to allow the RX node to receive 1 transmission at a time. + // So, use varying delay between retry attempts and 15 (at most) retry attempts + radio.setRetries(((role * 3) % 12) + 3, 15); // maximum value is 15 for both args + + unsigned int failures = 0; + while (failures < 6) { + clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer); // start the timer + bool report = radio.write(&payload, sizeof(payload)); // transmit & save the report + uint32_t timerEllapsed = getMicros(); // end the timer + + if (report) { + // payload was delivered + cout << "Transmission of PayloadID "; + cout << payload.payloadID; // print payload number + cout << " as node " << payload.nodeID; // print node number + cout << " successful! Time to transmit = "; + cout << timerEllapsed << " us" << endl; // print the timer result + } + else { + // payload was not delivered + failures++; + cout << "Transmission failed or timed out" << endl; + } + payload.payloadID++; // increment payload number + + // to make this example readable in the terminal + delay(1000); // slow transmissions down by 1 second + } // while + cout << failures << " failures detected. Leaving TX role." << endl; +} // master + +/** + * act as the RX node that receives from up to 6 other TX nodes + */ +void slave() +{ + + // Set the addresses for all pipes to TX nodes + for (uint8_t i = 0; i < 6; ++i) + radio.openReadingPipe(i, address[i]); + + radio.startListening(); // put radio in RX mode + + time_t startTimer = time(nullptr); // start a timer + while (time(nullptr) - startTimer < 6) { // use 6 second timeout + uint8_t pipe; + if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it + uint8_t bytes = radio.getPayloadSize(); // get the size of the payload + radio.read(&payload, bytes); // fetch payload from FIFO + cout << "Received " << (unsigned int)bytes; // print the size of the payload + cout << " bytes on pipe " << (unsigned int)pipe; // print the pipe number + cout << " from node " << payload.nodeID; // print the payload's origin + cout << ". PayloadID: " << payload.payloadID << endl; // print the payload's number + startTimer = time(nullptr); // reset timer + } + } + cout << "Nothing received in 6 seconds. Leaving RX role." << endl; +} // slave + +/** + * Calculate the ellapsed time in microseconds + */ +uint32_t getMicros() +{ + // this function assumes that the timer was started using + // `clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer);` + + clock_gettime(CLOCK_MONOTONIC_RAW, &endTimer); + uint32_t seconds = endTimer.tv_sec - startTimer.tv_sec; + uint32_t useconds = (endTimer.tv_nsec - startTimer.tv_nsec) / 1000; + + return ((seconds)*1000 + useconds) + 0.5; +} + +/** + * print a manual page of instructions on how to use this example's CLI args + */ +void printHelp(string progName) +{ + cout << "usage: " << progName << " [-h] [-n {0,1,2,3,4,5,r,R}]\n\n" + << "A simple example of sending data from as many as 6 nRF24L01 transceivers to\n" + << "1 receiving transceiver. This technique is trademarked by\n" + << "Nordic Semiconductors as 'MultiCeiver'.\n" + << "\nThis example was written to be used on up to 6 devices acting as TX nodes with\n" + << "another device acting as a RX node (that's a total of 7 devices).\n" + << "\noptional arguments:\n -h, --help\t\tshow this help message and exit\n" + << " -n {0,1,2,3,4,5,r,R}, --node {0,1,2,3,4,5,r,R}" + << "\n\t\t\t0-5 specifies the identifying node ID number for the TX role." + << "\n\t\t\t'r' or 'R' specifies the RX role." << endl; +} diff --git a/examples_linux/multiceiver_demo.py b/examples_linux/multiceiver_demo.py index 1209dc81d..9dc732bdb 100644 --- a/examples_linux/multiceiver_demo.py +++ b/examples_linux/multiceiver_demo.py @@ -14,15 +14,14 @@ parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument( "-n", "--node", choices=("0", "1", "2", "3", "4", "5", "R", "r"), help="the identifying node ID number for the TX role. " - "Use 'R' or 'r' to specify the RX role" + "Use 'R' or 'r' to specify the RX role", ) ########### USER CONFIGURATION ########### @@ -48,7 +47,7 @@ b"\xCD\xB6\xB5\xB4\xB3", b"\xA3\xB6\xB5\xB4\xB3", b"\x0F\xB6\xB5\xB4\xB3", - b"\x05\xB6\xB5\xB4\xB3" + b"\x05\xB6\xB5\xB4\xB3", ] # It is very helpful to think of an address as a path instead of as # an identifying device destination @@ -63,7 +62,9 @@ def master(node_number): # According to the datasheet, the auto-retry features's delay value should # be "skewed" to allow the RX node to receive 1 transmission at a time. # So, use varying delay between retry attempts and 15 (at most) retry attempts - radio.setRetries(((node_number * 3) % 12) + 3, 15) # maximum value is 15 for both args + radio.setRetries( + ((node_number * 3) % 12) + 3, 15 + ) # maximum value is 15 for both args radio.stopListening() # put radio in TX mode # set the TX address to the address of the base station. @@ -79,11 +80,8 @@ def master(node_number): end_timer = time.monotonic_ns() # show something to see it isn't frozen print( - "Transmission of payloadID {} as node {}".format( - counter, - node_number - ), - end=" " + "Transmission of payloadID {} as node {}".format(counter, node_number), + end=" ", ) if report: print( @@ -113,19 +111,11 @@ def slave(timeout=10): has_payload, pipe_number = radio.available_pipe() if has_payload: # unpack payload - nodeID, payloadID = struct.unpack( - " 1: diff --git a/examples_linux/streamingData.cpp b/examples_linux/streamingData.cpp index bb27baf48..b5657d13e 100644 --- a/examples_linux/streamingData.cpp +++ b/examples_linux/streamingData.cpp @@ -1,291 +1,292 @@ -/* - * See documentation at https://nRF24.github.io/RF24 - * See License information at root directory of this library - * Author: Brendan Doherty (2bndy5) - */ - -/** - * A simple example of streaming data from 1 nRF24L01 transceiver to another. - * - * This example was written to be used on 2 devices acting as "nodes". - * Use `ctrl+c` to quit at any time. - */ -#include // abs() -#include // time() -#include // strcmp() -#include // cin, cout, endl -#include // string, getline() -#include // CLOCK_MONOTONIC_RAW, timespec, clock_gettime() -#include // RF24, RF24_PA_LOW, delay() - -using namespace std; - -/****************** Linux ***********************/ -// Radio CE Pin, CSN Pin, SPI Speed -// CE Pin uses GPIO number with BCM and SPIDEV drivers, other platforms use their own pin numbering -// CS Pin addresses the SPI bus number at /dev/spidev. -// ie: RF24 radio(, *10+); spidev1.0 is 10, spidev1.1 is 11 etc.. - -// Generic: -RF24 radio(22, 0); -/****************** Linux (BBB,x86,etc) ***********************/ -// See http://nRF24.github.io/RF24/pages.html for more information on usage -// See http://iotdk.intel.com/docs/master/mraa/ for more information on MRAA -// See https://www.kernel.org/doc/Documentation/spi/spidev for more information on SPIDEV - -// For this example, we'll be sending 32 payloads each containing -// 32 bytes of data that looks like ASCII art when printed to the serial -// monitor. The TX node and RX node needs only a single 32 byte buffer. -#define SIZE 32 // this is the maximum for this example. (minimum is 1) -char buffer[SIZE + 1]; // for the RX node -unsigned int counter = 0; // for counting the number of received payloads -void makePayload(uint8_t); // prototype to construct a payload dynamically -void setRole(); // prototype to set the node's role -void master(); // prototype of the TX node's behavior -void slave(); // prototype of the RX node's behavior -void printHelp(string); // prototype to function that explain CLI arg usage - -// custom defined timer for evaluating transmission time in microseconds -struct timespec startTimer, endTimer; -uint32_t getMicros(); // prototype to get ellapsed time in microseconds - - -int main(int argc, char** argv) { - - // perform hardware check - if (!radio.begin()) { - cout << "radio hardware is not responding!!" << endl; - return 0; // quit now - } - - // add a NULL terminating 0 for printing as a c-string - buffer[SIZE] = 0; - - // Let these addresses be used for the pair of nodes used in this example - uint8_t address[2][6] = {"1Node", "2Node"}; - // the TX address^ , ^the RX address - // It is very helpful to think of an address as a path instead of as - // an identifying device destination - - // to use different addresses on a pair of radios, we need a variable to - // uniquely identify which address this radio will use to transmit - bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit - - bool foundArgNode = false; - bool foundArgRole = false; - bool role = false; - if (argc > 1) { - // CLI args are specified - if ((argc - 1) % 2 != 0) { - // some CLI arg doesn't have an option specified for it - printHelp(string(argv[0])); // all args need an option in this example - return 0; - } - else { - // iterate through args starting after program name - int a = 1; - while (a < argc) { - bool invalidOption = false; - if (strcmp(argv[a], "-n") == 0 || strcmp(argv[a], "--node") == 0) { - // "-n" or "--node" has been specified - foundArgNode = true; - if (argv[a + 1][0] - 48 <= 1) { - radioNumber = (argv[a + 1][0] - 48) == 1; - } - else { - // option is invalid - invalidOption = true; - } - } - else if (strcmp(argv[a], "-r") == 0 || strcmp(argv[a], "--role") == 0) { - // "-r" or "--role" has been specified - foundArgRole = true; - if (argv[a + 1][0] - 48 <= 1) { - role = (argv[a + 1][0] - 48) == 1; - } - else { - // option is invalid - invalidOption = true; - } - } - if (invalidOption) { - printHelp(string(argv[0])); - return 0; - } - a += 2; - } // while - if (!foundArgNode && !foundArgRole) { - // no valid args were specified - printHelp(string(argv[0])); - return 0; - } - } // else - } // if - - // print example's name - cout << argv[0] << endl; - - if (!foundArgNode) { - // Set the radioNumber via the terminal on startup - cout << "Which radio is this? Enter '0' or '1'. Defaults to '0' "; - string input; - getline(cin, input); - radioNumber = input.length() > 0 && (uint8_t)input[0] == 49; - } - - // save on transmission time by setting the radio to only transmit the - // number of bytes we need to transmit a float - radio.setPayloadSize(SIZE); // default value is the maximum 32 bytes - - // Set the PA Level low to try preventing power supply related problems - // because these examples are likely run with nodes in close proximity to - // each other. - radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. - - // set the TX address of the RX node into the TX pipe - radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 - - // set the RX address of the TX node into a RX pipe - radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 - - // For debugging info - // radio.printDetails(); // (smaller) function that prints raw register values - // radio.printPrettyDetails(); // (larger) function that prints human readable data - - // ready to execute program now - if (!foundArgRole) { // if CLI arg "-r"/"--role" was not specified - setRole(); // calls master() or slave() based on user input - } - else { // if CLI arg "-r"/"--role" was specified - role ? master() : slave(); // based on CLI arg option - } - return 0; -} - - -/** - * set this node's role from stdin stream. - * this only considers the first char as input. - */ -void setRole() { - string input = ""; - while (!input.length()) { - cout << "*** PRESS 'T' to begin transmitting to the other node\n"; - cout << "*** PRESS 'R' to begin receiving from the other node\n"; - cout << "*** PRESS 'Q' to exit" << endl; - getline(cin, input); - if (input.length() >= 1) { - if (input[0] == 'T' || input[0] == 't') - master(); - else if (input[0] == 'R' || input[0] == 'r') - slave(); - else if (input[0] == 'Q' || input[0] == 'q') - break; - else - cout << input[0] << " is an invalid input. Please try again." << endl; - } - input = ""; // stay in the while loop - } // while -} // setRole() - - -/** - * make this node act as the transmitter - */ -void master() { - radio.stopListening(); // put radio in TX mode - - unsigned int failures = 0; // keep track of failures - uint8_t i = 0; - clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer); // start the timer - while (i < SIZE) { - makePayload(i); - if (!radio.writeFast(&buffer, SIZE)) { - failures++; - radio.reUseTX(); - } else { - i++; - } - - if (failures >= 100) { - // most likely no device is listening for the data stream - cout << "Too many failures detected. "; - cout << "Aborting at payload " << buffer[0]; - break; - } - } // while - uint32_t ellapsedTime = getMicros(); // end the timer - cout << "Time to transmit data = "; - cout << ellapsedTime; // print the timer result - cout << " us. " << failures; // print number of retries - cout << " failures detected. Leaving TX role." << endl; -} // master - - -/** - * make this node act as the receiver - */ -void slave() { - - counter = 0; - radio.startListening(); // put radio in RX mode - time_t startTimer = time(nullptr); // start a timer - while (time(nullptr) - startTimer < 6) { // use 6 second timeout - if (radio.available()) { // is there a payload - radio.read(&buffer, SIZE); // fetch payload from FIFO - cout << "Received: " << buffer; // print the payload's value - cout << " - " << counter << endl; // print the counter - counter++; // increment counter - startTimer = time(nullptr); // reset timer - } - } - radio.stopListening(); // use TX mode for idle behavior - - cout << "Nothing received in 6 seconds. Leaving RX role." << endl; -} - - -/** - * Make a single payload based on position in stream. - * This example employs this function to save on memory allocated. - */ -void makePayload(uint8_t i) { - - // let the first character be an identifying alphanumeric prefix - // this lets us see which payload didn't get received - buffer[0] = i + (i < 26 ? 65 : 71); - for (uint8_t j = 0; j < SIZE - 1; ++j) { - char chr = j >= (SIZE - 1) / 2 + abs((SIZE - 1) / 2 - i); - chr |= j < (SIZE - 1) / 2 - abs((SIZE - 1) / 2 - i); - buffer[j + 1] = chr + 48; - } -} - - -/** - * Calculate the ellapsed time in microseconds - */ -uint32_t getMicros() { - // this function assumes that the timer was started using - // `clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer);` - - clock_gettime(CLOCK_MONOTONIC_RAW, &endTimer); - uint32_t seconds = endTimer.tv_sec - startTimer.tv_sec; - uint32_t useconds = (endTimer.tv_nsec - startTimer.tv_nsec) / 1000; - - return ((seconds) * 1000 + useconds) + 0.5; -} - - -/** - * print a manual page of instructions on how to use this example's CLI args - */ -void printHelp(string progName) { - cout << "usage: " << progName << " [-h] [-n {0,1}] [-r {0,1}]\n\n" - << "A simple example of streaming data from 1 nRF24L01 transceiver to another.\n" - << "\nThis example was written to be used on 2 devices acting as 'nodes'.\n" - << "\noptional arguments:\n -h, --help\t\tshow this help message and exit\n" - << " -n {0,1}, --node {0,1}\n\t\t\tthe identifying radio number\n" - << " -r {0,1}, --role {0,1}\n\t\t\t'1' specifies the TX role." - << " '0' specifies the RX role." << endl; -} \ No newline at end of file +/* + * See documentation at https://nRF24.github.io/RF24 + * See License information at root directory of this library + * Author: Brendan Doherty (2bndy5) + */ + +/** + * A simple example of streaming data from 1 nRF24L01 transceiver to another. + * + * This example was written to be used on 2 devices acting as "nodes". + * Use `ctrl+c` to quit at any time. + */ +#include // abs() +#include // time() +#include // strcmp() +#include // cin, cout, endl +#include // string, getline() +#include // CLOCK_MONOTONIC_RAW, timespec, clock_gettime() +#include // RF24, RF24_PA_LOW, delay() + +using namespace std; + +/****************** Linux ***********************/ +// Radio CE Pin, CSN Pin, SPI Speed +// CE Pin uses GPIO number with BCM and SPIDEV drivers, other platforms use their own pin numbering +// CS Pin addresses the SPI bus number at /dev/spidev. +// ie: RF24 radio(, *10+); spidev1.0 is 10, spidev1.1 is 11 etc.. + +// Generic: +RF24 radio(22, 0); +/****************** Linux (BBB,x86,etc) ***********************/ +// See http://nRF24.github.io/RF24/pages.html for more information on usage +// See http://iotdk.intel.com/docs/master/mraa/ for more information on MRAA +// See https://www.kernel.org/doc/Documentation/spi/spidev for more information on SPIDEV + +// For this example, we'll be sending 32 payloads each containing +// 32 bytes of data that looks like ASCII art when printed to the serial +// monitor. The TX node and RX node needs only a single 32 byte buffer. +#define SIZE 32 // this is the maximum for this example. (minimum is 1) +char buffer[SIZE + 1]; // for the RX node +unsigned int counter = 0; // for counting the number of received payloads +void makePayload(uint8_t); // prototype to construct a payload dynamically +void setRole(); // prototype to set the node's role +void master(); // prototype of the TX node's behavior +void slave(); // prototype of the RX node's behavior +void printHelp(string); // prototype to function that explain CLI arg usage + +// custom defined timer for evaluating transmission time in microseconds +struct timespec startTimer, endTimer; +uint32_t getMicros(); // prototype to get ellapsed time in microseconds + +int main(int argc, char** argv) +{ + + // perform hardware check + if (!radio.begin()) { + cout << "radio hardware is not responding!!" << endl; + return 0; // quit now + } + + // add a NULL terminating 0 for printing as a c-string + buffer[SIZE] = 0; + + // Let these addresses be used for the pair of nodes used in this example + uint8_t address[2][6] = {"1Node", "2Node"}; + // the TX address^ , ^the RX address + // It is very helpful to think of an address as a path instead of as + // an identifying device destination + + // to use different addresses on a pair of radios, we need a variable to + // uniquely identify which address this radio will use to transmit + bool radioNumber = 1; // 0 uses address[0] to transmit, 1 uses address[1] to transmit + + bool foundArgNode = false; + bool foundArgRole = false; + bool role = false; + if (argc > 1) { + // CLI args are specified + if ((argc - 1) % 2 != 0) { + // some CLI arg doesn't have an option specified for it + printHelp(string(argv[0])); // all args need an option in this example + return 0; + } + else { + // iterate through args starting after program name + int a = 1; + while (a < argc) { + bool invalidOption = false; + if (strcmp(argv[a], "-n") == 0 || strcmp(argv[a], "--node") == 0) { + // "-n" or "--node" has been specified + foundArgNode = true; + if (argv[a + 1][0] - 48 <= 1) { + radioNumber = (argv[a + 1][0] - 48) == 1; + } + else { + // option is invalid + invalidOption = true; + } + } + else if (strcmp(argv[a], "-r") == 0 || strcmp(argv[a], "--role") == 0) { + // "-r" or "--role" has been specified + foundArgRole = true; + if (argv[a + 1][0] - 48 <= 1) { + role = (argv[a + 1][0] - 48) == 1; + } + else { + // option is invalid + invalidOption = true; + } + } + if (invalidOption) { + printHelp(string(argv[0])); + return 0; + } + a += 2; + } // while + if (!foundArgNode && !foundArgRole) { + // no valid args were specified + printHelp(string(argv[0])); + return 0; + } + } // else + } // if + + // print example's name + cout << argv[0] << endl; + + if (!foundArgNode) { + // Set the radioNumber via the terminal on startup + cout << "Which radio is this? Enter '0' or '1'. Defaults to '0' "; + string input; + getline(cin, input); + radioNumber = input.length() > 0 && (uint8_t)input[0] == 49; + } + + // save on transmission time by setting the radio to only transmit the + // number of bytes we need to transmit a float + radio.setPayloadSize(SIZE); // default value is the maximum 32 bytes + + // Set the PA Level low to try preventing power supply related problems + // because these examples are likely run with nodes in close proximity to + // each other. + radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. + + // set the TX address of the RX node into the TX pipe + radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 + + // set the RX address of the TX node into a RX pipe + radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 + + // For debugging info + // radio.printDetails(); // (smaller) function that prints raw register values + // radio.printPrettyDetails(); // (larger) function that prints human readable data + + // ready to execute program now + if (!foundArgRole) { // if CLI arg "-r"/"--role" was not specified + setRole(); // calls master() or slave() based on user input + } + else { // if CLI arg "-r"/"--role" was specified + role ? master() : slave(); // based on CLI arg option + } + return 0; +} + +/** + * set this node's role from stdin stream. + * this only considers the first char as input. + */ +void setRole() +{ + string input = ""; + while (!input.length()) { + cout << "*** PRESS 'T' to begin transmitting to the other node\n"; + cout << "*** PRESS 'R' to begin receiving from the other node\n"; + cout << "*** PRESS 'Q' to exit" << endl; + getline(cin, input); + if (input.length() >= 1) { + if (input[0] == 'T' || input[0] == 't') + master(); + else if (input[0] == 'R' || input[0] == 'r') + slave(); + else if (input[0] == 'Q' || input[0] == 'q') + break; + else + cout << input[0] << " is an invalid input. Please try again." << endl; + } + input = ""; // stay in the while loop + } // while +} // setRole() + +/** + * make this node act as the transmitter + */ +void master() +{ + radio.stopListening(); // put radio in TX mode + + unsigned int failures = 0; // keep track of failures + uint8_t i = 0; + clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer); // start the timer + while (i < SIZE) { + makePayload(i); + if (!radio.writeFast(&buffer, SIZE)) { + failures++; + radio.reUseTX(); + } + else { + i++; + } + + if (failures >= 100) { + // most likely no device is listening for the data stream + cout << "Too many failures detected. "; + cout << "Aborting at payload " << buffer[0]; + break; + } + } // while + uint32_t ellapsedTime = getMicros(); // end the timer + cout << "Time to transmit data = "; + cout << ellapsedTime; // print the timer result + cout << " us. " << failures; // print number of retries + cout << " failures detected. Leaving TX role." << endl; +} // master + +/** + * make this node act as the receiver + */ +void slave() +{ + + counter = 0; + radio.startListening(); // put radio in RX mode + time_t startTimer = time(nullptr); // start a timer + while (time(nullptr) - startTimer < 6) { // use 6 second timeout + if (radio.available()) { // is there a payload + radio.read(&buffer, SIZE); // fetch payload from FIFO + cout << "Received: " << buffer; // print the payload's value + cout << " - " << counter << endl; // print the counter + counter++; // increment counter + startTimer = time(nullptr); // reset timer + } + } + radio.stopListening(); // use TX mode for idle behavior + + cout << "Nothing received in 6 seconds. Leaving RX role." << endl; +} + +/** + * Make a single payload based on position in stream. + * This example employs this function to save on memory allocated. + */ +void makePayload(uint8_t i) +{ + + // let the first character be an identifying alphanumeric prefix + // this lets us see which payload didn't get received + buffer[0] = i + (i < 26 ? 65 : 71); + for (uint8_t j = 0; j < SIZE - 1; ++j) { + char chr = j >= (SIZE - 1) / 2 + abs((SIZE - 1) / 2 - i); + chr |= j < (SIZE - 1) / 2 - abs((SIZE - 1) / 2 - i); + buffer[j + 1] = chr + 48; + } +} + +/** + * Calculate the ellapsed time in microseconds + */ +uint32_t getMicros() +{ + // this function assumes that the timer was started using + // `clock_gettime(CLOCK_MONOTONIC_RAW, &startTimer);` + + clock_gettime(CLOCK_MONOTONIC_RAW, &endTimer); + uint32_t seconds = endTimer.tv_sec - startTimer.tv_sec; + uint32_t useconds = (endTimer.tv_nsec - startTimer.tv_nsec) / 1000; + + return ((seconds)*1000 + useconds) + 0.5; +} + +/** + * print a manual page of instructions on how to use this example's CLI args + */ +void printHelp(string progName) +{ + cout << "usage: " << progName << " [-h] [-n {0,1}] [-r {0,1}]\n\n" + << "A simple example of streaming data from 1 nRF24L01 transceiver to another.\n" + << "\nThis example was written to be used on 2 devices acting as 'nodes'.\n" + << "\noptional arguments:\n -h, --help\t\tshow this help message and exit\n" + << " -n {0,1}, --node {0,1}\n\t\t\tthe identifying radio number\n" + << " -r {0,1}, --role {0,1}\n\t\t\t'1' specifies the TX role." + << " '0' specifies the RX role." << endl; +} diff --git a/examples_linux/streaming_data.py b/examples_linux/streaming_data.py index 02efedf0a..6bbe4dbc4 100644 --- a/examples_linux/streaming_data.py +++ b/examples_linux/streaming_data.py @@ -10,22 +10,21 @@ parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument( "-n", "--node", type=int, choices=range(2), - help="the identifying radio number (or node ID number)" + help="the identifying radio number (or node ID number)", ) parser.add_argument( "-r", "--role", type=int, choices=range(2), - help="'1' specifies the TX role. '0' specifies the RX role." + help="'1' specifies the TX role. '0' specifies the RX role.", ) ########### USER CONFIGURATION ########### @@ -84,10 +83,7 @@ def master(count=1): failures += 1 # increment manual retry count if failures > 99 and buf_iter < 7 and multiplier < 2: # we need to prevent an infinite loop - print( - "Too many failures detected. Aborting at payload ", - buffer[0] - ) + print("Too many failures detected. Aborting at payload ", buffer[0]) multiplier = count # be sure to exit the for loop break # exit the while loop radio.reUseTX() # resend payload in top level of TX FIFO @@ -96,8 +92,7 @@ def master(count=1): end_timer = time.monotonic_ns() # end timer print( "Time to transmit data = {} us. Detected {} failures.".format( - (end_timer - start_timer) / 1000, - failures + (end_timer - start_timer) / 1000, failures ) ) @@ -126,6 +121,7 @@ def slave(timeout=6): print("Nothing received in ", timeout, " seconds. Leaving RX role") + def set_role(): """Set the role using stdin stream. Role args can be specified using space delimiters (e.g. 'R 10' calls `slave(10)` & 'T 3' calls `master(3)`) @@ -134,11 +130,14 @@ def set_role(): - True when role is complete & app should continue running. - False when app should exit """ - user_input = input( - "*** Enter 'R' for receiver role.\n" - "*** Enter 'T' for transmitter role.\n" - "*** Enter 'Q' to quit example.\n" - ) or "?" + user_input = ( + input( + "*** Enter 'R' for receiver role.\n" + "*** Enter 'T' for transmitter role.\n" + "*** Enter 'Q' to quit example.\n" + ) + or "?" + ) user_input = user_input.split() if user_input[0].upper().startswith("R"): if len(user_input) > 1: @@ -181,11 +180,7 @@ def set_role(): radio_number = args.node # uses default value from `parser` if args.node is None: # if '--node' arg wasn't specified radio_number = bool( - int( - input( - "Which radio is this? Enter '0' or '1'. Defaults to '0' " - ) or 0 - ) + int(input("Which radio is this? Enter '0' or '1'. Defaults to '0' ") or 0) ) # set the Power Amplifier level to -12 dBm since this test example is diff --git a/examples_pico/acknowledgementPayloads.cpp b/examples_pico/acknowledgementPayloads.cpp index 318540a7a..66367ac05 100644 --- a/examples_pico/acknowledgementPayloads.cpp +++ b/examples_pico/acknowledgementPayloads.cpp @@ -21,21 +21,21 @@ RF24 radio(CE_PIN, CSN_PIN); // Used to control whether this node is sending or receiving -bool role = false; // true = TX role, false = RX role +bool role = false; // true = TX role, false = RX role // For this example, we'll be using a payload containing // a string & an integer number that will be incremented // on every successful transmission. // Make a data structure to store the entire payload of different datatypes -struct PayloadStruct { - char message[7]; // only using 6 characters for TX & ACK payloads +struct PayloadStruct +{ + char message[7]; // only using 6 characters for TX & ACK payloads uint8_t counter; }; PayloadStruct payload; - -bool setup() { - +bool setup() +{ // an identifying device destination // Let these addresses be used for the pair uint8_t address[][6] = {"1Node", "2Node"}; @@ -69,17 +69,17 @@ bool setup() { // Set the PA Level low to try preventing power supply related problems // because these examples are likely run with nodes in close proximity to // each other. - radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. + radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. // to use ACK payloads, we need to enable dynamic payload lengths (for all nodes) - radio.enableDynamicPayloads(); // ACK payloads are dynamically sized + radio.enableDynamicPayloads(); // ACK payloads are dynamically sized // Acknowledgement packets have no payloads by default. We need to enable // this feature for all nodes (TX & RX) to use ACK payloads. radio.enableAckPayload(); // set the TX address of the RX node into the TX pipe - radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 + radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 // set the RX address of the TX node into a RX pipe radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 @@ -88,17 +88,17 @@ bool setup() { if (role) { // setup the TX payload - memcpy(payload.message, "Hello ", 6); // set the payload message - radio.stopListening(); // put radio in TX mode + memcpy(payload.message, "Hello ", 6); // set the payload message + radio.stopListening(); // put radio in TX mode } else { // setup the ACK payload & load the first response into the FIFO - memcpy(payload.message, "World ", 6); // set the payload message + memcpy(payload.message, "World ", 6); // set the payload message // load the payload for the first received transmission on pipe 0 radio.writeAckPayload(1, &payload, sizeof(payload)); - radio.startListening(); // put radio in RX mode + radio.startListening(); // put radio in RX mode } // For debugging info @@ -111,7 +111,8 @@ bool setup() { return true; } -void loop() { +void loop() +{ if (role) { // This device is a TX node @@ -129,9 +130,9 @@ void loop() { payload.counter); uint8_t pipe; - if (radio.available(&pipe)) { // is there an ACK payload? grab the pipe number that received it + if (radio.available(&pipe)) { // is there an ACK payload? grab the pipe number that received it PayloadStruct received; - radio.read(&received, sizeof(received)); // get incoming ACK payload + radio.read(&received, sizeof(received)); // get incoming ACK payload // print details about incoming payload printf(" Recieved %d bytes on pipe %d: %s%d\n", @@ -142,16 +143,13 @@ void loop() { // save incoming counter & increment for next outgoing payload.counter = received.counter + 1; - } else { printf(" Recieved: an empty ACK packet\n"); // empty ACK packet received } - - } else { - printf("Transmission failed or timed out\n"); // payload was not delivered + printf("Transmission failed or timed out\n"); // payload was not delivered } // to make this example readable in the serial terminal @@ -161,10 +159,10 @@ void loop() { // This device is a RX node uint8_t pipe; - if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it + if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it uint8_t bytes = radio.getDynamicPayloadSize(); // get the size of the payload PayloadStruct received; - radio.read(&received, sizeof(received)); // get incoming payload + radio.read(&received, sizeof(received)); // get incoming payload // print the details of transaction printf("Received %d bytes on pipe %d: %s%d Sent: %s%d\n", @@ -194,7 +192,6 @@ void loop() { memcpy(payload.message, "Hello ", 6); // change payload message radio.stopListening(); // this also discards any unused ACK payloads - } else if ((input == 'R' || input == 'r') && role) { // Become the RX node diff --git a/examples_pico/defaultPins.h b/examples_pico/defaultPins.h index 1178e2601..319beed0d 100644 --- a/examples_pico/defaultPins.h +++ b/examples_pico/defaultPins.h @@ -2,32 +2,31 @@ #ifndef DEFAULTPINS_H #define DEFAULTPINS_H -#if defined (ADAFRUIT_QTPY_RP2040) -// for this board, you can still use the Stemma QT connector as a separate I2C bus (`i2c1`) -#define CE_PIN PICO_DEFAULT_I2C_SDA_PIN // the pin labeled SDA -#define CSN_PIN PICO_DEFAULT_I2C_SCL_PIN // the pin labeled SCL -#define IRQ_PIN PICO_DEFAULT_UART_RX_PIN // the pin labeled RX - -#elif defined (PIMORONI_TINY2040) -// default SPI_SCK_PIN = 6 -// default SPI_TX_PIN = 7 -// default SPI_RX_PIN = 4 -#define CE_PIN PICO_DEFAULT_I2C_SCL_PIN // pin 3 -#define CSN_PIN PICO_DEFAULT_SPI_CSN_PIN // pin 5 -#define IRQ_PIN PICO_DEFAULT_I2C_SDA_PIN // pin 2 +#if defined(ADAFRUIT_QTPY_RP2040) + // for this board, you can still use the Stemma QT connector as a separate I2C bus (`i2c1`) + #define CE_PIN PICO_DEFAULT_I2C_SDA_PIN // the pin labeled SDA + #define CSN_PIN PICO_DEFAULT_I2C_SCL_PIN // the pin labeled SCL + #define IRQ_PIN PICO_DEFAULT_UART_RX_PIN // the pin labeled RX +#elif defined(PIMORONI_TINY2040) + // default SPI_SCK_PIN = 6 + // default SPI_TX_PIN = 7 + // default SPI_RX_PIN = 4 + #define CE_PIN PICO_DEFAULT_I2C_SCL_PIN // pin 3 + #define CSN_PIN PICO_DEFAULT_SPI_CSN_PIN // pin 5 + #define IRQ_PIN PICO_DEFAULT_I2C_SDA_PIN // pin 2 #elif defined(SPARFUN_THINGPLUS) -#define CSN_PIN 16 // the pin labeled 16 -#define CE_PIN 7 // the pin labeled SCL -#define IRQ_PIN 6 // the pin labeled SDA + #define CSN_PIN 16 // the pin labeled 16 + #define CE_PIN 7 // the pin labeled SCL + #define IRQ_PIN 6 // the pin labeled SDA #else -// pins available on (ADAFRUIT_ITSYBITSY_RP2040 || ADAFRUIT_FEATHER_RP2040 || Pico_board || Sparkfun_ProMicro || SparkFun MicroMod) + // pins available on (ADAFRUIT_ITSYBITSY_RP2040 || ADAFRUIT_FEATHER_RP2040 || Pico_board || Sparkfun_ProMicro || SparkFun MicroMod) -#define CE_PIN 7 -#define CSN_PIN 8 -#define IRQ_PIN 6 + #define CE_PIN 7 + #define CSN_PIN 8 + #define IRQ_PIN 6 #endif // board detection macro defs #endif // DEFAULTPINS_H diff --git a/examples_pico/gettingStarted.cpp b/examples_pico/gettingStarted.cpp index cf2637221..32d83d285 100644 --- a/examples_pico/gettingStarted.cpp +++ b/examples_pico/gettingStarted.cpp @@ -27,7 +27,6 @@ bool role = false; // true = TX role, false = RX role // on every successful transmission float payload = 0.0; - bool setup() { // Let these addresses be used for the pair diff --git a/examples_pico/interruptConfigure.cpp b/examples_pico/interruptConfigure.cpp index 134a90c97..0b59aff6b 100644 --- a/examples_pico/interruptConfigure.cpp +++ b/examples_pico/interruptConfigure.cpp @@ -26,7 +26,7 @@ volatile bool wait_for_event = false; // used to wait for an IRQ event to trigge RF24 radio(CE_PIN, CSN_PIN); // Used to control whether this node is sending or receiving -bool role = false; // true = TX node, false = RX node +bool role = false; // true = TX node, false = RX node // For this example, we'll be using a payload containing // a string that changes on every transmission. (successful or not) @@ -41,7 +41,6 @@ char ack_payloads[][ack_pl_size + 1] = {"Yak ", "Back", " ACK"}; void interruptHandler(uint gpio, uint32_t events); // prototype to handle IRQ events void printRxFifo(); // prototype to print RX FIFO with 1 buffer - bool setup() { // Let these addresses be used for the pair @@ -83,12 +82,12 @@ bool setup() // Set the PA Level low to try preventing power supply related problems // because these examples are likely run with nodes in close proximity to // each other. - radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. + radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. // For this example we use acknowledgment (ACK) payloads to trigger the // IRQ pin when data is received on the TX node. // to use ACK payloads, we need to enable dynamic payload lengths - radio.enableDynamicPayloads(); // ACK payloads are dynamically sized + radio.enableDynamicPayloads(); // ACK payloads are dynamically sized // Acknowledgement packets have no payloads by default. We need to enable // this feature for all nodes (TX & RX) to use ACK payloads. @@ -96,7 +95,7 @@ bool setup() // Fot this example, we use the same address to send data back and forth // set the TX address of the RX node into the TX pipe - radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 + radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 // set the RX address of the TX node into a RX pipe radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 @@ -105,7 +104,6 @@ bool setup() if (role) { // setup for TX mode radio.stopListening(); // put radio in TX mode - } else { // setup for RX mode @@ -145,7 +143,6 @@ void loop() printf("\nConfiguring IRQ pin to ignore the 'data sent' event\n"); radio.maskIRQ(true, false, false); // args = "data_sent", "data_fail", "data_ready" printf(" Pinging RX node for 'data ready' event...\n"); - } else if (pl_iterator == 1) { // Test the "data sent" event with the IRQ pin @@ -153,7 +150,6 @@ void loop() printf("\nConfiguring IRQ pin to ignore the 'data ready' event\n"); radio.maskIRQ(false, false, true); // args = "data_sent", "data_fail", "data_ready" printf(" Pinging RX node for 'data sent' event...\n"); - } else if (pl_iterator == 2) { // Use this iteration to fill the RX node's FIFO which sets us up for the next test. @@ -175,7 +171,6 @@ void loop() printf("Transmission failed or timed out. Continuing anyway.\n"); radio.flush_tx(); // discard payload(s) that failed to transmit } - } else if (pl_iterator == 3) { // test the "data fail" event with the IRQ pin @@ -212,12 +207,10 @@ void loop() // inform user what to do next printf("\n*** PRESS 'T' to restart the transmissions"); printf("\n*** PRESS 'R' to change to Receive role\n"); - } else if (pl_iterator == 2) { pl_iterator++; // proceed from step 3 to last step (stop at step 4 for readability) } - } else if (!role && radio.rxFifoFull()) { // This device is a RX node @@ -253,14 +246,14 @@ void loop() role = true; wait_for_event = false; - pl_iterator = 0; // reset the iterator - radio.flush_tx(); // discard any payloads in the TX FIFO + pl_iterator = 0; // reset the iterator + radio.flush_tx(); // discard any payloads in the TX FIFO // startListening() clears the IRQ masks also. This is required for // continued TX operations when a transmission fails. radio.stopListening(); // this also discards any unused ACK payloads } - else if ((input == 'R' || input == 'r')/* && role */) { + else if ((input == 'R' || input == 'r') /* && role */) { // Become the RX node printf("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK\n"); @@ -325,18 +318,17 @@ void interruptHandler(uint gpio, uint32_t events) wait_for_event = false; // ready to continue with loop() operations } // interruptHandler - /** * Print the entire RX FIFO with one buffer. This will also flush the RX FIFO. * Remember that the payload sizes are declared as tx_pl_size and ack_pl_size. */ void printRxFifo() { - if (radio.available()) { // if there is data in the RX FIFO + if (radio.available()) { // if there is data in the RX FIFO // to flush the data from the RX FIFO, we'll fetch it all using 1 buffer uint8_t pl_size = !role ? tx_pl_size : ack_pl_size; - char rx_fifo[pl_size * 3 + 1]; // RX FIFO is full & we know ACK payloads' size + char rx_fifo[pl_size * 3 + 1]; // RX FIFO is full & we know ACK payloads' size if (radio.rxFifoFull()) { rx_fifo[pl_size * 3] = 0; // add a NULL terminating char to use as a c-string radio.read(&rx_fifo, pl_size * 3); // this clears the RX FIFO (for this example) @@ -347,7 +339,7 @@ void printRxFifo() radio.read(&rx_fifo + (i * pl_size), pl_size); i++; } - rx_fifo[i * pl_size] = 0; // add a NULL terminating char to use as a c-string + rx_fifo[i * pl_size] = 0; // add a NULL terminating char to use as a c-string } printf("Complete RX FIFO: %s\n", rx_fifo); // print the entire RX FIFO with 1 buffer } diff --git a/examples_pico/manualAcknowledgements.cpp b/examples_pico/manualAcknowledgements.cpp index 9f40ecaf1..bfe2d57f9 100644 --- a/examples_pico/manualAcknowledgements.cpp +++ b/examples_pico/manualAcknowledgements.cpp @@ -26,15 +26,16 @@ RF24 radio(CE_PIN, CSN_PIN); // Used to control whether this node is sending or receiving -bool role = false; // true = TX node, false = RX node +bool role = false; // true = TX node, false = RX node // For this example, we'll be using a payload containing // a string & an integer number that will be incremented // on every successful transmission. // Make a data structure to store the entire payload of different datatypes -struct PayloadStruct { - char message[7]; // only using 6 characters for TX & RX payloads - uint8_t counter; +struct PayloadStruct +{ + char message[7]; // only using 6 characters for TX & RX payloads + uint8_t counter; }; PayloadStruct payload; @@ -82,7 +83,7 @@ bool setup() radio.setPayloadSize(sizeof(payload)); // char[7] & uint8_t datatypes occupy 8 bytes // set the TX address of the RX node into the TX pipe - radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 + radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 // set the RX address of the TX node into a RX pipe radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 @@ -125,16 +126,16 @@ void loop() radio.startListening(); // put in RX mode uint64_t start_timeout = to_ms_since_boot(get_absolute_time()); // timer to detect timeout while (!radio.available()) { // wait for response - if (to_ms_since_boot(get_absolute_time()) - start_timeout > 200) // only wait 200 ms + if (to_ms_since_boot(get_absolute_time()) - start_timeout > 200) // only wait 200 ms break; } - uint64_t end_timer = to_us_since_boot(get_absolute_time()); // end the timer - radio.stopListening(); // put back in TX mode + uint64_t end_timer = to_us_since_boot(get_absolute_time()); // end the timer + radio.stopListening(); // put back in TX mode // print summary of transactions - printf("Transmission successful!"); // payload was delivered + printf("Transmission successful!"); // payload was delivered uint8_t pipe; - if (radio.available(&pipe)) { // is there a payload received + if (radio.available(&pipe)) { // is there a payload received // print details about outgoing payload printf(" Round-trip delay: %llu us. Sent: %s%d", end_timer - start_timer, @@ -159,7 +160,7 @@ void loop() } else { printf("Transmission failed or timed out\n"); // payload was not delivered - } // report + } // report // to make this example readable in the serial terminal sleep_ms(1000); // slow transmissions down by 1 second @@ -168,16 +169,16 @@ void loop() // This device is a RX node uint8_t pipe; - if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it + if (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it PayloadStruct received; radio.read(&received, sizeof(received)); // get incoming payload payload.counter = received.counter + 1; // increment incoming counter for next outgoing response // transmit response & save result to `report` - radio.stopListening(); // put in TX mode - radio.writeFast(&payload, sizeof(payload)); // load response to TX FIFO - bool report = radio.txStandBy(150); // keep retrying for 150 ms - radio.startListening(); // put back in RX mode + radio.stopListening(); // put in TX mode + radio.writeFast(&payload, sizeof(payload)); // load response to TX FIFO + bool report = radio.txStandBy(150); // keep retrying for 150 ms + radio.startListening(); // put back in RX mode // print summary of transactions, starting with details about incoming payload printf("Received %d bytes on pipe %d: %s%d", @@ -191,7 +192,7 @@ void loop() printf(" Sent: %s%d", payload.message, payload.counter); } else { - printf(" Response failed.\n"); // failed to send response + printf(" Response failed.\n"); // failed to send response } } } // role @@ -206,8 +207,7 @@ void loop() role = true; memcpy(payload.message, "Hello ", 6); // set the outgoing message printf("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK\n"); - radio.stopListening(); // put in TX mode - + radio.stopListening(); // put in TX mode } else if ((input == 'R' || input == 'r') && role) { // Become the RX node @@ -215,7 +215,7 @@ void loop() role = false; memcpy(payload.message, "World ", 6); // set the response message printf("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK\n"); - radio.startListening(); // put in RX mode + radio.startListening(); // put in RX mode } else if (input == 'b' || input == 'B') { // reset to bootloader diff --git a/examples_pico/multiceiverDemo.cpp b/examples_pico/multiceiverDemo.cpp index d970ece84..18a7d40f8 100644 --- a/examples_pico/multiceiverDemo.cpp +++ b/examples_pico/multiceiverDemo.cpp @@ -33,8 +33,7 @@ uint64_t address[6] = {0x7878787878LL, 0xB3B4B5B6CDLL, 0xB3B4B5B6A3LL, 0xB3B4B5B60FLL, - 0xB3B4B5B605LL - }; + 0xB3B4B5B605LL}; // Because this example allow up to 6 nodes (specified by numbers 0-5) to // transmit and only 1 node to receive, we will use a negative value in our @@ -48,8 +47,8 @@ char role = 'R'; // integers 0-5 = TX node; character 'R' or integer 82 = RX nod // Make a data structure to use as a payload. struct PayloadStruct { - unsigned long nodeID; - unsigned long payloadID; + unsigned long nodeID; + unsigned long payloadID; }; PayloadStruct payload; @@ -58,7 +57,6 @@ PayloadStruct payload; // payload's nodeID void setRole(); // declare a prototype; definition is found after the loop() - bool setup() { // wait here until the CDC ACM (serial port emulation) is connected @@ -100,7 +98,6 @@ bool setup() return true; } // setup() - void loop() { if (role <= 53) { @@ -130,7 +127,7 @@ void loop() // This device is the RX node uint8_t pipe; - while (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it + while (radio.available(&pipe)) { // is there a payload? get the pipe number that recieved it uint8_t bytes = radio.getPayloadSize(); // get the size of the payload radio.read(&payload, bytes); // fetch payload from FIFO @@ -155,7 +152,6 @@ void loop() printf("--- Enter a number between 0 and 5 (inclusive) to act as\n"); printf(" a unique node number that transmits to the RX node.\n"); setRole(); // change address on all pipes to TX nodes - } else if (input >= 48 && input <= 53 && input != role) { // Become a TX node with identifier 'input' @@ -186,7 +182,6 @@ void setRole() radio.openReadingPipe(i, address[i]); radio.startListening(); // put radio in RX mode - } else { // For the TX node diff --git a/examples_pico/streamingData.cpp b/examples_pico/streamingData.cpp index be7f4d484..4d02e1024 100644 --- a/examples_pico/streamingData.cpp +++ b/examples_pico/streamingData.cpp @@ -31,7 +31,6 @@ char buffer[SIZE + 1]; // for the RX node uint8_t counter = 0; // for counting the number of received payloads void makePayload(uint8_t); // prototype to construct a payload dynamically - bool setup() { buffer[SIZE] = 0; // add a NULL terminating character (for easy printing) @@ -68,21 +67,21 @@ bool setup() // Set the PA Level low to try preventing power supply related problems // because these examples are likely run with nodes in close proximity to // each other. - radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. + radio.setPALevel(RF24_PA_LOW); // RF24_PA_MAX is default. // save on transmission time by setting the radio to only transmit the // number of bytes we need to transmit - radio.setPayloadSize(SIZE); // default value is the maximum 32 bytes + radio.setPayloadSize(SIZE); // default value is the maximum 32 bytes // set the TX address of the RX node into the TX pipe - radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 + radio.openWritingPipe(address[radioNumber]); // always uses pipe 0 // set the RX address of the TX node into a RX pipe radio.openReadingPipe(1, address[!radioNumber]); // using pipe 1 // additional setup specific to the node's role if (role) { - radio.stopListening(); // put radio in TX mode + radio.stopListening(); // put radio in TX mode } else { radio.startListening(); // put radio in RX mode @@ -98,8 +97,8 @@ bool setup() return true; } // setup() - -void loop() { +void loop() +{ if (role) { // This device is a TX node @@ -109,7 +108,7 @@ void loop() { uint8_t failures = 0; uint64_t start_timer = to_us_since_boot(get_absolute_time()); // start the timer while (i < SIZE) { - makePayload(i); // make the payload + makePayload(i); // make the payload if (!radio.writeFast(&buffer, SIZE)) { failures++; radio.reUseTX(); @@ -134,8 +133,8 @@ void loop() { else { // This device is a RX node - if (radio.available()) { // is there a payload? - radio.read(&buffer, SIZE); // fetch payload from FIFO + if (radio.available()) { // is there a payload? + radio.read(&buffer, SIZE); // fetch payload from FIFO // print the received payload and its counter printf("Received: %s - %d\n", buffer, counter++); @@ -153,7 +152,6 @@ void loop() { counter = 0; //reset the RX node's counter printf("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK\n"); radio.stopListening(); - } else if ((input == 'R' || input == 'r') && role) { // Become the RX node @@ -170,8 +168,8 @@ void loop() { } } // loop - -void makePayload(uint8_t i) { +void makePayload(uint8_t i) +{ // Make a single payload based on position in stream. // This example employs function to save memory on certain boards. diff --git a/nRF24L01.h b/nRF24L01.h index 7ed9d267c..a072686a8 100644 --- a/nRF24L01.h +++ b/nRF24L01.h @@ -115,11 +115,11 @@ #define RF24_NOP 0xFF /* Non-P omissions */ -#define LNA_HCURR 0 +#define LNA_HCURR 0 /* P model memory Map */ -#define RPD 0x09 -#define W_TX_PAYLOAD_NO_ACK 0xB0 +#define RPD 0x09 +#define W_TX_PAYLOAD_NO_ACK 0xB0 /* P model bit Mnemonics */ #define RF_DR_LOW 5 diff --git a/printf.h b/printf.h index 381e2331c..7c8d4b58e 100644 --- a/printf.h +++ b/printf.h @@ -17,30 +17,30 @@ #ifndef __PRINTF_H__ #define __PRINTF_H__ -#if defined (ARDUINO_ARCH_AVR) || defined (__ARDUINO_X86__) || defined (ARDUINO_ARCH_MEGAAVR) +#if defined(ARDUINO_ARCH_AVR) || defined(__ARDUINO_X86__) || defined(ARDUINO_ARCH_MEGAAVR) -int serial_putc(char c, FILE *) +int serial_putc(char c, FILE*) { Serial.write(c); return c; } -#elif defined (ARDUINO_ARCH_MBED) +#elif defined(ARDUINO_ARCH_MBED) REDIRECT_STDOUT_TO(Serial); #endif // defined (ARDUINO_ARCH_AVR) || defined (__ARDUINO_X86__) || defined (ARDUINO_ARCH_MBED) || defined (ARDUINO_ARCH_MEGAAVR) void printf_begin(void) { - #if defined (ARDUINO_ARCH_AVR) || defined (ARDUINO_ARCH_MEGAAVR) +#if defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_MEGAAVR) fdevopen(&serial_putc, 0); - #elif defined (__ARDUINO_X86__) +#elif defined(__ARDUINO_X86__) // For redirect stdout to /dev/ttyGS0 (Serial Monitor port) stdout = freopen("/dev/ttyGS0", "w", stdout); delay(500); printf("Redirecting to Serial..."); - #endif // defined(__ARDUINO_X86__) +#endif // defined(__ARDUINO_X86__) } #endif // __PRINTF_H__ diff --git a/pyRF24/pyRF24.cpp b/pyRF24/pyRF24.cpp index 04a511572..857a2f0ce 100644 --- a/pyRF24/pyRF24.cpp +++ b/pyRF24/pyRF24.cpp @@ -97,12 +97,12 @@ void startWrite_wrap(RF24& ref, bp::object buf, const bool multicast) void openWritingPipe_wrap(RF24& ref, const bp::object address) { - ref.openWritingPipe((const uint8_t*) (get_bytes_or_bytearray_str(address))); + ref.openWritingPipe((const uint8_t*)(get_bytes_or_bytearray_str(address))); } void openReadingPipe_wrap(RF24& ref, uint8_t number, const bp::object address) { - ref.openReadingPipe(number, (const uint8_t*) (get_bytes_or_bytearray_str(address))); + ref.openReadingPipe(number, (const uint8_t*)(get_bytes_or_bytearray_str(address))); } bp::tuple whatHappened_wrap(RF24& ref) @@ -136,9 +136,9 @@ bool begin_with_pins(RF24& ref, uint16_t _cepin, uint16_t _cspin) bp::object sprintfPrettyDetails_wrap(RF24& ref) { - char *buf = new char[870]; + char* buf = new char[870]; ref.sprintfPrettyDetails(buf); - bp::object ret_str(bp::handle<>(PyUnicode_FromString(reinterpret_cast(buf)))); + bp::object ret_str(bp::handle<>(PyUnicode_FromString(reinterpret_cast(buf)))); delete[] buf; return ret_str; } @@ -153,7 +153,7 @@ BOOST_PYTHON_MODULE(RF24) { #ifdef BCM2835_H - bp::enum_< RPiGPIOPin>("RPiGPIOPin") + bp::enum_("RPiGPIOPin") .value("RPI_GPIO_P1_03", RPI_GPIO_P1_03) .value("RPI_GPIO_P1_05", RPI_GPIO_P1_05) .value("RPI_GPIO_P1_07", RPI_GPIO_P1_07) @@ -220,7 +220,7 @@ BOOST_PYTHON_MODULE(RF24) .value("RPI_BPLUS_GPIO_J8_40", RPI_BPLUS_GPIO_J8_40) .export_values(); - bp::enum_< bcm2835SPIClockDivider>("bcm2835SPIClockDivider") + bp::enum_("bcm2835SPIClockDivider") .value("BCM2835_SPI_CLOCK_DIVIDER_65536", BCM2835_SPI_CLOCK_DIVIDER_65536) .value("BCM2835_SPI_CLOCK_DIVIDER_32768", BCM2835_SPI_CLOCK_DIVIDER_32768) .value("BCM2835_SPI_CLOCK_DIVIDER_16384", BCM2835_SPI_CLOCK_DIVIDER_16384) @@ -240,15 +240,14 @@ BOOST_PYTHON_MODULE(RF24) .value("BCM2835_SPI_CLOCK_DIVIDER_1", BCM2835_SPI_CLOCK_DIVIDER_1) .export_values(); - - bp::enum_< bcm2835SPIChipSelect>("bcm2835SPIChipSelect") + bp::enum_("bcm2835SPIChipSelect") .value("BCM2835_SPI_CS0", BCM2835_SPI_CS0) .value("BCM2835_SPI_CS1", BCM2835_SPI_CS1) .value("BCM2835_SPI_CS2", BCM2835_SPI_CS2) .value("BCM2835_SPI_CS_NONE", BCM2835_SPI_CS_NONE) .export_values(); -#endif // BCM2835_H +#endif // BCM2835_H bp::enum_("rf24_crclength_e") .value("RF24_CRC_DISABLED", RF24_CRC_DISABLED) @@ -271,14 +270,14 @@ BOOST_PYTHON_MODULE(RF24) .export_values(); // ******************** RF24 class ************************** - bp::class_< RF24 >("RF24", bp::init< uint16_t, uint16_t >((bp::arg("_cepin"), bp::arg("_cspin")))) - #if defined (RF24_LINUX) && !defined (MRAA) - .def(bp::init< uint16_t, uint16_t, uint32_t >((bp::arg("_cepin"), bp::arg("_cspin"), bp::arg("spispeed")))) - .def(bp::init< uint32_t >((bp::arg("spispeed")))) - .def(bp::init< >()) - #endif + bp::class_("RF24", bp::init((bp::arg("_cepin"), bp::arg("_cspin")))) +#if defined(RF24_LINUX) && !defined(MRAA) + .def(bp::init((bp::arg("_cepin"), bp::arg("_cspin"), bp::arg("spispeed")))) + .def(bp::init((bp::arg("spispeed")))) + .def(bp::init<>()) +#endif .def("available", (bool (::RF24::*)())(&::RF24::available)) - .def("available_pipe", &available_wrap) // needed to rename this method as python does not allow such overloading + .def("available_pipe", &available_wrap) // needed to rename this method as python does not allow such overloading .def("begin", (bool (::RF24::*)(void))(&::RF24::begin)) .def("begin", &begin_with_pins) .def("closeReadingPipe", &RF24::closeReadingPipe) @@ -299,7 +298,7 @@ BOOST_PYTHON_MODULE(RF24) .def("isChipConnected", &RF24::isChipConnected) .def("maskIRQ", &RF24::maskIRQ, (bp::arg("tx_ok"), bp::arg("tx_fail"), bp::arg("rx_ready"))) .def("openReadingPipe", &openReadingPipe_wrap, (bp::arg("number"), bp::arg("address"))) - .def("openReadingPipe", (void (::RF24::*)(::uint8_t,::uint64_t))(&::RF24::openReadingPipe), (bp::arg("number"), bp::arg("address"))) + .def("openReadingPipe", (void (::RF24::*)(::uint8_t, ::uint64_t))(&::RF24::openReadingPipe), (bp::arg("number"), bp::arg("address"))) .def("openWritingPipe", &openWritingPipe_wrap, (bp::arg("address"))) .def("openWritingPipe", (void (::RF24::*)(::uint64_t))(&::RF24::openWritingPipe), (bp::arg("address"))) .def("powerDown", &RF24::powerDown) @@ -315,7 +314,7 @@ BOOST_PYTHON_MODULE(RF24) .def("setAutoAck", (void (::RF24::*)(::uint8_t, bool))(&::RF24::setAutoAck), (bp::arg("pipe"), bp::arg("enable"))) .def("setCRCLength", &RF24::setCRCLength, (bp::arg("length"))) .def("setDataRate", &RF24::setDataRate, (bp::arg("speed"))) - .def("setPALevel", &RF24::setPALevel, (bp::arg("level"), bp::arg("lnaEnable")=1)) + .def("setPALevel", &RF24::setPALevel, (bp::arg("level"), bp::arg("lnaEnable") = 1)) .def("setPALevel", &setPALevel_wrap, (bp::arg("level"))) .def("setRetries", &RF24::setRetries, (bp::arg("delay"), bp::arg("count"))) .def("startFastWrite", &startFastWrite_wrap1, (bp::arg("buf"), bp::arg("len"), bp::arg("multicast"))) diff --git a/utility/ATTiny/RF24_arch_config.h b/utility/ATTiny/RF24_arch_config.h index 4b527a899..f46a966f4 100644 --- a/utility/ATTiny/RF24_arch_config.h +++ b/utility/ATTiny/RF24_arch_config.h @@ -1,19 +1,18 @@ - /* TMRh20 2015 ATTiny Configuration File */ -#ifndef __RF24_ARCH_CONFIG_H__ -#define __RF24_ARCH_CONFIG_H__ +#ifndef RF24_UTILITY_ATTINY_RF24_ARCH_CONFIG_H_ +#define RF24_UTILITY_ATTINY_RF24_ARCH_CONFIG_H_ /*** USER DEFINES: ***/ //#define FAILURE_HANDLING //#define MINIMAL /**********************/ -#define rf24_max(a, b) (a>b?a:b) -#define rf24_min(a, b) (a b ? a : b) +#define rf24_min(a, b) (a < b ? a : b) #if ARDUINO < 100 #include @@ -28,26 +27,25 @@ #define _SPI SPI #if !defined(RF24_CSN_SETTLE_LOW_DELAY) -#define RF24_CSN_SETTLE_LOW_DELAY 11 + #define RF24_CSN_SETTLE_LOW_DELAY 11 #endif #if !defined(RF24_CSN_SETTLE_HIGH_DELAY) -#define RF24_CSN_SETTLE_HIGH_DELAY 100 + #define RF24_CSN_SETTLE_HIGH_DELAY 100 #endif - #ifdef SERIAL_DEBUG - #define IF_SERIAL_DEBUG(x) ({x;}) + #define IF_SERIAL_DEBUG(x) ({ x; }) #else #define IF_SERIAL_DEBUG(x) + #if defined(RF24_TINY) #define printf_P(...) #endif -#endif +#endif // !defined(SERIAL_DEBUG) #include #define PRIPSTR "%S" -#endif // __RF24_ARCH_CONFIG_H__ - +#endif // RF24_UTILITY_ATTINY_RF24_ARCH_CONFIG_H_ diff --git a/utility/ATXMegaD3/RF24_arch_config.h b/utility/ATXMegaD3/RF24_arch_config.h index ab51c15bc..8b0db4f0b 100644 --- a/utility/ATXMegaD3/RF24_arch_config.h +++ b/utility/ATXMegaD3/RF24_arch_config.h @@ -1,29 +1,19 @@ /* - 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. - + * 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 RF24_arch_config.h -* General defines and includes for RF24/Linux -*/ - -/** -* Example of RF24_arch_config.h for RF24 portability -* -* @defgroup Porting_General Porting: General -* -* -* @{ -*/ - + * @file RF24_arch_config.h + * General defines and includes for RF24/Linux + */ -#ifndef __RF24_ARCH_CONFIG_H__ -#define __RF24_ARCH_CONFIG_H__ +#ifndef RF24_UTILITY_ATXMEGAD3_RF24_ARCH_CONFIG_H_ +#define RF24_UTILITY_ATXMEGAD3_RF24_ARCH_CONFIG_H_ #include #include @@ -42,7 +32,7 @@ #undef SERIAL_DEBUG #ifdef SERIAL_DEBUG - #define IF_SERIAL_DEBUG(x) ({x;}) + #define IF_SERIAL_DEBUG(x) ({ x; }) #else #define IF_SERIAL_DEBUG(x) #endif @@ -68,17 +58,14 @@ typedef uint16_t prog_uint16_t; //#define pgm_read_byte(p) (*(p)) // Function, constant map as a result of migrating from Arduino -#define LOW GPIO::OUTPUT_LOW -#define HIGH GPIO::OUTPUT_HIGH -#define INPUT GPIO::DIRECTION_IN -#define OUTPUT GPIO::DIRECTION_OUT +#define LOW GPIO::OUTPUT_LOW +#define HIGH GPIO::OUTPUT_HIGH +#define INPUT GPIO::DIRECTION_IN +#define OUTPUT GPIO::DIRECTION_OUT #define digitalWrite(pin, value) GPIO::write(pin, value) -#define pinMode(pin, direction) GPIO::open(pin, direction) -#define delay(milisec) __msleep(milisec) -#define delayMicroseconds(usec) __usleep(usec) -#define millis() __millis() - -#endif // __RF24_ARCH_CONFIG_H__ - +#define pinMode(pin, direction) GPIO::open(pin, direction) +#define delay(milisec) __msleep(milisec) +#define delayMicroseconds(usec) __usleep(usec) +#define millis() __millis() -/*@}*/ +#endif // RF24_UTILITY_ATXMEGAD3_RF24_ARCH_CONFIG_H_ diff --git a/utility/ATXMegaD3/compatibility.c b/utility/ATXMegaD3/compatibility.c index ae07a9a93..4f8437e88 100644 --- a/utility/ATXMegaD3/compatibility.c +++ b/utility/ATXMegaD3/compatibility.c @@ -27,7 +27,6 @@ void __usleep(int usec) void __start_timer() { - // Timer details : Clock is 32MHz, Timer resolution is 8bit, Prescaler is 256, Period is 124, Real Time is 0.001s /* Set the timer to run at the fastest rate. */ @@ -58,7 +57,3 @@ void update_milisec() { _millis++; } - - - - diff --git a/utility/ATXMegaD3/compatibility.h b/utility/ATXMegaD3/compatibility.h index 31e8c4c23..75b04b2e8 100644 --- a/utility/ATXMegaD3/compatibility.h +++ b/utility/ATXMegaD3/compatibility.h @@ -1,28 +1,16 @@ -/* - * File: compatiblity.h - * Author: purinda +/** + * @file compatibility.h + * @author purinda * * Created on 24 June 2012, 3:08 PM + * + * Class declaration for SPI helper files */ -/** -* @file compatibility.h -* Class declaration for SPI helper files -*/ +#ifndef RF24_UTILITY_ATXMEGAD3_COMPATIBLITY_H_ +#define RF24_UTILITY_ATXMEGAD3_COMPATIBLITY_H_ -/** -* Example of compatibility.h class declaration for timing functions portability -* -* @defgroup Porting_Timing Porting: Timing -* -* -* @{ -*/ - -#ifndef COMPATIBLITY_H -#define COMPATIBLITY_H - -#ifdef __cplusplus +#ifdef __cplusplus extern "C" { #endif @@ -40,10 +28,8 @@ long __millis(); void update_milisec(); -#ifdef __cplusplus +#ifdef __cplusplus } #endif -#endif /* COMPATIBLITY_H */ - -/*@}*/ \ No newline at end of file +#endif // RF24_UTILITY_ATXMEGAD3_COMPATIBLITY_H_ diff --git a/utility/ATXMegaD3/gpio.cpp b/utility/ATXMegaD3/gpio.cpp index 23a644179..4195ab866 100644 --- a/utility/ATXMegaD3/gpio.cpp +++ b/utility/ATXMegaD3/gpio.cpp @@ -15,7 +15,8 @@ void GPIO::open(int port, int DDR) PORT_t* p = GPIO_getPort(port, &pin); if (DDR == 0) { p->DIRCLR = pin; - } else if (DDR == 1) { + } + else if (DDR == 1) { p->DIRSET = pin; } } @@ -38,9 +39,8 @@ void GPIO::write(int port, int value) PORT_t* p = GPIO_getPort(port, &pin); if (value == 0) { p->OUTCLR = pin; - } else if (value == 1) { + } + else if (value == 1) { p->OUTSET = pin; } - } - diff --git a/utility/ATXMegaD3/gpio.h b/utility/ATXMegaD3/gpio.h index 01c0b1896..b63e8eec0 100644 --- a/utility/ATXMegaD3/gpio.h +++ b/utility/ATXMegaD3/gpio.h @@ -1,27 +1,17 @@ - - /** * @file gpio.h * Class declaration for SPI helper files */ - -/** -* Example of gpio.h class declaration for GPIO portability -* -* @defgroup Porting_GPIO Porting: GPIO -* -* -* @{ -*/ -#ifndef GPIO_H -#define GPIO_H +#ifndef RF24_UTILITY_ATXMEGAD3_GPIO_H_ +#define RF24_UTILITY_ATXMEGAD3_GPIO_H_ #include #include "gpio_helper.h" -class GPIO { +class GPIO +{ + public: - /* Constants */ static const int DIRECTION_OUT = 1; static const int DIRECTION_IN = 0; @@ -30,35 +20,15 @@ class GPIO { GPIO(); - /** - * Similar to Arduino pinMode(pin,mode); - * @param port - * @param DDR - */ static void open(int port, int DDR); - /** - * - * @param port - */ static void close(int port); - /** - * Similar to Arduino digitalRead(pin); - * @param port - */ static int read(int port); - /** - * Similar to Arduino digitalWrite(pin,state); - * @param port - * @param value - */ static void write(int port, int value); virtual ~GPIO(); - }; -#endif /* GPIO_H */ -/*@}*/ \ No newline at end of file +#endif // RF24_UTILITY_ATXMEGAD3_GPIO_H_ diff --git a/utility/ATXMegaD3/gpio_helper.c b/utility/ATXMegaD3/gpio_helper.c index a0b5245d8..7c5a28643 100644 --- a/utility/ATXMegaD3/gpio_helper.c +++ b/utility/ATXMegaD3/gpio_helper.c @@ -8,8 +8,8 @@ #include "gpio_helper.h" /** -* Get the port corresponding in portnum. Default is PORTC. -*/ + * Get the port corresponding in portnum. Default is PORTC. + */ PORT_t* GPIO_getPort(int pinnum, uint8_t* pin_bm) //PORT_t * GPIO_getPort(int portnum) { @@ -17,23 +17,27 @@ PORT_t* GPIO_getPort(int pinnum, uint8_t* pin_bm) if ((pinnum >= XMEGA_PORTA_PIN0) && (pinnum <= XMEGA_PORTA_PIN7)) { port = &PORTA; *pin_bm = (1 << pinnum); - } else if ((pinnum >= XMEGA_PORTB_PIN0) && (pinnum <= XMEGA_PORTB_PIN7)) { + } + else if ((pinnum >= XMEGA_PORTB_PIN0) && (pinnum <= XMEGA_PORTB_PIN7)) { port = &PORTB; *pin_bm = (1 << (pinnum - 8)); - } else if ((pinnum >= XMEGA_PORTC_PIN0) && (pinnum <= XMEGA_PORTC_PIN7)) { + } + else if ((pinnum >= XMEGA_PORTC_PIN0) && (pinnum <= XMEGA_PORTC_PIN7)) { port = &PORTC; *pin_bm = (1 << (pinnum - 16)); - } else if ((pinnum >= XMEGA_PORTD_PIN0) && (pinnum <= XMEGA_PORTD_PIN7)) { + } + else if ((pinnum >= XMEGA_PORTD_PIN0) && (pinnum <= XMEGA_PORTD_PIN7)) { port = &PORTD; *pin_bm = (1 << (pinnum - 24)); - } else if ((pinnum >= XMEGA_PORTE_PIN0) && (pinnum <= XMEGA_PORTE_PIN7)) { + } + else if ((pinnum >= XMEGA_PORTE_PIN0) && (pinnum <= XMEGA_PORTE_PIN7)) { port = &PORTE; *pin_bm = (1 << (pinnum - 32)); - } else if ((pinnum >= XMEGA_PORTF_PIN0) && (pinnum <= XMEGA_PORTF_PIN7)) { + } + else if ((pinnum >= XMEGA_PORTF_PIN0) && (pinnum <= XMEGA_PORTF_PIN7)) { port = &PORTF; *pin_bm = (1 << (pinnum - 40)); } return port; - -} \ No newline at end of file +} diff --git a/utility/ATXMegaD3/gpio_helper.h b/utility/ATXMegaD3/gpio_helper.h index 1146fb015..b41a22af8 100644 --- a/utility/ATXMegaD3/gpio_helper.h +++ b/utility/ATXMegaD3/gpio_helper.h @@ -1,76 +1,73 @@ -/* - * gpio_helper.h +/** + * @file gpio_helper.h + * @author akatran * * Created: 22/1/2016 15:29:12 - * Author: akatran */ - - -#ifndef GPIO_HELPER_H_ -#define GPIO_HELPER_H_ +#ifndef RF24_UTILITY_MRAA_GPIO_HELPER_H_ +#define RF24_UTILITY_MRAA_GPIO_HELPER_H_ #include -#ifdef __cplusplus +#ifdef __cplusplus extern "C" { #endif /* Defines */ - -#define XMEGA_PORTA_PIN0 0 -#define XMEGA_PORTA_PIN1 1 -#define XMEGA_PORTA_PIN2 2 -#define XMEGA_PORTA_PIN3 3 -#define XMEGA_PORTA_PIN4 4 -#define XMEGA_PORTA_PIN5 5 -#define XMEGA_PORTA_PIN6 6 -#define XMEGA_PORTA_PIN7 7 - -#define XMEGA_PORTB_PIN0 8 -#define XMEGA_PORTB_PIN1 9 -#define XMEGA_PORTB_PIN2 10 -#define XMEGA_PORTB_PIN3 11 -#define XMEGA_PORTB_PIN4 12 -#define XMEGA_PORTB_PIN5 13 -#define XMEGA_PORTB_PIN6 14 -#define XMEGA_PORTB_PIN7 15 - -#define XMEGA_PORTC_PIN0 16 -#define XMEGA_PORTC_PIN1 17 -#define XMEGA_PORTC_PIN2 18 -#define XMEGA_PORTC_PIN3 19 -#define XMEGA_PORTC_PIN4 20 -#define XMEGA_PORTC_PIN5 21 -#define XMEGA_PORTC_PIN6 22 -#define XMEGA_PORTC_PIN7 23 - -#define XMEGA_PORTD_PIN0 24 -#define XMEGA_PORTD_PIN1 25 -#define XMEGA_PORTD_PIN2 26 -#define XMEGA_PORTD_PIN3 27 -#define XMEGA_PORTD_PIN4 28 -#define XMEGA_PORTD_PIN5 29 -#define XMEGA_PORTD_PIN6 30 -#define XMEGA_PORTD_PIN7 31 - -#define XMEGA_PORTE_PIN0 32 -#define XMEGA_PORTE_PIN1 33 -#define XMEGA_PORTE_PIN2 34 -#define XMEGA_PORTE_PIN3 35 -#define XMEGA_PORTE_PIN4 36 -#define XMEGA_PORTE_PIN5 37 -#define XMEGA_PORTE_PIN6 38 -#define XMEGA_PORTE_PIN7 39 - -#define XMEGA_PORTF_PIN0 40 -#define XMEGA_PORTF_PIN1 41 -#define XMEGA_PORTF_PIN2 42 -#define XMEGA_PORTF_PIN3 43 -#define XMEGA_PORTF_PIN4 44 -#define XMEGA_PORTF_PIN5 45 -#define XMEGA_PORTF_PIN6 46 -#define XMEGA_PORTF_PIN7 47 +#define XMEGA_PORTA_PIN0 0 +#define XMEGA_PORTA_PIN1 1 +#define XMEGA_PORTA_PIN2 2 +#define XMEGA_PORTA_PIN3 3 +#define XMEGA_PORTA_PIN4 4 +#define XMEGA_PORTA_PIN5 5 +#define XMEGA_PORTA_PIN6 6 +#define XMEGA_PORTA_PIN7 7 + +#define XMEGA_PORTB_PIN0 8 +#define XMEGA_PORTB_PIN1 9 +#define XMEGA_PORTB_PIN2 10 +#define XMEGA_PORTB_PIN3 11 +#define XMEGA_PORTB_PIN4 12 +#define XMEGA_PORTB_PIN5 13 +#define XMEGA_PORTB_PIN6 14 +#define XMEGA_PORTB_PIN7 15 + +#define XMEGA_PORTC_PIN0 16 +#define XMEGA_PORTC_PIN1 17 +#define XMEGA_PORTC_PIN2 18 +#define XMEGA_PORTC_PIN3 19 +#define XMEGA_PORTC_PIN4 20 +#define XMEGA_PORTC_PIN5 21 +#define XMEGA_PORTC_PIN6 22 +#define XMEGA_PORTC_PIN7 23 + +#define XMEGA_PORTD_PIN0 24 +#define XMEGA_PORTD_PIN1 25 +#define XMEGA_PORTD_PIN2 26 +#define XMEGA_PORTD_PIN3 27 +#define XMEGA_PORTD_PIN4 28 +#define XMEGA_PORTD_PIN5 29 +#define XMEGA_PORTD_PIN6 30 +#define XMEGA_PORTD_PIN7 31 + +#define XMEGA_PORTE_PIN0 32 +#define XMEGA_PORTE_PIN1 33 +#define XMEGA_PORTE_PIN2 34 +#define XMEGA_PORTE_PIN3 35 +#define XMEGA_PORTE_PIN4 36 +#define XMEGA_PORTE_PIN5 37 +#define XMEGA_PORTE_PIN6 38 +#define XMEGA_PORTE_PIN7 39 + +#define XMEGA_PORTF_PIN0 40 +#define XMEGA_PORTF_PIN1 41 +#define XMEGA_PORTF_PIN2 42 +#define XMEGA_PORTF_PIN3 43 +#define XMEGA_PORTF_PIN4 44 +#define XMEGA_PORTF_PIN5 45 +#define XMEGA_PORTF_PIN6 46 +#define XMEGA_PORTF_PIN7 47 #define XMEGA_SPI_PORT_C 20 #define XMEGA_SPI_PORT_D 28 @@ -79,8 +76,8 @@ extern "C" { //void GPIO_getPort(int pinnum, PORT_t * port, uint8_t * pin_bm); PORT_t* GPIO_getPort(int pinnum, uint8_t* pin_bm); -#ifdef __cplusplus +#ifdef __cplusplus } #endif -#endif /* GPIO_HELPER_H_ */ \ No newline at end of file +#endif // RF24_UTILITY_MRAA_GPIO_HELPER_H_ diff --git a/utility/ATXMegaD3/includes.h b/utility/ATXMegaD3/includes.h index cf12b0302..2cbf987f8 100644 --- a/utility/ATXMegaD3/includes.h +++ b/utility/ATXMegaD3/includes.h @@ -3,17 +3,8 @@ * Configuration defines for RF24/Linux */ -/** -* Example of includes.h for RF24 Linux portability -* -* @defgroup Porting_Includes Porting: Includes -* -* -* @{ -*/ - -#ifndef __RF24_INCLUDES_H__ -#define __RF24_INCLUDES_H__ +#ifndef RF24_UTILITY_INCLUDES_H_ +#define RF24_UTILITY_INCLUDES_H_ /** * Define a specific platform for this configuration @@ -22,9 +13,7 @@ /** * Load the correct configuration for this platform -*/ -//#include "BBB/RF24_arch_config.h" - -#endif + */ +// #include "BBB/RF24_arch_config.h" -/*@}*/ \ No newline at end of file +#endif // RF24_UTILITY_INCLUDES_H_ diff --git a/utility/ATXMegaD3/spi.cpp b/utility/ATXMegaD3/spi.cpp index 3207e50dd..b6b664ba3 100644 --- a/utility/ATXMegaD3/spi.cpp +++ b/utility/ATXMegaD3/spi.cpp @@ -17,7 +17,8 @@ void SPI::begin(uint8_t _port) { device = &SPIC; port = &PORTC; - } else if (_port == XMEGA_SPI_PORT_D) // Select SPI on PORTD + } + else if (_port == XMEGA_SPI_PORT_D) // Select SPI on PORTD { device = &SPID; port = &PORTD; @@ -45,20 +46,16 @@ void SPI::init() //device->CTRL = 0; device->CTRL = SPI_ENABLE_bm | SPI_MASTER_bm | SPI_MODE_0_gc | SPI_PRESCALER_DIV4_gc; device->INTCTRL = 0; //Disable interrupts - } SPI::SPI() { - } SPI::~SPI() { - } void operator delete(void* p) // or delete(void *, std::size_t) { - -} \ No newline at end of file +} diff --git a/utility/ATXMegaD3/spi.h b/utility/ATXMegaD3/spi.h index caf479236..7bf02164c 100644 --- a/utility/ATXMegaD3/spi.h +++ b/utility/ATXMegaD3/spi.h @@ -2,18 +2,8 @@ * @file spi.h * Class declaration for SPI helper files */ - -/** -* Example of spi.h class declaration for SPI portability -* -* @defgroup Porting_SPI Porting: SPI -* -* -* @{ -*/ - -#ifndef __XMEGASPI_H__ -#define __XMEGASPI_H__ +#ifndef RF24_UTILITY_ATXMEGAD3_SPI_H_ +#define RF24_UTILITY_ATXMEGAD3_SPI_H_ #include #include @@ -26,55 +16,36 @@ //#include //#include //#include -//#include +//#include -#define SPI_SS_bm (1<<4) /* SPI SS pin mask 4 */ -#define SPI_MOSI_bm (1<<5) /* SPI MOSI pin mask 5 */ -#define SPI_MISO_bm (1<<6) /* SPI MISO pin mask 6 */ -#define SPI_SCK_bm (1<<7) /* SPI SCK pin mask 7 */ +#define SPI_SS_bm (1 << 4) /* SPI SS pin mask 4 */ +#define SPI_MOSI_bm (1 << 5) /* SPI MOSI pin mask 5 */ +#define SPI_MISO_bm (1 << 6) /* SPI MISO pin mask 6 */ +#define SPI_SCK_bm (1 << 7) /* SPI SCK pin mask 7 */ using namespace std; -class SPI { -public: +class SPI +{ - /** - * SPI constructor - */ +public: SPI(); /** - * Start SPI - * @param port is the SPI port (XMEGA_SPI_PORT_C for SPI on PORTC, XMEGA_SPI_PORT_D on PORTD etc). - */ + * Start SPI + * @param port is the SPI port (XMEGA_SPI_PORT_C for SPI on PORTC, XMEGA_SPI_PORT_D on PORTD etc). + */ void begin(uint8_t port); - /** - * Transfer a single byte - * @param tx_ Byte to send - * @return Data returned via spi - */ uint8_t transfer(uint8_t tx_); - /** - * Transfer a buffer of data - * @param tbuf Transmit buffer - * @param rbuf Receive buffer - * @param len Length of the data - */ void transfernb(char* tbuf, char* rbuf, uint32_t len); - /** - * Transfer a buffer of data without an rx buffer - * @param buf Pointer to a buffer of data - * @param len Length of the data - */ void transfern(char* buf, uint32_t len); virtual ~SPI(); private: - /** Default SPI device */ SPI_t* device; /* Port of the SPI */ @@ -83,6 +54,4 @@ class SPI { void init(); }; -#endif /*__XMEGASPI_H__*/ - -/*@}*/ \ No newline at end of file +#endif //RF24_UTILITY_ATXMEGAD3_SPI_H_ diff --git a/utility/LittleWire/RF24_arch_config.h b/utility/LittleWire/RF24_arch_config.h index 9bf308d8c..d0548f045 100644 --- a/utility/LittleWire/RF24_arch_config.h +++ b/utility/LittleWire/RF24_arch_config.h @@ -1,5 +1,5 @@ -#ifndef __ARCH_CONFIG_H__ -#define __ARCH_CONFIG_H__ +#ifndef RF24_UTILITY_LITTLEWIRE_RF24_ARCH_CONFIG_H_ +#define RF24_UTILITY_LITTLEWIRE_RF24_ARCH_CONFIG_H_ #include #include @@ -15,20 +15,20 @@ extern LittleWireSPI _SPI; // GCC a Arduino Missing -#define _BV(x) (1<<(x)) +#define _BV(x) (1 << (x)) #define pgm_read_word(p) (*(p)) #define pgm_read_byte(p) (*(p)) -#define pgm_read_ptr(p) (*(p)) +#define pgm_read_ptr(p) (*(p)) //typedef uint16_t prog_uint16_t; -#define PSTR(x) (x) +#define PSTR(x) (x) #define printf_P printf #define strlen_P strlen #define PROGMEM #define PRIPSTR "%s" #ifdef SERIAL_DEBUG - #define IF_SERIAL_DEBUG(x) ({x;}) + #define IF_SERIAL_DEBUG(x) ({ x; }) #else #define IF_SERIAL_DEBUG(x) #if defined(RF24_TINY) @@ -36,4 +36,4 @@ extern LittleWireSPI _SPI; #endif #endif -#endif +#endif // RF24_UTILITY_LITTLEWIRE_RF24_ARCH_CONFIG_H_ diff --git a/utility/LittleWire/includes.h b/utility/LittleWire/includes.h index 197e4473f..dd0b6a887 100644 --- a/utility/LittleWire/includes.h +++ b/utility/LittleWire/includes.h @@ -1,19 +1,10 @@ /** -* @file includes.h -* Configuration defines for RF24/Linux -*/ - -/** -* Example of includes.h for RF24 Linux portability -* -* @defgroup Porting_Includes Porting: Includes -* -* -* @{ -*/ + * @file includes.h + * Configuration defines for RF24/Linux + */ -#ifndef __RF24_INCLUDES_H__ -#define __RF24_INCLUDES_H__ +#ifndef RF24_UTILITY_INCLUDES_H_ +#define RF24_UTILITY_INCLUDES_H_ /** * Define a specific platform for this configuration @@ -22,9 +13,7 @@ /** * Load the correct configuration for this platform -*/ + */ #include "LittleWire/RF24_arch_config.h" -#endif - -/*@}*/ +#endif // RF24_UTILITY_INCLUDES_H_ diff --git a/utility/MRAA/RF24_arch_config.h b/utility/MRAA/RF24_arch_config.h index 0699ca9d0..6fa067903 100644 --- a/utility/MRAA/RF24_arch_config.h +++ b/utility/MRAA/RF24_arch_config.h @@ -1,5 +1,5 @@ -#ifndef __ARCH_CONFIG_H__ -#define __ARCH_CONFIG_H__ +#ifndef RF24_UTILITY_MRAA_RF24_ARCH_CONFIG_H_ +#define RF24_UTILITY_MRAA_RF24_ARCH_CONFIG_H_ #include "mraa.h" #include "spi.h" @@ -19,41 +19,41 @@ //#include // Precompiled arduino x86 based utiltime for timing functions // GCC a Arduino Missing -#define HIGH 1 -#define LOW 0 -#define _BV(x) (1<<(x)) +#define HIGH 1 +#define LOW 0 +#define _BV(x) (1 << (x)) #define pgm_read_word(p) (*(p)) #define pgm_read_byte(p) (*(p)) -#define pgm_read_ptr(p) (*(p)) -#define _SPI spi +#define pgm_read_ptr(p) (*(p)) +#define _SPI spi #define RF24_LINUX //typedef uint16_t prog_uint16_t; -#define PSTR(x) (x) -#define printf_P printf +#define PSTR(x) (x) +#define printf_P printf #define sprintf_P sprintf -#define strlen_P strlen +#define strlen_P strlen #define PROGMEM #define PRIPSTR "%s" #ifdef SERIAL_DEBUG - #define IF_SERIAL_DEBUG(x) ({x;}) + #define IF_SERIAL_DEBUG(x) ({ x; }) #else #define IF_SERIAL_DEBUG(x) #endif #define digitalWrite(pin, value) gpio.write(pin, value) -#define digitalRead(pin) GPIO::read(pin) -#define pinMode(pin, direction) gpio.open(pin, direction) +#define digitalRead(pin) GPIO::read(pin) +#define pinMode(pin, direction) gpio.open(pin, direction) #ifndef __TIME_H__ -// Prophet: Redefine time functions only if precompiled arduino time is not included - #define delay(milisec) __msleep(milisec) + // Prophet: Redefine time functions only if precompiled arduino time is not included + #define delay(milisec) __msleep(milisec) #define delayMicroseconds(usec) __usleep(usec) - #define millis() __millis() + #define millis() __millis() #endif -#define INPUT mraa::DIR_IN +#define INPUT mraa::DIR_IN #define OUTPUT mraa::DIR_OUT // SPI defines for ARDUINO API @@ -61,4 +61,4 @@ //#define SPI_MODE0 mraa::SPI_MODE0 #define SPI_CLOCK_DIV2 RF24_SPI_SPEED -#endif +#endif // RF24_UTILITY_MRAA_RF24_ARCH_CONFIG_H_ diff --git a/utility/MRAA/compatibility.cpp b/utility/MRAA/compatibility.cpp index 5bc2a4034..8593fbd0b 100644 --- a/utility/MRAA/compatibility.cpp +++ b/utility/MRAA/compatibility.cpp @@ -13,7 +13,7 @@ void __msleep(int milisec) struct timespec req = {0}; req.tv_sec = 0; req.tv_nsec = milisec * 1000000L; - nanosleep(&req, (struct timespec*) NULL); + nanosleep(&req, (struct timespec*)NULL); //usleep(milisec*1000); } @@ -22,7 +22,7 @@ void __usleep(int milisec) struct timespec req = {0}; req.tv_sec = 0; req.tv_nsec = milisec * 1000L; - nanosleep(&req, (struct timespec*) NULL); + nanosleep(&req, (struct timespec*)NULL); //usleep(milisec); } @@ -39,6 +39,6 @@ void __start_timer() long __millis() { auto end = std::chrono::steady_clock::now(); - - return std::chrono::duration_cast(end - start).count(); + + return std::chrono::duration_cast(end - start).count(); } diff --git a/utility/MRAA/compatibility.h b/utility/MRAA/compatibility.h index f881d358e..ffc6953fb 100644 --- a/utility/MRAA/compatibility.h +++ b/utility/MRAA/compatibility.h @@ -1,12 +1,12 @@ -/* - * File: compatiblity.h - * Author: purinda +/** + * @file compatiblity.h + * @author purinda * * Created on 24 June 2012, 3:08 PM */ -#ifndef COMPATIBLITY_H -#define COMPATIBLITY_H +#ifndef RF24_UTILITY_MRAA_COMPATIBLITY_H_ +#define RF24_UTILITY_MRAA_COMPATIBLITY_H_ #ifdef __cplusplus extern "C" { @@ -24,9 +24,8 @@ void __start_timer(); long __millis(); -#ifdef __cplusplus +#ifdef __cplusplus } #endif -#endif /* COMPATIBLITY_H */ - +#endif // RF24_UTILITY_MRAA_COMPATIBLITY_H_ diff --git a/utility/MRAA/gpio.cpp b/utility/MRAA/gpio.cpp index 12c01d87f..31d249583 100644 --- a/utility/MRAA/gpio.cpp +++ b/utility/MRAA/gpio.cpp @@ -28,7 +28,7 @@ void GPIO::begin(uint8_t ce_pin, uint8_t cs_pin) // Prophet: owner can be set here, because we use our pins exclusively, and are making mraa:Gpio context persistent // so pins will be unexported only if close is called, or on destruction - gpio_0 = new mraa::Gpio(ce_pin/*,0*/); + gpio_0 = new mraa::Gpio(ce_pin /*,0*/); //gpio_1 = new mraa::Gpio(cs_pin/*,0*/); } @@ -38,13 +38,14 @@ void GPIO::open(int port, int DDR) gpio_0 = new mraa::Gpio(port, 0); // WARNING: use of memory mapped file system is deprecated in MRAA lib gpio_0->useMmap(true); // `false` (or just not calling `useMmap()`) uses default file system? - gpio_0->dir((mraa::Dir) DDR); - }/*else - if(port == gpio_cs_pin){ - gpio_1 = new mraa::Gpio(port,0); - gpio_1->useMmap(true); - gpio_1->dir( (mraa::Dir)DDR); - }*/ + gpio_0->dir((mraa::Dir)DDR); + } + /* + else if(port == gpio_cs_pin) { + gpio_1 = new mraa::Gpio(port,0); + gpio_1->useMmap(true); + gpio_1->dir( (mraa::Dir)DDR); + }*/ } void GPIO::close(int port) @@ -57,21 +58,25 @@ void GPIO::close(int port) } } - /*if(port == gpio_cs_pin) { + /* + if(port == gpio_cs_pin) { if (gpio_1 != NULL) { delete gpio_1; } - }*/ + } + */ } int GPIO::read(int port) { if (port == gpio_ce_pin) { return gpio_0->read(); - }/*else - if(port == gpio_cs_pin){ - return gpio_1->read(); - }*/ + } + /* + else if(port == gpio_cs_pin) { + return gpio_1->read(); + } + */ return -1; } @@ -80,8 +85,10 @@ void GPIO::write(int port, int value) if (port == gpio_ce_pin) { gpio_0->write(value); - }/*else - if(port == gpio_cs_pin){ - gpio_1->write( value); - }*/ + } + /* + else if(port == gpio_cs_pin) { + gpio_1->write( value); + } + */ } diff --git a/utility/MRAA/gpio.h b/utility/MRAA/gpio.h index e00624ecb..4252d3f28 100644 --- a/utility/MRAA/gpio.h +++ b/utility/MRAA/gpio.h @@ -1,68 +1,38 @@ -/* - * TMRh20 2015 - * +/** + * @file spi.h + * @author TMRh20 2015 + * Class declaration for GPIO helper files */ +#ifndef RF24_UTILITY_MRAA_GPIO_H_ +#define RF24_UTILITY_MRAA_GPIO_H_ -#ifndef RF24_ARCH_GPIO_H -#define RF24_ARCH_GPIO_H -/** -* @file spi.h -* @cond HIDDEN_SYMBOLS -* Class declaration for GPIO helper files -*/ #include #include #include "mraa.hpp" -class GPIO { -public: - - /* Constants */ +class GPIO +{ +public: GPIO(); virtual ~GPIO(); - /** - * Sets up GPIO on the CE & CS pins - * @param ce_pin - * @param cs_pin - */ void begin(uint8_t ce_pin, uint8_t cs_pin); - /** - * - * @param port - * @param DDR - */ void open(int port, int DDR); - /** - * - * @param port - */ void close(int port); - /** - * - * @param port - */ int read(int port); - /** - * - * @param port - * @param value - */ void write(int port, int value); private: int gpio_ce_pin; /** ce_pin value of the RF24 device **/ - //int gpio_cs_pin; /** cs_pin value of the RF24 device **/ + // int gpio_cs_pin; /** cs_pin value of the RF24 device **/ mraa::Gpio* gpio_0; /** gpio object for ce_pin **/ - //mraa::Gpio* gpio_1; /** gpio object for cs_pin **/ + // mraa::Gpio* gpio_1; /** gpio object for cs_pin **/ }; -/** - * @endcond - */ -#endif /* RF24_ARCH_GPIO_H */ + +#endif // RF24_UTILITY_MRAA_GPIO_H_ diff --git a/utility/MRAA/includes.h b/utility/MRAA/includes.h index feb55f46b..d5d697909 100644 --- a/utility/MRAA/includes.h +++ b/utility/MRAA/includes.h @@ -1,5 +1,5 @@ -#ifndef __RF24_INCLUDES_H__ -#define __RF24_INCLUDES_H__ +#ifndef RF24_UTILITY_INCLUDES_H_ +#define RF24_UTILITY_INCLUDES_H_ #ifndef MRAA #define MRAA @@ -7,4 +7,4 @@ #include "MRAA/RF24_arch_config.h" -#endif +#endif // RF24_UTILITY_INCLUDES_H_ diff --git a/utility/MRAA/spi.cpp b/utility/MRAA/spi.cpp index 799cb2a84..1e5c06345 100644 --- a/utility/MRAA/spi.cpp +++ b/utility/MRAA/spi.cpp @@ -9,13 +9,14 @@ SPI::SPI() void SPI::begin(int busNo, uint32_t spi_speed) { - mspi = new mraa::Spi( - busNo); // init mraa spi bus, it will handle chip select internally. For CS pin wiring user must check SPI details in hardware manual + // init mraa spi bus, it will handle chip select internally. For CS pin wiring user must check SPI details in hardware manual + mspi = new mraa::Spi(busNo); mspi->mode(mraa::SPI_MODE0); mspi->bitPerWord(8); - mspi->frequency( - spi_speed); // Prophet: this will try to set 8MHz, however MRAA will reset to max platform speed and syslog a message of it + + // Prophet: this will try to set 8MHz, however MRAA will reset to max platform speed and syslog a message of it + mspi->frequency(spi_speed); } void SPI::end() @@ -29,14 +30,14 @@ void SPI::end() void SPI::setBitOrder(uint8_t bit_order) { if (mspi != NULL) { - mspi->lsbmode((mraa_boolean_t) bit_order); + mspi->lsbmode((mraa_boolean_t)bit_order); } // Prophet: bit_order } void SPI::setDataMode(uint8_t data_mode) { if (mspi != NULL) { - mspi->mode((mraa::Spi_Mode) data_mode); + mspi->mode((mraa::Spi_Mode)data_mode); } } @@ -49,7 +50,6 @@ void SPI::setClockDivider(uint32_t spi_speed) void SPI::chipSelect(int csn_pin) { - } SPI::~SPI() diff --git a/utility/MRAA/spi.h b/utility/MRAA/spi.h index 6ea3eb030..a27fdeb17 100644 --- a/utility/MRAA/spi.h +++ b/utility/MRAA/spi.h @@ -3,23 +3,22 @@ * SPI layer for RF24 */ -#ifndef _SPI_H_INCLUDED -#define _SPI_H_INCLUDED +#ifndef RF24_UTILITY_MRAA_SPI_H_ +#define RF24_UTILITY_MRAA_SPI_H_ /** -* @file spi.h -* \cond HIDDEN_SYMBOLS -* Class declaration for SPI helper files -*/ + * @file spi.h + * Class declaration for SPI helper files + */ #include #include "mraa.h" #include "mraa.hpp" -#include "../../RF24_config.h" +#include "../../RF24_config.h" // This is cyclical and should be fixed -class SPI { +class SPI +{ public: - SPI(); virtual ~SPI(); @@ -52,7 +51,7 @@ uint8_t SPI::transfer(uint8_t _data) void SPI::transfernb(char* tbuf, char* rbuf, uint32_t len) { - mspi->transfer((uint8_t*) tbuf, (uint8_t*) rbuf, len); + mspi->transfer((uint8_t*)tbuf, (uint8_t*)rbuf, len); } void SPI::transfern(char* buf, uint32_t len) @@ -60,7 +59,4 @@ void SPI::transfern(char* buf, uint32_t len) transfernb(buf, buf, len); } -/** - * \endcond - */ -#endif +#endif // RF24_UTILITY_MRAA_SPI_H_ diff --git a/utility/RPi/RF24_arch_config.h b/utility/RPi/RF24_arch_config.h index 1ecec48d9..b3ab61cbb 100644 --- a/utility/RPi/RF24_arch_config.h +++ b/utility/RPi/RF24_arch_config.h @@ -1,5 +1,5 @@ -#ifndef __ARCH_CONFIG_H__ -#define __ARCH_CONFIG_H__ +#ifndef RF24_UTILITY_RPI_RF24_ARCH_CONFIG_H_ +#define RF24_UTILITY_RPI_RF24_ARCH_CONFIG_H_ #define RF24_LINUX @@ -16,32 +16,33 @@ #define _SPI spi -#if defined (SPI_HAS_TRANSACTION) +#if defined(SPI_HAS_TRANSACTION) // this gets triggered as /utility/RPi/spi.h defines SPI_HAS_TRANSACTION (unless modified by end-user) #define RF24_SPI_TRANSACTIONS #endif // GCC a Arduino Missing -#define _BV(x) (1<<(x)) +#define _BV(x) (1 << (x)) #define pgm_read_word(p) (*(p)) #define pgm_read_byte(p) (*(p)) -#define pgm_read_ptr(p) (*(p)) +#define pgm_read_ptr(p) (*(p)) //typedef uint16_t prog_uint16_t; -#define PSTR(x) (x) +#define PSTR(x) (x) #define printf_P printf #define strlen_P strlen #define PROGMEM #define PRIPSTR "%s" #ifdef SERIAL_DEBUG - #define IF_SERIAL_DEBUG(x) ({x;}) + #define IF_SERIAL_DEBUG(x) ({ x; }) #else #define IF_SERIAL_DEBUG(x) #endif #define digitalWrite(pin, value) bcm2835_gpio_write(pin, value) -#define pinMode(pin, value) bcm2835_gpio_fsel(pin, value) -#define OUTPUT BCM2835_GPIO_FSEL_OUTP -#define INPUT BCM2835_GPIO_FSEL_INPT -#endif \ No newline at end of file +#define pinMode(pin, value) bcm2835_gpio_fsel(pin, value) +#define OUTPUT BCM2835_GPIO_FSEL_OUTP +#define INPUT BCM2835_GPIO_FSEL_INPT + +#endif // RF24_UTILITY_RPI_RF24_ARCH_CONFIG_H_ diff --git a/utility/RPi/compatibility.cpp b/utility/RPi/compatibility.cpp index bca533b7c..7363ec282 100644 --- a/utility/RPi/compatibility.cpp +++ b/utility/RPi/compatibility.cpp @@ -6,6 +6,6 @@ auto start = std::chrono::steady_clock::now(); uint32_t millis(void) { auto end = std::chrono::steady_clock::now(); - - return std::chrono::duration_cast(end - start).count(); + + return std::chrono::duration_cast(end - start).count(); } diff --git a/utility/RPi/compatibility.h b/utility/RPi/compatibility.h index 00fa53151..58562beac 100644 --- a/utility/RPi/compatibility.h +++ b/utility/RPi/compatibility.h @@ -1,5 +1,5 @@ -#ifndef COMPATIBLITY_H -#define COMPATIBLITY_H +#ifndef RF24_UTILITY_RPI_COMPATIBLITY_H_ +#define RF24_UTILITY_RPI_COMPATIBLITY_H_ #include #include @@ -14,4 +14,4 @@ extern uint32_t millis(void); } #endif -#endif //Compatibility.h \ No newline at end of file +#endif // RF24_UTILITY_RPI_COMPATIBLITY_H_ diff --git a/utility/RPi/includes.h b/utility/RPi/includes.h index 458f8900f..d73f5cf63 100644 --- a/utility/RPi/includes.h +++ b/utility/RPi/includes.h @@ -1,5 +1,5 @@ -#ifndef __RF24_INCLUDES_H__ -#define __RF24_INCLUDES_H__ +#ifndef RF24_UTILITY_INCLUDES_H_ +#define RF24_UTILITY_INCLUDES_H_ #define RF24_RPi @@ -9,4 +9,4 @@ #include "RPi/interrupt.h" #endif -#endif +#endif // RF24_UTILITY_INCLUDES_H_ diff --git a/utility/RPi/interrupt.cpp b/utility/RPi/interrupt.cpp index afc431044..31a5f894e 100644 --- a/utility/RPi/interrupt.cpp +++ b/utility/RPi/interrupt.cpp @@ -5,25 +5,21 @@ Interrupt functions #include "interrupt.h" #include - -int attachInterrupt(int pin, int mode, void (* function)(void)) +int attachInterrupt(int pin, int mode, void (*function)(void)) { gpioInitialise(); - return gpioSetISRFunc(pin,mode,0,(gpioISRFunc_t)function); - + return gpioSetISRFunc(pin, mode, 0, (gpioISRFunc_t)function); } int detachInterrupt(int pin) { - return gpioSetISRFunc(pin,0,0,NULL); + return gpioSetISRFunc(pin, 0, 0, NULL); } void rfNoInterrupts() { - } void rfInterrupts() { - } \ No newline at end of file diff --git a/utility/RPi/interrupt.h b/utility/RPi/interrupt.h index 589340e03..f52117b55 100644 --- a/utility/RPi/interrupt.h +++ b/utility/RPi/interrupt.h @@ -7,11 +7,10 @@ Interrupt functions #include "RF24_arch_config.h" #include -#define INT_EDGE_SETUP 0 -#define INT_EDGE_FALLING FALLING_EDGE -#define INT_EDGE_RISING RISING_EDGE -#define INT_EDGE_BOTH EITHER_EDGE - +#define INT_EDGE_SETUP 0 +#define INT_EDGE_FALLING FALLING_EDGE +#define INT_EDGE_RISING RISING_EDGE +#define INT_EDGE_BOTH EITHER_EDGE #ifdef __cplusplus extern "C" { @@ -24,12 +23,12 @@ extern "C" { * back to the user supplied function. ********************************************************************************* */ -extern int attachInterrupt(int pin, int mode, void (* function)(void)); +extern int attachInterrupt(int pin, int mode, void (*function)(void)); /* * detachInterrupt: * Pi Specific detachInterrupt. - * Will cancel the interrupt thread, close the filehandle and + * Will cancel the interrupt thread, close the filehandle and * setting wiringPi back to 'none' mode. ********************************************************************************* */ @@ -46,4 +45,4 @@ extern void rfInterrupts(); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/utility/RPi/spi.cpp b/utility/RPi/spi.cpp index 5e5dfc9eb..794931e00 100644 --- a/utility/RPi/spi.cpp +++ b/utility/RPi/spi.cpp @@ -8,7 +8,6 @@ bool bcmIsInitialized = false; SPI::SPI() { - } void SPI::begin(int busNo, uint32_t spi_speed) @@ -62,5 +61,4 @@ void SPI::chipSelect(int csn_pin) SPI::~SPI() { - -} \ No newline at end of file +} diff --git a/utility/RPi/spi.h b/utility/RPi/spi.h index 688cc50fa..895ebe4e8 100644 --- a/utility/RPi/spi.h +++ b/utility/RPi/spi.h @@ -4,22 +4,22 @@ */ /** * @file spi.h - * \cond HIDDEN_SYMBOLS * Class declaration for SPI helper files */ -#ifndef _SPI_H_INCLUDED -#define _SPI_H_INCLUDED +#ifndef RF24_UTILITY_RPI_SPI_H_ +#define RF24_UTILITY_RPI_SPI_H_ #include #include "bcm2835.h" #include "../../RF24_config.h" #define SPI_HAS_TRANSACTION -#define MSBFIRST BCM2835_SPI_BIT_ORDER_MSBFIRST +#define MSBFIRST BCM2835_SPI_BIT_ORDER_MSBFIRST #define SPI_MODE0 BCM2835_SPI_MODE0 //#define RF24_SPI_SPEED 10000000 //BCM2835_SPI_SPEED_4MHZ -class SPISettings { +class SPISettings +{ public: SPISettings(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) { @@ -34,8 +34,8 @@ class SPISettings { uint32_t clck; uint8_t border; uint8_t dmode; -private: +private: void init(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) { clck = clock; @@ -46,9 +46,9 @@ class SPISettings { friend class SPIClass; }; -class SPI { +class SPI +{ public: - SPI(); virtual ~SPI(); @@ -74,8 +74,6 @@ class SPI { static void beginTransaction(SPISettings settings); static void endTransaction(); - - }; uint8_t SPI::transfer(uint8_t _data) @@ -93,7 +91,5 @@ void SPI::transfern(char* buf, uint32_t len) { transfernb(buf, buf, len); } -/** - * \endcond - */ -#endif + +#endif // RF24_UTILITY_RPI_SPI_H_ diff --git a/utility/SPIDEV/RF24_arch_config.h b/utility/SPIDEV/RF24_arch_config.h index 0e967dc38..d17b4dc55 100644 --- a/utility/SPIDEV/RF24_arch_config.h +++ b/utility/SPIDEV/RF24_arch_config.h @@ -6,8 +6,8 @@ version 2 as published by the Free Software Foundation. */ -#ifndef __ARCH_CONFIG_H__ -#define __ARCH_CONFIG_H__ +#ifndef RF24_UTILITY_SPIDEV_RF24_ARCH_CONFIG_H_ +#define RF24_UTILITY_SPIDEV_RF24_ARCH_CONFIG_H_ #define RF24_LINUX @@ -23,46 +23,45 @@ //#define RF24_SPI_SPEED RF24_SPIDEV_SPEED -#define _BV(x) (1<<(x)) -#define _SPI spi +#define _BV(x) (1 << (x)) +#define _SPI spi //#undef SERIAL_DEBUG #ifdef SERIAL_DEBUG - #define IF_SERIAL_DEBUG(x) ({x;}) + #define IF_SERIAL_DEBUG(x) ({ x; }) #else #define IF_SERIAL_DEBUG(x) #endif // Avoid spurious warnings #if 1 - #if !defined( NATIVE ) && defined( ARDUINO ) + #if !defined(NATIVE) && defined(ARDUINO) #undef PROGMEM - #define PROGMEM __attribute__(( section(".progmem.data") )) + #define PROGMEM __attribute__((section(".progmem.data"))) #undef PSTR - #define PSTR(s) (__extension__({static const char __c[] PROGMEM = (s); &__c[0];})) + #define PSTR(s) (__extension__({static const char __c[] PROGMEM = (s); &__c[0]; })) #endif #endif typedef uint16_t prog_uint16_t; -#define PSTR(x) (x) +#define PSTR(x) (x) #define printf_P printf #define strlen_P strlen #define PROGMEM #define pgm_read_word(p) (*(p)) -#define PRIPSTR "%s" +#define PRIPSTR "%s" #define pgm_read_byte(p) (*(p)) -#define pgm_read_ptr(p) (*(p)) +#define pgm_read_ptr(p) (*(p)) // Function, constant map as a result of migrating from Arduino -#define LOW GPIO::OUTPUT_LOW -#define HIGH GPIO::OUTPUT_HIGH -#define INPUT GPIO::DIRECTION_IN -#define OUTPUT GPIO::DIRECTION_OUT +#define LOW GPIO::OUTPUT_LOW +#define HIGH GPIO::OUTPUT_HIGH +#define INPUT GPIO::DIRECTION_IN +#define OUTPUT GPIO::DIRECTION_OUT #define digitalWrite(pin, value) GPIO::write(pin, value) -#define pinMode(pin, direction) GPIO::open(pin, direction) -#define delay(milisec) __msleep(milisec) -#define delayMicroseconds(usec) __usleep(usec) -#define millis() __millis() +#define pinMode(pin, direction) GPIO::open(pin, direction) +#define delay(milisec) __msleep(milisec) +#define delayMicroseconds(usec) __usleep(usec) +#define millis() __millis() -#endif // __ARCH_CONFIG_H__ -// vim:ai:cin:sts=2 sw=2 ft=cpp +#endif // RF24_UTILITY_SPIDEV_RF24_ARCH_CONFIG_H_ diff --git a/utility/SPIDEV/compatibility.cpp b/utility/SPIDEV/compatibility.cpp index 6ba649233..6b96f6588 100644 --- a/utility/SPIDEV/compatibility.cpp +++ b/utility/SPIDEV/compatibility.cpp @@ -12,8 +12,8 @@ long long mtime, seconds, useconds; */ void __msleep(int milisec) { - struct timespec req;// = {0}; - req.tv_sec = (time_t) milisec / 1000; + struct timespec req; // = {0}; + req.tv_sec = (time_t)milisec / 1000; req.tv_nsec = (milisec % 1000) * 1000000L; //nanosleep(&req, (struct timespec *)NULL); clock_nanosleep(CLOCK_REALTIME, 0, &req, NULL); @@ -21,8 +21,8 @@ void __msleep(int milisec) void __usleep(int microsec) { - struct timespec req;// = {0}; - req.tv_sec = (time_t) microsec / 1000000; + struct timespec req; // = {0}; + req.tv_sec = (time_t)microsec / 1000000; req.tv_nsec = (microsec / 1000000) * 1000; //nanosleep(&req, (struct timespec *)NULL); clock_nanosleep(CLOCK_REALTIME, 0, &req, NULL); @@ -36,15 +36,13 @@ bool timerStarted = false; void __start_timer() { - } auto start = std::chrono::steady_clock::now(); uint32_t __millis() { + auto end = std::chrono::steady_clock::now(); - auto end = std::chrono::steady_clock::now(); - - return std::chrono::duration_cast(end - start).count(); + return std::chrono::duration_cast(end - start).count(); } diff --git a/utility/SPIDEV/compatibility.h b/utility/SPIDEV/compatibility.h index 2a2167c85..70153233e 100644 --- a/utility/SPIDEV/compatibility.h +++ b/utility/SPIDEV/compatibility.h @@ -1,19 +1,19 @@ -/* - * File: compatiblity.h - * Author: purinda +/** + * @file compatiblity.h + * @author purinda * * Created on 24 June 2012, 3:08 PM * patch for safer monotonic clock & millis() correction for 64bit LDV 2018 */ -#ifndef COMPATIBLITY_H -#define COMPATIBLITY_H +#ifndef RF24_UTILITY_SPIDEV_COMPATIBLITY_H_ +#define RF24_UTILITY_SPIDEV_COMPATIBLITY_H_ #ifdef __cplusplus extern "C" { #endif -#include // for uintXX_t types +#include // for uintXX_t types #include #include #include @@ -30,5 +30,4 @@ uint32_t __millis(); } #endif -#endif /* COMPATIBLITY_H */ - +#endif // RF24_UTILITY_SPIDEV_COMPATIBLITY_H_ diff --git a/utility/SPIDEV/gpio.cpp b/utility/SPIDEV/gpio.cpp index 1745a7b8b..a8986009d 100644 --- a/utility/SPIDEV/gpio.cpp +++ b/utility/SPIDEV/gpio.cpp @@ -57,9 +57,10 @@ void GPIO::open(int port, int DDR) } /* if (DDR == 0) - fprintf(f, "in\n"); - else printf(f, "out\n"); - */ + fprintf(f, "in\n"); + else + printf(f, "out\n"); + */ fclose(f); // Caches the GPIO descriptor; @@ -68,11 +69,11 @@ void GPIO::open(int port, int DDR) int fd = ::open(file, flags); if (fd < 0) { throw GPIOException("Can't open the GPIO"); - } else { - cache[port] = fd; // cache the fd; + } + else { + cache[port] = fd; // cache the fd; lseek(fd, SEEK_SET, 0); } - } void GPIO::close(int port) @@ -81,7 +82,7 @@ void GPIO::close(int port) i = cache.find(port); if (i != cache.end()) { close(i->second); // close the cached fd - cache.erase(i); // Delete cache entry + cache.erase(i); // Delete cache entry } // Do unexport FILE* f; @@ -102,21 +103,25 @@ int GPIO::read(int port) i = cache.find(port); if (i == cache.end()) { throw GPIOException("can't access to GPIO"); - } else { + } + else { fd = i->second; } - } else { + } + else { fd = i->second; } char c; if (lseek(fd, 0, SEEK_SET) == 0 && ::read(fd, &c, 1) == 1) { return (c == '0') ? 0 : 1; - } else { + } + else { throw GPIOException("can't access to GPIO"); } - /*FILE *f; + /* + FILE *f; char file[128]; sprintf(file, "/sys/class/gpio/gpio%d/value", port); @@ -126,7 +131,7 @@ int GPIO::read(int port) fscanf(f, "%d", &i); fclose(f); return i; -*/ + */ } void GPIO::write(int port, int value) @@ -139,10 +144,12 @@ void GPIO::write(int port, int value) i = cache.find(port); if (i == cache.end()) { throw GPIOException("can't access to GPIO"); - } else { + } + else { fd = i->second; } - } else { + } + else { fd = i->second; } @@ -154,14 +161,18 @@ void GPIO::write(int port, int value) throw GPIOException("can't access to GPIO"); } - /*FILE *f; + /* + FILE *f; char file[128]; sprintf(file, "/sys/class/gpio/gpio%d/value", port); f = fopen(file, "w"); - if (value == 0) fprintf(f, "0\n"); - else fprintf(f, "1\n"); + if (value == 0) + fprintf(f, "0\n"); + else + fprintf(f, "1\n"); - fclose(f);*/ + fclose(f); + */ } diff --git a/utility/SPIDEV/gpio.h b/utility/SPIDEV/gpio.h index cc5a7b208..c802ce6ac 100644 --- a/utility/SPIDEV/gpio.h +++ b/utility/SPIDEV/gpio.h @@ -1,52 +1,38 @@ -/* +/** * https://github.com/mrshu/GPIOlib * Copyright (c) 2011, Copyright (c) 2011 mr.Shu * All rights reserved. * * Modified on 24 June 2012, 11:06 AM - * File: gpio.h + * @file gpio.h * Author: purinda (purinda@gmail.com) * + * Class declaration for GPIO helper files */ -#ifndef H -#define H +#ifndef RF24_UTILITY_SPIDEV_GPIO_H_ +#define RF24_UTILITY_SPIDEV_GPIO_H_ #include #include #include /** Specific excpetion for SPI errors */ -class GPIOException : public std::runtime_error { +class GPIOException : public std::runtime_error +{ public: explicit GPIOException(const std::string& msg) - :std::runtime_error(msg) + : std::runtime_error(msg) { } }; -/** - * @file gpio.h - * @cond HIDDEN_SYMBOLS - * Class declaration for GPIO helper files - */ - - -/** - * Example GPIO.h file - * - * @defgroup GPIO GPIO Example - * - * See RF24_arch_config.h for additional information - * @{ - */ - typedef int GPIOfdCache_t; -class GPIO { -public: +class GPIO +{ - /* Constants */ +public: static const int DIRECTION_OUT = 1; static const int DIRECTION_IN = 0; @@ -55,30 +41,12 @@ class GPIO { GPIO(); - /** - * Similar to Arduino pinMode(pin,mode); - * @param port - * @param DDR - */ static void open(int port, int DDR); - /** - * - * @param port - */ static void close(int port); - /** - * Similar to Arduino digitalRead(pin); - * @param port - */ static int read(int port); - /** - * Similar to Arduino digitalWrite(pin,state); - * @param port - * @param value - */ static void write(int port, int value); virtual ~GPIO(); @@ -87,8 +55,5 @@ class GPIO { /* fd cache */ static std::map cache; }; -/** - * @endcond - */ -/**@}*/ -#endif /* H */ + +#endif // RF24_UTILITY_SPIDEV_GPIO_H_ diff --git a/utility/SPIDEV/includes.h b/utility/SPIDEV/includes.h index 79e5e3d0b..fd82fd5d8 100644 --- a/utility/SPIDEV/includes.h +++ b/utility/SPIDEV/includes.h @@ -1,5 +1,5 @@ -#ifndef __RF24_INCLUDES_H__ -#define __RF24_INCLUDES_H__ +#ifndef RF24_UTILITY_INCLUDES_H_ +#define RF24_UTILITY_INCLUDES_H_ #define RF24_SPIDEV @@ -8,4 +8,4 @@ #include "SPIDEV/interrupt.h" #endif -#endif +#endif // RF24_UTILITY_INCLUDES_H_ diff --git a/utility/SPIDEV/interrupt.cpp b/utility/SPIDEV/interrupt.cpp index afc431044..4893dc51f 100644 --- a/utility/SPIDEV/interrupt.cpp +++ b/utility/SPIDEV/interrupt.cpp @@ -5,25 +5,21 @@ Interrupt functions #include "interrupt.h" #include - -int attachInterrupt(int pin, int mode, void (* function)(void)) +int attachInterrupt(int pin, int mode, void (*function)(void)) { gpioInitialise(); - return gpioSetISRFunc(pin,mode,0,(gpioISRFunc_t)function); - + return gpioSetISRFunc(pin, mode, 0, (gpioISRFunc_t)function); } int detachInterrupt(int pin) { - return gpioSetISRFunc(pin,0,0,NULL); + return gpioSetISRFunc(pin, 0, 0, NULL); } void rfNoInterrupts() { - } void rfInterrupts() { - -} \ No newline at end of file +} diff --git a/utility/SPIDEV/interrupt.h b/utility/SPIDEV/interrupt.h index 589340e03..f52117b55 100644 --- a/utility/SPIDEV/interrupt.h +++ b/utility/SPIDEV/interrupt.h @@ -7,11 +7,10 @@ Interrupt functions #include "RF24_arch_config.h" #include -#define INT_EDGE_SETUP 0 -#define INT_EDGE_FALLING FALLING_EDGE -#define INT_EDGE_RISING RISING_EDGE -#define INT_EDGE_BOTH EITHER_EDGE - +#define INT_EDGE_SETUP 0 +#define INT_EDGE_FALLING FALLING_EDGE +#define INT_EDGE_RISING RISING_EDGE +#define INT_EDGE_BOTH EITHER_EDGE #ifdef __cplusplus extern "C" { @@ -24,12 +23,12 @@ extern "C" { * back to the user supplied function. ********************************************************************************* */ -extern int attachInterrupt(int pin, int mode, void (* function)(void)); +extern int attachInterrupt(int pin, int mode, void (*function)(void)); /* * detachInterrupt: * Pi Specific detachInterrupt. - * Will cancel the interrupt thread, close the filehandle and + * Will cancel the interrupt thread, close the filehandle and * setting wiringPi back to 'none' mode. ********************************************************************************* */ @@ -46,4 +45,4 @@ extern void rfInterrupts(); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/utility/SPIDEV/spi.cpp b/utility/SPIDEV/spi.cpp index 0a08a6a90..4fb0113b9 100644 --- a/utility/SPIDEV/spi.cpp +++ b/utility/SPIDEV/spi.cpp @@ -1,6 +1,6 @@ -/* - * File: spi.cpp - * Author: Purinda Gunasekara +/** + * @file spi.cpp + * @author Purinda Gunasekara * * Created on 24 June 2012, 11:00 AM * @@ -23,11 +23,10 @@ #define RF24_SPIDEV_BITS 8 SPI::SPI() - :fd(-1), _spi_speed(RF24_SPI_SPEED) + : fd(-1), _spi_speed(RF24_SPI_SPEED) { } - void SPI::begin(int busNo, uint32_t spi_speed) { @@ -138,9 +137,9 @@ uint8_t SPI::transfer(uint8_t tx) { struct spi_ioc_transfer tr; memset(&tr, 0, sizeof(tr)); - tr.tx_buf = (unsigned long) &tx; + tr.tx_buf = (unsigned long)&tx; uint8_t rx; - tr.rx_buf = (unsigned long) ℞ + tr.rx_buf = (unsigned long)℞ tr.len = sizeof(tx); tr.speed_hz = _spi_speed; //RF24_SPI_SPEED; tr.delay_usecs = 0; @@ -164,8 +163,8 @@ void SPI::transfernb(char* tbuf, char* rbuf, uint32_t len) { struct spi_ioc_transfer tr; memset(&tr, 0, sizeof(tr)); - tr.tx_buf = (unsigned long) tbuf; - tr.rx_buf = (unsigned long) rbuf; + tr.tx_buf = (unsigned long)tbuf; + tr.rx_buf = (unsigned long)rbuf; tr.len = len; tr.speed_hz = _spi_speed; //RF24_SPI_SPEED; tr.delay_usecs = 0; @@ -183,6 +182,11 @@ void SPI::transfernb(char* tbuf, char* rbuf, uint32_t len) }*/ } +void SPI::transfern(char* buf, uint32_t len) +{ + transfernb(buf, buf, len); +} + SPI::~SPI() { if (this->fd >= 0) { diff --git a/utility/SPIDEV/spi.h b/utility/SPIDEV/spi.h index 0c277d499..35efe2d7b 100644 --- a/utility/SPIDEV/spi.h +++ b/utility/SPIDEV/spi.h @@ -1,93 +1,51 @@ -/* - * File: spi.h - * Author: Purinda Gunasekara - * - * Created on 24 June 2012, 11:00 AM - */ - -#ifndef SPI_H -#define SPI_H - /** * @file spi.h - * \cond HIDDEN_SYMBOLS + * @author Purinda Gunasekara + * + * Created on 24 June 2012, 11:00 AM + * * Class declaration for SPI helper files */ -/** -* Example GPIO.h file -* -* @defgroup SPI SPI Example -* -* See RF24_arch_config.h for additional information -* @{ -*/ +#ifndef RF24_UTILITY_SPIDEV_SPI_H_ +#define RF24_UTILITY_SPIDEV_SPI_H_ #include #include -#include "../../RF24_config.h" +#include "../../RF24_config.h" // This is cyclical and should be fixed /** Specific excpetion for SPI errors */ -class SPIException : public std::runtime_error { +class SPIException : public std::runtime_error +{ public: explicit SPIException(const std::string& msg) - :std::runtime_error(msg) + : std::runtime_error(msg) { } }; -class SPI { +class SPI +{ public: - - /** - * SPI constructor - */ SPI(); - /** - * Start SPI - */ void begin(int busNo, uint32_t spi_speed = RF24_SPI_SPEED); - /** - * Transfer a single byte - * @param tx Byte to send - * @return Data returned via spi - */ uint8_t transfer(uint8_t tx); - /** - * Transfer a buffer of data - * @param tbuf Transmit buffer - * @param rbuf Receive buffer - * @param len Length of the data - */ void transfernb(char* tbuf, char* rbuf, uint32_t len); - /** - * Transfer a buffer of data without an rx buffer - * @param buf Pointer to a buffer of data - * @param len Length of the data - */ - void transfern(char* buf, uint32_t len) - { - transfernb(buf, buf, len); - } + void transfern(char* buf, uint32_t len); ~SPI(); private: - int fd; uint32_t _spi_speed; bool spiIsInitialized = false; void init(uint32_t spi_speed = RF24_SPI_SPEED); }; -/** - * \endcond - */ -/*@}*/ -#endif /* SPI_H */ +#endif // RF24_UTILITY_SPIDEV_SPI_H_ diff --git a/utility/Teensy/RF24_arch_config.h b/utility/Teensy/RF24_arch_config.h index 19177a4bc..7ca162b45 100644 --- a/utility/Teensy/RF24_arch_config.h +++ b/utility/Teensy/RF24_arch_config.h @@ -1,5 +1,5 @@ - - +#ifndef RF24_UTILITY_TEENSY_RF24_ARCH_CONFIG_H_ +#define RF24_UTILITY_TEENSY_RF24_ARCH_CONFIG_H_ #if ARDUINO < 100 #include @@ -22,9 +22,11 @@ #define printf Serial.printf #ifdef SERIAL_DEBUG - #define IF_SERIAL_DEBUG(x) ({x;}) + #define IF_SERIAL_DEBUG(x) ({ x; }) #else #define IF_SERIAL_DEBUG(x) #endif #define PRIPSTR "%s" + +#endif // RF24_UTILITY_TEENSY_RF24_ARCH_CONFIG_H_ diff --git a/utility/Template/RF24_arch_config.h b/utility/Template/RF24_arch_config.h index 50e1b4d25..54e0ad694 100644 --- a/utility/Template/RF24_arch_config.h +++ b/utility/Template/RF24_arch_config.h @@ -4,7 +4,6 @@ * 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. - * */ /** @@ -16,13 +15,11 @@ * Example of RF24_arch_config.h for RF24 portability * * @defgroup Porting_General Porting: General - * * @{ */ - -#ifndef __ARCH_CONFIG_H__ -#define __ARCH_CONFIG_H__ +#ifndef RF24_UTILITY_TEMPLATE_RF24_ARCH_CONFIG_H_ +#define RF24_UTILITY_TEMPLATE_RF24_ARCH_CONFIG_H_ #define RF24_LINUX @@ -37,46 +34,43 @@ #include #define _BV(x) (1 << (x)) -#define _SPI spi +#define _SPI spi #undef SERIAL_DEBUG #ifdef SERIAL_DEBUG - #define IF_SERIAL_DEBUG(x) ({x;}) + #define IF_SERIAL_DEBUG(x) ({ x; }) #else #define IF_SERIAL_DEBUG(x) #endif // Avoid spurious warnings -#if 1 - #if !defined(NATIVE) && defined(ARDUINO) - #undef PROGMEM - #define PROGMEM __attribute__(( section(".progmem.data") )) - #undef PSTR - #define PSTR(s) (__extension__({static const char __c[] PROGMEM = (s); &__c[0];})) - #endif +#if !defined(NATIVE) && defined(ARDUINO) + #undef PROGMEM + #define PROGMEM __attribute__((section(".progmem.data"))) + #undef PSTR + #define PSTR(s) (__extension__({static const char __c[] PROGMEM = (s); &__c[0]; })) #endif typedef uint16_t prog_uint16_t; -#define PSTR(x) (x) +#define PSTR(x) (x) #define printf_P printf #define strlen_P strlen #define PROGMEM #define pgm_read_word(p) (*(p)) -#define PRIPSTR "%s" +#define PRIPSTR "%s" #define pgm_read_byte(p) (*(p)) // Function, constant map as a result of migrating from Arduino -#define LOW GPIO::OUTPUT_LOW -#define HIGH GPIO::OUTPUT_HIGH -#define INPUT GPIO::DIRECTION_IN -#define OUTPUT GPIO::DIRECTION_OUT +#define LOW GPIO::OUTPUT_LOW +#define HIGH GPIO::OUTPUT_HIGH +#define INPUT GPIO::DIRECTION_IN +#define OUTPUT GPIO::DIRECTION_OUT #define digitalWrite(pin, value) GPIO::write(pin, value) -#define pinMode(pin, direction) GPIO::open(pin, direction) -#define delay(milisec) __msleep(milisec) -#define delayMicroseconds(usec) __usleep(usec) -#define millis() __millis() - -#endif // __ARCH_CONFIG_H__ - +#define pinMode(pin, direction) GPIO::open(pin, direction) +#define delay(milisec) __msleep(milisec) +#define delayMicroseconds(usec) __usleep(usec) +#define millis() __millis() /**@}*/ + +#endif // RF24_UTILITY_TEMPLATE_RF24_ARCH_CONFIG_H_ diff --git a/utility/Template/compatibility.h b/utility/Template/compatibility.h index 6c53a7c88..1441302e3 100644 --- a/utility/Template/compatibility.h +++ b/utility/Template/compatibility.h @@ -1,10 +1,3 @@ -/* - * File: compatiblity.h - * Author: purinda - * - * Created on 24 June 2012, 3:08 PM - */ - /** * @file compatibility.h * Class declaration for SPI helper files @@ -14,12 +7,11 @@ * Example of compatibility.h class declaration for timing functions portability * * @defgroup Porting_Timing Porting: Timing - * * @{ */ -#ifndef COMPATIBLITY_H -#define COMPATIBLITY_H +#ifndef RF24_UTILITY_TEMPLATE_COMPATIBLITY_H_ +#define RF24_UTILITY_TEMPLATE_COMPATIBLITY_H_ #ifdef __cplusplus extern "C" { @@ -37,10 +29,10 @@ void __start_timer(); long __millis(); -#ifdef __cplusplus +#ifdef __cplusplus } #endif -#endif /* COMPATIBLITY_H */ +/**@}*/ -/**@}*/ \ No newline at end of file +#endif // RF24_UTILITY_TEMPLATE_COMPATIBLITY_H_ diff --git a/utility/Template/gpio.h b/utility/Template/gpio.h index 1f03a0ab3..dd03d5c5c 100644 --- a/utility/Template/gpio.h +++ b/utility/Template/gpio.h @@ -1,5 +1,3 @@ - - /** * @file gpio.h * Class declaration for SPI helper files @@ -9,9 +7,10 @@ * Example of gpio.h class declaration for GPIO portability * * @defgroup Porting_GPIO Porting: GPIO - * * @{ */ +#ifndef RF24_UTILITY_TEMPLATE_GPIO_H_ +#define RF24_UTILITY_TEMPLATE_GPIO_H_ #include @@ -20,6 +19,7 @@ class GPIO #endif { + public: /* Constants */ static const int DIRECTION_OUT = 1; @@ -57,9 +57,11 @@ class GPIO static void write(int port, int value); #ifndef DOXYGEN_FORCED -// exclude this line from the docs to prevent warnings docs generators - virtual ~ GPIO(); + // exclude this line from the docs to prevent warnings docs generators + virtual ~GPIO(); #endif }; /**@}*/ + +#endif // RF24_UTILITY_TEMPLATE_GPIO_H_ diff --git a/utility/Template/includes.h b/utility/Template/includes.h index 04c67a7a8..064bfe2a3 100644 --- a/utility/Template/includes.h +++ b/utility/Template/includes.h @@ -7,12 +7,11 @@ * Example of includes.h for RF24 Linux portability * * @defgroup Porting_Includes Porting: Includes - * * @{ */ -#ifndef __RF24_INCLUDES_H__ -#define __RF24_INCLUDES_H__ +#ifndef RF24_UTILITY_INCLUDES_H_ +#define RF24_UTILITY_INCLUDES_H_ /** * Define a specific platform for this configuration @@ -24,6 +23,6 @@ */ #include "BBB/RF24_arch_config.h" -#endif +/**@}*/ -/**@}*/ \ No newline at end of file +#endif // RF24_UTILITY_INCLUDES_H_ diff --git a/utility/Template/spi.h b/utility/Template/spi.h index d0813a120..3f5abada2 100644 --- a/utility/Template/spi.h +++ b/utility/Template/spi.h @@ -7,9 +7,11 @@ * Example of spi.h class declaration for SPI portability * * @defgroup Porting_SPI Porting: SPI - * * @{ */ +#ifndef RF24_UTILITY_TEMPLATE_SPI_H_ +#define RF24_UTILITY_TEMPLATE_SPI_H_ + #include #include #include @@ -29,58 +31,59 @@ using namespace std; class SPI #endif { -public: - /** +public: + /** * SPI constructor */ - SPI(); + SPI(); - /** + /** * Start SPI */ - void begin(int busNo); + void begin(int busNo); - /** + /** * Transfer a single byte * @param tx_ Byte to send * @return Data returned via spi */ - uint8_t transfer(uint8_t tx_); + uint8_t transfer(uint8_t tx_); - /** + /** * Transfer a buffer of data * @param tbuf Transmit buffer * @param rbuf Receive buffer * @param len Length of the data */ - void transfernb(char* tbuf, char* rbuf, uint32_t len); + void transfernb(char* tbuf, char* rbuf, uint32_t len); - /** + /** * Transfer a buffer of data without an rx buffer * @param buf Pointer to a buffer of data * @param len Length of the data */ - void transfern(char* buf, uint32_t len); + void transfern(char* buf, uint32_t len); #ifndef DOXYGEN_FORCED -// exclude this line from the docs to prevent warnings docs generators - virtual ~ SPI(); + // exclude this line from the docs to prevent warnings docs generators + virtual ~SPI(); #endif -private: - - /** Default SPI device */ - string device; - /** SPI Mode set */ - uint8_t mode; - /** word size*/ - uint8_t bits; - /** Set SPI speed*/ - uint32_t speed; - int fd; - void init(); +private: + /** Default SPI device */ + string device; + /** SPI Mode set */ + uint8_t mode; + /** word size*/ + uint8_t bits; + /** Set SPI speed*/ + uint32_t speed; + int fd; + void init(); }; /**@}*/ + +#endif // RF24_UTILITY_TEMPLATE_SPI_H_ diff --git a/utility/pigpio/RF24_arch_config.h b/utility/pigpio/RF24_arch_config.h index 4302c9ba5..b143d66e0 100644 --- a/utility/pigpio/RF24_arch_config.h +++ b/utility/pigpio/RF24_arch_config.h @@ -7,67 +7,67 @@ */ #ifndef __ARCH_CONFIG_H__ -#define __ARCH_CONFIG_H__ + #define __ARCH_CONFIG_H__ -#define RF24_LINUX + #define RF24_LINUX -#include -#include "spi.h" -#include "gpio.h" -#include "compatibility.h" -#include -#include -#include -#include -#include + #include + #include "spi.h" + #include "gpio.h" + #include "compatibility.h" + #include + #include + #include + #include + #include //#define RF24_SPI_SPEED RF24_SPIDEV_SPEED -#define _BV(x) (1<<(x)) -#define _SPI spi + #define _BV(x) (1 << (x)) + #define _SPI spi -//#undef SERIAL_DEBUG -#ifdef SERIAL_DEBUG - #define IF_SERIAL_DEBUG(x) ({x;}) -#else - #define IF_SERIAL_DEBUG(x) -#endif + //#undef SERIAL_DEBUG + #ifdef SERIAL_DEBUG + #define IF_SERIAL_DEBUG(x) ({ x; }) + #else + #define IF_SERIAL_DEBUG(x) + #endif + + // Avoid spurious warnings + #if 1 + #if !defined(NATIVE) && defined(ARDUINO) + #undef PROGMEM + #define PROGMEM __attribute__((section(".progmem.data"))) + #undef PSTR + #define PSTR(s) (__extension__({static const char __c[] PROGMEM = (s); &__c[0]; })) + #endif + #endif -// Avoid spurious warnings -#if 1 - #if !defined( NATIVE ) && defined( ARDUINO ) - #undef PROGMEM - #define PROGMEM __attribute__(( section(".progmem.data") )) - #undef PSTR - #define PSTR(s) (__extension__({static const char __c[] PROGMEM = (s); &__c[0];})) + #if RF24_SPI_SPEED > 1000000 + #undef RF24_SPI_SPEED + #define RF24_SPI_SPEED 1000000 #endif -#endif -#if RF24_SPI_SPEED > 1000000 - #undef RF24_SPI_SPEED - #define RF24_SPI_SPEED 1000000 -#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" -#define pgm_read_byte(p) (*(p)) -#define pgm_read_ptr(p) (*(p)) + #define PSTR(x) (x) + #define printf_P printf + #define strlen_P strlen + #define PROGMEM + #define pgm_read_word(p) (*(p)) + #define PRIPSTR "%s" + #define pgm_read_byte(p) (*(p)) + #define pgm_read_ptr(p) (*(p)) -// Function, constant map as a result of migrating from Arduino -#define LOW GPIO::OUTPUT_LOW -#define HIGH GPIO::OUTPUT_HIGH -#define INPUT GPIO::DIRECTION_IN -#define OUTPUT GPIO::DIRECTION_OUT -#define digitalWrite(pin, value) GPIO::write(pin, value) -#define pinMode(pin, direction) GPIO::open(pin, direction) -#define delay(milisec) __msleep(milisec) -#define delayMicroseconds(usec) __usleep(usec) -#define millis() __millis() + // Function, constant map as a result of migrating from Arduino + #define LOW GPIO::OUTPUT_LOW + #define HIGH GPIO::OUTPUT_HIGH + #define INPUT GPIO::DIRECTION_IN + #define OUTPUT GPIO::DIRECTION_OUT + #define digitalWrite(pin, value) GPIO::write(pin, value) + #define pinMode(pin, direction) GPIO::open(pin, direction) + #define delay(milisec) __msleep(milisec) + #define delayMicroseconds(usec) __usleep(usec) + #define millis() __millis() #endif // __ARCH_CONFIG_H__ // vim:ai:cin:sts=2 sw=2 ft=cpp diff --git a/utility/pigpio/compatibility.cpp b/utility/pigpio/compatibility.cpp index 6ba649233..c4e0e3355 100644 --- a/utility/pigpio/compatibility.cpp +++ b/utility/pigpio/compatibility.cpp @@ -12,8 +12,8 @@ long long mtime, seconds, useconds; */ void __msleep(int milisec) { - struct timespec req;// = {0}; - req.tv_sec = (time_t) milisec / 1000; + struct timespec req; // = {0}; + req.tv_sec = (time_t)milisec / 1000; req.tv_nsec = (milisec % 1000) * 1000000L; //nanosleep(&req, (struct timespec *)NULL); clock_nanosleep(CLOCK_REALTIME, 0, &req, NULL); @@ -21,8 +21,8 @@ void __msleep(int milisec) void __usleep(int microsec) { - struct timespec req;// = {0}; - req.tv_sec = (time_t) microsec / 1000000; + struct timespec req; // = {0}; + req.tv_sec = (time_t)microsec / 1000000; req.tv_nsec = (microsec / 1000000) * 1000; //nanosleep(&req, (struct timespec *)NULL); clock_nanosleep(CLOCK_REALTIME, 0, &req, NULL); @@ -36,7 +36,6 @@ bool timerStarted = false; void __start_timer() { - } auto start = std::chrono::steady_clock::now(); @@ -44,7 +43,7 @@ auto start = std::chrono::steady_clock::now(); uint32_t __millis() { - auto end = std::chrono::steady_clock::now(); + auto end = std::chrono::steady_clock::now(); - return std::chrono::duration_cast(end - start).count(); + return std::chrono::duration_cast(end - start).count(); } diff --git a/utility/pigpio/compatibility.h b/utility/pigpio/compatibility.h index 2a2167c85..fff69d2a6 100644 --- a/utility/pigpio/compatibility.h +++ b/utility/pigpio/compatibility.h @@ -13,7 +13,7 @@ extern "C" { #endif -#include // for uintXX_t types +#include // for uintXX_t types #include #include #include @@ -30,5 +30,4 @@ uint32_t __millis(); } #endif -#endif /* COMPATIBLITY_H */ - +#endif /* COMPATIBLITY_H */ diff --git a/utility/pigpio/gpio.cpp b/utility/pigpio/gpio.cpp index 2e521fdd7..2634d57ec 100644 --- a/utility/pigpio/gpio.cpp +++ b/utility/pigpio/gpio.cpp @@ -9,7 +9,6 @@ bool initialized = 0; GPIO::GPIO() { - } GPIO::~GPIO() @@ -19,7 +18,7 @@ GPIO::~GPIO() void GPIO::open(int port, int DDR) { - if(!initialized){ + if (!initialized) { gpioInitialise(); } initialized = true; @@ -28,12 +27,11 @@ void GPIO::open(int port, int DDR) void GPIO::close(int port) { - } int GPIO::read(int port) { - return gpioRead( port ); + return gpioRead(port); } void GPIO::write(int port, int value) diff --git a/utility/pigpio/gpio.h b/utility/pigpio/gpio.h index d625fdc03..5dea0ec29 100644 --- a/utility/pigpio/gpio.h +++ b/utility/pigpio/gpio.h @@ -10,10 +10,11 @@ #include /** Specific excpetion for SPI errors */ -class GPIOException : public std::runtime_error { +class GPIOException : public std::runtime_error +{ public: explicit GPIOException(const std::string& msg) - :std::runtime_error(msg) + : std::runtime_error(msg) { } }; @@ -24,7 +25,6 @@ class GPIOException : public std::runtime_error { * Class declaration for GPIO helper files */ - /** * Example GPIO.h file * @@ -34,10 +34,9 @@ class GPIOException : public std::runtime_error { * @{ */ - -class GPIO { +class GPIO +{ public: - /* Constants */ static const int DIRECTION_OUT = 1; static const int DIRECTION_IN = 0; @@ -76,10 +75,9 @@ class GPIO { virtual ~GPIO(); private: - }; /** * @endcond */ /**@}*/ -#endif /* H */ +#endif /* H */ diff --git a/utility/pigpio/interrupt.cpp b/utility/pigpio/interrupt.cpp index 47aa0af43..3b970c375 100644 --- a/utility/pigpio/interrupt.cpp +++ b/utility/pigpio/interrupt.cpp @@ -5,25 +5,21 @@ #include "interrupt.h" #include - -int attachInterrupt(int pin, int mode, void (* function)(void)) +int attachInterrupt(int pin, int mode, void (*function)(void)) { gpioInitialise(); - return gpioSetISRFunc(pin,mode,0,(gpioISRFunc_t)function); - + return gpioSetISRFunc(pin, mode, 0, (gpioISRFunc_t)function); } int detachInterrupt(int pin) { - return gpioSetISRFunc(pin,0,0,NULL); + return gpioSetISRFunc(pin, 0, 0, NULL); } void rfNoInterrupts() { - } void rfInterrupts() { - } \ No newline at end of file diff --git a/utility/pigpio/interrupt.h b/utility/pigpio/interrupt.h index f5f950d83..fb2527ac0 100644 --- a/utility/pigpio/interrupt.h +++ b/utility/pigpio/interrupt.h @@ -12,11 +12,10 @@ see #include "RF24_arch_config.h" #include -#define INT_EDGE_SETUP 0 -#define INT_EDGE_FALLING FALLING_EDGE -#define INT_EDGE_RISING RISING_EDGE -#define INT_EDGE_BOTH EITHER_EDGE - +#define INT_EDGE_SETUP 0 +#define INT_EDGE_FALLING FALLING_EDGE +#define INT_EDGE_RISING RISING_EDGE +#define INT_EDGE_BOTH EITHER_EDGE #ifdef __cplusplus extern "C" { @@ -29,7 +28,7 @@ extern "C" { * back to the user supplied function. ********************************************************************************* */ -extern int attachInterrupt(int pin, int mode, void (* function)(void)); +extern int attachInterrupt(int pin, int mode, void (*function)(void)); /* * detachInterrupt: diff --git a/utility/pigpio/spi.cpp b/utility/pigpio/spi.cpp index 839e96f4c..3a962a96c 100644 --- a/utility/pigpio/spi.cpp +++ b/utility/pigpio/spi.cpp @@ -5,12 +5,10 @@ #include "spi.h" #include - SPI::SPI() { } - void SPI::begin(int busNo, uint32_t spi_speed) { if (this->spiIsInitialized) { @@ -23,7 +21,6 @@ void SPI::begin(int busNo, uint32_t spi_speed) void SPI::init(uint32_t speed) { - } uint8_t SPI::transfer(char tx) @@ -40,6 +37,4 @@ void SPI::transfernb(char* tbuf, char* rbuf, uint32_t len) SPI::~SPI() { - } - diff --git a/utility/pigpio/spi.h b/utility/pigpio/spi.h index d738e69f5..8db0e8755 100644 --- a/utility/pigpio/spi.h +++ b/utility/pigpio/spi.h @@ -3,7 +3,7 @@ */ #ifndef SPI_H -#define SPI_H +#define SPI_H /** * @file spi.h @@ -26,18 +26,19 @@ #include "../../RF24_config.h" /** Specific excpetion for SPI errors */ -class SPIException : public std::runtime_error { +class SPIException : public std::runtime_error +{ public: explicit SPIException(const std::string& msg) - :std::runtime_error(msg) + : std::runtime_error(msg) { } }; -class SPI { +class SPI +{ public: - /** * SPI constructor */ @@ -76,16 +77,13 @@ class SPI { ~SPI(); private: - unsigned spiHandle; bool spiIsInitialized = false; void init(uint32_t spi_speed); - - }; /** * \endcond */ /*@}*/ -#endif /* SPI_H */ +#endif /* SPI_H */ diff --git a/utility/rp2/RF24_arch_config.h b/utility/rp2/RF24_arch_config.h index 13c16aa49..a06d230b0 100644 --- a/utility/rp2/RF24_arch_config.h +++ b/utility/rp2/RF24_arch_config.h @@ -13,8 +13,8 @@ * General defines and includes for RF24 using The Pico SDK */ -#ifndef __ARCH_CONFIG_H__ -#define __ARCH_CONFIG_H__ +#ifndef RF24_UTILITY_RP2_RF24_ARCH_CONFIG_H_ +#define RF24_UTILITY_RP2_RF24_ARCH_CONFIG_H_ #include "spi.h" #include "gpio.h" @@ -24,39 +24,37 @@ #define RF24_RP2 #define _BV(x) (1 << (x)) -#define _SPI SPI +#define _SPI SPI #define RF24_SPI_PTR static SPI spi; #ifdef SERIAL_DEBUG - #define IF_SERIAL_DEBUG(x) ({x;}) + #define IF_SERIAL_DEBUG(x) ({ x; }) #else #define IF_SERIAL_DEBUG(x) #endif typedef uint16_t prog_uint16_t; -#define PSTR(x) (x) +#define PSTR(x) (x) #define printf_P printf #define strlen_P strlen #define PROGMEM #define pgm_read_word(p) (*(p)) -#define PRIPSTR "%s" +#define PRIPSTR "%s" #define pgm_read_byte(p) (*(p)) #define pgm_read_ptr(p) (*(p)) // Function, constant map as a result of migrating from Arduino -#define LOW GPIO::OUTPUT_LOW -#define HIGH GPIO::OUTPUT_HIGH -#define INPUT GPIO::DIRECTION_IN -#define OUTPUT GPIO::DIRECTION_OUT +#define LOW GPIO::OUTPUT_LOW +#define HIGH GPIO::OUTPUT_HIGH +#define INPUT GPIO::DIRECTION_IN +#define OUTPUT GPIO::DIRECTION_OUT #define digitalWrite(pin, value) GPIO::write(pin, value) -#define pinMode(pin, direction) GPIO::open(pin, direction) -#define delay(milisec) sleep_ms(milisec) -#define delayMicroseconds(usec) sleep_us(usec) -#define millis() to_ms_since_boot(get_absolute_time()) +#define pinMode(pin, direction) GPIO::open(pin, direction) +#define delay(milisec) sleep_ms(milisec) +#define delayMicroseconds(usec) sleep_us(usec) +#define millis() to_ms_since_boot(get_absolute_time()) -#endif // __ARCH_CONFIG_H__ - -/**@}*/ +#endif // RF24_UTILITY_RP2_RF24_ARCH_CONFIG_H_ diff --git a/utility/rp2/gpio.cpp b/utility/rp2/gpio.cpp index b6d11d4fe..4b3132e12 100644 --- a/utility/rp2/gpio.cpp +++ b/utility/rp2/gpio.cpp @@ -4,20 +4,24 @@ GPIO::GPIO() { } -void GPIO::open(int port, int DDR) { +void GPIO::open(int port, int DDR) +{ gpio_init(port); gpio_set_dir(port, DDR); } -void GPIO::close(int port) { +void GPIO::close(int port) +{ gpio_init(port); } -int GPIO::read(int port) { +int GPIO::read(int port) +{ return gpio_get(port); } -void GPIO::write(int port, int value) { +void GPIO::write(int port, int value) +{ gpio_put(port, value); } diff --git a/utility/rp2/gpio.h b/utility/rp2/gpio.h index 3ef265f64..262a92d27 100644 --- a/utility/rp2/gpio.h +++ b/utility/rp2/gpio.h @@ -2,21 +2,16 @@ * @file gpio.h * Class declaration for SPI helper files */ - -/** - * Example of gpio.h class declaration for GPIO portability - * - * @defgroup Porting_GPIO Porting: GPIO - * - * @{ - */ +#ifndef RF24_UTILITY_RP2_GPIO_H_ +#define RF24_UTILITY_RP2_GPIO_H_ #include #include "pico/stdlib.h" -class GPIO { +class GPIO +{ + public: - /* Constants */ static const int DIRECTION_OUT = 1; static const int DIRECTION_IN = 0; @@ -25,33 +20,15 @@ class GPIO { GPIO(); - /** - * Similar to Arduino pinMode(pin,mode); - * @param port - * @param DDR - */ static void open(int port, int DDR); - /** - * - * @param port - */ static void close(int port); - /** - * Similar to Arduino digitalRead(pin); - * @param port - */ static int read(int port); - /** - * Similar to Arduino digitalWrite(pin,state); - * @param port - * @param value - */ static void write(int port, int value); - virtual ~ GPIO(); + virtual ~GPIO(); }; -/**@}*/ +#endif // RF24_UTILITY_RP2_GPIO_H_ diff --git a/utility/rp2/spi.h b/utility/rp2/spi.h index 4c545a692..2339b928f 100644 --- a/utility/rp2/spi.h +++ b/utility/rp2/spi.h @@ -2,25 +2,26 @@ * @file spi.h * Class declaration for SPI wrapping the Pico SDK */ +#ifndef RF24_UTILITY_RP2_SPI_H_ +#define RF24_UTILITY_RP2_SPI_H_ + #include #include "pico/stdlib.h" #include "hardware/spi.h" #define RF24_SPI_BYTE_SIZE 8 -#define RF24_SPI_ENDIAN SPI_MSB_FIRST -#define RF24_SPI_CPHA SPI_CPHA_0 -#define RF24_SPI_CPOL SPI_CPOL_0 +#define RF24_SPI_ENDIAN SPI_MSB_FIRST +#define RF24_SPI_CPHA SPI_CPHA_0 +#define RF24_SPI_CPOL SPI_CPOL_0 // this SPI class uses beginTransaction() & endTransaction() to // implement spi_init() & spi_deinit() #define SPI_HAS_TRANSACTION 1 -class SPI { -public: +class SPI +{ - /** - * SPI constructor - */ +public: SPI(); /** @@ -48,44 +49,22 @@ class SPI { */ static void begin(spi_inst_t* hw_id, uint8_t _sck, uint8_t _tx, uint8_t _rx); - /** - * Transfer a single byte - * @param tx_ Byte to send - * @return Data returned via spi - */ static uint8_t transfer(uint8_t tx_); - /** - * Transfer a buffer of data - * @param tbuf Transmit buffer - * @param rbuf Receive buffer - * @param len Length of the data - */ static void transfernb(const uint8_t* tbuf, uint8_t* rbuf, uint32_t len); - /** - * Transfer a buffer of data without an rx buffer - * @param buf Pointer to a buffer of data - * @param len Length of the data - */ static void transfern(const uint8_t* buf, uint32_t len); - /** - * init the SPI bus (using hw_id passed to begin()) - * @param _spi_speed The frequency to use for SPI transactions with the radio. - */ static void beginTransaction(uint32_t _spi_speed); /** deinit the SPI bus (using hw_id passed to begin()) */ static void endTransaction(); - virtual ~ SPI(); + virtual ~SPI(); private: - /** the ID of the hardware driven SPI bus */ static spi_inst_t* _hw_id; - }; -/**@}*/ +#endif // RF24_UTILITY_RP2_SPI_H_ diff --git a/utility/wiringPi/RF24_arch_config.h b/utility/wiringPi/RF24_arch_config.h index a60214ac1..321e61269 100644 --- a/utility/wiringPi/RF24_arch_config.h +++ b/utility/wiringPi/RF24_arch_config.h @@ -6,8 +6,8 @@ version 2 as published by the Free Software Foundation. */ -#ifndef __ARCH_CONFIG_H__ -#define __ARCH_CONFIG_H__ +#ifndef RF24_UTILITY_WIRINGPI_RF24_ARCH_CONFIG_H_ +#define RF24_UTILITY_WIRINGPI_RF24_ARCH_CONFIG_H_ #define RF24_LINUX @@ -20,36 +20,32 @@ #include #include -#define _BV(x) (1<<(x)) -#define _SPI spi +#define _BV(x) (1 << (x)) +#define _SPI spi #undef SERIAL_DEBUG #ifdef SERIAL_DEBUG - #define IF_SERIAL_DEBUG(x) ({x;}) + #define IF_SERIAL_DEBUG(x) ({ x; }) #else #define IF_SERIAL_DEBUG(x) #endif // Avoid spurious warnings -#if 1 - #if !defined( NATIVE ) && defined( ARDUINO ) - #undef PROGMEM - #define PROGMEM __attribute__(( section(".progmem.data") )) - #undef PSTR - #define PSTR(s) (__extension__({static const char __c[] PROGMEM = (s); &__c[0];})) - #endif +#if !defined(NATIVE) && defined(ARDUINO) + #undef PROGMEM + #define PROGMEM __attribute__((section(".progmem.data"))) + #undef PSTR + #define PSTR(s) (__extension__({static const char __c[] PROGMEM = (s); &__c[0]; })) #endif typedef uint16_t prog_uint16_t; -#define PSTR(x) (x) +#define PSTR(x) (x) #define printf_P printf #define strlen_P strlen #define PROGMEM #define pgm_read_word(p) (*(p)) -#define PRIPSTR "%s" +#define PRIPSTR "%s" #define pgm_read_byte(p) (*(p)) -#define pgm_read_ptr(p) (*(p)) -#endif // __ARCH_CONFIG_H__ +#define pgm_read_ptr(p) (*(p)) - -/*@}*/ +#endif // RF24_UTILITY_WIRINGPI_RF24_ARCH_CONFIG_H_ diff --git a/utility/wiringPi/includes.h b/utility/wiringPi/includes.h index b11c94a1b..a64262faf 100644 --- a/utility/wiringPi/includes.h +++ b/utility/wiringPi/includes.h @@ -3,17 +3,8 @@ * Configuration defines for RF24/Linux */ -/** -* Example of includes.h for RF24 Linux portability -* -* @defgroup Porting_Includes Porting: Includes -* -* -* @{ -*/ - -#ifndef __RF24_INCLUDES_H__ -#define __RF24_INCLUDES_H__ +#ifndef RF24_UTILITY_INCLUDES_H_ +#define RF24_UTILITY_INCLUDES_H_ /** * Define RF24_WIRINGPI configuration for RaspberryPi platform @@ -25,5 +16,4 @@ */ #include "wiringPi/RF24_arch_config.h" -#endif -/*@}*/ \ No newline at end of file +#endif // RF24_UTILITY_INCLUDES_H_ diff --git a/utility/wiringPi/spi.cpp b/utility/wiringPi/spi.cpp index eb59ae79c..d6abd4d8f 100644 --- a/utility/wiringPi/spi.cpp +++ b/utility/wiringPi/spi.cpp @@ -19,9 +19,9 @@ #include #include -#define RF24_SPI_CHANNEL 0 +#define RF24_SPI_CHANNEL 0 -SPI::SPI():fd(-1) +SPI::SPI() : fd(-1) { printf("wiringPi RF24 DRIVER\n"); } @@ -34,7 +34,8 @@ void SPI::begin(int csn_pin, uint32_t spi_speed) printf("Cannot configure the SPI device!\n"); fflush(stdout); abort(); - } else { + } + else { printf("Configured SPI fd: %d - pin: %d\n", fd, csn_pin); } } @@ -57,7 +58,7 @@ void SPI::transfern(char* buf, uint32_t len) { printf("transfern(tx: %s)\n", buf); - if (wiringPiSPIDataRW(RF24_SPI_CHANNEL, (uint8_t*) buf, len) < 0) { + if (wiringPiSPIDataRW(RF24_SPI_CHANNEL, (uint8_t*)buf, len) < 0) { printf("transfern(): Cannot send data %s\n", strerror(errno)); fflush(stdout); abort(); diff --git a/utility/wiringPi/spi.h b/utility/wiringPi/spi.h index 8083ad03b..efafce09c 100644 --- a/utility/wiringPi/spi.h +++ b/utility/wiringPi/spi.h @@ -3,62 +3,30 @@ * Class declaration for SPI helper files */ -#ifndef SPI_H -#define SPI_H - -/** -* Example of spi.h class declaration for SPI portability -* -* @defgroup Porting_SPI Porting: SPI -* -* @{ -*/ +#ifndef RF24_UTILITY_WIRINGPI_SPI_H_ +#define RF24_UTILITY_WIRINGPI_SPI_H_ #include #include -#include "../../RF24_config.h" +#include "../../RF24_config.h" // This is cyclical and should be fixed using namespace std; -class SPI { +class SPI +{ + public: - /** - * SPI default constructor - */ SPI(); - /** - * Start SPI communication - * @param pin used for SPI - */ void begin(int csn_pin, uint32_t spi_speed = RF24_SPI_SPEED); - /** - * Transfer a single byte of data - * @param tx Byte to send - * @return Data returned via spi - */ uint8_t transfer(uint8_t); - /** - * Transfer a buffer of data using rx and tx buffer - * @param tbuf Transmit buffer - * @param rbuf Receive buffer - * @param len Length of the data - */ void transfernb(char*, char*, uint32_t); - /** - * Transfer a buffer of data without using an rx buffer - * @param buf Pointer to a buffer of data - * @param len Length of the data - */ void transfern(char*, const uint32_t); - /** - * SPI destructor - */ virtual ~SPI(); private: @@ -67,6 +35,4 @@ class SPI { uint8_t msgByte; }; -/*@}*/ -#endif /* SPI_H */ - +#endif // RF24_UTILITY_WIRINGPI_SPI_H_