#include <SPI.h>
//#include <nRF24L01.h>
#include <RF24.h>
#include <Button.h>
#define RADIO_CE_PIN 7
#define RADIO_CS_PIN 6
RF24 radio(RADIO_CE_PIN, RADIO_CS_PIN); // CE, CSN pins
const byte address[6] = "00001";
const int txButtonPin = 2; // Pin connected to the button
const int txLedPin = 12;
const char text[13] = "Hello, world!";
byte lastAckTimeMs = 0;
bool lastSendResult = true;
Button txButton(txButtonPin); // Connect your button between pin 2 and GND
void setup() {
Serial.begin(9600);
pinMode(txLedPin, OUTPUT); // Initialize LED pin as output
//radio.begin();
radio.openWritingPipe(address);
radio.setPALevel(RF24_PA_HIGH);
radio.setRetries(15, 15);
//------- added 17/08/2025
radio.setChannel(115);
radio.setAutoAck(true);
radio.setPayloadSize(sizeof(text));
radio.openReadingPipe(1, address);
radio.begin();
// ------------------
txButton.begin();
}
void loop() {
toggleTxButton();
}
void toggleTxButton() {
// Toggled txButton
if (txButton.toggled()) {
if (txButton.read() == Button::PRESSED) {
Serial.println("txButton has been pressed: activate transmission");
digitalWrite(txLedPin, HIGH);
// Stop listening, send data, then start listening again
radio.stopListening(); // Prepare for transmission
radio.printPrettyDetails();
randomSeed(analogRead(0));
sendData();
delay(500); // Debounce delay
radio.startListening(); // Switch back to receiving mode
} else {
Serial.println("txButton has been released: stop transmission");
digitalWrite(txLedPin, LOW);
// Check for incoming data
receiveData();
}
}
}
void sendData() {
// if (!radio.begin()) {
// Serial.println(F("Radio hardware is not responding!"));
// while (1) {} // hold in infinite loop
// }
Serial.print("Sending: ");
Serial.println(text); // Print the data being sent
unsigned long startTime = millis();
lastSendResult = radio.write(&text, sizeof(text));
unsigned long currentTime = millis();
lastAckTimeMs = currentTime - startTime;
// Serial.print("Tx Start Time: ");
// Serial.print(startTime);
// Serial.print(", Tx Current Time: ");
// Serial.print(currentTime);
// Serial.print(", Last Ack Time MS: ");
// Serial.println(lastAckTimeMs);
if (lastSendResult) {
Serial.println("Data sent.");
} else {
Serial.println("Data send failed.");
}
delay(1000); // Small delay to ensure stability
}
void receiveData() {
// if (!radio.begin()) {
// Serial.println(F("Radio hardware is not responding!"));
// while (1) {} // hold in infinite loop
// }
radio.startListening(); // Ensure the radio is in listening mode
if (radio.available()) {
char text[32] = "";
radio.read(&text, sizeof(text));
// Print the received data
Serial.print("Received: '");
Serial.print(text);
Serial.println("'");
// Debugging: Print each character in hexadecimal
for (int i = 0; i < sizeof(text); i++) {
Serial.print(text[i], HEX);
Serial.print(" ");
}
Serial.println();
} else {
Serial.println("No data received.");
}
}