Serial communication record between matlab and stm32

Publisher:悠闲自在Latest update time:2018-09-09 Source: eefocusKeywords:matlab  stm32 Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

1. Functions involved


serial,fopen,fclose,

instrfindall,instrhwinfo,

fprintf,fscanf,fwrite,fread,isempty


1.1 Serial port function


scom = serial('com6','BaudRate',115200,'BytesAvailableFcnMode','byte'); 

fopen(scom); 

.

fclose(scom);


Or set the serial port properties separately as follows:


scom = serial(com);  

scom.BaudRate = 115200;

scom.InputBufferSize = 512;

scom.BytesAvailableFcnMode = 'terminator';  % 'byte'

scom.terminator = CR/LF ;

scom.Timeout = 50; %read or write wait time

fopen(scom);

.

fclose(scom);


Usually the serial port is deleted after closing it, and the serial port data is cleared in the MATLAB workspace:


delete(scom);

clear scom;


Question 1.: After opening Matlab, the serial port can be opened successfully for the first time, but the following error will be reported when opening it for the second time:


>> scom = serial('com6','BaudRate',115200,'BytesAvailableFcnMode','byte');

>> fopen(scom)

Error using serial/fopen (line 72)

Open failed: Port: COM6 is not

available. Available ports: COM1.

Use INSTRFIND to determine if other

instrument objects are connected to the

requested device.


Solution: My personal understanding is that after closing the serial port, the serial port is not completely cleared, just like some software will fail to be installed again after being uninstalled, so you need to delete all previous settings of the serial port before reopening it, as follows:


>> scom = serial('com6','BaudRate',115200,'BytesAvailableFcnMode','byte');

>> fopen(scom);

Error using serial/fopen (line 72)

Open failed: Port: COM6 is not

available. Available ports: COM1.

Use INSTRFIND to determine if other

instrument objects are connected to the

requested device.


>> delete(instrfindall('Type','serial'));

>> scom = serial('com6','BaudRate',115200,'BytesAvailableFcnMode','byte');

>> fopen(scom);

>> fclose(scom)


>> help instrfindall

 instrfindall Find all communication interface objects with specified

 property values.


The instrfindall function can find all interfaces that communicate with MATLAB, and can also find interfaces that meet specific parameters.


1.2 Understanding serial parameters 

All the parameters and current values ​​of the serial port can be obtained through >> s=get(scom), the main settings of which are:


BaudRate, baud rate

ByteOrder, data big endian or little endian mode, default small segment

DataBits, data bits, usually 8 bits by default

Parity, check bit, default is none

StopBits, stop bit, default 1

Timeout, waiting time for MATLAB serial port to send or read data

ReadAsyncMode, asynchronous reading mode, continuous or manual, the default is continuous


----------

BytesAvailableFcnMode

BytesAvailableFcnCount

BytesAvailableFcn

Terminator

BytesAvailable

indicates the trigger mode of data validity, which is equivalent to the interrupt trigger event in C: the default value is terminator, which means that when the serial port receives a specific terminator, the bytes-available event is triggered, the parameter is automatically increased by one, and the callback function pointed to by is entered, which is equivalent to the interrupt function in C; the optional value is byte, which means that when the serial port receives a byte, the bytes-available event is triggered, is automatically increased by one, and when it receives

The callback function is entered when bytes are available.

The terminator is usually a carriage return or line feed, but you can also set it yourself according to the communication protocol, [CR, LF, CR/LF line feed characters for Windows, Linux and MAC](http://blog.csdn.net/cckit/article/details/41604771).


Matlab searches for available serial port functions using instrhwinfo:


>> info = instrhwinfo('serial')

info = 

  HardwareInfo with properties:

     AvailableSerialPorts: {2x1 cell}

           JarFileVersion: 'Version 3.7'

    ObjectConstructorName: {2x1 cell}

              SerialPorts: {2x1 cell}

Access to your hardware may be provided by a support package. Go to the Support Package Installer to learn more.


>> info.SerialPorts

years = 

    'COM1'

    'COM6'

>> info.AvailableSerialPorts

years = 

    'COM1'

    'COM6'

>> str = char(info.SerialPorts(2))

str =

COM6

>> scom=serial(str);


I checked the computer device manager and found that the serial port used was 'COM6'. I don't know what 'COM1' is connected to, so the function of using MATLAB to automatically select the serial port has not been realized here.


1.3 Data reading and writing functions


matlab:

fprintf(scom,'%d\n', data,'async' );

data = fscanf(scom,'%d');

c:

scanf("%d",&data);

printf("%d\r\n",data);


Note1: The scanf and printf functions in C print and read data from the terminal by default, so the fputc and fgetc functions need to be redirected here. 

Note2: The scanf function in C will continue to run and not exit until it reads valid data.


Question 2: Call the scanf function in the serial port interrupt function of stm32 to read the data sent by matlab. Use fprintf(scom,'%d\r\n', data,'async') in matlab to send data. When stm32 enters the interrupt to read the data, it always enters the interrupt again and enters the scanf function and cannot come out. 

Processing method: The format of data sent in matlab is '%d\r\n', which is carriage return plus line feed. My personal understanding is that after the serial port sends a byte, it also sends out '\r', which is a carriage return character. Therefore, after the scanf function in the serial port receive buffer of stm32 reads the data, the carriage return character causes the receive interrupt again. 

After changing the data format in the matlab send function to '%d\n', stm32 can read the data normally.


matlab:

fwrite(scom,data,'uint8','async');

cmd_ack = fread(scom,1,'uint8');

c:

rec = USART_ReceiveData( DEBUG_USART );

Usart_SendByte(DEBUG_USART,data);


Note1: fwrite and fread send data in binary format, while fprintf and fscanf above send data in ASCII format. 

For example: data is the decimal number 123, its hexadecimal is 0x7b, the underlying binary data stream is 0111 1011, and it is sent as ASCII code as 0x31, 0x32, 0x33, and the underlying data stream is 0011 0001, 0011 0010, 0011 0011. 

If you use the fwrite and fread functions in Matlab, the serial port parameters must also be changed to byte.


Keywords:matlab  stm32 Reference address:Serial communication record between matlab and stm32

Previous article:STM32 combination device realizes USB to dual serial port
Next article:STM32 serial communication (buffer-based) programming and problems encountered

Recommended ReadingLatest update time:2024-11-15 11:25

Sharing of experience in STM32 CAN fieldbus experiment
Recently, I have been doing CAN field bus experiments on the STM32 experimental board. I have only done serial communication on STC51 before. In comparison, I found that CAN bus is quite complicated. At the beginning, I knew that I was a novice. I only knew that CAN bus, like serial communication, 485 communication, an
[Microcontroller]
Sharing of experience in STM32 CAN fieldbus experiment
Complementary output and dead zone insertion of stm32
1 Introduction Dead zone, simple explanation: Usually, high-power motors, inverters, etc., are all H-bridges or 3-phase bridges composed of high-power tubes, IGBTs and other components at the end. The upper and lower bridges of each bridge must not be turned on at the same time, but when the high-speed PWM drive signa
[Microcontroller]
Implementation of STM32+IAP solution under IAR environment
1. What is IAP and why do we need IAP?       IAP stands for In Application Programming. Generally, the devices with STM32F10x series chips as the main controller have already used J-Link emulator to burn the application code before leaving the factory. If the application code needs to be replaced or upgraded during th
[Microcontroller]
Implementation of STM32+IAP solution under IAR environment
STM32 Introduction - General Timer Configuration
Benefits of Universal Timer  Tout= ((arr+1)*(psc+1))/Tclk; TIM3 clock enable TIM3 is mounted under APB1, so we enable TIM3 through the clock enable function under the APB1 bus. The function called is: RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //Clock enable Initialize timer parameters, set auto-reload
[Microcontroller]
STM32 timer output comparison time mode
As mentioned in the SM32 Timer Essentials, the timer can be configured into six modes, as follows:   TIM_OCMode  Library Description  explain   TIM_OCMode_Timing  TIM Output Compare Time Mode  Freeze, output compare not working  TIM_OOCMode_Active  TIM output compare active mode  When
[Microcontroller]
STM32 timer output comparison time mode
Understanding the startup code of the medium-capacity STM32 processor
Today I want to introduce the startup code of STM32. I am using the medium-capacity STM32f103c8t6 here. The corresponding startup file is startup_stm32f10x_md.s. My startup file version is V3.6.2 Without further ado, here are the source codes I annotated:   /**   ***************************************************
[Microcontroller]
STM32 comment style
@brief: A brief description of the function; @ref: reference; @defgroup: used to add define grouping (defgroup); Format: example: @param: parameter description; @arg: You can select parameter enumeration in the parameter, and you can enumerate parameters for countable cases; @note: annotation, which can achiev
[Microcontroller]
STM32 comment style
Design of wireless communication terminal system based on STM32
1. Introduction Currently, most instruments and equipment use RS232 interfaces to communicate with computers. However, with the development of computer technology, the hot-swappable USB standard interface will replace the RS232 interface. Therefore, computers will be less and less equipped with RS232 interfaces or eve
[Power Management]
Design of wireless communication terminal system based on STM32
Latest Microcontroller Articles
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号