Receiving data and manipulating it how we want is a lot harder than transmitting data. Luckily the serial port class has a very useful DataReceived event.

So what we can do is create an event handler for then DataReceived event, and write a method inside the event handler to deal with the data that is received. The way that this is dealt with depends on the way in which you receive data. Usually you will have control over how the data you are receiving is formatted, sometimes you may not and that can make the task more difficult.

Lets look at the sceneario that we can design the incoming data stream ourselves. For this task I will describe the following scenario.

 We have a microcontroller connected to the serial port. The microcontroller is calculating some values a that it obtains by monitoring some external electronics. For example this could be a reading of temperature. The microcontroller will also send some text of a fixed length of 3 charactors to represent the day the reading is taken, pointless but good for an example. I am also assuming you are able to program the microcontroller to respond to requests made by our application.

 Firstly our program will need to ask the microcontroller for its current value. We need to design a command that we can send to the microcontroller. It is important to use what is known as a delimitor in all our communications, this tells the microcontroller or the application that the data being received is useful and intentional.

The delimitor can be anything you choose, it is sensible to avoid letters and number as they are easily typed over a terminal.

For making a request to the microcontroller I will use the charactor ‘!’ as the delimitor, and for the response I will use the charactor ‘$’.

Therefore my request to the microcontroller will use the following string.

“!,V” followed by a ‘\n’ (line feed charactor) as the termination.

My response will consist of the following string format:

$,V,<Text>,<VALUE>\n

e.g. “$,V,Fri,92.1\n”

 We can now get on with the coding.

Stage 1:- Create an new project.

In visual studio create a new winForms project. Add a textbox and name this “ResultBox”, also add a label and change the text to current value.

Similar to this:

Form example for sp_tx and rx tut

Now drag onto the form a SerialPort object, you will find this in the visual studio toolbox under components. This type of object does not land on the form, as it is not visible to the end user. It will appear in a grey area below the form editor. Doing this is the same as creating a new instance of the serial port class as we did in the previous section of this tutorial.

sp added to vs form

Above shows this step completed. Now select the serial port you have just droped onto the form, and click the events icon in the properties area for the serial port (bottom right corner in vs 2005 express), then double click in the DataReceived event box as shown below.

eg_create event handler for serial port

Visual studio will now automatically switch to a view of the code, and the event handler code has been automatically generated for us. You should see the following code appear.

event handler code serial port

We need to write our code to handle our incoming string in this method where our cursor is now sitting (the serialPort1_DataReceived method).

This code needs to do the following:-

  1. Detect the delimiter.

  2. Remove any unwanted charactors.

  3. Split the string into the neccesary data fields.

  4. Convert to the appropriate data types.

 Firstly you need to read the line of received code. This can be acheived using the readline() method. Remember it needs to be stored inside a varible. The readline method returns a string. Therefore:-

string RxString = serialPort1.ReadLine();

This will read in the whole line as a string exactly how it was transmitted. Note that because the string “RxString” that we have just created was created inside a method it is only available after the line it is created and only within this mehtod. When the method terminates or completes then RxString is erased and no longer exists.

So now hopefully if we ran the program and our microcontroller transmitted the correct data RxString would in theory contain.

“$,V,Fri,92.1\n”

When designing a communications string like this you are free to customize it with any charactors you choose, however I would recommend that fields with variable lengths are placed at the end to reduce processing.

The next step is to test for the delimitor. This is the very first charactor, to perform a test we use the “if” statement.

if(RxString.Remove(1) == “$”)
{                                                      
Do something
}                                                     

The conditions of the if statment are between the brackets (   ) after the if. The code to perform if the condition is met sits between the { } function brackets. Now lets look at our condition.

 (RxString.Remove(1) == “$”)

Notice that we are using a method called “Remove()” on our string. The remove method is used for removing charactors from a string. The remove method has two ways of operation.

  1. Single argument
    This is shown in the example above, the argument is an integer which equals the first place in the string to start removing from, and then it assumes removal until the end of the string.

  2. Dual argument
    This is the same except a second integer is passed to state when to stop removing characters from the string. For example:

RxString.Remove(1,4)

If RxString was equal “Hello World” then the result of this would be “H World”, if we passed (2,3) then the result would be “He World”.

String_remove diagram

If you struggle to work out the integers to pass use the above diagram as an example, each character is numbered exactly the same as in an array. Also remember that a space is also 1 character this is not always obvious to some begginers.

Processing
Now that we have tested for the delimiter we now need to write some code to deconstruct the rest of the data. We can also do this with the help of the remove() method. What we need to do is extract from “$,V,Fri,92.1\n” the ‘Fri’ part and the ‘92.1′ part.

At the top of the program outside any of the methods add the following variables to store our data.

double value;

string day;

Add the following lines to our function quotes for the if statement.

day = RxString.Remove(0,4).Remove(3);   // to result “Fri”

value = Convert.ToDouble(RxString.Remove(0,8));

Now we need to fill out textbox with this information. Of cource now we have used the convert method to store the value as a double instead of a string we can now perform mathematical operations on that number if we wish.

 Add the line:

ResultBox.Text = “Value: “+value.ToString() + ” on ” + day;

Set the default proerties of the serial port in visual studio to 9600 baud, and a Com port that is being emulated by virtual comport. (See previous page for details.)

After the line InitialiseComponent(); add the line serialPort1.Open();

Now run your application and send our string to it. You should get the following results.

result of tutorial sp rx data

 

 More soon…..