STM32 Serial port USART1 use method and procedure

Source: Internet
Author: User

The Universal Synchronous Asynchronous Transceiver (USART) provides a flexible method for full-duplex data exchange with external devices using the Industrial standard NR asynchronous serial data format. The Usart uses a fractional baud rate generator to provide a wide range of baud rate options, supporting synchronous one-way communication and half-duplex single-line communication.

1, STM32 firmware Library use of peripheral equipment, the main idea

In STM32, the configuration of peripheral devices is relatively fixed. The first is to enable the related clock, on the one hand is the clock of the device itself, on the other hand if the device through the IO port output also need to enable the IO port clock; Finally, if the corresponding IO port is the IO port of the multiplexing function, then the AFIO clock must be enabled.

The second is to configure the various properties of the Gpio,gpio by the Hardware manual Afio chapter detailed provisions, relatively simple.

Then the relevant equipment needs to use interrupt function, if necessary, must first configure the interrupt priority, the following article is detailed.

Then the related properties of the configuration peripherals, depending on the specific device, if the device needs to use the interrupt mode, must be able to enable the corresponding device interrupt, and then need to enable the relevant equipment.

Finally, if the device uses the interrupt function, it also needs to fill in the corresponding interrupt service program, in the service program to do the corresponding operation.

2, the UART configuration steps (Query method)

2.1. Turn on the clock

Since the UART TX and RX and Afio are both hung on the APB2 Bridge, the firmware library function Rcc_apb2periphclockcmd () is used for initialization. Uartx need to discuss the situation, if it is UART1, it hangs on the APB2 bridge, so the Rcc_apb2periphclockcmd () is initialized, the rest of the uart2~5 are hung on the APB1.

    Rcc_apb2periphclockcmd (Rcc_apb2periph_gpioa | Rcc_apb2periph_usart1, ENABLE);

2.2. Gpio Initialization

The properties of the GPIO are contained in the struct 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 null input) and no switching rate is required. Finally through the Gpio_init () Enable IO port.

The following is the instance code for the 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

It is determined by the structural body usart_inittypedef. The fields in the UART mode are as follows

Usart_baudrate: Baud rate, depending on device

Usart_wordlength: Word length

Usart_stopbits: Stop Bit

Usart_parity: Check mode

Usart_hardwareflowcontrol: Hardware flow control

Usart_mode: Single/Duplex

Last set. The instance code is:

   USART1 Configuration
  Usart_inittypedef usart_initstructure;

  9600 ; = usart_wordlength_8b; = usart_stopbits_1; = usart_parity_no; = Usart_hardwareflowcontrol_none; = Usart_mode_tx | Usart_mode_rx; &usart_initstructure);

Don't forget to end up using Usart_cmd () 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) resolves an issue    where the first character fails to send //One send character    Char ) ch);     //wait for Send to complete     while (Usart_getflagstatus (USART1,USART_FLAG_TC)! =SET)        ; return (CH);}

Finally, the direct output via the main function can be.

int Main (void) {    ///    usart1_config ();        printf ("Hello world! " );}

3, the UART configuration steps (Interrupt mode)

Turn on clock, Gpio initialization, configure UART-related properties, redirect print () functions the same as above.

3.1, the configuration of the interrupt priority level

This is STM32 strange place, in the case of only one interruption, still need to configure the priority, its role is to enable the trigger channel of an interrupt. STM32 interrupts have a maximum of two levels, respectively, priority and priority, and the length of the entire priority setting parameter is 4 bits, so it is necessary to first divide the first priority and the number of priority bits, through nvic_prioritygroupconfig () implementation;

The properties of the interrupt priority Nvic for a particular device are contained in the struct nvic_inittypedef, where the field Nvic_irqchannel contains the device's interrupt vector, saved in the startup code, and the field nvic_ Irqchannelpreemptionpriority priority, Nvic_irqchannelsubpriority is the priority, the range of values should be based on the situation of the number of bits; finally nvic_ The Irqchannelcmd field is enabled, general positioning enable. Finally, the interrupt vector can be obtained by Nvic_init (). The instance code is as follows:

//configuring UART1 Receive interruptsvoidNvic_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, the interruption of the service program design

The

currently uses the UART's two interrupt Usart_it_rxne (receive cache fill air break) and Usart_it_txe (send cache air break), the previous interrupt ensures that once the data is received to enter the interrupt to receive a specific length of data, The latter interrupt indicates that once a data is sent into the interrupt function, a continuous transmission of data is guaranteed. All interrupts for a device are included in an interrupt service program, so you must first clarify which interrupt this response is in, use the Usart_getitstatus () function to determine it, and use the Usart_receivedata () function to receive a byte of data, using Usart_ The SendData () function sends a byte of data that is interrupted by a usart_itconfig () failure response when the interrupt is closed. Instance Program:

void Usart1_irqhandler (void) {    uint8_t ch;         if (Usart_getitstatus (USART1, usart_it_rxne)! = RESET)    {             //ch = usart1->dr;            ch = usart_receivedata (USART1);     // Accept Data          " %c ", ch);    // Back to print     }      }

3.3. Receive data functions:

// REDIRECT scanf function to USART1 int fgetc (FILE *f) {        /* waits for serial 1 input data *         /while (Usart_ Getflagstatus (USART1, usart_flag_rxne) = = RESET)        ; return (int) usart_receivedata (USART1);}

4, STM32 serial port when the first character is sent, the first character lost solution

The code for sending characters online is mostly as follows:

Usart_senddata (USART1, (uint8_t) ch);
while (Usart_getflagstatus (USART1, USART_FLAG_TC)! = SET);

In fact, I look at the point of view, but in the careful reading of the manual found that the TC and TXE flag bit in the reset time is set 1, so that the first while loop is useless. This led to the first character has not been output, the following characters are overwritten, resulting in the actual loss of seeing. The solution is simple: Add a usart1->sr; to the front

The specific code is as follows:

usart1->sr;
Usart_senddata (USART1, (uint8_t) ch);
while (Usart_getflagstatus (USART1, USART_FLAG_TC)! = SET);

Let me say the reason: the first sentence reads the SR register, the second sentence writes the Dr Register just clears the TC flag bit. The first while loop works.

Usart1->sr; can also be replaced with Usart_getflagstatus (USART1, USART_FLAG_TC)

All procedures of this experiment, "STM32 serial port USART1 Query and Interrupt mode program"

Add: There has always been a question about accepting and sending data: For a string such as "Hello" is an acceptance or an entire acceptance display, the following experiment can be verified to be one-to-one.

[end] selected from: http://www.ciast.net/post/2015119.html

STM32 Serial port USART1 use method and procedure

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.