Advertisement
microrobotics

NRF24L01 RF Serial Converter

May 30th, 2023
1,186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <SoftwareSerial.h>
  2.  
  3. SoftwareSerial mySerial(10, 11); // RX, TX
  4.  
  5. void setup() {
  6.   // Open serial communications and wait for port to open:
  7.   Serial.begin(9600);
  8.  
  9.   // Set the data rate for the SoftwareSerial port
  10.   mySerial.begin(9600);
  11. }
  12.  
  13. void loop() {
  14.   // Check if the Serial Converter has sent any data
  15.   if (mySerial.available()) {
  16.     byte len = mySerial.read(); // Read the first byte - the length of the actual data
  17.     char data[32]; // Buffer to hold received data
  18.     for (int i = 0; i < len; i++) {
  19.       while (!mySerial.available()); // Wait for the next data byte
  20.       data[i] = mySerial.read();
  21.     }
  22.     data[len] = '\0'; // Null terminate the string
  23.  
  24.     Serial.println("Received: " + String(data));
  25.   }
  26.  
  27.   // To send data
  28.   String dataToSend = "Hello, world!";
  29.   byte len = dataToSend.length();
  30.   char sendBuffer[32];
  31.   sendBuffer[0] = len; // Set the length of the data in the first byte
  32.  
  33.   for (int i = 0; i < len; i++) {
  34.     sendBuffer[i + 1] = dataToSend[i]; // Store the actual data starting from the second byte
  35.   }
  36.  
  37.   mySerial.write(sendBuffer, len + 1); // Send the data, note the '+1' as we also need to send the length byte
  38.  
  39.   delay(1000); // Wait for a second before next loop iteration
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement