[Original handout] Matlab-based serial communication

Source: Internet
Author: User

Serial Communication, usually the communication between RS232 and rs422. MATLAB has a special serial function to create a serial object. If the serial port ID is set to COM1, the creation method is:

Copy content to clipboard

Code:

> Scom = serial ('com1 ');

After creating a serial object, you generally need to set the attributes of the serial object. Otherwise, the serial port will not communicate with each other.

Copy content to clipboard

Code:

> Get (scom)
Byteorder = littleendian
Bytesavailable = 0
Bytesavailablefcn =
Bytesavailablefcncount = 48
Bytesavailablefcnmode = Terminator
Bytestooutput = 0
Errorfcn =
Inputbuffersize = 512
Name = Serial-COM1
Objectvisibility = on
Outputbuffersize = 512
Outputemptyfcn =
Recorddetail = compact
Recordmode = Overwrite
Recordname = record.txt
Recordstatus = off
Status = closed
Tag =
Timeout = 10
Timerfcn =
Timerperiod = 1
Transferstatus = idle
Type = serial
Userdata = []
Valuesreceived = 0
Valuessent = 0
Serial specific properties:
Baudrate = 9600
Breakinterruptfcn =
Databits = 8
Dataterminalready = on
Flowcontrol = none
Parity = none
Pinstatus = [1x1 struct]
Pinstatusfcn =
Port = COM1
Readasyncmode = continuous
Requesttosend = off
Stopbits = 1
Terminator = lf

In these attributes, to make the serial port truly communicate, you must set these attributes:
Baudrate: baud rate;
Parity: parity type;
Databits: Data bit, which is generally 8 and does not need to be set;
Stopbits: The stop bit. Generally, it is 1. You do not need to set it;

Timerfcn: timed callback function;
Timerperiod: scheduled period;

Bytesavailablefcn: callback function for byte count
Bytesavailablefcncount: Byte Count
Bytesavailablefcnmode: generally set to byte mode, that is, byte

During serial communication, data is generally transmitted by frame. Some data volumes are large, and frames are packaged and sent. Here, we will only discuss how data is sent by frame.
Assume that the computer is connected to the single-chip microcomputer by a serial port. Each 50 ms of the single-chip microcomputer sends a frame of data to the computer through the serial port. The data format is as follows:
Frame data = frame header + Data + frame count + checksum, 9 bytes in total.
Frame header: two bytes 0x55, 0xaa
Data: 5-byte dat1 dat2 dat3 dat4 dat5
Frame Count: 1 byte 0 to 255, plus 1 loop (equivalent to marking each frame to prevent Frame loss)
Checksum: The sum of 1-byte data, and then the remainder of 256 is used for verification only.

Assume that the serial port baud rate is 115200, And the other attributes are the default values. We can set timerperiod = 0.05, timerfcn = {@ data_rec, handles }. The Property setting statement is:
Set (scom, 'parity ', 'even', 'badrate', 115200, 'timerperiod', 'timerfcn', {@ data_rec, handles })
The callback function can be written as follows:
Function data_rec (OBJ, event, handles)
N_bytes = get (OBJ, 'bytesavailable ');
If n_tytes = 9
Flag = fread (OBJ, n_bytes, 'uint8 ');
Process data under %
Elseif REM (n_tytes, 9) = 0
Flags = fread (OBJ, n_bytes, 'uint8 ');
Process data under %
Else
% If four consecutive REM (n_tytes, 9 )~ = 0. Read all data, calculate the correct frame, and discard the wrong frame.
End

This idea has been proven to be feasible. If the computer needs to return data to the microcontroller at the same time, you can add the fwrite statement before or after the if statement in the callback function to write data to the serial port. For example, if data is returned every MS, you can set a global variable in the callback function:

Copy content to clipboard

Code:

Freq_split = uint8 (0 );

Each input callback function,

Copy content to clipboard

Code:

Freq_split = freq_split + 1;
If freq_split> = 5
Freq_split = 0;
% Write data to serial port
End

Here, when writing data to the serial port, you need to set it to asynchronous writing. The specific statement is:

Copy content to clipboard

Code:

Fwrite (OBJ, datas, 'int8', 'async ');

In the specific project, the problem is much more complicated. When the reader encounters a problem, he must first carefully consider it.
The "Matlab GUI Design learning note" provides a basic and complete introduction to serial programming. The key lies in the compilation of callback functions.
In addition, the book also mentions that if you want to take into account the stability and real-time of the system, you can consider using a timer to replace the timerfcn of the serial object, because timer seems more powerful, because, if the timer execution mode is fixedspacing, the serial callback function is executed sequentially. If a callback function is not executed, the timer starts to be 50 ms, instead of running the previous callback, start timing.

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.