B4R Tutorial UDP Communication

Discussion in 'B4R Tutorials' started by Erel, May 5, 2016.

Thread Status:
Not open for further replies.
  1. Erel

    Erel Administrator Staff Member Licensed User

    rEthernet library v1.10 (included in v1.00 beta 9) includes a new type named EthernetUDP. It allows sending and receiving UDP packets.

    UDP is simple to work with as it is a connection-less protocol.

    Steps required:

    1. Initialize an Ethernet object with a static ip address or InitializeDHCP.
    2. Initialize the EthernetUDP object and set the port number.
    3. The PacketArrived event will be raised when a packet is received.
    4. Sending packets:
    Code:
    udp.BeginPacket(serverIp, serverPort) '<--- Begin
    udp.Write("Button is ".GetBytes) '<-- One or more calls to Write
    If State = False Then
       udp.Write(
    "down".GetBytes)
    Else
       udp.Write(
    "up".GetBytes)
    End If
    udp.SendPacket 
    '<--- Send
    Example of communication between an Android an Arduino:

    upload_2016-5-5_16-5-8.png

    [​IMG]

    B4R program:
    Code:
    #Region Project Attributes
       
    #AutoFlushLogs: True
       
    #StackBufferSize: 300
    #End Region

    Sub Process_Globals
       
    Public Serial1 As Serial
       
    Private eth As Ethernet
       
    Private udp As EthernetUDP
       
    Private serverIp() As Byte = Array As Byte(192168013)
       
    Private MacAddress() As Byte = Array As Byte(0xDE0xAD0xBE0xEF0xFE0xED)
       
    Private const serverPort As UInt = 51042
       
    Private leds(2As Pin
       
    Private btn As Pin
    End Sub

    Private Sub AppStart
       Serial1.Initialize(
    115200)
       
    Log("AppStart")
       leds(
    0).Initialize(leds(0).A0, leds(0).MODE_OUTPUT)
       leds(
    1).Initialize(leds(0).A1, leds(0).MODE_OUTPUT)
       btn.Initialize(btn.A2, btn.MODE_INPUT_PULLUP)
       btn.AddListener(
    "btn_StateChanged")
       
    If eth.InitializeDHCP(MacAddress) = False Then
         
    Log("Error connecting to network.")
         
    Return
       
    Else
         
    Log("Connected to network. My ip address: ", eth.LocalIp)
       
    End If
       udp.Initialize(
    12345"udp_PacketArrived")
    End Sub


    Sub Udp_PacketArrived (Data() As Byte, Ip() As Byte, Port As UInt)
       
    Log("PacketArrived from:")
       PrintIp(Ip)
       
    If Data.Length < 2 Then Return
       
    'first byte is the led index
       'second byte is the state
       leds(Data(0)).DigitalWrite(Data(1) = 1)
    End Sub

    Sub PrintIp(ip() As Byte)
       
    Log(ip(0),".", ip(1),".", ip(2),".", ip(3))
    End Sub


    Sub Btn_StateChanged (State As Boolean)
       udp.BeginPacket(serverIp, serverPort)
       
    '(It makes more sense to send a single byte instead of a string.)
       udp.Write("Button is ".GetBytes)
       
    If State = False Then
         udp.Write(
    "down".GetBytes)
       
    Else
         udp.Write(
    "up".GetBytes)
       
    End If
       
    Log(udp.SendPacket)
    End Sub
    The B4A program is attached.
     

    Attached Files:

    pesquera, Jaames, derez and 4 others like this.
  2. derez

    derez Expert Licensed User

    upload_2016-5-6_7-53-47.png


    Since eth is initialized by DHCP, should MaintainDHCP be called by a timer like the instructions say ?
     
  3. Erel

    Erel Administrator Staff Member Licensed User

    Yes you should call MaintainDHCP with a timer.
     
  4. ingo.tw

    ingo.tw Member Licensed User

    led is ok but button is not Sending
     
  5. ingo.tw

    ingo.tw Member Licensed User

  6. rwblinn

    rwblinn Well-Known Member Licensed User

    Hi,

    attached an example UDP Communication between B4R and B4J.
    B4R is reading DHT11 Temp & Humidity which are send to the B4J application. In addition send Hello World from B4J to B4R.
    This example requires the rDHT Library.

    upload_2016-5-6_18-22-48.png

    CORRECTED: Attachment
     

    Attached Files:

    Last edited: May 6, 2016
  7. ingo.tw

    ingo.tw Member Licensed User

    Last edited: May 7, 2016
  8. Erel

    Erel Administrator Staff Member Licensed User

    Try it with a real Android device.
     
  9. janderkan

    janderkan Active Member Licensed User

    I use both TCP and UDP connection.
    If the ethernet cable is removed and put back in, I can get the TCP connection up again.
    The Udp is initialized like this, UdpConnected = udpClient.Initialize(udpPort,"UDP_PacketArrived")
    Works fine, but if the cable is removed and put back in, I receive false if I try to initalize udp again.
    After this the PacketArrived function is no longer called.
    Only a hard reset works.
     
  10. Erel

    Erel Administrator Staff Member Licensed User

    rEthernet V1.11 is attached. It adds a Close method. Call this method before you reinitialize UDP.
     

    Attached Files:

    janderkan likes this.
  11. janderkan

    janderkan Active Member Licensed User

    You are the greatest, Thank you.
     
  12. MFX

    MFX Member Licensed User

    Sorry I know this is old but I'm coming back to B4A after a long break and working on a UDP/Arduino project. I appreciate the examples but I wish you would make more use of comments to explain what exactly is going on, for example in the B4A code for the above example there is the line

    usocket.Initialize("usocket", 51042, 8192)

    What does this line do? what does it mean? what do the numbers "51042, 8192" refer to and why are they different in other similar examples? Do I need to change them for my application?

    Regards.
    Martin.
     
  13. Herbert32

    Herbert32 Member Licensed User

    51042 specifies the Port and 8192 the buffer-size for udp-packets (larger packets will be trunkated)

    You can adjust these values regarding your demands

    take care that the buffer-size covers the expected packet-size and that port on sending and receiving-side matches

    regards
    Herbert
     
  14. thetahsk

    thetahsk Active Member Licensed User

  15. MFX

    MFX Member Licensed User

    Thanks I did a Google search but nothing came up, I did find out in the end by retyping the line and reading the context sensitive help pop up, I was just going to post a follow up saying that and saw your reply but comments would still make life a lot easier particularly when they're supposed to be tutorials to learn from.
     
  16. Erel

    Erel Administrator Staff Member Licensed User

    1. You are posting in the wrong place.

    2. Hover with the mouse over the Initialize word and see the method description. I don't see any reason to repeat it in the comments.

    You can also see it here: https://www.b4x.com/android/forum/pages/results/?query=udpsocket.initialize
     
Thread Status:
Not open for further replies.
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice