"Serial communication"--Write your Read event "Live"

Source: Internet
Author: User
Tags time interval

In the last blog, we introduced the thread application in serial communication to solve the problem of receiving data. But in the end, we have 3 questions to ask. Today we'll show you how the first problem is handled, that is, if the data length of the returned data is different, how to write a loop in the Read method to read the full return data.

Of course if you haven't read my last blog, here I'll write the Read method separately:

Private Sub Read ()
	Try
		serialport.discardinbuffer ()
		Dim str As String = ""
		Dim buf () as Byte 
  
   for i = 0 to 10 ' assumes that the data received should be 11
			Dim D as Integer
			d = _serialport.readbyte ' read a byte of data from the string, if the read timeout is set, not read at the specified time  The data will trigger a timeout error.
			str = convert.tostring (d, 16). PadLeft (2, "0")
		Next
		buf = getbyte (str)
		' according to protocol, processing received data
	Catch ex as Exception
		Throw ex 
   end Try End
Sub

  

The above code focuses on the for loop in which the number of loops is determined based on the length of the returned data, guaranteeing the integrity of each returned data. And the readbyte of the port class is blocking the call, the time is not read to the data will trigger a timeout error, which requires us to ensure that the number of cycles per accepted operation must be the same as the length of the data returned. But in our practical applications it is not possible to guarantee that the system we are dealing with is just a single type of return data. I also said that you can control the number of for loops in the Read method with the command type, just add one more parameter to the Send method (or encapsulate an entity with an additional attribute in the entity, one meaning.) But there are always exceptions, and this is what I encountered (I encountered the same type of command). But the data returned varies depending on the length of the data returned by the hardware. )



Someone would have asked. Such a powerful Microsoft does not encapsulate such a method, you can guarantee the integrity of receiving data each time. I've been looking for a long time, of course, and here's my collation of some of the Read methods of the SerialPort class: Serialport.read Method (byte[), Int32, Int32) Serialport.read method (char[], Int32, Int32)

Explanations of these two methods:

Reads a large number of characters (bytes) from the SerialPort input buffer and writes those characters (bytes) to the offset specified in a character (byte) array.

Parameters:

Buffer

Type: system.char[]

The character (byte) array into which input is written.

Offset

Type: System.Int32

The offset at which to begin writing in the buffer array.

Count

Type: System.Int32

The number of characters (bytes) to read.

return value:

Type: System.Int32

The number of characters (bytes) read.

Summary: One of the most important is the number of characters (bytes) to read. This also requires that we first know the length of the data we need to read.


Serialport.readchar Method Serialport.readbyte Method

Explanations of these two methods:

Reads a character (bytes) synchronously from the SerialPort input buffer.

Summary: Both of these methods read a byte or character of the buffer, so we have to figure out how many times to read, that is, we must first know the length of the data we want to read.


Serialport.readexisting Method:

The explanation of this method:

Reads the stream of the SerialPort object and all immediately available bytes in the input buffer, based on the encoding.

Summary: As if this method is the way we have been struggling to find, but we analyze the mechanism of serial communication, first of all, our Read method, is to send the data immediately after the read thread, and the serial read data will take time, which includes sending, hardware processing (depending on its frequency.) , the time returned, and these times must be longer than the processor's code to process the Read method, so often the data that readexisting reads is often empty (if we are stepping code debugging, this method is often correct, Because we slowed down the processor's time to process the code manually. )

For the serial port of their own listening time datareceive (Received data will trigger) event, as if this method will be more useful. But this approach, as MSDN says, "does not guarantee that the DataReceived event is raised for each byte received by the docking." This also means that I am less sure about the number of data we have read in this method. Of course, all the data received can be saved, and then wait for a certain amount of time to receive data, as all received data to deal with. The point of this is this "a certain amount of time control" (similar to the method described later) but not in detail here, after all, today's focus is our Read method.


ReadLine Method:

