Search code examples
matlabuser-interfaceparallel-processingmatlab-guidexbee

Running infinite loop to receive and send data in GUI | MATLAB


I'm working on a project for transmitting data via XBees from one laptop to another. I have done with the GUI interface, but I have a problem with the receiving part. As the receiver doesn't know the exact time the file is going to be received, I wrote an infinite loop which is:

    recv=[];
    while (1)

        while s.BytesAvailable==0
        end

        a=fscanf(s);
        recv=[recv a]

    end

How can I run this for loop all the time, starting from the very beginning of the program till the user close the program, and the user still be able to chose different data to transmit it?

In other words; dividing the duty into two parts receiving parts always running; while transmitting part works only when the user wants to transmit data...


Solution

  • Matlab support asynchronous read operations, triggered when the port receives data. The trigger can be a minimum number of bytes, or a special character.

    You have to use the BytesAvailableFcn callback property.

    You can use setappdata and getappdata to store arrays too large to fit within the input buffer of the port. Assuming you save the handle of the main figure into a variable named hfig:

    in the main gui code:

    s.BytesAvailableFcnCount = 1 ;                           %// number of byte to receive before the callback is triggered
    s.BytesAvailableFcnMode = 'byte' ;
    s.BytesAvailableFcn = {@myCustomReceiveFunction,hfig} ;  %// function to execute when the 'ByteAvailable' event is triggered.
    
    recv = [] ;                                              %// initialize the variable
    setappdata( hfig , 'LargeReceivedPacket' , recv )        %// store it into APPDATA
    

    and as a separate function:

    function myCustomReceiveFunction(hobj,evt,hfig)
        %// retrieve the variable in case you want to keep history data 
        %// (otherwise just initialize that to recv = [])
        recv = getappdata( hfig , 'LargeReceivedPacket' )
    
        %// now read all the input buffer until empty
        while hobj.BytesAvailable>0
            a=fscanf(hobj);
            recv=[recv a]
        end
        %// now do what you want with your received data
        %// this function will execute and return control to the main gui
        %// when terminated (when the input buffer is all read).
        %// it will be executed again each time the 'ByteAvailable' event is fired.
        %//
        %// if you did something with "recv" and want to save it, use setappdata again:
        setappdata( hfig , 'LargeReceivedPacket' , recv )        %// store it into APPDATA