Gcc Serial Port Communication Visual Basic

Gcc Serial Port Communication Visual Basic

Home Articles Access Serial Ports with Visual Basic.NET. Access Serial Ports with Visual Basic.NET. This article originally appeared in the April 2008 Nuts & Volts. Also see Access Serial Ports with PICBASIC. If you have a microcontroller circuit that needs to talk to a PC, a serial port can do the job.

  1. How to: Send Strings to Serial Ports in Visual Basic.; 2 minutes to read +5; In this article. This topic describes how to use My.Computer.Ports to send strings to the computer's serial ports in Visual Basic. This example sends a string to the COM1 serial port.
  2. Basic is the serial communication that uses the serial port. So, this platform is designed to solve the problem in serial communication and the programming language used is Visual Basic 2010 as it is the language used in one of the courses in Diploma in Electronic Engineering (Computer) structure; EC502 Visual Basic Programming.

Serial Communication with Visual Basic.NET Serial COM Port Serial COM Port Communication This page describes serial COM port communication by means of Visual Basic.NET The page is updated August 5 th 2010. It is only available in English. Windows COM Port Unfortunately Microsoft has never paid much attention to the serial port. In the Windows API it is just regarded as a file, and in the first version (1.1) of the.NET framework (managed code) there was no support for serial communication. Fortunately, a new namespace - System.IO.Ports - has been added in version 2.0, which has made things much easier although there are still some problems. For example, it is not possible to control the FIFO in the UART.

It is also not possible to tell when the transmitter serial register is empty, so it is almost impossible to control the modem control signals and send a break condition, but worst of all, Microsoft has put an 8 bit wide buffer on top of the 11-bit receiver FIFO and therefore destroyed the possibility for a precise Break, 9th bit and error detection. Besides, many of the examples in the help files are directly misleading and unnecessary complicated. For example, it is recommended to use My.Computer.Ports.OpenSerialPort('COMx') to open a serial port, but if it is done that way, it is not possible to set many of the properties of the port like for example the length of the receive buffer and it is not possible to tell when a port is open (IsOpen). In many developer forums there has been a lot of questions concerning serial port communication, but unless you are lucky enough to get in touch with the one, who has designed the serial port, it is usually very hard to get precise and helpful answers. For example, when we wanted to use very high speed communication (up to 921.6 Kbit/s), we only got the answer that it couldn't be done or we needed to write our own drivers!

However, it is in fact possible to use System.IO.Ports even up to 921.6 Kbit/s if a UART with a 128 byte FIFO is used (16C850 or 16C950). As a service to others with the same problems as we have been through we have chosen to publish a small program, which is able to communicate through the serial port.

The sample program is written in Visual Basic.NET (in the following just VB), because this language is as close as you get to our own suggestion for a simple and efficient programming language (see: ). In.NET there is no longer any performance difference between VB, C and C#. This description is based on VS 2005 and.NET 2.0. Unfortunately, SerialPort does not work in all versions of.Net. To clarify the various.Net releases:.Net 1.1 RTM (Release To Manufactoring) = No serial port support!.Net 2.0 RTM = First version with serial port support.Net 3.0 RTM =.Net 2.0 RTM + new.Net 3.0 RTM assemblies.Net 3.5 RTM =.Net 2.0 SP1 +.Net 3.0 SP1 + new.Net 3.5 RTM assemblies.Net 3.5 SP1 =.Net 2.0 SP2 +.Net 3.0 SP2 +.Net 3.5 SP1 + new.Net 3.5 SP1 assemblies. Only a few bug fixes were made to Serial Port in.Net 2.0 SP1:. Race condition between SerialPort.Close and event loop runner shutting down Serial IO WaitCommEvent enters high CPU and leaks memory when USB Serial Port removed (Internal Regression).

SerialPort.ReadExisting returns incorrect characters. And only one change were made to Serial Port in.Net 2.0 SP2:. UnauthorizedAccessException in SerialStream crashes application after disconnecting device from USB COM port. This should fix the issue of the unhandled exception when disconnecting a device from a USB COM port. However, there are reports indicating that the attempt to fix the bug doesn't work. The big problem is.Net 3.5 RTM, which includes.Net 2.0 SP1.

Almost nothing in SerialPort seems to work in that version! In fact, there seems to be so many errors that.Net 3.5 RTM may be regarded as completely useless for all serial port applications!

For the moment the following problems have been reported:. It may crash if you access the modem control signals while the port is receiving.

It may crash if you try to close a port set to a wrong speed - even if you have an error handler for the ErrorReceived event. You cannot use multiple ports. In many cases, the DataReceived event does not fire. If you try to run a 3.5 application generated under Vista on a XP PC, it may lock up the COM ports forever making them useless for all programs including Hyperterminal - even if you delete the application again or remove the 2.0/3.5 framework. It is necessary to repair or re-install Windows to return the ports to their funtionality prior to the loading of the application! Microsoft thinks that the many problems with serial port in.Net 3.5 RTM may be coursed by other, unrelated(!), bug fixes that went into.Net 2.0 SP1.

Most of these problems seems to be fixed in.Net 3.5 SP1, but the problem is that nobody knows what coursed all the problems so nobody knows whether the problems are fixed or not! For the moment it cannot be guaranteed that 3.5 SP1 works as well as 2.0.

VS 2008 allow you to select the wanted.NET version when you build your application. This is done in Advanced Compilation Options. Be sure to select either 2.0 or 3.5 SP1! Communication Methods Basically, there are two ways to do serial communication - polled and event driven. In the polled mode, the transmitter sends one or more bytes, which are typically the address of the unit to be polled.

The polled unit then returns the answer, which is then displayed. If the answer is not received within a given amount of time, an error message should be displayed. If the poll and the answer are short and the polled unit answers immediately, a poll program does not necessary need multithreading as everything is done in a precise order. The polled unit does not answer before the poll has been transmitted and a new poll is not initiated before an answer is received or a timeout situation occurs. The program may therefore consist of a single subroutine with a loop, which transmits the poll (unit address), waits for the answer or a timeout, converts any non-text answer to text and then display the text. The polled mode is very simple to program, but since both the poll and the answer depends on the application it is not possible to make a general-purpose program.

If you need this mode, you cannot use our program directly, but it may serve as an inspiration - especially in situations where multithreading is desiable to awoid blocking the UI thread. In the event driven mode, the transmitter and the receiver are completely asynchronous, that is, there is no connection between the transmitter and the receiver.

Serial

The receiver just displays everything, which is received. This is the mode our program is intended for, but it may also be used in polled mode if the transmitter is looped back to the receiver so that the poll is also received, and the transmission uses a protocol, which makes it possible to tell the start of the telegram (distinguish between poll and answer). Event Driven Sample Program When the program is loaded, a list of the available COM ports is generated and put into a ComboBox. One of these possibilities must be selected before any communication can take place. At any time it is possible to change the COM port selection and the Baud rate. The Transmitter TextBox accept any mix of ASCII characters embedded in quotation marks and hexadecimal numbers with an even number of digits like for example 'Test' 78 90 'UU' FF76. A Carriage Return (CR or Enter) is specified as its hexadecimal value 0D and a Line Feed (LF) as 0A.

Note that to transmit ' in an ASCII string it is necessary to write ' - exactly as in Visual Basic. In hexadecimal mode, all spaces, CR's and LF's are ignored. In case of hexadecimal numbers with four or more digits, the numbers are transmitted with the big-endian model, that is, with the most significant part first. The Send button transmits the content of the Transmitter TextBox and the Break button generates a Break condition. The receiver TextBox always writes hexadecimal characters except for a detected Break condition, which is written as 'Break'. Note that because both the transmitter and the receiver regard all numbers as hexadecimal, no hex specifier is used! 63 means 63 hex (99 decimal) - not 63 decimal!

