B4J Tutorial [RPi] - PiFace Control And Display (CAD)

SS-2016-01-21_14.23.06.png


jPi4J library supports the PiFace Digital extension. However it doesn't support the CAD module as the underlying library (Pi4J) doesn't support it.

So we need to be a bit more creative here.
We will run and interact with a simple Python script using UDP. Note that an external network is not required.

The Python script will receive the data and write it to the display. It will also monitor the buttons and will send our B4J program a message whenever a button is clicked.

The example program displays the current time on the display. Once the user clicks on a button it displays the button number (and the timer is stopped).

If this is the first time that you connect the PiFace CAD then you need to follow these instructions: http://www.piface.org.uk/guides/setting_up_pifacecad/fitting_PiFace_Control_and_Display/

The Python script is included in the Files folder.

The complete program:
B4X:
Sub Process_Globals
   Private timer1 As Timer
   Private us As UDPSocket
End Sub

Sub AppStart (Args() As String)
   us.Initialize("us", 52041, 8192)
   timer1.Initialize("Timer1", 1000)
   timer1.Enabled = True
   If ProcessIsRunning = False Then
     Log("starting piface_udp")
     Dim shl As Shell
     File.Copy(File.DirAssets, "piface_udp.py", File.DirApp, "piface_udp.py")
     shl.Initialize("shl", "python", Array(File.Combine(File.DirApp, "piface_udp.py")))
     shl.Run(-1)
   End If
   StartMessageLoop
End Sub

Sub shl_ProcessCompleted (Success As Boolean, ExitCode As Int, StdOut As String, StdErr As String)
   Log("Process completed: " & StdErr & ", " & StdOut)
End Sub

Sub ProcessIsRunning As Boolean
   Dim shl As Shell
   shl.Initialize("", "ps", Array("-ef"))
   Return shl.RunSynchronous(10000).StdOut.Contains("piface_udp.py")
End Sub

Private Sub Timer1_Tick
   SendMessage($"$Time{DateTime.Now}"$)
End Sub

Private Sub us_PacketArrived (Packet As UDPPacket)
   timer1.Enabled = False
   Dim btnNumber As Int = BytesToString(Packet.Data, 0, Packet.Length, "ASCII")
   SendMessage($"User clicked on
button #${btnNumber}"$)
End Sub

Private Sub SendMessage(msg As String)
   Dim Packet As UDPPacket
   Packet.Initialize(msg.GetBytes("ASCII"), "127.0.0.1", 52042)
   us.Send(Packet)
End Sub
 

Attachments

  • PiFace_CAD.zip
    1.7 KB · Views: 635

KMatle

Expert
Licensed User
Longtime User
I kept this app running on the RPi (using nohup to prevent it from being killed when the SSH connection is closed). It runs over a week now.

I did the same with httputils calling my Server (php -> MySql) to see how stable the RPI is: All good...
 
Top