The interpretation of this method;

Reads the newline value into the input buffer all the time. (newline: A value that represents the end of a line. Default value is line feed)

Summary: This method is very suitable for a chat program, we did not finish their sentence, need to send, click on the return (a newline). But for the hardware we face, no newline is waiting for you.


Readto Method:

The explanation of this method:

The string that is read to the specified value in the input buffer.

Summary: This approach has a similar problem with the previous methods, which is that you cannot know in advance what the last character you are going to read. (but this is possible if you have already set an end sign in the agreement that you stipulated earlier.)



Having said so many ways, I didn't find the right way to go through the thinking also has my following implementation methods, I hope for the same problem with my people to help:

Read method:

Private Sub Read () Try Dim str As String = "" ' defines a string variable that temporarily saves returned data Dim BUF () as Byte ' defines the number of saved returns Variable Dim datacount As Integer = _serialport.bytestoread ' defines the variable Dim datacountnew As I that holds the buffer data of type Byte Nteger = 0 ' defines the variable Dim counttimes as Integer = 0 ' attempts to read data from the buffer ' to save the latest buffer data that needs to be read ' This is the core of this paragraph, 1000*sleep ( 5 indicates the longest time to wait for the serial port to return data ' if the first time you get a buffer that needs to read 0, the thread pauses 5ms (and of course you can set it yourself, the smaller the number, the less performance may not be better. Appropriate on the line). Once you read the data, execute the following code.
            Or the loop completes, and you can't read the data and throw an exception. while (Datacount = 0 and Counttimes < 1000) Thread.Sleep (5) ' thread hibernate 5ms Datacount = _seria
                    Lport.bytestoread ' re-remove buffer to read data ' If the data is also 0 if (datacount <= 0) Then ' Read the number plus 1 counttimes = counttimes + 1 Continue while ' continues to execute the loop Els E ' Otherwise exits the loop exit while the ' End If ' is still not read after waiting 1000*5ms=5 seconds
Data            If Datacount = 0 Then ' throws an exception Throw New Exception ("Connection extension timeout, see whether the extension is started, or check the communication network ... ") End If" If read the data, first hibernate 500ms (this data is generally based on the number of returned data and the frequency of the crystal oscillator, as well as data transmission some time set, if the query data for the performance of time is not high can be appropriate to increase the length), read the buffer again Area to be read, compared to the data just read, and if equal, the read data is complete.
            can be processed.
                While True Thread.Sleep (m) datacountnew = _serialport.bytestoread ' The number of buffer data re-read. ' If not unequal, the number of buffer data read this time is saved as the most recent data if Datacount <> datacountnew Then DataCo
            UNT = Datacountnew Else ' If the same, the data returns complete, exit loop exit while End if
                The loop at this time for i = 0 to Datacount ' will vary according to the actual situation.    
                Dim D as Integer d = _serialport.readbyte ' reads one byte of data from the string, and if the read timeout is set, the timeout error is triggered when the data is not read at the specified time. str = convert.tostring (d, 16).
            PadLeft (2, "0") Next buf = getbyte (str) ' Converts the received data to an array of bytes. ' RootAccording to Protocol, processing received data Catch ex as Exception Throw ex end Try-end Sub 


The comments in the code above are clear and I don't want to be more descriptive.

It also requires two points: if the time to sleep in the second while loop after reading the data is too short, it can also cause a data read error, because after the first reading of the data, the serial buffer in the dormant time does not read the next data. The number of buffers to be read for the first time is the same as the number of buffer data read for the second time. The great benefit of this is that the program automatically determines the length of time to wait, we put the time of each while cycle as far as possible in a reasonable range of the shortest, (the first reasonable range is: the first time the serial port to receive data experience the time, the second reasonable range is: Once the command sent, The time interval for each return is generally based on the number of times the data returned and the frequency of the crystal oscillator, and some time settings for the data transfer.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.