Sending Data
In the previous section, we explained how to handle an incoming stream of data. You could say it was incoming-data driven. Sometimes you need just the opposite — you need to perform operations based on the sending of data.
For example, suppose that in a certain system you need to send out a long string of data when a button is pressed. Simple code for that would look like this:
sub on_button_pressed
ser.setdata("This is a long string waiting to be sent. Send me already!")
ser.send
end sub
The code above would work, but only if at the moment of code execution the necessary amount of free space was available in the TX buffer (otherwise the data would get truncated). So, obviously, you need to make sure that the TX buffer has the necessary amount of free space before sending. A simple polling solution would look like this:
sub on_button_pressed
dim s as string
s = "This is a long string waiting to be sent. Send me already!"
while ser.txfree < len(s) 'we will wait for the necessary amount of free space to become available
wend
ser.setdata(s)
ser.send
end sub
Again, this is not so good, as it would block other event handlers. So, instead of doing that, we would employ a code that uses on_ser_data_sent:
dim s as string
s = "This is a long string waiting to be sent. Send me already!"
sub on_button_pressed
ser.notifysent(ser.txbuffsize-len(s)) ' causes the on_ser_data_sent event to fire when the tx buffer has space for our string
end sub
sub on_ser_data_sent
ser.setdata(s) ' put data in tx buffer
ser.send ' start sending it.
end sub
When we press the button, an on_button_pressed event is generated, so now the system knows we have a string to send. Using ser.notifysent, we make the system fire the on_ser_data_sent event when the necessary amount of free space becomes available. This event will only be fired once — and will be fired immediately if there is already enough available space.
Within the on_ser_data_sent event handler we put the data in the TX buffer and start sending it.
The amount of data that will trigger on_ser_data_sent does not include uncommitted data in the TX buffer.