stm32 application-simple serial port receiving and sending program

Publisher:WanderlustGlowLatest update time:2015-11-18 Source: eefocusKeywords:stm32 Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere
Serial communication with the host computer is a very common program. The first simple program that I wrote when I first came into contact with the stm32 chip was serial communication. Now I will share the program code with you. The complete program~ I won't tell ordinary people

 Library version  : ST3.0.0

File: main.c

//Function: Initialize the serial port, turn on the timer interrupt, and then keep receiving data. Sending is implemented in the interrupt

#include "stm32f10x.h"
#include "usart.h"

u8 USART_rx_data;
int main(void)
{
  
  RCC_Configuration();      //System clock configuration
  GPIO_Configuration();      //Port initialization
  NVIC_Configuration();      //Interrupt source configuration
  USART_Configuration();     //Serial port 1 initialization
  Time_Init();            //Timer initialization
  #ifdef DEBUG
      debug();
  #endif
  TIM_Cmd(TIM3,ENABLE); 
  while(1)
  {

   }

}

 

 

File: usart.c

#include "stm32f10x.h"
#include "stdio.h"
#include "usart.h"
  unsigned char auchCRCHi [256] ={
  0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,
  0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,
  0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,
  0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,
  0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,
  0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,
  0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,
  0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,
  0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,
  0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,
  0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,
  0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,
  0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,
  0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,
  0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,
  0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40};
  unsigned char auchCRCLo [256] ={
  0x00,0xC0,0xC1,0x01,0xC3,0x03,0x02,0xC2,0xC6,0x06,0x07,0xC7,0x05,0xC5,0xC4,0x04,
  0xCC,0x0C,0x0D,0xCD,0x0F,0xCF,0xCE,0x0E,0x0A,0xCA,0xCB,0x0B,0xC9,0x09,0x08,0xC8,
  0xD8,0x18,0x19,0xD9,0x1B,0xDB,0xDA,0x1A,0x1E,0xDE,0xDF,0x1F,0xDD,0x1D,0x1C,0xDC,
  0x14,0xD4,0xD5,0x15,0xD7,0x17,0x16,0xD6,0xD2,0x12,0x13,0xD3,0x11,0xD1,0xD0,0x10,
  0xF0,0x30,0x31,0xF1,0x33,0xF3,0xF2,0x32,0x36,0xF6,0xF7,0x37,0xF5,0x35,0x34,0xF4,
  0x3C,0xFC,0xFD,0x3D,0xFF,0x3F,0x3E,0xFE,0xFA,0x3A,0x3B,0xFB,0x39,0xF9,0xF8,0x38,
  0x28,0xE8,0xE9,0x29,0xEB,0x2B,0x2A,0xEA,0xEE,0x2E,0x2F,0xEF,0x2D,0xED,0xEC,0x2C,
  0xE4,0x24,0x25,0xE5,0x27,0xE7,0xE6,0x26,0x22,0xE2,0xE3,0x23,0xE1,0x21,0x20,0xE0,
  0xA0,0x60,0x61,0xA1,0x63,0xA3,0xA2,0x62,0x66,0xA6,0xA7,0x67,0xA5,0x65,0x64,0xA4,
  0x6C,0xAC,0xAD,0x6D,0xAF,0x6F,0x6E,0xAE,0xAA,0x6A,0x6B,0xAB,0x69,0xA9,0xA8,0x68,
  0x78,0xB8,0xB9,0x79,0xBB,0x7B,0x7A,0xBA,0xBE,0x7E,0x7F,0xBF,0x7D,0xBD,0xBC,0x7C,
  0xB4,0x74,0x75,0xB5,0x77,0xB7,0xB6,0x76,0x72,0xB2,0xB3,0x73,0xB1,0x71,0x70,0xB0,
  0x50,0x90,0x91,0x51,0x93,0x53,0x52,0x92,0x96,0x56,0x57,0x97,0x55,0x95,0x94,0x54,
  0x9C,0x5C,0x5D,0x9D,0x5F,0x9F,0x9E,0x5E,0x5A,0x9A,0x9B,0x5B,0x99,0x59,0x58,0x98,
  0x88,0x48,0x49,0x89,0x4B,0x8B,0x8A,0x4A,0x4E,0x8E,0x8F,0x4F,0x8D,0x4D,0x4C,0x8C,
  0x44,0x84,0x85,0x45,0x87,0x47,0x46,0x86,0x82,0x42,0x43,0x83,0x41,0x81,0x80,0x40};