There is no decimal to hex conversion in the program. The maximum telegram length is limited to 2048 bytes, but it is very easy to change this if longer telegrams are needed. The sample program is very simple and the code speaks very much for itself, but because we know that it may still seem overwhelming to absolute beginners we will describe it step by step in the following together with a detailed description of the used.NET methods and properties.

Note however that some basic knowledge about subroutines, functions, data types and declarations etc. Are needed to understand the description. If you are a beginner, it may easily take you days or weeks to go through and understand this totorial, but don't step to a new chapter before you understand the previous one! Take it easy, step by step. The user interface (UI) of.Net is entierly event driven and serial port uses multithreading. Unless you understand how this works, you will never be a good.Net programmer and will never be able to make reliable programs. No matter what.Net programming you need to do, you will need most of the knowledge in this totorial so forget your serial port problems for a while (the reason why you came here) and get the necessary background knowledge first.

Then your serial port application will be a piece of cake to program. SerialPort is really not that difficult. For example, this is all you need to read an ASCII string and append it to the text in the Received textbox. The difficult part is to understand what you are doing! Imports System.IO.Ports Public Class MyFirstCOMProgram Public Delegate Sub StringSubPointer(ByVal Buffer As String) Dim WithEvents COMPort As New SerialPort Private Sub Receiver(ByVal sender As ObjectByVal e As SerialDataReceivedEventArgs) Handles COMPort.DataReceived Me.BeginInvoke(New StringSubPointer(AddressOf Display), COMPort.ReadLine) End Sub Private Sub Display(ByVal Buffer As String) Received.AppendText(Buffer) End Sub ' Initialization somewhere in the program where you open the port. COMPort.PortName = 'COM1' COMPort.BaudRate = 19200 COMPort.ReadTimeout = 2000 ' COMPort.NewLine = Chr(xx) in case the telegram is not terminated with LF.

Try COMPort.Open Catch ex As Exception MsgBox(ex.Message) End Try Private Sub MyFormClosing(ByVal sender As ObjectByVal e As ComponentModel.CancelEventArgs) Handles MyBase.Closing If COMPort.IsOpen Then COMPort.Close End Sub End Class Enumeration In.NET it is possible to assign values to names with the structure GroupName.Member like this: Public Enum MyColors MistyRose = &HE1E4FF& SlateGray = &H908070& DodgerBlue = &HFF901E& DeepSkyBlue = &HFFBF00& SpringGreen = &H7FFF00& ForestGreen = &H228B22& Goldenrod = &H20A5DA& Firebrick = &H2222B2& End Enum This is called an enumeration. When the compiler sees for example MyColors.MistyRose, it replaces it with the RGB value &HE1E4FF (Red = &HE1, Green = &HE4, Blue = &HFF). Note that you can only assign values like integers - not other enumerations. You can therefore not assign something like this: MyRed = colors.Red You can also use enumeration to get the value corresponding to a text string although it is more complicated. For example, you can load a ComboBox (ComboBox1) with all the names in the enumeration list like this: For Each s As String In Enum.GetNames(GetType(MyColors)) ComboBox1.Items.Add(s) Next When you select an item from the comboBox, you can convert to the equivalent RGB value like this: Dim RGBValue As Integer = Enum.Parse(GetType(MyColors), ComboBox1.Text) Note that in both cases, you use GetType(MyColors) to specify the group name. Constructions like this are used in the serial port program for example to select the parity and the software flow control.

It is also very useful in case of a Select-Case construction. Object Oriented Programming.NET is based on the so-called object oriented programming (OOP). If you want to build a machine, you start by making a drawing to define how the machine shall look like and what it is able to do. You can then use this drawing to build many machines of the same type. OOP works the same way.

