Wireless Chat using Arduino & NRF24L01+ 2.4GHz RF Transceiver

It has been quite some time since I’ve tinkered with an Arduino, and this go around I decided to learn something new.

The NRF24L01 2.4GHz Transceiver is an extremely affordable wireless chip, I managed to pickup 10 units for around $12. This chip allows sending and receiving on the 2.4GHz wireless band.

Lucky for us there is a great Arduino library just waiting to be imported, thanks maniacbug!

So what did I set out to accomplish you ask? Why a chat application of course!

Components

Source Code

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

#define CE_PIN   9
#define CSN_PIN 10

const byte Address[5] = {'N','e','s','s','y'};

RF24 radio(CE_PIN, CSN_PIN);

String username = "";
String dataInput;
char dataToSend[32];
char dataReceived[32];


void setup() {
    Serial.begin(9600);
    Serial.println("Enter username...");
    
    radio.begin();
    radio.setDataRate(RF24_250KBPS);
    radio.setRetries(3, 5);
    radio.openWritingPipe(Address);
    radio.openReadingPipe(1, Address);
}


void loop() {

  // set username
  while (username == "") {
    if ( Serial.available() ) {
      username = Serial.readStringUntil('\n');
      Serial.print("Welcome ");
      Serial.println(username);
    }
  }

  // listen for radio data
  radio.startListening();
  
  if ( radio.available() ) {
    // read data from radio
    radio.read( &dataReceived, sizeof(dataReceived) );
    Serial.println(dataReceived);  
  }

  if( Serial.available() ) {
    // stop listening on radio
    radio.stopListening();
     
    // get serial input
    dataInput = "[" + username + "] " + Serial.readStringUntil('\n');
    Serial.println(dataInput);
    dataInput.toCharArray(dataToSend, 32);

    // send data
    radio.write( &dataToSend, sizeof(dataToSend) );  
  }
  
}

Leave a Reply

Your email address will not be published. Required fields are marked *