unsigned short CRC16(unsigned char* puchMsg, unsigned short usDataLen)
{


  unsigned char uchCRCHi = 0xFF ;
  unsigned char uchCRCLo = 0xFF ;
  unsigned char uIndex ;
  while (usDataLen--)
  {
    uIndex = uchCRCHi^*puchMsg++;
    uchCRCHi = uchCRCLo^auchCRCHi[uIndex];
    uchCRCLo = auchCRCLo[uIndex];
  }
  return (uchCRCHi << 8 | uchCRCLo) ;
}


void RCC_Configuration(void)
{
 ErrorStatus HSEStartUpStatus;       //Enumeration variable, define the start status of high-speed clock
 RCC_DeInit();                   //RCC system reset, for Debug purpose
 RCC_HSEConfig(RCC_HSE_ON);                 //Enable high-speed clock source HSE   
 HSEStartUpStatus = RCC_WaitForHSEStartUp();    //Wait for HSE to stabilize
 if(HSEStartUpStatus == SUCCESS)
 {
   FLASH_SetLatency(FLASH_Latency_2);      
 FLASH_PrefetchBufferCmd(FLASH_PrefetchBuffer_Enable);      
   
   RCC_HCLKConfig(RCC_SYSCLK_Div1);         // HCLK = SYSCLK
   RCC_PCLK2Config(RCC_HCLK_Div1);          // PCLK2 = HCLK
   RCC_PCLK1Config(RCC_HCLK_Div2);         ///PCLK1 = HCLK/2
 
   RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9);
   RCC_PLLCmd(ENABLE);
   while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET){}

   
   RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
   while(RCC_GetSYSCLKSource() != 0x08){}
 }
 RCC_APB2PeriphClockCmd( RCC_APB2Periph_USART1 |RCC_APB2Periph_GPIOA |RCC_APB2Periph_AFIO |RCC_APB2Periph_GPIOB , ENABLE);
 RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
}
//------------------------------------------------------------------
//Function name: void GPIO_Configuration()
//Input parameter: null
//Return parameter: null
//Description: GPIO initialization function
//------------------------------------------------------------------
void GPIO_Configuration(void)
{
 GPIO_InitTypeDef GPIO_InitStructure;      //GPIO initialization structure declaration
 
 
 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;          //USART1 TX
 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;    //Multiplexed push-pull output
 GPIO_InitStructure.GPIO_Speed ​​= GPIO_Speed_50MHz;   
 GPIO_Init(GPIOA, &GPIO_InitStructure);      //A port
 
 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;          //USART1 RX
 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;   //Multiplexed floating input
 GPIO_Init(GPIOA, &GPIO_InitStructure);           //A port

 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6; 
 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;  
 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
 GPIO_Init(GPIOB, &GPIO_InitStructure);
}

//------------------------------------------------------------------
//Function name: void NVIC_Configuration()
//Input parameter: null
//Return parameter: null
//Description: NVIC initialization function
//------------------------------------------------------------------
void NVIC_Configuration(void)
             
 NVIC_InitTypeDef NVIC_InitStructure;       //NVIC initialization structure declaration
 
 #ifdef VECT_TAB_RAM        
   
   NVIC_SetVectorTable(NVIC_VectTab_RAM, 0x0); //If the program is debugged in RAM, then define the interrupt vector table in RAM, otherwise in Flash
 #else 
   
   NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x0);   
 #endif

   
  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);

  
 NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;          //Set serial port 1 interrupt
 NVIC_InitStructure.NVIC_IRQChannelPreemptionPrio rity = 0;         //Preempt priority 0
 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;     //Sub priority is 0
 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;      //Enable
 NVIC_Init(&NVIC_InitStructure);

 NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;           //Set timer 3 global interrupt
 NVIC_InitStructure.NVIC_IRQChannelPreemptionPrio rity = 1;        //Preempt priority 1
 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;            //Sub priority is 0
 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;           //Enable
 NVIC_Init(&NVIC_InitStructure);
}
//------------------------------------------------------------------
//Function name: void USART_Configuration()
//Input parameter: null
//Return parameter: null
//Description: Serial port initialization function
//------------------------------------------------------------------
void USART_Configuration(void){
 USART_InitTypeDef USART_InitStructure;                   //Serial port initialization structure declaration
 USART_ClockInitTypeDef USART_ClockInitStruct;
 USART_InitStructure.USART_BaudRate = 115200;       //Set the baud rate to 115200bps
 USART_InitStructure.USART_WordLength = USART_WordLength_8b;   //Data bits 8 bits
 USART_InitStructure.USART_StopBits = USART_StopBits_1;    //Stop bit 1 bit
 USART_InitStructure.USART_Parity = USART_Parity_No;     //No parity bit
 USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;   //No hardware flow control
 USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;      //Both receive and transmit modes are turned on

 USART_ClockInitStruct.USART_Clock=USART_Clock_Disable;      //Serial port clock disabled
 USART_ClockInitStruct.USART_CPOL=USART_CPOL_Low;        //Data low level is valid
 USART_ClockInitStruct.USART_CPHA=USART_CPHA_2Edge;     //Configure CPHA so that data is captured at the second edge
 USART_ClockInitStruct.USART_LastBit=USART_LastBit_Disable;   // Disable the last bit so that the corresponding clock pulse will no longer be output to the SCLK pin
 USART_ClockInit(USART1, &USART_ClockInitStruct);       //Configure USART clock-related settings

 USART_Init(USART1, &USART_InitStructure);        //Configure serial port parameters function

 USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);       //Enable receive interrupt
