Receiving Data

To read data from the RX buffer, use the bt.getdata method.

In a typical BLE system, there is a constant need to handle an inflow of data. A simple approach is to use polling. You just poll the buffer in a loop and see if it contains any data, and when fresh data becomes available, you read it out of the TX buffer. The code relies on bt.rxlen to check if there is any data waiting in the buffer:

** Tibbo Basic **


while 1 'endless loop
 if bt.rxlen>0 then
         dim s as string=bt.getdata(255) 'process the data
 end if
 doevents 'allow other events to execute

This approach will work, but it will forever keep you inside a waiting loop. This isn't how TiOS apps are supposed to work, so generally we recommend you to avoid this approach. Instead, use the on_bt_data_arrival event, which is generated whenever there is any data in the RX buffer:

** Tibbo Basic **

sub on_bt_data_arrival
 dim s as string
 s = bt.getdata(255) ' Extract the data -- but in a non-blocking way.
end sub

The on_bt_data_arrival event is always generated whenever there is data in the RX buffer, but only once. There are never two on_bt_data_arrival events waiting in the queue. The next event may only be generated after the previous one has completed processing (provided that there is still data waiting in the RX buffer).

When handling this event, you don't have to read all the data waiting in the RX buffer. You can simply handle a chunk of data and once you leave the event handler, a new event of the same type is generated if there is still any unprocessed data left.

Here is a nice example of implementing the data loopback (echo) on your device. Although it also transmits the data and we will only be getting to the explanation of data transmission in the next topic, we have decided to put this code snippet here as a beautiful illustration of how the on_bt_data_arrival event should be used in your apps.

** Tibbo Basic **

sub on_bt_data_arrival
end sub

Here are some additional properties and methods related to the RX buffer:

  • Bt.peekdata allows you to "preview" the data in the RX buffer.
  • Bt.rxclear deletes all data in the RX buffer.