"ALB Technical note" Serial communication interface data receiving case based on multi-threaded mode

Source: Internet
Author: User

Serial communication interface Data receiving case based on multi-thread mode

Guangdong Institute of Vocational and Technical technology Aohaoyuan

1. Case background

In this Blog "CC2530 Introductory Tutorial-06" CC2530 ADC Working principle and application of the design of voltage data acquisition, sensor module in the form of sending a frame of data every 1 seconds through the serial port to send voltage data. Its data frame consists of 4 bytes: A frame head and a frame end, the middle two bytes are voltage data, the format is as follows:

frame Head (0xAF) voltage Data high 8-bit voltage data low 8-bit frame tail (0xFA)

In this blog post, we will show you how to receive the data frames sent from the serial port via multi-threading, and display the data frame and the actual voltage value after conversion.

2. Interface design

3. Introduction of command Space

Using multithreading, you need to introduce a namespace:system.threading;

Using a serial communication interface, you need to introduce a namespace:System.IO.Ports;

4, the initialization of the work

first, define the object of a serial interface and the field of a thread,

Then, add the Form Mount event (the Load event ) to the main form, where the properties of each control are initialized.

SerialPort com =NewSerialPort ();//instantiate a serial port objectThread T;//Define a thread field        Private voidForm1_Load (Objectsender, EventArgs e) {textbox1.readonly=true;//text Box read-onlyTextbox1.scrollbars = scrollbars.vertical;//text box supports vertical scroll barCOMBOBOX1.ITEMS.ADD ("COM1"); COMBOBOX1.ITEMS.ADD ("COM2"); COMBOBOX1.ITEMS.ADD ("COM3"); COMBOBOX1.ITEMS.ADD ("COM4"); COMBOBOX1.ITEMS.ADD ("COM5"); Combobox1.selectedindex=2; COMBOBOX2.ITEMS.ADD ("4800"); COMBOBOX2.ITEMS.ADD ("9600"); COMBOBOX2.ITEMS.ADD ("19200"); COMBOBOX2.ITEMS.ADD ("57600"); COMBOBOX2.ITEMS.ADD ("115200"); Combobox2.selectedindex=1; COMBOBOX3.ITEMS.ADD ("6"); COMBOBOX3.ITEMS.ADD ("7"); COMBOBOX3.ITEMS.ADD ("8"); Combobox3.selectedindex=2; COMBOBOX4.ITEMS.ADD ("1"); COMBOBOX4.ITEMS.ADD ("1.5"); COMBOBOX4.ITEMS.ADD ("2"); Combobox4.selectedindex=0; }

5. Setting the Serial interface

in the serial communication, the general process is: first set the port number of communication, baud rate , data bit , stop bit and check bit , and then Open the serial port , then send the data and receive data, and finally to close the serial port .

In this case, the various parameters of the serial port configuration is completed, open the serial port, and then start the serial data received thread, began to poll the way to receive data.

        Private voidButton1_Click (Objectsender, EventArgs e) {            if(button1. Text = ="Open the serial port") {com. PortName= Combobox1.text;//Select serial NumberCom. BaudRate =int. Parse (Combobox2.text);//Select baud RateCom. DataBits =int. Parse (Combobox3.text);//Select the number of data bitsCom. StopBits = (stopbits)int. Parse (Combobox4.text);//Select the number of stop bitsCom. Parity = Parity.none;//Select whether the parity check                Try                {                    if(COM. IsOpen)//determine if the serial port is open{com.                        Close (); Com.                    Open (); }                    Else{com.                    Open (); } t=NewThread (com_datareceived);//Create and enable a data receive threadT.start (); }                Catch(Exception ex) {messagebox.referenceequals ("Error:"+ ex. Message,"Serial Communication"); } button1. Text="Close the serial port"; }            Else if(button1. Text = ="Close the serial port") {com.                        Close (); //Close the serial portT.abort ();//terminating a threadButton1. Text ="Open the serial port"; }        }

6. Serial data Receive threading method

In this method, the data in the serial buffer is read only when the serial port is open and the connection is successful.

First, by reading the Bytestoread property , get the number of bytes of data in the serial receive buffer, and then instantiate a byte type of data based on this property, reading the data from the buffer into the array through the Read method .

Displays the data frame in a 16-based format to the form's text box.

The actual voltage value is obtained by calculation and displayed to the corresponding lable label.

        Private voidcom_datareceived () { while(COM. IsOpen)//read data when the serial port is open            {                stringSTRRCV =""; intCount = com. Bytestoread;//Gets the number of bytes of the serial buffer                byte[] Readbuffer =New byte[Count];//instantiate an array of incoming serial data                if(Count! =0)//If the serial port receives the data{STRRCV= count. ToString () +" "; Com. Read (Readbuffer,0, count);//reading data from the serial port buffer to the array                     for(inti =0; i < readbuffer.length; i++) {STRRCV+ = Readbuffer[i]. ToString ("X2") +" ";//16 binary Display} TextBox1.Text+ = STRRCV +"\ r \ n"; if(readbuffer[0] ==0xAF&& readbuffer[3] ==0xFA)//determine the frame header and end of the frame of the data{Int32 ad= readbuffer[1]; DoubleAdvalue; Ad<<=8; Ad|= readbuffer[2];//extracting voltage data from a data frameAdvalue =AD; Advalue= (Advalue *3.3) /32768;//Convert the data to the actual voltage valueLabel6. Text = Advalue. ToString ("F2") +"V"; }} thread.sleep ( -); }

7. Program Operation result

8. Conclusion

Serial interface communication is a common method of data interaction in the application of Internet of things technology.

It is the most basic method to read the serial buffer data by means of multi-thread, but it is not the only method. The use of dadareceived event triggering method to receive data is also very common, when the design level is slightly more complicated, and then slowly tell.

ALB Technical note the serial communication interface data receiving case based on multithreading

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.