Reading data from a device connected to the computer's serial port has become an easy task in Visual Basic. Using only a few basic commands in the built-in library, you can write your own VB applications for dealing with external peripherals that you purchase or design yourself.
- Skill level:
- Moderately Easy
Other People Are Reading
Things you need
- Visual Basic 2008
Create a new project. Name your project "Serial Port Reading Tutorial" or give it some other appropriate name. On any other dialogue boxes, simply choose the default options until you find yourself faced with the blank window of the "Graphical User Interface" (GUI) designer.
Add a button from the components list on the left-hand side by dragging it into the form. While the button is still selected, go to the properties list and find the "text" property. Change this to read "Read 100 bytes from COM1" or any other appropriate caption you wish to give it.
Double-click the button. This will take you out of the GUI designer and into the source code editor. It will also create an event function to occur whenever the button is clicked by the user.
Add the following code to the button click function that Visual Basic just created for you:
Dim com1 As IO.Ports.SerialPort com1 = My.Computer.Ports.OpenSerialPort("COM1") Dim data(100) As Byte() com1.read(data, 0, 100)
The arguments for the read function refer to an array of bytes to write the data to, the amount to offset before reading and, finally, the amount to read from the port. In this case, we want the data placed into the data Byte array we've declared. We want to start at the beginning of the stream of data from the serial port, so our offset is zero. And finally, we want to read at most one hundred bytes, since that is how large our data array is.
You've now read a hundred bytes from a serial port and can use them in your application as you see fit.
Tips and warnings
- You can retrieve a list of serial ports connected to your computer using the command SerialPort.GetPortNames(). It will return an array of strings listing all ports currently connected to the computer. These names can be used in the OpenSerialPort("COM1") command in place of the COM1.
- If you wish to read more data from the serial port, you can increase the offset value from 0 to 100.
- This technique will read from traditional serial ports such as COM and LP ports. However, it cannot be used to read from USB ports.
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for