How to use and program the STM32 serial port USART1

Publisher:oplkjjjLatest update time:2017-09-08 Source: eefocusKeywords:STM32 Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

The Universal Synchronous Asynchronous Receiver/Transmitter (USART) provides a flexible method for full-duplex data exchange with external devices using the industry standard NR asynchronous serial data format. The USART provides a wide range of baud rate selections using a fractional baud rate generator, supporting both synchronous unidirectional communication and half-duplex single-wire communication.

1. The main idea of ​​using peripheral devices in the STM32 firmware library

In STM32, the configuration ideas of peripheral devices are relatively fixed. First, the relevant clocks are enabled. On the one hand, the clock of the device itself is enabled. On the other hand, if the device outputs through the IO port, the clock of the IO port also needs to be enabled; finally, if the corresponding IO port is an IO port with multiplexing function, the clock of AFIO must also be enabled.

The second step is to configure GPIO. The various properties of GPIO are detailed in the AFIO chapter of the hardware manual and are relatively simple.

Next, if the relevant device needs to use the interrupt function, the interrupt priority must be configured first, which will be described in detail later.

Then configure the related properties of the peripheral device, depending on the specific device. If the device needs to use the interrupt mode, the interrupt of the corresponding device must be enabled, and then the related devices need to be enabled.

Finally, if the device uses the interrupt function, you also need to fill in the corresponding interrupt service program and perform corresponding operations in the service program.

2. UART configuration steps (query method)

2.1. Open the clock

Since the TX, RX and AFIO of UART are all hung on the APB2 bridge, the firmware library function RCC_APB2PeriphClockCmd() is used for initialization. UARTx needs to be discussed separately. If it is UART1, it is hung on the APB2 bridge, so RCC_APB2PeriphClockCmd() is used for initialization, and the rest of UART2~5 are hung on APB1.

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE);

2.2 GPIO initialization

The properties of GPIO are contained in the structure GPIO_InitTypeDef, where for the TX pin, the GPIO_Mode field is set to GPIO_Mode_AF_PP (multiplexed push-pull output), and the GPIO_Speed ​​switching rate is set to GPIO_Speed_50MHz; for the RX pin, the GPIO_Mode field is set to GPIO_Mode_IN_FLOATING (floating input), and the switching rate does not need to be set. Finally, enable the IO port through GPIO_Init().

The following is the example code for GPIO settings:

    GPIO_InitTypeDef GPIO_InitStructure; //USART1 Tx(PA.09) 
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; 
    GPIO_InitStructure.GPIO_Speed ​​= GPIO_Speed_50MHz; 
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; 
    GPIO_Init(GPIOA, &GPIO_InitStructure); //USART1 Rx(PA.10) 
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; 
    GPIO_InitStructure.GPIO_Speed ​​= GPIO_Speed_50MHz; 
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; 
    GPIO_Init(GPIOA, &GPIO_InitStructure);

2.3. Configure UART related properties

Determined by the USART_InitTypeDef structure. The fields in UART mode are as follows

USART_BaudRate: baud rate, depending on the specific device

USART_WordLength: word length

USART_StopBits: Stop bits

USART_Parity: verification method

USART_HardwareFlowControl: Hardware flow control

USART_Mode: Single/Duplex

Finally set up. The example code is:

   //USART1 configuration
  USART_InitTypeDef USART_InitStructure; USART_InitStructure.USART_BaudRate = 9600; 
    USART_InitStructure.USART_WordLength = USART_WordLength_8b; 
    USART_InitStructure.USART_StopBits = USART_StopBits_1; 
    USART_InitStructure.USART_Parity = USART_Parity_No; 
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx; 
    USART_Init(USART1, &USART_InitStructure);
    USART_Cmd(USART1, ENABLE);

Don't forget to use USART_Cmd() at the end to start the device UART1.

2.4. Redirect the print() function.

int fputc(int ch,FILE *f)
{
    USART1->SR; //USART_GetFlagStatus(USART1, USART_FLAG_TC) Solve the problem of failure to send the first character //Send characters one by one
    USART_SendData(USART1, (unsigned char) ch); //Wait for sending to complete
    while(USART_GetFlagStatus(USART1,USART_FLAG_TC)!=SET);    
    return(ch);
}


int main(void)
{ // USART1 config 9600 8-N-1 USART1_Config();
    
    printf("hello world!");
}

3. UART configuration steps (interrupt mode)

Turning on the clock, initializing GPIO, configuring UART related properties, and redirecting the print() function are the same as above.

3.1、Configuration of interrupt priority

This is a strange thing about STM32. When there is only one interrupt, the priority still needs to be configured to enable the trigger channel of a certain interrupt. STM32 interrupts have at most two levels, namely preemptive priority and slave priority. The length of the entire priority setting parameter is 4 bits, so it is necessary to first divide the preemptive priority bit and the slave priority bit, which is implemented through NVIC_PriorityGroupConfig();

