STM32F10X Getting Started Guide 2 --- water lamp (Elementary)

Source: Internet
Author: User

How to Use STM32 to light up a streaming light? To put it bluntly, I/O Ports of STM32 are also used to generate high and low level changes. Next, let's briefly introduce the I/O port of STM32.


Introduction to STM32 I/O Ports

Different from the traditional 51 single-chip microcomputer, most of the traditional 51 Single-Chip Microcomputer outputs only two input and output methods, while the input and output methods of STM32 include input float, input pull, input drop-down, analog Input, out-of-the-box output, push-pull output, push-pull multiplexing, and out-of-the-box multiplexing. The speed of each output mode can also be set to 10 MHz and 2 MHz, 50 MHz. For more information, see the 105 page of The STM32 Data Manual.

In addition, STM32 also has a unique design, that is, each module (such as the IO port, I2C, SPI, USART and Other interfaces) has its own clock. To operate these modules, you must first turn on the clock of these modules. Otherwise, the operation is invalid. The official explanation for this design is that, as the core of CM3, STM32 is a speed advantage, and power consumption is also an advantage. STM32F10X is positioned in the low-end market and focuses on low power consumption. When some modules do not need to be used, shutting down their clock will save more power.

Speaking of this, we may have a little bit of knowledge about the STM32F10X product. Put down STM32 first. Let's take a look at keil mdk.

First, create a new project and select your own chip. You can add a file main. cpp first.In the future, all our self-compiled files will be suffixed with CPP, so that many features of C ++ can be used.

What does the compiler do for us when we select a chip?

Create a main. cpp file and add it to the project. The chip used by Qifan is STM32F103C8, which is selected when the project is created. Add the following code to the main function:

#ifdef STM32F10X_MD#error "User Error:Stm32f10x_Md"#endif#ifdef STM32F10X_HD#error "User Error: stm32f10x_Hd"#endifint main(){}
Click compile to see if the compiler will give the following warning:

.. \ Source \ main. cpp (3): error: #35: # error direve ve: "User Error: Stm32f10x_Md"

# Error "User Error: Stm32f10x_Md"

What does this mean? Let's look at our code. That is to say, if the macro STM32F10X_MD is defined, let the Compiler

An error is prompted. The error content is enclosed in quotation marks. Be sure to note that Qifan's chip is STM32F103C8.

You can also click Project-> Select device for target. Here, STM32F103VC,

After compilation, the compiler will find the following error:

.. \ Source \ main. cpp (7 ):

Error: #35: # error directive: "User Error: stm32f10x_Hd"
.. \ Source \ main. cpp: Error: stm32f10x_Hd"

What are the two errors described above? That is to say, when we select the chip model, the compiler only defines a macro for us,

This macro is followed by two letters representing the chip capacity. These macros are used in many libraries officially provided by STM. For example:

#if !defined (STM32F10X_LD) && !defined (STM32F10X_LD_VL) && !defined (STM32F10X_MD) && !defined (STM32F10X_MD_VL) && !defined (STM32F10X_HD) && !defined (STM32F10X_HD_VL) && !defined (STM32F10X_XL) && !defined (STM32F10X_CL) #error "Please select first the target STM32F10x device used in your application (in stm32f10x.h file)"#endif

Based on the capacity, the stm library defines different content:

typedef struct{  __IO uint32_t CR;  __IO uint32_t SWTRIGR;  __IO uint32_t DHR12R1;  __IO uint32_t DHR12L1;  __IO uint32_t DHR8R1;  __IO uint32_t DHR12R2;  __IO uint32_t DHR12L2;  __IO uint32_t DHR8R2;  __IO uint32_t DHR12RD;  __IO uint32_t DHR12LD;  __IO uint32_t DHR8RD;  __IO uint32_t DOR1;  __IO uint32_t DOR2;#if defined (STM32F10X_LD_VL) || defined (STM32F10X_MD_VL) || defined (STM32F10X_HD_VL)  __IO uint32_t SR;#endif} DAC_TypeDef;
This is a DAC register. We can see that some chips have SR registers and some chips do not.

STM official notes on these capacities:

/*  Tip: To avoid modifying this file each time you need to switch between these        devices, you can define the device in your toolchain compiler preprocessor. - Low-density devices are STM32F101xx, STM32F102xx and STM32F103xx microcontrollers   where the Flash memory density ranges between 16 and 32 Kbytes. - Low-density value line devices are STM32F100xx microcontrollers where the Flash   memory density ranges between 16 and 32 Kbytes. - Medium-density devices are STM32F101xx, STM32F102xx and STM32F103xx microcontrollers   where the Flash memory density ranges between 64 and 128 Kbytes. - Medium-density value line devices are STM32F100xx microcontrollers where the    Flash memory density ranges between 64 and 128 Kbytes.    - High-density devices are STM32F101xx and STM32F103xx microcontrollers where   the Flash memory density ranges between 256 and 512 Kbytes. - High-density value line devices are STM32F100xx microcontrollers where the    Flash memory density ranges between 256 and 512 Kbytes.    - XL-density devices are STM32F101xx and STM32F103xx microcontrollers where   the Flash memory density ranges between 512 and 1024 Kbytes. - Connectivity line devices are STM32F105xx and STM32F107xx microcontrollers.  */

Here, I think it is wrong to define a macro STM32F10X_HD in some tutorials. That is to say, you do not need to define this macro. This macro is automatically defined when you select a chip.


Add Lib

When we see this, we will actually write our water lamp below.

First, copy core_cm3.c, startup_stm32f10x_hd.s, stm32f10x_rcc.c, and system_stm32f10x.c in the library file to the Core-> Source in the created folder,

Copy the corresponding header file to the core-> Include folder of the created folder. Modify the path of the header file to include Core-> include.

Note: The startup_stm32f10x_hd.s should be selected based on the actual chip. If you use STM32F103C8, select startup_stm32f10x_md.s,

If it is STM32F103VC, select startup_stm32f10x_hd.s.

Note: The four files mentioned aboveCore_cm3.c, startup_stm32f10x_hd.s, stm32f10x_rcc.c, system_stm32f10x.c

In the future, we must add the project after the project is established. startup_stm32f10x_xx.s requires your own chip to choose from.

These four files can be found in the official library V3.50 of STM.

Double-click Source Group 1 (next to the left) to bring up the Add file dialog box. Add the four files mentioned above and STM32F10X_GPIO.C. As shown in (bottom right:

It is shown that there is a small key on some files because STM sets the file as read-only to prevent accidental changes to the library after completing the library file. If your code is modified later

It does not need to be changed. To prevent exceptions, you should also set it to read-only.


At this point, all the files required for the streaming lamp have been added. Write the program as follows:

Coding

#include"Stm32f10x_rcc.h"#include"Stm32f10x_gpio.h"int main(){RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC,ENABLE);//open gpioc clock//config all pinsGPIO_InitTypeDef init;init.GPIO_Mode=GPIO_Mode_Out_PP;init.GPIO_Speed=GPIO_Speed_10MHz;init.GPIO_Pin=GPIO_Pin_13;GPIO_Init(GPIOC,&init);while(1){GPIO_SetBits(GPIOC,GPIO_Pin_13);for(int i=0;i<7200000;i++) ;//for delay times,about 1sGPIO_ResetBits(GPIOC,GPIO_Pin_13);for(int i=0;i<7200000;i++) ;//for delay times}}
As we mentioned above, every module has its own clock. To make the module work, you must first turn on its clock (this is required, if the clock is not turned on, the operations on the module are invalid.) Remember this. This is like a TV set in the house. The power supply is the protection of his work. If your power supply is not turned on, how can you change the TV set? Qian Fan didn't notice this at the beginning of his learning, and no one said that he had to turn on the clock first. At that time, I had the illusion that I had to configure the register first and then enable the clock for him to work. This is actually wrong. The correct method is to enable the clock first. Only when the clock is turned on can we operate on its registers.

Build

Compile the following code! So many errors!

1. the header file is incorrect. The system prompts that the header file is not found or the header file cannot be opened;

Solution:

Set include path.

We know that the compiler is processing different header files referenced by <> and. When processing <>, the compiler first looks for it in the installation directory. If no Error is found.

If it is "", search for it in the folder where your Project is located. If it is not found, search for it in the IDE installation directory. If it is not found, the Error will be waited.

When we add an include path, this Include path is also part of the installation directory. You can also use <>, preferably "" (at least "", so that I can see at a glance that this header file is compiled by myself ).

Click Options for taget-> c/c ++-> new-> and then add your own path. As shown in.



2. assert_param (expr) and assert_failed are not defined

We tracked the two codes all the way, and finally found the following code in line 8296 of STM32F10X. h:

#ifdef USE_STDPERIPH_DRIVER  #include "stm32f10x_conf.h"#endif

Open the header file of the include code and you will find that the Code is as follows:

/* Exported types ------------------------------------------------------------*//* Exported constants --------------------------------------------------------*//* Uncomment the line below to expanse the "assert_param" macro in the    Standard Peripheral Library drivers code *//* #define USE_FULL_ASSERT    1 *//* Exported macro ------------------------------------------------------------*/#ifdef  USE_FULL_ASSERT/**  * @brief  The assert_param macro is used for function's parameters check.  * @param  expr: If expr is false, it calls assert_failed function which reports   *         the name of the source file and the source line number of the call   *         that failed. If expr is true, it returns no value.  * @retval None  */  #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__))/* Exported functions ------------------------------------------------------- */  void assert_failed(uint8_t* file, uint32_t line);#else  #define assert_param(expr) ((void)0)#endif /* USE_FULL_ASSERT */

Oh, it turns out that the macro definition in the file Stm32f10x_conf.h is the definition of assert_param (expr). This macro is selected based on the expr expression.

If expr = true, nothing is executed. If expr = false, assert_failed (uint8_t *) _ FILE __, _ LINE _) is called __)). This assert_failed (uint8_t *) _ FILE __, _ LINE _) is a conditional compilation function.

If define USE_FALL_ASSERT, declare a function assert_failed (uint8_t *) _ FILE __, _ LINE _) for you __)), you must implement this function by yourself. Generally, information can be sent through the serial port. For example:

void assert_failed((uint8_t *)__FILE__, __LINE__)){while(1){serial.Write("Error! In File:   ");serial.WriteLine(__FILE__);serial.Print("In Line: %d \n",__LINE__);}}

This serial class is a serial port class, which will be implemented by qianfan in the future blogs. There are two odd parameters: _ LINE __and _ FILE __. If you are not familiar with these two parameters, you need to make up the C language. These two parameters (note that the preceding parameters are followed by two underscores) are proposed in the C99 standard. _ LINE _ indicates the number of lines in the current Code, __file _ indicates the FILE name of the current Code. All ides that support the C99 standard support these two macros.

This assert_param macro is used to check whether the parameters comply with the specifications. General Chinese translation is assertion. The code is mainly reflected in the check parameters, for example:

Void GPIO_Init (GPIO_TypeDef * GPIOx, GPIO_InitTypeDef * GPIO_InitStruct) {uint32_t currentmode = 0x00, currentpin = 0x00, pinpos = 0x00, pos = 0x00; uint32_t tmpreg = 0x00, pinmask = 0x00;/* Check the parameters */assert_param (GPIOx); assert_param (IS_GPIO_MODE (GPIO_InitStruct-> GPIO_Mode )); assert_param (IS_GPIO_PIN (GPIO_InitStruct-> GPIO_Pin);/* -------------------------- GPIO Mode Configuration example */currentmode = (uint32_t) GPIO_InitStruct-> GPIO_Mode) & (uint32_t) 0x0F); if (uint32_t) GPIO_InitStruct-> GPIO_Mode) & (uint32_t) 0x10 ))! = 0x00) {/* Check the parameters * //... please refer to the source code for detailed explanation}
How can we solve this problem? Easy, just define USE_STDPERIPH_DRIVER.

Method: Add a macro to option for taget-> C/C ++-> define, for example:



Now compiled, 0 Error, 0 warning, OK, download! The light blinks. How is it? Is it easy to program using LIB?



Function:

Of course, this library contains more than one function. The declaration of all functions is as follows:

void GPIO_DeInit(GPIO_TypeDef* GPIOx);void GPIO_AFIODeInit(void);void GPIO_Init(GPIO_TypeDef* GPIOx, GPIO_InitTypeDef* GPIO_InitStruct);void GPIO_StructInit(GPIO_InitTypeDef* GPIO_InitStruct);uint8_t GPIO_ReadInputDataBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);uint16_t GPIO_ReadInputData(GPIO_TypeDef* GPIOx);uint8_t GPIO_ReadOutputDataBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);uint16_t GPIO_ReadOutputData(GPIO_TypeDef* GPIOx);void GPIO_SetBits(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);void GPIO_ResetBits(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);void GPIO_WriteBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, BitAction BitVal);void GPIO_Write(GPIO_TypeDef* GPIOx, uint16_t PortVal);void GPIO_PinLockConfig(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);void GPIO_EventOutputConfig(uint8_t GPIO_PortSource, uint8_t GPIO_PinSource);void GPIO_EventOutputCmd(FunctionalState NewState);void GPIO_PinRemapConfig(uint32_t GPIO_Remap, FunctionalState NewState);void GPIO_EXTILineConfig(uint8_t GPIO_PortSource, uint8_t GPIO_PinSource);void GPIO_ETH_MediaInterfaceConfig(uint32_t GPIO_ETH_MediaInterface);

For details about each function, see the help documentation of the Library:


You can easily view the source code, function functions, and parameter meanings. You can find it in the downloaded V3.50 library.


Some people may ask about Download. The Code has been compiled and compiled. But how can I Download my code to STM32? As we mentioned earlier, it would be especially convenient to have a debugger. Especially J-LINK or ST-LINK. The following Qifan takes the ST-LINK as an example to explain how to download the Code; 1. Install the ST-LINK driver. Go to the official website to download the ST-LINK driver, or Baidu ST-LINK driver, choose to install. How to judge that the driver of the ST-LINK has been installed successfully? In this case, you need to open the Device Manager of the Computer (right-click on my computer on the desktop, select the Device Manager in the pop-up menu; or press the win + R shortcut key and enter devmgmt in the running process. msc ). Open the Device Manager and find the item marked in the image in the Universal Serial Bus:

If the marked item is normal, the driver is installed normally. You can use STLINK to burn a program.
2. Set the DEBUG option in the MDK.

First select the ST-LINK Debugger of 1 annotation, and then click Settings of 2 annotation. After clicking 2, the following dialog box is displayed:






First, switch the place marked with 1 to SW. At this time, the place marked with 2 on the right will automatically appear. Select the second Trace tab, and set the Core frequency to 10.000000 MHz at the beginning. (You can do this without setting it, if this parameter is not set, the code execution time during debugging is incorrect ). Select the third tab Flash DownLoad, first check the area marked with 1, then click Add marked with 2, and select a density based on the size of the new part. After the selection is complete, it is marked as 3. Click OK.







Finally, click Load in the menu bar.





Related Article

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.