STM32 serial communication sending and receiving

Publisher:JoyfulSunflowerLatest update time:2017-11-28 Source: eefocusKeywords:STM32 Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

There are pros and cons to using STM32. There are many types --- but there are too many types, and the information is also messy. In addition, when calling the library, I often forget to use some functions ------ such as the most commonly used serial port ------


-------------------------------------------------------------------------------USART ----Setup-------------------------------

void USART1_Config(void)
{
        GPIO_InitTypeDef GPIO_InitStructure;
        USART_InitTypeDef USART_InitStructure;

        RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE); //USART1--clock--corresponding--GPIO--clock on
 

 //USART1 Tx---GPIO----PA.09----Multiplexed push-pull output
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
        GPIO_InitStructure.GPIO_Speed ​​= GPIO_Speed_50MHz;
        GPIO_Init(GPIOA, &GPIO_InitStructure);

 //USART1 Rx---GPIO----PA.10----Floating input
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
        GPIO_Init(GPIOA, &GPIO_InitStructure);

 //USART1 mode configuration
        USART_InitStructure.USART_BaudRate = 115200; //Baud rateUSART_InitStructure.USART_WordLength
        = USART_WordLength_8b; //Word length of serial transmissionUSART_InitStructure.USART_StopBits =
        USART_StopBits_1; //Stop
        bitUSART_InitStructure.USART_Parity = USART_Parity_No ; //Parity bitUSART_InitStructure.USART_HardwareFlowControl
        = USART_HardwareFlowControl_None; //Hardware flow controlUSART_InitStructure.USART_Mode
        = USART_Mode_Rx | USART_Mode_Tx; //Serial port mode --- receive --- sendUSART_Init
        (USART1, &USART_InitStructure); 

        USART_ClearFlag(USART1,USART_FLAG_TC); //Clear serial port 1 send interrupt, otherwise the first number will not occur

        USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); //Receive interrupt enable - usually used when an array is needed to save the received data in an interrupt

        USART_Cmd(USART1, ENABLE);//使能USART1
}

-----------------------------------------/Redirect C library function ----printf---- to USART1-----------------------------------


int fputc(int ch, FILE *f)
{
        USART_SendData(USART1, (uint8_t) ch); //Send one byte of data to USART1 
        while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET); //Wait for sending to complete

        return (ch);
}

-----------------------------------------/Redirect C library function ----scanf------ to USART1-----------------------
int fgetc(FILE *f)
{
        while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET); //Wait for serial port 1 to input data 
        return (int)USART_ReceiveData(USART1);
}

------The above two redirections----are to correspond the original C library functions to the current hardware---------

------We can also write similar functions ourselves--------Use the basic two functions----Send---USART_SendData()-----Receive------USART_ReceiveData()---

-----------------************************************************-------for example--------%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%-----

void MyPrintfByte(unsigned char byte) //Serial port sends a byte
{
        USART_SendData(USART1, byte); //Send data through library function
        while( USART_GetFlagStatus(USART1,USART_FLAG_TC)!= SET); //Wait for sending to complete, check if USART_FLAG_TC is set to 1       
}

---------------------------------------------
void MyPrintfStr(unsigned char *s) //Send string function--pointer--
{
        uint8_t i=0; //Define a local variable to send string++operationwhile

        (s[i]!='\0') //Each string ends with \0
        {
                USART_SendData(USART1,s[i]); //Send data through library functionwhile
                ( USART_GetFlagStatus(USART1,USART_FLAG_TC)!= SET); //Wait for sending to complete, check whether USART_FLAG_TC is set to 1
                 i++; //i++ once
        }
}

--------------------------------------------------
void MyPrintfArray(uint8_t send_array[],uint8_t num) //Two parameters, one is the array content, the other is the array length 1-255 
{
        uint8_t i=0; //Define a local variable to send the string++operationwhile

         (i        {
          USART_SendData(USART1,send_array[i]); //Send data through library functionwhile
         ( USART_GetFlagStatus(USART1,USART_FLAG_TC)!= SET); //Wait for sending to complete, check if USART_FLAG_TC is set to 1
          i++; //Add one         
        }        
}



-----------------------------------------An array needs to be defined in the main function-----to save the data received during the receive interrupt--------------------

uint8_t RS232_RX_BUF[24]; //array
uint8_t RS232_RX_CNT=0; //array real-time subscript

--------------------------When the time comes, directly judge or use the corresponding bit data in this array----------------------------------------


-----------------------------------------Interrupt--------Receive interrupt--------------------

----First declare that the receiving array is defined in the main function-----external variables----------------Pay special attention to the fact that values ​​cannot be assigned when declaring external variables-------------

extern uint8_t RS232_RX_BUF[24];
extern uint8_t RS232_RX_CNT;

-------------------------------------------Interrupt function---------------------------

void USART1_IRQHandler(void) 
{
        uint8_t res;         
        if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) //Received data  
        {        
                res =USART_ReceiveData(USART1); //Read received data   
               RS232_RX_BUF[RS232_RX_CNT]=res; //Record received value 
   

   //USART_SendData(USART1, res);//Send data----echo

                RS232_RX_CNT++; //Receive data increases by 1  
                if( RS232_RX_CNT>23)
                        RS232_RX_CNT=0;    
        }
        if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) 
        { 
                 USART_ClearITPendingBit(USART1, USART_IT_RXNE);//Clear the receive flag------need to be cleared each time the receive is completed
        }

}

----------------------------------------------------------Configure interrupt priority------------------------

static void NVIC_Configuration(void)
{
        NVIC_InitTypeDef NVIC_InitStructure;
  
        NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);//interrupt group
  
        NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;//interrupt source
        NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;//preemption priority
        NVIC_InitStructure.NVIC_IRQChannelSubPriority = ENABLE;
        NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;//enable
        NVIC_Init(&NVIC_InitStructure);
}

---------------------------------------------------------------Configuration call in main function--------------------------

  

  USART1_Config(); //Serial port 1 is used to output debug information
  NVIC_Configuration();

-----------------------------------------------------------

 printf("The received data is %d \r\n",temp); 


【--------------------------------------------Final Summary------------------------------------------------】

1.GPIO and clock settings

2. Mode configuration selection -------Note to enable interrupt-----USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);

3. Writing interrupt functions

4. Setting interrupt priority

5. Main function call


------------------------------------------------------------------485 communication---same as ------------------


Keywords:STM32 Reference address:STM32 serial communication sending and receiving

Previous article:STM32 485 communication self-study summary
Next article:LPC1788--SSP setting driver W25Q16--and special attention points

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号