This library wraps RF24 open source project: http://tmrh20.github.io/RF24/ (GPL license).
With this library it is simple to transmit or receive small packets between two or more Arduinos using nRF24L01+ radio modules.
Wiring:
1 - Ground
2 - 3.3 volt.
3 - CE pin. Any available pin (7 in the next example)
4 - CSN pin. Any available pin (8 in the next example)
5 - SCK pin. Uno - 13, Mega - 52 (other boards: https://www.arduino.cc/en/reference/SPI)
6 - MOSI pin. Uno - 11, Mega - 51
7 - MISO pin. Uno - 12, Mega - 50
8 - Not connected
Code:
- Initialize the RF24 object and set the CE and CSN pins.
- Set the reading and writing addresses.
- Handle the NewData event.
The maximum packet size is 32 bytes. The length of the array passed in the NewData event will always be 32. It will be padded with zeroes after the actual data.
Example of connecting an Uno and Mega. The Uno sends its current millis value every second. The Mega sends the button state.
B4X:
'UNO
Sub Process_Globals
Public Serial1 As Serial
Private rf24 As RF24
Private raf As RandomAccessFile
Private timer1 As Timer
Private led As Pin
Private const MEGA = 1, UNO = 2 As Byte
Private buffer(4) As Byte
End Sub
Private Sub AppStart
Serial1.Initialize(115200)
Log("AppStart")
rf24.Initialize(7, 8, "rf24_NewData")
rf24.OpenReadingPipe(UNO)
rf24.OpenWritingPipe(MEGA)
timer1.Initialize("timer1_Tick", 1000)
timer1.Enabled = True
led.Initialize(2, led.MODE_OUTPUT) 'connect led to pin #2
raf.Initialize(buffer, True)
End Sub
Sub rf24_NewData (Data() As Byte)
led.DigitalWrite(Data(0) = 1)
End Sub
Sub Timer1_Tick
raf.WriteULong32(Millis, 0)
rf24.Write(buffer)
End Sub
B4X:
'MEGA
Sub Process_Globals
Public Serial1 As Serial
Private rf24 As RF24
Private btn As Pin
Private const MEGA = 1, UNO = 2 As Byte
Private raf As RandomAccessFile
End Sub
Private Sub AppStart
Serial1.Initialize(115200)
Log("AppStart")
rf24.Initialize(7, 8, "rf24_NewData")
rf24.OpenReadingPipe(MEGA)
rf24.OpenWritingPipe(UNO)
btn.Initialize(2, btn.MODE_INPUT_PULLUP) 'button connected to pin #2.
btn.AddListener("btn_StateChanged")
End Sub
Sub btn_StateChanged (State As Boolean)
Dim b As Byte
If Not(State) Then b = 1 Else b = 0
Log("Write result: ", rf24.Write(Array As Byte(b)))
End Sub
Sub rf24_NewData (Data() As Byte)
raf.Initialize(Data, True)
Log("UNO Millis: ", raf.ReadULong32(raf.CurrentPosition))
End Sub
Attachments
Last edited: