diff --git a/.travis.yml.bck b/.travis.yml.bck deleted file mode 100644 index 91a585eb..00000000 --- a/.travis.yml.bck +++ /dev/null @@ -1,68 +0,0 @@ -sudo: required -language: c -dist: xenial -git: - depth: false - quiet: true - -env: - global: - - BSP_PATH="$HOME/.arduino15/packages/adafruit/hardware/nrf52" - jobs: - # empty env required, else allow_failures will SILENTY IGNORE matching against env... - - - -jobs: - fast_finish: true - include: - - name: "Feather nRF52840" - env: VARIANT="feather52840" - - name: "Feather nRF52840 (All warnings)" - env: ALL_WARNINGS="true" VARIANT="feather52840" - - name: "Circuit Playground nRF52840" - env: VARIANT="cplaynrf52840" - - name: "Circuit Playground nRF52840 (All warnings)" - env: ALL_WARNINGS="true" VARIANT="cplaynrf52840" - - name: "Feather nRF52832" - env: VARIANT="feather52832" - - name: "Feather nRF52832 (All warnings)" - env: ALL_WARNINGS="true" VARIANT="feather52832" - - name: "ItsyBitsy nRF52840 Express" - env: VARIANT="itsybitsy52840" - - name: "Clue nRF52840" - env: VARIANT="cluenrf52840" - allow_failures: - - env: ALL_WARNINGS="true" VARIANT="feather52840" - - env: ALL_WARNINGS="true" VARIANT="cplaynrf52840" - - env: ALL_WARNINGS="true" VARIANT="feather52832" - -addons: - apt: - packages: - - python3 - - python3-pip - - python3-setuptools - snaps: - - name: ubuntu-make - confinement: classic - -install: - # Filter only mDNS / Bonjour traffic - - sudo iptables --insert INPUT --jump DROP --protocol udp --dport 5353 -m comment --comment "silently drop all 5353/udp input" - - sudo iptables --insert INPUT --jump DROP --destination 224.0.0.251 -m comment --comment "silently drop all mDNS ipv4 broadcast" - # Install the nRF52 support files for arduino - - pip3 install --user adafruit-nrfutil - - umake electronics arduino $HOME/arduino_ide - - export PATH=$HOME/arduino_ide:$PATH - - arduino --pref "boardsmanager.additional.urls=https://adafruit.github.io/arduino-board-index/package_adafruit_index.json" --save-prefs - # Install BSP for tools, then remove and create symlink the git code - - arduino --install-boards adafruit:nrf52 - - BSP_VERSION=`eval ls $BSP_PATH` - - rm -r $BSP_PATH/* - - ln -s $TRAVIS_BUILD_DIR $BSP_PATH/$BSP_VERSION - - arduino --install-library "Adafruit NeoPixel","Adafruit NeoMatrix","Adafruit GFX Library","Adafruit SSD1306","MIDI Library","Adafruit ILI9341","Adafruit HX8357 Library","Adafruit Circuit Playground" - -before_script: - -script: - - python3 tools/build_all_travis.py diff --git a/changelog.md b/changelog.md index 1ef05204..0256db71 100644 --- a/changelog.md +++ b/changelog.md @@ -1,6 +1,6 @@ # Adafruit nRF52 Arduino Core Changelog -## 0.21.0 +## WIP This version implement comprehensive LESC and Legacy pairing using dynamic & staic Passkey. @@ -50,6 +50,25 @@ A new class BLESecurity (access with Bluefruit.Security) is added to handle secu - **cental_pairing** similar to pairing_passkey but for nRF running central role - **ancs_arcada** for displaying ancs on arcada such CLUE and/or CPB. +## 0.21.0 - 2020.08.31 + +Special thanks to @henrygab, @pyro9, @Nenik, @orrmany, @thaanstad, @kevinfrei for contributing and helping with this release. + +- Reworked HardwarePWM, analogWrite, Servo, Tone to address PWM hardware conflict with ownership. +- Reworked Tone to use no interrupt handler +- Added multiprotocol support such as ANT with additional ANT_LICENSE_KEY (require 3rd party library) +- Fixed pgm_read_ptr(addr) macro +- Updated & enhanced TinyUSB performance, usb event, task switching is much faster +- Fixed BLE Characteristic discovery when the central device returns more than 4 Characteristics in a discovery request +- Enhanced micro() to use DWT cyclecount if enabled for higher precision +- Fixed miscalculated tick when sleeping with delay() +- Fixed FPU-caused power consumption issue +- Added Wire.setPins() +- Added resumeLoop() +- Renamed I2C terminology +- Support precompiled library with compiler.libraries.ldflags e.g BSEC BME680 +- Added Hardware/tone_happy_birthday example sketch + ## 0.20.5 - 2020.07.05 - Updated toolchain from gcc 7-2017q4 to 9-2019q4 diff --git a/cores/nRF5/Arduino.h b/cores/nRF5/Arduino.h index e4ab380e..ee5b2ae9 100644 --- a/cores/nRF5/Arduino.h +++ b/cores/nRF5/Arduino.h @@ -36,6 +36,7 @@ void setup( void ) ; void loop( void ) ; void suspendLoop(void); +void resumeLoop(void); #include "WVariant.h" diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index 881c054d..441c3fcb 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -1,38 +1,28 @@ -/**************************************************************************/ -/*! - @file HardwarePWM.cpp - @author hathach (tinyusb.org) +/* + * The MIT License (MIT) + * + * Copyright (c) 2020 Ha Thach for Adafruit Industries + * Copyright (c) 2020 Henry Gabryjelski + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2018, Adafruit Industries (adafruit.com) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/**************************************************************************/ #include "Arduino.h" #include "HardwarePWM.h" @@ -53,9 +43,51 @@ HardwarePWM* HwPWMx[] = #endif }; -HardwarePWM::HardwarePWM(NRF_PWM_Type* pwm) +#if CFG_DEBUG +bool can_stringify_token(uint32_t token) { - _pwm = pwm; + uint8_t * t = (uint8_t *)&token; + for (size_t i = 0; i < sizeof(uint32_t); ++i, ++t) + { + uint8_t x = *t; + if ((x < 0x20) || (x > 0x7E)) return false; + } + return true; +} + +void HardwarePWM::DebugOutput(Stream& logger) +{ + const size_t count = arrcount(HwPWMx); + logger.printf("HwPWM Debug:"); + for (size_t i = 0; i < count; i++) { + HardwarePWM const * pwm = HwPWMx[i]; + uint32_t token = pwm->_owner_token; + logger.printf(" || %d:", i); + if (can_stringify_token(token)) { + uint8_t * t = (uint8_t*)(&token); + logger.printf(" \"%c%c%c%c\"", t[0], t[1], t[2], t[3] ); + } else { + logger.printf(" %08x", token); + } + for (size_t j = 0; j < MAX_CHANNELS; j++) { + uint32_t r = pwm->_pwm->PSEL.OUT[j]; // only read it once + if ( (r & PWM_PSEL_OUT_CONNECT_Msk) != (PWM_PSEL_OUT_CONNECT_Disconnected << PWM_PSEL_OUT_CONNECT_Pos) ) { + logger.printf(" %02x", r & 0x1F); + } else { + logger.printf(" xx"); + } + } + } + logger.printf("\n"); +} +#else +void HardwarePWM::DebugOutput(Stream& logger) {} +#endif // CFG_DEBUG + +HardwarePWM::HardwarePWM(NRF_PWM_Type* pwm) : + _pwm(pwm) +{ + _owner_token = 0U; arrclr(_seq0); _max_value = 255; @@ -65,6 +97,38 @@ HardwarePWM::HardwarePWM(NRF_PWM_Type* pwm) _pwm->PSEL.OUT[1] = 0xFFFFFFFFUL; } +void HardwarePWM::begin(void) +{ + // Initialize Registers + _pwm->MODE = PWM_MODE_UPDOWN_Up; + _pwm->COUNTERTOP = _max_value; // default is 255 (8 bit), can be configured before begin() + _pwm->PRESCALER = _clock_div; + _pwm->DECODER = PWM_DECODER_LOAD_Individual; + _pwm->LOOP = 0; + + _pwm->SEQ[0].PTR = (uint32_t) _seq0; + _pwm->SEQ[0].CNT = MAX_CHANNELS; // default mode is Individual --> count must be 4 + _pwm->SEQ[0].REFRESH = 0; + _pwm->SEQ[0].ENDDELAY = 0; + + _pwm->SEQ[1].PTR = 0; + _pwm->SEQ[1].CNT = 0; + _pwm->SEQ[1].REFRESH = 0; + _pwm->SEQ[1].ENDDELAY = 0; + + _pwm->ENABLE = 1; +} + +void HardwarePWM::stop(void) +{ + _pwm->ENABLE = 0; +} + +bool HardwarePWM::enabled (void) +{ + return _pwm->ENABLE; +} + void HardwarePWM::setResolution(uint8_t bitnum) { setMaxValue( bit(min8(bitnum, 15)) -1 ); @@ -82,6 +146,25 @@ void HardwarePWM::setClockDiv(uint8_t div) _pwm->PRESCALER = _clock_div; } +void HardwarePWM::_set_psel(int ch, uint32_t value) +{ + // Must disable before changing PSEL + if ( enabled() ) + { + _pwm->ENABLE = 0; + _pwm->PSEL.OUT[ch] = value; + _seq0[ch] = 0; + _pwm->ENABLE = 1; + + // re-start sequence + if ( usedChannelCount() ) _pwm->TASKS_SEQSTART[0] = 1; + }else + { + _pwm->PSEL.OUT[ch] = value; + _seq0[ch] = 0; + } +} + /** * Add pin to this group. * @param pin Pin to add @@ -108,17 +191,7 @@ bool HardwarePWM::addPin(uint8_t pin) pinMode(pin, OUTPUT); digitalWrite(pin, LOW); - // Must disable before changing PSEL - if ( enabled() ) - { - _pwm->ENABLE = 0; - _pwm->PSEL.OUT[ch] = g_ADigitalPinMap[pin]; - _pwm->ENABLE = 1; - _start(); - }else - { - _pwm->PSEL.OUT[ch] = g_ADigitalPinMap[pin]; - } + _set_psel(ch, g_ADigitalPinMap[pin]); return true; } @@ -128,70 +201,21 @@ bool HardwarePWM::removePin(uint8_t pin) int ch = pin2channel(pin); VERIFY( ch >= 0 ); - bool const en = enabled(); - - // Must disable before changing PSEL - if ( en ) _pwm->ENABLE = 0; - - _pwm->PSEL.OUT[ch] = 0xFFFFFFFFUL; - _seq0[ch] = 0; - - if ( en ) _pwm->ENABLE = 1; - + _set_psel(ch, 0xFFFFFFFFUL); return true; } -bool HardwarePWM::enabled (void) -{ - return _pwm->ENABLE; -} - -void HardwarePWM::begin(void) -{ - // Initialize Registers - _pwm->MODE = PWM_MODE_UPDOWN_Up; - _pwm->COUNTERTOP = _max_value; // default is 255 (8 bit), can be configured before begin() - _pwm->PRESCALER = _clock_div; - _pwm->DECODER = PWM_DECODER_LOAD_Individual; - _pwm->LOOP = 0; - - _pwm->SEQ[0].PTR = (uint32_t) _seq0; - _pwm->SEQ[0].CNT = MAX_CHANNELS; // default mode is Individual --> count must be 4 - _pwm->SEQ[0].REFRESH = 0; - _pwm->SEQ[0].ENDDELAY = 0; - - _pwm->SEQ[1].PTR = 0; - _pwm->SEQ[1].CNT = 0; - _pwm->SEQ[1].REFRESH = 0; - _pwm->SEQ[1].ENDDELAY = 0; - - _pwm->ENABLE = 1; -} - -void HardwarePWM::_start(void) -{ - // update sequence count (depending on mode) - // _pwm->SEQ[0].CNT = MAX_CHANNELS; - - // start sequence - _pwm->TASKS_SEQSTART[0] = 1; -} - -void HardwarePWM::stop(void) -{ - _pwm->ENABLE = 0; -} - -bool HardwarePWM::writeChannel(uint8_t ch, uint16_t value, bool inverted ) +bool HardwarePWM::writeChannel(uint8_t ch, uint16_t value, bool inverted) { VERIFY( ch < MAX_CHANNELS ); _seq0[ch] = value | (inverted ? 0 : bit(15)); - // Start PWM if not already + // Initialize PWM if not already if ( !enabled() ) begin(); - _start(); + // start sequence + _pwm->TASKS_SEQSTART[0] = 1; return true; } @@ -204,7 +228,7 @@ bool HardwarePWM::writePin(uint8_t pin, uint16_t value, bool inverted) return writeChannel(ch, value, inverted); } -uint16_t HardwarePWM::readPin(uint8_t pin) +uint16_t HardwarePWM::readPin(uint8_t pin) const { int ch = pin2channel(pin); VERIFY( ch >= 0, 0); @@ -212,9 +236,79 @@ uint16_t HardwarePWM::readPin(uint8_t pin) return readChannel(ch); } -uint16_t HardwarePWM::readChannel(uint8_t ch) +uint16_t HardwarePWM::readChannel(uint8_t ch) const { // remove inverted bit return (_seq0[ch] & 0x7FFF); } +uint8_t HardwarePWM::usedChannelCount(void) const +{ + uint8_t usedChannels = 0; + for(int i=0; iPSEL.OUT[i] & PWM_PSEL_OUT_CONNECT_Msk) != (PWM_PSEL_OUT_CONNECT_Disconnected << PWM_PSEL_OUT_CONNECT_Pos) ) + { + usedChannels++; + } + } + return usedChannels; +} + +uint8_t HardwarePWM::freeChannelCount(void) const +{ + return MAX_CHANNELS - usedChannelCount(); +} + +// returns true ONLY when (1) no PWM channel has a pin, and (2) the owner token is nullptr +bool HardwarePWM::takeOwnership(uint32_t token) +{ + bool const thread_mode = !isInISR(); + + if (token == 0) { + if (thread_mode) LOG_LV1("HwPWM", "zero is not a valid ownership token (attempted use in takeOwnership)"); + return false; + } + + if (token == this->_owner_token) { + if (thread_mode) LOG_LV1("HwPWM", "failing to acquire ownership because already owned by requesting token (cannot take ownership twice)"); + return false; + } + + if ( this->_owner_token != 0 ) return false; + if ( this->usedChannelCount() != 0 ) return false; + if ( this->enabled() ) return false; + + // Use C++11 atomic CAS operation + uint32_t expectedValue = 0U; + return this->_owner_token.compare_exchange_strong(expectedValue, token); +} + +// returns true ONLY when (1) no PWM channel has a pin attached, and (2) the owner token matches +bool HardwarePWM::releaseOwnership(uint32_t token) +{ + bool const thread_mode = !isInISR(); + + if (token == 0) { + if (thread_mode) LOG_LV1("HwPWM", "zero is not a valid ownership token (attempted use in releaseOwnership)"); + return false; + } + + if (!this->isOwner(token)) { + if (thread_mode) LOG_LV1("HwPWM", "attempt to release ownership when not the current owner"); + return false; + } + + if (this->usedChannelCount() != 0) { + if (thread_mode) LOG_LV1("HwPWM", "attempt to release ownership when at least on channel is still connected"); + return false; + } + + if (this->enabled()) { + if (thread_mode) LOG_LV1("HwPWM", "attempt to release ownership when PWM peripheral is still enabled"); + return false; // if it's enabled, do not allow ownership to be released, even with no pins in use + } + + // Use C++11 atomic CAS operation + return this->_owner_token.compare_exchange_strong(token, 0U); +} diff --git a/cores/nRF5/HardwarePWM.h b/cores/nRF5/HardwarePWM.h index bf2691e3..47ec16c5 100644 --- a/cores/nRF5/HardwarePWM.h +++ b/cores/nRF5/HardwarePWM.h @@ -38,6 +38,7 @@ #include "common_inc.h" #include "nrf.h" +#include #ifdef NRF52840_XXAA #define HWPWM_MODULE_NUM 4 @@ -49,15 +50,14 @@ class HardwarePWM { private: enum { MAX_CHANNELS = 4 }; // Max channel per group - NRF_PWM_Type* _pwm; + NRF_PWM_Type * const _pwm; + std::atomic_uint32_t _owner_token; uint16_t _seq0[MAX_CHANNELS]; uint16_t _max_value; uint8_t _clock_div; - void _start(void); - public: HardwarePWM(NRF_PWM_Type* pwm); @@ -67,10 +67,28 @@ class HardwarePWM void setClockDiv(uint8_t div); // value is PWM_PRESCALER_PRESCALER_DIV_x, DIV1 is 16Mhz + // Cooperative ownership sharing + + // returns true ONLY when (1) no PWM channel has a pin, and (2) the owner token is nullptr + bool takeOwnership (uint32_t token); + + // returns true ONLY when (1) no PWM channel has a pin attached, and (2) the owner token matches + bool releaseOwnership(uint32_t token); + + // allows caller to verify that they own the peripheral + bool isOwner(uint32_t token) const + { + return this->_owner_token == token; + } + + // Add a pin to PWM module bool addPin (uint8_t pin); + + // Remove a pin from PWM module bool removePin (uint8_t pin); - int pin2channel(uint8_t pin) + // Get the mapped channel of a pin + int pin2channel(uint8_t pin) const { pin = g_ADigitalPinMap[pin]; for(int i=0; i= 0; } @@ -94,8 +113,17 @@ class HardwarePWM bool writeChannel(uint8_t ch , uint16_t value, bool inverted = false); // Read current set value - uint16_t readPin (uint8_t pin); - uint16_t readChannel (uint8_t ch); + uint16_t readPin (uint8_t pin) const; + uint16_t readChannel (uint8_t ch) const; + + // Get count of used / free channels + uint8_t usedChannelCount(void) const; + uint8_t freeChannelCount(void) const; + + static void DebugOutput(Stream& logger); + + private: + void _set_psel(int ch, uint32_t value); }; extern HardwarePWM HwPWM0; diff --git a/cores/nRF5/TinyUSB/Adafruit_TinyUSB_ArduinoCore b/cores/nRF5/TinyUSB/Adafruit_TinyUSB_ArduinoCore index 238a5c0b..c36ecdaf 160000 --- a/cores/nRF5/TinyUSB/Adafruit_TinyUSB_ArduinoCore +++ b/cores/nRF5/TinyUSB/Adafruit_TinyUSB_ArduinoCore @@ -1 +1 @@ -Subproject commit 238a5c0b95fcd402d24524c7bebbdd822168a51e +Subproject commit c36ecdaf54aaa88cb678f05ea973d6795f2d6cae diff --git a/cores/nRF5/TinyUSB/Adafruit_TinyUSB_nRF.cpp b/cores/nRF5/TinyUSB/Adafruit_TinyUSB_nRF.cpp index e4f50237..d901b1cb 100644 --- a/cores/nRF5/TinyUSB/Adafruit_TinyUSB_nRF.cpp +++ b/cores/nRF5/TinyUSB/Adafruit_TinyUSB_nRF.cpp @@ -63,6 +63,14 @@ extern "C" void USBD_IRQHandler(void) // Init usb hardware when starting up. Softdevice is not enabled yet static void usb_hardware_init(void) { + // Priorities 0, 1, 4 (nRF52) are reserved for SoftDevice + // 2 is highest for application + NVIC_SetPriority(USBD_IRQn, 2); + + // USB power may already be ready at this time -> no event generated + // We need to invoke the handler based on the status initially + uint32_t usb_reg = NRF_POWER->USBREGSTATUS; + // Power module init const nrfx_power_config_t pwr_cfg = { 0 }; nrfx_power_init(&pwr_cfg); @@ -73,16 +81,7 @@ static void usb_hardware_init(void) nrfx_power_usbevt_enable(); - // Priorities 0, 1, 4 (nRF52) are reserved for SoftDevice - // 2 is highest for application - NVIC_SetPriority(USBD_IRQn, 2); - - // USB power may already be ready at this time -> no event generated - // We need to invoke the handler based on the status initially - uint32_t usb_reg = NRF_POWER->USBREGSTATUS; - if ( usb_reg & POWER_USBREGSTATUS_VBUSDETECT_Msk ) tusb_hal_nrf_power_event(NRFX_POWER_USB_EVT_DETECTED); - if ( usb_reg & POWER_USBREGSTATUS_OUTPUTRDY_Msk ) tusb_hal_nrf_power_event(NRFX_POWER_USB_EVT_READY); } // USB Device Driver task @@ -91,7 +90,7 @@ static void usb_device_task(void* param) { (void) param; - USBDevice.addInterface( (Adafruit_USBD_Interface&) Serial); + USBDevice.addInterface((Adafruit_USBD_Interface&) Serial); USBDevice.setID(USB_VID, USB_PID); USBDevice.begin(); @@ -111,11 +110,12 @@ static void usb_device_task(void* param) void Adafruit_TinyUSB_Core_init(void) { // Create a task for tinyusb device stack - xTaskCreate( usb_device_task, "usbd", USBD_STACK_SZ, NULL, TASK_PRIO_HIGH, NULL); + xTaskCreate(usb_device_task, "usbd", USBD_STACK_SZ, NULL, TASK_PRIO_HIGH, NULL); } void Adafruit_TinyUSB_Core_touch1200(void) { + delay(5); // a few millisecond for USB control status completion enterSerialDfu(); } diff --git a/cores/nRF5/TinyUSB/tusb_config.h b/cores/nRF5/TinyUSB/tusb_config.h index 3e7936ff..bf49dc3b 100644 --- a/cores/nRF5/TinyUSB/tusb_config.h +++ b/cores/nRF5/TinyUSB/tusb_config.h @@ -44,6 +44,10 @@ #define CFG_TUSB_MEM_SECTION #define CFG_TUSB_MEM_ALIGN __attribute__ ((aligned(4))) +#ifndef CFG_TUSB_DEBUG +#define CFG_TUSB_DEBUG 0 +#endif + //-------------------------------------------------------------------- // DEVICE CONFIGURATION //-------------------------------------------------------------------- diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index e244d391..4f52d31f 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -1,22 +1,22 @@ /* Tone.cpp - A Tone Generator Library +A Tone Generator Library - Written by Brett Hagman +Written by Brett Hagman - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Version Modified By Date Comments ------- ----------- -------- -------- @@ -32,163 +32,354 @@ Version Modified By Date Comments 0008 S Kanemoto 12/06/22 Fixed for Leonardo by @maris_HY 0009 Arduino.org 15/06/30 Add M0/M0 Pro support 0010 Arduino.org 16/07/27 Added Arduino Primo support +0011 Henry Gabryjelski 20/08/25 Rework/Rewrite the library to use no interrupt handler and + support HwPWM ownership *************************************************/ - +#include "Arduino.h" #include "Tone.h" #include "WVariant.h" +#include "limits.h" -unsigned long int count_duration=0; -volatile bool no_stop = false; -uint8_t pin_sound=0; +// NOTE: Currently hard-coded to only use PWM2 ... +// These are the relvant hard-coded variables +// TODO: Consider allowing dynamic use of any available PWM peripheral (but start with #2 for compatibility) +static NRF_PWM_Type * const _PWMInstance = NRF_PWM2; +static HardwarePWM * const _HwPWM = HwPWMx[2]; +// Defined a struct, to simplify validation testing ... also provides context when debugging +class TonePwmConfig { + private: + enum { TONE_TOKEN = 0x656e6f54 }; //< 'T' 'o' 'n' 'e' + uint64_t pulse_count; //< total number of PWM pulses + uint32_t seq0_refresh; //< count of pulses for each SEQ0 iteration + uint32_t seq1_refresh; //< count of pulses for each SEQ1 iteration + uint16_t loop_count; //< how many times to restart SEQ0/SEQ1? + uint16_t time_period; //< how many clock cycles allocated to each PWM pulse? + uint16_t duty_with_polarity; //< SEQ[N].PTR will point here, length == 1 + nrf_pwm_task_t task_to_start; //< Whether to start playback at SEQ0 or SEQ1 + nrf_pwm_short_mask_t shorts; //< shortcuts to enable -void tone(uint8_t pin, unsigned int frequency, unsigned long duration) -{ - unsigned int time_per=0; - - if((frequency < 20) | (frequency > 25000)) return; - + public: + bool ensurePwmPeripheralOwnership(void); + bool initializeFromPulseCountAndTimePeriod(uint64_t pulse_count, uint16_t time_period); + bool applyConfiguration(uint32_t pin); + bool startPlayback(void); + bool stopPlayback(bool releaseOwnership = false); +}; +TonePwmConfig _pwm_config; - float per=float(1)/frequency; - time_per=per/0.000008; - unsigned int duty=time_per/2; - if(duration > 0){ - no_stop = false; - float mil=float(duration)/1000; - if(per>mil) - count_duration=1; - else - count_duration= mil/per; - } - else - no_stop = true; - - // Configure PWM - static uint16_t seq_values[]={0}; - //In each value, the most significant bit (15) determines the polarity of the output - //0x8000 is MSB = 1 - seq_values[0]= duty | 0x8000; - nrf_pwm_sequence_t const seq={ - seq_values, - NRF_PWM_VALUES_LENGTH(seq_values), - 0, - 0 - }; - -#if 0 - //assign pin to pwm channel - look at WVariant.h for details about ulPWMChannel attribute - uint8_t pwm_type=g_APinDescription[pin].ulPWMChannel; - if(pwm_type == NOT_ON_PWM) - return; - - uint32_t pins[NRF_PWM_CHANNEL_COUNT]={NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED}; - pins[pwm_type & 0x0F]=g_APinDescription[pin].ulPin; - IRQn_Type IntNo = PWM0_IRQn; - NRF_PWM_Type * PWMInstance = NRF_PWM0; - switch(pwm_type &0xF0){ - case 16://0x10 - PWMInstance = NRF_PWM1; - IntNo = PWM1_IRQn; - break; - case 32://0x20 - PWMInstance = NRF_PWM2; - IntNo = PWM2_IRQn; - break; - } -#else - // Use fixed PWM2, TODO could conflict with other usage - uint32_t pins[NRF_PWM_CHANNEL_COUNT]={NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED}; - pins[0] = g_ADigitalPinMap[pin]; - - IRQn_Type IntNo = PWM2_IRQn; - NRF_PWM_Type * PWMInstance = NRF_PWM2; -#endif - - nrf_pwm_pins_set(PWMInstance, pins); - nrf_pwm_enable(PWMInstance); - nrf_pwm_configure(PWMInstance, NRF_PWM_CLK_125kHz, NRF_PWM_MODE_UP, time_per); - nrf_pwm_decoder_set(PWMInstance, NRF_PWM_LOAD_COMMON, NRF_PWM_STEP_AUTO); - nrf_pwm_sequence_set(PWMInstance, 0, &seq); - nrf_pwm_shorts_enable(PWMInstance, NRF_PWM_SHORT_SEQEND0_STOP_MASK); - - // enable interrupt - nrf_pwm_event_clear(PWMInstance, NRF_PWM_EVENT_PWMPERIODEND); - nrf_pwm_int_enable(PWMInstance, NRF_PWM_INT_PWMPERIODEND_MASK); - NVIC_SetPriority(IntNo, 6); //low priority - NVIC_ClearPendingIRQ(IntNo); - NVIC_EnableIRQ(IntNo); - - nrf_pwm_task_trigger(PWMInstance, NRF_PWM_TASK_SEQSTART0); +static bool _is_pwm_enabled(NRF_PWM_Type const * pwm_instance) { + bool isEnabled = + (pwm_instance->ENABLE & PWM_ENABLE_ENABLE_Msk) == + (PWM_ENABLE_ENABLE_Enabled << PWM_ENABLE_ENABLE_Pos); + return isEnabled; } +/* These two functions were verified as equivalent to + the prior calculations (except where the old floating-point + based code resulted in rounding errors ... and thus there + are some one-off differences ... but the integer-based + functions are more accurate). + + These functions entirely avoid floating point math, and all + the nasty edge cases they can create... (NaN, INF, etc.) + + See https://gist.github.com/henrygab/6b570ebd51354bf247633c72b8dc383b + for code that compares the new lambdas to the old calculations. +*/ +constexpr static uint16_t _calculate_time_period(uint32_t frequency) { + // range for frequency == [20..25000], + // so range of result == [ 5..62500] + // which fits in 16 bits. + return 125000 / frequency; +}; + +constexpr static uint64_t _calculate_pulse_count(uint32_t frequency, uint32_t duration) { + // range for frequency == [20..25000], + // range for duration == [ 1..0xFFFF_FFFF] + // so range of result == [ 1..0x18_FFFF_FFE7] (requires 37 bits) + return + (duration == 0) ? + 0 : + ((duration < 1000ULL) && (duration * frequency < 1000ULL)) ? + 1ULL : + (UINT64_MAX / frequency < duration) ? + (duration / 1000ULL) * frequency : + (((uint64_t)duration) * frequency / 1000ULL); +}; + +static int _bits_used(unsigned long x) { + if (0 == x) return 0; + unsigned int result = 0; + do { + result++; + } while (x >>= 1); + return result; +} + +static int _bits_used(unsigned long long x) { + if (0 == x) return 0; + unsigned int result = 0; + do { + result++; + } while (x >>= 1); + return result; +} + +/* +* In older versions of the BSP, tone() would cause an interrupt for every cycle, tracking whether +* the playback should be infinite or duration-based via two global, volatile variables, "nostop" +* and "count_duration". The interrupt would then trigger the STARTSEQ0 task, or stop playback +* by calling noTone(). +* +* What is available to configure looping with minimal memory usage: +* 1. SEQ[n].REFRESH === how many PWM period before loading next sample from sequence +* Thus, setting to 99 will cause 100 pulses per item +* Treat as a 23-bit value. +* 2. LOOP === how many times to loop back to SEQ[0] +* SEQ[0] will play the same count if started PWM at SEQ[0] +* SEQ[0] will play one fewer times if started PWM at SEQ[1] +* Treat as a 15-bit value. +* +* Therefore, between REFRESH and LOOP, can support up to 40-bit repeat WITHOUT INTERRUPTS. +* +* The value of duration is given in milliseconds. +* Frequency is limited to range [20 ... 25000]. +* +* Therefore, maximum pulse count is limited as follows: +* (32-bit duration) * (20 ... 25000) / 1000UL +* (0xFFFF_FFFF) * 25 +* 0x18_FFFF_FFE7 ... which is 37 bits +* +* Therefore, all possible values for tone() can be supported +* via a single one-time configuration of the PWM peripheral. +* +* PWM peripheral can be de-allocated by sketch call to noTone(). +* +* Design: +* 0. At each call to tone(), unconditionally stop any existing playback. +* 1. For infinite duration, configure large REFRESH and LOOP (to minimize reading of RAM / AHB traffic), +* and setup shortcut to repeat infinitely. +* 2. For specified duration, configure both SEQ0 and SEQ1: +* 1a. SEQ[1].REFRESH <-- total count % _iterations_per_loop +* 1b. SEQ[0].REFRESH <-- _iterations_per_loop - SEQ[1].CNT +* 1c. LOOP <-- duration_count / _iterations_per_loop +* +* Result: Zero CPU usage, minimal AHB traffic +*/ +void tone(uint8_t pin, unsigned int frequency, unsigned long duration) +{ + // limit frequency to reasonable audible range + if((frequency < 20) | (frequency > 25000)) { + LOG_LV1("Tone", "frequency outside range [20..25000] -- ignoring"); + return; + } + uint64_t pulse_count = _calculate_pulse_count(frequency, duration); + uint16_t time_period = _calculate_time_period(frequency); + if (!_pwm_config.ensurePwmPeripheralOwnership()) { + LOG_LV1("Tone", "Unable to acquire PWM peripheral"); + } else if (!_pwm_config.stopPlayback(false)) { + LOG_LV1("Tone", "Unable to stop playback"); + } else if (!_pwm_config.initializeFromPulseCountAndTimePeriod(pulse_count, time_period)) { + LOG_LV1("Tone", "Failed calculating configuration"); + } else if (!_pwm_config.applyConfiguration(pin)) { + LOG_LV1("Tone", "Failed applying configuration"); + } else if (!_pwm_config.startPlayback()) { + LOG_LV1("Tone", "Failed attempting to start PWM peripheral"); + } else { + //LOG_LV2("Tone", "Started playback of tone at frequency %d duration %ld", frequency, duration); + } + return; +} void noTone(uint8_t pin) { -#if 0 - uint8_t pwm_type=g_APinDescription[pin].ulPWMChannel; - NRF_PWM_Type * PWMInstance = NRF_PWM0; - switch(pwm_type &0xF0){ - case 16://0x10 - PWMInstance = NRF_PWM1; - break; - case 32://0x20 - PWMInstance = NRF_PWM2; - break; - } -#else - NRF_PWM_Type * PWMInstance = NRF_PWM2; -#endif - - nrf_pwm_task_trigger(PWMInstance, NRF_PWM_TASK_STOP); - nrf_pwm_disable(PWMInstance); + ( void )pin; // avoid unreferenced parameter compiler warning + _pwm_config.stopPlayback(true); // release ownership of PWM peripheral } -#ifdef __cplusplus -extern "C"{ -#endif - -#if 0 -void PWM0_IRQHandler(void){ - nrf_pwm_event_clear(NRF_PWM0, NRF_PWM_EVENT_PWMPERIODEND); - if(!no_stop){ - count_duration--; - if(count_duration == 0) - noTone(pin_sound); - else - nrf_pwm_task_trigger(NRF_PWM0, NRF_PWM_TASK_SEQSTART0); - } - else - nrf_pwm_task_trigger(NRF_PWM0, NRF_PWM_TASK_SEQSTART0); +bool TonePwmConfig::ensurePwmPeripheralOwnership(void) { + if (!_HwPWM->isOwner(TonePwmConfig::TONE_TOKEN) && !_HwPWM->takeOwnership(TonePwmConfig::TONE_TOKEN)) { + LOG_LV1("Tone", "unable to allocate PWM2 to Tone"); + return false; + } + return true; } -void PWM1_IRQHandler(void){ - nrf_pwm_event_clear(NRF_PWM1, NRF_PWM_EVENT_PWMPERIODEND); - if(!no_stop){ - count_duration--; - if(count_duration == 0) - noTone(pin_sound); - else - nrf_pwm_task_trigger(NRF_PWM1, NRF_PWM_TASK_SEQSTART0); - } - else - nrf_pwm_task_trigger(NRF_PWM1, NRF_PWM_TASK_SEQSTART0); -} -#endif +// +// The final loop's SEQ1 will ALWAYS output one pulse ... +// In other words, SEQ1's refresh is *IGNORED* for the final loop. +// +// Visually, with each sequence length set to one as is done with tone(): +// ====================================================================== +// +// Starting at SEQ0, loopCnt = 2, SEQ0 refresh == 4, SEQ1 refresh = 2: +// +// [----SEQ0-----] [SEQ1-] [----SEQ0-----] [1] +// 0 0 0 0 1 1 0 0 0 0 1 +// +// ====================================================================== +// +// Starting as SEQ1, loopCnt = 2, SEQ0 refresh == 4, SEQ1 refresh = 2: +// +// [SEQ1-] [----SEQ0-----] [1] +// 1 1 0 0 0 0 1 +// +// ====================================================================== +// +// Therefore, the total count of pulses that will be emitted by the +// PWM peripheral (per the configuration of tone() API): +// +// COUNT = (SEQ0.CNT * (SEQ0.REFRESH+1); +// COUNT += (SEQ1.CNT * (SEQ1.REFRESH+1); +// COUNT *= (loopCount-1); // the number of times SEQ0 and SEQ1 both run +// COUNT += (start at SEQ0) ? (SEQ0.CNT * (SEQ0.REFRESH+1) : 0; +// COUNT += 1; // final SEQ1 emits single pulse +// +bool TonePwmConfig::initializeFromPulseCountAndTimePeriod(uint64_t pulse_count_x, uint16_t time_period) { -void PWM2_IRQHandler(void){ - nrf_pwm_event_clear(NRF_PWM2, NRF_PWM_EVENT_PWMPERIODEND); - if(!no_stop){ - count_duration--; - if(count_duration == 0) - noTone(pin_sound); - else - nrf_pwm_task_trigger(NRF_PWM2, NRF_PWM_TASK_SEQSTART0); - } - else - nrf_pwm_task_trigger(NRF_PWM2, NRF_PWM_TASK_SEQSTART0); + if (_bits_used(pulse_count_x) > 37) { + LOG_LV1("Tone", "pulse count is limited to 37 bit long value"); + return false; + } + + this->pulse_count = pulse_count_x; + this->time_period = time_period; + this->duty_with_polarity = 0x8000U | (time_period / 2U); + + if (this->pulse_count == 0) { + this->seq0_refresh = 0xFFFFFFU; // 24-bit maximum value + this->seq1_refresh = 0xFFFFFFU; // 24-bit maximum value + this->loop_count = 0xFFFFU; // 16-bit maximum value + this->task_to_start = NRF_PWM_TASK_SEQSTART0; + this->shorts = NRF_PWM_SHORT_LOOPSDONE_SEQSTART0_MASK; + } + else if (this->pulse_count == 1) { + // yes, this is an edge case; e.g., frequency == 100, duration == 100 causes this + this->seq0_refresh = 0; + this->seq1_refresh = 0; + this->loop_count = 1; + this->task_to_start = NRF_PWM_TASK_SEQSTART1; + this->shorts = NRF_PWM_SHORT_LOOPSDONE_STOP_MASK; + } + else { + // This is the interesting section. + // + // To ensure refresh value stays within 24 bits, the maximum number of bits + // for the pulse_count is ((24 * 3) / 2) + 1 == (72/2) + 1 == 36 + 1 == 37. + // + // Validation: + // 37 * 2 / 3 == 74 / 3 == 24 (OK) -- leaves 13 bits for loop count + // 38 * 2 / 3 == 76 / 3 == 25 (fail) -- leaves 13 bits for loop count + // + // NOTE: theoretically possible to support up to 40 bit pulse count, but + // would require more complex logic. + // + unsigned int bits_needed = _bits_used(this->pulse_count); // bits_used is now in range [2..37] + + // split the number of bits between refresh and loop_count in 2:1 ratio + // so that, no matter what inputs are given, guaranteed to have interrupt-free solution + unsigned int bits_for_refresh = bits_needed * 2 / 3; // range is [1 .. 24] + //unsigned int bits_for_loop_count = bits_needed - bits_for_refresh; // range is [1 .. 13] + + // NOTE: Due to final SEQ1 outputting exactly one pulse, may need one additional bit for loop count + // ... but that will still be within the 16 bits available, because top of range is 13 bits. + + // now determine how many PWM pulses should occur per loop (when both SEQ0 and SEQ1 are played) + uint32_t total_refresh_count = 1 << bits_for_refresh; // range is [2 .. 2^24] + uint32_t full_loops = (this->pulse_count - 1) / total_refresh_count; // == loopCount - 1 + + // if (pulses - 1) % total_refresh_count == 0, then start at SEQ1 and split refresh evenly + // else, start at SEQ0, and set SEQ0 to extra pulses needed... + uint32_t extraPulsesNeededIfStartingAtSequence1 = (this->pulse_count - 1) % total_refresh_count; + uint32_t seq0_count; + + if (extraPulsesNeededIfStartingAtSequence1 == 0) { + seq0_count = total_refresh_count / 2; // range is [1 .. 2^23] + this->task_to_start = NRF_PWM_TASK_SEQSTART1; + } + else { + seq0_count = extraPulsesNeededIfStartingAtSequence1; + this->task_to_start = NRF_PWM_TASK_SEQSTART0; + } + this->loop_count = full_loops + 1; + this->seq0_refresh = seq0_count - 1; + this->seq1_refresh = (total_refresh_count - seq0_count) - 1; + this->shorts = NRF_PWM_SHORT_LOOPSDONE_STOP_MASK; + } + return true; } -#ifdef __cplusplus +bool TonePwmConfig::applyConfiguration(uint32_t pin) { + if (pin >= PINS_COUNT) { + return false; + } + if (!this->ensurePwmPeripheralOwnership()) { + return false; + } + this->stopPlayback(false); + + uint32_t pins[NRF_PWM_CHANNEL_COUNT] = { + g_ADigitalPinMap[pin], + NRF_PWM_PIN_NOT_CONNECTED, + NRF_PWM_PIN_NOT_CONNECTED, + NRF_PWM_PIN_NOT_CONNECTED + }; + + nrf_pwm_pins_set(_PWMInstance, pins); // must set pins before enabling + nrf_pwm_enable(_PWMInstance); + nrf_pwm_configure(_PWMInstance, NRF_PWM_CLK_125kHz, NRF_PWM_MODE_UP, this->time_period); + nrf_pwm_decoder_set(_PWMInstance, NRF_PWM_LOAD_COMMON, NRF_PWM_STEP_AUTO); + nrf_pwm_shorts_set(_PWMInstance, this->shorts); + nrf_pwm_int_set(_PWMInstance, 0); + + nrf_pwm_seq_ptr_set(_PWMInstance, 0, &this->duty_with_polarity); + nrf_pwm_seq_ptr_set(_PWMInstance, 1, &this->duty_with_polarity); + nrf_pwm_seq_cnt_set(_PWMInstance, 0, 1); + nrf_pwm_seq_cnt_set(_PWMInstance, 1, 1); + + nrf_pwm_seq_refresh_set(_PWMInstance, 0, seq0_refresh); + nrf_pwm_seq_refresh_set(_PWMInstance, 1, seq1_refresh); + nrf_pwm_seq_end_delay_set(_PWMInstance, 0, 0); + nrf_pwm_seq_end_delay_set(_PWMInstance, 1, 0); + nrf_pwm_loop_set(_PWMInstance, loop_count); + + nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_STOPPED); + nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_SEQSTARTED0); + nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_SEQSTARTED1); + nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_SEQEND0); + nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_SEQEND1); + nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_PWMPERIODEND); + nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_LOOPSDONE); + return true; +} + +bool TonePwmConfig::startPlayback(void) { + if (!this->ensurePwmPeripheralOwnership()) { + LOG_LV1("Tone", "PWM peripheral not available for playback"); + return false; + } + nrf_pwm_task_trigger(_PWMInstance, this->task_to_start); + return true; +} + +bool TonePwmConfig::stopPlayback(bool releaseOwnership) { + + if (!_HwPWM->isOwner(TonePwmConfig::TONE_TOKEN)) { + LOG_LV2("Tone", "Attempt to set noTone when not the owner of the PWM peripheral. Ignoring call...."); + return false; + } + // ensure stopped and then disable + if (_is_pwm_enabled(_PWMInstance)) { + nrf_pwm_task_trigger(_PWMInstance, NRF_PWM_TASK_STOP); + nrf_pwm_disable(_PWMInstance); + _PWMInstance->PSEL.OUT[0] = NRF_PWM_PIN_NOT_CONNECTED; + } + + if (releaseOwnership) { + _HwPWM->releaseOwnership(TonePwmConfig::TONE_TOKEN); + } + + return true; } -#endif diff --git a/cores/nRF5/Tone.h b/cores/nRF5/Tone.h index 8874a1ce..064cfad3 100644 --- a/cores/nRF5/Tone.h +++ b/cores/nRF5/Tone.h @@ -15,6 +15,7 @@ License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ +/** \file Tone.h */ #ifndef _WIRING_TONE_ #define _WIRING_TONE_ @@ -25,8 +26,44 @@ #include "wiring_digital.h" #include "nrf_pwm.h" - +/** + * \brief Generate a tone (PWM) output on the specified pin. + * + * \param[in] pin The Arduino pin for output + * + * \param[in] frequency The frequency, in hertz, of the requested tone. + * + * \param[in] duration An optional duration, in milliseconds (default: 0 == infinite) + * + * Generates a square wave of the specified frequency (and 50% duty cycle) + * on a pin. A duration can be specified, otherwise the wave continues until a call + * to `noTone()`. The pin can be connected to a piezo buzzer or other speaker to + * play tones. + * + * The `tone()` API has the following contracts, which were defined by + * the original Arduino code: + * + * 1. at most one `tone()` can be generated at a time + * 2. so long as the `pin` stays the same, `tone()` can be called repeatedly + * 3. a call to `noTone()` is required prior to calling `tone()` with a different pin. + * + * The third requirement is not enforced in the nRF52 BSP. Instead, if a call + * to `tone()` is made with a different pin, a call to `noTone()` occurs automatically, + * simplifying use somewhat. + * + * For the nRF52, the allowed range for parameter `frequency` is `[20..25000]`. + * + * \see noTone + */ void tone(uint8_t pin, unsigned int frequency, unsigned long duration = 0); +/** + * \brief Stops generation of a tone (PWM) output. + * + * \param pin For the nRF52, this argument is ignored + * + * Stops the generation of a square wave triggered by `tone()`. + * This function has no effect if no tone is being generated. + */ void noTone(uint8_t pin); diff --git a/cores/nRF5/common_func.h b/cores/nRF5/common_func.h index 32d56c5e..ed5ac272 100644 --- a/cores/nRF5/common_func.h +++ b/cores/nRF5/common_func.h @@ -73,6 +73,8 @@ #define ADA_COUNTER __LINE__ #endif +#include + #define COMMENT_OUT(x) #define memclr(buffer, size) memset(buffer, 0, size) diff --git a/cores/nRF5/common_inc.h b/cores/nRF5/common_inc.h index 51fbceeb..f179ad12 100644 --- a/cores/nRF5/common_inc.h +++ b/cores/nRF5/common_inc.h @@ -38,6 +38,7 @@ #include #include +#include #include "compiler_macro.h" #include "common_func.h" diff --git a/cores/nRF5/delay.c b/cores/nRF5/delay.c index f96d5058..73c68e1d 100644 --- a/cores/nRF5/delay.c +++ b/cores/nRF5/delay.c @@ -30,11 +30,6 @@ uint32_t millis( void ) return tick2ms(xTaskGetTickCount()); } -uint32_t micros( void ) -{ - return tick2us(xTaskGetTickCount()); -} - void delay( uint32_t ms ) { uint32_t ticks = ms2tick(ms); diff --git a/cores/nRF5/delay.h b/cores/nRF5/delay.h index f25809f7..404334ba 100644 --- a/cores/nRF5/delay.h +++ b/cores/nRF5/delay.h @@ -26,6 +26,13 @@ extern "C" { #include #include "nrfx.h" #include "variant.h" +#include "rtos.h" + +static inline bool dwt_enabled(void) __attribute__((always_inline)); +static inline bool dwt_enabled(void) +{ + return (CoreDebug->DEMCR & CoreDebug_DEMCR_TRCENA_Msk) && (DWT->CTRL & DWT_CTRL_CYCCNTENA_Msk); +} /** * \brief Returns the number of milliseconds since the Arduino board began running the current program. @@ -46,7 +53,12 @@ extern uint32_t millis( void ) ; * * \note There are 1,000 microseconds in a millisecond and 1,000,000 microseconds in a second. */ -extern uint32_t micros( void ) ; +static inline uint32_t micros( void ) __attribute__((always_inline)); +static inline uint32_t micros( void ) +{ + // Use DWT cycle count if it is enabled, otherwise use rtos tick + return dwt_enabled() ? (DWT->CYCCNT / 64) : tick2us(xTaskGetTickCount()); +} /** * \brief Pauses the program for the amount of time (in miliseconds) specified as parameter. diff --git a/cores/nRF5/freertos/config/FreeRTOSConfig.h b/cores/nRF5/freertos/config/FreeRTOSConfig.h index e463dd30..bff583b4 100644 --- a/cores/nRF5/freertos/config/FreeRTOSConfig.h +++ b/cores/nRF5/freertos/config/FreeRTOSConfig.h @@ -139,8 +139,7 @@ #endif #endif /* !assembler */ -/* The lowest interrupt priority that can be used in a call to a "set priority" -function. */ +/* The lowest interrupt priority that can be used in a call to a "set priority" function. */ #define configLIBRARY_LOWEST_INTERRUPT_PRIORITY ((1< 0 ) { -#if 0 // With FreeRTOS sd_app_evt_wait increases power consumption with FreeRTOS compared to _WFE (NRFFOSDK-11174) +#if (__FPU_USED == 1) + // nRF52832 errata 87: prevent FPU from keeping CPU on + // https://infocenter.nordicsemi.com/topic/errata_nRF52832_Rev2/ERR/nRF52832/Rev2/latest/anomaly_832_87.html?cp=4_2_1_0_1_24 + __set_FPSCR(__get_FPSCR() & ~(0x0000009F)); + (void) __get_FPSCR(); + NVIC_ClearPendingIRQ(FPU_IRQn); +#endif #ifdef SOFTDEVICE_PRESENT // TODO uint8_t sd_en = 0; (void) sd_softdevice_is_enabled(&sd_en); @@ -193,7 +199,6 @@ void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ) } else #endif -#endif // (NRFFOSDK-11174) { /* No SD - we would just block interrupts globally. * BASEPRI cannot be used for that because it would prevent WFE from wake up. @@ -227,9 +232,34 @@ void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ) diff = xExpectedIdleTime; } - if (diff > 0) + // nRF-provided fix for delay() wakeup 1ms spin-loop power waste + // See https://devzone.nordicsemi.com/f/nordic-q-a/63828/vtaskdelay-on-nrf52-freertos-port-wastes-cpu-power + BaseType_t switch_req = pdFALSE; + + if (diff > 1) { - vTaskStepTick(diff); + vTaskStepTick(diff - 1); + + // If dwt cycle count is enable, adjust it as welll + if ( (CoreDebug->DEMCR & CoreDebug_DEMCR_TRCENA_Msk) && (DWT->CTRL & DWT_CTRL_CYCCNTENA_Msk) ) + { + DWT->CYCCNT += (((diff-1) * 1000000) / configTICK_RATE_HZ) * 64; + } + + switch_req = xTaskIncrementTick(); + } + else if (diff == 1) + { + switch_req = xTaskIncrementTick(); + } + + /* Increment the RTOS tick as usual which checks if there is a need for rescheduling */ + if ( switch_req != pdFALSE ) + { + /* A context switch is required. Context switching is performed in + the PendSV interrupt. Pend the PendSV interrupt. */ + SCB->ICSR = SCB_ICSR_PENDSVSET_Msk; + __SEV(); } } } diff --git a/cores/nRF5/main.cpp b/cores/nRF5/main.cpp index 98e3a291..a9e78844 100644 --- a/cores/nRF5/main.cpp +++ b/cores/nRF5/main.cpp @@ -15,6 +15,9 @@ #define ARDUINO_MAIN #include "Arduino.h" +#if (CFG_LOGGER == 2) + #include +#endif // DEBUG Level 1 #if CFG_DEBUG @@ -26,6 +29,7 @@ void Bluefruit_printInfo() {} // From the UI, setting debug level to 3 will enable SysView #if CFG_SYSVIEW +#include "SEGGER_RTT.h" #include "SEGGER_SYSVIEW.h" #endif @@ -99,6 +103,18 @@ void suspendLoop(void) vTaskSuspend(_loopHandle); } +void resumeLoop(void) +{ + if ( isInISR() ) + { + xTaskResumeFromISR(_loopHandle); + } + else + { + vTaskResume(_loopHandle); + } +} + extern "C" { @@ -106,11 +122,16 @@ extern "C" int _write (int fd, const void *buf, size_t count) { (void) fd; - +#if (CFG_LOGGER == 2) + unsigned numBytes = count; + SEGGER_RTT_Write(0, buf, numBytes); + return (int)count; +#else if ( Serial ) { return Serial.write( (const uint8_t *) buf, count); } +#endif return 0; } diff --git a/cores/nRF5/wiring_analog.cpp b/cores/nRF5/wiring_analog.cpp index 570be9eb..79131a7e 100644 --- a/cores/nRF5/wiring_analog.cpp +++ b/cores/nRF5/wiring_analog.cpp @@ -1,41 +1,31 @@ -/**************************************************************************/ -/*! - @file wiring_analog.cpp - @author hathach (tinyusb.org) - - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2018, Adafruit Industries (adafruit.com) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/**************************************************************************/ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020 Ha Thach for Adafruit Industries + * Copyright (c) 2020 Henry Gabryjelski + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ #include "Arduino.h" + /* Implement analogWrite() and analogWriteResolution() using * HardwarePWM. * @@ -45,14 +35,27 @@ extern "C" { +enum +{ + ANALOG_TOKEN = 0x676f6c41 // 'A' 'l' 'o' 'g' +}; + +static uint8_t _analogResolution = 8; // default is 256 levels + /** - * This will apply to all PWM Hardware + * This will apply to all PWM Hardware currently used by analogWrite(), + * and automatically apply to future calls to analogWrite(). */ void analogWriteResolution( uint8_t res ) { + // save the resolution for when adding a new instance + _analogResolution = res; for (int i = 0; isetResolution(res); + if (HwPWMx[i]->isOwner(ANALOG_TOKEN)) + { + HwPWMx[i]->setResolution(res); + } } } @@ -65,17 +68,50 @@ void analogWriteResolution( uint8_t res ) */ void analogWrite( uint32_t pin, uint32_t value ) { + // first, handle the case where the pin is already in use by analogWrite() for(int i=0; iaddPin(pin) ) + if (HwPWMx[i]->isOwner(ANALOG_TOKEN)) { + int const ch = HwPWMx[i]->pin2channel(pin); + if (ch >= 0) + { + HwPWMx[i]->writeChannel(ch, value); + return; + } + } + } + + // Next, handle the case where can add the pin to a PWM instance already owned by analogWrite() + for(int i=0; iisOwner(ANALOG_TOKEN) && HwPWMx[i]->addPin(pin) ) + { + // successfully added the pin, so write the value also HwPWMx[i]->writePin(pin, value); + LOG_LV2("Analog", "Added pin %" PRIu32 " to already-owned PWM %d", pin, i); return; } } + + // Attempt to acquire a new HwPWMx instance ... but only where + // 1. it's not one already used for analog, and + // 2. it currently has no pins in use. + for(int i=0; itakeOwnership(ANALOG_TOKEN)) + { + // apply the cached analog resolution to newly owned instances + HwPWMx[i]->setResolution(_analogResolution); + HwPWMx[i]->addPin(pin); + HwPWMx[i]->writePin(pin, value); + LOG_LV2("Analog", "took ownership of, and added pin %" PRIu32 " to, PWM %d", pin, i); + return; + } + } + + LOG_LV1("Analog", "Unable to find a free PWM peripheral"); + return; } -} - - +} // end extern "C" diff --git a/cores/nRF5/wiring_analog_nRF52.c b/cores/nRF5/wiring_analog_nRF52.c index ee95d318..b8a50fc5 100644 --- a/cores/nRF5/wiring_analog_nRF52.c +++ b/cores/nRF5/wiring_analog_nRF52.c @@ -33,38 +33,14 @@ static uint32_t saadcGain = SAADC_CH_CONFIG_GAIN_Gain1_6; static bool saadcBurst = SAADC_CH_CONFIG_BURST_Disabled; -#if 0 // Note: Adafruit use seperated HardwarePWM class -#define PWM_COUNT 3 - -static NRF_PWM_Type* pwms[PWM_COUNT] = { - NRF_PWM0, - NRF_PWM1, - NRF_PWM2 -}; - -static uint32_t pwmChannelPins[PWM_COUNT] = { - 0xFFFFFFFF, - 0xFFFFFFFF, - 0xFFFFFFFF -}; -static uint16_t pwmChannelSequence[PWM_COUNT]; -#endif +// Note: Adafruit use seperated HardwarePWM class static int readResolution = 10; -//static int writeResolution = 8; - void analogReadResolution( int res ) { readResolution = res; } -#if 0 -void analogWriteResolution( int res ) -{ - writeResolution = res; -} -#endif - static inline uint32_t mapResolution( uint32_t value, uint32_t from, uint32_t to ) { if ( from == to ) @@ -273,48 +249,6 @@ uint32_t analogRead( uint32_t ulPin ) return mapResolution(value, resolution, readResolution); } -#if 0 -// Right now, PWM output only works on the pins with -// hardware support. These are defined in the appropriate -// pins_*.c file. For the rest of the pins, we default -// to digital output. -void analogWrite( uint32_t ulPin, uint32_t ulValue ) -{ - if (ulPin >= PINS_COUNT) { - return; - } - - ulPin = g_ADigitalPinMap[ulPin]; - - for (int i = 0; i < PWM_COUNT; i++) { - if (pwmChannelPins[i] == 0xFFFFFFFF || pwmChannelPins[i] == ulPin) { - pwmChannelPins[i] = ulPin; - pwmChannelSequence[i] = bit(15) | ulValue; - - NRF_PWM_Type* pwm = pwms[i]; - - pwm->PSEL.OUT[0] = ulPin; - pwm->PSEL.OUT[1] = ulPin; - pwm->PSEL.OUT[2] = ulPin; - pwm->PSEL.OUT[3] = ulPin; - pwm->ENABLE = (PWM_ENABLE_ENABLE_Enabled << PWM_ENABLE_ENABLE_Pos); - pwm->PRESCALER = PWM_PRESCALER_PRESCALER_DIV_1; - pwm->MODE = PWM_MODE_UPDOWN_Up; - pwm->COUNTERTOP = (1 << writeResolution) - 1; - pwm->LOOP = 0; - pwm->DECODER = ((uint32_t)PWM_DECODER_LOAD_Common << PWM_DECODER_LOAD_Pos) | ((uint32_t)PWM_DECODER_MODE_RefreshCount << PWM_DECODER_MODE_Pos); - pwm->SEQ[0].PTR = (uint32_t)&pwmChannelSequence[i]; - pwm->SEQ[0].CNT = 1; - pwm->SEQ[0].REFRESH = 1; - pwm->SEQ[0].ENDDELAY = 0; - pwm->TASKS_SEQSTART[0] = 0x1UL; - - break; - } - } -} -#endif - #ifdef __cplusplus } #endif diff --git a/libraries/Adafruit_LittleFS/src/littlefs/lfs_util.h b/libraries/Adafruit_LittleFS/src/littlefs/lfs_util.h index e992ee6f..14e26530 100644 --- a/libraries/Adafruit_LittleFS/src/littlefs/lfs_util.h +++ b/libraries/Adafruit_LittleFS/src/littlefs/lfs_util.h @@ -168,6 +168,7 @@ void lfs_crc(uint32_t *crc, const void *buffer, size_t size); // Allocate memory, only used if buffers are not provided to littlefs static inline void *lfs_malloc(size_t size) { #ifndef LFS_NO_MALLOC + extern void *pvPortMalloc( size_t xWantedSize ); return pvPortMalloc(size); #else (void)size; @@ -178,6 +179,7 @@ static inline void *lfs_malloc(size_t size) { // Deallocate memory, only used if buffers are not provided to littlefs static inline void lfs_free(void *p) { #ifndef LFS_NO_MALLOC + extern void vPortFree( void *pv ); vPortFree(p); #else (void)p; diff --git a/libraries/Bluefruit52Lib/examples/Hardware/tone_happy_birthday/tone_happy_birthday.ino b/libraries/Bluefruit52Lib/examples/Hardware/tone_happy_birthday/tone_happy_birthday.ino new file mode 100644 index 00000000..7500d1c7 --- /dev/null +++ b/libraries/Bluefruit52Lib/examples/Hardware/tone_happy_birthday/tone_happy_birthday.ino @@ -0,0 +1,146 @@ +// Circuit Playground Birthday Candles +// +// All the NeoPixels will flicker like candles and the speaker will +// play the tune to Happy Birthday continuously. Blow on the board +// to slowly blow out all the candles and hear a victory song! +// Controls: +// - Slide switch: Move this to +/on to hear music or -/off to disable sound. +// - Left button: Hold this down and press reset to use a rainbow flicker color. +// - Right button: Hold this down and press reset to use a simple solid color (no flicker). +// - If neither left or right button are pressed at startup then a flame-like +// flickering animation will be used. +// After all the candles are blown out press reset to reset and start over! +// +// Author: Tony DiCola +// License: MIT (https://opensource.org/licenses/MIT) + +#include + +// PIN_BUZZER should be defined by the supported variant e.g CPlay Bluefruit or CLUE. +// Otherwise please define the pin you would like to use for tone output +#ifndef PIN_BUZZER +#define PIN_BUZZER A0 +#endif + + +// A few music note frequencies as defined in this tone example: +// https://www.arduino.cc/en/Tutorial/toneMelody +#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 durations. You only need to adjust the whole note +// time and other notes will be subdivided from it directly. +#define WHOLE 2200 // Length of time in milliseconds of a whole note (i.e. a full bar). +#define HALF WHOLE/2 +#define QUARTER HALF/2 +#define EIGHTH QUARTER/2 +#define EIGHTH_TRIPLE QUARTER/3 +#define SIXTEENTH EIGHTH/2 + +// Play a note of the specified frequency and for the specified duration. +// Hold is an optional bool that specifies if this note should be held a +// little longer, i.e. for eigth notes that are tied together. +// While waiting for a note to play the waitBreath delay function is used +// so breath detection and pixel animation continues to run. No tones +// will play if the slide switch is in the -/off position or all the +// candles have been blown out. +void playNote(int frequency, int duration, bool hold=false, bool measure=true) { + (void) measure; + + if (hold) { + // For a note that's held play it a little longer than the specified duration + // so it blends into the next tone (but there's still a small delay to + // hear the next note). + tone(PIN_BUZZER, frequency, duration + duration/32); + } + else { + // For a note that isn't held just play it for the specified duration. + tone(PIN_BUZZER, frequency, duration); + } + + delay(duration + duration/16); +} + +// Song to play when the candles are blown out. +void celebrateSong() { + // Play a little charge melody, from: + // https://en.wikipedia.org/wiki/Charge_(fanfare) + // Note the explicit boolean parameters in particular the measure=false + // at the end. This means the notes will play without any breath measurement + // logic. Without this false value playNote will try to keep waiting for candles + // to blow out during the celebration song! + playNote(NOTE_G4, EIGHTH_TRIPLE, true, false); + playNote(NOTE_C5, EIGHTH_TRIPLE, true, false); + playNote(NOTE_E5, EIGHTH_TRIPLE, false, false); + playNote(NOTE_G5, EIGHTH, true, false); + playNote(NOTE_E5, SIXTEENTH, false); + playNote(NOTE_G5, HALF, false); +} + +void setup() { + // Initialize serial output and Circuit Playground library. + Serial.begin(115200); + + pinMode(PIN_BUZZER, OUTPUT); + digitalWrite(PIN_BUZZER, LOW); +} + +void loop() { + // Play happy birthday tune, from: + // http://www.irish-folk-songs.com/happy-birthday-tin-whistle-sheet-music.html#.WXFJMtPytBw + // Inside each playNote call it will play a note and drive the NeoPixel animation + // and check for a breath against the sound sensor. Once all the candles are blown out + // the playNote calls will stop playing music. + playNote(NOTE_D4, EIGHTH, true); + playNote(NOTE_D4, EIGHTH); + playNote(NOTE_E4, QUARTER); // Bar 1 + playNote(NOTE_D4, QUARTER); + playNote(NOTE_G4, QUARTER); + playNote(NOTE_FS4, HALF); // Bar 2 + playNote(NOTE_D4, EIGHTH, true); + playNote(NOTE_D4, EIGHTH); + playNote(NOTE_E4, QUARTER); // Bar 3 + playNote(NOTE_D4, QUARTER); + playNote(NOTE_A4, QUARTER); + playNote(NOTE_G4, HALF); // Bar 4 + playNote(NOTE_D4, EIGHTH, true); + playNote(NOTE_D4, EIGHTH); + playNote(NOTE_D5, QUARTER); // Bar 5 + playNote(NOTE_B4, QUARTER); + playNote(NOTE_G4, QUARTER); + playNote(NOTE_FS4, QUARTER); // Bar 6 + playNote(NOTE_E4, QUARTER); + playNote(NOTE_C5, EIGHTH, true); + playNote(NOTE_C5, EIGHTH); + playNote(NOTE_B4, QUARTER); // Bar 7 + playNote(NOTE_G4, QUARTER); + playNote(NOTE_A4, QUARTER); + playNote(NOTE_G4, HALF); // Bar 8 + + celebrateSong(); + + // One second pause before repeating the loop and playing + delay(1000); +} diff --git a/libraries/Bluefruit52Lib/library.properties b/libraries/Bluefruit52Lib/library.properties index bace4631..abdaacd4 100644 --- a/libraries/Bluefruit52Lib/library.properties +++ b/libraries/Bluefruit52Lib/library.properties @@ -1,5 +1,5 @@ name=Adafruit Bluefruit nRF52 Libraries -version=0.20.5 +version=0.21.0 author=Adafruit maintainer=Adafruit sentence=Arduino library for nRF52-based Adafruit Bluefruit LE modules diff --git a/libraries/Bluefruit52Lib/src/bluefruit.cpp b/libraries/Bluefruit52Lib/src/bluefruit.cpp index 97651ad1..62549455 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.cpp +++ b/libraries/Bluefruit52Lib/src/bluefruit.cpp @@ -78,6 +78,17 @@ void usb_softdevice_post_enable(void) sd_power_usbdetected_enable(true); sd_power_usbpwrrdy_enable(true); sd_power_usbremoved_enable(true); + + uint32_t usb_reg; + sd_power_usbregstatus_get(&usb_reg); + + // Note: Detect event is possibly handled by usb_hardware_init() however depending on how fast + // Bluefruit.begin() is called, Ready event may or may not be handled before we disable the nrfx_power. + // USBPULLUP not enabled -> Ready event not yet handled + if ( (usb_reg & POWER_USBREGSTATUS_OUTPUTRDY_Msk) && (NRF_USBD->USBPULLUP == 0) ) + { + tusb_hal_nrf_power_event(NRFX_POWER_USB_EVT_READY); + } } #endif @@ -165,7 +176,7 @@ AdafruitBluefruit::AdafruitBluefruit(void) _ble_event_sem = NULL; _soc_event_sem = NULL; #ifdef ANT_LICENSE_KEY - _mprot_event_sem = NULL; //additiona semaphore for multiprotocol + _mprot_event_sem = NULL; #endif _led_blink_th = NULL; @@ -282,34 +293,31 @@ bool AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count) #if defined( USE_LFXO ) nrf_clock_lf_cfg_t clock_cfg = { - // LFXO - .source = NRF_CLOCK_LF_SRC_XTAL, - .rc_ctiv = 0, - .rc_temp_ctiv = 0, - .accuracy = NRF_CLOCK_LF_ACCURACY_20_PPM + // LFXO + .source = NRF_CLOCK_LF_SRC_XTAL, + .rc_ctiv = 0, + .rc_temp_ctiv = 0, + .accuracy = NRF_CLOCK_LF_ACCURACY_20_PPM }; #elif defined( USE_LFRC ) nrf_clock_lf_cfg_t clock_cfg = { - // LXRC - .source = NRF_CLOCK_LF_SRC_RC, - .rc_ctiv = 16, - .rc_temp_ctiv = 2, - .accuracy = NRF_CLOCK_LF_ACCURACY_250_PPM + // LXRC + .source = NRF_CLOCK_LF_SRC_RC, + .rc_ctiv = 16, + .rc_temp_ctiv = 2, + .accuracy = NRF_CLOCK_LF_ACCURACY_250_PPM }; #else #error Clock Source is not configured, define USE_LFXO or USE_LFRC according to your board in variant.h #endif - /*------------------------------------------------------------------ - ** BLE only Softdevices have 2-args sd_softdevice_enable() - ** BLE & ANT+ Softdevices have 3-args sd_softdevice_enable() - */ - #ifdef ANT_LICENSE_KEY + // Enable SoftDevice +#ifdef ANT_LICENSE_KEY VERIFY_STATUS( sd_softdevice_enable(&clock_cfg, nrf_error_cb, ANT_LICENSE_KEY), false ); -#else //#ifdef ANT_LICENSE_KEY +#else VERIFY_STATUS( sd_softdevice_enable(&clock_cfg, nrf_error_cb), false ); -#endif //#ifdef ANT_LICENSE_KEY +#endif #ifdef USE_TINYUSB usb_softdevice_post_enable(); @@ -454,13 +462,6 @@ bool AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count) ble_gap_conn_sec_mode_t sec_mode = BLE_SECMODE_OPEN; VERIFY_STATUS(sd_ble_gap_device_name_set(&sec_mode, (uint8_t const *) CFG_DEFAULT_NAME, strlen(CFG_DEFAULT_NAME)), false); - //------------- USB -------------// -#ifdef USE_TINYUSB - sd_power_usbdetected_enable(true); - sd_power_usbpwrrdy_enable(true); - sd_power_usbremoved_enable(true); -#endif - // Init Central role if (_central_count) Central.begin(); @@ -650,13 +651,21 @@ void AdafruitBluefruit::setRssiCallback(rssi_cb_t fp) *------------------------------------------------------------------*/ extern "C" void SD_EVT_IRQHandler(void) { - // Notify both BLE & SOC Task +#if CFG_SYSVIEW + SEGGER_SYSVIEW_RecordEnterISR(); +#endif + + // Notify both BLE & SOC & MultiProtocol (if any) Task xSemaphoreGiveFromISR(Bluefruit._soc_event_sem, NULL); xSemaphoreGiveFromISR(Bluefruit._ble_event_sem, NULL); + #ifdef ANT_LICENSE_KEY - // Notify parallel multiprotocol Task, if any if (Bluefruit._mprot_event_sem) xSemaphoreGiveFromISR(Bluefruit._mprot_event_sem, NULL); #endif + +#if CFG_SYSVIEW + SEGGER_SYSVIEW_RecordExitISR(); +#endif } /** diff --git a/libraries/Servo/src/Servo.h b/libraries/Servo/src/Servo.h index 50979dfb..af145caa 100644 --- a/libraries/Servo/src/Servo.h +++ b/libraries/Servo/src/Servo.h @@ -101,7 +101,7 @@ class Servo { public: Servo(); - uint8_t attach(int pin); // attach the given pin to the next free channel, sets pinMode, returns channel number or 0 if failure + uint8_t attach(int pin); // attach the given pin to the next free channel, sets pinMode, returns channel number or INVALID_SERVO if failure (zero is a valid channel number) uint8_t attach(int pin, int min, int max); // as above but also sets min and max values for writes. void detach(); void write(int value); // if value is < 200 its treated as an angle, otherwise as pulse width in microseconds @@ -111,8 +111,8 @@ public: bool attached(); // return true if this servo is attached, otherwise false private: uint8_t servoIndex; // index into the channel data for this servo - int16_t min; // minimum pulse in µs - int16_t max; // maximum pulse in µs + int16_t min; // minimum pulse in µs + int16_t max; // maximum pulse in µs HardwarePWM* pwm; }; diff --git a/libraries/Servo/src/nrf52/Servo.cpp b/libraries/Servo/src/nrf52/Servo.cpp index b9b86c02..4103c43f 100644 --- a/libraries/Servo/src/nrf52/Servo.cpp +++ b/libraries/Servo/src/nrf52/Servo.cpp @@ -14,6 +14,9 @@ You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Modified by Ha Thach for Adafruit Industries + Modified by Henry Gabryjelski to add ownershp support */ #if defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT) @@ -21,6 +24,10 @@ #include #include +enum +{ + SERVO_TOKEN = 0x76726553 // 'S' 'e' 'r' 'v' +}; static servo_t servos[MAX_SERVOS]; // static array of servo structures uint8_t ServoCount = 0; // the total number of attached servos @@ -32,7 +39,6 @@ Servo::Servo() } else { this->servoIndex = INVALID_SERVO; // too many servos } - this->pwm = NULL; } @@ -43,55 +49,98 @@ uint8_t Servo::attach(int pin) uint8_t Servo::attach(int pin, int min, int max) { - if (this->servoIndex < MAX_SERVOS) { - pinMode(pin, OUTPUT); // set servo pin to output - servos[this->servoIndex].Pin.nbr = pin; + if (this->servoIndex == INVALID_SERVO) { + return INVALID_SERVO; + } + bool succeeded = false; - if (min < MIN_PULSE_WIDTH) min = MIN_PULSE_WIDTH; - if (max > MAX_PULSE_WIDTH) max = MAX_PULSE_WIDTH; + if (min < MIN_PULSE_WIDTH) + { + min = MIN_PULSE_WIDTH; + } - //fix min if conversion to pulse cycle value is too low - if((min/DUTY_CYCLE_RESOLUTION)*DUTY_CYCLE_RESOLUTIONmin = min; - this->max = max; + if (max > MAX_PULSE_WIDTH) + { + max = MAX_PULSE_WIDTH; + } - servos[this->servoIndex].Pin.isActive = true; + //fix min if conversion to pulse cycle value is too low + if ( (min / DUTY_CYCLE_RESOLUTION) * DUTY_CYCLE_RESOLUTION < min ) + { + min += DUTY_CYCLE_RESOLUTION; + } + + this->min = min; + this->max = max; - // Adafruit, add pin to 1 of available Hw PWM - for(int i=0; iisOwner(SERVO_TOKEN) && HwPWMx[i]->addPin(pin) ) { - if ( HwPWMx[i]->addPin(pin) ) + this->pwm = HwPWMx[i]; + succeeded = true; + break; + } + } + + // if could not add to existing owned PWM modules, try to add to a new PWM module + if ( !succeeded ) + { + for ( int i = 0; i < HWPWM_MODULE_NUM; i++ ) + { + if ( HwPWMx[i]->takeOwnership(SERVO_TOKEN) && HwPWMx[i]->addPin(pin) ) { this->pwm = HwPWMx[i]; + succeeded = true; break; } } + } + + if ( succeeded ) + { + pinMode(pin, OUTPUT); + servos[this->servoIndex].Pin.nbr = pin; + servos[this->servoIndex].Pin.isActive = true; this->pwm->setMaxValue(MAXVALUE); this->pwm->setClockDiv(CLOCKDIV); + return this->servoIndex; + }else + { + return INVALID_SERVO; } - return this->servoIndex; } void Servo::detach() { + if (this->servoIndex == INVALID_SERVO) { + return; + } + uint8_t const pin = servos[this->servoIndex].Pin.nbr; + servos[this->servoIndex].Pin.isActive = false; - servos[this->servoIndex].Pin.isActive = false; - - // remove pin from HW PWM - this->pwm->removePin(pin); + // remove pin from HW PWM + HardwarePWM * pwm = this->pwm; + this->pwm = nullptr; + pwm->removePin(pin); + if (pwm->usedChannelCount() == 0) { + pwm->stop(); // disables peripheral so can release ownership + pwm->releaseOwnership(SERVO_TOKEN); + } } - void Servo::write(int value) -{ - if (value < 0) +{ + if (value < 0) { value = 0; - else if (value > 180) + } else if (value > 180) { value = 180; + } value = map(value, 0, 180, this->min, this->max); writeMicroseconds(value); @@ -100,9 +149,10 @@ void Servo::write(int value) void Servo::writeMicroseconds(int value) { - uint8_t pin = servos[this->servoIndex].Pin.nbr; - - if ( this->pwm ) this->pwm->writePin(pin, value/DUTY_CYCLE_RESOLUTION); + if (this->pwm) { + uint8_t pin = servos[this->servoIndex].Pin.nbr; + this->pwm->writePin(pin, value/DUTY_CYCLE_RESOLUTION); + } } int Servo::read() // return the value as degrees @@ -112,15 +162,18 @@ int Servo::read() // return the value as degrees int Servo::readMicroseconds() { - uint8_t pin = servos[this->servoIndex].Pin.nbr; - - if ( this->pwm ) return this->pwm->readPin(pin)*DUTY_CYCLE_RESOLUTION; - + if (this->pwm) { + uint8_t pin = servos[this->servoIndex].Pin.nbr; + return this->pwm->readPin(pin)*DUTY_CYCLE_RESOLUTION; + } return 0; } bool Servo::attached() { + if (this->servoIndex == INVALID_SERVO) { + return false; + } return servos[this->servoIndex].Pin.isActive; } diff --git a/libraries/Wire/Wire.h b/libraries/Wire/Wire.h index ba993d1c..2100c9d2 100755 --- a/libraries/Wire/Wire.h +++ b/libraries/Wire/Wire.h @@ -39,6 +39,7 @@ class TwoWire : public Stream void begin(uint8_t); void end(); void setClock(uint32_t); + void setPins(uint8_t pinSDA, uint8_t pinSCL); void beginTransmission(uint8_t); uint8_t endTransmission(bool stopBit); diff --git a/libraries/Wire/Wire_nRF52.cpp b/libraries/Wire/Wire_nRF52.cpp index 39043059..3875039e 100755 --- a/libraries/Wire/Wire_nRF52.cpp +++ b/libraries/Wire/Wire_nRF52.cpp @@ -46,7 +46,7 @@ TwoWire::TwoWire(NRF_TWIM_Type * p_twim, NRF_TWIS_Type * p_twis, IRQn_Type IRQn, } void TwoWire::begin(void) { - //Master Mode + //Main Mode master = true; *pincfg_reg(_uc_pinSCL) = ((uint32_t)GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos) @@ -72,7 +72,7 @@ void TwoWire::begin(void) { } void TwoWire::begin(uint8_t address) { - //Slave mode + //Secondary mode master = false; *pincfg_reg(_uc_pinSCL) = ((uint32_t)GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos) @@ -127,6 +127,12 @@ void TwoWire::setClock(uint32_t baudrate) { } } +void TwoWire::setPins(uint8_t pinSDA, uint8_t pinSCL) +{ + this->_uc_pinSDA = g_ADigitalPinMap[pinSDA]; + this->_uc_pinSCL = g_ADigitalPinMap[pinSCL]; +} + void TwoWire::end() { if (master) { diff --git a/libraries/Wire/examples/SFRRanger_reader/SFRRanger_reader.ino b/libraries/Wire/examples/SFRRanger_reader/SFRRanger_reader.ino index f41511c1..67007804 100755 --- a/libraries/Wire/examples/SFRRanger_reader/SFRRanger_reader.ino +++ b/libraries/Wire/examples/SFRRanger_reader/SFRRanger_reader.ino @@ -14,7 +14,7 @@ void setup() { - Wire.begin(); // join i2c bus (address optional for master) + Wire.begin(); // join i2c bus (address optional for main) Serial.begin(9600); // start serial communication at 9600bps while ( !Serial ) delay(10); // for nrf52840 with native usb } @@ -42,7 +42,7 @@ void loop() Wire.endTransmission(); // stop transmitting // step 4: request reading from sensor - Wire.requestFrom(112, 2); // request 2 bytes from slave device #112 + Wire.requestFrom(112, 2); // request 2 bytes from secondary device #112 // step 5: receive reading from sensor if(2 <= Wire.available()) // if two bytes were received diff --git a/libraries/Wire/examples/digital_potentiometer/digital_potentiometer.ino b/libraries/Wire/examples/digital_potentiometer/digital_potentiometer.ino index 38da1c54..54909907 100755 --- a/libraries/Wire/examples/digital_potentiometer/digital_potentiometer.ino +++ b/libraries/Wire/examples/digital_potentiometer/digital_potentiometer.ino @@ -16,7 +16,7 @@ void setup() { - Wire.begin(); // join i2c bus (address optional for master) + Wire.begin(); // join i2c bus (address optional for main) } byte val = 0; diff --git a/libraries/Wire/examples/master_reader/master_reader.ino b/libraries/Wire/examples/main_reader/main_reader.ino similarity index 57% rename from libraries/Wire/examples/master_reader/master_reader.ino rename to libraries/Wire/examples/main_reader/main_reader.ino index ee59610e..7927fab4 100755 --- a/libraries/Wire/examples/master_reader/master_reader.ino +++ b/libraries/Wire/examples/main_reader/main_reader.ino @@ -1,9 +1,9 @@ -// Wire Master Reader +// Wire Main Reader // by Nicholas Zambetti // Demonstrates use of the Wire library -// Reads data from an I2C/TWI slave device -// Refer to the "Wire Slave Sender" example for use with this +// Reads data from an I2C/TWI secondary device +// Refer to the "Wire Secondary Sender" example for use with this // Created 29 March 2006 @@ -14,16 +14,16 @@ void setup() { - Wire.begin(); // join i2c bus (address optional for master) + Wire.begin(); // join i2c bus (address optional for main) Serial.begin(9600); // start serial for output while ( !Serial ) delay(10); // for nrf52840 with native usb } void loop() { - Wire.requestFrom(2, 6); // request 6 bytes from slave device #2 + Wire.requestFrom(2, 6); // request 6 bytes from secondary device #2 - while(Wire.available()) // slave may send less than requested + while(Wire.available()) // secondary may send less than requested { char c = Wire.read(); // receive a byte as character Serial.print(c); // print the character diff --git a/libraries/Wire/examples/master_scan/master_scan.ino b/libraries/Wire/examples/main_scan/main_scan.ino similarity index 88% rename from libraries/Wire/examples/master_scan/master_scan.ino rename to libraries/Wire/examples/main_scan/main_scan.ino index 1567477d..37c37f15 100644 --- a/libraries/Wire/examples/master_scan/master_scan.ino +++ b/libraries/Wire/examples/main_scan/main_scan.ino @@ -7,7 +7,7 @@ void setup() { Serial.begin(115200); // start serial for output while ( !Serial ) delay(10); // for nrf52840 with native usb - wi->begin(); // join i2c bus (address optional for master) + wi->begin(); // join i2c bus (address optional for main) } void loop() diff --git a/libraries/Wire/examples/master_writer/master_writer.ino b/libraries/Wire/examples/main_writer/main_writer.ino similarity index 70% rename from libraries/Wire/examples/master_writer/master_writer.ino rename to libraries/Wire/examples/main_writer/main_writer.ino index ccaa0361..988a3089 100755 --- a/libraries/Wire/examples/master_writer/master_writer.ino +++ b/libraries/Wire/examples/main_writer/main_writer.ino @@ -1,9 +1,9 @@ -// Wire Master Writer +// Wire Main Writer // by Nicholas Zambetti // Demonstrates use of the Wire library -// Writes data to an I2C/TWI slave device -// Refer to the "Wire Slave Receiver" example for use with this +// Writes data to an I2C/TWI secondary device +// Refer to the "Wire Secondary Receiver" example for use with this // Created 29 March 2006 @@ -14,7 +14,7 @@ void setup() { - Wire.begin(); // join i2c bus (address optional for master) + Wire.begin(); // join i2c bus (address optional for main) } byte x = 0; diff --git a/libraries/Wire/examples/slave_receiver/slave_receiver.ino b/libraries/Wire/examples/secondary_receiver/secondary_receiver.ino similarity index 81% rename from libraries/Wire/examples/slave_receiver/slave_receiver.ino rename to libraries/Wire/examples/secondary_receiver/secondary_receiver.ino index c0c26286..77e9590c 100755 --- a/libraries/Wire/examples/slave_receiver/slave_receiver.ino +++ b/libraries/Wire/examples/secondary_receiver/secondary_receiver.ino @@ -1,9 +1,9 @@ -// Wire Slave Receiver +// Wire Secondary Receiver // by Nicholas Zambetti // Demonstrates use of the Wire library -// Receives data as an I2C/TWI slave device -// Refer to the "Wire Master Writer" example for use with this +// Receives data as an I2C/TWI secondary device +// Refer to the "Wire Main Writer" example for use with this // Created 29 March 2006 @@ -25,7 +25,7 @@ void loop() delay(100); } -// function that executes whenever data is received from master +// function that executes whenever data is received from main // this function is registered as an event, see setup() void receiveEvent(int howMany) { diff --git a/libraries/Wire/examples/slave_sender/slave_sender.ino b/libraries/Wire/examples/secondary_sender/secondary_sender.ino similarity index 67% rename from libraries/Wire/examples/slave_sender/slave_sender.ino rename to libraries/Wire/examples/secondary_sender/secondary_sender.ino index d3b238af..974ea45d 100755 --- a/libraries/Wire/examples/slave_sender/slave_sender.ino +++ b/libraries/Wire/examples/secondary_sender/secondary_sender.ino @@ -1,9 +1,9 @@ -// Wire Slave Sender +// Wire Secondary Sender // by Nicholas Zambetti // Demonstrates use of the Wire library -// Sends data as an I2C/TWI slave device -// Refer to the "Wire Master Reader" example for use with this +// Sends data as an I2C/TWI secondary device +// Refer to the "Wire Main Reader" example for use with this // Created 29 March 2006 @@ -23,10 +23,10 @@ void loop() delay(100); } -// function that executes whenever data is requested by master +// function that executes whenever data is requested by main // this function is registered as an event, see setup() void requestEvent() { Wire.write("hello "); // respond with message of 6 bytes - // as expected by master + // as expected by main } diff --git a/platform.txt b/platform.txt index fddd0314..3c602a26 100644 --- a/platform.txt +++ b/platform.txt @@ -17,7 +17,7 @@ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA name=Adafruit nRF52 Boards -version=0.20.5 +version=0.21.0 # Compile variables # ----------------- @@ -28,29 +28,27 @@ compiler.warning_flags.default= compiler.warning_flags.more=-Wall compiler.warning_flags.all=-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Wno-pointer-arith +# Allow changing optimization settings via platform.local.txt / boards.local.txt +compiler.optimization_flag=-Ofast + compiler.path={runtime.tools.arm-none-eabi-gcc.path}/bin/ compiler.c.cmd=arm-none-eabi-gcc -compiler.c.flags=-mcpu={build.mcu} -mthumb -c -Ofast -g {compiler.warning_flags} {build.float_flags} -std=gnu11 -ffunction-sections -fdata-sections -nostdlib --param max-inline-insns-single=500 -MMD - +compiler.c.flags=-mcpu={build.mcu} -mthumb -c -g {compiler.warning_flags} {build.float_flags} -std=gnu11 -ffunction-sections -fdata-sections -nostdlib --param max-inline-insns-single=500 -MMD compiler.c.elf.cmd=arm-none-eabi-gcc -compiler.c.elf.flags=-Ofast -g -Wl,--gc-sections -save-temps - +compiler.c.elf.flags={compiler.optimization_flag} -Wl,--gc-sections -save-temps compiler.S.cmd=arm-none-eabi-gcc -compiler.S.flags=-mcpu={build.mcu} -mthumb -mabi=aapcs -Ofast -g -c {build.float_flags} -x assembler-with-cpp +compiler.S.flags=-mcpu={build.mcu} -mthumb -mabi=aapcs {compiler.optimization_flag} -g -c {build.float_flags} -x assembler-with-cpp compiler.cpp.cmd=arm-none-eabi-g++ -compiler.cpp.flags=-mcpu={build.mcu} -mthumb -c -Ofast -g {compiler.warning_flags} {build.float_flags} -std=gnu++11 -ffunction-sections -fdata-sections -fno-threadsafe-statics -nostdlib --param max-inline-insns-single=500 -fno-rtti -fno-exceptions -MMD +compiler.cpp.flags=-mcpu={build.mcu} -mthumb -c -g {compiler.warning_flags} {build.float_flags} -std=gnu++11 -ffunction-sections -fdata-sections -fno-threadsafe-statics -nostdlib --param max-inline-insns-single=500 -fno-rtti -fno-exceptions -MMD compiler.ar.cmd=arm-none-eabi-ar compiler.ar.flags=rcs - compiler.objcopy.cmd=arm-none-eabi-objcopy compiler.objcopy.eep.flags=-O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 - compiler.elf2bin.flags=-O binary compiler.elf2bin.cmd=arm-none-eabi-objcopy compiler.elf2hex.flags=-O ihex compiler.elf2hex.cmd=arm-none-eabi-objcopy - compiler.ldflags=-mcpu={build.mcu} -mthumb {build.float_flags} -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align --specs=nano.specs --specs=nosys.specs compiler.size.cmd=arm-none-eabi-size @@ -66,7 +64,7 @@ nordic.path={build.core.path}/nordic # build.logger_flags and build.sysview_flags are intentionally empty, # to allow modification via a user's own boards.local.txt or platform.local.txt files. -build.flags.nrf= -DSOFTDEVICE_PRESENT -DARDUINO_NRF52_ADAFRUIT -DNRF52_SERIES -DDX_CC_TEE -DLFS_NAME_MAX=64 -Ofast {build.debug_flags} {build.logger_flags} {build.sysview_flags} "-I{build.core.path}/cmsis/Core/Include" "-I{nordic.path}" "-I{nordic.path}/nrfx" "-I{nordic.path}/nrfx/hal" "-I{nordic.path}/nrfx/mdk" "-I{nordic.path}/nrfx/soc" "-I{nordic.path}/nrfx/drivers/include" "-I{nordic.path}/nrfx/drivers/src" "-I{nordic.path}/softdevice/{build.sd_name}_nrf52_{build.sd_version}_API/include" "-I{nordic.path}/softdevice/{build.sd_name}_nrf52_{build.sd_version}_API/include/nrf52" "-I{rtos.path}/Source/include" "-I{rtos.path}/config" "-I{rtos.path}/portable/GCC/nrf52" "-I{rtos.path}/portable/CMSIS/nrf52" "-I{build.core.path}/sysview/SEGGER" "-I{build.core.path}/sysview/Config" "-I{build.core.path}/TinyUSB" "-I{build.core.path}/TinyUSB/Adafruit_TinyUSB_ArduinoCore" "-I{build.core.path}/TinyUSB/Adafruit_TinyUSB_ArduinoCore/tinyusb/src" +build.flags.nrf= -DSOFTDEVICE_PRESENT -DARDUINO_NRF52_ADAFRUIT -DNRF52_SERIES -DDX_CC_TEE -DLFS_NAME_MAX=64 {compiler.optimization_flag} {build.debug_flags} {build.logger_flags} {build.sysview_flags} "-I{build.core.path}/cmsis/Core/Include" "-I{nordic.path}" "-I{nordic.path}/nrfx" "-I{nordic.path}/nrfx/hal" "-I{nordic.path}/nrfx/mdk" "-I{nordic.path}/nrfx/soc" "-I{nordic.path}/nrfx/drivers/include" "-I{nordic.path}/nrfx/drivers/src" "-I{nordic.path}/softdevice/{build.sd_name}_nrf52_{build.sd_version}_API/include" "-I{nordic.path}/softdevice/{build.sd_name}_nrf52_{build.sd_version}_API/include/nrf52" "-I{rtos.path}/Source/include" "-I{rtos.path}/config" "-I{rtos.path}/portable/GCC/nrf52" "-I{rtos.path}/portable/CMSIS/nrf52" "-I{build.core.path}/sysview/SEGGER" "-I{build.core.path}/sysview/Config" "-I{build.core.path}/TinyUSB" "-I{build.core.path}/TinyUSB/Adafruit_TinyUSB_ArduinoCore" "-I{build.core.path}/TinyUSB/Adafruit_TinyUSB_ArduinoCore/tinyusb/src" # usb flags build.flags.usb= -DUSBCON -DUSE_TINYUSB -DUSB_VID={build.vid} -DUSB_PID={build.pid} '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}' @@ -77,9 +75,9 @@ compiler.c.elf.extra_flags= compiler.cpp.extra_flags= compiler.S.extra_flags= compiler.ar.extra_flags= +compiler.libraries.ldflags= compiler.elf2bin.extra_flags= compiler.elf2hex.extra_flags= -compiler.libraries.ldflags= # Compile patterns @@ -98,7 +96,7 @@ recipe.S.o.pattern="{compiler.path}{compiler.S.cmd}" {compiler.S.flags} -DF_CPU= recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{archive_file_path}" "{object_file}" ## Combine gc-sections, archives, and objects -recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" "-L{build.path}" "-L{build.core.path}/linker" "-T{build.ldscript}" {compiler.c.elf.flags} {compiler.c.elf.extra_flags} "-Wl,-Map,{build.path}/{build.project_name}.map" {compiler.ldflags} -o "{build.path}/{build.project_name}.elf" {object_files} -Wl,--start-group -lm "{build.path}/{archive_file}" {compiler.libraries.ldflags} -Wl,--end-group +recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" "-L{build.path}" {compiler.c.elf.flags} {compiler.c.elf.extra_flags} "-L{build.core.path}/linker" "-T{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" {compiler.ldflags} -o "{build.path}/{build.project_name}.elf" {object_files} -Wl,--start-group -lm "{build.path}/{archive_file}" {compiler.libraries.ldflags} -Wl,--end-group ## Create output (bin file) #recipe.objcopy.bin.pattern="{compiler.path}{compiler.elf2bin.cmd}" {compiler.elf2bin.flags} {compiler.elf2bin.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.bin" diff --git a/tools/build_all.py b/tools/build_all.py index 0df2166e..2b2ec52e 100644 --- a/tools/build_all.py +++ b/tools/build_all.py @@ -2,19 +2,24 @@ import os import glob import sys import subprocess +from subprocess import Popen, PIPE import time +SUCCEEDED = "\033[32msucceeded\033[0m" +FAILED = "\033[31mfailed\033[0m" +SKIPPED = "\033[33mskipped\033[0m" +WARNING = "\033[31mwarnings\033[0m" + all_warnings = False exit_status = 0 success_count = 0 fail_count = 0 skip_count = 0 -build_format = '| {:20} | {:35} | {:9} | {:6} |' +build_format = '| {:20} | {:35} | {:18} | {:6} |' build_separator = '-' * 83 default_boards = [ 'cluenrf52840', 'cplaynrf52840', 'feather52832', 'feather52840', 'feather52840sense', 'itsybitsy52840' ] - build_boards = [] # build all variants if input not existed @@ -23,6 +28,9 @@ if len(sys.argv) > 1: else: build_boards = default_boards +all_examples = list(glob.iglob('libraries/**/*.ino', recursive=True)) +all_examples.sort() + def errorOutputFilter(line): if len(line) == 0: return False @@ -39,32 +47,29 @@ def build_examples(variant): print(build_separator) print('| {:^79} |'.format('Board ' + variant)) print(build_separator) - print(build_format.format('Library', 'Example', 'Result', 'Time')) + print(build_format.format('Library', 'Example', '\033[39mResult\033[0m', 'Time')) print(build_separator) fqbn = "adafruit:nrf52:{}:softdevice={},debug=l0".format(variant, 's140v6' if variant != 'feather52832' else 's132v6') - all_sketches = list(glob.iglob('libraries/**/*.ino', recursive=True)) - all_sketches.sort() - - for sketch in all_sketches: + for sketch in all_examples: start_time = time.monotonic() # Skip if contains: ".board.test.skip" or ".all.test.skip" # Skip if not contains: ".board.test.only" for a specific board sketchdir = os.path.dirname(sketch) if os.path.exists(sketchdir + '/.all.test.skip') or os.path.exists(sketchdir + '/.' + variant + '.test.skip'): - success = "\033[33mskipped\033[0m " + success = SKIPPED elif glob.glob(sketchdir+"/.*.test.only") and not os.path.exists(sketchdir + '/.' + variant + '.test.only'): - success = "\033[33mskipped\033[0m " + success = SKIPPED else: # TODO - preferably, would have STDERR show up in **both** STDOUT and STDERR. # preferably, would use Python logging handler to get both distinct outputs and one merged output # for now, split STDERR when building with all warnings enabled, so can detect warning/error output. if all_warnings: - build_result = subprocess.run("arduino-cli compile --warnings all --fqbn {} {}".format(fqbn, sketch), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + build_result = subprocess.run("arduino-cli compile --warnings all --fqbn {} {}".format(fqbn, sketch), shell=True, stdout=PIPE, stderr=PIPE) else: - build_result = subprocess.run("arduino-cli compile --warnings default --fqbn {} {}".format(fqbn, sketch), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + build_result = subprocess.run("arduino-cli compile --warnings default --fqbn {} {}".format(fqbn, sketch), shell=True, stdout=PIPE, stderr=PIPE) # get stderr into a form where len(warningLines) indicates a true warning was output to stderr warningLines = []; @@ -74,20 +79,21 @@ def build_examples(variant): if build_result.returncode != 0: exit_status = build_result.returncode - success = "\033[31mfailed\033[0m " + success = FAILED fail_count += 1 elif len(warningLines) != 0: exit_status = -1 - success = "\033[31mwarnings\033[0m " + success = WARNING fail_count += 1 else: - success = "\033[32msucceeded\033[0m" + success = SUCCEEDED success_count += 1 build_duration = time.monotonic() - start_time + print(build_format.format(sketch.split(os.path.sep)[1], os.path.basename(sketch), success, '{:5.2f}s'.format(build_duration))) - if success != "\033[33mskipped\033[0m ": + if success != SKIPPED: if build_result.returncode != 0: print(build_result.stdout.decode("utf-8")) if (build_result.stderr): @@ -98,7 +104,6 @@ def build_examples(variant): else: skip_count += 1 - build_time = time.monotonic() for board in build_boards: @@ -106,7 +111,7 @@ for board in build_boards: print(build_separator) build_time = time.monotonic() - build_time -print("Build Summary: {} \033[32msucceeded\033[0m, {} \033[31mfailed\033[0m, {} \033[33mskipped\033[0m and took {:.2f}s".format(success_count, fail_count, skip_count, build_time)) +print("Build Summary: {} {}, {} {}, {} {} and took {:.2f}s".format(success_count, SUCCEEDED, fail_count, FAILED, skip_count, SKIPPED, build_time)) print(build_separator) sys.exit(exit_status)