5.USART asynchronous serial port input/output (polling mode)

Source: Internet
Author: User

Learning is a simple process, as long as there are good to explore the eyes, always learn new knowledge, but how to persevere in learning is very difficult, for me, there are too many temptations in life, and finally only want to say a word do not forget beginner's mind. Gossip not much, this article is about the asynchronous serial port input and output, the serial port in the peripheral is a relatively simple communication mode, but in large-scale project debugging is also very important, understand the peripheral module for future communication protocol learning and software debugging is of great significance.

Communication protocol refers to the two entities to complete the communication or service must follow the rules and conventions, for the serial port, including the baud rate, data bit length, stop bit and data check bit, when the STM32 chip and the client has the same protocol agreement is able to correctly receive data, so the configuration of the serial port peripherals is the setting of these parameters. Using the previous chapters, for example, we should have a rough flow before peripheral settings USART1:

1. The serial peripheral peripherals and the GPIO ports they occupy are configured, and the Gpio port used is PA9 (USART1_TX), PA10 (USART1_RX).

2. The peripheral clock must be configured, and before initializing the peripheral and Gpio port configuration

3. Usart peripheral configuration is mainly protocol-related parameter configuration

Serial Peripheral Configuration

For the parameter reference of the GPIO port configuration <stm32f Series microcontroller reference manual > (hereafter referred to as manual) 110 page Table 21

For the peripheral clock area, refer to the RCC section so that the peripheral is initialized as follows:

Header file Definition:

#define Rcc_usart1           Rcc_apb2periph_gpioa                                   |  Rcc_apb2periph_usart1                                 | Rcc_apb2periph_afio #define USART1_RX            Gpioa#define usart1_tx            gpioa#define usart1_rx_pin     gpio_pin_10 #define Usart1_tx_pin        Gpio_pin_9

Initialization code:

Usart_inittypedef usart_initstructure;  Gpio_inittypedef gpio_initstructure;      Usart_deinit (USART1);                  Rcc_apb2periphclockcmd (Rcc_usart1, ENABLE); Gpio_initstructure.gpio_pin=Usart1_tx_pin; Gpio_initstructure.gpio_speed=Gpio_speed_50mhz; Gpio_initstructure.gpio_mode= GPIO_MODE_AF_PP;//Configuring the serial port 1 output for multiplexed push-pull outputGpio_init (usart1_tx,&gpio_initstructure); Gpio_initstructure.gpio_pin=Usart1_rx_pin; Gpio_initstructure.gpio_mode= gpio_mode_in_floating;//Configuring the serial port 1 input as a floating-space inputGpio_init (USART1_RX, &gpio_initstructure); Usart_initstructure.usart_baudrate=115200;//set the serial port baud rate to 9600Usart_initstructure.usart_wordlength = usart_wordlength_8b;//Input/output 8-bit data bitsUsart_initstructure.usart_stopbits = Usart_stopbits_1;//set stop bit to 1 bitsusart_initstructure.usart_parity = Usart_parity_no;//do not perform parity checksUsart_initstructure.usart_hardwareflowcontrol = Usart_hardwareflowcontrol_none;//No hardware flow control is usedUsart_initstructure.usart_mode = Usart_mode_rx | Usart_mode_tx;//serial 1 Start-up input/outputUsart_init (USART1,&usart_initstructure);                                             Usart_cmd (USART1, ENABLE); //Enable serial port

This completes the initialization of the peripheral.

Here are a few points of knowledge to say:

1. Baud rate The number of bits sent per second. For a certain length of data, the transfer time is calculated in the case of a known configuration:

(with 2k data B, 8 bits per frame, 1 bit stop bit, baud rate 9600, time spent on transfer completion)

T = 2*1024* (8+1)/9600*8 = 0.24s

Although the baud rate can be set directly with the library function, it is important to calculate the baud rate of the stm32 via the register, and the reference formula is configured USART->BRR (manual page 542):   


Where FCK is the serial port area peripheral clock, such as Usart is the PCLK2 clock, Usartdiv is to set the parameters:

The baud rate 115200,pclk equals the system clock Systick (48MHZ), Usartdiv is set to 48m/(16*115200), and turns into binary 0x1a0

2. Parity bit

Because of the parity bit participation, the received data frame has the following four formats:

Therefore, the client receives the data bit to be set to the actual data length, otherwise the received data will be garbled.

3. Hardware flow Control

For data flow control, the two sides of the communication will continue to receive information after the exchange is stopped, to avoid the cache overflow caused by processing the data speed problem, resulting in the loss of data .

CTS : data can only be sent if the CTS input signal is valid (low level). If the CTS signal becomes invalid during data transmission, the transmission stops after the data is sent out. If the CTS is invalid and the data is written to the data register, the data will not be sent until the CTS is valid.

RTS : Requests the next data only if there is free space in the receive buffer. After the current data is sent, the send operation needs to be paused. If the data can be received, the RTS output is set to active (pull to low level).

PS: Not used in this example, refer to manual page 537 for specific details

Serial input and output implementation

The output of the serial port is through the printf function, which is contained inside the stdio.h header file. In addition printf needs retarget processing, the specific code is as follows:

Retarget.h header file added:

  #ifdef __gnuc__  /*  with gcc/raisonance, small printf (option LD linker->libraries- >small printf     *  /#define putchar_prototype int __io_putchar (int ch)  # else  #define putchar_prototype int fputc (int ch, FILE *f)  #endif /* __gnuc__ */

retarget.c file Add:

putchar_prototype{  /**  /Usart_senddata (USART1, (uint8_t) ch        ); /* wait for transmission to end */   while (Usart_getflagstatus (USART1, usart_flag_tc) = = RESET)  {}          return  ch;}

After that, you can send the data with the printf function, and the receive uses the cached mode, stores the accepted data in the array, and receives \ n when it ends and sends:

U8 i =0; Do{                    while(Usart_getflagstatus (USART1, usart_flag_rxne) = =RESET) {} Usart_store[i]= usart1->DR; if(Usart_store[i] = ='\ n')   {       Break; } I++; if(I >=USART_ISL) {i=0; printf ("You input is Overlength");  Break; } } while(1); if(I <USART_ISL) {    //printf ("You are input is");printf"\n%s", Usart_store); }

This completes the configuration of the Usart peripheral and the input-output polling implementation.

Specific code reference: http://files.cnblogs.com/files/zc110747/2.1-USART%28%E8%BD%AE%E8%AF%A2%E6%A8%A1%E5%BC%8F%29.7z

5.USART asynchronous serial port input/output (polling mode)

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.