//USART_ITConfig(USART1, USART_IT_TXE, ENABLE);     //Enable transmit buffer empty interrupt
//USART_ITConfig(USART1, USART_IT_TC, ENABLE);     //Enable transmit complete interrupt
 USART_ClearFlag(USART1,USART_FLAG_TC);         //Clear transmit complete flag
 USART_Cmd(USART1, ENABLE);          //Enable serial port 1
}[page]
//------------------------------------------------------------------
//Function name: void Time_Init()
//Input parameter: null
//Return parameter: null
//Description: Timer initialization function
//------------------------------------------------------------------
void Time_Init(void)
{
 TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;

 TIM_DeInit(TIM3);             //Reset TIM3
 timerTIM_TimeBaseStructure.TIM_Period = 7999;           //Set auto-reload register latch value, 1ms overflowTIM_TimeBaseStructure.TIM_Prescaler       
 = 8;       //9 divisionTIM_TimeBaseStructure.TIM_ClockDivision 
 = 0x0;       //Clock division            
 factorTIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;  //Counter up counting                      
  
 modeTIM_TimeBaseInit(TIM3,&TIM_TimeBaseStructure);     //Write TIM3 register parameters

  TIM_ClearFlag(TIM3,TIM_FLAG_Update);

  TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE);

}

 

 

File: usart.h

#ifndef _USART_H
#define _USART_H

#include
#include "stm32f10x.h"


void RCC_Configuration(void);   //Declare RCC initialization function
void GPIO_Configuration(void);   //Declare GPIO initialization function
void NVIC_Configuration(void);   //Declare NVIC initialization function
void USART_Configuration(void);   //Declare serial port initialization function
void Time_Init(void);     //Declare timer initialization function
unsigned short CRC16(unsigned char* puchMsg, unsigned short usDataLen);

 

#endif

 

 

File: stm32f103x_it.c

//You need to set the serial port receiving interrupt and timer 3 interrupt, the interrupt time is 1ms

//------------------------------------------------------------------
//Function name: void USART1_IRQHandler(void)
//Input parameter: null
//Return parameter: null
//Description: Serial port receive interrupt service
//------------------------------------------------------------------
void USART1_IRQHandler(void)
{
  
  if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)          //Judge whether the read register is not empty
       
//     GPIO_SetBits(GPIOB,GPIO_Pin_6);
    rx_data[RbufCounter++]=USART_ReceiveData(USART1);   //Receive bytes to receive buffer
    if(USART_Rsv_Status==0)
    ​​{
      if(RbufCounter>1)
      {
        if(rx_data[0]==0xA5&&rx_data[1]==0x5A)    //When the first two bytes of the received data frame are 0xA5 and 0x5A at the same time
        {
          USART_Rsv_Status=1;
//            USART_SendData(USART1, rx_data[0]);
        }
        else
        {
          rx_data[0]=rx_data[1];
          RbufCounter=1;
         
        }
      }
    }
    else
    {
      USART_1ms_Cnt=0;
                  
          
}
//------------------------------------------------------------------
//Function name: void TIM2_IRQHandler(void)
//Input parameter: null
//Return parameter: null
//Description: Timer 2 interrupt service
//------------------------------------------------------------------
void TIM2_IRQHandler(void)
{

 

}
//------------------------------------------------------------------
//Function name: void TIM3_IRQHandler(void)
//Input parameter: null
//Return parameter: null
//Description: Timer 3 interrupt service
//------------------------------------------------------------------
void TIM3_IRQHandler(void)

  if(TIM_GetITStatus(TIM3,TIM_IT_Update)!=RESET)        //Judge whether it is timer 3 overflow interrupt
  {
    
    GPIO_SetBits(GPIOB,GPIO_Pin_6);
    TIM_ClearITPendingBit(TIM3, TIM_IT_Update);   //Clear interrupt flag

    if(USART_Rsv_Status==1)
    USART_1ms_Cnt++;
    if(USART_1ms_Cnt>5)      
    {
//       USART_SendData(USART1,0xAA);
      USART_Rsv_Status=0;      //If the continuous count exceeds 5 times, set USART_Rsv_Status to 0 and continue to wait for reception
      USART_1ms_Cnt=0;         //When USART_1ms_Cnt>5, clear USART_1ms_Cnt 
      if(RbufCounter==(u16)rx_data[4]+7)              //Check data integrity
      {
        int i;     //Define loop variable
        int j;
        data_length=rx_data[4];
        for(i=0;i
        {
          data[i]=rx_data[i];
        
        CRC_data_Hi=rx_data[RbufCounter-1];
        CRC_data_Lo=rx_data[RbufCounter-2];
        CRC_data=CRC16((unsigned char*)data,data_length+5);
        CRC_data_Hi1=CRC_data>>8;
        CRC_data_Lo1=CRC_data&0x00ff;
         if(CRC_data_Hi==(u8)CRC_data_Hi1 && CRC_data_Lo==CRC_data_Lo1)
         {
           for(j=0;rx_data[j]!='';j++)   //Loop and output word by word until the end word ''
                 
             USART_SendData(USART1, rx_data[j]);     //Send characters
             while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET)
             {
             } //Wait for the characters to be sent
           }
        }
      }
      RbufCounter=0;
        
  }
}