The interrupt priority NVIC property of a specific device is contained in the structure NVIC_InitTypeDef, where the field NVIC_IRQChannel contains the interrupt vector of the device, which is saved in the startup code; the field NVIC_IRQChannelPreemptionPriority is the primary priority, and NVIC_IRQChannelSubPriority is the secondary priority. The value range should be determined according to the bit division situation; finally, the NVIC_IRQChannelCmd field is whether to enable, generally located at ENABLE. Finally, NVIC_Init() is used to enable this interrupt vector. The example code is as follows:

//Configure UART1 receive interrupt void NVIC_Configuration(void)
{
    NVIC_InitTypeDef NVIC_InitStructure; 
    /* Configure the NVIC Preemption Priority Bits */  
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);    
    /* Enable the USARTy Interrupt */
    NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;     
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
}

 

3.2 Design of interrupt service program

Currently, two interrupts of UART are used: USART_IT_RXNE (receive buffer fill interrupt) and USART_IT_TXE (transmit buffer empty interrupt). The former interrupt ensures that once data is received, an interrupt is entered to receive data of a specific length. The latter interrupt means that once a data is sent, an interrupt function is entered to ensure continuous transmission of a segment of data. All interrupts of a device are included in an interrupt service routine, so it is necessary to first distinguish which interrupt is being responded to this time, and use the USART_GetITStatus() function to determine it; use the USART_ReceiveData() function to receive a byte of data, and use the USART_SendData() function to send a byte of data. When the interrupt is turned off, use USART_ITConfig() to disable the interrupt response. Example program:

 All programs in this experiment "STM32 serial port USART1 query and interrupt mode program"

 

Supplement: There has always been a question about receiving and sending data: for a string like "hello", are they received one by one or displayed as a whole? The following experiment can verify whether it is done one by one.


Keywords:STM32 Reference address:How to use and program the STM32 serial port USART1

Previous article:STM32 debug interface SWD connection
Next article:STM32 USART usage notes

Recommended ReadingLatest update time:2024-11-16 13:34

STM32 dynamically changes PWM wave frequency and duty cycle
STM32 PWM wave dynamic frequency modulation and duty cycle adjustment Take TIM3_CH1 as an example (1) Working principle of timer The time base unit of the timer consists of three parts: ① automatic loading register (TIMx_ARR), ② prescaler register (TIMx_PSC), ③ counter register (TIMx_CNT). Set the automatic loading
[Microcontroller]
STM32 dynamically changes PWM wave frequency and duty cycle
What is the difference between the regular channel and the injection channel of the STM32 ADC
Each ADC module of STM32 can switch to different input channels and perform conversions through the internal analog multiplexer. STM32 has specially added a variety of group conversion modes, which can be set by the program to automatically sample and convert multiple analog channels one by one.   There are two ways
[Microcontroller]
STM32 library function port initialization description
The following only describes the operation ports of these two MCU library functions. 1. Port function description STM32F0 series typedef struct {   uint32_t GPIO_Pin; //Pin configuration      GPIOMode_TypeDef GPIO_Mode; //Port mode   GPIOSpeed_TypeDef GPIO_Speed; //Pin speed   GPIOOType_TypeDef GPIO_OType; //Output s
[Microcontroller]
STM32 USB Learning Notes 5
Host environment: Windows 7 SP1 Development environment: MDK5.14 Target board: STM32F103C8T6 Development library: STM32F1Cube library and STM32_USB_Device_Library Following the previous article, for the upper-layer application, only the CDC class interface file, usbd_cdc_interface, is left. This file is mainly
[Microcontroller]
STM32 USB Learning Notes 5
STMicroelectronics' STM32 Smart Wireless Modules Accelerate Development of Innovative Connected Products
STMicroelectronics' STM32 Smart Wireless Modules Accelerate Development of Innovative Connected Products I-care Group uses STM32WB5MMGH6 wireless module in Wi-care smart industrial predictive maintenance system November 7, 2022, China -- STMicroelectronics (STMicroelectronics), a world-
[Embedded]
STM32 different flash memory capacity boot file selection instructions
Small-capacity products refer to STM32F101xx, STM32F102xx and STM32F103xx microcontrollers with flash memory capacities between 16K and 32K bytes. Select startup_stm32f10x_ld.s. Medium-density products refer to STM32F101xx, STM32F102xx and STM32F103xx microcontrollers with flash memory capacities between 64K and 128
[Microcontroller]
STM32 IoT TFTP file transfer
Remarks: Focus on IoT application development and share IoT technology experience. Software platform: IAR6.5 TCP/IP protocol stack: LWIP1.4.1 Hardware platform: STM32F103C8T6 wired communication board 1. TCP/IP protocol stack LWIP 1.1. LWIP Introduction        LWIP is a small open source TCP/IP protocol s
[Microcontroller]
Application of STM32 and CAN bus in temperature monitoring system
  introduction   In the field of modern industrial control, it is usually necessary to measure many signals, convert them into binary signals that can be recognized by computers, and use computers to monitor and record various measured signals. This process involves signal acquisition and processing. CAN bus is a ser
[Microcontroller]
Application of STM32 and CAN bus in temperature monitoring system
Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
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号