Each machine type is called a class. When you make the 'drawing', it is called to define the class, and when you build the machine, it is called to declare the object. Note that the 'drawing' is the class and the actual machine is the object. Also note the difference between definition and declaration.

Each new machine you build from the same drawings is called an instance of that class. Everything what the machine is able to do is called methods and all the parameters you set up on the machine to be able to define how the product shall look like are called properties.

For example, a machine may be able to drill holes and cut. This is the methods. The size and position of the holes are selected by means of the properties.

Ray part 2

In fact, everything is done by means of methods. When you set or read a property, you actually call some hidden methods to do the job. For example, myControl.BackColor = Colors.Green is really a shorthand for myControl.SetBackColor(Colors.Green). You cannot access these methods directly, but what is important to note is that setting a property is equivalent to calling a method (SetBackColor). This is important in case of cross thread calls (described later). The argument for the method (Colors.Green) is an example of an enumeration.

If you want to build a new machine similar - but not identical - to an existing one, you don't need to start all over by making a complete new set of drawings. This would also confuse things because it is difficult to tell what the difference between the two models is, and you have to change both set of drawings if a common detail is changed. Instead, you can just take an existing drawing and then specify the changes or additions you want to make. This is called to inherit a class from another class, and the new class is said to be derived from the old one. All data types are actually classes with a predefined definition. For example, a byte is defined as a storage location big enough to hold 8 bits of data. Some of the more complex data types like arrays and strings have methods.

Gcc Serial Port Communication Visual Basic

For example, you can get the length of a sting by calling the Length method like this: LengthOfString = YourString.Length VB use the keyword ' As' to declare the class, that is, to specify which 'drawing' to use, and it uses the keyword ' New' to actually build the object. Dim MyControl As Control specifies that MyControl is a member of the control class, but it does not build the object and therefore does not consume any memory! It is basically an information to the compiler. If you try to use MyControl before the object is build, you will get a NullReference exception. MyControl = New Control builds the object MyControl. Note that MyControl has to be declared by means of an 'As' statement before you can build the object.

If the class has a constructor method called 'New' to initialize the object, this method is called when the object is build. This is used to load a new object with initialization data like this: TextString = New String('Hello World!' ) In this case, 'Hello World!' Is passed to the constructor. The initialization data must be enclosed in parentheses following the class name. However, this is the same syntax as a function call, so in this case, the keyword 'New' is also used to be able to destinguish between the returned value from a function and the build of a new object. Without this keyword, it would be impossible to tell whether String('Hello World!'

) is a function (String) with 'Hello World!' As argument or a declaration of a new instance of the String class with 'Hello World!'

As (initialization) value. A constructor is always a subroutine and it is possible to have more constructors to make the input and initialization more flexible. If you for example have a class - MyClass, which may or may not require a string as input, the constructors may look like this: Public Class MyClass Public Sub New ' Executed in case of no input Me.New('Hello World!'

) ' Call the other contructor with a default input End Sub Public Sub New(ByVal TextInput As String). ' Make any further initialization common to the two constructors End Sub. End Class In this case, the default input 'Hello World!' Is used if no input is specified when the object is build.

In the chapter 'Delegates' of this tutorial, you will see another example of a constructor.

Visual Basic Serial Communication

Note To view the.NET Framework source code for this type, see the. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see.

Visual Basic Serial Port Programming

Use this class to control a serial port file resource. This class provides synchronous and event-driven I/O, access to pin and break states, and access to serial driver properties. Additionally, the functionality of this class can be wrapped in an internal object, accessible through the property, and passed to classes that wrap or use streams.

Visual Studio Serial Port Communication

The SerialPort class supports the following encodings:, and any encoding defined in mscorlib.dll where the code page is less than 50000 or the code page is 54936. You can use alternate encodings, but you must use the or method and perform the encoding yourself. You use the method to retrieve the valid ports for the current computer. If a SerialPort object becomes blocked during a read operation, do not abort the thread.

Instead, either close the base stream or dispose of the SerialPort object.