Nrf24L01-2
Jump to navigation
Jump to search
Nrf24L01-2.4GHz-ExampleSketches
These are example Arduino software sketches that show how to use the nRF24L01 radio modules.
Start with our overall nRF24L01 Information and How-To HERE to make sure you connect the nRF24L01 modules correctly. Consider using one of the "base modules" to get stable 3.3V DC power to your modules. Otherwise consider soldering capacitors across Vcc and Gnd on your modules. See the How-To..
Below are the different examples as they are written and tested here. Click on the names below. There are also many examples that come with the RF24 library and you can find them HERE
- [/Nrf24L01-2.4GHz-ExampleSketches#bm1 BARE MINIMUM EXAMPLE]
- [/Nrf24L01-2.4GHz-ExampleSketches#js1 TRANSMIT JOYSTICK POSITION DATA TO ANOTHER ARDUINO WITH 2 SERVOS]
Bare Minimum example:
This is not a very good example for practical use, but it details the few minimum things you need to do to create radio sketches that work for nRF24L01 Transmit and Receive. Copy and paste these examples into a BLANK window on your Arduino IDE. VERIFY to check them out. You NEED the RF24 library downloaded and installed. See the How-To.
nRF24L01-SimpleTransmit-01
/* YourDuinoStarter Example: Simple nRF24L01 Transmit - WHAT IT DOES: Transmits simple fixed data with nRF24L01 radio - SEE the comments after "//" on each line below Start with radios about 4 feet apart. - SEE the comments after "//" on each line below - CONNECTIONS: nRF24L01 Modules See: https://arduinoinfo.mywikis.net/wiki/Nrf24L01-2.4GHz-HowTo Uses the RF24 Library by TMRH2o here: https://github.com/TMRh20/RF24 1 - GND 2 - VCC 3.3V !!! NOT 5V 3 - CE to Arduino pin 7 4 - CSN to Arduino pin 8 5 - SCK to Arduino pin 13 6 - MOSI to Arduino pin 11 7 - MISO to Arduino pin 12 8 - UNUSED V1.02 02/06/2016 Questions: terry@yourduino.com */ /*-----( Import needed libraries )-----*/ #include <SPI.h> // Comes with Arduino IDE #include "RF24.h" // Download and Install (See above) /*-----( Declare Constants and Pin Numbers )-----*/ //None yet /*-----( Declare objects )-----*/ // (Create an instance of a radio, specifying the CE and CS pins. ) RF24 myRadio (7, 8); // "myRadio" is the identifier you will use in following methods /*-----( Declare Variables )-----*/ byte addresses[][6] = {"1Node"}; // Create address for 1 pipe. int dataTransmitted; // Data that will be Transmitted from the transmitter void setup() /****** SETUP: RUNS ONCE ******/ { // Use the serial Monitor (Symbol on far right). Set speed to 115200 (Bottom Right) Serial.begin(115200); delay(1000); Serial.println(F("RF24/Simple Transmit data Test")); Serial.println(F("Questions: terry@yourduino.com")); dataTransmitted = 100; // Arbitrary known data to transmit. Change it to test... myRadio.begin(); // Start up the physical nRF24L01 Radio myRadio.setChannel(108); // Above most Wifi Channels // Set the PA Level low to prevent power supply related issues since this is a // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default. myRadio.setPALevel(RF24_PA_MIN); // myRadio.setPALevel(RF24_PA_MAX); // Uncomment for more power myRadio.openWritingPipe( addresses[0]); // Use the first entry in array 'addresses' (Only 1 right now) delay(1000); }//--(end setup )--- void loop() /****** LOOP: RUNS CONSTANTLY ******/ { myRadio.write( &dataTransmitted, sizeof(dataTransmitted) ); // Transmit the data Serial.print(F("Data Transmitted = ")); Serial.print(dataTransmitted); Serial.println(F(" No Acknowledge expected")); dataTransmitted = dataTransmitted + 1; // Send different data next time delay(500); }//--(end main loop )--- /*-----( Declare User-written Functions )-----*/ //*********( THE END )***********
nRF24L01-SimpleReceive-01
/* YourDuinoStarter Example: Simple nRF24L01 Receive - WHAT IT DOES: Receives simple fixed data with nRF24L01 radio - SEE the comments after "//" on each line below Start with radios about 4 feet apart. - SEE the comments after "//" on each line below - CONNECTIONS: nRF24L01 Modules See: https://arduinoinfo.mywikis.net/wiki/Nrf24L01-2.4GHz-HowTo Uses the RF24 Library by TMRH2o here: https://github.com/TMRh20/RF24 1 - GND 2 - VCC 3.3V !!! NOT 5V 3 - CE to Arduino pin 7 4 - CSN to Arduino pin 8 5 - SCK to Arduino pin 13 6 - MOSI to Arduino pin 11 7 - MISO to Arduino pin 12 8 - UNUSED V1.02 02/06/2016 Questions: terry@yourduino.com */ /*-----( Import needed libraries )-----*/ #include <SPI.h> // Comes with Arduino IDE #include "RF24.h" // Download and Install (See above) /*-----( Declare Constants and Pin Numbers )-----*/ //None yet /*-----( Declare objects )-----*/ // (Create an instance of a radio, specifying the CE and CS pins. ) RF24 myRadio (7, 8); // "myRadio" is the identifier you will use in following methods /*-----( Declare Variables )-----*/ byte addresses[][6] = {"1Node"}; // Create address for 1 pipe. int dataReceived; // Data that will be received from the transmitter void setup() /****** SETUP: RUNS ONCE ******/ { // Use the serial Monitor (Symbol on far right). Set speed to 115200 (Bottom Right) Serial.begin(115200); delay(1000); Serial.println(F("RF24/Simple Receive data Test")); Serial.println(F("Questions: terry@yourduino.com")); myRadio.begin(); // Start up the physical nRF24L01 Radio myRadio.setChannel(108); // Above most Wifi Channels // Set the PA Level low to prevent power supply related issues since this is a // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default. myRadio.setPALevel(RF24_PA_MIN); // myRadio.setPALevel(RF24_PA_MAX); // Uncomment for more power myRadio.openReadingPipe(1, addresses[0]); // Use the first entry in array 'addresses' (Only 1 right now) myRadio.startListening(); }//--(end setup )--- void loop() /****** LOOP: RUNS CONSTANTLY ******/ { if ( myRadio.available()) // Check for incoming data from transmitter { while (myRadio.available()) // While there is data ready { myRadio.read( &dataReceived, sizeof(dataReceived) ); // Get the data payload (You must have defined that already!) } // DO something with the data, like print it Serial.print("Data received = "); Serial.println(dataReceived); } //END Radio available }//--(end main loop )--- /*-----( Declare User-written Functions )-----*/ //None yet //*********( THE END )***********
TRANSMIT JOYSTICK POSITION DATA TO ANOTHER ARDUINO WITH 2 SERVOS
These examples include a full round-trip error checking and acknowledge system. They use many of the features of the nRF24L01 Radios and the RF24 Library by TMRH2O such as setting the channel frequency and the power output level. They print the activity and data received on the Serial Monitor at 115200 speed.
OPTIONS: Hardware - This version defaults to using fixed data with no required Joystick or Servos, for test purposes. There is a variable in both sketches called 'hasHardware' which is set to 'false'. When you have joystick and/or servo hardware connected then set hasHardware = true;
OPTIONS: Radio RF Power Level - If you get your radios communicating OK and you think you have good 3.3V power, you can set the RF Power Amplifier to "RF24_PA_MAX". It is initially set to "RF24_PA_LOW" to be less sensitive to poor 3.3V power. See This Page about nRY24L01 problems, power solutions. We strongly recommend the 'base modules' to get reliable information.
SERVOS: Servos draw a lot of current and will not work when the Arduino is powered from USB. You must use some external 5V power supply for the servos. The YourDuino RoboRED pictured on the How-to page has a built-in 5V 2A power supply that can run 2 servos when the External power connector is supplied with 9 to 12V.
SKETCH: JOYSTICK DATA TRANSMITTED TO ANOTHER ARDUINO
(Cut and paste into a blank Arduino IDE window)
/* YourDuinoStarter Example: nRF24L01 Radio Remote control: Joystick to Servos - WHAT IT DOES Joystick on this Arduino communicates by nRF25L01 Radio to a second Arduino with an nRF24L01 radio and 2 pan-tilt servos SEE: The variable 'hasHardware'. You can test without Joystick and later set hasHardware = true; - SEE the comments after "//" on each line below - CONNECTIONS: - nRF24L01 Radio Module: See https://arduinoinfo.mywikis.net/wiki/Nrf24L01-2.4GHz-HowTo 1 - GND 2 - VCC 3.3V !!! NOT 5V 3 - CE to Arduino pin 7 4 - CSN to Arduino pin 8 5 - SCK to Arduino pin 13 6 - MOSI to Arduino pin 11 7 - MISO to Arduino pin 12 8 - UNUSED - V2.12 02/08/2016 - Uses the RF24 Library by TMRH20 and Maniacbug: https://github.com/TMRh20/RF24 (Download ZIP) Questions: terry@yourduino.com */ /*-----( Import needed libraries )-----*/ #include <SPI.h> // Comes with Arduino IDE #include "RF24.h" // Download and Install (See above) #include "printf.h" // Needed for "printDetails" Takes up some memory /*-----( Declare Constants and Pin Numbers )-----*/ #define CE_PIN 7 // The pins to be used for CE and SN #define CSN_PIN 8 #define JOYSTICK_X A0 // The Joystick potentiometers connected to Arduino Analog inputs #define JOYSTICK_Y A1 #define JOYSTICK_SW A2 // The Joystick push-down switch, will be used as a Digital input /*-----( Declare objects )-----*/ /* Hardware configuration: Set up nRF24L01 radio on SPI bus plus (usually) pins 7 & 8 (Can be changed) */ RF24 radio(CE_PIN, CSN_PIN); /*-----( Declare Variables )-----*/ byte addresses[][6] = {"1Node", "2Node"}; // These will be the names of the "Pipes" unsigned long timeNow; // Used to grab the current time, calculate delays unsigned long started_waiting_at; boolean timeout; // Timeout? True or False // Allows testing of radios and code without Joystick hardware. Set 'true' when joystick connected boolean hasHardware = false; //boolean hasHardware = true; /** Create a data structure for transmitting and receiving data This allows many variables to be easily sent and received in a single transmission See http://www.cplusplus.com/doc/tutorial/structures/ */ struct dataStruct { unsigned long _micros; // to save response times int Xposition; // The Joystick position values int Yposition; bool switchOn; // The Joystick push-down switch } myData; // This can be accessed in the form: myData.Xposition etc. void setup() /****** SETUP: RUNS ONCE ******/ { Serial.begin(115200); // MUST reset the Serial Monitor to 115200 (lower right of window ) // NOTE: The "F" in the print statements means "unchangable data; save in Flash Memory to conserve SRAM" Serial.println(F("YourDuino.com Example: Send joystick data by nRF24L01 radio to another Arduino")); printf_begin(); // Needed for "printDetails" Takes up some memory pinMode(JOYSTICK_SW, INPUT_PULLUP); // Pin A2 will be used as a digital input radio.begin(); // Initialize the nRF24L01 Radio radio.setChannel(108); // Above most WiFi frequencies radio.setDataRate(RF24_250KBPS); // Fast enough.. Better range // Set the Power Amplifier Level low to prevent power supply related issues since this is a // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default. // PALevelcan be one of four levels: RF24_PA_MIN, RF24_PA_LOW, RF24_PA_HIGH and RF24_PA_MAX radio.setPALevel(RF24_PA_LOW); // radio.setPALevel(RF24_PA_MAX); // Open a writing and reading pipe on each radio, with opposite addresses radio.openWritingPipe(addresses[0]); radio.openReadingPipe(1, addresses[1]); // Start the radio listening for data radio.startListening(); // radio.printDetails(); //Uncomment to show LOTS of debugging information }//--(end setup )--- void loop() /****** LOOP: RUNS CONSTANTLY ******/ { radio.stopListening(); // First, stop listening so we can talk. if (hasHardware) // Set in variables at top { /*********************( Read the Joystick positions )*************************/ myData.Xposition = analogRead(JOYSTICK_X); myData.Yposition = analogRead(JOYSTICK_Y); myData.switchOn = !digitalRead(JOYSTICK_SW); // Invert the pulldown switch } else { myData.Xposition = 256; // Send some known fake data myData.Yposition = 512; } myData._micros = micros(); // Send back for timing Serial.print(F("Now sending - ")); if (!radio.write( &myData, sizeof(myData) )) { // Send data, checking for error ("!" means NOT) Serial.println(F("Transmit failed ")); } radio.startListening(); // Now, continue listening started_waiting_at = micros(); // timeout period, get the current microseconds timeout = false; // variable to indicate if a response was received or not while ( ! radio.available() ) { // While nothing is received if (micros() - started_waiting_at > 200000 ) { // If waited longer than 200ms, indicate timeout and exit while loop timeout = true; break; } } if ( timeout ) { // Describe the results Serial.println(F("Response timed out - no Acknowledge.")); } else { // Grab the response, compare, and send to Serial Monitor radio.read( &myData, sizeof(myData) ); timeNow = micros(); // Show it Serial.print(F("Sent ")); Serial.print(timeNow); Serial.print(F(", Got response ")); Serial.print(myData._micros); Serial.print(F(", Round-trip delay ")); Serial.print(timeNow - myData._micros); Serial.println(F(" microseconds ")); } // Send again after delay. When working OK, change to something like 100 delay(100); }//--(end main loop )--- /*-----( Declare User-written Functions )-----*/ // NONE YET //*********( THE END )***********
SKETCH: JOYSTICK DATA RECEIVED FROM ANOTHER ARDUINO
(Cut and paste into a blank Arduino IDE window)
/* YourDuinoStarter Example: nRF24L01 Radio remote control of servos by joystick - WHAT IT DOES Joystick on other Arduino communicates by nRF25L01 Radio to this Arduino with 2 pan-tilt servos SEE: The variable 'hasHardware'. You can test without servos and later set hasHardware = true; You NEED separate Servo power, not USB. YourDuino RoboRED has built in 2A power for servos - SEE the comments after "//" on each line below - CONNECTIONS: - nRF24L01 Radio Module: See https://arduinoinfo.mywikis.net/wiki/Nrf24L01-2.4GHz-HowTo 1 - GND 2 - VCC 3.3V !!! NOT 5V 3 - CE to Arduino pin 7 4 - CSN to Arduino pin 8 5 - SCK to Arduino pin 13 6 - MOSI to Arduino pin 11 7 - MISO to Arduino pin 12 8 - UNUSED - V2.12 02/08/2016 - Uses the RF24 Library by TMRH20 and Maniacbug: https://github.com/TMRh20/RF24 (Download ZIP) Questions: terry@yourduino.com */ /*-----( Import needed libraries )-----*/ #include <SPI.h> // Comes with Arduino IDE #include "RF24.h" // Download and Install (See above) #include "printf.h" // Needed for "printDetails" Takes up some memory // NEED the SoftwareServo library installed // http://playground.arduino.cc/uploads/ComponentLib/SoftwareServo.zip #include <SoftwareServo.h> // Regular Servo library creates timer conflict! /*-----( Declare Constants and Pin Numbers )-----*/ #define CE_PIN 7 // The pins to be used for CE and SN #define CSN_PIN 8 #define ServoHorizontalPIN 3 //Pin Numbers for servos and laser/LED #define ServoVerticalPIN 5 #define LaserPIN 6 #define ServoMIN_H 30 // Don't go to very end of servo travel #define ServoMAX_H 150 // which may not be all the way from 0 to 180. #define ServoMIN_V 30 // Don't go to very end of servo travel #define ServoMAX_V 150 // which may not be all the way from 0 to 180 /*-----( Declare objects )-----*/ /* Hardware configuration: Set up nRF24L01 radio on SPI bus plus (usually) pins 7 & 8 (Can be changed) */ RF24 radio(CE_PIN, CSN_PIN); SoftwareServo HorizontalServo; SoftwareServo VerticalServo; // create servo objects to control servos /*-----( Declare Variables )-----*/ byte addresses[][6] = {"1Node", "2Node"}; // These will be the names of the "Pipes" // Allows testing of radios and code without servo hardware. Set 'true' when servos connected boolean hasHardware = false; // Allows testing of radios and code without Joystick hardware. //boolean hasHardware = true; int HorizontalJoystickReceived; // Variable to store received Joystick values int HorizontalServoPosition; // variable to store the servo position int VerticalJoystickReceived; // Variable to store received Joystick values int VerticalServoPosition; // variable to store the servo positio /** Create a data structure for transmitting and receiving data This allows many variables to be easily sent and received in a single transmission See http://www.cplusplus.com/doc/tutorial/structures/ */ struct dataStruct { unsigned long _micros; // to save response times int Xposition; // The Joystick position values int Yposition; bool switchOn; // The Joystick push-down switch } myData; // This can be accessed in the form: myData.Xposition etc. void setup() /****** SETUP: RUNS ONCE ******/ { Serial.begin(115200); // MUST reset the Serial Monitor to 115200 (lower right of window ) // NOTE: The "F" in the print statements means "unchangable data; save in Flash Memory to conserve SRAM" Serial.println(F("YourDuino.com Example: Receive joystick data by nRF24L01 radio from another Arduino")); Serial.println(F("and control servos if attached (Check 'hasHardware' variable")); printf_begin(); // Needed for "printDetails" Takes up some memory /*-----( Set up servos )-----*/ if (hasHardware) { HorizontalServo.attach(ServoHorizontalPIN); // attaches the servo to the servo object VerticalServo.attach(ServoVerticalPIN); } radio.begin(); // Initialize the nRF24L01 Radio radio.setChannel(108); // 2.508 Ghz - Above most Wifi Channels radio.setDataRate(RF24_250KBPS); // Fast enough.. Better range // Set the Power Amplifier Level low to prevent power supply related issues since this is a // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default. // PALevelcan be one of four levels: RF24_PA_MIN, RF24_PA_LOW, RF24_PA_HIGH and RF24_PA_MAX radio.setPALevel(RF24_PA_LOW); // radio.setPALevel(RF24_PA_MAX); // Open a writing and reading pipe on each radio, with opposite addresses radio.openWritingPipe(addresses[1]); radio.openReadingPipe(1, addresses[0]); // Start the radio listening for data radio.startListening(); // radio.printDetails(); //Uncomment to show LOTS of debugging information }//--(end setup )--- void loop() /****** LOOP: RUNS CONSTANTLY ******/ { if ( radio.available()) { while (radio.available()) // While there is data ready to be retrieved from the receive pipe { radio.read( &myData, sizeof(myData) ); // Get the data } radio.stopListening(); // First, stop listening so we can transmit radio.write( &myData, sizeof(myData) ); // Send the received data back. radio.startListening(); // Now, resume listening so we catch the next packets. Serial.print(F("Packet Received - Sent response ")); // Print the received packet data Serial.print(myData._micros); Serial.print(F("uS X= ")); Serial.print(myData.Xposition); Serial.print(F(" Y= ")); Serial.print(myData.Yposition); if ( myData.switchOn == 1) { Serial.println(F(" Switch ON")); } else { Serial.println(F(" Switch OFF")); } } // END radio available if (hasHardware) { /*-----( Calculate servo position values, send to the servos )-----*/ SoftwareServo::refresh();//refreshes servo to keep them updating HorizontalJoystickReceived = myData.Xposition; // Get the values received VerticalJoystickReceived = myData.Yposition; // scale it to use it with the servo (value between MIN and MAX) HorizontalServoPosition = map(HorizontalJoystickReceived, 0, 1023, ServoMIN_H , ServoMAX_H); VerticalServoPosition = map(VerticalJoystickReceived, 0, 1023, ServoMIN_V , ServoMAX_V); // tell servos to go to position HorizontalServo.write(HorizontalServoPosition); VerticalServo.write(VerticalServoPosition); } // END hasHardware }//--(end main loop )--- /*-----( Declare User-written Functions )-----*/ // NONE YET //*********( THE END )***********
zz