# Latching Button Code not Working over NRF24L01

**URL:** <https://forum.arduino.cc/t/latching-button-code-not-working-over-nrf24l01/988792>\
**Category:** Programming\
**Created:** [May 6, 2022, 1:49am UTC](https://forum.arduino.cc/t/latching-button-code-not-working-over-nrf24l01/988792 "2022-05-06T01:49:04Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![jedunlimited](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/jedunlimited/32/1013044_2.png) [@jedunlimited](https://forum.arduino.cc/u/jedunlimited)\
**Post date:** [May 6, 2022, 1:49am UTC](https://forum.arduino.cc/t/latching-button-code-not-working-over-nrf24l01/988792/1 "2022-05-06T01:49:04Z")

</div>

Please help. I put together some code to try and create a latching button for a project of mine. End goal I want to use the code to move motors one way with 1 click, and reverse that direction with another button click. For now I am just trying to get my boards to communicate a latching command to an led. I've tried the below code but it just wont work. Any help at all would be greatly appreciated

```cpp
TRANSMITTER
#include "nRF24L01.h" //NRF24L01 library created by TMRh20 https://github.com/TMRh20/RF24 
#include "RF24.h"
#include "SPI.h"

#define SwitchPin 2 

int SentMessage[1] = {000}; 
RF24 radio(9,10); // NRF24L01 used SPI pins + Pin 9 and 10 on the NANO

const uint64_t pipe = 0xE6E6E6E6E6E6; // Needs to be the same for communicating between 2 NRF24L01 

void setup()
{
  pinMode(SwitchPin, INPUT_PULLUP); 
  digitalWrite(SwitchPin,HIGH); 
  
  radio.begin(); // Start the NRF24L01
  radio.openWritingPipe(pipe); // Get NRF24L01 ready to transmit
}

void loop()
{
  if (digitalRead(SwitchPin) == LOW) // If switch is pressed
  { 
      SentMessage[0] = 111;
      radio.write(SentMessage, 1); // Send pressed data to NRF24L01
  }
  else 
  {
      SentMessage[0] = 000;
      radio.write(SentMessage, 1); // Send idle data to NRF24L01
  }
}

RECEIVER
#include "nRF24L01.h" // NRF24L01 library created by TMRh20 https://github.com/TMRh20/RF24 
#include "RF24.h"
#include "SPI.h"

#define LED_PIN 2

int flag= 1; //set flag to 1
int ReceivedMessage[1] = {000}; // Used to store value received by the NRF24L01
RF24 radio(9,10); // NRF24L01 SPI pins. Pin 9 and 10 on the Nano

const uint64_t pipe = 0xE6E6E6E6E6E6; // Needs to be the same for communicating between 2 NRF24L01 

void setup(void)
{
  radio.begin(); // Start the NRF24L01
  
  radio.openReadingPipe(1,pipe); // Get NRF24L01 ready to receive
  
  radio.startListening(); // Listen to see if information received
  
  pinMode(LED_PIN, OUTPUT); 
}

void loop(void)
{
  while (radio.available())
  {
    radio.read(ReceivedMessage, 1); // Read information from the NRF24L01

    if (ReceivedMessage[0] == 111) // Indicates switch is pressed
    {
      if (flag ==1) {
	digitalWrite(LED_PIN, HIGH);
         }

      else {
	digitalWrite(LED_PIN, LOW);
	}
      flag= -flag; // inverts flag
    }
    delay(2);
    }
}

```

---

<div class="post-metadata">

**Author:** ![groundFungus](https://avatars.discourse-cdn.com/v4/letter/g/73ab20/32.png) [@groundFungus](https://forum.arduino.cc/u/groundFungus)\
**Post date:** [May 6, 2022, 4:58am UTC](https://forum.arduino.cc/t/latching-button-code-not-working-over-nrf24l01/988792/2 "2022-05-06T04:58:08Z")

</div>

> [@jedunlimited](#):
>
> it just wont work

That is not a very detailed description of the problem. You should describe what the code actually does and how that differs from what you want.

I tried your code on a couple of Unos on mine. It kind of works. When I press the button the LED sometimes toggles but sometimes not. It is not consistent. Since you send every time through loop the receiver is getting spammed. I suggest not sending quite so often.

If you don't mind, here is how I would do it. This uses the [state change detection method](https://forum.arduino.cc/t/state-change-detection-for-active-low-inputs/680899) and example code from [Robin2's simple rf24 tutorial](https://forum.arduino.cc/t/simple-nrf24l01-2-4ghz-transceiver-demo/405123). The push button toggles the mode and the mode is sent to the receiver. The transmitter code only sends when the mode changes. The [blink without delay method](https://docs.arduino.cc/built-in-examples/digital/BlinkWithoutDelay) is used for timing the button reads.

Transmitter with button:

```arduino
// transmit the toggled button state 
// by c goulding aka groundfungus

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

const byte CE_PIN = 9;
const byte CSN_PIN = 10;
const byte buttonPin = 2;

const byte slaveAddress[5] = {'R', 'x', 'A', 'A', 'A'};

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

int dataToSend = 0;

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000; // send once per second

void setup()
{

   Serial.begin(115200);
   Serial.println("SimpleTx Starting");

   pinMode(buttonPin, INPUT_PULLUP);

   radio.begin();
   //RF24_1MBPS, RF24_2MBPS, RF24_250KBPS
   radio.setDataRate( RF24_250KBPS );
   radio.setRetries(3, 5); // delay, count
   //radio.setChannel(10);
   //RF24_PA_MIN = 0,RF24_PA_LOW, RF24_PA_HIGH, RF24_PA_MAX
   radio.setPALevel(RF24_PA_LOW);
   radio.openWritingPipe(slaveAddress);
}

//====================

void loop()
{
   static bool mode = 0;
   static bool lastButtonState = HIGH;
   static unsigned long timer = 0;
   unsigned long interval = 50;
   if (millis() - timer >= interval)
   {
      timer = millis();
      bool buttonState = digitalRead(buttonPin);
      if (buttonState != lastButtonState)
      {
         if (buttonState == LOW)
         {
            mode = !mode;
            dataToSend = mode;
            send();
         }
         lastButtonState = buttonState;
      }
   }
}

//====================

void send()
{
   bool rslt;
   rslt = radio.write( &dataToSend, sizeof(dataToSend) );
   // Always use sizeof() as it gives the size as the number of bytes.
   // For example if dataToSend was an int sizeof() would correctly return 2

   Serial.print("Data Sent ");
   Serial.print(dataToSend);
   if (rslt)
   {
      Serial.println(" Acknowledge received");
   }
   else
   {
      Serial.println(" Tx failed");
   }
}

```

Receiver code with LED:

```arduino
// receive the toggled button state and light the LED
// by c goulding aka groundfungus

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

const byte CE_PIN = 9;
const byte CSN_PIN = 10;
const byte ledPin = 2;

const byte thisSlaveAddress[5] = {'R', 'x', 'A', 'A', 'A'};

RF24 radio(CE_PIN, CSN_PIN);

int recvData;

bool newData = false;

//===========

void setup()
{
   Serial.begin(115200);
   Serial.println("SimpleRx Starting");

   pinMode(ledPin, OUTPUT);
   
   radio.begin();
   radio.setDataRate( RF24_250KBPS );
   radio.setRetries(3, 5); // delay, count
   radio.setPALevel(RF24_PA_LOW);
   radio.openReadingPipe(1, thisSlaveAddress);
   radio.startListening();
}

//=============

void loop()
{
   getData();
   showData();   
}

//==============

void getData()
{
   if ( radio.available() )
   {
      radio.read( &recvData, sizeof(recvData) );
      newData = true;
   }
}

void showData()
{
   if (newData == true)
   {
      Serial.print("Data received >> ");
      Serial.print("number = ");
      Serial.println(recvData);

      digitalWrite(ledPin, recvData); // light the LED (or not)
      newData = false;   
   }
}

```

---

<div class="post-metadata">

**Author:** ![johnwasser](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/johnwasser/32/214270_2.png) [@johnwasser](https://forum.arduino.cc/u/johnwasser)\
**Post date:** [May 6, 2022, 4:58pm UTC](https://forum.arduino.cc/t/latching-button-code-not-working-over-nrf24l01/988792/3 "2022-05-06T16:58:40Z")

</div>

> [@groundFungus](#):
>
> `rslt = radio.write( &dataToSend, sizeof(dataToSend) );`

One strange thing about the original code:

```arduino
int SentMessage[1] = {000}; 
      SentMessage[0] = 111;
      radio.write(SentMessage, 1); // Send pressed data to NRF24L01

int ReceivedMessage[1] = {000}; // Used to store value received by the NRF24L01
    radio.read(ReceivedMessage, 1); // Read information from the NRF24L01
    if (ReceivedMessage[0] == 111) // Indicates switch is pressed

```

The 'message' is an array of one 'int' but the code seems to be sending and receiving only one byte of the message.

---

<div class="post-metadata">

**Author:** ![jedunlimited](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/jedunlimited/32/1013044_2.png) [@jedunlimited](https://forum.arduino.cc/u/jedunlimited)\
**Post date:** [May 6, 2022, 10:50pm UTC](https://forum.arduino.cc/t/latching-button-code-not-working-over-nrf24l01/988792/4 "2022-05-06T22:50:41Z")

</div>

So how exactly should I fix that. I’ve been fighting this whole latched button for several weeks now and I’m out of ideas at this point.

---

<div class="post-metadata">

**Author:** ![jedunlimited](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/jedunlimited/32/1013044_2.png) [@jedunlimited](https://forum.arduino.cc/u/jedunlimited)\
**Post date:** [May 7, 2022, 1:05am UTC](https://forum.arduino.cc/t/latching-button-code-not-working-over-nrf24l01/988792/5 "2022-05-07T01:05:08Z")

</div>

Maybe these will help. I’m using an Arduino nano and a button board

 ![image](https://europe1.discourse-cdn.com/arduino/original/4X/6/f/e/6fec981e809c4c56ee763dddea258441d36d430f.jpeg)

---

<div class="post-metadata">

**Author:** ![jedunlimited](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/jedunlimited/32/1013044_2.png) [@jedunlimited](https://forum.arduino.cc/u/jedunlimited)\
**Post date:** [May 7, 2022, 1:05am UTC](https://forum.arduino.cc/t/latching-button-code-not-working-over-nrf24l01/988792/6 "2022-05-07T01:05:45Z")

</div>

![image](https://europe1.discourse-cdn.com/arduino/original/4X/c/9/b/c9bbd5eecc9ea89df46eaa02598f7a7188f65087.jpeg)

---

<div class="post-metadata">

**Author:** ![jedunlimited](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/jedunlimited/32/1013044_2.png) [@jedunlimited](https://forum.arduino.cc/u/jedunlimited)\
**Post date:** [May 7, 2022, 1:06am UTC](https://forum.arduino.cc/t/latching-button-code-not-working-over-nrf24l01/988792/7 "2022-05-07T01:06:27Z")

</div>

![image](https://europe1.discourse-cdn.com/arduino/original/4X/e/f/1/ef10811380d9be741dbc94ede93e779a9e6efaca.jpeg)

---

<div class="post-metadata">

**Author:** ![jedunlimited](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/jedunlimited/32/1013044_2.png) [@jedunlimited](https://forum.arduino.cc/u/jedunlimited)\
**Post date:** [May 7, 2022, 1:07am UTC](https://forum.arduino.cc/t/latching-button-code-not-working-over-nrf24l01/988792/8 "2022-05-07T01:07:52Z")

</div>

I tried the new code and when I press the button on the transmitter nothing happens to the led in the receiver. Of note when plugged into my computer power the LED on the receiver constantly flickers but stays on

---

<div class="post-metadata">

**Author:** ![6v6gt](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/6v6gt/32/225488_2.png) [@6v6gt](https://forum.arduino.cc/u/6v6gt)\
**Post date:** [May 7, 2022, 1:25am UTC](https://forum.arduino.cc/t/latching-button-code-not-working-over-nrf24l01/988792/9 "2022-05-07T01:25:09Z")

</div>

Apart from what has already been pointed out:

1. Wrong size parameter.
2. Transmission frequency too high.

the original code is flawed because a button press on the transmitter can result in a group of multiple consecutive transmissions of the value 111. However, the receiver treats each received individual 111 as an instruction to toggle the state.  
Instead, the receiver should watch for the end of a series of transmissions of 111 then toggle the state.

---

<div class="post-metadata">

**Author:** ![oldguyjn](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/oldguyjn/32/774597_2.png) [@oldguyjn](https://forum.arduino.cc/u/oldguyjn)\
**Post date:** [May 10, 2022, 8:57pm UTC](https://forum.arduino.cc/t/latching-button-code-not-working-over-nrf24l01/988792/10 "2022-05-10T20:57:55Z")

</div>

Hi groundFungus  
I dont know if the message was meant for myself I was repling to a post by another forum member I appreciate all help and advice from all members as I would not be able to achieve the basics without the contribution of forum members.  
Thanks again  
oldguyjn

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [November 6, 2022, 8:58pm UTC](https://forum.arduino.cc/t/latching-button-code-not-working-over-nrf24l01/988792/11 "2022-11-06T20:58:34Z")

</div>

Closed on November 6, 2022, 8:58pm UTC

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.
