Estimados, estoy hace ya varias semanas intentando hacer comunicar 2 arduino a través de radio con los integrados NRF24L01. He usado arduinos DUEs y UNOs, en todas sus combinaciones posibles... puse capacitores en la entrada de alimentación, he chequeado hasta el hartazgo los cableados y las masas, y usé las librerías
en todas sus formas posibles...
Pongo un ejemplo básico con el que me estoy rompiendo la cabeza, porque es con el que más cerca llego a comunicar, con la salvedad que el emisor sólo recibe CEROS constantemente (lo he sacado de alguna página tutorial...)
EMISOR
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <RF24_config.h>
//Declaremos los pines CE y el CSN
#define CE_PIN 9
#define CSN_PIN 10
//Variable con la dirección del canal por donde se va a transmitir
byte direccion[5] ={'c','a','n','a','l'};
//creamos el objeto radio (NRF24L01)
RF24 radio(CE_PIN, CSN_PIN);
//vector con los datos a enviar
float datos[3];
void setup()
{
//inicializamos el NRF24L01
radio.begin();
//inicializamos el puerto serie
Serial.begin(9600);
SPI.begin();
//Abrimos un canal de escritura
radio.openWritingPipe(direccion);
}
void loop()
{
//cargamos los datos en la variable datos[]
datos[0]=analogRead(0)* (5.0 / 1023.0);;
datos[1]=millis();
datos[2]=3.14;
//enviamos los datos
bool ok = radio.write(datos, sizeof(datos));
//reportamos por el puerto serial los datos enviados
if(ok)
{
Serial.print("Datos enviados: ");
Serial.print(datos[0]);
Serial.print(" , ");
Serial.print(datos[1]);
Serial.print(" , ");
Serial.println(datos[2]);
}
else
{
Serial.println("no se ha podido enviar");
}
delay(1000);
}
RECEPTOR
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <RF24_config.h>
//Declaremos los pines CE y el CSN
#define CE_PIN 9
#define CSN_PIN 10
//Variable con la dirección del canal que se va a leer
byte direccion[5] ={'c','a','n','a','l'};
//creamos el objeto radio (NRF24L01)
RF24 radio(CE_PIN, CSN_PIN);
//vector para los datos recibidos
float datos[3];
void setup()
{
//inicializamos el NRF24L01
radio.begin();
SPI.begin();
//inicializamos el puerto serie
Serial.begin(9600);
//Abrimos el canal de Lectura
radio.openReadingPipe(1, direccion);
//empezamos a escuchar por el canal
radio.startListening();
}
void loop() {
uint8_t numero_canal;
//if ( radio.available(&numero_canal) )
if ( radio.available() )
{
//Leemos los datos y los guardamos en la variable datos[]
radio.read(datos,sizeof(datos));
//reportamos por el puerto serial los datos recibidos
Serial.print("Dato0= " );
Serial.print(datos[0]);
Serial.print(" V, ");
Serial.print("Dato1= " );
Serial.print(datos[1]);
Serial.print(" ms, ");
Serial.print("Dato2= " );
Serial.println(datos[2]);
}
else
{
Serial.println("No hay datos de radio disponibles");
}
delay(1000);
}
Si puedo hacer funcionar éste codigo ya está... pero ando buscando una mano... miré el foro en español y en inglés de arriba abajo y no dar con la tecla... muchas gracias!
Vivo usando los nRF24L01+ y no me han dado problemas salvo al comienzo por algún error tonto.
Primero uniformicemos librerías.
Yo uso Tmrh20 y en la versión RF24, la encuentras aquí RF24 tmrh20 Library
Y este es el programa que instalas en ambos módulos GettingStarted.ino
Se controla con T o R para Transmitir o Recibir de uno u otro lado.
/*
* Getting Started example sketch for nRF24L01+ radios
* This is a very basic example of how to send data from one node to another
* Updated: Dec 2014 by TMRh20
*/
#include <SPI.h>
#include "RF24.h"
/****************** User Config ***************************/
/*** Set this radio as radio number 0 or 1 ***/
bool radioNumber = 0;
/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8 */
RF24 radio(7,8);
/**********************************************************/
byte addresses[][6] = {"1Node","2Node"};
// Used to control whether this node is sending or receiving
bool role = 0;
void setup() {
Serial.begin(115200);
Serial.println(F("RF24/examples/GettingStarted"));
Serial.println(F("*** PRESS 'T' to begin transmitting to the other node"));
radio.begin();
// 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.
radio.setPALevel(RF24_PA_LOW);
// Open a writing and reading pipe on each radio, with opposite addresses
if(radioNumber){
radio.openWritingPipe(addresses[1]);
radio.openReadingPipe(1,addresses[0]);
}else{
radio.openWritingPipe(addresses[0]);
radio.openReadingPipe(1,addresses[1]);
}
// Start the radio listening for data
radio.startListening();
}
void loop() {
/****************** Ping Out Role ***************************/
if (role == 1) {
radio.stopListening(); // First, stop listening so we can talk.
Serial.println(F("Now sending"));
unsigned long start_time = micros(); // Take the time, and send it. This will block until complete
if (!radio.write( &start_time, sizeof(unsigned long) )){
Serial.println(F("failed"));
}
radio.startListening(); // Now, continue listening
unsigned long started_waiting_at = micros(); // Set up a timeout period, get the current microseconds
boolean timeout = false; // Set up a 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("Failed, response timed out."));
}else{
unsigned long got_time; // Grab the response, compare, and send to debugging spew
radio.read( &got_time, sizeof(unsigned long) );
unsigned long end_time = micros();
// Spew it
Serial.print(F("Sent "));
Serial.print(start_time);
Serial.print(F(", Got response "));
Serial.print(got_time);
Serial.print(F(", Round-trip delay "));
Serial.print(end_time-start_time);
Serial.println(F(" microseconds"));
}
// Try again 1s later
delay(1000);
}
/****************** Pong Back Role ***************************/
if ( role == 0 )
{
unsigned long got_time;
if( radio.available()){
// Variable for the received timestamp
while (radio.available()) { // While there is data ready
radio.read( &got_time, sizeof(unsigned long) ); // Get the payload
}
radio.stopListening(); // First, stop listening so we can talk
radio.write( &got_time, sizeof(unsigned long) ); // Send the final one back.
radio.startListening(); // Now, resume listening so we catch the next packets.
Serial.print(F("Sent response "));
Serial.println(got_time);
}
}
/****************** Change Roles via Serial Commands ***************************/
if ( Serial.available() )
{
char c = toupper(Serial.read());
if ( c == 'T' && role == 0 ){
Serial.println(F("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK"));
role = 1; // Become the primary transmitter (ping out)
}else
if ( c == 'R' && role == 1 ){
Serial.println(F("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK"));
role = 0; // Become the primary receiver (pong back)
radio.startListening();
}
}
} // Loop
Gracias Jopapa, siempre tus tutoriales muy interesantes
Surbyte. Ese scketch nunca lo hice correr en ninguna placa! éste será el problema??.. cual es la función? Cargarle una configuración Rx o Tx a un dispositivo? como se integra éste GettingStarted al scketch principal que le quiiero cargar a cada uno?
No importa. Tu primero verifica que funcionan.
Instalas el sketch en ambos. En un abres el monitor serie y pones T y en el otro R y se deberían comunicar.
Verifiquemos eso primero y luego pasamos a lo que quieres.
Hola gente, he probado con el programa que me recomendó Surbyte. Tal cual me imaginaba y como me venía pasando, el "T"envía datos pero en el serial muestra "failed" constantemente. En el "R" mientras tanto no se mueve nada... tengo cada arduino alimentado con fuentes individuales, todo HW chequeado...
Lo raro del asunto, para mi por lo menos, es que cuando en el receptor cambio los pines de CE y CSN a revés, empieza a recibir basura, tipo 0 / 0 / 0 / 0 / 2139061768 / 4294967167 / 0 / 0 / 2139061768 etc etc etc
El transmisor mientras tanto tira en serial cosas como:
Sent 951634374, Got response 0, Round-trip delay 1670 microseconds
Now sending
failed
Sent 952636374, Got response 0, Round-trip delay 1433 microseconds
Now sending
failed
Sent 953638374, Got response 0, Round-trip delay 1247 microseconds
Now sending
failed
Sent 954640374, Got response 0, Round-trip delay 1117 microseconds
Now sending
failed....
etcetc
no creo, compré en paquete cerrado unas 20 unidades, las compré directo al fabricante, probé practicamente todas... y siempre pasa lo mismo, por puerto serial veo que puedo Transmitir, pero nunca recibo,... sólo recibo ceros o basura, con todas las librerias, cualquier placa, todas las antenas, etc...
Será problema de algún driver de la PC o del IDE que estoy usando?? es lo unico que nunca cambié..