diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 779c3533..0258df19 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -11,7 +11,7 @@ assignees: '' Before submitting new issue, please check the [Wiki](https://github.com/jgromes/RadioLib/wiki) and the [API documentation](https://jgromes.github.io/RadioLib/). You might find a solution to your issue there. **Describe the bug** -A clear and concise description of what the bug is. When applicable, please include debug mode output: uncomment [debug macro definitions in TypeDef.h](https://github.com/jgromes/RadioLib/blob/master/src/TypeDef.h#L36) and post the output. +A clear and concise description of what the bug is. When applicable, please include [debug mode output](https://github.com/jgromes/RadioLib/wiki/Debug-mode). **To Reproduce** Minimal Arduino sketch to reproduce the behavior. Please user Markdown to style the code to make it readable (see [Markdown Cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#code)). @@ -24,6 +24,7 @@ If applicable, add screenshots to help explain your problem. **Additional info (please complete):** - MCU: [e.g. Arduino Uno, ESP8266 etc.] - - Wireless module type [e.g. SX1276, ESP8266, etc.] + - Link to Arduino core: [e.g. https://github.com/stm32duino/Arduino_Core_STM32 when using official STM32 core. See readme for links to all supported cores] + - Wireless module type [e.g. CC1101, SX1268, etc.] - Arduino IDE version [e.g. 1.8.5] - - Library version [e.g. 1.0.1] + - Library version [e.g. 3.0.0] diff --git a/.github/ISSUE_TEMPLATE/module-not-working.md b/.github/ISSUE_TEMPLATE/module-not-working.md new file mode 100644 index 00000000..1b67e8d6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/module-not-working.md @@ -0,0 +1,34 @@ +--- +name: Module not working +about: Template to use when your module isn't working +title: '' +labels: '' +assignees: '' + +--- + +**IMPORTANT: Before submitting an issue, please check the following:** +1. **Read [CONTRIBUTING.md](https://github.com/jgromes/RadioLib/blob/master/CONTRIBUTING.md)!** Issues that do not follow this document will be closed/locked/deleted/ignored. +2. RadioLib has a [Wiki](https://github.com/jgromes/RadioLib/wiki) and an extensive [API documentation](https://jgromes.github.io/RadioLib/). You might find a solution to your issue there. +3. Make sure you're using the latest release of the library! Releases can be found [here](https://github.com/jgromes/RadioLib/releases). +4. Use [Arduino forums](https://forum.arduino.cc/) to ask generic questions about wireless modules, wiring, usage, etc. Only create issues for problems specific to RadioLib! +5. Error codes, their meaning and how to fix them can be found on [this page](https://jgromes.github.io/RadioLib/group__status__codes.html). + +**Sketch that is causing the module fail** + +```c++ +paste the sketch here, even if it is an unmodified example code +``` + +**Hardware setup** +Wiring diagram, schematic, pictures etc. + +**Debug mode output** +Enable all [debug levels](https://github.com/jgromes/RadioLib/wiki/Debug-mode) and paste the Serial monitor output here. + +**Additional info (please complete):** + - MCU: [e.g. Arduino Uno, ESP8266 etc.] + - Link to Arduino core: [e.g. https://github.com/stm32duino/Arduino_Core_STM32 when using official STM32 core. See readme for links to all supported cores] + - Wireless module type [e.g. CC1101, SX1268, etc.] + - Arduino IDE version [e.g. 1.8.5] + - Library version [e.g. 3.0.0] diff --git a/.travis.yml b/.travis.yml index 8e36b9cb..46945334 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,49 +1,145 @@ env: global: - - ARDUINO_IDE_VERSION="1.8.9" matrix: # see https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc#options # and https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification#boardstxt + - BOARD="arduino:avr:uno" + - BOARD="arduino:avr:mega:cpu=atmega2560" + - BOARD="arduino:avr:leonardo" + - BOARD="esp8266:esp8266:generic:xtal=80,ResetMethod=ck,CrystalFreq=26,FlashFreq=40,FlashMode=qio,eesz=512K" - BOARD="esp32:esp32:esp32" - BOARD="STM32:stm32:GenF3:pnum=BLACKPILL_F303CC" - - BOARD="esp8266:esp8266:generic:xtal=80,ResetMethod=ck,CrystalFreq=26,FlashFreq=40,FlashMode=qio,eesz=512K" - # - BOARD="SparkFun:apollo3:amap3redboard" - BOARD="arduino:samd:arduino_zero_native" - BOARD="arduino:sam:arduino_due_x" - - BOARD="arduino:avr:uno" - - BOARD="arduino:avr:leonardo" - - BOARD="arduino:avr:mega:cpu=atmega2560" + - BOARD="adafruit:nrf52:feather52832:softdevice=s132v6,debug=l0" + - BOARD="Intel:arc32:arduino_101" + - BOARD="arduino:megaavr:uno2018:mode=on" + - BOARD="SparkFun:apollo3:amap3redboard" + - BOARD="arduino:mbed:nano33ble" + - BOARD="stm32duino:STM32F1:mapleMini:bootloader_version=original,cpu_speed=speed_72mhz" + - BOARD="adafruit:samd:adafruit_feather_m0:usbstack=arduino,debug=off" + - BOARD="arduino-beta:mbed:envie_m4" + +addons: + apt: + packages: + # required for Adafruit nRF52 (adafruit-nrfutil package) + - python3 + - python3-pip + - python3-setuptools before_install: - # install Arduino IDE - - wget https://downloads.arduino.cc/arduino-$ARDUINO_IDE_VERSION-linux64.tar.xz - - tar xf arduino-$ARDUINO_IDE_VERSION-linux64.tar.xz - - mv arduino-$ARDUINO_IDE_VERSION $HOME/arduino-ide - - export PATH=$PATH:$HOME/arduino-ide + # install Arduino CLI + - curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | sh + - export PATH=$PATH:$PWD/bin - # firewall Arduino IDE noise (https://github.com/per1234/arduino-ci-script/issues/1#issuecomment-504158113) - - sudo iptables -P INPUT DROP - - sudo iptables -P FORWARD DROP - - sudo iptables -P OUTPUT ACCEPT - - sudo iptables -A INPUT -i lo -j ACCEPT - - sudo iptables -A OUTPUT -o lo -j ACCEPT - - sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT + # check every board in matrix and install 3rd party definitions + - | + if [[ "$BOARD" =~ "arduino:avr:uno" ]]; then + export BUILD_EXAMPLES=true; + export WARNINGS=all; + arduino-cli core update-index; + arduino-cli core install arduino:avr; - # install 3rd party boards - - arduino --pref "boardsmanager.additional.urls=http://arduino.esp8266.com/stable/package_esp8266com_index.json,https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json,https://github.com/stm32duino/BoardManagerFiles/raw/master/STM32/package_stm_index.json,https://raw.githubusercontent.com/sparkfun/Arduino_Boards/master/IDE_Board_Manager/package_sparkfun_index.json" --save-prefs 2>&1 - - if [[ "$BOARD" =~ "esp8266:esp8266:" ]]; then - arduino --install-boards esp8266:esp8266; + elif [[ "$BOARD" =~ "arduino:avr:mega" ]]; then + export BUILD_EXAMPLES=false; + export WARNINGS=all; + arduino-cli core update-index; + arduino-cli core install arduino:avr; + + elif [[ "$BOARD" =~ "arduino:avr:leonardo" ]]; then + export BUILD_EXAMPLES=false; + export WARNINGS=all; + arduino-cli core update-index; + arduino-cli core install arduino:avr; + + elif [[ "$BOARD" =~ "esp8266:esp8266:" ]]; then + export BUILD_EXAMPLES=false; + export WARNINGS=all; + arduino-cli core update-index --additional-urls http://arduino.esp8266.com/stable/package_esp8266com_index.json; + arduino-cli core install esp8266:esp8266 --additional-urls http://arduino.esp8266.com/stable/package_esp8266com_index.json; export SKIP_PAT='(HTTP|MQTT).*ino'; + elif [[ "$BOARD" =~ "esp32:esp32:" ]]; then - arduino --install-boards esp32:esp32; + export BUILD_EXAMPLES=false; + export WARNINGS=all; + arduino-cli core update-index --additional-urls https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json; + arduino-cli core install esp32:esp32 --additional-urls https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json; + elif [[ "$BOARD" =~ "STM32:stm32:" ]]; then - arduino --install-boards STM32:stm32; + export BUILD_EXAMPLES=false; + export WARNINGS=all; + arduino-cli core update-index --additional-urls https://github.com/stm32duino/BoardManagerFiles/raw/master/STM32/package_stm_index.json; + arduino-cli core install STM32:stm32 --additional-urls https://github.com/stm32duino/BoardManagerFiles/raw/master/STM32/package_stm_index.json; + elif [[ "$BOARD" =~ "arduino:samd:" ]]; then - arduino --install-boards arduino:samd; + export BUILD_EXAMPLES=false; + export WARNINGS=all; + arduino-cli core update-index; + arduino-cli core install arduino:samd; + elif [[ "$BOARD" =~ "arduino:sam:" ]]; then - arduino --install-boards arduino:sam; + export BUILD_EXAMPLES=false; + export WARNINGS=all; + arduino-cli core update-index; + arduino-cli core install arduino:sam; + + elif [[ "$BOARD" =~ "adafruit:nrf52:" ]]; then + pip3 install --user adafruit-nrfutil; + export BUILD_EXAMPLES=false; + export WARNINGS=all; + arduino-cli core update-index --additional-urls https://www.adafruit.com/package_adafruit_index.json; + arduino-cli core install adafruit:nrf52 --additional-urls https://www.adafruit.com/package_adafruit_index.json; + + elif [[ "$BOARD" =~ "Intel:arc32:" ]]; then + export BUILD_EXAMPLES=false; + export WARNINGS=all; + arduino-cli core update-index; + arduino-cli core install Intel:arc32; + + elif [[ "$BOARD" =~ "arduino:megaavr:" ]]; then + export BUILD_EXAMPLES=false; + export WARNINGS=all; + arduino-cli core update-index; + arduino-cli core install arduino:megaavr; + elif [[ "$BOARD" =~ "SparkFun:apollo3:" ]]; then - arduino --install-boards SparkFun:apollo3; + export BUILD_EXAMPLES=false; + export WARNINGS=none; + arduino-cli core update-index --additional-urls https://raw.githubusercontent.com/sparkfun/Arduino_Boards/master/IDE_Board_Manager/package_sparkfun_index.json; + arduino-cli core install SparkFun:apollo3 --additional-urls https://raw.githubusercontent.com/sparkfun/Arduino_Boards/master/IDE_Board_Manager/package_sparkfun_index.json; + + elif [[ "$BOARD" =~ "arduino:mbed:" ]]; then + export BUILD_EXAMPLES=false; + export WARNINGS=all; + arduino-cli core update-index; + arduino-cli core install arduino:mbed; + export SKIP_PAT='(HTTP|MQTT).*ino'; + + elif [[ "$BOARD" =~ "stm32duino:STM32F1:" ]]; then + export BUILD_EXAMPLES=false; + export WARNINGS=all; + arduino-cli core update-index --additional-urls http://dan.drown.org/stm32duino/package_STM32duino_index.json; + arduino-cli core install stm32duino:STM32F1 --additional-urls http://dan.drown.org/stm32duino/package_STM32duino_index.json; + + elif [[ "$BOARD" =~ "adafruit:samd:" ]]; then + export BUILD_EXAMPLES=false; + export WARNINGS=all; + arduino-cli core update-index --additional-urls https://www.adafruit.com/package_adafruit_index.json + arduino-cli core install adafruit:samd --additional-urls https://www.adafruit.com/package_adafruit_index.json + + elif [[ "$BOARD" =~ "arduino-beta:mbed:" ]]; then + export BUILD_EXAMPLES=false; + export WARNINGS=all; + arduino-cli core update-index; + arduino-cli core install arduino-beta:mbed; + export SKIP_PAT='(HTTP|MQTT).*ino'; + + fi + + # check if this release commit (or forced build) and if so, build for every board + - if [[ "$TRAVIS_COMMIT_MESSAGE" =~ "Bump version to" || "$TRAVIS_COMMIT_MESSAGE" =~ "TRAVIS_FORCE_BUILD" ]]; then + export BUILD_EXAMPLES=true; fi # create directory to save the library and create symbolic link @@ -59,23 +155,27 @@ branches: script: # build all example sketches - | - for example in $(find $PWD/examples -name '*.ino' | sort); do - # check whether to skip this sketch - if [ ! -z "$SKIP_PAT" ] && [[ ${example} =~ $SKIP_PAT ]]; then - # skip sketch - echo -e "\n\033[1;33mSkipped ${example##*/} (matched with $SKIP_PAT)\033[0m"; - else - # build sketch - echo -e "\n\033[1;33mBuilding ${example##*/} ... \033[0m"; - arduino --verify --board $BOARD $example; - if [ $? -ne 0 ]; then - echo -e "\033[1;31m${example##*/} build FAILED\033[0m\n"; - exit 1; + if [ ! -z "$BUILD_EXAMPLES" ] && [ "$BUILD_EXAMPLES" = true ] ; then + for example in $(find $PWD/examples -name '*.ino' | sort); do + # check whether to skip this sketch + if [ ! -z "$SKIP_PAT" ] && [[ ${example} =~ $SKIP_PAT ]]; then + # skip sketch + echo -e "\n\033[1;33mSkipped ${example##*/} (matched with $SKIP_PAT)\033[0m"; else - echo -e "\033[1;32m${example##*/} build PASSED\033[0m\n"; + # build sketch + echo -e "\n\033[1;33mBuilding ${example##*/} ... \033[0m"; + arduino-cli compile --fqbn $BOARD $example --warnings=$WARNINGS + if [ $? -ne 0 ]; then + echo -e "\033[1;31m${example##*/} build FAILED\033[0m\n"; + exit 1; + else + echo -e "\033[1;32m${example##*/} build PASSED\033[0m\n"; + fi fi - fi - done + done + else + echo -e "\n\033[1;33mExample builds skipped for $BOARD\033[0m"; + fi # generate Doxygen documentation (only for Arduino UNO) - if [ $BOARD = "arduino:avr:uno" ]; then diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 12fa8518..563d444f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -67,3 +67,44 @@ If you're adding a new method, make sure to add appropriate Doxygen comments, so 6. **Keywords** This is an Arduino library, so it needs to comply with the Arduino library specification. To add a new keyword to the Arduino IDE syntax highlighting, add it to the keywords.txt file. **Use true tabs in keywords.txt! No spaces there!** + +7. **Dynamic memory** +Sometimes, RadioLib might be used in critical applications where dynamic memory allocation using `new` or `malloc` might cause issues. For such cases, RadioLib provides the option to compile using only static arrays. This means that every dynamically allocated array must have a sufficiently large static counterpart. Naturally, all dynamically allocated memory must be properly de-allocated using `delete` or `free`. + +```c++ +// build a temporary buffer +#ifdef RADIOLIB_STATIC_ONLY + uint8_t data[RADIOLIB_STATIC_ARRAY_SIZE + 1]; +#else + uint8_t* data = new uint8_t[length + 1]; + if(!data) { + return(ERR_MEMORY_ALLOCATION_FAILED); + } +#endif + +// read the received data +readData(data, length); + +// deallocate temporary buffer +#ifndef RADIOLIB_STATIC_ONLY + delete[] data; +#endif +``` + +8. **God Mode** +During development, it can be useful to have access to the low level drivers, such as the SPI commands. These are incredibly powerful, since they will basically let user do anything he wants with the module, outside of the normal level of sanity checks. As such, they are normally protected using C++ access modifiers `private` or `protected`. God mode disables this protection, and so any newly implemented `class` must contain the appropriate macro check: + +```c++ +class Module { + void publicMethod(); + +#ifndef RADIOLIB_GODMODE + private: +#endif + + void privateMethod(); +}; +``` + +9. **No Arduino Strings** +Arduino `String` class should never be used internally in the library. The only allowed occurence of Arduino `String` is in public API methods, and only at the top-most layer. diff --git a/README.md b/README.md index b3980dee..e8677ece 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,8 @@ ## See the [Wiki](https://github.com/jgromes/RadioLib/wiki) for further information. See the [GitHub Pages](https://jgromes.github.io/RadioLib) for detailed and up-to-date API reference. -RadioLib allows its users to integrate all sorts of different wireless communication modules into a single consistent system. -Want to add a Bluetooth interface to your ZigBee network? Sure thing! Need to connect LoRa network to the Internet with a GSM module? RadioLib has got your back! +RadioLib allows its users to integrate all sorts of different wireless communication modules, protocols and even digital modes into a single consistent system. +Want to add a Bluetooth interface to your LoRa network? Sure thing! Do you just want to go really old-school and play around with radio teletype, slow-scan TV, or even Hellschreiber using nothing but a cheap radio module? Why not! RadioLib was originally created as a driver for [__RadioShield__](https://github.com/jgromes/RadioShield), but it can be used to control as many different wireless modules as you like - or at least as many as your Arduino can handle! @@ -18,42 +18,69 @@ RadioLib was originally created as a driver for [__RadioShield__](https://github * __JDY08__ BLE module * __nRF24L01__ 2.4 GHz module * __RF69__ FSK/OOK radio module +* __RFM2x__ series FSK modules (RFM22, RM23) * __RFM9x__ series LoRa modules (RFM95, RM96, RFM97, RFM98) -* __SX127x__ series LoRa modules (SX1272, SX1273, SX1276, SX1277, SX1278, SX1279) +* __Si443x__ series FSK modules (Si4430, Si4431, Si4432) * __SX126x__ series LoRa modules (SX1261, SX1262, SX1268) +* __SX127x__ series LoRa modules (SX1272, SX1273, SX1276, SX1277, SX1278, SX1279) +* __SX128x__ series LoRa/GFSK/BLE/FLRC modules (SX1280, SX1281, SX1282) * __SX1231__ FSK/OOK radio module * __XBee__ modules (S2B) -### Supported protocols: -* __MQTT__ for modules: ESP8266 -* __HTTP__ for modules: ESP8266 -* __RTTY__ for modules: SX127x, RFM9x, SX126x, RF69, SX1231, CC1101 and nRF24L01 -* __Morse Code__ for modules: SX127x, RFM9x, SX126x, RF69, SX1231, CC1101 and nRF24L01 -* __AX.25__ for modules: SX127x, RFM9x, SX126x, RF69, SX1231 and CC1101 +### Supported protocols and digital modes: +* __MQTT__ for modules: +ESP8266 +* __HTTP__ for modules: +ESP8266 +* __AX.25__ using 2-FSK or AFSK for modules: +SX127x, RFM9x, SX126x, RF69, SX1231, CC1101, RFM2x and Si443x +* [__RTTY__](https://www.sigidwiki.com/wiki/RTTY) using 2-FSK or AFSK for modules: +SX127x, RFM9x, SX126x, RF69, SX1231, CC1101, nRF24L01, RFM2x, Si443x and SX128x +* [__Morse Code__](https://www.sigidwiki.com/wiki/Morse_Code_(CW)) using 2-FSK or AFSK for modules: +SX127x, RFM9x, SX126x, RF69, SX1231, CC1101, nRF24L01, RFM2x, Si443x and SX128x +* [__SSTV__](https://www.sigidwiki.com/wiki/SSTV) using 2-FSK or AFSK for modules: +SX127x, RFM9x, SX126x, RF69, SX1231, CC1101, RFM2x and Si443x +* [__Hellschreiber__](https://www.sigidwiki.com/wiki/Hellschreiber) using 2-FSK or AFSK for modules: +SX127x, RFM9x, SX126x, RF69, SX1231, CC1101, nRF24L01, RFM2x, Si443x and SX128x ### Supported platforms: -* __AVR__ - tested with hardware on Uno, Mega and Leonardo -* __ESP8266__ - tested with hardware on NodeMCU and Wemos D1 -* __ESP32__ - tested with hardware on ESP-WROOM-32 -* __STM32__ - tested with hardware on Nucleo L452RE-P -* __SAMD__ - Arduino Zero, Arduino MKR boards, M0 Pro etc. -* __SAM__ - Arduino Due -* __nRF52__ - Adafruit Bluefruit Feather etc. -* _Intel Curie_ - Arduino 101 -* _megaAVR_ - Arduino Uno WiFi Rev.2 etc. -* _Apollo3_ - SparkFun Artemis Redboard etc. +* __Arduino__ + * [__AVR__](https://github.com/arduino/ArduinoCore-avr) - Arduino Uno, Mega, Leonardo, Pro Mini, Nano etc. + * [__mbed__](https://github.com/arduino/ArduinoCore-mbed) - Arduino Nano 33 BLE and Arduino Portenta H7 + * [__megaAVR__](https://github.com/arduino/ArduinoCore-megaavr) - Arduino Uno WiFi Rev.2 and Nano Every + * [__SAM__](https://github.com/arduino/ArduinoCore-sam) - Arduino Due + * [__SAMD__](https://github.com/arduino/ArduinoCore-samd) - Arduino Zero, MKR boards, M0 Pro etc. -The list above is by no means exhaustive. Most of RadioLib code is independent of the used platform, so as long as your board is running some Arduino-compatible core, RadioLib should work. Compilation of all examples is tested for all platoforms in __bold__ on each git push. Platforms in _italic_ are not tested on each push, but do compile and should be working. +* __Adafruit__ + * [__SAMD__](https://github.com/adafruit/ArduinoCore-samd) - Adafruit Feather M0 and M4 boards (Feather, Metro, Gemma, Trinket etc.) + * [__nRF52__](https://github.com/adafruit/Adafruit_nRF52_Arduino) - Adafruit Feather nRF528x, Bluefruit and CLUE + +* __Espressif__ + * [__ESP32__](https://github.com/espressif/arduino-esp32) - ESP32-based boards + * [__ESP8266__](https://github.com/esp8266/Arduino) - ESP8266-based boards + +* __Intel__ + * [__Curie__](https://github.com/arduino/ArduinoCore-arc32) - Arduino 101 + +* __SparkFun__ + * [__Apollo3__](https://github.com/sparkfun/Arduino_Apollo3) - Sparkfun Artemis Redboard + +* __ST Microelectronics__ + * [__STM32__ (official core)](https://github.com/stm32duino/Arduino_Core_STM32) - STM32 Nucleo, Discovery, Maple, BluePill, BlackPill etc. + * [__STM32__ (unofficial core)](https://github.com/rogerclarkmelbourne/Arduino_STM32) - STM32F1 and STM32F4-based boards + +The list above is by no means exhaustive. Most of RadioLib code is independent of the used platform, so as long as your board is running some Arduino-compatible core, RadioLib should work. Compilation of all examples is tested for all platforms prior to releasing new version. ### In development: * __SIM800C__ GSM module * __LoRaWAN__ protocol for SX127x, RFM9x and SX126x modules +* __APRS__ protocol for all the modules that can transmit AX.25 * ___and more!___ ## Frequently Asked Questions ### Where should I start? -First of all, take a look at the [examples](https://github.com/jgromes/RadioLib/tree/master/examples) and the [Wiki](https://github.com/jgromes/RadioLib/wiki) - especially the [Basics](https://github.com/jgromes/RadioLib/wiki/Basics) page. There's a lot of useful information over there. Also, you should check out [RadioShield](https://github.com/jgromes/RadioShield) - open source Arduino shield that will allow you to easily connect any two wireless modules supported by RadioLib! +First of all, take a look at the [examples](https://github.com/jgromes/RadioLib/tree/master/examples) and the [Wiki](https://github.com/jgromes/RadioLib/wiki) - especially the [Basics](https://github.com/jgromes/RadioLib/wiki/Basics) page. There's a lot of useful information over there. If something isn't working as expected, try searching the [issues](https://github.com/jgromes/RadioLib/issues/). ### Help, my module isn't working! The fastest way to get help is by creating an [issue](https://github.com/jgromes/RadioLib/issues/new?assignees=&labels=&template=bug_report.md&title=) using the appropriate template. It is also highly recommended to try running the examples first - their functionality is tested from time to time and they should work. Finally, RadioLib is still under development, which means that sometimes, backwards-incompatible changes might be introduced. Though these are kept at minimum, sometimes it is unavoidable. You can check the [release changelog](https://github.com/jgromes/RadioLib/releases) to find out if there's been such a major change recently. diff --git a/examples/AFSK/AFSK_Imperial_March/AFSK_Imperial_March.ino b/examples/AFSK/AFSK_Imperial_March/AFSK_Imperial_March.ino new file mode 100644 index 00000000..29469f48 --- /dev/null +++ b/examples/AFSK/AFSK_Imperial_March/AFSK_Imperial_March.ino @@ -0,0 +1,94 @@ +/* + RadioLib AFSK Imperial March Example + + This example shows how to EXECUTE ORDER 66 + + Other modules that can be used for AFSK: + - SX127x/RFM9x + - RF69 + - SX1231 + - CC1101 + - Si443x/RFM2x + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// include the melody +#include "melody.h" + +// SX1278 has the following connections: +// NSS pin: 10 +// DIO0 pin: 2 +// RESET pin: 9 +// DIO1 pin: 3 +SX1278 radio = new Module(10, 2, 9, 3); + +// create AFSK client instance using the FSK module +// this requires connection to the module direct +// input pin, here connected to Arduino pin 5 +// SX127x/RFM9x: DIO2 +// RF69: DIO2 +// SX1231: DIO2 +// CC1101: GDO2 +// Si443x/RFM2x: GPIO +AFSKClient audio(&radio, 5); + +void setup() { + Serial.begin(9600); + + // initialize SX1278 with default settings + Serial.print(F("[SX1278] Initializing ... ")); + int state = radio.beginFSK(); + + // when using one of the non-LoRa modules for AFSK + // (RF69, CC1101,, Si4432 etc.), use the basic begin() method + // int state = radio.begin(); + + if(state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while(true); + } +} + +void loop() { + Serial.print(F("[AFSK] Executing Order 66 ... ")); + + // calculate whole note duration + int wholenote = (60000 * 4) / 120; + + // iterate over the melody + for(unsigned int note = 0; note < sizeof(melody) / sizeof(melody[0]); note += 2) { + // calculate the duration of each note + int noteDuration = 0; + int divider = melody[note + 1]; + if(divider > 0) { + // regular note, just proceed + noteDuration = wholenote / divider; + } else if(divider < 0) { + // dotted notes are represented with negative durations!! + noteDuration = wholenote / abs(divider); + noteDuration *= 1.5; // increases the duration in half for dotted notes + } + + // we only play the note for 90% of the duration, leaving 10% as a pause + audio.tone(melody[note]); + delay(noteDuration*0.9); + audio.noTone(); + delay(noteDuration*0.1); + } + + Serial.println(F("done!")); + + // wait for a second + delay(1000); +} diff --git a/examples/AFSK/AFSK_Imperial_March/melody.h b/examples/AFSK/AFSK_Imperial_March/melody.h new file mode 100644 index 00000000..e4b15169 --- /dev/null +++ b/examples/AFSK/AFSK_Imperial_March/melody.h @@ -0,0 +1,128 @@ +/* + Note definitions, melody and melody-related functions + adapted from https://github.com/robsoncouto/arduino-songs + by Robson Couto, 2019 +*/ + +#define NOTE_B0 31 +#define NOTE_C1 33 +#define NOTE_CS1 35 +#define NOTE_D1 37 +#define NOTE_DS1 39 +#define NOTE_E1 41 +#define NOTE_F1 44 +#define NOTE_FS1 46 +#define NOTE_G1 49 +#define NOTE_GS1 52 +#define NOTE_A1 55 +#define NOTE_AS1 58 +#define NOTE_B1 62 +#define NOTE_C2 65 +#define NOTE_CS2 69 +#define NOTE_D2 73 +#define NOTE_DS2 78 +#define NOTE_E2 82 +#define NOTE_F2 87 +#define NOTE_FS2 93 +#define NOTE_G2 98 +#define NOTE_GS2 104 +#define NOTE_A2 110 +#define NOTE_AS2 117 +#define NOTE_B2 123 +#define NOTE_C3 131 +#define NOTE_CS3 139 +#define NOTE_D3 147 +#define NOTE_DS3 156 +#define NOTE_E3 165 +#define NOTE_F3 175 +#define NOTE_FS3 185 +#define NOTE_G3 196 +#define NOTE_GS3 208 +#define NOTE_A3 220 +#define NOTE_AS3 233 +#define NOTE_B3 247 +#define NOTE_C4 262 +#define NOTE_CS4 277 +#define NOTE_D4 294 +#define NOTE_DS4 311 +#define NOTE_E4 330 +#define NOTE_F4 349 +#define NOTE_FS4 370 +#define NOTE_G4 392 +#define NOTE_GS4 415 +#define NOTE_A4 440 +#define NOTE_AS4 466 +#define NOTE_B4 494 +#define NOTE_C5 523 +#define NOTE_CS5 554 +#define NOTE_D5 587 +#define NOTE_DS5 622 +#define NOTE_E5 659 +#define NOTE_F5 698 +#define NOTE_FS5 740 +#define NOTE_G5 784 +#define NOTE_GS5 831 +#define NOTE_A5 880 +#define NOTE_AS5 932 +#define NOTE_B5 988 +#define NOTE_C6 1047 +#define NOTE_CS6 1109 +#define NOTE_D6 1175 +#define NOTE_DS6 1245 +#define NOTE_E6 1319 +#define NOTE_F6 1397 +#define NOTE_FS6 1480 +#define NOTE_G6 1568 +#define NOTE_GS6 1661 +#define NOTE_A6 1760 +#define NOTE_AS6 1865 +#define NOTE_B6 1976 +#define NOTE_C7 2093 +#define NOTE_CS7 2217 +#define NOTE_D7 2349 +#define NOTE_DS7 2489 +#define NOTE_E7 2637 +#define NOTE_F7 2794 +#define NOTE_FS7 2960 +#define NOTE_G7 3136 +#define NOTE_GS7 3322 +#define NOTE_A7 3520 +#define NOTE_AS7 3729 +#define NOTE_B7 3951 +#define NOTE_C8 4186 +#define NOTE_CS8 4435 +#define NOTE_D8 4699 +#define NOTE_DS8 4978 +#define REST 0 + +// notes of the moledy followed by the duration. +// a 4 means a quarter note, 8 an eighteenth , 16 sixteenth, so on +// !!negative numbers are used to represent dotted notes, +// so -4 means a dotted quarter note, that is, a quarter plus an eighteenth!! +int melody[] = { + + // Darth Vader theme (Imperial March) - Star wars + // Score available at https://musescore.com/user/202909/scores/1141521 + // The tenor saxophone part was used + + NOTE_A4,-4, NOTE_A4,-4, NOTE_A4,16, NOTE_A4,16, NOTE_A4,16, NOTE_A4,16, NOTE_F4,8, REST,8, + NOTE_A4,-4, NOTE_A4,-4, NOTE_A4,16, NOTE_A4,16, NOTE_A4,16, NOTE_A4,16, NOTE_F4,8, REST,8, + NOTE_A4,4, NOTE_A4,4, NOTE_A4,4, NOTE_F4,-8, NOTE_C5,16, + + NOTE_A4,4, NOTE_F4,-8, NOTE_C5,16, NOTE_A4,2,//4 + NOTE_E5,4, NOTE_E5,4, NOTE_E5,4, NOTE_F5,-8, NOTE_C5,16, + NOTE_A4,4, NOTE_F4,-8, NOTE_C5,16, NOTE_A4,2, + + NOTE_A5,4, NOTE_A4,-8, NOTE_A4,16, NOTE_A5,4, NOTE_GS5,-8, NOTE_G5,16, //7 + NOTE_DS5,16, NOTE_D5,16, NOTE_DS5,8, REST,8, NOTE_A4,8, NOTE_DS5,4, NOTE_D5,-8, NOTE_CS5,16, + + NOTE_C5,16, NOTE_B4,16, NOTE_C5,16, REST,8, NOTE_F4,8, NOTE_GS4,4, NOTE_F4,-8, NOTE_A4,-16,//9 + NOTE_C5,4, NOTE_A4,-8, NOTE_C5,16, NOTE_E5,2, + + NOTE_A5,4, NOTE_A4,-8, NOTE_A4,16, NOTE_A5,4, NOTE_GS5,-8, NOTE_G5,16, //7 + NOTE_DS5,16, NOTE_D5,16, NOTE_DS5,8, REST,8, NOTE_A4,8, NOTE_DS5,4, NOTE_D5,-8, NOTE_CS5,16, + + NOTE_C5,16, NOTE_B4,16, NOTE_C5,16, REST,8, NOTE_F4,8, NOTE_GS4,4, NOTE_F4,-8, NOTE_A4,-16,//9 + NOTE_A4,4, NOTE_F4,-8, NOTE_C5,16, NOTE_A4,2, + +}; diff --git a/examples/AFSK/AFSK_Tone/AFSK_Tone.ino b/examples/AFSK/AFSK_Tone/AFSK_Tone.ino new file mode 100644 index 00000000..43286f84 --- /dev/null +++ b/examples/AFSK/AFSK_Tone/AFSK_Tone.ino @@ -0,0 +1,77 @@ +/* + RadioLib AFSK Example + + This example shows hot to send audio FSK tones + using SX1278's FSK modem. + + Other modules that can be used for AFSK: + - SX127x/RFM9x + - RF69 + - SX1231 + - CC1101 + - Si443x/RFM2x + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// SX1278 has the following connections: +// NSS pin: 10 +// DIO0 pin: 2 +// RESET pin: 9 +// DIO1 pin: 3 +SX1278 radio = new Module(10, 2, 9, 3); + +// create AFSK client instance using the FSK module +// this requires connection to the module direct +// input pin, here connected to Arduino pin 5 +// SX127x/RFM9x: DIO2 +// RF69: DIO2 +// SX1231: DIO2 +// CC1101: GDO2 +// Si443x/RFM2x: GPIO +AFSKClient audio(&radio, 5); + +void setup() { + Serial.begin(9600); + + // initialize SX1278 with default settings + Serial.print(F("[SX1278] Initializing ... ")); + int state = radio.beginFSK(); + + // when using one of the non-LoRa modules for AFSK + // (RF69, CC1101,, Si4432 etc.), use the basic begin() method + // int state = radio.begin(); + + if(state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while(true); + } +} + +void loop() { + // AFSKClient can be used to transmit tones, + // same as Arduino tone() function + + // 400 Hz tone + audio.tone(400); + delay(1000); + + // silence + audio.noTone(); + delay(1000); + + // AFSKClient can also be used to transmit HAM-friendly + // RTTY, Morse code, Hellschreiber, SSTV and AX.25. + // Details on how to use AFSK are in the example + // folders for each of the above modes. +} diff --git a/examples/AX25/AX25_Frames/AX25_Frames.ino b/examples/AX25/AX25_Frames/AX25_Frames.ino index 0d5ae5b6..0167214c 100644 --- a/examples/AX25/AX25_Frames/AX25_Frames.ino +++ b/examples/AX25/AX25_Frames/AX25_Frames.ino @@ -11,6 +11,7 @@ - CC1101 - SX126x - nRF24 + - Si443x/RFM2x Using raw AX.25 frames requires some knowledge of the protocol, refer to @@ -18,6 +19,12 @@ Frames shown in this example are not exhaustive; all possible AX.25 frames should be supported. + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ */ // include the library @@ -28,14 +35,14 @@ // DIO0 pin: 2 // RESET pin: 9 // DIO1 pin: 3 -SX1278 fsk = new Module(10, 2, 9, 3); +SX1278 radio = new Module(10, 2, 9, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//SX1278 fsk = RadioShield.ModuleA; +//SX1278 radio = RadioShield.ModuleA; // create AX.25 client instance using the FSK module -AX25Client ax25(&fsk); +AX25Client ax25(&radio); void setup() { Serial.begin(9600); @@ -43,13 +50,13 @@ void setup() { // initialize SX1278 Serial.print(F("[SX1278] Initializing ... ")); // carrier frequency: 434.0 MHz - // bit rate: 1.2 kbps (1200 baud AFSK AX.25) - // frequency deviation: 0.5 kHz (1200 baud AFSK AX.25) - int state = fsk.beginFSK(434.0, 1.2, 0.5); + // bit rate: 1.2 kbps (1200 baud 2-FSK AX.25) + // frequency deviation: 0.5 kHz (1200 baud 2-FSK AX.25) + int state = radio.beginFSK(434.0, 1.2, 0.5); // when using one of the non-LoRa modules for AX.25 - // (RF69, CC1101, etc.), use the basic begin() method - // int state = fsk.begin(); + // (RF69, CC1101, Si4432 etc.), use the basic begin() method + // int state = radio.begin(); if(state == ERR_NONE) { Serial.println(F("success!")); @@ -83,10 +90,10 @@ void loop() { // control field: UI, P/F not used, unnumbered frame // protocol identifier: no layer 3 protocol implemented // information field: "Hello World!" - AX25Frame frameUI("NJ7P", 0, "N7LEM", 0, AX25_CONTROL_U_UNNUMBERED_INFORMATION | + AX25Frame frameUI("NJ7P", 0, "N7LEM", 0, AX25_CONTROL_U_UNNUMBERED_INFORMATION | AX25_CONTROL_POLL_FINAL_DISABLED | AX25_CONTROL_UNNUMBERED_FRAME, AX25_PID_NO_LAYER_3, "Hello World (unnumbered)!"); - + // send the frame Serial.print(F("[AX.25] Sending UI frame ... ")); int state = ax25.sendFrame(&frameUI); @@ -109,12 +116,12 @@ void loop() { // source station callsign: "N7LEM" // source station SSID: 0 // control field: RR, P/F not used, supervisory frame - AX25Frame frameRR("NJ7P", 0, "N7LEM", 0, AX25_CONTROL_S_RECEIVE_READY | + AX25Frame frameRR("NJ7P", 0, "N7LEM", 0, AX25_CONTROL_S_RECEIVE_READY | AX25_CONTROL_POLL_FINAL_DISABLED | AX25_CONTROL_SUPERVISORY_FRAME); // set receive sequence number (0 - 7) frameRR.setRecvSequence(0); - + // send the frame Serial.print(F("[AX.25] Sending RR frame ... ")); state = ax25.sendFrame(&frameRR); @@ -139,7 +146,7 @@ void loop() { // control field: P/F not used, information frame // protocol identifier: no layer 3 protocol implemented // information field: "Hello World (numbered)!" - AX25Frame frameI("NJ7P", 0, "N7LEM", 0, AX25_CONTROL_POLL_FINAL_DISABLED | + AX25Frame frameI("NJ7P", 0, "N7LEM", 0, AX25_CONTROL_POLL_FINAL_DISABLED | AX25_CONTROL_INFORMATION_FRAME, AX25_PID_NO_LAYER_3, "Hello World (numbered)!"); @@ -148,7 +155,7 @@ void loop() { // set send sequence number (0 - 7) frameI.setSendSequence(0); - + // send the frame Serial.print(F("[AX.25] Sending I frame ... ")); state = ax25.sendFrame(&frameI); diff --git a/examples/AX25/AX25_Transmit/AX25_Transmit.ino b/examples/AX25/AX25_Transmit/AX25_Transmit.ino index fa97067d..2ed78875 100644 --- a/examples/AX25/AX25_Transmit/AX25_Transmit.ino +++ b/examples/AX25/AX25_Transmit/AX25_Transmit.ino @@ -11,6 +11,13 @@ - CC1101 - SX126x - nRF24 + - Si443x/RFM2x + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ */ // include the library @@ -21,14 +28,14 @@ // DIO0 pin: 2 // RESET pin: 9 // DIO1 pin: 3 -SX1278 fsk = new Module(10, 2, 9, 3); +SX1278 radio = new Module(10, 2, 9, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//SX1278 fsk = RadioShield.ModuleA; +//SX1278 radio = RadioShield.ModuleA; // create AX.25 client instance using the FSK module -AX25Client ax25(&fsk); +AX25Client ax25(&radio); void setup() { Serial.begin(9600); @@ -36,13 +43,13 @@ void setup() { // initialize SX1278 Serial.print(F("[SX1278] Initializing ... ")); // carrier frequency: 434.0 MHz - // bit rate: 1.2 kbps (1200 baud AFSK AX.25) - // frequency deviation: 0.5 kHz (1200 baud AFSK AX.25) - int state = fsk.beginFSK(434.0, 1.2, 0.5); + // bit rate: 1.2 kbps (1200 baud 2-FSK AX.25) + // frequency deviation: 0.5 kHz (1200 baud 2-FSK AX.25) + int state = radio.beginFSK(434.0, 1.2, 0.5); // when using one of the non-LoRa modules for AX.25 - // (RF69, CC1101, etc.), use the basic begin() method - // int state = fsk.begin(); + // (RF69, CC1101,, Si4432 etc.), use the basic begin() method + // int state = radio.begin(); if(state == ERR_NONE) { Serial.println(F("success!")); @@ -68,7 +75,7 @@ void setup() { } void loop() { - // send AX.25 unnumbered infomration frame + // send AX.25 unnumbered information frame Serial.print(F("[AX.25] Sending UI frame ... ")); // destination station callsign: "NJ7P" // destination station SSID: 0 diff --git a/examples/AX25/AX25_Transmit_AFSK/AX25_Transmit_AFSK.ino b/examples/AX25/AX25_Transmit_AFSK/AX25_Transmit_AFSK.ino new file mode 100644 index 00000000..703847af --- /dev/null +++ b/examples/AX25/AX25_Transmit_AFSK/AX25_Transmit_AFSK.ino @@ -0,0 +1,97 @@ +/* + RadioLib AX.25 Transmit AFSK Example + + This example sends AX.25 messages using + SX1278's FSK modem. The data is modulated + as AFSK at 1200 baud using Bell 202 tones. + + Other modules that can be used for AX.25 + with AFSK modulation: + - SX127x/RFM9x + - RF69 + - SX1231 + - CC1101 + - nRF24 + - Si443x/RFM2x + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// SX1278 has the following connections: +// NSS pin: 10 +// DIO0 pin: 2 +// RESET pin: 9 +// DIO1 pin: 3 +SX1278 radio = new Module(10, 2, 9, 3); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//SX1278 radio = RadioShield.ModuleA; + +// create AFSK client instance using the FSK module +// pin 5 is connected to SX1278 DIO2 +AFSKClient audio(&radio, 5); + +// create AX.25 client instance using the AFSK instance +AX25Client ax25(&audio); + +void setup() { + Serial.begin(9600); + + // initialize SX1278 with default settings + Serial.print(F("[SX1278] Initializing ... ")); + int state = radio.beginFSK(); + + // when using one of the non-LoRa modules for AX.25 + // (RF69, CC1101,, Si4432 etc.), use the basic begin() method + // int state = radio.begin(); + + if(state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while(true); + } + + // initialize AX.25 client + Serial.print(F("[AX.25] Initializing ... ")); + // source station callsign: "N7LEM" + // source station SSID: 0 + // preamble length: 8 bytes + state = ax25.begin("N7LEM"); + if(state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while(true); + } +} + +void loop() { + // send AX.25 unnumbered information frame + Serial.print(F("[AX.25] Sending UI frame ... ")); + // destination station callsign: "NJ7P" + // destination station SSID: 0 + int state = ax25.transmit("Hello World!", "NJ7P"); + if (state == ERR_NONE) { + // the packet was successfully transmitted + Serial.println(F("success!")); + + } else { + // some error occurred + Serial.print(F("failed, code ")); + Serial.println(state); + + } + + delay(1000); +} diff --git a/examples/CC1101/CC1101_Receive/CC1101_Receive.ino b/examples/CC1101/CC1101_Receive/CC1101_Receive.ino index e36c1d9a..b51bdf20 100644 --- a/examples/CC1101/CC1101_Receive/CC1101_Receive.ino +++ b/examples/CC1101/CC1101_Receive/CC1101_Receive.ino @@ -9,6 +9,9 @@ - frequency deviation - sync word + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#cc1101 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -21,23 +24,18 @@ // GDO0 pin: 2 // RST pin: unused // GDO2 pin: 3 (optional) -CC1101 cc = new Module(10, 2, NC, 3); +CC1101 radio = new Module(10, 2, RADIOLIB_NC, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//CC1101 cc = RadioShield.ModuleA; +//CC1101 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize CC1101 with default settings Serial.print(F("[CC1101] Initializing ... ")); - // carrier frequency: 868.0 MHz - // bit rate: 4.8 kbps - // frequency deviation: 48.0 kHz - // Rx bandwidth: 325.0 kHz - // sync word: 0xD391 - int state = cc.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -52,12 +50,12 @@ void loop() { // you can receive data as an Arduino String String str; - int state = cc.receive(str); + int state = radio.receive(str); // you can also receive data as byte array /* byte byteArr[8]; - int state = cc.receive(byteArr, 8); + int state = radio.receive(byteArr, 8); */ if (state == ERR_NONE) { @@ -71,13 +69,13 @@ void loop() { // print RSSI (Received Signal Strength Indicator) // of the last received packet Serial.print(F("[CC1101] RSSI:\t\t")); - Serial.print(cc.getRSSI()); + Serial.print(radio.getRSSI()); Serial.println(F(" dBm")); // print LQI (Link Quality Indicator) // of the last received packet, lower is better Serial.print(F("[CC1101] LQI:\t\t")); - Serial.println(cc.getLQI()); + Serial.println(radio.getLQI()); } else if (state == ERR_CRC_MISMATCH) { // packet was received, but is malformed diff --git a/examples/CC1101/CC1101_Receive_Address/CC1101_Receive_Address.ino b/examples/CC1101/CC1101_Receive_Address/CC1101_Receive_Address.ino index 4cbd10f2..81eac67c 100644 --- a/examples/CC1101/CC1101_Receive_Address/CC1101_Receive_Address.ino +++ b/examples/CC1101/CC1101_Receive_Address/CC1101_Receive_Address.ino @@ -7,6 +7,9 @@ will automatically filter out any packets that do not contain either node address or broadcast addresses. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#cc1101 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -19,23 +22,18 @@ // GDO0 pin: 2 // RST pin: unused // GDO2 pin: 3 (optional) -CC1101 cc = new Module(10, 2, NC, 3); +CC1101 radio = new Module(10, 2, RADIOLIB_NC, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//CC1101 cc = RadioShield.ModuleA; +//CC1101 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize CC1101 with default settings Serial.print(F("[CC1101] Initializing ... ")); - // carrier frequency: 868.0 MHz - // bit rate: 4.8 kbps - // frequency deviation: 48.0 kHz - // Rx bandwidth: 325.0 kHz - // sync word: 0xD391 - int state = cc.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -52,7 +50,7 @@ void setup() { // When setting two broadcast addresses, 0x00 and // 0xFF will be used. Serial.print(F("[CC1101] Setting node address ... ")); - state = cc.setNodeAddress(0x01, 1); + state = radio.setNodeAddress(0x01, 1); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -66,7 +64,7 @@ void setup() { // set node address /* Serial.print(F("[CC1101] Disabling address filtering ... ")); - state == cc.disableAddressFiltering(); + state == radio.disableAddressFiltering(); if(state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -82,12 +80,12 @@ void loop() { // you can receive data as an Arduino String String str; - int state = cc.receive(str); + int state = radio.receive(str); // you can also receive data as byte array /* byte byteArr[8]; - int state = cc.receive(byteArr, 8); + int state = radio.receive(byteArr, 8); */ if (state == ERR_NONE) { @@ -101,13 +99,13 @@ void loop() { // print RSSI (Received Signal Strength Indicator) // of the last received packet Serial.print(F("[CC1101] RSSI:\t\t")); - Serial.print(cc.getRSSI()); + Serial.print(radio.getRSSI()); Serial.println(F(" dBm")); // print LQI (Link Quality Indicator) // of the last received packet, lower is better Serial.print(F("[CC1101] LQI:\t\t")); - Serial.println(cc.getLQI()); + Serial.println(radio.getLQI()); } else if (state == ERR_CRC_MISMATCH) { // packet was received, but is malformed diff --git a/examples/CC1101/CC1101_Receive_Interrupt/CC1101_Receive_Interrupt.ino b/examples/CC1101/CC1101_Receive_Interrupt/CC1101_Receive_Interrupt.ino index 46f3279d..a7228de4 100644 --- a/examples/CC1101/CC1101_Receive_Interrupt/CC1101_Receive_Interrupt.ino +++ b/examples/CC1101/CC1101_Receive_Interrupt/CC1101_Receive_Interrupt.ino @@ -12,8 +12,11 @@ - frequency deviation - sync word - For full API reference, see the GitHub Pages - https://jgromes.github.io/RadioLib/ + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#cc1101 + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ */ // include the library @@ -24,23 +27,18 @@ // GDO0 pin: 2 // RST pin: unused // GDO2 pin: 3 (optional) -CC1101 cc = new Module(10, 2, NC, 3); +CC1101 radio = new Module(10, 2, RADIOLIB_NC, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//CC1101 cc = RadioShield.ModuleA; +//CC1101 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize CC1101 with default settings Serial.print(F("[CC1101] Initializing ... ")); - // carrier frequency: 868.0 MHz - // bit rate: 4.8 kbps - // frequency deviation: 48.0 kHz - // Rx bandwidth: 325.0 kHz - // sync word: 0xD391 - int state = cc.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -51,11 +49,11 @@ void setup() { // set the function that will be called // when new packet is received - cc.setGdo0Action(setFlag); + radio.setGdo0Action(setFlag); // start listening for packets Serial.print(F("[CC1101] Starting to listen ... ")); - state = cc.startReceive(); + state = radio.startReceive(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -67,11 +65,11 @@ void setup() { // if needed, 'listen' mode can be disabled by calling // any of the following methods: // - // cc.standby() - // cc.sleep() - // cc.transmit(); - // cc.receive(); - // cc.readData(); + // radio.standby() + // radio.sleep() + // radio.transmit(); + // radio.receive(); + // radio.readData(); } // flag to indicate that a packet was received @@ -106,12 +104,12 @@ void loop() { // you can read received data as an Arduino String String str; - int state = cc.readData(str); + int state = radio.readData(str); // you can also read received data as byte array /* byte byteArr[8]; - int state = cc.readData(byteArr, 8); + int state = radio.readData(byteArr, 8); */ if (state == ERR_NONE) { @@ -125,13 +123,13 @@ void loop() { // print RSSI (Received Signal Strength Indicator) // of the last received packet Serial.print(F("[CC1101] RSSI:\t\t")); - Serial.print(cc.getRSSI()); + Serial.print(radio.getRSSI()); Serial.println(F(" dBm")); // print LQI (Link Quality Indicator) // of the last received packet, lower is better Serial.print(F("[CC1101] LQI:\t\t")); - Serial.println(cc.getLQI()); + Serial.println(radio.getLQI()); } else if (state == ERR_CRC_MISMATCH) { // packet was received, but is malformed @@ -145,7 +143,7 @@ void loop() { } // put module back to listen mode - cc.startReceive(); + radio.startReceive(); // we're ready to receive more packets, // enable interrupt service routine diff --git a/examples/CC1101/CC1101_Settings/CC1101_Settings.ino b/examples/CC1101/CC1101_Settings/CC1101_Settings.ino index 74b2b3b1..e724f7b6 100644 --- a/examples/CC1101/CC1101_Settings/CC1101_Settings.ino +++ b/examples/CC1101/CC1101_Settings/CC1101_Settings.ino @@ -11,6 +11,9 @@ - output power during transmission - sync word + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#cc1101 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -23,30 +26,25 @@ // GDO0 pin: 2 // RST pin: unused // GDO2 pin: 3 (optional) -CC1101 cc1 = new Module(10, 2, NC, 3); +CC1101 radio1 = new Module(10, 2, RADIOLIB_NC, 3); // second CC1101 has different connections: // CS pin: 9 // GDO0 pin: 4 // RST pin: unused // GDO2 pin: 5 (optional) -CC1101 cc2 = new Module(9, 4, NC, 53); +CC1101 radio2 = new Module(9, 4, RADIOLIB_NC, 53); // or using RadioShield // https://github.com/jgromes/RadioShield -//CC1101 cc3 = RadioShield.ModuleB; +//CC1101 radio3 = RadioShield.ModuleB; void setup() { Serial.begin(9600); // initialize CC1101 with default settings Serial.print(F("[CC1101] Initializing ... ")); - // carrier frequency: 868.0 MHz - // bit rate: 4.8 kbps - // frequency deviation: 48.0 kHz - // Rx bandwidth: 325.0 kHz - // sync word: 0xD391 - int state = cc1.begin(); + int state = radio1.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -61,8 +59,9 @@ void setup() { // bit rate: 32.0 kbps // frequency deviation: 60.0 kHz // Rx bandwidth: 250.0 kHz - // sync word: 0xD391 - state = cc2.begin(434.0, 32.0, 60.0, 250.0); + // output power: 7 dBm + // preamble length: 32 bits + state = radio2.begin(434.0, 32.0, 60.0, 250.0, 7, 32); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -75,13 +74,13 @@ void setup() { // and check if the configuration was changed successfully // set carrier frequency to 433.5 MHz - if (cc1.setFrequency(433.5) == ERR_INVALID_FREQUENCY) { + if (radio1.setFrequency(433.5) == ERR_INVALID_FREQUENCY) { Serial.println(F("[CC1101] Selected frequency is invalid for this module!")); while (true); } // set bit rate to 100.0 kbps - state = cc1.setBitRate(100.0); + state = radio1.setBitRate(100.0); if (state == ERR_INVALID_BIT_RATE) { Serial.println(F("[CC1101] Selected bit rate is invalid for this module!")); while (true); @@ -92,25 +91,25 @@ void setup() { } // set receiver bandwidth to 250.0 kHz - if (cc1.setRxBandwidth(250.0) == ERR_INVALID_RX_BANDWIDTH) { + if (radio1.setRxBandwidth(250.0) == ERR_INVALID_RX_BANDWIDTH) { Serial.println(F("[CC1101] Selected receiver bandwidth is invalid for this module!")); while (true); } // set allowed frequency deviation to 10.0 kHz - if (cc1.setFrequencyDeviation(10.0) == ERR_INVALID_FREQUENCY_DEVIATION) { + if (radio1.setFrequencyDeviation(10.0) == ERR_INVALID_FREQUENCY_DEVIATION) { Serial.println(F("[CC1101] Selected frequency deviation is invalid for this module!")); while (true); } // set output power to 5 dBm - if (cc1.setOutputPower(5) == ERR_INVALID_OUTPUT_POWER) { + if (radio1.setOutputPower(5) == ERR_INVALID_OUTPUT_POWER) { Serial.println(F("[CC1101] Selected output power is invalid for this module!")); while (true); } // 2 bytes can be set as sync word - if (cc1.setSyncWord(0x01, 0x23) == ERR_INVALID_SYNC_WORD) { + if (radio1.setSyncWord(0x01, 0x23) == ERR_INVALID_SYNC_WORD) { Serial.println(F("[CC1101] Selected sync word is invalid for this module!")); while (true); } diff --git a/examples/CC1101/CC1101_Transmit/CC1101_Transmit.ino b/examples/CC1101/CC1101_Transmit/CC1101_Transmit.ino index 104fe2bb..3463c6f1 100644 --- a/examples/CC1101/CC1101_Transmit/CC1101_Transmit.ino +++ b/examples/CC1101/CC1101_Transmit/CC1101_Transmit.ino @@ -7,6 +7,9 @@ - null-terminated char array (C-string) - arbitrary binary data (byte array) + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#cc1101 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -19,23 +22,18 @@ // GDO0 pin: 2 // RST pin: unused // GDO2 pin: 3 (optional) -CC1101 cc = new Module(10, 2, NC, 3); +CC1101 radio = new Module(10, 2, RADIOLIB_NC, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//CC1101 cc = RadioShield.ModuleA; +//CC1101 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); - // initialize CC1101 + // initialize CC1101 with default settings Serial.print(F("[CC1101] Initializing ... ")); - // carrier frequency: 868.0 MHz - // bit rate: 4.8 kbps - // frequency deviation: 48.0 kHz - // Rx bandwidth: 325.0 kHz - // sync word: 0xD391 - int state = cc.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -49,12 +47,12 @@ void loop() { Serial.print(F("[CC1101] Transmitting packet ... ")); // you can transmit C-string or Arduino string up to 63 characters long - int state = cc.transmit("Hello World!"); + int state = radio.transmit("Hello World!"); // you can also transmit byte array up to 63 bytes long /* byte byteArr[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; - int state = cc.transmit(byteArr, 8); + int state = radio.transmit(byteArr, 8); */ if (state == ERR_NONE) { diff --git a/examples/CC1101/CC1101_Transmit_Address/CC1101_Transmit_Address.ino b/examples/CC1101/CC1101_Transmit_Address/CC1101_Transmit_Address.ino index 7e130920..430eafd8 100644 --- a/examples/CC1101/CC1101_Transmit_Address/CC1101_Transmit_Address.ino +++ b/examples/CC1101/CC1101_Transmit_Address/CC1101_Transmit_Address.ino @@ -7,6 +7,9 @@ will automatically filter out any packets that do not contain either node address or broadcast addresses. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#cc1101 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -19,23 +22,18 @@ // GDO0 pin: 2 // RST pin: unused // GDO2 pin: 3 (optional) -CC1101 cc = new Module(10, 2, NC, 3); +CC1101 radio = new Module(10, 2, RADIOLIB_NC, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//CC1101 cc = RadioShield.ModuleA; +//CC1101 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize CC1101 with default settings Serial.print(F("[CC1101] Initializing ... ")); - // carrier frequency: 868.0 MHz - // bit rate: 4.8 kbps - // frequency deviation: 48.0 kHz - // Rx bandwidth: 325.0 kHz - // sync word: 0xD391 - int state = cc.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -52,7 +50,7 @@ void setup() { // When setting two broadcast addresses, 0x00 and // 0xFF will be used. Serial.print(F("[CC1101] Setting node address ... ")); - state = cc.setNodeAddress(0x01, 1); + state = radio.setNodeAddress(0x01, 1); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -66,7 +64,7 @@ void setup() { // set node address /* Serial.print(F("[CC1101] Disabling address filtering ... ")); - state == cc.disableAddressFiltering(); + state == radio.disableAddressFiltering(); if(state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -81,21 +79,21 @@ void loop() { Serial.print(F("[CC1101] Transmitting packet ... ")); // you can transmit C-string or Arduino string up to 63 characters long - int state = cc.transmit("Hello World!"); + int state = radio.transmit("Hello World!"); // you can also transmit byte array up to 63 bytes long /* byte byteArr[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; - int state = cc.transmit(byteArr, 8); + int state = radio.transmit(byteArr, 8); */ if (state == ERR_NONE) { // the packet was successfully transmitted - Serial.println(F(" success!")); + Serial.println(F("success!")); } else if (state == ERR_PACKET_TOO_LONG) { // the supplied packet was longer than 255 bytes - Serial.println(F(" too long!")); + Serial.println(F("too long!")); } else { // some other error occurred diff --git a/examples/CC1101/CC1101_Transmit_Interrupt/CC1101_Transmit_Interrupt.ino b/examples/CC1101/CC1101_Transmit_Interrupt/CC1101_Transmit_Interrupt.ino index dde5d54d..c15652b6 100644 --- a/examples/CC1101/CC1101_Transmit_Interrupt/CC1101_Transmit_Interrupt.ino +++ b/examples/CC1101/CC1101_Transmit_Interrupt/CC1101_Transmit_Interrupt.ino @@ -8,6 +8,9 @@ - null-terminated char array (C-string) - arbitrary binary data (byte array) + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#cc1101 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -20,11 +23,11 @@ // GDO0 pin: 2 // RST pin: unused // GDO2 pin: 3 (optional) -CC1101 cc = new Module(10, 2, NC, 3); +CC1101 radio = new Module(10, 2, RADIOLIB_NC, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//CC1101 cc = RadioShield.ModuleA; +//CC1101 radio = RadioShield.ModuleA; // save transmission state between loops int transmissionState = ERR_NONE; @@ -34,12 +37,7 @@ void setup() { // initialize CC1101 with default settings Serial.print(F("[CC1101] Initializing ... ")); - // carrier frequency: 868.0 MHz - // bit rate: 4.8 kbps - // frequency deviation: 48.0 kHz - // Rx bandwidth: 325.0 kHz - // sync word: 0xD391 - int state = cc.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -50,20 +48,20 @@ void setup() { // set the function that will be called // when packet transmission is finished - cc.setGdo0Action(setFlag); + radio.setGdo0Action(setFlag); // start transmitting the first packet Serial.print(F("[CC1101] Sending first packet ... ")); // you can transmit C-string or Arduino string up to // 64 characters long - transmissionState = cc.startTransmit("Hello World!"); + transmissionState = radio.startTransmit("Hello World!"); // you can also transmit byte array up to 64 bytes long /* byte byteArr[] = {0x01, 0x23, 0x45, 0x56, 0x78, 0xAB, 0xCD, 0xEF}; - state = cc.startTransmit(byteArr, 8); + state = radio.startTransmit(byteArr, 8); */ } @@ -119,13 +117,13 @@ void loop() { // you can transmit C-string or Arduino string up to // 256 characters long - transmissionState = cc.startTransmit("Hello World!"); + transmissionState = radio.startTransmit("Hello World!"); // you can also transmit byte array up to 256 bytes long /* - byte byteArr[] = {0x01, 0x23, 0x45, 0x56, - 0x78, 0xAB, 0xCD, 0xEF}; - int state = cc.startTransmit(byteArr, 8); + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, + 0x89, 0xAB, 0xCD, 0xEF}; + int state = radio.startTransmit(byteArr, 8); */ // we're ready to send more packets, diff --git a/examples/Hellschreiber/Hellschreiber_Transmit/Hellschreiber_Transmit.ino b/examples/Hellschreiber/Hellschreiber_Transmit/Hellschreiber_Transmit.ino new file mode 100644 index 00000000..edadc5d6 --- /dev/null +++ b/examples/Hellschreiber/Hellschreiber_Transmit/Hellschreiber_Transmit.ino @@ -0,0 +1,116 @@ +/* + RadioLib Hellschreiber Transmit Example + + This example sends Hellschreiber message using + SX1278's FSK modem. + + Other modules that can be used for Hellschreiber: + - SX127x/RFM9x + - RF69 + - SX1231 + - CC1101 + - SX126x + - nRF24 + - Si443x/RFM2x + - SX128x + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// SX1278 has the following connections: +// NSS pin: 10 +// DIO0 pin: 2 +// RESET pin: 9 +// DIO1 pin: 3 +SX1278 radio = new Module(10, 2, 9, 3); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//SX1278 radio = RadioShield.ModuleA; + +// create Hellschreiber client instance using the FSK module +HellClient hell(&radio); + +void setup() { + Serial.begin(9600); + + // initialize SX1278 with default settings + Serial.print(F("[SX1278] Initializing ... ")); + int state = radio.beginFSK(); + + // when using one of the non-LoRa modules for Morse code + // (RF69, CC1101, Si4432 etc.), use the basic begin() method + // int state = radio.begin(); + + if(state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while(true); + } + + // initialize Hellschreiber client + Serial.print(F("[Hell] Initializing ... ")); + // base frequency: 434.0 MHz + // speed: 122.5 Baud ("Feld Hell") + state = hell.begin(434.0); + if(state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while(true); + } +} + +void loop() { + Serial.print(F("[Hell] Sending Hellschreiber data ... ")); + + // HellClient supports all methods of the Serial class + // NOTE: Lower case letter will be capitalized. + + // Arduino String class + String aStr = "Arduino String"; + hell.print(aStr); + + // character array (C-String) + hell.print("C-String"); + + // string saved in flash + hell.print(F("Flash String")); + + // character + hell.print('c'); + + // byte + // formatting DEC/HEX/OCT/BIN is supported for + // any integer type (byte/int/long) + hell.print(255, HEX); + + // integer number + int i = 1000; + hell.print(i); + + // floating point number + // NOTE: println() has no effect on the transmission, + // and is only kept for compatibility reasons. + float f = -3.1415; + hell.println(f, 3); + + // custom glyph - must be a 7 byte array of rows 7 pixels long + uint8_t customGlyph[] = { 0b0000000, 0b0010100, 0b0010100, 0b0000000, 0b0100010, 0b0011100, 0b0000000 }; + hell.printGlyph(customGlyph); + + Serial.println(F("done!")); + + // wait for a second before transmitting again + delay(1000); +} diff --git a/examples/Hellschreiber/Hellschreiber_Transmit_AFSK/Hellschreiber_Transmit_AFSK.ino b/examples/Hellschreiber/Hellschreiber_Transmit_AFSK/Hellschreiber_Transmit_AFSK.ino new file mode 100644 index 00000000..1938f34c --- /dev/null +++ b/examples/Hellschreiber/Hellschreiber_Transmit_AFSK/Hellschreiber_Transmit_AFSK.ino @@ -0,0 +1,119 @@ +/* + RadioLib Hellschreiber Transmit AFSK Example + + This example sends Hellschreiber message using + SX1278's FSK modem. The data is modulated + as AFSK. + + Other modules that can be used for Hellschreiber + with AFSK modulation: + - SX127x/RFM9x + - RF69 + - SX1231 + - CC1101 + - Si443x/RFM2x + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// SX1278 has the following connections: +// NSS pin: 10 +// DIO0 pin: 2 +// RESET pin: 9 +// DIO1 pin: 3 +SX1278 radio = new Module(10, 2, 9, 3); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//SX1278 radio = RadioShield.ModuleA; + +// create AFSK client instance using the FSK module +// pin 5 is connected to SX1278 DIO2 +AFSKClient audio(&radio, 5); + +// create Hellschreiber client instance using the AFSK instance +HellClient hell(&audio); + +void setup() { + Serial.begin(9600); + + // initialize SX1278 with default settings + Serial.print(F("[SX1278] Initializing ... ")); + int state = radio.beginFSK(); + + // when using one of the non-LoRa modules for Morse code + // (RF69, CC1101, Si4432 etc.), use the basic begin() method + // int state = radio.begin(); + + if(state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while(true); + } + + // initialize Hellschreiber client + Serial.print(F("[Hell] Initializing ... ")); + // AFSK tone frequency: 400 Hz + // speed: 122.5 Baud ("Feld Hell") + state = hell.begin(400); + if(state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while(true); + } +} + +void loop() { + Serial.print(F("[Hell] Sending Hellschreiber data ... ")); + + // HellClient supports all methods of the Serial class + // NOTE: Lower case letter will be capitalized. + + // Arduino String class + String aStr = "Arduino String"; + hell.print(aStr); + + // character array (C-String) + hell.print("C-String"); + + // string saved in flash + hell.print(F("Flash String")); + + // character + hell.print('c'); + + // byte + // formatting DEC/HEX/OCT/BIN is supported for + // any integer type (byte/int/long) + hell.print(255, HEX); + + // integer number + int i = 1000; + hell.print(i); + + // floating point number + // NOTE: println() has no effect on the transmission, + // and is only kept for compatibility reasons. + float f = -3.1415; + hell.println(f, 3); + + // custom glyph - must be a 7 byte array of rows 7 pixels long + uint8_t customGlyph[] = { 0b0000000, 0b0010100, 0b0010100, 0b0000000, 0b0100010, 0b0011100, 0b0000000 }; + hell.printGlyph(customGlyph); + + Serial.println(F("done!")); + + // wait for a second before transmitting again + delay(1000); +} diff --git a/examples/Morse/Morse_Transmit/Morse_Transmit.ino b/examples/Morse/Morse_Transmit/Morse_Transmit.ino index 6d71d1a4..9c39a3b7 100644 --- a/examples/Morse/Morse_Transmit/Morse_Transmit.ino +++ b/examples/Morse/Morse_Transmit/Morse_Transmit.ino @@ -11,6 +11,14 @@ - CC1101 - SX126x - nRF24 + - Si443x/RFM2x + - SX128x + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ */ // include the library @@ -21,32 +29,25 @@ // DIO0 pin: 2 // RESET pin: 9 // DIO1 pin: 3 -SX1278 fsk = new Module(10, 2, 9, 3); +SX1278 radio = new Module(10, 2, 9, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//SX1278 fsk = RadioShield.ModuleA; +//SX1278 radio = RadioShield.ModuleA; // create Morse client instance using the FSK module -MorseClient morse(&fsk); +MorseClient morse(&radio); void setup() { Serial.begin(9600); - // initialize SX1278 + // initialize SX1278 with default settings Serial.print(F("[SX1278] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bit rate: 48.0 kbps - // frequency deviation: 50.0 kHz - // Rx bandwidth: 125.0 kHz - // output power: 13 dBm - // current limit: 100 mA - // sync word: 0x2D 0x01 - int state = fsk.beginFSK(); + int state = radio.beginFSK(); // when using one of the non-LoRa modules for Morse code - // (RF69, CC1101, etc.), use the basic begin() method - // int state = fsk.begin(); + // (RF69, CC1101, Si4432 etc.), use the basic begin() method + // int state = radio.begin(); if(state == ERR_NONE) { Serial.println(F("success!")); diff --git a/examples/Morse/Morse_Transmit_AFSK/Morse_Transmit_AFSK.ino b/examples/Morse/Morse_Transmit_AFSK/Morse_Transmit_AFSK.ino new file mode 100644 index 00000000..ad89cb49 --- /dev/null +++ b/examples/Morse/Morse_Transmit_AFSK/Morse_Transmit_AFSK.ino @@ -0,0 +1,120 @@ +/* + RadioLib Morse Transmit AFSK Example + + This example sends Morse code message using + SX1278's FSK modem. The data is modulated + as AFSK. + + Other modules that can be used for Morse Code + with AFSK modulation: + - SX127x/RFM9x + - RF69 + - SX1231 + - CC1101 + - Si443x/RFM2x + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// SX1278 has the following connections: +// NSS pin: 10 +// DIO0 pin: 2 +// RESET pin: 9 +// DIO1 pin: 3 +SX1278 radio = new Module(10, 2, 9, 3); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//SX1278 radio = RadioShield.ModuleA; + +// create AFSK client instance using the FSK module +// pin 5 is connected to SX1278 DIO2 +AFSKClient audio(&radio, 5); + +// create Morse client instance using the AFSK instance +MorseClient morse(&audio); + +void setup() { + Serial.begin(9600); + + // initialize SX1278 with default settings + Serial.print(F("[SX1278] Initializing ... ")); + int state = radio.beginFSK(); + + // when using one of the non-LoRa modules for Morse code + // (RF69, CC1101, Si4432 etc.), use the basic begin() method + // int state = radio.begin(); + + if(state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while(true); + } + + // initialize Morse client + Serial.print(F("[Morse] Initializing ... ")); + // AFSK tone frequency: 400 MHz + // speed: 20 words per minute + state = morse.begin(400); + if(state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while(true); + } +} + +void loop() { + Serial.print(F("[Morse] Sending Morse data ... ")); + + // MorseClient supports all methods of the Serial class + // NOTE: Characters that do not have ITU-R M.1677-1 + // representation will not be sent! Lower case + // letters will be capitalized. + + // send start signal first + morse.startSignal(); + + // Arduino String class + String aStr = "Arduino String"; + morse.print(aStr); + + // character array (C-String) + morse.print("C-String"); + + // string saved in flash + morse.print(F("Flash String")); + + // character + morse.print('c'); + + // byte + // formatting DEC/HEX/OCT/BIN is supported for + // any integer type (byte/int/long) + morse.print(255, HEX); + + // integer number + int i = 1000; + morse.print(i); + + // floating point number + // NOTE: When using println(), the transmission will be + // terminated with end-of-work signal (...-.-). + float f = -3.1415; + morse.println(f, 3); + + Serial.println(F("done!")); + + // wait for a second before transmitting again + delay(1000); +} diff --git a/examples/RF69/RF69_Receive/RF69_Receive.ino b/examples/RF69/RF69_Receive/RF69_Receive.ino index 597ee63e..fd924755 100644 --- a/examples/RF69/RF69_Receive/RF69_Receive.ino +++ b/examples/RF69/RF69_Receive/RF69_Receive.ino @@ -9,6 +9,9 @@ - frequency deviation - sync word + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#rf69sx1231 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -20,24 +23,18 @@ // CS pin: 10 // DIO0 pin: 2 // RESET pin: 3 -RF69 rf = new Module(10, 2, 3); +RF69 radio = new Module(10, 2, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//RF69 rf = RadioShield.ModuleA; +//RF69 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize RF69 with default settings Serial.print(F("[RF69] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bit rate: 48.0 kbps - // frequency deviation: 50.0 kHz - // Rx bandwidth: 125.0 kHz - // output power: 13 dBm - // sync word: 0x2D01 - int state = rf.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -52,12 +49,12 @@ void loop() { // you can receive data as an Arduino String String str; - int state = rf.receive(str); + int state = radio.receive(str); // you can also receive data as byte array /* byte byteArr[8]; - int state = rf.receive(byteArr, 8); + int state = radio.receive(byteArr, 8); */ if (state == ERR_NONE) { @@ -68,6 +65,12 @@ void loop() { Serial.print(F("[RF69] Data:\t\t")); Serial.println(str); + // print RSSI (Received Signal Strength Indicator) + // of the last received packet + Serial.print(F("[RF69] RSSI:\t\t")); + Serial.print(radio.getRSSI()); + Serial.println(F(" dBm")); + } else if (state == ERR_RX_TIMEOUT) { // timeout occurred while waiting for a packet Serial.println(F("timeout!")); diff --git a/examples/RF69/RF69_Receive_AES/RF69_Receive_AES.ino b/examples/RF69/RF69_Receive_AES/RF69_Receive_AES.ino index 7c947cf0..c1fa2816 100644 --- a/examples/RF69/RF69_Receive_AES/RF69_Receive_AES.ino +++ b/examples/RF69/RF69_Receive_AES/RF69_Receive_AES.ino @@ -5,6 +5,9 @@ Packets are decrypted using hardware AES. NOTE: When using address filtering, the address byte is NOT encrypted! + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#rf69sx1231 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -16,24 +19,18 @@ // CS pin: 10 // DIO0 pin: 2 // RESET pin: 3 -RF69 rf = new Module(10, 2, 3); +RF69 radio = new Module(10, 2, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//RF69 rf = RadioShield.ModuleA; +//RF69 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize RF69 with default settings Serial.print(F("[RF69] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bit rate: 48.0 kbps - // frequency deviation: 50.0 kHz - // Rx bandwidth: 125.0 kHz - // output power: 13 dBm - // sync word: 0x2D01 - int state = rf.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -46,14 +43,14 @@ void setup() { // NOTE: the key must be exactly 16 bytes long! uint8_t key[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}; - rf.setAESKey(key); + radio.setAESKey(key); // enable AES encryption - rf.enableAES(); + radio.enableAES(); // AES encryption can also be disabled /* - rf.disableAES(); + radio.disableAES(); */ } @@ -62,12 +59,12 @@ void loop() { // you can receive data as an Arduino String String str; - int state = rf.receive(str); + int state = radio.receive(str); // you can also receive data as byte array /* byte byteArr[8]; - int state = rf.receive(byteArr, 8); + int state = radio.receive(byteArr, 8); */ if (state == ERR_NONE) { diff --git a/examples/RF69/RF69_Receive_Address/RF69_Receive_Address.ino b/examples/RF69/RF69_Receive_Address/RF69_Receive_Address.ino index 86e1ebbc..df20200c 100644 --- a/examples/RF69/RF69_Receive_Address/RF69_Receive_Address.ino +++ b/examples/RF69/RF69_Receive_Address/RF69_Receive_Address.ino @@ -7,6 +7,9 @@ automatically filter out any packets that do not contain either node address or broadcast address. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#rf69sx1231 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -18,24 +21,18 @@ // CS pin: 10 // DIO0 pin: 2 // RESET pin: 3 -RF69 rf = new Module(10, 2, 3); +RF69 radio = new Module(10, 2, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//RF69 rf = RadioShield.ModuleA; +//RF69 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize RF69 with default settings Serial.print(F("[RF69] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bit rate: 48.0 kbps - // frequency deviation: 50.0 kHz - // Rx bandwidth: 125.0 kHz - // output power: 13 dBm - // sync word: 0x2D01 - int state = rf.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -48,7 +45,7 @@ void setup() { // NOTE: calling this method will automatically enable // address filtering (node address only) Serial.print(F("[RF69] Setting node address ... ")); - state = rf.setNodeAddress(0x02); + state = radio.setNodeAddress(0x02); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -58,10 +55,10 @@ void setup() { } // set broadcast address - // NOTE: calling this method will autmatically enable - // address filtering (node or broadcast address) + // NOTE: calling this method will automatically enable + // address filtering (node or broadcast address) Serial.print(F("[RF69] Setting broadcast address ... ")); - state = rf.setBroadcastAddress(0xFF); + state = radio.setBroadcastAddress(0xFF); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -75,7 +72,7 @@ void setup() { // node and broadcast address /* Serial.print(F("[RF69] Disabling address filtering ... ")); - state == rf.disableAddressFiltering(); + state == radio.disableAddressFiltering(); if(state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -91,12 +88,12 @@ void loop() { // you can receive data as an Arduino String String str; - int state = rf.receive(str); + int state = radio.receive(str); // you can also receive data as byte array /* byte byteArr[8]; - int state = rf.receive(byteArr, 8); + int state = radio.receive(byteArr, 8); */ if (state == ERR_NONE) { diff --git a/examples/RF69/RF69_Receive_Interrupt/RF69_Receive_Interrupt.ino b/examples/RF69/RF69_Receive_Interrupt/RF69_Receive_Interrupt.ino index 2e8929ac..2a512783 100644 --- a/examples/RF69/RF69_Receive_Interrupt/RF69_Receive_Interrupt.ino +++ b/examples/RF69/RF69_Receive_Interrupt/RF69_Receive_Interrupt.ino @@ -5,6 +5,9 @@ receive them. Once a packet is received, an interrupt is triggered. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#rf69sx1231 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -16,24 +19,18 @@ // CS pin: 10 // DIO0 pin: 2 // RESET pin: 3 -RF69 rf = new Module(10, 2, 3); +RF69 radio = new Module(10, 2, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//RF69 rf = RadioShield.ModuleA; +//RF69 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize RF69 with default settings Serial.print(F("[RF69] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bit rate: 48.0 kbps - // frequency deviation: 50.0 kHz - // Rx bandwidth: 125.0 kHz - // output power: 13 dBm - // sync word: 0x2D01 - int state = rf.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -44,11 +41,11 @@ void setup() { // set the function that will be called // when new packet is received - rf.setDio0Action(setFlag); + radio.setDio0Action(setFlag); // start listening for packets Serial.print(F("[RF69] Starting to listen ... ")); - state = rf.startReceive(); + state = radio.startReceive(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -60,11 +57,11 @@ void setup() { // if needed, 'listen' mode can be disabled by calling // any of the following methods: // - // rf.standby() - // rf.sleep() - // rf.transmit(); - // rf.receive(); - // rf.readData(); + // radio.standby() + // radio.sleep() + // radio.transmit(); + // radio.receive(); + // radio.readData(); } // flag to indicate that a packet was received @@ -99,12 +96,12 @@ void loop() { // you can read received data as an Arduino String String str; - int state = rf.readData(str); + int state = radio.readData(str); // you can also read received data as byte array /* byte byteArr[8]; - int state = lora.readData(byteArr, 8); + int state = radio.readData(byteArr, 8); */ if (state == ERR_NONE) { @@ -112,9 +109,15 @@ void loop() { Serial.println(F("[RF69] Received packet!")); // print data of the packet - Serial.print(F("[RF69] Data:\t\t\t")); + Serial.print(F("[RF69] Data:\t\t")); Serial.println(str); + // print RSSI (Received Signal Strength Indicator) + // of the last received packet + Serial.print(F("[RF69] RSSI:\t\t")); + Serial.print(radio.getRSSI()); + Serial.println(F(" dBm")); + } else if (state == ERR_CRC_MISMATCH) { // packet was received, but is malformed Serial.println(F("CRC error!")); @@ -127,7 +130,7 @@ void loop() { } // put module back to listen mode - rf.startReceive(); + radio.startReceive(); // we're ready to receive more packets, // enable interrupt service routine diff --git a/examples/RF69/RF69_Settings/RF69_Settings.ino b/examples/RF69/RF69_Settings/RF69_Settings.ino index 2fee90ba..f936ee2e 100644 --- a/examples/RF69/RF69_Settings/RF69_Settings.ino +++ b/examples/RF69/RF69_Settings/RF69_Settings.ino @@ -11,6 +11,9 @@ - output power during transmission - sync word + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#rf69sx1231 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -22,30 +25,24 @@ // CS pin: 10 // DIO0 pin: 2 // RESET pin: 3 -RF69 rf1 = new Module(10, 2, 3); +RF69 radio1 = new Module(10, 2, 3); // second CC1101 has different connections: // CS pin: 9 // DIO0 pin: 4 // RESET pin: 5 -RF69 rf2 = new Module(9, 4, 5); +RF69 radio2 = new Module(9, 4, 5); // or using RadioShield // https://github.com/jgromes/RadioShield -//RF69 rf3 = RadioShield.ModuleB; +//RF69 radio3 = RadioShield.ModuleB; void setup() { Serial.begin(9600); // initialize RF69 with default settings Serial.print(F("[RF69] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bit rate: 48.0 kbps - // frequency deviation: 50.0 kHz - // Rx bandwidth: 125.0 kHz - // output power: 13 dBm - // sync word: 0x2D01 - int state = rf1.begin(); + int state = radio1.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -61,8 +58,8 @@ void setup() { // frequency deviation: 60.0 kHz // Rx bandwidth: 250.0 kHz // output power: 17 dBm - // sync word: 0x2D01 - state = rf2.begin(868.0, 300.0, 60.0, 250.0, 17); + // preamble length: 32 bits + state = radio2.begin(868.0, 300.0, 60.0, 250.0, 17, 32); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -75,13 +72,13 @@ void setup() { // and check if the configuration was changed successfully // set carrier frequency to 433.5 MHz - if (rf1.setFrequency(433.5) == ERR_INVALID_FREQUENCY) { + if (radio1.setFrequency(433.5) == ERR_INVALID_FREQUENCY) { Serial.println(F("[RF69] Selected frequency is invalid for this module!")); while (true); } // set bit rate to 100.0 kbps - state = rf1.setBitRate(100.0); + state = radio1.setBitRate(100.0); if (state == ERR_INVALID_BIT_RATE) { Serial.println(F("[RF69] Selected bit rate is invalid for this module!")); while (true); @@ -92,7 +89,7 @@ void setup() { } // set receiver bandwidth to 250.0 kHz - state = rf1.setRxBandwidth(250.0); + state = radio1.setRxBandwidth(250.0); if (state == ERR_INVALID_RX_BANDWIDTH) { Serial.println(F("[RF69] Selected receiver bandwidth is invalid for this module!")); while (true); @@ -103,13 +100,13 @@ void setup() { } // set allowed frequency deviation to 10.0 kHz - if (rf1.setFrequencyDeviation(10.0) == ERR_INVALID_FREQUENCY_DEVIATION) { + if (radio1.setFrequencyDeviation(10.0) == ERR_INVALID_FREQUENCY_DEVIATION) { Serial.println(F("[RF69] Selected frequency deviation is invalid for this module!")); while (true); } // set output power to 2 dBm - if (rf1.setOutputPower(2) == ERR_INVALID_OUTPUT_POWER) { + if (radio1.setOutputPower(2) == ERR_INVALID_OUTPUT_POWER) { Serial.println(F("[RF69] Selected output power is invalid for this module!")); while (true); } @@ -118,7 +115,7 @@ void setup() { // NOTE: sync word must not contain any zero bytes // set sync word to 0x0123456789ABCDEF uint8_t syncWord[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; - if (rf1.setSyncWord(syncWord, 8) == ERR_INVALID_SYNC_WORD) { + if (radio1.setSyncWord(syncWord, 8) == ERR_INVALID_SYNC_WORD) { Serial.println(F("[RF69] Selected sync word is invalid for this module!")); while (true); } @@ -128,13 +125,13 @@ void setup() { // RF69 can also measure temperature (roughly) // to get correct temperature measurements, the sensor must be calibrated // at ambient temperature - rf1.setAmbientTemperature(25); // replace 25 with your ambient temperature + radio1.setAmbientTemperature(25); // replace 25 with your ambient temperature } void loop() { // measure temperature Serial.print(F("[RF69] Measured temperature: ")); - Serial.print(rf1.getTemperature()); + Serial.print(radio1.getTemperature()); Serial.println(F(" deg C")); // wait 100 ms before the next measurement diff --git a/examples/RF69/RF69_Transmit/RF69_Transmit.ino b/examples/RF69/RF69_Transmit/RF69_Transmit.ino index 05879c0b..c57122b2 100644 --- a/examples/RF69/RF69_Transmit/RF69_Transmit.ino +++ b/examples/RF69/RF69_Transmit/RF69_Transmit.ino @@ -7,6 +7,9 @@ - null-terminated char array (C-string) - arbitrary binary data (byte array) + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#rf69sx1231 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -18,24 +21,18 @@ // CS pin: 10 // DIO0 pin: 2 // RESET pin: 3 -RF69 rf = new Module(10, 2, 3); +RF69 radio = new Module(10, 2, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//RF69 rf = RadioShield.ModuleA; +//RF69 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize RF69 with default settings Serial.print(F("[RF69] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bit rate: 48.0 kbps - // frequency deviation: 50.0 kHz - // Rx bandwidth: 125.0 kHz - // output power: 13 dBm - // sync word: 0x2D01 - int state = rf.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -43,18 +40,35 @@ void setup() { Serial.println(state); while (true); } + + // NOTE: some RF69 modules use high power output, + // those are usually marked RF69H(C/CW). + // To configure RadioLib for these modules, + // you must call setOutputPower() with + // second argument set to true. + /* + Serial.print(F("[RF69] Setting high power module ... ")); + state = radio.setOutputPower(20, true); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } + */ } void loop() { Serial.print(F("[RF69] Transmitting packet ... ")); // you can transmit C-string or Arduino string up to 64 characters long - int state = rf.transmit("Hello World!"); + int state = radio.transmit("Hello World!"); // you can also transmit byte array up to 64 bytes long /* byte byteArr[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; - int state = rf.transmit(byteArr, 8); + int state = radio.transmit(byteArr, 8); */ if (state == ERR_NONE) { diff --git a/examples/RF69/RF69_Transmit_AES/RF69_Transmit_AES.ino b/examples/RF69/RF69_Transmit_AES/RF69_Transmit_AES.ino index a9ec4ff5..d5bc2de2 100644 --- a/examples/RF69/RF69_Transmit_AES/RF69_Transmit_AES.ino +++ b/examples/RF69/RF69_Transmit_AES/RF69_Transmit_AES.ino @@ -5,6 +5,9 @@ Packets are encrypted using hardware AES. NOTE: When using address filtering, the address byte is NOT encrypted! + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#rf69sx1231 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -16,24 +19,18 @@ // CS pin: 10 // DIO0 pin: 2 // RESET pin: 3 -RF69 rf = new Module(10, 2, 3); +RF69 radio = new Module(10, 2, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//RF69 rf = RadioShield.ModuleA; +//RF69 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize RF69 with default settings Serial.print(F("[RF69] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bit rate: 48.0 kbps - // frequency deviation: 50.0 kHz - // Rx bandwidth: 125.0 kHz - // output power: 13 dBm - // sync word: 0x2D01 - int state = rf.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -46,14 +43,14 @@ void setup() { // NOTE: the key must be exactly 16 bytes long! uint8_t key[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}; - rf.setAESKey(key); + radio.setAESKey(key); // enable AES encryption - rf.enableAES(); + radio.enableAES(); // AES encryption can also be disabled /* - rf.disableAES(); + radio.disableAES(); */ } @@ -61,21 +58,21 @@ void loop() { Serial.print(F("[RF69] Transmitting packet ... ")); // you can transmit C-string or Arduino string up to 64 characters long - int state = rf.transmit("Hello World!"); + int state = radio.transmit("Hello World!"); // you can also transmit byte array up to 64 bytes long /* byte byteArr[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; - int state = rf.transmit(byteArr, 8); + int state = radio.transmit(byteArr, 8); */ if (state == ERR_NONE) { // the packet was successfully transmitted - Serial.println(F(" success!")); + Serial.println(F("success!")); } else if (state == ERR_PACKET_TOO_LONG) { // the supplied packet was longer than 64 bytes - Serial.println(F(" too long!")); + Serial.println(F("too long!")); } else { // some other error occurred diff --git a/examples/RF69/RF69_Transmit_Address/RF69_Transmit_Address.ino b/examples/RF69/RF69_Transmit_Address/RF69_Transmit_Address.ino index b9b36870..5f91e1f6 100644 --- a/examples/RF69/RF69_Transmit_Address/RF69_Transmit_Address.ino +++ b/examples/RF69/RF69_Transmit_Address/RF69_Transmit_Address.ino @@ -7,6 +7,9 @@ automatically filter out any packets that do not contain either node address or broadcast address. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#rf69sx1231 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -18,24 +21,18 @@ // CS pin: 10 // DIO0 pin: 2 // RESET pin: 3 -RF69 rf = new Module(10, 2, 3); +RF69 radio = new Module(10, 2, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//RF69 rf = RadioShield.ModuleA; +//RF69 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize RF69 with default settings Serial.print(F("[RF69] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bit rate: 48.0 kbps - // frequency deviation: 50.0 kHz - // Rx bandwidth: 125.0 kHz - // output power: 13 dBm - // sync word: 0x2D01 - int state = rf.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -48,7 +45,7 @@ void setup() { // NOTE: calling this method will automatically enable // address filtering (node address only) Serial.print(F("[RF69] Setting node address ... ")); - state = rf.setNodeAddress(0x01); + state = radio.setNodeAddress(0x01); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -61,7 +58,7 @@ void setup() { // NOTE: calling this method will automatically enable // address filtering (node or broadcast address) Serial.print(F("[RF69] Setting broadcast address ... ")); - state = rf.setBroadcastAddress(0xFF); + state = radio.setBroadcastAddress(0xFF); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -72,10 +69,10 @@ void setup() { // address filtering can also be disabled // NOTE: calling this method will also erase previously set - // node and broadcast address + // node and broadcast address /* Serial.print(F("[RF69] Disabling address filtering ... ")); - state = rf.disableAddressFiltering(); + state = radio.disableAddressFiltering(); if(state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -90,32 +87,32 @@ void loop() { Serial.print(F("[RF69] Transmitting packet ... ")); // transmit C-string or Arduino string to node with address 0x02 - int state = rf.transmit("Hello World!", 0x02); + int state = radio.transmit("Hello World!", 0x02); // transmit byte array to node with address 0x02 /* byte byteArr[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; - int state = rf.transmit(byteArr, 8, 0x02); + int state = radio.transmit(byteArr, 8, 0x02); */ // transmit C-string or Arduino string in broadcast mode /* - int state = rf.transmit("Hello World!", 0xFF); + int state = radio.transmit("Hello World!", 0xFF); */ // transmit byte array in broadcast mode /* - byte byteArr[] = {0x01, 0x23, 0x45, 0x56, 0x78, 0xAB, 0xCD, 0xEF}; - int state = rf.transmit(byteArr, 8, 0xFF); + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; + int state = radio.transmit(byteArr, 8, 0xFF); */ if (state == ERR_NONE) { // the packet was successfully transmitted - Serial.println(F(" success!")); + Serial.println(F("success!")); } else if (state == ERR_PACKET_TOO_LONG) { // the supplied packet was longer than 64 bytes - Serial.println(F(" too long!")); + Serial.println(F("too long!")); } else { // some other error occurred diff --git a/examples/RF69/RF69_Transmit_Interrupt/RF69_Transmit_Interrupt.ino b/examples/RF69/RF69_Transmit_Interrupt/RF69_Transmit_Interrupt.ino index 0387849a..0f03dad1 100644 --- a/examples/RF69/RF69_Transmit_Interrupt/RF69_Transmit_Interrupt.ino +++ b/examples/RF69/RF69_Transmit_Interrupt/RF69_Transmit_Interrupt.ino @@ -8,6 +8,9 @@ - null-terminated char array (C-string) - arbitrary binary data (byte array) + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#rf69sx1231 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -19,11 +22,11 @@ // CS pin: 10 // DIO0 pin: 2 // RESET pin: 3 -RF69 rf = new Module(10, 2, 3); +RF69 radio = new Module(10, 2, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//RF69 rf = RadioShield.ModuleA; +//RF69 radio = RadioShield.ModuleA; // save transmission state between loops int transmissionState = ERR_NONE; @@ -33,13 +36,7 @@ void setup() { // initialize RF69 with default settings Serial.print(F("[RF69] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bit rate: 48.0 kbps - // frequency deviation: 50.0 kHz - // Rx bandwidth: 125.0 kHz - // output power: 13 dBm - // sync word: 0x2D01 - int state = rf.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -50,20 +47,37 @@ void setup() { // set the function that will be called // when packet transmission is finished - rf.setDio0Action(setFlag); + radio.setDio0Action(setFlag); + + // NOTE: some RF69 modules use high power output, + // those are usually marked RF69H(C/CW). + // To configure RadioLib for these modules, + // you must call setOutputPower() with + // second argument set to true. + /* + Serial.print(F("[RF69] Setting high power module ... ")); + state = radio.setOutputPower(20, true); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } + */ // start transmitting the first packet Serial.print(F("[RF69] Sending first packet ... ")); // you can transmit C-string or Arduino string up to // 64 characters long - transmissionState = rf.startTransmit("Hello World!"); + transmissionState = radio.startTransmit("Hello World!"); // you can also transmit byte array up to 64 bytes long /* - byte byteArr[] = {0x01, 0x23, 0x45, 0x56, - 0x78, 0xAB, 0xCD, 0xEF}; - state = rf.startTransmit(byteArr, 8); + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, + 0x89, 0xAB, 0xCD, 0xEF}; + state = radio.startTransmit(byteArr, 8); */ } @@ -119,13 +133,13 @@ void loop() { // you can transmit C-string or Arduino string up to // 256 characters long - transmissionState = rf.startTransmit("Hello World!"); + transmissionState = radio.startTransmit("Hello World!"); // you can also transmit byte array up to 64 bytes long /* - byte byteArr[] = {0x01, 0x23, 0x45, 0x56, - 0x78, 0xAB, 0xCD, 0xEF}; - int state = rf.startTransmit(byteArr, 8); + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, + 0x89, 0xAB, 0xCD, 0xEF}; + int state = radio.startTransmit(byteArr, 8); */ // we're ready to send more packets, diff --git a/examples/RTTY/RTTY_Transmit/RTTY_Transmit.ino b/examples/RTTY/RTTY_Transmit/RTTY_Transmit.ino index da77ea5b..80c3c67f 100644 --- a/examples/RTTY/RTTY_Transmit/RTTY_Transmit.ino +++ b/examples/RTTY/RTTY_Transmit/RTTY_Transmit.ino @@ -11,6 +11,11 @@ - CC1101 - SX126x - nRF24 + - Si443x/RFM2x + - SX128x + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ @@ -24,32 +29,25 @@ // DIO0 pin: 2 // RESET pin: 9 // DIO1 pin: 3 -SX1278 fsk = new Module(10, 2, 9, 3); +SX1278 radio = new Module(10, 2, 9, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//SX1278 fsk = RadioShield.ModuleA; +//SX1278 radio = RadioShield.ModuleA; // create RTTY client instance using the FSK module -RTTYClient rtty(&fsk); +RTTYClient rtty(&radio); void setup() { Serial.begin(9600); - // initialize SX1278 + // initialize SX1278 with default settings Serial.print(F("[SX1278] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bit rate: 48.0 kbps - // frequency deviation: 50.0 kHz - // Rx bandwidth: 125.0 kHz - // output power: 13 dBm - // current limit: 100 mA - // sync word: 0x2D 0x01 - int state = fsk.beginFSK(); + int state = radio.beginFSK(); // when using one of the non-LoRa modules for RTTY - // (RF69, CC1101, etc.), use the basic begin() method - // int state = fsk.begin(); + // (RF69, CC1101, Si4432 etc.), use the basic begin() method + // int state = radio.begin(); if(state == ERR_NONE) { Serial.println(F("success!")); @@ -63,11 +61,13 @@ void setup() { // NOTE: RTTY frequency shift will be rounded // to the nearest multiple of frequency step size. // The exact value depends on the module: - // SX127x - 61 Hz + // SX127x/RFM9x - 61 Hz // RF69 - 61 Hz // CC1101 - 397 Hz // SX126x - 1 Hz // nRF24 - 1000000 Hz + // Si443x/RFM2x - 156 Hz + // SX128x - 198 Hz Serial.print(F("[RTTY] Initializing ... ")); // low ("space") frequency: 434.0 MHz // frequency shift: 183 Hz diff --git a/examples/RTTY/RTTY_Transmit_AFSK/RTTY_Transmit_AFSK.ino b/examples/RTTY/RTTY_Transmit_AFSK/RTTY_Transmit_AFSK.ino new file mode 100644 index 00000000..23a66598 --- /dev/null +++ b/examples/RTTY/RTTY_Transmit_AFSK/RTTY_Transmit_AFSK.ino @@ -0,0 +1,130 @@ +/* + RadioLib RTTY Transmit AFSK Example + + This example sends RTTY message using SX1278's + FSK modem. The data is modulated as AFSK. + + Other modules that can be used for RTTY: + - SX127x/RFM9x + - RF69 + - SX1231 + - CC1101 + - Si443x/RFM2x + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// SX1278 has the following connections: +// NSS pin: 10 +// DIO0 pin: 2 +// RESET pin: 9 +// DIO1 pin: 3 +SX1278 radio = new Module(10, 2, 9, 3); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//SX1278 radio = RadioShield.ModuleA; + +// create AFSK client instance using the FSK module +// pin 5 is connected to SX1278 DIO2 +AFSKClient audio(&radio, 5); + +// create RTTY client instance using the AFSK instance +RTTYClient rtty(&audio); + +void setup() { + Serial.begin(9600); + + // initialize SX1278 with default settings + Serial.print(F("[SX1278] Initializing ... ")); + int state = radio.beginFSK(); + + // when using one of the non-LoRa modules for RTTY + // (RF69, CC1101, Si4432 etc.), use the basic begin() method + // int state = radio.begin(); + + if(state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while(true); + } + + // initialize RTTY client + // NOTE: Unlike FSK RTTY, AFSK requires no rounding of + // the frequency shift. + Serial.print(F("[RTTY] Initializing ... ")); + // space frequency: 400 Hz + // frequency shift: 170 Hz + // baud rate: 45 baud + // encoding: ASCII (7-bit) + // stop bits: 1 + state = rtty.begin(400, 170, 45); + if(state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while(true); + } + + /* + // RadioLib also provides ITA2 ("Baudot") support + rtty.begin(400, 170, 45, ITA2); + + // All transmissions in loop() (strings and numbers) + // will now be encoded using ITA2 code + + // ASCII characters that do not have ITA2 equivalent + // will be sent as NUL (including lower case letters!) + */ +} + +void loop() { + Serial.print(F("[RTTY] Sending RTTY data ... ")); + + // send out idle condition for 500 ms + rtty.idle(); + delay(500); + + // RTTYClient supports all methods of the Serial class + + // Arduino String class + String aStr = "Arduino String"; + rtty.println(aStr); + + // character array (C-String) + rtty.println("C-String"); + + // string saved in flash + rtty.println(F("Flash String")); + + // character + rtty.println('c'); + + // byte + // formatting DEC/HEX/OCT/BIN is supported for + // any integer type (byte/int/long) + rtty.println(255, HEX); + + // integer number + int i = 1000; + rtty.println(i); + + // floating point number + float f = -3.1415; + rtty.println(f, 3); + + Serial.println(F("done!")); + + // wait for a second before transmitting again + delay(1000); +} diff --git a/examples/SSTV/SSTV_Transmit/SSTV_Transmit.ino b/examples/SSTV/SSTV_Transmit/SSTV_Transmit.ino new file mode 100644 index 00000000..6b06bae3 --- /dev/null +++ b/examples/SSTV/SSTV_Transmit/SSTV_Transmit.ino @@ -0,0 +1,156 @@ +/* + RadioLib SSTV Transmit Example + + The following example sends SSTV picture using + SX1278's FSK modem. + + Other modules that can be used for SSTV: + - SX127x/RFM9x + - RF69 + - SX1231 + - SX126x + + NOTE: SSTV is an analog modulation, and + requires precise frequency control. + Some of the above modules can only + set their frequency in rough steps, + so the result can be distorted. + Using high-precision radio with TCXO + (like SX126x) is recommended. + + NOTE: Some platforms (such as Arduino Uno) + might not be fast enough to correctly + send pictures via high-speed modes + like Scottie2 or Martin2. For those, + lower speed modes such as Wrasse, + Scottie1 or Martin1 are recommended. + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// SX1278 has the following connections: +// NSS pin: 10 +// DIO0 pin: 2 +// RESET pin: 9 +// DIO1 pin: 3 +SX1278 radio = new Module(10, 2, 9, 3); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//SX1278 radio = RadioShield.ModuleA; + +// create SSTV client instance using the FSK module +SSTVClient sstv(&radio); + +// test "image" - actually just a single 320px line +// will be sent over and over again, to create vertical color stripes at the receiver +uint32_t line[320] = { + // black + 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, + 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, + + // blue + 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, + 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, + + // green + 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, + 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, + + // cyan + 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, + 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, + + // red + 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, + 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, + + // magenta + 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, + 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, + + // yellow + 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, + 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, + + // white + 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, + 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF +}; + +void setup() { + Serial.begin(9600); + + // initialize SX1278 with default settings + Serial.print(F("[SX1278] Initializing ... ")); + int state = radio.beginFSK(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } + + // when using one of the non-LoRa modules for SSTV + // (RF69, SX1231 etc.), use the basic begin() method + // int state = radio.begin(); + + // initialize SSTV client + Serial.print(F("[SSTV] Initializing ... ")); + // 0 Hz tone frequency: 434.0 MHz + // SSTV mode: Wrasse (SC2-180) + // correction factor: 0.95 + // NOTE: Due to different speeds of various platforms + // supported by RadioLib (Arduino Uno, ESP32 etc), + // and because SSTV is analog protocol, incorrect + // timing of pulses can lead to distortions. + // To compensate, correction factor can be used + // to adjust the length of timing pulses + // (lower number = shorter pulses). + // The value is usually around 0.95 (95%). + state = sstv.begin(434.0, Wrasse, 0.95); + if(state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while(true); + } + + // to help tune the receiver, SSTVClient can send + // continuous beep at the frequency corresponding to + // 1900 Hz in upper sideband (aka USB) modulation + // (SSTV header "leader tone") + /* + sstv.idle(); + while(true); + */ +} + +void loop() { + // send picture with 8 color stripes + Serial.print(F("[SSTV] Sending test picture ... ")); + + // send synchronization header first + sstv.sendHeader(); + + // send all picture lines + for(uint16_t i = 0; i < sstv.getPictureHeight(); i++) { + sstv.sendLine(line); + } + + // turn off transmitter + radio.standby(); + + Serial.println(F("done!")); + + delay(30000); +} diff --git a/examples/SSTV/SSTV_Transmit_AFSK/SSTV_Transmit_AFSK.ino b/examples/SSTV/SSTV_Transmit_AFSK/SSTV_Transmit_AFSK.ino new file mode 100644 index 00000000..e27bf67e --- /dev/null +++ b/examples/SSTV/SSTV_Transmit_AFSK/SSTV_Transmit_AFSK.ino @@ -0,0 +1,152 @@ +/* + RadioLib SSTV Transmit AFSK Example + + The following example sends SSTV picture using + SX1278's FSK modem. The data is modulated + as AFSK. + + Other modules that can be used for SSTV: + with AFSK modulation: + - SX127x/RFM9x + - RF69 + - SX1231 + - CC1101 + - Si443x/RFM2x + + NOTE: Some platforms (such as Arduino Uno) + might not be fast enough to correctly + send pictures via high-speed modes + like Scottie2 or Martin2. For those, + lower speed modes such as Wrasse, + Scottie1 or Martin1 are recommended. + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// SX1278 has the following connections: +// NSS pin: 10 +// DIO0 pin: 2 +// RESET pin: 9 +// DIO1 pin: 3 +SX1278 radio = new Module(10, 2, 9, 3); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//SX1278 radio = RadioShield.ModuleA; + +// create AFSK client instance using the FSK module +// pin 5 is connected to SX1278 DIO2 +AFSKClient audio(&radio, 5); + +// create SSTV client instance using the AFSK instance +SSTVClient sstv(&audio); + +// test "image" - actually just a single 320px line +// will be sent over and over again, to create vertical color stripes at the receiver +uint32_t line[320] = { + // black + 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, + 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, + + // blue + 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, + 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, 0x0000FF, + + // green + 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, + 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, 0x00FF00, + + // cyan + 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, + 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, 0x00FFFF, + + // red + 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, + 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, 0xFF0000, + + // magenta + 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, + 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, 0xFF00FF, + + // yellow + 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, + 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, 0xFFFF00, + + // white + 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, + 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF +}; + +void setup() { + Serial.begin(9600); + + // initialize SX1278 with default settings + Serial.print(F("[SX1278] Initializing ... ")); + int state = radio.beginFSK(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } + + // when using one of the non-LoRa modules for SSTV + // (RF69, SX1231 etc.), use the basic begin() method + // int state = radio.begin(); + + // initialize SSTV client + Serial.print(F("[SSTV] Initializing ... ")); + // SSTV mode: Wrasse (SC2-180) + // correction factor: 0.95 + // NOTE: Due to different speeds of various platforms + // supported by RadioLib (Arduino Uno, ESP32 etc), + // and because SSTV is analog protocol, incorrect + // timing of pulses can lead to distortions. + // To compensate, correction factor can be used + // to adjust the length of timing pulses + // (lower number = shorter pulses). + // The value is usually around 0.95 (95%). + state = sstv.begin(Wrasse, 0.95); + if(state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while(true); + } + + // to help tune the receiver, SSTVClient can send + // continuous 1900 Hz beep + /* + sstv.idle(); + while(true); + */ +} + +void loop() { + // send picture with 8 color stripes + Serial.print(F("[SSTV] Sending test picture ... ")); + + // send synchronization header first + sstv.sendHeader(); + + // send all picture lines + for(uint16_t i = 0; i < sstv.getPictureHeight(); i++) { + sstv.sendLine(line); + } + + // turn off transmitter + radio.standby(); + + Serial.println(F("done!")); + + delay(30000); +} diff --git a/examples/SX1231/SX1231_Receive/SX1231_Receive.ino b/examples/SX1231/SX1231_Receive/SX1231_Receive.ino index 727de1e5..18d0354c 100644 --- a/examples/SX1231/SX1231_Receive/SX1231_Receive.ino +++ b/examples/SX1231/SX1231_Receive/SX1231_Receive.ino @@ -7,6 +7,9 @@ interface. Please see RF69 examples for examples on AES, address filtering, interrupts and settings. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#rf69sx1231 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -18,24 +21,18 @@ // CS pin: 10 // DIO0 pin: 2 // RESET pin: 3 -SX1231 rf = new Module(10, 2, 3); +SX1231 radio = new Module(10, 2, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//SX1231 rf = RadioShield.ModuleA; +//SX1231 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize SX1231 with default settings Serial.print(F("[SX1231] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bit rate: 48.0 kbps - // Rx bandwidth: 125.0 kHz - // frequency deviation: 50.0 kHz - // output power: 13 dBm - // sync word: 0x2D01 - int state = rf.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -50,12 +47,12 @@ void loop() { // you can receive data as an Arduino String String str; - int state = rf.receive(str); + int state = radio.receive(str); // you can also receive data as byte array /* byte byteArr[8]; - int state = rf.receive(byteArr, 8); + int state = radio.receive(byteArr, 8); */ if (state == ERR_NONE) { diff --git a/examples/SX1231/SX1231_Transmit/SX1231_Transmit.ino b/examples/SX1231/SX1231_Transmit/SX1231_Transmit.ino index c781b02a..0f8cd14b 100644 --- a/examples/SX1231/SX1231_Transmit/SX1231_Transmit.ino +++ b/examples/SX1231/SX1231_Transmit/SX1231_Transmit.ino @@ -7,6 +7,9 @@ interface. Please see RF69 examples for examples on AES, address filtering, interrupts and settings. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#rf69sx1231 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -18,24 +21,18 @@ // CS pin: 10 // DIO0 pin: 2 // RESET pin: 3 -SX1231 rf = new Module(10, 2, 3); +SX1231 radio = new Module(10, 2, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//SX1231 rf = RadioShield.ModuleA; +//SX1231 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize SX1231 with default settings Serial.print(F("[SX1231] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bit rate: 48.0 kbps - // Rx bandwidth: 125.0 kHz - // frequency deviation: 50.0 kHz - // output power: 13 dBm - // sync word: 0x2D01 - int state = rf.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -49,21 +46,21 @@ void loop() { Serial.print(F("[SX1231] Transmitting packet ... ")); // you can transmit C-string or Arduino string up to 256 characters long - int state = rf.transmit("Hello World!"); + int state = radio.transmit("Hello World!"); // you can also transmit byte array up to 256 bytes long /* - byte byteArr[] = {0x01, 0x23, 0x45, 0x56, 0x78, 0xAB, 0xCD, 0xEF}; - int state = rf.transmit(byteArr, 8); + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; + int state = radio.transmit(byteArr, 8); */ if (state == ERR_NONE) { // the packet was successfully transmitted - Serial.println(F(" success!")); + Serial.println(F("success!")); } else if (state == ERR_PACKET_TOO_LONG) { // the supplied packet was longer than 256 bytes - Serial.println(F(" too long!")); + Serial.println(F("too long!")); } diff --git a/examples/SX126x/SX126x_Channel_Activity_Detection/SX126x_Channel_Activity_Detection.ino b/examples/SX126x/SX126x_Channel_Activity_Detection/SX126x_Channel_Activity_Detection.ino index 99209b99..b888a95d 100644 --- a/examples/SX126x/SX126x_Channel_Activity_Detection/SX126x_Channel_Activity_Detection.ino +++ b/examples/SX126x/SX126x_Channel_Activity_Detection/SX126x_Channel_Activity_Detection.ino @@ -8,6 +8,9 @@ Other modules from SX126x family can also be used. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx126x---lora-modem + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -20,29 +23,18 @@ // DIO1 pin: 2 // NRST pin: 3 // BUSY pin: 9 -SX1262 lora = new Module(10, 2, 3, 9); +SX1262 radio = new Module(10, 2, 3, 9); // or using RadioShield // https://github.com/jgromes/RadioShield -//SX1262 lora = RadioShield.ModuleA; +//SX1262 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize SX1262 with default settings Serial.print(F("[SX1262] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bandwidth: 125.0 kHz - // spreading factor: 9 - // coding rate: 7 - // sync word: 0x12 (private network) - // output power: 14 dBm - // current limit: 60 mA - // preamble length: 8 symbols - // TCXO voltage: 1.6 V (set to 0 to not use TCXO) - // regulator: DC-DC (set to true to use LDO) - // CRC: enabled - int state = lora.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -56,7 +48,7 @@ void loop() { Serial.print(F("[SX1262] Scanning channel for LoRa transmission ... ")); // start scanning current channel - int state = lora.scanChannel(); + int state = radio.scanChannel(); if (state == LORA_DETECTED) { // LoRa preamble was detected diff --git a/examples/SX126x/SX126x_FSK_Modem/SX126x_FSK_Modem.ino b/examples/SX126x/SX126x_FSK_Modem/SX126x_FSK_Modem.ino index e3e04627..d450f9c6 100644 --- a/examples/SX126x/SX126x_FSK_Modem/SX126x_FSK_Modem.ino +++ b/examples/SX126x/SX126x_FSK_Modem/SX126x_FSK_Modem.ino @@ -9,6 +9,9 @@ modem and use the appropriate configuration methods. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx126x---fsk-modem + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -21,30 +24,18 @@ // DIO1 pin: 2 // NRST pin: 3 // BUSY pin: 9 -SX1262 fsk = new Module(10, 2, 3, 9); +SX1262 radio = new Module(10, 2, 3, 9); // or using RadioShield // https://github.com/jgromes/RadioShield -//SX1262 fsk = RadioShield.ModuleA; +//SX1262 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize SX1262 FSK modem with default settings Serial.print(F("[SX1262] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bit rate: 48.0 kbps - // frequency deviation: 50.0 kHz - // Rx bandwidth: 156.2 kHz - // output power: 14 dBm - // current limit: 60.0 mA - // preamble length: 16 bits - // data shaping: Gaussian, BT = 0.5 - // TCXO voltage: 1.6 V (set to 0 to not use TCXO) - // regulator: DC-DC (set to true to use LDO) - // sync word: 0x2D 0x01 - // CRC: enabled, CRC16 (CCIT) - int state = fsk.beginFSK(); + int state = radio.beginFSK(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -55,21 +46,21 @@ void setup() { // if needed, you can switch between LoRa and FSK modes // - // lora.begin() start LoRa mode (and disable FSK) - // lora.beginFSK() start FSK mode (and disable LoRa) + // radio.begin() start LoRa mode (and disable FSK) + // radio.beginFSK() start FSK mode (and disable LoRa) // the following settings can also // be modified at run-time - state = fsk.setFrequency(433.5); - state = fsk.setBitRate(100.0); - state = fsk.setFrequencyDeviation(10.0); - state = fsk.setRxBandwidth(250.0); - state = fsk.setOutputPower(10.0); - state = fsk.setCurrentLimit(100.0); - state = fsk.setDataShaping(1.0); + state = radio.setFrequency(433.5); + state = radio.setBitRate(100.0); + state = radio.setFrequencyDeviation(10.0); + state = radio.setRxBandwidth(250.0); + state = radio.setOutputPower(10.0); + state = radio.setCurrentLimit(100.0); + state = radio.setDataShaping(RADIOLIB_SHAPING_1_0); uint8_t syncWord[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; - state = fsk.setSyncWord(syncWord, 8); + state = radio.setSyncWord(syncWord, 8); if (state != ERR_NONE) { Serial.print(F("Unable to set configuration, code ")); Serial.println(state); @@ -78,15 +69,15 @@ void setup() { // FSK modem on SX126x can handle the sync word setting in bits, not just // whole bytes. The value used is left-justified. - // This makes same result as fsk.setSyncWord(syncWord, 8): - state = fsk.setSyncBits(syncWord, 64); + // This makes same result as radio.setSyncWord(syncWord, 8): + state = radio.setSyncBits(syncWord, 64); // This will use 0x012 as sync word (12 bits only): - state = fsk.setSyncBits(syncWord, 12); + state = radio.setSyncBits(syncWord, 12); // FSK modem allows advanced CRC configuration // Default is CCIT CRC16 (2 bytes, initial 0x1D0F, polynomial 0x1021, inverted) // Set CRC to IBM CRC (2 bytes, initial 0xFFFF, polynomial 0x8005, non-inverted) - state = fsk.setCRC(2, 0xFFFF, 0x8005, false); + state = radio.setCRC(2, 0xFFFF, 0x8005, false); // set CRC length to 0 to disable CRC #warning "This sketch is just an API guide! Read the note at line 6." @@ -97,11 +88,11 @@ void loop() { // as the LoRa modem, even their interrupt-driven versions // transmit FSK packet - int state = fsk.transmit("Hello World!"); + int state = radio.transmit("Hello World!"); /* - byte byteArr[] = {0x01, 0x23, 0x45, 0x56, - 0x78, 0xAB, 0xCD, 0xEF}; - int state = lora.transmit(byteArr, 8); + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, + 0x89, 0xAB, 0xCD, 0xEF}; + int state = radio.transmit(byteArr, 8); */ if (state == ERR_NONE) { Serial.println(F("[SX1262] Packet transmitted successfully!")); @@ -116,10 +107,10 @@ void loop() { // receive FSK packet String str; - state = fsk.receive(str); + state = radio.receive(str); /* byte byteArr[8]; - int state = lora.receive(byteArr, 8); + int state = radio.receive(byteArr, 8); */ if (state == ERR_NONE) { Serial.println(F("[SX1262] Received packet!")); @@ -139,13 +130,13 @@ void loop() { // to transmit packet to a particular address, // use the following methods: // - // fsk.transmit("Hello World!", address); - // fsk.startTransmit("Hello World!", address); + // radio.transmit("Hello World!", address); + // radio.startTransmit("Hello World!", address); // set node address to 0x02 - state = fsk.setNodeAddress(0x02); + state = radio.setNodeAddress(0x02); // set broadcast address to 0xFF - state = fsk.setBroadcastAddress(0xFF); + state = radio.setBroadcastAddress(0xFF); if (state != ERR_NONE) { Serial.println(F("[SX1262] Unable to set address filter, code ")); Serial.println(state); @@ -155,7 +146,7 @@ void loop() { // NOTE: calling this method will also erase previously set // node and broadcast address /* - state = fsk.disableAddressFiltering(); + state = radio.disableAddressFiltering(); if (state != ERR_NONE) { Serial.println(F("Unable to remove address filter, code ")); } diff --git a/examples/SX126x/SX126x_Receive/SX126x_Receive.ino b/examples/SX126x/SX126x_Receive/SX126x_Receive.ino index c95592f0..23969cb1 100644 --- a/examples/SX126x/SX126x_Receive/SX126x_Receive.ino +++ b/examples/SX126x/SX126x_Receive/SX126x_Receive.ino @@ -13,6 +13,9 @@ Other modules from SX126x family can also be used. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx126x---lora-modem + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -25,29 +28,18 @@ // DIO1 pin: 2 // NRST pin: 3 // BUSY pin: 9 -SX1262 lora = new Module(10, 2, 3, 9); +SX1262 radio = new Module(10, 2, 3, 9); // or using RadioShield // https://github.com/jgromes/RadioShield -//SX1262 lora = RadioShield.ModuleA; +//SX1262 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize SX1262 with default settings Serial.print(F("[SX1262] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bandwidth: 125.0 kHz - // spreading factor: 9 - // coding rate: 7 - // sync word: 0x12 (private network) - // output power: 14 dBm - // current limit: 60 mA - // preamble length: 8 symbols - // TCXO voltage: 1.6 V (set to 0 to not use TCXO) - // regulator: DC-DC (set to true to use LDO) - // CRC: enabled - int state = lora.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -65,12 +57,12 @@ void loop() { // See example ReceiveInterrupt for details // on non-blocking reception method. String str; - int state = lora.receive(str); + int state = radio.receive(str); // you can also receive data as byte array /* byte byteArr[8]; - int state = lora.receive(byteArr, 8); + int state = radio.receive(byteArr, 8); */ if (state == ERR_NONE) { @@ -84,13 +76,13 @@ void loop() { // print the RSSI (Received Signal Strength Indicator) // of the last received packet Serial.print(F("[SX1262] RSSI:\t\t")); - Serial.print(lora.getRSSI()); + Serial.print(radio.getRSSI()); Serial.println(F(" dBm")); // print the SNR (Signal-to-Noise Ratio) // of the last received packet Serial.print(F("[SX1262] SNR:\t\t")); - Serial.print(lora.getSNR()); + Serial.print(radio.getSNR()); Serial.println(F(" dB")); } else if (state == ERR_RX_TIMEOUT) { diff --git a/examples/SX126x/SX126x_Receive_Interrupt/SX126x_Receive_Interrupt.ino b/examples/SX126x/SX126x_Receive_Interrupt/SX126x_Receive_Interrupt.ino index 59d49f53..3932f7b0 100644 --- a/examples/SX126x/SX126x_Receive_Interrupt/SX126x_Receive_Interrupt.ino +++ b/examples/SX126x/SX126x_Receive_Interrupt/SX126x_Receive_Interrupt.ino @@ -12,7 +12,10 @@ - coding rate - sync word - Other modules from SX126x/RFM9x family can also be used. + Other modules from SX126x family can also be used. + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx126x---lora-modem For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ @@ -26,29 +29,18 @@ // DIO1 pin: 2 // NRST pin: 3 // BUSY pin: 9 -SX1262 lora = new Module(10, 2, 3, 9); +SX1262 radio = new Module(10, 2, 3, 9); // or using RadioShield // https://github.com/jgromes/RadioShield -//SX1262 lora = RadioShield.ModuleA; +//SX1262 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize SX1262 with default settings Serial.print(F("[SX1262] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bandwidth: 125.0 kHz - // spreading factor: 9 - // coding rate: 7 - // sync word: 0x12 (private network) - // output power: 14 dBm - // current limit: 60 mA - // preamble length: 8 symbols - // TCXO voltage: 1.6 V (set to 0 to not use TCXO) - // regulator: DC-DC (set to true to use LDO) - // CRC: enabled - int state = lora.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -59,11 +51,11 @@ void setup() { // set the function that will be called // when new packet is received - lora.setDio1Action(setFlag); + radio.setDio1Action(setFlag); // start listening for LoRa packets Serial.print(F("[SX1262] Starting to listen ... ")); - state = lora.startReceive(); + state = radio.startReceive(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -75,12 +67,12 @@ void setup() { // if needed, 'listen' mode can be disabled by calling // any of the following methods: // - // lora.standby() - // lora.sleep() - // lora.transmit(); - // lora.receive(); - // lora.readData(); - // lora.scanChannel(); + // radio.standby() + // radio.sleep() + // radio.transmit(); + // radio.receive(); + // radio.readData(); + // radio.scanChannel(); } // flag to indicate that a packet was received @@ -115,12 +107,12 @@ void loop() { // you can read received data as an Arduino String String str; - int state = lora.readData(str); + int state = radio.readData(str); // you can also read received data as byte array /* byte byteArr[8]; - int state = lora.readData(byteArr, 8); + int state = radio.readData(byteArr, 8); */ if (state == ERR_NONE) { @@ -133,12 +125,12 @@ void loop() { // print RSSI (Received Signal Strength Indicator) Serial.print(F("[SX1262] RSSI:\t\t")); - Serial.print(lora.getRSSI()); + Serial.print(radio.getRSSI()); Serial.println(F(" dBm")); // print SNR (Signal-to-Noise Ratio) Serial.print(F("[SX1262] SNR:\t\t")); - Serial.print(lora.getSNR()); + Serial.print(radio.getSNR()); Serial.println(F(" dB")); } else if (state == ERR_CRC_MISMATCH) { @@ -153,7 +145,7 @@ void loop() { } // put module back to listen mode - lora.startReceive(); + radio.startReceive(); // we're ready to receive more packets, // enable interrupt service routine diff --git a/examples/SX126x/SX126x_Settings/SX126x_Settings.ino b/examples/SX126x/SX126x_Settings/SX126x_Settings.ino index 3c8a3e5e..f485284f 100644 --- a/examples/SX126x/SX126x_Settings/SX126x_Settings.ino +++ b/examples/SX126x/SX126x_Settings/SX126x_Settings.ino @@ -17,6 +17,9 @@ Other modules from SX126x family can also be used. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx126x---lora-modem + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -29,36 +32,25 @@ // DIO1 pin: 2 // NRST pin: 3 // BUSY pin: 9 -SX1262 loraSX1262 = new Module(10, 2, 3, 9); +SX1262 radio1 = new Module(10, 2, 3, 9); // SX12628 has different connections: // NSS pin: 8 // DIO1 pin: 4 // NRST pin: 5 // BUSY pin: 6 -SX1268 loraSX1268 = new Module(8, 4, 5, 6); +SX1268 radio2 = new Module(8, 4, 5, 6); // or using RadioShield // https://github.com/jgromes/RadioShield -//SX1261 loraSX1261 = RadioShield.ModuleB; +//SX1261 radio3 = RadioShield.ModuleB; void setup() { Serial.begin(9600); // initialize SX1268 with default settings Serial.print(F("[SX1262] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bandwidth: 125.0 kHz - // spreading factor: 9 - // coding rate: 7 - // sync word: 0x12 (private network) - // output power: 14 dBm - // current limit: 60 mA - // preamble length: 8 symbols - // TCXO voltage: 1.6 V (set to 0 to not use TCXO) - // regulator: DC-DC (set to true to use LDO) - // CRC: enabled - int state = loraSX1262.begin(); + int state = radio1.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -76,12 +68,10 @@ void setup() { // bandwidth: 500.0 kHz // spreading factor: 6 // coding rate: 5 - // sync word: 0x34 (public network) + // sync word: 0x34 (public network/LoRaWAN) // output power: 2 dBm - // current limit: 50 mA // preamble length: 20 symbols - // CRC: enabled - state = loraSX1268.begin(915.0, 500.0, 6, 5, 0x3444, 50, 20); + state = radio2.begin(915.0, 500.0, 6, 5, 0x34, 20); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -94,56 +84,56 @@ void setup() { // and check if the configuration was changed successfully // set carrier frequency to 433.5 MHz - if (loraSX1262.setFrequency(433.5) == ERR_INVALID_FREQUENCY) { + if (radio1.setFrequency(433.5) == ERR_INVALID_FREQUENCY) { Serial.println(F("Selected frequency is invalid for this module!")); while (true); } // set bandwidth to 250 kHz - if (loraSX1262.setBandwidth(250.0) == ERR_INVALID_BANDWIDTH) { + if (radio1.setBandwidth(250.0) == ERR_INVALID_BANDWIDTH) { Serial.println(F("Selected bandwidth is invalid for this module!")); while (true); } // set spreading factor to 10 - if (loraSX1262.setSpreadingFactor(10) == ERR_INVALID_SPREADING_FACTOR) { + if (radio1.setSpreadingFactor(10) == ERR_INVALID_SPREADING_FACTOR) { Serial.println(F("Selected spreading factor is invalid for this module!")); while (true); } // set coding rate to 6 - if (loraSX1262.setCodingRate(6) == ERR_INVALID_CODING_RATE) { + if (radio1.setCodingRate(6) == ERR_INVALID_CODING_RATE) { Serial.println(F("Selected coding rate is invalid for this module!")); while (true); } - // set LoRa sync word to 0x1234 - if (loraSX1262.setSyncWord(0x1234) != ERR_NONE) { + // set LoRa sync word to 0xAB + if (radio1.setSyncWord(0xAB) != ERR_NONE) { Serial.println(F("Unable to set sync word!")); while (true); } // set output power to 10 dBm (accepted range is -17 - 22 dBm) - if (loraSX1262.setOutputPower(10) == ERR_INVALID_OUTPUT_POWER) { + if (radio1.setOutputPower(10) == ERR_INVALID_OUTPUT_POWER) { Serial.println(F("Selected output power is invalid for this module!")); while (true); } // set over current protection limit to 80 mA (accepted range is 45 - 240 mA) // NOTE: set value to 0 to disable overcurrent protection - if (loraSX1262.setCurrentLimit(80) == ERR_INVALID_CURRENT_LIMIT) { + if (radio1.setCurrentLimit(80) == ERR_INVALID_CURRENT_LIMIT) { Serial.println(F("Selected current limit is invalid for this module!")); while (true); } // set LoRa preamble length to 15 symbols (accepted range is 0 - 65535) - if (loraSX1262.setPreambleLength(15) == ERR_INVALID_PREAMBLE_LENGTH) { + if (radio1.setPreambleLength(15) == ERR_INVALID_PREAMBLE_LENGTH) { Serial.println(F("Selected preamble length is invalid for this module!")); while (true); } // disable CRC - if (loraSX1262.setCRC(false) == ERR_INVALID_CRC_CONFIGURATION) { + if (radio1.setCRC(false) == ERR_INVALID_CRC_CONFIGURATION) { Serial.println(F("Selected CRC is invalid for this module!")); while (true); } @@ -151,7 +141,7 @@ void setup() { // Some SX126x modules have TCXO (temperature compensated crystal // oscillator). To configure TCXO reference voltage, // the following method can be used. - if (loraSX1262.setTCXO(2.4) == ERR_INVALID_TCXO_VOLTAGE) { + if (radio1.setTCXO(2.4) == ERR_INVALID_TCXO_VOLTAGE) { Serial.println(F("Selected TCXO voltage is invalid for this module!")); while (true); } @@ -160,7 +150,7 @@ void setup() { // this feature, the following method can be used. // NOTE: As long as DIO2 is configured to control RF switch, // it can't be used as interrupt pin! - if (loraSX1262.setDio2AsRfSwitch() != ERR_NONE) { + if (radio1.setDio2AsRfSwitch() != ERR_NONE) { Serial.println(F("Failed to set DIO2 as RF switch!")); while (true); } diff --git a/examples/SX126x/SX126x_Transmit/SX126x_Transmit.ino b/examples/SX126x/SX126x_Transmit/SX126x_Transmit.ino index 574fdff3..541645ee 100644 --- a/examples/SX126x/SX126x_Transmit/SX126x_Transmit.ino +++ b/examples/SX126x/SX126x_Transmit/SX126x_Transmit.ino @@ -9,6 +9,9 @@ Other modules from SX126x family can also be used. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx126x---lora-modem + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -21,29 +24,18 @@ // DIO1 pin: 2 // NRST pin: 3 // BUSY pin: 9 -SX1262 lora = new Module(10, 2, 3, 9); +SX1262 radio = new Module(10, 2, 3, 9); // or using RadioShield // https://github.com/jgromes/RadioShield -//SX1262 lora = RadioShield.ModuleA; +//SX1262 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize SX1262 with default settings Serial.print(F("[SX1262] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bandwidth: 125.0 kHz - // spreading factor: 9 - // coding rate: 7 - // sync word: 0x12 (private network) - // output power: 14 dBm - // current limit: 60 mA - // preamble length: 8 symbols - // TCXO voltage: 1.6 V (set to 0 to not use TCXO) - // regulator: DC-DC (set to true to use LDO) - // CRC: enabled - int state = lora.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -51,6 +43,16 @@ void setup() { Serial.println(state); while (true); } + + // some modules have an external RF switch + // controlled via two pins (RX enable, TX enable) + // to enable automatic control of the switch, + // call the following method + // RX enable: 4 + // TX enable: 5 + /* + radio.setRfSwitchPins(4, 5); + */ } void loop() { @@ -61,12 +63,12 @@ void loop() { // NOTE: transmit() is a blocking method! // See example SX126x_Transmit_Interrupt for details // on non-blocking transmission method. - int state = lora.transmit("Hello World!"); + int state = radio.transmit("Hello World!"); // you can also transmit byte array up to 256 bytes long /* byte byteArr[] = {0x01, 0x23, 0x45, 0x56, 0x78, 0xAB, 0xCD, 0xEF}; - int state = lora.transmit(byteArr, 8); + int state = radio.transmit(byteArr, 8); */ if (state == ERR_NONE) { @@ -75,7 +77,7 @@ void loop() { // print measured data rate Serial.print(F("[SX1262] Datarate:\t")); - Serial.print(lora.getDataRate()); + Serial.print(radio.getDataRate()); Serial.println(F(" bps")); } else if (state == ERR_PACKET_TOO_LONG) { diff --git a/examples/SX126x/SX126x_Transmit_Interrupt/SX126x_Transmit_Interrupt.ino b/examples/SX126x/SX126x_Transmit_Interrupt/SX126x_Transmit_Interrupt.ino index 157f00a1..20600a11 100644 --- a/examples/SX126x/SX126x_Transmit_Interrupt/SX126x_Transmit_Interrupt.ino +++ b/examples/SX126x/SX126x_Transmit_Interrupt/SX126x_Transmit_Interrupt.ino @@ -10,6 +10,9 @@ Other modules from SX126x family can also be used. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx126x---lora-modem + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -22,7 +25,11 @@ // DIO1 pin: 2 // NRST pin: 3 // BUSY pin: 9 -SX1262 lora = new Module(10, 2, 3, 9); +SX1262 radio = new Module(10, 2, 3, 9); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//SX1262 radio = RadioShield.ModuleA; // save transmission state between loops int transmissionState = ERR_NONE; @@ -32,18 +39,7 @@ void setup() { // initialize SX1262 with default settings Serial.print(F("[SX1262] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bandwidth: 125.0 kHz - // spreading factor: 9 - // coding rate: 7 - // sync word: 0x12 (private network) - // output power: 14 dBm - // current limit: 60 mA - // preamble length: 8 symbols - // TCXO voltage: 1.6 V (set to 0 to not use TCXO) - // regulator: DC-DC (set to true to use LDO) - // CRC: enabled - int state = lora.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -54,20 +50,20 @@ void setup() { // set the function that will be called // when packet transmission is finished - lora.setDio1Action(setFlag); + radio.setDio1Action(setFlag); // start transmitting the first packet Serial.print(F("[SX1262] Sending first packet ... ")); // you can transmit C-string or Arduino string up to // 256 characters long - transmissionState = lora.startTransmit("Hello World!"); + transmissionState = radio.startTransmit("Hello World!"); // you can also transmit byte array up to 256 bytes long /* - byte byteArr[] = {0x01, 0x23, 0x45, 0x56, - 0x78, 0xAB, 0xCD, 0xEF}; - state = lora.transmit(byteArr, 8); + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, + 0x89, 0xAB, 0xCD, 0xEF}; + state = radio.startTransmit(byteArr, 8); */ } @@ -123,13 +119,13 @@ void loop() { // you can transmit C-string or Arduino string up to // 256 characters long - transmissionState = lora.startTransmit("Hello World!"); + transmissionState = radio.startTransmit("Hello World!"); // you can also transmit byte array up to 256 bytes long /* - byte byteArr[] = {0x01, 0x23, 0x45, 0x56, - 0x78, 0xAB, 0xCD, 0xEF}; - int state = lora.transmit(byteArr, 8); + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, + 0x89, 0xAB, 0xCD, 0xEF}; + int state = radio.startTransmit(byteArr, 8); */ // we're ready to send more packets, diff --git a/examples/SX127x/SX127x_Channel_Activity_Detection/SX127x_Channel_Activity_Detection.ino b/examples/SX127x/SX127x_Channel_Activity_Detection/SX127x_Channel_Activity_Detection.ino index 163f8273..ececb747 100644 --- a/examples/SX127x/SX127x_Channel_Activity_Detection/SX127x_Channel_Activity_Detection.ino +++ b/examples/SX127x/SX127x_Channel_Activity_Detection/SX127x_Channel_Activity_Detection.ino @@ -9,6 +9,9 @@ Other modules from SX127x/RFM9x family can also be used. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx127xrfm9x---lora-modem + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -21,27 +24,18 @@ // DIO0 pin: 2 // RESET pin: 9 // DIO1 pin: 3 -SX1278 lora = new Module(10, 2, 9, 3); +SX1278 radio = new Module(10, 2, 9, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//SX1278 lora = RadioShield.ModuleA; +//SX1278 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize SX1278 with default settings Serial.print(F("[SX1278] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bandwidth: 125.0 kHz - // spreading factor: 9 - // coding rate: 7 - // sync word: 0x12 - // output power: 17 dBm - // current limit: 100 mA - // preamble length: 8 symbols - // amplifier gain: 0 (automatic gain control) - int state = lora.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -55,15 +49,15 @@ void loop() { Serial.print(F("[SX1278] Scanning channel for LoRa preamble ... ")); // start scanning current channel - int state = lora.scanChannel(); + int state = radio.scanChannel(); if (state == PREAMBLE_DETECTED) { // LoRa preamble was detected - Serial.println(F(" detected preamble!")); + Serial.println(F("detected preamble!")); } else if (state == CHANNEL_FREE) { // no preamble was detected, channel is free - Serial.println(F(" channel is free!")); + Serial.println(F("channel is free!")); } diff --git a/examples/SX127x/SX127x_FSK_Modem/SX127x_FSK_Modem.ino b/examples/SX127x/SX127x_FSK_Modem/SX127x_FSK_Modem.ino index f9c89154..d6294889 100644 --- a/examples/SX127x/SX127x_FSK_Modem/SX127x_FSK_Modem.ino +++ b/examples/SX127x/SX127x_FSK_Modem/SX127x_FSK_Modem.ino @@ -9,6 +9,9 @@ modem and use the appropriate configuration methods. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx127xrfm9x---fsk-modem + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -21,7 +24,7 @@ // DIO0 pin: 2 // RESET pin: 9 // DIO1 pin: 3 -SX1278 fsk = new Module(10, 2, 9, 3); +SX1278 radio = new Module(10, 2, 9, 3); // or using RadioShield // https://github.com/jgromes/RadioShield @@ -32,16 +35,7 @@ void setup() { // initialize SX1278 FSK modem with default settings Serial.print(F("[SX1278] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bit rate: 48.0 kbps - // frequency deviation: 50.0 kHz - // Rx bandwidth: 125.0 kHz - // output power: 13 dBm - // current limit: 100 mA - // data shaping: Gaussian, BT = 0.3 - // sync word: 0x2D 0x01 - // OOK modulation: disabled - int state = fsk.beginFSK(); + int state = radio.beginFSK(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -52,21 +46,21 @@ void setup() { // if needed, you can switch between LoRa and FSK modes // - // lora.begin() start LoRa mode (and disable FSK) - // lora.beginFSK() start FSK mode (and disable LoRa) + // radio.begin() start LoRa mode (and disable FSK) + // radio.beginFSK() start FSK mode (and disable LoRa) // the following settings can also // be modified at run-time - state = fsk.setFrequency(433.5); - state = fsk.setBitRate(100.0); - state = fsk.setFrequencyDeviation(10.0); - state = fsk.setRxBandwidth(250.0); - state = fsk.setOutputPower(10.0); - state = fsk.setCurrentLimit(100); - state = fsk.setDataShaping(0.5); + state = radio.setFrequency(433.5); + state = radio.setBitRate(100.0); + state = radio.setFrequencyDeviation(10.0); + state = radio.setRxBandwidth(250.0); + state = radio.setOutputPower(10.0); + state = radio.setCurrentLimit(100); + state = radio.setDataShaping(RADIOLIB_SHAPING_0_5); uint8_t syncWord[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; - state = fsk.setSyncWord(syncWord, 8); + state = radio.setSyncWord(syncWord, 8); if (state != ERR_NONE) { Serial.print(F("Unable to set configuration, code ")); Serial.println(state); @@ -78,8 +72,8 @@ void setup() { // Also, data shaping changes from Gaussian filter to // simple filter with cutoff frequency. Make sure to call // setDataShapingOOK() to set the correct shaping! - state = fsk.setOOK(true); - state = fsk.setDataShapingOOK(1); + state = radio.setOOK(true); + state = radio.setDataShapingOOK(1); if (state != ERR_NONE) { Serial.print(F("Unable to change modulation, code ")); Serial.println(state); @@ -95,11 +89,11 @@ void loop() { // NOTE: FSK modem maximum packet length is 63 bytes! // transmit FSK packet - int state = fsk.transmit("Hello World!"); + int state = radio.transmit("Hello World!"); /* - byte byteArr[] = {0x01, 0x23, 0x45, 0x56, - 0x78, 0xAB, 0xCD, 0xEF}; - int state = lora.transmit(byteArr, 8); + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, + 0x89, 0xAB, 0xCD, 0xEF}; + int state = radio.transmit(byteArr, 8); */ if (state == ERR_NONE) { Serial.println(F("[SX1278] Packet transmitted successfully!")); @@ -114,10 +108,10 @@ void loop() { // receive FSK packet String str; - state = fsk.receive(str); + state = radio.receive(str); /* byte byteArr[8]; - int state = lora.receive(byteArr, 8); + int state = radio.receive(byteArr, 8); */ if (state == ERR_NONE) { Serial.println(F("[SX1278] Received packet!")); @@ -137,13 +131,13 @@ void loop() { // to transmit packet to a particular address, // use the following methods: // - // fsk.transmit("Hello World!", address); - // fsk.startTransmit("Hello World!", address); + // radio.transmit("Hello World!", address); + // radio.startTransmit("Hello World!", address); // set node address to 0x02 - state = fsk.setNodeAddress(0x02); + state = radio.setNodeAddress(0x02); // set broadcast address to 0xFF - state = fsk.setBroadcastAddress(0xFF); + state = radio.setBroadcastAddress(0xFF); if (state != ERR_NONE) { Serial.println(F("[SX1278] Unable to set address filter, code ")); Serial.println(state); @@ -151,9 +145,9 @@ void loop() { // address filtering can also be disabled // NOTE: calling this method will also erase previously set - // node and broadcast address + // node and broadcast address /* - state = fsk.disableAddressFiltering(); + state = radio.disableAddressFiltering(); if (state != ERR_NONE) { Serial.println(F("Unable to remove address filter, code ")); } @@ -164,7 +158,7 @@ void loop() { // sent to DIO1 (data) and DIO2 (clock) // activate direct mode transmitter - state = fsk.transmitDirect(); + state = radio.transmitDirect(); if (state != ERR_NONE) { Serial.println(F("[SX1278] Unable to start direct transmission mode, code ")); Serial.println(state); @@ -175,7 +169,7 @@ void loop() { // it is recommended to set data shaping to 0 // (no shaping) when transmitting audio - state = fsk.setDataShaping(0.0); + state = radio.setDataShaping(0.0); if (state != ERR_NONE) { Serial.println(F("[SX1278] Unable to set data shaping, code ")); Serial.println(state); @@ -199,7 +193,7 @@ void loop() { // direct mode transmissions can also be received // as bit stream on DIO1 (data) and DIO2 (clock) - state = fsk.receiveDirect(); + state = radio.receiveDirect(); if (state != ERR_NONE) { Serial.println(F("[SX1278] Unable to start direct reception mode, code ")); Serial.println(state); @@ -207,5 +201,5 @@ void loop() { // NOTE: you will not be able to send or receive packets // while direct mode is active! to deactivate it, call method - // fsk.packetMode() + // radio.packetMode() } diff --git a/examples/SX127x/SX127x_Receive/SX127x_Receive.ino b/examples/SX127x/SX127x_Receive/SX127x_Receive.ino index 5627bdc3..0f839eec 100644 --- a/examples/SX127x/SX127x_Receive/SX127x_Receive.ino +++ b/examples/SX127x/SX127x_Receive/SX127x_Receive.ino @@ -13,6 +13,9 @@ Other modules from SX127x/RFM9x family can also be used. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx127xrfm9x---lora-modem + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -25,27 +28,18 @@ // DIO0 pin: 2 // RESET pin: 9 // DIO1 pin: 3 -SX1278 lora = new Module(10, 2, 9, 3); +SX1278 radio = new Module(10, 2, 9, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//SX1278 lora = RadioShield.ModuleA; +//SX1278 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize SX1278 with default settings Serial.print(F("[SX1278] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bandwidth: 125.0 kHz - // spreading factor: 9 - // coding rate: 7 - // sync word: 0x12 - // output power: 17 dBm - // current limit: 100 mA - // preamble length: 8 symbols - // amplifier gain: 0 (automatic gain control) - int state = lora.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -63,12 +57,12 @@ void loop() { // See example ReceiveInterrupt for details // on non-blocking reception method. String str; - int state = lora.receive(str); + int state = radio.receive(str); // you can also receive data as byte array /* byte byteArr[8]; - int state = lora.receive(byteArr, 8); + int state = radio.receive(byteArr, 8); */ if (state == ERR_NONE) { @@ -82,19 +76,19 @@ void loop() { // print the RSSI (Received Signal Strength Indicator) // of the last received packet Serial.print(F("[SX1278] RSSI:\t\t\t")); - Serial.print(lora.getRSSI()); + Serial.print(radio.getRSSI()); Serial.println(F(" dBm")); // print the SNR (Signal-to-Noise Ratio) // of the last received packet Serial.print(F("[SX1278] SNR:\t\t\t")); - Serial.print(lora.getSNR()); + Serial.print(radio.getSNR()); Serial.println(F(" dB")); // print frequency error // of the last received packet Serial.print(F("[SX1278] Frequency error:\t")); - Serial.print(lora.getFrequencyError()); + Serial.print(radio.getFrequencyError()); Serial.println(F(" Hz")); } else if (state == ERR_RX_TIMEOUT) { diff --git a/examples/SX127x/SX127x_Receive_Interrupt/SX127x_Receive_Interrupt.ino b/examples/SX127x/SX127x_Receive_Interrupt/SX127x_Receive_Interrupt.ino index fbc20651..8a755bb8 100644 --- a/examples/SX127x/SX127x_Receive_Interrupt/SX127x_Receive_Interrupt.ino +++ b/examples/SX127x/SX127x_Receive_Interrupt/SX127x_Receive_Interrupt.ino @@ -14,6 +14,9 @@ Other modules from SX127x/RFM9x family can also be used. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx127xrfm9x---lora-modem + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -26,27 +29,18 @@ // DIO0 pin: 2 // RESET pin: 9 // DIO1 pin: 3 -SX1278 lora = new Module(10, 2, 9, 3); +SX1278 radio = new Module(10, 2, 9, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//SX1278 lora = RadioShield.ModuleA; +//SX1278 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize SX1278 with default settings Serial.print(F("[SX1278] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bandwidth: 125.0 kHz - // spreading factor: 9 - // coding rate: 7 - // sync word: 0x12 - // output power: 17 dBm - // current limit: 100 mA - // preamble length: 8 symbols - // amplifier gain: 0 (automatic gain control) - int state = lora.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -57,11 +51,11 @@ void setup() { // set the function that will be called // when new packet is received - lora.setDio0Action(setFlag); + radio.setDio0Action(setFlag); // start listening for LoRa packets Serial.print(F("[SX1278] Starting to listen ... ")); - state = lora.startReceive(); + state = radio.startReceive(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -73,12 +67,12 @@ void setup() { // if needed, 'listen' mode can be disabled by calling // any of the following methods: // - // lora.standby() - // lora.sleep() - // lora.transmit(); - // lora.receive(); - // lora.readData(); - // lora.scanChannel(); + // radio.standby() + // radio.sleep() + // radio.transmit(); + // radio.receive(); + // radio.readData(); + // radio.scanChannel(); } // flag to indicate that a packet was received @@ -113,12 +107,12 @@ void loop() { // you can read received data as an Arduino String String str; - int state = lora.readData(str); + int state = radio.readData(str); // you can also read received data as byte array /* byte byteArr[8]; - int state = lora.receive(byteArr, 8); + int state = radio.readData(byteArr, 8); */ if (state == ERR_NONE) { @@ -131,17 +125,17 @@ void loop() { // print RSSI (Received Signal Strength Indicator) Serial.print(F("[SX1278] RSSI:\t\t")); - Serial.print(lora.getRSSI()); + Serial.print(radio.getRSSI()); Serial.println(F(" dBm")); // print SNR (Signal-to-Noise Ratio) Serial.print(F("[SX1278] SNR:\t\t")); - Serial.print(lora.getSNR()); + Serial.print(radio.getSNR()); Serial.println(F(" dB")); // print frequency error Serial.print(F("[SX1278] Frequency error:\t")); - Serial.print(lora.getFrequencyError()); + Serial.print(radio.getFrequencyError()); Serial.println(F(" Hz")); } else if (state == ERR_CRC_MISMATCH) { @@ -156,7 +150,7 @@ void loop() { } // put module back to listen mode - lora.startReceive(); + radio.startReceive(); // we're ready to receive more packets, // enable interrupt service routine diff --git a/examples/SX127x/SX127x_Settings/SX127x_Settings.ino b/examples/SX127x/SX127x_Settings/SX127x_Settings.ino index 681c76d2..84f31fac 100644 --- a/examples/SX127x/SX127x_Settings/SX127x_Settings.ino +++ b/examples/SX127x/SX127x_Settings/SX127x_Settings.ino @@ -13,6 +13,9 @@ Other modules from SX127x/RFM9x family can also be used. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx127xrfm9x---lora-modem + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -25,34 +28,25 @@ // DIO0 pin: 2 // RESET pin: 9 // DIO1 pin: 3 -SX1278 loraSX1278 = new Module(10, 2, 9, 3); +SX1278 radio1 = new Module(10, 2, 9, 3); // SX1272 has different connections: // NSS pin: 9 // DIO0 pin: 4 // RESET pin: 5 // DIO1 pin: 6 -SX1272 loraSX1272 = new Module(9, 4, 5, 6); +SX1272 radio2 = new Module(9, 4, 5, 6); // or using RadioShield // https://github.com/jgromes/RadioShield -//SX1276 loraSX1276 = RadioShield.ModuleB; +//SX1276 radio3 = RadioShield.ModuleB; void setup() { Serial.begin(9600); // initialize SX1278 with default settings Serial.print(F("[SX1278] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bandwidth: 125.0 kHz - // spreading factor: 9 - // coding rate: 7 - // sync word: 0x12 - // output power: 17 dBm - // current limit: 100 mA - // preamble length: 8 symbols - // amplifier gain: 0 (automatic gain control) - int state = loraSX1278.begin(); + int state = radio1.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -76,10 +70,9 @@ void setup() { // coding rate: 5 // sync word: 0x14 // output power: 2 dBm - // current limit: 50 mA // preamble length: 20 symbols // amplifier gain: 1 (maximum gain) - state = loraSX1272.begin(915.0, 500.0, 6, 5, 0x14, 2); + state = radio2.begin(915.0, 500.0, 6, 5, 0x14, 2, 20, 1); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -91,36 +84,33 @@ void setup() { // you can also change the settings at runtime // and check if the configuration was changed successfully - // different modules accept different parameters - // see https://github.com/jgromes/LoRaLib/wiki/Supported-LoRa-modules - // set carrier frequency to 433.5 MHz - if (loraSX1278.setFrequency(433.5) == ERR_INVALID_FREQUENCY) { + if (radio1.setFrequency(433.5) == ERR_INVALID_FREQUENCY) { Serial.println(F("Selected frequency is invalid for this module!")); while (true); } // set bandwidth to 250 kHz - if (loraSX1278.setBandwidth(250.0) == ERR_INVALID_BANDWIDTH) { + if (radio1.setBandwidth(250.0) == ERR_INVALID_BANDWIDTH) { Serial.println(F("Selected bandwidth is invalid for this module!")); while (true); } // set spreading factor to 10 - if (loraSX1278.setSpreadingFactor(10) == ERR_INVALID_SPREADING_FACTOR) { + if (radio1.setSpreadingFactor(10) == ERR_INVALID_SPREADING_FACTOR) { Serial.println(F("Selected spreading factor is invalid for this module!")); while (true); } // set coding rate to 6 - if (loraSX1278.setCodingRate(6) == ERR_INVALID_CODING_RATE) { + if (radio1.setCodingRate(6) == ERR_INVALID_CODING_RATE) { Serial.println(F("Selected coding rate is invalid for this module!")); while (true); } // set LoRa sync word to 0x14 // NOTE: value 0x34 is reserved for LoRaWAN networks and should not be used - if (loraSX1278.setSyncWord(0x14) != ERR_NONE) { + if (radio1.setSyncWord(0x14) != ERR_NONE) { Serial.println(F("Unable to set sync word!")); while (true); } @@ -128,33 +118,33 @@ void setup() { // set output power to 10 dBm (accepted range is -3 - 17 dBm) // NOTE: 20 dBm value allows high power operation, but transmission // duty cycle MUST NOT exceed 1% - if (loraSX1278.setOutputPower(10) == ERR_INVALID_OUTPUT_POWER) { + if (radio1.setOutputPower(10) == ERR_INVALID_OUTPUT_POWER) { Serial.println(F("Selected output power is invalid for this module!")); while (true); } // set over current protection limit to 80 mA (accepted range is 45 - 240 mA) // NOTE: set value to 0 to disable overcurrent protection - if (loraSX1278.setCurrentLimit(80) == ERR_INVALID_CURRENT_LIMIT) { + if (radio1.setCurrentLimit(80) == ERR_INVALID_CURRENT_LIMIT) { Serial.println(F("Selected current limit is invalid for this module!")); while (true); } // set LoRa preamble length to 15 symbols (accepted range is 6 - 65535) - if (loraSX1278.setPreambleLength(15) == ERR_INVALID_PREAMBLE_LENGTH) { + if (radio1.setPreambleLength(15) == ERR_INVALID_PREAMBLE_LENGTH) { Serial.println(F("Selected preamble length is invalid for this module!")); while (true); } // set amplifier gain to 1 (accepted range is 1 - 6, where 1 is maximum gain) - // NOTE: set value to 0 to enable autmatic gain control + // NOTE: set value to 0 to enable automatic gain control // leave at 0 unless you know what you're doing - if (loraSX1278.setGain(1) == ERR_INVALID_GAIN) { + if (radio1.setGain(1) == ERR_INVALID_GAIN) { Serial.println(F("Selected gain is invalid for this module!")); while (true); } - Serial.println(F("All settings succesfully changed!")); + Serial.println(F("All settings successfully changed!")); } void loop() { diff --git a/examples/SX127x/SX127x_Transmit/SX127x_Transmit.ino b/examples/SX127x/SX127x_Transmit/SX127x_Transmit.ino index d14e76f7..6113046b 100644 --- a/examples/SX127x/SX127x_Transmit/SX127x_Transmit.ino +++ b/examples/SX127x/SX127x_Transmit/SX127x_Transmit.ino @@ -9,6 +9,9 @@ Other modules from SX127x/RFM9x family can also be used. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx127xrfm9x---lora-modem + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -21,27 +24,18 @@ // DIO0 pin: 2 // RESET pin: 9 // DIO1 pin: 3 -SX1278 lora = new Module(10, 2, 9, 3); +SX1278 radio = new Module(10, 2, 9, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//SX1278 lora = RadioShield.ModuleA; +//SX1278 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); // initialize SX1278 with default settings Serial.print(F("[SX1278] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bandwidth: 125.0 kHz - // spreading factor: 9 - // coding rate: 7 - // sync word: 0x12 - // output power: 17 dBm - // current limit: 100 mA - // preamble length: 8 symbols - // amplifier gain: 0 (automatic gain control) - int state = lora.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -49,6 +43,16 @@ void setup() { Serial.println(state); while (true); } + + // some modules have an external RF switch + // controlled via two pins (RX enable, TX enable) + // to enable automatic control of the switch, + // call the following method + // RX enable: 4 + // TX enable: 5 + /* + radio.setRfSwitchPins(4, 5); + */ } void loop() { @@ -59,12 +63,12 @@ void loop() { // NOTE: transmit() is a blocking method! // See example SX127x_Transmit_Interrupt for details // on non-blocking transmission method. - int state = lora.transmit("Hello World!"); + int state = radio.transmit("Hello World!"); // you can also transmit byte array up to 256 bytes long /* - byte byteArr[] = {0x01, 0x23, 0x45, 0x56, 0x78, 0xAB, 0xCD, 0xEF}; - int state = lora.transmit(byteArr, 8); + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; + int state = radio.transmit(byteArr, 8); */ if (state == ERR_NONE) { @@ -73,16 +77,16 @@ void loop() { // print measured data rate Serial.print(F("[SX1278] Datarate:\t")); - Serial.print(lora.getDataRate()); + Serial.print(radio.getDataRate()); Serial.println(F(" bps")); } else if (state == ERR_PACKET_TOO_LONG) { // the supplied packet was longer than 256 bytes - Serial.println(F(" too long!")); + Serial.println(F("too long!")); } else if (state == ERR_TX_TIMEOUT) { - // timeout occured while transmitting packet - Serial.println(F(" timeout!")); + // timeout occurred while transmitting packet + Serial.println(F("timeout!")); } else { // some other error occurred diff --git a/examples/SX127x/SX127x_Transmit_Interrupt/SX127x_Transmit_Interrupt.ino b/examples/SX127x/SX127x_Transmit_Interrupt/SX127x_Transmit_Interrupt.ino index 8368a7d4..7f4b33be 100644 --- a/examples/SX127x/SX127x_Transmit_Interrupt/SX127x_Transmit_Interrupt.ino +++ b/examples/SX127x/SX127x_Transmit_Interrupt/SX127x_Transmit_Interrupt.ino @@ -10,6 +10,9 @@ Other modules from SX127x/RFM9x family can also be used. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx127xrfm9x---lora-modem + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -22,11 +25,11 @@ // DIO0 pin: 2 // RESET pin: 9 // DIO1 pin: 3 -SX1278 lora = new Module(10, 2, 9, 3); +SX1278 radio = new Module(10, 2, 9, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//SX1278 lora = RadioShield.ModuleA; +//SX1278 radio = RadioShield.ModuleA; // save transmission state between loops int transmissionState = ERR_NONE; @@ -36,16 +39,7 @@ void setup() { // initialize SX1278 with default settings Serial.print(F("[SX1278] Initializing ... ")); - // carrier frequency: 434.0 MHz - // bandwidth: 125.0 kHz - // spreading factor: 9 - // coding rate: 7 - // sync word: 0x12 - // output power: 17 dBm - // current limit: 100 mA - // preamble length: 8 symbols - // amplifier gain: 0 (automatic gain control) - int state = lora.begin(); + int state = radio.begin(); if (state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -56,20 +50,20 @@ void setup() { // set the function that will be called // when packet transmission is finished - lora.setDio0Action(setFlag); + radio.setDio0Action(setFlag); // start transmitting the first packet Serial.print(F("[SX1278] Sending first packet ... ")); // you can transmit C-string or Arduino string up to // 256 characters long - transmissionState = lora.startTransmit("Hello World!"); + transmissionState = radio.startTransmit("Hello World!"); // you can also transmit byte array up to 256 bytes long /* - byte byteArr[] = {0x01, 0x23, 0x45, 0x56, - 0x78, 0xAB, 0xCD, 0xEF}; - state = lora.transmit(byteArr, 8); + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, + 0x89, 0xAB, 0xCD, 0xEF}; + state = radio.startTransmit(byteArr, 8); */ } @@ -125,13 +119,13 @@ void loop() { // you can transmit C-string or Arduino string up to // 256 characters long - transmissionState = lora.startTransmit("Hello World!"); + transmissionState = radio.startTransmit("Hello World!"); // you can also transmit byte array up to 256 bytes long /* - byte byteArr[] = {0x01, 0x23, 0x45, 0x56, - 0x78, 0xAB, 0xCD, 0xEF}; - int state = lora.transmit(byteArr, 8); + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, + 0x89, 0xAB, 0xCD, 0xEF}; + int state = radio.startTransmit(byteArr, 8); */ // we're ready to send more packets, diff --git a/examples/SX128x/SX128x_BLE_Modem/SX128x_BLE_Modem.ino b/examples/SX128x/SX128x_BLE_Modem/SX128x_BLE_Modem.ino new file mode 100644 index 00000000..96a96ffa --- /dev/null +++ b/examples/SX128x/SX128x_BLE_Modem/SX128x_BLE_Modem.ino @@ -0,0 +1,110 @@ +/* + RadioLib SX128x BLE Modem Example + + This example shows how to use BLE modem in SX128x chips. + RadioLib does not provide BLE protocol support (yet), + only compatibility with the physical layer. + + NOTE: The sketch below is just a guide on how to use + BLE modem, so this code should not be run directly! + Instead, modify the other examples to use BLE + modem and use the appropriate configuration + methods. + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx128x---ble-modem + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// SX1280 has the following connections: +// NSS pin: 10 +// DIO1 pin: 2 +// NRST pin: 3 +// BUSY pin: 9 +SX1280 radio = new Module(10, 2, 3, 9); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//SX1280 radio = RadioShield.ModuleA; + +void setup() { + Serial.begin(9600); + + // initialize SX1280 with default settings + Serial.print(F("[SX1280] Initializing ... ")); + int state = radio.beginBLE(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } + + // if needed, you can switch between any of the modems + // + // radio.begin() start LoRa modem (and disable BLE) + // radio.beginBLE() start BLE modem (and disable LoRa) + + // the following settings can also + // be modified at run-time + state = radio.setFrequency(2410.5); + state = radio.setBitRate(250); + state = radio.setFrequencyDeviation(100.0); + state = radio.setOutputPower(5); + state = radio.setDataShaping(1.0); + state = radio.setAccessAddress(0x12345678); + if (state != ERR_NONE) { + Serial.print(F("Unable to set configuration, code ")); + Serial.println(state); + while (true); + } + + #warning "This sketch is just an API guide! Read the note at line 6." +} + +void loop() { + // BLE modem can use the same transmit/receive methods + // as the LoRa modem, even their interrupt-driven versions + + // transmit BLE packet + int state = radio.transmit("Hello World!"); + /* + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, + 0x89, 0xAB, 0xCD, 0xEF}; + int state = radio.transmit(byteArr, 8); + */ + if (state == ERR_NONE) { + Serial.println(F("[SX1280] Packet transmitted successfully!")); + } else if (state == ERR_PACKET_TOO_LONG) { + Serial.println(F("[SX1280] Packet too long!")); + } else if (state == ERR_TX_TIMEOUT) { + Serial.println(F("[SX1280] Timed out while transmitting!")); + } else { + Serial.print(F("[SX1280] Failed to transmit packet, code ")); + Serial.println(state); + } + + // receive BLE packet + String str; + state = radio.receive(str); + /* + byte byteArr[8]; + int state = radio.receive(byteArr, 8); + */ + if (state == ERR_NONE) { + Serial.println(F("[SX1280] Received packet!")); + Serial.print(F("[SX1280] Data:\t")); + Serial.println(str); + } else if (state == ERR_RX_TIMEOUT) { + Serial.println(F("[SX1280] Timed out while waiting for packet!")); + } else { + Serial.print(F("[SX1280] Failed to receive packet, code ")); + Serial.println(state); + } +} diff --git a/examples/SX128x/SX128x_Channel_Activity_Detection/SX128x_Channel_Activity_Detection.ino b/examples/SX128x/SX128x_Channel_Activity_Detection/SX128x_Channel_Activity_Detection.ino new file mode 100644 index 00000000..cec1560a --- /dev/null +++ b/examples/SX128x/SX128x_Channel_Activity_Detection/SX128x_Channel_Activity_Detection.ino @@ -0,0 +1,68 @@ +/* + RadioLib SX128x Channel Activity Detection Example + + This example uses SX1280 to scan the current LoRa + channel and detect ongoing LoRa transmissions. + + Other modules from SX128x family can also be used. + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx128x---lora-modem + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// SX1280 has the following connections: +// NSS pin: 10 +// DIO1 pin: 2 +// NRST pin: 3 +// BUSY pin: 9 +SX1280 radio = new Module(10, 2, 3, 9); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//SX1280 radio = RadioShield.ModuleA; + +void setup() { + Serial.begin(9600); + + // initialize SX1280 with default settings + Serial.print(F("[SX1280] Initializing ... ")); + int state = radio.begin(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } +} + +void loop() { + Serial.print(F("[SX1280] Scanning channel for LoRa transmission ... ")); + + // start scanning current channel + int state = radio.scanChannel(); + + if (state == LORA_DETECTED) { + // LoRa preamble was detected + Serial.println(F("detected!")); + + } else if (state == CHANNEL_FREE) { + // no preamble was detected, channel is free + Serial.println(F("channel is free!")); + + } else { + // some other error occurred + Serial.print(F("failed, code ")); + Serial.println(state); + + } + + // wait 100 ms before new scan + delay(100); +} diff --git a/examples/SX128x/SX128x_FLRC_Modem/SX128x_FLRC_Modem.ino b/examples/SX128x/SX128x_FLRC_Modem/SX128x_FLRC_Modem.ino new file mode 100644 index 00000000..cf2d0e7c --- /dev/null +++ b/examples/SX128x/SX128x_FLRC_Modem/SX128x_FLRC_Modem.ino @@ -0,0 +1,109 @@ +/* + RadioLib SX128x FLRC Modem Example + + This example shows how to use FLRC modem in SX128x chips. + + NOTE: The sketch below is just a guide on how to use + FLRC modem, so this code should not be run directly! + Instead, modify the other examples to use FLRC + modem and use the appropriate configuration + methods. + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx128x---flrc-modem + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// SX1280 has the following connections: +// NSS pin: 10 +// DIO1 pin: 2 +// NRST pin: 3 +// BUSY pin: 9 +SX1280 radio = new Module(10, 2, 3, 9); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//SX1280 radio = RadioShield.ModuleA; + +void setup() { + Serial.begin(9600); + + // initialize SX1280 with default settings + Serial.print(F("[SX1280] Initializing ... ")); + int state = radio.beginFLRC(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } + + // if needed, you can switch between any of the modems + // + // radio.begin() start LoRa modem (and disable FLRC) + // radio.beginFLRC() start FLRC modem (and disable LoRa) + + // the following settings can also + // be modified at run-time + state = radio.setFrequency(2410.5); + state = radio.setBitRate(520); + state = radio.setCodingRate(2); + state = radio.setOutputPower(5); + state = radio.setDataShaping(1.0); + uint8_t syncWord[] = {0x01, 0x23, 0x45, 0x67}; + state = radio.setSyncWord(syncWord, 4); + if (state != ERR_NONE) { + Serial.print(F("Unable to set configuration, code ")); + Serial.println(state); + while (true); + } + + #warning "This sketch is just an API guide! Read the note at line 6." +} + +void loop() { + // FLRC modem can use the same transmit/receive methods + // as the LoRa modem, even their interrupt-driven versions + + // transmit FLRC packet + int state = radio.transmit("Hello World!"); + /* + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, + 0x89, 0xAB, 0xCD, 0xEF}; + int state = radio.transmit(byteArr, 8); + */ + if (state == ERR_NONE) { + Serial.println(F("[SX1280] Packet transmitted successfully!")); + } else if (state == ERR_PACKET_TOO_LONG) { + Serial.println(F("[SX1280] Packet too long!")); + } else if (state == ERR_TX_TIMEOUT) { + Serial.println(F("[SX1280] Timed out while transmitting!")); + } else { + Serial.println(F("[SX1280] Failed to transmit packet, code ")); + Serial.println(state); + } + + // receive FLRC packet + String str; + state = radio.receive(str); + /* + byte byteArr[8]; + int state = radio.receive(byteArr, 8); + */ + if (state == ERR_NONE) { + Serial.println(F("[SX1280] Received packet!")); + Serial.print(F("[SX1280] Data:\t")); + Serial.println(str); + } else if (state == ERR_RX_TIMEOUT) { + Serial.println(F("[SX1280] Timed out while waiting for packet!")); + } else { + Serial.print(F("[SX1280] Failed to receive packet, code ")); + Serial.println(state); + } +} diff --git a/examples/SX128x/SX128x_GFSK_Modem/SX128x_GFSK_Modem.ino b/examples/SX128x/SX128x_GFSK_Modem/SX128x_GFSK_Modem.ino new file mode 100644 index 00000000..2df0d6ac --- /dev/null +++ b/examples/SX128x/SX128x_GFSK_Modem/SX128x_GFSK_Modem.ino @@ -0,0 +1,109 @@ +/* + RadioLib SX128x GFSK Modem Example + + This example shows how to use GFSK modem in SX128x chips. + + NOTE: The sketch below is just a guide on how to use + GFSK modem, so this code should not be run directly! + Instead, modify the other examples to use GFSK + modem and use the appropriate configuration + methods. + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx128x---gfsk-modem + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// SX1280 has the following connections: +// NSS pin: 10 +// DIO1 pin: 2 +// NRST pin: 3 +// BUSY pin: 9 +SX1280 radio = new Module(10, 2, 3, 9); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//SX1280 radio = RadioShield.ModuleA; + +void setup() { + Serial.begin(9600); + + // initialize SX1280 with default settings + Serial.print(F("[SX1280] Initializing ... ")); + int state = radio.beginGFSK(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } + + // if needed, you can switch between any of the modems + // + // radio.begin() start LoRa modem (and disable GFSK) + // radio.beginGFSK() start GFSK modem (and disable LoRa) + + // the following settings can also + // be modified at run-time + state = radio.setFrequency(2410.5); + state = radio.setBitRate(200); + state = radio.setFrequencyDeviation(100.0); + state = radio.setOutputPower(5); + state = radio.setDataShaping(RADIOLIB_SHAPING_1_0); + uint8_t syncWord[] = {0x01, 0x23, 0x45, 0x67, 0x89}; + state = radio.setSyncWord(syncWord, 5); + if (state != ERR_NONE) { + Serial.print(F("Unable to set configuration, code ")); + Serial.println(state); + while (true); + } + + #warning "This sketch is just an API guide! Read the note at line 6." +} + +void loop() { + // GFSK modem can use the same transmit/receive methods + // as the LoRa modem, even their interrupt-driven versions + + // transmit GFSK packet + int state = radio.transmit("Hello World!"); + /* + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, + 0x89, 0xAB, 0xCD, 0xEF}; + int state = radio.transmit(byteArr, 8); + */ + if (state == ERR_NONE) { + Serial.println(F("[SX1280] Packet transmitted successfully!")); + } else if (state == ERR_PACKET_TOO_LONG) { + Serial.println(F("[SX1280] Packet too long!")); + } else if (state == ERR_TX_TIMEOUT) { + Serial.println(F("[SX1280] Timed out while transmitting!")); + } else { + Serial.println(F("[SX1280] Failed to transmit packet, code ")); + Serial.println(state); + } + + // receive GFSK packet + String str; + state = radio.receive(str); + /* + byte byteArr[8]; + int state = radio.receive(byteArr, 8); + */ + if (state == ERR_NONE) { + Serial.println(F("[SX1280] Received packet!")); + Serial.print(F("[SX1280] Data:\t")); + Serial.println(str); + } else if (state == ERR_RX_TIMEOUT) { + Serial.println(F("[SX1280] Timed out while waiting for packet!")); + } else { + Serial.print(F("[SX1280] Failed to receive packet, code ")); + Serial.println(state); + } +} diff --git a/examples/SX128x/SX128x_Ranging/SX128x_Ranging.ino b/examples/SX128x/SX128x_Ranging/SX128x_Ranging.ino new file mode 100644 index 00000000..f53b1a2d --- /dev/null +++ b/examples/SX128x/SX128x_Ranging/SX128x_Ranging.ino @@ -0,0 +1,80 @@ +/* + RadioLib SX128x Ranging Example + + This example performs ranging exchange between two + SX1280 LoRa radio modules. Ranging allows to measure + distance between the modules using time-of-flight + measurement. + + Only SX1280 and SX1282 support ranging! + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx128x---lora-modem + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// SX1280 has the following connections: +// NSS pin: 10 +// DIO1 pin: 2 +// NRST pin: 3 +// BUSY pin: 9 +SX1280 radio = new Module(10, 2, 3, 9); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//SX1280 radio = RadioShield.ModuleA; + +void setup() { + Serial.begin(9600); + + // initialize SX1280 with default settings + Serial.print(F("[SX1280] Initializing ... ")); + int state = radio.begin(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } +} + +void loop() { + Serial.print(F("[SX1280] Ranging ... ")); + + // start ranging exchange + // range as master: true + // slave address: 0x12345678 + int state = radio.range(true, 0x12345678); + + // the other module must be configured as slave with the same address + /* + int state = radio.range(false, 0x12345678); + */ + + if (state == ERR_NONE) { + // ranging finished successfully + Serial.println(F("success!")); + Serial.print(F("[SX1280] Distance:\t\t\t")); + Serial.print(radio.getRangingResult()); + Serial.println(F(" meters")); + + } else if (state == ERR_RANGING_TIMEOUT) { + // timed out waiting for ranging packet + Serial.println(F("timed out!")); + + } else { + // some other error occurred + Serial.print(F("failed, code ")); + Serial.println(state); + + } + + // wait for a second before ranging again + delay(1000); +} diff --git a/examples/SX128x/SX128x_Receive/SX128x_Receive.ino b/examples/SX128x/SX128x_Receive/SX128x_Receive.ino new file mode 100644 index 00000000..ff5adc41 --- /dev/null +++ b/examples/SX128x/SX128x_Receive/SX128x_Receive.ino @@ -0,0 +1,102 @@ +/* + RadioLib SX128x Receive Example + + This example listens for LoRa transmissions using SX126x Lora modules. + To successfully receive data, the following settings have to be the same + on both transmitter and receiver: + - carrier frequency + - bandwidth + - spreading factor + - coding rate + - sync word + - preamble length + + Other modules from SX128x family can also be used. + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx128x---lora-modem + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// SX1280 has the following connections: +// NSS pin: 10 +// DIO1 pin: 2 +// NRST pin: 3 +// BUSY pin: 9 +SX1280 radio = new Module(10, 2, 3, 9); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//SX1280 radio = RadioShield.ModuleA; + +void setup() { + Serial.begin(9600); + + // initialize SX1280 with default settings + Serial.print(F("[SX1280] Initializing ... ")); + int state = radio.begin(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } +} + +void loop() { + Serial.print(F("[SX1280] Waiting for incoming transmission ... ")); + + // you can receive data as an Arduino String + // NOTE: receive() is a blocking method! + // See example ReceiveInterrupt for details + // on non-blocking reception method. + String str; + int state = radio.receive(str); + + // you can also receive data as byte array + /* + byte byteArr[8]; + int state = radio.receive(byteArr, 8); + */ + + if (state == ERR_NONE) { + // packet was successfully received + Serial.println(F("success!")); + + // print the data of the packet + Serial.print(F("[SX1280] Data:\t\t")); + Serial.println(str); + + // print the RSSI (Received Signal Strength Indicator) + // of the last received packet + Serial.print(F("[SX1280] RSSI:\t\t")); + Serial.print(radio.getRSSI()); + Serial.println(F(" dBm")); + + // print the SNR (Signal-to-Noise Ratio) + // of the last received packet + Serial.print(F("[SX1280] SNR:\t\t")); + Serial.print(radio.getSNR()); + Serial.println(F(" dB")); + + } else if (state == ERR_RX_TIMEOUT) { + // timeout occurred while waiting for a packet + Serial.println(F("timeout!")); + + } else if (state == ERR_CRC_MISMATCH) { + // packet was received, but is malformed + Serial.println(F("CRC error!")); + + } else { + // some other error occurred + Serial.print(F("failed, code ")); + Serial.println(state); + + } +} diff --git a/examples/SX128x/SX128x_Receive_Interrupt/SX128x_Receive_Interrupt.ino b/examples/SX128x/SX128x_Receive_Interrupt/SX128x_Receive_Interrupt.ino new file mode 100644 index 00000000..65e03f7d --- /dev/null +++ b/examples/SX128x/SX128x_Receive_Interrupt/SX128x_Receive_Interrupt.ino @@ -0,0 +1,155 @@ +/* + RadioLib SX128x Receive with Interrupts Example + + This example listens for LoRa transmissions and tries to + receive them. Once a packet is received, an interrupt is + triggered. To successfully receive data, the following + settings have to be the same on both transmitter + and receiver: + - carrier frequency + - bandwidth + - spreading factor + - coding rate + - sync word + + Other modules from SX128x family can also be used. + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx128x---lora-modem + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// SX1280 has the following connections: +// NSS pin: 10 +// DIO1 pin: 2 +// NRST pin: 3 +// BUSY pin: 9 +SX1280 radio = new Module(10, 2, 3, 9); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//SX1280 radio = RadioShield.ModuleA; + +void setup() { + Serial.begin(9600); + + // initialize SX1280 with default settings + Serial.print(F("[SX1280] Initializing ... ")); + int state = radio.begin(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } + + // set the function that will be called + // when new packet is received + radio.setDio1Action(setFlag); + + // start listening for LoRa packets + Serial.print(F("[SX1280] Starting to listen ... ")); + state = radio.startReceive(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } + + // if needed, 'listen' mode can be disabled by calling + // any of the following methods: + // + // radio.standby() + // radio.sleep() + // radio.transmit(); + // radio.receive(); + // radio.readData(); + // radio.scanChannel(); +} + +// flag to indicate that a packet was received +volatile bool receivedFlag = false; + +// disable interrupt when it's not needed +volatile bool enableInterrupt = true; + +// this function is called when a complete packet +// is received by the module +// IMPORTANT: this function MUST be 'void' type +// and MUST NOT have any arguments! +void setFlag(void) { + // check if the interrupt is enabled + if(!enableInterrupt) { + return; + } + + // we got a packet, set the flag + receivedFlag = true; +} + +void loop() { + // check if the flag is set + if(receivedFlag) { + // disable the interrupt service routine while + // processing the data + enableInterrupt = false; + + // reset flag + receivedFlag = false; + + // you can read received data as an Arduino String + String str; + int state = radio.readData(str); + + // you can also read received data as byte array + /* + byte byteArr[8]; + int state = radio.readData(byteArr, 8); + */ + + if (state == ERR_NONE) { + // packet was successfully received + Serial.println(F("[SX1280] Received packet!")); + + // print data of the packet + Serial.print(F("[SX1280] Data:\t\t")); + Serial.println(str); + + // print RSSI (Received Signal Strength Indicator) + Serial.print(F("[SX1280] RSSI:\t\t")); + Serial.print(radio.getRSSI()); + Serial.println(F(" dBm")); + + // print SNR (Signal-to-Noise Ratio) + Serial.print(F("[SX1280] SNR:\t\t")); + Serial.print(radio.getSNR()); + Serial.println(F(" dB")); + + } else if (state == ERR_CRC_MISMATCH) { + // packet was received, but is malformed + Serial.println(F("CRC error!")); + + } else { + // some other error occurred + Serial.print(F("failed, code ")); + Serial.println(state); + + } + + // put module back to listen mode + radio.startReceive(); + + // we're ready to receive more packets, + // enable interrupt service routine + enableInterrupt = true; + } + +} diff --git a/examples/SX128x/SX128x_Settings/SX128x_Settings.ino b/examples/SX128x/SX128x_Settings/SX128x_Settings.ino new file mode 100644 index 00000000..0963d85a --- /dev/null +++ b/examples/SX128x/SX128x_Settings/SX128x_Settings.ino @@ -0,0 +1,129 @@ +/* + RadioLib SX128x Settings Example + + This example shows how to change all the properties of LoRa transmission. + RadioLib currently supports the following settings: + - pins (SPI slave select, DIO1, DIO2, BUSY pin) + - carrier frequency + - bandwidth + - spreading factor + - coding rate + - output power during transmission + - CRC + - preamble length + + Other modules from SX128x family can also be used. + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx128x---lora-modem + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// SX1280 has the following connections: +// NSS pin: 10 +// DIO1 pin: 2 +// NRST pin: 3 +// BUSY pin: 9 +SX1280 radio1 = new Module(10, 2, 3, 9); + +// SX1280 has the following connections: +// NSS pin: 8 +// DIO1 pin: 4 +// NRST pin: 5 +// BUSY pin: 6 +SX1281 radio2 = new Module(8, 4, 5, 6); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//SX1282 radio3 = RadioShield.ModuleB; + +void setup() { + Serial.begin(9600); + + // initialize SX1280 with default settings + Serial.print(F("[SX1280] Initializing ... ")); + int state = radio1.begin(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } + + // initialize the second LoRa instance with + // non-default settings + // this LoRa link will have high data rate, + // but lower range + Serial.print(F("[SX1281] Initializing ... ")); + // carrier frequency: 2450.0 MHz + // bandwidth: 1625.0 kHz + // spreading factor: 7 + // coding rate: 5 + // output power: 2 dBm + // preamble length: 20 symbols + state = radio2.begin(2450.0, 1625.0, 7, 5, 2, 20); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } + + // you can also change the settings at runtime + // and check if the configuration was changed successfully + + // set carrier frequency to 2410.5 MHz + if (radio1.setFrequency(2410.5) == ERR_INVALID_FREQUENCY) { + Serial.println(F("Selected frequency is invalid for this module!")); + while (true); + } + + // set bandwidth to 203.125 kHz + if (radio1.setBandwidth(203.125) == ERR_INVALID_BANDWIDTH) { + Serial.println(F("Selected bandwidth is invalid for this module!")); + while (true); + } + + // set spreading factor to 10 + if (radio1.setSpreadingFactor(10) == ERR_INVALID_SPREADING_FACTOR) { + Serial.println(F("Selected spreading factor is invalid for this module!")); + while (true); + } + + // set coding rate to 6 + if (radio1.setCodingRate(6) == ERR_INVALID_CODING_RATE) { + Serial.println(F("Selected coding rate is invalid for this module!")); + while (true); + } + + // set output power to -2 dBm + if (radio1.setOutputPower(-2) == ERR_INVALID_OUTPUT_POWER) { + Serial.println(F("Selected output power is invalid for this module!")); + while (true); + } + + // set LoRa preamble length to 16 symbols (accepted range is 2 - 65535) + if (radio1.setPreambleLength(16) == ERR_INVALID_PREAMBLE_LENGTH) { + Serial.println(F("Selected preamble length is invalid for this module!")); + while (true); + } + + // disable CRC + if (radio1.setCRC(false) == ERR_INVALID_CRC_CONFIGURATION) { + Serial.println(F("Selected CRC is invalid for this module!")); + while (true); + } + + Serial.println(F("All settings succesfully changed!")); +} + +void loop() { + // nothing here +} diff --git a/examples/SX128x/SX128x_Transmit/SX128x_Transmit.ino b/examples/SX128x/SX128x_Transmit/SX128x_Transmit.ino new file mode 100644 index 00000000..a4037def --- /dev/null +++ b/examples/SX128x/SX128x_Transmit/SX128x_Transmit.ino @@ -0,0 +1,98 @@ +/* + RadioLib SX128x Transmit Example + + This example transmits packets using SX1280 LoRa radio module. + Each packet contains up to 256 bytes of data, in the form of: + - Arduino String + - null-terminated char array (C-string) + - arbitrary binary data (byte array) + + Other modules from SX128x family can also be used. + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx128x---lora-modem + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// SX1280 has the following connections: +// NSS pin: 10 +// DIO1 pin: 2 +// NRST pin: 3 +// BUSY pin: 9 +SX1280 radio = new Module(10, 2, 3, 9); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//SX1280 radio = RadioShield.ModuleA; + +void setup() { + Serial.begin(9600); + + // initialize SX1280 with default settings + Serial.print(F("[SX1280] Initializing ... ")); + // carrier frequency: 2400.0 MHz + // bandwidth: 812.5 kHz + // spreading factor: 9 + // coding rate: 7 + // output power: 10 dBm + // preamble length: 12 symbols + // CRC: enabled + int state = radio.begin(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } + + // some modules have an external RF switch + // controlled via two pins (RX enable, TX enable) + // to enable automatic control of the switch, + // call the following method + // RX enable: 4 + // TX enable: 5 + /* + radio.setRfSwitchPins(4, 5); + */ +} + +void loop() { + Serial.print(F("[SX1280] Transmitting packet ... ")); + + // you can transmit C-string or Arduino string up to + // 256 characters long + // NOTE: transmit() is a blocking method! + // See example SX128x_Transmit_Interrupt for details + // on non-blocking transmission method. + int state = radio.transmit("Hello World!"); + + // you can also transmit byte array up to 256 bytes long + /* + byte byteArr[] = {0x01, 0x23, 0x45, 0x56, 0x78, 0xAB, 0xCD, 0xEF}; + int state = radio.transmit(byteArr, 8); + */ + + if (state == ERR_NONE) { + // the packet was successfully transmitted + Serial.println(F("success!")); + + } else if (state == ERR_PACKET_TOO_LONG) { + // the supplied packet was longer than 256 bytes + Serial.println(F("too long!")); + + } else { + // some other error occurred + Serial.print(F("failed, code ")); + Serial.println(state); + + } + + // wait for a second before transmitting again + delay(1000); +} diff --git a/examples/SX128x/SX128x_Transmit_Interrupt/SX128x_Transmit_Interrupt.ino b/examples/SX128x/SX128x_Transmit_Interrupt/SX128x_Transmit_Interrupt.ino new file mode 100644 index 00000000..ecdd9312 --- /dev/null +++ b/examples/SX128x/SX128x_Transmit_Interrupt/SX128x_Transmit_Interrupt.ino @@ -0,0 +1,131 @@ +/* + RadioLib SX128x Transmit with Interrupts Example + + This example transmits LoRa packets with one second delays + between them. Each packet contains up to 256 bytes + of data, in the form of: + - Arduino String + - null-terminated char array (C-string) + - arbitrary binary data (byte array) + + Other modules from SX128x family can also be used. + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#sx128x---lora-modem + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// SX1280 has the following connections: +// NSS pin: 10 +// DIO1 pin: 2 +// NRST pin: 3 +// BUSY pin: 9 +SX1280 radio = new Module(10, 2, 3, 9); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//SX1280 radio = RadioShield.ModuleA; + +// save transmission state between loops +int transmissionState = ERR_NONE; + +void setup() { + Serial.begin(9600); + + // initialize SX1280 with default settings + Serial.print(F("[SX1280] Initializing ... ")); + int state = radio.begin(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } + + // set the function that will be called + // when packet transmission is finished + radio.setDio1Action(setFlag); + + // start transmitting the first packet + Serial.print(F("[SX1280] Sending first packet ... ")); + + // you can transmit C-string or Arduino string up to + // 256 characters long + transmissionState = radio.startTransmit("Hello World!"); + + // you can also transmit byte array up to 256 bytes long + /* + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, + 0x89, 0xAB, 0xCD, 0xEF}; + state = radio.startTransmit(byteArr, 8); + */ +} + +// flag to indicate that a packet was sent +volatile bool transmittedFlag = false; + +// disable interrupt when it's not needed +volatile bool enableInterrupt = true; + +// this function is called when a complete packet +// is transmitted by the module +// IMPORTANT: this function MUST be 'void' type +// and MUST NOT have any arguments! +void setFlag(void) { + // check if the interrupt is enabled + if(!enableInterrupt) { + return; + } + + // we sent a packet, set the flag + transmittedFlag = true; +} + +void loop() { + // check if the previous transmission finished + if(transmittedFlag) { + // disable the interrupt service routine while + // processing the data + enableInterrupt = false; + + // reset flag + transmittedFlag = false; + + if (transmissionState == ERR_NONE) { + // packet was successfully sent + Serial.println(F("transmission finished!")); + + } else { + Serial.print(F("failed, code ")); + Serial.println(transmissionState); + + } + + // wait a second before transmitting again + delay(1000); + + // send another one + Serial.print(F("[SX1280] Sending another packet ... ")); + + // you can transmit C-string or Arduino string up to + // 256 characters long + transmissionState = radio.startTransmit("Hello World!"); + + // you can also transmit byte array up to 256 bytes long + /* + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, + 0x89, 0xAB, 0xCD, 0xEF}; + int state = radio.startTransmit(byteArr, 8); + */ + + // we're ready to send more packets, + // enable interrupt service routine + enableInterrupt = true; + } +} diff --git a/examples/Si443x/Si443x_Receive/Si443x_Receive.ino b/examples/Si443x/Si443x_Receive/Si443x_Receive.ino new file mode 100644 index 00000000..846e46e3 --- /dev/null +++ b/examples/Si443x/Si443x_Receive/Si443x_Receive.ino @@ -0,0 +1,84 @@ +/* + RadioLib Si443x Receive Example + + This example receives packets using Si443x FSK radio module. + To successfully receive data, the following settings have to be the same + on both transmitter and receiver: + - carrier frequency + - bit rate + - frequency deviation + - sync word + + Other modules from Si443x/RFM2x family can also be used. + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#si443xrfm2x + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// Si4432 has the following connections: +// nSEL pin: 10 +// nIRQ pin: 2 +// SDN pin: 9 +Si4432 radio = new Module(10, 2, 9); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//Si4432 radio = RadioShield.ModuleA; + +void setup() { + Serial.begin(9600); + + // initialize Si4432 with default settings + Serial.print(F("[Si4432] Initializing ... ")); + int state = radio.begin(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } +} + +void loop() { + Serial.print(F("[Si4432] Waiting for incoming transmission ... ")); + + // you can receive data as an Arduino String + String str; + int state = radio.receive(str); + + // you can also receive data as byte array + /* + byte byteArr[8]; + int state = radio.receive(byteArr, 8); + */ + + if (state == ERR_NONE) { + // packet was successfully received + Serial.println(F("success!")); + + // print the data of the packet + Serial.print(F("[Si4432] Data:\t\t")); + Serial.println(str); + + } else if (state == ERR_RX_TIMEOUT) { + // timeout occurred while waiting for a packet + Serial.println(F("timeout!")); + + } else if (state == ERR_CRC_MISMATCH) { + // packet was received, but is malformed + Serial.println(F("CRC error!")); + + } else { + // some other error occurred + Serial.print(F("failed, code ")); + Serial.println(state); + + } +} diff --git a/examples/Si443x/Si443x_Receive_Interrupt/Si443x_Receive_Interrupt.ino b/examples/Si443x/Si443x_Receive_Interrupt/Si443x_Receive_Interrupt.ino new file mode 100644 index 00000000..e890b08d --- /dev/null +++ b/examples/Si443x/Si443x_Receive_Interrupt/Si443x_Receive_Interrupt.ino @@ -0,0 +1,136 @@ +/* + RadioLib Si443x Receive with Interrupts Example + + This example listens for FSK transmissions and tries to + receive them. Once a packet is received, an interrupt is + triggered. + + Other modules from Si443x/RFM2x family can also be used. + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#si443xrfm2x + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// Si4432 has the following connections: +// nSEL pin: 10 +// nIRQ pin: 2 +// SDN pin: 9 +Si4432 radio = new Module(10, 2, 9); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//Si4432 radio = RadioShield.ModuleA; + +void setup() { + Serial.begin(9600); + + // initialize Si4432 with default settings + Serial.print(F("[Si4432] Initializing ... ")); + int state = radio.begin(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } + + // set the function that will be called + // when new packet is received + radio.setIrqAction(setFlag); + + // start listening for packets + Serial.print(F("[Si4432] Starting to listen ... ")); + state = radio.startReceive(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } + + // if needed, 'listen' mode can be disabled by calling + // any of the following methods: + // + // radio.standby() + // radio.sleep() + // radio.transmit(); + // radio.receive(); + // radio.readData(); +} + +// flag to indicate that a packet was received +volatile bool receivedFlag = false; + +// disable interrupt when it's not needed +volatile bool enableInterrupt = true; + +// this function is called when a complete packet +// is received by the module +// IMPORTANT: this function MUST be 'void' type +// and MUST NOT have any arguments! +void setFlag(void) { + // check if the interrupt is enabled + if(!enableInterrupt) { + return; + } + + // we got a packet, set the flag + receivedFlag = true; +} + +void loop() { + // check if the flag is set + if(receivedFlag) { + // disable the interrupt service routine while + // processing the data + enableInterrupt = false; + + // reset flag + receivedFlag = false; + + // you can read received data as an Arduino String + String str; + int state = radio.readData(str); + + // you can also read received data as byte array + /* + byte byteArr[8]; + int state = radio.readData(byteArr, 8); + */ + + if (state == ERR_NONE) { + // packet was successfully received + Serial.println(F("[Si4432] Received packet!")); + + // print data of the packet + Serial.print(F("[Si4432] Data:\t\t\t")); + Serial.println(str); + + } else if (state == ERR_CRC_MISMATCH) { + // packet was received, but is malformed + Serial.println(F("CRC error!")); + + } else { + // some other error occurred + Serial.print(F("failed, code ")); + Serial.println(state); + + } + + // put module back to listen mode + radio.startReceive(); + + // we're ready to receive more packets, + // enable interrupt service routine + enableInterrupt = true; + } + +} diff --git a/examples/Si443x/Si443x_Settings/Si443x_Settings.ino b/examples/Si443x/Si443x_Settings/Si443x_Settings.ino new file mode 100644 index 00000000..cd420505 --- /dev/null +++ b/examples/Si443x/Si443x_Settings/Si443x_Settings.ino @@ -0,0 +1,123 @@ +/* + RadioLib Si443x Settings Example + + This example shows how to change all the properties of RF69 radio. + RadioLib currently supports the following settings: + - pins (SPI slave select, nIRQ, shutdown) + - carrier frequency + - bit rate + - receiver bandwidth + - frequency deviation + - output power during transmission + - sync word + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#si443xrfm2x + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// Si4432 has the following connections: +// nSEL pin: 10 +// nIRQ pin: 2 +// SDN pin: 9 +Si4432 radio1 = new Module(10, 2, 9); + +// Si4432 has the following connections: +// nSEL pin: 8 +// nIRQ pin: 3 +// SDN pin: 7 +Si4432 radio2 = new Module(8, 3, 7); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//Si4432 radio3 = RadioShield.ModuleB; + +void setup() { + Serial.begin(9600); + + // initialize Si4432 with default settings + Serial.print(F("[Si4432] Initializing ... ")); + int state = radio1.begin(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } + + // initialize Si4432 with non-default settings + Serial.print(F("[Si4432] Initializing ... ")); + // carrier frequency: 868.0 MHz + // bit rate: 200.0 kbps + // frequency deviation: 60.0 kHz + // Rx bandwidth: 335.5 kHz + // output power: 17 dBm + // preamble length: 32 bits + state = radio2.begin(868.0, 200.0, 60.0, 335.5, 17, 32); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } + + // you can also change the settings at runtime + // and check if the configuration was changed successfully + + // set carrier frequency to 433.5 MHz + if (radio1.setFrequency(433.5) == ERR_INVALID_FREQUENCY) { + Serial.println(F("[Si4432] Selected frequency is invalid for this module!")); + while (true); + } + + // set bit rate to 100.0 kbps + state = radio1.setBitRate(100.0); + if (state == ERR_INVALID_BIT_RATE) { + Serial.println(F("[Si4432] Selected bit rate is invalid for this module!")); + while (true); + } else if (state == ERR_INVALID_BIT_RATE_BW_RATIO) { + Serial.println(F("[Si4432] Selected bit rate to bandwidth ratio is invalid!")); + Serial.println(F("[Si4432] Increase receiver bandwidth to set this bit rate.")); + while (true); + } + + // set receiver bandwidth to 284.8 kHz + state = radio1.setRxBandwidth(284.8); + if (state == ERR_INVALID_RX_BANDWIDTH) { + Serial.println(F("[Si4432] Selected receiver bandwidth is invalid for this module!")); + while (true); + } + + // set frequency deviation to 10.0 kHz + if (radio1.setFrequencyDeviation(10.0) == ERR_INVALID_FREQUENCY_DEVIATION) { + Serial.println(F("[Si4432] Selected frequency deviation is invalid for this module!")); + while (true); + } + + // set output power to 2 dBm + if (radio1.setOutputPower(2) == ERR_INVALID_OUTPUT_POWER) { + Serial.println(F("[Si4432] Selected output power is invalid for this module!")); + while (true); + } + + // up to 4 bytes can be set as sync word + // set sync word to 0x01234567 + uint8_t syncWord[] = {0x01, 0x23, 0x45, 0x67}; + if (radio1.setSyncWord(syncWord, 4) == ERR_INVALID_SYNC_WORD) { + Serial.println(F("[Si4432] Selected sync word is invalid for this module!")); + while (true); + } + + Serial.println(F("[Si4432] All settings changed successfully!")); +} + +void loop() { + // nothing here +} diff --git a/examples/Si443x/Si443x_Transmit/Si443x_Transmit.ino b/examples/Si443x/Si443x_Transmit/Si443x_Transmit.ino new file mode 100644 index 00000000..ca267624 --- /dev/null +++ b/examples/Si443x/Si443x_Transmit/Si443x_Transmit.ino @@ -0,0 +1,84 @@ +/* + RadioLib Si443x Transmit Example + + This example transmits packets using Si4432 FSK radio module. + Each packet contains up to 64 bytes of data, in the form of: + - Arduino String + - null-terminated char array (C-string) + - arbitrary binary data (byte array) + + Other modules from Si443x/RFM2x family can also be used. + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#si443xrfm2x + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// Si4432 has the following connections: +// nSEL pin: 10 +// nIRQ pin: 2 +// SDN pin: 9 +Si4432 radio = new Module(10, 2, 9); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//Si4432 radio = RadioShield.ModuleA; + +void setup() { + Serial.begin(9600); + + // initialize Si4432 with default settings + Serial.print(F("[Si4432] Initializing ... ")); + int state = radio.begin(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } +} + +void loop() { + Serial.print(F("[Si4432] Transmitting packet ... ")); + + // you can transmit C-string or Arduino string up to + // 64 characters long + // NOTE: transmit() is a blocking method! + // See example Si443x_Transmit_Interrupt for details + // on non-blocking transmission method. + int state = radio.transmit("Hello World!"); + + // you can also transmit byte array up to 64 bytes long + /* + byte byteArr[] = {0x01, 0x23, 0x45, 0x56, 0x78, 0xAB, 0xCD, 0xEF}; + int state = radio.transmit(byteArr, 8); + */ + + if (state == ERR_NONE) { + // the packet was successfully transmitted + Serial.println(F(" success!")); + + } else if (state == ERR_PACKET_TOO_LONG) { + // the supplied packet was longer than 256 bytes + Serial.println(F(" too long!")); + + } else if (state == ERR_TX_TIMEOUT) { + // timeout occured while transmitting packet + Serial.println(F(" timeout!")); + + } else { + // some other error occurred + Serial.print(F("failed, code ")); + Serial.println(state); + + } + + // wait for a second before transmitting again + delay(1000); +} diff --git a/examples/Si443x/Si443x_Transmit_Interrupt/Si443x_Transmit_Interrupt.ino b/examples/Si443x/Si443x_Transmit_Interrupt/Si443x_Transmit_Interrupt.ino new file mode 100644 index 00000000..82c5364d --- /dev/null +++ b/examples/Si443x/Si443x_Transmit_Interrupt/Si443x_Transmit_Interrupt.ino @@ -0,0 +1,129 @@ +/* + RadioLib Si443x Transmit with Interrupts Example + + This example transmits packets using Si4432 FSK radio module. + Each packet contains up to 64 bytes of data, in the form of: + - Arduino String + - null-terminated char array (C-string) + - arbitrary binary data (byte array) + + Other modules from Si443x/RFM2x family can also be used. + + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#si443xrfm2x + + For full API reference, see the GitHub Pages + https://jgromes.github.io/RadioLib/ +*/ + +// include the library +#include + +// Si4432 has the following connections: +// nSEL pin: 10 +// nIRQ pin: 2 +// SDN pin: 9 +Si4432 radio = new Module(10, 2, 9); + +// or using RadioShield +// https://github.com/jgromes/RadioShield +//Si4432 radio = RadioShield.ModuleA; + +// save transmission state between loops +int transmissionState = ERR_NONE; + +void setup() { + Serial.begin(9600); + + // initialize Si4432 with default settings + Serial.print(F("[Si4432] Initializing ... ")); + int state = radio.begin(); + if (state == ERR_NONE) { + Serial.println(F("success!")); + } else { + Serial.print(F("failed, code ")); + Serial.println(state); + while (true); + } + + // set the function that will be called + // when packet transmission is finished + radio.setIrqAction(setFlag); + + // start transmitting the first packet + Serial.print(F("[Si4432] Sending first packet ... ")); + + // you can transmit C-string or Arduino string up to + // 64 characters long + transmissionState = radio.startTransmit("Hello World!"); + + // you can also transmit byte array up to 64 bytes long + /* + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, + 0x89, 0xAB, 0xCD, 0xEF}; + state = radio.startTransmit(byteArr, 8); + */ +} + +// flag to indicate that a packet was sent +volatile bool transmittedFlag = false; + +// disable interrupt when it's not needed +volatile bool enableInterrupt = true; + +// this function is called when a complete packet +// is transmitted by the module +// IMPORTANT: this function MUST be 'void' type +// and MUST NOT have any arguments! +void setFlag(void) { + // check if the interrupt is enabled + if(!enableInterrupt) { + return; + } + + // we sent a packet, set the flag + transmittedFlag = true; +} + +void loop() { + // check if the previous transmission finished + if(transmittedFlag) { + // disable the interrupt service routine while + // processing the data + enableInterrupt = false; + + // reset flag + transmittedFlag = false; + + if (transmissionState == ERR_NONE) { + // packet was successfully sent + Serial.println(F("transmission finished!")); + + } else { + Serial.print(F("failed, code ")); + Serial.println(transmissionState); + + } + + // wait a second before transmitting again + delay(1000); + + // send another one + Serial.print(F("[Si4432] Sending another packet ... ")); + + // you can transmit C-string or Arduino string up to + // 256 characters long + transmissionState = radio.startTransmit("Hello World!"); + + // you can also transmit byte array up to 64 bytes long + /* + byte byteArr[] = {0x01, 0x23, 0x45, 0x67, + 0x89, 0xAB, 0xCD, 0xEF}; + int state = radio.startTransmit(byteArr, 8); + */ + + // we're ready to send more packets, + // enable interrupt service routine + enableInterrupt = true; + } +} diff --git a/examples/nRF24/nRF24_Receive/nRF24_Receive.ino b/examples/nRF24/nRF24_Receive/nRF24_Receive.ino index b5b5571e..2c036fd6 100644 --- a/examples/nRF24/nRF24_Receive/nRF24_Receive.ino +++ b/examples/nRF24/nRF24_Receive/nRF24_Receive.ino @@ -9,6 +9,9 @@ - transmit pipe on transmitter must match receive pipe on receiver + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#nrf24 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -20,22 +23,18 @@ // CS pin: 10 // IRQ pin: 2 // CE pin: 3 -nRF24 nrf = new Module(10, 2, 3); +nRF24 radio = new Module(10, 2, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//nRF24 nrf = RadioShield.ModuleA; +//nRF24 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); - // initialize nRF24 + // initialize nRF24 with default settings Serial.print(F("[nRF24] Initializing ... ")); - // carrier frequency: 2400 MHz - // data rate: 1000 kbps - // output power: -12 dBm - // address width: 5 bytes - int state = nrf.begin(); + int state = radio.begin(); if(state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -50,7 +49,7 @@ void setup() { // methods (5 by default) Serial.print(F("[nRF24] Setting address for receive pipe 0 ... ")); byte addr[] = {0x01, 0x23, 0x45, 0x67, 0x89}; - state = nrf.setReceivePipe(0, addr); + state = radio.setReceivePipe(0, addr); if(state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -68,12 +67,12 @@ void loop() { // See example ReceiveInterrupt for details // on non-blocking reception method. String str; - int state = nrf.receive(str); + int state = radio.receive(str); // you can also receive data as byte array /* byte byteArr[8]; - int state = nrf.receive(byteArr, 8); + int state = radio.receive(byteArr, 8); */ if (state == ERR_NONE) { diff --git a/examples/nRF24/nRF24_Transmit/nRF24_Transmit.ino b/examples/nRF24/nRF24_Transmit/nRF24_Transmit.ino index 89006b38..c692e8a8 100644 --- a/examples/nRF24/nRF24_Transmit/nRF24_Transmit.ino +++ b/examples/nRF24/nRF24_Transmit/nRF24_Transmit.ino @@ -9,6 +9,9 @@ Packet delivery is automatically acknowledged by the receiver. + For default module settings, see the wiki page + https://github.com/jgromes/RadioLib/wiki/Default-configuration#nrf24 + For full API reference, see the GitHub Pages https://jgromes.github.io/RadioLib/ */ @@ -20,22 +23,18 @@ // CS pin: 10 // IRQ pin: 2 // CE pin: 3 -nRF24 nrf = new Module(10, 2, 3); +nRF24 radio = new Module(10, 2, 3); // or using RadioShield // https://github.com/jgromes/RadioShield -//nRF24 nrf = RadioShield.ModuleA; +//nRF24 radio = RadioShield.ModuleA; void setup() { Serial.begin(9600); - // initialize nRF24 + // initialize nRF24 with default settings Serial.print(F("[nRF24] Initializing ... ")); - // carrier frequency: 2400 MHz - // data rate: 1000 kbps - // output power: -12 dBm - // address width: 5 bytes - int state = nrf.begin(); + int state = radio.begin(); if(state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -50,7 +49,7 @@ void setup() { // methods (5 by default) byte addr[] = {0x01, 0x23, 0x45, 0x67, 0x89}; Serial.print(F("[nRF24] Setting transmit pipe ... ")); - state = nrf.setTransmitPipe(addr); + state = radio.setTransmitPipe(addr); if(state == ERR_NONE) { Serial.println(F("success!")); } else { @@ -65,7 +64,7 @@ void loop() { // you can transmit C-string or Arduino string up to // 32 characters long - int state = nrf.transmit("Hello World!"); + int state = radio.transmit("Hello World!"); if (state == ERR_NONE) { // the packet was successfully transmitted diff --git a/extras/ModuleTemplate.cpp b/extras/ModuleTemplate.cpp index 0ee26318..07267305 100644 --- a/extras/ModuleTemplate.cpp +++ b/extras/ModuleTemplate.cpp @@ -1,4 +1,5 @@ #include ".h" +#if !defined(RADIOLIB_EXCLUDE_) ::(Module* mod) { /* @@ -12,10 +13,10 @@ int16_t ::begin() { "begin" method implementation MUST call the "init" method with appropriate settings. */ _mod->init(); - + /* "begin" method SHOULD implement some sort of mechanism to verify the connection between Arduino and the module. - + For example, sending AT command for UART modules, or reading a version register for SPI/I2C modules */ } diff --git a/extras/ModuleTemplate.h b/extras/ModuleTemplate.h index dcb7b0f9..4d957cb0 100644 --- a/extras/ModuleTemplate.h +++ b/extras/ModuleTemplate.h @@ -12,14 +12,16 @@ If at any point you are unsure about the required style, please refer to the rest of the modules. */ +#if !defined(_RADIOLIB__H) && !defined(RADIOLIB_EXCLUDE_) #ifndef _RADIOLIB__H #define _RADIOLIB__H /* - Header file for each module MUST include Module.h. + Header file for each module MUST include Module.h and TypeDef.h in the src folder. The header file MAY include additional header files. */ -#include "Module.h" +#include "../../Module.h" +#include "../../TypeDef.h" /* Only use the following include if the module implements methods for OSI transport layer control. @@ -29,7 +31,7 @@ You also MUST provide crystal oscillator frequency and frequency configuration divisor step resolution to the TransportLayer constructor. */ -//#include "../protocols/TransportLayer.h" +//#include "../../protocols/PhysicalLayer/TransportLayer.h" /* Only use the following include if the module implements methods for OSI physical layer control. @@ -37,7 +39,7 @@ In this case, your class MUST implement all virtual methods of PhysicalLayer class. */ -//#include "../protocols/PhysicalLayer.h" +//#include "../../protocols/PhysicalLayer/PhysicalLayer.h" /* Register map @@ -74,7 +76,7 @@ class { The class MAY implement additional overloaded constructors. */ // constructor - (Module* module); + (Module* mod); /* The class MUST implement at least one basic method called "begin". @@ -105,3 +107,5 @@ class { }; #endif + +#endif diff --git a/keywords.txt b/keywords.txt index 10f66074..a564bcf6 100644 --- a/keywords.txt +++ b/keywords.txt @@ -10,16 +10,22 @@ RadioLib KEYWORD1 RadioShield KEYWORD1 Module KEYWORD1 +# modules CC1101 KEYWORD1 ESP8266 KEYWORD1 HC05 KEYWORD1 JDY08 KEYWORD1 nRF24 KEYWORD1 RF69 KEYWORD1 +RFM22 KEYWORD1 +RFM23 KEYWORD1 RFM95 KEYWORD1 RFM96 KEYWORD1 RFM97 KEYWORD1 RFM98 KEYWORD1 +Si4430 KEYWORD1 +Si4431 KEYWORD1 +Si4432 KEYWORD1 SIM800 KEYWORD1 SX1231 KEYWORD1 SX1261 KEYWORD1 @@ -31,9 +37,13 @@ SX1276 KEYWORD1 SX1277 KEYWORD1 SX1278 KEYWORD1 SX1279 KEYWORD1 +SX1280 KEYWORD1 +SX1281 KEYWORD1 +SX1282 KEYWORD1 XBee KEYWORD1 XBeeSerial KEYWORD1 +# protocols MQTTClient KEYWORD1 HTTPClient KEYWORD1 RTTYClient KEYWORD1 @@ -41,6 +51,20 @@ MorseClient KEYWORD1 PagerClient KEYWORD1 AX25Client KEYWORD1 AX25Frame KEYWORD1 +SSTVClient KEYWORD1 +HellClient KEYWORD1 +AFSKClient KEYWORD1 + +# SSTV modes +Scottie1 KEYWORD1 +Scottie2 KEYWORD1 +ScottieDX KEYWORD1 +Martin1 KEYWORD1 +Martin2 KEYWORD1 +Wrasse KEYWORD1 +PasokonP3 KEYWORD1 +PasokonP5 KEYWORD1 +PasokonP7 KEYWORD1 ####################################### # Methods and Functions (KEYWORD2) @@ -100,6 +124,12 @@ disableSyncWordFiltering KEYWORD2 setPromiscuous KEYWORD2 setRSSIConfig KEYWORD2 setEncoding KEYWORD2 +getIRQFlags KEYWORD2 +getModemStatus KEYWORD2 +getTempRaw KEYWORD2 +setRfSwitchPins KEYWORD2 +forceLDRO KEYWORD2 +autoLDRO KEYWORD2 # RF69-specific setAESKey KEYWORD2 @@ -140,6 +170,7 @@ getPacketSource KEYWORD2 getPacketData KEYWORD2 # nRF24 +setIrqAction KEYWORD2 setAddressWidth KEYWORD2 setTransmitPipe KEYWORD2 setReceivePipe KEYWORD2 @@ -184,13 +215,44 @@ setRecvSequence KEYWORD2 setSendSequence KEYWORD2 sendFrame KEYWORD2 +# SSTV +sendHeader KEYWORD2 +sendLine KEYWORD2 +getPictureHeight KEYWORD2 + +# SX128x +beginGFSK KEYWORD2 +beginFLRC KEYWORD2 +beginBLE KEYWORD2 +setAccessAddress KEYWORD2 +range KEYWORD2 +startRanging KEYWORD2 +getRangingResult KEYWORD2 + +# Hellschreiber +printGlyph KEYWORD2 + +# AFSK +tone KEYWORD2 +noTone KEYWORD2 + ####################################### # Constants (LITERAL1) ####################################### -NC LITERAL1 +RADIOLIB_NC LITERAL1 RADIOLIB_VERSION LITERAL1 +RADIOLIB_SHAPING_NONE LITERAL1 +RADIOLIB_SHAPING_0_3 LITERAL1 +RADIOLIB_SHAPING_0_5 LITERAL1 +RADIOLIB_SHAPING_0_7 LITERAL1 +RADIOLIB_SHAPING_1_0 LITERAL1 + +RADIOLIB_ENCODING_NRZ LITERAL1 +RADIOLIB_ENCODING_MANCHESTER LITERAL1 +RADIOLIB_ENCODING_WHITENING LITERAL1 + ERR_NONE LITERAL1 ERR_UNKNOWN LITERAL1 @@ -274,3 +336,5 @@ ERR_INVALID_RX_PERIOD LITERAL1 ERR_INVALID_CALLSIGN LITERAL1 ERR_INVALID_NUM_REPEATERS LITERAL1 ERR_INVALID_REPEATER_CALLSIGN LITERAL1 + +ERR_RANGING_TIMEOUT LITERAL1 diff --git a/library.properties b/library.properties index bee08568..14217d0d 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=RadioLib -version=3.3.1 +version=4.0.1 author=Jan Gromes maintainer=Jan Gromes sentence=Universal wireless communication library for Arduino diff --git a/src/BuildOpt.h b/src/BuildOpt.h new file mode 100644 index 00000000..07a21840 --- /dev/null +++ b/src/BuildOpt.h @@ -0,0 +1,343 @@ +#ifndef _RADIOLIB_BUILD_OPTIONS_H +#define _RADIOLIB_BUILD_OPTIONS_H + +#if ARDUINO >= 100 + #include "Arduino.h" +#else + #error "Unsupported Arduino version (< 1.0.0)" +#endif + +/* + * Platform-specific configuration. + * + * RADIOLIB_PLATFORM - platform name, used in debugging to quickly check the correct platform is detected, + * RADIOLIB_PIN_TYPE - which type should be used for pin numbers in functions like digitalRead(). + * RADIOLIB_PIN_MODE - which type should be used for pin modes in functions like pinMode(). + * RADIOLIB_PIN_STATUS - which type should be used for pin values in functions like digitalWrite(). + * RADIOLIB_DIGITAL_PIN_TO_INTERRUPT - function to be used to convert digital pin number to interrupt pin number. + * RADIOLIB_INTERRUPT_STATUS - which type should be used for pin changes in functions like attachInterrupt(). + * RADIOLIB_NC - alias for unused pin, usually the largest possible value of RADIOLIB_PIN_TYPE. + * RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED - defined if the specific platform does not support SoftwareSerial. + * RADIOLIB_HARDWARE_SERIAL_PORT - which hardware serial port should be used on platform that do not have SoftwareSerial support. + * RADIOLIB_TONE_UNSUPPORTED - some platforms do not have tone()/noTone(), which is required for AFSK. + * + * In addition, some platforms may require RadioLib to disable specific drivers (such as ESP8266). + * + * Users may also specify their own configuration by uncommenting the RADIOLIB_CUSTOM_PLATFORM, + * and then specifying all platform parameters in the section below. This will override automatic + * platform detection. + */ + +// uncomment to enable custom platform definition +//#define RADIOLIB_CUSTOM_PLATFORM + +#if defined(RADIOLIB_CUSTOM_PLATFORM) + // name for your platform + #define RADIOLIB_PLATFORM "Custom" + + // the following parameters must always be defined + #define RADIOLIB_PIN_TYPE uint8_t + #define RADIOLIB_PIN_MODE uint8_t + #define RADIOLIB_PIN_STATUS uint8_t + #define RADIOLIB_INTERRUPT_STATUS RADIOLIB_PIN_STATUS + #define RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(p) digitalPinToInterrupt(p) + #define RADIOLIB_NC (0xFF) + #define RADIOLIB_DEFAULT_SPI SPI + + // the following must be defined if the Arduino core does not support SoftwareSerial library + //#define RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED + //#define RADIOLIB_HARDWARE_SERIAL_PORT Serial1 + + // the following must be defined if the Arduino core does not support tone function + //#define RADIOLIB_TONE_UNSUPPORTED + + // some of RadioLib drivers may be excluded, to prevent collisions with platforms (or to speed up build process) + // the following is a complete list of all possible exclusion macros, uncomment any of them to disable that driver + // NOTE: Some of the exclusion macros are dependent on each other. For example, it is not possible to exclude RF69 + // while keeping SX1231 (because RF69 is the base class for SX1231). The dependency is always uni-directional, + // so excluding SX1231 and keeping RF69 is valid. + //#define RADIOLIB_EXCLUDE_CC1101 + //#define RADIOLIB_EXCLUDE_ESP8266 + //#define RADIOLIB_EXCLUDE_HC05 + //#define RADIOLIB_EXCLUDE_JDY08 + //#define RADIOLIB_EXCLUDE_NRF24 + //#define RADIOLIB_EXCLUDE_RF69 + //#define RADIOLIB_EXCLUDE_SX1231 // dependent on RADIOLIB_EXCLUDE_RF69 + //#define RADIOLIB_EXCLUDE_SI443X + //#define RADIOLIB_EXCLUDE_RFM2X // dependent on RADIOLIB_EXCLUDE_SI443X + //#define RADIOLIB_EXCLUDE_SX127X + //#define RADIOLIB_EXCLUDE_RFM9X // dependent on RADIOLIB_EXCLUDE_SX127X + //#define RADIOLIB_EXCLUDE_SX126X + //#define RADIOLIB_EXCLUDE_SX128X + //#define RADIOLIB_EXCLUDE_XBEE + //#define RADIOLIB_EXCLUDE_AFSK + //#define RADIOLIB_EXCLUDE_AX25 + //#define RADIOLIB_EXCLUDE_HELLSCHREIBER + //#define RADIOLIB_EXCLUDE_HTTP + //#define RADIOLIB_EXCLUDE_MORSE + //#define RADIOLIB_EXCLUDE_MQTT + //#define RADIOLIB_EXCLUDE_RTTY + //#define RADIOLIB_EXCLUDE_SSTV + +#else + #if defined(__AVR__) && !(defined(ARDUINO_AVR_UNO_WIFI_REV2) || defined(ARDUINO_AVR_NANO_EVERY)) + // Arduino AVR boards (except for megaAVR) - Uno, Mega etc. + #define RADIOLIB_PLATFORM "Arduino AVR" + #define RADIOLIB_PIN_TYPE uint8_t + #define RADIOLIB_PIN_MODE uint8_t + #define RADIOLIB_PIN_STATUS uint8_t + #define RADIOLIB_INTERRUPT_STATUS RADIOLIB_PIN_STATUS + #define RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(p) digitalPinToInterrupt(p) + #define RADIOLIB_NC (0xFF) + #define RADIOLIB_DEFAULT_SPI SPI + + #elif defined(ESP8266) + // ESP8266 boards + #define RADIOLIB_PLATFORM "ESP8266" + #define RADIOLIB_PIN_TYPE uint8_t + #define RADIOLIB_PIN_MODE uint8_t + #define RADIOLIB_PIN_STATUS uint8_t + #define RADIOLIB_INTERRUPT_STATUS RADIOLIB_PIN_STATUS + #define RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(p) digitalPinToInterrupt(p) + #define RADIOLIB_NC (0xFF) + #define RADIOLIB_DEFAULT_SPI SPI + + // RadioLib has ESP8266 driver, this must be disabled to use ESP8266 as platform + #define RADIOLIB_EXCLUDE_ESP8266 + + #elif defined(ESP32) + // ESP32 boards + #define RADIOLIB_PLATFORM "ESP32" + #define RADIOLIB_PIN_TYPE uint8_t + #define RADIOLIB_PIN_MODE uint8_t + #define RADIOLIB_PIN_STATUS uint8_t + #define RADIOLIB_INTERRUPT_STATUS RADIOLIB_PIN_STATUS + #define RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(p) digitalPinToInterrupt(p) + #define RADIOLIB_NC (0xFF) + #define RADIOLIB_DEFAULT_SPI SPI + #define RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED + #define RADIOLIB_HARDWARE_SERIAL_PORT Serial1 + #define RADIOLIB_TONE_UNSUPPORTED + + #elif defined(ARDUINO_ARCH_STM32) + // official STM32 Arduino core (https://github.com/stm32duino/Arduino_Core_STM32) + #define RADIOLIB_PLATFORM "Arduino STM32 (official)" + #define RADIOLIB_PIN_TYPE uint32_t + #define RADIOLIB_PIN_MODE uint32_t + #define RADIOLIB_PIN_STATUS uint32_t + #define RADIOLIB_INTERRUPT_STATUS RADIOLIB_PIN_STATUS + #define RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(p) digitalPinToInterrupt(digitalPinToPinName(p)) + #define RADIOLIB_NC (0xFFFFFFFF) + #define RADIOLIB_DEFAULT_SPI SPI + #define RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED + #define RADIOLIB_HARDWARE_SERIAL_PORT Serial1 + + #elif defined(SAMD_SERIES) + // Arduino SAMD (Zero, MKR, etc.) and Adafruit SAMD boards (M0 and M4) + #define RADIOLIB_PLATFORM "Arduino/Adafruit SAMD" + #define RADIOLIB_PIN_TYPE uint32_t + #define RADIOLIB_PIN_MODE uint32_t + #define RADIOLIB_PIN_STATUS uint32_t + #define RADIOLIB_INTERRUPT_STATUS RADIOLIB_PIN_STATUS + #define RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(p) digitalPinToInterrupt(p) + #define RADIOLIB_NC (0xFFFFFFFF) + #define RADIOLIB_DEFAULT_SPI SPI + #define RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED + #define RADIOLIB_HARDWARE_SERIAL_PORT Serial1 + + #elif defined(__SAM3X8E__) + // Arduino Due + #define RADIOLIB_PLATFORM "Arduino Due" + #define RADIOLIB_PIN_TYPE uint32_t + #define RADIOLIB_PIN_MODE uint32_t + #define RADIOLIB_PIN_STATUS uint32_t + #define RADIOLIB_INTERRUPT_STATUS RADIOLIB_PIN_STATUS + #define RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(p) digitalPinToInterrupt(p) + #define RADIOLIB_NC (0xFFFFFFFF) + #define RADIOLIB_DEFAULT_SPI SPI + #define RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED + #define RADIOLIB_HARDWARE_SERIAL_PORT Serial1 + #define RADIOLIB_TONE_UNSUPPORTED + + #elif (defined(NRF52832_XXAA) || defined(NRF52840_XXAA)) && !defined(ARDUINO_ARDUINO_NANO33BLE) + // Adafruit nRF52 boards + #define RADIOLIB_PLATFORM "Adafruit nRF52" + #define RADIOLIB_PIN_TYPE uint32_t + #define RADIOLIB_PIN_MODE uint32_t + #define RADIOLIB_PIN_STATUS uint32_t + #define RADIOLIB_INTERRUPT_STATUS RADIOLIB_PIN_STATUS + #define RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(p) digitalPinToInterrupt(p) + #define RADIOLIB_NC (0xFFFFFFFF) + #define RADIOLIB_DEFAULT_SPI SPI + + #elif defined(ARDUINO_ARC32_TOOLS) + // Intel Curie + #define RADIOLIB_PLATFORM "Intel Curie" + #define RADIOLIB_PIN_TYPE uint8_t + #define RADIOLIB_PIN_MODE uint8_t + #define RADIOLIB_PIN_STATUS uint8_t + #define RADIOLIB_INTERRUPT_STATUS RADIOLIB_PIN_STATUS + #define RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(p) digitalPinToInterrupt(p) + #define RADIOLIB_NC (0xFF) + #define RADIOLIB_DEFAULT_SPI SPI + + #elif defined(ARDUINO_AVR_UNO_WIFI_REV2) || defined(ARDUINO_AVR_NANO_EVERY) + // Arduino megaAVR boards - Uno Wifi Rev.2, Nano Every + #define RADIOLIB_PLATFORM "Arduino megaAVR" + #define RADIOLIB_PIN_TYPE uint8_t + #define RADIOLIB_PIN_MODE PinMode + #define RADIOLIB_PIN_STATUS PinStatus + #define RADIOLIB_INTERRUPT_STATUS RADIOLIB_PIN_STATUS + #define RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(p) digitalPinToInterrupt(p) + #define RADIOLIB_NC (0xFF) + #define RADIOLIB_DEFAULT_SPI SPI + + #elif defined(AM_PART_APOLLO3) + // Sparkfun Artemis boards + #define RADIOLIB_PLATFORM "Sparkfun Artemis" + #define RADIOLIB_PIN_TYPE uint8_t + #define RADIOLIB_PIN_MODE uint8_t + #define RADIOLIB_PIN_STATUS uint8_t + #define RADIOLIB_INTERRUPT_STATUS RADIOLIB_PIN_STATUS + #define RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(p) digitalPinToInterrupt(p) + #define RADIOLIB_NC (0xFF) + #define RADIOLIB_DEFAULT_SPI SPI + #define RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED + #define RADIOLIB_HARDWARE_SERIAL_PORT Serial1 + #define RADIOLIB_TONE_UNSUPPORTED + + #elif defined(ARDUINO_ARDUINO_NANO33BLE) + // Arduino Nano 33 BLE + #define RADIOLIB_PLATFORM "Arduino Nano 33 BLE" + #define RADIOLIB_PIN_TYPE pin_size_t + #define RADIOLIB_PIN_MODE PinMode + #define RADIOLIB_PIN_STATUS PinStatus + #define RADIOLIB_INTERRUPT_STATUS RADIOLIB_PIN_STATUS + #define RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(p) digitalPinToInterrupt(p) + #define RADIOLIB_NC (0xFF) + #define RADIOLIB_DEFAULT_SPI SPI + #define RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED + #define RADIOLIB_HARDWARE_SERIAL_PORT Serial1 + + // Nano 33 BLE uses mbed libraries, which already contain ESP8266 driver + #define RADIOLIB_EXCLUDE_ESP8266 + + #elif defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_PORTENTA_H7_M4) + // Arduino Portenta H7 + #define RADIOLIB_PLATFORM "Portenta H7" + #define RADIOLIB_PIN_TYPE pin_size_t + #define RADIOLIB_PIN_MODE PinMode + #define RADIOLIB_PIN_STATUS PinStatus + #define RADIOLIB_INTERRUPT_STATUS RADIOLIB_PIN_STATUS + #define RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(p) digitalPinToInterrupt(p) + #define RADIOLIB_NC (0xFF) + #define RADIOLIB_DEFAULT_SPI SPI + #define RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED + #define RADIOLIB_HARDWARE_SERIAL_PORT Serial1 + + // Arduino Portenta H7 uses mbed libraries, which already contain ESP8266 driver + #define RADIOLIB_EXCLUDE_ESP8266 + + #elif defined(__STM32F4__) || defined(__STM32F1__) + // Arduino STM32 core by Roger Clark (https://github.com/rogerclarkmelbourne/Arduino_STM32) + #define RADIOLIB_PLATFORM "STM32duino (unofficial)" + #define RADIOLIB_PIN_TYPE uint8_t + #define RADIOLIB_PIN_MODE WiringPinMode + #define RADIOLIB_PIN_STATUS uint8_t + #define RADIOLIB_INTERRUPT_STATUS ExtIntTriggerMode + #define RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(p) digitalPinToInterrupt(p) + #define RADIOLIB_NC (0xFF) + #define RADIOLIB_DEFAULT_SPI SPI + #define RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED + #define RADIOLIB_HARDWARE_SERIAL_PORT Serial1 + #define RADIOLIB_TONE_UNSUPPORTED + + #else + // other platforms not covered by the above list - this may or may not work + #define RADIOLIB_PLATFORM "Unknown" + #define RADIOLIB_UNKNOWN_PLATFORM + #define RADIOLIB_PIN_TYPE uint8_t + #define RADIOLIB_PIN_MODE uint8_t + #define RADIOLIB_PIN_STATUS uint8_t + #define RADIOLIB_INTERRUPT_STATUS RADIOLIB_PIN_STATUS + #define RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(p) digitalPinToInterrupt(p) + #define RADIOLIB_NC (0xFF) + #define RADIOLIB_DEFAULT_SPI SPI + + #endif +#endif + +/* + * Uncomment to enable debug output. + * Warning: Debug output will slow down the whole system significantly. + * Also, it will result in larger compiled binary. + * Levels: debug - only main info + * verbose - full transcript of all SPI/UART communication + */ + +//#define RADIOLIB_DEBUG +//#define RADIOLIB_VERBOSE + +// set which Serial port should be used for debug output +#define RADIOLIB_DEBUG_PORT Serial + +#if defined(RADIOLIB_DEBUG) + #define RADIOLIB_DEBUG_PRINT(...) { RADIOLIB_DEBUG_PORT.print(__VA_ARGS__); } + #define RADIOLIB_DEBUG_PRINTLN(...) { RADIOLIB_DEBUG_PORT.println(__VA_ARGS__); } +#else + #define RADIOLIB_DEBUG_PRINT(...) {} + #define RADIOLIB_DEBUG_PRINTLN(...) {} +#endif + +#if defined(RADIOLIB_VERBOSE) + #define RADIOLIB_VERBOSE_PRINT(...) { RADIOLIB_DEBUG_PORT.print(__VA_ARGS__); } + #define RADIOLIB_VERBOSE_PRINTLN(...) { RADIOLIB_DEBUG_PORT.println(__VA_ARGS__); } +#else + #define RADIOLIB_VERBOSE_PRINT(...) {} + #define RADIOLIB_VERBOSE_PRINTLN(...) {} +#endif + +/* + * Uncomment to enable god mode - all methods and member variables in all classes will be made public, thus making them accessible from Arduino code. + * Warning: Come on, it's called GOD mode - obviously only use this if you know what you're doing. + * Failure to heed the above warning may result in bricked module. + */ +//#define RADIOLIB_GODMODE + +/* + * Uncomment to enable pre-defined modules when using RadioShield. + */ +//#define RADIOLIB_RADIOSHIELD + +/* + * Uncomment to enable static-only memory management: no dynamic allocation will be performed. + * Warning: Large static arrays will be created in some methods. It is not advised to send large packets in this mode. + */ + +//#define RADIOLIB_STATIC_ONLY + +// set the size of static arrays to use +#if !defined(RADIOLIB_STATIC_ARRAY_SIZE) +#define RADIOLIB_STATIC_ARRAY_SIZE 256 +#endif + +/*! + \brief A simple assert macro, will return on error. +*/ +#define RADIOLIB_ASSERT(STATEVAR) { if((STATEVAR) != ERR_NONE) { return(STATEVAR); } } + +/*! + \brief Macro to check variable is within constraints - this is commonly used to check parameter ranges. +*/ +#define RADIOLIB_CHECK_RANGE(VAR, MIN, MAX, ERR) { if(!(((VAR) >= (MIN)) && ((VAR) <= (MAX)))) { return(ERR); } } + + +// version definitions +#define RADIOLIB_VERSION_MAJOR (0x04) +#define RADIOLIB_VERSION_MINOR (0x00) +#define RADIOLIB_VERSION_PATCH (0x01) +#define RADIOLIB_VERSION_EXTRA (0x00) + +#define RADIOLIB_VERSION ((RADIOLIB_VERSION_MAJOR << 24) | (RADIOLIB_VERSION_MINOR << 16) | (RADIOLIB_VERSION_PATCH << 8) | (RADIOLIB_VERSION_EXTRA)) + +#endif diff --git a/src/ISerial.cpp b/src/ISerial.cpp index 8cd4c65a..dbfa6a30 100644 --- a/src/ISerial.cpp +++ b/src/ISerial.cpp @@ -8,41 +8,10 @@ void ISerial::begin(long speed) { _mod->ModuleSerial->begin(speed); } -bool ISerial::listen() { -#ifdef RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED - return true; -#else - return(_mod->ModuleSerial->listen()); -#endif -} - void ISerial::end() { _mod->ModuleSerial->end(); } -bool ISerial::isListening() { -#ifdef RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED - return true; -#else - return(_mod->ModuleSerial->isListening()); -#endif -} - -bool ISerial::stopListening() { -#ifdef RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED - return true; -#else - return(_mod->ModuleSerial->stopListening()); -#endif -} - -bool ISerial::overflow() { -#ifdef RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED - return false; -#else - return(_mod->ModuleSerial->overflow()); -#endif -} int ISerial::peek() { return(_mod->ModuleSerial->peek()); @@ -64,6 +33,25 @@ void ISerial::flush() { _mod->ModuleSerial->flush(); } +// SoftwareSerial-only methods +#if !defined(RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED) +bool ISerial::listen() { + return(_mod->ModuleSerial->listen()); +} + +bool ISerial::isListening() { + return(_mod->ModuleSerial->isListening()); +} + +bool ISerial::stopListening() { + return(_mod->ModuleSerial->stopListening()); +} + +bool ISerial::overflow() { + return(_mod->ModuleSerial->overflow()); +} +#endif + size_t ISerial::print(const __FlashStringHelper *ifsh) { return(_mod->ModuleSerial->print(ifsh)); } diff --git a/src/ISerial.h b/src/ISerial.h index d086beaf..34064934 100644 --- a/src/ISerial.h +++ b/src/ISerial.h @@ -15,20 +15,24 @@ */ class ISerial { public: - ISerial(Module* mod); + explicit ISerial(Module* mod); void begin(long); - bool listen(); void end(); - bool isListening(); - bool stopListening(); - bool overflow(); int peek(); size_t write(uint8_t); int read(); int available(); void flush(); + // SoftwareSerial-only methods + #if !defined(RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED) + bool listen(); + bool isListening(); + bool stopListening(); + bool overflow(); + #endif + size_t print(const __FlashStringHelper *); size_t print(const String &); size_t print(const char[]); diff --git a/src/Module.cpp b/src/Module.cpp index bce8abd4..774b409b 100644 --- a/src/Module.cpp +++ b/src/Module.cpp @@ -1,84 +1,150 @@ #include "Module.h" -Module::Module(int16_t rx, int16_t tx, HardwareSerial* useSer, int16_t rst) { - _cs = NC; - _rx = rx; - _tx = tx; - _irq = NC; - _rst = rst; +Module::Module(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst): + _cs(cs), + _irq(irq), + _rst(rst), + _rx(RADIOLIB_NC), + _tx(RADIOLIB_NC), + _spiSettings(SPISettings(2000000, MSBFIRST, SPI_MODE0)) +{ + _spi = &RADIOLIB_DEFAULT_SPI; + _initInterface = true; + ModuleSerial = NULL; +} + +Module::Module(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE gpio): + _cs(cs), + _irq(irq), + _rst(rst), + _rx(gpio), + _tx(RADIOLIB_NC), + _spiSettings(SPISettings(2000000, MSBFIRST, SPI_MODE0)) +{ + _spi = &RADIOLIB_DEFAULT_SPI; + _initInterface = true; + ModuleSerial = NULL; +} + +Module::Module(RADIOLIB_PIN_TYPE rx, RADIOLIB_PIN_TYPE tx, HardwareSerial* serial, RADIOLIB_PIN_TYPE rst): + _cs(RADIOLIB_NC), + _irq(RADIOLIB_NC), + _rst(rst), + _rx(rx), + _tx(tx), + _spiSettings(SPISettings(2000000, MSBFIRST, SPI_MODE0)) +{ + _initInterface = true; #ifdef RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED - ModuleSerial = useSer; + ModuleSerial = serial; #else ModuleSerial = new SoftwareSerial(_rx, _tx); - (void)useSer; + (void)serial; #endif } -Module::Module(int16_t cs, int16_t irq, int16_t rst, SPIClass& spi, SPISettings spiSettings) { - _cs = cs; - _rx = NC; - _tx = NC; - _irq = irq; - _rst = rst; +Module::Module(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, SPIClass& spi, SPISettings spiSettings): + _cs(cs), + _irq(irq), + _rst(rst), + _rx(RADIOLIB_NC), + _tx(RADIOLIB_NC), + _spiSettings(spiSettings) +{ _spi = &spi; - _spiSettings = spiSettings; + _initInterface = false; + ModuleSerial = NULL; } -Module::Module(int16_t cs, int16_t irq, int16_t rst, int16_t gpio, SPIClass& spi, SPISettings spiSettings) { - _cs = cs; - _rx = gpio; - _tx = NC; - _irq = irq; - _rst = rst; +Module::Module(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE gpio, SPIClass& spi, SPISettings spiSettings): + _cs(cs), + _irq(irq), + _rst(rst), + _rx(gpio), + _tx(RADIOLIB_NC), + _spiSettings(spiSettings) +{ _spi = &spi; - _spiSettings = spiSettings; + _initInterface = false; + ModuleSerial = NULL; } -Module::Module(int16_t cs, int16_t irq, int16_t rst, int16_t rx, int16_t tx, SPIClass& spi, SPISettings spiSettings, HardwareSerial* useSer) { - _cs = cs; - _rx = rx; - _tx = tx; - _irq = irq; - _rst = rst; +Module::Module(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE rx, RADIOLIB_PIN_TYPE tx, SPIClass& spi, SPISettings spiSettings, HardwareSerial* serial): + _cs(cs), + _irq(irq), + _rst(rst), + _rx(rx), + _tx(tx), + _spiSettings(spiSettings) +{ _spi = &spi; - _spiSettings = spiSettings; + _initInterface = false; #ifdef RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED - ModuleSerial = useSer; + ModuleSerial = serial; #else ModuleSerial = new SoftwareSerial(_rx, _tx); - (void)useSer; + (void)serial; #endif } +Module::Module(const Module& mod) { + *this = mod; +} + +Module& Module::operator=(const Module& mod) { + this->ModuleSerial = mod.ModuleSerial; + this->baudrate = mod.baudrate; + memcpy(this->AtLineFeed, mod.AtLineFeed, strlen(mod.AtLineFeed)); + this->SPIreadCommand = mod.SPIreadCommand; + this->SPIwriteCommand = mod.SPIwriteCommand; + this->_cs = mod.getCs(); + this->_irq = mod.getIrq(); + this->_rst = mod.getRst(); + this->_rx = mod.getRx(); + this->_tx = mod.getTx(); + this->_spiSettings = mod.getSpiSettings(); + this->_spi = mod.getSpi(); + + return(*this); +} + void Module::init(uint8_t interface) { // select interface switch(interface) { case RADIOLIB_USE_SPI: Module::pinMode(_cs, OUTPUT); Module::digitalWrite(_cs, HIGH); - _spi->begin(); + if(_initInterface) { + _spi->begin(); + } break; case RADIOLIB_USE_UART: + if(_initInterface) { #if defined(ESP32) - ModuleSerial->begin(baudrate, SERIAL_8N1, _rx, _tx); + ModuleSerial->begin(baudrate, SERIAL_8N1, _rx, _tx); #else - ModuleSerial->begin(baudrate); + ModuleSerial->begin(baudrate); #endif + } break; case RADIOLIB_USE_I2C: break; } } -void Module::term() { - // stop hardware interfaces - if(_spi != nullptr) { +void Module::term(uint8_t interface) { + // stop hardware interfaces (if they were initialized by the library) + if(!_initInterface) { + return; + } + + if((interface == RADIOLIB_USE_SPI) && (_spi != nullptr)) { _spi->end(); } - if(ModuleSerial != nullptr) { + if(((interface == RADIOLIB_USE_UART) && ModuleSerial != nullptr)) { ModuleSerial->end(); } } @@ -107,19 +173,20 @@ bool Module::ATsendData(uint8_t* data, uint32_t len) { } bool Module::ATgetResponse() { - String data = ""; + char data[128]; + char* dataPtr = data; uint32_t start = millis(); - while (millis() - start < _ATtimeout) { + while(millis() - start < _ATtimeout) { while(ModuleSerial->available() > 0) { char c = ModuleSerial->read(); RADIOLIB_VERBOSE_PRINT(c); - data += c; + *dataPtr++ = c; } - if(data.indexOf("OK") != -1) { + if(strstr(data, "OK") == 0) { RADIOLIB_VERBOSE_PRINTLN(); return(true); - } else if (data.indexOf("ERROR") != -1) { + } else if(strstr(data, "ERROR") == 0) { RADIOLIB_VERBOSE_PRINTLN(); return(false); } @@ -152,7 +219,7 @@ int16_t Module::SPIsetRegValue(uint8_t reg, uint8_t value, uint8_t msb, uint8_t // check register value each millisecond until check interval is reached // some registers need a bit of time to process the change (e.g. SX127X_REG_OP_MODE) uint32_t start = micros(); - uint8_t readValue = 0; + uint8_t readValue; while(micros() - start < (checkInterval * 1000)) { readValue = SPIreadRegister(reg); if(readValue == newValue) { @@ -224,16 +291,20 @@ void Module::SPItransfer(uint8_t cmd, uint8_t reg, uint8_t* dataOut, uint8_t* da // send data or get response if(cmd == SPIwriteCommand) { - for(size_t n = 0; n < numBytes; n++) { - _spi->transfer(dataOut[n]); - RADIOLIB_VERBOSE_PRINT(dataOut[n], HEX); - RADIOLIB_VERBOSE_PRINT('\t'); + if(dataOut != NULL) { + for(size_t n = 0; n < numBytes; n++) { + _spi->transfer(dataOut[n]); + RADIOLIB_VERBOSE_PRINT(dataOut[n], HEX); + RADIOLIB_VERBOSE_PRINT('\t'); + } } } else if (cmd == SPIreadCommand) { - for(size_t n = 0; n < numBytes; n++) { - dataIn[n] = _spi->transfer(0x00); - RADIOLIB_VERBOSE_PRINT(dataIn[n], HEX); - RADIOLIB_VERBOSE_PRINT('\t'); + if(dataIn != NULL) { + for(size_t n = 0; n < numBytes; n++) { + dataIn[n] = _spi->transfer(0x00); + RADIOLIB_VERBOSE_PRINT(dataIn[n], HEX); + RADIOLIB_VERBOSE_PRINT('\t'); + } } } RADIOLIB_VERBOSE_PRINTLN(); @@ -245,14 +316,58 @@ void Module::SPItransfer(uint8_t cmd, uint8_t reg, uint8_t* dataOut, uint8_t* da _spi->endTransaction(); } -void Module::pinMode(int16_t pin, uint8_t mode) { - if(pin != NC) { +void Module::pinMode(RADIOLIB_PIN_TYPE pin, RADIOLIB_PIN_MODE mode) { + if(pin != RADIOLIB_NC) { ::pinMode(pin, mode); } } -void Module::digitalWrite(int16_t pin, uint8_t value) { - if(pin != NC) { +void Module::digitalWrite(RADIOLIB_PIN_TYPE pin, RADIOLIB_PIN_STATUS value) { + if(pin != RADIOLIB_NC) { ::digitalWrite(pin, value); } } + +RADIOLIB_PIN_STATUS Module::digitalRead(RADIOLIB_PIN_TYPE pin) { + if(pin != RADIOLIB_NC) { + return(::digitalRead(pin)); + } + return(LOW); +} + +void Module::tone(RADIOLIB_PIN_TYPE pin, uint16_t value) { + /// \todo Add tone support for platforms without tone() + #ifndef RADIOLIB_TONE_UNSUPPORTED + if(pin != RADIOLIB_NC) { + ::tone(pin, value); + } + #endif +} + +void Module::noTone(RADIOLIB_PIN_TYPE pin) { + /// \todo Add tone support for platforms without tone() + #ifndef RADIOLIB_TONE_UNSUPPORTED + if(pin != RADIOLIB_NC) { + ::noTone(pin); + } + #endif +} + +void Module::setRfSwitchPins(RADIOLIB_PIN_TYPE rxEn, RADIOLIB_PIN_TYPE txEn) { + _useRfSwitch = true; + _rxEn = rxEn; + _txEn = txEn; + Module::pinMode(rxEn, OUTPUT); + Module::pinMode(txEn, OUTPUT); +} + +void Module::setRfSwitchState(RADIOLIB_PIN_STATUS rxPinState, RADIOLIB_PIN_STATUS txPinState) { + // check RF switch control is enabled + if(!_useRfSwitch) { + return; + } + + // set pins + Module::digitalWrite(_rxEn, rxPinState); + Module::digitalWrite(_txEn, txPinState); +} diff --git a/src/Module.h b/src/Module.h index cb688435..aa12389f 100644 --- a/src/Module.h +++ b/src/Module.h @@ -21,20 +21,44 @@ class Module { /*! \brief UART-based module constructor. - \param tx Arduino pin to be used as Tx pin for SoftwareSerial communication. - \param rx Arduino pin to be used as Rx pin for SoftwareSerial communication. + \param tx Arduino pin to be used as Tx pin for SoftwareSerial communication. + \param serial HardwareSerial to be used on platforms that do not support SoftwareSerial. Defaults to Serial1. - \param rst Arduino pin to be used as hardware reset for the module. Defaults to -1 (unused). + \param rst Arduino pin to be used as hardware reset for the module. Defaults to NC (unused). */ #ifdef RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED - Module(int16_t tx, int16_t rx, HardwareSerial* serial = &Serial1, int16_t rst = -1); + Module(RADIOLIB_PIN_TYPE rx, RADIOLIB_PIN_TYPE tx, HardwareSerial* serial = &RADIOLIB_HARDWARE_SERIAL_PORT, RADIOLIB_PIN_TYPE rst = RADIOLIB_NC); #else - Module(int16_t tx, int16_t rx, HardwareSerial* serial = nullptr, int16_t rst = -1); + Module(RADIOLIB_PIN_TYPE rx, RADIOLIB_PIN_TYPE tx, HardwareSerial* serial = nullptr, RADIOLIB_PIN_TYPE rst = RADIOLIB_NC); #endif + /*! + \brief SPI-based module constructor. Will use the default SPI interface automatically initialize it. + + \param cs Arduino pin to be used as chip select. + + \param irq Arduino pin to be used as interrupt/GPIO. + + \param rst Arduino pin to be used as hardware reset for the module. + */ + Module(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst); + + /*! + \brief Extended SPI-based module constructor. Will use the default SPI interface automatically initialize it. + + \param cs Arduino pin to be used as chip select. + + \param irq Arduino pin to be used as interrupt/GPIO. + + \param rst Arduino pin to be used as hardware reset for the module. + + \param gpio Arduino pin to be used as additional interrupt/GPIO. + */ + Module(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE gpio); + /*! \brief SPI-based module constructor. @@ -44,11 +68,11 @@ class Module { \param rst Arduino pin to be used as hardware reset for the module. - \param spi SPI interface to be used. Defaults to Arduino hardware SPI interface, can also use software SPI implementations. + \param spi SPI interface to be used, can also use software SPI implementations. - \param spiSettings SPI interface settings. Defaults to 2 MHz clock, MSB first, mode 0. + \param spiSettings SPI interface settings. */ - Module(int16_t cs, int16_t irq, int16_t rst, SPIClass& spi = SPI, SPISettings spiSettings = SPISettings(2000000, MSBFIRST, SPI_MODE0)); + Module(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, SPIClass& spi, SPISettings spiSettings); /*! \brief Extended SPI-based module constructor. @@ -61,11 +85,11 @@ class Module { \param gpio Arduino pin to be used as additional interrupt/GPIO. - \param spi SPI interface to be used. Defaults to Arduino hardware SPI interface, can also use software SPI implementations. + \param spi SPI interface to be used, can also use software SPI implementations. - \param spiSettings SPI interface settings. Defaults to 2 MHz clock, MSB first, mode 0. + \param spiSettings SPI interface settings. */ - Module(int16_t cs, int16_t irq, int16_t rst, int16_t gpio, SPIClass& spi = SPI, SPISettings spiSettings = SPISettings(2000000, MSBFIRST, SPI_MODE0)); + Module(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE gpio, SPIClass& spi, SPISettings spiSettings); /*! \brief Generic module constructor. @@ -87,11 +111,24 @@ class Module { \param serial HardwareSerial to be used on ESP32 and SAMD. Defaults to 1 */ #ifdef RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED - Module(int16_t cs, int16_t irq, int16_t rst, int16_t rx, int16_t tx, SPIClass& spi = SPI, SPISettings spiSettings = SPISettings(2000000, MSBFIRST, SPI_MODE0), HardwareSerial* serial = &Serial1); + Module(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE rx, RADIOLIB_PIN_TYPE tx, SPIClass& spi = RADIOLIB_DEFAULT_SPI, SPISettings spiSettings = SPISettings(2000000, MSBFIRST, SPI_MODE0), HardwareSerial* serial = &RADIOLIB_HARDWARE_SERIAL_PORT); #else - Module(int16_t cs, int16_t irq, int16_t rst, int16_t rx, int16_t tx, SPIClass& spi = SPI, SPISettings spiSettings = SPISettings(2000000, MSBFIRST, SPI_MODE0), HardwareSerial* serial = nullptr); + Module(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE rx, RADIOLIB_PIN_TYPE tx, SPIClass& spi = RADIOLIB_DEFAULT_SPI, SPISettings spiSettings = SPISettings(2000000, MSBFIRST, SPI_MODE0), HardwareSerial* serial = nullptr); #endif + /*! + \brief Copy constructor. + + \param mod Module instance to copy. + */ + Module(const Module& mod); + + /*! + \brief Overload for assignment operator. + + \param frame rvalue Module. + */ + Module& operator=(const Module& mod); // public member variables @@ -112,7 +149,7 @@ class Module { /*! \brief Line feed to be used when sending AT commands. Defaults to CR+LF. */ - const char* AtLineFeed = "\r\n"; + char AtLineFeed[3] = {'\r', '\n'}; /*! \brief Basic SPI read command. Defaults to 0x00. @@ -135,8 +172,10 @@ class Module { /*! \brief Terminate low-level module control. + + \param interface Interface to be terminated. See \ref shield_config for details. */ - void term(); + void term(uint8_t interface); // AT methods @@ -148,7 +187,7 @@ class Module { /*! \brief Get response after sending AT command. - \returns True if AT response contains the string "OK", false otehrwise. + \returns True if AT response contains the string "OK", false otherwise. */ bool ATgetResponse(); @@ -266,42 +305,42 @@ class Module { \returns Pin number of SPI chip select configured in the constructor. */ - int16_t getCs() const { return(_cs); } + RADIOLIB_PIN_TYPE getCs() const { return(_cs); } /*! \brief Access method to get the pin number of interrupt/GPIO. \returns Pin number of interrupt/GPIO configured in the constructor. */ - int16_t getIrq() const { return(_irq); } + RADIOLIB_PIN_TYPE getIrq() const { return(_irq); } /*! \brief Access method to get the pin number of hardware reset pin. \returns Pin number of hardware reset pin configured in the constructor. */ - int16_t getRst() const { return(_rst); } + RADIOLIB_PIN_TYPE getRst() const { return(_rst); } /*! \brief Access method to get the pin number of second interrupt/GPIO. \returns Pin number of second interrupt/GPIO configured in the constructor. */ - int16_t getGpio() const { return(_rx); } + RADIOLIB_PIN_TYPE getGpio() const { return(_rx); } /*! \brief Access method to get the pin number of UART Rx. \returns Pin number of UART Rx configured in the constructor. */ - int16_t getRx() const { return(_rx); } + RADIOLIB_PIN_TYPE getRx() const { return(_rx); } /*! \brief Access method to get the pin number of UART Rx. \returns Pin number of UART Rx configured in the constructor. */ - int16_t getTx() const { return(_tx); } + RADIOLIB_PIN_TYPE getTx() const { return(_tx); } /*! \brief Access method to get the SPI interface. @@ -318,34 +357,83 @@ class Module { SPISettings getSpiSettings() const { return(_spiSettings); } /*! - \brief Arduino core pinMode override that checks -1 as alias for unused pin. + \brief Arduino core pinMode override that checks RADIOLIB_NC as alias for unused pin. \param pin Pin to change the mode of. \param mode Which mode to set. */ - static void pinMode(int16_t pin, uint8_t mode); + static void pinMode(RADIOLIB_PIN_TYPE pin, RADIOLIB_PIN_MODE mode); /*! - \brief Arduino core digitalWrite override that checks -1 as alias for unused pin. + \brief Arduino core digitalWrite override that checks RADIOLIB_NC as alias for unused pin. \param pin Pin to write to. \param value Whether to set the pin high or low. */ - static void digitalWrite(int16_t pin, uint8_t value); + static void digitalWrite(RADIOLIB_PIN_TYPE pin, RADIOLIB_PIN_STATUS value); + + /*! + \brief Arduino core digitalWrite override that checks RADIOLIB_NC as alias for unused pin. + + \param pin Pin to read from. + + \returns Pin value. + */ + static RADIOLIB_PIN_STATUS digitalRead(RADIOLIB_PIN_TYPE pin); + + /*! + \brief Arduino core tone override that checks RADIOLIB_NC as alias for unused pin and RADIOLIB_TONE_UNSUPPORTED to make sure the platform does support tone. + + \param pin Pin to write to. + + \param value Frequency to output. + */ + static void tone(RADIOLIB_PIN_TYPE pin, uint16_t value); + + /*! + \brief Arduino core noTone override that checks RADIOLIB_NC as alias for unused pin and RADIOLIB_TONE_UNSUPPORTED to make sure the platform does support tone. + + \param pin Pin to write to. + */ + static void noTone(RADIOLIB_PIN_TYPE pin); + + /*! + \brief Some modules contain external RF switch controlled by two pins. This function gives RadioLib control over those two pins to automatically switch Rx and Tx state. + When using automatic RF switch control, DO NOT change the pin mode of rxEn or txEn from Arduino sketch! + + \param rxEn RX enable pin. + + \param txEn TX enable pin. + */ + void setRfSwitchPins(RADIOLIB_PIN_TYPE rxEn, RADIOLIB_PIN_TYPE txEn); + + /*! + \brief Set RF switch state. + + \param rxPinState Pin state to set on Tx enable pin (usually high to transmit). + + \param txPinState Pin state to set on Rx enable pin (usually high to receive). + */ + void setRfSwitchState(RADIOLIB_PIN_STATUS rxPinState, RADIOLIB_PIN_STATUS txPinState); #ifndef RADIOLIB_GODMODE private: #endif - int16_t _cs; - int16_t _tx; - int16_t _rx; - int16_t _irq; - int16_t _rst; + RADIOLIB_PIN_TYPE _cs = RADIOLIB_NC; + RADIOLIB_PIN_TYPE _irq = RADIOLIB_NC; + RADIOLIB_PIN_TYPE _rst = RADIOLIB_NC; + RADIOLIB_PIN_TYPE _rx = RADIOLIB_NC; + RADIOLIB_PIN_TYPE _tx = RADIOLIB_NC; - SPIClass* _spi; - SPISettings _spiSettings; + SPISettings _spiSettings = SPISettings(2000000, MSBFIRST, SPI_MODE0); + + bool _initInterface = false; + SPIClass* _spi = NULL; + + bool _useRfSwitch = false; + RADIOLIB_PIN_TYPE _rxEn = RADIOLIB_NC, _txEn = RADIOLIB_NC; uint32_t _ATtimeout = 15000; }; diff --git a/src/RadioLib.h b/src/RadioLib.h index 1775fa0e..c6afae7a 100644 --- a/src/RadioLib.h +++ b/src/RadioLib.h @@ -11,14 +11,18 @@ - HC05 Bluetooth module - JDY08 BLE module - RF69 FSK module + - Si443x FSK module - SX126x LoRa/FSK module - SX127x LoRa/FSK module + - SX128x LoRa/GFSK/BLE/FLRC module - SX1231 FSK module - XBee module (S2B) - PhysicalLayer protocols - RTTY (RTTYClient) - Morse Code (MorseClient) - AX.25 (AX25Client) + - SSTV (SSTVClient) + - Hellschreiber (HellClient) - TransportLayer protocols - HTTP (HTTPClient) - MQTT (MQTTClient) @@ -39,21 +43,37 @@ #include "TypeDef.h" #include "Module.h" +// warnings are printed in this file since BuildOpt.h is compiled in multiple places + +// check God mode #ifdef RADIOLIB_GODMODE #warning "God mode active, I hope it was intentional. Buckle up, lads." #endif -#include "modules/CC1101/CC1101.h" -#ifndef ESP8266 -#include "modules/ESP8266/ESP8266.h" +// print debug info +#ifdef RADIOLIB_DEBUG + #pragma message "RADIOLIB_PLATFORM: " RADIOLIB_PLATFORM #endif + +// check unknown/unsupported platform +#ifdef RADIOLIB_UNKNOWN_PLATFORM + #warning "RadioLib might not be compatible with this Arduino board - check supported platforms at https://github.com/jgromes/RadioLib!" +#endif + +#include "modules/CC1101/CC1101.h" +#include "modules/ESP8266/ESP8266.h" #include "modules/HC05/HC05.h" #include "modules/JDY08/JDY08.h" #include "modules/nRF24/nRF24.h" #include "modules/RF69/RF69.h" +#include "modules/RFM2x/RFM22.h" +#include "modules/RFM2x/RFM23.h" #include "modules/RFM9x/RFM95.h" #include "modules/RFM9x/RFM96.h" #include "modules/RFM9x/RFM97.h" +#include "modules/Si443x/Si4430.h" +#include "modules/Si443x/Si4431.h" +#include "modules/Si443x/Si4432.h" #include "modules/SX1231/SX1231.h" #include "modules/SX126x/SX1261.h" #include "modules/SX126x/SX1262.h" @@ -64,20 +84,24 @@ #include "modules/SX127x/SX1277.h" #include "modules/SX127x/SX1278.h" #include "modules/SX127x/SX1279.h" +#include "modules/SX128x/SX1280.h" +#include "modules/SX128x/SX1281.h" +#include "modules/SX128x/SX1282.h" #include "modules/XBee/XBee.h" // physical layer protocols #include "protocols/PhysicalLayer/PhysicalLayer.h" +#include "protocols/AFSK/AFSK.h" #include "protocols/AX25/AX25.h" +#include "protocols/Hellschreiber/Hellschreiber.h" #include "protocols/Morse/Morse.h" #include "protocols/RTTY/RTTY.h" +#include "protocols/SSTV/SSTV.h" // transport layer protocols -#ifndef ESP8266 #include "protocols/TransportLayer/TransportLayer.h" #include "protocols/HTTP/HTTP.h" #include "protocols/MQTT/MQTT.h" -#endif // only create Radio class when using RadioShield #ifdef RADIOLIB_RADIOSHIELD @@ -98,7 +122,6 @@ \brief Library control object when using RadioShield. Contains two pre-configured "modules", which correspond to the slots on shield. */ - class Radio { public: diff --git a/src/TypeDef.h b/src/TypeDef.h index 8ed5b4ee..aa4c41af 100644 --- a/src/TypeDef.h +++ b/src/TypeDef.h @@ -1,90 +1,7 @@ #ifndef _RADIOLIB_TYPES_H #define _RADIOLIB_TYPES_H -#if ARDUINO >= 100 - #include "Arduino.h" -#else - #error "Unsupported Arduino version (< 1.0.0)" -#endif - -// version definitions -#define RADIOLIB_VERSION_MAJOR (0x03) -#define RADIOLIB_VERSION_MINOR (0x03) -#define RADIOLIB_VERSION_PATCH (0x01) -#define RADIOLIB_VERSION_EXTRA (0x00) - -#define RADIOLIB_VERSION ((RADIOLIB_VERSION_MAJOR << 24) | (RADIOLIB_VERSION_MAJOR << 16) | (RADIOLIB_VERSION_MAJOR << 8) | (RADIOLIB_VERSION_EXTRA)) - -/* - * Uncomment to enable static-only memory management: no dynamic allocation will be performed. - * Warning: Large static arrays will be created in some methods. It is not advised to send large packets in this mode. - */ - -//#define RADIOLIB_STATIC_ONLY - -// set the size of static arrays to use -#define RADIOLIB_STATIC_ARRAY_SIZE 256 - -/* - * Uncomment to enable debug output. - * Warning: Debug output will slow down the whole system significantly. - * Also, it will result in larger compiled binary. - * Levels: debug - only main info - * verbose - full transcript of all SPI/UART communication - */ - -//#define RADIOLIB_DEBUG -//#define RADIOLIB_VERBOSE - -// set which Serial port should be used for debug output -#define RADIOLIB_DEBUG_PORT Serial - -#ifdef RADIOLIB_DEBUG - #define RADIOLIB_DEBUG_PRINT(...) { RADIOLIB_DEBUG_PORT.print(__VA_ARGS__); } - #define RADIOLIB_DEBUG_PRINTLN(...) { RADIOLIB_DEBUG_PORT.println(__VA_ARGS__); } -#else - #define RADIOLIB_DEBUG_PRINT(...) {} - #define RADIOLIB_DEBUG_PRINTLN(...) {} -#endif - -#ifdef RADIOLIB_VERBOSE - #define RADIOLIB_VERBOSE_PRINT(...) { RADIOLIB_DEBUG_PORT.print(__VA_ARGS__); } - #define RADIOLIB_VERBOSE_PRINTLN(...) { RADIOLIB_DEBUG_PORT.println(__VA_ARGS__); } -#else - #define RADIOLIB_VERBOSE_PRINT(...) {} - #define RADIOLIB_VERBOSE_PRINTLN(...) {} -#endif - -/* - * Uncomment to enable god mode - all methods and member variables in all classes will be made public, thus making them accessible from Arduino code. - * Warning: Come on, it's called GOD mode - obviously only use this if you know what you're doing. - * Failure to heed the above warning may result in bricked module. - */ -//#define RADIOLIB_GODMODE - -/* - * Uncomment to enable pre-defined modules when using RadioShield. - */ -//#define RADIOLIB_RADIOSHIELD - -/* - * The following platforms do not support SoftwareSerial library. - */ -#if defined(ESP32) || defined(SAMD_SERIES) || defined(ARDUINO_ARCH_STM32) || defined(__SAM3X8E__) || defined(AM_PART_APOLLO3) - #define RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED -#endif - -/*! - \brief Alias for unused pin, if not supplied by the Arduino core. -*/ -#if !(defined(NC) || defined(ARDUINO_ARCH_STM32)) -#define NC (-1) -#endif - -/*! - \brief A simple assert macro, will return on error. -*/ -#define RADIOLIB_ASSERT(STATEVAR) { if(STATEVAR != ERR_NONE) { return(STATEVAR); } } +#include "BuildOpt.h" /*! \defgroup shield_config Shield Configuration @@ -171,6 +88,66 @@ \} */ +/*! + \defgroup config_shaping Data shaping filter values aliases. + + \{ +*/ + +/*! + \brief No shaping. +*/ +#define RADIOLIB_SHAPING_NONE 0x00 + +/*! + \brief Gaussin shaping filter, BT = 0.3 +*/ +#define RADIOLIB_SHAPING_0_3 0x01 + +/*! + \brief Gaussin shaping filter, BT = 0.5 +*/ +#define RADIOLIB_SHAPING_0_5 0x02 + +/*! + \brief Gaussin shaping filter, BT = 0.7 +*/ +#define RADIOLIB_SHAPING_0_7 0x03 + +/*! + \brief Gaussin shaping filter, BT = 1.0 +*/ +#define RADIOLIB_SHAPING_1_0 0x04 + +/*! + \} +*/ + +/*! + \defgroup config_encoding Encoding type aliases. + + \{ +*/ + +/*! + \brief Non-return to zero - no encoding. +*/ +#define RADIOLIB_ENCODING_NRZ 0x00 + +/*! + \brief Manchester encoding. +*/ +#define RADIOLIB_ENCODING_MANCHESTER 0x01 + +/*! + \brief Whitening. +*/ +#define RADIOLIB_ENCODING_WHITENING 0x02 + +/*! + \} +*/ + /*! \defgroup status_codes Status Codes @@ -563,6 +540,13 @@ */ #define ERR_INVALID_REPEATER_CALLSIGN -803 +// SX128x-specific status codes + +/*! + \brief Timed out waiting for ranging exchange finish. +*/ +#define ERR_RANGING_TIMEOUT -901 + /*! \} */ diff --git a/src/modules/CC1101/CC1101.cpp b/src/modules/CC1101/CC1101.cpp index 6b01a9d8..46e10452 100644 --- a/src/modules/CC1101/CC1101.cpp +++ b/src/modules/CC1101/CC1101.cpp @@ -1,12 +1,8 @@ #include "CC1101.h" +#if !defined(RADIOLIB_EXCLUDE_CC1101) CC1101::CC1101(Module* module) : PhysicalLayer(CC1101_FREQUENCY_STEP_SIZE, CC1101_MAX_PACKET_LENGTH) { _mod = module; - _packetLengthQueried = false; - _packetLengthConfig = CC1101_LENGTH_CONFIG_VARIABLE; - _modulation = CC1101_MOD_FORMAT_2_FSK; - - _syncWordLength = 2; } int16_t CC1101::begin(float freq, float br, float freqDev, float rxBw, int8_t power, uint8_t preambleLength) { @@ -35,14 +31,14 @@ int16_t CC1101::begin(float freq, float br, float freqDev, float rxBw, int8_t po RADIOLIB_DEBUG_PRINT(F(", expected 0x0014")); RADIOLIB_DEBUG_PRINTLN(); #endif - delay(1000); + delay(10); i++; } } if(!flagFound) { RADIOLIB_DEBUG_PRINTLN(F("No CC1101 found!")); - SPI.end(); + _mod->term(RADIOLIB_USE_SPI); return(ERR_CHIP_NOT_FOUND); } else { RADIOLIB_DEBUG_PRINTLN(F("Found CC1101! (match by CC1101_REG_VERSION == 0x14)")); @@ -76,16 +72,20 @@ int16_t CC1101::begin(float freq, float br, float freqDev, float rxBw, int8_t po state = variablePacketLengthMode(); RADIOLIB_ASSERT(state); - // configure default preamble lenght + // configure default preamble length state = setPreambleLength(preambleLength); RADIOLIB_ASSERT(state); // set default data shaping - state = setDataShaping(0); + state = setDataShaping(RADIOLIB_ENCODING_NRZ); RADIOLIB_ASSERT(state); // set default encoding - state = setEncoding(2); + state = setEncoding(RADIOLIB_SHAPING_NONE); + RADIOLIB_ASSERT(state); + + // set default sync word + state = setSyncWord(0x12, 0xAD, 0, false); RADIOLIB_ASSERT(state); // flush FIFOs @@ -134,11 +134,18 @@ int16_t CC1101::receive(uint8_t* data, size_t len) { } int16_t CC1101::standby() { + // set idle mode SPIsendCommand(CC1101_CMD_IDLE); + + // set RF switch (if present) + _mod->setRfSwitchState(LOW, LOW); return(ERR_NONE); } int16_t CC1101::transmitDirect(uint32_t frf) { + // set RF switch (if present) + _mod->setRfSwitchState(LOW, HIGH); + // user requested to start transmitting immediately (required for RTTY) if(frf != 0) { SPIwriteRegister(CC1101_REG_FREQ2, (frf & 0xFF0000) >> 16); @@ -158,6 +165,9 @@ int16_t CC1101::transmitDirect(uint32_t frf) { } int16_t CC1101::receiveDirect() { + // set RF switch (if present) + _mod->setRfSwitchState(HIGH, LOW); + // activate direct mode int16_t state = directMode(); RADIOLIB_ASSERT(state); @@ -174,27 +184,27 @@ int16_t CC1101::packetMode() { return(state); } -void CC1101::setGdo0Action(void (*func)(void), uint8_t dir) { - attachInterrupt(digitalPinToInterrupt(_mod->getIrq()), func, dir); +void CC1101::setGdo0Action(void (*func)(void), RADIOLIB_INTERRUPT_STATUS dir) { + attachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getIrq()), func, dir); } void CC1101::clearGdo0Action() { - detachInterrupt(digitalPinToInterrupt(_mod->getIrq())); + detachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getIrq())); } -void CC1101::setGdo2Action(void (*func)(void), uint8_t dir) { - if(_mod->getGpio() != NC) { +void CC1101::setGdo2Action(void (*func)(void), RADIOLIB_INTERRUPT_STATUS dir) { + if(_mod->getGpio() != RADIOLIB_NC) { return; } Module::pinMode(_mod->getGpio(), INPUT); - attachInterrupt(digitalPinToInterrupt(_mod->getGpio()), func, dir); + attachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getGpio()), func, dir); } void CC1101::clearGdo2Action() { - if(_mod->getGpio() != NC) { + if(_mod->getGpio() != RADIOLIB_NC) { return; } - detachInterrupt(digitalPinToInterrupt(_mod->getGpio())); + detachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getGpio())); } int16_t CC1101::startTransmit(uint8_t* data, size_t len, uint8_t addr) { @@ -240,6 +250,9 @@ int16_t CC1101::startTransmit(uint8_t* data, size_t len, uint8_t addr) { SPIwriteRegisterBurst(CC1101_REG_FIFO, data, initialWrite); dataSent += initialWrite; + // set RF switch (if present) + _mod->setRfSwitchState(LOW, HIGH); + // set mode to transmit SPIsendCommand(CC1101_CMD_TX); @@ -274,6 +287,9 @@ int16_t CC1101::startReceive() { state |= SPIsetRegValue(CC1101_REG_FIFOTHR, CC1101_FIFO_THR_TX_61_RX_4, 3, 0); RADIOLIB_ASSERT(state); + // set RF switch (if present) + _mod->setRfSwitchState(HIGH, LOW); + // set mode to receive SPIsendCommand(CC1101_CMD_RX); @@ -385,15 +401,12 @@ int16_t CC1101::setFrequency(float freq) { } int16_t CC1101::setBitRate(float br) { - // check allowed bit rate range - if(!((br >= 0.025) && (br <= 600.0))) { - return(ERR_INVALID_BIT_RATE); - } + RADIOLIB_CHECK_RANGE(br, 0.025, 600.0, ERR_INVALID_BIT_RATE); // set mode to standby SPIsendCommand(CC1101_CMD_IDLE); - // calculate exponent and mantisa values + // calculate exponent and mantissa values uint8_t e = 0; uint8_t m = 0; getExpMant(br * 1000.0, 256, 28, 14, e, m); @@ -410,15 +423,12 @@ int16_t CC1101::setBitRate(float br) { } int16_t CC1101::setRxBandwidth(float rxBw) { - // check allowed bandwidth range - if(!((rxBw >= 58.0) && (rxBw <= 812.0))) { - return(ERR_INVALID_RX_BANDWIDTH); - } + RADIOLIB_CHECK_RANGE(rxBw, 58.0, 812.0, ERR_INVALID_RX_BANDWIDTH); // set mode to standby SPIsendCommand(CC1101_CMD_IDLE); - // calculate exponent and mantisa values + // calculate exponent and mantissa values for(int8_t e = 3; e >= 0; e--) { for(int8_t m = 3; m >= 0; m --) { float point = (CC1101_CRYSTAL_FREQ * 1000000.0)/(8 * (m + 4) * ((uint32_t)1 << e)); @@ -440,15 +450,12 @@ int16_t CC1101::setFrequencyDeviation(float freqDev) { return(state); } - // check allowed frequency deviation range - if(!((freqDev >= 1.587) && (freqDev <= 380.8))) { - return(ERR_INVALID_FREQUENCY_DEVIATION); - } + RADIOLIB_CHECK_RANGE(freqDev, 1.587, 380.8, ERR_INVALID_FREQUENCY_DEVIATION); // set mode to standby SPIsendCommand(CC1101_CMD_IDLE); - // calculate exponent and mantisa values + // calculate exponent and mantissa values uint8_t e = 0; uint8_t m = 0; getExpMant(freqDev * 1000.0, 8, 17, 7, e, m); @@ -569,28 +576,28 @@ int16_t CC1101::setPreambleLength(uint8_t preambleLength) { // check allowed values uint8_t value; switch(preambleLength){ - case 2: + case 16: value = CC1101_NUM_PREAMBLE_2; break; - case 3: + case 24: value = CC1101_NUM_PREAMBLE_3; break; - case 4: + case 32: value = CC1101_NUM_PREAMBLE_4; break; - case 6: + case 48: value = CC1101_NUM_PREAMBLE_6; break; - case 8: + case 64: value = CC1101_NUM_PREAMBLE_8; break; - case 12: + case 96: value = CC1101_NUM_PREAMBLE_12; break; - case 16: + case 128: value = CC1101_NUM_PREAMBLE_16; break; - case 24: + case 192: value = CC1101_NUM_PREAMBLE_24; break; default: @@ -603,9 +610,7 @@ int16_t CC1101::setPreambleLength(uint8_t preambleLength) { int16_t CC1101::setNodeAddress(uint8_t nodeAddr, uint8_t numBroadcastAddrs) { - if(!(numBroadcastAddrs > 0) && (numBroadcastAddrs <= 2)) { - return(ERR_INVALID_NUM_BROAD_ADDRS); - } + RADIOLIB_CHECK_RANGE(numBroadcastAddrs, 1, 2, ERR_INVALID_NUM_BROAD_ADDRS); // enable address filtering int16_t state = SPIsetRegValue(CC1101_REG_PKTCTRL1, numBroadcastAddrs + 0x01, 1, 0); @@ -631,8 +636,8 @@ int16_t CC1101::setOOK(bool enableOOK) { int16_t state = SPIsetRegValue(CC1101_REG_MDMCFG2, CC1101_MOD_FORMAT_ASK_OOK, 6, 4); RADIOLIB_ASSERT(state); - // PA_TABLE[0] is (by default) the power value used when transmitting a "0L". - // Set PA_TABLE[1] to be used when transmitting a "1L". + // PA_TABLE[0] is (by default) the power value used when transmitting a "0". + // Set PA_TABLE[1] to be used when transmitting a "1". state = SPIsetRegValue(CC1101_REG_FREND0, 1, 2, 0); RADIOLIB_ASSERT(state); @@ -656,7 +661,7 @@ int16_t CC1101::setOOK(bool enableOOK) { } -float CC1101::getRSSI() { +float CC1101::getRSSI() const { float rssi; if(_rawRSSI >= 128) { rssi = (((float)_rawRSSI - 256.0)/2.0) - 74.0; @@ -666,7 +671,7 @@ float CC1101::getRSSI() { return(rssi); } -uint8_t CC1101::getLQI() { +uint8_t CC1101::getLQI() const { return(_rawLQI); } @@ -695,11 +700,11 @@ int16_t CC1101::variablePacketLengthMode(uint8_t maxLen) { int16_t CC1101::enableSyncWordFiltering(uint8_t maxErrBits, bool requireCarrierSense) { switch (maxErrBits){ case 0: - // in 16 bit sync word, expect all 16 bits. + // in 16 bit sync word, expect all 16 bits return (SPIsetRegValue(CC1101_REG_MDMCFG2, requireCarrierSense ? CC1101_SYNC_MODE_16_16_THR : CC1101_SYNC_MODE_16_16, 2, 0)); case 1: - // in 16 bit sync word, expect at least 15 bits. + // in 16 bit sync word, expect at least 15 bits return (SPIsetRegValue(CC1101_REG_MDMCFG2, requireCarrierSense ? CC1101_SYNC_MODE_15_16_THR : CC1101_SYNC_MODE_15_16, 2, 0)); default: @@ -748,19 +753,21 @@ int16_t CC1101::setPromiscuousMode(bool promiscuous) { return(state); } -int16_t CC1101::setDataShaping(float sh) { +int16_t CC1101::setDataShaping(uint8_t sh) { // set mode to standby int16_t state = standby(); RADIOLIB_ASSERT(state); // set data shaping - sh *= 10.0; - if(abs(sh - 0.0) <= 0.001) { - state = _mod->SPIsetRegValue(CC1101_REG_MDMCFG2, CC1101_MOD_FORMAT_2_FSK, 6, 4); - } else if(abs(sh - 5.0) <= 0.001) { - state = _mod->SPIsetRegValue(CC1101_REG_MDMCFG2, CC1101_MOD_FORMAT_GFSK, 6, 4); - } else { - return(ERR_INVALID_DATA_SHAPING); + switch(sh) { + case RADIOLIB_SHAPING_NONE: + state = _mod->SPIsetRegValue(CC1101_REG_MDMCFG2, CC1101_MOD_FORMAT_2_FSK, 6, 4); + break; + case RADIOLIB_SHAPING_0_5: + state = _mod->SPIsetRegValue(CC1101_REG_MDMCFG2, CC1101_MOD_FORMAT_GFSK, 6, 4); + break; + default: + return(ERR_INVALID_DATA_SHAPING); } return(state); } @@ -772,15 +779,15 @@ int16_t CC1101::setEncoding(uint8_t encoding) { // set encoding switch(encoding) { - case 0: + case RADIOLIB_ENCODING_NRZ: state = _mod->SPIsetRegValue(CC1101_REG_MDMCFG2, CC1101_MANCHESTER_EN_OFF, 3, 3); RADIOLIB_ASSERT(state); return(_mod->SPIsetRegValue(CC1101_REG_PKTCTRL0, CC1101_WHITE_DATA_OFF, 6, 6)); - case 1: + case RADIOLIB_ENCODING_MANCHESTER: state = _mod->SPIsetRegValue(CC1101_REG_MDMCFG2, CC1101_MANCHESTER_EN_ON, 3, 3); RADIOLIB_ASSERT(state); return(_mod->SPIsetRegValue(CC1101_REG_PKTCTRL0, CC1101_WHITE_DATA_OFF, 6, 6)); - case 2: + case RADIOLIB_ENCODING_WHITENING: state = _mod->SPIsetRegValue(CC1101_REG_MDMCFG2, CC1101_MANCHESTER_EN_OFF, 3, 3); RADIOLIB_ASSERT(state); return(_mod->SPIsetRegValue(CC1101_REG_PKTCTRL0, CC1101_WHITE_DATA_ON, 6, 6)); @@ -789,6 +796,10 @@ int16_t CC1101::setEncoding(uint8_t encoding) { } } +void CC1101::setRfSwitchPins(RADIOLIB_PIN_TYPE rxEn, RADIOLIB_PIN_TYPE txEn) { + _mod->setRfSwitchPins(rxEn, txEn); +} + int16_t CC1101::config() { // Reset the radio. Registers may be dirty from previous usage. SPIsendCommand(CC1101_CMD_RESET); @@ -916,3 +927,5 @@ void CC1101::SPIsendCommand(uint8_t cmd) { SPI.endTransaction(); Module::digitalWrite(_mod->getCs(), HIGH); } + +#endif diff --git a/src/modules/CC1101/CC1101.h b/src/modules/CC1101/CC1101.h index 56062f73..3ae59291 100644 --- a/src/modules/CC1101/CC1101.h +++ b/src/modules/CC1101/CC1101.h @@ -1,4 +1,4 @@ -#ifndef _RADIOLIB_CC1101_H +#if !defined(_RADIOLIB_CC1101_H) && !defined(RADIOLIB_EXCLUDE_CC1101) #define _RADIOLIB_CC1101_H #include "../../TypeDef.h" @@ -522,21 +522,21 @@ class CC1101: public PhysicalLayer { /*! \brief Initialization method. - \param freq Carrier frequency in MHz. Defaults to 868.0 MHz. + \param freq Carrier frequency in MHz. Defaults to 434.0 MHz. - \param br Bit rate to be used in kbps. Defaults to 4.8 kbps. + \param br Bit rate to be used in kbps. Defaults to 48.0 kbps. \param freqDev Frequency deviation from carrier frequency in kHz Defaults to 48.0 kHz. - \param rxBw Receiver bandwidth in kHz. Defaults to 325.0 kHz. + \param rxBw Receiver bandwidth in kHz. Defaults to 125.0 kHz. - \param power Output power in dBm. Defaults to 0 dBm. + \param power Output power in dBm. Defaults to 10 dBm. - \param preambleLength Preamble Length in bytes. Defaults to 4 bytes. + \param preambleLength Preamble Length in bits. Defaults to 16 bits. \returns \ref status_codes */ - int16_t begin(float freq = 868.0, float br = 4.8, float freqDev = 48.0, float rxBw = 325.0, int8_t power = 0, uint8_t preambleLength = 4); + int16_t begin(float freq = 434.0, float br = 48.0, float freqDev = 48.0, float rxBw = 135.0, int8_t power = 10, uint8_t preambleLength = 16); /*! \brief Blocking binary transmit method. @@ -550,7 +550,7 @@ class CC1101: public PhysicalLayer { \returns \ref status_codes */ - int16_t transmit(uint8_t* data, size_t len, uint8_t addr = 0); + int16_t transmit(uint8_t* data, size_t len, uint8_t addr = 0) override; /*! \brief Blocking binary receive method. @@ -562,14 +562,14 @@ class CC1101: public PhysicalLayer { \returns \ref status_codes */ - int16_t receive(uint8_t* data, size_t len); + int16_t receive(uint8_t* data, size_t len) override; /*! \brief Sets the module to standby mode. \returns \ref status_codes */ - int16_t standby(); + int16_t standby() override; /*! \brief Starts direct mode transmission. @@ -578,14 +578,14 @@ class CC1101: public PhysicalLayer { \returns \ref status_codes */ - int16_t transmitDirect(uint32_t frf = 0); + int16_t transmitDirect(uint32_t frf = 0) override; /*! \brief Starts direct mode reception. \returns \ref status_codes */ - int16_t receiveDirect(); + int16_t receiveDirect() override; /*! \brief Stops direct mode. It is required to call this method to switch from direct transmissions to packet-based transmissions. @@ -601,7 +601,7 @@ class CC1101: public PhysicalLayer { \param dir Signal change direction. Defaults to RISING. */ - void setGdo0Action(void (*func)(void), uint8_t dir = RISING); + void setGdo0Action(void (*func)(void), RADIOLIB_INTERRUPT_STATUS dir = FALLING); /*! \brief Clears interrupt service routine to call when GDO0 activates. @@ -615,7 +615,7 @@ class CC1101: public PhysicalLayer { \param dir Signal change direction. Defaults to FALLING. */ - void setGdo2Action(void (*func)(void), uint8_t dir = FALLING); + void setGdo2Action(void (*func)(void), RADIOLIB_INTERRUPT_STATUS dir = FALLING); /*! \brief Clears interrupt service routine to call when GDO0 activates. @@ -634,7 +634,7 @@ class CC1101: public PhysicalLayer { \returns \ref status_codes */ - int16_t startTransmit(uint8_t* data, size_t len, uint8_t addr = 0); + int16_t startTransmit(uint8_t* data, size_t len, uint8_t addr = 0) override; /*! \brief Interrupt-driven receive method. GDO0 will be activated when full packet is received. @@ -652,7 +652,7 @@ class CC1101: public PhysicalLayer { \returns \ref status_codes */ - int16_t readData(uint8_t* data, size_t len); + int16_t readData(uint8_t* data, size_t len) override; // configuration methods @@ -690,7 +690,7 @@ class CC1101: public PhysicalLayer { \returns \ref status_codes */ - int16_t setFrequencyDeviation(float freqDev); + int16_t setFrequencyDeviation(float freqDev) override; /*! \brief Sets output power. Allowed values are -30, -20, -15, -10, 0, 5, 7 or 10 dBm. @@ -734,7 +734,7 @@ class CC1101: public PhysicalLayer { /*! \brief Sets preamble length. - \param preambleLength Preamble length to be set (in bytes), allowed values: 2, 3, 4, 6, 8, 12, 16, 24 + \param preambleLength Preamble length to be set (in bits), allowed values: 16, 24, 32, 48, 64, 96, 128 and 192. \returns \ref status_codes */ @@ -772,14 +772,14 @@ class CC1101: public PhysicalLayer { \returns Last packet RSSI in dBm. */ - float getRSSI(); + float getRSSI() const; /*! \brief Gets LQI (Link Quality Indicator) of the last received packet. \returns Last packet LQI (lower is better). */ - uint8_t getLQI(); + uint8_t getLQI() const; /*! \brief Query modem for the packet length of received payload. @@ -788,7 +788,7 @@ class CC1101: public PhysicalLayer { \returns Length of last received packet in bytes. */ - size_t getPacketLength(bool update = true); + size_t getPacketLength(bool update = true) override; /*! \brief Set modem in fixed packet length mode. @@ -848,47 +848,64 @@ class CC1101: public PhysicalLayer { /*! \brief Sets Gaussian filter bandwidth-time product that will be used for data shaping. - Allowed value is 0.5. Set to 0 to disable data shaping. + Allowed value is RADIOLIB_SHAPING_0_5. Set to RADIOLIB_SHAPING_NONE to disable data shaping. - \param sh Gaussian shaping bandwidth-time product that will be used for data shaping + \param sh Gaussian shaping bandwidth-time product that will be used for data shaping. \returns \ref status_codes */ - int16_t setDataShaping(float sh); + int16_t setDataShaping(uint8_t sh) override; /*! - \brief Sets transmission encoding. + \brief Sets transmission encoding. Allowed values are RADIOLIB_ENCODING_NRZ and RADIOLIB_ENCODING_WHITENING. - \param encoding Encoding to be used. Set to 0 for NRZ, 1 for Manchester and 2 for whitening. + \param encoding Encoding to be used. \returns \ref status_codes */ - int16_t setEncoding(uint8_t encoding); + int16_t setEncoding(uint8_t encoding) override; + + /*! + \brief Some modules contain external RF switch controlled by two pins. This function gives RadioLib control over those two pins to automatically switch Rx and Tx state. + When using automatic RF switch control, DO NOT change the pin mode of rxEn or txEn from Arduino sketch! + + \param rxEn RX enable pin. + + \param txEn TX enable pin. + */ + void setRfSwitchPins(RADIOLIB_PIN_TYPE rxEn, RADIOLIB_PIN_TYPE txEn); #ifndef RADIOLIB_GODMODE private: #endif Module* _mod; +<<<<<<< HEAD float _freq; float _br; uint8_t _rawRSSI; uint8_t _rawLQI; uint8_t _modulation; +======= + float _freq = 0; + uint8_t _rawRSSI = 0; + uint8_t _rawLQI = 0; + uint8_t _modulation = CC1101_MOD_FORMAT_2_FSK; +>>>>>>> upstream/master - size_t _packetLength; - bool _packetLengthQueried; - uint8_t _packetLengthConfig; + size_t _packetLength = 0; + bool _packetLengthQueried = false; + uint8_t _packetLengthConfig = CC1101_LENGTH_CONFIG_VARIABLE; - bool _promiscuous; + bool _promiscuous = false; bool _crcOn = true; - uint8_t _syncWordLength; - int8_t _power; + uint8_t _syncWordLength = 2; + int8_t _power = 0; int16_t config(); int16_t directMode(); - void getExpMant(float target, uint16_t mantOffset, uint8_t divExp, uint8_t expMax, uint8_t& exp, uint8_t& mant); + static void getExpMant(float target, uint16_t mantOffset, uint8_t divExp, uint8_t expMax, uint8_t& exp, uint8_t& mant); int16_t setPacketMode(uint8_t mode, uint8_t len); // SPI read overrides to set bit for burst write and status registers access diff --git a/src/modules/ESP8266/ESP8266.cpp b/src/modules/ESP8266/ESP8266.cpp index ab50f640..98d8c8d5 100644 --- a/src/modules/ESP8266/ESP8266.cpp +++ b/src/modules/ESP8266/ESP8266.cpp @@ -1,5 +1,5 @@ -#ifndef ESP8266 #include "ESP8266.h" +#if !defined(RADIOLIB_EXCLUDE_ESP8266) && !defined(ESP8266) ESP8266::ESP8266(Module* module) { _mod = module; @@ -7,7 +7,8 @@ ESP8266::ESP8266(Module* module) { int16_t ESP8266::begin(long speed) { // set module properties - _mod->AtLineFeed = "\r\n"; + char lf[3] = "\r\n"; + memcpy(_mod->AtLineFeed, lf, strlen(lf)); _mod->baudrate = speed; _mod->init(RADIOLIB_USE_UART); @@ -83,19 +84,19 @@ int16_t ESP8266::join(const char* ssid, const char* password) { int16_t ESP8266::openTransportConnection(const char* host, const char* protocol, uint16_t port, uint16_t tcpKeepAlive) { char portStr[6]; - itoa(port, portStr, 10); + sprintf(portStr, "%u", port); char tcpKeepAliveStr[6]; - itoa(tcpKeepAlive, tcpKeepAliveStr, 10); + sprintf(tcpKeepAliveStr, "%u", tcpKeepAlive); // build AT command const char* atStr = "AT+CIPSTART=\""; - uint8_t cmdLen = strlen(atStr) + strlen(protocol) + strlen(host) + strlen(portStr) + 5; - if((strcmp(protocol, "TCP") == 0) && (tcpKeepAlive > 0)) { - cmdLen += strlen(tcpKeepAliveStr) + 1; - } #ifdef RADIOLIB_STATIC_ONLY char cmd[RADIOLIB_STATIC_ARRAY_SIZE]; #else + uint8_t cmdLen = strlen(atStr) + strlen(protocol) + strlen(host) + strlen(portStr) + 5; + if((strcmp(protocol, "TCP") == 0) && (tcpKeepAlive > 0)) { + cmdLen += strlen(tcpKeepAliveStr) + 1; + } char* cmd = new char[cmdLen + 1]; #endif strcpy(cmd, atStr); @@ -131,8 +132,8 @@ int16_t ESP8266::closeTransportConnection() { int16_t ESP8266::send(const char* data) { // build AT command - char lenStr[8]; - itoa(strlen(data), lenStr, 10); + char lenStr[12]; + sprintf(lenStr, "%u", (uint16_t)strlen(data)); const char* atStr = "AT+CIPSEND="; #ifdef RADIOLIB_STATIC_ONLY char cmd[RADIOLIB_STATIC_ARRAY_SIZE]; @@ -159,10 +160,10 @@ int16_t ESP8266::send(const char* data) { return(ERR_NONE); } -int16_t ESP8266::send(uint8_t* data, uint32_t len) { +int16_t ESP8266::send(uint8_t* data, size_t len) { // build AT command char lenStr[8]; - itoa(len, lenStr, 10); + sprintf(lenStr, "%u", (uint16_t)len); const char atStr[] = "AT+CIPSEND="; #ifdef RADIOLIB_STATIC_ONLY char cmd[RADIOLIB_STATIC_ARRAY_SIZE]; @@ -195,6 +196,7 @@ size_t ESP8266::receive(uint8_t* data, size_t len, uint32_t timeout) { // wait until the required number of bytes is received or until timeout while((millis() - start < timeout) && (i < len)) { + yield(); while(_mod->ModuleSerial->available() > 0) { uint8_t b = _mod->ModuleSerial->read(); RADIOLIB_DEBUG_PRINT(b); @@ -209,6 +211,7 @@ size_t ESP8266::getNumBytes(uint32_t timeout, size_t minBytes) { // wait for available data uint32_t start = millis(); while(_mod->ModuleSerial->available() < (int16_t)minBytes) { + yield(); if(millis() - start >= timeout) { return(0); } @@ -219,6 +222,7 @@ size_t ESP8266::getNumBytes(uint32_t timeout, size_t minBytes) { uint8_t i = 0; start = millis(); while(_mod->ModuleSerial->available() > 0) { + yield(); char c = _mod->ModuleSerial->read(); rawStr[i++] = c; if(c == ':') { diff --git a/src/modules/ESP8266/ESP8266.h b/src/modules/ESP8266/ESP8266.h index aa4e145c..cc999500 100644 --- a/src/modules/ESP8266/ESP8266.h +++ b/src/modules/ESP8266/ESP8266.h @@ -1,6 +1,7 @@ -#if !defined(_RADIOLIB_ESP8266_H) && !defined(ESP8266) +#if !defined(_RADIOLIB_ESP8266_H) && !defined(RADIOLIB_EXCLUDE_ESP8266) && !defined(ESP8266) #define _RADIOLIB_ESP8266_H +#include "../../TypeDef.h" #include "../../Module.h" #include "../../protocols/TransportLayer/TransportLayer.h" @@ -46,13 +47,13 @@ class ESP8266: public TransportLayer { */ int16_t join(const char* ssid, const char* password); - // transport layer methods (implementations of purely virtual methods in TransportMethod class) - int16_t openTransportConnection(const char* host, const char* protocol, uint16_t port, uint16_t tcpKeepAlive = 0); - int16_t closeTransportConnection(); - int16_t send(const char* data); - int16_t send(uint8_t* data, uint32_t len); - size_t receive(uint8_t* data, size_t len, uint32_t timeout = 10000); - size_t getNumBytes(uint32_t timeout = 10000, size_t minBytes = 10); + // transport layer methods (implementations of purely virtual methods in TransportLayer class) + int16_t openTransportConnection(const char* host, const char* protocol, uint16_t port, uint16_t tcpKeepAlive = 0) override; + int16_t closeTransportConnection() override; + int16_t send(const char* data) override; + int16_t send(uint8_t* data, size_t len) override; + size_t receive(uint8_t* data, size_t len, uint32_t timeout = 10000) override; + size_t getNumBytes(uint32_t timeout = 10000, size_t minBytes = 10) override; #ifndef RADIOLIB_GODMODE private: diff --git a/src/modules/HC05/HC05.cpp b/src/modules/HC05/HC05.cpp index 2aecab76..7a35ce71 100644 --- a/src/modules/HC05/HC05.cpp +++ b/src/modules/HC05/HC05.cpp @@ -1,4 +1,5 @@ #include "HC05.h" +#if !defined(RADIOLIB_EXCLUDE_HC05) HC05::HC05(Module* mod) : ISerial(mod) { @@ -9,3 +10,5 @@ void HC05::begin(long speed) { _mod->baudrate = speed; _mod->init(RADIOLIB_USE_UART); } + +#endif diff --git a/src/modules/HC05/HC05.h b/src/modules/HC05/HC05.h index 2bfacb48..7721a50a 100644 --- a/src/modules/HC05/HC05.h +++ b/src/modules/HC05/HC05.h @@ -1,4 +1,4 @@ -#ifndef _RADIOLIB_HC05_H +#if !defined(_RADIOLIB_HC05_H) && !defined(RADIOLIB_EXCLUDE_HC05) #define _RADIOLIB_HC05_H #include "../../ISerial.h" diff --git a/src/modules/JDY08/JDY08.cpp b/src/modules/JDY08/JDY08.cpp index 78bc596b..0179a142 100644 --- a/src/modules/JDY08/JDY08.cpp +++ b/src/modules/JDY08/JDY08.cpp @@ -1,3 +1,4 @@ +#if !defined(_RADIOLIB_JDY08_H) && !defined(RADIOLIB_EXCLUDE_JDY08) #include "JDY08.h" JDY08::JDY08(Module* mod) : ISerial(mod) { @@ -6,7 +7,10 @@ JDY08::JDY08(Module* mod) : ISerial(mod) { void JDY08::begin(long speed) { // set module properties - _mod->AtLineFeed = ""; + char lf[3] = ""; + memcpy(_mod->AtLineFeed, lf, strlen(lf)); _mod->baudrate = speed; _mod->init(RADIOLIB_USE_UART); } + +#endif diff --git a/src/modules/JDY08/JDY08.h b/src/modules/JDY08/JDY08.h index be01ef19..7bb64011 100644 --- a/src/modules/JDY08/JDY08.h +++ b/src/modules/JDY08/JDY08.h @@ -1,4 +1,4 @@ -#ifndef _RADIOLIB_JDY08_H +#if !defined(_RADIOLIB_JDY08_H) && !defined(RADIOLIB_EXCLUDE_JDY08) #define _RADIOLIB_JDY08_H #include "../../ISerial.h" diff --git a/src/modules/RF69/RF69.cpp b/src/modules/RF69/RF69.cpp index b652a5fd..ddffc532 100644 --- a/src/modules/RF69/RF69.cpp +++ b/src/modules/RF69/RF69.cpp @@ -1,18 +1,11 @@ #include "RF69.h" +#if !defined(RADIOLIB_EXCLUDE_RF69) RF69::RF69(Module* module) : PhysicalLayer(RF69_FREQUENCY_STEP_SIZE, RF69_MAX_PACKET_LENGTH) { _mod = module; - _tempOffset = 0; - - _packetLengthQueried = false; - _packetLengthConfig = RF69_PACKET_FORMAT_VARIABLE; - - _promiscuous = false; - - _syncWordLength = 2; } -int16_t RF69::begin(float freq, float br, float freqDev, float rxBw, int8_t power) { +int16_t RF69::begin(float freq, float br, float freqDev, float rxBw, int8_t power, uint8_t preambleLen) { // set module properties _mod->init(RADIOLIB_USE_SPI); Module::pinMode(_mod->getIrq(), INPUT); @@ -40,14 +33,14 @@ int16_t RF69::begin(float freq, float br, float freqDev, float rxBw, int8_t powe RADIOLIB_DEBUG_PRINT(F(", expected 0x0024")); RADIOLIB_DEBUG_PRINTLN(); #endif - delay(1000); + delay(10); i++; } } if(!flagFound) { RADIOLIB_DEBUG_PRINTLN(F("No RF69 found!")); - _mod->term(); + _mod->term(RADIOLIB_USE_SPI); return(ERR_CHIP_NOT_FOUND); } else { RADIOLIB_DEBUG_PRINTLN(F("Found RF69! (match by RF69_REG_VERSION == 0x24)")); @@ -78,30 +71,38 @@ int16_t RF69::begin(float freq, float br, float freqDev, float rxBw, int8_t powe state = setOutputPower(power); RADIOLIB_ASSERT(state); + // configure default preamble length + state = setPreambleLength(preambleLen); + RADIOLIB_ASSERT(state); + // set default packet length mode state = variablePacketLengthMode(); RADIOLIB_ASSERT(state); - // default sync word values 0x2D01 is the same as the default in LowPowerLab RFM69 library - uint8_t syncWord[] = {0x2D, 0x01}; + // set default sync word + uint8_t syncWord[] = {0x12, 0xAD}; state = setSyncWord(syncWord, sizeof(syncWord)); RADIOLIB_ASSERT(state); // set default data shaping - state = setDataShaping(0); + state = setDataShaping(RADIOLIB_SHAPING_NONE); RADIOLIB_ASSERT(state); // set default encoding - state = setEncoding(0); + state = setEncoding(RADIOLIB_ENCODING_NRZ); RADIOLIB_ASSERT(state); - return(ERR_NONE); + // set CRC on by default + state = setCrcFiltering(true); + RADIOLIB_ASSERT(state); + + return(state); } void RF69::reset() { Module::pinMode(_mod->getRst(), OUTPUT); Module::digitalWrite(_mod->getRst(), HIGH); - delayMicroseconds(100); + delay(1); Module::digitalWrite(_mod->getRst(), LOW); delay(10); } @@ -117,6 +118,8 @@ int16_t RF69::transmit(uint8_t* data, size_t len, uint8_t addr) { // wait for transmission end or timeout uint32_t start = micros(); while(!digitalRead(_mod->getIrq())) { + yield(); + if(micros() - start > timeout) { standby(); clearIRQFlags(); @@ -144,6 +147,8 @@ int16_t RF69::receive(uint8_t* data, size_t len) { // wait for packet reception or timeout uint32_t start = micros(); while(!digitalRead(_mod->getIrq())) { + yield(); + if(micros() - start > timeout) { standby(); clearIRQFlags(); @@ -156,16 +161,25 @@ int16_t RF69::receive(uint8_t* data, size_t len) { } int16_t RF69::sleep() { + // set RF switch (if present) + _mod->setRfSwitchState(LOW, LOW); + // set module to sleep return(setMode(RF69_SLEEP)); } int16_t RF69::standby() { + // set RF switch (if present) + _mod->setRfSwitchState(LOW, LOW); + // set module to standby return(setMode(RF69_STANDBY)); } int16_t RF69::transmitDirect(uint32_t frf) { + // set RF switch (if present) + _mod->setRfSwitchState(LOW, HIGH); + // user requested to start transmitting immediately (required for RTTY) if(frf != 0) { _mod->SPIwriteRegister(RF69_REG_FRF_MSB, (frf & 0xFF0000) >> 16); @@ -184,6 +198,9 @@ int16_t RF69::transmitDirect(uint32_t frf) { } int16_t RF69::receiveDirect() { + // set RF switch (if present) + _mod->setRfSwitchState(HIGH, LOW); + // activate direct mode int16_t state = directMode(); RADIOLIB_ASSERT(state); @@ -224,6 +241,7 @@ int16_t RF69::disableAES() { int16_t RF69::startReceive() { // set mode to standby int16_t state = setMode(RF69_STANDBY); + RADIOLIB_ASSERT(state); // set RX timeouts and DIO pin mapping state = _mod->SPIsetRegValue(RF69_REG_DIO_MAPPING_1, RF69_DIO0_PACK_PAYLOAD_READY, 7, 4); @@ -234,35 +252,41 @@ int16_t RF69::startReceive() { // clear interrupt flags clearIRQFlags(); + // set RF switch (if present) + _mod->setRfSwitchState(HIGH, LOW); + // set mode to receive - state = _mod->SPIsetRegValue(RF69_REG_TEST_PA1, RF69_PA1_NORMAL); + state = _mod->SPIsetRegValue(RF69_REG_OCP, RF69_OCP_ON | RF69_OCP_TRIM); + state |= _mod->SPIsetRegValue(RF69_REG_TEST_PA1, RF69_PA1_NORMAL); state |= _mod->SPIsetRegValue(RF69_REG_TEST_PA2, RF69_PA2_NORMAL); - state |= setMode(RF69_RX); + RADIOLIB_ASSERT(state); + + state = setMode(RF69_RX); return(state); } void RF69::setDio0Action(void (*func)(void)) { - attachInterrupt(digitalPinToInterrupt(_mod->getIrq()), func, RISING); + attachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getIrq()), func, RISING); } void RF69::clearDio0Action() { - detachInterrupt(digitalPinToInterrupt(_mod->getIrq())); + detachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getIrq())); } void RF69::setDio1Action(void (*func)(void)) { - if(_mod->getGpio() != NC) { + if(_mod->getGpio() != RADIOLIB_NC) { return; } Module::pinMode(_mod->getGpio(), INPUT); - attachInterrupt(digitalPinToInterrupt(_mod->getGpio()), func, RISING); + attachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getGpio()), func, RISING); } void RF69::clearDio1Action() { - if(_mod->getGpio() != NC) { + if(_mod->getGpio() != RADIOLIB_NC) { return; } - detachInterrupt(digitalPinToInterrupt(_mod->getGpio())); + detachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getGpio())); } int16_t RF69::startTransmit(uint8_t* data, size_t len, uint8_t addr) { @@ -299,18 +323,28 @@ int16_t RF69::startTransmit(uint8_t* data, size_t len, uint8_t addr) { // write packet to FIFO _mod->SPIwriteRegisterBurst(RF69_REG_FIFO, data, len); + // enable +20 dBm operation + if(_power > 17) { + state = _mod->SPIsetRegValue(RF69_REG_OCP, RF69_OCP_OFF | 0x0F); + state |= _mod->SPIsetRegValue(RF69_REG_TEST_PA1, RF69_PA1_20_DBM); + state |= _mod->SPIsetRegValue(RF69_REG_TEST_PA2, RF69_PA2_20_DBM); + RADIOLIB_ASSERT(state); + } + + // set RF switch (if present) + _mod->setRfSwitchState(LOW, HIGH); + // set mode to transmit - state = _mod->SPIsetRegValue(RF69_REG_TEST_PA1, RF69_PA1_20_DBM); - state |= _mod->SPIsetRegValue(RF69_REG_TEST_PA2, RF69_PA2_20_DBM); - state |= setMode(RF69_TX); + state = setMode(RF69_TX); return(state); } int16_t RF69::readData(uint8_t* data, size_t len) { - // set mdoe to standby + // set mode to standby int16_t state = standby(); RADIOLIB_ASSERT(state); + // get packet length size_t length = len; if(len == RF69_MAX_PACKET_LENGTH) { @@ -326,9 +360,6 @@ int16_t RF69::readData(uint8_t* data, size_t len) { // read packet data _mod->SPIreadRegisterBurst(RF69_REG_FIFO, length, data); - // update RSSI - lastPacketRSSI = -1.0 * (_mod->SPIgetRegValue(RF69_REG_RSSI_VALUE)/2.0); - // clear internal flag so getPacketLength can return the new packet length _packetLengthQueried = false; @@ -359,10 +390,7 @@ int16_t RF69::setFrequency(float freq) { } int16_t RF69::setBitRate(float br) { - // check allowed bitrate - if((br < 1.2) || (br > 300.0)) { - return(ERR_INVALID_BIT_RATE); - } + RADIOLIB_CHECK_RANGE(br, 1.2, 300.0, ERR_INVALID_BIT_RATE); // check bitrate-bandwidth ratio if(!(br < 2000 * _rxBw)) { @@ -495,10 +523,11 @@ int16_t RF69::setFrequencyDeviation(float freqDev) { return(state); } -int16_t RF69::setOutputPower(int8_t power) { - // check output power range - if((power < -18) || (power > 17)) { - return(ERR_INVALID_OUTPUT_POWER); +int16_t RF69::setOutputPower(int8_t power, bool highPower) { + if(highPower) { + RADIOLIB_CHECK_RANGE(power, -2, 20, ERR_INVALID_OUTPUT_POWER); + } else { + RADIOLIB_CHECK_RANGE(power, -18, 13, ERR_INVALID_OUTPUT_POWER); } // set mode to standby @@ -506,14 +535,29 @@ int16_t RF69::setOutputPower(int8_t power) { // set output power int16_t state; - if(power > 13) { - // requested output power is higher than 13 dBm, enable PA2 + PA1 on PA_BOOST - state = _mod->SPIsetRegValue(RF69_REG_PA_LEVEL, RF69_PA0_OFF | RF69_PA1_ON | RF69_PA2_ON | (power + 14), 7, 0); + if(highPower) { + // check if both PA1 and PA2 are needed + if(power <= 10) { + // -2 to 13 dBm, PA1 is enough + state = _mod->SPIsetRegValue(RF69_REG_PA_LEVEL, RF69_PA0_OFF | RF69_PA1_ON | RF69_PA2_OFF | (power + 18), 7, 0); + } else if(power <= 17) { + // 13 to 17 dBm, both PAs required + state = _mod->SPIsetRegValue(RF69_REG_PA_LEVEL, RF69_PA0_OFF | RF69_PA1_ON | RF69_PA2_ON | (power + 14), 7, 0); + } else { + // 18 - 20 dBm, both PAs and hig power settings required + state = _mod->SPIsetRegValue(RF69_REG_PA_LEVEL, RF69_PA0_OFF | RF69_PA1_ON | RF69_PA2_ON | (power + 11), 7, 0); + } + } else { - // requested output power is lower than 13 dBm, enable PA0 on RFIO + // low power module, use only PA0 state = _mod->SPIsetRegValue(RF69_REG_PA_LEVEL, RF69_PA0_ON | RF69_PA1_OFF | RF69_PA2_OFF | (power + 18), 7, 0); } + // cache the power value + if(state == ERR_NONE) { + _power = power; + } + return(state); } @@ -540,6 +584,17 @@ int16_t RF69::setSyncWord(uint8_t* syncWord, size_t len, uint8_t maxErrBits) { return(ERR_NONE); } +int16_t RF69::setPreambleLength(uint8_t preambleLen) { + // RF69 configures preamble length in bytes + if(preambleLen % 8 != 0) { + return(ERR_INVALID_PREAMBLE_LENGTH); + } + + uint8_t preLenBytes = preambleLen / 8; + _mod->SPIwriteRegister(RF69_REG_PREAMBLE_MSB, 0x00); + return(_mod->SPIsetRegValue(RF69_REG_PREAMBLE_LSB, preLenBytes)); +} + int16_t RF69::setNodeAddress(uint8_t nodeAddr) { // enable address filtering (node only) int16_t state = _mod->SPIsetRegValue(RF69_REG_PACKET_CONFIG_1, RF69_ADDRESS_FILTERING_NODE, 2, 1); @@ -664,25 +719,24 @@ int16_t RF69::setPromiscuousMode(bool promiscuous) { return(state); } -int16_t RF69::setDataShaping(float sh) { +int16_t RF69::setDataShaping(uint8_t sh) { // set mode to standby int16_t state = standby(); RADIOLIB_ASSERT(state); // set data shaping - sh *= 10.0; - if(abs(sh - 0.0) <= 0.001) { - state = _mod->SPIsetRegValue(RF69_REG_DATA_MODUL, RF69_NO_SHAPING, 1, 0); - } else if(abs(sh - 3.0) <= 0.001) { - state = _mod->SPIsetRegValue(RF69_REG_DATA_MODUL, RF69_FSK_GAUSSIAN_0_3, 1, 0); - } else if(abs(sh - 5.0) <= 0.001) { - state = _mod->SPIsetRegValue(RF69_REG_DATA_MODUL, RF69_FSK_GAUSSIAN_0_5, 1, 0); - } else if(abs(sh - 10.0) <= 0.001) { - state = _mod->SPIsetRegValue(RF69_REG_DATA_MODUL, RF69_FSK_GAUSSIAN_1_0, 1, 0); - } else { - return(ERR_INVALID_DATA_SHAPING); + switch(sh) { + case RADIOLIB_SHAPING_NONE: + return(_mod->SPIsetRegValue(RF69_REG_DATA_MODUL, RF69_NO_SHAPING, 1, 0)); + case RADIOLIB_SHAPING_0_3: + return(_mod->SPIsetRegValue(RF69_REG_DATA_MODUL, RF69_FSK_GAUSSIAN_0_3, 1, 0)); + case RADIOLIB_SHAPING_0_5: + return(_mod->SPIsetRegValue(RF69_REG_DATA_MODUL, RF69_FSK_GAUSSIAN_0_5, 1, 0)); + case RADIOLIB_SHAPING_1_0: + return(_mod->SPIsetRegValue(RF69_REG_DATA_MODUL, RF69_FSK_GAUSSIAN_1_0, 1, 0)); + default: + return(ERR_INVALID_DATA_SHAPING); } - return(state); } int16_t RF69::setEncoding(uint8_t encoding) { @@ -692,17 +746,25 @@ int16_t RF69::setEncoding(uint8_t encoding) { // set encoding switch(encoding) { - case 0: + case RADIOLIB_ENCODING_NRZ: return(_mod->SPIsetRegValue(RF69_REG_PACKET_CONFIG_1, RF69_DC_FREE_NONE, 6, 5)); - case 1: + case RADIOLIB_ENCODING_MANCHESTER: return(_mod->SPIsetRegValue(RF69_REG_PACKET_CONFIG_1, RF69_DC_FREE_MANCHESTER, 6, 5)); - case 2: + case RADIOLIB_ENCODING_WHITENING: return(_mod->SPIsetRegValue(RF69_REG_PACKET_CONFIG_1, RF69_DC_FREE_WHITENING, 6, 5)); default: return(ERR_INVALID_ENCODING); } } +float RF69::getRSSI() { + return(-1.0 * (_mod->SPIgetRegValue(RF69_REG_RSSI_VALUE)/2.0)); +} + +void RF69::setRfSwitchPins(RADIOLIB_PIN_TYPE rxEn, RADIOLIB_PIN_TYPE txEn) { + _mod->setRfSwitchPins(rxEn, txEn); +} + int16_t RF69::config() { int16_t state = ERR_NONE; @@ -750,13 +812,13 @@ int16_t RF69::config() { // set Rx timeouts state = _mod->SPIsetRegValue(RF69_REG_RX_TIMEOUT_1, RF69_TIMEOUT_RX_START, 7, 0); - state = _mod->SPIsetRegValue(RF69_REG_RX_TIMEOUT_2, RF69_TIMEOUT_RSSI_THRESH, 7, 0); + state |= _mod->SPIsetRegValue(RF69_REG_RX_TIMEOUT_2, RF69_TIMEOUT_RSSI_THRESH, 7, 0); RADIOLIB_ASSERT(state); // enable improved fading margin state = _mod->SPIsetRegValue(RF69_REG_TEST_DAGC, RF69_CONTINUOUS_DAGC_LOW_BETA_OFF, 7, 0); - return(ERR_NONE); + return(state); } int16_t RF69::setPacketMode(uint8_t mode, uint8_t len) { @@ -786,3 +848,5 @@ void RF69::clearIRQFlags() { _mod->SPIwriteRegister(RF69_REG_IRQ_FLAGS_1, 0b11111111); _mod->SPIwriteRegister(RF69_REG_IRQ_FLAGS_2, 0b11111111); } + +#endif diff --git a/src/modules/RF69/RF69.h b/src/modules/RF69/RF69.h index 6c5333fe..63b63513 100644 --- a/src/modules/RF69/RF69.h +++ b/src/modules/RF69/RF69.h @@ -1,7 +1,10 @@ -#ifndef _RADIOLIB_RF69_H +#if !defined(_RADIOLIB_RF69_H) #define _RADIOLIB_RF69_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_RF69) + #include "../../Module.h" #include "../../protocols/PhysicalLayer/PhysicalLayer.h" @@ -144,7 +147,7 @@ #define RF69_LISTEN_RES_IDLE_64_US 0b01000000 // 7 6 resolution of Listen mode idle time: 64 us #define RF69_LISTEN_RES_IDLE_4_1_MS 0b10000000 // 7 6 4.1 ms (default) #define RF69_LISTEN_RES_IDLE_262_MS 0b11000000 // 7 6 262 ms -#define RF69_LISTEN_RES_RX_64_US 0b00010000 // 5 4 resolution of Listen mode ry time: 64 us (default) +#define RF69_LISTEN_RES_RX_64_US 0b00010000 // 5 4 resolution of Listen mode rx time: 64 us (default) #define RF69_LISTEN_RES_RX_4_1_MS 0b00100000 // 5 4 4.1 ms #define RF69_LISTEN_RES_RX_262_MS 0b00110000 // 5 4 262 ms #define RF69_LISTEN_ACCEPT_ABOVE_RSSI_THRESH 0b00000000 // 3 3 packet acceptance criteria: RSSI above threshold @@ -188,7 +191,7 @@ // RF69_REG_OCP #define RF69_OCP_OFF 0b00000000 // 4 4 PA overload current protection disabled -#define RF69_OCP_ON 0b00100000 // 4 4 PA overload current protection enabled +#define RF69_OCP_ON 0b00010000 // 4 4 PA overload current protection enabled #define RF69_OCP_TRIM 0b00001010 // 3 0 OCP current: I_max(OCP_TRIM = 0b1010) = 95 mA // RF69_REG_LNA @@ -305,7 +308,7 @@ #define RF69_IRQ_TX_READY 0b00100000 // 5 5 Tx mode ready #define RF69_IRQ_PLL_LOCK 0b00010000 // 4 4 PLL is locked #define RF69_IRQ_RSSI 0b00001000 // 3 3 RSSI value exceeded RssiThreshold -#define RF69_IRQ_TIMEOUT 0b00000100 // 2 2 timeout occured +#define RF69_IRQ_TIMEOUT 0b00000100 // 2 2 timeout occurred #define RF69_IRQ_AUTO_MODE 0b00000010 // 1 1 entered intermediate mode #define RF69_SYNC_ADDRESS_MATCH 0b00000001 // 0 0 sync address detected @@ -313,7 +316,7 @@ #define RF69_IRQ_FIFO_FULL 0b10000000 // 7 7 FIFO is full #define RF69_IRQ_FIFO_NOT_EMPTY 0b01000000 // 6 6 FIFO contains at least 1 byte #define RF69_IRQ_FIFO_LEVEL 0b00100000 // 5 5 FIFO contains more than FifoThreshold bytes -#define RF69_IRQ_FIFO_OVERRUN 0b00010000 // 4 4 FIFO overrun occured +#define RF69_IRQ_FIFO_OVERRUN 0b00010000 // 4 4 FIFO overrun occurred #define RF69_IRQ_PACKET_SENT 0b00001000 // 3 3 packet was sent #define RF69_IRQ_PAYLOAD_READY 0b00000100 // 2 2 last payload byte received and CRC check passed #define RF69_IRQ_CRC_OK 0b00000010 // 1 1 CRC check passed @@ -441,11 +444,6 @@ class RF69: public PhysicalLayer { */ RF69(Module* module); - /*! - \brief RSSI value of the last received packet. - */ - float lastPacketRSSI; - // basic methods /*! @@ -459,11 +457,13 @@ class RF69: public PhysicalLayer { \param rxBw Receiver bandwidth in kHz. Defaults to 125.0 kHz. - \param power Output power in dBm. Defaults to 13 dBm. + \param power Output power in dBm. Defaults to 10 dBm. + + \param preambleLen Preamble Length in bits. Defaults to 16 bits. \returns \ref status_codes */ - int16_t begin(float freq = 434.0, float br = 48.0, float freqDev = 50.0, float rxBw = 125.0, int8_t power = 13); + int16_t begin(float freq = 434.0, float br = 48.0, float freqDev = 50.0, float rxBw = 125.0, int8_t power = 10, uint8_t preambleLen = 16); /*! \brief Reset method. Will reset the chip to the default state using RST pin. @@ -482,7 +482,7 @@ class RF69: public PhysicalLayer { \returns \ref status_codes */ - int16_t transmit(uint8_t* data, size_t len, uint8_t addr = 0); + int16_t transmit(uint8_t* data, size_t len, uint8_t addr = 0) override; /*! \brief Blocking binary receive method. @@ -494,7 +494,7 @@ class RF69: public PhysicalLayer { \returns \ref status_codes */ - int16_t receive(uint8_t* data, size_t len); + int16_t receive(uint8_t* data, size_t len) override; /*! \brief Sets the module to sleep mode. @@ -508,7 +508,7 @@ class RF69: public PhysicalLayer { \returns \ref status_codes */ - int16_t standby(); + int16_t standby() override; /*! \brief Starts direct mode transmission. @@ -517,14 +517,14 @@ class RF69: public PhysicalLayer { \returns \ref status_codes */ - int16_t transmitDirect(uint32_t frf = 0); + int16_t transmitDirect(uint32_t frf = 0) override; /*! \brief Starts direct mode reception. \returns \ref status_codes */ - int16_t receiveDirect(); + int16_t receiveDirect() override; /*! \brief Stops direct mode. It is required to call this method to switch from direct transmissions to packet-based transmissions. @@ -592,7 +592,7 @@ class RF69: public PhysicalLayer { \returns \ref status_codes */ - int16_t startTransmit(uint8_t* data, size_t len, uint8_t addr = 0); + int16_t startTransmit(uint8_t* data, size_t len, uint8_t addr = 0) override; /*! \brief Interrupt-driven receive method. GDO0 will be activated when full packet is received. @@ -610,7 +610,7 @@ class RF69: public PhysicalLayer { \returns \ref status_codes */ - int16_t readData(uint8_t* data, size_t len); + int16_t readData(uint8_t* data, size_t len) override; // configuration methods @@ -648,16 +648,18 @@ class RF69: public PhysicalLayer { \returns \ref status_codes */ - int16_t setFrequencyDeviation(float freqDev); + int16_t setFrequencyDeviation(float freqDev) override; /*! - \brief Sets output power. Allowed values are -30, -20, -15, -10, 0, 5, 7 or 10 dBm. + \brief Sets output power. Allowed values range from -18 to 13 dBm for low power modules (RF69C/CW) or -2 to 20 dBm (RF69H/HC/HCW). \param power Output power to be set in dBm. + \param highPower Set to true when using modules high power port (RF69H/HC/HCW). Defaults to false (models without high power port - RF69C/CW). + \returns \ref status_codes */ - int16_t setOutputPower(int8_t power); + int16_t setOutputPower(int8_t power, bool highPower = false); /*! \brief Sets sync word. Up to 8 bytes can be set as sync word. @@ -670,6 +672,15 @@ class RF69: public PhysicalLayer { */ int16_t setSyncWord(uint8_t* syncWord, size_t len, uint8_t maxErrBits = 0); + /*! + \brief Sets preamble length. + + \param preambleLen Preamble length to be set (in bits), allowed values: 16, 24, 32, 48, 64, 96, 128 and 192. + + \returns \ref status_codes + */ + int16_t setPreambleLength(uint8_t preambleLen); + /*! \brief Sets node address. Calling this method will also enable address filtering for node address only. @@ -718,7 +729,7 @@ class RF69: public PhysicalLayer { \returns Length of last received packet in bytes. */ - size_t getPacketLength(bool update = true); + size_t getPacketLength(bool update = true) override; /*! \brief Set modem in fixed packet length mode. @@ -774,39 +785,58 @@ class RF69: public PhysicalLayer { /*! \brief Sets Gaussian filter bandwidth-time product that will be used for data shaping. - Allowed values are 0.3, 0.5 or 1.0. Set to 0 to disable data shaping. + Allowed values are RADIOLIB_SHAPING_0_3, RADIOLIB_SHAPING_0_5 or RADIOLIB_SHAPING_1_0. Set to RADIOLIB_SHAPING_NONE to disable data shaping. \param sh Gaussian shaping bandwidth-time product that will be used for data shaping \returns \ref status_codes */ - int16_t setDataShaping(float sh); + int16_t setDataShaping(uint8_t sh) override; /*! \brief Sets transmission encoding. + Allowed values are RADIOLIB_ENCODING_NRZ, RADIOLIB_ENCODING_MANCHESTER and RADIOLIB_ENCODING_WHITENING. - \param encoding Encoding to be used. Set to 0 for NRZ, 1 for Manchester and 2 for whitening. + \param encoding Encoding to be used. \returns \ref status_codes */ - int16_t setEncoding(uint8_t encoding); + int16_t setEncoding(uint8_t encoding) override; + + /*! + \brief Gets RSSI (Recorded Signal Strength Indicator) of the last received packet. + + \returns Last packet RSSI in dBm. + */ + float getRSSI(); + + /*! + \brief Some modules contain external RF switch controlled by two pins. This function gives RadioLib control over those two pins to automatically switch Rx and Tx state. + When using automatic RF switch control, DO NOT change the pin mode of rxEn or txEn from Arduino sketch! + + \param rxEn RX enable pin. + + \param txEn TX enable pin. + */ + void setRfSwitchPins(RADIOLIB_PIN_TYPE rxEn, RADIOLIB_PIN_TYPE txEn); #ifndef RADIOLIB_GODMODE protected: #endif Module* _mod; - float _br; - float _rxBw; - int16_t _tempOffset; + float _br = 0; + float _rxBw = 0; + int16_t _tempOffset = 0; + int8_t _power = 0; - size_t _packetLength; - bool _packetLengthQueried; - uint8_t _packetLengthConfig; + size_t _packetLength = 0; + bool _packetLengthQueried = false; + uint8_t _packetLengthConfig = RF69_PACKET_FORMAT_VARIABLE; - bool _promiscuous; + bool _promiscuous = false; - uint8_t _syncWordLength; + uint8_t _syncWordLength = 2; int16_t config(); int16_t directMode(); @@ -820,3 +850,5 @@ class RF69: public PhysicalLayer { }; #endif + +#endif diff --git a/src/modules/RFM2x/RFM22.h b/src/modules/RFM2x/RFM22.h new file mode 100644 index 00000000..3204c7ca --- /dev/null +++ b/src/modules/RFM2x/RFM22.h @@ -0,0 +1,21 @@ +#if !defined(_RADIOLIB_RFM22_H) +#define _RADIOLIB_RFM22_H + +#include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_RFM2X) + +#include "../../Module.h" +#include "../Si443x/Si443x.h" +#include "../Si443x/Si4432.h" + +/*! + \class RFM22 + + \brief Only exists as alias for Si4432, since there seems to be no difference between %RFM22 and %Si4432 modules. +*/ +using RFM22 = Si4432; + +#endif + +#endif diff --git a/src/modules/RFM2x/RFM23.h b/src/modules/RFM2x/RFM23.h new file mode 100644 index 00000000..45a708a2 --- /dev/null +++ b/src/modules/RFM2x/RFM23.h @@ -0,0 +1,21 @@ +#if !defined(_RADIOLIB_RFM23_H) +#define _RADIOLIB_RFM23_H + +#include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_RFM2X) + +#include "../../Module.h" +#include "../Si443x/Si443x.h" +#include "../Si443x/Si4431.h" + +/*! + \class RFM23 + + \brief Only exists as alias for Si4431, since there seems to be no difference between %RFM23 and %Si4431 modules. +*/ +using RFM23 = Si4431; + +#endif + +#endif diff --git a/src/modules/RFM9x/RFM95.cpp b/src/modules/RFM9x/RFM95.cpp index 72df63c4..f2b4a302 100644 --- a/src/modules/RFM9x/RFM95.cpp +++ b/src/modules/RFM9x/RFM95.cpp @@ -1,13 +1,21 @@ #include "RFM95.h" +#if !defined(RADIOLIB_EXCLUDE_RFM9X) RFM95::RFM95(Module* mod) : SX1278(mod) { } -int16_t RFM95::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint8_t currentLimit, uint16_t preambleLength, uint8_t gain) { +int16_t RFM95::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint16_t preambleLength, uint8_t gain) { // execute common part - int16_t state = SX127x::begin(RFM95_CHIP_VERSION, syncWord, currentLimit, preambleLength); - RADIOLIB_ASSERT(state); + int16_t state = SX127x::begin(RFM9X_CHIP_VERSION_OFFICIAL, syncWord, preambleLength); + if(state == ERR_CHIP_NOT_FOUND) { + // SX127X_REG_VERSION might be set 0x12 + state = SX127x::begin(RFM9X_CHIP_VERSION_UNOFFICIAL, syncWord, preambleLength); + RADIOLIB_ASSERT(state); + } else if(state != ERR_NONE) { + // some other error + return(state); + } // configure settings not accessible by API state = config(); @@ -35,11 +43,10 @@ int16_t RFM95::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncW } int16_t RFM95::setFrequency(float freq) { - // check frequency range - if((freq < 868.0) || (freq > 915.0)) { - return(ERR_INVALID_FREQUENCY); - } + RADIOLIB_CHECK_RANGE(freq, 862.0, 1020.0, ERR_INVALID_FREQUENCY); // set frequency return(SX127x::setFrequencyRaw(freq)); } + +#endif diff --git a/src/modules/RFM9x/RFM95.h b/src/modules/RFM9x/RFM95.h index 78758971..f6c02840 100644 --- a/src/modules/RFM9x/RFM95.h +++ b/src/modules/RFM9x/RFM95.h @@ -1,13 +1,17 @@ -#ifndef _RADIOLIB_RFM95_H +#if !defined(_RADIOLIB_RFM95_H) #define _RADIOLIB_RFM95_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_RFM9X) + #include "../../Module.h" #include "../SX127x/SX127x.h" #include "../SX127x/SX1278.h" // SX127X_REG_VERSION -#define RFM95_CHIP_VERSION 0x11 +#define RFM9X_CHIP_VERSION_OFFICIAL 0x11 +#define RFM9X_CHIP_VERSION_UNOFFICIAL 0x12 // according to datasheet, only 0x11 should be possible, but some modules seem to have 0x12 /*! \class RFM95 @@ -43,9 +47,6 @@ class RFM95: public SX1278 { \param power Transmission output power in dBm. Allowed values range from 2 to 17 dBm. - \param currentLimit Trim value for OCP (over current protection) in mA. Can be set to multiplies of 5 in range 45 to 120 mA and to multiples of 10 in range 120 to 240 mA. - Set to 0 to disable OCP (not recommended). - \param preambleLength Length of %LoRa transmission preamble in symbols. The actual preamble length is 4.25 symbols longer than the set number. Allowed values range from 6 to 65535. @@ -54,7 +55,7 @@ class RFM95: public SX1278 { \returns \ref status_codes */ - int16_t begin(float freq = 915.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX127X_SYNC_WORD, int8_t power = 17, uint8_t currentLimit = 100, uint16_t preambleLength = 8, uint8_t gain = 0); + int16_t begin(float freq = 915.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX127X_SYNC_WORD, int8_t power = 10, uint16_t preambleLength = 8, uint8_t gain = 0); // configuration methods @@ -74,3 +75,5 @@ class RFM95: public SX1278 { }; #endif + +#endif diff --git a/src/modules/RFM9x/RFM96.cpp b/src/modules/RFM9x/RFM96.cpp index 1e045536..c2f43f0e 100644 --- a/src/modules/RFM9x/RFM96.cpp +++ b/src/modules/RFM9x/RFM96.cpp @@ -1,13 +1,21 @@ #include "RFM96.h" +#if !defined(RADIOLIB_EXCLUDE_RFM9X) RFM96::RFM96(Module* mod) : SX1278(mod) { } -int16_t RFM96::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint8_t currentLimit, uint16_t preambleLength, uint8_t gain) { +int16_t RFM96::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint16_t preambleLength, uint8_t gain) { // execute common part - int16_t state = SX127x::begin(RFM9X_CHIP_VERSION, syncWord, currentLimit, preambleLength); - RADIOLIB_ASSERT(state); + int16_t state = SX127x::begin(RFM9X_CHIP_VERSION_OFFICIAL, syncWord, preambleLength); + if(state == ERR_CHIP_NOT_FOUND) { + // SX127X_REG_VERSION might be set 0x12 + state = SX127x::begin(RFM9X_CHIP_VERSION_UNOFFICIAL, syncWord, preambleLength); + RADIOLIB_ASSERT(state); + } else if(state != ERR_NONE) { + // some other error + return(state); + } // configure settings not accessible by API state = config(); @@ -30,16 +38,16 @@ int16_t RFM96::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncW RADIOLIB_ASSERT(state); state = setGain(gain); + RADIOLIB_ASSERT(state); return(state); } int16_t RFM96::setFrequency(float freq) { - // check frequency range - if((freq < 433.0) || (freq > 470.0)) { - return(ERR_INVALID_FREQUENCY); - } + RADIOLIB_CHECK_RANGE(freq, 410.0, 525.0, ERR_INVALID_FREQUENCY); // set frequency return(SX127x::setFrequencyRaw(freq)); } + +#endif diff --git a/src/modules/RFM9x/RFM96.h b/src/modules/RFM9x/RFM96.h index 1288c797..c18019b2 100644 --- a/src/modules/RFM9x/RFM96.h +++ b/src/modules/RFM9x/RFM96.h @@ -1,13 +1,17 @@ -#ifndef _RADIOLIB_RFM96_H +#if !defined(_RADIOLIB_RFM96_H) #define _RADIOLIB_RFM96_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_RFM9X) + #include "../../Module.h" #include "../SX127x/SX127x.h" #include "../SX127x/SX1278.h" // SX127X_REG_VERSION -#define RFM9X_CHIP_VERSION 0x12 // according to datasheet, this should be 0x11, but all modules seem to have 0x12 +#define RFM9X_CHIP_VERSION_OFFICIAL 0x11 +#define RFM9X_CHIP_VERSION_UNOFFICIAL 0x12 // according to datasheet, only 0x11 should be possible, but some modules seem to have 0x12 /*! \class RFM96 @@ -43,9 +47,6 @@ class RFM96: public SX1278 { \param power Transmission output power in dBm. Allowed values range from 2 to 17 dBm. - \param currentLimit Trim value for OCP (over current protection) in mA. Can be set to multiplies of 5 in range 45 to 120 mA and to multiples of 10 in range 120 to 240 mA. - Set to 0 to disable OCP (not recommended). - \param preambleLength Length of %LoRa transmission preamble in symbols. The actual preamble length is 4.25 symbols longer than the set number. Allowed values range from 6 to 65535. @@ -54,7 +55,7 @@ class RFM96: public SX1278 { \returns \ref status_codes */ - int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX127X_SYNC_WORD, int8_t power = 17, uint8_t currentLimit = 100, uint16_t preambleLength = 8, uint8_t gain = 0); + int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX127X_SYNC_WORD, int8_t power = 10, uint16_t preambleLength = 8, uint8_t gain = 0); // configuration methods @@ -81,3 +82,5 @@ class RFM96: public SX1278 { using RFM98 = RFM96; #endif + +#endif diff --git a/src/modules/RFM9x/RFM97.cpp b/src/modules/RFM9x/RFM97.cpp index 102fecf9..ccf19134 100644 --- a/src/modules/RFM9x/RFM97.cpp +++ b/src/modules/RFM9x/RFM97.cpp @@ -1,4 +1,5 @@ #include "RFM97.h" +#if !defined(RADIOLIB_EXCLUDE_RFM9X) RFM97::RFM97(Module* mod) : RFM95(mod) { @@ -37,3 +38,5 @@ int16_t RFM97::setSpreadingFactor(uint8_t sf) { } return(state); } + +#endif diff --git a/src/modules/RFM9x/RFM97.h b/src/modules/RFM9x/RFM97.h index b5dcbbdf..30454f91 100644 --- a/src/modules/RFM9x/RFM97.h +++ b/src/modules/RFM9x/RFM97.h @@ -1,7 +1,10 @@ -#ifndef _RADIOLIB_RFM97_H +#if !defined(_RADIOLIB_RFM97_H) #define _RADIOLIB_RFM97_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_RFM9X) + #include "../../Module.h" #include "../SX127x/SX127x.h" #include "../SX127x/SX1278.h" @@ -42,3 +45,5 @@ class RFM97: public RFM95 { }; #endif + +#endif diff --git a/src/modules/SX1231/SX1231.cpp b/src/modules/SX1231/SX1231.cpp index b7412bcb..3b4668e9 100644 --- a/src/modules/SX1231/SX1231.cpp +++ b/src/modules/SX1231/SX1231.cpp @@ -1,10 +1,11 @@ #include "SX1231.h" +#if !defined(RADIOLIB_EXCLUDE_SX1231) SX1231::SX1231(Module* mod) : RF69(mod) { } -int16_t SX1231::begin(float freq, float br, float rxBw, float freqDev, int8_t power) { +int16_t SX1231::begin(float freq, float br, float rxBw, float freqDev, int8_t power, uint8_t preambleLen) { // set module properties _mod->init(RADIOLIB_USE_SPI); Module::pinMode(_mod->getIrq(), INPUT); @@ -20,9 +21,9 @@ int16_t SX1231::begin(float freq, float br, float rxBw, float freqDev, int8_t po _chipRevision = version; } else { #ifdef RADIOLIB_DEBUG - RADIOLIB_DEBUG_PRINT(F("SX127x not found! (")); + RADIOLIB_DEBUG_PRINT(F("SX1231 not found! (")); RADIOLIB_DEBUG_PRINT(i + 1); - RADIOLIB_DEBUG_PRINT(F(" of 10 tries) SX127X_REG_VERSION == ")); + RADIOLIB_DEBUG_PRINT(F(" of 10 tries) RF69_REG_VERSION == ")); char buffHex[7]; sprintf(buffHex, "0x%04X", version); @@ -30,14 +31,14 @@ int16_t SX1231::begin(float freq, float br, float rxBw, float freqDev, int8_t po RADIOLIB_DEBUG_PRINT(F(", expected 0x0021 / 0x0022 / 0x0023")); RADIOLIB_DEBUG_PRINTLN(); #endif - delay(1000); + delay(10); i++; } } if(!flagFound) { RADIOLIB_DEBUG_PRINTLN(F("No SX1231 found!")); - _mod->term(); + _mod->term(RADIOLIB_USE_SPI); return(ERR_CHIP_NOT_FOUND); } else { RADIOLIB_DEBUG_PRINTLN(F("Found SX1231!")); @@ -68,6 +69,10 @@ int16_t SX1231::begin(float freq, float br, float rxBw, float freqDev, int8_t po state = setOutputPower(power); RADIOLIB_ASSERT(state); + // configure default preamble length + state = setPreambleLength(preambleLen); + RADIOLIB_ASSERT(state); + // default sync word values 0x2D01 is the same as the default in LowPowerLab RFM69 library uint8_t syncWord[] = {0x2D, 0x01}; state = setSyncWord(syncWord, 2); @@ -92,3 +97,5 @@ int16_t SX1231::begin(float freq, float br, float rxBw, float freqDev, int8_t po return(ERR_NONE); } + +#endif diff --git a/src/modules/SX1231/SX1231.h b/src/modules/SX1231/SX1231.h index d048fd02..08cea4d4 100644 --- a/src/modules/SX1231/SX1231.h +++ b/src/modules/SX1231/SX1231.h @@ -1,7 +1,10 @@ -#ifndef _RADIOLIB_SX1231_H +#if !defined(_RADIOLIB_SX1231_H) #define _RADIOLIB_SX1231_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SX1231) + #include "../../Module.h" #include "../RF69/RF69.h" @@ -40,16 +43,20 @@ class SX1231: public RF69 { \param freqDev Frequency deviation from carrier frequency in kHz Defaults to 50.0 kHz. - \param power Output power in dBm. Defaults to 13 dBm. + \param power Output power in dBm. Defaults to 10 dBm. + + \param preambleLen Preamble Length in bits. Defaults to 16 bits. \returns \ref status_codes */ - int16_t begin(float freq = 434.0, float br = 48.0, float rxBw = 125.0, float freqDev = 50.0, int8_t power = 13); + int16_t begin(float freq = 434.0, float br = 48.0, float rxBw = 125.0, float freqDev = 50.0, int8_t power = 10, uint8_t preambleLen = 16); #ifndef RADIOLIB_GODMODE private: #endif - uint8_t _chipRevision; + uint8_t _chipRevision = 0; }; #endif + +#endif diff --git a/src/modules/SX126x/SX1261.cpp b/src/modules/SX126x/SX1261.cpp index dcf34fac..1e035651 100644 --- a/src/modules/SX126x/SX1261.cpp +++ b/src/modules/SX126x/SX1261.cpp @@ -1,14 +1,12 @@ #include "SX1261.h" +#if !defined(RADIOLIB_EXCLUDE_SX126X) SX1261::SX1261(Module* mod): SX1262(mod) { } int16_t SX1261::setOutputPower(int8_t power) { - // check allowed power range - if (!((power >= -17) && (power <= 14))) { - return(ERR_INVALID_OUTPUT_POWER); - } + RADIOLIB_CHECK_RANGE(power, -17, 14, ERR_INVALID_OUTPUT_POWER); // get current OCP configuration uint8_t ocp = 0; @@ -20,10 +18,12 @@ int16_t SX1261::setOutputPower(int8_t power) { RADIOLIB_ASSERT(state); // set output power - // TODO power ramp time configuration + /// \todo power ramp time configuration state = SX126x::setTxParams(power); RADIOLIB_ASSERT(state); // restore OCP configuration return(writeRegister(SX126X_REG_OCP_CONFIGURATION, &ocp, 1)); } + +#endif diff --git a/src/modules/SX126x/SX1261.h b/src/modules/SX126x/SX1261.h index 2dca7ed1..a52d4235 100644 --- a/src/modules/SX126x/SX1261.h +++ b/src/modules/SX126x/SX1261.h @@ -1,7 +1,10 @@ -#ifndef _RADIOLIB_SX1261_H +#if !defined(_RADIOLIB_SX1261_H) #define _RADIOLIB_SX1261_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SX126X) + #include "../../Module.h" #include "SX126x.h" #include "SX1262.h" @@ -38,5 +41,6 @@ class SX1261 : public SX1262 { }; +#endif #endif diff --git a/src/modules/SX126x/SX1262.cpp b/src/modules/SX126x/SX1262.cpp index 3a9d211a..0d78eea5 100644 --- a/src/modules/SX126x/SX1262.cpp +++ b/src/modules/SX126x/SX1262.cpp @@ -1,12 +1,13 @@ #include "SX1262.h" +#if !defined(RADIOLIB_EXCLUDE_SX126X) SX1262::SX1262(Module* mod) : SX126x(mod) { } -int16_t SX1262::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, float currentLimit, uint16_t preambleLength, float tcxoVoltage, bool useRegulatorLDO) { +int16_t SX1262::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint16_t preambleLength, float tcxoVoltage, bool useRegulatorLDO) { // execute common part - int16_t state = SX126x::begin(bw, sf, cr, syncWord, currentLimit, preambleLength, tcxoVoltage, useRegulatorLDO); + int16_t state = SX126x::begin(bw, sf, cr, syncWord, preambleLength, tcxoVoltage, useRegulatorLDO); RADIOLIB_ASSERT(state); // configure publicly accessible settings @@ -17,13 +18,14 @@ int16_t SX1262::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t sync RADIOLIB_ASSERT(state); state = SX126x::fixPaClamping(); + RADIOLIB_ASSERT(state); return(state); } -int16_t SX1262::beginFSK(float freq, float br, float freqDev, float rxBw, int8_t power, float currentLimit, uint16_t preambleLength, float dataShaping, float tcxoVoltage, bool useRegulatorLDO) { +int16_t SX1262::beginFSK(float freq, float br, float freqDev, float rxBw, int8_t power, uint16_t preambleLength, float tcxoVoltage, bool useRegulatorLDO) { // execute common part - int16_t state = SX126x::beginFSK(br, freqDev, rxBw, currentLimit, preambleLength, dataShaping, tcxoVoltage, useRegulatorLDO); + int16_t state = SX126x::beginFSK(br, freqDev, rxBw, preambleLength, tcxoVoltage, useRegulatorLDO); RADIOLIB_ASSERT(state); // configure publicly accessible settings @@ -34,17 +36,13 @@ int16_t SX1262::beginFSK(float freq, float br, float freqDev, float rxBw, int8_t RADIOLIB_ASSERT(state); state = SX126x::fixPaClamping(); + RADIOLIB_ASSERT(state); return(state); } int16_t SX1262::setFrequency(float freq, bool calibrate) { - // check frequency range - if((freq < 150.0) || (freq > 960.0)) { - return(ERR_INVALID_FREQUENCY); - } - - int16_t state = ERR_NONE; + RADIOLIB_CHECK_RANGE(freq, 150.0, 960.0, ERR_INVALID_FREQUENCY); // calibrate image if(calibrate) { @@ -65,7 +63,7 @@ int16_t SX1262::setFrequency(float freq, bool calibrate) { data[0] = SX126X_CAL_IMG_430_MHZ_1; data[1] = SX126X_CAL_IMG_430_MHZ_2; } - state = SX126x::calibrateImage(data); + int16_t state = SX126x::calibrateImage(data); RADIOLIB_ASSERT(state); } @@ -74,10 +72,7 @@ int16_t SX1262::setFrequency(float freq, bool calibrate) { } int16_t SX1262::setOutputPower(int8_t power) { - // check allowed power range - if (!((power >= -17) && (power <= 22))) { - return(ERR_INVALID_OUTPUT_POWER); - } + RADIOLIB_CHECK_RANGE(power, -17, 22, ERR_INVALID_OUTPUT_POWER); // get current OCP configuration uint8_t ocp = 0; @@ -89,10 +84,12 @@ int16_t SX1262::setOutputPower(int8_t power) { RADIOLIB_ASSERT(state); // set output power - // TODO power ramp time configuration + /// \todo power ramp time configuration state = SX126x::setTxParams(power); RADIOLIB_ASSERT(state); // restore OCP configuration return(writeRegister(SX126X_REG_OCP_CONFIGURATION, &ocp, 1)); } + +#endif diff --git a/src/modules/SX126x/SX1262.h b/src/modules/SX126x/SX1262.h index e33f568b..616cd407 100644 --- a/src/modules/SX126x/SX1262.h +++ b/src/modules/SX126x/SX1262.h @@ -1,7 +1,10 @@ -#ifndef _RADIOLIB_SX1262_H +#if !defined(_RADIOLIB_SX1262_H) #define _RADIOLIB_SX1262_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SX126X) + #include "../../Module.h" #include "SX126x.h" @@ -37,17 +40,15 @@ class SX1262: public SX126x { \param syncWord 2-byte LoRa sync word. Defaults to SX126X_SYNC_WORD_PRIVATE (0x12). - \param power Output power in dBm. Defaults to 14 dBm. + \param power Output power in dBm. Defaults to 10 dBm. - \param currentLimit Current protection limit in mA. Defaults to 60.0 mA. - - \param preambleLength LoRa preamble length in symbols.Defaults to 8 symbols. + \param preambleLength LoRa preamble length in symbols. Defaults to 8 symbols. \param tcxoVoltage TCXO reference voltage to be set on DIO3. Defaults to 1.6 V, set to 0 to skip. \returns \ref status_codes */ - int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX126X_SYNC_WORD_PRIVATE, int8_t power = 14, float currentLimit = 60.0, uint16_t preambleLength = 8, float tcxoVoltage = 1.6, bool useRegulatorLDO = false); + int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX126X_SYNC_WORD_PRIVATE, int8_t power = 10, uint16_t preambleLength = 8, float tcxoVoltage = 1.6, bool useRegulatorLDO = false); /*! \brief Initialization method for FSK modem. @@ -60,19 +61,17 @@ class SX1262: public SX126x { \param rxBw Receiver bandwidth in kHz. Defaults to 156.2 kHz. - \param power Output power in dBm. Defaults to 14 dBm. - - \param currentLimit Current protection limit in mA. Defaults to 60.0 mA. + \param power Output power in dBm. Defaults to 10 dBm. \parma preambleLength FSK preamble length in bits. Defaults to 16 bits. - \param dataShaping Time-bandwidth product of the Gaussian filter to be used for shaping. Defaults to 0.5. - \param tcxoVoltage TCXO reference voltage to be set on DIO3. Defaults to 1.6 V, set to 0 to skip. + \param useRegulatorLDO Whether to use only LDO regulator (true) or DC-DC regulator (false). Defaults to false. + \returns \ref status_codes */ - int16_t beginFSK(float freq = 434.0, float br = 48.0, float freqDev = 50.0, float rxBw = 156.2, int8_t power = 14, float currentLimit = 60.0, uint16_t preambleLength = 16, float dataShaping = 0.5, float tcxoVoltage = 1.6, bool useRegulatorLDO = false); + int16_t beginFSK(float freq = 434.0, float br = 48.0, float freqDev = 50.0, float rxBw = 156.2, int8_t power = 10, uint16_t preambleLength = 16, float tcxoVoltage = 1.6, bool useRegulatorLDO = false); // configuration methods @@ -103,3 +102,5 @@ class SX1262: public SX126x { }; #endif + +#endif diff --git a/src/modules/SX126x/SX1268.cpp b/src/modules/SX126x/SX1268.cpp index b6daa489..0addddf8 100644 --- a/src/modules/SX126x/SX1268.cpp +++ b/src/modules/SX126x/SX1268.cpp @@ -1,12 +1,13 @@ #include "SX1268.h" +#if !defined(RADIOLIB_EXCLUDE_SX126X) SX1268::SX1268(Module* mod) : SX126x(mod) { } -int16_t SX1268::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, float currentLimit, uint16_t preambleLength, float tcxoVoltage, bool useRegulatorLDO) { +int16_t SX1268::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint16_t preambleLength, float tcxoVoltage, bool useRegulatorLDO) { // execute common part - int16_t state = SX126x::begin(bw, sf, cr, syncWord, currentLimit, preambleLength, tcxoVoltage, useRegulatorLDO); + int16_t state = SX126x::begin(bw, sf, cr, syncWord, preambleLength, tcxoVoltage, useRegulatorLDO); RADIOLIB_ASSERT(state); // configure publicly accessible settings @@ -17,12 +18,14 @@ int16_t SX1268::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t sync RADIOLIB_ASSERT(state); state = SX126x::fixPaClamping(); + RADIOLIB_ASSERT(state); return(state); } -int16_t SX1268::beginFSK(float freq, float br, float freqDev, float rxBw, int8_t power, float currentLimit, uint16_t preambleLength, float dataShaping, float tcxoVoltage, bool useRegulatorLDO) { + +int16_t SX1268::beginFSK(float freq, float br, float freqDev, float rxBw, int8_t power, uint16_t preambleLength, float tcxoVoltage, bool useRegulatorLDO) { // execute common part - int16_t state = SX126x::beginFSK(br, freqDev, rxBw, currentLimit, preambleLength, dataShaping, tcxoVoltage, useRegulatorLDO); + int16_t state = SX126x::beginFSK(br, freqDev, rxBw, preambleLength, tcxoVoltage, useRegulatorLDO); RADIOLIB_ASSERT(state); // configure publicly accessible settings @@ -33,17 +36,14 @@ int16_t SX1268::beginFSK(float freq, float br, float freqDev, float rxBw, int8_t RADIOLIB_ASSERT(state); state = SX126x::fixPaClamping(); + RADIOLIB_ASSERT(state); return(state); } +/// \todo integers only (all modules - frequency, data rate, bandwidth etc.) int16_t SX1268::setFrequency(float freq, bool calibrate) { - // check frequency range - if((freq < 410.0) || (freq > 810.0)) { - return(ERR_INVALID_FREQUENCY); - } - - int16_t state = ERR_NONE; + RADIOLIB_CHECK_RANGE(freq, 410.0, 810.0, ERR_INVALID_FREQUENCY); // calibrate image if(calibrate) { @@ -58,7 +58,7 @@ int16_t SX1268::setFrequency(float freq, bool calibrate) { data[0] = SX126X_CAL_IMG_430_MHZ_1; data[1] = SX126X_CAL_IMG_430_MHZ_2; } - state = SX126x::calibrateImage(data); + int16_t state = SX126x::calibrateImage(data); RADIOLIB_ASSERT(state); } @@ -67,10 +67,7 @@ int16_t SX1268::setFrequency(float freq, bool calibrate) { } int16_t SX1268::setOutputPower(int8_t power) { - // check allowed power range - if(!((power >= -9) && (power <= 22))) { - return(ERR_INVALID_OUTPUT_POWER); - } + RADIOLIB_CHECK_RANGE(power, -9, 22, ERR_INVALID_OUTPUT_POWER); // get current OCP configuration uint8_t ocp = 0; @@ -82,10 +79,12 @@ int16_t SX1268::setOutputPower(int8_t power) { RADIOLIB_ASSERT(state); // set output power - // TODO power ramp time configuration + /// \todo power ramp time configuration state = SX126x::setTxParams(power); RADIOLIB_ASSERT(state); // restore OCP configuration return(writeRegister(SX126X_REG_OCP_CONFIGURATION, &ocp, 1)); } + +#endif diff --git a/src/modules/SX126x/SX1268.h b/src/modules/SX126x/SX1268.h index 5b203b72..909dd334 100644 --- a/src/modules/SX126x/SX1268.h +++ b/src/modules/SX126x/SX1268.h @@ -1,7 +1,10 @@ -#ifndef _RADIOLIB_SX1268_H +#if !defined(_RADIOLIB_SX1268_H) #define _RADIOLIB_SX1268_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SX126X) + #include "../../Module.h" #include "SX126x.h" @@ -37,9 +40,7 @@ class SX1268: public SX126x { \param syncWord 2-byte LoRa sync word. Defaults to SX126X_SYNC_WORD_PRIVATE (0x12). - \param power Output power in dBm. Defaults to 14 dBm. - - \param currentLimit Current protection limit in mA. Defaults to 60.0 mA. + \param power Output power in dBm. Defaults to 10 dBm. \param preambleLength LoRa preamble length in symbols. Defaults to 8 symbols. @@ -47,7 +48,7 @@ class SX1268: public SX126x { \returns \ref status_codes */ - int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX126X_SYNC_WORD_PRIVATE, int8_t power = 14, float currentLimit = 60.0, uint16_t preambleLength = 8, float tcxoVoltage = 1.6, bool useRegulatorLDO = false); + int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX126X_SYNC_WORD_PRIVATE, int8_t power = 10, uint16_t preambleLength = 8, float tcxoVoltage = 1.6, bool useRegulatorLDO = false); /*! \brief Initialization method for FSK modem. @@ -56,23 +57,21 @@ class SX1268: public SX126x { \param br FSK bit rate in kbps. Defaults to 48.0 kbps. - \param freqDev Frequency deviation from carrier frequency in kHz. Defaults to 50.0 kHz. + \param freqDev Frequency deviation from carrier frequency in kHz. Defaults to 50.0 kHz. \param rxBw Receiver bandwidth in kHz. Defaults to 156.2 kHz. - \param power Output power in dBm. Defaults to 14 dBm. - - \param currentLimit Current protection limit in mA. Defaults to 60.0 mA. + \param power Output power in dBm. Defaults to 10 dBm. \parma preambleLength FSK preamble length in bits. Defaults to 16 bits. - \param dataShaping Time-bandwidth product of the Gaussian filter to be used for shaping. Defaults to 0.5. - \param tcxoVoltage TCXO reference voltage to be set on DIO3. Defaults to 1.6 V, set to 0 to skip. + \param useRegulatorLDO Whether to use only LDO regulator (true) or DC-DC regulator (false). Defaults to false. + \returns \ref status_codes */ - int16_t beginFSK(float freq = 434.0, float br = 48.0, float freqDev = 50.0, float rxBw = 156.2, int8_t power = 14, float currentLimit = 60.0, uint16_t preambleLength = 16, float dataShaping = 0.5, float tcxoVoltage = 1.6, bool useRegulatorLDO = false); + int16_t beginFSK(float freq = 434.0, float br = 48.0, float freqDev = 50.0, float rxBw = 156.2, int8_t power = 10, uint16_t preambleLength = 16, float tcxoVoltage = 1.6, bool useRegulatorLDO = false); // configuration methods @@ -103,3 +102,5 @@ class SX1268: public SX126x { }; #endif + +#endif diff --git a/src/modules/SX126x/SX126x.cpp b/src/modules/SX126x/SX126x.cpp index b089f247..fbd0edf4 100644 --- a/src/modules/SX126x/SX126x.cpp +++ b/src/modules/SX126x/SX126x.cpp @@ -1,10 +1,11 @@ #include "SX126x.h" +#if !defined(RADIOLIB_EXCLUDE_SX126X) SX126x::SX126x(Module* mod) : PhysicalLayer(SX126X_FREQUENCY_STEP_SIZE, SX126X_MAX_PACKET_LENGTH) { _mod = mod; } -int16_t SX126x::begin(float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, float currentLimit, uint16_t preambleLength, float tcxoVoltage, bool useRegulatorLDO) { +int16_t SX126x::begin(float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, uint16_t preambleLength, float tcxoVoltage, bool useRegulatorLDO) { // set module properties _mod->init(RADIOLIB_USE_SPI); Module::pinMode(_mod->getIrq(), INPUT); @@ -55,13 +56,13 @@ int16_t SX126x::begin(float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, float state = setSyncWord(syncWord); RADIOLIB_ASSERT(state); - state = setCurrentLimit(currentLimit); - RADIOLIB_ASSERT(state); - state = setPreambleLength(preambleLength); RADIOLIB_ASSERT(state); // set publicly accessible settings that are not a part of begin method + state = setCurrentLimit(60.0); + RADIOLIB_ASSERT(state); + state = setDio2AsRfSwitch(true); RADIOLIB_ASSERT(state); @@ -74,10 +75,11 @@ int16_t SX126x::begin(float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, float return(state); } -int16_t SX126x::beginFSK(float br, float freqDev, float rxBw, float currentLimit, uint16_t preambleLength, float dataShaping, float tcxoVoltage, bool useRegulatorLDO) { +int16_t SX126x::beginFSK(float br, float freqDev, float rxBw, uint16_t preambleLength, float tcxoVoltage, bool useRegulatorLDO) { // set module properties _mod->init(RADIOLIB_USE_SPI); Module::pinMode(_mod->getIrq(), INPUT); + Module::pinMode(_mod->getGpio(), INPUT); // initialize configuration variables (will be overwritten during public settings configuration) _br = 21333; // 48.0 kbps @@ -117,34 +119,38 @@ int16_t SX126x::beginFSK(float br, float freqDev, float rxBw, float currentLimit state = setRxBandwidth(rxBw); RADIOLIB_ASSERT(state); - state = setCurrentLimit(currentLimit); - RADIOLIB_ASSERT(state); - - state = setDataShaping(dataShaping); + state = setCurrentLimit(60.0); RADIOLIB_ASSERT(state); state = setPreambleLength(preambleLength); RADIOLIB_ASSERT(state); + if(useRegulatorLDO) { + state = setRegulatorLDO(); + } else { + state = setRegulatorDCDC(); + } + RADIOLIB_ASSERT(state); + // set publicly accessible settings that are not a part of begin method - uint8_t sync[] = {0x2D, 0x01}; + uint8_t sync[] = {0x12, 0xAD}; state = setSyncWord(sync, 2); RADIOLIB_ASSERT(state); - state = setWhitening(true, 0x0100); + state = setDataShaping(RADIOLIB_SHAPING_NONE); + RADIOLIB_ASSERT(state); + + state = setEncoding(RADIOLIB_ENCODING_NRZ); RADIOLIB_ASSERT(state); state = variablePacketLengthMode(SX126X_MAX_PACKET_LENGTH); RADIOLIB_ASSERT(state); - state = setDio2AsRfSwitch(false); + state = setCRC(2); RADIOLIB_ASSERT(state); - if (useRegulatorLDO) { - state = setRegulatorLDO(); - } else { - state = setRegulatorDCDC(); - } + state = setDio2AsRfSwitch(false); + RADIOLIB_ASSERT(state); return(state); } @@ -153,7 +159,7 @@ int16_t SX126x::reset(bool verify) { // run the reset sequence Module::pinMode(_mod->getRst(), OUTPUT); Module::digitalWrite(_mod->getRst(), LOW); - delayMicroseconds(150); + delay(1); Module::digitalWrite(_mod->getRst(), HIGH); // return immediately when verification is disabled @@ -219,6 +225,7 @@ int16_t SX126x::transmit(uint8_t* data, size_t len, uint8_t addr) { // wait for packet transmission or timeout uint32_t start = micros(); while(!digitalRead(_mod->getIrq())) { + yield(); if(micros() - start > timeout) { clearIrqStatus(); standby(); @@ -278,6 +285,7 @@ int16_t SX126x::receive(uint8_t* data, size_t len) { // wait for packet reception or timeout uint32_t start = micros(); while(!digitalRead(_mod->getIrq())) { + yield(); if(micros() - start > timeout) { fixImplicitTimeout(); clearIrqStatus(); @@ -297,6 +305,9 @@ int16_t SX126x::receive(uint8_t* data, size_t len) { } int16_t SX126x::transmitDirect(uint32_t frf) { + // set RF switch (if present) + _mod->setRfSwitchState(LOW, HIGH); + // user requested to start transmitting immediately (required for RTTY) int16_t state = ERR_NONE; if(frf != 0) { @@ -310,7 +321,10 @@ int16_t SX126x::transmitDirect(uint32_t frf) { } int16_t SX126x::receiveDirect() { - // SX126x is unable to ouput received data directly + // set RF switch (if present) + _mod->setRfSwitchState(HIGH, LOW); + + // SX126x is unable to output received data directly return(ERR_UNKNOWN); } @@ -324,6 +338,9 @@ int16_t SX126x::scanChannel() { int16_t state = standby(); RADIOLIB_ASSERT(state); + // set RF switch (if present) + _mod->setRfSwitchState(HIGH, LOW); + // set DIO pin mapping state = setDioIrqParams(SX126X_IRQ_CAD_DETECTED | SX126X_IRQ_CAD_DONE, SX126X_IRQ_CAD_DETECTED | SX126X_IRQ_CAD_DONE); RADIOLIB_ASSERT(state); @@ -357,6 +374,9 @@ int16_t SX126x::scanChannel() { } int16_t SX126x::sleep(bool retainConfig) { + // set RF switch (if present) + _mod->setRfSwitchState(LOW, LOW); + uint8_t sleepMode = SX126X_SLEEP_START_WARM | SX126X_SLEEP_RTC_OFF; if(!retainConfig) { sleepMode = SX126X_SLEEP_START_COLD | SX126X_SLEEP_RTC_OFF; @@ -364,7 +384,7 @@ int16_t SX126x::sleep(bool retainConfig) { int16_t state = SPIwriteCommand(SX126X_CMD_SET_SLEEP, &sleepMode, 1, false); // wait for SX126x to safely enter sleep mode - delayMicroseconds(500); + delay(1); return(state); } @@ -374,16 +394,19 @@ int16_t SX126x::standby() { } int16_t SX126x::standby(uint8_t mode) { + // set RF switch (if present) + _mod->setRfSwitchState(LOW, LOW); + uint8_t data[] = {mode}; return(SPIwriteCommand(SX126X_CMD_SET_STANDBY, data, 1)); } void SX126x::setDio1Action(void (*func)(void)) { - attachInterrupt(digitalPinToInterrupt(_mod->getIrq()), func, RISING); + attachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getIrq()), func, RISING); } void SX126x::clearDio1Action() { - detachInterrupt(digitalPinToInterrupt(_mod->getIrq())); + detachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getIrq())); } int16_t SX126x::startTransmit(uint8_t* data, size_t len, uint8_t addr) { @@ -432,6 +455,9 @@ int16_t SX126x::startTransmit(uint8_t* data, size_t len, uint8_t addr) { state = fixSensitivity(); RADIOLIB_ASSERT(state); + // set RF switch (if present) + _mod->setRfSwitchState(LOW, HIGH); + // start transmission state = setTx(SX126X_TX_TIMEOUT_NONE); RADIOLIB_ASSERT(state); @@ -448,6 +474,9 @@ int16_t SX126x::startReceive(uint32_t timeout) { int16_t state = startReceiveCommon(); RADIOLIB_ASSERT(state); + // set RF switch (if present) + _mod->setRfSwitchState(HIGH, LOW); + // set mode to receive state = setRx(timeout); @@ -486,7 +515,7 @@ int16_t SX126x::startReceiveDutyCycleAuto(uint16_t senderPreambleLength, uint16_ senderPreambleLength = _preambleLength; } - // worst case is that the sender starts transmiting when we're just less than minSymbols from going back to sleep. + // worst case is that the sender starts transmitting when we're just less than minSymbols from going back to sleep. // in this case, we don't catch minSymbols before going to sleep, // so we must be awake for at least that long before the sender stops transmitting. uint16_t sleepSymbols = senderPreambleLength - 2 * minSymbols; @@ -504,7 +533,7 @@ int16_t SX126x::startReceiveDutyCycleAuto(uint16_t senderPreambleLength, uint16_ // when the unit detects a preamble, it starts a timer that will timeout if it doesn't receive a header in time. // the duration is sleepPeriod + 2 * wakePeriod. // The sleepPeriod doesn't take into account shutdown and startup time for the unit (~1ms) - // We need to ensure that the timout is longer than senderPreambleLength. + // We need to ensure that the timeout is longer than senderPreambleLength. // So we must satisfy: wakePeriod > (preamblePeriod - (sleepPeriod - 1000)) / 2. (A) // we also need to ensure the unit is awake to see at least minSymbols. (B) uint32_t wakePeriod = max( @@ -513,7 +542,7 @@ int16_t SX126x::startReceiveDutyCycleAuto(uint16_t senderPreambleLength, uint16_ RADIOLIB_DEBUG_PRINT(F("Auto wake period: ")); RADIOLIB_DEBUG_PRINTLN(wakePeriod); - //If our sleep period is shorter than our transition time, just use the standard startReceive + // If our sleep period is shorter than our transition time, just use the standard startReceive if(sleepPeriod < _tcxoDelay + 1016) { return(startReceive()); } @@ -551,7 +580,6 @@ int16_t SX126x::readData(uint8_t* data, size_t len) { uint16_t irq = getIrqStatus(); int16_t crcState = ERR_NONE; if((irq & SX126X_IRQ_CRC_ERR) || (irq & SX126X_IRQ_HEADER_ERR)) { - clearIrqStatus(); crcState = ERR_CRC_MISMATCH; } @@ -580,12 +608,10 @@ int16_t SX126x::setBandwidth(float bw) { return(ERR_WRONG_MODEM); } - // ensure byte conversion doesn't overflow: - if(!((bw > 0) && (bw < 510))) { - return(ERR_INVALID_BANDWIDTH); - } + // ensure byte conversion doesn't overflow + RADIOLIB_CHECK_RANGE(bw, 0.0, 510.0, ERR_INVALID_BANDWIDTH); - // check alowed bandwidth values + // check allowed bandwidth values uint8_t bw_div2 = bw / 2 + 0.01; switch (bw_div2) { case 3: // 7.8: @@ -624,7 +650,7 @@ int16_t SX126x::setBandwidth(float bw) { // update modulation parameters _bwKhz = bw; - return(setModulationParams(_sf, _bw, _cr)); + return(setModulationParams(_sf, _bw, _cr, _ldro)); } int16_t SX126x::setSpreadingFactor(uint8_t sf) { @@ -633,14 +659,11 @@ int16_t SX126x::setSpreadingFactor(uint8_t sf) { return(ERR_WRONG_MODEM); } - // check allowed spreading factor values - if(!((sf >= 5) && (sf <= 12))) { - return(ERR_INVALID_SPREADING_FACTOR); - } + RADIOLIB_CHECK_RANGE(sf, 5, 12, ERR_INVALID_SPREADING_FACTOR); // update modulation parameters _sf = sf; - return(setModulationParams(_sf, _bw, _cr)); + return(setModulationParams(_sf, _bw, _cr, _ldro)); } int16_t SX126x::setCodingRate(uint8_t cr) { @@ -649,14 +672,11 @@ int16_t SX126x::setCodingRate(uint8_t cr) { return(ERR_WRONG_MODEM); } - // check allowed spreading factor values - if(!((cr >= 5) && (cr <= 8))) { - return(ERR_INVALID_CODING_RATE); - } + RADIOLIB_CHECK_RANGE(cr, 5, 8, ERR_INVALID_CODING_RATE); // update modulation parameters _cr = cr - 4; - return(setModulationParams(_sf, _bw, _cr)); + return(setModulationParams(_sf, _bw, _cr, _ldro)); } int16_t SX126x::setSyncWord(uint8_t syncWord, uint8_t controlBits) { @@ -711,10 +731,7 @@ int16_t SX126x::setFrequencyDeviation(float freqDev) { return(ERR_WRONG_MODEM); } - // check alowed frequency deviation values - if(!(freqDev <= 200.0)) { - return(ERR_INVALID_FREQUENCY_DEVIATION); - } + RADIOLIB_CHECK_RANGE(freqDev, 0.0, 200.0, ERR_INVALID_FREQUENCY_DEVIATION); // calculate raw frequency deviation value uint32_t freqDevRaw = (uint32_t)(((freqDev * 1000.0) * (float)((uint32_t)(1) << 25)) / (SX126X_CRYSTAL_FREQ * 1000000.0)); @@ -735,10 +752,7 @@ int16_t SX126x::setBitRate(float br) { return(ERR_WRONG_MODEM); } - // check alowed bit rate values - if(!((br >= 0.6) && (br <= 300.0))) { - return(ERR_INVALID_BIT_RATE); - } + RADIOLIB_CHECK_RANGE(br, 0.6, 300.0, ERR_INVALID_BIT_RATE); // calculate raw bit rate value uint32_t brRaw = (uint32_t)((SX126X_CRYSTAL_FREQ * 1000000.0 * 32.0) / (br * 1000.0)); @@ -765,7 +779,7 @@ int16_t SX126x::setRxBandwidth(float rxBw) { }*/ _rxBwKhz = rxBw; - // check alowed receiver bandwidth values + // check allowed receiver bandwidth values if(abs(rxBw - 4.8) <= 0.001) { _rxBw = SX126X_GFSK_RX_BW_4_8; } else if(abs(rxBw - 5.8) <= 0.001) { @@ -816,26 +830,31 @@ int16_t SX126x::setRxBandwidth(float rxBw) { return(setModulationParamsFSK(_br, _pulseShape, _rxBw, _freqDev)); } -int16_t SX126x::setDataShaping(float sh) { +int16_t SX126x::setDataShaping(uint8_t sh) { // check active modem if(getPacketType() != SX126X_PACKET_TYPE_GFSK) { return(ERR_WRONG_MODEM); } - // check allowed values - sh *= 10.0; - if(abs(sh - 0.0) <= 0.001) { - _pulseShape = SX126X_GFSK_FILTER_NONE; - } else if(abs(sh - 3.0) <= 0.001) { - _pulseShape = SX126X_GFSK_FILTER_GAUSS_0_3; - } else if(abs(sh - 5.0) <= 0.001) { - _pulseShape = SX126X_GFSK_FILTER_GAUSS_0_5; - } else if(abs(sh - 7.0) <= 0.001) { - _pulseShape = SX126X_GFSK_FILTER_GAUSS_0_7; - } else if(abs(sh - 10.0) <= 0.001) { - _pulseShape = SX126X_GFSK_FILTER_GAUSS_1; - } else { - return(ERR_INVALID_DATA_SHAPING); + // set data shaping + switch(sh) { + case RADIOLIB_SHAPING_NONE: + _pulseShape = SX126X_GFSK_FILTER_NONE; + break; + case RADIOLIB_SHAPING_0_3: + _pulseShape = SX126X_GFSK_FILTER_GAUSS_0_3; + break; + case RADIOLIB_SHAPING_0_5: + _pulseShape = SX126X_GFSK_FILTER_GAUSS_0_5; + break; + case RADIOLIB_SHAPING_0_7: + _pulseShape = SX126X_GFSK_FILTER_GAUSS_0_7; + break; + case RADIOLIB_SHAPING_1_0: + _pulseShape = SX126X_GFSK_FILTER_GAUSS_1; + break; + default: + return(ERR_INVALID_DATA_SHAPING); } // update modulation parameters @@ -980,7 +999,7 @@ int16_t SX126x::setCRC(uint8_t len, uint16_t initial, uint16_t polynomial, bool return(state); } else if(modem == SX126X_PACKET_TYPE_LORA) { - // LoRa CRC doesn't allow to set CRC polynomial, inital value, or inversion + // LoRa CRC doesn't allow to set CRC polynomial, initial value, or inversion // update packet parameters if(len) { @@ -1002,12 +1021,13 @@ int16_t SX126x::setWhitening(bool enabled, uint16_t initial) { } int16_t state = ERR_NONE; - if(enabled != true) { + if(!enabled) { // disable whitening _whitening = SX126X_GFSK_WHITENING_OFF; state = setPacketParamsFSK(_preambleLengthFSK, _crcTypeFSK, _syncWordLength, _addrComp, _whitening, _packetType); RADIOLIB_ASSERT(state); + } else { // enable whitening _whitening = SX126X_GFSK_WHITENING_ON; @@ -1031,7 +1051,7 @@ int16_t SX126x::setWhitening(bool enabled, uint16_t initial) { return(state); } -float SX126x::getDataRate() { +float SX126x::getDataRate() const { return(_dataRate); } @@ -1128,6 +1148,31 @@ int16_t SX126x::setEncoding(uint8_t encoding) { return(setWhitening(encoding)); } +void SX126x::setRfSwitchPins(RADIOLIB_PIN_TYPE rxEn, RADIOLIB_PIN_TYPE txEn) { + _mod->setRfSwitchPins(rxEn, txEn); +} + +int16_t SX126x::forceLDRO(bool enable) { + // check active modem + if(getPacketType() != SX126X_PACKET_TYPE_LORA) { + return(ERR_WRONG_MODEM); + } + + // update modulation parameters + _ldroAuto = false; + _ldro = (uint8_t)enable; + return(setModulationParams(_sf, _bw, _cr, _ldro)); +} + +int16_t SX126x::autoLDRO() { + if(getPacketType() != SX126X_PACKET_TYPE_LORA) { + return(ERR_WRONG_MODEM); + } + + _ldroAuto = true; + return(ERR_NONE); +} + int16_t SX126x::setTCXO(float voltage, uint32_t delay) { // set mode to standby standby(); @@ -1182,12 +1227,12 @@ int16_t SX126x::setDio2AsRfSwitch(bool enable) { } int16_t SX126x::setTx(uint32_t timeout) { - uint8_t data[3] = {(uint8_t)((timeout >> 16) & 0xFF), (uint8_t)((timeout >> 8) & 0xFF), (uint8_t)(timeout & 0xFF)}; + uint8_t data[] = { (uint8_t)((timeout >> 16) & 0xFF), (uint8_t)((timeout >> 8) & 0xFF), (uint8_t)(timeout & 0xFF)} ; return(SPIwriteCommand(SX126X_CMD_SET_TX, data, 3)); } int16_t SX126x::setRx(uint32_t timeout) { - uint8_t data[3] = {(uint8_t)((timeout >> 16) & 0xFF), (uint8_t)((timeout >> 8) & 0xFF), (uint8_t)(timeout & 0xFF)}; + uint8_t data[] = { (uint8_t)((timeout >> 16) & 0xFF), (uint8_t)((timeout >> 8) & 0xFF), (uint8_t)(timeout & 0xFF) }; return(SPIwriteCommand(SX126X_CMD_SET_RX, data, 3)); } @@ -1196,32 +1241,28 @@ int16_t SX126x::setCad() { } int16_t SX126x::setPaConfig(uint8_t paDutyCycle, uint8_t deviceSel, uint8_t hpMax, uint8_t paLut) { - uint8_t data[4] = {paDutyCycle, hpMax, deviceSel, paLut}; + uint8_t data[] = { paDutyCycle, hpMax, deviceSel, paLut }; return(SPIwriteCommand(SX126X_CMD_SET_PA_CONFIG, data, 4)); } int16_t SX126x::writeRegister(uint16_t addr, uint8_t* data, uint8_t numBytes) { uint8_t cmd[] = { SX126X_CMD_WRITE_REGISTER, (uint8_t)((addr >> 8) & 0xFF), (uint8_t)(addr & 0xFF) }; - int16_t state = SPIwriteCommand(cmd, 3, data, numBytes); - return(state); + return(SPIwriteCommand(cmd, 3, data, numBytes)); } int16_t SX126x::readRegister(uint16_t addr, uint8_t* data, uint8_t numBytes) { - uint8_t cmd[] = {SX126X_CMD_READ_REGISTER, (uint8_t)((addr >> 8) & 0xFF), (uint8_t)(addr & 0xFF)}; + uint8_t cmd[] = { SX126X_CMD_READ_REGISTER, (uint8_t)((addr >> 8) & 0xFF), (uint8_t)(addr & 0xFF) }; return(SX126x::SPItransfer(cmd, 3, false, NULL, data, numBytes, true)); } int16_t SX126x::writeBuffer(uint8_t* data, uint8_t numBytes, uint8_t offset) { uint8_t cmd[] = { SX126X_CMD_WRITE_BUFFER, offset }; - int16_t state = SPIwriteCommand(cmd, 2, data, numBytes); - - return(state); + return(SPIwriteCommand(cmd, 2, data, numBytes)); } int16_t SX126x::readBuffer(uint8_t* data, uint8_t numBytes) { uint8_t cmd[] = { SX126X_CMD_READ_BUFFER, SX126X_CMD_NOP }; - int16_t state = SPIreadCommand(cmd, 2, data, numBytes); - return(state); + return(SPIreadCommand(cmd, 2, data, numBytes)); } int16_t SX126x::setDioIrqParams(uint16_t irqMask, uint16_t dio1Mask, uint16_t dio2Mask, uint16_t dio3Mask) { @@ -1233,18 +1274,18 @@ int16_t SX126x::setDioIrqParams(uint16_t irqMask, uint16_t dio1Mask, uint16_t di } uint16_t SX126x::getIrqStatus() { - uint8_t data[2] = {0, 0};; + uint8_t data[] = { 0x00, 0x00 }; SPIreadCommand(SX126X_CMD_GET_IRQ_STATUS, data, 2); return(((uint16_t)(data[0]) << 8) | data[1]); } int16_t SX126x::clearIrqStatus(uint16_t clearIrqParams) { - uint8_t data[2] = {(uint8_t)((clearIrqParams >> 8) & 0xFF), (uint8_t)(clearIrqParams & 0xFF)}; + uint8_t data[] = { (uint8_t)((clearIrqParams >> 8) & 0xFF), (uint8_t)(clearIrqParams & 0xFF) }; return(SPIwriteCommand(SX126X_CMD_CLEAR_IRQ_STATUS, data, 2)); } int16_t SX126x::setRfFrequency(uint32_t frf) { - uint8_t data[4] = {(uint8_t)((frf >> 24) & 0xFF), (uint8_t)((frf >> 16) & 0xFF), (uint8_t)((frf >> 8) & 0xFF), (uint8_t)(frf & 0xFF)}; + uint8_t data[] = { (uint8_t)((frf >> 24) & 0xFF), (uint8_t)((frf >> 16) & 0xFF), (uint8_t)((frf >> 8) & 0xFF), (uint8_t)(frf & 0xFF) }; return(SPIwriteCommand(SX126X_CMD_SET_RF_FREQUENCY, data, 4)); } @@ -1259,7 +1300,7 @@ uint8_t SX126x::getPacketType() { } int16_t SX126x::setTxParams(uint8_t power, uint8_t rampTime) { - uint8_t data[2] = {power, rampTime}; + uint8_t data[] = { power, rampTime }; return(SPIwriteCommand(SX126X_CMD_SET_TX_PARAMS, data, 2)); } @@ -1296,8 +1337,8 @@ int16_t SX126x::setHeaderType(uint8_t headerType, size_t len) { } int16_t SX126x::setModulationParams(uint8_t sf, uint8_t bw, uint8_t cr, uint8_t ldro) { - // calculate symbol length and enable low data rate optimization, if needed - if(ldro == 0xFF) { + // calculate symbol length and enable low data rate optimization, if auto-configuration is enabled + if(_ldroAuto) { float symbolLength = (float)(uint32_t(1) << _sf) / (float)_bwKhz; RADIOLIB_DEBUG_PRINT("Symbol length: "); RADIOLIB_DEBUG_PRINT(symbolLength); @@ -1526,10 +1567,12 @@ int16_t SX126x::SPItransfer(uint8_t* cmd, uint8_t cmdLen, bool write, uint8_t* d // pull NSS low digitalWrite(_mod->getCs(), LOW); - // ensure BUSY is low (state meachine ready) + // ensure BUSY is low (state machine ready) uint32_t start = millis(); while(digitalRead(_mod->getGpio())) { + yield(); if(millis() - start >= timeout) { + digitalWrite(_mod->getCs(), HIGH); return(ERR_SPI_CMD_TIMEOUT); } } @@ -1596,6 +1639,7 @@ int16_t SX126x::SPItransfer(uint8_t* cmd, uint8_t cmdLen, bool write, uint8_t* d delayMicroseconds(1); start = millis(); while(digitalRead(_mod->getGpio())) { + yield(); if(millis() - start >= timeout) { status = SX126X_STATUS_CMD_TIMEOUT; break; @@ -1645,7 +1689,7 @@ int16_t SX126x::SPItransfer(uint8_t* cmd, uint8_t cmdLen, bool write, uint8_t* d // some faster platforms require a short delay here // not sure why, but it seems that long enough SPI transaction // (e.g. setPacketParams for GFSK) will fail without it - #if defined(ARDUINO_ARCH_STM32) + #if defined(ARDUINO_ARCH_STM32) || defined(SAMD_SERIES) delay(1); #endif #endif @@ -1664,3 +1708,5 @@ int16_t SX126x::SPItransfer(uint8_t* cmd, uint8_t cmdLen, bool write, uint8_t* d return(ERR_NONE); } } + +#endif diff --git a/src/modules/SX126x/SX126x.h b/src/modules/SX126x/SX126x.h index df6e8028..3d45266a 100644 --- a/src/modules/SX126x/SX126x.h +++ b/src/modules/SX126x/SX126x.h @@ -1,7 +1,10 @@ -#ifndef _RADIOLIB_SX126X_H +#if !defined(_RADIOLIB_SX126X_H) #define _RADIOLIB_SX126X_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SX126X) + #include "../../Module.h" #include "../../protocols/PhysicalLayer/PhysicalLayer.h" @@ -106,7 +109,7 @@ // SX126X SPI command variables -//SX126X_CMD_SET_SLEEP +//SX126X_CMD_SET_SLEEP MSB LSB DESCRIPTION #define SX126X_SLEEP_START_COLD 0b00000000 // 2 2 sleep mode: cold start, configuration is lost (default) #define SX126X_SLEEP_START_WARM 0b00000100 // 2 2 warm start, configuration is retained #define SX126X_SLEEP_RTC_OFF 0b00000000 // 0 0 wake on RTC timeout: disabled @@ -364,8 +367,6 @@ class SX126x: public PhysicalLayer { \param syncWord 1-byte LoRa sync word. - \param currentLimit Current protection limit in mA. - \param preambleLength LoRa preamble length in symbols. Allowed values range from 1 to 65535. \param tcxoVoltage TCXO reference voltage to be set on DIO3. Defaults to 1.6 V, set to 0 to skip. @@ -374,7 +375,7 @@ class SX126x: public PhysicalLayer { \returns \ref status_codes */ - int16_t begin(float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, float currentLimit, uint16_t preambleLength, float tcxoVoltage, bool useRegulatorLDO = false); + int16_t begin(float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, uint16_t preambleLength, float tcxoVoltage, bool useRegulatorLDO = false); /*! \brief Initialization method for FSK modem. @@ -385,19 +386,15 @@ class SX126x: public PhysicalLayer { \param rxBw Receiver bandwidth in kHz. Allowed values are 4.8, 5.8, 7.3, 9.7, 11.7, 14.6, 19.5, 23.4, 29.3, 39.0, 46.9, 58.6, 78.2, 93.8, 117.3, 156.2, 187.2, 234.3, 312.0, 373.6 and 467.0 kHz. - \param currentLimit Current protection limit in mA. - \param preambleLength FSK preamble length in bits. Allowed values range from 0 to 65535. - \param dataShaping Time-bandwidth product of the Gaussian filter to be used for shaping. Allowed values are 0.3, 0.5, 0.7 and 1.0. Set to 0 to disable shaping. - \param tcxoVoltage TCXO reference voltage to be set on DIO3. Defaults to 1.6 V, set to 0 to skip. \param useRegulatorLDO use the LDO instead of DC-DC converter (default false). This is necessary for some modules such as the LAMBDA from RF solutions. \returns \ref status_codes */ - int16_t beginFSK(float br, float freqDev, float rxBw, float currentLimit, uint16_t preambleLength, float dataShaping, float tcxoVoltage, bool useRegulatorLDO = false); + int16_t beginFSK(float br, float freqDev, float rxBw, uint16_t preambleLength, float tcxoVoltage, bool useRegulatorLDO = false); /*! \brief Reset method. Will reset the chip to the default state using RST pin. @@ -421,7 +418,7 @@ class SX126x: public PhysicalLayer { \returns \ref status_codes */ - int16_t transmit(uint8_t* data, size_t len, uint8_t addr = 0); + int16_t transmit(uint8_t* data, size_t len, uint8_t addr = 0) override; /*! \brief Blocking binary receive method. @@ -433,7 +430,7 @@ class SX126x: public PhysicalLayer { \returns \ref status_codes */ - int16_t receive(uint8_t* data, size_t len); + int16_t receive(uint8_t* data, size_t len) override; /*! \brief Starts direct mode transmission. @@ -442,7 +439,7 @@ class SX126x: public PhysicalLayer { \returns \ref status_codes */ - int16_t transmitDirect(uint32_t frf = 0); + int16_t transmitDirect(uint32_t frf = 0) override; /*! \brief Starts direct mode reception. Only implemented for PhysicalLayer compatibility, as %SX126x series does not support direct mode reception. @@ -450,7 +447,7 @@ class SX126x: public PhysicalLayer { \returns \ref status_codes */ - int16_t receiveDirect(); + int16_t receiveDirect() override; /*! \brief Performs scan for LoRa transmission in the current channel. Detects both preamble and payload. @@ -473,7 +470,7 @@ class SX126x: public PhysicalLayer { \returns \ref status_codes */ - int16_t standby(); + int16_t standby() override; /*! \brief Sets the module to standby mode. @@ -510,7 +507,7 @@ class SX126x: public PhysicalLayer { \returns \ref status_codes */ - int16_t startTransmit(uint8_t* data, size_t len, uint8_t addr = 0); + int16_t startTransmit(uint8_t* data, size_t len, uint8_t addr = 0) override; /*! \brief Interrupt-driven receive method. DIO1 will be activated when full packet is received. @@ -555,7 +552,7 @@ class SX126x: public PhysicalLayer { \returns \ref status_codes */ - int16_t readData(uint8_t* data, size_t len); + int16_t readData(uint8_t* data, size_t len) override; // configuration methods @@ -629,7 +626,7 @@ class SX126x: public PhysicalLayer { \returns \ref status_codes */ - int16_t setFrequencyDeviation(float freqDev); + int16_t setFrequencyDeviation(float freqDev) override; /*! \brief Sets FSK bit rate. Allowed values range from 0.6 to 300.0 kbps. @@ -650,13 +647,15 @@ class SX126x: public PhysicalLayer { int16_t setRxBandwidth(float rxBw); /*! - \brief Sets time-bandwidth product of Gaussian filter applied for shaping. Allowed values are 0.3, 0.5, 0.7 and 1.0. Set to 0 to disable shaping. + \brief Sets time-bandwidth product of Gaussian filter applied for shaping. + Allowed values are RADIOLIB_SHAPING_0_3, RADIOLIB_SHAPING_0_5, RADIOLIB_SHAPING_0_7 or RADIOLIB_SHAPING_1_0. + Set to RADIOLIB_SHAPING_NONE to disable data shaping. \param sh Time-bandwidth product of Gaussian filter to be set. \returns \ref status_codes */ - int16_t setDataShaping(float sh); + int16_t setDataShaping(uint8_t sh) override; /*! \brief Sets FSK sync word in the form of array of up to 8 bytes. @@ -725,7 +724,7 @@ class SX126x: public PhysicalLayer { \param enabled True = Whitening enabled - \param initial Initial value used for the whitening LFSR in FSK mode. + \param initial Initial value used for the whitening LFSR in FSK mode. Defaults to 0x0100, use 0x01FF for SX127x compatibility. \returns \ref status_codes */ @@ -752,7 +751,7 @@ class SX126x: public PhysicalLayer { \returns Effective data rate in bps. */ - float getDataRate(); + float getDataRate() const; /*! \brief Gets RSSI (Recorded Signal Strength Indicator) of the last received packet. @@ -768,14 +767,14 @@ class SX126x: public PhysicalLayer { */ float getSNR(); - /*! + /*! \brief Query modem for the packet length of received payload. \param update Update received packet length. Will return cached value when set to false. \returns Length of last received packet in bytes. */ - size_t getPacketLength(bool update = true); + size_t getPacketLength(bool update = true) override; /*! \brief Set modem in fixed packet length mode. Available in FSK mode only. @@ -786,7 +785,7 @@ class SX126x: public PhysicalLayer { */ int16_t fixedPacketLengthMode(uint8_t len = SX126X_MAX_PACKET_LENGTH); - /*! + /*! \brief Set modem in variable packet length mode. Available in FSK mode only. \param len Maximum packet length. @@ -795,7 +794,7 @@ class SX126x: public PhysicalLayer { */ int16_t variablePacketLengthMode(uint8_t maxLen = SX126X_MAX_PACKET_LENGTH); - /*! + /*! \brief Get expected time-on-air for a given size of payload \param len Payload length in bytes. @@ -804,14 +803,14 @@ class SX126x: public PhysicalLayer { */ uint32_t getTimeOnAir(size_t len); - /*! + /*! \brief Set implicit header mode for future reception/transmission. \returns \ref status_codes */ int16_t implicitHeader(size_t len); - /*! + /*! \brief Set explicit header mode for future reception/transmission. \param len Payload length in bytes. @@ -821,17 +820,17 @@ class SX126x: public PhysicalLayer { int16_t explicitHeader(); /*! - \brief Set regulator mode to LDO. + \brief Set regulator mode to LDO. - \returns \ref status_codes - */ + \returns \ref status_codes + */ int16_t setRegulatorLDO(); /*! - \brief Set regulator mode to DC-DC. + \brief Set regulator mode to DC-DC. - \returns \ref status_codes - */ + \returns \ref status_codes + */ int16_t setRegulatorDCDC(); /*! @@ -841,12 +840,40 @@ class SX126x: public PhysicalLayer { \returns \ref status_codes */ - int16_t setEncoding(uint8_t encoding); + int16_t setEncoding(uint8_t encoding) override; + + /*! + \brief Some modules contain external RF switch controlled by two pins. This function gives RadioLib control over those two pins to automatically switch Rx and Tx state. + When using automatic RF switch control, DO NOT change the pin mode of rxEn or txEn from Arduino sketch! + + \param rxEn RX enable pin. + + \param txEn TX enable pin. + */ + void setRfSwitchPins(RADIOLIB_PIN_TYPE rxEn, RADIOLIB_PIN_TYPE txEn); + + /*! + \brief Forces LoRa low data rate optimization. Only available in LoRa mode. After calling this method, LDRO will always be set to + the provided value, regardless of symbol length. To re-enable automatic LDRO configuration, call SX1278::autoLDRO() + + \param enable Force LDRO to be always enabled (true) or disabled (false). + + \returns \ref status_codes + */ + int16_t forceLDRO(bool enable); + + /*! + \brief Re-enables automatic LDRO configuration. Only available in LoRa mode. After calling this method, LDRO will be enabled automatically + when symbol length exceeds 16 ms. + + \returns \ref status_codes + */ + int16_t autoLDRO(); #ifndef RADIOLIB_GODMODE protected: #endif - // SX1276x SPI command implementations + // SX126x SPI command implementations int16_t setTx(uint32_t timeout = 0); int16_t setRx(uint32_t timeout); int16_t setCad(); @@ -862,7 +889,7 @@ class SX126x: public PhysicalLayer { int16_t calibrateImage(uint8_t* data); uint8_t getPacketType(); int16_t setTxParams(uint8_t power, uint8_t rampTime = SX126X_PA_RAMP_200U); - int16_t setModulationParams(uint8_t sf, uint8_t bw, uint8_t cr, uint8_t ldro = 0xFF); + int16_t setModulationParams(uint8_t sf, uint8_t bw, uint8_t cr, uint8_t ldro); int16_t setModulationParamsFSK(uint32_t br, uint8_t pulseShape, uint8_t rxBw, uint32_t freqDev); int16_t setPacketParams(uint16_t preambleLength, uint8_t crcType, uint8_t payloadLength, uint8_t headerType, uint8_t invertIQ = SX126X_LORA_IQ_STANDARD); int16_t setPacketParamsFSK(uint16_t preambleLength, uint8_t crcType, uint8_t syncWordLength, uint8_t addrComp, uint8_t whitening, uint8_t packetType = SX126X_GFSK_PACKET_VARIABLE, uint8_t payloadLength = 0xFF, uint8_t preambleDetectorLength = SX126X_GFSK_PREAMBLE_DETECT_16); @@ -889,20 +916,21 @@ class SX126x: public PhysicalLayer { #endif Module* _mod; - uint8_t _bw, _sf, _cr, _ldro, _crcType, _headerType; - uint16_t _preambleLength; - float _bwKhz; + uint8_t _bw = 0, _sf = 0, _cr = 0, _ldro = 0, _crcType = 0, _headerType = 0; + uint16_t _preambleLength = 0; + float _bwKhz = 0; + bool _ldroAuto = true; - uint32_t _br, _freqDev; - uint8_t _rxBw, _pulseShape, _crcTypeFSK, _syncWordLength, _addrComp, _whitening, _packetType; - uint16_t _preambleLengthFSK; - float _rxBwKhz; + uint32_t _br = 0, _freqDev = 0; + uint8_t _rxBw = 0, _pulseShape = 0, _crcTypeFSK = 0, _syncWordLength = 0, _addrComp = 0, _whitening = 0, _packetType = 0; + uint16_t _preambleLengthFSK = 0; + float _rxBwKhz = 0; - float _dataRate; + float _dataRate = 0; - uint32_t _tcxoDelay; + uint32_t _tcxoDelay = 0; - size_t _implicitLen; + size_t _implicitLen = 0; int16_t config(uint8_t modem); @@ -915,3 +943,5 @@ class SX126x: public PhysicalLayer { }; #endif + +#endif diff --git a/src/modules/SX127x/SX1272.cpp b/src/modules/SX127x/SX1272.cpp index d5bb554c..cc3e8133 100644 --- a/src/modules/SX127x/SX1272.cpp +++ b/src/modules/SX127x/SX1272.cpp @@ -1,12 +1,13 @@ #include "SX1272.h" +#if !defined(RADIOLIB_EXCLUDE_SX127X) SX1272::SX1272(Module* mod) : SX127x(mod) { } -int16_t SX1272::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint8_t currentLimit, uint16_t preambleLength, uint8_t gain) { +int16_t SX1272::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint16_t preambleLength, uint8_t gain) { // execute common part - int16_t state = SX127x::begin(SX1272_CHIP_VERSION, syncWord, currentLimit, preambleLength); + int16_t state = SX127x::begin(SX1272_CHIP_VERSION, syncWord, preambleLength); RADIOLIB_ASSERT(state); // configure settings not accessible by API @@ -35,13 +36,14 @@ int16_t SX1272::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t sync RADIOLIB_ASSERT(state); state = setGain(gain); + RADIOLIB_ASSERT(state); return(state); } -int16_t SX1272::beginFSK(float freq, float br, float rxBw, float freqDev, int8_t power, uint8_t currentLimit, uint16_t preambleLength, bool enableOOK) { +int16_t SX1272::beginFSK(float freq, float br, float rxBw, float freqDev, int8_t power, uint16_t preambleLength, bool enableOOK) { // execute common part - int16_t state = SX127x::beginFSK(SX1272_CHIP_VERSION, br, rxBw, freqDev, currentLimit, preambleLength, enableOOK); + int16_t state = SX127x::beginFSK(SX1272_CHIP_VERSION, br, rxBw, freqDev, preambleLength, enableOOK); RADIOLIB_ASSERT(state); // configure settings not accessible by API @@ -52,16 +54,25 @@ int16_t SX1272::beginFSK(float freq, float br, float rxBw, float freqDev, int8_t state = setFrequency(freq); RADIOLIB_ASSERT(state); + state = setDataShaping(RADIOLIB_SHAPING_NONE); + RADIOLIB_ASSERT(state); + state = setOutputPower(power); + RADIOLIB_ASSERT(state); return(state); } +void SX1272::reset() { + Module::pinMode(_mod->getRst(), OUTPUT); + Module::digitalWrite(_mod->getRst(), HIGH); + delay(1); + Module::digitalWrite(_mod->getRst(), LOW); + delay(5); +} + int16_t SX1272::setFrequency(float freq) { - // check frequency range - if((freq < 860.0) || (freq > 1020.0)) { - return(ERR_INVALID_FREQUENCY); - } + RADIOLIB_CHECK_RANGE(freq, 860.0, 1020.0, ERR_INVALID_FREQUENCY); // set frequency and if successful, save the new setting int16_t state = SX127x::setFrequencyRaw(freq); @@ -95,15 +106,17 @@ int16_t SX1272::setBandwidth(float bw) { if(state == ERR_NONE) { SX127x::_bw = bw; - // calculate symbol length and set low data rate optimization, if needed - float symbolLength = (float)(uint32_t(1) << SX127x::_sf) / (float)SX127x::_bw; - RADIOLIB_DEBUG_PRINT("Symbol length: "); - RADIOLIB_DEBUG_PRINT(symbolLength); - RADIOLIB_DEBUG_PRINTLN(" ms"); - if(symbolLength >= 16.0) { - state = _mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_1, SX1272_LOW_DATA_RATE_OPT_ON, 0, 0); - } else { - state = _mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_1, SX1272_LOW_DATA_RATE_OPT_OFF, 0, 0); + // calculate symbol length and set low data rate optimization, if auto-configuration is enabled + if(_ldroAuto) { + float symbolLength = (float)(uint32_t(1) << SX127x::_sf) / (float)SX127x::_bw; + RADIOLIB_DEBUG_PRINT("Symbol length: "); + RADIOLIB_DEBUG_PRINT(symbolLength); + RADIOLIB_DEBUG_PRINTLN(" ms"); + if(symbolLength >= 16.0) { + state = _mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_1, SX1272_LOW_DATA_RATE_OPT_ON, 0, 0); + } else { + state = _mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_1, SX1272_LOW_DATA_RATE_OPT_OFF, 0, 0); + } } } return(state); @@ -149,15 +162,17 @@ int16_t SX1272::setSpreadingFactor(uint8_t sf) { if(state == ERR_NONE) { SX127x::_sf = sf; - // calculate symbol length and set low data rate optimization, if needed + // calculate symbol length and set low data rate optimization, if auto-configuration is enabled + if(_ldroAuto) { float symbolLength = (float)(uint32_t(1) << SX127x::_sf) / (float)SX127x::_bw; - RADIOLIB_DEBUG_PRINT("Symbol length: "); - RADIOLIB_DEBUG_PRINT(symbolLength); - RADIOLIB_DEBUG_PRINTLN(" ms"); - if(symbolLength >= 16.0) { - state = _mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_1, SX1272_LOW_DATA_RATE_OPT_ON, 0, 0); - } else { - state = _mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_1, SX1272_LOW_DATA_RATE_OPT_OFF, 0, 0); + RADIOLIB_DEBUG_PRINT("Symbol length: "); + RADIOLIB_DEBUG_PRINT(symbolLength); + RADIOLIB_DEBUG_PRINTLN(" ms"); + if(symbolLength >= 16.0) { + state = _mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_1, SX1272_LOW_DATA_RATE_OPT_ON, 0, 0); + } else { + state = _mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_1, SX1272_LOW_DATA_RATE_OPT_OFF, 0, 0); + } } } return(state); @@ -212,7 +227,7 @@ int16_t SX1272::setOutputPower(int8_t power) { state |= _mod->SPIsetRegValue(SX127X_REG_PA_CONFIG, SX127X_PA_SELECT_RFO, 7, 7); state |= _mod->SPIsetRegValue(SX127X_REG_PA_CONFIG, (power + 1), 3, 0); state |= _mod->SPIsetRegValue(SX1272_REG_PA_DAC, SX127X_PA_BOOST_OFF, 2, 0); - } else if((power >= 2) && (power <= 17)) { + } else if(power <= 17) { // power is 2 - 17 dBm, enable PA1 + PA2 on PA_BOOST state |= _mod->SPIsetRegValue(SX127X_REG_PA_CONFIG, SX127X_PA_SELECT_BOOST, 7, 7); state |= _mod->SPIsetRegValue(SX127X_REG_PA_CONFIG, (power - 2), 3, 0); @@ -251,7 +266,7 @@ int16_t SX1272::setGain(uint8_t gain) { return(state); } -int16_t SX1272::setDataShaping(float sh) { +int16_t SX1272::setDataShaping(uint8_t sh) { // check active modem if(getActiveModem() != SX127X_FSK_OOK) { return(ERR_WRONG_MODEM); @@ -264,21 +279,21 @@ int16_t SX1272::setDataShaping(float sh) { // set mode to standby int16_t state = SX127x::standby(); + RADIOLIB_ASSERT(state); // set data shaping - sh *= 10.0; - if(abs(sh - 0.0) <= 0.001) { - state |= _mod->SPIsetRegValue(SX127X_REG_OP_MODE, SX1272_NO_SHAPING, 4, 3); - } else if(abs(sh - 3.0) <= 0.001) { - state |= _mod->SPIsetRegValue(SX127X_REG_OP_MODE, SX1272_FSK_GAUSSIAN_0_3, 4, 3); - } else if(abs(sh - 5.0) <= 0.001) { - state |= _mod->SPIsetRegValue(SX127X_REG_OP_MODE, SX1272_FSK_GAUSSIAN_0_5, 4, 3); - } else if(abs(sh - 10.0) <= 0.001) { - state |= _mod->SPIsetRegValue(SX127X_REG_OP_MODE, SX1272_FSK_GAUSSIAN_1_0, 4, 3); - } else { - return(ERR_INVALID_DATA_SHAPING); + switch(sh) { + case RADIOLIB_SHAPING_NONE: + return(_mod->SPIsetRegValue(SX127X_REG_OP_MODE, SX1272_NO_SHAPING, 4, 3)); + case RADIOLIB_SHAPING_0_3: + return(_mod->SPIsetRegValue(SX127X_REG_OP_MODE, SX1272_FSK_GAUSSIAN_0_3, 4, 3)); + case RADIOLIB_SHAPING_0_5: + return(_mod->SPIsetRegValue(SX127X_REG_OP_MODE, SX1272_FSK_GAUSSIAN_0_5, 4, 3)); + case RADIOLIB_SHAPING_1_0: + return(_mod->SPIsetRegValue(SX127X_REG_OP_MODE, SX1272_FSK_GAUSSIAN_1_0, 4, 3)); + default: + return(ERR_INVALID_DATA_SHAPING); } - return(state); } int16_t SX1272::setDataShapingOOK(uint8_t sh) { @@ -361,6 +376,29 @@ int16_t SX1272::setCRC(bool enableCRC) { } } +int16_t SX1272::forceLDRO(bool enable) { + if(getActiveModem() != SX127X_LORA) { + return(ERR_WRONG_MODEM); + } + + _ldroAuto = false; + if(enable) { + return(_mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_1, SX1272_LOW_DATA_RATE_OPT_ON, 0, 0)); + } else { + return(_mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_1, SX1272_LOW_DATA_RATE_OPT_OFF, 0, 0)); + } +} + +int16_t SX1272::autoLDRO() { + if(getActiveModem() != SX127X_LORA) { + return(ERR_WRONG_MODEM); + } + + _ldroAuto = true; + return(ERR_NONE); +} + + int16_t SX1272::setBandwidthRaw(uint8_t newBandwidth) { // set mode to standby int16_t state = SX127x::standby(); @@ -405,6 +443,12 @@ int16_t SX1272::configFSK() { // set fast PLL hop state = _mod->SPIsetRegValue(SX1272_REG_PLL_HOP, SX127X_FAST_HOP_ON, 7, 7); + RADIOLIB_ASSERT(state); + + // set Gauss filter BT product to 0.5 + state = _mod->SPIsetRegValue(SX127X_REG_OP_MODE, SX1272_FSK_GAUSSIAN_0_5, 4, 3); return(state); } + +#endif diff --git a/src/modules/SX127x/SX1272.h b/src/modules/SX127x/SX1272.h index dd90b739..78e009d3 100644 --- a/src/modules/SX127x/SX1272.h +++ b/src/modules/SX127x/SX1272.h @@ -1,7 +1,10 @@ -#ifndef _RADIOLIB_SX1272_H +#if !defined(_RADIOLIB_SX1272_H) #define _RADIOLIB_SX1272_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SX127X) + #include "../../Module.h" #include "SX127x.h" @@ -116,8 +119,6 @@ class SX1272: public SX127x { \param syncWord %LoRa sync word. Can be used to distinguish different networks. Note that value 0x34 is reserved for LoRaWAN networks. - \param power Transmission output power in dBm. Allowed values range from 2 to 17 dBm. - \param currentLimit Trim value for OCP (over current protection) in mA. Can be set to multiplies of 5 in range 45 to 120 mA and to multiples of 10 in range 120 to 240 mA. Set to 0 to disable OCP (not recommended). @@ -129,7 +130,7 @@ class SX1272: public SX127x { \returns \ref status_codes */ - int16_t begin(float freq = 915.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX127X_SYNC_WORD, int8_t power = 17, uint8_t currentLimit = 100, uint16_t preambleLength = 8, uint8_t gain = 0); + int16_t begin(float freq = 915.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX127X_SYNC_WORD, int8_t power = 10, uint16_t preambleLength = 8, uint8_t gain = 0); /*! \brief FSK modem initialization method. Must be called at least once from Arduino sketch to initialize the module. @@ -145,16 +146,18 @@ class SX1272: public SX127x { \param power Transmission output power in dBm. Allowed values range from 2 to 17 dBm. - \param currentLimit Trim value for OCP (over current protection) in mA. Can be set to multiplies of 5 in range 45 to 120 mA and to multiples of 10 in range 120 to 240 mA. - Set to 0 to disable OCP (not recommended). - \param preambleLength Length of FSK preamble in bits. \param enableOOK Use OOK modulation instead of FSK. \returns \ref status_codes */ - int16_t beginFSK(float freq = 915.0, float br = 48.0, float rxBw = 125.0, float freqDev = 50.0, int8_t power = 13, uint8_t currentLimit = 100, uint16_t preambleLength = 16, bool enableOOK = false); + int16_t beginFSK(float freq = 915.0, float br = 48.0, float rxBw = 125.0, float freqDev = 50.0, int8_t power = 10, uint16_t preambleLength = 16, bool enableOOK = false); + + /*! + \brief Reset method. Will reset the chip to the default state using RST pin. + */ + void reset() override; // configuration methods @@ -214,14 +217,14 @@ class SX1272: public SX127x { int16_t setGain(uint8_t gain); /*! - \brief Sets Gaussian filter bandwidth-time product that will be used for data shaping. - Allowed values are 0.3, 0.5 or 1.0. Set to 0 to disable data shaping. Only available in FSK mode with FSK modulation. + \brief Sets Gaussian filter bandwidth-time product that will be used for data shaping. Only available in FSK mode with FSK modulation. + Allowed values are RADIOLIB_SHAPING_0_3, RADIOLIB_SHAPING_0_5 or RADIOLIB_SHAPING_1_0. Set to RADIOLIB_SHAPING_NONE to disable data shaping. \param sh Gaussian shaping bandwidth-time product that will be used for data shaping \returns \ref status_codes */ - int16_t setDataShaping(float sh); + int16_t setDataShaping(uint8_t sh) override; /*! \brief Sets filter cutoff frequency that will be used for data shaping. @@ -250,6 +253,24 @@ class SX1272: public SX127x { */ int16_t setCRC(bool enableCRC); + /*! + \brief Forces LoRa low data rate optimization. Only available in LoRa mode. After calling this method, LDRO will always be set to + the provided value, regardless of symbol length. To re-enable automatic LDRO configuration, call SX1278::autoLDRO() + + \param enable Force LDRO to be always enabled (true) or disabled (false). + + \returns \ref status_codes + */ + int16_t forceLDRO(bool enable); + + /*! + \brief Re-enables automatic LDRO configuration. Only available in LoRa mode. After calling this method, LDRO will be enabled automatically + when symbol length exceeds 16 ms. + + \returns \ref status_codes + */ + int16_t autoLDRO(); + #ifndef RADIOLIB_GODMODE protected: #endif @@ -262,7 +283,11 @@ class SX1272: public SX127x { #ifndef RADIOLIB_GODMODE private: #endif + bool _ldroAuto = true; + bool _ldroEnabled = false; }; #endif + +#endif diff --git a/src/modules/SX127x/SX1273.cpp b/src/modules/SX127x/SX1273.cpp index ee0a48fc..97178f81 100644 --- a/src/modules/SX127x/SX1273.cpp +++ b/src/modules/SX127x/SX1273.cpp @@ -1,12 +1,13 @@ #include "SX1273.h" +#if !defined(RADIOLIB_EXCLUDE_SX127X) SX1273::SX1273(Module* mod) : SX1272(mod) { } -int16_t SX1273::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint8_t currentLimit, uint16_t preambleLength, uint8_t gain) { +int16_t SX1273::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint16_t preambleLength, uint8_t gain) { // execute common part - int16_t state = SX127x::begin(SX1272_CHIP_VERSION, syncWord, currentLimit, preambleLength); + int16_t state = SX127x::begin(SX1272_CHIP_VERSION, syncWord, preambleLength); RADIOLIB_ASSERT(state); // configure settings not accessible by API @@ -35,6 +36,7 @@ int16_t SX1273::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t sync RADIOLIB_ASSERT(state); state = setGain(gain); + RADIOLIB_ASSERT(state); return(state); } @@ -68,3 +70,5 @@ int16_t SX1273::setSpreadingFactor(uint8_t sf) { return(state); } + +#endif diff --git a/src/modules/SX127x/SX1273.h b/src/modules/SX127x/SX1273.h index 52ffafd1..83b43dd4 100644 --- a/src/modules/SX127x/SX1273.h +++ b/src/modules/SX127x/SX1273.h @@ -1,7 +1,10 @@ -#ifndef _RADIOLIB_SX1273_H +#if !defined(_RADIOLIB_SX1273_H) #define _RADIOLIB_SX1273_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SX127X) + #include "SX1272.h" /*! @@ -38,9 +41,6 @@ class SX1273: public SX1272 { \param power Transmission output power in dBm. Allowed values range from 2 to 17 dBm. - \param currentLimit Trim value for OCP (over current protection) in mA. Can be set to multiplies of 5 in range 45 to 120 mA and to multiples of 10 in range 120 to 240 mA. - Set to 0 to disable OCP (not recommended). - \param preambleLength Length of %LoRa transmission preamble in symbols. The actual preamble length is 4.25 symbols longer than the set number. Allowed values range from 6 to 65535. @@ -49,7 +49,7 @@ class SX1273: public SX1272 { \returns \ref status_codes */ - int16_t begin(float freq = 915.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX127X_SYNC_WORD, int8_t power = 17, uint8_t currentLimit = 100, uint16_t preambleLength = 8, uint8_t gain = 0); + int16_t begin(float freq = 915.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX127X_SYNC_WORD, int8_t power = 10, uint16_t preambleLength = 8, uint8_t gain = 0); // configuration methods @@ -69,3 +69,5 @@ class SX1273: public SX1272 { }; #endif + +#endif diff --git a/src/modules/SX127x/SX1276.cpp b/src/modules/SX127x/SX1276.cpp index 40a141a4..b331fe95 100644 --- a/src/modules/SX127x/SX1276.cpp +++ b/src/modules/SX127x/SX1276.cpp @@ -1,12 +1,13 @@ #include "SX1276.h" +#if !defined(RADIOLIB_EXCLUDE_SX127X) SX1276::SX1276(Module* mod) : SX1278(mod) { } -int16_t SX1276::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint8_t currentLimit, uint16_t preambleLength, uint8_t gain) { +int16_t SX1276::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint16_t preambleLength, uint8_t gain) { // execute common part - int16_t state = SX127x::begin(SX1278_CHIP_VERSION, syncWord, currentLimit, preambleLength); + int16_t state = SX127x::begin(SX1278_CHIP_VERSION, syncWord, preambleLength); RADIOLIB_ASSERT(state); // configure settings not accessible by API @@ -30,15 +31,13 @@ int16_t SX1276::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t sync RADIOLIB_ASSERT(state); state = setGain(gain); + RADIOLIB_ASSERT(state); return(state); } int16_t SX1276::setFrequency(float freq) { - // check frequency range - if((freq < 137.0) || (freq > 1020.0)) { - return(ERR_INVALID_FREQUENCY); - } + RADIOLIB_CHECK_RANGE(freq, 137.0, 1020.0, ERR_INVALID_FREQUENCY); // SX1276/77/78 Errata fixes if(getActiveModem() == SX127X_LORA) { @@ -106,3 +105,5 @@ int16_t SX1276::setFrequency(float freq) { // set frequency return(SX127x::setFrequencyRaw(freq)); } + +#endif diff --git a/src/modules/SX127x/SX1276.h b/src/modules/SX127x/SX1276.h index 8a320ec8..ec6e33d6 100644 --- a/src/modules/SX127x/SX1276.h +++ b/src/modules/SX127x/SX1276.h @@ -1,7 +1,10 @@ -#ifndef _RADIOLIB_SX1276_H +#if !defined(_RADIOLIB_SX1276_H) #define _RADIOLIB_SX1276_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SX127X) + #include "SX1278.h" /*! @@ -38,9 +41,6 @@ class SX1276: public SX1278 { \param power Transmission output power in dBm. Allowed values range from 2 to 17 dBm. - \param currentLimit Trim value for OCP (over current protection) in mA. Can be set to multiplies of 5 in range 45 to 120 mA and to multiples of 10 in range 120 to 240 mA. - Set to 0 to disable OCP (not recommended). - \param preambleLength Length of %LoRa transmission preamble in symbols. The actual preamble length is 4.25 symbols longer than the set number. Allowed values range from 6 to 65535. @@ -49,7 +49,7 @@ class SX1276: public SX1278 { \returns \ref status_codes */ - int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX127X_SYNC_WORD, int8_t power = 17, uint8_t currentLimit = 100, uint16_t preambleLength = 8, uint8_t gain = 0); + int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX127X_SYNC_WORD, int8_t power = 10, uint16_t preambleLength = 8, uint8_t gain = 0); // configuration methods @@ -69,3 +69,5 @@ class SX1276: public SX1278 { }; #endif + +#endif diff --git a/src/modules/SX127x/SX1277.cpp b/src/modules/SX127x/SX1277.cpp index bed5a84e..371c125e 100644 --- a/src/modules/SX127x/SX1277.cpp +++ b/src/modules/SX127x/SX1277.cpp @@ -1,12 +1,13 @@ #include "SX1277.h" +#if !defined(RADIOLIB_EXCLUDE_SX127X) SX1277::SX1277(Module* mod) : SX1278(mod) { } -int16_t SX1277::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint8_t currentLimit, uint16_t preambleLength, uint8_t gain) { +int16_t SX1277::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint16_t preambleLength, uint8_t gain) { // execute common part - int16_t state = SX127x::begin(SX1278_CHIP_VERSION, syncWord, currentLimit, preambleLength); + int16_t state = SX127x::begin(SX1278_CHIP_VERSION, syncWord, preambleLength); RADIOLIB_ASSERT(state); // configure settings not accessible by API @@ -30,15 +31,13 @@ int16_t SX1277::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t sync RADIOLIB_ASSERT(state); state = setGain(gain); + RADIOLIB_ASSERT(state); return(state); } int16_t SX1277::setFrequency(float freq) { - // check frequency range - if((freq < 137.0) || (freq > 1020.0)) { - return(ERR_INVALID_FREQUENCY); - } + RADIOLIB_CHECK_RANGE(freq, 137.0, 1020.0, ERR_INVALID_FREQUENCY); // SX1276/77/78 Errata fixes if(getActiveModem() == SX127X_LORA) { @@ -136,3 +135,5 @@ int16_t SX1277::setSpreadingFactor(uint8_t sf) { return(state); } + +#endif diff --git a/src/modules/SX127x/SX1277.h b/src/modules/SX127x/SX1277.h index cee312a3..6598f066 100644 --- a/src/modules/SX127x/SX1277.h +++ b/src/modules/SX127x/SX1277.h @@ -1,7 +1,10 @@ -#ifndef _RADIOLIB_SX1277_H +#if !defined(_RADIOLIB_SX1277_H) #define _RADIOLIB_SX1277_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SX127X) + #include "SX1278.h" /*! @@ -38,9 +41,6 @@ class SX1277: public SX1278 { \param power Transmission output power in dBm. Allowed values range from 2 to 17 dBm. - \param currentLimit Trim value for OCP (over current protection) in mA. Can be set to multiplies of 5 in range 45 to 120 mA and to multiples of 10 in range 120 to 240 mA. - Set to 0 to disable OCP (not recommended). - \param preambleLength Length of %LoRa transmission preamble in symbols. The actual preamble length is 4.25 symbols longer than the set number. Allowed values range from 6 to 65535. @@ -49,7 +49,7 @@ class SX1277: public SX1278 { \returns \ref status_codes */ - int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX127X_SYNC_WORD, int8_t power = 17, uint8_t currentLimit = 100, uint16_t preambleLength = 8, uint8_t gain = 0); + int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX127X_SYNC_WORD, int8_t power = 10, uint16_t preambleLength = 8, uint8_t gain = 0); // configuration methods @@ -78,3 +78,5 @@ class SX1277: public SX1278 { }; #endif + +#endif diff --git a/src/modules/SX127x/SX1278.cpp b/src/modules/SX127x/SX1278.cpp index b2ab0b3c..c4f6ff40 100644 --- a/src/modules/SX127x/SX1278.cpp +++ b/src/modules/SX127x/SX1278.cpp @@ -1,12 +1,13 @@ #include "SX1278.h" +#if !defined(RADIOLIB_EXCLUDE_SX127X) SX1278::SX1278(Module* mod) : SX127x(mod) { } -int16_t SX1278::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint8_t currentLimit, uint16_t preambleLength, uint8_t gain) { +int16_t SX1278::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint16_t preambleLength, uint8_t gain) { // execute common part - int16_t state = SX127x::begin(SX1278_CHIP_VERSION, syncWord, currentLimit, preambleLength); + int16_t state = SX127x::begin(SX1278_CHIP_VERSION, syncWord, preambleLength); RADIOLIB_ASSERT(state); // configure settings not accessible by API @@ -30,13 +31,14 @@ int16_t SX1278::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t sync RADIOLIB_ASSERT(state); state = setGain(gain); + RADIOLIB_ASSERT(state); return(state); } -int16_t SX1278::beginFSK(float freq, float br, float freqDev, float rxBw, int8_t power, uint8_t currentLimit, uint16_t preambleLength, bool enableOOK) { +int16_t SX1278::beginFSK(float freq, float br, float freqDev, float rxBw, int8_t power, uint16_t preambleLength, bool enableOOK) { // execute common part - int16_t state = SX127x::beginFSK(SX1278_CHIP_VERSION, br, freqDev, rxBw, currentLimit, preambleLength, enableOOK); + int16_t state = SX127x::beginFSK(SX1278_CHIP_VERSION, br, freqDev, rxBw, preambleLength, enableOOK); RADIOLIB_ASSERT(state); // configure settings not accessible by API @@ -48,15 +50,24 @@ int16_t SX1278::beginFSK(float freq, float br, float freqDev, float rxBw, int8_t RADIOLIB_ASSERT(state); state = setOutputPower(power); + RADIOLIB_ASSERT(state); + + state = setDataShaping(RADIOLIB_SHAPING_NONE); + RADIOLIB_ASSERT(state); return(state); } +void SX1278::reset() { + Module::pinMode(_mod->getRst(), OUTPUT); + Module::digitalWrite(_mod->getRst(), LOW); + delay(1); + Module::digitalWrite(_mod->getRst(), HIGH); + delay(5); +} + int16_t SX1278::setFrequency(float freq) { - // check frequency range - if((freq < 137.0) || (freq > 525.0)) { - return(ERR_INVALID_FREQUENCY); - } + RADIOLIB_CHECK_RANGE(freq, 137.0, 525.0, ERR_INVALID_FREQUENCY); // SX1276/77/78 Errata fixes if(getActiveModem() == SX127X_LORA) { @@ -167,15 +178,17 @@ int16_t SX1278::setBandwidth(float bw) { if(state == ERR_NONE) { SX127x::_bw = bw; - // calculate symbol length and set low data rate optimization, if needed - float symbolLength = (float)(uint32_t(1) << SX127x::_sf) / (float)SX127x::_bw; - RADIOLIB_DEBUG_PRINT("Symbol length: "); - RADIOLIB_DEBUG_PRINT(symbolLength); - RADIOLIB_DEBUG_PRINTLN(" ms"); - if(symbolLength >= 16.0) { - state = _mod->SPIsetRegValue(SX1278_REG_MODEM_CONFIG_3, SX1278_LOW_DATA_RATE_OPT_ON, 3, 3); - } else { - state = _mod->SPIsetRegValue(SX1278_REG_MODEM_CONFIG_3, SX1278_LOW_DATA_RATE_OPT_OFF, 3, 3); + // calculate symbol length and set low data rate optimization, if auto-configuration is enabled + if(_ldroAuto) { + float symbolLength = (float)(uint32_t(1) << SX127x::_sf) / (float)SX127x::_bw; + RADIOLIB_DEBUG_PRINT("Symbol length: "); + RADIOLIB_DEBUG_PRINT(symbolLength); + RADIOLIB_DEBUG_PRINTLN(" ms"); + if(symbolLength >= 16.0) { + state = _mod->SPIsetRegValue(SX1278_REG_MODEM_CONFIG_3, SX1278_LOW_DATA_RATE_OPT_ON, 3, 3); + } else { + state = _mod->SPIsetRegValue(SX1278_REG_MODEM_CONFIG_3, SX1278_LOW_DATA_RATE_OPT_OFF, 3, 3); + } } } return(state); @@ -221,15 +234,17 @@ int16_t SX1278::setSpreadingFactor(uint8_t sf) { if(state == ERR_NONE) { SX127x::_sf = sf; - // calculate symbol length and set low data rate optimization, if needed - float symbolLength = (float)(uint32_t(1) << SX127x::_sf) / (float)SX127x::_bw; - RADIOLIB_DEBUG_PRINT("Symbol length: "); - RADIOLIB_DEBUG_PRINT(symbolLength); - RADIOLIB_DEBUG_PRINTLN(" ms"); - if(symbolLength >= 16.0) { - state = _mod->SPIsetRegValue(SX1278_REG_MODEM_CONFIG_3, SX1278_LOW_DATA_RATE_OPT_ON, 3, 3); - } else { - state = _mod->SPIsetRegValue(SX1278_REG_MODEM_CONFIG_3, SX1278_LOW_DATA_RATE_OPT_OFF, 3, 3); + // calculate symbol length and set low data rate optimization, if auto-configuration is enabled + if(_ldroAuto) { + float symbolLength = (float)(uint32_t(1) << SX127x::_sf) / (float)SX127x::_bw; + RADIOLIB_DEBUG_PRINT("Symbol length: "); + RADIOLIB_DEBUG_PRINT(symbolLength); + RADIOLIB_DEBUG_PRINTLN(" ms"); + if(symbolLength >= 16.0) { + state = _mod->SPIsetRegValue(SX1278_REG_MODEM_CONFIG_3, SX1278_LOW_DATA_RATE_OPT_ON, 3, 3); + } else { + state = _mod->SPIsetRegValue(SX1278_REG_MODEM_CONFIG_3, SX1278_LOW_DATA_RATE_OPT_OFF, 3, 3); + } } } return(state); @@ -284,7 +299,7 @@ int16_t SX1278::setOutputPower(int8_t power) { state |= _mod->SPIsetRegValue(SX127X_REG_PA_CONFIG, SX127X_PA_SELECT_RFO, 7, 7); state |= _mod->SPIsetRegValue(SX127X_REG_PA_CONFIG, SX1278_LOW_POWER | (power + 3), 6, 0); state |= _mod->SPIsetRegValue(SX1278_REG_PA_DAC, SX127X_PA_BOOST_OFF, 2, 0); - } else if((power >= 2) && (power <= 17)) { + } else if(power <= 17) { // power is 2 - 17 dBm, enable PA1 + PA2 on PA_BOOST state |= _mod->SPIsetRegValue(SX127X_REG_PA_CONFIG, SX127X_PA_SELECT_BOOST, 7, 7); state |= _mod->SPIsetRegValue(SX127X_REG_PA_CONFIG, SX1278_MAX_POWER | (power - 2), 6, 0); @@ -323,7 +338,7 @@ int16_t SX1278::setGain(uint8_t gain) { return(state); } -int16_t SX1278::setDataShaping(float sh) { +int16_t SX1278::setDataShaping(uint8_t sh) { // check active modem if(getActiveModem() != SX127X_FSK_OOK) { return(ERR_WRONG_MODEM); @@ -336,21 +351,21 @@ int16_t SX1278::setDataShaping(float sh) { // set mode to standby int16_t state = SX127x::standby(); + RADIOLIB_ASSERT(state); // set data shaping - sh *= 10.0; - if(abs(sh - 0.0) <= 0.001) { - state |= _mod->SPIsetRegValue(SX127X_REG_PA_RAMP, SX1278_NO_SHAPING, 6, 5); - } else if(abs(sh - 3.0) <= 0.001) { - state |= _mod->SPIsetRegValue(SX127X_REG_PA_RAMP, SX1278_FSK_GAUSSIAN_0_3, 6, 5); - } else if(abs(sh - 5.0) <= 0.001) { - state |= _mod->SPIsetRegValue(SX127X_REG_PA_RAMP, SX1278_FSK_GAUSSIAN_0_5, 6, 5); - } else if(abs(sh - 10.0) <= 0.001) { - state |= _mod->SPIsetRegValue(SX127X_REG_PA_RAMP, SX1278_FSK_GAUSSIAN_1_0, 6, 5); - } else { - return(ERR_INVALID_DATA_SHAPING); + switch(sh) { + case RADIOLIB_SHAPING_NONE: + return(_mod->SPIsetRegValue(SX127X_REG_OP_MODE, SX1278_NO_SHAPING, 6, 5)); + case RADIOLIB_SHAPING_0_3: + return(_mod->SPIsetRegValue(SX127X_REG_OP_MODE, SX1278_FSK_GAUSSIAN_0_3, 6, 5)); + case RADIOLIB_SHAPING_0_5: + return(_mod->SPIsetRegValue(SX127X_REG_OP_MODE, SX1278_FSK_GAUSSIAN_0_5, 6, 5)); + case RADIOLIB_SHAPING_1_0: + return(_mod->SPIsetRegValue(SX127X_REG_OP_MODE, SX1278_FSK_GAUSSIAN_1_0, 6, 5)); + default: + return(ERR_INVALID_DATA_SHAPING); } - return(state); } int16_t SX1278::setDataShapingOOK(uint8_t sh) { @@ -439,6 +454,28 @@ int16_t SX1278::setCRC(bool enableCRC) { } } +int16_t SX1278::forceLDRO(bool enable) { + if(getActiveModem() != SX127X_LORA) { + return(ERR_WRONG_MODEM); + } + + _ldroAuto = false; + if(enable) { + return(_mod->SPIsetRegValue(SX1278_REG_MODEM_CONFIG_3, SX1278_LOW_DATA_RATE_OPT_ON, 3, 3)); + } else { + return(_mod->SPIsetRegValue(SX1278_REG_MODEM_CONFIG_3, SX1278_LOW_DATA_RATE_OPT_OFF, 3, 3)); + } +} + +int16_t SX1278::autoLDRO() { + if(getActiveModem() != SX127X_LORA) { + return(ERR_WRONG_MODEM); + } + + _ldroAuto = true; + return(ERR_NONE); +} + int16_t SX1278::setBandwidthRaw(uint8_t newBandwidth) { // set mode to standby int16_t state = SX127x::standby(); @@ -483,6 +520,12 @@ int16_t SX1278::configFSK() { // set fast PLL hop state = _mod->SPIsetRegValue(SX1278_REG_PLL_HOP, SX127X_FAST_HOP_ON, 7, 7); + RADIOLIB_ASSERT(state); + + // set Gauss filter BT product to 0.5 + state = _mod->SPIsetRegValue(SX127X_REG_PA_RAMP, SX1278_FSK_GAUSSIAN_0_5, 6, 5); return(state); } + +#endif diff --git a/src/modules/SX127x/SX1278.h b/src/modules/SX127x/SX1278.h index c081e76c..cba8c635 100644 --- a/src/modules/SX127x/SX1278.h +++ b/src/modules/SX127x/SX1278.h @@ -1,7 +1,10 @@ -#ifndef _RADIOLIB_SX1278_H +#if !defined(_RADIOLIB_SX1278_H) #define _RADIOLIB_SX1278_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SX127X) + #include "../../Module.h" #include "SX127x.h" @@ -127,9 +130,6 @@ class SX1278: public SX127x { \param power Transmission output power in dBm. Allowed values range from 2 to 17 dBm. - \param currentLimit Trim value for OCP (over current protection) in mA. Can be set to multiplies of 5 in range 45 to 120 mA and to multiples of 10 in range 120 to 240 mA. - Set to 0 to disable OCP (not recommended). - \param preambleLength Length of %LoRa transmission preamble in symbols. The actual preamble length is 4.25 symbols longer than the set number. Allowed values range from 6 to 65535. @@ -138,7 +138,7 @@ class SX1278: public SX127x { \returns \ref status_codes */ - int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX127X_SYNC_WORD, int8_t power = 17, uint8_t currentLimit = 100, uint16_t preambleLength = 8, uint8_t gain = 0); + int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX127X_SYNC_WORD, int8_t power = 10, uint16_t preambleLength = 8, uint8_t gain = 0); /*! \brief FSK modem initialization method. Must be called at least once from Arduino sketch to initialize the module. @@ -154,16 +154,18 @@ class SX1278: public SX127x { \param power Transmission output power in dBm. Allowed values range from 2 to 17 dBm. - \param currentLimit Trim value for OCP (over current protection) in mA. Can be set to multiplies of 5 in range 45 to 120 mA and to multiples of 10 in range 120 to 240 mA. - Set to 0 to disable OCP (not recommended). - \param preambleLength Length of FSK preamble in bits. \param enableOOK Use OOK modulation instead of FSK. \returns \ref status_codes */ - int16_t beginFSK(float freq = 434.0, float br = 48.0, float freqDev = 50.0, float rxBw = 125.0, int8_t power = 13, uint8_t currentLimit = 100, uint16_t preambleLength = 16, bool enableOOK = false); + int16_t beginFSK(float freq = 434.0, float br = 48.0, float freqDev = 50.0, float rxBw = 125.0, int8_t power = 10, uint16_t preambleLength = 16, bool enableOOK = false); + + /*! + \brief Reset method. Will reset the chip to the default state using RST pin. + */ + void reset() override; // configuration methods @@ -223,14 +225,14 @@ class SX1278: public SX127x { int16_t setGain(uint8_t gain); /*! - \brief Sets Gaussian filter bandwidth-time product that will be used for data shaping. - Allowed values are 0.3, 0.5 or 1.0. Set to 0 to disable data shaping. Only available in FSK mode with FSK modulation. + \brief Sets Gaussian filter bandwidth-time product that will be used for data shaping. Only available in FSK mode with FSK modulation. + Allowed values are RADIOLIB_SHAPING_0_3, RADIOLIB_SHAPING_0_5 or RADIOLIB_SHAPING_1_0. Set to RADIOLIB_SHAPING_NONE to disable data shaping. \param sh Gaussian shaping bandwidth-time product that will be used for data shaping \returns \ref status_codes */ - int16_t setDataShaping(float sh); + int16_t setDataShaping(uint8_t sh) override; /*! \brief Sets filter cutoff frequency that will be used for data shaping. @@ -259,6 +261,24 @@ class SX1278: public SX127x { */ int16_t setCRC(bool enableCRC); + /*! + \brief Forces LoRa low data rate optimization. Only available in LoRa mode. After calling this method, LDRO will always be set to + the provided value, regardless of symbol length. To re-enable automatic LDRO configuration, call SX1278::autoLDRO() + + \param enable Force LDRO to be always enabled (true) or disabled (false). + + \returns \ref status_codes + */ + int16_t forceLDRO(bool enable); + + /*! + \brief Re-enables automatic LDRO configuration. Only available in LoRa mode. After calling this method, LDRO will be enabled automatically + when symbol length exceeds 16 ms. + + \returns \ref status_codes + */ + int16_t autoLDRO(); + #ifndef RADIOLIB_GODMODE protected: #endif @@ -271,7 +291,11 @@ class SX1278: public SX127x { #ifndef RADIOLIB_GODMODE private: #endif + bool _ldroAuto = true; + bool _ldroEnabled = false; }; #endif + +#endif diff --git a/src/modules/SX127x/SX1279.cpp b/src/modules/SX127x/SX1279.cpp index 3468b0b1..21d1f598 100644 --- a/src/modules/SX127x/SX1279.cpp +++ b/src/modules/SX127x/SX1279.cpp @@ -1,12 +1,13 @@ #include "SX1279.h" +#if !defined(RADIOLIB_EXCLUDE_SX127X) SX1279::SX1279(Module* mod) : SX1278(mod) { } -int16_t SX1279::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint8_t currentLimit, uint16_t preambleLength, uint8_t gain) { +int16_t SX1279::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint16_t preambleLength, uint8_t gain) { // execute common part - int16_t state = SX127x::begin(SX1278_CHIP_VERSION, syncWord, currentLimit, preambleLength); + int16_t state = SX127x::begin(SX1278_CHIP_VERSION, syncWord, preambleLength); RADIOLIB_ASSERT(state); // configure settings not accessible by API @@ -30,16 +31,16 @@ int16_t SX1279::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t sync RADIOLIB_ASSERT(state); state = setGain(gain); + RADIOLIB_ASSERT(state); return(state); } int16_t SX1279::setFrequency(float freq) { - // check frequency range - if((freq < 137.0) || (freq > 960.0)) { - return(ERR_INVALID_FREQUENCY); - } + RADIOLIB_CHECK_RANGE(freq, 137.0, 960.0, ERR_INVALID_FREQUENCY); // set frequency return(SX127x::setFrequencyRaw(freq)); } + +#endif diff --git a/src/modules/SX127x/SX1279.h b/src/modules/SX127x/SX1279.h index f0953ecd..27220119 100644 --- a/src/modules/SX127x/SX1279.h +++ b/src/modules/SX127x/SX1279.h @@ -1,7 +1,10 @@ -#ifndef _RADIOLIB_SX1279_H +#if !defined(_RADIOLIB_SX1279_H) #define _RADIOLIB_SX1279_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SX127X) + #include "SX1278.h" /*! @@ -38,9 +41,6 @@ class SX1279: public SX1278 { \param power Transmission output power in dBm. Allowed values range from 2 to 17 dBm. - \param currentLimit Trim value for OCP (over current protection) in mA. Can be set to multiplies of 5 in range 45 to 120 mA and to multiples of 10 in range 120 to 240 mA. - Set to 0 to disable OCP (not recommended). - \param preambleLength Length of %LoRa transmission preamble in symbols. The actual preamble length is 4.25 symbols longer than the set number. Allowed values range from 6 to 65535. @@ -49,7 +49,7 @@ class SX1279: public SX1278 { \returns \ref status_codes */ - int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX127X_SYNC_WORD, int8_t power = 17, uint8_t currentLimit = 100, uint16_t preambleLength = 8, uint8_t gain = 0); + int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX127X_SYNC_WORD, int8_t power = 10, uint16_t preambleLength = 8, uint8_t gain = 0); // configuration methods @@ -69,3 +69,5 @@ class SX1279: public SX1278 { }; #endif + +#endif diff --git a/src/modules/SX127x/SX127x.cpp b/src/modules/SX127x/SX127x.cpp index 73d796bf..2890ff5f 100644 --- a/src/modules/SX127x/SX127x.cpp +++ b/src/modules/SX127x/SX127x.cpp @@ -1,11 +1,11 @@ #include "SX127x.h" +#if !defined(RADIOLIB_EXCLUDE_SX127X) SX127x::SX127x(Module* mod) : PhysicalLayer(SX127X_FREQUENCY_STEP_SIZE, SX127X_MAX_PACKET_LENGTH) { _mod = mod; - _packetLengthQueried = false; } -int16_t SX127x::begin(uint8_t chipVersion, uint8_t syncWord, uint8_t currentLimit, uint16_t preambleLength) { +int16_t SX127x::begin(uint8_t chipVersion, uint8_t syncWord, uint16_t preambleLength) { // set module properties _mod->init(RADIOLIB_USE_SPI); Module::pinMode(_mod->getIrq(), INPUT); @@ -14,7 +14,7 @@ int16_t SX127x::begin(uint8_t chipVersion, uint8_t syncWord, uint8_t currentLimi // try to find the SX127x chip if(!SX127x::findChip(chipVersion)) { RADIOLIB_DEBUG_PRINTLN(F("No SX127x found!")); - _mod->term(); + _mod->term(RADIOLIB_USE_SPI); return(ERR_CHIP_NOT_FOUND); } else { RADIOLIB_DEBUG_PRINTLN(F("Found SX127x!")); @@ -36,31 +36,28 @@ int16_t SX127x::begin(uint8_t chipVersion, uint8_t syncWord, uint8_t currentLimi RADIOLIB_ASSERT(state); // set over current protection - state = SX127x::setCurrentLimit(currentLimit); + state = SX127x::setCurrentLimit(60); RADIOLIB_ASSERT(state); // set preamble length state = SX127x::setPreambleLength(preambleLength); RADIOLIB_ASSERT(state); - // initalize internal variables + // initialize internal variables _dataRate = 0.0; return(state); } -int16_t SX127x::beginFSK(uint8_t chipVersion, float br, float freqDev, float rxBw, uint8_t currentLimit, uint16_t preambleLength, bool enableOOK) { +int16_t SX127x::beginFSK(uint8_t chipVersion, float br, float freqDev, float rxBw, uint16_t preambleLength, bool enableOOK) { // set module properties _mod->init(RADIOLIB_USE_SPI); Module::pinMode(_mod->getIrq(), INPUT); - // reset the module - reset(); - // try to find the SX127x chip if(!SX127x::findChip(chipVersion)) { RADIOLIB_DEBUG_PRINTLN(F("No SX127x found!")); - _mod->term(); + _mod->term(RADIOLIB_USE_SPI); return(ERR_CHIP_NOT_FOUND); } else { RADIOLIB_DEBUG_PRINTLN(F("Found SX127x!")); @@ -91,15 +88,15 @@ int16_t SX127x::beginFSK(uint8_t chipVersion, float br, float freqDev, float rxB RADIOLIB_ASSERT(state); // set over current protection - state = SX127x::setCurrentLimit(currentLimit); + state = SX127x::setCurrentLimit(60); RADIOLIB_ASSERT(state); // set preamble length state = SX127x::setPreambleLength(preambleLength); RADIOLIB_ASSERT(state); - // default sync word value 0x2D01 is the same as the default in LowPowerLab RFM69 library - uint8_t syncWord[] = {0x2D, 0x01}; + // set default sync word + uint8_t syncWord[] = {0x12, 0xAD}; state = setSyncWord(syncWord, 2); RADIOLIB_ASSERT(state); @@ -112,7 +109,7 @@ int16_t SX127x::beginFSK(uint8_t chipVersion, float br, float freqDev, float rxB RADIOLIB_ASSERT(state); // set default encoding - state = setEncoding(0); + state = setEncoding(RADIOLIB_ENCODING_NRZ); RADIOLIB_ASSERT(state); // set default packet length mode @@ -121,17 +118,10 @@ int16_t SX127x::beginFSK(uint8_t chipVersion, float br, float freqDev, float rxB return(state); } -void SX127x::reset() { - Module::pinMode(_mod->getRst(), OUTPUT); - Module::digitalWrite(_mod->getRst(), LOW); - delayMicroseconds(100); - Module::digitalWrite(_mod->getRst(), HIGH); - delay(5); -} - int16_t SX127x::transmit(uint8_t* data, size_t len, uint8_t addr) { // set mode to standby int16_t state = setMode(SX127X_STANDBY); + RADIOLIB_ASSERT(state); int16_t modem = getActiveModem(); uint32_t start = 0; @@ -155,6 +145,7 @@ int16_t SX127x::transmit(uint8_t* data, size_t len, uint8_t addr) { // wait for packet transmission or timeout start = micros(); while(!digitalRead(_mod->getIrq())) { + yield(); if(micros() - start > timeout) { clearIRQFlags(); return(ERR_TX_TIMEOUT); @@ -172,6 +163,7 @@ int16_t SX127x::transmit(uint8_t* data, size_t len, uint8_t addr) { // wait for transmission end or timeout start = micros(); while(!digitalRead(_mod->getIrq())) { + yield(); if(micros() - start > timeout) { clearIRQFlags(); standby(); @@ -196,6 +188,7 @@ int16_t SX127x::transmit(uint8_t* data, size_t len, uint8_t addr) { int16_t SX127x::receive(uint8_t* data, size_t len) { // set mode to standby int16_t state = setMode(SX127X_STANDBY); + RADIOLIB_ASSERT(state); int16_t modem = getActiveModem(); if(modem == SX127X_LORA) { @@ -205,6 +198,7 @@ int16_t SX127x::receive(uint8_t* data, size_t len) { // wait for packet reception or timeout (100 LoRa symbols) while(!digitalRead(_mod->getIrq())) { + yield(); if(digitalRead(_mod->getGpio())) { clearIRQFlags(); return(ERR_RX_TIMEOUT); @@ -222,6 +216,7 @@ int16_t SX127x::receive(uint8_t* data, size_t len) { // wait for packet reception or timeout uint32_t start = micros(); while(!digitalRead(_mod->getIrq())) { + yield(); if(micros() - start > timeout) { clearIRQFlags(); return(ERR_RX_TIMEOUT); @@ -252,12 +247,16 @@ int16_t SX127x::scanChannel() { // clear interrupt flags clearIRQFlags(); + // set RF switch (if present) + _mod->setRfSwitchState(HIGH, LOW); + // set mode to CAD state = setMode(SX127X_CAD); RADIOLIB_ASSERT(state); // wait for channel activity detected or timeout while(!digitalRead(_mod->getIrq())) { + yield(); if(digitalRead(_mod->getGpio())) { clearIRQFlags(); return(PREAMBLE_DETECTED); @@ -271,26 +270,35 @@ int16_t SX127x::scanChannel() { } int16_t SX127x::sleep() { + // set RF switch (if present) + _mod->setRfSwitchState(LOW, LOW); + // set mode to sleep return(setMode(SX127X_SLEEP)); } int16_t SX127x::standby() { + // set RF switch (if present) + _mod->setRfSwitchState(LOW, LOW); + // set mode to standby return(setMode(SX127X_STANDBY)); } -int16_t SX127x::transmitDirect(uint32_t FRF) { +int16_t SX127x::transmitDirect(uint32_t frf) { // check modem if(getActiveModem() != SX127X_FSK_OOK) { return(ERR_WRONG_MODEM); } + // set RF switch (if present) + _mod->setRfSwitchState(LOW, HIGH); + // user requested to start transmitting immediately (required for RTTY) - if(FRF != 0) { - _mod->SPIwriteRegister(SX127X_REG_FRF_MSB, (FRF & 0xFF0000) >> 16); - _mod->SPIwriteRegister(SX127X_REG_FRF_MID, (FRF & 0x00FF00) >> 8); - _mod->SPIwriteRegister(SX127X_REG_FRF_LSB, FRF & 0x0000FF); + if(frf != 0) { + _mod->SPIwriteRegister(SX127X_REG_FRF_MSB, (frf & 0xFF0000) >> 16); + _mod->SPIwriteRegister(SX127X_REG_FRF_MID, (frf & 0x00FF00) >> 8); + _mod->SPIwriteRegister(SX127X_REG_FRF_LSB, frf & 0x0000FF); return(setMode(SX127X_TX)); } @@ -309,6 +317,9 @@ int16_t SX127x::receiveDirect() { return(ERR_WRONG_MODEM); } + // set RF switch (if present) + _mod->setRfSwitchState(HIGH, LOW); + // activate direct mode int16_t state = directMode(); RADIOLIB_ASSERT(state); @@ -342,11 +353,12 @@ int16_t SX127x::packetMode() { int16_t SX127x::startReceive(uint8_t len, uint8_t mode) { // set mode to standby int16_t state = setMode(SX127X_STANDBY); + RADIOLIB_ASSERT(state); int16_t modem = getActiveModem(); if(modem == SX127X_LORA) { // set DIO pin mapping - state |= _mod->SPIsetRegValue(SX127X_REG_DIO_MAPPING_1, SX127X_DIO0_RX_DONE | SX127X_DIO1_RX_TIMEOUT, 7, 4); + state = _mod->SPIsetRegValue(SX127X_REG_DIO_MAPPING_1, SX127X_DIO0_RX_DONE | SX127X_DIO1_RX_TIMEOUT, 7, 4); // set expected packet length for SF6 if(_sf == 6) { @@ -363,7 +375,8 @@ int16_t SX127x::startReceive(uint8_t len, uint8_t mode) { } else if(modem == SX127X_FSK_OOK) { // set DIO pin mapping - state |= _mod->SPIsetRegValue(SX127X_REG_DIO_MAPPING_1, SX127X_DIO0_PACK_PAYLOAD_READY, 7, 6); + state = _mod->SPIsetRegValue(SX127X_REG_DIO_MAPPING_1, SX127X_DIO0_PACK_PAYLOAD_READY, 7, 6); + RADIOLIB_ASSERT(state); // clear interrupt flags clearIRQFlags(); @@ -374,30 +387,33 @@ int16_t SX127x::startReceive(uint8_t len, uint8_t mode) { } } + // set RF switch (if present) + _mod->setRfSwitchState(HIGH, LOW); + // set mode to receive return(setMode(mode)); } void SX127x::setDio0Action(void (*func)(void)) { - attachInterrupt(digitalPinToInterrupt(_mod->getIrq()), func, RISING); + attachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getIrq()), func, RISING); } void SX127x::clearDio0Action() { - detachInterrupt(digitalPinToInterrupt(_mod->getIrq())); + detachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getIrq())); } void SX127x::setDio1Action(void (*func)(void)) { - if(_mod->getGpio() != NC) { + if(_mod->getGpio() != RADIOLIB_NC) { return; } - attachInterrupt(digitalPinToInterrupt(_mod->getGpio()), func, RISING); + attachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getGpio()), func, RISING); } void SX127x::clearDio1Action() { - if(_mod->getGpio() != NC) { + if(_mod->getGpio() != RADIOLIB_NC) { return; } - detachInterrupt(digitalPinToInterrupt(_mod->getGpio())); + detachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getGpio())); } int16_t SX127x::startTransmit(uint8_t* data, size_t len, uint8_t addr) { @@ -424,15 +440,6 @@ int16_t SX127x::startTransmit(uint8_t* data, size_t len, uint8_t addr) { state |= _mod->SPIsetRegValue(SX127X_REG_FIFO_TX_BASE_ADDR, SX127X_FIFO_TX_BASE_ADDR_MAX); state |= _mod->SPIsetRegValue(SX127X_REG_FIFO_ADDR_PTR, SX127X_FIFO_TX_BASE_ADDR_MAX); - // write packet to FIFO - _mod->SPIwriteRegisterBurst(SX127X_REG_FIFO, data, len); - - // start transmission - state |= setMode(SX127X_TX); - RADIOLIB_ASSERT(state); - - return(ERR_NONE); - } else if(modem == SX127X_FSK_OOK) { // check packet length if(len >= SX127X_MAX_PACKET_LENGTH_FSK) { @@ -453,18 +460,19 @@ int16_t SX127x::startTransmit(uint8_t* data, size_t len, uint8_t addr) { if((filter == SX127X_ADDRESS_FILTERING_NODE) || (filter == SX127X_ADDRESS_FILTERING_NODE_BROADCAST)) { _mod->SPIwriteRegister(SX127X_REG_FIFO, addr); } - - // write packet to FIFO - _mod->SPIwriteRegisterBurst(SX127X_REG_FIFO, data, len); - - // start transmission - state |= setMode(SX127X_TX); - RADIOLIB_ASSERT(state); - - return(ERR_NONE); } - return(ERR_UNKNOWN); + // write packet to FIFO + _mod->SPIwriteRegisterBurst(SX127X_REG_FIFO, data, len); + + // set RF switch (if present) + _mod->setRfSwitchState(LOW, HIGH); + + // start transmission + state |= setMode(SX127X_TX); + RADIOLIB_ASSERT(state); + + return(ERR_NONE); } int16_t SX127x::readData(uint8_t* data, size_t len) { @@ -646,7 +654,7 @@ float SX127x::getSNR() { return(rawSNR / 4.0); } -float SX127x::getDataRate() { +float SX127x::getDataRate() const { return(_dataRate); } @@ -658,13 +666,9 @@ int16_t SX127x::setBitRate(float br) { // check allowed bit rate if(_ook) { - if((br < 1.2) || (br > 32.768)) { - return(ERR_INVALID_BIT_RATE); - } + RADIOLIB_CHECK_RANGE(br, 1.2, 32.768, ERR_INVALID_BIT_RATE); } else { - if((br < 1.2) || (br > 300.0)) { - return(ERR_INVALID_BIT_RATE); - } + RADIOLIB_CHECK_RANGE(br, 1.2, 300.0, ERR_INVALID_BIT_RATE); } // set mode to STANDBY @@ -676,7 +680,7 @@ int16_t SX127x::setBitRate(float br) { state = _mod->SPIsetRegValue(SX127X_REG_BITRATE_MSB, (bitRate & 0xFF00) >> 8, 7, 0); state |= _mod->SPIsetRegValue(SX127X_REG_BITRATE_LSB, bitRate & 0x00FF, 7, 0); - // TODO fractional part of bit rate setting (not in OOK) + /// \todo fractional part of bit rate setting (not in OOK) if(state == ERR_NONE) { SX127x::_br = br; } @@ -712,10 +716,7 @@ int16_t SX127x::setRxBandwidth(float rxBw) { return(ERR_WRONG_MODEM); } - // check allowed bandwidth values - if(!((rxBw >= 2.6) && (rxBw <= 250.0))) { - return(ERR_INVALID_RX_BANDWIDTH); - } + RADIOLIB_CHECK_RANGE(rxBw, 2.6, 250.0, ERR_INVALID_RX_BANDWIDTH); // set mode to STANDBY int16_t state = setMode(SX127X_STANDBY); @@ -749,10 +750,7 @@ int16_t SX127x::setSyncWord(uint8_t* syncWord, size_t len) { return(ERR_WRONG_MODEM); } - // check constraints - if((len > 8) || (len < 1)) { - return(ERR_INVALID_SYNC_WORD); - } + RADIOLIB_CHECK_RANGE(len, 1, 8, ERR_INVALID_SYNC_WORD); // sync word must not contain value 0x00 for(uint8_t i = 0; i < len; i++) { @@ -898,9 +896,7 @@ int16_t SX127x::setRSSIConfig(uint8_t smoothingSamples, int8_t offset) { return(ERR_INVALID_NUM_SAMPLES); } - if(!((offset >= -16) && (offset <= 15))) { - return(ERR_INVALID_RSSI_OFFSET); - } + RADIOLIB_CHECK_RANGE(offset, -16, 15, ERR_INVALID_RSSI_OFFSET); // set new register values state = _mod->SPIsetRegValue(SX127X_REG_RSSI_CONFIG, offset, 7, 3); @@ -916,17 +912,98 @@ int16_t SX127x::setEncoding(uint8_t encoding) { // set encoding switch(encoding) { - case 0: + case RADIOLIB_ENCODING_NRZ: return(_mod->SPIsetRegValue(SX127X_REG_PACKET_CONFIG_1, SX127X_DC_FREE_NONE, 6, 5)); - case 1: + case RADIOLIB_ENCODING_MANCHESTER: return(_mod->SPIsetRegValue(SX127X_REG_PACKET_CONFIG_1, SX127X_DC_FREE_MANCHESTER, 6, 5)); - case 2: + case RADIOLIB_ENCODING_WHITENING: return(_mod->SPIsetRegValue(SX127X_REG_PACKET_CONFIG_1, SX127X_DC_FREE_WHITENING, 6, 5)); default: return(ERR_INVALID_ENCODING); } } +uint16_t SX127x::getIRQFlags() { + // check active modem + if(getActiveModem() == SX127X_LORA) { + // LoRa, just 8-bit value + return((uint16_t)_mod->SPIreadRegister(SX127X_REG_IRQ_FLAGS)); + + } else { + // FSK, the IRQ flags are 16 bits in total + uint16_t flags = ((uint16_t)_mod->SPIreadRegister(SX127X_REG_IRQ_FLAGS_2)) << 8; + flags |= (uint16_t)_mod->SPIreadRegister(SX127X_REG_IRQ_FLAGS_1); + return(flags); + } + +} + +uint8_t SX127x::getModemStatus() { + // check active modem + if(getActiveModem() != SX127X_LORA) { + return(0x00); + } + + // read the register + return(_mod->SPIreadRegister(SX127X_REG_MODEM_STAT)); +} + +void SX127x::setRfSwitchPins(RADIOLIB_PIN_TYPE rxEn, RADIOLIB_PIN_TYPE txEn) { + _mod->setRfSwitchPins(rxEn, txEn); +} + +int8_t SX127x::getTempRaw() { + int8_t temp = 0; + uint8_t previousOpMode; + uint8_t ival; + + // save current Op Mode + previousOpMode = _mod->SPIgetRegValue(SX127X_REG_OP_MODE); + + // check if we need to step out of LoRa mode first + if ((previousOpMode & SX127X_LORA) == SX127X_LORA) { + _mod->SPIsetRegValue(SX127X_REG_OP_MODE, (SX127X_LORA | SX127X_SLEEP)); + } + + // put device in FSK sleep + _mod->SPIsetRegValue(SX127X_REG_OP_MODE, (SX127X_FSK_OOK | SX127X_SLEEP)); + + // put device in FSK RxSynth + _mod->SPIsetRegValue(SX127X_REG_OP_MODE, (SX127X_FSK_OOK | SX127X_FSRX)); + + // enable temperature reading + _mod->SPIsetRegValue(SX127X_REG_IMAGE_CAL, SX127X_TEMP_MONITOR_ON, 0, 0); + + // wait + delayMicroseconds(200); + + // disable temperature reading + _mod->SPIsetRegValue(SX127X_REG_IMAGE_CAL, SX127X_TEMP_MONITOR_OFF, 0, 0); + + // put device in FSK sleep + _mod->SPIsetRegValue(SX127X_REG_OP_MODE, (SX127X_FSK_OOK | SX127X_SLEEP)); + + // read temperature + ival = _mod->SPIgetRegValue(SX127X_REG_TEMP); + + // convert very raw value + if ((ival & 0x80) == 0x80) { + temp = 255 - ival; + } else { + temp = -1 * ival; + } + + // check if we need to step back into LoRa mode + if ((previousOpMode & SX127X_LORA) == SX127X_LORA) { + _mod->SPIsetRegValue(SX127X_REG_OP_MODE, (SX127X_LORA | SX127X_SLEEP)); + } + + // reload previous Op Mode + _mod->SPIsetRegValue(SX127X_REG_OP_MODE, previousOpMode); + + return(temp); +} + int16_t SX127x::config() { // turn off frequency hopping int16_t state = _mod->SPIsetRegValue(SX127X_REG_HOP_PERIOD, SX127X_HOP_PERIOD_OFF); @@ -1010,13 +1087,13 @@ bool SX127x::findChip(uint8_t ver) { RADIOLIB_DEBUG_PRINT(i + 1); RADIOLIB_DEBUG_PRINT(F(" of 10 tries) SX127X_REG_VERSION == ")); - char buffHex[5]; + char buffHex[12]; sprintf(buffHex, "0x%02X", version); RADIOLIB_DEBUG_PRINT(buffHex); RADIOLIB_DEBUG_PRINT(F(", expected 0x00")); RADIOLIB_DEBUG_PRINTLN(ver, HEX); #endif - delay(1000); + delay(10); i++; } } @@ -1061,27 +1138,4 @@ void SX127x::clearFIFO(size_t count) { } } -#ifdef RADIOLIB_DEBUG -void SX127x::regDump() { - RADIOLIB_DEBUG_PRINTLN(); - RADIOLIB_DEBUG_PRINTLN(F("ADDR\tVALUE")); - for(uint16_t addr = 0x01; addr <= 0x70; addr++) { - if(addr <= 0x0F) { - RADIOLIB_DEBUG_PRINT(F("0x0")); - } else { - RADIOLIB_DEBUG_PRINT(F("0x")); - } - RADIOLIB_DEBUG_PRINT(addr, HEX); - RADIOLIB_DEBUG_PRINT('\t'); - uint8_t val = _mod->SPIreadRegister(addr); - if(val <= 0x0F) { - RADIOLIB_DEBUG_PRINT(F("0x0")); - } else { - RADIOLIB_DEBUG_PRINT(F("0x")); - } - RADIOLIB_DEBUG_PRINTLN(val, HEX); - - delay(50); - } -} #endif diff --git a/src/modules/SX127x/SX127x.h b/src/modules/SX127x/SX127x.h index d48e9e30..61953144 100644 --- a/src/modules/SX127x/SX127x.h +++ b/src/modules/SX127x/SX127x.h @@ -1,7 +1,10 @@ -#ifndef _RADIOLIB_SX127X_H +#if !defined(_RADIOLIB_SX127X_H) #define _RADIOLIB_SX127X_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SX127X) + #include "../../Module.h" #include "../../protocols/PhysicalLayer/PhysicalLayer.h" @@ -459,8 +462,8 @@ #define SX127X_TEMP_THRESHOLD_10_DEG_C 0b00000010 // 2 1 10 deg. C (default) #define SX127X_TEMP_THRESHOLD_15_DEG_C 0b00000100 // 2 1 15 deg. C #define SX127X_TEMP_THRESHOLD_20_DEG_C 0b00000110 // 2 1 20 deg. C -#define SX127X_TEMP_MONITOR_OFF 0b00000000 // 0 0 temperature monitoring disabled (default) -#define SX127X_TEMP_MONITOR_ON 0b00000001 // 0 0 temperature monitoring enabled +#define SX127X_TEMP_MONITOR_ON 0b00000000 // 0 0 temperature monitoring enabled (default) +#define SX127X_TEMP_MONITOR_OFF 0b00000001 // 0 0 temperature monitoring disabled // SX127X_REG_LOW_BAT #define SX127X_LOW_BAT_OFF 0b00000000 // 3 3 low battery detector disabled @@ -480,7 +483,7 @@ #define SX127X_FLAG_TX_READY 0b00100000 // 5 5 transmission ready (after PA ramp-up) #define SX127X_FLAG_PLL_LOCK 0b00010000 // 4 4 PLL locked #define SX127X_FLAG_RSSI 0b00001000 // 3 3 RSSI value exceeds RSSI threshold -#define SX127X_FLAG_TIMEOUT 0b00000100 // 2 2 timeout occured +#define SX127X_FLAG_TIMEOUT 0b00000100 // 2 2 timeout occurred #define SX127X_FLAG_PREAMBLE_DETECT 0b00000010 // 1 1 valid preamble was detected #define SX127X_FLAG_SYNC_ADDRESS_MATCH 0b00000001 // 0 0 sync address matched @@ -488,7 +491,7 @@ #define SX127X_FLAG_FIFO_FULL 0b10000000 // 7 7 FIFO is full #define SX127X_FLAG_FIFO_EMPTY 0b01000000 // 6 6 FIFO is empty #define SX127X_FLAG_FIFO_LEVEL 0b00100000 // 5 5 number of bytes in FIFO exceeds FIFO_THRESHOLD -#define SX127X_FLAG_FIFO_OVERRUN 0b00010000 // 4 4 FIFO overrun occured +#define SX127X_FLAG_FIFO_OVERRUN 0b00010000 // 4 4 FIFO overrun occurred #define SX127X_FLAG_PACKET_SENT 0b00001000 // 3 3 packet was successfully sent #define SX127X_FLAG_PAYLOAD_READY 0b00000100 // 2 2 packet was successfully received #define SX127X_FLAG_CRC_OK 0b00000010 // 1 1 CRC check passed @@ -556,18 +559,16 @@ class SX127x: public PhysicalLayer { \param syncWord %LoRa sync word. - \param currentLimit Trim value for OCP (over current protection) in mA. - \param preambleLength Length of %LoRa transmission preamble in symbols. \returns \ref status_codes */ - int16_t begin(uint8_t chipVersion, uint8_t syncWord, uint8_t currentLimit, uint16_t preambleLength); + int16_t begin(uint8_t chipVersion, uint8_t syncWord, uint16_t preambleLength); /*! - \brief Reset method. Will reset the chip to the default state using RST pin. + \brief Reset method. Will reset the chip to the default state using RST pin. Declared pure virtual since SX1272 and SX1278 implementations differ. */ - void reset(); + virtual void reset() = 0; /*! \brief Initialization method for FSK modem. Will be called with appropriate parameters when calling FSK initialization method from derived class. @@ -580,15 +581,13 @@ class SX127x: public PhysicalLayer { \param rxBw Receiver bandwidth in kHz. - \param currentLimit Trim value for OCP (over current protection) in mA. - \param preambleLength Length of FSK preamble in bits. \param enableOOK Flag to specify OOK mode. This modulation is similar to FSK. \returns \ref status_codes */ - int16_t beginFSK(uint8_t chipVersion, float br, float freqDev, float rxBw, uint8_t currentLimit, uint16_t preambleLength, bool enableOOK); + int16_t beginFSK(uint8_t chipVersion, float br, float freqDev, float rxBw, uint16_t preambleLength, bool enableOOK); /*! \brief Binary transmit method. Will transmit arbitrary binary data up to 255 bytes long using %LoRa or up to 63 bytes using FSK modem. @@ -602,7 +601,7 @@ class SX127x: public PhysicalLayer { \returns \ref status_codes */ - int16_t transmit(uint8_t* data, size_t len, uint8_t addr = 0); + int16_t transmit(uint8_t* data, size_t len, uint8_t addr = 0) override; /*! \brief Binary receive method. Will attempt to receive arbitrary binary data up to 255 bytes long using %LoRa or up to 63 bytes using FSK modem. @@ -614,7 +613,7 @@ class SX127x: public PhysicalLayer { \returns \ref status_codes */ - int16_t receive(uint8_t* data, size_t len); + int16_t receive(uint8_t* data, size_t len) override; /*! \brief Performs scan for valid %LoRa preamble in the current channel. @@ -636,17 +635,17 @@ class SX127x: public PhysicalLayer { \returns \ref status_codes */ - int16_t standby(); + int16_t standby() override; /*! \brief Enables direct transmission mode on pins DIO1 (clock) and DIO2 (data). While in direct mode, the module will not be able to transmit or receive packets. Can only be activated in FSK mode. - \param FRF 24-bit raw frequency value to start transmitting at. Required for quick frequency shifts in RTTY. + \param frf 24-bit raw frequency value to start transmitting at. Required for quick frequency shifts in RTTY. \returns \ref status_codes */ - int16_t transmitDirect(uint32_t FRF = 0); + int16_t transmitDirect(uint32_t frf = 0) override; /*! \brief Enables direct reception mode on pins DIO1 (clock) and DIO2 (data). @@ -654,7 +653,7 @@ class SX127x: public PhysicalLayer { \returns \ref status_codes */ - int16_t receiveDirect(); + int16_t receiveDirect() override; /*! \brief Disables direct mode and enables packet mode, allowing the module to receive packets. Can only be activated in FSK mode. @@ -663,7 +662,6 @@ class SX127x: public PhysicalLayer { */ int16_t packetMode(); - // interrupt methods /*! @@ -701,7 +699,7 @@ class SX127x: public PhysicalLayer { \returns \ref status_codes */ - int16_t startTransmit(uint8_t* data, size_t len, uint8_t addr = 0); + int16_t startTransmit(uint8_t* data, size_t len, uint8_t addr = 0) override; /*! \brief Interrupt-driven receive method. DIO0 will be activated when full valid packet is received. @@ -723,7 +721,7 @@ class SX127x: public PhysicalLayer { \returns \ref status_codes */ - int16_t readData(uint8_t* data, size_t len); + int16_t readData(uint8_t* data, size_t len) override; // configuration methods @@ -776,7 +774,7 @@ class SX127x: public PhysicalLayer { \returns Last packet data rate in bps (bits per second). */ - float getDataRate(); + float getDataRate() const; /*! \brief Sets FSK bit rate. Allowed values range from 1.2 to 300 kbps. Only available in FSK mode. @@ -794,7 +792,7 @@ class SX127x: public PhysicalLayer { \returns \ref status_codes */ - int16_t setFrequencyDeviation(float freqDev); + int16_t setFrequencyDeviation(float freqDev) override; /*! \brief Sets FSK receiver bandwidth. Allowed values range from 2.6 to 250 kHz. Only available in FSK mode. @@ -857,7 +855,7 @@ class SX127x: public PhysicalLayer { \returns Length of last received packet in bytes. */ - size_t getPacketLength(bool update = true); + size_t getPacketLength(bool update = true) override; /*! \brief Set modem in fixed packet length mode. Available in FSK mode only. @@ -880,7 +878,7 @@ class SX127x: public PhysicalLayer { /*! \brief Sets RSSI measurement configuration in FSK mode. - \param smoothingSamples Number of samples taken to avergae the RSSI result. + \param smoothingSamples Number of samples taken to average the RSSI result. numSamples = 2 ^ (1 + smoothingSamples), allowed values are in range 0 (2 samples) - 7 (256 samples) \param offset Signed RSSI offset that will be automatically compensated. 1 dB per LSB, defaults to 0, allowed values are in range -16 dB to +15 dB. @@ -891,29 +889,60 @@ class SX127x: public PhysicalLayer { /*! \brief Sets transmission encoding. Only available in FSK mode. + Allowed values are RADIOLIB_ENCODING_NRZ, RADIOLIB_ENCODING_MANCHESTER and RADIOLIB_ENCODING_WHITENING. - \param encoding Encoding to be used. Set to 0 for NRZ, 1 for Manchester and 2 for whitening. + \param encoding Encoding to be used. \returns \ref status_codes */ - int16_t setEncoding(uint8_t encoding); + int16_t setEncoding(uint8_t encoding) override; - #ifdef RADIOLIB_DEBUG - void regDump(); - #endif + /*! + \brief Reads currently active IRQ flags, can be used to check which event caused an interrupt. + In LoRa mode, this is the content of SX127X_REG_IRQ_FLAGS register. + In FSK mode, this is the contents of SX127X_REG_IRQ_FLAGS_2 (MSB) and SX127X_REG_IRQ_FLAGS_1 (LSB) registers. + + \returns IRQ flags. + */ + uint16_t getIRQFlags(); + + /*! + \brief Reads modem status. Only available in LoRa mode. + + \returns Modem status. + */ + uint8_t getModemStatus(); + + /*! + \brief Reads uncalibrated temperature value. This function will change operating mode + and should not be called during Tx, Rx or CAD. + + \returns Uncalibrated temperature sensor reading. + */ + int8_t getTempRaw(); + + /*! + \brief Some modules contain external RF switch controlled by two pins. This function gives RadioLib control over those two pins to automatically switch Rx and Tx state. + When using automatic RF switch control, DO NOT change the pin mode of rxEn or txEn from Arduino sketch! + + \param rxEn RX enable pin. + + \param txEn TX enable pin. + */ + void setRfSwitchPins(RADIOLIB_PIN_TYPE rxEn, RADIOLIB_PIN_TYPE txEn); #ifndef RADIOLIB_GODMODE protected: #endif Module* _mod; - float _freq; - float _bw; - uint8_t _sf; - uint8_t _cr; - float _br; - float _rxBw; - bool _ook; + float _freq = 0; + float _bw = 0; + uint8_t _sf = 0; + uint8_t _cr = 0; + float _br = 0; + float _rxBw = 0; + bool _ook = false; int16_t setFrequencyRaw(float newFreq); int16_t config(); @@ -925,10 +954,10 @@ class SX127x: public PhysicalLayer { #ifndef RADIOLIB_GODMODE private: #endif - float _dataRate; - size_t _packetLength; - bool _packetLengthQueried; // FSK packet length is the first byte in FIFO, length can only be queried once - uint8_t _packetLengthConfig; + float _dataRate = 0; + size_t _packetLength = 0; + bool _packetLengthQueried = false; // FSK packet length is the first byte in FIFO, length can only be queried once + uint8_t _packetLengthConfig = SX127X_PACKET_VARIABLE; bool findChip(uint8_t ver); int16_t setMode(uint8_t mode); @@ -938,3 +967,5 @@ class SX127x: public PhysicalLayer { }; #endif + +#endif diff --git a/src/modules/SX128x/SX1280.cpp b/src/modules/SX128x/SX1280.cpp new file mode 100644 index 00000000..b0d513ef --- /dev/null +++ b/src/modules/SX128x/SX1280.cpp @@ -0,0 +1,116 @@ +#include "SX1280.h" +#if !defined(RADIOLIB_EXCLUDE_SX128X) + +SX1280::SX1280(Module* mod) : SX1281(mod) { + +} + +int16_t SX1280::range(bool master, uint32_t addr) { + // start ranging + int16_t state = startRanging(master, addr); + RADIOLIB_ASSERT(state); + + // wait until ranging is finished + uint32_t start = millis(); + while(!digitalRead(_mod->getIrq())) { + yield(); + if(millis() - start > 10000) { + clearIrqStatus(); + standby(); + return(ERR_RANGING_TIMEOUT); + } + } + + // clear interrupt flags + state = clearIrqStatus(); + RADIOLIB_ASSERT(state); + + // set mode to standby + state = standby(); + + return(state); +} + +int16_t SX1280::startRanging(bool master, uint32_t addr) { + // check active modem + uint8_t modem = getPacketType(); + if(!((modem == SX128X_PACKET_TYPE_LORA) || (modem == SX128X_PACKET_TYPE_RANGING))) { + return(ERR_WRONG_MODEM); + } + + // ensure modem is set to ranging + int16_t state = ERR_NONE; + if(modem == SX128X_PACKET_TYPE_LORA) { + state = setPacketType(SX128X_PACKET_TYPE_RANGING); + RADIOLIB_ASSERT(state); + } + + // set modulation parameters + state = setModulationParams(_sf, _bw, _cr); + RADIOLIB_ASSERT(state); + + // set packet parameters + state = setPacketParamsLoRa(_preambleLengthLoRa, _headerType, _payloadLen, _crcLoRa); + RADIOLIB_ASSERT(state); + + // check all address bits + uint8_t regValue; + state = readRegister(SX128X_REG_SLAVE_RANGING_ADDRESS_WIDTH, ®Value, 1); + RADIOLIB_ASSERT(state); + regValue &= 0b00111111; + regValue |= 0b11000000; + state = writeRegister(SX128X_REG_SLAVE_RANGING_ADDRESS_WIDTH, ®Value, 1); + RADIOLIB_ASSERT(state); + + // set remaining parameter values + uint32_t addrReg = SX128X_REG_SLAVE_RANGING_ADDRESS_BYTE_3; + uint32_t irqMask = SX128X_IRQ_RANGING_SLAVE_RESP_DONE | SX128X_IRQ_RANGING_SLAVE_REQ_DISCARD; + uint32_t irqDio1 = SX128X_IRQ_RANGING_SLAVE_RESP_DONE; + if(master) { + addrReg = SX128X_REG_MASTER_RANGING_ADDRESS_BYTE_3; + irqMask = SX128X_IRQ_RANGING_MASTER_RES_VALID | SX128X_IRQ_RANGING_MASTER_TIMEOUT; + irqDio1 = SX128X_IRQ_RANGING_MASTER_RES_VALID; + } + + // set ranging address + uint8_t addrBuff[] = { (uint8_t)((addr >> 24) & 0xFF), (uint8_t)((addr >> 16) & 0xFF), (uint8_t)((addr >> 8) & 0xFF), (uint8_t)(addr & 0xFF) }; + state = writeRegister(addrReg, addrBuff, 4); + RADIOLIB_ASSERT(state); + + // set DIO mapping + state = setDioIrqParams(irqMask, irqDio1); + RADIOLIB_ASSERT(state); + + // set role and start ranging + if(master) { + state = setRangingRole(SX128X_RANGING_ROLE_MASTER); + RADIOLIB_ASSERT(state); + + state = setTx(SX128X_TX_TIMEOUT_NONE); + RADIOLIB_ASSERT(state); + + } else { + state = setRangingRole(SX128X_RANGING_ROLE_SLAVE); + RADIOLIB_ASSERT(state); + + state = setRx(SX128X_RX_TIMEOUT_INF); + RADIOLIB_ASSERT(state); + + } + + return(state); +} + +float SX1280::getRangingResult() { + // read the register values + uint8_t data[4]; + int16_t state = readRegister(SX128X_REG_RANGING_RESULT_MSB, data + 1, 3); + RADIOLIB_ASSERT(state); + + // calculate the real result + uint32_t raw = 0; + memcpy(&raw, data, sizeof(uint32_t)); + return((float)raw * (150.0/(4.096 * _bwKhz))); +} + +#endif diff --git a/src/modules/SX128x/SX1280.h b/src/modules/SX128x/SX1280.h new file mode 100644 index 00000000..3cd3184a --- /dev/null +++ b/src/modules/SX128x/SX1280.h @@ -0,0 +1,63 @@ +#if !defined(_RADIOLIB_SX1280_H) +#define _RADIOLIB_SX1280_H + +#include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SX128X) + +#include "../../Module.h" +#include "SX128x.h" +#include "SX1281.h" + +/*! + \class SX1280 + + \brief Derived class for %SX1280 modules. +*/ +class SX1280: public SX1281 { + public: + /*! + \brief Default constructor. + + \param mod Instance of Module that will be used to communicate with the radio. + */ + SX1280(Module* mod); + + /*! + \brief Blocking ranging method. + + \param master Whether to execute ranging in master mode (true) or slave mode (false). + + \param addr Ranging address to be used. + + \returns \ref status_codes + */ + int16_t range(bool master, uint32_t addr); + + /*! + \brief Interrupt-driven ranging method. + + \param master Whether to execute ranging in master mode (true) or slave mode (false). + + \param addr Ranging address to be used. + + \returns \ref status_codes + */ + int16_t startRanging(bool master, uint32_t addr); + + /*! + \brief Gets ranging result of the last ranging exchange. + + \returns Ranging result in meters. + */ + float getRangingResult(); + +#ifndef RADIOLIB_GODMODE + private: +#endif + +}; + +#endif + +#endif diff --git a/src/modules/SX128x/SX1281.cpp b/src/modules/SX128x/SX1281.cpp new file mode 100644 index 00000000..c6b2b5eb --- /dev/null +++ b/src/modules/SX128x/SX1281.cpp @@ -0,0 +1,8 @@ +#include "SX1281.h" +#if !defined(RADIOLIB_EXCLUDE_SX128X) + +SX1281::SX1281(Module* mod) : SX128x(mod) { + +} + +#endif diff --git a/src/modules/SX128x/SX1281.h b/src/modules/SX128x/SX1281.h new file mode 100644 index 00000000..67a0a323 --- /dev/null +++ b/src/modules/SX128x/SX1281.h @@ -0,0 +1,33 @@ +#if !defined(_RADIOLIB_SX1281_H) +#define _RADIOLIB_SX1281_H + +#include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SX128X) + +#include "../../Module.h" +#include "SX128x.h" + +/*! + \class SX1281 + + \brief Derived class for %SX1281 modules. +*/ +class SX1281: public SX128x { + public: + /*! + \brief Default constructor. + + \param mod Instance of Module that will be used to communicate with the radio. + */ + SX1281(Module* mod); + +#ifndef RADIOLIB_GODMODE + private: +#endif + +}; + +#endif + +#endif diff --git a/src/modules/SX128x/SX1282.cpp b/src/modules/SX128x/SX1282.cpp new file mode 100644 index 00000000..33deee97 --- /dev/null +++ b/src/modules/SX128x/SX1282.cpp @@ -0,0 +1,9 @@ +#include "SX1282.h" +#if !defined(RADIOLIB_EXCLUDE_SX128X) + +/// \todo implement advanced ranging +SX1282::SX1282(Module* mod) : SX1280(mod) { + +} + +#endif diff --git a/src/modules/SX128x/SX1282.h b/src/modules/SX128x/SX1282.h new file mode 100644 index 00000000..f6cbdbd7 --- /dev/null +++ b/src/modules/SX128x/SX1282.h @@ -0,0 +1,34 @@ +#if !defined(_RADIOLIB_SX1282_H) +#define _RADIOLIB_SX1282_H + +#include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SX128X) + +#include "../../Module.h" +#include "SX128x.h" +#include "SX1280.h" + +/*! + \class SX1282 + + \brief Derived class for %SX1282 modules. +*/ +class SX1282: public SX1280 { + public: + /*! + \brief Default constructor. + + \param mod Instance of Module that will be used to communicate with the radio. + */ + SX1282(Module* mod); + +#ifndef RADIOLIB_GODMODE + private: +#endif + +}; + +#endif + +#endif diff --git a/src/modules/SX128x/SX128x.cpp b/src/modules/SX128x/SX128x.cpp new file mode 100644 index 00000000..8638ebc9 --- /dev/null +++ b/src/modules/SX128x/SX128x.cpp @@ -0,0 +1,1442 @@ +#include "SX128x.h" +#if !defined(RADIOLIB_EXCLUDE_SX128X) + +SX128x::SX128x(Module* mod) : PhysicalLayer(SX128X_FREQUENCY_STEP_SIZE, SX128X_MAX_PACKET_LENGTH) { + _mod = mod; +} + +int16_t SX128x::begin(float freq, float bw, uint8_t sf, uint8_t cr, int8_t power, uint16_t preambleLength) { + // set module properties + _mod->init(RADIOLIB_USE_SPI); + Module::pinMode(_mod->getIrq(), INPUT); + Module::pinMode(_mod->getGpio(), INPUT); + + // initialize LoRa modulation variables + _bwKhz = bw; + _sf = SX128X_LORA_SF_9; + _cr = SX128X_LORA_CR_4_7; + + // initialize LoRa packet variables + _preambleLengthLoRa = preambleLength; + _headerType = SX128X_LORA_HEADER_EXPLICIT; + _payloadLen = 0xFF; + _crcLoRa = SX128X_LORA_CRC_ON; + + // reset the module and verify startup + int16_t state = reset(); + RADIOLIB_ASSERT(state); + + // set mode to standby + state = standby(); + RADIOLIB_ASSERT(state); + + // configure settings not accessible by API + state = config(SX128X_PACKET_TYPE_LORA); + RADIOLIB_ASSERT(state); + + // configure publicly accessible settings + state = setFrequency(freq); + RADIOLIB_ASSERT(state); + + state = setBandwidth(bw); + RADIOLIB_ASSERT(state); + + state = setSpreadingFactor(sf); + RADIOLIB_ASSERT(state); + + state = setCodingRate(cr); + RADIOLIB_ASSERT(state); + + state = setPreambleLength(preambleLength); + RADIOLIB_ASSERT(state); + + state = setOutputPower(power); + RADIOLIB_ASSERT(state); + + return(state); +} + +int16_t SX128x::beginGFSK(float freq, uint16_t br, float freqDev, int8_t power, uint16_t preambleLength) { + // set module properties + _mod->init(RADIOLIB_USE_SPI); + Module::pinMode(_mod->getIrq(), INPUT); + Module::pinMode(_mod->getGpio(), INPUT); + + // initialize GFSK modulation variables + _brKbps = br; + _br = SX128X_BLE_GFSK_BR_0_800_BW_2_4; + _modIndexReal = 1.0; + _modIndex = SX128X_BLE_GFSK_MOD_IND_1_00; + _shaping = SX128X_BLE_GFSK_BT_0_5; + + // initialize GFSK packet variables + _preambleLengthGFSK = preambleLength; + _syncWordLen = 2; + _syncWordMatch = SX128X_GFSK_FLRC_SYNC_WORD_1; + _crcGFSK = SX128X_GFSK_FLRC_CRC_2_BYTE; + _whitening = SX128X_GFSK_BLE_WHITENING_ON; + + // reset the module and verify startup + int16_t state = reset(); + RADIOLIB_ASSERT(state); + + // set mode to standby + state = standby(); + RADIOLIB_ASSERT(state); + + // configure settings not accessible by API + state = config(SX128X_PACKET_TYPE_GFSK); + RADIOLIB_ASSERT(state); + + // configure publicly accessible settings + state = setFrequency(freq); + RADIOLIB_ASSERT(state); + + state = setBitRate(br); + RADIOLIB_ASSERT(state); + + state = setFrequencyDeviation(freqDev); + RADIOLIB_ASSERT(state); + + state = setOutputPower(power); + RADIOLIB_ASSERT(state); + + state = setPreambleLength(preambleLength); + RADIOLIB_ASSERT(state); + + state = setDataShaping(RADIOLIB_SHAPING_0_5); + RADIOLIB_ASSERT(state); + + // set publicly accessible settings that are not a part of begin method + uint8_t sync[] = { 0x12, 0xAD }; + state = setSyncWord(sync, 2); + RADIOLIB_ASSERT(state); + + state = setEncoding(RADIOLIB_ENCODING_NRZ); + RADIOLIB_ASSERT(state); + + return(state); +} + +int16_t SX128x::beginBLE(float freq, uint16_t br, float freqDev, int8_t power, uint8_t dataShaping) { + // set module properties + _mod->init(RADIOLIB_USE_SPI); + Module::pinMode(_mod->getIrq(), INPUT); + Module::pinMode(_mod->getGpio(), INPUT); + + // initialize BLE modulation variables + _brKbps = br; + _br = SX128X_BLE_GFSK_BR_0_800_BW_2_4; + _modIndexReal = 1.0; + _modIndex = SX128X_BLE_GFSK_MOD_IND_1_00; + _shaping = SX128X_BLE_GFSK_BT_0_5; + + // initialize BLE packet variables + _crcGFSK = SX128X_BLE_CRC_3_BYTE; + _whitening = SX128X_GFSK_BLE_WHITENING_ON; + + // reset the module and verify startup + int16_t state = reset(); + RADIOLIB_ASSERT(state); + + // set mode to standby + state = standby(); + RADIOLIB_ASSERT(state); + + // configure settings not accessible by API + state = config(SX128X_PACKET_TYPE_BLE); + RADIOLIB_ASSERT(state); + + // configure publicly accessible settings + state = setFrequency(freq); + RADIOLIB_ASSERT(state); + + state = setBitRate(br); + RADIOLIB_ASSERT(state); + + state = setFrequencyDeviation(freqDev); + RADIOLIB_ASSERT(state); + + state = setOutputPower(power); + RADIOLIB_ASSERT(state); + + state = setDataShaping(dataShaping); + RADIOLIB_ASSERT(state); + + return(state); +} + +int16_t SX128x::beginFLRC(float freq, uint16_t br, uint8_t cr, int8_t power, uint16_t preambleLength, uint8_t dataShaping) { + // set module properties + _mod->init(RADIOLIB_USE_SPI); + Module::pinMode(_mod->getIrq(), INPUT); + Module::pinMode(_mod->getGpio(), INPUT); + + // initialize FLRC modulation variables + _brKbps = br; + _br = SX128X_FLRC_BR_0_650_BW_0_6; + _crFLRC = SX128X_FLRC_CR_3_4; + _shaping = SX128X_FLRC_BT_0_5; + + // initialize FLRC packet variables + _preambleLengthGFSK = preambleLength; + _syncWordLen = 2; + _syncWordMatch = SX128X_GFSK_FLRC_SYNC_WORD_1; + _crcGFSK = SX128X_GFSK_FLRC_CRC_2_BYTE; + _whitening = SX128X_GFSK_BLE_WHITENING_OFF; + + // reset the module and verify startup + int16_t state = reset(); + RADIOLIB_ASSERT(state); + + // set mode to standby + state = standby(); + RADIOLIB_ASSERT(state); + + // configure settings not accessible by API + state = config(SX128X_PACKET_TYPE_FLRC); + RADIOLIB_ASSERT(state); + + // configure publicly accessible settings + state = setFrequency(freq); + RADIOLIB_ASSERT(state); + + state = setBitRate(br); + RADIOLIB_ASSERT(state); + + state = setCodingRate(cr); + RADIOLIB_ASSERT(state); + + state = setOutputPower(power); + RADIOLIB_ASSERT(state); + + state = setPreambleLength(preambleLength); + RADIOLIB_ASSERT(state); + + state = setDataShaping(dataShaping); + RADIOLIB_ASSERT(state); + + // set publicly accessible settings that are not a part of begin method + uint8_t sync[] = { 0x2D, 0x01, 0x4B, 0x1D}; + state = setSyncWord(sync, 4); + RADIOLIB_ASSERT(state); + + return(state); +} + +int16_t SX128x::reset(bool verify) { + // run the reset sequence - same as SX126x, as SX128x docs don't seem to mention this + Module::pinMode(_mod->getRst(), OUTPUT); + Module::digitalWrite(_mod->getRst(), LOW); + delay(1); + Module::digitalWrite(_mod->getRst(), HIGH); + + // return immediately when verification is disabled + if(!verify) { + return(ERR_NONE); + } + + // set mode to standby + uint32_t start = millis(); + while(true) { + // try to set mode to standby + int16_t state = standby(); + if(state == ERR_NONE) { + // standby command successful + return(ERR_NONE); + } + + // standby command failed, check timeout and try again + if(millis() - start >= 3000) { + // timed out, possibly incorrect wiring + return(state); + } + + // wait a bit to not spam the module + delay(10); + } +} + +int16_t SX128x::transmit(uint8_t* data, size_t len, uint8_t addr) { + // check packet length + if(len > SX128X_MAX_PACKET_LENGTH) { + return(ERR_PACKET_TOO_LONG); + } + + // check active modem + uint8_t modem = getPacketType(); + if(modem == SX128X_PACKET_TYPE_RANGING) { + return(ERR_WRONG_MODEM); + } + + // set mode to standby + int16_t state = standby(); + RADIOLIB_ASSERT(state); + + // calculate timeout (500% of expected time-on-air) + uint32_t timeout = getTimeOnAir(len) * 5; + + RADIOLIB_DEBUG_PRINT(F("Timeout in ")); + RADIOLIB_DEBUG_PRINT(timeout); + RADIOLIB_DEBUG_PRINTLN(F(" us")); + + // start transmission + state = startTransmit(data, len, addr); + RADIOLIB_ASSERT(state); + + // wait for packet transmission or timeout + uint32_t start = micros(); + while(!digitalRead(_mod->getIrq())) { + yield(); + if(micros() - start > timeout) { + clearIrqStatus(); + standby(); + return(ERR_TX_TIMEOUT); + } + } + + // clear interrupt flags + state = clearIrqStatus(); + RADIOLIB_ASSERT(state); + + // set mode to standby to disable transmitter + state = standby(); + + return(state); +} + +int16_t SX128x::receive(uint8_t* data, size_t len) { + // check active modem + uint8_t modem = getPacketType(); + if(modem == SX128X_PACKET_TYPE_RANGING) { + return(ERR_WRONG_MODEM); + } + + // set mode to standby + int16_t state = standby(); + RADIOLIB_ASSERT(state); + + // calculate timeout (1000% of expected time-on-air) + uint32_t timeout = getTimeOnAir(len) * 10; + + RADIOLIB_DEBUG_PRINT(F("Timeout in ")); + RADIOLIB_DEBUG_PRINT(timeout); + RADIOLIB_DEBUG_PRINTLN(F(" us")); + + // start reception + uint32_t timeoutValue = (uint32_t)((float)timeout / 15.625); + state = startReceive(timeoutValue); + RADIOLIB_ASSERT(state); + + // wait for packet reception or timeout + uint32_t start = micros(); + while(!digitalRead(_mod->getIrq())) { + yield(); + if(micros() - start > timeout) { + clearIrqStatus(); + standby(); + return(ERR_RX_TIMEOUT); + } + } + + // read the received data + return(readData(data, len)); +} + +int16_t SX128x::transmitDirect(uint32_t frf) { + // set RF switch (if present) + _mod->setRfSwitchState(LOW, HIGH); + + // user requested to start transmitting immediately (required for RTTY) + int16_t state = ERR_NONE; + if(frf != 0) { + state = setRfFrequency(frf); + } + RADIOLIB_ASSERT(state); + + // start transmitting + return(SPIwriteCommand(SX128X_CMD_SET_TX_CONTINUOUS_WAVE, NULL, 0)); +} + +int16_t SX128x::receiveDirect() { + // set RF switch (if present) + _mod->setRfSwitchState(HIGH, LOW); + + // SX128x is unable to output received data directly + return(ERR_UNKNOWN); +} + +int16_t SX128x::scanChannel() { + // check active modem + if(getPacketType() != SX128X_PACKET_TYPE_LORA) { + return(ERR_WRONG_MODEM); + } + + // set mode to standby + int16_t state = standby(); + RADIOLIB_ASSERT(state); + + // set DIO pin mapping + state = setDioIrqParams(SX128X_IRQ_CAD_DETECTED | SX128X_IRQ_CAD_DONE, SX128X_IRQ_CAD_DETECTED | SX128X_IRQ_CAD_DONE); + RADIOLIB_ASSERT(state); + + // clear interrupt flags + state = clearIrqStatus(); + RADIOLIB_ASSERT(state); + + // set RF switch (if present) + _mod->setRfSwitchState(HIGH, LOW); + + // set mode to CAD + state = setCad(); + RADIOLIB_ASSERT(state); + + // wait for channel activity detected or timeout + while(!digitalRead(_mod->getIrq())) { + yield(); + } + + // check CAD result + uint16_t cadResult = getIrqStatus(); + if(cadResult & SX128X_IRQ_CAD_DETECTED) { + // detected some LoRa activity + clearIrqStatus(); + return(LORA_DETECTED); + } else if(cadResult & SX128X_IRQ_CAD_DONE) { + // channel is free + clearIrqStatus(); + return(CHANNEL_FREE); + } + + return(ERR_UNKNOWN); +} + +int16_t SX128x::sleep(bool retainConfig) { + // set RF switch (if present) + _mod->setRfSwitchState(LOW, LOW); + + uint8_t sleepConfig = SX128X_SLEEP_DATA_BUFFER_RETAIN | SX128X_SLEEP_DATA_RAM_RETAIN; + if(!retainConfig) { + sleepConfig = SX128X_SLEEP_DATA_BUFFER_FLUSH | SX128X_SLEEP_DATA_RAM_FLUSH; + } + int16_t state = SPIwriteCommand(SX128X_CMD_SET_SLEEP, &sleepConfig, 1, false); + + // wait for SX128x to safely enter sleep mode + delay(1); + + return(state); +} + +int16_t SX128x::standby() { + return(SX128x::standby(SX128X_STANDBY_RC)); +} + +int16_t SX128x::standby(uint8_t mode) { + // set RF switch (if present) + _mod->setRfSwitchState(LOW, LOW); + + uint8_t data[] = { mode }; + return(SPIwriteCommand(SX128X_CMD_SET_STANDBY, data, 1)); +} + +void SX128x::setDio1Action(void (*func)(void)) { + attachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getIrq()), func, RISING); +} + +void SX128x::clearDio1Action() { + detachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getIrq())); +} + +int16_t SX128x::startTransmit(uint8_t* data, size_t len, uint8_t addr) { + // suppress unused variable warning + (void)addr; + + // check packet length + if(len > SX128X_MAX_PACKET_LENGTH) { + return(ERR_PACKET_TOO_LONG); + } + + // set packet Length + int16_t state = ERR_NONE; + uint8_t modem = getPacketType(); + if(modem == SX128X_PACKET_TYPE_LORA) { + state = setPacketParamsLoRa(_preambleLengthLoRa, _headerType, len, _crcLoRa); + } else if((modem == SX128X_PACKET_TYPE_GFSK) || (modem == SX128X_PACKET_TYPE_FLRC)) { + state = setPacketParamsGFSK(_preambleLengthGFSK, _syncWordLen, _syncWordMatch, _crcGFSK, _whitening, len); + } else if(modem == SX128X_PACKET_TYPE_BLE) { + state = setPacketParamsBLE(_connectionState, _crcBLE, _bleTestPayload, _whitening); + } else { + return(ERR_WRONG_MODEM); + } + RADIOLIB_ASSERT(state); + + // update output power + state = setTxParams(_pwr); + RADIOLIB_ASSERT(state); + + // set buffer pointers + state = setBufferBaseAddress(); + RADIOLIB_ASSERT(state); + + // write packet to buffer + if(modem == SX128X_PACKET_TYPE_BLE) { + // first 2 bytes of BLE payload are PDU header + state = writeBuffer(data, len, 2); + RADIOLIB_ASSERT(state); + } else { + state = writeBuffer(data, len); + RADIOLIB_ASSERT(state); + } + + // set DIO mapping + state = setDioIrqParams(SX128X_IRQ_TX_DONE | SX128X_IRQ_RX_TX_TIMEOUT, SX128X_IRQ_TX_DONE); + RADIOLIB_ASSERT(state); + + // clear interrupt flags + state = clearIrqStatus(); + RADIOLIB_ASSERT(state); + + // set RF switch (if present) + _mod->setRfSwitchState(LOW, HIGH); + + // start transmission + state = setTx(SX128X_TX_TIMEOUT_NONE); + RADIOLIB_ASSERT(state); + + // wait for BUSY to go low (= PA ramp up done) + while(digitalRead(_mod->getGpio())) { + yield(); + } + + return(state); +} + +int16_t SX128x::startReceive(uint16_t timeout) { + // check active modem + if(getPacketType() == SX128X_PACKET_TYPE_RANGING) { + return(ERR_WRONG_MODEM); + } + + // set DIO mapping + int16_t state = setDioIrqParams(SX128X_IRQ_RX_DONE | SX128X_IRQ_RX_TX_TIMEOUT | SX128X_IRQ_CRC_ERROR | SX128X_IRQ_HEADER_ERROR, SX128X_IRQ_RX_DONE); + RADIOLIB_ASSERT(state); + + // set buffer pointers + state = setBufferBaseAddress(); + RADIOLIB_ASSERT(state); + + // clear interrupt flags + state = clearIrqStatus(); + RADIOLIB_ASSERT(state); + + // set implicit mode and expected len if applicable + if((_headerType == SX128X_LORA_HEADER_IMPLICIT) && (getPacketType() == SX128X_PACKET_TYPE_LORA)) { + state = setPacketParamsLoRa(_preambleLengthLoRa, _headerType, _payloadLen, _crcLoRa); + RADIOLIB_ASSERT(state); + } + + // set RF switch (if present) + _mod->setRfSwitchState(HIGH, LOW); + + // set mode to receive + state = setRx(timeout); + + return(state); +} + +int16_t SX128x::readData(uint8_t* data, size_t len) { + // check active modem + if(getPacketType() == SX128X_PACKET_TYPE_RANGING) { + return(ERR_WRONG_MODEM); + } + + // set mode to standby + int16_t state = standby(); + RADIOLIB_ASSERT(state); + + // check integrity CRC + uint16_t irq = getIrqStatus(); + int16_t crcState = ERR_NONE; + if((irq & SX128X_IRQ_CRC_ERROR) || (irq & SX128X_IRQ_HEADER_ERROR)) { + crcState = ERR_CRC_MISMATCH; + } + + // get packet length + size_t length = len; + if(len == SX128X_MAX_PACKET_LENGTH) { + length = getPacketLength(); + } + + // read packet data + state = readBuffer(data, length); + RADIOLIB_ASSERT(state); + + // clear interrupt flags + state = clearIrqStatus(); + + // check if CRC failed - this is done after reading data to give user the option to keep them + RADIOLIB_ASSERT(crcState); + + return(state); +} + +int16_t SX128x::setFrequency(float freq) { + RADIOLIB_CHECK_RANGE(freq, 2400.0, 2500.0, ERR_INVALID_FREQUENCY); + + // calculate raw value + uint32_t frf = (freq * (uint32_t(1) << SX128X_DIV_EXPONENT)) / SX128X_CRYSTAL_FREQ; + return(setRfFrequency(frf)); +} + +int16_t SX128x::setBandwidth(float bw) { + // check active modem + uint8_t modem = getPacketType(); + if(modem == SX128X_PACKET_TYPE_LORA) { + // check range for LoRa + RADIOLIB_CHECK_RANGE(bw, 203.125, 1625.0, ERR_INVALID_BANDWIDTH); + } else if(modem == SX128X_PACKET_TYPE_RANGING) { + // check range for ranging + RADIOLIB_CHECK_RANGE(bw, 406.25, 1625.0, ERR_INVALID_BANDWIDTH); + } else { + return(ERR_WRONG_MODEM); + } + + if(abs(bw - 203.125) <= 0.001) { + _bw = SX128X_LORA_BW_203_125; + } else if(abs(bw - 406.25) <= 0.001) { + _bw = SX128X_LORA_BW_406_25; + } else if(abs(bw - 812.5) <= 0.001) { + _bw = SX128X_LORA_BW_812_50; + } else if(abs(bw - 1625.0) <= 0.001) { + _bw = SX128X_LORA_BW_1625_00; + } else { + return(ERR_INVALID_BANDWIDTH); + } + + // update modulation parameters + _bwKhz = bw; + return(setModulationParams(_sf, _bw, _cr)); +} + +int16_t SX128x::setSpreadingFactor(uint8_t sf) { + // check active modem + uint8_t modem = getPacketType(); + if(modem == SX128X_PACKET_TYPE_LORA) { + // check range for LoRa + RADIOLIB_CHECK_RANGE(sf, 5, 12, ERR_INVALID_SPREADING_FACTOR); + } else if(modem == SX128X_PACKET_TYPE_RANGING) { + // check range for ranging + RADIOLIB_CHECK_RANGE(sf, 5, 10, ERR_INVALID_SPREADING_FACTOR); + } else { + return(ERR_WRONG_MODEM); + } + + // update modulation parameters + _sf = sf << 4; + int16_t state = setModulationParams(_sf, _bw, _cr); + RADIOLIB_ASSERT(state); + + // update mystery register in LoRa mode - SX1280 datasheet v3.0 section 13.4.1 + if(modem == SX128X_PACKET_TYPE_LORA) { + uint8_t data = 0; + if((_sf == SX128X_LORA_SF_5) || (_sf == SX128X_LORA_SF_6)) { + data = 0x1E; + } else if((_sf == SX128X_LORA_SF_7) || (_sf == SX128X_LORA_SF_8)) { + data = 0x37; + } else { + data = 0x32; + } + state = SX128x::writeRegister(SX128X_REG_LORA_SF_CONFIG, &data, 1); + } + + return(state); +} + +int16_t SX128x::setCodingRate(uint8_t cr, bool longInterleaving) { + // check active modem + uint8_t modem = getPacketType(); + + // LoRa/ranging + if((modem == SX128X_PACKET_TYPE_LORA) || (modem == SX128X_PACKET_TYPE_RANGING)) { + RADIOLIB_CHECK_RANGE(cr, 5, 8, ERR_INVALID_CODING_RATE); + + // update modulation parameters + if(longInterleaving && (modem == SX128X_PACKET_TYPE_LORA)) { + _cr = cr; + } else { + _cr = cr - 4; + } + return(setModulationParams(_sf, _bw, _cr)); + + // FLRC + } else if(modem == SX128X_PACKET_TYPE_FLRC) { + RADIOLIB_CHECK_RANGE(cr, 2, 4, ERR_INVALID_CODING_RATE); + + // update modulation parameters + _crFLRC = (cr - 2) * 2; + return(setModulationParams(_br, _crFLRC, _shaping)); + } + + return(ERR_WRONG_MODEM); +} + +int16_t SX128x::setOutputPower(int8_t power) { + RADIOLIB_CHECK_RANGE(power, -18, 13, ERR_INVALID_OUTPUT_POWER); + _pwr = power + 18; + return(setTxParams(_pwr)); +} + +int16_t SX128x::setPreambleLength(uint32_t preambleLength) { + uint8_t modem = getPacketType(); + if((modem == SX128X_PACKET_TYPE_LORA) || (modem == SX128X_PACKET_TYPE_RANGING)) { + // LoRa or ranging + RADIOLIB_CHECK_RANGE(preambleLength, 2, 491520, ERR_INVALID_PREAMBLE_LENGTH); + + // check preamble length is even - no point even trying odd numbers + if(preambleLength % 2 != 0) { + return(ERR_INVALID_PREAMBLE_LENGTH); + } + + // calculate exponent and mantissa values (use the next longer preamble if there's no exact match) + uint8_t e = 1; + uint8_t m = 1; + uint32_t len = 0; + for(; e <= 15; e++) { + for(; m <= 15; m++) { + len = m * (uint32_t(1) << e); + if(len >= preambleLength) { + break; + } + } + if(len >= preambleLength) { + break; + } + } + + // update packet parameters + _preambleLengthLoRa = (e << 4) | m; + return(setPacketParamsLoRa(_preambleLengthLoRa, _headerType, _payloadLen, _crcLoRa)); + + } else if((modem == SX128X_PACKET_TYPE_GFSK) || (modem == SX128X_PACKET_TYPE_FLRC)) { + // GFSK or FLRC + RADIOLIB_CHECK_RANGE(preambleLength, 4, 32, ERR_INVALID_PREAMBLE_LENGTH); + + // check preamble length is multiple of 4 + if(preambleLength % 4 != 0) { + return(ERR_INVALID_PREAMBLE_LENGTH); + } + + // update packet parameters + _preambleLengthGFSK = ((preambleLength / 4) - 1) << 4; + return(setPacketParamsGFSK(_preambleLengthGFSK, _syncWordLen, _syncWordMatch, _crcGFSK, _whitening)); + } + + return(ERR_WRONG_MODEM); +} + +int16_t SX128x::setBitRate(uint16_t br) { + // check active modem + uint8_t modem = getPacketType(); + + // GFSK/BLE + if((modem == SX128X_PACKET_TYPE_GFSK) || (modem == SX128X_PACKET_TYPE_BLE)) { + if(br == 125) { + _br = SX128X_BLE_GFSK_BR_0_125_BW_0_3; + } else if(br == 250) { + _br = SX128X_BLE_GFSK_BR_0_250_BW_0_6; + } else if(br == 400) { + _br = SX128X_BLE_GFSK_BR_0_400_BW_1_2; + } else if(br == 500) { + _br = SX128X_BLE_GFSK_BR_0_500_BW_1_2; + } else if(br == 800) { + _br = SX128X_BLE_GFSK_BR_0_800_BW_2_4; + } else if(br == 1000) { + _br = SX128X_BLE_GFSK_BR_1_000_BW_2_4; + } else if(br == 1600) { + _br = SX128X_BLE_GFSK_BR_1_600_BW_2_4; + } else if(br == 2000) { + _br = SX128X_BLE_GFSK_BR_2_000_BW_2_4; + } else { + return(ERR_INVALID_BIT_RATE); + } + + // update modulation parameters + _brKbps = br; + return(setModulationParams(_br, _modIndex, _shaping)); + + // FLRC + } else if(modem == SX128X_PACKET_TYPE_FLRC) { + if(br == 260) { + _br = SX128X_FLRC_BR_0_260_BW_0_3; + } else if(br == 325) { + _br = SX128X_FLRC_BR_0_325_BW_0_3; + } else if(br == 520) { + _br = SX128X_FLRC_BR_0_520_BW_0_6; + } else if(br == 650) { + _br = SX128X_FLRC_BR_0_650_BW_0_6; + } else if(br == 1000) { + _br = SX128X_FLRC_BR_1_000_BW_1_2; + } else if(br == 1300) { + _br = SX128X_FLRC_BR_1_300_BW_1_2; + } else { + return(ERR_INVALID_BIT_RATE); + } + + // update modulation parameters + _brKbps = br; + return(setModulationParams(_br, _crFLRC, _shaping)); + + } + + return(ERR_WRONG_MODEM); +} + +int16_t SX128x::setFrequencyDeviation(float freqDev) { + // check active modem + uint8_t modem = getPacketType(); + if(!((modem == SX128X_PACKET_TYPE_GFSK) || (modem == SX128X_PACKET_TYPE_BLE))) { + return(ERR_WRONG_MODEM); + } + + RADIOLIB_CHECK_RANGE(freqDev, 0.0, 3200.0, ERR_INVALID_FREQUENCY_DEVIATION); + + // override for the lowest possible frequency deviation - required for some PhysicalLayer protocols + if(freqDev == 0.0) { + _modIndex = SX128X_BLE_GFSK_MOD_IND_0_35; + _br = SX128X_BLE_GFSK_BR_0_125_BW_0_3; + return(setModulationParams(_br, _modIndex, _shaping)); + } + + // update modulation parameters + uint8_t modIndex = (uint8_t)((8.0 * (freqDev / (float)_brKbps)) - 1.0); + if(modIndex > SX128X_BLE_GFSK_MOD_IND_4_00) { + return(ERR_INVALID_MODULATION_PARAMETERS); + } + + // update modulation parameters + _modIndex = modIndex; + return(setModulationParams(_br, _modIndex, _shaping)); +} + +int16_t SX128x::setDataShaping(uint8_t sh) { + // check active modem + uint8_t modem = getPacketType(); + if(!((modem == SX128X_PACKET_TYPE_GFSK) || (modem == SX128X_PACKET_TYPE_BLE) || (modem == SX128X_PACKET_TYPE_FLRC))) { + return(ERR_WRONG_MODEM); + } + + // set data shaping + switch(sh) { + case RADIOLIB_SHAPING_NONE: + _shaping = SX128X_BLE_GFSK_BT_OFF; + break; + case RADIOLIB_SHAPING_0_5: + _shaping = SX128X_BLE_GFSK_BT_0_5; + break; + case RADIOLIB_SHAPING_1_0: + _shaping = SX128X_BLE_GFSK_BT_1_0; + break; + default: + return(ERR_INVALID_DATA_SHAPING); + } + + // update modulation parameters + if((modem == SX128X_PACKET_TYPE_GFSK) || (modem == SX128X_PACKET_TYPE_BLE)) { + return(setModulationParams(_br, _modIndex, _shaping)); + } else { + return(setModulationParams(_br, _crFLRC, _shaping)); + } +} + +int16_t SX128x::setSyncWord(uint8_t* syncWord, uint8_t len) { + // check active modem + uint8_t modem = getPacketType(); + if(!((modem == SX128X_PACKET_TYPE_GFSK) || (modem == SX128X_PACKET_TYPE_FLRC))) { + return(ERR_WRONG_MODEM); + } + + if(modem == SX128X_PACKET_TYPE_GFSK) { + // GFSK can use up to 5 bytes as sync word + if(len > 5) { + return(ERR_INVALID_SYNC_WORD); + } + + // calculate sync word length parameter value + if(len > 0) { + _syncWordLen = (len - 1)*2; + } + + } else { + // FLRC requires 32-bit sync word + if(!((len == 0) || (len == 4))) { + return(ERR_INVALID_SYNC_WORD); + } + + // save sync word length parameter value + _syncWordLen = len; + } + + // reverse sync word byte order + uint8_t syncWordBuff[] = { 0x00, 0x00, 0x00, 0x00, 0x00 }; + for(uint8_t i = 0; i < len; i++) { + syncWordBuff[4 - i] = syncWord[i]; + } + + // update sync word + int16_t state = SX128x::writeRegister(SX128X_REG_SYNC_WORD_1_BYTE_4, syncWordBuff, 5); + RADIOLIB_ASSERT(state); + + // update packet parameters + if(_syncWordLen == 0) { + _syncWordMatch = SX128X_GFSK_FLRC_SYNC_WORD_OFF; + } else { + /// \todo add support for multiple sync words + _syncWordMatch = SX128X_GFSK_FLRC_SYNC_WORD_1; + } + return(setPacketParamsGFSK(_preambleLengthGFSK, _syncWordLen, _syncWordMatch, _crcGFSK, _whitening)); +} + +int16_t SX128x::setCRC(uint8_t len, uint32_t initial, uint16_t polynomial) { + // check active modem + uint8_t modem = getPacketType(); + + int16_t state; + if((modem == SX128X_PACKET_TYPE_GFSK) || (modem == SX128X_PACKET_TYPE_FLRC)) { + // update packet parameters + if(modem == SX128X_PACKET_TYPE_GFSK) { + if(len > 2) { + return(ERR_INVALID_CRC_CONFIGURATION); + } + } else { + if(len > 3) { + return(ERR_INVALID_CRC_CONFIGURATION); + } + } + _crcGFSK = len << 4; + state = setPacketParamsGFSK(_preambleLengthGFSK, _syncWordLen, _syncWordMatch, _crcGFSK, _whitening); + RADIOLIB_ASSERT(state); + + // set initial CRC value + uint8_t data[] = { (uint8_t)((initial >> 8) & 0xFF), (uint8_t)(initial & 0xFF) }; + state = writeRegister(SX128X_REG_CRC_INITIAL_MSB, data, 2); + RADIOLIB_ASSERT(state); + + // set CRC polynomial + data[0] = (uint8_t)((polynomial >> 8) & 0xFF); + data[1] = (uint8_t)(polynomial & 0xFF); + state = writeRegister(SX128X_REG_CRC_POLYNOMIAL_MSB, data, 2); + return(state); + + } else if(modem == SX128X_PACKET_TYPE_BLE) { + // update packet parameters + if(len == 0) { + _crcBLE = SX128X_BLE_CRC_OFF; + } else if(len == 3) { + _crcBLE = SX128X_BLE_CRC_3_BYTE; + } else { + return(ERR_INVALID_CRC_CONFIGURATION); + } + state = setPacketParamsBLE(_connectionState, _crcBLE, _bleTestPayload, _whitening); + RADIOLIB_ASSERT(state); + + // set initial CRC value + uint8_t data[] = { (uint8_t)((initial >> 16) & 0xFF), (uint8_t)((initial >> 8) & 0xFF), (uint8_t)(initial & 0xFF) }; + state = writeRegister(SX128X_REG_BLE_CRC_INITIAL_MSB, data, 3); + return(state); + + } else if((modem == SX128X_PACKET_TYPE_LORA) || (modem == SX128X_PACKET_TYPE_RANGING)) { + // update packet parameters + if(len == 0) { + _crcLoRa = SX128X_LORA_CRC_OFF; + } else if(len == 2) { + _crcLoRa = SX128X_LORA_CRC_ON; + } else { + return(ERR_INVALID_CRC_CONFIGURATION); + } + state = setPacketParamsLoRa(_preambleLengthLoRa, _headerType, _payloadLen, _crcLoRa); + return(state); + } + + return(ERR_UNKNOWN); +} + +int16_t SX128x::setWhitening(bool enabled) { + // check active modem + uint8_t modem = getPacketType(); + if(!((modem == SX128X_PACKET_TYPE_GFSK) || (modem == SX128X_PACKET_TYPE_BLE))) { + return(ERR_WRONG_MODEM); + } + + // update packet parameters + if(enabled) { + _whitening = SX128X_GFSK_BLE_WHITENING_ON; + } else { + _whitening = SX128X_GFSK_BLE_WHITENING_OFF; + } + + if(modem == SX128X_PACKET_TYPE_GFSK) { + return(setPacketParamsGFSK(_preambleLengthGFSK, _syncWordLen, _syncWordMatch, _crcGFSK, _whitening)); + } + return(setPacketParamsBLE(_connectionState, _crcBLE, _bleTestPayload, _whitening)); +} + +int16_t SX128x::setAccessAddress(uint32_t addr) { + // check active modem + if(getPacketType() != SX128X_PACKET_TYPE_BLE) { + return(ERR_WRONG_MODEM); + } + + // set the address + uint8_t addrBuff[] = { (uint8_t)((addr >> 24) & 0xFF), (uint8_t)((addr >> 16) & 0xFF), (uint8_t)((addr >> 8) & 0xFF), (uint8_t)(addr & 0xFF) }; + return(SX128x::writeRegister(SX128X_REG_ACCESS_ADDRESS_BYTE_3, addrBuff, 4)); +} + +float SX128x::getRSSI() { + // get packet status + uint8_t packetStatus[5]; + SPIreadCommand(SX128X_CMD_GET_PACKET_STATUS, packetStatus, 5); + + // check active modem + uint8_t modem = getPacketType(); + if((modem == SX128X_PACKET_TYPE_LORA) || (modem == SX128X_PACKET_TYPE_RANGING)) { + // LoRa or ranging + uint8_t rssiSync = packetStatus[0]; + float rssiMeasured = -1.0 * rssiSync/2.0; + float snr = getSNR(); + if(snr <= 0.0) { + return(rssiMeasured - snr); + } else { + return(rssiMeasured); + } + } else { + // GFSK, BLE or FLRC + uint8_t rssiSync = packetStatus[1]; + return(-1.0 * rssiSync/2.0); + } +} + +float SX128x::getSNR() { + // check active modem + uint8_t modem = getPacketType(); + if(!((modem == SX128X_PACKET_TYPE_LORA) || (modem == SX128X_PACKET_TYPE_RANGING))) { + return(0.0); + } + + // get packet status + uint8_t packetStatus[5]; + SPIreadCommand(SX128X_CMD_GET_PACKET_STATUS, packetStatus, 5); + + // calculate real SNR + uint8_t snr = packetStatus[1]; + if(snr < 128) { + return(snr/4.0); + } else { + return((snr - 256)/4.0); + } +} + +size_t SX128x::getPacketLength(bool update) { + (void)update; + uint8_t rxBufStatus[2] = {0, 0}; + SPIreadCommand(SX128X_CMD_GET_RX_BUFFER_STATUS, rxBufStatus, 2); + return((size_t)rxBufStatus[0]); +} + +uint32_t SX128x::getTimeOnAir(size_t len) { + // check active modem + uint8_t modem = getPacketType(); + if(modem == SX128X_PACKET_TYPE_LORA) { + // calculate number of symbols + float N_symbol = 0; + uint8_t sf = _sf >> 4; + if(_cr <= SX128X_LORA_CR_4_8) { + // legacy coding rate - nice and simple + + // get SF coefficients + float coeff1 = 0; + int16_t coeff2 = 0; + int16_t coeff3 = 0; + if(sf < 7) { + // SF5, SF6 + coeff1 = 6.25; + coeff2 = 4*sf; + coeff3 = 4*sf; + } else if(sf < 11) { + // SF7. SF8, SF9, SF10 + coeff1 = 4.25; + coeff2 = 4*sf + 8; + coeff3 = 4*sf; + } else { + // SF11, SF12 + coeff1 = 4.25; + coeff2 = 4*sf + 8; + coeff3 = 4*(sf - 2); + } + + // get CRC length + int16_t N_bitCRC = 16; + if(_crcLoRa == SX128X_LORA_CRC_OFF) { + N_bitCRC = 0; + } + + // get header length + int16_t N_symbolHeader = 20; + if(_headerType == SX128X_LORA_HEADER_IMPLICIT) { + N_symbolHeader = 0; + } + + // calculate number of LoRa preamble symbols + uint32_t N_symbolPreamble = (_preambleLengthLoRa & 0x0F) * (uint32_t(1) << ((_preambleLengthLoRa & 0xF0) >> 4)); + + // calculate the number of symbols + N_symbol = (float)N_symbolPreamble + coeff1 + 8.0 + ceil(max((int16_t)(8 * len + N_bitCRC - coeff2 + N_symbolHeader), (int16_t)0) / (float)coeff3) * (float)(_cr + 4); + + } else { + // long interleaving - abandon hope all ye who enter here + /// \todo implement this mess - SX1280 datasheet v3.0 section 7.4.4.2 + + } + + // get time-on-air in us + return(((uint32_t(1) << sf) / _bwKhz) * N_symbol * 1000.0); + + } else { + return(((uint32_t)len * 8 * 1000) / _brKbps); + } + +} + +int16_t SX128x::implicitHeader(size_t len) { + return(setHeaderType(SX128X_LORA_HEADER_IMPLICIT, len)); +} + +int16_t SX128x::explicitHeader() { + return(setHeaderType(SX128X_LORA_HEADER_EXPLICIT)); +} + +int16_t SX128x::setEncoding(uint8_t encoding) { + return(setWhitening(encoding)); +} + +void SX128x::setRfSwitchPins(RADIOLIB_PIN_TYPE rxEn, RADIOLIB_PIN_TYPE txEn) { + _mod->setRfSwitchPins(rxEn, txEn); +} + +uint8_t SX128x::getStatus() { + uint8_t data = 0; + SPIreadCommand(SX128X_CMD_GET_STATUS, &data, 1); + return(data); +} + +int16_t SX128x::writeRegister(uint16_t addr, uint8_t* data, uint8_t numBytes) { + uint8_t cmd[] = { SX128X_CMD_WRITE_REGISTER, (uint8_t)((addr >> 8) & 0xFF), (uint8_t)(addr & 0xFF) }; + return(SPIwriteCommand(cmd, 3, data, numBytes)); +} + +int16_t SX128x::readRegister(uint16_t addr, uint8_t* data, uint8_t numBytes) { + uint8_t cmd[] = { SX128X_CMD_READ_REGISTER, (uint8_t)((addr >> 8) & 0xFF), (uint8_t)(addr & 0xFF) }; + return(SX128x::SPItransfer(cmd, 3, false, NULL, data, numBytes, true)); +} + +int16_t SX128x::writeBuffer(uint8_t* data, uint8_t numBytes, uint8_t offset) { + uint8_t cmd[] = { SX128X_CMD_WRITE_BUFFER, offset }; + return(SPIwriteCommand(cmd, 2, data, numBytes)); +} + +int16_t SX128x::readBuffer(uint8_t* data, uint8_t numBytes) { + uint8_t cmd[] = { SX128X_CMD_READ_BUFFER, SX128X_CMD_NOP }; + return(SPIreadCommand(cmd, 2, data, numBytes)); +} + +int16_t SX128x::setTx(uint16_t periodBaseCount, uint8_t periodBase) { + uint8_t data[] = { periodBase, (uint8_t)((periodBaseCount >> 8) & 0xFF), (uint8_t)(periodBaseCount & 0xFF) }; + return(SPIwriteCommand(SX128X_CMD_SET_TX, data, 3)); +} + +int16_t SX128x::setRx(uint16_t periodBaseCount, uint8_t periodBase) { + uint8_t data[] = { periodBase, (uint8_t)((periodBaseCount >> 8) & 0xFF), (uint8_t)(periodBaseCount & 0xFF) }; + return(SPIwriteCommand(SX128X_CMD_SET_RX, data, 3)); +} + +int16_t SX128x::setCad() { + return(SPIwriteCommand(SX128X_CMD_SET_CAD, NULL, 0)); +} + +uint8_t SX128x::getPacketType() { + uint8_t data = 0xFF; + SPIreadCommand(SX128X_CMD_GET_PACKET_TYPE, &data, 1); + return(data); +} + +int16_t SX128x::setRfFrequency(uint32_t frf) { + uint8_t data[] = { (uint8_t)((frf >> 16) & 0xFF), (uint8_t)((frf >> 8) & 0xFF), (uint8_t)(frf & 0xFF) }; + return(SPIwriteCommand(SX128X_CMD_SET_RF_FREQUENCY, data, 3)); +} + +int16_t SX128x::setTxParams(uint8_t power, uint8_t rampTime) { + uint8_t data[] = { power, rampTime }; + return(SPIwriteCommand(SX128X_CMD_SET_TX_PARAMS, data, 2)); +} + +int16_t SX128x::setBufferBaseAddress(uint8_t txBaseAddress, uint8_t rxBaseAddress) { + uint8_t data[] = { txBaseAddress, rxBaseAddress }; + return(SPIwriteCommand(SX128X_CMD_SET_BUFFER_BASE_ADDRESS, data, 2)); +} + +int16_t SX128x::setModulationParams(uint8_t modParam1, uint8_t modParam2, uint8_t modParam3) { + uint8_t data[] = { modParam1, modParam2, modParam3 }; + return(SPIwriteCommand(SX128X_CMD_SET_MODULATION_PARAMS, data, 3)); +} + +int16_t SX128x::setPacketParamsGFSK(uint8_t preambleLen, uint8_t syncWordLen, uint8_t syncWordMatch, uint8_t crcLen, uint8_t whitening, uint8_t payloadLen, uint8_t headerType) { + uint8_t data[] = { preambleLen, syncWordLen, syncWordMatch, headerType, payloadLen, crcLen, whitening }; + return(SPIwriteCommand(SX128X_CMD_SET_PACKET_PARAMS, data, 7)); +} + +int16_t SX128x::setPacketParamsBLE(uint8_t connState, uint8_t crcLen, uint8_t bleTestPayload, uint8_t whitening) { + uint8_t data[] = { connState, crcLen, bleTestPayload, whitening, 0x00, 0x00, 0x00 }; + return(SPIwriteCommand(SX128X_CMD_SET_PACKET_PARAMS, data, 7)); +} + +int16_t SX128x::setPacketParamsLoRa(uint8_t preambleLen, uint8_t headerType, uint8_t payloadLen, uint8_t crc, uint8_t invertIQ) { + uint8_t data[] = { preambleLen, headerType, payloadLen, crc, invertIQ, 0x00, 0x00 }; + return(SPIwriteCommand(SX128X_CMD_SET_PACKET_PARAMS, data, 7)); +} + +int16_t SX128x::setDioIrqParams(uint16_t irqMask, uint16_t dio1Mask, uint16_t dio2Mask, uint16_t dio3Mask) { + uint8_t data[] = { (uint8_t)((irqMask >> 8) & 0xFF), (uint8_t)(irqMask & 0xFF), + (uint8_t)((dio1Mask >> 8) & 0xFF), (uint8_t)(dio1Mask & 0xFF), + (uint8_t)((dio2Mask >> 8) & 0xFF), (uint8_t)(dio2Mask & 0xFF), + (uint8_t)((dio3Mask >> 8) & 0xFF), (uint8_t)(dio3Mask & 0xFF) }; + return(SPIwriteCommand(SX128X_CMD_SET_DIO_IRQ_PARAMS, data, 8)); +} + +uint16_t SX128x::getIrqStatus() { + uint8_t data[] = { 0x00, 0x00 }; + SPIreadCommand(SX128X_CMD_GET_IRQ_STATUS, data, 2); + return(((uint16_t)(data[0]) << 8) | data[1]); +} + +int16_t SX128x::clearIrqStatus(uint16_t clearIrqParams) { + uint8_t data[] = { (uint8_t)((clearIrqParams >> 8) & 0xFF), (uint8_t)(clearIrqParams & 0xFF) }; + return(SPIwriteCommand(SX128X_CMD_CLEAR_IRQ_STATUS, data, 2)); +} + +int16_t SX128x::setRangingRole(uint8_t role) { + uint8_t data[] = { role }; + return(SPIwriteCommand(SX128X_CMD_SET_RANGING_ROLE, data, 1)); +} + +int16_t SX128x::setPacketType(uint8_t type) { + uint8_t data[] = { type }; + return(SPIwriteCommand(SX128X_CMD_SET_PACKET_TYPE, data, 1)); +} + +int16_t SX128x::setHeaderType(uint8_t headerType, size_t len) { + // check active modem + uint8_t modem = getPacketType(); + if(!((modem == SX128X_PACKET_TYPE_LORA) || (modem == SX128X_PACKET_TYPE_RANGING))) { + return(ERR_WRONG_MODEM); + } + + // update packet parameters + _headerType = headerType; + _payloadLen = len; + return(setPacketParamsLoRa(_preambleLengthLoRa, _headerType, _payloadLen, _crcLoRa)); +} + +int16_t SX128x::config(uint8_t modem) { + // reset buffer base address + int16_t state = setBufferBaseAddress(); + RADIOLIB_ASSERT(state); + + // set modem + uint8_t data[1]; + data[0] = modem; + state = SPIwriteCommand(SX128X_CMD_SET_PACKET_TYPE, data, 1); + RADIOLIB_ASSERT(state); + + // set CAD parameters + data[0] = SX128X_CAD_ON_8_SYMB; + state = SPIwriteCommand(SX128X_CMD_SET_CAD_PARAMS, data, 1); + RADIOLIB_ASSERT(state); + + // set regulator mode to DC-DC + data[0] = SX128X_REGULATOR_DC_DC; + state = SPIwriteCommand(SX128X_CMD_SET_REGULATOR_MODE, data, 1); + RADIOLIB_ASSERT(state); + + return(ERR_NONE); +} + +int16_t SX128x::SPIwriteCommand(uint8_t* cmd, uint8_t cmdLen, uint8_t* data, uint8_t numBytes, bool waitForBusy) { + return(SX128x::SPItransfer(cmd, cmdLen, true, data, NULL, numBytes, waitForBusy)); +} + +int16_t SX128x::SPIwriteCommand(uint8_t cmd, uint8_t* data, uint8_t numBytes, bool waitForBusy) { + return(SX128x::SPItransfer(&cmd, 1, true, data, NULL, numBytes, waitForBusy)); +} + +int16_t SX128x::SPIreadCommand(uint8_t* cmd, uint8_t cmdLen, uint8_t* data, uint8_t numBytes, bool waitForBusy) { + return(SX128x::SPItransfer(cmd, cmdLen, false, NULL, data, numBytes, waitForBusy)); +} + +int16_t SX128x::SPIreadCommand(uint8_t cmd, uint8_t* data, uint8_t numBytes, bool waitForBusy) { + return(SX128x::SPItransfer(&cmd, 1, false, NULL, data, numBytes, waitForBusy)); +} + +int16_t SX128x::SPItransfer(uint8_t* cmd, uint8_t cmdLen, bool write, uint8_t* dataOut, uint8_t* dataIn, uint8_t numBytes, bool waitForBusy, uint32_t timeout) { + // get pointer to used SPI interface and the settings + SPIClass* spi = _mod->getSpi(); + SPISettings spiSettings = _mod->getSpiSettings(); + + #ifdef RADIOLIB_VERBOSE + uint8_t debugBuff[256]; + #endif + + // ensure BUSY is low (state machine ready) + uint32_t start = millis(); + while(digitalRead(_mod->getGpio())) { + yield(); + if(millis() - start >= timeout) { + digitalWrite(_mod->getCs(), HIGH); + return(ERR_SPI_CMD_TIMEOUT); + } + } + + // pull NSS low + digitalWrite(_mod->getCs(), LOW); + + // start transfer + spi->beginTransaction(spiSettings); + + // send command byte(s) + for(uint8_t n = 0; n < cmdLen; n++) { + spi->transfer(cmd[n]); + } + + // variable to save error during SPI transfer + uint8_t status = 0; + + // send/receive all bytes + if(write) { + for(uint8_t n = 0; n < numBytes; n++) { + // send byte + uint8_t in = spi->transfer(dataOut[n]); + #ifdef RADIOLIB_VERBOSE + debugBuff[n] = in; + #endif + + // check status + if(((in & 0b00011100) == SX128X_STATUS_CMD_TIMEOUT) || + ((in & 0b00011100) == SX128X_STATUS_CMD_ERROR) || + ((in & 0b00011100) == SX128X_STATUS_CMD_FAILED)) { + status = in & 0b00011100; + break; + } else if(in == 0x00 || in == 0xFF) { + status = SX128X_STATUS_SPI_FAILED; + break; + } + } + + } else { + // skip the first byte for read-type commands (status-only) + uint8_t in = spi->transfer(SX128X_CMD_NOP); + #ifdef RADIOLIB_VERBOSE + debugBuff[0] = in; + #endif + + // check status + if(((in & 0b00011100) == SX128X_STATUS_CMD_TIMEOUT) || + ((in & 0b00011100) == SX128X_STATUS_CMD_ERROR) || + ((in & 0b00011100) == SX128X_STATUS_CMD_FAILED)) { + status = in & 0b00011100; + } else if(in == 0x00 || in == 0xFF) { + status = SX128X_STATUS_SPI_FAILED; + } else { + for(uint8_t n = 0; n < numBytes; n++) { + dataIn[n] = spi->transfer(SX128X_CMD_NOP); + } + } + } + + // stop transfer + spi->endTransaction(); + digitalWrite(_mod->getCs(), HIGH); + + // wait for BUSY to go high and then low + if(waitForBusy) { + delayMicroseconds(1); + start = millis(); + while(digitalRead(_mod->getGpio())) { + yield(); + if(millis() - start >= timeout) { + status = SX128X_STATUS_CMD_TIMEOUT; + break; + } + } + } + + // print debug output + #ifdef RADIOLIB_VERBOSE + // print command byte(s) + RADIOLIB_VERBOSE_PRINT("CMD\t"); + for(uint8_t n = 0; n < cmdLen; n++) { + RADIOLIB_VERBOSE_PRINT(cmd[n], HEX); + RADIOLIB_VERBOSE_PRINT('\t'); + } + RADIOLIB_VERBOSE_PRINTLN(); + + // print data bytes + RADIOLIB_VERBOSE_PRINT("DAT"); + if(write) { + RADIOLIB_VERBOSE_PRINT("W\t"); + for(uint8_t n = 0; n < numBytes; n++) { + RADIOLIB_VERBOSE_PRINT(dataOut[n], HEX); + RADIOLIB_VERBOSE_PRINT('\t'); + RADIOLIB_VERBOSE_PRINT(debugBuff[n], HEX); + RADIOLIB_VERBOSE_PRINT('\t'); + } + RADIOLIB_VERBOSE_PRINTLN(); + } else { + RADIOLIB_VERBOSE_PRINT("R\t"); + // skip the first byte for read-type commands (status-only) + RADIOLIB_VERBOSE_PRINT(SX128X_CMD_NOP, HEX); + RADIOLIB_VERBOSE_PRINT('\t'); + RADIOLIB_VERBOSE_PRINT(debugBuff[0], HEX); + RADIOLIB_VERBOSE_PRINT('\t') + + for(uint8_t n = 0; n < numBytes; n++) { + RADIOLIB_VERBOSE_PRINT(SX128X_CMD_NOP, HEX); + RADIOLIB_VERBOSE_PRINT('\t'); + RADIOLIB_VERBOSE_PRINT(dataIn[n], HEX); + RADIOLIB_VERBOSE_PRINT('\t'); + } + RADIOLIB_VERBOSE_PRINTLN(); + } + RADIOLIB_VERBOSE_PRINTLN(); + #else + // some faster platforms require a short delay here + // not sure why, but it seems that long enough SPI transaction + // (e.g. setPacketParams for GFSK) will fail without it + #if defined(ARDUINO_ARCH_STM32) || defined(SAMD_SERIES) + delay(1); + #endif + #endif + + // parse status + switch(status) { + case SX128X_STATUS_CMD_TIMEOUT: + return(ERR_SPI_CMD_TIMEOUT); + case SX128X_STATUS_CMD_ERROR: + return(ERR_SPI_CMD_INVALID); + case SX128X_STATUS_CMD_FAILED: + return(ERR_SPI_CMD_FAILED); + case SX128X_STATUS_SPI_FAILED: + return(ERR_CHIP_NOT_FOUND); + default: + return(ERR_NONE); + } +} + +#endif diff --git a/src/modules/SX128x/SX128x.h b/src/modules/SX128x/SX128x.h new file mode 100644 index 00000000..bf82c0cc --- /dev/null +++ b/src/modules/SX128x/SX128x.h @@ -0,0 +1,821 @@ +#if !defined(_RADIOLIB_SX128X_H) +#define _RADIOLIB_SX128X_H + +#include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SX128X) + +#include "../../Module.h" + +#include "../../protocols/PhysicalLayer/PhysicalLayer.h" + +// SX128X physical layer properties +#define SX128X_FREQUENCY_STEP_SIZE 198.3642578 +#define SX128X_MAX_PACKET_LENGTH 255 +#define SX128X_CRYSTAL_FREQ 52.0 +#define SX128X_DIV_EXPONENT 18 + +// SX128X SPI commands +#define SX128X_CMD_NOP 0x00 +#define SX128X_CMD_GET_STATUS 0xC0 +#define SX128X_CMD_WRITE_REGISTER 0x18 +#define SX128X_CMD_READ_REGISTER 0x19 +#define SX128X_CMD_WRITE_BUFFER 0x1A +#define SX128X_CMD_READ_BUFFER 0x1B +#define SX128X_CMD_SET_SLEEP 0x84 +#define SX128X_CMD_SET_STANDBY 0x80 +#define SX128X_CMD_SET_FS 0xC1 +#define SX128X_CMD_SET_TX 0x83 +#define SX128X_CMD_SET_RX 0x82 +#define SX128X_CMD_SET_RX_DUTY_CYCLE 0x94 +#define SX128X_CMD_SET_CAD 0xC5 +#define SX128X_CMD_SET_TX_CONTINUOUS_WAVE 0xD1 +#define SX128X_CMD_SET_TX_CONTINUOUS_PREAMBLE 0xD2 +#define SX128X_CMD_SET_PACKET_TYPE 0x8A +#define SX128X_CMD_GET_PACKET_TYPE 0x03 +#define SX128X_CMD_SET_RF_FREQUENCY 0x86 +#define SX128X_CMD_SET_TX_PARAMS 0x8E +#define SX128X_CMD_SET_CAD_PARAMS 0x88 +#define SX128X_CMD_SET_BUFFER_BASE_ADDRESS 0x8F +#define SX128X_CMD_SET_MODULATION_PARAMS 0x8B +#define SX128X_CMD_SET_PACKET_PARAMS 0x8C +#define SX128X_CMD_GET_RX_BUFFER_STATUS 0x17 +#define SX128X_CMD_GET_PACKET_STATUS 0x1D +#define SX128X_CMD_GET_RSSI_INST 0x1F +#define SX128X_CMD_SET_DIO_IRQ_PARAMS 0x8D +#define SX128X_CMD_GET_IRQ_STATUS 0x15 +#define SX128X_CMD_CLEAR_IRQ_STATUS 0x97 +#define SX128X_CMD_SET_REGULATOR_MODE 0x96 +#define SX128X_CMD_SET_SAVE_CONTEXT 0xD5 +#define SX128X_CMD_SET_AUTO_TX 0x98 +#define SX128X_CMD_SET_AUTO_FS 0x9E +#define SX128X_CMD_SET_PERF_COUNTER_MODE 0x9C +#define SX128X_CMD_SET_LONG_PREAMBLE 0x9B +#define SX128X_CMD_SET_UART_SPEED 0x9D +#define SX128X_CMD_SET_RANGING_ROLE 0xA3 +#define SX128X_CMD_SET_ADVANCED_RANGING 0x9A + +// SX128X register map +#define SX128X_REG_SYNC_WORD_1_BYTE_4 0x09CE +#define SX128X_REG_SYNC_WORD_1_BYTE_3 0x09CF +#define SX128X_REG_SYNC_WORD_1_BYTE_2 0x09D0 +#define SX128X_REG_SYNC_WORD_1_BYTE_1 0x09D1 +#define SX128X_REG_SYNC_WORD_1_BYTE_0 0x09D2 +#define SX128X_REG_SYNC_WORD_2_BYTE_4 0x09D3 +#define SX128X_REG_SYNC_WORD_2_BYTE_3 0x09D4 +#define SX128X_REG_SYNC_WORD_2_BYTE_2 0x09D5 +#define SX128X_REG_SYNC_WORD_2_BYTE_1 0x09D6 +#define SX128X_REG_SYNC_WORD_2_BYTE_0 0x09D7 +#define SX128X_REG_SYNC_WORD_3_BYTE_4 0x09D8 +#define SX128X_REG_SYNC_WORD_3_BYTE_3 0x09D9 +#define SX128X_REG_SYNC_WORD_3_BYTE_2 0x09DA +#define SX128X_REG_SYNC_WORD_3_BYTE_1 0x09DB +#define SX128X_REG_SYNC_WORD_3_BYTE_0 0x09DC +#define SX128X_REG_CRC_INITIAL_MSB 0x09C8 +#define SX128X_REG_CRC_INITIAL_LSB 0x09C9 +#define SX128X_REG_CRC_POLYNOMIAL_MSB 0x09C6 +#define SX128X_REG_CRC_POLYNOMIAL_LSB 0x09C7 +#define SX128X_REG_ACCESS_ADDRESS_BYTE_3 (SX128X_REG_SYNC_WORD_1_BYTE_3) +#define SX128X_REG_ACCESS_ADDRESS_BYTE_2 (SX128X_REG_SYNC_WORD_1_BYTE_2) +#define SX128X_REG_ACCESS_ADDRESS_BYTE_1 (SX128X_REG_SYNC_WORD_1_BYTE_1) +#define SX128X_REG_ACCESS_ADDRESS_BYTE_0 (SX128X_REG_SYNC_WORD_1_BYTE_0) +#define SX128X_REG_BLE_CRC_INITIAL_MSB 0x09C7 +#define SX128X_REG_BLE_CRC_INITIAL_MID (SX128X_REG_CRC_INITIAL_MSB) +#define SX128X_REG_BLE_CRC_INITIAL_LSB (SX128X_REG_CRC_INITIAL_LSB) +#define SX128X_REG_SLAVE_RANGING_ADDRESS_BYTE_3 0x0916 +#define SX128X_REG_SLAVE_RANGING_ADDRESS_BYTE_2 0x0917 +#define SX128X_REG_SLAVE_RANGING_ADDRESS_BYTE_1 0x0918 +#define SX128X_REG_SLAVE_RANGING_ADDRESS_BYTE_0 0x0919 +#define SX128X_REG_SLAVE_RANGING_ADDRESS_WIDTH 0x0931 +#define SX128X_REG_MASTER_RANGING_ADDRESS_BYTE_3 0x0912 +#define SX128X_REG_MASTER_RANGING_ADDRESS_BYTE_2 0x0913 +#define SX128X_REG_MASTER_RANGING_ADDRESS_BYTE_1 0x0914 +#define SX128X_REG_MASTER_RANGING_ADDRESS_BYTE_0 0x0915 +#define SX128X_REG_RANGING_CALIBRATION_MSB 0x092C +#define SX128X_REG_RANGING_CALIBRATION_LSB 0x092D +#define SX128X_REG_RANGING_RESULT_MSB 0x0961 +#define SX128X_REG_RANGING_RESULT_MID 0x0962 +#define SX128X_REG_RANGING_RESULT_LSB 0x0963 +#define SX128X_REG_MANUAL_GAIN_CONTROL_ENABLE_1 0x089F +#define SX128X_REG_MANUAL_GAIN_CONTROL_ENABLE_2 0x0895 +#define SX128X_REG_MANUAL_GAIN_SETTING 0x089E +#define SX128X_REG_GAIN_MODE 0x0891 +#define SX128X_REG_LORA_FIXED_PAYLOAD_LENGTH 0x0901 +#define SX128X_REG_LORA_SF_CONFIG 0x0925 +#define SX128X_REG_FEI_MSB 0x0954 +#define SX128X_REG_FEI_MID 0x0955 +#define SX128X_REG_FEI_LSB 0x0956 +#define SX128X_REG_RANGING_FILTER_WINDOW_SIZE 0x091E +#define SX128X_REG_RANGING_FILTER_RSSI_OFFSET 0x0953 +#define SX128X_REG_RANGING_FILTER_RESET 0x0923 +#define SX128X_REG_RANGING_LORA_CLOCK_ENABLE 0x097F +#define SX128X_REG_RANGING_TYPE 0x0924 +#define SX128X_REG_RANGING_ADDRESS_SWITCH 0x0927 +#define SX128X_REG_RANGING_ADDRESS_MSB 0x095F +#define SX128X_REG_RANGING_ADDRESS_LSB 0x0960 + + +// SX128X SPI command variables +//SX128X_CMD_GET_STATUS MSB LSB DESCRIPTION +#define SX128X_STATUS_MODE_STDBY_RC 0b01000000 // 7 5 current chip mode: STDBY_RC +#define SX128X_STATUS_MODE_STDBY_XOSC 0b01100000 // 7 5 STDBY_XOSC +#define SX128X_STATUS_MODE_FS 0b10000000 // 7 5 FS +#define SX128X_STATUS_MODE_RX 0b10100000 // 7 5 Rx +#define SX128X_STATUS_MODE_TX 0b11000000 // 7 5 Tx +#define SX128X_STATUS_CMD_PROCESSED 0b00000100 // 4 2 command status: processing OK +#define SX128X_STATUS_DATA_AVAILABLE 0b00001000 // 4 2 data available +#define SX128X_STATUS_CMD_TIMEOUT 0b00001100 // 4 2 timeout +#define SX128X_STATUS_CMD_ERROR 0b00010000 // 4 2 processing error +#define SX128X_STATUS_CMD_FAILED 0b00010100 // 4 2 failed to execute +#define SX128X_STATUS_TX_DONE 0b00011000 // 4 2 transmission finished +#define SX128X_STATUS_BUSY 0b00000001 // 0 0 chip busy +#define SX128X_STATUS_SPI_FAILED 0b11111111 // 7 0 SPI transaction failed + +//SX128X_CMD_SET_SLEEP +#define SX128X_SLEEP_DATA_BUFFER_FLUSH 0b00000000 // 1 1 data buffer behavior in sleep mode: flush +#define SX128X_SLEEP_DATA_BUFFER_RETAIN 0b00000010 // 1 1 retain +#define SX128X_SLEEP_DATA_RAM_FLUSH 0b00000000 // 0 0 data RAM (configuration) behavior in sleep mode: flush +#define SX128X_SLEEP_DATA_RAM_RETAIN 0b00000001 // 0 0 retain + +//SX128X_CMD_SET_STANDBY +#define SX128X_STANDBY_RC 0x00 // 7 0 standby mode: 13 MHz RC oscillator +#define SX128X_STANDBY_XOSC 0x01 // 7 0 52 MHz crystal oscillator + +//SX128X_CMD_SET_TX + SX128X_CMD_SET_RX + SX128X_CMD_SET_RX_DUTY_CYCLE +#define SX128X_PERIOD_BASE_15_625_US 0x00 // 7 0 time period step: 15.625 us +#define SX128X_PERIOD_BASE_62_5_US 0x01 // 7 0 62.5 us +#define SX128X_PERIOD_BASE_1_MS 0x02 // 7 0 1 ms +#define SX128X_PERIOD_BASE_4_MS 0x03 // 7 0 4 ms + +//SX128X_CMD_SET_TX +#define SX128X_TX_TIMEOUT_NONE 0x0000 // 15 0 Tx timeout duration: no timeout (Tx single mode) + +//SX128X_CMD_SET_RX +#define SX128X_RX_TIMEOUT_NONE 0x0000 // 15 0 Rx timeout duration: no timeout (Rx single mode) +#define SX128X_RX_TIMEOUT_INF 0xFFFF // 15 0 infinite (Rx continuous mode) + +//SX128X_CMD_SET_PACKET_TYPE +#define SX128X_PACKET_TYPE_GFSK 0x00 // 7 0 packet type: (G)FSK +#define SX128X_PACKET_TYPE_LORA 0x01 // 7 0 LoRa +#define SX128X_PACKET_TYPE_RANGING 0x02 // 7 0 ranging engine +#define SX128X_PACKET_TYPE_FLRC 0x03 // 7 0 FLRC +#define SX128X_PACKET_TYPE_BLE 0x04 // 7 0 BLE + +//SX128X_CMD_SET_TX_PARAMS +#define SX128X_PA_RAMP_02_US 0x00 // 7 0 PA ramp time: 2 us +#define SX128X_PA_RAMP_04_US 0x20 // 7 0 4 us +#define SX128X_PA_RAMP_06_US 0x40 // 7 0 6 us +#define SX128X_PA_RAMP_08_US 0x60 // 7 0 8 us +#define SX128X_PA_RAMP_10_US 0x80 // 7 0 10 us +#define SX128X_PA_RAMP_12_US 0xA0 // 7 0 12 us +#define SX128X_PA_RAMP_16_US 0xC0 // 7 0 16 us +#define SX128X_PA_RAMP_20_US 0xE0 // 7 0 20 us + +//SX128X_CMD_SET_CAD_PARAMS +#define SX128X_CAD_ON_1_SYMB 0x00 // 7 0 number of symbols used for CAD: 1 +#define SX128X_CAD_ON_2_SYMB 0x20 // 7 0 2 +#define SX128X_CAD_ON_4_SYMB 0x40 // 7 0 4 +#define SX128X_CAD_ON_8_SYMB 0x60 // 7 0 8 +#define SX128X_CAD_ON_16_SYMB 0x80 // 7 0 16 + +//SX128X_CMD_SET_MODULATION_PARAMS +#define SX128X_BLE_GFSK_BR_2_000_BW_2_4 0x04 // 7 0 GFSK/BLE bit rate and bandwidth setting: 2.0 Mbps 2.4 MHz +#define SX128X_BLE_GFSK_BR_1_600_BW_2_4 0x28 // 7 0 1.6 Mbps 2.4 MHz +#define SX128X_BLE_GFSK_BR_1_000_BW_2_4 0x4C // 7 0 1.0 Mbps 2.4 MHz +#define SX128X_BLE_GFSK_BR_1_000_BW_1_2 0x45 // 7 0 1.0 Mbps 1.2 MHz +#define SX128X_BLE_GFSK_BR_0_800_BW_2_4 0x70 // 7 0 0.8 Mbps 2.4 MHz +#define SX128X_BLE_GFSK_BR_0_800_BW_1_2 0x69 // 7 0 0.8 Mbps 1.2 MHz +#define SX128X_BLE_GFSK_BR_0_500_BW_1_2 0x8D // 7 0 0.5 Mbps 1.2 MHz +#define SX128X_BLE_GFSK_BR_0_500_BW_0_6 0x86 // 7 0 0.5 Mbps 0.6 MHz +#define SX128X_BLE_GFSK_BR_0_400_BW_1_2 0xB1 // 7 0 0.4 Mbps 1.2 MHz +#define SX128X_BLE_GFSK_BR_0_400_BW_0_6 0xAA // 7 0 0.4 Mbps 0.6 MHz +#define SX128X_BLE_GFSK_BR_0_250_BW_0_6 0xCE // 7 0 0.25 Mbps 0.6 MHz +#define SX128X_BLE_GFSK_BR_0_250_BW_0_3 0xC7 // 7 0 0.25 Mbps 0.3 MHz +#define SX128X_BLE_GFSK_BR_0_125_BW_0_3 0xEF // 7 0 0.125 Mbps 0.3 MHz +#define SX128X_BLE_GFSK_MOD_IND_0_35 0x00 // 7 0 GFSK/BLE modulation index: 0.35 +#define SX128X_BLE_GFSK_MOD_IND_0_50 0x01 // 7 0 0.50 +#define SX128X_BLE_GFSK_MOD_IND_0_75 0x02 // 7 0 0.75 +#define SX128X_BLE_GFSK_MOD_IND_1_00 0x03 // 7 0 1.00 +#define SX128X_BLE_GFSK_MOD_IND_1_25 0x04 // 7 0 1.25 +#define SX128X_BLE_GFSK_MOD_IND_1_50 0x05 // 7 0 1.50 +#define SX128X_BLE_GFSK_MOD_IND_1_75 0x06 // 7 0 1.75 +#define SX128X_BLE_GFSK_MOD_IND_2_00 0x07 // 7 0 2.00 +#define SX128X_BLE_GFSK_MOD_IND_2_25 0x08 // 7 0 2.25 +#define SX128X_BLE_GFSK_MOD_IND_2_50 0x09 // 7 0 2.50 +#define SX128X_BLE_GFSK_MOD_IND_2_75 0x0A // 7 0 2.75 +#define SX128X_BLE_GFSK_MOD_IND_3_00 0x0B // 7 0 3.00 +#define SX128X_BLE_GFSK_MOD_IND_3_25 0x0C // 7 0 3.25 +#define SX128X_BLE_GFSK_MOD_IND_3_50 0x0D // 7 0 3.50 +#define SX128X_BLE_GFSK_MOD_IND_3_75 0x0E // 7 0 3.75 +#define SX128X_BLE_GFSK_MOD_IND_4_00 0x0F // 7 0 4.00 +#define SX128X_BLE_GFSK_BT_OFF 0x00 // 7 0 GFSK Gaussian filter BT product: filter disabled +#define SX128X_BLE_GFSK_BT_1_0 0x10 // 7 0 1.0 +#define SX128X_BLE_GFSK_BT_0_5 0x20 // 7 0 0.5 +#define SX128X_FLRC_BR_1_300_BW_1_2 0x45 // 7 0 FLRC bit rate and bandwidth setting: 1.3 Mbps 1.2 MHz +#define SX128X_FLRC_BR_1_000_BW_1_2 0x69 // 7 0 1.04 Mbps 1.2 MHz +#define SX128X_FLRC_BR_0_650_BW_0_6 0x86 // 7 0 0.65 Mbps 0.6 MHz +#define SX128X_FLRC_BR_0_520_BW_0_6 0xAA // 7 0 0.52 Mbps 0.6 MHz +#define SX128X_FLRC_BR_0_325_BW_0_3 0xC7 // 7 0 0.325 Mbps 0.3 MHz +#define SX128X_FLRC_BR_0_260_BW_0_3 0xEB // 7 0 0.260 Mbps 0.3 MHz +#define SX128X_FLRC_CR_1_2 0x00 // 7 0 FLRC coding rate: 1/2 +#define SX128X_FLRC_CR_3_4 0x02 // 7 0 3/4 +#define SX128X_FLRC_CR_1_0 0x04 // 7 0 1/1 +#define SX128X_FLRC_BT_OFF 0x00 // 7 0 FLRC Gaussian filter BT product: filter disabled +#define SX128X_FLRC_BT_1_0 0x10 // 7 0 1.0 +#define SX128X_FLRC_BT_0_5 0x20 // 7 0 0.5 +#define SX128X_LORA_SF_5 0x50 // 7 0 LoRa spreading factor: 5 +#define SX128X_LORA_SF_6 0x60 // 7 0 6 +#define SX128X_LORA_SF_7 0x70 // 7 0 7 +#define SX128X_LORA_SF_8 0x80 // 7 0 8 +#define SX128X_LORA_SF_9 0x90 // 7 0 9 +#define SX128X_LORA_SF_10 0xA0 // 7 0 10 +#define SX128X_LORA_SF_11 0xB0 // 7 0 11 +#define SX128X_LORA_SF_12 0xC0 // 7 0 12 +#define SX128X_LORA_BW_1625_00 0x0A // 7 0 LoRa bandwidth: 1625.0 kHz +#define SX128X_LORA_BW_812_50 0x18 // 7 0 812.5 kHz +#define SX128X_LORA_BW_406_25 0x26 // 7 0 406.25 kHz +#define SX128X_LORA_BW_203_125 0x34 // 7 0 203.125 kHz +#define SX128X_LORA_CR_4_5 0x01 // 7 0 LoRa coding rate: 4/5 +#define SX128X_LORA_CR_4_6 0x02 // 7 0 4/6 +#define SX128X_LORA_CR_4_7 0x03 // 7 0 4/7 +#define SX128X_LORA_CR_4_8 0x04 // 7 0 4/8 +#define SX128X_LORA_CR_4_5_LI 0x05 // 7 0 4/5, long interleaving +#define SX128X_LORA_CR_4_6_LI 0x06 // 7 0 4/6, long interleaving +#define SX128X_LORA_CR_4_7_LI 0x07 // 7 0 4/7, long interleaving + +//SX128X_CMD_SET_PACKET_PARAMS +#define SX128X_GFSK_FLRC_SYNC_WORD_OFF 0x00 // 7 0 GFSK/FLRC sync word used: none +#define SX128X_GFSK_FLRC_SYNC_WORD_1 0x10 // 7 0 sync word 1 +#define SX128X_GFSK_FLRC_SYNC_WORD_2 0x20 // 7 0 sync word 2 +#define SX128X_GFSK_FLRC_SYNC_WORD_1_2 0x30 // 7 0 sync words 1 and 2 +#define SX128X_GFSK_FLRC_SYNC_WORD_3 0x40 // 7 0 sync word 3 +#define SX128X_GFSK_FLRC_SYNC_WORD_1_3 0x50 // 7 0 sync words 1 and 3 +#define SX128X_GFSK_FLRC_SYNC_WORD_2_3 0x60 // 7 0 sync words 2 and 3 +#define SX128X_GFSK_FLRC_SYNC_WORD_1_2_3 0x70 // 7 0 sync words 1, 2 and 3 +#define SX128X_GFSK_FLRC_PACKET_FIXED 0x00 // 7 0 GFSK/FLRC packet length mode: fixed +#define SX128X_GFSK_FLRC_PACKET_VARIABLE 0x20 // 7 0 variable +#define SX128X_GFSK_FLRC_CRC_OFF 0x00 // 7 0 GFSK/FLRC packet CRC: none +#define SX128X_GFSK_FLRC_CRC_1_BYTE 0x10 // 7 0 1 byte +#define SX128X_GFSK_FLRC_CRC_2_BYTE 0x20 // 7 0 2 bytes +#define SX128X_GFSK_FLRC_CRC_3_BYTE 0x30 // 7 0 3 bytes (FLRC only) +#define SX128X_GFSK_BLE_WHITENING_ON 0x00 // 7 0 GFSK/BLE whitening: enabled +#define SX128X_GFSK_BLE_WHITENING_OFF 0x08 // 7 0 disabled +#define SX128X_BLE_PAYLOAD_LENGTH_MAX_31 0x00 // 7 0 BLE maximum payload length: 31 bytes +#define SX128X_BLE_PAYLOAD_LENGTH_MAX_37 0x20 // 7 0 37 bytes +#define SX128X_BLE_PAYLOAD_LENGTH_TEST 0x40 // 7 0 63 bytes (test mode) +#define SX128X_BLE_PAYLOAD_LENGTH_MAX_255 0x80 // 7 0 255 bytes (Bluetooth 4.2 and above) +#define SX128X_BLE_CRC_OFF 0x00 // 7 0 BLE packet CRC: none +#define SX128X_BLE_CRC_3_BYTE 0x10 // 7 0 3 byte +#define SX128X_BLE_PRBS_9 0x00 // 7 0 BLE test payload contents: PRNG sequence using x^9 + x^5 + x +#define SX128X_BLE_EYELONG 0x04 // 7 0 repeated 0xF0 +#define SX128X_BLE_EYESHORT 0x08 // 7 0 repeated 0xAA +#define SX128X_BLE_PRBS_15 0x0C // 7 0 PRNG sequence using x^15 + x^14 + x^13 + x^12 + x^2 + x + 1 +#define SX128X_BLE_ALL_1 0x10 // 7 0 repeated 0xFF +#define SX128X_BLE_ALL_0 0x14 // 7 0 repeated 0x00 +#define SX128X_BLE_EYELONG_INV 0x18 // 7 0 repeated 0x0F +#define SX128X_BLE_EYESHORT_INV 0x1C // 7 0 repeated 0x55 +#define SX128X_FLRC_SYNC_WORD_OFF 0x00 // 7 0 FLRC sync word: disabled +#define SX128X_FLRC_SYNC_WORD_ON 0x04 // 7 0 enabled +#define SX128X_LORA_HEADER_EXPLICIT 0x00 // 7 0 LoRa header mode: explicit +#define SX128X_LORA_HEADER_IMPLICIT 0x80 // 7 0 implicit +#define SX128X_LORA_CRC_OFF 0x00 // 7 0 LoRa packet CRC: disabled +#define SX128X_LORA_CRC_ON 0x20 // 7 0 enabled +#define SX128X_LORA_IQ_STANDARD 0x40 // 7 0 LoRa IQ: standard +#define SX128X_LORA_IQ_INVERTED 0x00 // 7 0 inverted + +//SX128X_CMD_GET_PACKET_STATUS +#define SX128X_PACKET_STATUS_SYNC_ERROR 0b01000000 // 6 6 packet status errors byte: sync word error +#define SX128X_PACKET_STATUS_LENGTH_ERROR 0b00100000 // 5 5 packet length error +#define SX128X_PACKET_STATUS_CRC_ERROR 0b00010000 // 4 4 CRC error +#define SX128X_PACKET_STATUS_ABORT_ERROR 0b00001000 // 3 3 packet reception aborted +#define SX128X_PACKET_STATUS_HEADER_RECEIVED 0b00000100 // 2 2 header received +#define SX128X_PACKET_STATUS_PACKET_RECEIVED 0b00000010 // 1 1 packet received +#define SX128X_PACKET_STATUS_PACKET_CTRL_BUSY 0b00000001 // 0 0 packet controller is busy +#define SX128X_PACKET_STATUS_RX_PID 0b11000000 // 7 6 packet status status byte: PID field of the received packet +#define SX128X_PACKET_STATUS_NO_ACK 0b00100000 // 5 5 NO_ACK field of the received packet +#define SX128X_PACKET_STATUS_RX_PID_ERROR 0b00010000 // 4 4 PID field error +#define SX128X_PACKET_STATUS_PACKET_SENT 0b00000001 // 0 0 packet sent +#define SX128X_PACKET_STATUS_SYNC_DET_ERROR 0b00000000 // 2 0 packet status sync byte: sync word detection error +#define SX128X_PACKET_STATUS_SYNC_DET_1 0b00000001 // 2 0 detected sync word 1 +#define SX128X_PACKET_STATUS_SYNC_DET_2 0b00000010 // 2 0 detected sync word 2 +#define SX128X_PACKET_STATUS_SYNC_DET_3 0b00000100 // 2 0 detected sync word 3 + +//SX128X_CMD_SET_DIO_IRQ_PARAMS +#define SX128X_IRQ_PREAMBLE_DETECTED 0x8000 // 15 15 interrupt source: preamble detected +#define SX128X_IRQ_ADVANCED_RANGING_DONE 0x8000 // 15 15 advanced ranging done +#define SX128X_IRQ_RX_TX_TIMEOUT 0x4000 // 14 14 Rx or Tx timeout +#define SX128X_IRQ_CAD_DETECTED 0x2000 // 13 13 channel activity detected +#define SX128X_IRQ_CAD_DONE 0x1000 // 12 12 CAD finished +#define SX128X_IRQ_RANGING_SLAVE_REQ_VALID 0x0800 // 11 11 ranging request valid (slave) +#define SX128X_IRQ_RANGING_MASTER_TIMEOUT 0x0400 // 10 10 ranging timeout (master) +#define SX128X_IRQ_RANGING_MASTER_RES_VALID 0x0200 // 9 9 ranging result valid (master) +#define SX128X_IRQ_RANGING_SLAVE_REQ_DISCARD 0x0100 // 8 8 ranging result valid (master) +#define SX128X_IRQ_RANGING_SLAVE_RESP_DONE 0x0080 // 7 7 ranging response complete (slave) +#define SX128X_IRQ_CRC_ERROR 0x0040 // 6 6 CRC error +#define SX128X_IRQ_HEADER_ERROR 0x0020 // 5 5 header error +#define SX128X_IRQ_HEADER_VALID 0x0010 // 4 4 header valid +#define SX128X_IRQ_SYNC_WORD_ERROR 0x0008 // 3 3 sync word error +#define SX128X_IRQ_SYNC_WORD_VALID 0x0004 // 2 2 sync word valid +#define SX128X_IRQ_RX_DONE 0x0002 // 1 1 Rx done +#define SX128X_IRQ_TX_DONE 0x0001 // 0 0 Tx done +#define SX128X_IRQ_NONE 0x0000 // 15 0 none +#define SX128X_IRQ_ALL 0xFFFF // 15 0 all + +//SX128X_CMD_SET_REGULATOR_MODE +#define SX128X_REGULATOR_LDO 0x00 // 7 0 set regulator mode: LDO (default) +#define SX128X_REGULATOR_DC_DC 0x01 // 7 0 DC-DC + +//SX128X_CMD_SET_RANGING_ROLE +#define SX128X_RANGING_ROLE_MASTER 0x01 // 7 0 ranging role: master +#define SX128X_RANGING_ROLE_SLAVE 0x00 // 7 0 slave + + +/*! + \class SX128x + + \brief Base class for %SX128x series. All derived classes for %SX128x (e.g. SX1280 or SX1281) inherit from this base class. + This class should not be instantiated directly from Arduino sketch, only from its derived classes. +*/ +class SX128x: public PhysicalLayer { + public: + // introduce PhysicalLayer overloads + using PhysicalLayer::transmit; + using PhysicalLayer::receive; + using PhysicalLayer::startTransmit; + using PhysicalLayer::readData; + + /*! + \brief Default constructor. + + \param mod Instance of Module that will be used to communicate with the radio. + */ + SX128x(Module* mod); + + // basic methods + + /*! + \brief Initialization method for LoRa modem. + + \param freq Carrier frequency in MHz. Defaults to 2400.0 MHz. + + \param bw LoRa bandwidth in kHz. Defaults to 812.5 kHz. + + \param sf LoRa spreading factor. Defaults to 9. + + \param cr LoRa coding rate denominator. Defaults to 7 (coding rate 4/7). + + \param power Output power in dBm. Defaults to 10 dBm. + + \param preambleLength LoRa preamble length in symbols. Defaults to 12 symbols. + + \returns \ref status_codes + */ + int16_t begin(float freq = 2400.0, float bw = 812.5, uint8_t sf = 9, uint8_t cr = 7, int8_t power = 10, uint16_t preambleLength = 12); + + /*! + \brief Initialization method for GFSK modem. + + \param freq Carrier frequency in MHz. Defaults to 2400.0 MHz. + + \param br FSK bit rate in kbps. Defaults to 800 kbps. + + \param freqDev Frequency deviation from carrier frequency in kHz. Defaults to 400.0 kHz. + + \param power Output power in dBm. Defaults to 10 dBm. + + \parma preambleLength FSK preamble length in bits. Defaults to 16 bits. + + \returns \ref status_codes + */ + int16_t beginGFSK(float freq = 2400.0, uint16_t br = 800, float freqDev = 400.0, int8_t power = 10, uint16_t preambleLength = 16); + + /*! + \brief Initialization method for BLE modem. + + \param freq Carrier frequency in MHz. Defaults to 2400.0 MHz. + + \param br BLE bit rate in kbps. Defaults to 800 kbps. + + \param freqDev Frequency deviation from carrier frequency in kHz. Defaults to 400.0 kHz. + + \param power Output power in dBm. Defaults to 10 dBm. + + \param dataShaping Time-bandwidth product of the Gaussian filter to be used for shaping. Defaults to 0.5. + + \returns \ref status_codes + */ + int16_t beginBLE(float freq = 2400.0, uint16_t br = 800, float freqDev = 400.0, int8_t power = 10, uint8_t dataShaping = RADIOLIB_SHAPING_0_5); + + /*! + \brief Initialization method for FLRC modem. + + \param freq Carrier frequency in MHz. Defaults to 2400.0 MHz. + + \param br FLRC bit rate in kbps. Defaults to 650 kbps. + + \param cr FLRC coding rate. Defaults to 3 (coding rate 3/4). + + \param power Output power in dBm. Defaults to 10 dBm. + + \parma preambleLength FLRC preamble length in bits. Defaults to 16 bits. + + \param dataShaping Time-bandwidth product of the Gaussian filter to be used for shaping. Defaults to 0.5. + + \returns \ref status_codes + */ + int16_t beginFLRC(float freq = 2400.0, uint16_t br = 650, uint8_t cr = 3, int8_t power = 10, uint16_t preambleLength = 16, uint8_t dataShaping = RADIOLIB_SHAPING_0_5); + + /*! + \brief Reset method. Will reset the chip to the default state using RST pin. + + \param verify Whether correct module startup should be verified. When set to true, RadioLib will attempt to verify the module has started correctly + by repeatedly issuing setStandby command. Enabled by default. + + \returns \ref status_codes + */ + int16_t reset(bool verify = true); + + /*! + \brief Blocking binary transmit method. + Overloads for string-based transmissions are implemented in PhysicalLayer. + + \param data Binary data to be sent. + + \param len Number of bytes to send. + + \param addr Address to send the data to. Unsupported, compatibility only. + + \returns \ref status_codes + */ + int16_t transmit(uint8_t* data, size_t len, uint8_t addr = 0) override; + + /*! + \brief Blocking binary receive method. + Overloads for string-based transmissions are implemented in PhysicalLayer. + + \param data Binary data to be sent. + + \param len Number of bytes to send. + + \returns \ref status_codes + */ + int16_t receive(uint8_t* data, size_t len) override; + + /*! + \brief Starts direct mode transmission. + + \param frf Raw RF frequency value. Defaults to 0, required for quick frequency shifts in RTTY. + + \returns \ref status_codes + */ + int16_t transmitDirect(uint32_t frf = 0) override; + + /*! + \brief Starts direct mode reception. Only implemented for PhysicalLayer compatibility, as %SX128x series does not support direct mode reception. + Will always return ERR_UNKNOWN. + + \returns \ref status_codes + */ + int16_t receiveDirect() override; + + /*! + \brief Performs scan for LoRa transmission in the current channel. Detects both preamble and payload. + + \returns \ref status_codes + */ + int16_t scanChannel(); + + /*! + \brief Sets the module to sleep mode. + + \param retainConfig Set to true to retain configuration and data buffer or to false to discard current configuration and data buffer. Defaults to true. + + \returns \ref status_codes + */ + int16_t sleep(bool retainConfig = true); + + /*! + \brief Sets the module to standby mode (overload for PhysicalLayer compatibility, uses 13 MHz RC oscillator). + + \returns \ref status_codes + */ + int16_t standby() override; + + /*! + \brief Sets the module to standby mode. + + \param mode Oscillator to be used in standby mode. Can be set to SX128X_STANDBY_RC (13 MHz RC oscillator) or SX128X_STANDBY_XOSC (52 MHz external crystal oscillator). + + \returns \ref status_codes + */ + int16_t standby(uint8_t mode); + + // interrupt methods + + /*! + \brief Sets interrupt service routine to call when DIO1 activates. + + \param func ISR to call. + */ + void setDio1Action(void (*func)(void)); + + /*! + \brief Clears interrupt service routine to call when DIO1 activates. + */ + void clearDio1Action(); + + /*! + \brief Interrupt-driven binary transmit method. + Overloads for string-based transmissions are implemented in PhysicalLayer. + + \param data Binary data to be sent. + + \param len Number of bytes to send. + + \param addr Address to send the data to. Unsupported, compatibility only. + + \returns \ref status_codes + */ + int16_t startTransmit(uint8_t* data, size_t len, uint8_t addr = 0) override; + + /*! + \brief Interrupt-driven receive method. DIO1 will be activated when full packet is received. + + \param timeout Raw timeout value, expressed as multiples of 15.625 us. Defaults to SX128X_RX_TIMEOUT_INF for infinite timeout (Rx continuous mode), set to SX128X_RX_TIMEOUT_NONE for no timeout (Rx single mode). + + \returns \ref status_codes + */ + int16_t startReceive(uint16_t timeout = SX128X_RX_TIMEOUT_INF); + + /*! + \brief Reads data received after calling startReceive method. + + \param data Pointer to array to save the received binary data. + + \param len Number of bytes that will be received. Must be known in advance for binary transmissions. + + \returns \ref status_codes + */ + int16_t readData(uint8_t* data, size_t len) override; + + // configuration methods + + /*! + \brief Sets carrier frequency. Allowed values are in range from 2400.0 to 2500.0 MHz. + + \param freq Carrier frequency to be set in MHz. + + \returns \ref status_codes + */ + int16_t setFrequency(float freq); + + /*! + \brief Sets LoRa bandwidth. Allowed values are 203.125, 406.25, 812.5 and 1625.0 kHz. + + \param bw LoRa bandwidth to be set in kHz. + + \returns \ref status_codes + */ + int16_t setBandwidth(float bw); + + /*! + \brief Sets LoRa spreading factor. Allowed values range from 5 to 12. + + \param sf LoRa spreading factor to be set. + + \returns \ref status_codes + */ + int16_t setSpreadingFactor(uint8_t sf); + + /*! + \brief Sets LoRa coding rate denominator. Allowed values range from 5 to 8. + + \param cr LoRa coding rate denominator to be set. + + \param longInterleaving Whether to enable long interleaving mode. Not available for coding rate 4/7, defaults to false. + + \returns \ref status_codes + */ + int16_t setCodingRate(uint8_t cr, bool longInterleaving = false); + + /*! + \brief Sets output power. Allowed values are in range from -18 to 13 dBm. + + \param power Output power to be set in dBm. + + \returns \ref status_codes + */ + int16_t setOutputPower(int8_t power); + + /*! + \brief Sets preamble length for currently active modem. Allowed values range from 1 to 65535. + + \param preambleLength Preamble length to be set in symbols (LoRa) or bits (FSK/BLE/FLRC). + + \returns \ref status_codes + */ + int16_t setPreambleLength(uint32_t preambleLength); + + /*! + \brief Sets FSK or FLRC bit rate. Allowed values are 125, 250, 400, 500, 800, 1000, 1600 and 2000 kbps (for FSK modem) or 260, 325, 520, 650, 1000 and 1300 (for FLRC modem). + + \param br FSK/FLRC bit rate to be set in kbps. + + \returns \ref status_codes + */ + int16_t setBitRate(uint16_t br); + + /*! + \brief Sets FSK frequency deviation. Allowed values range from 0.0 to 3200.0 kHz. + + \param freqDev FSK frequency deviation to be set in kHz. + + \returns \ref status_codes + */ + int16_t setFrequencyDeviation(float freqDev) override; + + /*! + \brief Sets time-bandwidth product of Gaussian filter applied for shaping. + Allowed values are RADIOLIB_SHAPING_0_5 or RADIOLIB_SHAPING_1_0. Set to RADIOLIB_SHAPING_NONE to disable data shaping. + + \param sh Time-bandwidth product of Gaussian filter to be set. + + \returns \ref status_codes + */ + int16_t setDataShaping(uint8_t sh) override; + + /*! + \brief Sets FSK/FLRC sync word in the form of array of up to 5 bytes (FSK). For FLRC modem, the sync word must be exactly 4 bytes long + + \param syncWord Sync word to be set. + + \param len Sync word length in bytes. + + \returns \ref status_codes + */ + int16_t setSyncWord(uint8_t* syncWord, uint8_t len); + + /*! + \brief Sets CRC configuration. + + \param len CRC length in bytes, Allowed values are 1, 2 or 3, set to 0 to disable CRC. + + \param initial Initial CRC value. Defaults to 0x1D0F (CCIT CRC), not available for LoRa modem. + + \param polynomial Polynomial for CRC calculation. Defaults to 0x1021 (CCIT CRC), not available for LoRa or BLE modem. + + \returns \ref status_codes + */ + int16_t setCRC(uint8_t len, uint32_t initial = 0x1D0F, uint16_t polynomial = 0x1021); + + /*! + \brief Sets whitening parameters, not available for LoRa or FLRC modem. + + \param enabled Set to true to enable whitening. + + \returns \ref status_codes + */ + int16_t setWhitening(bool enabled); + + /*! + \brief Sets BLE access address. + + \param addr BLE access address. + + \returns \ref status_codes + */ + int16_t setAccessAddress(uint32_t addr); + + /*! + \brief Gets RSSI (Recorded Signal Strength Indicator) of the last received packet. + + \returns RSSI of the last received packet in dBm. + */ + float getRSSI(); + + /*! + \brief Gets SNR (Signal to Noise Ratio) of the last received packet. Only available for LoRa or ranging modem. + + \returns SNR of the last received packet in dB. + */ + float getSNR(); + + /*! + \brief Query modem for the packet length of received payload. + + \param update Update received packet length. Will return cached value when set to false. + + \returns Length of last received packet in bytes. + */ + size_t getPacketLength(bool update = true) override; + + /*! + \brief Get expected time-on-air for a given size of payload. + + \param len Payload length in bytes. + + \returns Expected time-on-air in microseconds. + */ + uint32_t getTimeOnAir(size_t len); + + /*! + \brief Set implicit header mode for future reception/transmission. + + \returns \ref status_codes + */ + int16_t implicitHeader(size_t len); + + /*! + \brief Set explicit header mode for future reception/transmission. + + \param len Payload length in bytes. + + \returns \ref status_codes + */ + int16_t explicitHeader(); + + /*! + \brief Sets transmission encoding. Serves only as alias for PhysicalLayer compatibility. + + \param encoding Encoding to be used. Set to 0 for NRZ, and 2 for whitening. + + \returns \ref status_codes + */ + int16_t setEncoding(uint8_t encoding) override; + + /*! + \brief Some modules contain external RF switch controlled by two pins. This function gives RadioLib control over those two pins to automatically switch Rx and Tx state. + When using automatic RF switch control, DO NOT change the pin mode of rxEn or txEn from Arduino sketch! + + \param rxEn RX enable pin. + + \param txEn TX enable pin. + */ + void setRfSwitchPins(RADIOLIB_PIN_TYPE rxEn, RADIOLIB_PIN_TYPE txEn); + +#ifndef RADIOLIB_GODMODE + protected: +#endif + Module* _mod; + + // cached LoRa parameters + float _bwKhz = 0; + uint8_t _bw = 0, _sf = 0, _cr = 0; + uint8_t _preambleLengthLoRa = 0, _headerType = 0, _payloadLen = 0, _crcLoRa = 0; + + // SX128x SPI command implementations + uint8_t getStatus(); + int16_t writeRegister(uint16_t addr, uint8_t* data, uint8_t numBytes); + int16_t readRegister(uint16_t addr, uint8_t* data, uint8_t numBytes); + int16_t writeBuffer(uint8_t* data, uint8_t numBytes, uint8_t offset = 0x00); + int16_t readBuffer(uint8_t* data, uint8_t numBytes); + int16_t setTx(uint16_t periodBaseCount = SX128X_TX_TIMEOUT_NONE, uint8_t periodBase = SX128X_PERIOD_BASE_15_625_US); + int16_t setRx(uint16_t periodBaseCount, uint8_t periodBase = SX128X_PERIOD_BASE_15_625_US); + int16_t setCad(); + uint8_t getPacketType(); + int16_t setRfFrequency(uint32_t frf); + int16_t setTxParams(uint8_t power, uint8_t rampTime = SX128X_PA_RAMP_10_US); + int16_t setBufferBaseAddress(uint8_t txBaseAddress = 0x00, uint8_t rxBaseAddress = 0x00); + int16_t setModulationParams(uint8_t modParam1, uint8_t modParam2, uint8_t modParam3); + int16_t setPacketParamsGFSK(uint8_t preambleLen, uint8_t syncWordLen, uint8_t syncWordMatch, uint8_t crcLen, uint8_t whitening, uint8_t payloadLen = 0xFF, uint8_t headerType = SX128X_GFSK_FLRC_PACKET_VARIABLE); + int16_t setPacketParamsBLE(uint8_t connState, uint8_t crcLen, uint8_t bleTestPayload, uint8_t whitening); + int16_t setPacketParamsLoRa(uint8_t preambleLen, uint8_t headerType, uint8_t payloadLen, uint8_t crc, uint8_t invertIQ = SX128X_LORA_IQ_STANDARD); + int16_t setDioIrqParams(uint16_t irqMask, uint16_t dio1Mask, uint16_t dio2Mask = SX128X_IRQ_NONE, uint16_t dio3Mask = SX128X_IRQ_NONE); + uint16_t getIrqStatus(); + int16_t clearIrqStatus(uint16_t clearIrqParams = SX128X_IRQ_ALL); + int16_t setRangingRole(uint8_t role); + int16_t setPacketType(uint8_t type); + + int16_t setHeaderType(uint8_t headerType, size_t len = 0xFF); + +#ifndef RADIOLIB_GODMODE + private: +#endif + // common parameters + uint8_t _pwr = 0; + + // cached GFSK parameters + float _modIndexReal = 0; + uint16_t _brKbps = 0; + uint8_t _br = 0, _modIndex = 0, _shaping = 0; + uint8_t _preambleLengthGFSK = 0, _syncWordLen = 0, _syncWordMatch = 0, _crcGFSK = 0, _whitening = 0; + + // cached FLRC parameters + uint8_t _crFLRC = 0; + + // cached BLE parameters + uint8_t _connectionState = 0, _crcBLE = 0, _bleTestPayload = 0; + + int16_t config(uint8_t modem); + + // common low-level SPI interface + int16_t SPIwriteCommand(uint8_t cmd, uint8_t* data, uint8_t numBytes, bool waitForBusy = true); + int16_t SPIwriteCommand(uint8_t* cmd, uint8_t cmdLen, uint8_t* data, uint8_t numBytes, bool waitForBusy = true); + int16_t SPIreadCommand(uint8_t cmd, uint8_t* data, uint8_t numBytes, bool waitForBusy = true); + int16_t SPIreadCommand(uint8_t* cmd, uint8_t cmdLen, uint8_t* data, uint8_t numBytes, bool waitForBusy = true); + int16_t SPItransfer(uint8_t* cmd, uint8_t cmdLen, bool write, uint8_t* dataOut, uint8_t* dataIn, uint8_t numBytes, bool waitForBusy, uint32_t timeout = 5000); +}; + +#endif + +#endif diff --git a/src/modules/Si443x/Si4430.cpp b/src/modules/Si443x/Si4430.cpp new file mode 100644 index 00000000..778ee9dd --- /dev/null +++ b/src/modules/Si443x/Si4430.cpp @@ -0,0 +1,37 @@ +#include "Si4430.h" +#if !defined(RADIOLIB_EXCLUDE_SI443X) + +Si4430::Si4430(Module* mod) : Si4432(mod) { + +} + +int16_t Si4430::begin(float freq, float br, float freqDev, float rxBw, int8_t power, uint8_t preambleLen) { + // execute common part + int16_t state = Si443x::begin(br, freqDev, rxBw, preambleLen); + RADIOLIB_ASSERT(state); + + // configure publicly accessible settings + state = setFrequency(freq); + RADIOLIB_ASSERT(state); + + state = setOutputPower(power); + RADIOLIB_ASSERT(state); + + return(state); +} + +int16_t Si4430::setFrequency(float freq) { + RADIOLIB_CHECK_RANGE(freq, 900.0, 960.0, ERR_INVALID_FREQUENCY); + + // set frequency + return(Si443x::setFrequencyRaw(freq)); +} + +int16_t Si4430::setOutputPower(int8_t power) { + RADIOLIB_CHECK_RANGE(power, -8, 13, ERR_INVALID_OUTPUT_POWER); + + // set output power + return(_mod->SPIsetRegValue(SI443X_REG_TX_POWER, (uint8_t)((power + 8) / 3), 2, 0)); +} + +#endif diff --git a/src/modules/Si443x/Si4430.h b/src/modules/Si443x/Si4430.h new file mode 100644 index 00000000..ca8a1b8f --- /dev/null +++ b/src/modules/Si443x/Si4430.h @@ -0,0 +1,81 @@ +#if !defined(_RADIOLIB_SI4430_H) +#define _RADIOLIB_SI4430_H + +#include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SI443X) + +#include "../../Module.h" +#include "Si4432.h" + +/*! + \class Si4430 + + \brief Derived class for %Si4430 modules. +*/ +class Si4430: public Si4432 { + public: + + // constructor + + /*! + \brief Default constructor. + + \param mod Instance of Module that will be used to communicate with the radio chip. + */ + Si4430(Module* mod); + + // basic methods + + /*! + \brief Initialization method. Must be called at least once from Arduino sketch to initialize the module. + + \param freq Carrier frequency in MHz. Allowed values range from 900.0 MHz to 960.0 MHz. + + \param br Bit rate of the FSK transmission in kbps (kilobits per second). Allowed values range from 0.123 to 256.0 kbps. + + \param freqDev Frequency deviation of the FSK transmission in kHz. Allowed values range from 0.625 to 320.0 kbps. + + \param rxBw Receiver bandwidth in kHz. Allowed values range from 2.6 to 620.7 kHz. + + \param power Transmission output power in dBm. Allowed values range from -8 to 13 dBm in 3 dBm steps. + + \param preambleLen Preamble Length in bits. Defaults to 16 bits. + + \returns \ref status_codes + */ + int16_t begin(float freq = 434.0, float br = 48.0, float freqDev = 50.0, float rxBw = 181.1, int8_t power = 10, uint8_t preambleLen = 16); + + // configuration methods + + /*! + \brief Sets carrier frequency. Allowed values range from 900.0 MHz to 960.0 MHz. + + \param freq Carrier frequency to be set in MHz. + + \returns \ref status_codes + */ + int16_t setFrequency(float freq); + + /*! + \brief Sets output power. Allowed values range from -8 to 13 dBm in 3 dBm steps. + + \param power Output power to be set in dBm. + + \returns \ref status_codes + */ + int16_t setOutputPower(int8_t power); + + +#ifndef RADIOLIB_GODMODE + protected: +#endif + +#ifndef RADIOLIB_GODMODE + private: +#endif +}; + +#endif + +#endif diff --git a/src/modules/Si443x/Si4431.cpp b/src/modules/Si443x/Si4431.cpp new file mode 100644 index 00000000..88e43396 --- /dev/null +++ b/src/modules/Si443x/Si4431.cpp @@ -0,0 +1,30 @@ +#include "Si4431.h" +#if !defined(RADIOLIB_EXCLUDE_SI443X) + +Si4431::Si4431(Module* mod) : Si4432(mod) { + +} + +int16_t Si4431::begin(float freq, float br, float freqDev, float rxBw, int8_t power, uint8_t preambleLen) { + // execute common part + int16_t state = Si443x::begin(br, freqDev, rxBw, preambleLen); + RADIOLIB_ASSERT(state); + + // configure publicly accessible settings + state = setFrequency(freq); + RADIOLIB_ASSERT(state); + + state = setOutputPower(power); + RADIOLIB_ASSERT(state); + + return(state); +} + +int16_t Si4431::setOutputPower(int8_t power) { + RADIOLIB_CHECK_RANGE(power, -8, 13, ERR_INVALID_OUTPUT_POWER); + + // set output power + return(_mod->SPIsetRegValue(SI443X_REG_TX_POWER, (uint8_t)((power + 8) / 3), 2, 0)); +} + +#endif diff --git a/src/modules/Si443x/Si4431.h b/src/modules/Si443x/Si4431.h new file mode 100644 index 00000000..0143d41b --- /dev/null +++ b/src/modules/Si443x/Si4431.h @@ -0,0 +1,72 @@ +#if !defined(_RADIOLIB_SI4431_H) +#define _RADIOLIB_SI4431_H + +#include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SI443X) + +#include "../../Module.h" +#include "Si4432.h" + +/*! + \class Si4431 + + \brief Derived class for %Si4431 modules. +*/ +class Si4431: public Si4432 { + public: + + // constructor + + /*! + \brief Default constructor. + + \param mod Instance of Module that will be used to communicate with the radio chip. + */ + Si4431(Module* mod); + + // basic methods + + /*! + \brief Initialization method. Must be called at least once from Arduino sketch to initialize the module. + + \param freq Carrier frequency in MHz. Allowed values range from 240.0 MHz to 930.0 MHz. + + \param br Bit rate of the FSK transmission in kbps (kilobits per second). Allowed values range from 0.123 to 256.0 kbps. + + \param freqDev Frequency deviation of the FSK transmission in kHz. Allowed values range from 0.625 to 320.0 kbps. + + \param rxBw Receiver bandwidth in kHz. Allowed values range from 2.6 to 620.7 kHz. + + \param power Transmission output power in dBm. Allowed values range from -8 to 13 dBm in 3 dBm steps. + + \param preambleLen Preamble Length in bits. Defaults to 16 bits. + + \returns \ref status_codes + */ + int16_t begin(float freq = 434.0, float br = 48.0, float freqDev = 50.0, float rxBw = 181.1, int8_t power = 10, uint8_t preambleLen = 16); + + // configuration methods + + /*! + \brief Sets output power. Allowed values range from -8 to 13 dBm in 3 dBm steps. + + \param power Output power to be set in dBm. + + \returns \ref status_codes + */ + int16_t setOutputPower(int8_t power); + + +#ifndef RADIOLIB_GODMODE + protected: +#endif + +#ifndef RADIOLIB_GODMODE + private: +#endif +}; + +#endif + +#endif diff --git a/src/modules/Si443x/Si4432.cpp b/src/modules/Si443x/Si4432.cpp new file mode 100644 index 00000000..8037edcf --- /dev/null +++ b/src/modules/Si443x/Si4432.cpp @@ -0,0 +1,37 @@ +#include "Si4432.h" +#if !defined(RADIOLIB_EXCLUDE_SI443X) + +Si4432::Si4432(Module* mod) : Si443x(mod) { + +} + +int16_t Si4432::begin(float freq, float br, float freqDev, float rxBw, int8_t power, uint8_t preambleLen) { + // execute common part + int16_t state = Si443x::begin(br, freqDev, rxBw, preambleLen); + RADIOLIB_ASSERT(state); + + // configure publicly accessible settings + state = setFrequency(freq); + RADIOLIB_ASSERT(state); + + state = setOutputPower(power); + RADIOLIB_ASSERT(state); + + return(state); +} + +int16_t Si4432::setFrequency(float freq) { + RADIOLIB_CHECK_RANGE(freq, 240.0, 930.0, ERR_INVALID_FREQUENCY); + + // set frequency + return(Si443x::setFrequencyRaw(freq)); +} + +int16_t Si4432::setOutputPower(int8_t power) { + RADIOLIB_CHECK_RANGE(power, -1, 20, ERR_INVALID_OUTPUT_POWER); + + // set output power + return(_mod->SPIsetRegValue(SI443X_REG_TX_POWER, (uint8_t)((power + 1) / 3), 2, 0)); +} + +#endif diff --git a/src/modules/Si443x/Si4432.h b/src/modules/Si443x/Si4432.h new file mode 100644 index 00000000..2f785634 --- /dev/null +++ b/src/modules/Si443x/Si4432.h @@ -0,0 +1,81 @@ +#if !defined(_RADIOLIB_SI4432_H) +#define _RADIOLIB_SI4432_H + +#include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SI443X) + +#include "../../Module.h" +#include "Si443x.h" + +/*! + \class Si4432 + + \brief Derived class for %Si4432 modules. +*/ +class Si4432: public Si443x { + public: + + // constructor + + /*! + \brief Default constructor. + + \param mod Instance of Module that will be used to communicate with the radio chip. + */ + Si4432(Module* mod); + + // basic methods + + /*! + \brief Initialization method. Must be called at least once from Arduino sketch to initialize the module. + + \param freq Carrier frequency in MHz. Allowed values range from 240.0 MHz to 930.0 MHz. + + \param br Bit rate of the FSK transmission in kbps (kilobits per second). Allowed values range from 0.123 to 256.0 kbps. + + \param freqDev Frequency deviation of the FSK transmission in kHz. Allowed values range from 0.625 to 320.0 kbps. + + \param rxBw Receiver bandwidth in kHz. Allowed values range from 2.6 to 620.7 kHz. + + \param power Transmission output power in dBm. Allowed values range from -1 to 20 dBm in 3 dBm steps. + + \param preambleLen Preamble Length in bits. Defaults to 16 bits. + + \returns \ref status_codes + */ + int16_t begin(float freq = 434.0, float br = 48.0, float freqDev = 50.0, float rxBw = 181.1, int8_t power = 10, uint8_t preambleLen = 16); + + // configuration methods + + /*! + \brief Sets carrier frequency. Allowed values range from 240.0 MHz to 930.0 MHz. + + \param freq Carrier frequency to be set in MHz. + + \returns \ref status_codes + */ + int16_t setFrequency(float freq); + + /*! + \brief Sets output power. Allowed values range from -1 to 20 dBm in 3 dBm steps. + + \param power Output power to be set in dBm. + + \returns \ref status_codes + */ + int16_t setOutputPower(int8_t power); + + +#ifndef RADIOLIB_GODMODE + protected: +#endif + +#ifndef RADIOLIB_GODMODE + private: +#endif +}; + +#endif + +#endif diff --git a/src/modules/Si443x/Si443x.cpp b/src/modules/Si443x/Si443x.cpp new file mode 100644 index 00000000..8f2b9cfe --- /dev/null +++ b/src/modules/Si443x/Si443x.cpp @@ -0,0 +1,714 @@ +#include "Si443x.h" +#if !defined(RADIOLIB_EXCLUDE_SI443X) + +Si443x::Si443x(Module* mod) : PhysicalLayer(SI443X_FREQUENCY_STEP_SIZE, SI443X_MAX_PACKET_LENGTH) { + _mod = mod; +} + +int16_t Si443x::begin(float br, float freqDev, float rxBw, uint8_t preambleLen) { + // set module properties + _mod->init(RADIOLIB_USE_SPI); + Module::pinMode(_mod->getIrq(), INPUT); + Module::pinMode(_mod->getRst(), OUTPUT); + Module::digitalWrite(_mod->getRst(), LOW); + + // try to find the Si443x chip + if(!Si443x::findChip()) { + RADIOLIB_DEBUG_PRINTLN(F("No Si443x found!")); + _mod->term(RADIOLIB_USE_SPI); + return(ERR_CHIP_NOT_FOUND); + } else { + RADIOLIB_DEBUG_PRINTLN(F("Found Si443x!")); + } + + // clear POR interrupt + clearIRQFlags(); + + // configure settings not accessible by API + int16_t state = config(); + RADIOLIB_ASSERT(state); + + // configure publicly accessible settings + state = setBitRate(br); + RADIOLIB_ASSERT(state); + + state = setFrequencyDeviation(freqDev); + RADIOLIB_ASSERT(state); + + state = setRxBandwidth(rxBw); + RADIOLIB_ASSERT(state); + + state = setPreambleLength(preambleLen); + RADIOLIB_ASSERT(state); + + uint8_t syncWord[] = {0x12, 0xAD}; + state = setSyncWord(syncWord, sizeof(syncWord)); + RADIOLIB_ASSERT(state); + + state = packetMode(); + RADIOLIB_ASSERT(state); + + state = setDataShaping(0); + RADIOLIB_ASSERT(state); + + state = setEncoding(0); + RADIOLIB_ASSERT(state); + + return(state); +} + +void Si443x::reset() { + Module::pinMode(_mod->getRst(), OUTPUT); + Module::digitalWrite(_mod->getRst(), HIGH); + delay(1); + Module::digitalWrite(_mod->getRst(), LOW); + delay(100); +} + +int16_t Si443x::transmit(uint8_t* data, size_t len, uint8_t addr) { + // calculate timeout (5ms + 500 % of expected time-on-air) + uint32_t timeout = 5000000 + (uint32_t)((((float)(len * 8)) / (_br * 1000.0)) * 5000000.0); + + // start transmission + int16_t state = startTransmit(data, len, addr); + RADIOLIB_ASSERT(state); + + // wait for transmission end or timeout + uint32_t start = micros(); + while(digitalRead(_mod->getIrq())) { + yield(); + if(micros() - start > timeout) { + standby(); + clearIRQFlags(); + return(ERR_TX_TIMEOUT); + } + } + + // set mode to standby + state = standby(); + + // clear interrupt flags + clearIRQFlags(); + + return(state); +} + +int16_t Si443x::receive(uint8_t* data, size_t len) { + // calculate timeout (500 ms + 400 full 64-byte packets at current bit rate) + uint32_t timeout = 500000 + (1.0/(_br*1000.0))*(SI443X_MAX_PACKET_LENGTH*400.0); + + // start reception + int16_t state = startReceive(); + RADIOLIB_ASSERT(state); + + // wait for packet reception or timeout + uint32_t start = micros(); + while(digitalRead(_mod->getIrq())) { + if(micros() - start > timeout) { + standby(); + clearIRQFlags(); + return(ERR_RX_TIMEOUT); + } + } + + // read packet data + return(readData(data, len)); +} + +int16_t Si443x::sleep() { + // set RF switch (if present) + _mod->setRfSwitchState(LOW, LOW); + + // disable wakeup timer interrupt + int16_t state = _mod->SPIsetRegValue(SI443X_REG_INTERRUPT_ENABLE_1, 0x00); + RADIOLIB_ASSERT(state); + state = _mod->SPIsetRegValue(SI443X_REG_INTERRUPT_ENABLE_2, 0x00); + RADIOLIB_ASSERT(state); + + // enable wakeup timer to set mode to sleep + _mod->SPIwriteRegister(SI443X_REG_OP_FUNC_CONTROL_1, SI443X_ENABLE_WAKEUP_TIMER); + + return(state); +} + +int16_t Si443x::standby() { + // set RF switch (if present) + _mod->setRfSwitchState(LOW, LOW); + + return(_mod->SPIsetRegValue(SI443X_REG_OP_FUNC_CONTROL_1, SI443X_XTAL_ON, 7, 0, 10)); +} + +int16_t Si443x::transmitDirect(uint32_t frf) { + // set RF switch (if present) + _mod->setRfSwitchState(LOW, HIGH); + + // user requested to start transmitting immediately (required for RTTY) + if(frf != 0) { + // convert the 24-bit frequency to the format accepted by the module + /// \todo integers only + float newFreq = frf / 6400.0; + + // check high/low band + uint8_t bandSelect = SI443X_BAND_SELECT_LOW; + uint8_t freqBand = (newFreq / 10) - 24; + if(newFreq >= 480.0) { + bandSelect = SI443X_BAND_SELECT_HIGH; + freqBand = (newFreq / 20) - 24; + } + + // calculate register values + uint16_t freqCarrier = ((newFreq / (10 * ((bandSelect >> 5) + 1))) - freqBand - 24) * (uint32_t)64000; + + // update registers + _mod->SPIwriteRegister(SI443X_REG_FREQUENCY_BAND_SELECT, SI443X_SIDE_BAND_SELECT_LOW | bandSelect | freqBand); + _mod->SPIwriteRegister(SI443X_REG_NOM_CARRIER_FREQUENCY_1, (uint8_t)((freqCarrier & 0xFF00) >> 8)); + _mod->SPIwriteRegister(SI443X_REG_NOM_CARRIER_FREQUENCY_0, (uint8_t)(freqCarrier & 0xFF)); + + // start direct transmission + directMode(); + _mod->SPIwriteRegister(SI443X_REG_OP_FUNC_CONTROL_1, SI443X_TX_ON); + + return(ERR_NONE); + } + + // activate direct mode + int16_t state = directMode(); + RADIOLIB_ASSERT(state); + + // start transmitting + _mod->SPIwriteRegister(SI443X_REG_OP_FUNC_CONTROL_1, SI443X_TX_ON); + return(state); +} + +int16_t Si443x::receiveDirect() { + // set RF switch (if present) + _mod->setRfSwitchState(HIGH, LOW); + + // activate direct mode + int16_t state = directMode(); + RADIOLIB_ASSERT(state); + + // start receiving + _mod->SPIwriteRegister(SI443X_REG_OP_FUNC_CONTROL_1, SI443X_RX_ON); + return(state); +} + +int16_t Si443x::packetMode() { + return(_mod->SPIsetRegValue(SI443X_REG_MODULATION_MODE_CONTROL_2, SI443X_TX_DATA_SOURCE_FIFO, 5, 4)); +} + +void Si443x::setIrqAction(void (*func)(void)) { + attachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getIrq()), func, FALLING); +} + +void Si443x::clearIrqAction() { + detachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getIrq())); +} + +int16_t Si443x::startTransmit(uint8_t* data, size_t len, uint8_t addr) { + // check packet length + if(len > SI443X_MAX_PACKET_LENGTH) { + return(ERR_PACKET_TOO_LONG); + } + + // set mode to standby + int16_t state = standby(); + RADIOLIB_ASSERT(state); + + // clear Tx FIFO + _mod->SPIsetRegValue(SI443X_REG_OP_FUNC_CONTROL_2, SI443X_TX_FIFO_RESET, 0, 0); + _mod->SPIsetRegValue(SI443X_REG_OP_FUNC_CONTROL_2, SI443X_TX_FIFO_CLEAR, 0, 0); + + // set interrupt mapping + state = _mod->SPIsetRegValue(SI443X_REG_INTERRUPT_ENABLE_1, SI443X_PACKET_SENT_ENABLED); + RADIOLIB_ASSERT(state); + + // clear interrupt flags + clearIRQFlags(); + + // set packet length + /// \todo variable packet length + _mod->SPIwriteRegister(SI443X_REG_TRANSMIT_PACKET_LENGTH, len); + + /// \todo use header as address field? + (void)addr; + + // write packet to FIFO + _mod->SPIwriteRegisterBurst(SI443X_REG_FIFO_ACCESS, data, len); + + // set RF switch (if present) + _mod->setRfSwitchState(LOW, HIGH); + + // set mode to transmit + _mod->SPIwriteRegister(SI443X_REG_OP_FUNC_CONTROL_1, SI443X_TX_ON); + + return(state); +} + +int16_t Si443x::startReceive() { + // set mode to standby + int16_t state = standby(); + RADIOLIB_ASSERT(state); + + // clear Rx FIFO + _mod->SPIsetRegValue(SI443X_REG_OP_FUNC_CONTROL_2, SI443X_RX_FIFO_RESET, 1, 1); + _mod->SPIsetRegValue(SI443X_REG_OP_FUNC_CONTROL_2, SI443X_RX_FIFO_CLEAR, 1, 1); + + // set interrupt mapping + state = _mod->SPIsetRegValue(SI443X_REG_INTERRUPT_ENABLE_1, SI443X_VALID_PACKET_RECEIVED_ENABLED, SI443X_CRC_ERROR_ENABLED); + RADIOLIB_ASSERT(state); + state = _mod->SPIsetRegValue(SI443X_REG_INTERRUPT_ENABLE_2, 0x00); + RADIOLIB_ASSERT(state); + + // clear interrupt flags + clearIRQFlags(); + + // set RF switch (if present) + _mod->setRfSwitchState(HIGH, LOW); + + // set mode to receive + _mod->SPIwriteRegister(SI443X_REG_OP_FUNC_CONTROL_1, SI443X_RX_ON); + + return(state); +} + +int16_t Si443x::readData(uint8_t* data, size_t len) { + // clear interrupt flags + clearIRQFlags(); + + // get packet length + size_t length = len; + if(len == SI443X_MAX_PACKET_LENGTH) { + length = getPacketLength(); + } + + // read packet data + _mod->SPIreadRegisterBurst(SI443X_REG_FIFO_ACCESS, length, data); + + // clear internal flag so getPacketLength can return the new packet length + _packetLengthQueried = false; + + // set mode to standby + int16_t state = standby(); + RADIOLIB_ASSERT(state); + + // clear interrupt flags + clearIRQFlags(); + + return(ERR_NONE); +} + +int16_t Si443x::setBitRate(float br) { + RADIOLIB_CHECK_RANGE(br, 0.123, 256.0, ERR_INVALID_BIT_RATE); + + // check high data rate + uint8_t dataRateMode = SI443X_LOW_DATA_RATE_MODE; + uint8_t exp = 21; + if(br >= 30.0) { + // bit rate above 30 kbps + dataRateMode = SI443X_HIGH_DATA_RATE_MODE; + exp = 16; + } + + // calculate raw data rate value + uint16_t txDr = (br * ((uint32_t)1 << exp)) / 1000.0; + + // update registers + int16_t state = _mod->SPIsetRegValue(SI443X_REG_MODULATION_MODE_CONTROL_1, dataRateMode, 5, 5); + _mod->SPIwriteRegister(SI443X_REG_TX_DATA_RATE_1, (uint8_t)((txDr & 0xFF00) >> 8)); + _mod->SPIwriteRegister(SI443X_REG_TX_DATA_RATE_0, (uint8_t)(txDr & 0xFF)); + + if(state == ERR_NONE) { + _br = br; + } + RADIOLIB_ASSERT(state); + + // update clock recovery + state = updateClockRecovery(); + + return(state); +} + +int16_t Si443x::setFrequencyDeviation(float freqDev) { + // set frequency deviation to lowest available setting (required for RTTY) + if(freqDev == 0.0) { + int16_t state = _mod->SPIsetRegValue(SI443X_REG_MODULATION_MODE_CONTROL_2, 0x00, 2, 2); + _mod->SPIwriteRegister(SI443X_REG_FREQUENCY_DEVIATION, 0x00); + + if(state == ERR_NONE) { + _freqDev = freqDev; + } + + } + + RADIOLIB_CHECK_RANGE(freqDev, 0.625, 320.0, ERR_INVALID_FREQUENCY_DEVIATION); + + // calculate raw frequency deviation value + uint16_t fdev = (uint16_t)(freqDev / 0.625); + + // update registers + int16_t state = _mod->SPIsetRegValue(SI443X_REG_MODULATION_MODE_CONTROL_2, (uint8_t)((fdev & 0x0100) >> 6), 2, 2); + _mod->SPIwriteRegister(SI443X_REG_FREQUENCY_DEVIATION, (uint8_t)(fdev & 0xFF)); + + if(state == ERR_NONE) { + _freqDev = freqDev; + } + + return(state); +} + +int16_t Si443x::setRxBandwidth(float rxBw) { + RADIOLIB_CHECK_RANGE(rxBw, 2.6, 620.7, ERR_INVALID_RX_BANDWIDTH); + + // decide which approximation to use for decimation rate and filter tap calculation + uint8_t bypass = SI443X_BYPASS_DEC_BY_3_OFF; + uint8_t decRate = SI443X_IF_FILTER_DEC_RATE; + uint8_t filterSet = SI443X_IF_FILTER_COEFF_SET; + + // this is the "well-behaved" section - can be linearly approximated + if((rxBw >= 2.6) && (rxBw <= 4.5)) { + decRate = 5; + filterSet = ((rxBw - 2.1429)/0.3250 + 0.5); + } else if((rxBw > 4.5) && (rxBw <= 8.8)) { + decRate = 4; + filterSet = ((rxBw - 3.9857)/0.6643 + 0.5); + } else if((rxBw > 8.8) && (rxBw <= 17.5)) { + decRate = 3; + filterSet = ((rxBw - 7.6714)/1.3536 + 0.5); + } else if((rxBw > 17.5) && (rxBw <= 34.7)) { + decRate = 2; + filterSet = ((rxBw - 15.2000)/2.6893 + 0.5); + } else if((rxBw > 34.7) && (rxBw <= 69.2)) { + decRate = 1; + filterSet = ((rxBw - 30.2430)/5.3679 + 0.5); + } else if((rxBw > 69.2) && (rxBw <= 137.9)) { + decRate = 0; + filterSet = ((rxBw - 60.286)/10.7000 + 0.5); + + // this is the "Lord help thee who tread 'ere" section - no way to approximate this mess + } else if(rxBw == 142.8) { + bypass = SI443X_BYPASS_DEC_BY_3_ON; + decRate = 1; + filterSet = 4; + } else if(rxBw == 167.8) { + bypass = SI443X_BYPASS_DEC_BY_3_ON; + decRate = 1; + filterSet = 5; + } else if(rxBw == 181.1) { + bypass = SI443X_BYPASS_DEC_BY_3_ON; + decRate = 1; + filterSet = 6; + } else if(rxBw == 191.5) { + bypass = SI443X_BYPASS_DEC_BY_3_ON; + decRate = 0; + filterSet = 15; + } else if(rxBw == 225.1) { + bypass = SI443X_BYPASS_DEC_BY_3_ON; + decRate = 0; + filterSet = 1; + } else if(rxBw == 248.8) { + bypass = SI443X_BYPASS_DEC_BY_3_ON; + decRate = 0; + filterSet = 2; + } else if(rxBw == 269.3) { + bypass = SI443X_BYPASS_DEC_BY_3_ON; + decRate = 0; + filterSet = 3; + } else if(rxBw == 284.8) { + bypass = SI443X_BYPASS_DEC_BY_3_ON; + decRate = 0; + filterSet = 4; + } else if(rxBw == 335.5) { + bypass = SI443X_BYPASS_DEC_BY_3_ON; + decRate = 0; + filterSet = 8; + } else if(rxBw == 391.8) { + bypass = SI443X_BYPASS_DEC_BY_3_ON; + decRate = 0; + filterSet = 9; + } else if(rxBw == 420.2) { + bypass = SI443X_BYPASS_DEC_BY_3_ON; + decRate = 0; + filterSet = 10; + } else if(rxBw == 468.4) { + bypass = SI443X_BYPASS_DEC_BY_3_ON; + decRate = 0; + filterSet = 11; + } else if(rxBw == 518.8) { + bypass = SI443X_BYPASS_DEC_BY_3_ON; + decRate = 0; + filterSet = 12; + } else if(rxBw == 577.0) { + bypass = SI443X_BYPASS_DEC_BY_3_ON; + decRate = 0; + filterSet = 13; + } else if(rxBw == 620.7) { + bypass = SI443X_BYPASS_DEC_BY_3_ON; + decRate = 0; + filterSet = 14; + } else { + return(ERR_INVALID_RX_BANDWIDTH); + } + + // shift decimation rate bits + decRate <<= 4; + + // update register + int16_t state = _mod->SPIsetRegValue(SI443X_REG_IF_FILTER_BANDWIDTH, bypass | decRate | filterSet); + RADIOLIB_ASSERT(state); + + // update clock recovery + state = updateClockRecovery(); + + return(state); +} + +int16_t Si443x::setSyncWord(uint8_t* syncWord, size_t len) { + RADIOLIB_CHECK_RANGE(len, 1, 4, ERR_INVALID_SYNC_WORD); + + // set mode to standby + int16_t state = standby(); + RADIOLIB_ASSERT(state); + + // set sync word length + state = _mod->SPIsetRegValue(SI443X_REG_HEADER_CONTROL_2, (uint8_t)(len - 1) << 1, 2, 1); + RADIOLIB_ASSERT(state); + + // set sync word bytes + _mod->SPIwriteRegisterBurst(SI443X_REG_SYNC_WORD_3, syncWord, len); + + return(state); +} + +int16_t Si443x::setPreambleLength(uint8_t preambleLen) { + // Si443x configures preamble length in bytes + if(preambleLen % 8 != 0) { + return(ERR_INVALID_PREAMBLE_LENGTH); + } + + // set default preamble length + uint8_t preLenBytes = preambleLen / 8; + int16_t state = _mod->SPIsetRegValue(SI443X_REG_PREAMBLE_LENGTH, preLenBytes); + RADIOLIB_ASSERT(state); + + // set default preamble detection threshold to 50% of preamble length (in units of 4 bits) + uint8_t preThreshold = preambleLen / 4; + return(_mod->SPIsetRegValue(SI443X_REG_PREAMBLE_DET_CONTROL, preThreshold << 4, 3, 7)); +} + +size_t Si443x::getPacketLength(bool update) { + /// \todo variable length mode + if(!_packetLengthQueried && update) { + _packetLength = _mod->SPIreadRegister(SI443X_REG_RECEIVED_PACKET_LENGTH); + _packetLengthQueried = true; + } + + return(_packetLength); +} + +int16_t Si443x::setEncoding(uint8_t encoding) { + // set mode to standby + int16_t state = standby(); + RADIOLIB_ASSERT(state); + + // set encoding + /// \todo - add inverted Manchester? + switch(encoding) { + case RADIOLIB_ENCODING_NRZ: + return(_mod->SPIsetRegValue(SI443X_REG_MODULATION_MODE_CONTROL_1, SI443X_MANCHESTER_INVERTED_OFF | SI443X_MANCHESTER_OFF | SI443X_WHITENING_OFF, 2, 0)); + case RADIOLIB_ENCODING_MANCHESTER: + return(_mod->SPIsetRegValue(SI443X_REG_MODULATION_MODE_CONTROL_1, SI443X_MANCHESTER_INVERTED_OFF | SI443X_MANCHESTER_ON | SI443X_WHITENING_OFF, 2, 0)); + case RADIOLIB_ENCODING_WHITENING: + return(_mod->SPIsetRegValue(SI443X_REG_MODULATION_MODE_CONTROL_1, SI443X_MANCHESTER_INVERTED_OFF | SI443X_MANCHESTER_OFF | SI443X_WHITENING_ON, 2, 0)); + default: + return(ERR_INVALID_ENCODING); + } +} + +int16_t Si443x::setDataShaping(uint8_t sh) { + // set mode to standby + int16_t state = standby(); + RADIOLIB_ASSERT(state); + + // set data shaping + switch(sh) { + case RADIOLIB_SHAPING_NONE: + return(_mod->SPIsetRegValue(SI443X_REG_MODULATION_MODE_CONTROL_1, SI443X_MANCHESTER_INVERTED_OFF | SI443X_MANCHESTER_OFF | SI443X_WHITENING_OFF, 2, 0)); + case RADIOLIB_SHAPING_0_3: + case RADIOLIB_SHAPING_0_5: + case RADIOLIB_SHAPING_1_0: + /// \todo implement fiter configuration - docs claim this should be possible, but seems undocumented + return(_mod->SPIsetRegValue(SI443X_REG_MODULATION_MODE_CONTROL_1, SI443X_MANCHESTER_INVERTED_OFF | SI443X_MANCHESTER_OFF | SI443X_WHITENING_ON, 2, 0)); + default: + return(ERR_INVALID_ENCODING); + } +} + +void Si443x::setRfSwitchPins(RADIOLIB_PIN_TYPE rxEn, RADIOLIB_PIN_TYPE txEn) { + _mod->setRfSwitchPins(rxEn, txEn); +} + +int16_t Si443x::setFrequencyRaw(float newFreq) { + // set mode to standby + int16_t state = standby(); + RADIOLIB_ASSERT(state); + + // check high/low band + uint8_t bandSelect = SI443X_BAND_SELECT_LOW; + uint8_t freqBand = (newFreq / 10) - 24; + if(newFreq >= 480.0) { + bandSelect = SI443X_BAND_SELECT_HIGH; + freqBand = (newFreq / 20) - 24; + } + + // calculate register values + uint16_t freqCarrier = ((newFreq / (10 * ((bandSelect >> 5) + 1))) - freqBand - 24) * (uint32_t)64000; + + // update registers + state = _mod->SPIsetRegValue(SI443X_REG_FREQUENCY_BAND_SELECT, bandSelect | freqBand, 5, 0); + state |= _mod->SPIsetRegValue(SI443X_REG_NOM_CARRIER_FREQUENCY_1, (uint8_t)((freqCarrier & 0xFF00) >> 8)); + state |= _mod->SPIsetRegValue(SI443X_REG_NOM_CARRIER_FREQUENCY_0, (uint8_t)(freqCarrier & 0xFF)); + + return(state); +} + +bool Si443x::findChip() { + uint8_t i = 0; + bool flagFound = false; + while((i < 10) && !flagFound) { + // reset the module + reset(); + + // check version register + uint8_t version = _mod->SPIreadRegister(SI443X_REG_DEVICE_VERSION); + if(version == SI443X_DEVICE_VERSION) { + flagFound = true; + } else { + #ifdef RADIOLIB_DEBUG + RADIOLIB_DEBUG_PRINT(F("Si443x not found! (")); + RADIOLIB_DEBUG_PRINT(i + 1); + RADIOLIB_DEBUG_PRINT(F(" of 10 tries) SI443X_REG_DEVICE_VERSION == ")); + + char buffHex[5]; + sprintf(buffHex, "0x%02X", version); + RADIOLIB_DEBUG_PRINT(buffHex); + RADIOLIB_DEBUG_PRINT(F(", expected 0x00")); + RADIOLIB_DEBUG_PRINTLN(SI443X_DEVICE_VERSION, HEX); + #endif + delay(10); + i++; + } + } + + return(flagFound); +} + +void Si443x::clearIRQFlags() { + _mod->SPIreadRegister(SI443X_REG_INTERRUPT_STATUS_1); + _mod->SPIreadRegister(SI443X_REG_INTERRUPT_STATUS_2); +} + +int16_t Si443x::config() { + // set mode to standby + int16_t state = standby(); + RADIOLIB_ASSERT(state); + + // disable POR and chip ready interrupts + state = _mod->SPIsetRegValue(SI443X_REG_INTERRUPT_ENABLE_2, 0x00); + RADIOLIB_ASSERT(state); + + // disable packet header + state = _mod->SPIsetRegValue(SI443X_REG_HEADER_CONTROL_2, SI443X_SYNC_WORD_TIMEOUT_ON | SI443X_HEADER_LENGTH_HEADER_NONE, 7, 4); + RADIOLIB_ASSERT(state); + + // disable packet header checking + state = _mod->SPIsetRegValue(SI443X_REG_HEADER_CONTROL_1, SI443X_BROADCAST_ADDR_CHECK_NONE | SI443X_RECEIVED_HEADER_CHECK_NONE); + RADIOLIB_ASSERT(state); + + return(state); +} + +int16_t Si443x::updateClockRecovery() { + // get the parameters + uint8_t bypass = _mod->SPIgetRegValue(SI443X_REG_IF_FILTER_BANDWIDTH, 7, 7) >> 7; + uint8_t decRate = _mod->SPIgetRegValue(SI443X_REG_IF_FILTER_BANDWIDTH, 6, 4) >> 4; + uint8_t manch = _mod->SPIgetRegValue(SI443X_REG_MODULATION_MODE_CONTROL_1, 1, 1) >> 1; + + // calculate oversampling ratio, NCO offset and clock recovery gain + float rxOsr = ((float)(500 * (1 + 2*bypass))) / (((float)((uint16_t)(1) << decRate)) * _br * ((float)(1 + manch))); + uint32_t ncoOff = (_br * (1 + manch) * ((uint32_t)(1) << (20 + decRate))) / (500 * (1 + 2*bypass)); + uint16_t crGain = 2 + (((float)(65536.0 * (1 + manch)) * _br) / (rxOsr * (_freqDev / 0.625))); + + // convert oversampling ratio from float to fixed point + uint8_t rxOsr_int = (uint8_t)rxOsr; + uint8_t rxOsr_dec = 0; + float rxOsr_temp = rxOsr; + if((rxOsr_temp - rxOsr_int) >= 0.5) { + rxOsr_dec |= 0x04; + rxOsr_temp -= 0.5; + } + if((rxOsr_temp - rxOsr_int) >= 0.25) { + rxOsr_dec |= 0x02; + rxOsr_temp -= 0.25; + } + if((rxOsr_temp - rxOsr_int) >= 0.125) { + rxOsr_dec |= 0x01; + } + uint16_t rxOsr_fixed = ((uint16_t)rxOsr_int << 3) | ((uint16_t)rxOsr_dec); + + // print that whole mess + RADIOLIB_DEBUG_PRINTLN(bypass, HEX); + RADIOLIB_DEBUG_PRINTLN(decRate, HEX); + RADIOLIB_DEBUG_PRINTLN(manch, HEX); + RADIOLIB_DEBUG_PRINT(rxOsr, 3); + RADIOLIB_DEBUG_PRINT('\t'); + RADIOLIB_DEBUG_PRINT(rxOsr_int); + RADIOLIB_DEBUG_PRINT('\t'); + RADIOLIB_DEBUG_PRINT(rxOsr_int, HEX); + RADIOLIB_DEBUG_PRINT('\t'); + RADIOLIB_DEBUG_PRINT(rxOsr_dec); + RADIOLIB_DEBUG_PRINT('\t'); + RADIOLIB_DEBUG_PRINT(rxOsr_dec, HEX); + RADIOLIB_DEBUG_PRINT('\t'); + RADIOLIB_DEBUG_PRINT(rxOsr_fixed); + RADIOLIB_DEBUG_PRINT('\t'); + RADIOLIB_DEBUG_PRINTLN(rxOsr_fixed, HEX); + RADIOLIB_DEBUG_PRINT(ncoOff); + RADIOLIB_DEBUG_PRINT('\t'); + RADIOLIB_DEBUG_PRINTLN(ncoOff, HEX); + RADIOLIB_DEBUG_PRINT(crGain); + RADIOLIB_DEBUG_PRINT('\t'); + RADIOLIB_DEBUG_PRINTLN(crGain, HEX); + + // update oversampling ratio + int16_t state = _mod->SPIsetRegValue(SI443X_REG_CLOCK_REC_OFFSET_2, (uint8_t)((rxOsr_fixed & 0x0700) >> 3), 7, 5); + RADIOLIB_ASSERT(state); + state = _mod->SPIsetRegValue(SI443X_REG_CLOCK_REC_OVERSAMP_RATIO, (uint8_t)(rxOsr_fixed & 0x00FF)); + RADIOLIB_ASSERT(state); + + // update NCO offset + state = _mod->SPIsetRegValue(SI443X_REG_CLOCK_REC_OFFSET_2, (uint8_t)((ncoOff & 0x0F0000) >> 16), 3, 0); + RADIOLIB_ASSERT(state); + state = _mod->SPIsetRegValue(SI443X_REG_CLOCK_REC_OFFSET_1, (uint8_t)((ncoOff & 0x00FF00) >> 8)); + RADIOLIB_ASSERT(state); + state = _mod->SPIsetRegValue(SI443X_REG_CLOCK_REC_OFFSET_0, (uint8_t)(ncoOff & 0x0000FF)); + RADIOLIB_ASSERT(state); + + // update clock recovery loop gain + state = _mod->SPIsetRegValue(SI443X_REG_CLOCK_REC_TIMING_LOOP_GAIN_1, (uint8_t)((crGain & 0x0700) >> 8), 2, 0); + RADIOLIB_ASSERT(state); + state = _mod->SPIsetRegValue(SI443X_REG_CLOCK_REC_TIMING_LOOP_GAIN_0, (uint8_t)(crGain & 0x00FF)); + RADIOLIB_ASSERT(state); + + return(state); +} + +int16_t Si443x::directMode() { + int16_t state = _mod->SPIsetRegValue(SI443X_REG_MODULATION_MODE_CONTROL_2, SI443X_TX_DATA_SOURCE_GPIO, 5, 4); + RADIOLIB_ASSERT(state); + + state = _mod->SPIsetRegValue(SI443X_REG_MODULATION_MODE_CONTROL_2, SI443X_MODULATION_NONE, 1, 0); + return(state); +} + +#endif diff --git a/src/modules/Si443x/Si443x.h b/src/modules/Si443x/Si443x.h new file mode 100644 index 00000000..b5ffeb54 --- /dev/null +++ b/src/modules/Si443x/Si443x.h @@ -0,0 +1,813 @@ +#if !defined(_RADIOLIB_SI443X_H) +#define _RADIOLIB_SI443X_H + +#include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SI443X) + +#include "../../Module.h" + +#include "../../protocols/PhysicalLayer/PhysicalLayer.h" + +// Si443x physical layer properties +#define SI443X_FREQUENCY_STEP_SIZE 156.25 +#define SI443X_MAX_PACKET_LENGTH 64 + +// Si443x series common registers +#define SI443X_REG_DEVICE_TYPE 0x00 +#define SI443X_REG_DEVICE_VERSION 0x01 +#define SI443X_REG_DEVICE_STATUS 0x02 +#define SI443X_REG_INTERRUPT_STATUS_1 0x03 +#define SI443X_REG_INTERRUPT_STATUS_2 0x04 +#define SI443X_REG_INTERRUPT_ENABLE_1 0x05 +#define SI443X_REG_INTERRUPT_ENABLE_2 0x06 +#define SI443X_REG_OP_FUNC_CONTROL_1 0x07 +#define SI443X_REG_OP_FUNC_CONTROL_2 0x08 +#define SI443X_REG_XOSC_LOAD_CAPACITANCE 0x09 +#define SI443X_REG_MCU_OUTPUT_CLOCK 0x0A +#define SI443X_REG_GPIO0_CONFIG 0x0B +#define SI443X_REG_GPIO1_CONFIG 0x0C +#define SI443X_REG_GPIO2_CONFIG 0x0D +#define SI443X_REG_IO_PORT_CONFIG 0x0E +#define SI443X_REG_ADC_CONFIG 0x0F +#define SI443X_REG_ADC_SENSOR_AMP_OFFSET 0x10 +#define SI443X_REG_ADC_VALUE 0x11 +#define SI443X_REG_TEMP_SENSOR_CONTROL 0x12 +#define SI443X_REG_TEMP_VALUE_OFFSET 0x13 +#define SI443X_REG_WAKEUP_TIMER_PERIOD_1 0x14 +#define SI443X_REG_WAKEUP_TIMER_PERIOD_2 0x15 +#define SI443X_REG_WAKEUP_TIMER_PERIOD_3 0x16 +#define SI443X_REG_WAKEUP_TIMER_VALUE_1 0x17 +#define SI443X_REG_WAKEUP_TIMER_VALUE_2 0x18 +#define SI443X_REG_LOW_DC_MODE_DURATION 0x19 +#define SI443X_REG_LOW_BATT_DET_THRESHOLD 0x1A +#define SI443X_REG_BATT_VOLTAGE_LEVEL 0x1B +#define SI443X_REG_IF_FILTER_BANDWIDTH 0x1C +#define SI443X_REG_AFC_LOOP_GEARSHIFT_OVERRIDE 0x1D +#define SI443X_REG_AFC_TIMING_CONTROL 0x1E +#define SI443X_REG_CLOCK_REC_GEARSHIFT_OVERRIDE 0x1F +#define SI443X_REG_CLOCK_REC_OVERSAMP_RATIO 0x20 +#define SI443X_REG_CLOCK_REC_OFFSET_2 0x21 +#define SI443X_REG_CLOCK_REC_OFFSET_1 0x22 +#define SI443X_REG_CLOCK_REC_OFFSET_0 0x23 +#define SI443X_REG_CLOCK_REC_TIMING_LOOP_GAIN_1 0x24 +#define SI443X_REG_CLOCK_REC_TIMING_LOOP_GAIN_0 0x25 +#define SI443X_REG_RSSI 0x26 +#define SI443X_REG_RSSI_CLEAR_CHANNEL_THRESHOLD 0x27 +#define SI443X_REG_ANTENNA_DIVERSITY_1 0x28 +#define SI443X_REG_ANTENNA_DIVERSITY_2 0x29 +#define SI443X_REG_AFC_LIMITER 0x2A +#define SI443X_REG_AFC_CORRECTION 0x2B +#define SI443X_REG_OOK_COUNTER_1 0x2C +#define SI443X_REG_OOK_COUNTER_2 0x2D +#define SI443X_REG_SLICER_PEAK_HOLD 0x2E +#define SI443X_REG_DATA_ACCESS_CONTROL 0x30 +#define SI443X_REG_EZMAC_STATUS 0x31 +#define SI443X_REG_HEADER_CONTROL_1 0x32 +#define SI443X_REG_HEADER_CONTROL_2 0x33 +#define SI443X_REG_PREAMBLE_LENGTH 0x34 +#define SI443X_REG_PREAMBLE_DET_CONTROL 0x35 +#define SI443X_REG_SYNC_WORD_3 0x36 +#define SI443X_REG_SYNC_WORD_2 0x37 +#define SI443X_REG_SYNC_WORD_1 0x38 +#define SI443X_REG_SYNC_WORD_0 0x39 +#define SI443X_REG_TRANSMIT_HEADER_3 0x3A +#define SI443X_REG_TRANSMIT_HEADER_2 0x3B +#define SI443X_REG_TRANSMIT_HEADER_1 0x3C +#define SI443X_REG_TRANSMIT_HEADER_0 0x3D +#define SI443X_REG_TRANSMIT_PACKET_LENGTH 0x3E +#define SI443X_REG_CHECK_HEADER_3 0x3F +#define SI443X_REG_CHECK_HEADER_2 0x40 +#define SI443X_REG_CHECK_HEADER_1 0x41 +#define SI443X_REG_CHECK_HEADER_0 0x42 +#define SI443X_REG_HEADER_ENABLE_3 0x43 +#define SI443X_REG_HEADER_ENABLE_2 0x44 +#define SI443X_REG_HEADER_ENABLE_1 0x45 +#define SI443X_REG_HEADER_ENABLE_0 0x46 +#define SI443X_REG_RECEIVED_HEADER_3 0x47 +#define SI443X_REG_RECEIVED_HEADER_2 0x48 +#define SI443X_REG_RECEIVED_HEADER_1 0x49 +#define SI443X_REG_RECEIVED_HEADER_0 0x4A +#define SI443X_REG_RECEIVED_PACKET_LENGTH 0x4B +#define SI443X_REG_ADC8_CONTROL 0x4F +#define SI443X_REG_CHANNEL_FILTER_COEFF 0x60 +#define SI443X_REG_XOSC_CONTROL_TEST 0x62 +#define SI443X_REG_AGC_OVERRIDE_1 0x69 +#define SI443X_REG_TX_POWER 0x6D +#define SI443X_REG_TX_DATA_RATE_1 0x6E +#define SI443X_REG_TX_DATA_RATE_0 0x6F +#define SI443X_REG_MODULATION_MODE_CONTROL_1 0x70 +#define SI443X_REG_MODULATION_MODE_CONTROL_2 0x71 +#define SI443X_REG_FREQUENCY_DEVIATION 0x72 +#define SI443X_REG_FREQUENCY_OFFSET_1 0x73 +#define SI443X_REG_FREQUENCY_OFFSET_2 0x74 +#define SI443X_REG_FREQUENCY_BAND_SELECT 0x75 +#define SI443X_REG_NOM_CARRIER_FREQUENCY_1 0x76 +#define SI443X_REG_NOM_CARRIER_FREQUENCY_0 0x77 +#define SI443X_REG_FREQUENCY_HOPPING_CHANNEL_SEL 0x79 +#define SI443X_REG_FREQUENCY_HOPPING_STEP_SIZE 0x7A +#define SI443X_REG_TX_FIFO_CONTROL_1 0x7C +#define SI443X_REG_TX_FIFO_CONTROL_2 0x7D +#define SI443X_REG_RX_FIFO_CONTROL 0x7E +#define SI443X_REG_FIFO_ACCESS 0x7F + +// SI443X_REG_DEVICE_TYPE MSB LSB DESCRIPTION +#define SI443X_DEVICE_TYPE 0x08 // 4 0 device identification register + +// SI443X_REG_DEVICE_VERSION +#define SI443X_DEVICE_VERSION 0x06 // 4 0 chip version register + +// SI443X_REG_DEVICE_STATUS +#define SI443X_RX_TX_FIFO_OVERFLOW 0b10000000 // 7 7 Rx/Tx FIFO overflow flag +#define SI443X_RX_TX_FIFO_UNDERFLOW 0b01000000 // 6 6 Rx/Tx FIFO underflow flag +#define SI443X_RX_FIFO_EMPTY 0b00100000 // 5 5 Rx FIFO empty flag +#define SI443X_HEADER_ERROR 0b00010000 // 4 4 header error flag +#define SI443X_FREQUENCY_ERROR 0b00001000 // 3 3 frequency error flag (frequency outside allowed range) +#define SI443X_TX 0b00000010 // 1 0 power state: Tx +#define SI443X_RX 0b00000001 // 1 0 Rx +#define SI443X_IDLE 0b00000000 // 1 0 idle + +// SI443X_REG_INTERRUPT_STATUS_1 +#define SI443X_FIFO_LEVEL_ERROR_INTERRUPT 0b10000000 // 7 7 Tx/Rx FIFO overflow or underflow +#define SI443X_TX_FIFO_ALMOST_FULL_INTERRUPT 0b01000000 // 6 6 Tx FIFO almost full +#define SI443X_TX_FIFO_ALMOST_EMPTY_INTERRUPT 0b00100000 // 5 5 Tx FIFO almost empty +#define SI443X_RX_FIFO_ALMOST_FULL_INTERRUPT 0b00010000 // 4 4 Rx FIFO almost full +#define SI443X_EXTERNAL_INTERRUPT 0b00001000 // 3 3 external interrupt occurred on GPIOx +#define SI443X_PACKET_SENT_INTERRUPT 0b00000100 // 2 2 packet transmission done +#define SI443X_VALID_PACKET_RECEIVED_INTERRUPT 0b00000010 // 1 1 valid packet has been received +#define SI443X_CRC_ERROR_INTERRUPT 0b00000001 // 0 0 CRC failed + +// SI443X_REG_INTERRUPT_STATUS_2 +#define SI443X_SYNC_WORD_DETECTED_INTERRUPT 0b10000000 // 7 7 sync word has been detected +#define SI443X_VALID_PREAMBLE_DETECTED_INTERRUPT 0b01000000 // 6 6 valid preamble has been detected +#define SI443X_INVALID_PREAMBLE_DETECTED_INTERRUPT 0b00100000 // 5 5 invalid preamble has been detected +#define SI443X_RSSI_INTERRUPT 0b00010000 // 4 4 RSSI exceeded programmed threshold +#define SI443X_WAKEUP_TIMER_INTERRUPT 0b00001000 // 3 3 wake-up timer expired +#define SI443X_LOW_BATTERY_INTERRUPT 0b00000100 // 2 2 low battery detected +#define SI443X_CHIP_READY_INTERRUPT 0b00000010 // 1 1 chip ready event detected +#define SI443X_POWER_ON_RESET_INTERRUPT 0b00000001 // 0 0 power-on-reset detected + +// SI443X_REG_INTERRUPT_ENABLE_1 +#define SI443X_FIFO_LEVEL_ERROR_ENABLED 0b10000000 // 7 7 Tx/Rx FIFO overflow or underflow interrupt enabled +#define SI443X_TX_FIFO_ALMOST_FULL_ENABLED 0b01000000 // 6 6 Tx FIFO almost full interrupt enabled +#define SI443X_TX_FIFO_ALMOST_EMPTY_ENABLED 0b00100000 // 5 5 Tx FIFO almost empty interrupt enabled +#define SI443X_RX_FIFO_ALMOST_FULL_ENABLED 0b00010000 // 4 4 Rx FIFO almost full interrupt enabled +#define SI443X_EXTERNAL_ENABLED 0b00001000 // 3 3 external interrupt interrupt enabled +#define SI443X_PACKET_SENT_ENABLED 0b00000100 // 2 2 packet transmission done interrupt enabled +#define SI443X_VALID_PACKET_RECEIVED_ENABLED 0b00000010 // 1 1 valid packet received interrupt enabled +#define SI443X_CRC_ERROR_ENABLED 0b00000001 // 0 0 CRC failed interrupt enabled + +// SI443X_REG_INTERRUPT_ENABLE_2 +#define SI443X_SYNC_WORD_DETECTED_ENABLED 0b10000000 // 7 7 sync word interrupt enabled +#define SI443X_VALID_PREAMBLE_DETECTED_ENABLED 0b01000000 // 6 6 valid preamble interrupt enabled +#define SI443X_INVALID_PREAMBLE_DETECTED_ENABLED 0b00100000 // 5 5 invalid preamble interrupt enabled +#define SI443X_RSSI_ENABLED 0b00010000 // 4 4 RSSI exceeded programmed threshold interrupt enabled +#define SI443X_WAKEUP_TIMER_ENABLED 0b00001000 // 3 3 wake-up timer interrupt enabled +#define SI443X_LOW_BATTERY_ENABLED 0b00000100 // 2 2 low battery interrupt enabled +#define SI443X_CHIP_READY_ENABLED 0b00000010 // 1 1 chip ready event interrupt enabled +#define SI443X_POWER_ON_RESET_ENABLED 0b00000001 // 0 0 power-on-reset interrupt enabled + +// SI443X_REG_OP_FUNC_CONTROL_1 +#define SI443X_SOFTWARE_RESET 0b10000000 // 7 7 reset all registers to default values +#define SI443X_ENABLE_LOW_BATTERY_DETECT 0b01000000 // 6 6 enable low battery detection +#define SI443X_ENABLE_WAKEUP_TIMER 0b00100000 // 5 5 enable wakeup timer +#define SI443X_32_KHZ_RC 0b00000000 // 4 4 32.768 kHz source: RC oscillator (default) +#define SI443X_32_KHZ_XOSC 0b00010000 // 4 4 crystal oscillator +#define SI443X_TX_ON 0b00001000 // 3 3 Tx on in manual transmit mode +#define SI443X_RX_ON 0b00000100 // 2 2 Rx on in manual receive mode +#define SI443X_PLL_ON 0b00000010 // 1 1 PLL on (tune mode) +#define SI443X_XTAL_OFF 0b00000000 // 0 0 crystal oscillator: off (standby mode) +#define SI443X_XTAL_ON 0b00000001 // 0 0 on (ready mode) + +// SI443X_REG_OP_FUNC_CONTROL_2 +#define SI443X_ANT_DIV_TR_HL_IDLE_L 0b00000000 // 7 5 GPIO1/2 states: Tx/Rx GPIO1 H, GPIO2 L; idle low (default) +#define SI443X_ANT_DIV_TR_LH_IDLE_L 0b00100000 // 7 5 Tx/Rx GPIO1 L, GPIO2 H; idle low +#define SI443X_ANT_DIV_TR_HL_IDLE_H 0b01000000 // 7 5 Tx/Rx GPIO1 H, GPIO2 L; idle high +#define SI443X_ANT_DIV_TR_LH_IDLE_H 0b01100000 // 7 5 Tx/Rx GPIO1 L, GPIO2 H; idle high +#define SI443X_ANT_DIV_TR_ALG_IDLE_L 0b10000000 // 7 5 Tx/Rx diversity algorithm; idle low +#define SI443X_ANT_DIV_TR_ALG_IDLE_H 0b10100000 // 7 5 Tx/Rx diversity algorithm; idle high +#define SI443X_ANT_DIV_TR_ALG_BEACON_IDLE_L 0b11000000 // 7 5 Tx/Rx diversity algorithm (beacon); idle low +#define SI443X_ANT_DIV_TR_ALG_BEACON_IDLE_H 0b11100000 // 7 5 Tx/Rx diversity algorithm (beacon); idle high +#define SI443X_RX_MULTIPACKET_OFF 0b00000000 // 4 4 Rx multipacket: disabled (default) +#define SI443X_RX_MULTIPACKET_ON 0b00010000 // 4 4 enabled +#define SI443X_AUTO_TX_OFF 0b00000000 // 3 3 Tx autotransmit on FIFO almost full: disabled (default) +#define SI443X_AUTO_TX_ON 0b00001000 // 3 3 enabled +#define SI443X_LOW_DUTY_CYCLE_OFF 0b00000000 // 2 2 low duty cycle mode: disabled (default) +#define SI443X_LOW_DUTY_CYCLE_ON 0b00000100 // 2 2 enabled +#define SI443X_RX_FIFO_RESET 0b00000010 // 1 1 Rx FIFO reset/clear: reset (call first) +#define SI443X_RX_FIFO_CLEAR 0b00000000 // 1 1 clear (call second) +#define SI443X_TX_FIFO_RESET 0b00000001 // 0 0 Tx FIFO reset/clear: reset (call first) +#define SI443X_TX_FIFO_CLEAR 0b00000000 // 0 0 clear (call second) + +// SI443X_REG_XOSC_LOAD_CAPACITANCE +#define SI443X_XTAL_SHIFT 0b00000000 // 7 7 crystal capacitance configuration: +#define SI443X_XTAL_LOAD_CAPACITANCE 0b01111111 // 6 0 C_int = 1.8 pF + 0.085 pF * SI443X_XTAL_LOAD_CAPACITANCE + 3.7 pF * SI443X_XTAL_SHIFT + +// SI443X_REG_MCU_OUTPUT_CLOCK +#define SI443X_CLOCK_TAIL_CYCLES_OFF 0b00000000 // 5 4 additional clock cycles: none (default) +#define SI443X_CLOCK_TAIL_CYCLES_128 0b00010000 // 5 4 128 +#define SI443X_CLOCK_TAIL_CYCLES_256 0b00100000 // 5 4 256 +#define SI443X_CLOCK_TAIL_CYCLES_512 0b00110000 // 5 4 512 +#define SI443X_LOW_FREQ_CLOCK_OFF 0b00000000 // 3 3 32.768 kHz clock output: disabled (default) +#define SI443X_LOW_FREQ_CLOCK_ON 0b00001000 // 3 3 enabled +#define SI443X_MCU_CLOCK_30_MHZ 0b00000000 // 2 0 GPIO clock output: 30 MHz +#define SI443X_MCU_CLOCK_15_MHZ 0b00000001 // 2 0 15 MHz +#define SI443X_MCU_CLOCK_10_MHZ 0b00000010 // 2 0 10 MHz +#define SI443X_MCU_CLOCK_4_MHZ 0b00000011 // 2 0 4 MHz +#define SI443X_MCU_CLOCK_3_MHZ 0b00000100 // 2 0 3 MHz +#define SI443X_MCU_CLOCK_2_MHZ 0b00000101 // 2 0 2 MHz +#define SI443X_MCU_CLOCK_1_MHZ 0b00000110 // 2 0 1 MHz (default) +#define SI443X_MCU_CLOCK_32_KHZ 0b00000111 // 2 0 32.768 kHz + +// SI443X_REG_GPIO0_CONFIG + SI443X_REG_GPIO1_CONFIG + SI443X_REG_GPIO2_CONFIG +#define SI443X_GPIOX_DRIVE_STRENGTH 0b00000000 // 7 6 GPIOx drive strength (higher number = stronger drive) +#define SI443X_GPIOX_PULLUP_OFF 0b00000000 // 5 5 GPIOx internal 200k pullup: disabled (default) +#define SI443X_GPIOX_PULLUP_ON 0b00100000 // 5 5 enabled +#define SI443X_GPIO0_POWER_ON_RESET_OUT 0b00000000 // 4 0 GPIOx function: power-on-reset output (GPIO0 only, default) +#define SI443X_GPIO1_POWER_ON_RESET_INV_OUT 0b00000000 // 4 0 inverted power-on-reset output (GPIO1 only, default) +#define SI443X_GPIO2_MCU_CLOCK_OUT 0b00000000 // 4 0 MCU clock output (GPIO2 only, default) +#define SI443X_GPIOX_WAKEUP_OUT 0b00000001 // 4 0 wakeup timer expired output +#define SI443X_GPIOX_LOW_BATTERY_OUT 0b00000010 // 4 0 low battery detect output +#define SI443X_GPIOX_DIGITAL_OUT 0b00000011 // 4 0 direct digital output +#define SI443X_GPIOX_EXT_INT_FALLING_IN 0b00000100 // 4 0 external interrupt, falling edge +#define SI443X_GPIOX_EXT_INT_RISING_IN 0b00000101 // 4 0 external interrupt, rising edge +#define SI443X_GPIOX_EXT_INT_CHANGE_IN 0b00000110 // 4 0 external interrupt, state change +#define SI443X_GPIOX_ADC_IN 0b00000111 // 4 0 ADC analog input +#define SI443X_GPIOX_ANALOG_TEST_N_IN 0b00001000 // 4 0 analog test N input +#define SI443X_GPIOX_ANALOG_TEST_P_IN 0b00001001 // 4 0 analog test P input +#define SI443X_GPIOX_DIGITAL_IN 0b00001010 // 4 0 direct digital input +#define SI443X_GPIOX_DIGITAL_TEST_OUT 0b00001011 // 4 0 digital test output +#define SI443X_GPIOX_ANALOG_TEST_N_OUT 0b00001100 // 4 0 analog test N output +#define SI443X_GPIOX_ANALOG_TEST_P_OUT 0b00001101 // 4 0 analog test P output +#define SI443X_GPIOX_REFERENCE_VOLTAGE_OUT 0b00001110 // 4 0 reference voltage output +#define SI443X_GPIOX_TX_RX_DATA_CLK_OUT 0b00001111 // 4 0 Tx/Rx clock output in direct mode +#define SI443X_GPIOX_TX_DATA_IN 0b00010000 // 4 0 Tx data input direct mode +#define SI443X_GPIOX_EXT_RETRANSMIT_REQUEST_IN 0b00010001 // 4 0 external retransmission request input +#define SI443X_GPIOX_TX_STATE_OUT 0b00010010 // 4 0 Tx state output +#define SI443X_GPIOX_TX_FIFO_ALMOST_FULL_OUT 0b00010011 // 4 0 Tx FIFO almost full output +#define SI443X_GPIOX_RX_DATA_OUT 0b00010100 // 4 0 Rx data output +#define SI443X_GPIOX_RX_STATE_OUT 0b00010101 // 4 0 Rx state output +#define SI443X_GPIOX_RX_FIFO_ALMOST_FULL_OUT 0b00010110 // 4 0 Rx FIFO almost full output +#define SI443X_GPIOX_ANT_DIV_1_OUT 0b00010111 // 4 0 antenna diversity output 1 +#define SI443X_GPIOX_ANT_DIV_2_OUT 0b00011000 // 4 0 antenna diversity output 2 +#define SI443X_GPIOX_VALID_PREAMBLE_OUT 0b00011001 // 4 0 valid preamble detected output +#define SI443X_GPIOX_INVALID_PREAMBLE_OUT 0b00011010 // 4 0 invalid preamble detected output +#define SI443X_GPIOX_SYNC_WORD_DETECTED_OUT 0b00011011 // 4 0 sync word detected output +#define SI443X_GPIOX_CLEAR_CHANNEL_OUT 0b00011100 // 4 0 clear channel assessment output +#define SI443X_GPIOX_VDD 0b00011101 // 4 0 VDD +#define SI443X_GPIOX_GND 0b00011110 // 4 0 GND + +// SI443X_REG_IO_PORT_CONFIG +#define SI443X_GPIO2_EXT_INT_STATE_MASK 0b01000000 // 6 6 external interrupt state mask for: GPIO2 +#define SI443X_GPIO1_EXT_INT_STATE_MASK 0b00100000 // 5 5 GPIO1 +#define SI443X_GPIO0_EXT_INT_STATE_MASK 0b00010000 // 4 4 GPIO0 +#define SI443X_IRQ_BY_SDO_OFF 0b00000000 // 3 3 output IRQ state on SDO pin: disabled (default) +#define SI443X_IRQ_BY_SDO_ON 0b00001000 // 3 3 enabled +#define SI443X_GPIO2_DIGITAL_STATE_MASK 0b00000100 // 2 2 digital state mask for: GPIO2 +#define SI443X_GPIO1_DIGITAL_STATE_MASK 0b00000010 // 1 1 GPIO1 +#define SI443X_GPIO0_DIGITAL_STATE_MASK 0b00000001 // 0 0 GPIO0 + +// SI443X_REG_ADC_CONFIG +#define SI443X_ADC_START 0b10000000 // 7 7 ADC control: start measurement +#define SI443X_ADC_RUNNING 0b00000000 // 7 7 measurement in progress +#define SI443X_ADC_DONE 0b10000000 // 7 7 done +#define SI443X_ADC_SOURCE_TEMPERATURE 0b00000000 // 6 4 ADC source: internal temperature sensor (default) +#define SI443X_ADC_SOURCE_GPIO0_SINGLE 0b00010000 // 6 4 single-ended on GPIO0 +#define SI443X_ADC_SOURCE_GPIO1_SINGLE 0b00100000 // 6 4 single-ended on GPIO1 +#define SI443X_ADC_SOURCE_GPIO2_SINGLE 0b00110000 // 6 4 single-ended on GPIO2 +#define SI443X_ADC_SOURCE_GPIO01_DIFF 0b01000000 // 6 4 differential on GPIO0 (+) and GPIO1 (-) +#define SI443X_ADC_SOURCE_GPIO12_DIFF 0b01010000 // 6 4 differential on GPIO1 (+) and GPIO2 (-) +#define SI443X_ADC_SOURCE_GPIO02_DIFF 0b01100000 // 6 4 differential on GPIO0 (+) and GPIO2 (-) +#define SI443X_ADC_SOURCE_GND 0b01110000 // 6 4 GND +#define SI443X_ADC_REFERNCE_BAND_GAP 0b00000000 // 3 2 ADC reference: internal bandgap 1.2 V (default) +#define SI443X_ADC_REFERNCE_VDD_3 0b00001000 // 3 2 VDD/3 +#define SI443X_ADC_REFERNCE_VDD_2 0b00001100 // 3 2 VDD/2 +#define SI443X_ADC_GAIN 0b00000000 // 1 0 ADC amplifier gain + +// SI443X_REG_ADC_SENSOR_AMP_OFFSET +#define SI443X_ADC_OFFSET 0b00000000 // 3 0 ADC offset + +// SI443X_REG_TEMP_SENSOR_CONTROL +#define SI443X_TEMP_SENSOR_RANGE_64_TO_64_C 0b00000000 // 7 6 temperature sensor range: -64 to 64 deg. C, 0.5 deg. C resolution (default) +#define SI443X_TEMP_SENSOR_RANGE_64_TO_192_C 0b01000000 // 7 6 -64 to 192 deg. C, 1.0 deg. C resolution +#define SI443X_TEMP_SENSOR_RANGE_0_TO_128_C 0b11000000 // 7 6 0 to 128 deg. C, 0.5 deg. C resolution +#define SI443X_TEMP_SENSOR_RANGE_40_TO_216_F 0b10000000 // 7 6 -40 to 216 deg. F, 1.0 deg. F resolution +#define SI443X_TEMP_SENSOR_KELVIN_TO_CELSIUS_OFF 0b00000000 // 5 5 Kelvin to Celsius offset: disabled +#define SI443X_TEMP_SENSOR_KELVIN_TO_CELSIUS_ON 0b00100000 // 5 5 enabled (default) +#define SI443X_TEMP_SENSOR_TRIM_OFF 0b00000000 // 4 4 temperature sensor trim: disabled (default) +#define SI443X_TEMP_SENSOR_TRIM_ON 0b00010000 // 4 4 enabled +#define SI443X_TEMP_SENSOR_TRIM_VALUE 0b00000000 // 3 0 temperature sensor trim value + +// SI443X_REG_WAKEUP_TIMER_PERIOD_1 +#define SI443X_WAKEUP_TIMER_EXPONENT 0b00000011 // 4 0 wakeup timer value exponent + +// SI443X_REG_WAKEUP_TIMER_PERIOD_2 + SI443X_REG_WAKEUP_TIMER_PERIOD_3 +#define SI443X_WAKEUP_TIMER_MANTISSA_MSB 0x00 // 7 0 wakeup timer value: +#define SI443X_WAKEUP_TIMER_MANTISSA_LSB 0x01 // 7 0 T = (4 * SI443X_WAKEUP_TIMER_MANTISSA * 2 ^ SI443X_WAKEUP_TIMER_EXPONENT) / 32.768 ms + +// SI443X_REG_LOW_DC_MODE_DURATION +#define SI443X_LOW_DC_MODE_DURATION_MANTISSA 0x01 // 7 0 low duty cycle mode duration: T = (4 * SI443X_LOW_DC_MODE_DURATION_MANTISSA * 2 ^ SI443X_WAKEUP_TIMER_EXPONENT) / 32.768 ms + +// SI443X_REG_LOW_BATT_DET_THRESHOLD +#define SI443X_LOW_BATT_DET_THRESHOLD 0b00010100 // 4 0 low battery detection threshold: Vth = 1.7 + SI443X_LOW_BATT_DET_THRESHOLD * 0.05 V (defaults to 2.7 V) + +// SI443X_REG_IF_FILTER_BANDWIDTH +#define SI443X_BYPASS_DEC_BY_3_OFF 0b00000000 // 7 7 bypass decimate-by-3 stage: disabled (default) +#define SI443X_BYPASS_DEC_BY_3_ON 0b10000000 // 7 7 enabled +#define SI443X_IF_FILTER_DEC_RATE 0b00000000 // 6 4 IF filter decimation rate +#define SI443X_IF_FILTER_COEFF_SET 0b00000001 // 3 0 IF filter coefficient set selection + +// SI443X_REG_AFC_LOOP_GEARSHIFT_OVERRIDE +#define SI443X_AFC_WIDEBAND_OFF 0b00000000 // 7 7 AFC wideband: disabled (default) +#define SI443X_AFC_WIDEBAND_ON 0b10000000 // 7 7 enabled +#define SI443X_AFC_OFF 0b00000000 // 6 6 AFC: disabled +#define SI443X_AFC_ON 0b01000000 // 6 6 enabled (default) +#define SI443X_AFC_HIGH_GEAR_SETTING 0b00000000 // 5 3 AFC high gear setting +#define SI443X_SECOND_PHASE_BIAS_0_DB 0b00000100 // 2 2 second phase antenna selection bias: 0 dB (default) +#define SI443X_SECOND_PHASE_BIAS_1_5_DB 0b00000000 // 2 2 1.5 dB +#define SI443X_MOVING_AVERAGE_TAP_8 0b00000010 // 1 1 moving average filter tap length: 8*Tb +#define SI443X_MOVING_AVERAGE_TAP_4 0b00000000 // 1 1 4*Tb after first preamble (default) +#define SI443X_ZERO_PHASE_RESET_5 0b00000000 // 0 0 reset preamble detector after: 5 zero phases (default) +#define SI443X_ZERO_PHASE_RESET_2 0b00000001 // 0 0 3 zero phases + +// SI443X_REG_AFC_TIMING_CONTROL +#define SI443X_SW_ANT_TIMER 0b00000000 // 7 6 number of periods to wait for RSSI to stabilize during antenna switching +#define SI443X_SHORT_WAIT 0b00001000 // 5 3 period to wait after AFC correction +#define SI443X_ANTENNA_SWITCH_WAIT 0b00000010 // 2 0 antenna switching wait time + +// SI443X_REG_CLOCK_REC_GEARSHIFT_OVERRIDE +#define SI443X_CLOCK_RECOVER_FAST_GEARSHIFT 0b00000000 // 5 3 clock recovery fast gearshift value +#define SI443X_CLOCK_RECOVER_SLOW_GEARSHIFT 0b00000011 // 2 0 clock recovery slow gearshift value + +// SI443X_REG_CLOCK_REC_OVERSAMP_RATIO +#define SI443X_CLOCK_REC_OVERSAMP_RATIO_LSB 0b01100100 // 7 0 oversampling rate LSB, defaults to 12.5 clock cycles per bit + +// SI443X_REG_CLOCK_REC_OFFSET_2 +#define SI443X_CLOCK_REC_OVERSAMP_RATIO_MSB 0b00000000 // 7 5 oversampling rate MSB, defaults to 12.5 clock cycles per bit +#define SI443X_SECOND_PHASE_SKIP_THRESHOLD 0b00000000 // 4 4 skip seconds phase antenna diversity threshold +#define SI443X_NCO_OFFSET_MSB 0b00000001 // 3 0 NCO offset MSB + +// SI443X_REG_CLOCK_REC_OFFSET_1 +#define SI443X_NCO_OFFSET_MID 0b01000111 // 7 0 NCO offset MID + +// SI443X_REG_CLOCK_REC_OFFSET_0 +#define SI443X_NCO_OFFSET_LSB 0b10101110 // 7 0 NCO offset LSB + +// SI443X_REG_CLOCK_REC_TIMING_LOOP_GAIN_1 +#define SI443X_RX_COMPENSATION_OFF 0b00000000 // 4 4 Rx compensation for high data rate: disabled (default) +#define SI443X_RX_COMPENSATION_ON 0b00010000 // 4 4 enabled +#define SI443X_CLOCK_REC_GAIN_DOUBLE_OFF 0b00000000 // 3 3 clock recovery gain doubling: disabled (default) +#define SI443X_CLOCK_REC_GAIN_DOUBLE_ON 0b00001000 // 3 3 enabled +#define SI443X_CLOCK_REC_LOOP_GAIN_MSB 0b00000010 // 2 0 clock recovery timing loop gain MSB + +// SI443X_REG_CLOCK_REC_TIMING_LOOP_GAIN_0 +#define SI443X_CLOCK_REC_LOOP_GAIN_LSB 0b10001111 // 7 0 clock recovery timing loop gain LSB + +// SI443X_REG_RSSI_CLEAR_CHANNEL_THRESHOLD +#define SI443X_RSSI_CLEAR_CHANNEL_THRESHOLD 0b00011110 // 7 0 RSSI clear channel interrupt threshold + +// SI443X_REG_AFC_LIMITER +#define SI443X_AFC_LIMITER 0x00 // 7 0 AFC limiter value + +// SI443X_REG_OOK_COUNTER_1 +#define SI443X_OOK_FREEZE_OFF 0b00000000 // 5 5 OOK moving average detector freeze: disabled (default) +#define SI443X_OOK_FREEZE_ON 0b00100000 // 5 5 enabled +#define SI443X_PEAK_DETECTOR_OFF 0b00000000 // 4 4 peak detector: disabled +#define SI443X_PEAK_DETECTOR_ON 0b00010000 // 4 4 enabled (default) +#define SI443X_OOK_MOVING_AVERAGE_OFF 0b00000000 // 3 3 OOK moving average: disabled +#define SI443X_OOK_MOVING_AVERAGE_ON 0b00001000 // 3 3 enabled (default) +#define SI443X_OOK_COUNTER_MSB 0b00000000 // 2 0 OOK counter MSB + +// SI443X_REG_OOK_COUNTER_2 +#define SI443X_OOK_COUNTER_LSB 0b10111100 // 7 0 OOK counter LSB + +// SI443X_REG_SLICER_PEAK_HOLD +#define SI443X_PEAK_DETECTOR_ATTACK 0b00010000 // 6 4 OOK peak detector attach time +#define SI443X_PEAK_DETECTOR_DECAY 0b00001100 // 3 0 OOK peak detector decay time + +// SI443X_REG_DATA_ACCESS_CONTROL +#define SI443X_PACKET_RX_HANDLING_OFF 0b00000000 // 7 7 packet Rx handling: disabled +#define SI443X_PACKET_RX_HANDLING_ON 0b10000000 // 7 7 enabled (default) +#define SI443X_LSB_FIRST_OFF 0b00000000 // 6 6 LSB first transmission: disabled (default) +#define SI443X_LSB_FIRST_ON 0b01000000 // 6 6 enabled +#define SI443X_CRC_DATA_ONLY_OFF 0b00000000 // 5 5 CRC calculated only from data fields: disabled (default) +#define SI443X_CRC_DATA_ONLY_ON 0b00100000 // 5 5 enabled +#define SI443X_SKIP_SECOND_PHASE_PREAMBLE_DET_OFF 0b00000000 // 4 4 skip second phase of preamble detection: disabled (default) +#define SI443X_SKIP_SECOND_PHASE_PREAMBLE_DET_ON 0b00010000 // 4 4 enabled +#define SI443X_PACKET_TX_HANDLING_OFF 0b00000000 // 3 3 packet Tx handling: disabled +#define SI443X_PACKET_TX_HANDLING_ON 0b00001000 // 3 3 enabled (default) +#define SI443X_CRC_OFF 0b00000000 // 2 2 CRC: disabled +#define SI443X_CRC_ON 0b00000100 // 2 2 enabled (default) +#define SI443X_CRC_CCITT 0b00000000 // 1 0 CRC type: CCITT +#define SI443X_CRC_IBM_CRC16 0b00000001 // 1 0 IBM CRC-16 (default) +#define SI443X_CRC_IEC16 0b00000010 // 1 0 IEC-16 +#define SI443X_CRC_BIACHEVA 0b00000011 // 1 0 Biacheva + +// SI443X_REG_EZMAC_STATUS +#define SI443X_CRC_ALL_ONE 0b01000000 // 6 6 last received CRC was all ones +#define SI443X_PACKET_SEARCHING 0b00100000 // 5 5 radio is searching for a valid packet +#define SI443X_PACKET_RECEIVING 0b00010000 // 4 4 radio is currently receiving packet +#define SI443X_VALID_PACKET_RECEIVED 0b00001000 // 3 3 valid packet was received +#define SI443X_CRC_ERROR 0b00000100 // 2 2 CRC check failed +#define SI443X_PACKET_TRANSMITTING 0b00000010 // 1 1 radio is currently transmitting packet +#define SI443X_PACKET_SENT 0b00000001 // 0 0 packet sent + +// SI443X_REG_HEADER_CONTROL_1 +#define SI443X_BROADCAST_ADDR_CHECK_NONE 0b00000000 // 7 4 broadcast address check: none (default) +#define SI443X_BROADCAST_ADDR_CHECK_BYTE0 0b00010000 // 7 4 on byte 0 +#define SI443X_BROADCAST_ADDR_CHECK_BYTE1 0b00100000 // 7 4 on byte 1 +#define SI443X_BROADCAST_ADDR_CHECK_BYTE2 0b01000000 // 7 4 on byte 2 +#define SI443X_BROADCAST_ADDR_CHECK_BYTE3 0b10000000 // 7 4 on byte 3 +#define SI443X_RECEIVED_HEADER_CHECK_NONE 0b00000000 // 3 0 received header check: none +#define SI443X_RECEIVED_HEADER_CHECK_BYTE0 0b00000001 // 3 0 on byte 0 +#define SI443X_RECEIVED_HEADER_CHECK_BYTE1 0b00000010 // 3 0 on byte 1 +#define SI443X_RECEIVED_HEADER_CHECK_BYTE2 0b00000100 // 3 0 on byte 2 (default) +#define SI443X_RECEIVED_HEADER_CHECK_BYTE3 0b00001000 // 3 0 on byte 3 (default) + +// SI443X_REG_HEADER_CONTROL_2 +#define SI443X_SYNC_WORD_TIMEOUT_OFF 0b00000000 // 7 7 ignore timeout period when searching for sync word: disabled (default) +#define SI443X_SYNC_WORD_TIMEOUT_ON 0b10000000 // 7 7 enabled +#define SI443X_HEADER_LENGTH_HEADER_NONE 0b00000000 // 6 4 header length: none +#define SI443X_HEADER_LENGTH_HEADER_3 0b00010000 // 6 4 header 3 +#define SI443X_HEADER_LENGTH_HEADER_32 0b00100000 // 6 4 header 3 and 2 +#define SI443X_HEADER_LENGTH_HEADER_321 0b00110000 // 6 4 header 3, 2 and 1 (default) +#define SI443X_HEADER_LENGTH_HEADER_3210 0b01000000 // 6 4 header 3, 2, 1, and 0 +#define SI443X_FIXED_PACKET_LENGTH_OFF 0b00000000 // 3 3 fixed packet length mode: disabled (default) +#define SI443X_FIXED_PACKET_LENGTH_ON 0b00001000 // 3 3 enabled +#define SI443X_SYNC_LENGTH_SYNC_3 0b00000000 // 2 1 sync word length: sync 3 +#define SI443X_SYNC_LENGTH_SYNC_32 0b00000010 // 2 1 sync 3 and 2 (default) +#define SI443X_SYNC_LENGTH_SYNC_321 0b00000100 // 2 1 sync 3, 2 and 1 +#define SI443X_SYNC_LENGTH_SYNC_3210 0b00000110 // 2 1 sync 3, 2, 1 and 0 +#define SI443X_PREAMBLE_LENGTH_MSB 0b00000000 // 0 0 preamble length MSB + +// SI443X_REG_PREAMBLE_LENGTH +#define SI443X_PREAMBLE_LENGTH_LSB 0b00001000 // 0 0 preamble length LSB, defaults to 32 bits + +// SI443X_REG_PREAMBLE_DET_CONTROL +#define SI443X_PREAMBLE_DET_THRESHOLD 0b00101000 // 7 3 number of 4-bit nibbles in valid preamble, defaults to 20 bits +#define SI443X_RSSI_OFFSET 0b00000010 // 2 0 RSSI calculation offset, defaults to +8 dB + +// SI443X_REG_SYNC_WORD_3 - SI443X_REG_SYNC_WORD_0 +#define SI443X_SYNC_WORD_3 0x2D // 7 0 sync word: 4th byte (MSB) +#define SI443X_SYNC_WORD_2 0xD4 // 7 0 3rd byte +#define SI443X_SYNC_WORD_1 0x00 // 7 0 2nd byte +#define SI443X_SYNC_WORD_0 0x00 // 7 0 1st byte (LSB) + +// SI443X_REG_CHANNEL_FILTER_COEFF +#define SI443X_INVALID_PREAMBLE_THRESHOLD 0b00000000 // 7 4 invalid preamble threshold in nibbles + +// SI443X_REG_XOSC_CONTROL_TEST +#define SI443X_STATE_LOW_POWER 0b00000000 // 7 5 chip power state: low power +#define SI443X_STATE_READY 0b00100000 // 7 5 ready +#define SI443X_STATE_TUNE 0b01100000 // 7 5 tune +#define SI443X_STATE_TX 0b01000000 // 7 5 Tx +#define SI443X_STATE_RX 0b11100000 // 7 5 Rx + +// SI443X_REG_AGC_OVERRIDE_1 +#define SI443X_AGC_GAIN_INCREASE_OFF 0b00000000 // 6 6 AGC gain increase override: disabled (default) +#define SI443X_AGC_GAIN_INCREASE_ON 0b01000000 // 6 6 enabled +#define SI443X_AGC_OFF 0b00000000 // 5 5 AGC loop: disabled +#define SI443X_AGC_ON 0b00100000 // 5 5 enabled (default) +#define SI443X_LNA_GAIN_MIN 0b00000000 // 4 4 LNA gain select: 5 dB (default) +#define SI443X_LNA_GAIN_MAX 0b00010000 // 4 4 25 dB +#define SI443X_PGA_GAIN_OVERRIDE 0b00000000 // 3 0 PGA gain override, gain = SI443X_PGA_GAIN_OVERRIDE * 3 dB + +// SI443X_REG_TX_POWER +#define SI443X_LNA_SWITCH_OFF 0b00000000 // 3 3 LNA switch control: disabled +#define SI443X_LNA_SWITCH_ON 0b00001000 // 3 3 enabled (default) +#define SI443X_OUTPUT_POWER 0b00000000 // 2 0 output power in 3 dB steps, 0 is chip min, 7 is chip max + +// SI443X_REG_TX_DATA_RATE_1 + SI443X_REG_TX_DATA_RATE_0 +#define SI443X_DATA_RATE_MSB 0x0A // 7 0 data rate: DR = 10^6 * (SI443X_DATA_RATE / 2^16) in high data rate mode or +#define SI443X_DATA_RATE_LSB 0x3D // 7 0 DR = 10^6 * (SI443X_DATA_RATE / 2^21) in low data rate mode (defaults to 40 kbps) + +// SI443X_REG_MODULATION_MODE_CONTROL_1 +#define SI443X_HIGH_DATA_RATE_MODE 0b00000000 // 5 5 data rate: above 30 kbps (default) +#define SI443X_LOW_DATA_RATE_MODE 0b00100000 // 5 5 below 30 kbps +#define SI443X_PACKET_HANDLER_POWER_DOWN_OFF 0b00000000 // 4 4 power off packet handler in low power mode: disabled (default) +#define SI443X_PACKET_HANDLER_POWER_DOWN_ON 0b00010000 // 4 4 enabled +#define SI443X_MANCHESTER_PREAMBLE_POL_LOW 0b00000000 // 3 3 preamble polarity in Manchester mode: low +#define SI443X_MANCHESTER_PREAMBLE_POL_HIGH 0b00001000 // 3 3 high (default) +#define SI443X_MANCHESTER_INVERTED_OFF 0b00000000 // 2 2 inverted Manchester encoding: disabled +#define SI443X_MANCHESTER_INVERTED_ON 0b00000100 // 2 2 enabled (default) +#define SI443X_MANCHESTER_OFF 0b00000000 // 1 1 Manchester encoding: disabled (default) +#define SI443X_MANCHESTER_ON 0b00000010 // 1 1 enabled +#define SI443X_WHITENING_OFF 0b00000000 // 0 0 data whitening: disabled (default) +#define SI443X_WHITENING_ON 0b00000001 // 0 0 enabled + +// SI443X_REG_MODULATION_MODE_CONTROL_2 +#define SI443X_TX_DATA_CLOCK_NONE 0b00000000 // 7 6 Tx data clock: disabled (default) +#define SI443X_TX_DATA_CLOCK_GPIO 0b01000000 // 7 6 GPIO pin +#define SI443X_TX_DATA_CLOCK_SDI 0b10000000 // 7 6 SDI pin +#define SI443X_TX_DATA_CLOCK_NIRQ 0b11000000 // 7 6 nIRQ pin +#define SI443X_TX_DATA_SOURCE_GPIO 0b00000000 // 5 4 Tx data source in direct mode: GPIO pin (default) +#define SI443X_TX_DATA_SOURCE_SDI 0b00010000 // 5 4 SDI pin +#define SI443X_TX_DATA_SOURCE_FIFO 0b00100000 // 5 4 FIFO +#define SI443X_TX_DATA_SOURCE_PN9 0b00110000 // 5 4 PN9 internal +#define SI443X_TX_RX_INVERTED_OFF 0b00000000 // 3 3 Tx/Rx data inverted: disabled (default) +#define SI443X_TX_RX_INVERTED_ON 0b00001000 // 3 3 enabled +#define SI443X_FREQUENCY_DEVIATION_MSB 0b00000000 // 2 2 frequency deviation MSB +#define SI443X_MODULATION_NONE 0b00000000 // 1 0 modulation type: unmodulated carrier (default) +#define SI443X_MODULATION_OOK 0b00000001 // 1 0 OOK +#define SI443X_MODULATION_FSK 0b00000010 // 1 0 FSK +#define SI443X_MODULATION_GFSK 0b00000011 // 1 0 GFSK + +// SI443X_REG_FREQUENCY_DEVIATION +#define SI443X_FREQUENCY_DEVIATION_LSB 0b00100000 // 7 0 frequency deviation LSB, Fd = 625 Hz * SI443X_FREQUENCY_DEVIATION, defaults to 20 kHz + +// SI443X_REG_FREQUENCY_OFFSET_1 + SI443X_REG_FREQUENCY_OFFSET_2 +#define SI443X_FREQUENCY_OFFSET_MSB 0x00 // 7 0 frequency offset: +#define SI443X_FREQUENCY_OFFSET_LSB 0x00 // 1 0 Foff = 156.25 Hz * (SI443X_BAND_SELECT + 1) * SI443X_FREQUENCY_OFFSET, defaults to 156.25 Hz + +// SI443X_REG_FREQUENCY_BAND_SELECT +#define SI443X_SIDE_BAND_SELECT_LOW 0b00000000 // 6 6 Rx LO tuning: below channel frequency (default) +#define SI443X_SIDE_BAND_SELECT_HIGH 0b01000000 // 6 6 above channel frequency +#define SI443X_BAND_SELECT_LOW 0b00000000 // 5 5 band select: low, 240 - 479.9 MHz +#define SI443X_BAND_SELECT_HIGH 0b00100000 // 5 5 high, 480 - 960 MHz (default) +#define SI443X_FREQUENCY_BAND_SELECT 0b00010101 // 4 0 frequency band select + +// SI443X_REG_NOM_CARRIER_FREQUENCY_1 + SI443X_REG_NOM_CARRIER_FREQUENCY_0 +#define SI443X_NOM_CARRIER_FREQUENCY_MSB 0b10111011 // 7 0 nominal carrier frequency: +#define SI443X_NOM_CARRIER_FREQUENCY_LSB 0b10000000 // 7 0 Fc = (SI443X_BAND_SELECT + 1)*10*(SI443X_FREQUENCY_BAND_SELECT + 24) + (SI443X_NOM_CARRIER_FREQUENCY - SI443X_FREQUENCY_OFFSET)/6400 [MHz] + +// SI443X_REG_FREQUENCY_HOPPING_CHANNEL_SEL +#define SI443X_FREQUENCY_HOPPING_CHANNEL 0x00 // 7 0 frequency hopping channel number + +// SI443X_REG_FREQUENCY_HOPPING_STEP_SIZE +#define SI443X_FREQUENCY_HOPPING_STEP_SIZE 0x00 // 7 0 frequency hopping step size + +// SI443X_REG_TX_FIFO_CONTROL_1 +#define SI443X_TX_FIFO_ALMOST_FULL_THRESHOLD 0x37 // 5 0 Tx FIFO almost full threshold + +// SI443X_REG_TX_FIFO_CONTROL_2 +#define SI443X_TX_FIFO_ALMOST_EMPTY_THRESHOLD 0x04 // 5 0 Tx FIFO almost full threshold + +// SI443X_REG_RX_FIFO_CONTROL +#define SI443X_RX_FIFO_ALMOST_FULL_THRESHOLD 0x37 // 5 0 Rx FIFO almost full threshold + +/*! + \class Si443x + + \brief Base class for Si443x series. All derived classes for Si443x (e.g. Si4431 or Si4432) inherit from this base class. + This class should not be instantiated directly from Arduino sketch, only from its derived classes. +*/ +class Si443x: public PhysicalLayer { + public: + // introduce PhysicalLayer overloads + using PhysicalLayer::transmit; + using PhysicalLayer::receive; + using PhysicalLayer::startTransmit; + using PhysicalLayer::readData; + + // constructor + + /*! + \brief Default constructor. + + \param mod Instance of Module that will be used to communicate with the radio. + */ + Si443x(Module* mod); + + // basic methods + + /*! + \brief Initialization method. + + \param br Bit rate of the FSK transmission in kbps (kilobits per second). + + \param freqDev Frequency deviation of the FSK transmission in kHz. + + \param rxBw Receiver bandwidth in kHz. + + \param preambleLen Preamble Length in bits. + + \returns \ref status_codes + */ + int16_t begin(float br, float freqDev, float rxBw, uint8_t preambleLen); + + /*! + \brief Reset method. Will reset the chip to the default state using SDN pin. + */ + void reset(); + + /*! + \brief Binary transmit method. Will transmit arbitrary binary data up to 64 bytes long. + For overloads to transmit Arduino String or C-string, see PhysicalLayer::transmit. + + \param data Binary data that will be transmitted. + + \param len Length of binary data to transmit (in bytes). + + \param addr Node address to transmit the packet to. + + \returns \ref status_codes + */ + int16_t transmit(uint8_t* data, size_t len, uint8_t addr = 0) override; + + /*! + \brief Binary receive method. Will attempt to receive arbitrary binary data up to 64 bytes long. + For overloads to receive Arduino String, see PhysicalLayer::receive. + + \param data Pointer to array to save the received binary data. + + \param len Number of bytes that will be received. Must be known in advance for binary transmissions. + + \returns \ref status_codes + */ + int16_t receive(uint8_t* data, size_t len) override; + + /*! + \brief Sets the module to sleep to save power. %Module will not be able to transmit or receive any data while in sleep mode. + %Module will wake up automatically when methods like transmit or receive are called. + + \returns \ref status_codes + */ + int16_t sleep(); + + /*! + \brief Sets the module to standby. + + \returns \ref status_codes + */ + int16_t standby() override; + + /*! + \brief Enables direct transmission mode. While in direct mode, the module will not be able to transmit or receive packets. + + \param FRF 24-bit raw frequency value to start transmitting at. Required for quick frequency shifts in RTTY. + + \returns \ref status_codes + */ + int16_t transmitDirect(uint32_t frf = 0) override; + + /*! + \brief Enables direct reception mode. While in direct mode, the module will not be able to transmit or receive packets. + + \returns \ref status_codes + */ + int16_t receiveDirect() override; + + /*! + \brief Disables direct mode and enables packet mode, allowing the module to receive packets. + + \returns \ref status_codes + */ + int16_t packetMode(); + + // interrupt methods + + /*! + \brief Sets interrupt service routine to call when IRQ activates. + + \param func ISR to call. + */ + void setIrqAction(void (*func)(void)); + + /*! + \brief Clears interrupt service routine to call when IRQ activates. + */ + void clearIrqAction(); + + /*! + \brief Interrupt-driven binary transmit method. Will start transmitting arbitrary binary data up to 64 bytes long. + + \param data Binary data that will be transmitted. + + \param len Length of binary data to transmit (in bytes). + + \param addr Node address to transmit the packet to. + + \returns \ref status_codes + */ + int16_t startTransmit(uint8_t* data, size_t len, uint8_t addr = 0) override; + + /*! + \brief Interrupt-driven receive method. IRQ will be activated when full valid packet is received. + + \returns \ref status_codes + */ + int16_t startReceive(); + + /*! + \brief Reads data that was received after calling startReceive method. This method reads len characters. + + \param data Pointer to array to save the received binary data. + + \param len Number of bytes that will be received. Must be known in advance for binary transmissions. + + \returns \ref status_codes + */ + int16_t readData(uint8_t* data, size_t len) override; + + // configuration methods + + /*! + \brief Sets FSK bit rate. Allowed values range from 0.123 to 256.0 kbps. + + \param br Bit rate to be set (in kbps). + + \returns \ref status_codes + */ + int16_t setBitRate(float br); + + /*! + \brief Sets FSK frequency deviation from carrier frequency. Allowed values range from 0.625 to 320.0 kHz. + + \param freqDev Frequency deviation to be set (in kHz). + + \returns \ref status_codes + */ + int16_t setFrequencyDeviation(float freqDev) override; + + /*! + \brief Sets receiver bandwidth. Allowed values range from 2.6 to 620.7 kHz. + + \param rxBw Receiver bandwidth to be set in kHz. + + \returns \ref status_codes + */ + int16_t setRxBandwidth(float rxBw); + + /*! + \brief Sets sync word. Up to 4 bytes can be set as sync word. + + \param syncWord Pointer to the array of sync word bytes. + + \param len Sync word length in bytes. + */ + int16_t setSyncWord(uint8_t* syncWord, size_t len); + + /*! + \brief Sets preamble length. + + \param preambleLen Preamble length to be set (in bits). + + \returns \ref status_codes + */ + int16_t setPreambleLength(uint8_t preambleLen); + + /*! + \brief Query modem for the packet length of received payload. + + \param update Update received packet length. Will return cached value when set to false. + + \returns Length of last received packet in bytes. + */ + size_t getPacketLength(bool update = true) override; + + /*! + \brief Sets transmission encoding. Only available in FSK mode. + Allowed values are RADIOLIB_ENCODING_NRZ, RADIOLIB_ENCODING_MANCHESTER and RADIOLIB_ENCODING_WHITENING. + + \param encoding Encoding to be used. + + \returns \ref status_codes + */ + int16_t setEncoding(uint8_t encoding) override; + + /*! + \brief Sets Gaussian filter bandwidth-time product that will be used for data shaping. Only available in FSK mode with FSK modulation. + Allowed values are RADIOLIB_SHAPING_0_3, RADIOLIB_SHAPING_0_5 or RADIOLIB_SHAPING_1_0. Set to RADIOLIB_SHAPING_NONE to disable data shaping. + + \param sh Gaussian shaping bandwidth-time product that will be used for data shaping + + \returns \ref status_codes + */ + int16_t setDataShaping(uint8_t sh) override; + + /*! + \brief Some modules contain external RF switch controlled by two pins. This function gives RadioLib control over those two pins to automatically switch Rx and Tx state. + When using automatic RF switch control, DO NOT change the pin mode of rxEn or txEn from Arduino sketch! + + \param rxEn RX enable pin. + + \param txEn TX enable pin. + */ + void setRfSwitchPins(RADIOLIB_PIN_TYPE rxEn, RADIOLIB_PIN_TYPE txEn); + +#ifndef RADIOLIB_GODMODE + protected: +#endif + Module* _mod; + + float _br = 0; + float _freqDev = 0; + + size_t _packetLength = 0; + bool _packetLengthQueried = false; + + int16_t setFrequencyRaw(float newFreq); + +#ifndef RADIOLIB_GODMODE + private: +#endif + bool findChip(); + void clearIRQFlags(); + int16_t config(); + int16_t updateClockRecovery(); + int16_t directMode(); +}; + +#endif + +#endif diff --git a/src/modules/XBee/XBee.cpp b/src/modules/XBee/XBee.cpp index 1e5d7a15..9b1abe73 100644 --- a/src/modules/XBee/XBee.cpp +++ b/src/modules/XBee/XBee.cpp @@ -1,10 +1,9 @@ #include "XBee.h" +#if !defined(RADIOLIB_EXCLUDE_XBEE) XBee::XBee(Module* mod) { _mod = mod; - _frameID = 0x01; - _frameLength = 0; - _frameHeaderProcessed = false; + _packetData[0] = '\0'; } int16_t XBee::begin(long speed) { @@ -35,7 +34,7 @@ int16_t XBee::begin(long speed) { RADIOLIB_DEBUG_PRINTLN(state); RADIOLIB_DEBUG_PRINTLN(F("Resetting ...")); reset(); - delay(1000); + delay(10); _mod->ATemptyBuffer(); i++; } @@ -54,7 +53,7 @@ int16_t XBee::begin(long speed) { void XBee::reset() { pinMode(_mod->getRst(), OUTPUT); digitalWrite(_mod->getRst(), LOW); - delayMicroseconds(200); + delay(1); digitalWrite(_mod->getRst(), HIGH); } @@ -96,9 +95,9 @@ size_t XBee::available() { return(0); } - uint8_t header[3]; if(!_frameHeaderProcessed) { // read frame header + uint8_t header[3]; for(uint8_t i = 0; i < 3; i++) { header[i] = _mod->ModuleSerial->read(); } @@ -184,7 +183,8 @@ XBeeSerial::XBeeSerial(Module* mod) : ISerial(mod) { int16_t XBeeSerial::begin(long speed) { // set module properties - _mod->AtLineFeed = "\r"; + char lf[3] = "\r"; + memcpy(_mod->AtLineFeed, lf, strlen(lf)); _mod->baudrate = speed; _mod->init(RADIOLIB_USE_UART); @@ -218,7 +218,7 @@ int16_t XBeeSerial::begin(long speed) { void XBeeSerial::reset() { pinMode(_mod->getRst(), OUTPUT); digitalWrite(_mod->getRst(), LOW); - delayMicroseconds(200); + delay(1); digitalWrite(_mod->getRst(), HIGH); pinMode(_mod->getRst(), INPUT); } @@ -391,7 +391,7 @@ void XBee::sendApiFrame(uint8_t type, uint8_t id, uint8_t* data, uint16_t length } int16_t XBee::readApiFrame(uint8_t frameID, uint8_t codePos, uint16_t timeout) { - // TODO: modemStatus frames may be sent at any time, interfering with frame parsing. Add check to make sure this does not happen. + /// \todo modemStatus frames may be sent at any time, interfering with frame parsing. Add check to make sure this does not happen. // get number of bytes in response (must be enough to read the length field uint16_t numBytes = getNumBytes(timeout/2, 3); @@ -405,6 +405,7 @@ int16_t XBee::readApiFrame(uint8_t frameID, uint8_t codePos, uint16_t timeout) { // wait until all response bytes are available (5s timeout) uint32_t start = millis(); while(_mod->ModuleSerial->available() < (int16_t)numBytes) { + yield(); if(millis() - start >= timeout/2) { return(ERR_FRAME_MALFORMED); } @@ -456,6 +457,7 @@ uint16_t XBee::getNumBytes(uint32_t timeout, size_t minBytes) { // wait for available data uint32_t start = millis(); while((size_t)_mod->ModuleSerial->available() < minBytes) { + yield(); if(millis() - start >= timeout) { return(0); } @@ -466,6 +468,7 @@ uint16_t XBee::getNumBytes(uint32_t timeout, size_t minBytes) { uint8_t i = 0; RADIOLIB_DEBUG_PRINT(F("reading frame length: ")); while(_mod->ModuleSerial->available() > 0) { + yield(); uint8_t b = _mod->ModuleSerial->read(); RADIOLIB_DEBUG_PRINT(b, HEX); RADIOLIB_DEBUG_PRINT('\t'); @@ -478,3 +481,5 @@ uint16_t XBee::getNumBytes(uint32_t timeout, size_t minBytes) { return((resp[1] << 8) | resp[2]); } + +#endif diff --git a/src/modules/XBee/XBee.h b/src/modules/XBee/XBee.h index 1cb9607a..15d7cb92 100644 --- a/src/modules/XBee/XBee.h +++ b/src/modules/XBee/XBee.h @@ -1,4 +1,4 @@ -#ifndef _RADIOLIB_XBEE_H +#if !defined(_RADIOLIB_XBEE_H) && !defined(RADIOLIB_EXCLUDE_XBEE) #define _RADIOLIB_XBEE_H #include "../../ISerial.h" @@ -79,7 +79,7 @@ class XBeeSerial: public ISerial { \param panId 8-byte PAN ID to be used, in the form of uppercase hexadecimal string (i.e. 16 characters). */ - int16_t setPanId(const char* panID); + int16_t setPanId(const char* panId); #ifndef RADIOLIB_GODMODE private: @@ -170,22 +170,22 @@ class XBee { \param panId 8-byte PAN ID to be used, in the form of uppercase hexadecimal string (i.e. 16 characters). */ - int16_t setPanId(uint8_t* panID); + int16_t setPanId(uint8_t* panId); #ifndef RADIOLIB_GODMODE private: #endif Module* _mod; - uint8_t _frameID; - size_t _frameLength; - bool _frameHeaderProcessed; + uint8_t _frameID = 0x01; + size_t _frameLength = 0; + bool _frameHeaderProcessed = false; #ifdef RADIOLIB_STATIC_ONLY char _packetData[RADIOLIB_STATIC_ARRAY_SIZE]; #else char* _packetData = new char[0]; #endif - uint8_t _packetSource[8]; + uint8_t _packetSource[8] = {0, 0, 0, 0, 0, 0, 0, 0}; int16_t confirmChanges(); diff --git a/src/modules/nRF24/nRF24.cpp b/src/modules/nRF24/nRF24.cpp index 732fc20b..9a8db289 100644 --- a/src/modules/nRF24/nRF24.cpp +++ b/src/modules/nRF24/nRF24.cpp @@ -1,4 +1,5 @@ #include "nRF24.h" +#if !defined(RADIOLIB_EXCLUDE_NRF24) nRF24::nRF24(Module* mod) : PhysicalLayer(NRF24_FREQUENCY_STEP_SIZE, NRF24_MAX_PACKET_LENGTH) { _mod = mod; @@ -21,7 +22,7 @@ int16_t nRF24::begin(int16_t freq, int16_t dataRate, int8_t power, uint8_t addrW int16_t val = _mod->SPIgetRegValue(NRF24_REG_SETUP_AW); if(!((val >= 0) && (val <= 3))) { RADIOLIB_DEBUG_PRINTLN(F("No nRF24 found!")); - _mod->term(); + _mod->term(RADIOLIB_USE_SPI); return(ERR_CHIP_NOT_FOUND); } @@ -32,6 +33,7 @@ int16_t nRF24::begin(int16_t freq, int16_t dataRate, int8_t power, uint8_t addrW // set mode to standby state = standby(); RADIOLIB_ASSERT(state); + // set frequency state = setFrequency(freq); RADIOLIB_ASSERT(state); @@ -46,6 +48,15 @@ int16_t nRF24::begin(int16_t freq, int16_t dataRate, int8_t power, uint8_t addrW // set address width state = setAddressWidth(addrWidth); + RADIOLIB_ASSERT(state); + + // set CRC + state = setCrcFiltering(true); + RADIOLIB_ASSERT(state); + + // set auto-ACK on all pipes + state = setAutoAck(true); + RADIOLIB_ASSERT(state); return(state); } @@ -72,6 +83,8 @@ int16_t nRF24::transmit(uint8_t* data, size_t len, uint8_t addr) { // wait until transmission is finished uint32_t start = micros(); while(digitalRead(_mod->getIrq())) { + yield(); + // check maximum number of retransmits if(getStatus(NRF24_MAX_RT)) { standby(); @@ -101,6 +114,8 @@ int16_t nRF24::receive(uint8_t* data, size_t len) { // wait for Rx_DataReady or timeout uint32_t start = micros(); while(digitalRead(_mod->getIrq())) { + yield(); + // check timeout: 15 retries * 4ms (max Tx time as per datasheet) if(micros() - start >= 60000) { standby(); @@ -135,7 +150,7 @@ int16_t nRF24::receiveDirect() { } void nRF24::setIrqAction(void (*func)(void)) { - attachInterrupt(digitalPinToInterrupt(_mod->getIrq()), func, FALLING); + attachInterrupt(RADIOLIB_DIGITAL_PIN_TO_INTERRUPT(_mod->getIrq()), func, FALLING); } int16_t nRF24::startTransmit(uint8_t* data, size_t len, uint8_t addr) { @@ -172,7 +187,7 @@ int16_t nRF24::startTransmit(uint8_t* data, size_t len, uint8_t addr) { // CE high to start transmitting digitalWrite(_mod->getRst(), HIGH); - delayMicroseconds(10); + delay(1); digitalWrite(_mod->getRst(), LOW); return(state); @@ -199,7 +214,7 @@ int16_t nRF24::startReceive() { digitalWrite(_mod->getRst(), HIGH); // wait to enter Rx state - delayMicroseconds(130); + delay(1); return(state); } @@ -225,6 +240,7 @@ int16_t nRF24::readData(uint8_t* data, size_t len) { } int16_t nRF24::setFrequency(int16_t freq) { +<<<<<<< HEAD // check allowed range if(!((freq >= 2400) && (freq <= 2525))) { return(ERR_INVALID_FREQUENCY); @@ -233,6 +249,13 @@ int16_t nRF24::setFrequency(int16_t freq) { // set frequency uint8_t freqRaw = freq - 2400; return _mod->SPIsetRegValue(NRF24_REG_RF_CH, freqRaw, 6, 0); +======= + RADIOLIB_CHECK_RANGE(freq, 2400, 2525, ERR_INVALID_FREQUENCY); + + // set frequency + uint8_t freqRaw = freq - 2400; + return(_mod->SPIsetRegValue(NRF24_REG_RF_CH, freqRaw, 6, 0)); +>>>>>>> upstream/master } int16_t nRF24::setDataRate(int16_t dataRate) { @@ -420,7 +443,7 @@ int16_t nRF24::getStatus(uint8_t mask) { } bool nRF24::isCarrierDetected() { - return(_mod->SPIgetRegValue(NRF24_REG_RPD, 0,0)) == 1; + return(_mod->SPIgetRegValue(NRF24_REG_RPD, 0, 0) == 1); } int16_t nRF24::setFrequencyDeviation(float freqDev) { @@ -477,7 +500,7 @@ int16_t nRF24::setAutoAck(uint8_t pipeNum, bool autoAckOn){ } } -int16_t nRF24::setDataShaping(float sh) { +int16_t nRF24::setDataShaping(uint8_t sh) { // nRF24 is unable to set data shaping // this method is implemented only for PhysicalLayer compatibility (void)sh; @@ -567,3 +590,5 @@ void nRF24::SPItransfer(uint8_t cmd, bool write, uint8_t* dataOut, uint8_t* data spi->endTransaction(); digitalWrite(_mod->getCs(), HIGH); } + +#endif diff --git a/src/modules/nRF24/nRF24.h b/src/modules/nRF24/nRF24.h index bf56a317..d1e7a8b3 100644 --- a/src/modules/nRF24/nRF24.h +++ b/src/modules/nRF24/nRF24.h @@ -1,4 +1,4 @@ -#ifndef _RADIOLIB_NRF24_H +#if !defined(_RADIOLIB_NRF24_H) && !defined(RADIOLIB_EXCLUDE_NRF24) #define _RADIOLIB_NRF24_H #include "../../Module.h" @@ -189,7 +189,7 @@ class nRF24: public PhysicalLayer { \param mod Instance of Module that will be used to communicate with the radio. */ - nRF24(Module* module); + nRF24(Module* mod); // basic methods @@ -220,7 +220,7 @@ class nRF24: public PhysicalLayer { \returns \ref status_codes */ - int16_t standby(); + int16_t standby() override; /*! \brief Blocking binary transmit method. @@ -234,7 +234,7 @@ class nRF24: public PhysicalLayer { \returns \ref status_codes */ - int16_t transmit(uint8_t* data, size_t len, uint8_t addr); + int16_t transmit(uint8_t* data, size_t len, uint8_t addr) override; /*! \brief Blocking binary receive method. @@ -246,7 +246,7 @@ class nRF24: public PhysicalLayer { \returns \ref status_codes */ - int16_t receive(uint8_t* data, size_t len); + int16_t receive(uint8_t* data, size_t len) override; /*! \brief Starts direct mode transmission. @@ -255,14 +255,14 @@ class nRF24: public PhysicalLayer { \returns \ref status_codes */ - int16_t transmitDirect(uint32_t frf = 0); + int16_t transmitDirect(uint32_t frf = 0) override; /*! \brief Dummy direct mode reception method, to ensure PhysicalLayer compatibility. \returns \ref status_codes */ - int16_t receiveDirect(); + int16_t receiveDirect() override; // interrupt methods @@ -285,7 +285,7 @@ class nRF24: public PhysicalLayer { \returns \ref status_codes */ - int16_t startTransmit(uint8_t* data, size_t len, uint8_t addr); + int16_t startTransmit(uint8_t* data, size_t len, uint8_t addr) override; /*! \brief Interrupt-driven receive method. IRQ will be activated when full packet is received. @@ -303,7 +303,7 @@ class nRF24: public PhysicalLayer { \returns \ref status_codes */ - int16_t readData(uint8_t* data, size_t len); + int16_t readData(uint8_t* data, size_t len) override; // configuration methods @@ -406,7 +406,7 @@ class nRF24: public PhysicalLayer { \returns \ref status_codes */ - int16_t setFrequencyDeviation(float freqDev); + int16_t setFrequencyDeviation(float freqDev) override; /*! \brief Query modem for the packet length of received payload. @@ -415,7 +415,7 @@ class nRF24: public PhysicalLayer { \returns Length of last received packet in bytes. */ - size_t getPacketLength(bool update = true); + size_t getPacketLength(bool update = true) override; /*! \brief Enable CRC filtering and generation. @@ -427,7 +427,7 @@ class nRF24: public PhysicalLayer { int16_t setCrcFiltering(bool crcOn = true); /*! - \brief Enable or disable auto-acknowlede packets on all pipes + \brief Enable or disable auto-acknowledge packets on all pipes \param autoAckOn Enable (true) or disable (false) auto-acks. @@ -436,7 +436,7 @@ class nRF24: public PhysicalLayer { int16_t setAutoAck(bool autoAckOn = true); /*! - \brief Enable or disable auto-acknowlede packets on given pipe. + \brief Enable or disable auto-acknowledge packets on given pipe. \param pipeNum Number of pipe to which enable / disable auto-acks. @@ -453,7 +453,7 @@ class nRF24: public PhysicalLayer { \returns \ref status_codes */ - int16_t setDataShaping(float sh); + int16_t setDataShaping(uint8_t sh) override; /*! \brief Dummy encoding configuration method, to ensure PhysicalLayer compatibility. @@ -462,14 +462,14 @@ class nRF24: public PhysicalLayer { \returns \ref status_codes */ - int16_t setEncoding(uint8_t encoding); + int16_t setEncoding(uint8_t encoding) override; #ifndef RADIOLIB_GODMODE private: #endif Module* _mod; - uint8_t _addrWidth; + uint8_t _addrWidth = 0; int16_t config(); void clearIRQ(); diff --git a/src/protocols/AFSK/AFSK.cpp b/src/protocols/AFSK/AFSK.cpp new file mode 100644 index 00000000..831a278d --- /dev/null +++ b/src/protocols/AFSK/AFSK.cpp @@ -0,0 +1,27 @@ +#include "AFSK.h" +#if !defined(RADIOLIB_EXCLUDE_AFSK) + +AFSKClient::AFSKClient(PhysicalLayer* phy, RADIOLIB_PIN_TYPE pin): _pin(pin) { + _phy = phy; +} + +int16_t AFSKClient::tone(uint16_t freq, bool autoStart) { + if(freq == 0) { + return(ERR_INVALID_FREQUENCY); + } + + if(autoStart) { + int16_t state = _phy->transmitDirect(); + RADIOLIB_ASSERT(state); + } + + Module::tone(_pin, freq); + return(ERR_NONE); +} + +int16_t AFSKClient::noTone() { + Module::noTone(_pin); + return(_phy->standby()); +} + +#endif diff --git a/src/protocols/AFSK/AFSK.h b/src/protocols/AFSK/AFSK.h new file mode 100644 index 00000000..d92ffe65 --- /dev/null +++ b/src/protocols/AFSK/AFSK.h @@ -0,0 +1,62 @@ +#if !defined(_RADIOLIB_AFSK_H) +#define _RADIOLIB_AFSK_H + +#include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_AFSK) + +#include "../../Module.h" + +#include "../PhysicalLayer/PhysicalLayer.h" + +/*! + \class AFSKClient + + \brief Client for audio-based transmissions. Requires Arduino tone() function, and a module capable of direct mode transmission using DIO pins. +*/ +class AFSKClient { + public: + /*! + \brief Default contructor. + + \param phy Pointer to the wireless module providing PhysicalLayer communication. + + \param pin The pin that will be used for audio output. + */ + AFSKClient(PhysicalLayer* phy, RADIOLIB_PIN_TYPE pin); + + /*! + \brief Start transmitting audio tone. + + \param freq Frequency of the tone in Hz. + + \param autoStart Whether to automatically enter transmission mode. Defaults to true. + + \returns \ref status_codes + */ + int16_t tone(uint16_t freq, bool autoStart = true); + + /*! + \brief Stops transmitting audio tone. + + \returns \ref status_codes + */ + int16_t noTone(); + +#ifndef RADIOLIB_GODMODE + private: +#endif + PhysicalLayer* _phy; + RADIOLIB_PIN_TYPE _pin; + + // allow specific classes access the private PhysicalLayer pointer + friend class RTTYClient; + friend class MorseClient; + friend class HellClient; + friend class SSTVClient; + friend class AX25Client; +}; + +#endif + +#endif diff --git a/src/protocols/AX25/AX25.cpp b/src/protocols/AX25/AX25.cpp index 7c6a7933..7f5c0ef6 100644 --- a/src/protocols/AX25/AX25.cpp +++ b/src/protocols/AX25/AX25.cpp @@ -1,4 +1,5 @@ #include "AX25.h" +#if !defined(RADIOLIB_EXCLUDE_AX25) AX25Frame::AX25Frame(const char* destCallsign, uint8_t destSSID, const char* srcCallsign, uint8_t srcSSID, uint8_t control) : AX25Frame(destCallsign, destSSID, srcCallsign, srcSSID, control, 0, NULL, 0) { @@ -48,6 +49,10 @@ AX25Frame::AX25Frame(const char* destCallsign, uint8_t destSSID, const char* src } } +AX25Frame::AX25Frame(const AX25Frame& frame) { + *this = frame; +} + AX25Frame::~AX25Frame() { #ifndef RADIOLIB_STATIC_ONLY // deallocate info field @@ -66,6 +71,41 @@ AX25Frame::~AX25Frame() { #endif } +AX25Frame& AX25Frame::operator=(const AX25Frame& frame) { + // destination callsign/SSID + memcpy(this->destCallsign, frame.destCallsign, strlen(frame.destCallsign)); + this->destCallsign[strlen(frame.destCallsign)] = '\0'; + this->destSSID = frame.destSSID; + + // source callsign/SSID + memcpy(this->srcCallsign, frame.srcCallsign, strlen(frame.srcCallsign)); + this->srcCallsign[strlen(frame.srcCallsign)] = '\0'; + this->srcSSID = frame.srcSSID; + + // repeaters + this->numRepeaters = frame.numRepeaters; + for(uint8_t i = 0; i < this->numRepeaters; i++) { + memcpy(this->repeaterCallsigns[i], frame.repeaterCallsigns[i], strlen(frame.repeaterCallsigns[i])); + } + memcpy(this->repeaterSSIDs, frame.repeaterSSIDs, this->numRepeaters); + + // control field + this->control = frame.control; + + // sequence numbers + this->rcvSeqNumber = frame.rcvSeqNumber; + this->sendSeqNumber = frame.sendSeqNumber; + + // PID field + this->protocolID = frame.protocolID; + + // info field + this->infoLen = frame.infoLen; + memcpy(this->info, frame.info, this->infoLen); + + return(*this); +} + int16_t AX25Frame::setRepeaters(char** repeaterCallsigns, uint8_t* repeaterSSIDs, uint8_t numRepeaters) { // check number of repeaters if((numRepeaters < 1) || (numRepeaters > 8)) { @@ -73,8 +113,7 @@ int16_t AX25Frame::setRepeaters(char** repeaterCallsigns, uint8_t* repeaterSSIDs } // check repeater configuration - if(!(((repeaterCallsigns == NULL) && (repeaterSSIDs == NULL) && (numRepeaters == 0)) || - ((repeaterCallsigns != NULL) && (repeaterSSIDs != NULL) && (numRepeaters != 0)))) { + if((repeaterCallsigns == NULL) || (repeaterSSIDs == NULL)) { return(ERR_INVALID_NUM_REPEATERS); } for(uint16_t i = 0; i < numRepeaters; i++) { @@ -112,8 +151,18 @@ void AX25Frame::setSendSequence(uint8_t seqNumber) { AX25Client::AX25Client(PhysicalLayer* phy) { _phy = phy; + #if !defined(RADIOLIB_EXCLUDE_AFSK) + _audio = nullptr; + #endif } +#if !defined(RADIOLIB_EXCLUDE_AFSK) +AX25Client::AX25Client(AFSKClient* audio) { + _phy = audio->_phy; + _audio = audio; +} +#endif + int16_t AX25Client::begin(const char* srcCallsign, uint8_t srcSSID, uint8_t preambleLen) { // set source SSID _srcSSID = srcSSID; @@ -130,11 +179,16 @@ int16_t AX25Client::begin(const char* srcCallsign, uint8_t srcSSID, uint8_t prea // save preamble length _preambleLen = preambleLen; - // disable physical layer data shaping and set encoding to NRZ - int16_t state = _phy->setDataShaping(0.0); - RADIOLIB_ASSERT(state); + // set module frequency deviation to 0 if using FSK + int16_t state = ERR_NONE; + #if !defined(RADIOLIB_EXCLUDE_AFSK) + if(_audio == nullptr) { + state = _phy->setFrequencyDeviation(0); + RADIOLIB_ASSERT(state); - state = _phy->setEncoding(0); + state = _phy->setEncoding(0); + } + #endif return(state); } @@ -154,7 +208,7 @@ int16_t AX25Client::sendFrame(AX25Frame* frame) { if(strlen(frame->destCallsign) > AX25_MAX_CALLSIGN_LEN) { return(ERR_INVALID_CALLSIGN); } - + // check repeater configuration #ifndef RADIOLIB_STATIC_ONLY if(!(((frame->repeaterCallsigns == NULL) && (frame->repeaterSSIDs == NULL) && (frame->numRepeaters == 0)) || @@ -254,6 +308,9 @@ int16_t AX25Client::sendFrame(AX25Frame* frame) { uint8_t stuffedFrameBuff[RADIOLIB_STATIC_ARRAY_SIZE]; #endif + // initialize buffer to all zeros + memset(stuffedFrameBuff, 0x00, _preambleLen + 1 + (6*frameBuffLen)/5 + 2); + // stuff bits (skip preamble and both flags) uint16_t stuffedFrameBuffLenBits = 8*(_preambleLen + 1); uint8_t count = 0; @@ -333,7 +390,37 @@ int16_t AX25Client::sendFrame(AX25Frame* frame) { } // transmit - int16_t state = _phy->transmit(stuffedFrameBuff, stuffedFrameBuffLen); + int16_t state = ERR_NONE; + #if !defined(RADIOLIB_EXCLUDE_AFSK) + if(_audio != nullptr) { + _phy->transmitDirect(); + + // iterate over all bytes in the buffer + for(uint32_t i = 0; i < stuffedFrameBuffLen; i++) { + + // check each bit + for(uint16_t mask = 0x80; mask >= 0x01; mask >>= 1) { + uint32_t start = micros(); + if(stuffedFrameBuff[i] & mask) { + _audio->tone(AX25_AFSK_MARK, false); + } else { + _audio->tone(AX25_AFSK_SPACE, false); + } + while(micros() - start < 833) { + yield(); + } + } + + } + + _audio->noTone(); + + } else { + #endif + state = _phy->transmit(stuffedFrameBuff, stuffedFrameBuffLen); + #if !defined(RADIOLIB_EXCLUDE_AFSK) + } + #endif // deallocate memory #ifndef RADIOLIB_STATIC_ONLY @@ -350,8 +437,8 @@ int16_t AX25Client::sendFrame(AX25Frame* frame) { https://creativecommons.org/licenses/by-sa/4.0/ */ uint16_t AX25Client::getFrameCheckSequence(uint8_t* buff, size_t len) { - uint8_t outBit = 0; - uint16_t mask = 0x0000; + uint8_t outBit; + uint16_t mask; uint16_t shiftReg = CRC_CCITT_INIT; for(size_t i = 0; i < len; i++) { @@ -380,3 +467,5 @@ uint16_t AX25Client::flipBits16(uint16_t i) { i = (i & 0xAAAA) >> 1 | (i & 0x5555) << 1; return i; } + +#endif diff --git a/src/protocols/AX25/AX25.h b/src/protocols/AX25/AX25.h index bfe322af..8f005b3f 100644 --- a/src/protocols/AX25/AX25.h +++ b/src/protocols/AX25/AX25.h @@ -1,8 +1,12 @@ -#ifndef _RADIOLIB_AX25_H +#if !defined(_RADIOLIB_AX25_H) #define _RADIOLIB_AX25_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_AX25) + #include "../PhysicalLayer/PhysicalLayer.h" +#include "../AFSK/AFSK.h" // macros to access bits in byte array, from http://www.mathcs.emory.edu/~cheung/Courses/255/Syllabus/1-C-intro/bit-array.html #define SET_BIT_IN_ARRAY(A, k) ( A[(k/8)] |= (1 << (k%8)) ) @@ -69,6 +73,13 @@ #define AX25_PID_NO_LAYER_3 0xF0 #define AX25_PID_ESCAPE_CHARACTER 0xFF +// AFSK tones in Hz +#define AX25_AFSK_MARK 1200 +#define AX25_AFSK_SPACE 2200 + +// tone duration in us (for 1200 baud AFSK) +#define AX25_AFSK_TONE_DURATION 833 + /*! \class AX25Frame @@ -213,11 +224,25 @@ class AX25Frame { */ AX25Frame(const char* destCallsign, uint8_t destSSID, const char* srcCallsign, uint8_t srcSSID, uint8_t control, uint8_t protocolID, uint8_t* info, uint16_t infoLen); + /*! + \brief Copy constructor. + + \param frame AX25Frame instance to copy. + */ + AX25Frame(const AX25Frame& frame); + /*! \brief Default destructor. */ ~AX25Frame(); + /*! + \brief Overload for assignment operator. + + \param frame rvalue AX25Frame. + */ + AX25Frame& operator=(const AX25Frame& frame); + /*! \brief Method to set the repeater callsigns and SSIDs. @@ -254,11 +279,20 @@ class AX25Frame { class AX25Client { public: /*! - \brief Default constructor. + \brief Constructor for 2-FSK mode. \param phy Pointer to the wireless module providing PhysicalLayer communication. */ - AX25Client(PhysicalLayer* phy); + explicit AX25Client(PhysicalLayer* phy); + + #if !defined(RADIOLIB_EXCLUDE_AFSK) + /*! + \brief Constructor for AFSK mode. + + \param audio Pointer to the AFSK instance providing audio. + */ + explicit AX25Client(AFSKClient* audio); + #endif // basic methods @@ -301,14 +335,19 @@ class AX25Client { private: #endif PhysicalLayer* _phy; + #if !defined(RADIOLIB_EXCLUDE_AFSK) + AFSKClient* _audio; + #endif - char _srcCallsign[AX25_MAX_CALLSIGN_LEN + 1]; - uint8_t _srcSSID; - uint16_t _preambleLen; + char _srcCallsign[AX25_MAX_CALLSIGN_LEN + 1] = {0, 0, 0, 0, 0, 0, 0}; + uint8_t _srcSSID = 0; + uint16_t _preambleLen = 0; - uint16_t getFrameCheckSequence(uint8_t* buff, size_t len); - uint8_t flipBits(uint8_t b); - uint16_t flipBits16(uint16_t i); + static uint16_t getFrameCheckSequence(uint8_t* buff, size_t len); + static uint8_t flipBits(uint8_t b); + static uint16_t flipBits16(uint16_t i); }; #endif + +#endif diff --git a/src/protocols/HTTP/HTTP.cpp b/src/protocols/HTTP/HTTP.cpp index 9200acb0..63b2fe95 100644 --- a/src/protocols/HTTP/HTTP.cpp +++ b/src/protocols/HTTP/HTTP.cpp @@ -1,4 +1,5 @@ #include "HTTP.h" +#if !defined(RADIOLIB_EXCLUDE_HTTP) HTTPClient::HTTPClient(TransportLayer* tl, uint16_t port) { _tl = tl; @@ -140,8 +141,8 @@ int16_t HTTPClient::post(const char* url, const char* content, String& response, } // build the POST request - char contentLengthStr[8]; - itoa(strlen(content), contentLengthStr, 10); + char contentLengthStr[12]; + sprintf(contentLengthStr, "%u", (uint16_t)strlen(content)); char* request = new char[strlen(endpoint) + strlen(host) + strlen(contentType) + strlen(contentLengthStr) + strlen(content) + 64 + 1]; strcpy(request, "POST "); strcat(request, endpoint); @@ -216,3 +217,5 @@ int16_t HTTPClient::post(const char* url, const char* content, String& response, statusStr[3] = 0x00; return(atoi(statusStr)); } + +#endif diff --git a/src/protocols/HTTP/HTTP.h b/src/protocols/HTTP/HTTP.h index 118df7ec..0f30a43e 100644 --- a/src/protocols/HTTP/HTTP.h +++ b/src/protocols/HTTP/HTTP.h @@ -1,9 +1,11 @@ -#ifndef _RADIOLIB_HTTP_H +#if !defined(_RADIOLIB_HTTP_H) #define _RADIOLIB_HTTP_H #include "../../TypeDef.h" -#include "../TransportLayer/TransportLayer.h" +#if !defined(RADIOLIB_EXCLUDE_HTTP) + +#include "../TransportLayer/TransportLayer.h" /*! \class HTTPClient @@ -19,7 +21,7 @@ class HTTPClient { \param port Port to be used for HTTP. Defaults to 80. */ - HTTPClient(TransportLayer* tl, uint16_t port = 80); + explicit HTTPClient(TransportLayer* tl, uint16_t port = 80); /*! \brief Sends HTTP GET request. @@ -67,3 +69,5 @@ class HTTPClient { }; #endif + +#endif diff --git a/src/protocols/Hellschreiber/Hellschreiber.cpp b/src/protocols/Hellschreiber/Hellschreiber.cpp new file mode 100644 index 00000000..3a7bb6fc --- /dev/null +++ b/src/protocols/Hellschreiber/Hellschreiber.cpp @@ -0,0 +1,310 @@ +#include "Hellschreiber.h" +#if !defined(RADIOLIB_EXCLUDE_HELLSCHREIBER) + +HellClient::HellClient(PhysicalLayer* phy) { + _phy = phy; + + #if !defined(RADIOLIB_EXCLUDE_AFSK) + _audio = nullptr; + #endif +} + +#if !defined(RADIOLIB_EXCLUDE_AFSK) +HellClient::HellClient(AFSKClient* audio) { + _phy = audio->_phy; + _audio = audio; +} +#endif + +int16_t HellClient::begin(float base, float rate) { + // calculate 24-bit frequency + _baseHz = base; + _base = (base * 1000000.0) / _phy->getFreqStep(); + + // calculate "pixel" duration + _pixelDuration = 1000000.0/rate; + + // set module frequency deviation to 0 if using FSK + int16_t state = ERR_NONE; + #if !defined(RADIOLIB_EXCLUDE_AFSK) + if(_audio == nullptr) { + state = _phy->setFrequencyDeviation(0); + } + #endif + + return(state); +} + +size_t HellClient::printGlyph(uint8_t* buff) { + // print the character + for(uint8_t mask = 0x40; mask >= 0x01; mask >>= 1) { + for(int8_t i = HELL_FONT_HEIGHT - 1; i >= 0; i--) { + uint32_t start = micros(); + if(buff[i] & mask) { + transmitDirect(_base, _baseHz); + } else { + standby(); + } + while(micros() - start < _pixelDuration); + } + } + + // make sure transmitter is off + standby(); + + return(1); +} + +size_t HellClient::write(const char* str) { + if(str == NULL) { + return(0); + } + return(HellClient::write((uint8_t *)str, strlen(str))); +} + +size_t HellClient::write(uint8_t* buff, size_t len) { + size_t n = 0; + for(size_t i = 0; i < len; i++) { + n += HellClient::write(buff[i]); + } + return(n); +} + +size_t HellClient::write(uint8_t b) { + // convert to position in font buffer + uint8_t pos = b; + if((pos >= ' ') && (pos <= '_')) { + pos -= ' '; + } else if((pos >= 'a') && (pos <= 'z')) { + pos -= (2*' '); + } else { + return(0); + } + + // fetch character from flash + uint8_t buff[HELL_FONT_WIDTH]; + buff[0] = 0x00; + for(uint8_t i = 0; i < HELL_FONT_WIDTH - 2; i++) { + buff[i + 1] = pgm_read_byte(&HellFont[pos][i]); + } + buff[HELL_FONT_WIDTH - 1] = 0x00; + + // print the character + return(printGlyph(buff)); +} + +size_t HellClient::print(__FlashStringHelper* fstr) { + PGM_P p = reinterpret_cast(fstr); + size_t n = 0; + while(true) { + char c = pgm_read_byte(p++); + if(c == '\0') { + break; + } + n += HellClient::write(c); + } + return n; +} + +size_t HellClient::print(const String& str) { + return(HellClient::write((uint8_t*)str.c_str(), str.length())); +} + +size_t HellClient::print(const char* str) { + return(HellClient::write((uint8_t*)str, strlen(str))); +} + +size_t HellClient::print(char c) { + return(HellClient::write(c)); +} + +size_t HellClient::print(unsigned char b, int base) { + return(HellClient::print((unsigned long)b, base)); +} + +size_t HellClient::print(int n, int base) { + return(HellClient::print((long)n, base)); +} + +size_t HellClient::print(unsigned int n, int base) { + return(HellClient::print((unsigned long)n, base)); +} + +size_t HellClient::print(long n, int base) { + if(base == 0) { + return(HellClient::write(n)); + } else if(base == DEC) { + if (n < 0) { + int t = HellClient::print('-'); + n = -n; + return(HellClient::printNumber(n, DEC) + t); + } + return(HellClient::printNumber(n, DEC)); + } else { + return(HellClient::printNumber(n, base)); + } +} + +size_t HellClient::print(unsigned long n, int base) { + if(base == 0) { + return(HellClient::write(n)); + } else { + return(HellClient::printNumber(n, base)); + } +} + +size_t HellClient::print(double n, int digits) { + return(HellClient::printFloat(n, digits)); +} + +size_t HellClient::println(void) { + // Hellschreiber has no concept of "line ending", print one space instead + return(HellClient::print(' ')); +} + +size_t HellClient::println(__FlashStringHelper* fstr) { + size_t n = HellClient::print(fstr); + n += HellClient::println(); + return(n); +} + +size_t HellClient::println(const String& str) { + size_t n = HellClient::print(str); + n += HellClient::println(); + return(n); +} + +size_t HellClient::println(const char* str) { + size_t n = HellClient::print(str); + n += HellClient::println(); + return(n); +} + +size_t HellClient::println(char c) { + size_t n = HellClient::print(c); + n += HellClient::println(); + return(n); +} + +size_t HellClient::println(unsigned char b, int base) { + size_t n = HellClient::print(b, base); + n += HellClient::println(); + return(n); +} + +size_t HellClient::println(int num, int base) { + size_t n = HellClient::print(num, base); + n += HellClient::println(); + return(n); +} + +size_t HellClient::println(unsigned int num, int base) { + size_t n = HellClient::print(num, base); + n += HellClient::println(); + return(n); +} + +size_t HellClient::println(long num, int base) { + size_t n = HellClient::print(num, base); + n += HellClient::println(); + return(n); +} + +size_t HellClient::println(unsigned long num, int base) { + size_t n = HellClient::print(num, base); + n += HellClient::println(); + return(n); +} + +size_t HellClient::println(double d, int digits) { + size_t n = HellClient::print(d, digits); + n += HellClient::println(); + return(n); +} + +size_t HellClient::printNumber(unsigned long n, uint8_t base) { + char buf[8 * sizeof(long) + 1]; + char *str = &buf[sizeof(buf) - 1]; + + *str = '\0'; + + if(base < 2) { + base = 10; + } + + do { + char c = n % base; + n /= base; + + *--str = c < 10 ? c + '0' : c + 'A' - 10; + } while(n); + + return(HellClient::write(str)); +} + +size_t HellClient::printFloat(double number, uint8_t digits) { + size_t n = 0; + + char code[] = {0x00, 0x00, 0x00, 0x00}; + if (isnan(number)) strcpy(code, "nan"); + if (isinf(number)) strcpy(code, "inf"); + if (number > 4294967040.0) strcpy(code, "ovf"); // constant determined empirically + if (number <-4294967040.0) strcpy(code, "ovf"); // constant determined empirically + + if(code[0] != 0x00) { + return(HellClient::write(code)); + } + + // Handle negative numbers + if (number < 0.0) { + n += HellClient::print('-'); + number = -number; + } + + // Round correctly so that print(1.999, 2) prints as "2.00" + double rounding = 0.5; + for(uint8_t i = 0; i < digits; ++i) { + rounding /= 10.0; + } + number += rounding; + + // Extract the integer part of the number and print it + unsigned long int_part = (unsigned long)number; + double remainder = number - (double)int_part; + n += HellClient::print(int_part); + + // Print the decimal point, but only if there are digits beyond + if(digits > 0) { + n += HellClient::print('.'); + } + + // Extract digits from the remainder one at a time + while(digits-- > 0) { + remainder *= 10.0; + unsigned int toPrint = (unsigned int)(remainder); + n += HellClient::print(toPrint); + remainder -= toPrint; + } + + return n; +} + +int16_t HellClient::transmitDirect(uint32_t freq, uint32_t freqHz) { + #if !defined(RADIOLIB_EXCLUDE_AFSK) + if(_audio != nullptr) { + return(_audio->tone(freqHz)); + } + #endif + return(_phy->transmitDirect(freq)); +} + +int16_t HellClient::standby() { + #if !defined(RADIOLIB_EXCLUDE_AFSK) + if(_audio != nullptr) { + return(_audio->noTone()); + } + #endif + return(_phy->standby()); +} + +#endif diff --git a/src/protocols/Hellschreiber/Hellschreiber.h b/src/protocols/Hellschreiber/Hellschreiber.h new file mode 100644 index 00000000..bfe20473 --- /dev/null +++ b/src/protocols/Hellschreiber/Hellschreiber.h @@ -0,0 +1,172 @@ +#if !defined(_RADIOLIB_HELLSCHREIBER_H) +#define _RADIOLIB_HELLSCHREIBER_H + +#include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_HELLSCHREIBER) + +#include "../PhysicalLayer/PhysicalLayer.h" +#include "../AFSK/AFSK.h" + +#define HELL_FONT_WIDTH 7 +#define HELL_FONT_HEIGHT 7 + +// font definition: characters are stored in rows, +// least significant byte of each character is the first row +// Hellschreiber use 7x7 characters, but this simplified font uses only 5x5 - the extra bytes aren't stored +static const uint8_t HellFont[64][HELL_FONT_WIDTH - 2] PROGMEM = { + { 0b0000000, 0b0000000, 0b0000000, 0b0000000, 0b0000000 }, // space + { 0b0001000, 0b0001000, 0b0001000, 0b0000000, 0b0001000 }, // ! + { 0b0010100, 0b0010100, 0b0000000, 0b0000000, 0b0000000 }, // " + { 0b0010100, 0b0111110, 0b0010100, 0b0111110, 0b0010100 }, // # + { 0b0111110, 0b0101000, 0b0111110, 0b0001010, 0b0111110 }, // $ + { 0b0110010, 0b0110100, 0b0001000, 0b0010110, 0b0100110 }, // % + { 0b0010000, 0b0101000, 0b0010000, 0b0101000, 0b0110100 }, // & + { 0b0001000, 0b0001000, 0b0000000, 0b0000000, 0b0000000 }, // ' + { 0b0000100, 0b0001000, 0b0001000, 0b0001000, 0b0000100 }, // ( + { 0b0010000, 0b0001000, 0b0001000, 0b0001000, 0b0010000 }, // ) + { 0b0010100, 0b0001000, 0b0010100, 0b0000000, 0b0000000 }, // * + { 0b0001000, 0b0001000, 0b0111110, 0b0001000, 0b0001000 }, // + + { 0b0001000, 0b0010000, 0b0000000, 0b0000000, 0b0000000 }, // ยด + { 0b0000000, 0b0000000, 0b0111110, 0b0000000, 0b0000000 }, // - + { 0b0000000, 0b0000000, 0b0000000, 0b0000000, 0b0001000 }, // . + { 0b0000010, 0b0000100, 0b0001000, 0b0010000, 0b0100000 }, // / + { 0b0011100, 0b0100110, 0b0101010, 0b0110010, 0b0011100 }, // 0 + { 0b0011000, 0b0001000, 0b0001000, 0b0001000, 0b0001000 }, // 1 + { 0b0011000, 0b0100100, 0b0001000, 0b0010000, 0b0111100 }, // 2 + { 0b0111100, 0b0000100, 0b0011100, 0b0000100, 0b0111100 }, // 3 + { 0b0100100, 0b0100100, 0b0111100, 0b0000100, 0b0000100 }, // 4 + { 0b0011100, 0b0100000, 0b0111100, 0b0000100, 0b0111100 }, // 5 + { 0b0111100, 0b0100000, 0b0111100, 0b0100100, 0b0111100 }, // 6 + { 0b0111100, 0b0000100, 0b0001000, 0b0010000, 0b0100000 }, // 7 + { 0b0111100, 0b0100100, 0b0011000, 0b0100100, 0b0111100 }, // 8 + { 0b0111100, 0b0100100, 0b0111100, 0b0000100, 0b0111100 }, // 9 + { 0b0000000, 0b0001000, 0b0000000, 0b0000000, 0b0001000 }, // : + { 0b0000000, 0b0001000, 0b0000000, 0b0001000, 0b0001000 }, // ; + { 0b0000100, 0b0001000, 0b0010000, 0b0001000, 0b0000100 }, // < + { 0b0000000, 0b0111110, 0b0000000, 0b0111110, 0b0000000 }, // = + { 0b0010000, 0b0001000, 0b0000100, 0b0001000, 0b0010000 }, // > + { 0b0011100, 0b0000100, 0b0001000, 0b0000000, 0b0001000 }, // ? + { 0b0011100, 0b0100010, 0b0101110, 0b0101010, 0b0001100 }, // @ + { 0b0111110, 0b0100010, 0b0111110, 0b0100010, 0b0100010 }, // A + { 0b0111100, 0b0010010, 0b0011110, 0b0010010, 0b0111100 }, // B + { 0b0011110, 0b0110000, 0b0100000, 0b0110000, 0b0011110 }, // C + { 0b0111100, 0b0100010, 0b0100010, 0b0100010, 0b0111100 }, // D + { 0b0111110, 0b0100000, 0b0111100, 0b0100000, 0b0111110 }, // E + { 0b0111110, 0b0100000, 0b0111100, 0b0100000, 0b0100000 }, // F + { 0b0111110, 0b0100000, 0b0101110, 0b0100010, 0b0111110 }, // G + { 0b0100010, 0b0100010, 0b0111110, 0b0100010, 0b0100010 }, // H + { 0b0011100, 0b0001000, 0b0001000, 0b0001000, 0b0011100 }, // I + { 0b0111100, 0b0001000, 0b0001000, 0b0101000, 0b0111000 }, // J + { 0b0100100, 0b0101000, 0b0110000, 0b0101000, 0b0100100 }, // K + { 0b0100000, 0b0100000, 0b0100000, 0b0100000, 0b0111100 }, // L + { 0b0100010, 0b0110110, 0b0101010, 0b0100010, 0b0100010 }, // M + { 0b0100010, 0b0110010, 0b0101010, 0b0100110, 0b0100010 }, // N + { 0b0011100, 0b0100010, 0b0100010, 0b0100010, 0b0011100 }, // O + { 0b0111110, 0b0100010, 0b0111110, 0b0100000, 0b0100000 }, // P + { 0b0111110, 0b0100010, 0b0100010, 0b0100110, 0b0111110 }, // Q + { 0b0111110, 0b0100010, 0b0111110, 0b0100100, 0b0100010 }, // R + { 0b0111110, 0b0100000, 0b0111110, 0b0000010, 0b0111110 }, // S + { 0b0111110, 0b0001000, 0b0001000, 0b0001000, 0b0001000 }, // T + { 0b0100010, 0b0100010, 0b0100010, 0b0100010, 0b0111110 }, // U + { 0b0100010, 0b0100010, 0b0010100, 0b0010100, 0b0001000 }, // V + { 0b0100010, 0b0100010, 0b0101010, 0b0110110, 0b0100010 }, // W + { 0b0100010, 0b0010100, 0b0001000, 0b0010100, 0b0100010 }, // X + { 0b0100010, 0b0010100, 0b0001000, 0b0001000, 0b0001000 }, // Y + { 0b0111110, 0b0000100, 0b0001000, 0b0010000, 0b0111110 }, // Z + { 0b0001100, 0b0001000, 0b0001000, 0b0001000, 0b0001100 }, // [ + { 0b0100000, 0b0010000, 0b0001000, 0b0000100, 0b0000010 }, // backslash + { 0b0011000, 0b0001000, 0b0001000, 0b0001000, 0b0011000 }, // ] + { 0b0001000, 0b0010100, 0b0000000, 0b0000000, 0b0000000 }, // ^ + { 0b0000000, 0b0000000, 0b0000000, 0b0000000, 0b0111110 } // _ +}; + +/*! + \class HellClient + + \brief Client for Hellschreiber transmissions. +*/ +class HellClient { + public: + /*! + \brief Constructor for 2-FSK mode. + + \param phy Pointer to the wireless module providing PhysicalLayer communication. + */ + explicit HellClient(PhysicalLayer* phy); + + #if !defined(RADIOLIB_EXCLUDE_AFSK) + /*! + \brief Constructor for AFSK mode. + + \param audio Pointer to the AFSK instance providing audio. + */ + explicit HellClient(AFSKClient* audio); + #endif + + // basic methods + + /*! + \brief Initialization method. + + \param base Base RF frequency to be used in MHz (in 2-FSK mode), or the tone frequency in Hz (in AFSK mode). + + \param rate Baud rate to be used during transmission. Defaults to 122.5 ("Feld Hell") + */ + int16_t begin(float base, float rate = 122.5); + + /*! + \brief Method to "print" a buffer of pixels, this is exposed to allow users to send custom characters. + + \param buff Buffer of pixels to send, in a 7x7 pixel array. + */ + size_t printGlyph(uint8_t* buff); + + size_t write(const char* str); + size_t write(uint8_t* buff, size_t len); + size_t write(uint8_t b); + + size_t print(__FlashStringHelper*); + size_t print(const String &); + size_t print(const char[]); + size_t print(char); + size_t print(unsigned char, int = DEC); + size_t print(int, int = DEC); + size_t print(unsigned int, int = DEC); + size_t print(long, int = DEC); + size_t print(unsigned long, int = DEC); + size_t print(double, int = 2); + + size_t println(void); + size_t println(__FlashStringHelper*); + size_t println(const String &); + size_t println(const char[]); + size_t println(char); + size_t println(unsigned char, int = DEC); + size_t println(int, int = DEC); + size_t println(unsigned int, int = DEC); + size_t println(long, int = DEC); + size_t println(unsigned long, int = DEC); + size_t println(double, int = 2); + +#ifndef RADIOLIB_GODMODE + private: +#endif + PhysicalLayer* _phy; + #if !defined(RADIOLIB_EXCLUDE_AFSK) + AFSKClient* _audio; + #endif + + uint32_t _base = 0, _baseHz = 0; + uint32_t _pixelDuration = 0; + + size_t printNumber(unsigned long, uint8_t); + size_t printFloat(double, uint8_t); + + int16_t transmitDirect(uint32_t freq = 0, uint32_t freqHz = 0); + int16_t standby(); +}; + +#endif + +#endif diff --git a/src/protocols/MQTT/MQTT.cpp b/src/protocols/MQTT/MQTT.cpp index 92583cbb..b86b548f 100644 --- a/src/protocols/MQTT/MQTT.cpp +++ b/src/protocols/MQTT/MQTT.cpp @@ -1,4 +1,5 @@ #include "MQTT.h" +#if !defined(RADIOLIB_EXCLUDE_MQTT) MQTTClient::MQTTClient(TransportLayer* tl, uint16_t port) { _tl = tl; @@ -95,7 +96,6 @@ int16_t MQTTClient::connect(const char* host, const char* clientId, const char* packet[pos++] = (passwordLen & 0xFF00) >> 8;; packet[pos++] = passwordLen & 0x00FF; memcpy(packet + pos, password, passwordLen); - pos += passwordLen; } // create TCP connection @@ -197,7 +197,6 @@ int16_t MQTTClient::publish(const char* topic, const char* message) { // payload // message memcpy(packet + pos, message, messageLen); - pos += messageLen; // send MQTT packet int16_t state = _tl->send(packet, 1 + encodedBytes + remainingLength); @@ -206,7 +205,7 @@ int16_t MQTTClient::publish(const char* topic, const char* message) { #endif return(state); - //TODO: implement QoS > 0 and PUBACK response checking + /// \todo implement QoS > 0 and PUBACK response checking } int16_t MQTTClient::subscribe(const char* topicFilter) { @@ -313,7 +312,6 @@ int16_t MQTTClient::unsubscribe(const char* topicFilter) { packet[pos++] = (topicFilterLen & 0xFF00) >> 8;; packet[pos++] = topicFilterLen & 0x00FF; memcpy(packet + pos, topicFilter, topicFilterLen); - pos += topicFilterLen; // send MQTT packet int16_t state = _tl->send(packet, 1 + encodedBytes + remainingLength); @@ -412,11 +410,11 @@ int16_t MQTTClient::check(void (*func)(const char*, const char*)) { uint8_t* dataIn = new uint8_t[numBytes]; _tl->receive(dataIn, numBytes); if(dataIn[0] == MQTT_PUBLISH << 4) { - // TODO: properly decode remaining length - uint8_t remainingLength = dataIn[1]; + uint8_t remLenFieldLen = 0; + uint32_t remainingLength = decodeLength(dataIn + 1, remLenFieldLen); // get the topic - size_t topicLength = dataIn[3] | dataIn[2] << 8; + size_t topicLength = dataIn[remLenFieldLen + 2] | dataIn[remLenFieldLen + 1] << 8; char* topic = new char[topicLength + 1]; memcpy(topic, dataIn + 4, topicLength); topic[topicLength] = 0x00; @@ -424,7 +422,7 @@ int16_t MQTTClient::check(void (*func)(const char*, const char*)) { // get the message size_t messageLength = remainingLength - topicLength - 2; char* message = new char[messageLength + 1]; - memcpy(message, dataIn + 4 + topicLength, messageLength); + memcpy(message, dataIn + remLenFieldLen + 3 + topicLength, messageLength); message[messageLength] = 0x00; // execute the callback function provided by user @@ -454,7 +452,7 @@ size_t MQTTClient::encodeLength(uint32_t len, uint8_t* encoded) { return(i); } -uint32_t MQTTClient::decodeLength(uint8_t* encoded) { +uint32_t MQTTClient::decodeLength(uint8_t* encoded, uint8_t& numBytes) { // algorithm to decode packet length as per MQTT specification 3.1.1 uint32_t mult = 1; uint32_t len = 0; @@ -466,6 +464,9 @@ uint32_t MQTTClient::decodeLength(uint8_t* encoded) { // malformed remaining length return(0); } - } while((encoded[i] & 128) != 0); + } while((encoded[i++] & 128) != 0); + numBytes = i; return len; } + +#endif diff --git a/src/protocols/MQTT/MQTT.h b/src/protocols/MQTT/MQTT.h index b7a94bdb..6f21f585 100644 --- a/src/protocols/MQTT/MQTT.h +++ b/src/protocols/MQTT/MQTT.h @@ -1,7 +1,10 @@ -#ifndef _RADIOLIB_MQTT_H +#if !defined(_RADIOLIB_MQTT_H) #define _RADIOLIB_MQTT_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_MQTT) + #include "../TransportLayer/TransportLayer.h" // MQTT packet types @@ -39,7 +42,7 @@ class MQTTClient { \param tl Pointer to the wireless module providing TransportLayer communication. */ - MQTTClient(TransportLayer* tl, uint16_t port = 1883); + explicit MQTTClient(TransportLayer* tl, uint16_t port = 1883); // basic methods @@ -135,8 +138,10 @@ class MQTTClient { uint16_t _port; uint16_t _packetId; - size_t encodeLength(uint32_t len, uint8_t* encoded); - uint32_t decodeLength(uint8_t* encoded); + static size_t encodeLength(uint32_t len, uint8_t* encoded); + static uint32_t decodeLength(uint8_t* encoded, uint8_t& numBytes); }; #endif + +#endif diff --git a/src/protocols/Morse/Morse.cpp b/src/protocols/Morse/Morse.cpp index 6b3e0c16..80a44d46 100644 --- a/src/protocols/Morse/Morse.cpp +++ b/src/protocols/Morse/Morse.cpp @@ -1,18 +1,35 @@ #include "Morse.h" +#if !defined(RADIOLIB_EXCLUDE_MORSE) MorseClient::MorseClient(PhysicalLayer* phy) { _phy = phy; + #if !defined(RADIOLIB_EXCLUDE_AFSK) + _audio = nullptr; + #endif } +#if !defined(RADIOLIB_EXCLUDE_AFSK) +MorseClient::MorseClient(AFSKClient* audio) { + _phy = audio->_phy; + _audio = audio; +} +#endif + int16_t MorseClient::begin(float base, uint8_t speed) { // calculate 24-bit frequency + _baseHz = base; _base = (base * 1000000.0) / _phy->getFreqStep(); // calculate dot length (assumes PARIS as typical word) _dotLength = 1200 / speed; - // set module frequency deviation to 0 - int16_t state = _phy->setFrequencyDeviation(0); + // set module frequency deviation to 0 if using FSK + int16_t state = ERR_NONE; + #if !defined(RADIOLIB_EXCLUDE_AFSK) + if(_audio == nullptr) { + state = _phy->setFrequencyDeviation(0); + } + #endif return(state); } @@ -46,7 +63,7 @@ size_t MorseClient::write(uint8_t b) { // inter-word pause (space) if(b == ' ') { RADIOLIB_DEBUG_PRINTLN(F("space")); - _phy->standby(); + standby(); delay(4 * _dotLength); return(1); } @@ -65,16 +82,16 @@ size_t MorseClient::write(uint8_t b) { // send dot or dash if (code & MORSE_DASH) { RADIOLIB_DEBUG_PRINT('-'); - _phy->transmitDirect(_base); + transmitDirect(_base, _baseHz); delay(3 * _dotLength); } else { RADIOLIB_DEBUG_PRINT('.'); - _phy->transmitDirect(_base); + transmitDirect(_base, _baseHz); delay(_dotLength); } // symbol space - _phy->standby(); + standby(); delay(_dotLength); // move onto the next bit @@ -82,7 +99,7 @@ size_t MorseClient::write(uint8_t b) { } // letter space - _phy->standby(); + standby(); delay(2 * _dotLength); RADIOLIB_DEBUG_PRINTLN(); @@ -283,3 +300,23 @@ size_t MorseClient::printFloat(double number, uint8_t digits) { return n; } + +int16_t MorseClient::transmitDirect(uint32_t freq, uint32_t freqHz) { + #if !defined(RADIOLIB_EXCLUDE_AFSK) + if(_audio != nullptr) { + return(_audio->tone(freqHz)); + } + #endif + return(_phy->transmitDirect(freq)); +} + +int16_t MorseClient::standby() { + #if !defined(RADIOLIB_EXCLUDE_AFSK) + if(_audio != nullptr) { + return(_audio->noTone()); + } + #endif + return(_phy->standby()); +} + +#endif diff --git a/src/protocols/Morse/Morse.h b/src/protocols/Morse/Morse.h index 66df3280..d94fad0d 100644 --- a/src/protocols/Morse/Morse.h +++ b/src/protocols/Morse/Morse.h @@ -1,8 +1,9 @@ -#ifndef _RADIOLIB_MORSE_H +#if !defined(_RADIOLIB_MORSE_H) && !defined(RADIOLIB_EXCLUDE_MORSE) #define _RADIOLIB_MORSE_H #include "../../TypeDef.h" #include "../PhysicalLayer/PhysicalLayer.h" +#include "../AFSK/AFSK.h" #define MORSE_DOT 0b0 #define MORSE_DASH 0b1 @@ -88,18 +89,27 @@ static const uint8_t MorseTable[] PROGMEM = { class MorseClient { public: /*! - \brief Default constructor. + \brief Constructor for 2-FSK mode. \param phy Pointer to the wireless module providing PhysicalLayer communication. */ - MorseClient(PhysicalLayer* phy); + explicit MorseClient(PhysicalLayer* phy); + + #if !defined(RADIOLIB_EXCLUDE_AFSK) + /*! + \brief Constructor for AFSK mode. + + \param audio Pointer to the AFSK instance providing audio. + */ + explicit MorseClient(AFSKClient* audio); + #endif // basic methods /*! \brief Initialization method. - \param base Base RF frequency to be used in MHz. + \param base Base RF frequency to be used in MHz (in 2-FSK mode), or the tone frequency in Hz (in AFSK mode) \param speed Coding speed in words per minute. @@ -131,7 +141,7 @@ class MorseClient { size_t println(void); size_t println(__FlashStringHelper*); - size_t println(const String &s); + size_t println(const String &); size_t println(const char[]); size_t println(char); size_t println(unsigned char, int = DEC); @@ -145,11 +155,18 @@ class MorseClient { private: #endif PhysicalLayer* _phy; - uint32_t _base; - uint16_t _dotLength; + #if !defined(RADIOLIB_EXCLUDE_AFSK) + AFSKClient* _audio; + #endif + + uint32_t _base = 0, _baseHz = 0; + uint16_t _dotLength = 0; size_t printNumber(unsigned long, uint8_t); size_t printFloat(double, uint8_t); + + int16_t transmitDirect(uint32_t freq = 0, uint32_t freqHz = 0); + int16_t standby(); }; #endif diff --git a/src/protocols/PhysicalLayer/PhysicalLayer.cpp b/src/protocols/PhysicalLayer/PhysicalLayer.cpp index 0fc34b5b..9bb8e322 100644 --- a/src/protocols/PhysicalLayer/PhysicalLayer.cpp +++ b/src/protocols/PhysicalLayer/PhysicalLayer.cpp @@ -140,6 +140,6 @@ int16_t PhysicalLayer::receive(String& str, size_t len) { return(state); } -float PhysicalLayer::getFreqStep() { +float PhysicalLayer::getFreqStep() const { return(_freqStep); } diff --git a/src/protocols/PhysicalLayer/PhysicalLayer.h b/src/protocols/PhysicalLayer/PhysicalLayer.h index a434bcb3..11bfb490 100644 --- a/src/protocols/PhysicalLayer/PhysicalLayer.h +++ b/src/protocols/PhysicalLayer/PhysicalLayer.h @@ -164,11 +164,11 @@ class PhysicalLayer { \brief Enables direct transmission mode on pins DIO1 (clock) and DIO2 (data). Must be implemented in module class. While in direct mode, the module will not be able to transmit or receive packets. Can only be activated in FSK mode. - \param FRF 24-bit raw frequency value to start transmitting at. Required for quick frequency shifts in RTTY. + \param frf 24-bit raw frequency value to start transmitting at. Required for quick frequency shifts in RTTY. \returns \ref status_codes */ - virtual int16_t transmitDirect(uint32_t FRF = 0) = 0; + virtual int16_t transmitDirect(uint32_t frf = 0) = 0; /*! \brief Enables direct reception mode on pins DIO1 (clock) and DIO2 (data). Must be implemented in module class. @@ -193,16 +193,16 @@ class PhysicalLayer { /*! \brief Sets GFSK data shaping. Only available in FSK mode. Must be implemented in module class. - \param sh Shaping to be set. Set to zero to disable data shaping. + \param sh Shaping to be set. See \ref config_shaping for possible values. \returns \ref status_codes */ - virtual int16_t setDataShaping(float sh) = 0; + virtual int16_t setDataShaping(uint8_t sh) = 0; /*! \brief Sets FSK data encoding. Only available in FSK mode. Must be implemented in module class. - \param enc Encoding to be used. Set to zero to for no encoding (NRZ). + \param enc Encoding to be used. See \ref config_encoding for possible values. \returns \ref status_codes */ @@ -213,7 +213,7 @@ class PhysicalLayer { \returns Synthesizer frequency step size in Hz. */ - float getFreqStep(); + float getFreqStep() const; /*! \brief Query modem for the packet length of received payload. diff --git a/src/protocols/RTTY/RTTY.cpp b/src/protocols/RTTY/RTTY.cpp index c5eebe6c..686c3494 100644 --- a/src/protocols/RTTY/RTTY.cpp +++ b/src/protocols/RTTY/RTTY.cpp @@ -1,4 +1,5 @@ #include "RTTY.h" +#if !defined(RADIOLIB_EXCLUDE_RTTY) ITA2String::ITA2String(char c) { _len = 1; @@ -106,12 +107,24 @@ uint16_t ITA2String::getBits(char c) { RTTYClient::RTTYClient(PhysicalLayer* phy) { _phy = phy; + #if !defined(RADIOLIB_EXCLUDE_AFSK) + _audio = nullptr; + #endif } +#if !defined(RADIOLIB_EXCLUDE_AFSK) +RTTYClient::RTTYClient(AFSKClient* audio) { + _phy = audio->_phy; + _audio = audio; +} +#endif + int16_t RTTYClient::begin(float base, uint32_t shift, uint16_t rate, uint8_t encoding, uint8_t stopBits) { // save configuration _encoding = encoding; _stopBits = stopBits; + _baseHz = base; + _shiftHz = shift; switch(encoding) { case ASCII: @@ -148,15 +161,19 @@ int16_t RTTYClient::begin(float base, uint32_t shift, uint16_t rate, uint8_t enc // calculate 24-bit frequency _base = (base * 1000000.0) / _phy->getFreqStep(); - // set module frequency deviation to 0 - int16_t state = _phy->setFrequencyDeviation(0); + // set module frequency deviation to 0 if using FSK + int16_t state = ERR_NONE; + #if !defined(RADIOLIB_EXCLUDE_AFSK) + if(_audio == nullptr) { + state = _phy->setFrequencyDeviation(0); + } + #endif return(state); } void RTTYClient::idle() { - _phy->transmitDirect(); - + transmitDirect(); mark(); } @@ -190,7 +207,7 @@ size_t RTTYClient::write(uint8_t b) { mark(); } - _phy->standby(); + standby(); return(1); } @@ -222,7 +239,7 @@ size_t RTTYClient::print(__FlashStringHelper* fstr) { size_t n = 0; if(_encoding == ITA2) { - ITA2String ita2 = str; + ITA2String ita2 = ITA2String(str); n = RTTYClient::print(ita2); } else if((_encoding == ASCII) || (_encoding == ASCII_EXTENDED)) { n = RTTYClient::write((uint8_t*)str, len); @@ -243,7 +260,7 @@ size_t RTTYClient::print(ITA2String& ita2) { size_t RTTYClient::print(const String& str) { size_t n = 0; if(_encoding == ITA2) { - ITA2String ita2 = str.c_str(); + ITA2String ita2 = ITA2String(str.c_str()); n = RTTYClient::print(ita2); } else if((_encoding == ASCII) || (_encoding == ASCII_EXTENDED)) { n = RTTYClient::write((uint8_t*)str.c_str(), str.length()); @@ -254,7 +271,7 @@ size_t RTTYClient::print(const String& str) { size_t RTTYClient::print(const char str[]) { size_t n = 0; if(_encoding == ITA2) { - ITA2String ita2 = str; + ITA2String ita2 = ITA2String(str); n = RTTYClient::print(ita2); } else if((_encoding == ASCII) || (_encoding == ASCII_EXTENDED)) { n = RTTYClient::write((uint8_t*)str, strlen(str)); @@ -265,7 +282,7 @@ size_t RTTYClient::print(const char str[]) { size_t RTTYClient::print(char c) { size_t n = 0; if(_encoding == ITA2) { - ITA2String ita2 = c; + ITA2String ita2 = ITA2String(c); n = RTTYClient::print(ita2); } else if((_encoding == ASCII) || (_encoding == ASCII_EXTENDED)) { n = RTTYClient::write(c); @@ -315,7 +332,7 @@ size_t RTTYClient::print(double n, int digits) { size_t RTTYClient::println(void) { size_t n = 0; if(_encoding == ITA2) { - ITA2String lf = "\r\n"; + ITA2String lf = ITA2String("\r\n"); n = RTTYClient::print(lf); } else if((_encoding == ASCII) || (_encoding == ASCII_EXTENDED)) { n = RTTYClient::write("\r\n"); @@ -391,14 +408,18 @@ size_t RTTYClient::println(double d, int digits) { void RTTYClient::mark() { uint32_t start = micros(); - _phy->transmitDirect(_base + _shift); - while(micros() - start < _bitDuration); + transmitDirect(_base + _shift, _baseHz + _shiftHz); + while(micros() - start < _bitDuration) { + yield(); + } } void RTTYClient::space() { uint32_t start = micros(); - _phy->transmitDirect(_base); - while(micros() - start < _bitDuration); + transmitDirect(_base, _baseHz); + while(micros() - start < _bitDuration) { + yield(); + } } size_t RTTYClient::printNumber(unsigned long n, uint8_t base) { @@ -420,7 +441,7 @@ size_t RTTYClient::printNumber(unsigned long n, uint8_t base) { size_t l = 0; if(_encoding == ITA2) { - ITA2String ita2 = str; + ITA2String ita2 = ITA2String(str); uint8_t* arr = ita2.byteArr(); l = RTTYClient::write(arr, ita2.length()); delete[] arr; @@ -431,8 +452,7 @@ size_t RTTYClient::printNumber(unsigned long n, uint8_t base) { return(l); } -// TODO: improve ITA2 float print speed -// (characters are sent one at a time) +/// \todo improve ITA2 float print speed (characters are sent one at a time) size_t RTTYClient::printFloat(double number, uint8_t digits) { size_t n = 0; @@ -444,7 +464,7 @@ size_t RTTYClient::printFloat(double number, uint8_t digits) { if(code[0] != 0x00) { if(_encoding == ITA2) { - ITA2String ita2 = code; + ITA2String ita2 = ITA2String(code); uint8_t* arr = ita2.byteArr(); n = RTTYClient::write(arr, ita2.length()); delete[] arr; @@ -457,7 +477,7 @@ size_t RTTYClient::printFloat(double number, uint8_t digits) { // Handle negative numbers if (number < 0.0) { if(_encoding == ITA2) { - ITA2String ita2 = "-"; + ITA2String ita2 = ITA2String("-"); uint8_t* arr = ita2.byteArr(); n += RTTYClient::write(arr, ita2.length()); delete[] arr; @@ -482,7 +502,7 @@ size_t RTTYClient::printFloat(double number, uint8_t digits) { // Print the decimal point, but only if there are digits beyond if(digits > 0) { if(_encoding == ITA2) { - ITA2String ita2 = "."; + ITA2String ita2 = ITA2String("."); uint8_t* arr = ita2.byteArr(); n += RTTYClient::write(arr, ita2.length()); delete[] arr; @@ -501,3 +521,23 @@ size_t RTTYClient::printFloat(double number, uint8_t digits) { return n; } + +int16_t RTTYClient::transmitDirect(uint32_t freq, uint32_t freqHz) { + #if !defined(RADIOLIB_EXCLUDE_AFSK) + if(_audio != nullptr) { + return(_audio->tone(freqHz)); + } + #endif + return(_phy->transmitDirect(freq)); +} + +int16_t RTTYClient::standby() { + #if !defined(RADIOLIB_EXCLUDE_AFSK) + if(_audio != nullptr) { + return(_audio->noTone()); + } + #endif + return(_phy->standby()); +} + +#endif diff --git a/src/protocols/RTTY/RTTY.h b/src/protocols/RTTY/RTTY.h index 5c22568c..baf89fe1 100644 --- a/src/protocols/RTTY/RTTY.h +++ b/src/protocols/RTTY/RTTY.h @@ -1,8 +1,12 @@ -#ifndef _RADIOLIB_RTTY_H +#if !defined(_RADIOLIB_RTTY_H) #define _RADIOLIB_RTTY_H #include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_RTTY) + #include "../PhysicalLayer/PhysicalLayer.h" +#include "../AFSK/AFSK.h" #define ITA2_FIGS 0x1B #define ITA2_LTRS 0x1F @@ -28,14 +32,14 @@ class ITA2String { \param c ASCII-encoded character to encode as ITA2. */ - ITA2String(char c); + explicit ITA2String(char c); /*! \brief Default string constructor. \param str ASCII-encoded string to encode as ITA2. */ - ITA2String(const char* str); + explicit ITA2String(const char* str); /*! \brief Default destructor. @@ -68,7 +72,7 @@ class ITA2String { size_t _len; size_t _ita2Len; - uint16_t getBits(char c); + static uint16_t getBits(char c); }; // supported encoding schemes @@ -84,18 +88,27 @@ class ITA2String { class RTTYClient { public: /*! - \brief Default constructor. + \brief Constructor for 2-FSK mode. \param phy Pointer to the wireless module providing PhysicalLayer communication. */ - RTTYClient(PhysicalLayer* phy); + explicit RTTYClient(PhysicalLayer* phy); + + #if !defined(RADIOLIB_EXCLUDE_AFSK) + /*! + \brief Constructor for AFSK mode. + + \param audio Pointer to the AFSK instance providing audio. + */ + explicit RTTYClient(AFSKClient* audio); + #endif // basic methods /*! \brief Initialization method. - \param base Base (space) RF frequency to be used in MHz. + \param base Base (space) frequency to be used in MHz (in 2-FSK mode), or the space tone frequency in Hz (in AFSK mode) \param shift Frequency shift between mark and space in Hz. @@ -133,7 +146,7 @@ class RTTYClient { size_t println(void); size_t println(__FlashStringHelper*); size_t println(ITA2String &); - size_t println(const String &s); + size_t println(const String &); size_t println(const char[]); size_t println(char); size_t println(unsigned char, int = DEC); @@ -147,19 +160,27 @@ class RTTYClient { private: #endif PhysicalLayer* _phy; + #if !defined(RADIOLIB_EXCLUDE_AFSK) + AFSKClient* _audio; + #endif - uint8_t _encoding; - uint32_t _base; - uint32_t _shift; - uint32_t _bitDuration; - uint8_t _dataBits; - uint8_t _stopBits; + uint8_t _encoding = ASCII; + uint32_t _base = 0, _baseHz = 0; + uint32_t _shift = 0, _shiftHz = 0; + uint32_t _bitDuration = 0; + uint8_t _dataBits = 0; + uint8_t _stopBits = 0; void mark(); void space(); size_t printNumber(unsigned long, uint8_t); size_t printFloat(double, uint8_t); + + int16_t transmitDirect(uint32_t freq = 0, uint32_t freqHz = 0); + int16_t standby(); }; #endif + +#endif diff --git a/src/protocols/SSTV/SSTV.cpp b/src/protocols/SSTV/SSTV.cpp new file mode 100644 index 00000000..9fc9fd3e --- /dev/null +++ b/src/protocols/SSTV/SSTV.cpp @@ -0,0 +1,307 @@ +#include "SSTV.h" +#if !defined(RADIOLIB_EXCLUDE_SSTV) + +const SSTVMode_t Scottie1 { + .visCode = SSTV_SCOTTIE_1, + .width = 320, + .height = 256, + .scanPixelLen = 432, + .numTones = 7, + .tones = { + { .type = tone_t::GENERIC, .len = 1500, .freq = 1500 }, + { .type = tone_t::SCAN_GREEN, .len = 0, .freq = 0 }, + { .type = tone_t::GENERIC, .len = 1500, .freq = 1500 }, + { .type = tone_t::SCAN_BLUE, .len = 0, .freq = 0 }, + { .type = tone_t::GENERIC, .len = 9000, .freq = 1200 }, + { .type = tone_t::GENERIC, .len = 1500, .freq = 1500 }, + { .type = tone_t::SCAN_RED, .len = 0, .freq = 0 } + } +}; + +const SSTVMode_t Scottie2 { + .visCode = SSTV_SCOTTIE_2, + .width = 320, + .height = 256, + .scanPixelLen = 275, + .numTones = 7, + .tones = { + { .type = tone_t::GENERIC, .len = 1500, .freq = 1500 }, + { .type = tone_t::SCAN_GREEN, .len = 0, .freq = 0 }, + { .type = tone_t::GENERIC, .len = 1500, .freq = 1500 }, + { .type = tone_t::SCAN_BLUE, .len = 0, .freq = 0 }, + { .type = tone_t::GENERIC, .len = 9000, .freq = 1200 }, + { .type = tone_t::GENERIC, .len = 1500, .freq = 1500 }, + { .type = tone_t::SCAN_RED, .len = 0, .freq = 0 } + } +}; + +const SSTVMode_t ScottieDX { + .visCode = SSTV_SCOTTIE_DX, + .width = 320, + .height = 256, + .scanPixelLen = 1080, + .numTones = 7, + .tones = { + { .type = tone_t::GENERIC, .len = 1500, .freq = 1500 }, + { .type = tone_t::SCAN_GREEN, .len = 0, .freq = 0 }, + { .type = tone_t::GENERIC, .len = 1500, .freq = 1500 }, + { .type = tone_t::SCAN_BLUE, .len = 0, .freq = 0 }, + { .type = tone_t::GENERIC, .len = 9000, .freq = 1200 }, + { .type = tone_t::GENERIC, .len = 1500, .freq = 1500 }, + { .type = tone_t::SCAN_RED, .len = 0, .freq = 0 } + } +}; + +const SSTVMode_t Martin1 { + .visCode = SSTV_MARTIN_1, + .width = 320, + .height = 256, + .scanPixelLen = 458, + .numTones = 8, + .tones = { + { .type = tone_t::GENERIC, .len = 4862, .freq = 1200 }, + { .type = tone_t::GENERIC, .len = 572, .freq = 1500 }, + { .type = tone_t::SCAN_GREEN, .len = 0, .freq = 0 }, + { .type = tone_t::GENERIC, .len = 572, .freq = 1500 }, + { .type = tone_t::SCAN_BLUE, .len = 0, .freq = 0 }, + { .type = tone_t::GENERIC, .len = 572, .freq = 1500 }, + { .type = tone_t::SCAN_RED, .len = 0, .freq = 0 }, + { .type = tone_t::GENERIC, .len = 572, .freq = 1500 } + } +}; + +const SSTVMode_t Martin2 { + .visCode = SSTV_MARTIN_2, + .width = 320, + .height = 256, + .scanPixelLen = 229, + .numTones = 8, + .tones = { + { .type = tone_t::GENERIC, .len = 4862, .freq = 1200 }, + { .type = tone_t::GENERIC, .len = 572, .freq = 1500 }, + { .type = tone_t::SCAN_GREEN, .len = 0, .freq = 0 }, + { .type = tone_t::GENERIC, .len = 572, .freq = 1500 }, + { .type = tone_t::SCAN_BLUE, .len = 0, .freq = 0 }, + { .type = tone_t::GENERIC, .len = 572, .freq = 1500 }, + { .type = tone_t::SCAN_RED, .len = 0, .freq = 0 }, + { .type = tone_t::GENERIC, .len = 572, .freq = 1500 } + } +}; + +const SSTVMode_t Wrasse { + .visCode = SSTV_WRASSE_SC2_180, + .width = 320, + .height = 256, + .scanPixelLen = 734, + .numTones = 5, + .tones = { + { .type = tone_t::GENERIC, .len = 5523, .freq = 1200 }, + { .type = tone_t::GENERIC, .len = 500, .freq = 1500 }, + { .type = tone_t::SCAN_RED, .len = 0, .freq = 0 }, + { .type = tone_t::SCAN_GREEN, .len = 0, .freq = 0 }, + { .type = tone_t::SCAN_BLUE, .len = 0, .freq = 0 } + } +}; + +const SSTVMode_t PasokonP3 { + .visCode = SSTV_PASOKON_P3, + .width = 640, + .height = 496, + .scanPixelLen = 208, + .numTones = 7, + .tones = { + { .type = tone_t::GENERIC, .len = 5208, .freq = 1200 }, + { .type = tone_t::GENERIC, .len = 1042, .freq = 1500 }, + { .type = tone_t::SCAN_RED, .len = 0, .freq = 0 }, + { .type = tone_t::GENERIC, .len = 1042, .freq = 1500 }, + { .type = tone_t::SCAN_GREEN, .len = 0, .freq = 0 }, + { .type = tone_t::GENERIC, .len = 1042, .freq = 1500 }, + { .type = tone_t::SCAN_BLUE, .len = 0, .freq = 0 } + } +}; + +const SSTVMode_t PasokonP5 { + .visCode = SSTV_PASOKON_P5, + .width = 640, + .height = 496, + .scanPixelLen = 312, + .numTones = 7, + .tones = { + { .type = tone_t::GENERIC, .len = 7813, .freq = 1200 }, + { .type = tone_t::GENERIC, .len = 1563, .freq = 1500 }, + { .type = tone_t::SCAN_RED, .len = 0, .freq = 0 }, + { .type = tone_t::GENERIC, .len = 1563, .freq = 1500 }, + { .type = tone_t::SCAN_GREEN, .len = 0, .freq = 0 }, + { .type = tone_t::GENERIC, .len = 1563, .freq = 1500 }, + { .type = tone_t::SCAN_BLUE, .len = 0, .freq = 0 } + } +}; + +const SSTVMode_t PasokonP7 { + .visCode = SSTV_PASOKON_P7, + .width = 640, + .height = 496, + .scanPixelLen = 417, + .numTones = 7, + .tones = { + { .type = tone_t::GENERIC, .len = 10417, .freq = 1200 }, + { .type = tone_t::GENERIC, .len = 2083, .freq = 1500 }, + { .type = tone_t::SCAN_RED, .len = 0, .freq = 0 }, + { .type = tone_t::GENERIC, .len = 2083, .freq = 1500 }, + { .type = tone_t::SCAN_GREEN, .len = 0, .freq = 0 }, + { .type = tone_t::GENERIC, .len = 2083, .freq = 1500 }, + { .type = tone_t::SCAN_BLUE, .len = 0, .freq = 0 } + } +}; + +SSTVClient::SSTVClient(PhysicalLayer* phy) { + _phy = phy; + #if !defined(RADIOLIB_EXCLUDE_AFSK) + _audio = nullptr; + #endif +} + +#if !defined(RADIOLIB_EXCLUDE_AFSK) +SSTVClient::SSTVClient(AFSKClient* audio) { + _phy = audio->_phy; + _audio = audio; +} +#endif + +#if !defined(RADIOLIB_EXCLUDE_AFSK) +int16_t SSTVClient::begin(const SSTVMode_t& mode, float correction) { + if(_audio == nullptr) { + // this initialization method can only be used in AFSK mode + return(ERR_WRONG_MODEM); + } + + return(begin(0, mode, correction)); +} +#endif + +int16_t SSTVClient::begin(float base, const SSTVMode_t& mode, float correction) { + // save mode + _mode = mode; + + // apply correction factor to all timings + _mode.scanPixelLen *= correction; + for(uint8_t i = 0; i < _mode.numTones; i++) { + _mode.tones[i].len *= correction; + } + + // calculate 24-bit frequency + _base = (base * 1000000.0) / _phy->getFreqStep(); + + // set module frequency deviation to 0 if using FSK + int16_t state = ERR_NONE; + #if !defined(RADIOLIB_EXCLUDE_AFSK) + if(_audio == nullptr) { + state = _phy->setFrequencyDeviation(0); + } + #endif + + return(state); +} + +void SSTVClient::idle() { + _phy->transmitDirect(); + tone(SSTV_TONE_LEADER); +} + +void SSTVClient::sendHeader() { + // save first header flag for Scottie modes + _firstLine = true; + _phy->transmitDirect(); + + // send the first part of header (leader-break-leader) + tone(SSTV_TONE_LEADER, SSTV_HEADER_LEADER_LENGTH); + tone(SSTV_TONE_BREAK, SSTV_HEADER_BREAK_LENGTH); + tone(SSTV_TONE_LEADER, SSTV_HEADER_LEADER_LENGTH); + + // VIS start bit + tone(SSTV_TONE_BREAK, SSTV_HEADER_BIT_LENGTH); + + // VIS code + uint8_t parityCount = 0; + for(uint8_t mask = 0x01; mask < 0x80; mask <<= 1) { + if(_mode.visCode & mask) { + tone(SSTV_TONE_VIS_1, SSTV_HEADER_BIT_LENGTH); + parityCount++; + } else { + tone(SSTV_TONE_VIS_0, SSTV_HEADER_BIT_LENGTH); + } + } + + // VIS parity + if(parityCount % 2 == 0) { + // even parity + tone(SSTV_TONE_VIS_0, SSTV_HEADER_BIT_LENGTH); + } else { + // odd parity + tone(SSTV_TONE_VIS_1, SSTV_HEADER_BIT_LENGTH); + } + + // VIS stop bit + tone(SSTV_TONE_BREAK, SSTV_HEADER_BIT_LENGTH); +} + +void SSTVClient::sendLine(uint32_t* imgLine) { + // check first line flag in Scottie modes + if(_firstLine && ((_mode.visCode == SSTV_SCOTTIE_1) || (_mode.visCode == SSTV_SCOTTIE_2) || (_mode.visCode == SSTV_SCOTTIE_DX))) { + _firstLine = false; + + // send start sync tone + tone(SSTV_TONE_BREAK, 9000); + } + + // send all tones in sequence + for(uint8_t i = 0; i < _mode.numTones; i++) { + if((_mode.tones[i].type == tone_t::GENERIC) && (_mode.tones[i].len > 0)) { + // sync/porch tones + tone(_mode.tones[i].freq, _mode.tones[i].len); + } else { + // scan lines + for(uint16_t j = 0; j < _mode.width; j++) { + uint32_t color = imgLine[j]; + switch(_mode.tones[i].type) { + case(tone_t::SCAN_RED): + color &= 0x00FF0000; + color >>= 16; + break; + case(tone_t::SCAN_GREEN): + color &= 0x0000FF00; + color >>= 8; + break; + case(tone_t::SCAN_BLUE): + color &= 0x000000FF; + break; + case(tone_t::GENERIC): + break; + } + tone(SSTV_TONE_BRIGHTNESS_MIN + ((float)color * 3.1372549), _mode.scanPixelLen); + } + } + } +} + +uint16_t SSTVClient::getPictureHeight() const { + return(_mode.height); +} + +void SSTVClient::tone(float freq, uint32_t len) { + uint32_t start = micros(); + #if !defined(RADIOLIB_EXCLUDE_AFSK) + if(_audio != nullptr) { + _audio->tone(freq, false); + } else { + _phy->transmitDirect(_base + (freq / _phy->getFreqStep())); + } + #else + _phy->transmitDirect(_base + (freq / _phy->getFreqStep())); + #endif + while(micros() - start < len) { + yield(); + } +} + +#endif diff --git a/src/protocols/SSTV/SSTV.h b/src/protocols/SSTV/SSTV.h new file mode 100644 index 00000000..fb8fc27a --- /dev/null +++ b/src/protocols/SSTV/SSTV.h @@ -0,0 +1,207 @@ +#if !defined(_RADIOLIB_SSTV_H) +#define _RADIOLIB_SSTV_H + +#include "../../TypeDef.h" + +#if !defined(RADIOLIB_EXCLUDE_SSTV) + +#include "../PhysicalLayer/PhysicalLayer.h" +#include "../AFSK/AFSK.h" + +// the following implementation is based on information from +// http://www.barberdsp.com/downloads/Dayton%20Paper.pdf + +// VIS codes +#define SSTV_SCOTTIE_1 60 +#define SSTV_SCOTTIE_2 56 +#define SSTV_SCOTTIE_DX 76 +#define SSTV_MARTIN_1 44 +#define SSTV_MARTIN_2 40 +#define SSTV_WRASSE_SC2_180 55 +#define SSTV_PASOKON_P3 113 +#define SSTV_PASOKON_P5 114 +#define SSTV_PASOKON_P7 115 + +// SSTV tones in Hz +#define SSTV_TONE_LEADER 1900 +#define SSTV_TONE_BREAK 1200 +#define SSTV_TONE_VIS_1 1100 +#define SSTV_TONE_VIS_0 1300 +#define SSTV_TONE_BRIGHTNESS_MIN 1500 +#define SSTV_TONE_BRIGHTNESS_MAX 2300 + +// calibration header timing in us +#define SSTV_HEADER_LEADER_LENGTH 300000 +#define SSTV_HEADER_BREAK_LENGTH 10000 +#define SSTV_HEADER_BIT_LENGTH 30000 + +/*! + \struct tone_t + + \brief Structure to save data about tone. +*/ +struct tone_t { + + /*! + \brief Tone type: GENERIC for sync and porch tones, SCAN_GREEN, SCAN_BLUE and SCAN_RED for scan lines. + */ + enum { + GENERIC = 0, + SCAN_GREEN, + SCAN_BLUE, + SCAN_RED + } type; + + /*! + \brief Length of tone in us, set to 0 for picture scan tones. + */ + uint32_t len; + + /*! + \brief Frequency of tone in Hz, set to 0 for picture scan tones. + */ + uint16_t freq; +}; + +/*! + \struct SSTVMode_t + + \brief Structure to save data about supported SSTV modes. +*/ +struct SSTVMode_t { + + /*! + \brief Unique VIS code of the SSTV mode. + */ + uint8_t visCode; + + /*! + \brief Picture width in pixels. + */ + uint16_t width; + + /*! + \brief Picture height in pixels. + */ + uint16_t height; + + /*! + \brief Pixel scan length in us. + */ + uint16_t scanPixelLen; + + /*! + \brief Number of tones in each transmission line. Picture scan data is considered single tone. + */ + uint8_t numTones; + + /*! + \brief Sequence of tones in each transmission line. This is used to create the correct encoding sequence. + */ + tone_t tones[8]; +}; + +// all currently supported SSTV modes +extern const SSTVMode_t Scottie1; +extern const SSTVMode_t Scottie2; +extern const SSTVMode_t ScottieDX; +extern const SSTVMode_t Martin1; +extern const SSTVMode_t Martin2; +extern const SSTVMode_t Wrasse; +extern const SSTVMode_t PasokonP3; +extern const SSTVMode_t PasokonP5; +extern const SSTVMode_t PasokonP7; + +/*! + \class SSTVClient + + \brief Client for SSTV transmissions. +*/ +class SSTVClient { + public: + /*! + \brief Constructor for 2-FSK mode. + + \param phy Pointer to the wireless module providing PhysicalLayer communication. + */ + explicit SSTVClient(PhysicalLayer* phy); + + #if !defined(RADIOLIB_EXCLUDE_AFSK) + /*! + \brief Constructor for AFSK mode. + + \param audio Pointer to the AFSK instance providing audio. + */ + explicit SSTVClient(AFSKClient* audio); + #endif + + // basic methods + + /*! + \brief Initialization method for 2-FSK. + + \param base Base "0 Hz tone" RF frequency to be used in MHz. + + \param mode SSTV mode to be used. Currently supported modes are Scottie1, Scottie2, ScottieDX, Martin1, Martin2, Wrasse, PasokonP3, PasokonP5 and PasokonP7. + + \param correction Timing correction factor, used to adjust the length of timing pulses. Less than 1.0 leads to shorter timing pulses, defaults to 1.0 (no correction). + + \returns \ref status_codes + */ + int16_t begin(float base, const SSTVMode_t& mode, float correction = 1.0); + + #if !defined(RADIOLIB_EXCLUDE_AFSK) + /*! + \brief Initialization method for AFSK. + + \param mode SSTV mode to be used. Currently supported modes are Scottie1, Scottie2, ScottieDX, Martin1, Martin2, Wrasse, PasokonP3, PasokonP5 and PasokonP7. + + \param correction Timing correction factor, used to adjust the length of timing pulses. Less than 1.0 leads to shorter timing pulses, defaults to 1.0 (no correction). + + \returns \ref status_codes + */ + int16_t begin(const SSTVMode_t& mode, float correction = 1.0); + #endif + + /*! + \brief Sends out tone at 1900 Hz. + */ + void idle(); + + /*! + \brief Sends synchronization header for the SSTV mode set in begin method. + */ + void sendHeader(); + + /*! + \brief Sends single picture line in the currently configured SSTV mode. + + \param imgLine Image line to send, in 24-bit RGB. It is up to the user to ensure that imgLine has enough pixels to send it in the current SSTV mode. + */ + void sendLine(uint32_t* imgLine); + + /*! + \brief Get picture height of the currently configured SSTV mode. + + \returns Picture height of the currently configured SSTV mode in pixels. + */ + uint16_t getPictureHeight() const; + +#ifndef RADIOLIB_GODMODE + private: +#endif + PhysicalLayer* _phy; + #if !defined(RADIOLIB_EXCLUDE_AFSK) + AFSKClient* _audio; + #endif + + uint32_t _base = 0; + SSTVMode_t _mode = Scottie1; + bool _firstLine = true; + + void tone(float freq, uint32_t len = 0); +}; + +#endif + +#endif diff --git a/src/protocols/TransportLayer/TransportLayer.h b/src/protocols/TransportLayer/TransportLayer.h index ecf3ad5b..eb23bd8e 100644 --- a/src/protocols/TransportLayer/TransportLayer.h +++ b/src/protocols/TransportLayer/TransportLayer.h @@ -56,7 +56,7 @@ class TransportLayer { \returns \ref status_codes */ - virtual int16_t send(uint8_t* data, uint32_t len) = 0; + virtual int16_t send(uint8_t* data, size_t len) = 0; /*! \brief Receive data.