Keywords:stm32 Reference address:stm32 application-simple serial port receiving and sending program

Previous article:STM32 serial communication
Next article:STM32 drives TFT display ILI9325

Recommended ReadingLatest update time:2024-11-16 15:35

STC12C5A60S2 uses NRF24L01 and stm32 to communicate
/******************************************/ // // The main frequency of this program is 12MHz, and the microcontroller uses STC12C5A60S2 // /******************************************/ #include "STC12C5A60S2.H" #define uchar unsigned char #define uint  unsigned int /********** NRF24L01 register operation comman
[Microcontroller]
stm32 basic experiment 2 (key input-query mode)
1. Experimental Principle 1. Implementation steps  (1) Enable the IO port clock corresponding to the button. Call function: RCC_APB2PeriphClockCmd();  (2) Initialize IO mode: pull-up/pull-down input. Call function: GPIO_Init();  (3) Scan the IO port level (library function/register/bit operation).  Three way
[Microcontroller]
stm32 basic experiment 2 (key input-query mode)
STM32 SPI master routine
#include "stm32f10x.h" /*RCC clock configuration*/ void RCC_config(void) {  ErrorStatus HSEStartUpStatus; /* RCC registers are set to default configuration */ RCC_DeInit(); /* Turn on external high speed clock */ RCC_HSEConfig(RCC_HSE_ON); /* Wait for the external high-speed clock to stabilize*/ HSEStartUpStatus
[Microcontroller]
STM32 MCU (8) Program encryption
References http://www.cnblogs.com/pied/archive/2011/06/08/2075481.html http://v.pps.tv/play_38DQ4J.html#vfrm=8-8-0-1 related articles Serial port interrupt communication  http://blog.csdn.net/leytton/article/details/38393553 Serial communication printf redirection  http://blog.csdn.net/leytton/article/details/3839
[Microcontroller]
STM32 UART4 UART5
Today, when debugging the serial port program (STM32107RC), I found that UART4 was clearly configured and could send, but it could not interrupt the reception. I saw many people on the Internet had this question. I finally solved it tonight and wrote a blog by the way. I hope it can help the next person who encounters
[Microcontroller]
Detailed explanation of STM32 clock system and clock startup sequence
Conceptual basis: The STM32 clock system is basically the same, with slight differences between different series. This document mainly introduces the clock system of STM32F446. 1. Clock Tree Overview Why not use a system clock? For example,  STM32 is very complex and has many peripherals, but not all peripherals req
[Microcontroller]
Detailed explanation of STM32 clock system and clock startup sequence
Definition of STM32 CPU ID, Unique ID, Flash size register
Note that CPU ID and Unique ID have different definitions for ST. The CPU ID is built-in to CortexM3, and the reset value is consistent. There are definitions in PM0056.pdf. Unique ID is a different ID for each chip, which is defined in RM0008.PDF. For example, F103 is defined in Section 30.2. Flash size register is
[Microcontroller]
STM32's strip fingerprint collection and splicing system
Introduction As a technology with high reliability, convenience and cost-effectiveness in biometric authentication, fingerprint recognition has been widely used. Fingerprint acquisition is an important component of fingerprint recognition, and its core hardware is the fingerprint sensor. As the size of mobile em
[Microcontroller]
STM32's strip fingerprint collection and splicing 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号