The main purpose of constructing a Graphical User Interface is to test the complete functionality of the bot manually before it is handed over to the Artificial Intelligence team who would then run the bots autonomously. To make this possible we need to communicate with the bot via a wireless medium. From the GUI’s end this is achieved with the help of serial ports. We use a wireless module(XBee) which is connected to the computer. On connecting this wireless module to the computer, the computer automatically assigns the module a COM port. To begin with it we need to include the following statement in our Form.
With this included in our code we can now access various Ports on our computer. First and foremost, we would require to declare an object of the class SerialPort.
public partial class Form1 : Form
Now we need to instantiate the object of Serial port.
port = new SerialPort(“COM23″, 38400, Parity.None, 8, StopBits.One);
The instance can take several arguments. However, providing only the name of the Port and the Baud rate can suffice for our purpose.
“COM23″ is the name of the port which has been assigned to our wireless module. This name can be found out by looking up the list of ports assigned in the Device Manager.
Baud rate is the speed with which data transfer across the port takes place in pulses per second. For our purpose we use a Baud rate of 38400.
After initializing the port we need to open it. We can assign a button named “Connect” which would open the port when clicked. And within the button-click function we can open the port by simply calling its port.Open(); function.
With the Serial port now opened, we can write onto as well as receive data from the wireless module. Say, we have an array of byte values which has been declared as follows
byte data = new byte;
We use the port.Write(); function to write data onto the the port. It has several overloads, in most of our GUIs we would generally be working with byte values and hence we will use the required overload.
port.Write(data, 0, 6);
Here “data” is the array of byte values, “0″ refers to the starting index of the array and “6″ signifies the no. of bytes to be written. Once this line has been executed the data has been written onto the port and has been transferred wirelessly.
In a very similar way we can also read data from the port using the port.Read(); function which has the same format of arguments as the Write(); function.
When done with our job it is a good practice to close the port using the port.Close(); function.
This article covers the basic elements of using a Serial Port. In the next tutorial we will integrate all that we have learnt to form a simple GUI that is capable of taking input from the user and communicate it to the bot wirelessly.