A simple example of sending data from 1 nRF24L01 transceiver to another.
This example was written to be used on 2 devices acting as "nodes". Use the Serial Monitor to change each node's behavior.
1
2
3
4
5
6
13#include <SPI.h>
16
17#define CE_PIN 7
18#define CSN_PIN 8
19
20RF24 radio(CE_PIN, CSN_PIN);
21
22
23uint8_t address[][6] = { "1Node", "2Node" };
24
25
26
27
28
29bool radioNumber = 1;
30
31
32bool role = false;
33
34
35
36
37float payload = 0.0;
38
39void setup() {
40
41 Serial.begin(115200);
42 while (!Serial) {
43
44 }
45
46
47 if (!radio.begin()) {
48 Serial.println(F("radio hardware is not responding!!"));
49 while (1) {}
50 }
51
52
53 Serial.println(F("RF24/examples/GettingStarted"));
54
55
56 Serial.println(F("Which radio is this? Enter '0' or '1'. Defaults to '0'"));
57 while (!Serial.available()) {
58
59 }
60 char input = Serial.parseInt();
61 radioNumber = input == 1;
62 Serial.print(F("radioNumber = "));
63 Serial.println((int)radioNumber);
64
65
66 Serial.println(F("*** PRESS 'T' to begin transmitting to the other node"));
67
68
69
70
72
73
74
75 radio.setPayloadSize(sizeof(payload));
76
77
78 radio.stopListening(address[radioNumber]);
79
80
81 radio.openReadingPipe(1, address[!radioNumber]);
82
83
84 if (!role) {
85 radio.startListening();
86 }
87
88
89
90
91
92
93}
94
95void loop() {
96
97 if (role) {
98
99
100 unsigned long start_timer = micros();
101 bool report = radio.write(&payload, sizeof(float));
102 unsigned long end_timer = micros();
103
104 if (report) {
105 Serial.print(F("Transmission successful! "));
106 Serial.print(F("Time to transmit = "));
107 Serial.print(end_timer - start_timer);
108 Serial.print(F(" us. Sent: "));
109 Serial.println(payload);
110 payload += 0.01;
111 } else {
112 Serial.println(F("Transmission failed or timed out"));
113 }
114
115
117
118 } else {
119
120
121 uint8_t pipe;
122 if (radio.available(&pipe)) {
123 uint8_t bytes = radio.getPayloadSize();
124 radio.read(&payload, bytes);
125 Serial.print(F("Received "));
126 Serial.print(bytes);
127 Serial.print(F(" bytes on pipe "));
128 Serial.print(pipe);
129 Serial.print(F(": "));
130 Serial.println(payload);
131 }
132 }
133
134 if (Serial.available()) {
135
136
137 char c = toupper(Serial.read());
138 if (c == 'T' && !role) {
139
140
141 role = true;
142 Serial.println(F("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK"));
143 radio.stopListening();
144
145 } else if (c == 'R' && role) {
146
147
148 role = false;
149 Serial.println(F("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK"));
150 radio.startListening();
151 }
152 }
153
154}
Driver class for nRF24L01(+) 2.4GHz Wireless Transceiver.