nRF5 action!


  • Hero Member

    So, I figure the way to get started is to do something "easy", like maybe use the PPI to blink an LED.

    We want the lower power RTC, not the system clock. We want to use the RTC TICK event, so that the mpu can be powered down while the PPI is running.

    So, because I want a timer event every 100ms, that means the prescaler should be 3276.


  • Hero Member

    So, just starting on this, where I'm at is:

    #include <nrf.h>
    #include <MySensors.h>
    
    
    #define LED_PIN 18
    
    bool toggle=false;  //track whether or not to toggle the LED pin
    
    void setup() {
      NRF_CLOCK->LFCLKSRC=1;  //use the crystal oscillator.
      NRF_CLOCK->TASKS_LFCLKSTART=1;  //start the crystal oscillator clock
      while (!(NRF_CLOCK->EVENTS_LFCLKSTARTED)) {}  //busy-wait until the clock is confirmed started.
    
      NRF_RTC1->TASKS_STOP=1;  //stop the RTC so that we can set the prescaler
      NRF_RTC1->PRESCALER=3276;  //once per 100ms
      NRF_RTC1->TASKS_START=1;  //start the RTC so that we can start getting TICK events
    
      hwPinMode(LED_PIN,OUTPUT_H0H1);  //establish P0.18 as the LED pin.
    }
    
    void loop() {
      if (NRF_RTC1->EVENTS_TICK) {
        toggle=!toggle;
        digitalWrite(LED_PIN,toggle);
      }
    }
    

    Unfortunately, this does not work because (NRF_RTC1->EVENTS_TICK) always reads as zero. Not sure why(?).



  • @NeverDie you will need long range capabilities on both sides of the link. So two preview kits work great. Long range is supported by SDK 14 and the current softdevice.



  • @scalz the nRF52832 has a hotter receiver. ( better sensitivity.) at 1 mb/ s then the nRF24l series. Overall link Budget is better. 840 even better with a 8dB output.


  • Hardware Contributor

    @Jokgi
    of course I agree !
    that's why in the past i preferred rfm69 modules (better range of course, but more power hungry). 832 being better than nrf24, i'm now using it. And I also like the 840dk (neat package) 👍
    That said, if i remember well, nrf52832 is not fully BLE5 long range compatible as 840 is.


  • Hero Member

    @Jokgi said in nRF5 Bluetooth action!:

    @NeverDie you will need long range capabilities on both sides of the link. So two preview kits work great. Long range is supported by SDK 14 and the current softdevice.

    I'm not disagreeing, but presently modules for it (other than the preview DK) aren't yet available. Meanwhile, hopefully nearly all of what's being learned here about the nRF52832 will be of direct relevance. For instance: PPI.


  • Hero Member

    @NeverDie said in nRF5 Bluetooth action!:

    Unfortunately, this does not work because (NRF_RTC1->EVENTS_TICK) always reads as zero. Not sure why(?).

    It should be working, but it isn't. Nor do I see a way to check it with an oscilliscope. So, my current theory is that it gets set but cleared so quickly that it can't be read by the MCU. So, the next step will be to assume that it is, in fact, working, and to use it as a PPI trigger, which is what this is all building toward anyway.

    On the other hand, perhaps there's an easy way to have the EVENTS_TICK set an interrupt bit, which would persist until it was cleared? Hmmm. No, not quite, but there is INTENSET, which will set an interrupt on an EVENT_TICK. That will do. Exactly which interrupt gets triggered though? Figure 46 shows that an IRQ signal is sent to NVIC ( the Nested Vectored Interrupt Controller). According to the table in sectoin 7.3, the NVIC has 37 interrupt vectors. According to section 15.8:

    A peripheral only occupies one interrupt, and the interrupt number follows the peripheral ID. For example, the
    peripheral with ID=4 is connected to interrupt number 4 in the Nested Vectored Interrupt Controller (NVIC).

    So, based on that, we need to know the ID number for the RTC, and then we'll know which interrupt number to track. According to Table 10, the Peripheral ID for the RTC is 11 (well, at least it is for the RTC0, so I will recode to use RTC0 instead of RTC1).

    Now, according to Table 10, the memory location that corresponds to Peripheral ID 11 is 0x4000B000. Therefore, it is this memory location we need to examine to know if a TICK interrupt has occured.


  • Hero Member

    Close, but no cigar. What I found out is that if I set the TICK interrupt with:

          NRF_RTC0->INTENSET=1;  //set the TICK interrupt bit
    

    then at the following memory addresses, the value stored there immediately becomes 1:
    4000B300
    4000B304
    4000B308

    and if I clear the TICK interrupt with:

          NRF_RTC0->INTENCLR=1;  //clear the TICK interrupt bit
    

    then the values at those same memory addresses immediately becomes zero. I can toggle back and forth as much as I want, and this is always true.

    However, none of this is telling me whether the TICK interrupt has actually triggered. Where do I find that?

    Based on the current pre-scaler, COUNTER increments once every TICK (i.e. once every 100ms). However, is there an actual TICK flag somewhere that goes high at those times and then low again after getting cleared? Or, is it only accessible indirectly by using PPI?


  • Hero Member

    OK, I came up with a simple equivalent. Basically, every time COUNTER is incremented, I reset it to zero. It then effectively acts much the way a TICK should. For whatever reason, once EVENTS_TICK goes high, it just stays high forever. So, it doesn't seem very useful per se, though maybe there's a way to clear it that I haven't yet found.


  • Hero Member

    Strangely enough, the overflow is the same: once it goes HIGH, it stays that way:
    https://pastebin.com/vypuVJeh

    So, I would think there must be some way (?) to clear them.


  • Hero Member

    I found the answer. Unlike EVENTS in other peripherals, which are read-only, the EVENTS in RTC are RW. So, the way you clear the TICK and OVRFLW events is just by setting them to zero manually:
    e.g.

    NRF_RTC0->EVENTS_TICK=0;
    

    LOL. Of course, the DS never mentions this.

    In any case, with that change, it can now work properly:
    https://pastebin.com/nHWAGFkd


  • Hero Member

    However, it does raise the question: if I were to use EVENTS_TICK to trigger some PPI actions, how could PPI also be used to set EVENTS_TICK back to zero so that those actions can be repeated on the next TICK? I haven't yet found an PPI TASKS that can directly manipulate, or even just clear, a particular memory location.


  • Hero Member

    Since there are no apparent shortcuts pertaining to the RTC, it looks as though all non-MCU manipulations will have to happen via PPI.

    I don't see how to clear a TICK using PPI, so I think the simplest thing would be clearing the counter back to zero if it hits one.

    If there's no way to do this basic thing, then I see no way to have a "listen mode" equivalent for the nRF52832 that runs via PPI.

    So, adapting what @d00616 wrote earlier, maybe the PPI code to do that would be:

      #define CHANNEL (1)
      NRF_PPI->CH[CHANNEL].EEP = (uint32_t)&NRF_RTC0->COUNTER;  //when COUNTER goes from zero to one.
      NRF_PPI->CH[CHANNEL].TEP = (uint32_t)&NRF_RTC0->TASKS_CLEAR;  //clear COUNTER back to zero.
      NRF_PPI->CHENSET = (1 << CHANNEL) ;
    

    Well, it does compile, but it doesn't work. 😞 I think it doesn't work because COUNTER is not an event.

    Unfortunately, changing COUNTER to EVENTS_TICK fails also:

      NRF_PPI->CH[0].EEP = (uint32_t)&NRF_RTC0->EVENTS_TICK;  //when TICK occurs.
      NRF_PPI->CH[0].TEP = (uint32_t)&NRF_RTC0->TASKS_CLEAR;  //clear COUNTER back to zero.
      NRF_PPI->CHENSET=1;   //Enable Channel 0.
    

    Unfortunately, the PPI Example code from Nordic's SDK doesn't look even remotely similar to what we're doing here.

    Anyhow, the last thing I tried was this:

      NRF_RTC0->INTENSET=1;  //Allows TICK to create an interrupt.
      NRF_PPI->CH[0].EEP = (uint32_t)&NRF_RTC0->EVENTS_TICK;  //when TICK occurs.
      NRF_PPI->CH[0].TEP = (uint32_t)&NRF_RTC0->TASKS_CLEAR;  //clear COUNTER back to zero.
      NRF_PPI->CHENSET=1; //enable Channel 0.
    

    hoping that it might make a difference, but it still fails. Why? What is wrong with it?



  • @NeverDie said in nRF5 Bluetooth action!:

    EVENTS_TICK

    From the datasheet:

    15.6 Events
    Events are used to notify peripherals and the CPU about events that have happened, for example, a state
    change in a peripheral. A peripheral may generate multiple events with each event having a separate
    register in that peripheral’s event register group.
    An event is generated when the peripheral itself toggles the corresponding event signal, and the event
    register is updated to reflect that the event has been generated. See Figure 10: Tasks, events, shortcuts,
    and interrupts on page 68. An event register is only cleared when firmware writes a '0' to it.
    Events can be generated by the peripheral even when the event register is set to '1'.
    

    Maybe I don't get the problem here, but the way I see it, you have to actively write a '0' to the event register to clear it, but in fact it shouldn't matter, because the timer can nevertheless generate an event.


  • Hero Member

    @Uhrheber said in nRF5 Bluetooth action!:

    you have to actively write a '0' to the event register to clear it

    This is right. I later confirmed it (see above), but thank you for the passage in the datasheet. I could have sworn that somewhere the DS said that events were read-only, but the passage you quoted contradicts that recollection. So, thank you again.

    Any thoughts on the PPI question (directly above your post)?



  • So, you want to shut the CPU down, leaving only RTC and PPI running, and generate a wakeup event every 100ms, did I get that right?
    I didn't dig that far into the datasheet, and also I don't have any board for testing (yet).

    Also, I didn't check whether the debugger will survive a power down/up cycle.
    Does it?


  • Hero Member

    @Uhrheber said in nRF5 Bluetooth action!:

    So, you want to shut the CPU down, leaving only RTC and PPI running, and generate a wakeup event every 100ms, did I get that right?

    Yes. I hope to do more than only just that using the PPI while the CPU sleeps, but that does seem like the first step.


  • Hero Member

    @Uhrheber said in nRF5 Bluetooth action!:

    Also, I didn't check whether the debugger will survive a power down/up cycle.
    Does it?

    Don't know. I haven't started using the debugger yet.



  • In this example from Nordic, they're using the RTC's compare interrupt:
    http://infocenter.nordicsemi.com/index.jsp?topic=%2Fcom.nordic.infocenter.nrf52%2Fdita%2Fnrf52%2Fapp_example%2Fsolar_beacon%2Fintroduction.html

    Average current consumption is 19µA, including sensor reading, data transmission and Bluetooth advertizing.
    Not too bad, I'd say.


  • Hero Member

    @Uhrheber said in nRF5 Bluetooth action!:

    In this example from Nordic, they're using the RTC's compare interrupt:

    Yeah, but that part of it is running on the MCU, not the PPI.

    void RTC0_IRQHandler(void)
    {
        NRF_RTC0->EVTENCLR = (RTC_EVTENCLR_COMPARE0_Enabled << RTC_EVTENCLR_COMPARE0_Pos);
        NRF_RTC0->INTENCLR = (RTC_INTENCLR_COMPARE0_Enabled << RTC_INTENCLR_COMPARE0_Pos);
        NRF_RTC0->EVENTS_COMPARE[0] = 0;
        
        m_rtc_isr_called = true;    
    }
    

  • Hero Member

    Anyhow, I don't see a way to do an RFM69 style "listen mode" using just the PPI on the nRF52832. I think this may be a dead end.


  • Hero Member

    Looks as though there is EVTEN, which on the RTC needs to be enabled to get the PPI to work. Shown in Figure 46.


  • Hero Member

    Bingo! Added this, and it now works:

      NRF_RTC0->EVTENSET=1;  //enable routing of RTC events to PPI.
    

    🙂


  • Hero Member

    More good news. As far as the PPI is concerned, an event such as OVRFLW is still just as active as if it had been cleared, even if it hasn't. Here's the proof:

      NRF_RTC0->TASKS_TRIGOVRFLW=1;
    
      NRF_PPI->CH[0].EEP = (uint32_t)&NRF_RTC0->EVENTS_OVRFLW;  //when RTC overflow occurs.
      NRF_PPI->CH[0].TEP = (uint32_t)&NRF_RTC0->TASKS_TRIGOVRFLW;  //set COUNTER to be near another overflow.
      NRF_PPI->CHENSET=1; //enable Channel 0.
      NRF_RTC0->EVTENSET=B10;  //enable routing of RTC OVRFLW events to PPI.
    

    functions as follows:
    https://pastebin.com/Z09e7tMK


  • Contest Winner

    @NeverDie said in nRF5 Bluetooth action!:

    Anyhow, I don't see a way to do an RFM69 style "listen mode" using just the PPI on the nRF52832. I think this may be a dead end.

    It looks like you are implementing a new radio protocol and you are coming forward.

    What do you think about forking the MY_RADIO_NRF5_ESB into a new one? The nRF5 code is designed to implement additional protocols for nRF5.

    If you remove the address reverse code, there are no OTA conflicts with the ESB protocol. The address width can be enhanced by 2 bits to allow better AES encryption and lager packages.


  • Hero Member

    @d00616 said in nRF5 Bluetooth action!:

    It looks like you are implementing a new radio protocol and you are coming forward.

    Yes, I'm presently focused on trying to reduce the amount of energy consumed by probably the hardest case of all: a battery/solar/supercap receiver that needs to be both highly responsive (within 100ms) and listening 24/7 without running out of juice. Of course, one can always throw bigger batteries or bigger solar panels at the problem, but I'm first trying to be as ultra efficient as possible so that won't be necessary. The benefit will be smaller size, not to mention lower cost.

    I am posting my findings as I go because there is precious little in the way of working examples, so I may yet still be of help to others in that way. From the view count, it does seem that people are reading this thread, even if not many are posting.


  • Contest Winner

    @NeverDie said in nRF5 Bluetooth action!:

    I am posting my findings as I go because there is precious little in the way of working examples, so I may yet still be of help to others in that way. From the view count, it does seem that people are reading this thread, even if not many are posting.

    btw. Thank you for sharing you knowledge here. In my option this is very helpful for me.


  • Hero Member

    @d00616

    I think you'll find this interesting:

      NRF_RADIO->TASKS_DISABLE=1;  //sleep the radio
      while (NRF_RADIO->STATE) {}; //wait until radio is DISABLED (i.e. STATE=0);
    
      NRF_RTC0->TASKS_TRIGOVRFLW=1;  //set COUNTER to trigger an overflow after 16 TICKS.
    
      NRF_PPI->CH[0].EEP = (uint32_t)&NRF_RTC0->EVENTS_OVRFLW;  //when RTC overflow occurs.
      NRF_PPI->CH[0].TEP = (uint32_t)&NRF_RTC0->TASKS_TRIGOVRFLW;  //set COUNTER to be near another overflow.
      NRF_PPI->FORK[0].TEP = (uint32_t)&NRF_RADIO->TASKS_RXEN;  //turn on the radio receiver
      NRF_RTC0->EVTENSET=B10;  //enable routing of RTC OVRFLW events to PPI.
    
      //When Radio state TXIDLE is reached, perform an RSSI sample.  There is no shortcut for this, so we must use PPI.
      NRF_PPI->CH[1].EEP = (uint32_t)&NRF_RADIO->EVENTS_READY;  //After event READY, radio shall be in state TXIDLE.
      NRF_PPI->CH[1].TEP = (uint32_t)&NRF_RADIO->TASKS_RSSISTART; //Take the RSSI sample
    
      NRF_PPI->CH[2].EEP = (uint32_t)&NRF_RADIO->EVENTS_RSSIEND;  //After event RSSIEND, RSSI measurement is finished and radio will be in state TXIDLE.
      NRF_PPI->CH[2].TEP = (uint32_t)&NRF_RADIO->TASKS_DISABLE; //Sleep the radio
      NRF_PPI->CHENSET=B111; //enable Channel 2, Channel 1 and Channel 0.
      sleep(1000000000);  //sleep a million seconds so as not to interfere with current measurements.
    

    It sleeps the MCU, and using just PPI, it wakes up the radio every 16 TICKS (each tick is 100ms) and measures the RSSI. Then it puts the radio back to sleep.

    So, looking at the current consumption from a macro viewpoint, it's this:
    0_1505333124723_NewFile2.jpg

    The taller peaks are when the RSSI measurements happen. Zooming in on one of the RSSI measurements, the current consumption is this:

    0_1505333166548_NewFile1.jpg

    As you can see, very little, and only for a very short time!


  • Hero Member

    So all I need now is a way for the PPI to compare the RSSI measurement it obtained above with a threshold benchmark to decide whether or not to wake the MCU, which can take it from there. From that point onward, the regular ESB code could be used. 🙂


  • Hero Member

    Nordic could have taken this a lot farther if they had included some comparison tasks, so that the PPI could make decisions about what to do next. However, I don't see that there are any that can be used for comparing an RSSI measurement against a benchmark. Too bad. 😞



  • Great that it works.

    But I'm not so convinced about the usefulness of this method, anyways.
    I know that a lot of receivers use simple RSSI measurement to implement a low power listening mode, but when you are in a noisy environment, the system will wake up quite often, draining the battery fast. And unless you live in a very remote area, 2.4 GHz IS a noisy environment.


  • Hero Member

    @Uhrheber said in nRF5 Bluetooth action!:

    Great that it works.

    But I'm not so convinced about the usefulness of this method, anyways.
    I know that a lot of receivers use simple RSSI measurement to implement a low power listening mode, but when you are in a noisy environment, the system will wake up quite often, draining the battery fast. And unless you live in a very remote area, 2.4 GHz IS a noisy environment.

    And your better alternative is....?


  • Hardware Contributor

    @NeverDie said in nRF5 Bluetooth action!:

    From the view count, it does seem that people are reading this thread, even if not many are posting.

    I'm following your work with interest of course 😉 On my side i'm pretty busy on other stuff (rpi and my HA) so i'm missing time for try..I'll be back soon on this!

    @NeverDie said in nRF5 Bluetooth action!:

    t what to do next. However, I don't see

    I thought too, about implementing this kind of listenmode for rfm69 in my HA. What i don't like so much, is I think i would need a dedicated node for the scheduling and it complicates a bit thing. I'm not fond of using gw resources for the wakeup broadcast.
    I think, maybe I'm wrong, that, ideally, the best would be "time slots" so everything would be in sync, no flooding broadcast, lost msg, collisions etc.. but that implies some work regarding the lib, and some hw issues (with simple 8bits without precise rtc).

    Keep the good work!



  • @NeverDie None, unfortunately. The manufacturer would have to take care of that, by implementing a low power mode in the receiver (maybe with reduced sensitivity), and an additional low power wakeup pattern detector.
    There are transceiver that can do that, but the nRF52 can't.

    Some of the simple 433MHz OOK receivers have a low current consumption, but they're pretty insensitive, high bandwidth and low speed, so of not much use except switching some battery powered lamp, or such.

    Some time ago I searched for a transceiver with low current receive mode, to use it in a battery powered node, that could be woken up by rf, but found nothing.
    All of the standard data transceivers are pretty power hungry.





  • @Toyman Indeed:

    Nonetheless, larger AA or AAA type
    batteries are still required to reliably achieve operation times
    of a year or longer with high advertising rates.

    As I thought.
    And for more advanced modulations, like LoRa, the power consumption is even higher.


  • Hero Member

    @Uhrheber said in nRF5 Bluetooth action!:

    Some time ago I searched for a transceiver with low current receive mode, to use it in a battery powered node, that could be woken up by rf, but found nothing.

    TI and Silicon Labs have both had chips with "wake on radio". e.g. http://www.ti.com/lit/an/swra126b/swra126b.pdf

    The Rx current consumption of the nRF52832 seems pretty good, especially with DCDC regulator enabled. Seems to me that the RSSI detection implemented in PPI is a big improvement, even in noisy environments for the following reasons: the RSSI measurement takes only 0.25us, according to the DS. That's very little overhead. If the Radio gets switched on due to a false positive on the RSSI, well, it would have had to be switched on anyway even without the RSSI. I don't see the downside to this. The more noisy the environment, the less effective the technique is, but I don't see that you'd ever really be worse off for using it.


  • Hero Member

    @d00616
    If I'm using

    sleep(1000000000);
    

    to sleep the CPU while keeping the PPI active, is there a way for the PPI to subsequently wake the CPU so that the CPU can resume where it left off? I'm not seeing any TASKS which look suitable for doing that. Or do I need an altogether different configuration for sleeping the CPU?

    Back on August 5, @RMTUCKER had suggested using:

    sleep(digitalPinToInterrupt(10), FALLING,0);
    

    If I were to go that route, I could probably have the PPI toggle PIN 10 to do a wake-up, but I found that, for whatever reason, that method of sleeping had a much higher current draw.

    [Edit: scratch that. I just tried "sleep(digitalPinToInterrupt(10), FALLING,0);", and it appears to turn-off PPI. Oddly enough, it appears to leave the RTC running, which is actually just fine by me. However, I need the PPI running too. ]



  • @Uhrheber not really. If you read carefully, they claim almost 1year battery life with 1hz (once per sec) advertising.
    Typical MYS node sends data once per minute? So, actually, 2-3 years are easily achievable.


  • Hero Member

    It turns out the cost in current consumption of waking the MCU merely to check the RSSISAMPLE result is relatively high:
    0_1505404541889_NewFile6.jpg

    The first hump is the current drawn by the PPI and RSSI sample. The second hump is the current drawn by MCU.

    Measurement Scale: 1mv=1ma.

    Anyhow, the RSSISAMPLE measurement, as reported by the MCU, is abnormally high. It may be that I need to put the radio into RX state, instead of just RXIDLE, before taking the RSSI measurement.


  • Hero Member

    This post is deleted!

  • Hero Member

    @d00616

    Are there special reserved names to always use for the IRQ handlers? e.g. RADIO_IRQHandler(void), and so on?


  • Contest Winner

    @NeverDie said in nRF5 Bluetooth action!:

    to sleep the CPU while keeping the PPI active, is there a way for the PPI to subsequently wake the CPU so that the CPU can resume where it left off? I'm not seeing any TASKS which look suitable for doing that. Or do I need an altogether different configuration for sleeping the CPU?

    The PPI cannot wake up the CPU. You can try to trigger events to a timer which resumes the CPU.

    @NeverDie said in nRF5 Bluetooth action!:

    Are there special reserved names to always use for the IRQ handlers? e.g. GPIOTE_IRQHandler(void), and so on?

    The names are defined there:

    https://github.com/sandeepmistry/arduino-nRF5/blob/dc53980c8bac27898fca90d8ecb268e11111edc1/cores/nRF5/SDK/components/device/nrf52.h#L65


  • Hero Member

    @d00616 said in nRF5 Bluetooth action!:

    Yes. In a sketch, you have to put the interrupt routine into one line. You can define the interrupt only once. If you want to use the radio ISR, you can't enable the radio in MySensors.

    Does the current development software support the use of at most one ISR in total at any one time?


  • Hero Member

    @d00616

    I changed your example to use sleep(...) instead of delay(...) in the main loop, but what then becomes obvious is that the interrupts don't wake up the MCU. Well, in a sense they do, because the ISR is executed, but the MCU doesn't remain awake like it would on an Arduino. So, how does one escape the sleep mode after it has begun without waiting for it to simply time out?

    // This code is public domain
    
    #include <nrf.h>
    #include <MySensors.h>
    
    //#define RTC NRF_RTC0
    //#define RTC_IRQ RTC0_IRQn
    
    int interrupt = 0;
    
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(250000);
      Serial.println("Start");
    
      // Configure RTC
      NRF_RTC0->TASKS_STOP = 1;
      NRF_RTC0->PRESCALER = 31; //1024Hz frequency
      NRF_RTC0->CC[0] = NRF_RTC0->COUNTER + (3 * 1024);
      NRF_RTC0->EVTENSET = RTC_EVTENSET_COMPARE0_Msk;
      NRF_RTC0->INTENSET = RTC_INTENSET_COMPARE0_Msk;
      NRF_RTC0->TASKS_START = 1;
      NRF_RTC0->EVENTS_COMPARE[0] = 0;
    
      // Enable interrupt
      NVIC_SetPriority(RTC0_IRQn, 15);
      NVIC_ClearPendingIRQ(RTC0_IRQn);
      NVIC_EnableIRQ(RTC0_IRQn);
      Serial.println();
      Serial.println();
      Serial.println("Starting...");
    }
    
    void loop() {
      Serial.print(millis());
      Serial.print(" ");
      Serial.print(NRF_RTC0->COUNTER);
      Serial.print(" ");
      Serial.println(interrupt);
      sleep(10000);
    }
    
    /**
     * Reset events and read back on nRF52
     * http://infocenter.nordicsemi.com/pdf/nRF52_Series_Migration_v1.0.pdf
     */
    #if __CORTEX_M == 0x04
    #define NRF5_RESET_EVENT(event)                                                 \
            event = 0;                                                                   \
            (void)event
    #else
    #define NRF5_RESET_EVENT(event) event = 0
    #endif
    
    // This must be in one line
    extern "C" { void RTC0_IRQHandler(void) { NRF5_RESET_EVENT(NRF_RTC0->EVENTS_COMPARE[0]); interrupt++; NRF_RTC0->TASKS_CLEAR = 1; }}
    

    I guess maybe the answer is to clear the SLEEPONEXIT bit in the System Control Register (SCR) before exiting the ISR? The SCR is described on page 4-19 of: http://infocenter.arm.com/help/topic/com.arm.doc.dui0553a/DUI0553A_cortex_m4_dgug.pdf
    At the moment, though, I'm not even sure how to access that register, as so far I've only seen the API for the nRF52832 generally, not the code interface for the ARM Cortex M4 per se that's inside it.



  • @NeverDie
    I am a little lost with this,I am using sleep and wake from ext int on the nrf51 and it has been working every second for the last 2 weeks.
    What kind of int are you trying to implement?


  • Hero Member

    @rmtucker said in nRF5 Bluetooth action!:

    @NeverDie
    I am a little lost with this,I am using sleep and wake from ext int on the nrf51 and it has been working every second for the last 2 weeks.
    What kind of int are you trying to implement?

    This is for the case where the PPI is doing things (like, for example, getting the radio to periodically listen for incoming packets) all while the CPU is sleeping. If, for instance, a packet is received in that mode, the CPU needs to be awoken to process it.

    So, this is different than the easier case (which I already have working) of sleeping the CPU, then it wakes up every, say, 100ms, and then the CPU controls the radio to listen for packets and then takes action if one is received. Instead, this is a case where the PPI is controlling the radio while the CPU sleeps.

    The PPI has a lot of power saving potential, so we're figuring out how best to exploit that potential.

    Also, the more general topic of how to use interrupts and ISR's on the nRF52832 (such as how many different ones can be active at once, as supported by the current development code) needs to be addressed, independent of the regular sleep(..) function.



  • This post is deleted!

  • Hero Member

    @rmtucker said in nRF5 Bluetooth action!:

    @NeverDie
    All we need right now is a controller that covers the majority of home use.
    Tried domoticz for 2 years and it covers energy use and cost really well but then is limited to saving data every 5mins and no mixed/multisensor graphs to any extent so useless for my current needs.
    Tried myHouse for 6 months and it,s graphing was great but the display of binary sensors were not in real time and it does not do energy use at all.
    I can not find a controller that seems to cover average needs for automation/energy/and realtime feedback.
    I know it's a little off topic but it is a big problem when you can build the range of mysensors using the nrf5 but then not be able to get the feedback and energy/cost stuff on the screen.
    Maybe i am just disgruntled that the controllers do not seem to keep up with the electronics very well.

    Yes, agreed, but please let's not go into that here, because it would seriously throw us off topic. You might try: https://forum.mysensors.org/topic/7178/are-folks-here-happy-with-domoticz/63 which has some useful suggestions, especially regarding Node Red and MQTT.



  • @NeverDie
    Sorry mate i have deleted it i am just a little miffed with the controller searching😠


  • Hero Member

    @NeverDie said in nRF5 Bluetooth action!:

    At the moment, though, I'm not even sure how to access that register, as so far I've only seen the API for the nRF52832 generally, not the code interface for the ARM Cortex M4 per se that's inside it.

    OK, the file core_cm4.h is where the structure that contains the SCR is defined:

    typedef struct
    {
      __IM  uint32_t CPUID;                  /*!< Offset: 0x000 (R/ )  CPUID Base Register */
      __IOM uint32_t ICSR;                   /*!< Offset: 0x004 (R/W)  Interrupt Control and State Register */
      __IOM uint32_t VTOR;                   /*!< Offset: 0x008 (R/W)  Vector Table Offset Register */
      __IOM uint32_t AIRCR;                  /*!< Offset: 0x00C (R/W)  Application Interrupt and Reset Control Register */
      __IOM uint32_t SCR;                    /*!< Offset: 0x010 (R/W)  System Control Register */
      __IOM uint32_t CCR;                    /*!< Offset: 0x014 (R/W)  Configuration Control Register */
      __IOM uint8_t  SHP[12U];               /*!< Offset: 0x018 (R/W)  System Handlers Priority Registers (4-7, 8-11, 12-15) */
      __IOM uint32_t SHCSR;                  /*!< Offset: 0x024 (R/W)  System Handler Control and State Register */
      __IOM uint32_t CFSR;                   /*!< Offset: 0x028 (R/W)  Configurable Fault Status Register */
      __IOM uint32_t HFSR;                   /*!< Offset: 0x02C (R/W)  HardFault Status Register */
      __IOM uint32_t DFSR;                   /*!< Offset: 0x030 (R/W)  Debug Fault Status Register */
      __IOM uint32_t MMFAR;                  /*!< Offset: 0x034 (R/W)  MemManage Fault Address Register */
      __IOM uint32_t BFAR;                   /*!< Offset: 0x038 (R/W)  BusFault Address Register */
      __IOM uint32_t AFSR;                   /*!< Offset: 0x03C (R/W)  Auxiliary Fault Status Register */
      __IM  uint32_t PFR[2U];                /*!< Offset: 0x040 (R/ )  Processor Feature Register */
      __IM  uint32_t DFR;                    /*!< Offset: 0x048 (R/ )  Debug Feature Register */
      __IM  uint32_t ADR;                    /*!< Offset: 0x04C (R/ )  Auxiliary Feature Register */
      __IM  uint32_t MMFR[4U];               /*!< Offset: 0x050 (R/ )  Memory Model Feature Register */
      __IM  uint32_t ISAR[5U];               /*!< Offset: 0x060 (R/ )  Instruction Set Attributes Register */
            uint32_t RESERVED0[5U];
      __IOM uint32_t CPACR;                  /*!< Offset: 0x088 (R/W)  Coprocessor Access Control Register */
    } SCB_Type;
    

    Unfortunately, I just checked its status, and it's already cleared. So, something else is causing the MCU to go back to sleep at the end of the ISR.

    The problem is that an ISR needs to be as short as possible. If something more elaborate needs to happen as a result of an interrupt, whether it be printing a bunch of debug information or something else, it should happen outside the ISR. Right now I don't see how to do that, because the MCU always immediately goes back to sleep after the ISR finishes. I suppose it must be something inside the sleep(..) routine that causes this?


  • Hero Member

    I suspect it may be the while statement in this part of the library code that's doing it:

    
    int8_t hwSleep(unsigned long ms)
    {
    	hwSleepPrepare(ms);
    	while (nrf5_rtc_event_triggered == false) {
    		hwSleep();
    	}
    	hwSleepEnd(ms);
    	return MY_WAKE_UP_BY_TIMER;
    }
    

  • Hero Member

    Yup, that was it. I excised the while-loop and re-wrote it as a differently named function, which I now call instead of sleep(..):

    int8_t myHwSleep(unsigned long ms)
    {
      hwSleepPrepare(ms);
      //while (nrf5_rtc_event_triggered == false) {
        hwSleep();
      //}
      hwSleepEnd(ms);
      return MY_WAKE_UP_BY_TIMER;
    }
    

    and it now works "correctly"--well, at least what I want it to do. 🙂 I'll flag it for @d00616, who may have good reasons for keeping it as-is.



  • @NeverDie said in nRF5 Bluetooth action!:

    From the view count, it does seem that people are reading this thread, even if not many are posting.

    I follow your journey with great interest, one day Ill find the time to do something with it 🙂



  • Just wondering if ota updates are possible with the nrf5 because it does not have the usual memory constraints?


  • Hero Member

    Epilog: It turns out that the reason I was getting erroneous readings of RSSISAMPLE by the CPU is that the radio must be turned-on when that register is being read. I had hoped it was being stored somewhere else in memory, but it's not. So, probably the best that can be done from an energy standpoint is to have the PPI pipeline the waking of the radio and the CPU from sleep, such that neither is waiting for the other to wake up in order to get work done. Ideally, the moment the RSSI measurement is taken by the PPI, the CPU would have just then fully woken up and be able to evaluate RSSISAMPLE, while the radio is still turned on.

    A different approach would be to have the PPI cyclically wake the radio into Rx mode for a period of time and then shut it down. If it received a packet, it would trigger a wake-up on the CPU. This is more or less how the RFM69's "listen mode" works. I may give this a try also so as to measure whether total current consumed is greater or less than the current consumed by the revised RSSI approach (above). I think it might. Although the radio has to remain on longer than it would if it were doing purely an RSSI measurement, it has the advantage that the CPU can remain asleep until an actual packet is received. Given that the radio spends a lot of time just ramping up after being disabled, I'm guessing the incremental Rx time needed for packet detection won't seem so much in comparison. The hard part to this approach will be timing just how long the Radio is in RX mode. Although there are technically three RTC instantiations that can be used, they all share the same prescaler.

    So, in order to create a short delay timer, I set one GPIO pin high, which charges a second GPIO pin through a very small capacitor and diode in parallel. Then, when the first GPIO pin goes low, the voltage on the second GPIO pin decays. By setting a PPI event on the second pin to trigger from a Hi2Lo transition, I'm able to create an analog delay, which varies in duration depending on the value of the capacitor. Presently, using a 2.2nF capacitor creates about a 2ms delay between the first pin going LOW and the second pin detecting a Hi2Lo event. It is that event which could be used to trigger turning off the radio after it has listened for packets, whereas it is the first pin going LOW that would have triggered turning on the radio and putting it into RX mode. This is all controlled by the PPI, so no energy needs to be used by the CPU. 🙂

    If anyone can think of a better or more of a digital way to create a predictable time delay, please do post. However, I'm using this method for now just for proof of concept purposes.


  • Hero Member

    Here's a scope capture of it:
    0_1505580444088_NewFile7.jpg

    The yellow line shows the rapid charging and then subsequent decay of voltage on the second pin. The blip on the blue line shows that after slightly more than 2ms, the Hi2Lo event was triggered, because the voltage on the second pin had dropped enough for the Hi2Lo transition to occur. As you can see, it happens at around 1v. I was able to capture it on the scope because I used that event to very briefly set a third pin (the one whose voltage is being tracked by the blue line) HIGH.

    Again, all of this is being managed by the PPI while the CPU is asleep. 🙂


  • Contest Winner

    @NeverDie said in nRF5 Bluetooth action!:
    If your goal is to minimize the RX-on time, then you can trigger the RX start and stop by a timer for your minimal window where the frame must be start. Then use the bitcounter top stop the timer in case a packet is received. A shortcut to the end is disabling the RX mode. You can wakeup the CPU with the END event.

    P.S.: you can reduce the RX/TX time by enabling fast ramp up in MODECNF0 if you haven't to care about nRF51 compatibility.


  • Hero Member

    @d00616 said in nRF5 Bluetooth action!:

    @NeverDie said in nRF5 Bluetooth action!:
    If your goal is to minimize the RX-on time, then you can trigger the RX start and stop by a timer for your minimal window where the frame must be start. Then use the bitcounter top stop the timer in case a packet is received. A shortcut to the end is disabling the RX mode. You can wakeup the CPU with the END event.

    P.S.: you can reduce the RX/TX time by enabling fast ramp up in MODECNF0 if you haven't to care about nRF51 compatibility.

    Thanks! It finally dawned on me that having the PPI use the RTC's CC registers would be a far better way to schedule turning on and off the radio's RX than using the stopgap analog delay that I had devised (above). Your interrupt handler example helped me see what had been staring me in the face the entire time, but without my recognizing it as the answer to the problem. Funny how that can sometimes happen, where the whole gestalt can just suddenly change. So, thanks again for sharing your example code. This will be a much less awkward solution! 🙂


  • Hero Member

    Where exactly do I look to find all the pin mappings that are assumed for the "Generic nRF52" board? For example, what are the pin numbers that are assumed for RXI, TXO, MISO, MOSI, etc.?



  • @NeverDie
    /variants/Generic/variant.h i think


  • Hero Member

    I just now posted a source code example and hardware demo for my recently completed breakout board which uses "MyNRF52Board nRF52832" board as the reference when compiling within the Arduino IDE:
    https://www.openhardware.io/view/471#tabs-source

    I think from this point forward I'm going to use "MyNRF52Board nRF52832" for any custom boards I develop. Thanks to @d00616, it is a very convenient framework for organizing and enabling the preferred pin mappings. 🙂



  • @NeverDie That is a meandered Inverted F Antenna (IFA). It will give you better performance then a standard meandering antenna and a much smaller size then a standard 1/4wave trace antenna. Not as easy to tune however. You can read about the one that TI designed for their 2.4Ghz dongle. http://www.ti.com/lit/an/swra117d/swra117d.pdf
    Of course this is not Device dependent as you need to feed it with a 50 ohm feed point. A Pi network before between the Chip's ANT output and the Antenna is desired from a tuning standpoint.

    Note that on the nRF52 designs, the two components (Cap and Inductor) connected to the ANT pin are used for harmonic filtering AND impedance matching and has nothing to do with the antenna tuning other to present a 50ohm feed point.


  • Hero Member

    @Jokgi said in nRF5 Bluetooth action!:

    @NeverDie That is a meandered Inverted F Antenna (IFA). It will give you better performance then a standard meandering antenna and a much smaller size then a standard 1/4wave trace antenna. Not as easy to tune however. You can read about the one that TI designed for their 2.4Ghz dongle. http://www.ti.com/lit/an/swra117d/swra117d.pdf
    Of course this is not Device dependent as you need to feed it with a 50 ohm feed point. A Pi network before between the Chip's ANT output and the Antenna is desired from a tuning standpoint.

    Note that on the nRF52 designs, the two components (Cap and Inductor) connected to the ANT pin are used for harmonic filtering AND impedance matching and has nothing to do with the antenna tuning other to present a 50ohm feed point.

    It looks the same as the antenna on the Ebyte E73-2G4M04S nRF52832 module. Is there any difference? i.e. are you just supplying background information, or are you making a suggestion for improvement?



  • @NeverDie nRFgo Studio uses the Segger J-link firmware. When using the Softdevice make sure that your application does not start below the top of the Softdevice or you will get a error on most programmers that there is something located in that protected space. If it does not see this as a protected area then you will corrupt the Softdevice.

    Most programmers only need the two SWD lines, ground and a voltage reference from your target board back to the programmer. This is to tell the programmer you have a target board connected and what voltage it is running on. Note that the nRF52-DK does NOT have voltage translators on the programming lines (P19 and P20) so you must be powering your target boards with 3vdc to 3.3vdc. (I have tested down to 2.8vdc but it is not guaranteed to work consistently.) Not sure about ST or other programmers.



  • @NeverDie someone did not read the datasheet. The harmonic filter / impedance matching network on the output of Pin 30 (ANT) is connected incorrectly. There needs to be abolded text Cap from ANT out to Pin 31 ONLY. (Not connected to any other ground pour as it seems they did here. Seems to be a few "extra components between there and the Antenna matching network too.

    From the nRF52832 datasheet.
    bolded text53.8 PCB layout example
    The PCB layout shown below is a reference layout for the QFN package with internal LDO setup.
    Important: Pay attention to how the capacitor C3 is grounded. It is not directly connected to the
    ground plane, but grounded via VSS pin 31. This is done to create additional filtering of harmonic
    components.[link text](link url)



  • @NeverDie Pretty much a reference only. In a previous post you inquired about the grounding on the meandering antenna. I posted the TI application note as a frame of reference only. However if you do create your own module you should be aware that the two matching components coming off the ANT pin are NOT antenna matching components but are three for output impedance matching and also acts as a low pass filter. Pi network is still required for tuning of the antenna. (may not use all three components after tuning)


  • Hero Member

    @Jokgi said in nRF5 Bluetooth action!:

    you must be powering your target boards with 3vdc to 3.3vdc. (I have tested down to 2.8vdc but it is not guaranteed to work consistently.) Not sure about ST or other programmers.

    Thanks for reminding me of this. It turns out to be true for the J-Link programmers which are for sale on Aliexpress.com as well.



  • @NeverDie I am not sure about all the boards for sell on that site. but I would have to say that any J-link programmer that is packaged as such for $12-$40 dollars is probably counterfeit. Updating these items with newer J-link firmware would more then likely disable them. (On purpose) You may wish to contact Segger in Boston prior to spending money on these potential clones. I would be interested to hear what experiences other people have had with the products from that site.

    The genuine J-link and j-link plus programmers are over $400.00 as you can see on the Digi-Key website. Per the Segger license agreements, the only J-link 0B devices that are able to be sold are to be bundled with a Evaluation / Development kit such as the nRF52-DK, ST, Rigato, and other semiconductor / module manufacture's dev kits.


  • Hero Member

    @Jokgi said in nRF5 Bluetooth action!:

    @NeverDie I am not sure about all the boards for sell on that site. but I would have to say that any J-link programmer that is packaged as such for $12-$40 dollars is probably counterfeit. Updating these items with newer J-link firmware would more then likely disable them. (On purpose) You may wish to contact Segger in Boston prior to spending money on these potential clones. I would be interested to hear what experiences other people have had with the products from that site.

    The genuine J-link and j-link plus programmers are over $400.00 as you can see on the Digi-Key website. Per the Segger license agreements, the only J-link 0B devices that are able to be sold are to be bundled with a Evaluation / Development kit such as the nRF52-DK, ST, Rigato, and other semiconductor / module manufacture's dev kits.

    When would I need to upgrade the firmware? At least for now it seems to work just fine.


  • Hardware Contributor

    @Jokgi said in nRF5 Bluetooth action!:

    @NeverDie I am not sure about all the boards for sell on that site. but I would have to say that any J-link programmer that is packaged as such for $12-$40 dollars is probably counterfeit. Updating these items with newer J-link firmware would more then likely disable them. (On purpose)

    Yes they are of course counterfeit, and using old firmware. You have a message when you use them with Segger software asking you to upgrade to newer firmware and if you accept your programmer is disabled (web is full of solutions to reflash a firmware).
    But if you don't upgrade the firmware it works fine as a SWD programmer, at least for basic use (programming). I have not tried any debugging.



  • @Nca78 Corrrect. It seems to me that a < 50 dollar Nordic nRF52 based Dev kit (or similar) which can be updated would be much less hassle.


  • Hero Member

    Are we limited to using RTC0? I've tried switching to RTC1 and RTC2, and I get the sense there are conflicts with both of them and the MySensors code if they're used.


  • Contest Winner

    @NeverDie said in nRF5 Bluetooth action!:

    Are we limited to using RTC0? I've tried switching to RTC1 and RTC2, and I get the sense there are conflicts with both of them and the MySensors code if they're used.

    RTC1 is blocked by arduino (nRF5/delay.c) and RTC0 (nRF51) and RTC2 (nRF52) is used in MySensors (hal/architecture/MyHwNRF5.cpp)


  • Hero Member

    Success. I now have a "listen mode" for the nRF52832 radio that's completely controlled by the PPI while the MCU sleeps. Presently, it wakes up the radio every 100ms and listens for 1ms. This means no wasted power from oversight by the MCU. Using just the PPI, I can control to within about 30us over how long to make the cycle period and/or the listening duration.
    0_1505768284420_NewFile2.jpg
    0_1505768305717_NewFile1.jpg

    The scope shots show the current drawn. Scale: 1mv=1ma. As you can see, the DCDC regulator is engaged.

    Next step will be to have packet receipt wake up the MCU via an ISR, so that the packet can be processed. After that, I'll see how narrow I can make the receive window and still receive packets reliably. I think under 100us will be possible. Maybe even less than 60us if the bitrate is 2mbps. 🙂



  • @NeverDie Great Job!!!! Suggestion... If you are going to use the BTLE Softdevice you will have a smaller receive window if you use the external 32khz crystal option rather then the internal 32khz RC one. (+/- 20ppm with the crystal vs +/- 250 or 500ppm with the RC.


  • Hero Member

    At the extreme, one of the questions that will need answering is: what's the minimum number of bytes in a transmitted frame that you really do need before the receiver starts receiving garbage packets? For instance, a 10 byte frame, which should be more than adequate, would take 40us of airtime to either transmit or receive at 2mbps bitrate. One could get to a lower number by maybe sending a null packet as a wake-up packet, in which case maybe you also don't need CRC. So, that leaves you with some preamble, a network ID, and maybe a destination ID--or about 5 bytes. So, that would be around 20us of airtime. One could shrink that further by reducing the number of network ID bytes, but too much of that and possibly one starts to receive garbage packets.

    The RFM69 doesn't try to decode packets whose RSSI is below a specific programmable threshhold. I don't believe the nRF52 radio uses RSSI as a filter in that way though. It seems that the nRF52832 radio tries to decode whatever it's receiving, regardless of the RSSI. Or, at least, that's how I remember it. Anyone else played around with it?


  • Hero Member

    @d00616

    I adapted your RTC0 code for handling IRQ's, and it looks like this:

    
      NRF_RADIO->INTENSET = B100;  //interrupt MCU if a payload is received.
      // Enable interrupt
      NVIC_SetPriority(RADIO_IRQn, 15);
      NVIC_ClearPendingIRQ(RADIO_IRQn);
      NVIC_EnableIRQ(RADIO_IRQn);
    
    #if __CORTEX_M == 0x04
    #define NRF5_RESET_EVENT(event)                                                 \
            event = 0;                                                                   \
            (void)event
    #else
    #define NRF5_RESET_EVENT(event) event = 0
    #endif
    
    
    // This must be in one line
    extern "C" { void RADIO_IRQHandler(void) {packetCounter++; NRF5_RESET_EVENT(NRF_RADIO->EVENTS_PAYLOAD); NRF_RADIO->EVENTS_PAYLOAD=0; }}
    

    Question: Is

    NRF5_RESET_EVENT(NRF_RADIO->EVENTS_PAYLOAD); 
    

    doing anything more than

    NRF_RADIO->EVENTS_PAYLOAD=0;
    

    is?


  • Hero Member

    The good news is that I can now literally "see" that the listen-mode is receiving packets, because I've programmed the PPI to toggle an LED every time a packet is received (and it only toggles the LED if and only if I know that I'm sending the node packets from a different node). The bad news is that--so far, anyway--it doesn't appear to trigger an IRQ event that wakes up the MCU and runs the ISR.


  • Mod

    @NeverDie it seems like the preamble can be configured to be either 8 or 16 bits. Not sure if that's of any use, but I've been thinking about adjusting the LoRa preamble to get better sleep times. Maybe that could be applicable for nrf as well.


  • Hero Member

    It turns out that using just the standard radiohead packet/frame structure, I'm able to 100% reliably receive a two byte string (in this case, the letter "H" followed by a zero as the termination character) using the above PPI solution with a receive window of about 200ms. That includes preamble, CRC, and a long network ID number.

    I'm pleased with that result. It's vastly better than without the PPI solution.


  • Hero Member

    OK, I'm going to start with this, which works:

    //A simplified re-mix of code mostly written by d00616
    
    #include <nrf.h>
    #include <MySensors.h>
    
    int interrupt = 0;
    uint32_t theCounter;
    
    
    int8_t myHwSleep(unsigned long ms)
    {
      hwSleepPrepare(ms);
      //while (nrf5_rtc_event_triggered == false) {
        hwSleep();
      //}
      hwSleepEnd(ms);
      return MY_WAKE_UP_BY_TIMER;
    }
    
    
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(250000);
      Serial.println("Start");
    
      // Configure RTC
      NRF_RTC0->TASKS_STOP = 1;
      NRF_RTC0->PRESCALER = 32;  
      NRF_RTC0->CC[0] = NRF_RTC0->COUNTER + (655);  //comparison for when to turn off the Rx.
      NRF_RTC0->EVTENSET = RTC_EVTENSET_COMPARE0_Msk;
      NRF_RTC0->INTENSET = RTC_INTENSET_COMPARE0_Msk;
      NRF_RTC0->TASKS_START = 1;
      NRF_RTC0->EVENTS_COMPARE[0] = 0;
    
      // Enable interrupt
      NVIC_SetPriority(RTC0_IRQn, 15);
      NVIC_ClearPendingIRQ(RTC0_IRQn);
      NVIC_EnableIRQ(RTC0_IRQn);
      Serial.println();
      Serial.println();
      Serial.println("Starting...");
    }
    
    
    void loop() {
    
      Serial.print(millis());
      Serial.print(" ");
      Serial.print(theCounter);
      Serial.print(" ");
      Serial.println(interrupt);
      myHwSleep(5000000);
    }
    
    /**
     * Reset events and read back on nRF52
     * http://infocenter.nordicsemi.com/pdf/nRF52_Series_Migration_v1.0.pdf
     */
    #if __CORTEX_M == 0x04
    #define NRF5_RESET_EVENT(event)                                                 \
            event = 0;                                                                   \
            (void)event
    #else
    #define NRF5_RESET_EVENT(event) event = 0
    #endif
    
    // This must be in one line
    extern "C" { void RTC0_IRQHandler(void) {   theCounter=NRF_RTC0->COUNTER; NRF5_RESET_EVENT(NRF_RTC0->EVENTS_COMPARE[0]); interrupt++; NRF_RTC0->TASKS_CLEAR = 1; }}
    

    and see if I can generate equivalent code which triggers on a pin change instead of an RTC event. If I can get that to work, then I'll take another stab at getting it to work based on the radio receiving a packet.


  • Hero Member

    I was only partially done with the code, but I decided to run it anyway. Oddly enough, even though there is no reference to " RTC0_IRQHandler(void)" as being the event handler, it gets fired off anyway whenever I press the button (pin P0.16):

    
    #include <nrf.h>
    #include <MySensors.h>
    
    int interrupt = 0;
    uint32_t theCounter;
    
    
    int8_t myHwSleep(unsigned long ms)
    {
      hwSleepPrepare(ms);
       hwSleep();
      hwSleepEnd(ms);
      return MY_WAKE_UP_BY_TIMER;
    }
    
    
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(250000);
      Serial.println("Start");
    
      //Configure GPIOTE 
      NRF_GPIOTE->CONFIG[0]=0x31001;  // Toggle Event; Pin P0.16; Event Mode 
                                      //So, any pin change on P0.16 will trigger an event.
                                       //On the Nordic nRF52 DK, Pin 0.16 is a button.
                                       
      NRF_GPIOTE->CONFIG[1]=0x131203;  //Initial setting: HIGH; Toggle Task; Pin P0.18; Task Mode
                                       //On the Nordic nRF52 DK, Pin 0.18 is an LED.
                                       //Note: initial setting of HIGH means that the LED will be initially OFF.
    
      NRF_GPIOTE->INTENSET=1;  //Enable an event on Pin P0.16 to trigger an interrupt.
                                       
      NRF_PPI->CH[0].EEP = (uint32_t)&NRF_GPIOTE->EVENTS_IN[0];  //P0.16 pin change occured.
      NRF_PPI->CH[0].TEP = (uint32_t)&NRF_GPIOTE->TASKS_OUT[1]; //Toggle LED on pin P0.18.
      
      NRF_PPI->CHENSET=B1; //enable Channel 0.
    
      // Enable interrupt
      NVIC_SetPriority(GPIOTE_IRQn, 15);
      NVIC_ClearPendingIRQ(GPIOTE_IRQn);
      NVIC_EnableIRQ(GPIOTE_IRQn);
      Serial.println();
      Serial.println();
      Serial.println("Starting...");
    }
    
    
    void loop() {
    
      Serial.print(millis());
      Serial.print(" ");
      Serial.print(theCounter);
      Serial.print(" ");
      Serial.println(interrupt);
      myHwSleep(5000000);
    }
    
    /**
     * Reset events and read back on nRF52
     * http://infocenter.nordicsemi.com/pdf/nRF52_Series_Migration_v1.0.pdf
     */
    #if __CORTEX_M == 0x04
    #define NRF5_RESET_EVENT(event)                                                 \
            event = 0;                                                                   \
            (void)event
    #else
    #define NRF5_RESET_EVENT(event) event = 0
    #endif
    
    // This must be in one line
    extern "C" { void RTC0_IRQHandler(void) {   theCounter=NRF_RTC0->COUNTER; NRF5_RESET_EVENT(NRF_RTC0->EVENTS_COMPARE[0]); interrupt++; NRF_RTC0->TASKS_CLEAR = 1; }}
    

    So, it looks as though, at present, there can be only a single ISR for an entire sketch?


  • Hero Member

    Interesting result. I eliminated most of the sample code, and it actually manages to work even without an ISR! Instead of running an ISR, it appears to simply wake up from exactly where it last fell asleep. Then it continues running until it's put to sleep again:

    #include <nrf.h>
    #include <MySensors.h>
    
    uint32_t buttonPressCounter=0;
    
    
    int8_t myHwSleep(unsigned long ms)
    {
      hwSleepPrepare(ms);
      hwSleep();
      hwSleepEnd(ms);
      return MY_WAKE_UP_BY_TIMER;
    }
    
    
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(250000);
      Serial.println("Start");
    
      //Configure GPIOTE 
      NRF_GPIOTE->CONFIG[0]=0x31001;  // Toggle Event; Pin P0.16; Event Mode 
                                      //So, any pin change on P0.16 will trigger an event.
                                       //On the Nordic nRF52 DK, Pin 0.16 is a button.
                                       
      NRF_GPIOTE->CONFIG[1]=0x131203;  //Initial setting: HIGH; Toggle Task; Pin P0.18; Task Mode
                                       //On the Nordic nRF52 DK, Pin 0.18 is an LED.
                                       //Note: initial setting of HIGH means that the LED will be initially OFF.
    
      NRF_GPIOTE->INTENSET=1;  //Enable an event on Pin P0.16 to trigger an interrupt.
                                       
      NRF_PPI->CH[0].EEP = (uint32_t)&NRF_GPIOTE->EVENTS_IN[0];  //P0.16 pin change occured.
      NRF_PPI->CH[0].TEP = (uint32_t)&NRF_GPIOTE->TASKS_OUT[1]; //Toggle LED on pin P0.18.
      
      NRF_PPI->CHENSET=B1; //enable Channel 0.
    
      // Enable interrupt
      NVIC_SetPriority(GPIOTE_IRQn, 15);
      NVIC_ClearPendingIRQ(GPIOTE_IRQn);
      NVIC_EnableIRQ(GPIOTE_IRQn);
      Serial.println();
      Serial.println();
      Serial.println("Starting...");
    }
    
    
    void loop() {
      Serial.print("time=");
      Serial.print(millis());
      Serial.print(", buttonPressCounter=");
      Serial.println(buttonPressCounter++);
      myHwSleep(5000000);
    }
    

  • Contest Winner

    @NeverDie said in nRF5 Bluetooth action!:

    Question: Is
    NRF5_RESET_EVENT(NRF_RADIO->EVENTS_PAYLOAD);

    doing anything more than
    NRF_RADIO->EVENTS_PAYLOAD=0;

    is?

    Yes. It reads back the register. http://infocenter.nordicsemi.com/topic/com.nordic.infocenter.nrf52/dita/nrf52/migration/functional.html?cp=2_4_0


  • Hero Member

    Whenever I use:

    #include <MySensors.h>
    

    on the nRF52832, there is around a 10 second delay between the end of "void startup()" and the beginning of "loop()". Why is that, and what is the MySensors library doing during that interval?


  • Mod

    @NeverDie it depends on the value of MY_TRANSPORT_WAIT_READY_MS
    See https://github.com/mysensors/MySensors/issues/927 for a discussion on what happens when - we're trying to clarify the documentation.


  • Hero Member

    @d00616 said in nRF5 Bluetooth action!:

    P.S.: you can reduce the RX/TX time by enabling fast ramp up in MODECNF0 if you haven't to care about nRF51 compatibility.

    Thanks for the tip. I tried it both ways. The first scope capture below is taken without MODECNF0 enabled on bit 0, and the second is with it enabled on bit 0.
    0_1505865330798_NewFile5.png
    0_1505865340675_NewFile6.png

    I don't really see any difference. Do you?
    Scale: 1mv=1ma. Scope captures of current drawn.

    Maybe @jokgi can comment? His bio says he's a Senior Field Application Engineer at Nordic Semiconductor.
    Maybe he sees (or knows) something that's not apparent about the fast ramp enable bit?


  • Contest Winner

    @NeverDie said in nRF5 Bluetooth action!:

    Whenever I use:
    #include <MySensors.h>

    on the nRF52832, there is around a 10 second delay between the end of "void startup()" and the beginning of "loop()". Why is that, and what is the MySensors library doing during that interval?

    As an alternative, you can define '#define MY_CORE_ONLY' and use ' transportInit(); transportSetAddress(MY_NODE_ID);' to initialize the radio. This dosn't work at the moment with the nRF5. I'm currently looking what the reason is. All radio registers are equal when it's initialized after MySensors normal and my setup(). It's not able to send or receive packages.

    Maybe someone has an idea about the reason. Here is my code for nRF5 and other with nRF24.

    // Undefine to work in gateway mode
    #define MY_CORE_ONLY
    
    
    #define MY_NODE_ID (0)
    
    // Enable debug
    #define MY_DEBUG
    #define MY_DEBUG_VERBOSE_RF24
    #define MY_DEBUG_VERBOSE_NRF5_ESB
    
    // Enable and select radio type attached
    #ifndef ARDUINO_ARCH_NRF5
    #define MY_RADIO_NRF24
    #else
    #define MY_RADIO_NRF5_ESB
    #include <nrf.h>
    #endif
    //#define MY_RADIO_RFM69
    //#define MY_RADIO_RFM95
    
    //#define MY_OTA_LOG_SENDER_FEATURE
    //#define MY_OTA_LOG_RECEIVER_FEATURE
    
    #ifndef MY_CORE_ONLY
    #define MY_GATEWAY_SERIAL
    #endif
    #include <MySensors.h>
    
    void state() {
    #ifdef ARDUINO_ARCH_NRF5
     Serial.println("----------------------------------");
     Serial.print("NRF_RADIO->STATE  ");
     Serial.println(NRF_RADIO->STATE, HEX);
     Serial.print("NRF_RADIO->EVENTS_READY  ");
     Serial.println(NRF_RADIO->EVENTS_READY, HEX);
     Serial.print("NRF_RADIO->EVENTS_ADDRESS  ");
     Serial.println(NRF_RADIO->EVENTS_ADDRESS, HEX);
     Serial.print("NRF_RADIO->EVENTS_PAYLOAD  ");
     Serial.println(NRF_RADIO->EVENTS_PAYLOAD, HEX);
     Serial.print("NRF_RADIO->EVENTS_END  ");
     Serial.println(NRF_RADIO->EVENTS_END, HEX);
     Serial.print("NRF_RADIO->EVENTS_DISABLED  ");
     Serial.println(NRF_RADIO->EVENTS_DISABLED, HEX);
     Serial.print("NRF_RADIO->EVENTS_DEVMATCH  ");
     Serial.println(NRF_RADIO->EVENTS_DEVMATCH, HEX);
     Serial.print("NRF_RADIO->EVENTS_DEVMISS  ");
     Serial.println(NRF_RADIO->EVENTS_DEVMISS, HEX);
     Serial.print("NRF_RADIO->EVENTS_RSSIEND  ");
     Serial.println(NRF_RADIO->EVENTS_RSSIEND, HEX);
     Serial.print("NRF_RADIO->EVENTS_BCMATCH  ");
     Serial.println(NRF_RADIO->EVENTS_BCMATCH, HEX);
     Serial.print("NRF_RADIO->CRCSTATUS  ");
     Serial.println(NRF_RADIO->CRCSTATUS, HEX);
     Serial.print("NRF_RADIO->RXMATCH  ");
     Serial.println(NRF_RADIO->RXMATCH, HEX);
     Serial.print("NRF_RADIO->RXCRC  ");
     Serial.println(NRF_RADIO->RXCRC, HEX);
     Serial.print("NRF_RADIO->DAI  ");
     Serial.println(NRF_RADIO->DAI, HEX);
     Serial.print("NRF_RADIO->PACKETPTR  ");
     Serial.println(NRF_RADIO->PACKETPTR, HEX);
     Serial.print("NRF_RADIO->FREQUENCY  ");
     Serial.println(NRF_RADIO->FREQUENCY, HEX);
     Serial.print("NRF_RADIO->TXPOWER  ");
     Serial.println(NRF_RADIO->TXPOWER, HEX);
     Serial.print("NRF_RADIO->MODE  ");
     Serial.println(NRF_RADIO->MODE, HEX);
     Serial.print("NRF_RADIO->PCNF0  ");
     Serial.println(NRF_RADIO->PCNF0, HEX);
     Serial.print("NRF_RADIO->PCNF1  ");
     Serial.println(NRF_RADIO->PCNF1, HEX);
     Serial.print("NRF_RADIO->BASE0  ");
     Serial.println(NRF_RADIO->BASE0, HEX);
     Serial.print("NRF_RADIO->BASE1  ");
     Serial.println(NRF_RADIO->BASE1, HEX);
     Serial.print("NRF_RADIO->PREFIX0  ");
     Serial.println(NRF_RADIO->PREFIX0, HEX);
     Serial.print("NRF_RADIO->PREFIX1  ");
     Serial.println(NRF_RADIO->PREFIX1, HEX);
     Serial.print("NRF_RADIO->TXADDRESS  ");
     Serial.println(NRF_RADIO->TXADDRESS, HEX);
     Serial.print("NRF_RADIO->RXADDRESSES  ");
     Serial.println(NRF_RADIO->RXADDRESSES, HEX);
     Serial.print("NRF_RADIO->CRCCNF  ");
     Serial.println(NRF_RADIO->CRCCNF, HEX);
     Serial.print("NRF_RADIO->SHORTS  ");
     Serial.println(NRF_RADIO->SHORTS, HEX);
     Serial.print("NRF5_RADIO_TIMER->MODE ");
     Serial.println(NRF5_RADIO_TIMER->MODE);
     Serial.print("NRF5_RADIO_TIMER->BITMODE ");
     Serial.println(NRF5_RADIO_TIMER->BITMODE);
     Serial.print("NRF5_RADIO_TIMER->SHORTS ");
     Serial.println(NRF5_RADIO_TIMER->SHORTS);
     Serial.print("NRF5_RADIO_TIMER->PRESCALER ");
     Serial.println(NRF5_RADIO_TIMER->PRESCALER);
      // Reset compare events
    #ifdef NRF51
      for (uint8_t i=0;i<4;i++) {
    #else
      for (uint8_t i=0;i<6;i++) {
    #endif
     Serial.print("NRF5_RADIO_TIMER->EVENTS_COMPARE[");
     Serial.print(i);
     Serial.print("] ");
     Serial.println(NRF5_RADIO_TIMER->EVENTS_COMPARE[i]);
    }
    Serial.println("----------------------------------");
    #endif
    }
    
    void setup() {
      Serial.begin(115200);
      
      #ifdef MY_CORE_ONLY
      transportInit();
      delay(1000);
      transportSetAddress(MY_NODE_ID);
      #endif
    }
    
    void loop() {
      state();
    
      #ifdef MY_CORE_ONLY
      // Check for packages
      if (transportAvailable()) {
        uint8_t buffer[256];
        uint8_t num = transportReceive(&buffer);
        for (int i=0;i<num;i++) {
          if (buffer[i]<0x10) Serial.print("0");
          Serial.print(buffer[i], HEX);
          Serial.print(" ");
        }
        Serial.println();
      }
      #endif
    
      // Pause
      //sleep(1000); don't use this on SAMD. The device must be restored with reset doubleclick
      delay(1000);
      
      // Send data
      //transportSend(MY_NODE_ID, "abcd", 4, false);
    }
    

    @NeverDie said in nRF5 Bluetooth action!:

    @d00616 said in nRF5 Bluetooth action!:

    P.S.: you can reduce the RX/TX time by enabling fast ramp up in MODECNF0 if you haven't to care about nRF51 compatibility.

    Thanks for the tip. I tried it both ways. The first scope capture below is taken without MODECNF0 enabled on bit 0, and the second is with it enabled on bit 0.

    Have you checked the MODECNF0 register after ramp up? Maybe the register must be changed in a specific state?


  • Hero Member

    Not sure why, but so far I haven't been able to get the radio to generate an interrupt (after it receives a packet) that directly wakes the MCU. So, as a workaround, I'm using PPI to have the radio toggle a GPIO output pin, which is directly shorted to a GPIO input pin. Changes in that input pin are able to trigger an interrupt which wakes the MCU. So, in this circuitous way, I'm able to get the radio to wake the MCU. It works, but with a propagation delay, and obviously I shouldn't have to be doing it so indirectly.

    Has anyone else had any success yet in waking the MCU from sleep upon packet receipt by the radio?

    Which interrupt register in the MCU is the interrupt generated by the radio tied to? Perhaps it needs to be premptively cleared. I think the next step is to check whether the radio's interrupt is even being received by the MCU.


  • Contest Winner

    @d00616 said in nRF5 Bluetooth action!:

    Maybe someone has an idea about the reason. Here is my code for nRF5 and other with nRF24.

    Now, I have the NRF5_ESB working under MY_CORE_ONLY condition. The HFCLK is not initialized. I do some code changes to allow using the radio in core only mode.


  • Hero Member

    @d00616 said in nRF5 Bluetooth action!:

    @d00616 said in nRF5 Bluetooth action!:

    Maybe someone has an idea about the reason. Here is my code for nRF5 and other with nRF24.

    Now, I have the NRF5_ESB working under MY_CORE_ONLY condition. The HFCLK is not initialized. I do some code changes to allow using the radio in core only mode.

    I'm not sure what that means. Can you clarify what is working and what isn't, especially with regards to interrupts? If the code isn't yet ready, I'll just stick with the GPIO pins solution (above) and revisit this topic again at some future date when its further along.


  • Hero Member

    Actually, there's another reason for wanting to avoid using the GPIO pins to intermediate waking up the MCU: earlier measurements in this thread showed that using the GPIO's in anything other than a "disconnected" state noticeably increases the current draw while sleeping.


  • Hero Member

    @d00616 said in nRF5 Bluetooth action!:

    The HFCLK is not initialized.

    Not sure if it helps you at all, but to save extra energy I'm using the PPI to turn-on HFCLK before the Rx "listen-mode" begins, and then turn it off after the receiver is subsequently put to sleep:

      //Note: radio is assumed to be sleeping by this point, and with high frequency crystal oscillator turned off.
      NRF_PPI->CH[0].EEP = (uint32_t)&NRF_RTC0->EVENTS_OVRFLW;  //when COUNTER overflows.
      NRF_PPI->CH[0].TEP = (uint32_t)&NRF_CLOCK->TASKS_HFCLKSTART;  //turn-on the HF crystal oscillator
    
      NRF_PPI->CH[1].EEP = (uint32_t)&NRF_CLOCK->EVENTS_HFCLKSTARTED;  //After HF Clock started.
      NRF_PPI->CH[1].TEP = (uint32_t)&NRF_RADIO->TASKS_RXEN;  //turn on the radio receiver
    
      NRF_PPI->CH[2].EEP = (uint32_t)&NRF_RADIO->EVENTS_READY;  //After event READY, radio shall be in state RXIDLE.
      NRF_PPI->CH[2].TEP = (uint32_t)&NRF_RADIO->TASKS_START;  //Move from RXIDLE mode into RX mode.
    
      NRF_PPI->CH[3].EEP = (uint32_t)&NRF_RTC0->EVENTS_COMPARE[0];  // If time to turn off the radio receiver
      NRF_PPI->CH[3].TEP = (uint32_t)&NRF_RADIO->TASKS_STOP; //Move radio from RX mode back into RXIDLE mode
      
      NRF_PPI->CH[4].EEP = (uint32_t)&NRF_RTC0->EVENTS_COMPARE[1];  // If enough time has passed
      NRF_PPI->CH[4].TEP = (uint32_t)&NRF_RADIO->TASKS_DISABLE; //Sleep the radio
      NRF_PPI->FORK[4].TEP = (uint32_t)&NRF_CLOCK->TASKS_HFCLKSTOP; //Turn-off the high frequency crystal oscillator 
      
      NRF_PPI->CH[5].EEP = (uint32_t)&NRF_RTC0->EVENTS_COMPARE[2];  // If 100ms has passed
      NRF_PPI->CH[5].TEP = (uint32_t)&NRF_RTC0->TASKS_TRIGOVRFLW; //Set COUNTER so that it will overflow in 16 ticks.
    
      NRF_PPI->CH[6].EEP = (uint32_t)&NRF_RADIO->EVENTS_END;  //packet received.
      NRF_PPI->CH[6].TEP = (uint32_t)&NRF_GPIOTE->TASKS_OUT[1]; //Make pin P0.18. be LOW (turn on the LED).
    
      NRF_PPI->CH[7].EEP = (uint32_t)&NRF_GPIOTE->EVENTS_IN[0];  //P0.16 pin change occured.
      NRF_PPI->CH[7].TEP = (uint32_t)&NRF_GPIOTE->TASKS_OUT[2]; //Make pin P0.17. be LOW (turn on the LED).
      
      NRF_PPI->CHENSET=B11111111; //enable Channels 7,6,5,4,3,2,1,and 0.
    

    It works. 🙂


  • Hero Member

    @d00616

    Can you see any reason as to why the radio isn't waking the MCU after it receives a packet? Here's the entire sketch:

    #include <nrf.h>
    //#include <MySensors.h>
    #include <RH_NRF51.h>
    
    // Singleton instance of the radio driver
    RH_NRF51 nrf51;
    
    bool toggle=true;
    uint32_t packetCounter=0;
    uint8_t myBuffer[20];  //required buffer for transmitting packet
    uint8_t my_default_network_address[] = {0xE7, 0xE7, 0xE7, 0xE7, 0xE7};
    
    bool mySetNetworkAddress(uint8_t* address, uint8_t len)
    {
        if (len < 3 || len > 5)
      return false;
    
        // First byte is the prefix, remainder are base
        NRF_RADIO->PREFIX0    = ((address[0] << RADIO_PREFIX0_AP0_Pos) & RADIO_PREFIX0_AP0_Msk);
        uint32_t base;
        memcpy(&base, address+1, len-1);
        NRF_RADIO->BASE0 = base;
    
        NRF_RADIO->PCNF1 =  (
      (((sizeof(myBuffer)) << RADIO_PCNF1_MAXLEN_Pos)  & RADIO_PCNF1_MAXLEN_Msk)  // maximum length of payload
      | (((0UL)        << RADIO_PCNF1_STATLEN_Pos) & RADIO_PCNF1_STATLEN_Msk) // expand the payload with 0 bytes
      | (((len-1)      << RADIO_PCNF1_BALEN_Pos)   & RADIO_PCNF1_BALEN_Msk)); // base address length in number of bytes.
    
        return true;
    }
    
    void myHwSleepPrepare(unsigned long ms)
    {
      // Idle serial device
      NRF_UART0->TASKS_STOPRX = 1;
      NRF_UART0->TASKS_STOPTX = 1;
      NRF_UART0->TASKS_SUSPEND = 1;
    
      //NRF_CLOCK->TASKS_HFCLKSTOP = 1;
      
      // Enable low power sleep mode
      NRF_POWER->TASKS_LOWPWR = 1;
    }
    
    // Sleep in System ON mode
    inline void doTheSleep()
    {
      __WFE();
      __SEV();
      __WFE();
    }
    
    void myHwSleepEnd(unsigned long ms)
    {
      // Start HFCLK
      //if (nrf5_pwr_hfclk) {
      if (false) {
        NRF_CLOCK->EVENTS_HFCLKSTARTED = 0;
        NRF_CLOCK->TASKS_HFCLKSTART = 1;
        while (NRF_CLOCK->EVENTS_HFCLKSTARTED == 0)
          ;
        // Enable low latency sleep mode
        NRF_POWER->TASKS_CONSTLAT = 1;
      }
    
       // Start serial device
    //#ifndef MY_DISABLED_SERIAL
      NRF_UART0->TASKS_STARTRX = 1;
      NRF_UART0->TASKS_STARTTX = 1;
    //#endif
    }
    
    void myHwSleep(unsigned long ms)
    {
      myHwSleepPrepare(ms);
      doTheSleep();
      //now sleeping
      myHwSleepEnd(ms);
    
    }
    
    
    
    void setup() {
      Serial.begin(250000);
      Serial.println();
      Serial.println("Starting...");
      Serial.flush();
    
      NRF_POWER->DCDCEN=1;  //enable the DCDC voltage regulator as the default.
      
      // Configure RTC
      NRF_RTC0->TASKS_STOP = 1;  //stop the RTC counter so that it can be configured without incident
    
      // Enable interrupt
      //NVIC_SetPriority(GPIOTE_IRQn, 15);
      //NVIC_ClearPendingIRQ(GPIOTE_IRQn);
      //NVIC_EnableIRQ(GPIOTE_IRQn);
      
      NVIC_SetPriority(RADIO_IRQn, 15);
      NVIC_ClearPendingIRQ(RADIO_IRQn);
      NVIC_EnableIRQ(RADIO_IRQn);
      NRF_RADIO->INTENSET = B1000;  //interrupt MCU if a packet is received.
      while (NRF_RADIO->INTENSET != B1000) {}  //wait until confirmed
          
      //NRF_GPIOTE->INTENSET = 1;  //interrupt MCU if change detected on pin P0.16.
      //while (NRF_GPIOTE->INTENSET != 1) {}  //wait until confirmed
      
      Serial.print("LFCLKSTAT=0X");
      Serial.print(NRF_CLOCK->LFCLKSTAT,HEX);
      Serial.print("=B");
      Serial.println(NRF_CLOCK->LFCLKSTAT,BIN);
      Serial.flush();
    
      NRF_RADIO->FREQUENCY=123;
      NRF_RADIO->MODE=1;  //set 2Mbps datarate.
      NRF_RADIO->MODECNF0=1;  //enable fast ramp-up of radio from DISABLED state.
    
      if (!nrf51.init())
        Serial.println("init failed");
      mySetNetworkAddress(my_default_network_address, sizeof(my_default_network_address));   
      
      if ((NRF_CLOCK->LFCLKSTAT)>>2) {//if LF clock is running
        NRF_CLOCK->TASKS_LFCLKSTOP=1;  //stop the clock
        while ((NRF_CLOCK->LFCLKSTAT)& 1)  {}  //busy-wait until LF clock has stopped running
        Serial.println("LF clock is stopped.");
      }
    
      Serial.print("LFCLKSTAT=0x");
      Serial.print(NRF_CLOCK->LFCLKSTAT,HEX);
      Serial.print("=B");
      Serial.println(NRF_CLOCK->LFCLKSTAT,BIN);
      Serial.flush();
      
      NRF_CLOCK->LFCLKSRC=1;  //use the crystal oscillator.
      while (!(NRF_CLOCK->LFCLKSRC=1)) {}  //
    
      Serial.println("Crystal oscillator is now the LF choice.");
      Serial.print("LFCLKSTAT=0x");
      Serial.print(NRF_CLOCK->LFCLKSTAT,HEX);
      Serial.print("=B");
      Serial.println(NRF_CLOCK->LFCLKSTAT,BIN);
      Serial.flush();
     
      NRF_CLOCK->TASKS_LFCLKSTART=1;  //start the crystal oscillator clock
    
    
      
      while (!(NRF_CLOCK->EVENTS_LFCLKSTARTED)) {}  //busy-wait until the clock is confirmed started.
      Serial.println("Low Frequency crystal oscillator started.");
      Serial.flush();
    
    
      Serial.print("LFCLKSTAT=0x");
      Serial.print(NRF_CLOCK->LFCLKSTAT,HEX);
      Serial.print("=B");
      Serial.println(NRF_CLOCK->LFCLKSTAT,BIN);
      
      Serial.print("LFCLKSRC=0x");
      Serial.print(NRF_CLOCK->LFCLKSRC,HEX);
      Serial.print("=B");
      Serial.println(NRF_CLOCK->LFCLKSRC,BIN);
      
      Serial.print("Present PRESCALER=");
      Serial.println(NRF_RTC0->PRESCALER);
    
      Serial.print("LFCLKSTAT=0x");
      Serial.print(NRF_CLOCK->LFCLKSTAT,HEX);
      Serial.print("=B");
      Serial.println(NRF_CLOCK->LFCLKSTAT,BIN);
      NRF_RTC0->PRESCALER=0;  //32768 frequency
      while (NRF_RTC0->PRESCALER!=0)  {}  //busy-wait until pre-scaler changes
      Serial.print("New PRESCALER=");
      Serial.println(NRF_RTC0->PRESCALER);
    
      Serial.println();
      Serial.println("Finished setup.");
      Serial.flush();
    
      //Radio enters RXIDLE soon after COUNTER overflows.
      NRF_RTC0->CC[0] = 24;  //the time to exit RX state.
      NRF_RTC0->CC[1] = 25;  //the time to put radio to sleep from RXIDLE
      NRF_RTC0->CC[2] = 3300;  //the time to restart the cycle
    
      NRF_RTC0->EVENTS_COMPARE[0] = 0;  //Clear the event flag.
      NRF_RTC0->EVENTS_COMPARE[1] = 0;  //Clear the event flag.
      NRF_RTC0->EVENTS_COMPARE[2] = 0;  //Clear the event flag.
        
      NRF_RADIO->TASKS_DISABLE=1;  //sleep the radio
      while (NRF_RADIO->STATE) {}; //wait until radio is DISABLED (i.e. STATE=0);
    
      //Configure GPIOTE 
      NRF_GPIOTE->CONFIG[0]=0x31001;  // Toggle Event; Pin P0.16; Event Mode 
                                      //So, any pin change on P0.16 will trigger an event.
                                       //On the Nordic nRF52 DK, Pin 0.16 is a button.
                                       
      NRF_GPIOTE->CONFIG[1]=0x131203;  //Initial setting: HIGH; Toggle Task; Pin P0.18; Task Mode
                                       //On the Nordic nRF52 DK, Pin 0.18 is an LED.
                                       //Note: initial setting of HIGH means that the LED will be initially OFF.
    
      NRF_GPIOTE->CONFIG[2]=0x131103;  //Initial setting: HIGH; Toggle Task; Pin P0.17; Task Mode
                                       //On the Nordic nRF52 DK, Pin P0.17 is an LED.
                                       //Note: initial setting of HIGH means that the LED will be initially OFF.          
    
      
      //Note: radio is assumed to be sleeping by this point, and with high frequency crystal oscillator turned off.
      NRF_PPI->CH[0].EEP = (uint32_t)&NRF_RTC0->EVENTS_OVRFLW;  //when COUNTER overflows.
      NRF_PPI->CH[0].TEP = (uint32_t)&NRF_CLOCK->TASKS_HFCLKSTART;  //turn on the HF crystal oscillator
    
      NRF_PPI->CH[1].EEP = (uint32_t)&NRF_CLOCK->EVENTS_HFCLKSTARTED;  //After HF Clock started.
      NRF_PPI->CH[1].TEP = (uint32_t)&NRF_RADIO->TASKS_RXEN;  //turn on the radio receiver
      //NRF_PPI->FORK[1].TEP = (uint32_t)&NRF_GPIOTE->TASKS_OUT[0]; //Make pin P0.18. be HIGH
    
    
      NRF_PPI->CH[2].EEP = (uint32_t)&NRF_RADIO->EVENTS_READY;  //After event READY, radio shall be in state RXIDLE.
      NRF_PPI->CH[2].TEP = (uint32_t)&NRF_RADIO->TASKS_START;  //Move from RXIDLE mode into RX mode.
    
      NRF_PPI->CH[3].EEP = (uint32_t)&NRF_RTC0->EVENTS_COMPARE[0];  // If time to turn off the radio receiver
      NRF_PPI->CH[3].TEP = (uint32_t)&NRF_RADIO->TASKS_STOP; //Move radio from RX mode back into RXIDLE mode
      
      NRF_PPI->CH[4].EEP = (uint32_t)&NRF_RTC0->EVENTS_COMPARE[1];  // If enough time has passed
      NRF_PPI->CH[4].TEP = (uint32_t)&NRF_RADIO->TASKS_DISABLE; //Sleep the radio
      NRF_PPI->FORK[4].TEP = (uint32_t)&NRF_CLOCK->TASKS_HFCLKSTOP; //Turn off the high frequency crystal oscillator 
      
      NRF_PPI->CH[5].EEP = (uint32_t)&NRF_RTC0->EVENTS_COMPARE[2];  // If 100ms has passed
      NRF_PPI->CH[5].TEP = (uint32_t)&NRF_RTC0->TASKS_TRIGOVRFLW; //Set COUNTER so that it will overflow in 16 ticks.
    
      NRF_PPI->CH[6].EEP = (uint32_t)&NRF_RADIO->EVENTS_END;  //packet received.
      NRF_PPI->CH[6].TEP = (uint32_t)&NRF_GPIOTE->TASKS_OUT[1]; //Make pin P0.18. be LOW (turn on the LED).
    
      NRF_PPI->CH[7].EEP = (uint32_t)&NRF_GPIOTE->EVENTS_IN[0];  //P0.16 pin change occured.
      NRF_PPI->CH[7].TEP = (uint32_t)&NRF_GPIOTE->TASKS_OUT[2]; //Make pin P0.17. be LOW (turn on the LED).
      
      NRF_PPI->CHENSET=B11111111; //enable Channels 7,6,5,4,3,2,1,and 0.
      
      NRF_CLOCK->TASKS_LFCLKSTART=1;  //start the crystal oscillator clock
      
      while (!(NRF_CLOCK->EVENTS_LFCLKSTARTED)) {}  //busy-wait until the clock is confirmed started.
      Serial.println("Crystal oscillator started.");
      Serial.flush();
    
      NRF_RTC0->EVTENSET=0x70003;  //enable routing of RTC TICK, OVRFLW, and comparison events to PPI for the comparisons
      while (NRF_RTC0->EVTEN!= (0x70003)) {};  //wait until EVTENSET setting is confirmed.
      
      NRF_RTC0->EVENTS_TICK=0;  //clear TICKS flag
      NRF_RTC0->EVENTS_OVRFLW=0;  //clear overflow flag
      NRF_RADIO->EVENTS_END=0;  //clear payload received flag.
    
      NRF_CLOCK->TASKS_HFCLKSTOP=1;  //Turn off the high frequency crystal oscillator.
      NRF_RTC0->TASKS_TRIGOVRFLW=1;  //prepare COUNTER so that an overflow will ensue in 16 ticks.
      while (NRF_RTC0->COUNTER!=0xFFFFF0) {} //wait until COUNTER is primed to overflow.
      NRF_RTC0->TASKS_START=1;  //  Resume the RTC, which had been paused.
      while ((NRF_RTC0->EVENTS_TICK==0)) {}  //wait until the radio is confirmed to be started.
    }
    uint32_t loopCounter=0;
    void loop() {
    
      
      Serial.print("time=");
      Serial.print(millis());
      Serial.print(", packetCounter=");
      Serial.println(packetCounter);
      
      Serial.flush();
      
      myHwSleep(500000000);  //sleep 100ms.  Already offset in setup by 1ms from wake-up of PPI.
    }
    
    
    // * Reset events and read back on nRF52
    //* http://infocenter.nordicsemi.com/pdf/nRF52_Series_Migration_v1.0.pdf
     
    #if __CORTEX_M == 0x04
    #define NRF5_RESET_EVENT(event)                                                 \
            event = 0;                                                                   \
            (void)event
    #else
    #define NRF5_RESET_EVENT(event) event = 0
    #endif
    
    
    // This must be in one line
    extern "C" { void RADIO_IRQHandler(void) {packetCounter++; NRF5_RESET_EVENT(NRF_RADIO->EVENTS_END); NRF_RADIO->EVENTS_END=0; }}
    
    
    

    The PPI does toggle an LED each time it receives a packet, but unfortunately the CPU remains asleep. Nonetheless, it does seem to follow your prescription for the ISR.



  • @NeverDie
    What if you activate a pin change interrupt/wake at the pin the PPI toggles?
    Or connect it to another pin with pin change wake?


  • Hero Member

    @Uhrheber said in nRF5 Bluetooth action!:

    @NeverDie
    What if you activate a pin change interrupt/wake at the pin the PPI toggles?
    Or connect it to another pin with pin change wake?

    Yes, I have tested that as a workaround. It "works", but using GPIO pins increases the current drain.


  • Hero Member

    Well, I guess it's almost moot now, because I found and tested a better workaround. I re-wrote the PPI code so that after packet receipt, the PPI triggers an RTC0 overflow. It is that which is then used to wake-up the MCU. No GPIO pins need be involved, so no propagation delays and no increase in current drawn. It works.

    I still think the radio ISR code (above) should have worked, but fortunately that's no longer holding me back now that I have a good enough workaround. 🙂


  • Hero Member

    However, there's one fly in the ointment remaining. It turns out that some other timer is sometimes waking up the CPU:

    time=15798, Radio STATE=0, COUNTER=0x49, packetCounter=22
    time=15900, Radio STATE=0, COUNTER=0x49, packetCounter=23
    time=16001, Radio STATE=0, COUNTER=0x49, packetCounter=24
    time=16103, Radio STATE=0, COUNTER=0x49, packetCounter=25
    time=16204, Radio STATE=0, COUNTER=0x49, packetCounter=26
    time=16306, Radio STATE=0, COUNTER=0x49, packetCounter=27
    time=512000, Radio STATE=0, COUNTER=0x2035, packetCounter=27
    time=1024000, Radio STATE=0, COUNTER=0x269, packetCounter=27
    time=1536000, Radio STATE=0, COUNTER=0x1803, packetCounter=27
    time=2048000, Radio STATE=3, COUNTER=0x36, packetCounter=27
    time=2560000, Radio STATE=0, COUNTER=0x1570, packetCounter=27
    time=3072000, Radio STATE=0, COUNTER=0x3104, packetCounter=27
    time=3584000, Radio STATE=0, COUNTER=0x1337, packetCounter=27
    time=4096000, Radio STATE=0, COUNTER=0x2871, packetCounter=27
    time=4608000, Radio STATE=0, COUNTER=0x1104, packetCounter=27
    time=5120000, Radio STATE=0, COUNTER=0x2638, packetCounter=27
    

    All the lines labelled packetCounter=27 (after the first one that is) are a result of this. Looking at the time, they appear to happen on the rollover of some other timer (?)--apparently the one that is responsible for keeping track of millis(). I can filter them out after-the-fact, but I'd rather they not be waking up the CPU for no reason, as that is just a waste of energy.


  • Contest Winner

    @NeverDie said in nRF5 Bluetooth action!:

    @d00616
    Can you see any reason as to why the radio isn't waking the MCU after it receives a packet? Here's the entire sketch:

    I have no Idea why. The code is looking fine.


Log in to reply
 

Suggested Topics

  • 8
  • 2
  • 44
  • 1
  • 7
  • 90

11
Online

11.4k
Users

11.1k
Topics

112.7k
Posts